/*
Forum: https://forum.arduino.cc/t/reading-hex-binary-from-pc-serial-then-output/1302803/9
Wokwi: https://wokwi.com/projects/409852867075662849
Copy one of the following lines to Serial input and press return to test the routines:
01234567890123456789<#This part is okay #>
Test<- This part is okay->EndOfTest
01234567890123456789<A01234567890123456GFGFGF>
01234567890123456789<This part is okay !!>01234567890123456789<A01234567890123456GFGFGF>
Be aware that < and > are used as START and STOPCHARACTER.
There must be exactly messageLen characters between these brackets to be considered a valid
message.
*/
#include <LiquidCrystal_I2C.h>
#define I2C_ADDR 0x27
#define LCD_COLUMNS 20
#define LCD_LINES 4
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
const byte STARTCHARACTER = '<'; // Replace by 0x1B
const byte STOPCHARACTER = '>'; // Replace by 0x12
const byte bufferLen = 21; // Allows to read more than the message length to detect length errors
const byte messageLen = 20; // This is the length of a valid message
byte msg[bufferLen]; //byte array to store values not including the STOPCHARACTER
int bytesRead = 0; // Counts the numbers of bytes read
boolean msgBegin = false; // Becomes true if STARTCHARACTER was recveived
boolean msgFound = false; // Becomes true if a valid message was found
// means: messageLen characters between START- and STOPCHARACTER
boolean error = false; // Becomes true if more or less that messageLen characters were received
// between START- and STOPCHARACTER
void setup() {
setupLCD();
Serial.begin(115200); // opens input serial port, sets data rate to 1115200 bps
Serial.println("Start");
}
void loop() {
if (Serial.available() > 0) { // check if data is available
byte aChar = Serial.read();
if (aChar == STOPCHARACTER) {
msgBegin = false;
msgFound = (bytesRead == messageLen);
error = !msgFound;
bytesRead = 0;
}
if (msgBegin && bytesRead < bufferLen) {
msg[bytesRead] = aChar;
bytesRead++;
}
if (aChar == STARTCHARACTER) {
msgBegin = true;
bytesRead = 0;
}
}
if (msgFound) {
writeToLCD();
msgFound = false;
}
if (error) {
Serial.println("Wrong message length");
error = false;
}
}
void setupLCD() {
lcd.init();
lcd.backlight();
}
void writeToLCD() {
Serial.println("Message found!");
lcd.clear();
lcd.print("STX");
lcd.print("0");
lcd.print("1");
lcd.setCursor(0, 1);
for (int i = 0; i < messageLen; i++) {
lcd.print(char(msg[i]));
}
lcd.setCursor(0, 2);
lcd.print("ETX");
}