简体   繁体   中英

C style function in structured text?

Our company has bought our first of many Beckhoff PLCs and I am currently developing a state machine.

What I typically do in C is using a switch case in which every case calls a function, the state function of that particular state. This state function returns true when it is finished. The switch-case selects a new state after a state function returns true

A short example:

// state functions
uint8_t fooF() {
    //do foo stuff
    if( /*whateevr*/ ) return 1;
    return 0;
}

uint8_t barF() {
    // do bar stuff
    if( /*whateevr*/ ) return 1;
    return 0;
}    

uint8_t foobarF() {
    // do foobar stuff
    if( /*whateevr*/ ) return 1;
    return 0;
}

// state machine 
void stateMachine() {
    switch( state ) {
        case foo: 
        if( fooF() ) {
            nextState( bar); 
        }
        break;

        case bar: 
        if( barF() ) {
            nextState( foobar); 
        }
        break;

        case foobar: 
        if( foobarF() ) {
            if( /* flow condition */ ) { nextState( foo ); 
            else                       { nextState( bar ); 
        }
        break;
    }
}

This I want to reproduce this structure in ST for as much as possible.

I have not yet found how I can make a simple function in ST. I understand I can use POU to make a new function block. But the problem that this gives me, is that the funcion is put in a different file. I want the function block to be in the same file as my state machine as I demonstrated in the C style state machine I showed you.

Can I do this? And if so, how?

Bas

EDIT: This is generated function block code:

FUNCTION_BLOCK fillBufferF
VAR_INPUT
END_VAR
VAR_OUTPUT
END_VAR
VAR
END_VAR

If you are using Twincat 3, you can add methods to your FB to be called in your switch case.

Otherwise if you are using Twincat 2 you can't add methods to your FB because Twincat 2 does not support object oriented programming.

You can create functions though (not only Function Blocks) to be added to your project. You can then group your specific functions in a folder together with your state machine function block.

Another thing that you can do if you are working with Twincat 2 is adding Actions to your Function Block. They differ from Twincat 3 methods because of the absence of an own method stack.

You can't declare variables in an Action and you can't return values from them, but they come in handy if you want to better organize the code of your Function Block.

You can't declare your functions inside your Function Block call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM