It’s time to upload the Arduino sketch for the Terrific Tilt Switch. Example 18-1 takes information from the tilt switch and sends it to the Arduino IDE (integrated development environment) Serial Monitor, displaying a series of the characters “H” and “L” with each rotation of the tilt switch.
Did you notice that parts of the program look like the listing shown. That’s because the serial communication technique—the part of the code that lets the Arduino talk with Processing—remains the same no matter what the Arduino is using as input or how Processing displays the data. Here are the steps you’ll need to follow:
- Attach the Arduino to your computer using a USB cable.
- Open the Arduino software and type Example 18-1 into the software’s text editor.
- Upload the sketch to the Arduino.
Once the Terrific Tilt Switch sketch has been uploaded to the Arduino, the Serial Monitor will display “L” repeatedly in a row, as shown in Figure 18-3. If you tilt the switch, the Serial Monitor will display “H” repeatedly (see Figure 18-4).
Figure 18-3. L’s being displayed on the Arduino Serial Monitor
Figure 18-4. H’s being displayed on the Arduino Serial Monitor
Example 18-1. The Terrific Tilt Switch sketch
/*
* The Terrific Tilt Switch
*
* Reads a digital input from a tilt switch and sends a series of
* L's or H's to the Serial Monitor.
*
*
*/
// variables for input pin and control LED
int digitalInput = 7;
int LEDpin = 13;
// variable to store the value
int value = 0;
void setup(){
// declaration pin modes
pinMode(digitalInput, INPUT);
pinMode(LEDpin, OUTPUT);
// begin sending over serial port
Serial.begin(9600);
}
void loop(){
// read the value on digital input
value = digitalRead(digitalInput);
// write this value to the control LED pin
digitalWrite(LEDpin, value);
// if value is high then send the letter 'H'; otherwise, send 'L' for low
if (value) Serial.print('H');
else
Serial.print('L');
// wait a bit to not overload the port
delay(10);
}
Leave a Reply