Jan Jongboom
/
arduino-serial-find
Serial#Find method for Arduino, implemented in Mbed
Embed:
(wiki syntax)
Show/hide line numbers
main.cpp
00001 #include "mbed.h" 00002 00003 Serial pc(USBTX, USBRX); 00004 00005 /** 00006 * Arduino's Serial#Find method (https://www.arduino.cc/en/Serial/Find) adopted to Mbed OS. 00007 * Does not allocate buffers inside. 00008 * 00009 * Example (finding the string 'ready' in a stream): 00010 * Serial uart(D1, D0); 00011 * uart.baud(115200); 00012 * 00013 * bool found = serial_find(&uart, "ready", 10); 00014 * printf("Found it? %d\n", found) 00015 * 00016 * @param serial Pointer to an initialized UART Serial object 00017 * @param str_to_find String to find in the UART stream 00018 * @param timeout_s Timeout in seconds 00019 * @returns True if found, false if timed out 00020 */ 00021 static bool serial_find(Serial *serial, const char *str_to_find, uint32_t timeout_s) { 00022 // Use RTC (instead of interrupt) for timeout detection 00023 time_t curr = time(NULL); 00024 00025 bool is_partial_match = false; 00026 uint16_t match_ix = 0; 00027 size_t str_to_find_len = strlen(str_to_find); 00028 00029 while (1) { 00030 // timeout detection 00031 if (time(NULL) - curr > timeout_s) return false; 00032 00033 while (serial->readable()) { 00034 // also do timeout detection here... 00035 if (time(NULL) - curr > timeout_s) return false; 00036 00037 char c = serial->getc(); 00038 00039 if (!is_partial_match) { 00040 // Find the first character in the stream 00041 if (c == str_to_find[0]) { 00042 if (str_to_find_len == 1) return true; 00043 00044 match_ix = 1; 00045 is_partial_match = true; 00046 } 00047 continue; 00048 } 00049 00050 // is_partial_match is correct, check remaining characters 00051 if (c == str_to_find[match_ix]) { 00052 if (str_to_find_len == match_ix + 1) return true; 00053 00054 match_ix++; 00055 } 00056 else { 00057 // not a match anymore, continue 00058 is_partial_match = false; 00059 } 00060 } 00061 } 00062 00063 return false; 00064 } 00065 00066 int main() { 00067 pc.baud(115200); 00068 pc.printf("Hello world\n"); 00069 00070 // set up connection over UART, e.g. to ESP8266 WiFi module... 00071 Serial uart(D1, D0); 00072 uart.baud(115200); 00073 00074 bool found = serial_find(&uart, "ready", 10); 00075 printf("Found it? %d\n", found); 00076 }
Generated on Fri Jul 15 2022 20:42:27 by 1.7.2