Tag

Serial

Browsing
Sending simple serial commands to an Arduino is the easiest way to communicate between an Arduino and a computer. The computer could be a PC, a Raspberry Pi, or any device that communicates with serial. By sending and “decoding” a single character it is easy to add a simple debug menu or even serial menu. Plus, it is easy to extend.

Single Character vs. Full Words

The mistake I see many people make is that they try to send full-text strings as serial commands. For example, to turn on a LED, I have seen (silly) commands like “RED LED ON” or “RED LED OFF.” While you could use something like strcmp(), as I showed on the Multiple MQTT Topics example, that tends to be overkill for most serial commands. Humans like words, computers like binary. Just send one character over serial.

switch (variable) {
  case 'a':
	// A Stuff

  case 'b':
  case 'c':
	// B and C Stuff
  break;
}

In the Arduino library, the Serial object has a method called “flush().”  Often users go throwing it into programs without fully understanding what it does. It doesn’t help that it’s functionality changed when version 1.0 of the Arduino IDE was released.

Does Serial.flush() affect the Transmit Buffer or the Receive Buffer and when do you need to use it?

When Serial data is transmitted to an Arduino, it is sent one byte at a time.  Even though you might type “123” in the Serial Monitor, that’s not quite what is sent.  Instead the bytes “1” then “2” then “3” are sent.  Once received into a buffer on the Arduino, these individual bytes need to be reassembled into something useful.