Hey
I am trying to implement a switch case in my program in conjunction with a serial function i found on youtube Using Serial.read() with Arduino | Part 2 - YouTube .see code below.
The serial works as intended, but if i add a serial USB_serial_read_string(); String a = usb_data;
in any of the cases the cases after (in this example _idle, _read, _error, _init) will not be entered even tho a "USB.println(state)" indicates that the state is correct and the cases before the read statement work fine.
So my question is why will the USB.println( )
not execute below state = _conf if i enter "4\n"
, "5\n"
or "9\n"
in the Serial Monitor?
#include <Wire.h>
#include <SPI.h>
#define USB Serial
const unsigned int MAX_MESSAGE_LENGTH = 100;
static char usb_data[MAX_MESSAGE_LENGTH];
const int SSN = 10; //need to verify
const int INTN = 25; //need to verify
enum CDCState { _stop,
_start,
_conf,
_idle,
_read,
_error,
_init };
volatile enum CDCState state = _init;
void setup() {
SPI.begin();
USB.begin(115200);
}
void loop() {
if (USB.available()) {
USB_serial_read_string();
USB.println(usb_data);
if (usb_data[0] == '0') {
state = _stop;
} else if (usb_data[0] == '1') {
state = _start;
} else if (usb_data[0] == '2') {
state = _conf;
} else if (usb_data[0] == '3') {
state = _idle;
} else if (usb_data[0] == '4') {
state = _read;
} else if (usb_data[0] == '5') {
state = _error;
} else if (usb_data[0] == '9') {
state = _init;
} else {
state = _idle;
}
usb_data[0] = 0;
USB.println(state);
}
switch (state) {
case _stop:
USB.println("In stop");
state = _idle;
break;
case _start:
USB.println("In start");
state = _start;
break;
case _conf:
USB.println("In conf");
USB_serial_read_string();
String a = usb_data;
USB_serial_read_string();
String b = usb_data;
USB.println(a);
USB.println(b);
usb_data[0] = 0;
state = _idle;
break;
case _idle:
//empty
state = _idle;
break;
case _read:
USB.println("In read");
state = _idle;
break;
case _error:
USB.println("In error");
state = _idle;
break;
case _init:
USB.println("In init");
state = _idle;
break;
default:
state = _idle;
}
}
void USB_serial_read_string(void) {
//read PC to MCU until terminating char '\n'
char inByte = 0;
static unsigned int usb_data_pos = 0;
while (inByte != '\n') { //polling
while (USB.available() > 0) {
inByte = USB.read();
if (inByte != '\n' && (usb_data_pos - MAX_MESSAGE_LENGTH - 1)) {
usb_data[usb_data_pos++] = inByte;
} else {
usb_data[usb_data_pos] = '\0';
//reset array for next data transmission
usb_data_pos = 0;
}
}
}
}