Serial test sketch
This is a little sketch that I find useful for testing the serial communication on an Arduino-like board. It not only sends data of its own accord (millis()
every second), but also echoes back what it receives. That way it will test both transmission and reception, so if one is failing you can easily see.
void setup() {
Serial.begin(115200);
}
void loop() {
static uint32_t ts = 0;
if (millis() - ts >= 1000) {
ts = millis();
Serial.println(millis());
}
if (Serial.available()) {
char c = Serial.read();
Serial.print("Recv: 0x");
Serial.print((int)c, HEX);
Serial.print(" ");
Serial.println(c);
}
}
Another variant of this is the "Serial Pass-through" sketch. This allows you to pass data from your PC through your Arduino to another serially-connected device, such as an ESP8266.
In this example I'm using SoftwareSerial
though you could (if your Arduino has one) use another hardware UART such as Serial1
instead.
#include <SoftwareSerial.h>
#define SS_TX 10
#define SS_RX 11
SoftwareSerial mySerial(SS_RX, SS_TX);
void setup() {
Serial.begin(9600);
Serial.begin(9600);
}
void loop() {
if (Serial.available()) {
mySerial.write(Serial.read());
}
if (mySerial.available()) {
Serial.write(mySerial.read());
}
}
Note that when using SoftwareSerial
most 8-bit Arduino boards will not work reliably at faster baud rates (e.g., 115200) and can't be used at all at very fast baud rates. It's best to limit yourself (if possible) to 9600 or slower.
Add new comment