variable does not get updated from serial input

10 Sep 2019

hi,

I am writing a code for serial input from the PC to the KL25Z board and convert it to a float number and save to variable V1. it appears that the KL25Z successfully receives and convert the serial string into a floating point number, however it only print once and the value of V1 returns to initial value of 0,

May I know the error in the code causing this issue? thank you

here's my code

serial input

#include "mbed.h"
#include "millis.h"
Serial pc(USBTX, USBRX);

void serial_read(float *V0);

float V1 = 0;


unsigned short size_command;

long _time = 0;


int main()
{
    pc.baud(9600);
    millisStart();
    while(1) {
        serial_read(&V1);
        if (millis() - _time > 1000) {
            _time = millis();
            pc.printf("%f\r\n",V1);
        }
    }
}

void serial_read(float *V0)
{

    if (pc.readable()) {
        size_command=pc.getc();
        char command[size_command];
        for (int i=0; i<size_command; i++)
            command[i]= pc.putc(pc.getc());
        
        sscanf(command, "%f", V0);
        
    }
}

printf stop printing once I sent a serial string to the KL25Z, also the first digit is missing in the first trial. And it does not create a new line as well. /media/uploads/conrad2001/serial_V3S6pH3.png

thank you

10 Sep 2019

Hi Conrad,

Since size_command is a run time variable, you can't to use the value to create an array like that char command[size_command];.

Instead, you should use char* command = malloc(size_command); and free().

Regards, Desmond

You need to log in to post a reply