Making a Serial Connection
Now that we’ve seen how a basic Arduino sketch works, let’s move on to sending and receiving data from the Arduino board. We’ll need to know how to do this because this is how we’ll control the Arduino or get sensor readings from it when we connect it to our iOS device. For now, however, we’re going to use the Serial Monitor (see Figure 1-7 again), inside the development environment.
Open a new sketch by clicking File→New (⌘N) to open a new window:
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() <= 0) {
Serial.println("Hello world");
delay(300);
}
}
Sets the data rate in bits per second (baud) for serial data transmission.
Here we get the number of bytes available for reading from the serial port. If there are no bytes waiting in the buffer, we loop until some arrive.
Finally, here inside the loop we print “Hello World” to the serial connection. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access