Adventures in Arduino by Becky Stewart

Page 91

DIGGING INTO THE CODE

So what’s going on in the code? There are the sections that you are probably getting used to: the setup() and loop() functions. The setup() function doesn’t have much going on. The first four lines are comments explaining what is happening. The serial communication is then started and a message is sent: Hello, this is from setup. The Arduino Uno is then paused for 3 seconds, just so that messages don’t print too fast to read.

void setup() { // to start serial communication // the argument needs to match // the rate you choose in the // Serial Monitor Serial.begin(9600); Serial.println("Hello, this is from setup"); // a delay so that messages aren’t too quick to read delay(3000); } The loop() function then prints messages in three different ways. It first uses Serial.print() to print This is from loop, with a print. and then waits for 1 second. Because the message used Serial.print() and not Serial.println(), the next message appears on the same line, with the new message printing right after the previous one. There’s another 1-second delay and then a new variable is created to hold the number 27. A Serial.print() function prints a message and then the variable prints at the end of the line. Because the variable is printed without the surrounding quotation marks (not "myVariable"), the number 27 is printed.

void loop() { // printing a message and then waiting a second Serial.print("This is from loop, with a print. "); delay(1000); Serial.println("And this is from loop with a println."); delay(1000); int myVariable = 27; Serial.print("And this is printing a variable: "); Serial.println(myVariable); delay(1000); }

The setup() function is run once when the Arduino Uno is first turned on, but the Arduino Uno calls the setup() function a couple other times besides when it is first turned on. For example, there’s a reset button on the board that you can use to manually restart the board, so the setup() function is called before going on to the loop() function. Also, whenever a new serial connection is made, the board restarts. So whenever you open the Serial Monitor, the Arduino board restarts and runs the setup() function again. You may notice this happening when you open the Serial Monitor. The message being printed gets interrupted, and the message in the setup() function starts printing instead. Try opening the Serial Monitor and then pressing the reset button on the Arduino Uno.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.