bExcute is the trigger pin. When using it, just set it to True to activate the block.
tTimeout is the timeout response time, defaulting to 5 seconds if not specified.
bBussy is a status bit, an output pin used to check if the function block is currently running. It will be FALSE once the operation is complete.
bError and nErrorld are error detection bits, also output pins. If bError is TRUE, it indicates an error in the function block operation, and nErrorld will provide an error code for reference.
The output pin HFile is a number representing the file handle, which is used in other function blocks that require the file to be opened first.
Note that the way function blocks open files is not like opening a window in Windows; they deal with memory data. If you try to delete the target file in Windows Explorer after only executing FB_OpenFile, you'll see a message saying "The operation cannot be completed because the file is open in TwinCAT3 System Service." When a txt file hasn't been created yet, choosing FOPEN_MODEAPPEND or FOPEN_MODEPLUS for the file opening mode allows for both reading and writing permissions upon opening. If the specified filename doesn't exist, it will be created.
Naturally, as there is an opening, there is also a closing. The function block used to close files is FB_FileClose. Its pins are almost identical to FB_FileOpen, except the input pin hFile is different because it looks for the file by handle rather than by path. Here, HFile is the handle generated by FB_FileOpen. When using it, simply assign the handle from FB_FileOpen to FB_FileClose.
FB_FilePuts
Beyond opening and closing files, you'll often need to modify file content. In the example, FB_FilePuts is used for input. Before starting this block, remember two things: first, the file must be open; second, the open mode must support writing. Otherwise, you'll see an error code 1792 in nErrId. Writing with this block is initially done to memory, and it's only saved to disk after closing with FB_FileClose.
Note: Since we are testing with Notepad, the encoding format is ASCII, so we use String type data for writing and reading.
To know whose score this is, the example uses the CONCAT() function to concatenate "Julias score is" with " 90 $L" and writes them together. ($L is the newline character in TwinCAT.)
FB_FileOpen, FB_FileGets, and FB_FileClose are executed in sequence. To determine if the previous block has finished, check if the input pin bExecute is TRUE and the output pin bBussy is FALSE, then proceed to the next block. The trigger pin for the whole program is b_excute.
Reading File Content
How do you know if writing to a file was successful?
We can use FB_FileOpen, FB_FileGets, and FB_FileClose to retrieve the contents of the file.
To avoid overwriting files or encountering gibberish, the example "TwinCAT ReadContent Project" uses the file opening mode FOPEN_MODEREAD (read-only). We set a STRING variable s_content to extract the data from the function block.
Note: Before using this routine, change the corresponding AmsNetId, and run "TwinCAT WriteContent Project" first to have content to read. If the corresponding file path or name isn't found, an error will occur.
FB_FileGets
The function block for reading strings is FB_FileGets. Input pins won't be detailed here as they've been discussed above. The output pin bEOF is a detection bit: it's True when you've reached the end of the file and no more bytes can be read; otherwise, it's False if bytes are still readable. You still need to open the file before reading, or you'll see error code 1795 in nErrId.
After loading the program, FB_FileOpen, FB_FileGets, and FB_FileClose are executed sequentially using CASE statements and logical checks. The whole program's trigger pin is b_excute.
Appending File Content
It's not feasible to upload all scores at once, especially with the size limitations of STRING data type. How do we append a new student's score?
This requires FB_FileOpen, FB_FileWrite, and FB_FileClose. In the example "TwinCAT AddContent Project", we still use FOPEN_MODEAPPEND or FOPEN_MODEPLUS for opening the file. (Be mindful of the format and size limits of STRING data when testing.)
To demonstrate adding content, it's best to run "TwinCAT WriteContent Project" first and modify the AmsNetId.
FB_FileWrite
With this function block, you can append new content to the end of the file. Pay attention to two pins: pWriteBuff for the address of the content to write and cbWriteLen for the size in bytes of the content. Use the ADR and SIZEOF functions to set these. Appending still requires the file to be open and writable, or you'll see error code 1792 in nErrId.
ADR() function explanation:
[Link to Beckhoff documentation]
SIZEOF() function explanation:
[Link to Beckhoff documentation]
After loading the program, FB_FileOpen, FB_FileWrite, and FB_FileClose are executed in sequence using CASE statements and logical checks. The whole program's trigger pin is b_excute.
Note: By default, the string byte size for the write block is 81; for consistency, it's recommended to add a newline character ($L) after the appended content. Otherwise, any space before 81 bytes without content might be replaced with spaces.
Copying Source Files
New Function Block: FB_FileCopy
To prevent file loss, backing up files is common. The simplest backup method is to copy the file. How can we do this?
Using FB_FileOpen, FB_FileRead, FB_FileWrite, and FB_FileClose, we can create a new function block FB_FileCopy in the example "TwinCAT CopyFile Project".
Note: Before use, ensure the source file exists and change the AmsNetId and file paths, or you'll get an error.
FB_FileRead
Another function block for reading file content is FB_FileRead. It's different from FB_FileGets as it reads via pointers (more flexible and powerful). You need to open the file beforehand. When setting the pins, pay attention to pReadBuff and cbReadLen, which are similar to the input pins pWriteBuff and cbWriteLen from FB_FileWrite. Use ADR and SIZEOF to fill these in.
The internal structure of this function block involves five steps:
Parameter initialization
Opening both source and destination files
Reading source file content
Writing content to the destination file
Resetting
Once completed, you can call it in the main program, just fill in the AmsNetId for the source and destination systems, and corresponding file paths and names. After loading, set bExcute to True, and a new file will appear below the original with identical content.
Other File and Folder Operations
Often, with an accumulation of files, you might encounter "duplicate file name" issues. What to do then?
The first solution is to delete the old file directly, calling FB_FileDelete.
FB_FileDelete
The function block for deleting files is FB_FileDelete. Its pins are almost the same as FB_FileOpen, except there's no nMode. Remember to close the file before deleting, not just in Windows but using FB_FileClose, or you'll see error code 1804 in nErrId. The second solution is to rename the file, calling FB_FileRename.
FB_FileRename
The function block for renaming files is FB_FileRename. Just fill in the pins to use it. sOldName is the old name, and sNewName is the new name. The file must be closed before renaming, or you'll get error code 1804 in nErrId.
In projects, data types vary, and for organization, you might need to create different folders. Use FB_CreateDir to create and FB_RemoveDir to delete folders.
FB_CreateDir
To create a new folder, use FB_CreateDir. After declaring and calling, just fill in the folder name sPathName and path type ePath, then activate to create a new folder in the specified directory.
FB_RemoveDir
The function block for deleting a folder is FB_RemoveDir. The usage is similar to FB_CreateDir. If the folder doesn't exist, you'll see error code 1804 in nErrId.
All these examples are in the "TwinCAT OtherFunction Project". These function blocks are simple to use, no need for additional blocks; just set their trigger pins to TRUE.
File Management Function Blocks in Power Loss Scenarios
Power loss retention is very practical in industrial production, with Beckhoff offering Persistent and Retain variables. However, after power loss, the data can only be viewed in TwinCAT upon rebooting. How to access this data externally?
With file management function blocks, you can extract this data. The example "TwinCAT Write UPS Data Project" uses axis motion control and includes four parts:
Motion control program (enable, motion function block)
Power loss detection program (CX5130 UPS command)
File management program (open, write, close blocks) and data conversion program.
Note: Before use, change the relevant hardware settings, or the program won't run. Also, the UPS commands in this example are only for the CX51 series controllers; adjust according to your controller during debugging.
When loading the program, you can first debug the axis motion. As the axis moves, its actual position is converted into a WSTRING variable (WSTRING for displaying Chinese), concatenated with "Axis actual position". Since txt files are in UTF-8 format, convert the Chinese content using WSTRING_TO_UTF8(). During axis movement, power off the CX5130 controller. FB_S_UPS_CX51x0 detects the power loss, sets b_excute to true, and through logical statements, executes the open, write, and close file operations in sequence.
WSTRING_TO_UTF8()