Skip to content

Commit 760e4b8

Browse files
committed
Rewrite suffix/prefix example to use for NMEA encoding of a message.
1 parent aa64ae2 commit 760e4b8

File tree

1 file changed

+34
-12
lines changed

1 file changed

+34
-12
lines changed

examples/Threadsafe_Serial_Prefix_Suffix/Threadsafe_Serial_Prefix_Suffix.ino

Lines changed: 34 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -56,28 +56,50 @@ void serial_thread_func()
5656
{
5757
Serial.begin(9600);
5858

59-
char const * thread_name = rtos::ThisThread::get_name();
60-
Serial.prefix([thread_name](String const & /* msg */) -> String
59+
Serial.prefix([](String const & /* msg */) -> String
6160
{
62-
char msg[64] = {0};
63-
snprintf(msg, sizeof(msg), "[%05lu] %s ", millis(), thread_name);
64-
return String(msg);
61+
return String("$");
6562
});
66-
Serial.suffix([](String const & /* prefix */, String const & /* msg */) -> String
63+
Serial.suffix([](String const & prefix, String const & msg) -> String
6764
{
68-
return String("\r\n");
65+
/* NMEA checksum is calculated over the complete message
66+
* starting with '$' and ending with the end of the message.
67+
*/
68+
byte checksum = 0;
69+
std::for_each(msg.c_str(),
70+
msg.c_str() + msg.length(),
71+
[&checksum](char const c)
72+
{
73+
checksum ^= static_cast<uint8_t>(c);
74+
});
75+
/* Assemble the footer of the NMEA message. */
76+
char footer[16] = {0};
77+
snprintf(footer, sizeof(footer), "*%02X\r\n", checksum);
78+
return String(footer);
6979
});
7080

7181
for(;;)
7282
{
7383
/* Sleep between 5 and 500 ms */
7484
rtos::ThisThread::sleep_for(rtos::Kernel::Clock::duration_u32(random(5,500)));
75-
/* Print a unbroken log message including thread name and timestamp as a prefix. */
85+
/* Print a fake NMEA GPRMC message:
86+
* $GPRMC,062101.714,A,5001.869,N,01912.114,E,955535.7,116.2,290520,000.0,W*45\r\n
87+
*/
7688
Serial.block();
77-
Serial.print("My ");
78-
Serial.print("unbroken ");
79-
Serial.print("thread-safe ");
80-
Serial.print("message!");
89+
90+
Serial.print("GPRMC,");
91+
Serial.print(millis());
92+
Serial.print(",A,");
93+
Serial.print("5001.869,");
94+
Serial.print("N,");
95+
Serial.print("01912.114,");
96+
Serial.print("E,");
97+
Serial.print("955535.7,");
98+
Serial.print("116.2,");
99+
Serial.print("290520,");
100+
Serial.print("000.0,");
101+
Serial.print("W");
102+
81103
Serial.unblock();
82104
}
83105
}

0 commit comments

Comments
 (0)