Skip to content

Instantly share code, notes, and snippets.

@njh
Created April 8, 2023 22:07
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save njh/1b5eb27c24834f4a4cb5a65ad6b2c1dd to your computer and use it in GitHub Desktop.
Arduino sketch to receive bytes from Serial Port 1 and print them in hex to the Serial Monitor
/*
This simple sketch receives bytes on the hardware serial port
and echos it to the Arduino Serial Monitor (over USB)
The bytes are printed out as a hexadecimal string
This sketch requires an Arduino that has a separate
serial port for the USB port - such as the Arduino Leonardo
Serial: Serial Monitor (USB)
Serial1: Hardward serial (Pins 0 and 1) connected
The enablePin is used to configure a RS-485 transceiver into receive mode.
Author: Nicholas Humfrey
License: https://unlicense.org
*/
int enablePin = 2;
uint8_t buffer[256];
void setup()
{
// Configure Serial1 (hardware serial port)
pinMode(enablePin, OUTPUT);
digitalWrite(enablePin, LOW);
Serial1.begin(9600);
// Configure USB Serial
Serial.begin(57600);
while (!Serial);
Serial.println("RS-485 Echo Sketch Started");
}
void loop()
{
int available = Serial1.available();
if (available > 0)
{
Serial.print(available, DEC);
Serial.println(" bytes available");
int read = Serial1.readBytes(buffer, sizeof(buffer));
Serial.print(read, DEC);
Serial.println(" bytes read");
for(int i=0; i<read; i++) {
int n = buffer[i];
Serial.print("0x");
Serial.print(n < 16 ? "0" : "");
Serial.print(n, HEX);
Serial.print(" ");
}
Serial.println();
}
delay(100);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment