Starting Interface for CTS Control

Dependencies:   mbed mbedWSEsbc

main.cpp

Committer:
jdawkins
Date:
2021-02-09
Revision:
0:4dbf26d91614

File content as of revision 0:4dbf26d91614:

#include "mbed.h"
#include "mbedWSEsbc.h"

#define PI 3.14159
#define LOG_FREQ 5.0
#define CTRL_FREQ 100.0


DigitalOut myled(LED1);
DigitalOut rx_LED(LED2);
DigitalOut log_LED(LED3);
DigitalOut run_LED(LED4);

float pwm;
bool run_flag;
float dt;
char buf[64];
Ticker control_tick;
Ticker log_tick;
float tank1,tank2;

int parseMessage(char * msg)
{
    if(!strncmp(msg, "$CMD", 4)) {
        float arg1;

        sscanf(msg,"$CMD,%f\n",&arg1);
        pwm = arg1;
        //  rx_LED = ! rx_LED;// toggle led to indicate position message receipt
        run_flag = true;

        return 1;
    }   //end of $CMD

    if(!strncmp(msg, "$STP", 4)) {
        rx_LED = ! rx_LED;// toggle led to indicate position message receipt
        run_flag = false;
        pwm = 0;
        return 1;
    }   //end of $STP

    return 0;
}

void controlLoop(){
    
    tank2 = read_max1270_volts(0, 1, 1);   //chan, range, bipol
    tank1 = read_max1270_volts(1, 1, 1);
    //Logic to exit loop if tank gets too full
    if(tank1 > 4.1 || tank2 > 4.1) {
        run_flag = false;
    }    

    if(run_flag) {
        mot_control(1, -pwm); // negative value required due do polarity of pump motor

    } else {
        mot_control(1,0);
    }    
    myled = !myled;
}

void logLoop(){
    
    pc.printf("$SEN,%.3f,%.3f,%.3f\r\n", tank1,tank2,pwm); //write data to scren
  
    log_LED = !log_LED;
}

int main()
{
    pc.printf("Quanser Twin Tank Control Data Aquisition Program\r\n");

    float log_timer = 0;  //initialize variable for log timer
    run_flag = true;
    myled = 1;
    pwm = 0;
    //  pc.attach(&rxCallback);
    mbedWSEsbcInit(9600);  //Initialize the mbed WSE Project SBC
    wait(.2);   //delay at beginning for voltage settle purposes
    t.start();  // Set up timer
    Timer tc;
    tc.start();
    tc.reset();
    
    control_tick.attach(&controlLoop, 0.1);
    log_tick.attach(&logLoop,1.0);

    t.reset(); // zero timer
    dt = 1/(CTRL_FREQ);

    while(1) {

        if(pc.readable()) {
            int i=0;
            char c = pc.getc();
            // pc.printf("%s",c);
            if(c=='$') {
                buf[i] = c;
                i++;
                while(1) {
                    buf[i] = pc.getc();
                    if(buf[i]=='\n') {
                        break;
                    }
                    i++;
                }
            }

            parseMessage(buf);

        } // If PC Readable


        //if run flag
        wait(dt);   //Wait for sample time of loop frequency
    }//while
}//main