MySQL for the Internet of Things

(Steven Felgate) #1

ChApTEr 2 ■ hArdwArE for IoT SoluTIonS


■Note Most Arduino boards have an lEd connected to pin 13. You reuse the pin to demonstrate how to


use analog output. Thus, you may see a small lEd near pin 13 illuminate at the same time as the lEd on the


breadboard.


Writing the Sketch


The sketch you need for this project uses two I/O pins on the Arduino: one output and one input. The output
pin will illuminate the LED, and the input pin will detect the pushbutton engagement. You connect positive
voltage to one side of the pushbutton and the other side to the input pin. When you detect voltage on the
input pin, you tell the Arduino processor to send positive voltage to the output pin. In this case, the positive
side of the LED is connected to the output pin.
As you see in the drawing in Figure 2-17, the input pin is pin 2, and the output pin is pin 13. Let’s use a
variable to store these numbers so you don’t have to worry about repeating the hard-coded numbers (and
risk getting them wrong). Use the pinMode() method to set the mode of each pin (INPUT, OUTPUT). You place
the variable statements before the setup() method and set the pinMode() calls in the setup() method, as
follows:


int led = 13; // LED on pin 13
int button = 2; // button on pin 2


void setup() {
pinMode(led, OUTPUT);
pinMode(button, INPUT);
}


In the loop() method, you place code to detect the button press. Use the digitalRead() method to
read the status of the pin (LOW or HIGH), where LOW means there is no voltage on the pin and HIGH means
positive voltage is detected on the pin.
You also place in the loop() method the code to turn on the LED when the input pin state is HIGH. In
this case, you use the digitalWrite() method to set the output pin to HIGH when the input pin state is HIGH
and similarly set the output pin to LOW when the input pin state is LOW. The following shows the statements
needed:


void loop() {
int state = digitalRead(button);
if (state == HIGH) {
digitalWrite(led, HIGH);
}
else {
digitalWrite(led, LOW);
}
}


Now let’s see the entire sketch, complete with the proper documentation. Listing 2-1 shows the
completed sketch.

Free download pdf