I need help regarding my code. I am trying to convert my incoming data that is coming from my Software serial port (Connected with a RS232 connector) into Char. How exactly do I do that? My code is below:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("Goodnight moon!");
// set the data rate for the SoftwareSerial port
mySerial.begin(9600);
mySerial.println("Hello, world?");
}
void loop() { // run over and over
if (mySerial.available()) {
Serial.write(mySerial.read()); //Need to convert this line into CHAR
Serial.println("Im coming from Arduino");
}
if (Serial.available()) {
mySerial.write(Serial.read());
}
}
From softwareserial.c - it returns an integer, not a char!
Why, I'm not sure - it strikes me as wrong, frankly.
Well, you are wrong, then.
The byte that is read from the serial buffer could be ANY value in the range 0 to 255. That leaves NOTHING to indicate that there was nothing to read. Hence, the function needs to return a multi-byte value so that there is a way to return an error condition.
OP: If you ALWAYS call read only after available() returns a positive value, you can assign the return value to a char variable. The high order byte will be discarded, but that's OK because it will be 0 if the low order byte contains valid data.
If you don't always call available() first (or assume that available() returning 1 means you can read 12 bytes), then you shouldn't assign the return code to a char until after you check that the return value is not -1.