I have the following problem. I would like to read in the following protocol via Serial 2 and then output it again via Serial 1 as a test. The protocol consists of a mix of HEX and ASCII characters.
this compiles on an UNO if I map Serial2 to Serial.
it captures a string of characters. it re-transmits it when EOT is detected
It drops it if it exceeds the size of the buffer.
you may need to recognize an ESC if ESC, SOH or EOT can be valid data
#define NUL 0x00
#define SOH 0x01
#define EOT 0x04
#define N 80
char variable [N];
int i = 0;
#if 1
#define Serial2 Serial
#endif
void setup() {
Serial.begin(9600, SERIAL_8N1);
Serial2.begin(9600, SERIAL_8N1);
}
void loop() {
if (Serial2.available()) {
byte c = Serial2.read();
variable [i++] = c;
// drop frame if start of new frame or too long
if (SOH == c || N-1 <= i)
i = 0;
if (EOT == c)
Serial.write (variable, i);
}
}
I think the first numbers are read currently. But as soon as I want to read the ASCII characters, it’s unreadable. How can I get the ascii string correctly?
struber:
I think the first numbers are read currently. But as soon as I want to read the ASCII characters, it’s unreadable. How can I get the ascii string correctly?
You need to explain where the data is coming from and where you got the image that you posted in your Original Reply.
My guess is that your program is working properly but the data that is being sent is not what you expect.
I use some code for a similar purpose, you are welcome to have it, use it, adapt to your own needs:
// Receives data on serial port 1 and sends to the serial monitor with an index.
// Each character is on a new line.
uint16_t baudHeating = 57600;
void setup() {
Serial.begin(250000);
Serial.println("Serial monitor started");
Serial1.begin(baudHeating);
Serial.println("Serial 1 started");
}
void loop() {
serialMonitor();
}
void serialMonitor() {
char RxTemp;
static uint8_t charCount;
while (Serial1.available() > 0) {
RxTemp = Serial1.read();
Serial.print(charCount);
Serial.print(" byte ");
Serial.print((byte)RxTemp, HEX);
Serial.print(" char ");
Serial.println((char)RxTemp);
++charCount;
if ((uint8_t)RxTemp == 0) {
charCount = 0;
Serial.println("charCount = 0");
}
}
}
Each character is on its own line with its hex value and ASCII character, if there is one. Note that as there are about 15 or so output characters to each received character the serial monitor needs to be set to go much faster then the other serial port.
++Karma; // For posting code correctly on your first post.