Wie man eine längenpräfixierte Binärnachricht aus Serial mit Arduino liest
English
Deutsch
Die folgende Funktion erlaubt es Ihnen, eine Binärnachricht, die mit einem einzelnen length-Byte präfixiert ist, aus Serial zu lesen:
read_length_prefixed_serial.cpp
#include <Arduino.h>
void setup() {
Serial.begin(115200);
}
void HandleMessage(String msg) {
// TODO: Your code to handle the message goes here.
// See https://techoverflow.net/2022/11/15/how-to-print-string-as-sequence-of-hex-bytes-in-arduino/
// for an example of how to print the message as a sequence of hex bytes.
}
void ReadMessageFromSerial() {
// Wait until the length byte is available on Serial
while (Serial.available() == 0);
// Read the length of the message
int length = Serial.read();
// Read the rest of the message
String message = "";
for (int i = 0; i < length; i++) {
while (Serial.available() == 0);
message += char(Serial.read());
}
// Handle the message
HandleMessage(message);
}
void loop() {
ReadMessageFromSerial();
}Check out similar posts by category:
Allgemein, Arduino, Electronics, Embedded
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow