Hardware Reference
In-Depth Information
The first four examples in this chapter (Listings 3-1 to 3-4) show how to set up serial communications. All the
examples are written using Arduino 1.0.1 and openFrameworks version 0071 but have been tested with Arduino
1.5.1r2 and openFrameworks 0073.
Arduino Code
Listing 3-1 shows the code to set up the Arduino, connect to a push button on pin 8, and check if the button is pressed
or released and report the change in this state to a serial connection using a character. The code also checks for an
incoming character from the serial; a and s signify turning on and off an LED on pin 13, respectively. This passing of
characters is important when developing code for openFrameworks to control the Arduino, thus making the Arduino
a possible controller for a game, a sensor for a door, and so on.
Listing 3-1. Arduino Sketch That Sets Up the Arduino
int button = 8 , ledPin = 13; // pin assignments: button on pin 8,LED on pin 13
boolean oldState = 0 , newState = 0; // state change variables
void setup () {
pinMode(button, INPUT); ////////////////////////////
pinMode(ledPin,OUTPUT); // set pin I/O types
Serial.begin(9600); // starts serial at baud rate 9600
} // end setup()
void loop () {
newState = digitalRead(button); // save current button state
if(newState != oldState){ // test for change in button state
if (newState == true) // for button press, send the "h" to serial
Serial.print('h');
if (newState == false) // for button release, send the "l" to serial
Serial.print('l');
} // end if(state0 != state1)
oldState = newState; // save new state to old state for comparison
delay(40); // delay for bounce control
} // end void loop()
void serialEvent () { // called upon incoming serial
switch (Serial.read()){ // determine if serial is one of the required inputs
case 'a': digitalWrite(ledPin, HIGH);
break; // for input of "a", turn on LED
case 's': digitalWrite(ledPin, LOW);
break; // for input of "s", turn off LED
} // end switch (Serial.read())
} // end serialEvent()
Note the serialEvent() function does not work with the Leonardo board. to convert for the Leonardo board change
void serialEvent() to if (Serial.available() > 0) and move the loop ending bracket to below the ex void
serialEvent() function.
Verifying the Code
Load Listing 3-1 and hook up the Arduino with a momentary push-button switch and a pull-down resistor hooked
to pin 8. The LED set up on pin 13 is optional because the Arduino has one on the board. With the board
 
 
Search WWH ::




Custom Search