1
0
mirror of https://github.com/arduino/Arduino.git synced 2025-01-17 06:52:18 +01:00

Run new astyle formatter against all the examples

This commit is contained in:
Federico Fissore 2013-10-21 09:58:40 +02:00
parent 3c6ee46828
commit b4c68b3dff
259 changed files with 5160 additions and 5217 deletions

View File

@ -2,7 +2,7 @@
AnalogReadSerial AnalogReadSerial
Reads an analog input on pin 0, prints the result to the serial monitor. Reads an analog input on pin 0, prints the result to the serial monitor.
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground. Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
This example code is in the public domain. This example code is in the public domain.
*/ */

View File

@ -4,6 +4,6 @@ void setup() {
} }
void loop() { void loop() {
// put your main code here, to run repeatedly: // put your main code here, to run repeatedly:
} }

View File

@ -1,18 +1,18 @@
/* /*
Blink Blink
Turns on an LED on for one second, then off for one second, repeatedly. Turns on an LED on for one second, then off for one second, repeatedly.
This example code is in the public domain. This example code is in the public domain.
*/ */
// Pin 13 has an LED connected on most Arduino boards. // Pin 13 has an LED connected on most Arduino boards.
// give it a name: // give it a name:
int led = 13; int led = 13;
// the setup routine runs once when you press reset: // the setup routine runs once when you press reset:
void setup() { void setup() {
// initialize the digital pin as an output. // initialize the digital pin as an output.
pinMode(led, OUTPUT); pinMode(led, OUTPUT);
} }
// the loop routine runs over and over again forever: // the loop routine runs over and over again forever:

View File

@ -1,7 +1,7 @@
/* /*
DigitalReadSerial DigitalReadSerial
Reads a digital input on pin 2, prints the result to the serial monitor Reads a digital input on pin 2, prints the result to the serial monitor
This example code is in the public domain. This example code is in the public domain.
*/ */

View File

@ -1,9 +1,9 @@
/* /*
Fade Fade
This example shows how to fade an LED on pin 9 This example shows how to fade an LED on pin 9
using the analogWrite() function. using the analogWrite() function.
This example code is in the public domain. This example code is in the public domain.
*/ */
@ -12,24 +12,24 @@ int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by int fadeAmount = 5; // how many points to fade the LED by
// the setup routine runs once when you press reset: // the setup routine runs once when you press reset:
void setup() { void setup() {
// declare pin 9 to be an output: // declare pin 9 to be an output:
pinMode(led, OUTPUT); pinMode(led, OUTPUT);
} }
// the loop routine runs over and over again forever: // the loop routine runs over and over again forever:
void loop() { void loop() {
// set the brightness of pin 9: // set the brightness of pin 9:
analogWrite(led, brightness); analogWrite(led, brightness);
// change the brightness for next time through the loop: // change the brightness for next time through the loop:
brightness = brightness + fadeAmount; brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade: // reverse the direction of the fading at the ends of the fade:
if (brightness == 0 || brightness == 255) { if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ; fadeAmount = -fadeAmount ;
} }
// wait for 30 milliseconds to see the dimming effect // wait for 30 milliseconds to see the dimming effect
delay(30); delay(30);
} }

View File

@ -2,7 +2,7 @@
ReadAnalogVoltage ReadAnalogVoltage
Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor. Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor.
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground. Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
This example code is in the public domain. This example code is in the public domain.
*/ */

View File

@ -1,27 +1,27 @@
/* Blink without Delay /* Blink without Delay
Turns on and off a light emitting diode(LED) connected to a digital Turns on and off a light emitting diode(LED) connected to a digital
pin, without using the delay() function. This means that other code pin, without using the delay() function. This means that other code
can run at the same time without being interrupted by the LED code. can run at the same time without being interrupted by the LED code.
The circuit: The circuit:
* LED attached from pin 13 to ground. * LED attached from pin 13 to ground.
* Note: on most Arduinos, there is already an LED on the board * Note: on most Arduinos, there is already an LED on the board
that's attached to pin 13, so no hardware is needed for this example. that's attached to pin 13, so no hardware is needed for this example.
created 2005 created 2005
by David A. Mellis by David A. Mellis
modified 8 Feb 2010 modified 8 Feb 2010
by Paul Stoffregen by Paul Stoffregen
This example code is in the public domain. This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/ */
// constants won't change. Used here to // constants won't change. Used here to
// set pin numbers: // set pin numbers:
const int ledPin = 13; // the number of the LED pin const int ledPin = 13; // the number of the LED pin
@ -35,22 +35,22 @@ long interval = 1000; // interval at which to blink (milliseconds)
void setup() { void setup() {
// set the digital pin as output: // set the digital pin as output:
pinMode(ledPin, OUTPUT); pinMode(ledPin, OUTPUT);
} }
void loop() void loop()
{ {
// here is where you'd put code that needs to be running all the time. // here is where you'd put code that needs to be running all the time.
// check to see if it's time to blink the LED; that is, if the // check to see if it's time to blink the LED; that is, if the
// difference between the current time and last time you blinked // difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to // the LED is bigger than the interval at which you want to
// blink the LED. // blink the LED.
unsigned long currentMillis = millis(); unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) { if (currentMillis - previousMillis > interval) {
// save the last time you blinked the LED // save the last time you blinked the LED
previousMillis = currentMillis; previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa: // if the LED is off turn it on and vice-versa:
if (ledState == LOW) if (ledState == LOW)

View File

@ -1,30 +1,30 @@
/* /*
Button Button
Turns on and off a light emitting diode(LED) connected to digital Turns on and off a light emitting diode(LED) connected to digital
pin 13, when pressing a pushbutton attached to pin 2. pin 13, when pressing a pushbutton attached to pin 2.
The circuit: The circuit:
* LED attached from pin 13 to ground * LED attached from pin 13 to ground
* pushbutton attached to pin 2 from +5V * pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground * 10K resistor attached to pin 2 from ground
* Note: on most Arduinos there is already an LED on the board * Note: on most Arduinos there is already an LED on the board
attached to pin 13. attached to pin 13.
created 2005 created 2005
by DojoDave <http://www.0j0.org> by DojoDave <http://www.0j0.org>
modified 30 Aug 2011 modified 30 Aug 2011
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Button http://www.arduino.cc/en/Tutorial/Button
*/ */
// constants won't change. They're used here to // constants won't change. They're used here to
// set pin numbers: // set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin const int ledPin = 13; // the number of the LED pin
@ -34,23 +34,23 @@ int buttonState = 0; // variable for reading the pushbutton status
void setup() { void setup() {
// initialize the LED pin as an output: // initialize the LED pin as an output:
pinMode(ledPin, OUTPUT); pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input: // initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT); pinMode(buttonPin, INPUT);
} }
void loop(){ void loop() {
// read the state of the pushbutton value: // read the state of the pushbutton value:
buttonState = digitalRead(buttonPin); buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. // check if the pushbutton is pressed.
// if it is, the buttonState is HIGH: // if it is, the buttonState is HIGH:
if (buttonState == HIGH) { if (buttonState == HIGH) {
// turn LED on: // turn LED on:
digitalWrite(ledPin, HIGH); digitalWrite(ledPin, HIGH);
} }
else { else {
// turn LED off: // turn LED off:
digitalWrite(ledPin, LOW); digitalWrite(ledPin, LOW);
} }
} }

View File

@ -1,33 +1,33 @@
/* /*
Debounce Debounce
Each time the input pin goes from LOW to HIGH (e.g. because of a push-button Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
press), the output pin is toggled from LOW to HIGH or HIGH to LOW. There's press), the output pin is toggled from LOW to HIGH or HIGH to LOW. There's
a minimum delay between toggles to debounce the circuit (i.e. to ignore a minimum delay between toggles to debounce the circuit (i.e. to ignore
noise). noise).
The circuit: The circuit:
* LED attached from pin 13 to ground * LED attached from pin 13 to ground
* pushbutton attached from pin 2 to +5V * pushbutton attached from pin 2 to +5V
* 10K resistor attached from pin 2 to ground * 10K resistor attached from pin 2 to ground
* Note: On most Arduino boards, there is already an LED on the board * Note: On most Arduino boards, there is already an LED on the board
connected to pin 13, so you don't need any extra components for this example. connected to pin 13, so you don't need any extra components for this example.
created 21 November 2006 created 21 November 2006
by David A. Mellis by David A. Mellis
modified 30 Aug 2011 modified 30 Aug 2011
by Limor Fried by Limor Fried
modified 28 Dec 2012 modified 28 Dec 2012
by Mike Walters by Mike Walters
This example code is in the public domain. This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Debounce http://www.arduino.cc/en/Tutorial/Debounce
*/ */
// constants won't change. They're used here to // constants won't change. They're used here to
// set pin numbers: // set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin const int ledPin = 13; // the number of the LED pin
@ -54,16 +54,16 @@ void loop() {
// read the state of the switch into a local variable: // read the state of the switch into a local variable:
int reading = digitalRead(buttonPin); int reading = digitalRead(buttonPin);
// check to see if you just pressed the button // check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited // (i.e. the input went from LOW to HIGH), and you've waited
// long enough since the last press to ignore any noise: // long enough since the last press to ignore any noise:
// If the switch changed, due to noise or pressing: // If the switch changed, due to noise or pressing:
if (reading != lastButtonState) { if (reading != lastButtonState) {
// reset the debouncing timer // reset the debouncing timer
lastDebounceTime = millis(); lastDebounceTime = millis();
} }
if ((millis() - lastDebounceTime) > debounceDelay) { if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer // whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state: // than the debounce delay, so take it as the actual current state:
@ -78,7 +78,7 @@ void loop() {
} }
} }
} }
// set the LED: // set the LED:
digitalWrite(ledPin, ledState); digitalWrite(ledPin, ledState);

View File

@ -1,48 +1,48 @@
/* /*
Input Pullup Serial Input Pullup Serial
This example demonstrates the use of pinMode(INPUT_PULLUP). It reads a This example demonstrates the use of pinMode(INPUT_PULLUP). It reads a
digital input on pin 2 and prints the results to the serial monitor. digital input on pin 2 and prints the results to the serial monitor.
The circuit: The circuit:
* Momentary switch attached from pin 2 to ground * Momentary switch attached from pin 2 to ground
* Built-in LED on pin 13 * Built-in LED on pin 13
Unlike pinMode(INPUT), there is no pull-down resistor necessary. An internal Unlike pinMode(INPUT), there is no pull-down resistor necessary. An internal
20K-ohm resistor is pulled to 5V. This configuration causes the input to 20K-ohm resistor is pulled to 5V. This configuration causes the input to
read HIGH when the switch is open, and LOW when it is closed. read HIGH when the switch is open, and LOW when it is closed.
created 14 March 2012 created 14 March 2012
by Scott Fitzgerald by Scott Fitzgerald
http://www.arduino.cc/en/Tutorial/InputPullupSerial http://www.arduino.cc/en/Tutorial/InputPullupSerial
This example code is in the public domain This example code is in the public domain
*/ */
void setup(){ void setup() {
//start serial connection //start serial connection
Serial.begin(9600); Serial.begin(9600);
//configure pin2 as an input and enable the internal pull-up resistor //configure pin2 as an input and enable the internal pull-up resistor
pinMode(2, INPUT_PULLUP); pinMode(2, INPUT_PULLUP);
pinMode(13, OUTPUT); pinMode(13, OUTPUT);
} }
void loop(){ void loop() {
//read the pushbutton value into a variable //read the pushbutton value into a variable
int sensorVal = digitalRead(2); int sensorVal = digitalRead(2);
//print out the value of the pushbutton //print out the value of the pushbutton
Serial.println(sensorVal); Serial.println(sensorVal);
// Keep in mind the pullup means the pushbutton's // Keep in mind the pullup means the pushbutton's
// logic is inverted. It goes HIGH when it's open, // logic is inverted. It goes HIGH when it's open,
// and LOW when it's pressed. Turn on pin 13 when the // and LOW when it's pressed. Turn on pin 13 when the
// button's pressed, and off when it's not: // button's pressed, and off when it's not:
if (sensorVal == HIGH) { if (sensorVal == HIGH) {
digitalWrite(13, LOW); digitalWrite(13, LOW);
} }
else { else {
digitalWrite(13, HIGH); digitalWrite(13, HIGH);
} }

View File

@ -1,28 +1,28 @@
/* /*
State change detection (edge detection) State change detection (edge detection)
Often, you don't need to know the state of a digital input all the time, Often, you don't need to know the state of a digital input all the time,
but you just need to know when the input changes from one state to another. but you just need to know when the input changes from one state to another.
For example, you want to know when a button goes from OFF to ON. This is called For example, you want to know when a button goes from OFF to ON. This is called
state change detection, or edge detection. state change detection, or edge detection.
This example shows how to detect when a button or button changes from off to on This example shows how to detect when a button or button changes from off to on
and on to off. and on to off.
The circuit: The circuit:
* pushbutton attached to pin 2 from +5V * pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground * 10K resistor attached to pin 2 from ground
* LED attached from pin 13 to ground (or use the built-in LED on * LED attached from pin 13 to ground (or use the built-in LED on
most Arduino boards) most Arduino boards)
created 27 Sep 2005 created 27 Sep 2005
modified 30 Aug 2011 modified 30 Aug 2011
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://arduino.cc/en/Tutorial/ButtonStateChange http://arduino.cc/en/Tutorial/ButtonStateChange
*/ */
// this constant won't change: // this constant won't change:
@ -58,30 +58,30 @@ void loop() {
Serial.println("on"); Serial.println("on");
Serial.print("number of button pushes: "); Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter); Serial.println(buttonPushCounter);
} }
else { else {
// if the current state is LOW then the button // if the current state is LOW then the button
// wend from on to off: // wend from on to off:
Serial.println("off"); Serial.println("off");
} }
// Delay a little bit to avoid bouncing // Delay a little bit to avoid bouncing
delay(50); delay(50);
} }
// save the current state as the last state, // save the current state as the last state,
//for next time through the loop //for next time through the loop
lastButtonState = buttonState; lastButtonState = buttonState;
// turns on the LED every four button pushes by // turns on the LED every four button pushes by
// checking the modulo of the button push counter. // checking the modulo of the button push counter.
// the modulo function gives you the remainder of // the modulo function gives you the remainder of
// the division of two numbers: // the division of two numbers:
if (buttonPushCounter % 4 == 0) { if (buttonPushCounter % 4 == 0) {
digitalWrite(ledPin, HIGH); digitalWrite(ledPin, HIGH);
} else { } else {
digitalWrite(ledPin, LOW); digitalWrite(ledPin, LOW);
} }
} }

View File

@ -1,21 +1,21 @@
/* /*
keyboard keyboard
Plays a pitch that changes based on a changing analog input Plays a pitch that changes based on a changing analog input
circuit: circuit:
* 3 force-sensing resistors from +5V to analog in 0 through 5 * 3 force-sensing resistors from +5V to analog in 0 through 5
* 3 10K resistors from analog in 0 through 5 to ground * 3 10K resistors from analog in 0 through 5 to ground
* 8-ohm speaker on digital pin 8 * 8-ohm speaker on digital pin 8
created 21 Jan 2010 created 21 Jan 2010
modified 9 Apr 2012 modified 9 Apr 2012
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://arduino.cc/en/Tutorial/Tone3 http://arduino.cc/en/Tutorial/Tone3
*/ */
#include "pitches.h" #include "pitches.h"
@ -24,7 +24,8 @@ const int threshold = 10; // minimum reading of the sensors that generates a
// notes to play, corresponding to the 3 sensors: // notes to play, corresponding to the 3 sensors:
int notes[] = { int notes[] = {
NOTE_A4, NOTE_B4,NOTE_C3 }; NOTE_A4, NOTE_B4, NOTE_C3
};
void setup() { void setup() {
@ -39,6 +40,6 @@ void loop() {
if (sensorReading > threshold) { if (sensorReading > threshold) {
// play the note corresponding to this sensor: // play the note corresponding to this sensor:
tone(8, notes[thisSensor], 20); tone(8, notes[thisSensor], 20);
} }
} }
} }

View File

@ -1,39 +1,41 @@
/* /*
Melody Melody
Plays a melody Plays a melody
circuit: circuit:
* 8-ohm speaker on digital pin 8 * 8-ohm speaker on digital pin 8
created 21 Jan 2010 created 21 Jan 2010
modified 30 Aug 2011 modified 30 Aug 2011
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://arduino.cc/en/Tutorial/Tone http://arduino.cc/en/Tutorial/Tone
*/ */
#include "pitches.h" #include "pitches.h"
// notes in the melody: // notes in the melody:
int melody[] = { int melody[] = {
NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4}; NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
// note durations: 4 = quarter note, 8 = eighth note, etc.: // note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = { int noteDurations[] = {
4, 8, 8, 4,4,4,4,4 }; 4, 8, 8, 4, 4, 4, 4, 4
};
void setup() { void setup() {
// iterate over the notes of the melody: // iterate over the notes of the melody:
for (int thisNote = 0; thisNote < 8; thisNote++) { for (int thisNote = 0; thisNote < 8; thisNote++) {
// to calculate the note duration, take one second // to calculate the note duration, take one second
// divided by the note type. // divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc. //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 1000/noteDurations[thisNote]; int noteDuration = 1000 / noteDurations[thisNote];
tone(8, melody[thisNote],noteDuration); tone(8, melody[thisNote], noteDuration);
// to distinguish the notes, set a minimum time between them. // to distinguish the notes, set a minimum time between them.
// the note's duration + 30% seems to work well: // the note's duration + 30% seems to work well:

View File

@ -1,19 +1,19 @@
/* /*
Multiple tone player Multiple tone player
Plays multiple tones on multiple pins in sequence Plays multiple tones on multiple pins in sequence
circuit: circuit:
* 3 8-ohm speaker on digital pins 6, 7, and 8 * 3 8-ohm speaker on digital pins 6, 7, and 8
created 8 March 2010 created 8 March 2010
by Tom Igoe by Tom Igoe
based on a snippet from Greg Borenstein based on a snippet from Greg Borenstein
This example code is in the public domain. This example code is in the public domain.
http://arduino.cc/en/Tutorial/Tone4 http://arduino.cc/en/Tutorial/Tone4
*/ */
void setup() { void setup() {
@ -22,7 +22,7 @@ void setup() {
void loop() { void loop() {
// turn off tone function for pin 8: // turn off tone function for pin 8:
noTone(8); noTone(8);
// play a note on pin 6 for 200 ms: // play a note on pin 6 for 200 ms:
tone(6, 440, 200); tone(6, 440, 200);
delay(200); delay(200);
@ -32,9 +32,9 @@ void loop() {
// play a note on pin 7 for 500 ms: // play a note on pin 7 for 500 ms:
tone(7, 494, 500); tone(7, 494, 500);
delay(500); delay(500);
// turn off tone function for pin 7: // turn off tone function for pin 7:
noTone(7); noTone(7);
// play a note on pin 8 for 500 ms: // play a note on pin 8 for 500 ms:
tone(8, 523, 300); tone(8, 523, 300);
delay(300); delay(300);

View File

@ -1,21 +1,21 @@
/* /*
Pitch follower Pitch follower
Plays a pitch that changes based on a changing analog input Plays a pitch that changes based on a changing analog input
circuit: circuit:
* 8-ohm speaker on digital pin 9 * 8-ohm speaker on digital pin 9
* photoresistor on analog 0 to 5V * photoresistor on analog 0 to 5V
* 4.7K resistor on analog 0 to ground * 4.7K resistor on analog 0 to ground
created 21 Jan 2010 created 21 Jan 2010
modified 31 May 2012 modified 31 May 2012
by Tom Igoe, with suggestion from Michael Flynn by Tom Igoe, with suggestion from Michael Flynn
This example code is in the public domain. This example code is in the public domain.
http://arduino.cc/en/Tutorial/Tone2 http://arduino.cc/en/Tutorial/Tone2
*/ */

View File

@ -1,22 +1,22 @@
/* /*
Analog input, analog output, serial output Analog input, analog output, serial output
Reads an analog input pin, maps the result to a range from 0 to 255 Reads an analog input pin, maps the result to a range from 0 to 255
and uses the result to set the pulsewidth modulation (PWM) of an output pin. and uses the result to set the pulsewidth modulation (PWM) of an output pin.
Also prints the results to the serial monitor. Also prints the results to the serial monitor.
The circuit: The circuit:
* potentiometer connected to analog pin 0. * potentiometer connected to analog pin 0.
Center pin of the potentiometer goes to the analog pin. Center pin of the potentiometer goes to the analog pin.
side pins of the potentiometer go to +5V and ground side pins of the potentiometer go to +5V and ground
* LED connected from digital pin 9 to ground * LED connected from digital pin 9 to ground
created 29 Dec. 2008 created 29 Dec. 2008
modified 9 Apr 2012 modified 9 Apr 2012
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
*/ */
// These constants won't change. They're used to give names // These constants won't change. They're used to give names
@ -29,25 +29,25 @@ int outputValue = 0; // value output to the PWM (analog out)
void setup() { void setup() {
// initialize serial communications at 9600 bps: // initialize serial communications at 9600 bps:
Serial.begin(9600); Serial.begin(9600);
} }
void loop() { void loop() {
// read the analog in value: // read the analog in value:
sensorValue = analogRead(analogInPin); sensorValue = analogRead(analogInPin);
// map it to the range of the analog out: // map it to the range of the analog out:
outputValue = map(sensorValue, 0, 1023, 0, 255); outputValue = map(sensorValue, 0, 1023, 0, 255);
// change the analog out value: // change the analog out value:
analogWrite(analogOutPin, outputValue); analogWrite(analogOutPin, outputValue);
// print the results to the serial monitor: // print the results to the serial monitor:
Serial.print("sensor = " ); Serial.print("sensor = " );
Serial.print(sensorValue); Serial.print(sensorValue);
Serial.print("\t output = "); Serial.print("\t output = ");
Serial.println(outputValue); Serial.println(outputValue);
// wait 2 milliseconds before the next loop // wait 2 milliseconds before the next loop
// for the analog-to-digital converter to settle // for the analog-to-digital converter to settle
// after the last reading: // after the last reading:
delay(2); delay(2);
} }

View File

@ -1,10 +1,10 @@
/* /*
Analog Input Analog Input
Demonstrates analog input by reading an analog sensor on analog pin 0 and Demonstrates analog input by reading an analog sensor on analog pin 0 and
turning on and off a light emitting diode(LED) connected to digital pin 13. turning on and off a light emitting diode(LED) connected to digital pin 13.
The amount of time the LED will be on and off depends on The amount of time the LED will be on and off depends on
the value obtained by analogRead(). the value obtained by analogRead().
The circuit: The circuit:
* Potentiometer attached to analog input 0 * Potentiometer attached to analog input 0
* center pin of the potentiometer to the analog pin * center pin of the potentiometer to the analog pin
@ -12,19 +12,19 @@
* the other side pin to +5V * the other side pin to +5V
* LED anode (long leg) attached to digital output 13 * LED anode (long leg) attached to digital output 13
* LED cathode (short leg) attached to ground * LED cathode (short leg) attached to ground
* Note: because most Arduinos have a built-in LED attached * Note: because most Arduinos have a built-in LED attached
to pin 13 on the board, the LED is optional. to pin 13 on the board, the LED is optional.
Created by David Cuartielles Created by David Cuartielles
modified 30 Aug 2011 modified 30 Aug 2011
By Tom Igoe By Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://arduino.cc/en/Tutorial/AnalogInput http://arduino.cc/en/Tutorial/AnalogInput
*/ */
int sensorPin = A0; // select the input pin for the potentiometer int sensorPin = A0; // select the input pin for the potentiometer
@ -33,18 +33,18 @@ int sensorValue = 0; // variable to store the value coming from the sensor
void setup() { void setup() {
// declare the ledPin as an OUTPUT: // declare the ledPin as an OUTPUT:
pinMode(ledPin, OUTPUT); pinMode(ledPin, OUTPUT);
} }
void loop() { void loop() {
// read the value from the sensor: // read the value from the sensor:
sensorValue = analogRead(sensorPin); sensorValue = analogRead(sensorPin);
// turn the ledPin on // turn the ledPin on
digitalWrite(ledPin, HIGH); digitalWrite(ledPin, HIGH);
// stop the program for <sensorValue> milliseconds: // stop the program for <sensorValue> milliseconds:
delay(sensorValue); delay(sensorValue);
// turn the ledPin off: // turn the ledPin off:
digitalWrite(ledPin, LOW); digitalWrite(ledPin, LOW);
// stop the program for for <sensorValue> milliseconds: // stop the program for for <sensorValue> milliseconds:
delay(sensorValue); delay(sensorValue);
} }

View File

@ -1,17 +1,17 @@
/* /*
Mega analogWrite() test Mega analogWrite() test
This sketch fades LEDs up and down one at a time on digital pins 2 through 13. This sketch fades LEDs up and down one at a time on digital pins 2 through 13.
This sketch was written for the Arduino Mega, and will not work on previous boards. This sketch was written for the Arduino Mega, and will not work on previous boards.
The circuit: The circuit:
* LEDs attached from pins 2 through 13 to ground. * LEDs attached from pins 2 through 13 to ground.
created 8 Feb 2009 created 8 Feb 2009
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
*/ */
// These constants won't change. They're used to give names // These constants won't change. They're used to give names
// to the pins used: // to the pins used:
@ -21,24 +21,24 @@ const int highestPin = 13;
void setup() { void setup() {
// set pins 2 through 13 as outputs: // set pins 2 through 13 as outputs:
for (int thisPin =lowestPin; thisPin <= highestPin; thisPin++) { for (int thisPin = lowestPin; thisPin <= highestPin; thisPin++) {
pinMode(thisPin, OUTPUT); pinMode(thisPin, OUTPUT);
} }
} }
void loop() { void loop() {
// iterate over the pins: // iterate over the pins:
for (int thisPin =lowestPin; thisPin <= highestPin; thisPin++) { for (int thisPin = lowestPin; thisPin <= highestPin; thisPin++) {
// fade the LED on thisPin from off to brightest: // fade the LED on thisPin from off to brightest:
for (int brightness = 0; brightness < 255; brightness++) { for (int brightness = 0; brightness < 255; brightness++) {
analogWrite(thisPin, brightness); analogWrite(thisPin, brightness);
delay(2); delay(2);
} }
// fade the LED on thisPin from brithstest to off: // fade the LED on thisPin from brithstest to off:
for (int brightness = 255; brightness >= 0; brightness--) { for (int brightness = 255; brightness >= 0; brightness--) {
analogWrite(thisPin, brightness); analogWrite(thisPin, brightness);
delay(2); delay(2);
} }
// pause between LEDs: // pause between LEDs:
delay(100); delay(100);
} }

View File

@ -1,29 +1,29 @@
/* /*
Calibration Calibration
Demonstrates one technique for calibrating sensor input. The Demonstrates one technique for calibrating sensor input. The
sensor readings during the first five seconds of the sketch sensor readings during the first five seconds of the sketch
execution define the minimum and maximum of expected values execution define the minimum and maximum of expected values
attached to the sensor pin. attached to the sensor pin.
The sensor minimum and maximum initial values may seem backwards. The sensor minimum and maximum initial values may seem backwards.
Initially, you set the minimum high and listen for anything Initially, you set the minimum high and listen for anything
lower, saving it as the new minimum. Likewise, you set the lower, saving it as the new minimum. Likewise, you set the
maximum low and listen for anything higher as the new maximum. maximum low and listen for anything higher as the new maximum.
The circuit: The circuit:
* Analog sensor (potentiometer will do) attached to analog input 0 * Analog sensor (potentiometer will do) attached to analog input 0
* LED attached from digital pin 9 to ground * LED attached from digital pin 9 to ground
created 29 Oct 2008 created 29 Oct 2008
By David A Mellis By David A Mellis
modified 30 Aug 2011 modified 30 Aug 2011
By Tom Igoe By Tom Igoe
http://arduino.cc/en/Tutorial/Calibration http://arduino.cc/en/Tutorial/Calibration
This example code is in the public domain. This example code is in the public domain.
*/ */
// These constants won't change: // These constants won't change:
@ -41,7 +41,7 @@ void setup() {
pinMode(13, OUTPUT); pinMode(13, OUTPUT);
digitalWrite(13, HIGH); digitalWrite(13, HIGH);
// calibrate during the first five seconds // calibrate during the first five seconds
while (millis() < 5000) { while (millis() < 5000) {
sensorValue = analogRead(sensorPin); sensorValue = analogRead(sensorPin);

View File

@ -1,45 +1,45 @@
/* /*
Fading Fading
This example shows how to fade an LED using the analogWrite() function. This example shows how to fade an LED using the analogWrite() function.
The circuit: The circuit:
* LED attached from digital pin 9 to ground. * LED attached from digital pin 9 to ground.
Created 1 Nov 2008 Created 1 Nov 2008
By David A. Mellis By David A. Mellis
modified 30 Aug 2011 modified 30 Aug 2011
By Tom Igoe By Tom Igoe
http://arduino.cc/en/Tutorial/Fading http://arduino.cc/en/Tutorial/Fading
This example code is in the public domain. This example code is in the public domain.
*/ */
int ledPin = 9; // LED connected to digital pin 9 int ledPin = 9; // LED connected to digital pin 9
void setup() { void setup() {
// nothing happens in setup // nothing happens in setup
} }
void loop() { void loop() {
// fade in from min to max in increments of 5 points: // fade in from min to max in increments of 5 points:
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) { for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
// sets the value (range from 0 to 255): // sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue); analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect // wait for 30 milliseconds to see the dimming effect
delay(30); delay(30);
} }
// fade out from max to min in increments of 5 points: // fade out from max to min in increments of 5 points:
for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) { for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {
// sets the value (range from 0 to 255): // sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue); analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect // wait for 30 milliseconds to see the dimming effect
delay(30); delay(30);
} }
} }

View File

@ -3,9 +3,9 @@
Smoothing Smoothing
Reads repeatedly from an analog input, calculating a running average Reads repeatedly from an analog input, calculating a running average
and printing it to the computer. Keeps ten readings in an array and and printing it to the computer. Keeps ten readings in an array and
continually averages them. continually averages them.
The circuit: The circuit:
* Analog sensor (potentiometer will do) attached to analog input 0 * Analog sensor (potentiometer will do) attached to analog input 0
@ -14,7 +14,7 @@
modified 9 Apr 2012 modified 9 Apr 2012
by Tom Igoe by Tom Igoe
http://www.arduino.cc/en/Tutorial/Smoothing http://www.arduino.cc/en/Tutorial/Smoothing
This example code is in the public domain. This example code is in the public domain.
@ -37,32 +37,32 @@ int inputPin = A0;
void setup() void setup()
{ {
// initialize serial communication with computer: // initialize serial communication with computer:
Serial.begin(9600); Serial.begin(9600);
// initialize all the readings to 0: // initialize all the readings to 0:
for (int thisReading = 0; thisReading < numReadings; thisReading++) for (int thisReading = 0; thisReading < numReadings; thisReading++)
readings[thisReading] = 0; readings[thisReading] = 0;
} }
void loop() { void loop() {
// subtract the last reading: // subtract the last reading:
total= total - readings[index]; total = total - readings[index];
// read from the sensor: // read from the sensor:
readings[index] = analogRead(inputPin); readings[index] = analogRead(inputPin);
// add the reading to the total: // add the reading to the total:
total= total + readings[index]; total = total + readings[index];
// advance to the next position in the array: // advance to the next position in the array:
index = index + 1; index = index + 1;
// if we're at the end of the array... // if we're at the end of the array...
if (index >= numReadings) if (index >= numReadings)
// ...wrap around to the beginning: // ...wrap around to the beginning:
index = 0; index = 0;
// calculate the average: // calculate the average:
average = total / numReadings; average = total / numReadings;
// send it to the computer as ASCII digits // send it to the computer as ASCII digits
Serial.println(average); Serial.println(average);
delay(1); // delay in between reads for stability delay(1); // delay in between reads for stability
} }

View File

@ -1,78 +1,78 @@
/* /*
ASCII table ASCII table
Prints out byte values in all possible formats: Prints out byte values in all possible formats:
* as raw binary values * as raw binary values
* as ASCII-encoded decimal, hex, octal, and binary values * as ASCII-encoded decimal, hex, octal, and binary values
For more on ASCII, see http://www.asciitable.com and http://en.wikipedia.org/wiki/ASCII For more on ASCII, see http://www.asciitable.com and http://en.wikipedia.org/wiki/ASCII
The circuit: No external hardware needed. The circuit: No external hardware needed.
created 2006 created 2006
by Nicholas Zambetti by Nicholas Zambetti
modified 9 Apr 2012 modified 9 Apr 2012
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
<http://www.zambetti.com> <http://www.zambetti.com>
*/ */
void setup() { void setup() {
//Initialize serial and wait for port to open: //Initialize serial and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only ; // wait for serial port to connect. Needed for Leonardo only
} }
// prints title with ending line break // prints title with ending line break
Serial.println("ASCII Table ~ Character Map"); Serial.println("ASCII Table ~ Character Map");
} }
// first visible ASCIIcharacter '!' is number 33: // first visible ASCIIcharacter '!' is number 33:
int thisByte = 33; int thisByte = 33;
// you can also write ASCII characters in single quotes. // you can also write ASCII characters in single quotes.
// for example. '!' is the same as 33, so you could also use this: // for example. '!' is the same as 33, so you could also use this:
//int thisByte = '!'; //int thisByte = '!';
void loop() { void loop() {
// prints value unaltered, i.e. the raw binary version of the // prints value unaltered, i.e. the raw binary version of the
// byte. The serial monitor interprets all bytes as // byte. The serial monitor interprets all bytes as
// ASCII, so 33, the first number, will show up as '!' // ASCII, so 33, the first number, will show up as '!'
Serial.write(thisByte); Serial.write(thisByte);
Serial.print(", dec: "); Serial.print(", dec: ");
// prints value as string as an ASCII-encoded decimal (base 10). // prints value as string as an ASCII-encoded decimal (base 10).
// Decimal is the default format for Serial.print() and Serial.println(), // Decimal is the default format for Serial.print() and Serial.println(),
// so no modifier is needed: // so no modifier is needed:
Serial.print(thisByte); Serial.print(thisByte);
// But you can declare the modifier for decimal if you want to. // But you can declare the modifier for decimal if you want to.
//this also works if you uncomment it: //this also works if you uncomment it:
// Serial.print(thisByte, DEC); // Serial.print(thisByte, DEC);
Serial.print(", hex: "); Serial.print(", hex: ");
// prints value as string in hexadecimal (base 16): // prints value as string in hexadecimal (base 16):
Serial.print(thisByte, HEX); Serial.print(thisByte, HEX);
Serial.print(", oct: "); Serial.print(", oct: ");
// prints value as string in octal (base 8); // prints value as string in octal (base 8);
Serial.print(thisByte, OCT); Serial.print(thisByte, OCT);
Serial.print(", bin: "); Serial.print(", bin: ");
// prints value as string in binary (base 2) // prints value as string in binary (base 2)
// also prints ending line break: // also prints ending line break:
Serial.println(thisByte, BIN); Serial.println(thisByte, BIN);
// if printed last visible character '~' or 126, stop: // if printed last visible character '~' or 126, stop:
if(thisByte == 126) { // you could also use if (thisByte == '~') { if (thisByte == 126) { // you could also use if (thisByte == '~') {
// This loop loops forever and does nothing // This loop loops forever and does nothing
while(true) { while (true) {
continue; continue;
} }
} }
// go on to the next character // go on to the next character
thisByte++; thisByte++;
} }

View File

@ -1,24 +1,24 @@
/* /*
Dimmer Dimmer
Demonstrates the sending data from the computer to the Arduino board, Demonstrates the sending data from the computer to the Arduino board,
in this case to control the brightness of an LED. The data is sent in this case to control the brightness of an LED. The data is sent
in individual bytes, each of which ranges from 0 to 255. Arduino in individual bytes, each of which ranges from 0 to 255. Arduino
reads these bytes and uses them to set the brightness of the LED. reads these bytes and uses them to set the brightness of the LED.
The circuit: The circuit:
LED attached from digital pin 9 to ground. LED attached from digital pin 9 to ground.
Serial connection to Processing, Max/MSP, or another serial application Serial connection to Processing, Max/MSP, or another serial application
created 2006 created 2006
by David A. Mellis by David A. Mellis
modified 30 Aug 2011 modified 30 Aug 2011
by Tom Igoe and Scott Fitzgerald by Tom Igoe and Scott Fitzgerald
This example code is in the public domain. This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Dimmer http://www.arduino.cc/en/Tutorial/Dimmer
*/ */
const int ledPin = 9; // the pin that the LED is attached to const int ledPin = 9; // the pin that the LED is attached to
@ -47,35 +47,35 @@ void loop() {
// Dimmer - sends bytes over a serial port // Dimmer - sends bytes over a serial port
// by David A. Mellis // by David A. Mellis
//This example code is in the public domain. //This example code is in the public domain.
import processing.serial.*; import processing.serial.*;
Serial port; Serial port;
void setup() { void setup() {
size(256, 150); size(256, 150);
println("Available serial ports:"); println("Available serial ports:");
println(Serial.list()); println(Serial.list());
// Uses the first port in this list (number 0). Change this to // Uses the first port in this list (number 0). Change this to
// select the port corresponding to your Arduino board. The last // select the port corresponding to your Arduino board. The last
// parameter (e.g. 9600) is the speed of the communication. It // parameter (e.g. 9600) is the speed of the communication. It
// has to correspond to the value passed to Serial.begin() in your // has to correspond to the value passed to Serial.begin() in your
// Arduino sketch. // Arduino sketch.
port = new Serial(this, Serial.list()[0], 9600); port = new Serial(this, Serial.list()[0], 9600);
// If you know the name of the port used by the Arduino board, you // If you know the name of the port used by the Arduino board, you
// can specify it directly like this. // can specify it directly like this.
//port = new Serial(this, "COM1", 9600); //port = new Serial(this, "COM1", 9600);
} }
void draw() { void draw() {
// draw a gradient from black to white // draw a gradient from black to white
for (int i = 0; i < 256; i++) { for (int i = 0; i < 256; i++) {
stroke(i); stroke(i);
line(i, 0, i, 150); line(i, 0, i, 150);
} }
// write the current X-position of the mouse to the serial port as // write the current X-position of the mouse to the serial port as
// a single byte // a single byte
port.write(mouseX); port.write(mouseX);
@ -83,7 +83,7 @@ void loop() {
*/ */
/* Max/MSP v5 patch for this example /* Max/MSP v5 patch for this example
----------begin_max5_patcher---------- ----------begin_max5_patcher----------
1008.3ocuXszaiaCD9r8uhA5rqAeHIa0aAMaAVf1S6hdoYQAsDiL6JQZHQ2M 1008.3ocuXszaiaCD9r8uhA5rqAeHIa0aAMaAVf1S6hdoYQAsDiL6JQZHQ2M
YWr+2KeX4vjnjXKKkKhhiGQ9MeyCNz+X9rnMp63sQvuB+MLa1OlOalSjUvrC YWr+2KeX4vjnjXKKkKhhiGQ9MeyCNz+X9rnMp63sQvuB+MLa1OlOalSjUvrC

View File

@ -1,26 +1,26 @@
/* /*
Graph Graph
A simple example of communication from the Arduino board to the computer: A simple example of communication from the Arduino board to the computer:
the value of analog input 0 is sent out the serial port. We call this "serial" the value of analog input 0 is sent out the serial port. We call this "serial"
communication because the connection appears to both the Arduino and the communication because the connection appears to both the Arduino and the
computer as a serial port, even though it may actually use computer as a serial port, even though it may actually use
a USB cable. Bytes are sent one after another (serially) from the Arduino a USB cable. Bytes are sent one after another (serially) from the Arduino
to the computer. to the computer.
You can use the Arduino serial monitor to view the sent data, or it can You can use the Arduino serial monitor to view the sent data, or it can
be read by Processing, PD, Max/MSP, or any other program capable of reading be read by Processing, PD, Max/MSP, or any other program capable of reading
data from a serial port. The Processing code below graphs the data received data from a serial port. The Processing code below graphs the data received
so you can see the value of the analog input changing over time. so you can see the value of the analog input changing over time.
The circuit: The circuit:
Any analog input sensor is attached to analog in pin 0. Any analog input sensor is attached to analog in pin 0.
created 2006 created 2006
by David A. Mellis by David A. Mellis
modified 9 Apr 2012 modified 9 Apr 2012
by Tom Igoe and Scott Fitzgerald by Tom Igoe and Scott Fitzgerald
This example code is in the public domain. This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Graph http://www.arduino.cc/en/Tutorial/Graph
@ -34,34 +34,34 @@ void setup() {
void loop() { void loop() {
// send the value of analog input 0: // send the value of analog input 0:
Serial.println(analogRead(A0)); Serial.println(analogRead(A0));
// wait a bit for the analog-to-digital converter // wait a bit for the analog-to-digital converter
// to stabilize after the last reading: // to stabilize after the last reading:
delay(2); delay(2);
} }
/* Processing code for this example /* Processing code for this example
// Graphing sketch // Graphing sketch
// This program takes ASCII-encoded strings // This program takes ASCII-encoded strings
// from the serial port at 9600 baud and graphs them. It expects values in the // from the serial port at 9600 baud and graphs them. It expects values in the
// range 0 to 1023, followed by a newline, or newline and carriage return // range 0 to 1023, followed by a newline, or newline and carriage return
// Created 20 Apr 2005 // Created 20 Apr 2005
// Updated 18 Jan 2008 // Updated 18 Jan 2008
// by Tom Igoe // by Tom Igoe
// This example code is in the public domain. // This example code is in the public domain.
import processing.serial.*; import processing.serial.*;
Serial myPort; // The serial port Serial myPort; // The serial port
int xPos = 1; // horizontal position of the graph int xPos = 1; // horizontal position of the graph
void setup () { void setup () {
// set the window size: // set the window size:
size(400, 300); size(400, 300);
// List all the available serial ports // List all the available serial ports
println(Serial.list()); println(Serial.list());
// I know that the first port in the serial list on my mac // I know that the first port in the serial list on my mac
@ -76,34 +76,34 @@ void loop() {
void draw () { void draw () {
// everything happens in the serialEvent() // everything happens in the serialEvent()
} }
void serialEvent (Serial myPort) { void serialEvent (Serial myPort) {
// get the ASCII string: // get the ASCII string:
String inString = myPort.readStringUntil('\n'); String inString = myPort.readStringUntil('\n');
if (inString != null) { if (inString != null) {
// trim off any whitespace: // trim off any whitespace:
inString = trim(inString); inString = trim(inString);
// convert to an int and map to the screen height: // convert to an int and map to the screen height:
float inByte = float(inString); float inByte = float(inString);
inByte = map(inByte, 0, 1023, 0, height); inByte = map(inByte, 0, 1023, 0, height);
// draw the line: // draw the line:
stroke(127,34,255); stroke(127,34,255);
line(xPos, height, xPos, height - inByte); line(xPos, height, xPos, height - inByte);
// at the edge of the screen, go back to the beginning: // at the edge of the screen, go back to the beginning:
if (xPos >= width) { if (xPos >= width) {
xPos = 0; xPos = 0;
background(0); background(0);
} }
else { else {
// increment the horizontal position: // increment the horizontal position:
xPos++; xPos++;
} }
} }
} }
*/ */
/* Max/MSP v5 patch for this example /* Max/MSP v5 patch for this example
@ -145,5 +145,5 @@ RnMj5vGl1Fs16drnk7Tf1XOLgv1n0d2iEsCxR.eQsNOZ4FGF7whofgfI3kES
1kCeOX5L2rifbdu0A9ae2X.V33B1Z+.Bj1FrP5iFrCYCG5EUWSG.hhunHJd. 1kCeOX5L2rifbdu0A9ae2X.V33B1Z+.Bj1FrP5iFrCYCG5EUWSG.hhunHJd.
HJ5hhnng3h9HPj4lud02.1bxGw. HJ5hhnng3h9HPj4lud02.1bxGw.
-----------end_max5_patcher----------- -----------end_max5_patcher-----------
*/ */

View File

@ -1,11 +1,11 @@
/* /*
MIDI note player MIDI note player
This sketch shows how to use the serial transmit pin (pin 1) to send MIDI note data. This sketch shows how to use the serial transmit pin (pin 1) to send MIDI note data.
If this circuit is connected to a MIDI synth, it will play If this circuit is connected to a MIDI synth, it will play
the notes F#-0 (0x1E) to F#-5 (0x5A) in sequence. the notes F#-0 (0x1E) to F#-5 (0x5A) in sequence.
The circuit: The circuit:
* digital in 1 connected to MIDI jack pin 5 * digital in 1 connected to MIDI jack pin 5
* MIDI jack pin 2 connected to ground * MIDI jack pin 2 connected to ground
@ -14,12 +14,12 @@
created 13 Jun 2006 created 13 Jun 2006
modified 13 Aug 2012 modified 13 Aug 2012
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Midi http://www.arduino.cc/en/Tutorial/Midi
*/ */
void setup() { void setup() {
@ -34,7 +34,7 @@ void loop() {
noteOn(0x90, note, 0x45); noteOn(0x90, note, 0x45);
delay(100); delay(100);
//Note on channel 1 (0x90), some note value (note), silent velocity (0x00): //Note on channel 1 (0x90), some note value (note), silent velocity (0x00):
noteOn(0x90, note, 0x00); noteOn(0x90, note, 0x00);
delay(100); delay(100);
} }
} }

View File

@ -1,21 +1,21 @@
/* /*
Mega multple serial test Mega multple serial test
Receives from the main serial port, sends to the others. Receives from the main serial port, sends to the others.
Receives from serial port 1, sends to the main serial (Serial 0). Receives from serial port 1, sends to the main serial (Serial 0).
This example works only on the Arduino Mega This example works only on the Arduino Mega
The circuit: The circuit:
* Any serial device attached to Serial port 1 * Any serial device attached to Serial port 1
* Serial monitor open on Serial port 0: * Serial monitor open on Serial port 0:
created 30 Dec. 2008 created 30 Dec. 2008
modified 20 May 2012 modified 20 May 2012
by Tom Igoe & Jed Roach by Tom Igoe & Jed Roach
This example code is in the public domain. This example code is in the public domain.
*/ */
@ -29,12 +29,12 @@ void loop() {
// read from port 1, send to port 0: // read from port 1, send to port 0:
if (Serial1.available()) { if (Serial1.available()) {
int inByte = Serial1.read(); int inByte = Serial1.read();
Serial.write(inByte); Serial.write(inByte);
} }
// read from port 0, send to port 1: // read from port 0, send to port 1:
if (Serial.available()) { if (Serial.available()) {
int inByte = Serial.read(); int inByte = Serial.read();
Serial1.write(inByte); Serial1.write(inByte);
} }
} }

View File

@ -1,23 +1,23 @@
/* /*
Physical Pixel Physical Pixel
An example of using the Arduino board to receive data from the An example of using the Arduino board to receive data from the
computer. In this case, the Arduino boards turns on an LED when computer. In this case, the Arduino boards turns on an LED when
it receives the character 'H', and turns off the LED when it it receives the character 'H', and turns off the LED when it
receives the character 'L'. receives the character 'L'.
The data can be sent from the Arduino serial monitor, or another The data can be sent from the Arduino serial monitor, or another
program like Processing (see code below), Flash (via a serial-net program like Processing (see code below), Flash (via a serial-net
proxy), PD, or Max/MSP. proxy), PD, or Max/MSP.
The circuit: The circuit:
* LED connected from digital pin 13 to ground * LED connected from digital pin 13 to ground
created 2006 created 2006
by David A. Mellis by David A. Mellis
modified 30 Aug 2011 modified 30 Aug 2011
by Tom Igoe and Scott Fitzgerald by Tom Igoe and Scott Fitzgerald
This example code is in the public domain. This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/PhysicalPixel http://www.arduino.cc/en/Tutorial/PhysicalPixel
@ -41,7 +41,7 @@ void loop() {
// if it's a capital H (ASCII 72), turn on the LED: // if it's a capital H (ASCII 72), turn on the LED:
if (incomingByte == 'H') { if (incomingByte == 'H') {
digitalWrite(ledPin, HIGH); digitalWrite(ledPin, HIGH);
} }
// if it's an L (ASCII 76) turn off the LED: // if it's an L (ASCII 76) turn off the LED:
if (incomingByte == 'L') { if (incomingByte == 'L') {
digitalWrite(ledPin, LOW); digitalWrite(ledPin, LOW);
@ -50,76 +50,76 @@ void loop() {
} }
/* Processing code for this example /* Processing code for this example
// mouseover serial // mouseover serial
// Demonstrates how to send data to the Arduino I/O board, in order to // Demonstrates how to send data to the Arduino I/O board, in order to
// turn ON a light if the mouse is over a square and turn it off // turn ON a light if the mouse is over a square and turn it off
// if the mouse is not. // if the mouse is not.
// created 2003-4 // created 2003-4
// based on examples by Casey Reas and Hernando Barragan // based on examples by Casey Reas and Hernando Barragan
// modified 30 Aug 2011 // modified 30 Aug 2011
// by Tom Igoe // by Tom Igoe
// This example code is in the public domain. // This example code is in the public domain.
import processing.serial.*; import processing.serial.*;
float boxX; float boxX;
float boxY; float boxY;
int boxSize = 20; int boxSize = 20;
boolean mouseOverBox = false; boolean mouseOverBox = false;
Serial port; Serial port;
void setup() { void setup() {
size(200, 200); size(200, 200);
boxX = width/2.0; boxX = width/2.0;
boxY = height/2.0; boxY = height/2.0;
rectMode(RADIUS); rectMode(RADIUS);
// List all the available serial ports in the output pane. // List all the available serial ports in the output pane.
// You will need to choose the port that the Arduino board is // You will need to choose the port that the Arduino board is
// connected to from this list. The first port in the list is // connected to from this list. The first port in the list is
// port #0 and the third port in the list is port #2. // port #0 and the third port in the list is port #2.
println(Serial.list()); println(Serial.list());
// Open the port that the Arduino board is connected to (in this case #0) // Open the port that the Arduino board is connected to (in this case #0)
// Make sure to open the port at the same speed Arduino is using (9600bps) // Make sure to open the port at the same speed Arduino is using (9600bps)
port = new Serial(this, Serial.list()[0], 9600); port = new Serial(this, Serial.list()[0], 9600);
} }
void draw() void draw()
{ {
background(0); background(0);
// Test if the cursor is over the box // Test if the cursor is over the box
if (mouseX > boxX-boxSize && mouseX < boxX+boxSize && if (mouseX > boxX-boxSize && mouseX < boxX+boxSize &&
mouseY > boxY-boxSize && mouseY < boxY+boxSize) { mouseY > boxY-boxSize && mouseY < boxY+boxSize) {
mouseOverBox = true; mouseOverBox = true;
// draw a line around the box and change its color: // draw a line around the box and change its color:
stroke(255); stroke(255);
fill(153); fill(153);
// send an 'H' to indicate mouse is over square: // send an 'H' to indicate mouse is over square:
port.write('H'); port.write('H');
} }
else { else {
// return the box to it's inactive state: // return the box to it's inactive state:
stroke(153); stroke(153);
fill(153); fill(153);
// send an 'L' to turn the LED off: // send an 'L' to turn the LED off:
port.write('L'); port.write('L');
mouseOverBox = false; mouseOverBox = false;
} }
// Draw the box // Draw the box
rect(boxX, boxY, boxSize, boxSize); rect(boxX, boxY, boxSize, boxSize);
} }
*/ */
/* /*
@ -165,6 +165,6 @@ uVr3PO8wWwEoTW8lsfraX7ZqzZDDXCRqNkztHsGCYpIDDAOqxDpMVUMKcOrp
hN97JSnSfLUXGUoj6ujWXd6Pk1SAC+Pkogm.tZ.1lX1qL.pe6PE11DPeMMZ2 hN97JSnSfLUXGUoj6ujWXd6Pk1SAC+Pkogm.tZ.1lX1qL.pe6PE11DPeMMZ2
.P0K+3peBt3NskC .P0K+3peBt3NskC
-----------end_max5_patcher----------- -----------end_max5_patcher-----------
*/ */

View File

@ -1,19 +1,19 @@
/* /*
Reading a serial ASCII-encoded string. Reading a serial ASCII-encoded string.
This sketch demonstrates the Serial parseInt() function. This sketch demonstrates the Serial parseInt() function.
It looks for an ASCII string of comma-separated values. It looks for an ASCII string of comma-separated values.
It parses them into ints, and uses those to fade an RGB LED. It parses them into ints, and uses those to fade an RGB LED.
Circuit: Common-anode RGB LED wired like so: Circuit: Common-anode RGB LED wired like so:
* Red cathode: digital pin 3 * Red cathode: digital pin 3
* Green cathode: digital pin 5 * Green cathode: digital pin 5
* blue cathode: digital pin 6 * blue cathode: digital pin 6
* anode: +5V * anode: +5V
created 13 Apr 2012 created 13 Apr 2012
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
*/ */
@ -26,9 +26,9 @@ void setup() {
// initialize serial: // initialize serial:
Serial.begin(9600); Serial.begin(9600);
// make the pins outputs: // make the pins outputs:
pinMode(redPin, OUTPUT); pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT); pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT); pinMode(bluePin, OUTPUT);
} }
@ -37,11 +37,11 @@ void loop() {
while (Serial.available() > 0) { while (Serial.available() > 0) {
// look for the next valid integer in the incoming serial stream: // look for the next valid integer in the incoming serial stream:
int red = Serial.parseInt(); int red = Serial.parseInt();
// do it again: // do it again:
int green = Serial.parseInt(); int green = Serial.parseInt();
// do it again: // do it again:
int blue = Serial.parseInt(); int blue = Serial.parseInt();
// look for the newline. That's the end of your // look for the newline. That's the end of your
// sentence: // sentence:
@ -52,7 +52,7 @@ void loop() {
green = 255 - constrain(green, 0, 255); green = 255 - constrain(green, 0, 255);
blue = 255 - constrain(blue, 0, 255); blue = 255 - constrain(blue, 0, 255);
// fade the red, green, and blue legs of the LED: // fade the red, green, and blue legs of the LED:
analogWrite(redPin, red); analogWrite(redPin, red);
analogWrite(greenPin, green); analogWrite(greenPin, green);
analogWrite(bluePin, blue); analogWrite(bluePin, blue);

View File

@ -1,18 +1,18 @@
/* /*
Serial Call and Response Serial Call and Response
Language: Wiring/Arduino Language: Wiring/Arduino
This program sends an ASCII A (byte of value 65) on startup This program sends an ASCII A (byte of value 65) on startup
and repeats that until it gets some data in. and repeats that until it gets some data in.
Then it waits for a byte in the serial port, and Then it waits for a byte in the serial port, and
sends three sensor values whenever it gets a byte in. sends three sensor values whenever it gets a byte in.
Thanks to Greg Shakar and Scott Fitzgerald for the improvements Thanks to Greg Shakar and Scott Fitzgerald for the improvements
The circuit: The circuit:
* potentiometers attached to analog inputs 0 and 1 * potentiometers attached to analog inputs 0 and 1
* pushbutton attached to digital I/O 2 * pushbutton attached to digital I/O 2
Created 26 Sept. 2005 Created 26 Sept. 2005
by Tom Igoe by Tom Igoe
modified 24 April 2012 modified 24 April 2012
@ -38,7 +38,7 @@ void setup()
} }
pinMode(2, INPUT); // digital sensor is on digital pin 2 pinMode(2, INPUT); // digital sensor is on digital pin 2
establishContact(); // send a byte to establish contact until receiver responds establishContact(); // send a byte to establish contact until receiver responds
} }
void loop() void loop()
@ -48,17 +48,17 @@ void loop()
// get incoming byte: // get incoming byte:
inByte = Serial.read(); inByte = Serial.read();
// read first analog input, divide by 4 to make the range 0-255: // read first analog input, divide by 4 to make the range 0-255:
firstSensor = analogRead(A0)/4; firstSensor = analogRead(A0) / 4;
// delay 10ms to let the ADC recover: // delay 10ms to let the ADC recover:
delay(10); delay(10);
// read second analog input, divide by 4 to make the range 0-255: // read second analog input, divide by 4 to make the range 0-255:
secondSensor = analogRead(1)/4; secondSensor = analogRead(1) / 4;
// read switch, map it to 0 or 255L // read switch, map it to 0 or 255L
thirdSensor = map(digitalRead(2), 0, 1, 0, 255); thirdSensor = map(digitalRead(2), 0, 1, 0, 255);
// send sensor values: // send sensor values:
Serial.write(firstSensor); Serial.write(firstSensor);
Serial.write(secondSensor); Serial.write(secondSensor);
Serial.write(thirdSensor); Serial.write(thirdSensor);
} }
} }
@ -115,15 +115,15 @@ void serialEvent(Serial myPort) {
int inByte = myPort.read(); int inByte = myPort.read();
// if this is the first byte received, and it's an A, // if this is the first byte received, and it's an A,
// clear the serial buffer and note that you've // clear the serial buffer and note that you've
// had first contact from the microcontroller. // had first contact from the microcontroller.
// Otherwise, add the incoming byte to the array: // Otherwise, add the incoming byte to the array:
if (firstContact == false) { if (firstContact == false) {
if (inByte == 'A') { if (inByte == 'A') {
myPort.clear(); // clear the serial port buffer myPort.clear(); // clear the serial port buffer
firstContact = true; // you've had first contact from the microcontroller firstContact = true; // you've had first contact from the microcontroller
myPort.write('A'); // ask for more myPort.write('A'); // ask for more
} }
} }
else { else {
// Add the latest byte from the serial port to array: // Add the latest byte from the serial port to array:
serialInArray[serialCount] = inByte; serialInArray[serialCount] = inByte;

View File

@ -1,31 +1,31 @@
/* /*
Serial Call and Response in ASCII Serial Call and Response in ASCII
Language: Wiring/Arduino Language: Wiring/Arduino
This program sends an ASCII A (byte of value 65) on startup This program sends an ASCII A (byte of value 65) on startup
and repeats that until it gets some data in. and repeats that until it gets some data in.
Then it waits for a byte in the serial port, and Then it waits for a byte in the serial port, and
sends three ASCII-encoded, comma-separated sensor values, sends three ASCII-encoded, comma-separated sensor values,
truncated by a linefeed and carriage return, truncated by a linefeed and carriage return,
whenever it gets a byte in. whenever it gets a byte in.
Thanks to Greg Shakar and Scott Fitzgerald for the improvements Thanks to Greg Shakar and Scott Fitzgerald for the improvements
The circuit: The circuit:
* potentiometers attached to analog inputs 0 and 1 * potentiometers attached to analog inputs 0 and 1
* pushbutton attached to digital I/O 2 * pushbutton attached to digital I/O 2
Created 26 Sept. 2005 Created 26 Sept. 2005
by Tom Igoe by Tom Igoe
modified 24 Apr 2012 modified 24 Apr 2012
by Tom Igoe and Scott Fitzgerald by Tom Igoe and Scott Fitzgerald
This example code is in the public domain. This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/SerialCallResponseASCII http://www.arduino.cc/en/Tutorial/SerialCallResponseASCII
*/ */
int firstSensor = 0; // first analog sensor int firstSensor = 0; // first analog sensor
@ -41,9 +41,9 @@ void setup()
; // wait for serial port to connect. Needed for Leonardo only ; // wait for serial port to connect. Needed for Leonardo only
} }
pinMode(2, INPUT); // digital sensor is on digital pin 2 pinMode(2, INPUT); // digital sensor is on digital pin 2
establishContact(); // send a byte to establish contact until receiver responds establishContact(); // send a byte to establish contact until receiver responds
} }
void loop() void loop()
@ -57,13 +57,13 @@ void loop()
// read second analog input: // read second analog input:
secondSensor = analogRead(A1); secondSensor = analogRead(A1);
// read switch, map it to 0 or 255L // read switch, map it to 0 or 255L
thirdSensor = map(digitalRead(2), 0, 1, 0, 255); thirdSensor = map(digitalRead(2), 0, 1, 0, 255);
// send sensor values: // send sensor values:
Serial.print(firstSensor); Serial.print(firstSensor);
Serial.print(","); Serial.print(",");
Serial.print(secondSensor); Serial.print(secondSensor);
Serial.print(","); Serial.print(",");
Serial.println(thirdSensor); Serial.println(thirdSensor);
} }
} }
@ -101,7 +101,7 @@ void setup() {
// read bytes into a buffer until you get a linefeed (ASCII 10): // read bytes into a buffer until you get a linefeed (ASCII 10):
myPort.bufferUntil('\n'); myPort.bufferUntil('\n');
// draw with smooth edges: // draw with smooth edges:
smooth(); smooth();
} }
@ -114,22 +114,22 @@ void draw() {
} }
// serialEvent method is run automatically by the Processing applet // serialEvent method is run automatically by the Processing applet
// whenever the buffer reaches the byte value set in the bufferUntil() // whenever the buffer reaches the byte value set in the bufferUntil()
// method in the setup(): // method in the setup():
void serialEvent(Serial myPort) { void serialEvent(Serial myPort) {
// read the serial buffer: // read the serial buffer:
String myString = myPort.readStringUntil('\n'); String myString = myPort.readStringUntil('\n');
// if you got any bytes other than the linefeed: // if you got any bytes other than the linefeed:
myString = trim(myString); myString = trim(myString);
// split the string at the commas // split the string at the commas
// and convert the sections into integers: // and convert the sections into integers:
int sensors[] = int(split(myString, ',')); int sensors[] = int(split(myString, ','));
// print out the values you got: // print out the values you got:
for (int sensorNum = 0; sensorNum < sensors.length; sensorNum++) { for (int sensorNum = 0; sensorNum < sensors.length; sensorNum++) {
print("Sensor " + sensorNum + ": " + sensors[sensorNum] + "\t"); print("Sensor " + sensorNum + ": " + sensors[sensorNum] + "\t");
} }
// add a linefeed after all the sensor values are printed: // add a linefeed after all the sensor values are printed:
println(); println();

View File

@ -1,20 +1,20 @@
/* /*
Serial Event example Serial Event example
When new serial data arrives, this sketch adds it to a String. When new serial data arrives, this sketch adds it to a String.
When a newline is received, the loop prints the string and When a newline is received, the loop prints the string and
clears it. clears it.
A good test for this is to try it with a GPS receiver A good test for this is to try it with a GPS receiver
that sends out NMEA 0183 sentences. that sends out NMEA 0183 sentences.
Created 9 May 2011 Created 9 May 2011
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/SerialEvent http://www.arduino.cc/en/Tutorial/SerialEvent
*/ */
String inputString = ""; // a string to hold incoming data String inputString = ""; // a string to hold incoming data
@ -30,7 +30,7 @@ void setup() {
void loop() { void loop() {
// print the string when a newline arrives: // print the string when a newline arrives:
if (stringComplete) { if (stringComplete) {
Serial.println(inputString); Serial.println(inputString);
// clear the string: // clear the string:
inputString = ""; inputString = "";
stringComplete = false; stringComplete = false;
@ -46,14 +46,14 @@ void loop() {
void serialEvent() { void serialEvent() {
while (Serial.available()) { while (Serial.available()) {
// get the new byte: // get the new byte:
char inChar = (char)Serial.read(); char inChar = (char)Serial.read();
// add it to the inputString: // add it to the inputString:
inputString += inChar; inputString += inChar;
// if the incoming character is a newline, set a flag // if the incoming character is a newline, set a flag
// so the main loop can do something about it: // so the main loop can do something about it:
if (inChar == '\n') { if (inChar == '\n') {
stringComplete = true; stringComplete = true;
} }
} }
} }

View File

@ -2,17 +2,17 @@
This example reads three analog sensors (potentiometers are easiest) This example reads three analog sensors (potentiometers are easiest)
and sends their values serially. The Processing and Max/MSP programs at the bottom and sends their values serially. The Processing and Max/MSP programs at the bottom
take those three values and use them to change the background color of the screen. take those three values and use them to change the background color of the screen.
The circuit: The circuit:
* potentiometers attached to analog inputs 0, 1, and 2 * potentiometers attached to analog inputs 0, 1, and 2
http://www.arduino.cc/en/Tutorial/VirtualColorMixer http://www.arduino.cc/en/Tutorial/VirtualColorMixer
created 2 Dec 2006 created 2 Dec 2006
by David A. Mellis by David A. Mellis
modified 30 Aug 2011 modified 30 Aug 2011
by Tom Igoe and Scott Fitzgerald by Tom Igoe and Scott Fitzgerald
This example code is in the public domain. This example code is in the public domain.
*/ */
@ -35,20 +35,20 @@ void loop()
} }
/* Processing code for this example /* Processing code for this example
// This example code is in the public domain. // This example code is in the public domain.
import processing.serial.*; import processing.serial.*;
float redValue = 0; // red value float redValue = 0; // red value
float greenValue = 0; // green value float greenValue = 0; // green value
float blueValue = 0; // blue value float blueValue = 0; // blue value
Serial myPort; Serial myPort;
void setup() { void setup() {
size(200, 200); size(200, 200);
// List all the available serial ports // List all the available serial ports
println(Serial.list()); println(Serial.list());
// I know that the first port in the serial list on my mac // I know that the first port in the serial list on my mac
@ -58,20 +58,20 @@ void loop()
// don't generate a serialEvent() unless you get a newline character: // don't generate a serialEvent() unless you get a newline character:
myPort.bufferUntil('\n'); myPort.bufferUntil('\n');
} }
void draw() { void draw() {
// set the background color with the color values: // set the background color with the color values:
background(redValue, greenValue, blueValue); background(redValue, greenValue, blueValue);
} }
void serialEvent(Serial myPort) { void serialEvent(Serial myPort) {
// get the ASCII string: // get the ASCII string:
String inString = myPort.readStringUntil('\n'); String inString = myPort.readStringUntil('\n');
if (inString != null) { if (inString != null) {
// trim off any whitespace: // trim off any whitespace:
inString = trim(inString); inString = trim(inString);
// split the string on the commas and convert the // split the string on the commas and convert the
// resulting substrings into an integer array: // resulting substrings into an integer array:
float[] colors = float(split(inString, ",")); float[] colors = float(split(inString, ","));
// if the array has at least three elements, you know // if the array has at least three elements, you know
@ -126,5 +126,5 @@ ASi6Zyw8.RQi65J8ZsNx3ho93OhGWENtWpowepae4YhCFeLErOLENtXJrOSc
iadi39rf4hwc8xdhHz3gn3dBI7iDRlFe8huAfIZhq iadi39rf4hwc8xdhHz3gn3dBI7iDRlFe8huAfIZhq
-----------end_max5_patcher----------- -----------end_max5_patcher-----------
*/ */

View File

@ -1,52 +1,53 @@
/* /*
Arrays Arrays
Demonstrates the use of an array to hold pin numbers Demonstrates the use of an array to hold pin numbers
in order to iterate over the pins in a sequence. in order to iterate over the pins in a sequence.
Lights multiple LEDs in sequence, then in reverse. Lights multiple LEDs in sequence, then in reverse.
Unlike the For Loop tutorial, where the pins have to be Unlike the For Loop tutorial, where the pins have to be
contiguous, here the pins can be in any random order. contiguous, here the pins can be in any random order.
The circuit: The circuit:
* LEDs from pins 2 through 7 to ground * LEDs from pins 2 through 7 to ground
created 2006 created 2006
by David A. Mellis by David A. Mellis
modified 30 Aug 2011 modified 30 Aug 2011
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Array http://www.arduino.cc/en/Tutorial/Array
*/ */
int timer = 100; // The higher the number, the slower the timing. int timer = 100; // The higher the number, the slower the timing.
int ledPins[] = { int ledPins[] = {
2, 7, 4, 6, 5, 3 }; // an array of pin numbers to which LEDs are attached 2, 7, 4, 6, 5, 3
}; // an array of pin numbers to which LEDs are attached
int pinCount = 6; // the number of pins (i.e. the length of the array) int pinCount = 6; // the number of pins (i.e. the length of the array)
void setup() { void setup() {
// the array elements are numbered from 0 to (pinCount - 1). // the array elements are numbered from 0 to (pinCount - 1).
// use a for loop to initialize each pin as an output: // use a for loop to initialize each pin as an output:
for (int thisPin = 0; thisPin < pinCount; thisPin++) { for (int thisPin = 0; thisPin < pinCount; thisPin++) {
pinMode(ledPins[thisPin], OUTPUT); pinMode(ledPins[thisPin], OUTPUT);
} }
} }
void loop() { void loop() {
// loop from the lowest pin to the highest: // loop from the lowest pin to the highest:
for (int thisPin = 0; thisPin < pinCount; thisPin++) { for (int thisPin = 0; thisPin < pinCount; thisPin++) {
// turn the pin on: // turn the pin on:
digitalWrite(ledPins[thisPin], HIGH); digitalWrite(ledPins[thisPin], HIGH);
delay(timer); delay(timer);
// turn the pin off: // turn the pin off:
digitalWrite(ledPins[thisPin], LOW); digitalWrite(ledPins[thisPin], LOW);
} }
// loop from the highest pin to the lowest: // loop from the highest pin to the lowest:
for (int thisPin = pinCount - 1; thisPin >= 0; thisPin--) { for (int thisPin = pinCount - 1; thisPin >= 0; thisPin--) {
// turn the pin on: // turn the pin on:
digitalWrite(ledPins[thisPin], HIGH); digitalWrite(ledPins[thisPin], HIGH);
delay(timer); delay(timer);

View File

@ -1,19 +1,19 @@
/* /*
For Loop Iteration For Loop Iteration
Demonstrates the use of a for() loop. Demonstrates the use of a for() loop.
Lights multiple LEDs in sequence, then in reverse. Lights multiple LEDs in sequence, then in reverse.
The circuit: The circuit:
* LEDs from pins 2 through 7 to ground * LEDs from pins 2 through 7 to ground
created 2006 created 2006
by David A. Mellis by David A. Mellis
modified 30 Aug 2011 modified 30 Aug 2011
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/ForLoop http://www.arduino.cc/en/Tutorial/ForLoop
*/ */
@ -21,23 +21,23 @@ int timer = 100; // The higher the number, the slower the timing.
void setup() { void setup() {
// use a for loop to initialize each pin as an output: // use a for loop to initialize each pin as an output:
for (int thisPin = 2; thisPin < 8; thisPin++) { for (int thisPin = 2; thisPin < 8; thisPin++) {
pinMode(thisPin, OUTPUT); pinMode(thisPin, OUTPUT);
} }
} }
void loop() { void loop() {
// loop from the lowest pin to the highest: // loop from the lowest pin to the highest:
for (int thisPin = 2; thisPin < 8; thisPin++) { for (int thisPin = 2; thisPin < 8; thisPin++) {
// turn the pin on: // turn the pin on:
digitalWrite(thisPin, HIGH); digitalWrite(thisPin, HIGH);
delay(timer); delay(timer);
// turn the pin off: // turn the pin off:
digitalWrite(thisPin, LOW); digitalWrite(thisPin, LOW);
} }
// loop from the highest pin to the lowest: // loop from the highest pin to the lowest:
for (int thisPin = 7; thisPin >= 2; thisPin--) { for (int thisPin = 7; thisPin >= 2; thisPin--) {
// turn the pin on: // turn the pin on:
digitalWrite(thisPin, HIGH); digitalWrite(thisPin, HIGH);
delay(timer); delay(timer);

View File

@ -1,30 +1,30 @@
/* /*
Conditionals - If statement Conditionals - If statement
This example demonstrates the use of if() statements. This example demonstrates the use of if() statements.
It reads the state of a potentiometer (an analog input) and turns on an LED It reads the state of a potentiometer (an analog input) and turns on an LED
only if the LED goes above a certain threshold level. It prints the analog value only if the LED goes above a certain threshold level. It prints the analog value
regardless of the level. regardless of the level.
The circuit: The circuit:
* potentiometer connected to analog pin 0. * potentiometer connected to analog pin 0.
Center pin of the potentiometer goes to the analog pin. Center pin of the potentiometer goes to the analog pin.
side pins of the potentiometer go to +5V and ground side pins of the potentiometer go to +5V and ground
* LED connected from digital pin 13 to ground * LED connected from digital pin 13 to ground
* Note: On most Arduino boards, there is already an LED on the board * Note: On most Arduino boards, there is already an LED on the board
connected to pin 13, so you don't need any extra components for this example. connected to pin 13, so you don't need any extra components for this example.
created 17 Jan 2009 created 17 Jan 2009
modified 9 Apr 2012 modified 9 Apr 2012
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://arduino.cc/en/Tutorial/IfStatement http://arduino.cc/en/Tutorial/IfStatement
*/ */
// These constants won't change: // These constants won't change:
const int analogPin = A0; // pin that the sensor is attached to const int analogPin = A0; // pin that the sensor is attached to
const int ledPin = 13; // pin that the LED is attached to const int ledPin = 13; // pin that the LED is attached to
@ -44,9 +44,9 @@ void loop() {
// if the analog value is high enough, turn on the LED: // if the analog value is high enough, turn on the LED:
if (analogValue > threshold) { if (analogValue > threshold) {
digitalWrite(ledPin, HIGH); digitalWrite(ledPin, HIGH);
} }
else { else {
digitalWrite(ledPin,LOW); digitalWrite(ledPin, LOW);
} }
// print the analog value: // print the analog value:

View File

@ -1,29 +1,29 @@
/* /*
Conditionals - while statement Conditionals - while statement
This example demonstrates the use of while() statements. This example demonstrates the use of while() statements.
While the pushbutton is pressed, the sketch runs the calibration routine. While the pushbutton is pressed, the sketch runs the calibration routine.
The sensor readings during the while loop define the minimum and maximum The sensor readings during the while loop define the minimum and maximum
of expected values from the photo resistor. of expected values from the photo resistor.
This is a variation on the calibrate example. This is a variation on the calibrate example.
The circuit: The circuit:
* photo resistor connected from +5V to analog in pin 0 * photo resistor connected from +5V to analog in pin 0
* 10K resistor connected from ground to analog in pin 0 * 10K resistor connected from ground to analog in pin 0
* LED connected from digital pin 9 to ground through 220 ohm resistor * LED connected from digital pin 9 to ground through 220 ohm resistor
* pushbutton attached from pin 2 to +5V * pushbutton attached from pin 2 to +5V
* 10K resistor attached from pin 2 to ground * 10K resistor attached from pin 2 to ground
created 17 Jan 2009 created 17 Jan 2009
modified 30 Aug 2011 modified 30 Aug 2011
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://arduino.cc/en/Tutorial/WhileLoop http://arduino.cc/en/Tutorial/WhileLoop
*/ */
@ -50,10 +50,10 @@ void setup() {
void loop() { void loop() {
// while the button is pressed, take calibration readings: // while the button is pressed, take calibration readings:
while (digitalRead(buttonPin) == HIGH) { while (digitalRead(buttonPin) == HIGH) {
calibrate(); calibrate();
} }
// signal the end of the calibration period // signal the end of the calibration period
digitalWrite(indicatorLedPin, LOW); digitalWrite(indicatorLedPin, LOW);
// read the sensor: // read the sensor:
sensorValue = analogRead(sensorPin); sensorValue = analogRead(sensorPin);

View File

@ -1,24 +1,24 @@
/* /*
Switch statement Switch statement
Demonstrates the use of a switch statement. The switch Demonstrates the use of a switch statement. The switch
statement allows you to choose from among a set of discrete values statement allows you to choose from among a set of discrete values
of a variable. It's like a series of if statements. of a variable. It's like a series of if statements.
To see this sketch in action, but the board and sensor in a well-lit To see this sketch in action, but the board and sensor in a well-lit
room, open the serial monitor, and and move your hand gradually room, open the serial monitor, and and move your hand gradually
down over the sensor. down over the sensor.
The circuit: The circuit:
* photoresistor from analog in 0 to +5V * photoresistor from analog in 0 to +5V
* 10K resistor from analog in 0 to ground * 10K resistor from analog in 0 to ground
created 1 Jul 2009 created 1 Jul 2009
modified 9 Apr 2012 modified 9 Apr 2012
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/SwitchCase http://www.arduino.cc/en/Tutorial/SwitchCase
*/ */
@ -29,7 +29,7 @@ const int sensorMax = 600; // sensor maximum, discovered through experiment
void setup() { void setup() {
// initialize serial communication: // initialize serial communication:
Serial.begin(9600); Serial.begin(9600);
} }
void loop() { void loop() {
@ -38,22 +38,22 @@ void loop() {
// map the sensor range to a range of four options: // map the sensor range to a range of four options:
int range = map(sensorReading, sensorMin, sensorMax, 0, 3); int range = map(sensorReading, sensorMin, sensorMax, 0, 3);
// do something different depending on the // do something different depending on the
// range value: // range value:
switch (range) { switch (range) {
case 0: // your hand is on the sensor case 0: // your hand is on the sensor
Serial.println("dark"); Serial.println("dark");
break; break;
case 1: // your hand is close to the sensor case 1: // your hand is close to the sensor
Serial.println("dim"); Serial.println("dim");
break; break;
case 2: // your hand is a few inches from the sensor case 2: // your hand is a few inches from the sensor
Serial.println("medium"); Serial.println("medium");
break; break;
case 3: // your hand is nowhere near the sensor case 3: // your hand is nowhere near the sensor
Serial.println("bright"); Serial.println("bright");
break; break;
} }
delay(1); // delay in between reads for stability delay(1); // delay in between reads for stability
} }

View File

@ -1,66 +1,66 @@
/* /*
Switch statement with serial input Switch statement with serial input
Demonstrates the use of a switch statement. The switch Demonstrates the use of a switch statement. The switch
statement allows you to choose from among a set of discrete values statement allows you to choose from among a set of discrete values
of a variable. It's like a series of if statements. of a variable. It's like a series of if statements.
To see this sketch in action, open the Serial monitor and send any character. To see this sketch in action, open the Serial monitor and send any character.
The characters a, b, c, d, and e, will turn on LEDs. Any other character will turn The characters a, b, c, d, and e, will turn on LEDs. Any other character will turn
the LEDs off. the LEDs off.
The circuit: The circuit:
* 5 LEDs attached to digital pins 2 through 6 through 220-ohm resistors * 5 LEDs attached to digital pins 2 through 6 through 220-ohm resistors
created 1 Jul 2009 created 1 Jul 2009
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/SwitchCase2 http://www.arduino.cc/en/Tutorial/SwitchCase2
*/ */
void setup() { void setup() {
// initialize serial communication: // initialize serial communication:
Serial.begin(9600); Serial.begin(9600);
// initialize the LED pins: // initialize the LED pins:
for (int thisPin = 2; thisPin < 7; thisPin++) { for (int thisPin = 2; thisPin < 7; thisPin++) {
pinMode(thisPin, OUTPUT); pinMode(thisPin, OUTPUT);
} }
} }
void loop() { void loop() {
// read the sensor: // read the sensor:
if (Serial.available() > 0) { if (Serial.available() > 0) {
int inByte = Serial.read(); int inByte = Serial.read();
// do something different depending on the character received. // do something different depending on the character received.
// The switch statement expects single number values for each case; // The switch statement expects single number values for each case;
// in this exmaple, though, you're using single quotes to tell // in this exmaple, though, you're using single quotes to tell
// the controller to get the ASCII value for the character. For // the controller to get the ASCII value for the character. For
// example 'a' = 97, 'b' = 98, and so forth: // example 'a' = 97, 'b' = 98, and so forth:
switch (inByte) { switch (inByte) {
case 'a': case 'a':
digitalWrite(2, HIGH); digitalWrite(2, HIGH);
break; break;
case 'b': case 'b':
digitalWrite(3, HIGH); digitalWrite(3, HIGH);
break; break;
case 'c': case 'c':
digitalWrite(4, HIGH); digitalWrite(4, HIGH);
break; break;
case 'd': case 'd':
digitalWrite(5, HIGH); digitalWrite(5, HIGH);
break; break;
case 'e': case 'e':
digitalWrite(6, HIGH); digitalWrite(6, HIGH);
break; break;
default: default:
// turn all the LEDs off: // turn all the LEDs off:
for (int thisPin = 2; thisPin < 7; thisPin++) { for (int thisPin = 2; thisPin < 7; thisPin++) {
digitalWrite(thisPin, LOW); digitalWrite(thisPin, LOW);
} }
} }
} }
} }

View File

@ -1,7 +1,7 @@
/* /*
ADXL3xx ADXL3xx
Reads an Analog Devices ADXL3xx accelerometer and communicates the Reads an Analog Devices ADXL3xx accelerometer and communicates the
acceleration to the computer. The pins used are designed to be easily acceleration to the computer. The pins used are designed to be easily
compatible with the breakout boards from Sparkfun, available from: compatible with the breakout boards from Sparkfun, available from:
@ -16,12 +16,12 @@
analog 3: x-axis analog 3: x-axis
analog 4: ground analog 4: ground
analog 5: vcc analog 5: vcc
created 2 Jul 2008 created 2 Jul 2008
by David A. Mellis by David A. Mellis
modified 30 Aug 2011 modified 30 Aug 2011
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
*/ */
@ -37,14 +37,14 @@ void setup()
{ {
// initialize the serial communications: // initialize the serial communications:
Serial.begin(9600); Serial.begin(9600);
// Provide ground and power by using the analog inputs as normal // Provide ground and power by using the analog inputs as normal
// digital pins. This makes it possible to directly connect the // digital pins. This makes it possible to directly connect the
// breakout board to the Arduino. If you use the normal 5V and // breakout board to the Arduino. If you use the normal 5V and
// GND pins on the Arduino, you can remove these lines. // GND pins on the Arduino, you can remove these lines.
pinMode(groundpin, OUTPUT); pinMode(groundpin, OUTPUT);
pinMode(powerpin, OUTPUT); pinMode(powerpin, OUTPUT);
digitalWrite(groundpin, LOW); digitalWrite(groundpin, LOW);
digitalWrite(powerpin, HIGH); digitalWrite(powerpin, HIGH);
} }

View File

@ -1,26 +1,26 @@
/* Knock Sensor /* Knock Sensor
This sketch reads a piezo element to detect a knocking sound. This sketch reads a piezo element to detect a knocking sound.
It reads an analog pin and compares the result to a set threshold. It reads an analog pin and compares the result to a set threshold.
If the result is greater than the threshold, it writes If the result is greater than the threshold, it writes
"knock" to the serial port, and toggles the LED on pin 13. "knock" to the serial port, and toggles the LED on pin 13.
The circuit: The circuit:
* + connection of the piezo attached to analog in 0 * + connection of the piezo attached to analog in 0
* - connection of the piezo attached to ground * - connection of the piezo attached to ground
* 1-megohm resistor attached from analog in 0 to ground * 1-megohm resistor attached from analog in 0 to ground
http://www.arduino.cc/en/Tutorial/Knock http://www.arduino.cc/en/Tutorial/Knock
created 25 Mar 2007 created 25 Mar 2007
by David Cuartielles <http://www.0j0.org> by David Cuartielles <http://www.0j0.org>
modified 30 Aug 2011 modified 30 Aug 2011
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
*/ */
// these constants won't change: // these constants won't change:
const int ledPin = 13; // led connected to digital pin 13 const int ledPin = 13; // led connected to digital pin 13
@ -33,22 +33,22 @@ int sensorReading = 0; // variable to store the value read from the sensor
int ledState = LOW; // variable used to store the last LED status, to toggle the light int ledState = LOW; // variable used to store the last LED status, to toggle the light
void setup() { void setup() {
pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
Serial.begin(9600); // use the serial port Serial.begin(9600); // use the serial port
} }
void loop() { void loop() {
// read the sensor and store it in the variable sensorReading: // read the sensor and store it in the variable sensorReading:
sensorReading = analogRead(knockSensor); sensorReading = analogRead(knockSensor);
// if the sensor reading is greater than the threshold: // if the sensor reading is greater than the threshold:
if (sensorReading >= threshold) { if (sensorReading >= threshold) {
// toggle the status of the ledPin: // toggle the status of the ledPin:
ledState = !ledState; ledState = !ledState;
// update the LED pin itself: // update the LED pin itself:
digitalWrite(ledPin, ledState); digitalWrite(ledPin, ledState);
// send the string "Knock!" back to the computer, followed by newline // send the string "Knock!" back to the computer, followed by newline
Serial.println("Knock!"); Serial.println("Knock!");
} }
delay(100); // delay to avoid overloading the serial port buffer delay(100); // delay to avoid overloading the serial port buffer
} }

View File

@ -1,24 +1,24 @@
/* /*
Memsic2125 Memsic2125
Read the Memsic 2125 two-axis accelerometer. Converts the Read the Memsic 2125 two-axis accelerometer. Converts the
pulses output by the 2125 into milli-g's (1/1000 of earth's pulses output by the 2125 into milli-g's (1/1000 of earth's
gravity) and prints them over the serial connection to the gravity) and prints them over the serial connection to the
computer. computer.
The circuit: The circuit:
* X output of accelerometer to digital pin 2 * X output of accelerometer to digital pin 2
* Y output of accelerometer to digital pin 3 * Y output of accelerometer to digital pin 3
* +V of accelerometer to +5V * +V of accelerometer to +5V
* GND of accelerometer to ground * GND of accelerometer to ground
http://www.arduino.cc/en/Tutorial/Memsic2125 http://www.arduino.cc/en/Tutorial/Memsic2125
created 6 Nov 2008 created 6 Nov 2008
by David A. Mellis by David A. Mellis
modified 30 Aug 2011 modified 30 Aug 2011
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
*/ */
@ -41,13 +41,13 @@ void loop() {
int pulseX, pulseY; int pulseX, pulseY;
// variables to contain the resulting accelerations // variables to contain the resulting accelerations
int accelerationX, accelerationY; int accelerationX, accelerationY;
// read pulse from x- and y-axes: // read pulse from x- and y-axes:
pulseX = pulseIn(xPin,HIGH); pulseX = pulseIn(xPin, HIGH);
pulseY = pulseIn(yPin,HIGH); pulseY = pulseIn(yPin, HIGH);
// convert the pulse width into acceleration // convert the pulse width into acceleration
// accelerationX and accelerationY are in milli-g's: // accelerationX and accelerationY are in milli-g's:
// earth's gravity is 1000 milli-g's, or 1g. // earth's gravity is 1000 milli-g's, or 1g.
accelerationX = ((pulseX / 10) - 500) * 8; accelerationX = ((pulseX / 10) - 500) * 8;
accelerationY = ((pulseY / 10) - 500) * 8; accelerationY = ((pulseY / 10) - 500) * 8;

View File

@ -1,23 +1,23 @@
/* Ping))) Sensor /* Ping))) Sensor
This sketch reads a PING))) ultrasonic rangefinder and returns the This sketch reads a PING))) ultrasonic rangefinder and returns the
distance to the closest object in range. To do this, it sends a pulse distance to the closest object in range. To do this, it sends a pulse
to the sensor to initiate a reading, then listens for a pulse to the sensor to initiate a reading, then listens for a pulse
to return. The length of the returning pulse is proportional to to return. The length of the returning pulse is proportional to
the distance of the object from the sensor. the distance of the object from the sensor.
The circuit: The circuit:
* +V connection of the PING))) attached to +5V * +V connection of the PING))) attached to +5V
* GND connection of the PING))) attached to ground * GND connection of the PING))) attached to ground
* SIG connection of the PING))) attached to digital pin 7 * SIG connection of the PING))) attached to digital pin 7
http://www.arduino.cc/en/Tutorial/Ping http://www.arduino.cc/en/Tutorial/Ping
created 3 Nov 2008 created 3 Nov 2008
by David A. Mellis by David A. Mellis
modified 30 Aug 2011 modified 30 Aug 2011
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
*/ */
@ -33,7 +33,7 @@ void setup() {
void loop() void loop()
{ {
// establish variables for duration of the ping, // establish variables for duration of the ping,
// and the distance result in inches and centimeters: // and the distance result in inches and centimeters:
long duration, inches, cm; long duration, inches, cm;
@ -55,13 +55,13 @@ void loop()
// convert the time into a distance // convert the time into a distance
inches = microsecondsToInches(duration); inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration); cm = microsecondsToCentimeters(duration);
Serial.print(inches); Serial.print(inches);
Serial.print("in, "); Serial.print("in, ");
Serial.print(cm); Serial.print(cm);
Serial.print("cm"); Serial.print("cm");
Serial.println(); Serial.println();
delay(100); delay(100);
} }

View File

@ -1,23 +1,23 @@
/* /*
Row-Column Scanning an 8x8 LED matrix with X-Y input Row-Column Scanning an 8x8 LED matrix with X-Y input
This example controls an 8x8 LED matrix using two analog inputs This example controls an 8x8 LED matrix using two analog inputs
created 27 May 2009 created 27 May 2009
modified 30 Aug 2011 modified 30 Aug 2011
by Tom Igoe by Tom Igoe
This example works for the Lumex LDM-24488NI Matrix. See This example works for the Lumex LDM-24488NI Matrix. See
http://sigma.octopart.com/140413/datasheet/Lumex-LDM-24488NI.pdf http://sigma.octopart.com/140413/datasheet/Lumex-LDM-24488NI.pdf
for the pin connections for the pin connections
For other LED cathode column matrixes, you should only need to change For other LED cathode column matrixes, you should only need to change
the pin numbers in the row[] and column[] arrays the pin numbers in the row[] and column[] arrays
rows are the anodes rows are the anodes
cols are the cathodes cols are the cathodes
--------- ---------
Pin numbers: Pin numbers:
Matrix: Matrix:
* Digital pins 2 through 13, * Digital pins 2 through 13,
@ -25,25 +25,27 @@
Potentiometers: Potentiometers:
* center pins are attached to analog pins 0 and 1, respectively * center pins are attached to analog pins 0 and 1, respectively
* side pins attached to +5V and ground, respectively. * side pins attached to +5V and ground, respectively.
This example code is in the public domain. This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/RowColumnScanning http://www.arduino.cc/en/Tutorial/RowColumnScanning
see also http://www.tigoe.net/pcomp/code/category/arduinowiring/514 for more see also http://www.tigoe.net/pcomp/code/category/arduinowiring/514 for more
*/ */
// 2-dimensional array of row pin numbers: // 2-dimensional array of row pin numbers:
const int row[8] = { const int row[8] = {
2,7,19,5,13,18,12,16 }; 2, 7, 19, 5, 13, 18, 12, 16
};
// 2-dimensional array of column pin numbers: // 2-dimensional array of column pin numbers:
const int col[8] = { const int col[8] = {
6,11,10,3,17,4,8,9 }; 6, 11, 10, 3, 17, 4, 8, 9
};
// 2-dimensional array of pixels: // 2-dimensional array of pixels:
int pixels[8][8]; int pixels[8][8];
// cursor position: // cursor position:
int x = 5; int x = 5;
@ -54,11 +56,11 @@ void setup() {
// iterate over the pins: // iterate over the pins:
for (int thisPin = 0; thisPin < 8; thisPin++) { for (int thisPin = 0; thisPin < 8; thisPin++) {
// initialize the output pins: // initialize the output pins:
pinMode(col[thisPin], OUTPUT); pinMode(col[thisPin], OUTPUT);
pinMode(row[thisPin], OUTPUT); pinMode(row[thisPin], OUTPUT);
// take the col pins (i.e. the cathodes) high to ensure that // take the col pins (i.e. the cathodes) high to ensure that
// the LEDS are off: // the LEDS are off:
digitalWrite(col[thisPin], HIGH); digitalWrite(col[thisPin], HIGH);
} }
// initialize the pixel matrix: // initialize the pixel matrix:

View File

@ -1,22 +1,22 @@
/* /*
LED bar graph LED bar graph
Turns on a series of LEDs based on the value of an analog sensor. Turns on a series of LEDs based on the value of an analog sensor.
This is a simple way to make a bar graph display. Though this graph This is a simple way to make a bar graph display. Though this graph
uses 10 LEDs, you can use any number by changing the LED count uses 10 LEDs, you can use any number by changing the LED count
and the pins in the array. and the pins in the array.
This method can be used to control any series of digital outputs that This method can be used to control any series of digital outputs that
depends on an analog input. depends on an analog input.
The circuit: The circuit:
* LEDs from pins 2 through 11 to ground * LEDs from pins 2 through 11 to ground
created 4 Sep 2010 created 4 Sep 2010
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/BarGraph http://www.arduino.cc/en/Tutorial/BarGraph
*/ */
@ -25,14 +25,15 @@
const int analogPin = A0; // the pin that the potentiometer is attached to const int analogPin = A0; // the pin that the potentiometer is attached to
const int ledCount = 10; // the number of LEDs in the bar graph const int ledCount = 10; // the number of LEDs in the bar graph
int ledPins[] = { int ledPins[] = {
2, 3, 4, 5, 6, 7,8,9,10,11 }; // an array of pin numbers to which LEDs are attached 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
}; // an array of pin numbers to which LEDs are attached
void setup() { void setup() {
// loop over the pin array and set them all to output: // loop over the pin array and set them all to output:
for (int thisLed = 0; thisLed < ledCount; thisLed++) { for (int thisLed = 0; thisLed < ledCount; thisLed++) {
pinMode(ledPins[thisLed], OUTPUT); pinMode(ledPins[thisLed], OUTPUT);
} }
} }
@ -48,10 +49,10 @@ void loop() {
// turn the pin for this element on: // turn the pin for this element on:
if (thisLed < ledLevel) { if (thisLed < ledLevel) {
digitalWrite(ledPins[thisLed], HIGH); digitalWrite(ledPins[thisLed], HIGH);
} }
// turn off all pins higher than the ledLevel: // turn off all pins higher than the ledLevel:
else { else {
digitalWrite(ledPins[thisLed], LOW); digitalWrite(ledPins[thisLed], LOW);
} }
} }
} }

View File

@ -1,13 +1,13 @@
/* /*
Character analysis operators Character analysis operators
Examples using the character analysis operators. Examples using the character analysis operators.
Send any byte and the sketch will tell you about it. Send any byte and the sketch will tell you about it.
created 29 Nov 2010 created 29 Nov 2010
modified 2 Apr 2012 modified 2 Apr 2012
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
*/ */
@ -35,40 +35,40 @@ void loop() {
Serial.println(thisChar); Serial.println(thisChar);
// analyze what was sent: // analyze what was sent:
if(isAlphaNumeric(thisChar)) { if (isAlphaNumeric(thisChar)) {
Serial.println("it's alphanumeric"); Serial.println("it's alphanumeric");
} }
if(isAlpha(thisChar)) { if (isAlpha(thisChar)) {
Serial.println("it's alphabetic"); Serial.println("it's alphabetic");
} }
if(isAscii(thisChar)) { if (isAscii(thisChar)) {
Serial.println("it's ASCII"); Serial.println("it's ASCII");
} }
if(isWhitespace(thisChar)) { if (isWhitespace(thisChar)) {
Serial.println("it's whitespace"); Serial.println("it's whitespace");
} }
if(isControl(thisChar)) { if (isControl(thisChar)) {
Serial.println("it's a control character"); Serial.println("it's a control character");
} }
if(isDigit(thisChar)) { if (isDigit(thisChar)) {
Serial.println("it's a numeric digit"); Serial.println("it's a numeric digit");
} }
if(isGraph(thisChar)) { if (isGraph(thisChar)) {
Serial.println("it's a printable character that's not whitespace"); Serial.println("it's a printable character that's not whitespace");
} }
if(isLowerCase(thisChar)) { if (isLowerCase(thisChar)) {
Serial.println("it's lower case"); Serial.println("it's lower case");
} }
if(isPrintable(thisChar)) { if (isPrintable(thisChar)) {
Serial.println("it's printable"); Serial.println("it's printable");
} }
if(isPunct(thisChar)) { if (isPunct(thisChar)) {
Serial.println("it's punctuation"); Serial.println("it's punctuation");
} }
if(isSpace(thisChar)) { if (isSpace(thisChar)) {
Serial.println("it's a space character"); Serial.println("it's a space character");
} }
if(isUpperCase(thisChar)) { if (isUpperCase(thisChar)) {
Serial.println("it's upper case"); Serial.println("it's upper case");
} }
if (isHexadecimalDigit(thisChar)) { if (isHexadecimalDigit(thisChar)) {

View File

@ -1,16 +1,16 @@
/* /*
Adding Strings together Adding Strings together
Examples of how to add strings together Examples of how to add strings together
You can also add several different data types to string, as shown here: You can also add several different data types to string, as shown here:
created 27 July 2010 created 27 July 2010
modified 2 Apr 2012 modified 2 Apr 2012
by Tom Igoe by Tom Igoe
http://arduino.cc/en/Tutorial/StringAdditionOperator http://arduino.cc/en/Tutorial/StringAdditionOperator
This example code is in the public domain. This example code is in the public domain.
*/ */
// declare three strings: // declare three strings:
@ -59,10 +59,10 @@ void loop() {
// adding a variable long integer to a string: // adding a variable long integer to a string:
long currentTime = millis(); long currentTime = millis();
stringOne="millis() value: "; stringOne = "millis() value: ";
stringThree = stringOne + millis(); stringThree = stringOne + millis();
Serial.println(stringThree); // prints "The millis: 345345" or whatever value currentTime has Serial.println(stringThree); // prints "The millis: 345345" or whatever value currentTime has
// do nothing while true: // do nothing while true:
while(true); while (true);
} }

View File

@ -1,14 +1,14 @@
/* /*
Appending to Strings using the += operator and concat() Appending to Strings using the += operator and concat()
Examples of how to append different data types to strings Examples of how to append different data types to strings
created 27 July 2010 created 27 July 2010
modified 2 Apr 2012 modified 2 Apr 2012
by Tom Igoe by Tom Igoe
http://arduino.cc/en/Tutorial/StringAppendOperator http://arduino.cc/en/Tutorial/StringAppendOperator
This example code is in the public domain. This example code is in the public domain.
*/ */
@ -68,6 +68,6 @@ void loop() {
Serial.println(stringTwo); // prints "The millis(): 43534" or whatever the value of the millis() is Serial.println(stringTwo); // prints "The millis(): 43534" or whatever the value of the millis() is
// do nothing while true: // do nothing while true:
while(true); while (true);
} }

View File

@ -1,14 +1,14 @@
/* /*
String Case changes String Case changes
Examples of how to change the case of a string Examples of how to change the case of a string
created 27 July 2010 created 27 July 2010
modified 2 Apr 2012 modified 2 Apr 2012
by Tom Igoe by Tom Igoe
http://arduino.cc/en/Tutorial/StringCaseChanges http://arduino.cc/en/Tutorial/StringCaseChanges
This example code is in the public domain. This example code is in the public domain.
*/ */
@ -31,7 +31,7 @@ void loop() {
stringOne.toUpperCase(); stringOne.toUpperCase();
Serial.println(stringOne); Serial.println(stringOne);
// toLowerCase() changes all letters to lower case: // toLowerCase() changes all letters to lower case:
String stringTwo = "</BODY></HTML>"; String stringTwo = "</BODY></HTML>";
Serial.println(stringTwo); Serial.println(stringTwo);
stringTwo.toLowerCase(); stringTwo.toLowerCase();
@ -39,5 +39,5 @@ void loop() {
// do nothing while true: // do nothing while true:
while(true); while (true);
} }

View File

@ -1,14 +1,14 @@
/* /*
String charAt() and setCharAt() String charAt() and setCharAt()
Examples of how to get and set characters of a String Examples of how to get and set characters of a String
created 27 July 2010 created 27 July 2010
modified 2 Apr 2012 modified 2 Apr 2012
by Tom Igoe by Tom Igoe
http://arduino.cc/en/Tutorial/StringCharacters http://arduino.cc/en/Tutorial/StringCharacters
This example code is in the public domain. This example code is in the public domain.
*/ */
@ -30,17 +30,17 @@ void loop() {
// the reading's most significant digit is at position 15 in the reportString: // the reading's most significant digit is at position 15 in the reportString:
char mostSignificantDigit = reportString.charAt(15); char mostSignificantDigit = reportString.charAt(15);
String message = "Most significant digit of the sensor reading is: "; String message = "Most significant digit of the sensor reading is: ";
Serial.println(message + mostSignificantDigit); Serial.println(message + mostSignificantDigit);
// add blank space: // add blank space:
Serial.println(); Serial.println();
// you can alo set the character of a string. Change the : to a = character // you can alo set the character of a string. Change the : to a = character
reportString.setCharAt(13, '='); reportString.setCharAt(13, '=');
Serial.println(reportString); Serial.println(reportString);
// do nothing while true: // do nothing while true:
while(true); while (true);
} }

View File

@ -1,14 +1,14 @@
/* /*
Comparing Strings Comparing Strings
Examples of how to compare strings using the comparison operators Examples of how to compare strings using the comparison operators
created 27 July 2010 created 27 July 2010
modified 2 Apr 2012 modified 2 Apr 2012
by Tom Igoe by Tom Igoe
http://arduino.cc/en/Tutorial/StringComparisonOperators http://arduino.cc/en/Tutorial/StringComparisonOperators
This example code is in the public domain. This example code is in the public domain.
*/ */
@ -33,7 +33,7 @@ void setup() {
void loop() { void loop() {
// two strings equal: // two strings equal:
if (stringOne == "this") { if (stringOne == "this") {
Serial.println("StringOne == \"this\""); Serial.println("StringOne == \"this\"");
} }
// two strings not equal: // two strings not equal:
if (stringOne != stringTwo) { if (stringOne != stringTwo) {
@ -49,7 +49,7 @@ void loop() {
// you can also use equals() to see if two strings are the same: // you can also use equals() to see if two strings are the same:
if (stringOne.equals(stringTwo)) { if (stringOne.equals(stringTwo)) {
Serial.println(stringOne + " equals " + stringTwo); Serial.println(stringOne + " equals " + stringTwo);
} }
else { else {
Serial.println(stringOne + " does not equal " + stringTwo); Serial.println(stringOne + " does not equal " + stringTwo);
} }
@ -57,7 +57,7 @@ void loop() {
// or perhaps you want to ignore case: // or perhaps you want to ignore case:
if (stringOne.equalsIgnoreCase(stringTwo)) { if (stringOne.equalsIgnoreCase(stringTwo)) {
Serial.println(stringOne + " equals (ignoring case) " + stringTwo); Serial.println(stringOne + " equals (ignoring case) " + stringTwo);
} }
else { else {
Serial.println(stringOne + " does not equal (ignoring case) " + stringTwo); Serial.println(stringOne + " does not equal (ignoring case) " + stringTwo);
} }
@ -81,20 +81,20 @@ void loop() {
// comparison operators can be used to compare strings for alphabetic sorting too: // comparison operators can be used to compare strings for alphabetic sorting too:
stringOne = String("Brown"); stringOne = String("Brown");
if (stringOne < "Charles") { if (stringOne < "Charles") {
Serial.println(stringOne + " < Charles"); Serial.println(stringOne + " < Charles");
} }
if (stringOne > "Adams") { if (stringOne > "Adams") {
Serial.println(stringOne + " > Adams"); Serial.println(stringOne + " > Adams");
} }
if (stringOne <= "Browne") { if (stringOne <= "Browne") {
Serial.println(stringOne + " <= Browne"); Serial.println(stringOne + " <= Browne");
} }
if (stringOne >= "Brow") { if (stringOne >= "Brow") {
Serial.println(stringOne + " >= Brow"); Serial.println(stringOne + " >= Brow");
} }
// the compareTo() operator also allows you to compare strings // the compareTo() operator also allows you to compare strings
@ -104,10 +104,10 @@ void loop() {
stringOne = "Cucumber"; stringOne = "Cucumber";
stringTwo = "Cucuracha"; stringTwo = "Cucuracha";
if (stringOne.compareTo(stringTwo) < 0 ) { if (stringOne.compareTo(stringTwo) < 0 ) {
Serial.println(stringOne + " comes before " + stringTwo); Serial.println(stringOne + " comes before " + stringTwo);
} }
else { else {
Serial.println(stringOne + " comes after " + stringTwo); Serial.println(stringOne + " comes after " + stringTwo);
} }
delay(10000); // because the next part is a loop: delay(10000); // because the next part is a loop:
@ -116,16 +116,16 @@ void loop() {
while (true) { while (true) {
stringOne = "Sensor: "; stringOne = "Sensor: ";
stringTwo= "Sensor: "; stringTwo = "Sensor: ";
stringOne += analogRead(A0); stringOne += analogRead(A0);
stringTwo += analogRead(A5); stringTwo += analogRead(A5);
if (stringOne.compareTo(stringTwo) < 0 ) { if (stringOne.compareTo(stringTwo) < 0 ) {
Serial.println(stringOne + " comes before " + stringTwo); Serial.println(stringOne + " comes before " + stringTwo);
} }
else { else {
Serial.println(stringOne + " comes after " + stringTwo); Serial.println(stringOne + " comes after " + stringTwo);
} }
} }

View File

@ -1,14 +1,14 @@
/* /*
String constructors String constructors
Examples of how to create strings from other data types Examples of how to create strings from other data types
created 27 July 2010 created 27 July 2010
modified 30 Aug 2011 modified 30 Aug 2011
by Tom Igoe by Tom Igoe
http://arduino.cc/en/Tutorial/StringConstructors http://arduino.cc/en/Tutorial/StringConstructors
This example code is in the public domain. This example code is in the public domain.
*/ */
@ -18,7 +18,7 @@ void setup() {
while (!Serial) { while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only ; // wait for serial port to connect. Needed for Leonardo only
} }
// send an intro: // send an intro:
Serial.println("\n\nString Constructors:"); Serial.println("\n\nString Constructors:");
Serial.println(); Serial.println();
@ -26,47 +26,47 @@ void setup() {
void loop() { void loop() {
// using a constant String: // using a constant String:
String stringOne = "Hello String"; String stringOne = "Hello String";
Serial.println(stringOne); // prints "Hello String" Serial.println(stringOne); // prints "Hello String"
// converting a constant char into a String: // converting a constant char into a String:
stringOne = String('a'); stringOne = String('a');
Serial.println(stringOne); // prints "a" Serial.println(stringOne); // prints "a"
// converting a constant string into a String object: // converting a constant string into a String object:
String stringTwo = String("This is a string"); String stringTwo = String("This is a string");
Serial.println(stringTwo); // prints "This is a string" Serial.println(stringTwo); // prints "This is a string"
// concatenating two strings: // concatenating two strings:
stringOne = String(stringTwo + " with more"); stringOne = String(stringTwo + " with more");
// prints "This is a string with more": // prints "This is a string with more":
Serial.println(stringOne); Serial.println(stringOne);
// using a constant integer: // using a constant integer:
stringOne = String(13); stringOne = String(13);
Serial.println(stringOne); // prints "13" Serial.println(stringOne); // prints "13"
// using an int and a base: // using an int and a base:
stringOne = String(analogRead(A0), DEC); stringOne = String(analogRead(A0), DEC);
// prints "453" or whatever the value of analogRead(A0) is // prints "453" or whatever the value of analogRead(A0) is
Serial.println(stringOne); Serial.println(stringOne);
// using an int and a base (hexadecimal): // using an int and a base (hexadecimal):
stringOne = String(45, HEX); stringOne = String(45, HEX);
// prints "2d", which is the hexadecimal version of decimal 45: // prints "2d", which is the hexadecimal version of decimal 45:
Serial.println(stringOne); Serial.println(stringOne);
// using an int and a base (binary) // using an int and a base (binary)
stringOne = String(255, BIN); stringOne = String(255, BIN);
// prints "11111111" which is the binary value of 255 // prints "11111111" which is the binary value of 255
Serial.println(stringOne); Serial.println(stringOne);
// using a long and a base: // using a long and a base:
stringOne = String(millis(), DEC); stringOne = String(millis(), DEC);
// prints "123456" or whatever the value of millis() is: // prints "123456" or whatever the value of millis() is:
Serial.println(stringOne); Serial.println(stringOne);
// do nothing while true: // do nothing while true:
while(true); while (true);
} }

View File

@ -1,15 +1,15 @@
/* /*
String indexOf() and lastIndexOf() functions String indexOf() and lastIndexOf() functions
Examples of how to evaluate, look for, and replace characters in a String Examples of how to evaluate, look for, and replace characters in a String
created 27 July 2010 created 27 July 2010
modified 2 Apr 2012 modified 2 Apr 2012
by Tom Igoe by Tom Igoe
http://arduino.cc/en/Tutorial/StringIndexOf http://arduino.cc/en/Tutorial/StringIndexOf
This example code is in the public domain. This example code is in the public domain.
*/ */
void setup() { void setup() {
@ -61,6 +61,6 @@ void loop() {
Serial.println("The index of the second last paragraph tag " + stringOne + " is " + secondLastGraf); Serial.println("The index of the second last paragraph tag " + stringOne + " is " + secondLastGraf);
// do nothing while true: // do nothing while true:
while(true); while (true);
} }

View File

@ -1,14 +1,14 @@
/* /*
String length() String length()
Examples of how to use length() in a String. Examples of how to use length() in a String.
Open the Serial Monitor and start sending characters to see the results. Open the Serial Monitor and start sending characters to see the results.
created 1 Aug 2010 created 1 Aug 2010
by Tom Igoe by Tom Igoe
http://arduino.cc/en/Tutorial/StringLengthTrim http://arduino.cc/en/Tutorial/StringLengthTrim
This example code is in the public domain. This example code is in the public domain.
*/ */
@ -32,7 +32,7 @@ void loop() {
while (Serial.available() > 0) { while (Serial.available() > 0) {
char inChar = Serial.read(); char inChar = Serial.read();
txtMsg += inChar; txtMsg += inChar;
} }
// print the message and a notice if it's changed: // print the message and a notice if it's changed:
if (txtMsg.length() != lastStringLength) { if (txtMsg.length() != lastStringLength) {
@ -41,9 +41,9 @@ void loop() {
// if the String's longer than 140 characters, complain: // if the String's longer than 140 characters, complain:
if (txtMsg.length() < 140) { if (txtMsg.length() < 140) {
Serial.println("That's a perfectly acceptable text message"); Serial.println("That's a perfectly acceptable text message");
} }
else { else {
Serial.println("That's too long for a text message."); Serial.println("That's too long for a text message.");
} }
// note the length for next time through the loop: // note the length for next time through the loop:
lastStringLength = txtMsg.length(); lastStringLength = txtMsg.length();

View File

@ -1,14 +1,14 @@
/* /*
String length() and trim() String length() and trim()
Examples of how to use length() and trim() in a String Examples of how to use length() and trim() in a String
created 27 July 2010 created 27 July 2010
modified 2 Apr 2012 modified 2 Apr 2012
by Tom Igoe by Tom Igoe
http://arduino.cc/en/Tutorial/StringLengthTrim http://arduino.cc/en/Tutorial/StringLengthTrim
This example code is in the public domain. This example code is in the public domain.
*/ */
@ -38,5 +38,5 @@ void loop() {
Serial.println(stringOne.length()); Serial.println(stringOne.length());
// do nothing while true: // do nothing while true:
while(true); while (true);
} }

View File

@ -1,15 +1,15 @@
/* /*
String replace() String replace()
Examples of how to replace characters or substrings of a string Examples of how to replace characters or substrings of a string
created 27 July 2010 created 27 July 2010
modified 2 Apr 2012 modified 2 Apr 2012
by Tom Igoe by Tom Igoe
http://arduino.cc/en/Tutorial/StringReplace http://arduino.cc/en/Tutorial/StringReplace
This example code is in the public domain. This example code is in the public domain.
*/ */
void setup() { void setup() {
@ -46,5 +46,5 @@ void loop() {
Serial.println("l33tspeak: " + leetString); Serial.println("l33tspeak: " + leetString);
// do nothing while true: // do nothing while true:
while(true); while (true);
} }

View File

@ -1,14 +1,14 @@
/* /*
String startWith() and endsWith() String startWith() and endsWith()
Examples of how to use startsWith() and endsWith() in a String Examples of how to use startsWith() and endsWith() in a String
created 27 July 2010 created 27 July 2010
modified 2 Apr 2012 modified 2 Apr 2012
by Tom Igoe by Tom Igoe
http://arduino.cc/en/Tutorial/StringStartsWithEndsWith http://arduino.cc/en/Tutorial/StringStartsWithEndsWith
This example code is in the public domain. This example code is in the public domain.
*/ */
@ -29,27 +29,27 @@ void loop() {
String stringOne = "HTTP/1.1 200 OK"; String stringOne = "HTTP/1.1 200 OK";
Serial.println(stringOne); Serial.println(stringOne);
if (stringOne.startsWith("HTTP/1.1")) { if (stringOne.startsWith("HTTP/1.1")) {
Serial.println("Server's using http version 1.1"); Serial.println("Server's using http version 1.1");
} }
// you can also look for startsWith() at an offset position in the string: // you can also look for startsWith() at an offset position in the string:
stringOne = "HTTP/1.1 200 OK"; stringOne = "HTTP/1.1 200 OK";
if (stringOne.startsWith("200 OK", 9)) { if (stringOne.startsWith("200 OK", 9)) {
Serial.println("Got an OK from the server"); Serial.println("Got an OK from the server");
} }
// endsWith() checks to see if a String ends with a particular character: // endsWith() checks to see if a String ends with a particular character:
String sensorReading = "sensor = "; String sensorReading = "sensor = ";
sensorReading += analogRead(A0); sensorReading += analogRead(A0);
Serial.print (sensorReading); Serial.print (sensorReading);
if (sensorReading.endsWith(0)) { if (sensorReading.endsWith(0)) {
Serial.println(". This reading is divisible by ten"); Serial.println(". This reading is divisible by ten");
} }
else { else {
Serial.println(". This reading is not divisible by ten"); Serial.println(". This reading is not divisible by ten");
} }
// do nothing while true: // do nothing while true:
while(true); while (true);
} }

View File

@ -1,14 +1,14 @@
/* /*
String substring() String substring()
Examples of how to use substring in a String Examples of how to use substring in a String
created 27 July 2010, created 27 July 2010,
modified 2 Apr 2012 modified 2 Apr 2012
by Zach Eveland by Zach Eveland
http://arduino.cc/en/Tutorial/StringSubstring http://arduino.cc/en/Tutorial/StringSubstring
This example code is in the public domain. This example code is in the public domain.
*/ */
@ -31,13 +31,13 @@ void loop() {
// substring(index) looks for the substring from the index position to the end: // substring(index) looks for the substring from the index position to the end:
if (stringOne.substring(19) == "html") { if (stringOne.substring(19) == "html") {
Serial.println("It's an html file"); Serial.println("It's an html file");
} }
// you can also look for a substring in the middle of a string: // you can also look for a substring in the middle of a string:
if (stringOne.substring(14,18) == "text") { if (stringOne.substring(14, 18) == "text") {
Serial.println("It's a text-based file"); Serial.println("It's a text-based file");
} }
// do nothing while true: // do nothing while true:
while(true); while (true);
} }

View File

@ -1,16 +1,16 @@
/* /*
String to Integer conversion String to Integer conversion
Reads a serial input string until it sees a newline, then converts Reads a serial input string until it sees a newline, then converts
the string to a number if the characters are digits. the string to a number if the characters are digits.
The circuit: The circuit:
No external components needed. No external components needed.
created 29 Nov 2010 created 29 Nov 2010
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
*/ */
String inString = ""; // string to hold input String inString = ""; // string to hold input
@ -32,9 +32,9 @@ void loop() {
while (Serial.available() > 0) { while (Serial.available() > 0) {
int inChar = Serial.read(); int inChar = Serial.read();
if (isDigit(inChar)) { if (isDigit(inChar)) {
// convert the incoming byte to a char // convert the incoming byte to a char
// and add it to the string: // and add it to the string:
inString += (char)inChar; inString += (char)inChar;
} }
// if you get a newline, print the string, // if you get a newline, print the string,
// then the string's value: // then the string's value:
@ -44,7 +44,7 @@ void loop() {
Serial.print("String: "); Serial.print("String: ");
Serial.println(inString); Serial.println(inString);
// clear the string for new input: // clear the string for new input:
inString = ""; inString = "";
} }
} }
} }

View File

@ -1,23 +1,23 @@
/* /*
Serial RGB controller Serial RGB controller
Reads a serial input string looking for three comma-separated Reads a serial input string looking for three comma-separated
integers with a newline at the end. Values should be between integers with a newline at the end. Values should be between
0 and 255. The sketch uses those values to set the color 0 and 255. The sketch uses those values to set the color
of an RGB LED attached to pins 9 - 11. of an RGB LED attached to pins 9 - 11.
The circuit: The circuit:
* Common-anode RGB LED cathodes attached to pins 9 - 11 * Common-anode RGB LED cathodes attached to pins 9 - 11
* LED anode connected to pin 13 * LED anode connected to pin 13
To turn on any given channel, set the pin LOW. To turn on any given channel, set the pin LOW.
To turn off, set the pin HIGH. The higher the analogWrite level, To turn off, set the pin HIGH. The higher the analogWrite level,
the lower the brightness. the lower the brightness.
created 29 Nov 2010 created 29 Nov 2010
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
*/ */
String inString = ""; // string to hold input String inString = ""; // string to hold input
@ -52,9 +52,9 @@ void loop() {
} }
if (isDigit(inChar)) { if (isDigit(inChar)) {
// convert the incoming byte to a char // convert the incoming byte to a char
// and add it to the string: // and add it to the string:
inString += (char)inChar; inString += (char)inChar;
} }
// if you get a comma, convert to a number, // if you get a comma, convert to a number,
@ -63,16 +63,16 @@ void loop() {
if (inChar == ',') { if (inChar == ',') {
// do something different for each value of currentColor: // do something different for each value of currentColor:
switch (currentColor) { switch (currentColor) {
case 0: // 0 = red case 0: // 0 = red
red = inString.toInt(); red = inString.toInt();
// clear the string for new input: // clear the string for new input:
inString = ""; inString = "";
break; break;
case 1: // 1 = green: case 1: // 1 = green:
green = inString.toInt(); green = inString.toInt();
// clear the string for new input: // clear the string for new input:
inString = ""; inString = "";
break; break;
} }
currentColor++; currentColor++;
} }
@ -98,7 +98,7 @@ void loop() {
Serial.println(blue); Serial.println(blue);
// clear the string for new input: // clear the string for new input:
inString = ""; inString = "";
// reset the color counter: // reset the color counter:
currentColor = 0; currentColor = 0;
} }
@ -109,33 +109,33 @@ void loop() {
/* /*
Here's a Processing sketch that will draw a color wheel and send a serial Here's a Processing sketch that will draw a color wheel and send a serial
string with the color you click on: string with the color you click on:
// Subtractive Color Wheel with Serial // Subtractive Color Wheel with Serial
// Based on a Processing example by Ira Greenberg. // Based on a Processing example by Ira Greenberg.
// Serial output added by Tom Igoe // Serial output added by Tom Igoe
// //
// The primaries are red, yellow, and blue. The secondaries are green, // The primaries are red, yellow, and blue. The secondaries are green,
// purple, and orange. The tertiaries are yellow-orange, red-orange, // purple, and orange. The tertiaries are yellow-orange, red-orange,
// red-purple, blue-purple, blue-green, and yellow-green. // red-purple, blue-purple, blue-green, and yellow-green.
// //
// Create a shade or tint of the subtractive color wheel using // Create a shade or tint of the subtractive color wheel using
// SHADE or TINT parameters. // SHADE or TINT parameters.
// Updated 29 November 2010. // Updated 29 November 2010.
import processing.serial.*; import processing.serial.*;
int segs = 12; int segs = 12;
int steps = 6; int steps = 6;
float rotAdjust = TWO_PI / segs / 2; float rotAdjust = TWO_PI / segs / 2;
float radius; float radius;
float segWidth; float segWidth;
float interval = TWO_PI / segs; float interval = TWO_PI / segs;
Serial myPort; Serial myPort;
void setup() { void setup() {
size(200, 200); size(200, 200);
background(127); background(127);
@ -145,70 +145,70 @@ Here's a Processing sketch that will draw a color wheel and send a serial
// make the diameter 90% of the sketch area // make the diameter 90% of the sketch area
radius = min(width, height) * 0.45; radius = min(width, height) * 0.45;
segWidth = radius / steps; segWidth = radius / steps;
// swap which line is commented out to draw the other version // swap which line is commented out to draw the other version
// drawTintWheel(); // drawTintWheel();
drawShadeWheel(); drawShadeWheel();
// open the first serial port in your computer's list // open the first serial port in your computer's list
myPort = new Serial(this, Serial.list()[0], 9600); myPort = new Serial(this, Serial.list()[0], 9600);
} }
void drawShadeWheel() { void drawShadeWheel() {
for (int j = 0; j < steps; j++) { for (int j = 0; j < steps; j++) {
color[] cols = { color[] cols = {
color(255-(255/steps)*j, 255-(255/steps)*j, 0), color(255-(255/steps)*j, 255-(255/steps)*j, 0),
color(255-(255/steps)*j, (255/1.5)-((255/1.5)/steps)*j, 0), color(255-(255/steps)*j, (255/1.5)-((255/1.5)/steps)*j, 0),
color(255-(255/steps)*j, (255/2)-((255/2)/steps)*j, 0), color(255-(255/steps)*j, (255/2)-((255/2)/steps)*j, 0),
color(255-(255/steps)*j, (255/2.5)-((255/2.5)/steps)*j, 0), color(255-(255/steps)*j, (255/2.5)-((255/2.5)/steps)*j, 0),
color(255-(255/steps)*j, 0, 0), color(255-(255/steps)*j, 0, 0),
color(255-(255/steps)*j, 0, (255/2)-((255/2)/steps)*j), color(255-(255/steps)*j, 0, (255/2)-((255/2)/steps)*j),
color(255-(255/steps)*j, 0, 255-(255/steps)*j), color(255-(255/steps)*j, 0, 255-(255/steps)*j),
color((255/2)-((255/2)/steps)*j, 0, 255-(255/steps)*j), color((255/2)-((255/2)/steps)*j, 0, 255-(255/steps)*j),
color(0, 0, 255-(255/steps)*j), color(0, 0, 255-(255/steps)*j),
color(0, 255-(255/steps)*j, (255/2.5)-((255/2.5)/steps)*j), color(0, 255-(255/steps)*j, (255/2.5)-((255/2.5)/steps)*j),
color(0, 255-(255/steps)*j, 0), color(0, 255-(255/steps)*j, 0),
color((255/2)-((255/2)/steps)*j, 255-(255/steps)*j, 0) color((255/2)-((255/2)/steps)*j, 255-(255/steps)*j, 0)
}; };
for (int i = 0; i < segs; i++) { for (int i = 0; i < segs; i++) {
fill(cols[i]); fill(cols[i]);
arc(width/2, height/2, radius, radius, arc(width/2, height/2, radius, radius,
interval*i+rotAdjust, interval*(i+1)+rotAdjust); interval*i+rotAdjust, interval*(i+1)+rotAdjust);
} }
radius -= segWidth; radius -= segWidth;
} }
} }
void drawTintWheel() { void drawTintWheel() {
for (int j = 0; j < steps; j++) { for (int j = 0; j < steps; j++) {
color[] cols = { color[] cols = {
color((255/steps)*j, (255/steps)*j, 0), color((255/steps)*j, (255/steps)*j, 0),
color((255/steps)*j, ((255/1.5)/steps)*j, 0), color((255/steps)*j, ((255/1.5)/steps)*j, 0),
color((255/steps)*j, ((255/2)/steps)*j, 0), color((255/steps)*j, ((255/2)/steps)*j, 0),
color((255/steps)*j, ((255/2.5)/steps)*j, 0), color((255/steps)*j, ((255/2.5)/steps)*j, 0),
color((255/steps)*j, 0, 0), color((255/steps)*j, 0, 0),
color((255/steps)*j, 0, ((255/2)/steps)*j), color((255/steps)*j, 0, ((255/2)/steps)*j),
color((255/steps)*j, 0, (255/steps)*j), color((255/steps)*j, 0, (255/steps)*j),
color(((255/2)/steps)*j, 0, (255/steps)*j), color(((255/2)/steps)*j, 0, (255/steps)*j),
color(0, 0, (255/steps)*j), color(0, 0, (255/steps)*j),
color(0, (255/steps)*j, ((255/2.5)/steps)*j), color(0, (255/steps)*j, ((255/2.5)/steps)*j),
color(0, (255/steps)*j, 0), color(0, (255/steps)*j, 0),
color(((255/2)/steps)*j, (255/steps)*j, 0) color(((255/2)/steps)*j, (255/steps)*j, 0)
}; };
for (int i = 0; i < segs; i++) { for (int i = 0; i < segs; i++) {
fill(cols[i]); fill(cols[i]);
arc(width/2, height/2, radius, radius, arc(width/2, height/2, radius, radius,
interval*i+rotAdjust, interval*(i+1)+rotAdjust); interval*i+rotAdjust, interval*(i+1)+rotAdjust);
} }
radius -= segWidth; radius -= segWidth;
} }
} }
void draw() { void draw() {
// nothing happens here // nothing happens here
} }
void mouseReleased() { void mouseReleased() {
// get the color of the mouse position's pixel: // get the color of the mouse position's pixel:
color targetColor = get(mouseX, mouseY); color targetColor = get(mouseX, mouseY);
@ -221,7 +221,7 @@ Here's a Processing sketch that will draw a color wheel and send a serial
// send it out the serial port: // send it out the serial port:
myPort.write(colorString ); myPort.write(colorString );
} }
*/ */

View File

@ -1,30 +1,30 @@
/* /*
Keyboard logout Keyboard logout
This sketch demonstrates the Keyboard library. This sketch demonstrates the Keyboard library.
When you connect pin 2 to ground, it performs a logout. When you connect pin 2 to ground, it performs a logout.
It uses keyboard combinations to do this, as follows: It uses keyboard combinations to do this, as follows:
On Windows, CTRL-ALT-DEL followed by ALT-l On Windows, CTRL-ALT-DEL followed by ALT-l
On Ubuntu, CTRL-ALT-DEL, and ENTER On Ubuntu, CTRL-ALT-DEL, and ENTER
On OSX, CMD-SHIFT-q On OSX, CMD-SHIFT-q
To wake: Spacebar. To wake: Spacebar.
Circuit: Circuit:
* Arduino Leonardo or Micro * Arduino Leonardo or Micro
* wire to connect D2 to ground. * wire to connect D2 to ground.
created 6 Mar 2012 created 6 Mar 2012
modified 27 Mar 2012 modified 27 Mar 2012
by Tom Igoe by Tom Igoe
This example is in the public domain This example is in the public domain
http://www.arduino.cc/en/Tutorial/KeyboardLogout http://www.arduino.cc/en/Tutorial/KeyboardLogout
*/ */
#define OSX 0 #define OSX 0
#define WINDOWS 1 #define WINDOWS 1
#define UBUNTU 2 #define UBUNTU 2
@ -33,13 +33,13 @@
int platform = OSX; int platform = OSX;
void setup() { void setup() {
// make pin 2 an input and turn on the // make pin 2 an input and turn on the
// pullup resistor so it goes high unless // pullup resistor so it goes high unless
// connected to ground: // connected to ground:
pinMode(2, INPUT_PULLUP); pinMode(2, INPUT_PULLUP);
Keyboard.begin(); Keyboard.begin();
} }
void loop() { void loop() {
while (digitalRead(2) == HIGH) { while (digitalRead(2) == HIGH) {
// do nothing until pin 2 goes low // do nothing until pin 2 goes low
@ -48,43 +48,43 @@ void loop() {
delay(1000); delay(1000);
switch (platform) { switch (platform) {
case OSX: case OSX:
Keyboard.press(KEY_LEFT_GUI); Keyboard.press(KEY_LEFT_GUI);
// Shift-Q logs out: // Shift-Q logs out:
Keyboard.press(KEY_LEFT_SHIFT); Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.press('Q'); Keyboard.press('Q');
delay(100); delay(100);
Keyboard.releaseAll(); Keyboard.releaseAll();
// enter: // enter:
Keyboard.write(KEY_RETURN); Keyboard.write(KEY_RETURN);
break; break;
case WINDOWS: case WINDOWS:
// CTRL-ALT-DEL: // CTRL-ALT-DEL:
Keyboard.press(KEY_LEFT_CTRL); Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_ALT); Keyboard.press(KEY_LEFT_ALT);
Keyboard.press(KEY_DELETE); Keyboard.press(KEY_DELETE);
delay(100); delay(100);
Keyboard.releaseAll(); Keyboard.releaseAll();
//ALT-s: //ALT-s:
delay(2000); delay(2000);
Keyboard.press(KEY_LEFT_ALT); Keyboard.press(KEY_LEFT_ALT);
Keyboard.press('l'); Keyboard.press('l');
Keyboard.releaseAll(); Keyboard.releaseAll();
break; break;
case UBUNTU: case UBUNTU:
// CTRL-ALT-DEL: // CTRL-ALT-DEL:
Keyboard.press(KEY_LEFT_CTRL); Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_ALT); Keyboard.press(KEY_LEFT_ALT);
Keyboard.press(KEY_DELETE); Keyboard.press(KEY_DELETE);
delay(1000); delay(1000);
Keyboard.releaseAll(); Keyboard.releaseAll();
// Enter to confirm logout: // Enter to confirm logout:
Keyboard.write(KEY_RETURN); Keyboard.write(KEY_RETURN);
break; break;
} }
// do nothing: // do nothing:
while(true); while (true);
} }

View File

@ -1,21 +1,21 @@
/* /*
Keyboard Button test Keyboard Button test
For the Arduino Leonardo, Micro and Due boards. For the Arduino Leonardo, Micro and Due boards.
Sends a text string when a button is pressed. Sends a text string when a button is pressed.
The circuit: The circuit:
* pushbutton attached from pin 2 to +5V on AVR boards * pushbutton attached from pin 2 to +5V on AVR boards
and to +3.3V to the Arduino Due and to +3.3V to the Arduino Due
* 10-kilohm resistor attached from pin 2 to ground * 10-kilohm resistor attached from pin 2 to ground
created 24 Oct 2011 created 24 Oct 2011
modified 27 Mar 2012 modified 27 Mar 2012
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/KeyboardButton http://www.arduino.cc/en/Tutorial/KeyboardButton
*/ */
@ -33,18 +33,18 @@ void setup() {
void loop() { void loop() {
// read the pushbutton: // read the pushbutton:
int buttonState = digitalRead(buttonPin); int buttonState = digitalRead(buttonPin);
// if the button state has changed, // if the button state has changed,
if ((buttonState != previousButtonState) if ((buttonState != previousButtonState)
// and it's currently pressed: // and it's currently pressed:
&& (buttonState == HIGH)) { && (buttonState == HIGH)) {
// increment the button counter // increment the button counter
counter++; counter++;
// type out a message // type out a message
Keyboard.print("You pressed the button "); Keyboard.print("You pressed the button ");
Keyboard.print(counter); Keyboard.print(counter);
Keyboard.println(" times."); Keyboard.println(" times.");
} }
// save the current button state for comparison next time: // save the current button state for comparison next time:
previousButtonState = buttonState; previousButtonState = buttonState;
} }

View File

@ -1,40 +1,40 @@
/* /*
Arduino Programs Blink Arduino Programs Blink
This sketch demonstrates the Keyboard library. This sketch demonstrates the Keyboard library.
For Leonardo and Due boards only. For Leonardo and Due boards only.
When you connect pin 2 to ground, it creates a new When you connect pin 2 to ground, it creates a new
window with a key combination (CTRL-N), window with a key combination (CTRL-N),
then types in the Blink sketch, then auto-formats the text then types in the Blink sketch, then auto-formats the text
using another key combination (CTRL-T), then using another key combination (CTRL-T), then
uploads the sketch to the currently selected Arduino using uploads the sketch to the currently selected Arduino using
a final key combination (CTRL-U). a final key combination (CTRL-U).
Circuit: Circuit:
* Arduino Leonardo, Micro or Due * Arduino Leonardo, Micro or Due
* wire to connect D2 to ground. * wire to connect D2 to ground.
created 5 Mar 2012 created 5 Mar 2012
modified 29 Mar 2012 modified 29 Mar 2012
by Tom Igoe by Tom Igoe
This example is in the public domain This example is in the public domain
http://www.arduino.cc/en/Tutorial/KeyboardReprogram http://www.arduino.cc/en/Tutorial/KeyboardReprogram
*/ */
// use this option for OSX. // use this option for OSX.
// Comment it out if using Windows or Linux: // Comment it out if using Windows or Linux:
char ctrlKey = KEY_LEFT_GUI; char ctrlKey = KEY_LEFT_GUI;
// use this option for Windows and Linux. // use this option for Windows and Linux.
// leave commented out if using OSX: // leave commented out if using OSX:
// char ctrlKey = KEY_LEFT_CTRL; // char ctrlKey = KEY_LEFT_CTRL;
void setup() { void setup() {
// make pin 2 an input and turn on the // make pin 2 an input and turn on the
// pullup resistor so it goes high unless // pullup resistor so it goes high unless
// connected to ground: // connected to ground:
pinMode(2, INPUT_PULLUP); pinMode(2, INPUT_PULLUP);
@ -65,9 +65,9 @@ void loop() {
Keyboard.println("digitalWrite(13, HIGH);"); Keyboard.println("digitalWrite(13, HIGH);");
Keyboard.print("delay(3000);"); Keyboard.print("delay(3000);");
// 3000 ms is too long. Delete it: // 3000 ms is too long. Delete it:
for (int keystrokes=0; keystrokes < 6; keystrokes++) { for (int keystrokes = 0; keystrokes < 6; keystrokes++) {
delay(500); delay(500);
Keyboard.write(KEY_BACKSPACE); Keyboard.write(KEY_BACKSPACE);
} }
// make it 1000 instead: // make it 1000 instead:
Keyboard.println("1000);"); Keyboard.println("1000);");
@ -87,7 +87,7 @@ void loop() {
Keyboard.releaseAll(); Keyboard.releaseAll();
// wait for the sweet oblivion of reprogramming: // wait for the sweet oblivion of reprogramming:
while(true); while (true);
} }

View File

@ -1,21 +1,21 @@
/* /*
Keyboard test Keyboard test
For the Arduino Leonardo, Micro or Due For the Arduino Leonardo, Micro or Due
Reads a byte from the serial port, sends a keystroke back. Reads a byte from the serial port, sends a keystroke back.
The sent keystroke is one higher than what's received, e.g. The sent keystroke is one higher than what's received, e.g.
if you send a, you get b, send A you get B, and so forth. if you send a, you get b, send A you get B, and so forth.
The circuit: The circuit:
* none * none
created 21 Oct 2011 created 21 Oct 2011
modified 27 Mar 2012 modified 27 Mar 2012
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/KeyboardSerial http://www.arduino.cc/en/Tutorial/KeyboardSerial
*/ */
@ -32,7 +32,7 @@ void loop() {
// read incoming serial data: // read incoming serial data:
char inChar = Serial.read(); char inChar = Serial.read();
// Type the next ASCII value from what you received: // Type the next ASCII value from what you received:
Keyboard.write(inChar+1); Keyboard.write(inChar + 1);
} }
} }

View File

@ -3,38 +3,38 @@
KeyboardAndMouseControl KeyboardAndMouseControl
Controls the mouse from five pushbuttons on an Arduino Leonardo, Micro or Due. Controls the mouse from five pushbuttons on an Arduino Leonardo, Micro or Due.
Hardware: Hardware:
* 5 pushbuttons attached to D2, D3, D4, D5, D6 * 5 pushbuttons attached to D2, D3, D4, D5, D6
The mouse movement is always relative. This sketch reads The mouse movement is always relative. This sketch reads
four pushbuttons, and uses them to set the movement of the mouse. four pushbuttons, and uses them to set the movement of the mouse.
WARNING: When you use the Mouse.move() command, the Arduino takes WARNING: When you use the Mouse.move() command, the Arduino takes
over your mouse! Make sure you have control before you use the mouse commands. over your mouse! Make sure you have control before you use the mouse commands.
created 15 Mar 2012 created 15 Mar 2012
modified 27 Mar 2012 modified 27 Mar 2012
by Tom Igoe by Tom Igoe
this code is in the public domain this code is in the public domain
*/ */
// set pin numbers for the five buttons: // set pin numbers for the five buttons:
const int upButton = 2; const int upButton = 2;
const int downButton = 3; const int downButton = 3;
const int leftButton = 4; const int leftButton = 4;
const int rightButton = 5; const int rightButton = 5;
const int mouseButton = 6; const int mouseButton = 6;
void setup() { // initialize the buttons' inputs: void setup() { // initialize the buttons' inputs:
pinMode(upButton, INPUT); pinMode(upButton, INPUT);
pinMode(downButton, INPUT); pinMode(downButton, INPUT);
pinMode(leftButton, INPUT); pinMode(leftButton, INPUT);
pinMode(rightButton, INPUT); pinMode(rightButton, INPUT);
pinMode(mouseButton, INPUT); pinMode(mouseButton, INPUT);
Serial.begin(9600); Serial.begin(9600);
// initialize mouse control: // initialize mouse control:
Mouse.begin(); Mouse.begin();
@ -46,45 +46,45 @@ void loop() {
if (Serial.available() > 0) { if (Serial.available() > 0) {
char inChar = Serial.read(); char inChar = Serial.read();
switch (inChar) { switch (inChar) {
case 'u': case 'u':
// move mouse up // move mouse up
Mouse.move(0, -40); Mouse.move(0, -40);
break; break;
case 'd': case 'd':
// move mouse down // move mouse down
Mouse.move(0, 40); Mouse.move(0, 40);
break; break;
case 'l': case 'l':
// move mouse left // move mouse left
Mouse.move(-40, 0); Mouse.move(-40, 0);
break; break;
case 'r': case 'r':
// move mouse right // move mouse right
Mouse.move(40, 0); Mouse.move(40, 0);
break; break;
case 'm': case 'm':
// perform mouse left click // perform mouse left click
Mouse.click(MOUSE_LEFT); Mouse.click(MOUSE_LEFT);
break; break;
} }
} }
// use the pushbuttons to control the keyboard: // use the pushbuttons to control the keyboard:
if (digitalRead(upButton) == HIGH) { if (digitalRead(upButton) == HIGH) {
Keyboard.write('u'); Keyboard.write('u');
} }
if (digitalRead(downButton) == HIGH) { if (digitalRead(downButton) == HIGH) {
Keyboard.write('d'); Keyboard.write('d');
} }
if (digitalRead(leftButton) == HIGH) { if (digitalRead(leftButton) == HIGH) {
Keyboard.write('l'); Keyboard.write('l');
} }
if (digitalRead(rightButton) == HIGH) { if (digitalRead(rightButton) == HIGH) {
Keyboard.write('r'); Keyboard.write('r');
} }
if (digitalRead(mouseButton) == HIGH) { if (digitalRead(mouseButton) == HIGH) {
Keyboard.write('m'); Keyboard.write('m');
} }
} }

View File

@ -2,31 +2,31 @@
/* /*
ButtonMouseControl ButtonMouseControl
For Leonardo and Due boards only. For Leonardo and Due boards only.
Controls the mouse from five pushbuttons on an Arduino Leonardo, Micro or Due. Controls the mouse from five pushbuttons on an Arduino Leonardo, Micro or Due.
Hardware: Hardware:
* 5 pushbuttons attached to D2, D3, D4, D5, D6 * 5 pushbuttons attached to D2, D3, D4, D5, D6
The mouse movement is always relative. This sketch reads The mouse movement is always relative. This sketch reads
four pushbuttons, and uses them to set the movement of the mouse. four pushbuttons, and uses them to set the movement of the mouse.
WARNING: When you use the Mouse.move() command, the Arduino takes WARNING: When you use the Mouse.move() command, the Arduino takes
over your mouse! Make sure you have control before you use the mouse commands. over your mouse! Make sure you have control before you use the mouse commands.
created 15 Mar 2012 created 15 Mar 2012
modified 27 Mar 2012 modified 27 Mar 2012
by Tom Igoe by Tom Igoe
this code is in the public domain this code is in the public domain
*/ */
// set pin numbers for the five buttons: // set pin numbers for the five buttons:
const int upButton = 2; const int upButton = 2;
const int downButton = 3; const int downButton = 3;
const int leftButton = 4; const int leftButton = 4;
const int rightButton = 5; const int rightButton = 5;
const int mouseButton = 6; const int mouseButton = 6;
@ -37,10 +37,10 @@ int responseDelay = 10; // response delay of the mouse, in ms
void setup() { void setup() {
// initialize the buttons' inputs: // initialize the buttons' inputs:
pinMode(upButton, INPUT); pinMode(upButton, INPUT);
pinMode(downButton, INPUT); pinMode(downButton, INPUT);
pinMode(leftButton, INPUT); pinMode(leftButton, INPUT);
pinMode(rightButton, INPUT); pinMode(rightButton, INPUT);
pinMode(mouseButton, INPUT); pinMode(mouseButton, INPUT);
// initialize mouse control: // initialize mouse control:
Mouse.begin(); Mouse.begin();
@ -55,8 +55,8 @@ void loop() {
int clickState = digitalRead(mouseButton); int clickState = digitalRead(mouseButton);
// calculate the movement distance based on the button states: // calculate the movement distance based on the button states:
int xDistance = (leftState - rightState)*range; int xDistance = (leftState - rightState) * range;
int yDistance = (upState - downState)*range; int yDistance = (upState - downState) * range;
// if X or Y is non-zero, move: // if X or Y is non-zero, move:
if ((xDistance != 0) || (yDistance != 0)) { if ((xDistance != 0) || (yDistance != 0)) {
@ -67,14 +67,14 @@ void loop() {
if (clickState == HIGH) { if (clickState == HIGH) {
// if the mouse is not pressed, press it: // if the mouse is not pressed, press it:
if (!Mouse.isPressed(MOUSE_LEFT)) { if (!Mouse.isPressed(MOUSE_LEFT)) {
Mouse.press(MOUSE_LEFT); Mouse.press(MOUSE_LEFT);
} }
} }
// else the mouse button is not pressed: // else the mouse button is not pressed:
else { else {
// if the mouse is pressed, release it: // if the mouse is pressed, release it:
if (Mouse.isPressed(MOUSE_LEFT)) { if (Mouse.isPressed(MOUSE_LEFT)) {
Mouse.release(MOUSE_LEFT); Mouse.release(MOUSE_LEFT);
} }
} }

View File

@ -1,53 +1,53 @@
/* /*
JoystickMouseControl JoystickMouseControl
Controls the mouse from a joystick on an Arduino Leonardo, Micro or Due. Controls the mouse from a joystick on an Arduino Leonardo, Micro or Due.
Uses a pushbutton to turn on and off mouse control, and Uses a pushbutton to turn on and off mouse control, and
a second pushbutton to click the left mouse button a second pushbutton to click the left mouse button
Hardware: Hardware:
* 2-axis joystick connected to pins A0 and A1 * 2-axis joystick connected to pins A0 and A1
* pushbuttons connected to pin D2 and D3 * pushbuttons connected to pin D2 and D3
The mouse movement is always relative. This sketch reads The mouse movement is always relative. This sketch reads
two analog inputs that range from 0 to 1023 (or less on either end) two analog inputs that range from 0 to 1023 (or less on either end)
and translates them into ranges of -6 to 6. and translates them into ranges of -6 to 6.
The sketch assumes that the joystick resting values are around the The sketch assumes that the joystick resting values are around the
middle of the range, but that they vary within a threshold. middle of the range, but that they vary within a threshold.
WARNING: When you use the Mouse.move() command, the Arduino takes WARNING: When you use the Mouse.move() command, the Arduino takes
over your mouse! Make sure you have control before you use the command. over your mouse! Make sure you have control before you use the command.
This sketch includes a pushbutton to toggle the mouse control state, so This sketch includes a pushbutton to toggle the mouse control state, so
you can turn on and off mouse control. you can turn on and off mouse control.
created 15 Sept 2011 created 15 Sept 2011
updated 28 Mar 2012 updated 28 Mar 2012
by Tom Igoe by Tom Igoe
this code is in the public domain this code is in the public domain
*/ */
// set pin numbers for switch, joystick axes, and LED: // set pin numbers for switch, joystick axes, and LED:
const int switchPin = 2; // switch to turn on and off mouse control const int switchPin = 2; // switch to turn on and off mouse control
const int mouseButton = 3; // input pin for the mouse pushButton const int mouseButton = 3; // input pin for the mouse pushButton
const int xAxis = A0; // joystick X axis const int xAxis = A0; // joystick X axis
const int yAxis = A1; // joystick Y axis const int yAxis = A1; // joystick Y axis
const int ledPin = 5; // Mouse control LED const int ledPin = 5; // Mouse control LED
// parameters for reading the joystick: // parameters for reading the joystick:
int range = 12; // output range of X or Y movement int range = 12; // output range of X or Y movement
int responseDelay = 5; // response delay of the mouse, in ms int responseDelay = 5; // response delay of the mouse, in ms
int threshold = range/4; // resting threshold int threshold = range / 4; // resting threshold
int center = range/2; // resting position value int center = range / 2; // resting position value
boolean mouseIsActive = false; // whether or not to control the mouse boolean mouseIsActive = false; // whether or not to control the mouse
int lastSwitchState = LOW; // previous switch state int lastSwitchState = LOW; // previous switch state
void setup() { void setup() {
pinMode(switchPin, INPUT); // the switch pin pinMode(switchPin, INPUT); // the switch pin
pinMode(ledPin, OUTPUT); // the LED pin pinMode(ledPin, OUTPUT); // the LED pin
// take control of the mouse: // take control of the mouse:
Mouse.begin(); Mouse.begin();
} }
@ -60,7 +60,7 @@ void loop() {
mouseIsActive = !mouseIsActive; mouseIsActive = !mouseIsActive;
// turn on LED to indicate mouse state: // turn on LED to indicate mouse state:
digitalWrite(ledPin, mouseIsActive); digitalWrite(ledPin, mouseIsActive);
} }
} }
// save switch state for next comparison: // save switch state for next comparison:
lastSwitchState = switchState; lastSwitchState = switchState;
@ -72,21 +72,21 @@ void loop() {
// if the mouse control state is active, move the mouse: // if the mouse control state is active, move the mouse:
if (mouseIsActive) { if (mouseIsActive) {
Mouse.move(xReading, yReading, 0); Mouse.move(xReading, yReading, 0);
} }
// read the mouse button and click or not click: // read the mouse button and click or not click:
// if the mouse button is pressed: // if the mouse button is pressed:
if (digitalRead(mouseButton) == HIGH) { if (digitalRead(mouseButton) == HIGH) {
// if the mouse is not pressed, press it: // if the mouse is not pressed, press it:
if (!Mouse.isPressed(MOUSE_LEFT)) { if (!Mouse.isPressed(MOUSE_LEFT)) {
Mouse.press(MOUSE_LEFT); Mouse.press(MOUSE_LEFT);
} }
} }
// else the mouse button is not pressed: // else the mouse button is not pressed:
else { else {
// if the mouse is pressed, release it: // if the mouse is pressed, release it:
if (Mouse.isPressed(MOUSE_LEFT)) { if (Mouse.isPressed(MOUSE_LEFT)) {
Mouse.release(MOUSE_LEFT); Mouse.release(MOUSE_LEFT);
} }
} }
@ -94,11 +94,11 @@ void loop() {
} }
/* /*
reads an axis (0 or 1 for x or y) and scales the reads an axis (0 or 1 for x or y) and scales the
analog input range to a range from 0 to <range> analog input range to a range from 0 to <range>
*/ */
int readAxis(int thisAxis) { int readAxis(int thisAxis) {
// read the analog input: // read the analog input:
int reading = analogRead(thisAxis); int reading = analogRead(thisAxis);
@ -111,7 +111,7 @@ int readAxis(int thisAxis) {
if (abs(distance) < threshold) { if (abs(distance) < threshold) {
distance = 0; distance = 0;
} }
// return the distance for this axis: // return the distance for this axis:
return distance; return distance;

View File

@ -1,58 +1,58 @@
/* /*
Arduino Starter Kit example Arduino Starter Kit example
Project 2 - Spaceship Interface Project 2 - Spaceship Interface
This sketch is written to accompany Project 2 in the This sketch is written to accompany Project 2 in the
Arduino Starter Kit Arduino Starter Kit
Parts required: Parts required:
1 green LED 1 green LED
2 red LEDs 2 red LEDs
pushbutton pushbutton
10 kilohm resistor 10 kilohm resistor
3 220 ohm resistors 3 220 ohm resistors
Created 13 September 2012 Created 13 September 2012
by Scott Fitzgerald by Scott Fitzgerald
http://arduino.cc/starterKit http://arduino.cc/starterKit
This example code is part of the public domain This example code is part of the public domain
*/ */
// Create a global variable to hold the // Create a global variable to hold the
// state of the switch. This variable is persistent // state of the switch. This variable is persistent
// throughout the program. Whenever you refer to // throughout the program. Whenever you refer to
// switchState, youre talking about the number it holds // switchState, youre talking about the number it holds
int switchstate = 0; int switchstate = 0;
void setup(){ void setup() {
// declare the LED pins as outputs // declare the LED pins as outputs
pinMode(3,OUTPUT); pinMode(3, OUTPUT);
pinMode(4,OUTPUT); pinMode(4, OUTPUT);
pinMode(5,OUTPUT); pinMode(5, OUTPUT);
// declare the switch pin as an input // declare the switch pin as an input
pinMode(2,INPUT); pinMode(2, INPUT);
} }
void loop(){ void loop() {
// read the value of the switch // read the value of the switch
// digitalRead() checks to see if there is voltage // digitalRead() checks to see if there is voltage
// on the pin or not // on the pin or not
switchstate = digitalRead(2); switchstate = digitalRead(2);
// if the button is not pressed // if the button is not pressed
// blink the red LEDs // blink the red LEDs
if (switchstate == LOW) { if (switchstate == LOW) {
digitalWrite(3, HIGH); // turn the green LED on pin 3 on digitalWrite(3, HIGH); // turn the green LED on pin 3 on
digitalWrite(4, LOW); // turn the red LED on pin 4 off digitalWrite(4, LOW); // turn the red LED on pin 4 off
digitalWrite(5, LOW); // turn the red LED on pin 5 off digitalWrite(5, LOW); // turn the red LED on pin 5 off
} }
// this else is part of the above if() statement. // this else is part of the above if() statement.
// if the switch is not LOW (the button is pressed) // if the switch is not LOW (the button is pressed)
// the code below will run // the code below will run
else { else {
digitalWrite(3, LOW); // turn the green LED on pin 3 off digitalWrite(3, LOW); // turn the green LED on pin 3 off
digitalWrite(4, LOW); // turn the red LED on pin 4 off digitalWrite(4, LOW); // turn the red LED on pin 4 off

View File

@ -1,21 +1,21 @@
/* /*
Arduino Starter Kit example Arduino Starter Kit example
Project 3 - Love-O-Meter Project 3 - Love-O-Meter
This sketch is written to accompany Project 3 in the This sketch is written to accompany Project 3 in the
Arduino Starter Kit Arduino Starter Kit
Parts required: Parts required:
1 TMP36 temperature sensor 1 TMP36 temperature sensor
3 red LEDs 3 red LEDs
3 220 ohm resistors 3 220 ohm resistors
Created 13 September 2012 Created 13 September 2012
by Scott Fitzgerald by Scott Fitzgerald
http://arduino.cc/starterKit http://arduino.cc/starterKit
This example code is part of the public domain This example code is part of the public domain
*/ */
// named constant for the pin the sensor is connected to // named constant for the pin the sensor is connected to
@ -23,28 +23,28 @@ const int sensorPin = A0;
// room temperature in Celcius // room temperature in Celcius
const float baselineTemp = 20.0; const float baselineTemp = 20.0;
void setup(){ void setup() {
// open a serial connection to display values // open a serial connection to display values
Serial.begin(9600); Serial.begin(9600);
// set the LED pins as outputs // set the LED pins as outputs
// the for() loop saves some extra coding // the for() loop saves some extra coding
for(int pinNumber = 2; pinNumber<5; pinNumber++){ for (int pinNumber = 2; pinNumber < 5; pinNumber++) {
pinMode(pinNumber,OUTPUT); pinMode(pinNumber, OUTPUT);
digitalWrite(pinNumber, LOW); digitalWrite(pinNumber, LOW);
} }
} }
void loop(){ void loop() {
// read the value on AnalogIn pin 0 // read the value on AnalogIn pin 0
// and store it in a variable // and store it in a variable
int sensorVal = analogRead(sensorPin); int sensorVal = analogRead(sensorPin);
// send the 10-bit sensor value out the serial port // send the 10-bit sensor value out the serial port
Serial.print("sensor Value: "); Serial.print("sensor Value: ");
Serial.print(sensorVal); Serial.print(sensorVal);
// convert the ADC reading to voltage // convert the ADC reading to voltage
float voltage = (sensorVal/1024.0) * 5.0; float voltage = (sensorVal / 1024.0) * 5.0;
// Send the voltage level out the Serial port // Send the voltage level out the Serial port
Serial.print(", Volts: "); Serial.print(", Volts: ");
@ -54,28 +54,28 @@ void loop(){
// the sensor changes 10 mV per degree // the sensor changes 10 mV per degree
// the datasheet says there's a 500 mV offset // the datasheet says there's a 500 mV offset
// ((volatge - 500mV) times 100) // ((volatge - 500mV) times 100)
Serial.print(", degrees C: "); Serial.print(", degrees C: ");
float temperature = (voltage - .5) * 100; float temperature = (voltage - .5) * 100;
Serial.println(temperature); Serial.println(temperature);
// if the current temperature is lower than the baseline // if the current temperature is lower than the baseline
// turn off all LEDs // turn off all LEDs
if(temperature < baselineTemp){ if (temperature < baselineTemp) {
digitalWrite(2, LOW); digitalWrite(2, LOW);
digitalWrite(3, LOW); digitalWrite(3, LOW);
digitalWrite(4, LOW); digitalWrite(4, LOW);
} // if the temperature rises 2-4 degrees, turn an LED on } // if the temperature rises 2-4 degrees, turn an LED on
else if(temperature >= baselineTemp+2 && temperature < baselineTemp+4){ else if (temperature >= baselineTemp + 2 && temperature < baselineTemp + 4) {
digitalWrite(2, HIGH); digitalWrite(2, HIGH);
digitalWrite(3, LOW); digitalWrite(3, LOW);
digitalWrite(4, LOW); digitalWrite(4, LOW);
} // if the temperature rises 4-6 degrees, turn a second LED on } // if the temperature rises 4-6 degrees, turn a second LED on
else if(temperature >= baselineTemp+4 && temperature < baselineTemp+6){ else if (temperature >= baselineTemp + 4 && temperature < baselineTemp + 6) {
digitalWrite(2, HIGH); digitalWrite(2, HIGH);
digitalWrite(3, HIGH); digitalWrite(3, HIGH);
digitalWrite(4, LOW); digitalWrite(4, LOW);
} // if the temperature rises more than 6 degrees, turn all LEDs on } // if the temperature rises more than 6 degrees, turn all LEDs on
else if(temperature >= baselineTemp+6){ else if (temperature >= baselineTemp + 6) {
digitalWrite(2, HIGH); digitalWrite(2, HIGH);
digitalWrite(3, HIGH); digitalWrite(3, HIGH);
digitalWrite(4, HIGH); digitalWrite(4, HIGH);

View File

@ -1,56 +1,56 @@
/* /*
Arduino Starter Kit example Arduino Starter Kit example
Project 4 - Color Mixing Lamp Project 4 - Color Mixing Lamp
This sketch is written to accompany Project 3 in the This sketch is written to accompany Project 3 in the
Arduino Starter Kit Arduino Starter Kit
Parts required: Parts required:
1 RGB LED 1 RGB LED
three 10 kilohm resistors three 10 kilohm resistors
3 220 ohm resistors 3 220 ohm resistors
3 photoresistors 3 photoresistors
red green and blue colored gels red green and blue colored gels
Created 13 September 2012 Created 13 September 2012
Modified 14 November 2012 Modified 14 November 2012
by Scott Fitzgerald by Scott Fitzgerald
Thanks to Federico Vanzati for improvements Thanks to Federico Vanzati for improvements
http://arduino.cc/starterKit http://arduino.cc/starterKit
This example code is part of the public domain This example code is part of the public domain
*/ */
const int greenLEDPin = 9; // LED connected to digital pin 9 const int greenLEDPin = 9; // LED connected to digital pin 9
const int redLEDPin = 10; // LED connected to digital pin 10 const int redLEDPin = 10; // LED connected to digital pin 10
const int blueLEDPin = 11; // LED connected to digital pin 11 const int blueLEDPin = 11; // LED connected to digital pin 11
const int redSensorPin = A0; // pin with the photoresistor with the red gel const int redSensorPin = A0; // pin with the photoresistor with the red gel
const int greenSensorPin = A1; // pin with the photoresistor with the green gel const int greenSensorPin = A1; // pin with the photoresistor with the green gel
const int blueSensorPin = A2; // pin with the photoresistor with the blue gel const int blueSensorPin = A2; // pin with the photoresistor with the blue gel
int redValue = 0; // value to write to the red LED int redValue = 0; // value to write to the red LED
int greenValue = 0; // value to write to the green LED int greenValue = 0; // value to write to the green LED
int blueValue = 0; // value to write to the blue LED int blueValue = 0; // value to write to the blue LED
int redSensorValue = 0; // variable to hold the value from the red sensor int redSensorValue = 0; // variable to hold the value from the red sensor
int greenSensorValue = 0; // variable to hold the value from the green sensor int greenSensorValue = 0; // variable to hold the value from the green sensor
int blueSensorValue = 0; // variable to hold the value from the blue sensor int blueSensorValue = 0; // variable to hold the value from the blue sensor
void setup() { void setup() {
// initialize serial communications at 9600 bps: // initialize serial communications at 9600 bps:
Serial.begin(9600); Serial.begin(9600);
// set the digital pins as outputs // set the digital pins as outputs
pinMode(greenLEDPin,OUTPUT); pinMode(greenLEDPin, OUTPUT);
pinMode(redLEDPin,OUTPUT); pinMode(redLEDPin, OUTPUT);
pinMode(blueLEDPin,OUTPUT); pinMode(blueLEDPin, OUTPUT);
} }
void loop() { void loop() {
// Read the sensors first: // Read the sensors first:
// read the value from the red-filtered photoresistor: // read the value from the red-filtered photoresistor:
redSensorValue = analogRead(redSensorPin); redSensorValue = analogRead(redSensorPin);
// give the ADC a moment to settle // give the ADC a moment to settle
@ -60,9 +60,9 @@ void loop() {
// give the ADC a moment to settle // give the ADC a moment to settle
delay(5); delay(5);
// read the value from the blue-filtered photoresistor: // read the value from the blue-filtered photoresistor:
blueSensorValue = analogRead(blueSensorPin); blueSensorValue = analogRead(blueSensorPin);
// print out the values to the serial monitor // print out the values to the serial monitor
Serial.print("raw sensor Values \t red: "); Serial.print("raw sensor Values \t red: ");
Serial.print(redSensorValue); Serial.print(redSensorValue);
Serial.print("\t green: "); Serial.print("\t green: ");
@ -71,22 +71,22 @@ void loop() {
Serial.println(blueSensorValue); Serial.println(blueSensorValue);
/* /*
In order to use the values from the sensor for the LED, In order to use the values from the sensor for the LED,
you need to do some math. The ADC provides a 10-bit number, you need to do some math. The ADC provides a 10-bit number,
but analogWrite() uses 8 bits. You'll want to divide your but analogWrite() uses 8 bits. You'll want to divide your
sensor readings by 4 to keep them in range of the output. sensor readings by 4 to keep them in range of the output.
*/ */
redValue = redSensorValue/4; redValue = redSensorValue / 4;
greenValue = greenSensorValue/4; greenValue = greenSensorValue / 4;
blueValue = blueSensorValue/4; blueValue = blueSensorValue / 4;
// print out the mapped values // print out the mapped values
Serial.print("Mapped sensor Values \t red: "); Serial.print("Mapped sensor Values \t red: ");
Serial.print(redValue); Serial.print(redValue);
Serial.print("\t green: "); Serial.print("\t green: ");
Serial.print(greenValue); Serial.print(greenValue);
Serial.print("\t Blue: "); Serial.print("\t Blue: ");
Serial.println(blueValue); Serial.println(blueValue);
/* /*
Now that you have a usable value, it's time to PWM the LED. Now that you have a usable value, it's time to PWM the LED.

View File

@ -1,34 +1,34 @@
/* /*
Arduino Starter Kit example Arduino Starter Kit example
Project 5 - Servo Mood Indicator Project 5 - Servo Mood Indicator
This sketch is written to accompany Project 5 in the This sketch is written to accompany Project 5 in the
Arduino Starter Kit Arduino Starter Kit
Parts required: Parts required:
servo motor servo motor
10 kilohm potentiometer 10 kilohm potentiometer
2 100 uF electrolytic capacitors 2 100 uF electrolytic capacitors
Created 13 September 2012 Created 13 September 2012
by Scott Fitzgerald by Scott Fitzgerald
http://arduino.cc/starterKit http://arduino.cc/starterKit
This example code is part of the public domain This example code is part of the public domain
*/ */
// include the servo library // include the servo library
#include <Servo.h> #include <Servo.h>
Servo myServo; // create a servo object Servo myServo; // create a servo object
int const potPin = A0; // analog pin used to connect the potentiometer int const potPin = A0; // analog pin used to connect the potentiometer
int potVal; // variable to read the value from the analog pin int potVal; // variable to read the value from the analog pin
int angle; // variable to hold the angle for the servo motor int angle; // variable to hold the angle for the servo motor
void setup() { void setup() {
myServo.attach(9); // attaches the servo on pin 9 to the servo object myServo.attach(9); // attaches the servo on pin 9 to the servo object
Serial.begin(9600); // open a serial connection to your computer Serial.begin(9600); // open a serial connection to your computer
} }
@ -38,17 +38,17 @@ void loop() {
Serial.print("potVal: "); Serial.print("potVal: ");
Serial.print(potVal); Serial.print(potVal);
// scale the numbers from the pot // scale the numbers from the pot
angle = map(potVal, 0, 1023, 0, 179); angle = map(potVal, 0, 1023, 0, 179);
// print out the angle for the servo motor // print out the angle for the servo motor
Serial.print(", angle: "); Serial.print(", angle: ");
Serial.println(angle); Serial.println(angle);
// set the servo position // set the servo position
myServo.write(angle); myServo.write(angle);
// wait for the servo to get there // wait for the servo to get there
delay(15); delay(15);
} }

View File

@ -1,21 +1,21 @@
/* /*
Arduino Starter Kit example Arduino Starter Kit example
Project 6 - Light Theremin Project 6 - Light Theremin
This sketch is written to accompany Project 6 in the This sketch is written to accompany Project 6 in the
Arduino Starter Kit Arduino Starter Kit
Parts required: Parts required:
photoresistor photoresistor
10 kilohm resistor 10 kilohm resistor
piezo piezo
Created 13 September 2012 Created 13 September 2012
by Scott Fitzgerald by Scott Fitzgerald
http://arduino.cc/starterKit http://arduino.cc/starterKit
This example code is part of the public domain This example code is part of the public domain
*/ */
// variable to hold sensor value // variable to hold sensor value

View File

@ -1,32 +1,32 @@
/* /*
Arduino Starter Kit example Arduino Starter Kit example
Project 7 - Keyboard Project 7 - Keyboard
This sketch is written to accompany Project 7 in the This sketch is written to accompany Project 7 in the
Arduino Starter Kit Arduino Starter Kit
Parts required: Parts required:
two 10 kilohm resistors two 10 kilohm resistors
1 Megohm resistor 1 Megohm resistor
220 ohm resistor 220 ohm resistor
4 pushbuttons 4 pushbuttons
piezo piezo
Created 13 September 2012 Created 13 September 2012
by Scott Fitzgerald by Scott Fitzgerald
http://arduino.cc/starterKit http://arduino.cc/starterKit
This example code is part of the public domain This example code is part of the public domain
*/ */
// create an array of notes // create an array of notes
// the numbers below correspond to // the numbers below correspond to
// the frequencies of middle C, D, E, and F // the frequencies of middle C, D, E, and F
int notes[] = {262, 294, 330, 349}; int notes[] = {262, 294, 330, 349};
void setup() { void setup() {
//start serial communication //start serial communication
Serial.begin(9600); Serial.begin(9600);
} }
@ -35,27 +35,27 @@ void loop() {
int keyVal = analogRead(A0); int keyVal = analogRead(A0);
// send the value from A0 to the Serial Monitor // send the value from A0 to the Serial Monitor
Serial.println(keyVal); Serial.println(keyVal);
// play the note corresponding to each value on A0 // play the note corresponding to each value on A0
if(keyVal == 1023){ if (keyVal == 1023) {
// play the first frequency in the array on pin 8 // play the first frequency in the array on pin 8
tone(8, notes[0]); tone(8, notes[0]);
} }
else if(keyVal >= 990 && keyVal <= 1010){ else if (keyVal >= 990 && keyVal <= 1010) {
// play the second frequency in the array on pin 8 // play the second frequency in the array on pin 8
tone(8, notes[1]); tone(8, notes[1]);
} }
else if(keyVal >= 505 && keyVal <= 515){ else if (keyVal >= 505 && keyVal <= 515) {
// play the third frequency in the array on pin 8 // play the third frequency in the array on pin 8
tone(8, notes[2]); tone(8, notes[2]);
} }
else if(keyVal >= 5 && keyVal <= 10){ else if (keyVal >= 5 && keyVal <= 10) {
// play the fourth frequency in the array on pin 8 // play the fourth frequency in the array on pin 8
tone(8, notes[3]); tone(8, notes[3]);
} }
else{ else {
// if the value is out of range, play no tone // if the value is out of range, play no tone
noTone(8); noTone(8);
} }
} }

View File

@ -1,22 +1,22 @@
/* /*
Arduino Starter Kit example Arduino Starter Kit example
Project 8 - Digital Hourglass Project 8 - Digital Hourglass
This sketch is written to accompany Project 8 in the This sketch is written to accompany Project 8 in the
Arduino Starter Kit Arduino Starter Kit
Parts required: Parts required:
10 kilohm resistor 10 kilohm resistor
six 220 ohm resistors six 220 ohm resistors
six LEDs six LEDs
tilt switch tilt switch
Created 13 September 2012 Created 13 September 2012
by Scott Fitzgerald by Scott Fitzgerald
http://arduino.cc/starterKit http://arduino.cc/starterKit
This example code is part of the public domain This example code is part of the public domain
*/ */
// named constant for the switch pin // named constant for the switch pin
@ -28,50 +28,50 @@ int prevSwitchState = 0; // the previous switch state
int led = 2; // a variable to refer to the LEDs int led = 2; // a variable to refer to the LEDs
// 600000 = 10 minutes in milliseconds // 600000 = 10 minutes in milliseconds
long interval = 600000; // interval at which to light the next LED long interval = 600000; // interval at which to light the next LED
void setup() { void setup() {
// set the LED pins as outputs // set the LED pins as outputs
for(int x = 2;x<8;x++){ for (int x = 2; x < 8; x++) {
pinMode(x, OUTPUT); pinMode(x, OUTPUT);
} }
// set the tilt switch pin as input // set the tilt switch pin as input
pinMode(switchPin, INPUT); pinMode(switchPin, INPUT);
} }
void loop(){ void loop() {
// store the time since the Arduino started running in a variable // store the time since the Arduino started running in a variable
unsigned long currentTime = millis(); unsigned long currentTime = millis();
// compare the current time to the previous time an LED turned on // compare the current time to the previous time an LED turned on
// if it is greater than your interval, run the if statement // if it is greater than your interval, run the if statement
if(currentTime - previousTime > interval) { if (currentTime - previousTime > interval) {
// save the current time as the last time you changed an LED // save the current time as the last time you changed an LED
previousTime = currentTime; previousTime = currentTime;
// Turn the LED on // Turn the LED on
digitalWrite(led, HIGH); digitalWrite(led, HIGH);
// increment the led variable // increment the led variable
// in 10 minutes the next LED will light up // in 10 minutes the next LED will light up
led++; led++;
if(led == 7){ if (led == 7) {
// the hour is up // the hour is up
} }
} }
// read the switch value // read the switch value
switchState = digitalRead(switchPin); switchState = digitalRead(switchPin);
// if the switch has changed // if the switch has changed
if(switchState != prevSwitchState){ if (switchState != prevSwitchState) {
// turn all the LEDs low // turn all the LEDs low
for(int x = 2;x<8;x++){ for (int x = 2; x < 8; x++) {
digitalWrite(x, LOW); digitalWrite(x, LOW);
} }
// reset the LED variable to the first one // reset the LED variable to the first one
led = 2; led = 2;
//reset the timer //reset the timer
previousTime = currentTime; previousTime = currentTime;
} }

View File

@ -1,10 +1,10 @@
/* /*
Arduino Starter Kit example Arduino Starter Kit example
Project 9 - Motorized Pinwheel Project 9 - Motorized Pinwheel
This sketch is written to accompany Project 9 in the This sketch is written to accompany Project 9 in the
Arduino Starter Kit Arduino Starter Kit
Parts required: Parts required:
10 kilohm resistor 10 kilohm resistor
pushbutton pushbutton
@ -12,13 +12,13 @@
9V battery 9V battery
IRF520 MOSFET IRF520 MOSFET
1N4007 diode 1N4007 diode
Created 13 September 2012 Created 13 September 2012
by Scott Fitzgerald by Scott Fitzgerald
http://arduino.cc/starterKit http://arduino.cc/starterKit
This example code is part of the public domain This example code is part of the public domain
*/ */
// named constants for the switch and motor pins // named constants for the switch and motor pins
@ -29,22 +29,22 @@ int switchState = 0; // variable for reading the switch's status
void setup() { void setup() {
// initialize the motor pin as an output: // initialize the motor pin as an output:
pinMode(motorPin, OUTPUT); pinMode(motorPin, OUTPUT);
// initialize the switch pin as an input: // initialize the switch pin as an input:
pinMode(switchPin, INPUT); pinMode(switchPin, INPUT);
} }
void loop(){ void loop() {
// read the state of the switch value: // read the state of the switch value:
switchState = digitalRead(switchPin); switchState = digitalRead(switchPin);
// check if the switch is pressed. // check if the switch is pressed.
if (switchState == HIGH) { if (switchState == HIGH) {
// turn motor on: // turn motor on:
digitalWrite(motorPin, HIGH); digitalWrite(motorPin, HIGH);
} }
else { else {
// turn motor off: // turn motor off:
digitalWrite(motorPin, LOW); digitalWrite(motorPin, LOW);
} }
} }

View File

@ -1,10 +1,10 @@
/* /*
Arduino Starter Kit example Arduino Starter Kit example
Project 10 - Zoetrope Project 10 - Zoetrope
This sketch is written to accompany Project 10 in the This sketch is written to accompany Project 10 in the
Arduino Starter Kit Arduino Starter Kit
Parts required: Parts required:
two 10 kilohm resistors two 10 kilohm resistors
2 momentary pushbuttons 2 momentary pushbuttons
@ -12,14 +12,14 @@
motor motor
9V battery 9V battery
H-Bridge H-Bridge
Created 13 September 2012 Created 13 September 2012
by Scott Fitzgerald by Scott Fitzgerald
Thanks to Federico Vanzati for improvements Thanks to Federico Vanzati for improvements
http://arduino.cc/starterKit http://arduino.cc/starterKit
This example code is part of the public domain This example code is part of the public domain
*/ */
const int controlPin1 = 2; // connected to pin 7 on the H-bridge const int controlPin1 = 2; // connected to pin 7 on the H-bridge
@ -39,7 +39,7 @@ int motorEnabled = 0; // Turns the motor on/off
int motorSpeed = 0; // speed of the motor int motorSpeed = 0; // speed of the motor
int motorDirection = 1; // current direction of the motor int motorDirection = 1; // current direction of the motor
void setup(){ void setup() {
// intialize the inputs and outputs // intialize the inputs and outputs
pinMode(directionSwitchPin, INPUT); pinMode(directionSwitchPin, INPUT);
pinMode(onOffSwitchStateSwitchPin, INPUT); pinMode(onOffSwitchStateSwitchPin, INPUT);
@ -51,44 +51,44 @@ void setup(){
digitalWrite(enablePin, LOW); digitalWrite(enablePin, LOW);
} }
void loop(){ void loop() {
// read the value of the on/off switch // read the value of the on/off switch
onOffSwitchState = digitalRead(onOffSwitchStateSwitchPin); onOffSwitchState = digitalRead(onOffSwitchStateSwitchPin);
delay(1); delay(1);
// read the value of the direction switch // read the value of the direction switch
directionSwitchState = digitalRead(directionSwitchPin); directionSwitchState = digitalRead(directionSwitchPin);
// read the value of the pot and divide by 4 to get // read the value of the pot and divide by 4 to get
// a value that can be used for PWM // a value that can be used for PWM
motorSpeed = analogRead(potPin)/4; motorSpeed = analogRead(potPin) / 4;
// if the on/off button changed state since the last loop() // if the on/off button changed state since the last loop()
if(onOffSwitchState != previousOnOffSwitchState){ if (onOffSwitchState != previousOnOffSwitchState) {
// change the value of motorEnabled if pressed // change the value of motorEnabled if pressed
if(onOffSwitchState == HIGH){ if (onOffSwitchState == HIGH) {
motorEnabled = !motorEnabled; motorEnabled = !motorEnabled;
} }
} }
// if the direction button changed state since the last loop() // if the direction button changed state since the last loop()
if (directionSwitchState != previousDirectionSwitchState) { if (directionSwitchState != previousDirectionSwitchState) {
// change the value of motorDirection if pressed // change the value of motorDirection if pressed
if (directionSwitchState == HIGH) { if (directionSwitchState == HIGH) {
motorDirection = !motorDirection; motorDirection = !motorDirection;
} }
} }
// change the direction the motor spins by talking // change the direction the motor spins by talking
// to the control pins on the H-Bridge // to the control pins on the H-Bridge
if (motorDirection == 1) { if (motorDirection == 1) {
digitalWrite(controlPin1, HIGH); digitalWrite(controlPin1, HIGH);
digitalWrite(controlPin2, LOW); digitalWrite(controlPin2, LOW);
} }
else { else {
digitalWrite(controlPin1, LOW); digitalWrite(controlPin1, LOW);
digitalWrite(controlPin2, HIGH); digitalWrite(controlPin2, HIGH);
} }
// if the motor is supposed to be on // if the motor is supposed to be on
if (motorEnabled == 1) { if (motorEnabled == 1) {
@ -99,7 +99,7 @@ void loop(){
//turn the motor off //turn the motor off
analogWrite(enablePin, 0); analogWrite(enablePin, 0);
} }
// save the current On/Offswitch state as the previous // save the current On/Offswitch state as the previous
previousDirectionSwitchState = directionSwitchState; previousDirectionSwitchState = directionSwitchState;
// save the current switch state as the previous // save the current switch state as the previous
previousOnOffSwitchState = onOffSwitchState; previousOnOffSwitchState = onOffSwitchState;

View File

@ -1,24 +1,24 @@
/* /*
Arduino Starter Kit example Arduino Starter Kit example
Project 11 - Crystal Ball Project 11 - Crystal Ball
This sketch is written to accompany Project 11 in the This sketch is written to accompany Project 11 in the
Arduino Starter Kit Arduino Starter Kit
Parts required: Parts required:
220 ohm resistor 220 ohm resistor
10 kilohm resistor 10 kilohm resistor
10 kilohm potentiometer 10 kilohm potentiometer
16x2 LCD screen 16x2 LCD screen
tilt switch tilt switch
Created 13 September 2012 Created 13 September 2012
by Scott Fitzgerald by Scott Fitzgerald
http://arduino.cc/starterKit http://arduino.cc/starterKit
This example code is part of the public domain This example code is part of the public domain
*/ */
// include the library code: // include the library code:
@ -40,12 +40,12 @@ int prevSwitchState = 0;
int reply; int reply;
void setup() { void setup() {
// set up the number of columns and rows on the LCD // set up the number of columns and rows on the LCD
lcd.begin(16, 2); lcd.begin(16, 2);
// set up the switch pin as an input // set up the switch pin as an input
pinMode(switchPin,INPUT); pinMode(switchPin, INPUT);
// Print a message to the LCD. // Print a message to the LCD.
lcd.print("Ask the"); lcd.print("Ask the");
// set the cursor to column 0, line 1 // set the cursor to column 0, line 1
@ -62,57 +62,57 @@ void loop() {
// compare the switchState to its previous state // compare the switchState to its previous state
if (switchState != prevSwitchState) { if (switchState != prevSwitchState) {
// if the state has changed from HIGH to LOW // if the state has changed from HIGH to LOW
// you know that the ball has been tilted from // you know that the ball has been tilted from
// one direction to the other // one direction to the other
if (switchState == LOW) { if (switchState == LOW) {
// randomly chose a reply // randomly chose a reply
reply = random(8); reply = random(8);
// clean up the screen before printing a new reply // clean up the screen before printing a new reply
lcd.clear(); lcd.clear();
// set the cursor to column 0, line 0 // set the cursor to column 0, line 0
lcd.setCursor(0, 0); lcd.setCursor(0, 0);
// print some text // print some text
lcd.print("the ball says:"); lcd.print("the ball says:");
// move the cursor to the second line // move the cursor to the second line
lcd.setCursor(0, 1); lcd.setCursor(0, 1);
// choose a saying to print baed on the value in reply // choose a saying to print baed on the value in reply
switch(reply){ switch (reply) {
case 0: case 0:
lcd.print("Yes"); lcd.print("Yes");
break; break;
case 1: case 1:
lcd.print("Most likely"); lcd.print("Most likely");
break; break;
case 2: case 2:
lcd.print("Certainly"); lcd.print("Certainly");
break; break;
case 3: case 3:
lcd.print("Outlook good"); lcd.print("Outlook good");
break; break;
case 4: case 4:
lcd.print("Unsure"); lcd.print("Unsure");
break; break;
case 5: case 5:
lcd.print("Ask again"); lcd.print("Ask again");
break; break;
case 6: case 6:
lcd.print("Doubtful"); lcd.print("Doubtful");
break; break;
case 7: case 7:
lcd.print("No"); lcd.print("No");
break; break;
} }
} }
} }
// save the current switch state as the last state // save the current switch state as the last state
prevSwitchState = switchState; prevSwitchState = switchState;
} }

View File

@ -1,10 +1,10 @@
/* /*
Arduino Starter Kit example Arduino Starter Kit example
Project 12 - Knock Lock Project 12 - Knock Lock
This sketch is written to accompany Project 12 in the This sketch is written to accompany Project 12 in the
Arduino Starter Kit Arduino Starter Kit
Parts required: Parts required:
1 Megohm resistor 1 Megohm resistor
10 kilohm resistor 10 kilohm resistor
@ -16,17 +16,17 @@
one yellow LED one yellow LED
one green LED one green LED
100 uF capacitor 100 uF capacitor
Created 18 September 2012 Created 18 September 2012
by Scott Fitzgerald by Scott Fitzgerald
Thanks to Federico Vanzati for improvements Thanks to Federico Vanzati for improvements
http://arduino.cc/starterKit http://arduino.cc/starterKit
This example code is part of the public domain This example code is part of the public domain
*/ */
// import the library // import the library
#include <Servo.h> #include <Servo.h>
// create an instance of the servo library // create an instance of the servo library
Servo myServo; Servo myServo;
@ -51,7 +51,7 @@ boolean locked = false;
// how many valid knocks you've received // how many valid knocks you've received
int numberOfKnocks = 0; int numberOfKnocks = 0;
void setup(){ void setup() {
// attach the servo to pin 9 // attach the servo to pin 9
myServo.attach(9); myServo.attach(9);
@ -76,22 +76,22 @@ void setup(){
Serial.println("the box is unlocked!"); Serial.println("the box is unlocked!");
} }
void loop(){ void loop() {
// if the box is unlocked // if the box is unlocked
if(locked == false){ if (locked == false) {
// read the value of the switch pin // read the value of the switch pin
switchVal = digitalRead(switchPin); switchVal = digitalRead(switchPin);
// if the button is pressed, lock the box // if the button is pressed, lock the box
if(switchVal == HIGH){ if (switchVal == HIGH) {
// set the locked variable to "true" // set the locked variable to "true"
locked = true; locked = true;
// change the status LEDs // change the status LEDs
digitalWrite(greenLed,LOW); digitalWrite(greenLed, LOW);
digitalWrite(redLed,HIGH); digitalWrite(redLed, HIGH);
// move the servo to the locked position // move the servo to the locked position
myServo.write(90); myServo.write(90);
@ -105,16 +105,16 @@ void loop(){
} }
// if the box is locked // if the box is locked
if(locked == true){ if (locked == true) {
// check the value of the piezo // check the value of the piezo
knockVal = analogRead(piezo); knockVal = analogRead(piezo);
// if there are not enough valid knocks // if there are not enough valid knocks
if(numberOfKnocks < 3 && knockVal > 0){ if (numberOfKnocks < 3 && knockVal > 0) {
// check to see if the knock is in range // check to see if the knock is in range
if(checkForKnock(knockVal) == true){ if (checkForKnock(knockVal) == true) {
// increment the number of valid knocks // increment the number of valid knocks
numberOfKnocks++; numberOfKnocks++;
@ -126,7 +126,7 @@ void loop(){
} }
// if there are three knocks // if there are three knocks
if(numberOfKnocks >= 3){ if (numberOfKnocks >= 3) {
// unlock the box // unlock the box
locked = false; locked = false;
@ -137,19 +137,19 @@ void loop(){
delay(20); delay(20);
// change status LEDs // change status LEDs
digitalWrite(greenLed,HIGH); digitalWrite(greenLed, HIGH);
digitalWrite(redLed,LOW); digitalWrite(redLed, LOW);
Serial.println("the box is unlocked!"); Serial.println("the box is unlocked!");
} }
} }
} }
// this function checks to see if a // this function checks to see if a
// detected knock is within max and min range // detected knock is within max and min range
boolean checkForKnock(int value){ boolean checkForKnock(int value) {
// if the value of the knock is greater than // if the value of the knock is greater than
// the minimum, and larger than the maximum // the minimum, and larger than the maximum
if(value > quietKnock && value < loudKnock){ if (value > quietKnock && value < loudKnock) {
// turn the status LED on // turn the status LED on
digitalWrite(yellowLed, HIGH); digitalWrite(yellowLed, HIGH);
delay(50); delay(50);
@ -164,7 +164,7 @@ boolean checkForKnock(int value){
else { else {
// print status // print status
Serial.print("Bad knock value "); Serial.print("Bad knock value ");
Serial.println(value); Serial.println(value);
// return false // return false
return false; return false;
} }

View File

@ -1,26 +1,26 @@
/* /*
Arduino Starter Kit example Arduino Starter Kit example
Project 13 - Touch Sensor Lamp Project 13 - Touch Sensor Lamp
This sketch is written to accompany Project 13 in the This sketch is written to accompany Project 13 in the
Arduino Starter Kit Arduino Starter Kit
Parts required: Parts required:
1 Megohm resistor 1 Megohm resistor
metal foil or copper mesh metal foil or copper mesh
220 ohm resistor 220 ohm resistor
LED LED
Software required : Software required :
CapacitiveSensor library by Paul Badger CapacitiveSensor library by Paul Badger
http://arduino.cc/playground/Main/CapacitiveSensor http://arduino.cc/playground/Main/CapacitiveSensor
Created 18 September 2012 Created 18 September 2012
by Scott Fitzgerald by Scott Fitzgerald
http://arduino.cc/starterKit http://arduino.cc/starterKit
This example code is part of the public domain This example code is part of the public domain
*/ */
// import the library (must be located in the // import the library (must be located in the
@ -30,7 +30,7 @@
// create an instance of the library // create an instance of the library
// pin 4 sends electrical energy // pin 4 sends electrical energy
// pin 2 senses senses a change // pin 2 senses senses a change
CapacitiveSensor capSensor = CapacitiveSensor(4,2); CapacitiveSensor capSensor = CapacitiveSensor(4, 2);
// threshold for turning the lamp on // threshold for turning the lamp on
int threshold = 1000; int threshold = 1000;
@ -51,10 +51,10 @@ void loop() {
long sensorValue = capSensor.capacitiveSensor(30); long sensorValue = capSensor.capacitiveSensor(30);
// print out the sensor value // print out the sensor value
Serial.println(sensorValue); Serial.println(sensorValue);
// if the value is greater than the threshold // if the value is greater than the threshold
if(sensorValue > threshold) { if (sensorValue > threshold) {
// turn the LED on // turn the LED on
digitalWrite(ledPin, HIGH); digitalWrite(ledPin, HIGH);
} }

View File

@ -1,23 +1,23 @@
/* /*
Arduino Starter Kit example Arduino Starter Kit example
Project 14 - Tweak the Arduino Logo Project 14 - Tweak the Arduino Logo
This sketch is written to accompany Project 14 in the This sketch is written to accompany Project 14 in the
Arduino Starter Kit Arduino Starter Kit
Parts required: Parts required:
10 kilohm potentiometer 10 kilohm potentiometer
Software required : Software required :
Processing http://processing.org Processing http://processing.org
Active internet connection Active internet connection
Created 18 September 2012 Created 18 September 2012
by Scott Fitzgerald by Scott Fitzgerald
http://arduino.cc/starterKit http://arduino.cc/starterKit
This example code is part of the public domain This example code is part of the public domain
*/ */
@ -27,9 +27,9 @@ void setup() {
} }
void loop() { void loop() {
// read the value of A0, divide by 4 and // read the value of A0, divide by 4 and
// send it as a byte over the serial connection // send it as a byte over the serial connection
Serial.write(analogRead(A0)/4); Serial.write(analogRead(A0) / 4);
delay(1); delay(1);
} }
@ -37,68 +37,68 @@ void loop() {
// Tweak the Arduno Logo // Tweak the Arduno Logo
// by Scott Fitzgerald // by Scott Fitzgerald
// This example code is in the public domain // This example code is in the public domain
// import the serial library // import the serial library
import processing.serial.*; import processing.serial.*;
// create an instance of the serial library // create an instance of the serial library
Serial myPort; Serial myPort;
// create an instance of PImage // create an instance of PImage
PImage logo; PImage logo;
// a variable to hold the background color // a variable to hold the background color
int bgcolor = 0; int bgcolor = 0;
void setup() { void setup() {
// set the color mode to Hue/Saturation/Brightness // set the color mode to Hue/Saturation/Brightness
colorMode(HSB, 255); colorMode(HSB, 255);
// load the Arduino logo into the PImage instance // load the Arduino logo into the PImage instance
logo = loadImage("http://arduino.cc/en/pub/skins/arduinoWide/img/logo.png"); logo = loadImage("http://arduino.cc/en/pub/skins/arduinoWide/img/logo.png");
// make the window the same size as the image // make the window the same size as the image
size(logo.width, logo.height); size(logo.width, logo.height);
// print a list of available serial ports to the // print a list of available serial ports to the
// Processing staus window // Processing staus window
println("Available serial ports:"); println("Available serial ports:");
println(Serial.list()); println(Serial.list());
// Tell the serial object the information it needs to communicate // Tell the serial object the information it needs to communicate
// with the Arduno. Change Serial.list()[0] to the correct // with the Arduno. Change Serial.list()[0] to the correct
// port corresponding to your Arduino board. The last // port corresponding to your Arduino board. The last
// parameter (e.g. 9600) is the speed of the communication. It // parameter (e.g. 9600) is the speed of the communication. It
// has to correspond to the value passed to Serial.begin() in your // has to correspond to the value passed to Serial.begin() in your
// Arduino sketch. // Arduino sketch.
myPort = new Serial(this, Serial.list()[0], 9600); myPort = new Serial(this, Serial.list()[0], 9600);
// If you know the name of the port used by the Arduino board, you // If you know the name of the port used by the Arduino board, you
// can specify it directly like this. // can specify it directly like this.
// port = new Serial(this, "COM1", 9600); // port = new Serial(this, "COM1", 9600);
} }
void draw() { void draw() {
// if there is information in the serial port // if there is information in the serial port
if ( myPort.available() > 0) { if ( myPort.available() > 0) {
// read the value and store it in a variable // read the value and store it in a variable
bgcolor = myPort.read(); bgcolor = myPort.read();
// print the value to the status window // print the value to the status window
println(bgcolor); println(bgcolor);
} }
// Draw the background. the variable bgcolor // Draw the background. the variable bgcolor
// contains the Hue, determined by the value // contains the Hue, determined by the value
// from the serial port // from the serial port
background(bgcolor, 255, 255); background(bgcolor, 255, 255);
// draw the Arduino logo // draw the Arduino logo
image(logo, 0, 0); image(logo, 0, 0);
} }
*/ */

View File

@ -1,37 +1,37 @@
/* /*
Arduino Starter Kit example Arduino Starter Kit example
Project 15 - Hacking Buttons Project 15 - Hacking Buttons
This sketch is written to accompany Project 15 in the This sketch is written to accompany Project 15 in the
Arduino Starter Kit Arduino Starter Kit
Parts required: Parts required:
batery powered component batery powered component
220 ohm resistor 220 ohm resistor
4N35 optocoupler 4N35 optocoupler
Created 18 September 2012 Created 18 September 2012
by Scott Fitzgerald by Scott Fitzgerald
http://arduino.cc/starterKit http://arduino.cc/starterKit
This example code is part of the public domain This example code is part of the public domain
*/ */
const int optoPin = 2; // the pin the optocoupler is connected to const int optoPin = 2; // the pin the optocoupler is connected to
void setup(){ void setup() {
// make the pin with the optocoupler an output // make the pin with the optocoupler an output
pinMode(optoPin, OUTPUT); pinMode(optoPin, OUTPUT);
} }
void loop(){ void loop() {
digitalWrite(optoPin, HIGH); // pull pin 2 HIGH, activating the optocoupler digitalWrite(optoPin, HIGH); // pull pin 2 HIGH, activating the optocoupler
delay(15); // give the optocoupler a moment to activate delay(15); // give the optocoupler a moment to activate
digitalWrite(optoPin, LOW); // pull pin 2 low until you're ready to activate again digitalWrite(optoPin, LOW); // pull pin 2 low until you're ready to activate again
delay(21000); // wait for 21 seconds delay(21000); // wait for 21 seconds
} }

View File

@ -1,16 +1,16 @@
// ArduinoISP version 04m3 // ArduinoISP version 04m3
// Copyright (c) 2008-2011 Randall Bohn // Copyright (c) 2008-2011 Randall Bohn
// If you require a license, see // If you require a license, see
// http://www.opensource.org/licenses/bsd-license.php // http://www.opensource.org/licenses/bsd-license.php
// //
// This sketch turns the Arduino into a AVRISP // This sketch turns the Arduino into a AVRISP
// using the following arduino pins: // using the following arduino pins:
// //
// pin name: not-mega: mega(1280 and 2560) // pin name: not-mega: mega(1280 and 2560)
// slave reset: 10: 53 // slave reset: 10: 53
// MOSI: 11: 51 // MOSI: 11: 51
// MISO: 12: 50 // MISO: 12: 50
// SCK: 13: 52 // SCK: 13: 52
// //
// Put an LED (with resistor) on the following pins: // Put an LED (with resistor) on the following pins:
// 9: Heartbeat - shows the programmer is running // 9: Heartbeat - shows the programmer is running
@ -31,7 +31,7 @@
// //
// October 2009 by David A. Mellis // October 2009 by David A. Mellis
// - Added support for the read signature command // - Added support for the read signature command
// //
// February 2009 by Randall Bohn // February 2009 by Randall Bohn
// - Added support for writing to EEPROM (what took so long?) // - Added support for writing to EEPROM (what took so long?)
// Windows users should consider WinAVR's avrdude instead of the // Windows users should consider WinAVR's avrdude instead of the
@ -40,7 +40,7 @@
// January 2008 by Randall Bohn // January 2008 by Randall Bohn
// - Thanks to Amplificar for helping me with the STK500 protocol // - Thanks to Amplificar for helping me with the STK500 protocol
// - The AVRISP/STK500 (mk I) protocol is used in the arduino bootloader // - The AVRISP/STK500 (mk I) protocol is used in the arduino bootloader
// - The SPI functions herein were developed for the AVR910_ARD programmer // - The SPI functions herein were developed for the AVR910_ARD programmer
// - More information at http://code.google.com/p/mega-isp // - More information at http://code.google.com/p/mega-isp
#include "pins_arduino.h" #include "pins_arduino.h"
@ -75,8 +75,8 @@ void setup() {
pulse(LED_HB, 2); pulse(LED_HB, 2);
} }
int error=0; int error = 0;
int pmode=0; int pmode = 0;
// address for reading and writing, set by 'U' command // address for reading and writing, set by 'U' command
int here; int here;
uint8_t buff[256]; // global block storage uint8_t buff[256]; // global block storage
@ -96,14 +96,14 @@ typedef struct param {
int pagesize; int pagesize;
int eepromsize; int eepromsize;
int flashsize; int flashsize;
} }
parameter; parameter;
parameter param; parameter param;
// this provides a heartbeat on pin 9, so you can tell the software is running. // this provides a heartbeat on pin 9, so you can tell the software is running.
uint8_t hbval=128; uint8_t hbval = 128;
int8_t hbdelta=8; int8_t hbdelta = 8;
void heartbeat() { void heartbeat() {
if (hbval > 192) hbdelta = -hbdelta; if (hbval > 192) hbdelta = -hbdelta;
if (hbval < 32) hbdelta = -hbdelta; if (hbval < 32) hbdelta = -hbdelta;
@ -115,10 +115,10 @@ void heartbeat() {
void loop(void) { void loop(void) {
// is pmode active? // is pmode active?
if (pmode) digitalWrite(LED_PMODE, HIGH); if (pmode) digitalWrite(LED_PMODE, HIGH);
else digitalWrite(LED_PMODE, LOW); else digitalWrite(LED_PMODE, LOW);
// is there an error? // is there an error?
if (error) digitalWrite(LED_ERR, HIGH); if (error) digitalWrite(LED_ERR, HIGH);
else digitalWrite(LED_ERR, LOW); else digitalWrite(LED_ERR, LOW);
// light the heartbeat LED // light the heartbeat LED
@ -129,7 +129,7 @@ void loop(void) {
} }
uint8_t getch() { uint8_t getch() {
while(!Serial.available()); while (!Serial.available());
return Serial.read(); return Serial.read();
} }
void fill(int n) { void fill(int n) {
@ -145,7 +145,7 @@ void pulse(int pin, int times) {
delay(PTIME); delay(PTIME);
digitalWrite(pin, LOW); digitalWrite(pin, LOW);
delay(PTIME); delay(PTIME);
} }
while (times--); while (times--);
} }
@ -157,19 +157,19 @@ void prog_lamp(int state) {
void spi_init() { void spi_init() {
uint8_t x; uint8_t x;
SPCR = 0x53; SPCR = 0x53;
x=SPSR; x = SPSR;
x=SPDR; x = SPDR;
} }
void spi_wait() { void spi_wait() {
do { do {
} }
while (!(SPSR & (1 << SPIF))); while (!(SPSR & (1 << SPIF)));
} }
uint8_t spi_send(uint8_t b) { uint8_t spi_send(uint8_t b) {
uint8_t reply; uint8_t reply;
SPDR=b; SPDR = b;
spi_wait(); spi_wait();
reply = SPDR; reply = SPDR;
return reply; return reply;
@ -177,10 +177,10 @@ uint8_t spi_send(uint8_t b) {
uint8_t spi_transaction(uint8_t a, uint8_t b, uint8_t c, uint8_t d) { uint8_t spi_transaction(uint8_t a, uint8_t b, uint8_t c, uint8_t d) {
uint8_t n; uint8_t n;
spi_send(a); spi_send(a);
n=spi_send(b); n = spi_send(b);
//if (n != a) error = -1; //if (n != a) error = -1;
n=spi_send(c); n = spi_send(c);
return spi_send(d); return spi_send(d);
} }
@ -188,7 +188,7 @@ void empty_reply() {
if (CRC_EOP == getch()) { if (CRC_EOP == getch()) {
Serial.print((char)STK_INSYNC); Serial.print((char)STK_INSYNC);
Serial.print((char)STK_OK); Serial.print((char)STK_OK);
} }
else { else {
error++; error++;
Serial.print((char)STK_NOSYNC); Serial.print((char)STK_NOSYNC);
@ -200,7 +200,7 @@ void breply(uint8_t b) {
Serial.print((char)STK_INSYNC); Serial.print((char)STK_INSYNC);
Serial.print((char)b); Serial.print((char)b);
Serial.print((char)STK_OK); Serial.print((char)STK_OK);
} }
else { else {
error++; error++;
Serial.print((char)STK_NOSYNC); Serial.print((char)STK_NOSYNC);
@ -208,21 +208,21 @@ void breply(uint8_t b) {
} }
void get_version(uint8_t c) { void get_version(uint8_t c) {
switch(c) { switch (c) {
case 0x80: case 0x80:
breply(HWVER); breply(HWVER);
break; break;
case 0x81: case 0x81:
breply(SWMAJ); breply(SWMAJ);
break; break;
case 0x82: case 0x82:
breply(SWMIN); breply(SWMIN);
break; break;
case 0x93: case 0x93:
breply('S'); // serial programmer breply('S'); // serial programmer
break; break;
default: default:
breply(0); breply(0);
} }
} }
@ -236,7 +236,7 @@ void set_parameters() {
param.selftimed = buff[5]; param.selftimed = buff[5];
param.lockbytes = buff[6]; param.lockbytes = buff[6];
param.fusebytes = buff[7]; param.fusebytes = buff[7];
param.flashpoll = buff[8]; param.flashpoll = buff[8];
// ignore buff[9] (= buff[8]) // ignore buff[9] (= buff[8])
// following are 16 bits (big endian) // following are 16 bits (big endian)
param.eeprompoll = beget16(&buff[10]); param.eeprompoll = beget16(&buff[10]);
@ -245,9 +245,9 @@ void set_parameters() {
// 32 bits flashsize (big endian) // 32 bits flashsize (big endian)
param.flashsize = buff[16] * 0x01000000 param.flashsize = buff[16] * 0x01000000
+ buff[17] * 0x00010000 + buff[17] * 0x00010000
+ buff[18] * 0x00000100 + buff[18] * 0x00000100
+ buff[19]; + buff[19];
} }
@ -285,10 +285,10 @@ void universal() {
} }
void flash(uint8_t hilo, int addr, uint8_t data) { void flash(uint8_t hilo, int addr, uint8_t data) {
spi_transaction(0x40+8*hilo, spi_transaction(0x40 + 8 * hilo,
addr>>8 & 0xFF, addr >> 8 & 0xFF,
addr & 0xFF, addr & 0xFF,
data); data);
} }
void commit(int addr) { void commit(int addr) {
if (PROG_FLICKER) prog_lamp(LOW); if (PROG_FLICKER) prog_lamp(LOW);
@ -314,7 +314,7 @@ void write_flash(int length) {
if (CRC_EOP == getch()) { if (CRC_EOP == getch()) {
Serial.print((char) STK_INSYNC); Serial.print((char) STK_INSYNC);
Serial.print((char) write_flash_pages(length)); Serial.print((char) write_flash_pages(length));
} }
else { else {
error++; error++;
Serial.print((char) STK_NOSYNC); Serial.print((char) STK_NOSYNC);
@ -363,11 +363,11 @@ uint8_t write_eeprom_chunk(int start, int length) {
fill(length); fill(length);
prog_lamp(LOW); prog_lamp(LOW);
for (int x = 0; x < length; x++) { for (int x = 0; x < length; x++) {
int addr = start+x; int addr = start + x;
spi_transaction(0xC0, (addr>>8) & 0xFF, addr & 0xFF, buff[x]); spi_transaction(0xC0, (addr >> 8) & 0xFF, addr & 0xFF, buff[x]);
delay(45); delay(45);
} }
prog_lamp(HIGH); prog_lamp(HIGH);
return STK_OK; return STK_OK;
} }
@ -386,7 +386,7 @@ void program_page() {
if (CRC_EOP == getch()) { if (CRC_EOP == getch()) {
Serial.print((char) STK_INSYNC); Serial.print((char) STK_INSYNC);
Serial.print(result); Serial.print(result);
} }
else { else {
error++; error++;
Serial.print((char) STK_NOSYNC); Serial.print((char) STK_NOSYNC);
@ -399,13 +399,13 @@ void program_page() {
uint8_t flash_read(uint8_t hilo, int addr) { uint8_t flash_read(uint8_t hilo, int addr) {
return spi_transaction(0x20 + hilo * 8, return spi_transaction(0x20 + hilo * 8,
(addr >> 8) & 0xFF, (addr >> 8) & 0xFF,
addr & 0xFF, addr & 0xFF,
0); 0);
} }
char flash_read_page(int length) { char flash_read_page(int length) {
for (int x = 0; x < length; x+=2) { for (int x = 0; x < length; x += 2) {
uint8_t low = flash_read(LOW, here); uint8_t low = flash_read(LOW, here);
Serial.print((char) low); Serial.print((char) low);
uint8_t high = flash_read(HIGH, here); uint8_t high = flash_read(HIGH, here);
@ -464,89 +464,89 @@ void read_signature() {
//////////////////////////////////// ////////////////////////////////////
//////////////////////////////////// ////////////////////////////////////
int avrisp() { int avrisp() {
uint8_t data, low, high; uint8_t data, low, high;
uint8_t ch = getch(); uint8_t ch = getch();
switch (ch) { switch (ch) {
case '0': // signon case '0': // signon
error = 0; error = 0;
empty_reply(); empty_reply();
break; break;
case '1': case '1':
if (getch() == CRC_EOP) { if (getch() == CRC_EOP) {
Serial.print((char) STK_INSYNC); Serial.print((char) STK_INSYNC);
Serial.print("AVR ISP"); Serial.print("AVR ISP");
Serial.print((char) STK_OK); Serial.print((char) STK_OK);
} }
break; break;
case 'A': case 'A':
get_version(getch()); get_version(getch());
break; break;
case 'B': case 'B':
fill(20); fill(20);
set_parameters(); set_parameters();
empty_reply(); empty_reply();
break; break;
case 'E': // extended parameters - ignore for now case 'E': // extended parameters - ignore for now
fill(5); fill(5);
empty_reply(); empty_reply();
break; break;
case 'P': case 'P':
start_pmode(); start_pmode();
empty_reply(); empty_reply();
break; break;
case 'U': // set address (word) case 'U': // set address (word)
here = getch(); here = getch();
here += 256 * getch(); here += 256 * getch();
empty_reply(); empty_reply();
break; break;
case 0x60: //STK_PROG_FLASH case 0x60: //STK_PROG_FLASH
low = getch(); low = getch();
high = getch(); high = getch();
empty_reply(); empty_reply();
break; break;
case 0x61: //STK_PROG_DATA case 0x61: //STK_PROG_DATA
data = getch(); data = getch();
empty_reply(); empty_reply();
break; break;
case 0x64: //STK_PROG_PAGE case 0x64: //STK_PROG_PAGE
program_page(); program_page();
break; break;
case 0x74: //STK_READ_PAGE 't' case 0x74: //STK_READ_PAGE 't'
read_page(); read_page();
break; break;
case 'V': //0x56 case 'V': //0x56
universal(); universal();
break; break;
case 'Q': //0x51 case 'Q': //0x51
error=0; error = 0;
end_pmode(); end_pmode();
empty_reply(); empty_reply();
break; break;
case 0x75: //STK_READ_SIGN 'u' case 0x75: //STK_READ_SIGN 'u'
read_signature(); read_signature();
break; break;
// expecting a command, not CRC_EOP // expecting a command, not CRC_EOP
// this is how we can get back in sync // this is how we can get back in sync
case CRC_EOP: case CRC_EOP:
error++; error++;
Serial.print((char) STK_NOSYNC); Serial.print((char) STK_NOSYNC);
break; break;
// anything else we will return STK_UNKNOWN // anything else we will return STK_UNKNOWN
default: default:
error++; error++;
if (CRC_EOP == getch()) if (CRC_EOP == getch())
Serial.print((char)STK_UNKNOWN); Serial.print((char)STK_UNKNOWN);
else else
Serial.print((char)STK_NOSYNC); Serial.print((char)STK_NOSYNC);
} }
} }

View File

@ -2,18 +2,18 @@
Simple Audio Player Simple Audio Player
Demonstrates the use of the Audio library for the Arduino Due Demonstrates the use of the Audio library for the Arduino Due
Hardware required : Hardware required :
* Arduino shield with a SD card on CS4 * Arduino shield with a SD card on CS4
* A sound file named "test.wav" in the root directory of the SD card * A sound file named "test.wav" in the root directory of the SD card
* An audio amplifier to connect to the DAC0 and ground * An audio amplifier to connect to the DAC0 and ground
* A speaker to connect to the audio amplifier * A speaker to connect to the audio amplifier
Original by Massimo Banzi September 20, 2012 Original by Massimo Banzi September 20, 2012
Modified by Scott Fitzgerald October 19, 2012 Modified by Scott Fitzgerald October 19, 2012
This example code is in the public domain This example code is in the public domain
http://arduino.cc/en/Tutorial/SimpleAudioPlayer http://arduino.cc/en/Tutorial/SimpleAudioPlayer
*/ */
@ -44,7 +44,7 @@ void setup()
void loop() void loop()
{ {
int count=0; int count = 0;
// open wave file from sdcard // open wave file from sdcard
File myFile = SD.open("test.wav"); File myFile = SD.open("test.wav");
@ -54,7 +54,7 @@ void loop()
while (true); while (true);
} }
const int S=1024; // Number of samples to read in block const int S = 1024; // Number of samples to read in block
short buffer[S]; short buffer[S];
Serial.print("Playing"); Serial.print("Playing");

View File

@ -1,12 +1,12 @@
/* /*
Arduino Yun Bridge example Arduino Yun Bridge example
This example for the Arduino Yun shows how to use the This example for the Arduino Yun shows how to use the
Bridge library to access the digital and analog pins Bridge library to access the digital and analog pins
on the board through REST calls. It demonstrates how on the board through REST calls. It demonstrates how
you can create your own API when using REST style you can create your own API when using REST style
calls through the browser. calls through the browser.
Possible commands created in this shetch: Possible commands created in this shetch:
* "/arduino/digital/13" -> digitalRead(13) * "/arduino/digital/13" -> digitalRead(13)
@ -15,9 +15,9 @@
* "/arduino/analog/2" -> analogRead(2) * "/arduino/analog/2" -> analogRead(2)
* "/arduino/mode/13/input" -> pinMode(13, INPUT) * "/arduino/mode/13/input" -> pinMode(13, INPUT)
* "/arduino/mode/13/output" -> pinMode(13, OUTPUT) * "/arduino/mode/13/output" -> pinMode(13, OUTPUT)
This example code is part of the public domain This example code is part of the public domain
http://arduino.cc/en/Tutorial/Bridge http://arduino.cc/en/Tutorial/Bridge
*/ */
@ -32,7 +32,7 @@ YunServer server;
void setup() { void setup() {
// Bridge startup // Bridge startup
pinMode(13,OUTPUT); pinMode(13, OUTPUT);
digitalWrite(13, LOW); digitalWrite(13, LOW);
Bridge.begin(); Bridge.begin();
digitalWrite(13, HIGH); digitalWrite(13, HIGH);
@ -90,7 +90,7 @@ void digitalCommand(YunClient client) {
if (client.read() == '/') { if (client.read() == '/') {
value = client.parseInt(); value = client.parseInt();
digitalWrite(pin, value); digitalWrite(pin, value);
} }
else { else {
value = digitalRead(pin); value = digitalRead(pin);
} }

View File

@ -1,95 +1,95 @@
/* /*
ASCII table ASCII table
Prints out byte values in all possible formats: Prints out byte values in all possible formats:
* as raw binary values * as raw binary values
* as ASCII-encoded decimal, hex, octal, and binary values * as ASCII-encoded decimal, hex, octal, and binary values
For more on ASCII, see http://www.asciitable.com and http://en.wikipedia.org/wiki/ASCII For more on ASCII, see http://www.asciitable.com and http://en.wikipedia.org/wiki/ASCII
The circuit: No external hardware needed. The circuit: No external hardware needed.
created 2006 created 2006
by Nicholas Zambetti by Nicholas Zambetti
http://www.zambetti.com http://www.zambetti.com
modified 9 Apr 2012 modified 9 Apr 2012
by Tom Igoe by Tom Igoe
modified 22 May 2013 modified 22 May 2013
by Cristian Maglie by Cristian Maglie
This example code is in the public domain. This example code is in the public domain.
http://arduino.cc/en/Tutorial/ConsoleAsciiTable http://arduino.cc/en/Tutorial/ConsoleAsciiTable
*/ */
#include <Console.h> #include <Console.h>
void setup() { void setup() {
//Initialize Console and wait for port to open: //Initialize Console and wait for port to open:
Bridge.begin(); Bridge.begin();
Console.begin(); Console.begin();
// Uncomment the following line to enable buffering: // Uncomment the following line to enable buffering:
// - better transmission speed and efficiency // - better transmission speed and efficiency
// - needs to call Console.flush() to ensure that all // - needs to call Console.flush() to ensure that all
// transmitted data is sent // transmitted data is sent
//Console.buffer(64); //Console.buffer(64);
while (!Console) { while (!Console) {
; // wait for Console port to connect. ; // wait for Console port to connect.
} }
// prints title with ending line break // prints title with ending line break
Console.println("ASCII Table ~ Character Map"); Console.println("ASCII Table ~ Character Map");
} }
// first visible ASCIIcharacter '!' is number 33: // first visible ASCIIcharacter '!' is number 33:
int thisByte = 33; int thisByte = 33;
// you can also write ASCII characters in single quotes. // you can also write ASCII characters in single quotes.
// for example. '!' is the same as 33, so you could also use this: // for example. '!' is the same as 33, so you could also use this:
//int thisByte = '!'; //int thisByte = '!';
void loop() { void loop() {
// prints value unaltered, i.e. the raw binary version of the // prints value unaltered, i.e. the raw binary version of the
// byte. The Console monitor interprets all bytes as // byte. The Console monitor interprets all bytes as
// ASCII, so 33, the first number, will show up as '!' // ASCII, so 33, the first number, will show up as '!'
Console.write(thisByte); Console.write(thisByte);
Console.print(", dec: "); Console.print(", dec: ");
// prints value as string as an ASCII-encoded decimal (base 10). // prints value as string as an ASCII-encoded decimal (base 10).
// Decimal is the default format for Console.print() and Console.println(), // Decimal is the default format for Console.print() and Console.println(),
// so no modifier is needed: // so no modifier is needed:
Console.print(thisByte); Console.print(thisByte);
// But you can declare the modifier for decimal if you want to. // But you can declare the modifier for decimal if you want to.
//this also works if you uncomment it: //this also works if you uncomment it:
// Console.print(thisByte, DEC); // Console.print(thisByte, DEC);
Console.print(", hex: "); Console.print(", hex: ");
// prints value as string in hexadecimal (base 16): // prints value as string in hexadecimal (base 16):
Console.print(thisByte, HEX); Console.print(thisByte, HEX);
Console.print(", oct: "); Console.print(", oct: ");
// prints value as string in octal (base 8); // prints value as string in octal (base 8);
Console.print(thisByte, OCT); Console.print(thisByte, OCT);
Console.print(", bin: "); Console.print(", bin: ");
// prints value as string in binary (base 2) // prints value as string in binary (base 2)
// also prints ending line break: // also prints ending line break:
Console.println(thisByte, BIN); Console.println(thisByte, BIN);
// if printed last visible character '~' or 126, stop: // if printed last visible character '~' or 126, stop:
if(thisByte == 126) { // you could also use if (thisByte == '~') { if (thisByte == 126) { // you could also use if (thisByte == '~') {
// ensure the latest bit of data is sent // ensure the latest bit of data is sent
Console.flush(); Console.flush();
// This loop loops forever and does nothing // This loop loops forever and does nothing
while(true) { while (true) {
continue; continue;
} }
} }
// go on to the next character // go on to the next character
thisByte++; thisByte++;
} }

View File

@ -1,30 +1,30 @@
/* /*
Console Pixel Console Pixel
An example of using the Arduino board to receive data from the An example of using the Arduino board to receive data from the
Console on the Arduino Yun. In this case, the Arduino boards turns on an LED when Console on the Arduino Yun. In this case, the Arduino boards turns on an LED when
it receives the character 'H', and turns off the LED when it it receives the character 'H', and turns off the LED when it
receives the character 'L'. receives the character 'L'.
To see the Console, pick your Yún's name and IP address in the Port menu To see the Console, pick your Yún's name and IP address in the Port menu
then open the Port Monitor. You can also see it by opening a terminal window then open the Port Monitor. You can also see it by opening a terminal window
and typing and typing
ssh root@ yourYunsName.local 'telnet localhost 6571' ssh root@ yourYunsName.local 'telnet localhost 6571'
then pressing enter. When prompted for the password, enter it. then pressing enter. When prompted for the password, enter it.
The circuit: The circuit:
* LED connected from digital pin 13 to ground * LED connected from digital pin 13 to ground
created 2006 created 2006
by David A. Mellis by David A. Mellis
modified 25 Jun 2013 modified 25 Jun 2013
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://arduino.cc/en/Tutorial/ConsolePixel http://arduino.cc/en/Tutorial/ConsolePixel
*/ */
#include <Console.h> #include <Console.h>
@ -37,7 +37,7 @@ void setup() {
Console.begin(); // Initialize Console Console.begin(); // Initialize Console
// Wait for the Console port to connect // Wait for the Console port to connect
while(!Console); while (!Console);
Console.println("type H or L to turn pin 13 on or off"); Console.println("type H or L to turn pin 13 on or off");
@ -54,7 +54,7 @@ void loop() {
// if it's a capital H (ASCII 72), turn on the LED: // if it's a capital H (ASCII 72), turn on the LED:
if (incomingByte == 'H') { if (incomingByte == 'H') {
digitalWrite(ledPin, HIGH); digitalWrite(ledPin, HIGH);
} }
// if it's an L (ASCII 76) turn off the LED: // if it's an L (ASCII 76) turn off the LED:
if (incomingByte == 'L') { if (incomingByte == 'L') {
digitalWrite(ledPin, LOW); digitalWrite(ledPin, LOW);

View File

@ -3,22 +3,22 @@
Read data coming from bridge using the Console.read() function Read data coming from bridge using the Console.read() function
and store it in a string. and store it in a string.
To see the Console, pick your Yún's name and IP address in the Port menu To see the Console, pick your Yún's name and IP address in the Port menu
then open the Port Monitor. You can also see it by opening a terminal window then open the Port Monitor. You can also see it by opening a terminal window
and typing: and typing:
ssh root@ yourYunsName.local 'telnet localhost 6571' ssh root@ yourYunsName.local 'telnet localhost 6571'
then pressing enter. When prompted for the password, enter it. then pressing enter. When prompted for the password, enter it.
created 13 Jun 2013 created 13 Jun 2013
by Angelo Scialabba by Angelo Scialabba
modified 16 June 2013 modified 16 June 2013
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://arduino.cc/en/Tutorial/ConsoleRead http://arduino.cc/en/Tutorial/ConsoleRead
*/ */
#include <Console.h> #include <Console.h>
@ -28,13 +28,13 @@ String name;
void setup() { void setup() {
// Initialize Console and wait for port to open: // Initialize Console and wait for port to open:
Bridge.begin(); Bridge.begin();
Console.begin(); Console.begin();
// Wait for Console port to connect // Wait for Console port to connect
while (!Console); while (!Console);
Console.println("Hi, what's your name?"); Console.println("Hi, what's your name?");
} }
void loop() { void loop() {
if (Console.available() > 0) { if (Console.available() > 0) {
@ -49,7 +49,7 @@ void loop() {
// Ask again for name and clear the old name // Ask again for name and clear the old name
Console.println("Hi, what's your name?"); Console.println("Hi, what's your name?");
name = ""; // clear the name string name = ""; // clear the name string
} }
else { // if the buffer is empty Cosole.read() returns -1 else { // if the buffer is empty Cosole.read() returns -1
name += c; // append the read char from Console to the name string name += c; // append the read char from Console to the name string
} }

View File

@ -1,21 +1,21 @@
/* /*
SD card datalogger SD card datalogger
This example shows how to log data from three analog sensors This example shows how to log data from three analog sensors
to an SD card mounted on the Arduino Yún using the Bridge library. to an SD card mounted on the Arduino Yún using the Bridge library.
The circuit: The circuit:
* analog sensors on analog pins 0, 1 and 2 * analog sensors on analog pins 0, 1 and 2
* SD card attached to SD card slot of the Arduino Yún * SD card attached to SD card slot of the Arduino Yún
Prepare your SD card creating an empty folder in the SD root Prepare your SD card creating an empty folder in the SD root
named "arduino". This will ensure that the Yún will create a link named "arduino". This will ensure that the Yún will create a link
to the SD to the "/mnt/sd" path. to the SD to the "/mnt/sd" path.
You can remove the SD card while the Linux and the You can remove the SD card while the Linux and the
sketch are running but be careful not to remove it while sketch are running but be careful not to remove it while
the system is writing to it. the system is writing to it.
created 24 Nov 2010 created 24 Nov 2010
modified 9 Apr 2012 modified 9 Apr 2012
by Tom Igoe by Tom Igoe
@ -23,11 +23,11 @@
by Federico Vanzati by Federico Vanzati
modified 21 Jun 2013 modified 21 Jun 2013
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://arduino.cc/en/Tutorial/YunDatalogger http://arduino.cc/en/Tutorial/YunDatalogger
*/ */
#include <FileIO.h> #include <FileIO.h>
@ -38,7 +38,7 @@ void setup() {
Serial.begin(9600); Serial.begin(9600);
FileSystem.begin(); FileSystem.begin();
while(!Serial); // wait for Serial port to connect. while (!Serial); // wait for Serial port to connect.
Serial.println("Filesystem datalogger\n"); Serial.println("Filesystem datalogger\n");
} }
@ -69,12 +69,12 @@ void loop () {
dataFile.close(); dataFile.close();
// print to the serial port too: // print to the serial port too:
Serial.println(dataString); Serial.println(dataString);
} }
// if the file isn't open, pop up an error: // if the file isn't open, pop up an error:
else { else {
Serial.println("error opening datalog.txt"); Serial.println("error opening datalog.txt");
} }
delay(15000); delay(15000);
} }
@ -83,19 +83,19 @@ void loop () {
String getTimeStamp() { String getTimeStamp() {
String result; String result;
Process time; Process time;
// date is a command line utility to get the date and the time // date is a command line utility to get the date and the time
// in different formats depending on the additional parameter // in different formats depending on the additional parameter
time.begin("date"); time.begin("date");
time.addParameter("+%D-%T"); // parameters: D for the complete date mm/dd/yy time.addParameter("+%D-%T"); // parameters: D for the complete date mm/dd/yy
// T for the time hh:mm:ss // T for the time hh:mm:ss
time.run(); // run the command time.run(); // run the command
// read the output of the command // read the output of the command
while(time.available()>0) { while (time.available() > 0) {
char c = time.read(); char c = time.read();
if(c != '\n') if (c != '\n')
result += c; result += c;
} }
return result; return result;
} }

View File

@ -1,18 +1,18 @@
/* /*
Write to file using FileIO classes. Write to file using FileIO classes.
This sketch demonstrate how to write file into the Yún filesystem. This sketch demonstrate how to write file into the Yún filesystem.
A shell script file is created in /tmp, and it is executed afterwards. A shell script file is created in /tmp, and it is executed afterwards.
created 7 June 2010 created 7 June 2010
by Cristian Maglie by Cristian Maglie
This example code is in the public domain. This example code is in the public domain.
http://arduino.cc/en/Tutorial/FileWriteScript http://arduino.cc/en/Tutorial/FileWriteScript
*/ */
#include <FileIO.h> #include <FileIO.h>
void setup() { void setup() {
@ -20,16 +20,16 @@ void setup() {
Bridge.begin(); Bridge.begin();
// Initialize the Serial // Initialize the Serial
Serial.begin(9600); Serial.begin(9600);
while(!Serial); // wait for Serial port to connect. while (!Serial); // wait for Serial port to connect.
Serial.println("File Write Script example\n\n"); Serial.println("File Write Script example\n\n");
// Setup File IO // Setup File IO
FileSystem.begin(); FileSystem.begin();
// Upload script used to gain network statistics // Upload script used to gain network statistics
uploadScript(); uploadScript();
} }
void loop() { void loop() {
// Run stats script every 5 secs. // Run stats script every 5 secs.
@ -41,10 +41,10 @@ void loop() {
// to check the network traffic of the WiFi interface // to check the network traffic of the WiFi interface
void uploadScript() { void uploadScript() {
// Write our shell script in /tmp // Write our shell script in /tmp
// Using /tmp stores the script in RAM this way we can preserve // Using /tmp stores the script in RAM this way we can preserve
// the limited amount of FLASH erase/write cycles // the limited amount of FLASH erase/write cycles
File script = FileSystem.open("/tmp/wlan-stats.sh", FILE_WRITE); File script = FileSystem.open("/tmp/wlan-stats.sh", FILE_WRITE);
// Shell script header // Shell script header
script.print("#!/bin/sh\n"); script.print("#!/bin/sh\n");
// shell commands: // shell commands:
// ifconfig: is a command line utility for controlling the network interfaces. // ifconfig: is a command line utility for controlling the network interfaces.
@ -53,7 +53,7 @@ void uploadScript() {
// and extract the line that contains it // and extract the line that contains it
script.print("ifconfig wlan0 | grep 'RX bytes'\n"); script.print("ifconfig wlan0 | grep 'RX bytes'\n");
script.close(); // close the file script.close(); // close the file
// Make the script executable // Make the script executable
Process chmod; Process chmod;
chmod.begin("chmod"); // chmod: change mode chmod.begin("chmod"); // chmod: change mode
@ -69,9 +69,9 @@ void runScript() {
Process myscript; Process myscript;
myscript.begin("/tmp/wlan-stats.sh"); myscript.begin("/tmp/wlan-stats.sh");
myscript.run(); myscript.run();
String output = ""; String output = "";
// read the output of the script // read the output of the script
while (myscript.available()) { while (myscript.available()) {
output += (char)myscript.read(); output += (char)myscript.read();

View File

@ -1,9 +1,9 @@
/* /*
Yun HTTP Client Yun HTTP Client
This example for the Arduino Yún shows how create a basic This example for the Arduino Yún shows how create a basic
HTTP client that connects to the internet and downloads HTTP client that connects to the internet and downloads
content. In this case, you'll connect to the Arduino content. In this case, you'll connect to the Arduino
website and download a version of the logo as ASCII text. website and download a version of the logo as ASCII text.
created by Tom igoe created by Tom igoe
@ -21,32 +21,32 @@
void setup() { void setup() {
// Bridge takes about two seconds to start up // Bridge takes about two seconds to start up
// it can be helpful to use the on-board LED // it can be helpful to use the on-board LED
// as an indicator for when it has initialized // as an indicator for when it has initialized
pinMode(13, OUTPUT); pinMode(13, OUTPUT);
digitalWrite(13, LOW); digitalWrite(13, LOW);
Bridge.begin(); Bridge.begin();
digitalWrite(13, HIGH); digitalWrite(13, HIGH);
Serial.begin(9600); Serial.begin(9600);
while(!Serial); // wait for a serial connection while (!Serial); // wait for a serial connection
} }
void loop() { void loop() {
// Initialize the client library // Initialize the client library
HttpClient client; HttpClient client;
// Make a HTTP request: // Make a HTTP request:
client.get("http://arduino.cc/asciilogo.txt"); client.get("http://arduino.cc/asciilogo.txt");
// if there are incoming bytes available // if there are incoming bytes available
// from the server, read them and print them: // from the server, read them and print them:
while (client.available()) { while (client.available()) {
char c = client.read(); char c = client.read();
Serial.print(c); Serial.print(c);
} }
Serial.flush(); Serial.flush();
delay(5000); delay(5000);
} }

View File

@ -1,14 +1,14 @@
/* /*
Running process using Process class. Running process using Process class.
This sketch demonstrate how to run linux processes This sketch demonstrate how to run linux processes
using an Arduino Yún. using an Arduino Yún.
created 5 Jun 2013 created 5 Jun 2013
by Cristian Maglie by Cristian Maglie
This example code is in the public domain. This example code is in the public domain.
http://arduino.cc/en/Tutorial/Process http://arduino.cc/en/Tutorial/Process
*/ */
@ -18,10 +18,10 @@
void setup() { void setup() {
// Initialize Bridge // Initialize Bridge
Bridge.begin(); Bridge.begin();
// Initialize Serial // Initialize Serial
Serial.begin(9600); Serial.begin(9600);
// Wait until a Serial Monitor is connected. // Wait until a Serial Monitor is connected.
while (!Serial); while (!Serial);
@ -44,7 +44,7 @@ void runCurl() {
// Print arduino logo over the Serial // Print arduino logo over the Serial
// A process output can be read with the stream methods // A process output can be read with the stream methods
while (p.available()>0) { while (p.available() > 0) {
char c = p.read(); char c = p.read();
Serial.print(c); Serial.print(c);
} }
@ -62,7 +62,7 @@ void runCpuInfo() {
// Print command output on the Serial. // Print command output on the Serial.
// A process output can be read with the stream methods // A process output can be read with the stream methods
while (p.available()>0) { while (p.available() > 0) {
char c = p.read(); char c = p.read();
Serial.print(c); Serial.print(c);
} }

View File

@ -1,24 +1,24 @@
/* /*
Running shell commands using Process class. Running shell commands using Process class.
This sketch demonstrate how to run linux shell commands This sketch demonstrate how to run linux shell commands
using an Arduino Yún. It runs the wifiCheck script on the linino side using an Arduino Yún. It runs the wifiCheck script on the linino side
of the Yun, then uses grep to get just the signal strength line. of the Yun, then uses grep to get just the signal strength line.
Then it uses parseInt() to read the wifi signal strength as an integer, Then it uses parseInt() to read the wifi signal strength as an integer,
and finally uses that number to fade an LED using analogWrite(). and finally uses that number to fade an LED using analogWrite().
The circuit: The circuit:
* Arduino Yun with LED connected to pin 9 * Arduino Yun with LED connected to pin 9
created 12 Jun 2013 created 12 Jun 2013
by Cristian Maglie by Cristian Maglie
modified 25 June 2013 modified 25 June 2013
by Tom Igoe by Tom Igoe
This example code is in the public domain. This example code is in the public domain.
http://arduino.cc/en/Tutorial/ShellCommands http://arduino.cc/en/Tutorial/ShellCommands
*/ */
#include <Process.h> #include <Process.h>
@ -28,18 +28,18 @@ void setup() {
Serial.begin(9600); // Initialize the Serial Serial.begin(9600); // Initialize the Serial
// Wait until a Serial Monitor is connected. // Wait until a Serial Monitor is connected.
while(!Serial); while (!Serial);
} }
void loop() { void loop() {
Process p; Process p;
// This command line runs the WifiStatus script, (/usr/bin/pretty-wifi-info.lua), then // This command line runs the WifiStatus script, (/usr/bin/pretty-wifi-info.lua), then
// sends the result to the grep command to look for a line containing the word // sends the result to the grep command to look for a line containing the word
// "Signal:" the result is passed to this sketch: // "Signal:" the result is passed to this sketch:
p.runShellCommand("/usr/bin/pretty-wifi-info.lua | grep Signal"); p.runShellCommand("/usr/bin/pretty-wifi-info.lua | grep Signal");
// do nothing until the process finishes, so you get the whole output: // do nothing until the process finishes, so you get the whole output:
while(p.running()); while (p.running());
// Read command output. runShellCommand() should have passed "Signal: xx&": // Read command output. runShellCommand() should have passed "Signal: xx&":
while (p.available()) { while (p.available()) {
@ -47,7 +47,7 @@ void loop() {
int signal = map(result, 0, 100, 0, 255); // map result from 0-100 range to 0-255 int signal = map(result, 0, 100, 0, 255); // map result from 0-100 range to 0-255
analogWrite(9, signal); // set the brightness of LED on pin 9 analogWrite(9, signal); // set the brightness of LED on pin 9
Serial.println(result); // print the number as well Serial.println(result); // print the number as well
} }
delay(5000); // wait 5 seconds before you do it again delay(5000); // wait 5 seconds before you do it again
} }

View File

@ -2,23 +2,23 @@
Input Output Input Output
Demonstrates how to create a sketch that sends and receives all standard Demonstrates how to create a sketch that sends and receives all standard
spacebrew data types, and a custom data type. Every time data is spacebrew data types, and a custom data type. Every time data is
received it is output to the Serial monitor. received it is output to the Serial monitor.
Make sure that your Yun is connected to the internet for this example Make sure that your Yun is connected to the internet for this example
to function properly. to function properly.
The circuit: The circuit:
- No circuit required - No circuit required
created 2013 created 2013
by Julio Terra by Julio Terra
This example code is in the public domain. This example code is in the public domain.
More information about Spacebrew is available at: More information about Spacebrew is available at:
http://spacebrew.cc/ http://spacebrew.cc/
*/ */
#include <Bridge.h> #include <Bridge.h>
@ -33,98 +33,100 @@ int interval = 2000;
int counter = 0; int counter = 0;
void setup() { void setup() {
// start the serial port // start the serial port
Serial.begin(57600); Serial.begin(57600);
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
delay(4000); delay(4000);
while (!Serial) { ; } while (!Serial) {
;
}
// start-up the bridge // start-up the bridge
Bridge.begin(); Bridge.begin();
// configure the spacebrew object to print status messages to serial // configure the spacebrew object to print status messages to serial
sb.verbose(true); sb.verbose(true);
// configure the spacebrew publisher and subscriber // configure the spacebrew publisher and subscriber
sb.addPublish("string test", "string"); sb.addPublish("string test", "string");
sb.addPublish("range test", "range"); sb.addPublish("range test", "range");
sb.addPublish("boolean test", "boolean"); sb.addPublish("boolean test", "boolean");
sb.addPublish("custom test", "crazy"); sb.addPublish("custom test", "crazy");
sb.addSubscribe("string test", "string"); sb.addSubscribe("string test", "string");
sb.addSubscribe("range test", "range"); sb.addSubscribe("range test", "range");
sb.addSubscribe("boolean test", "boolean"); sb.addSubscribe("boolean test", "boolean");
sb.addSubscribe("custom test", "crazy"); sb.addSubscribe("custom test", "crazy");
// register the string message handler method // register the string message handler method
sb.onRangeMessage(handleRange); sb.onRangeMessage(handleRange);
sb.onStringMessage(handleString); sb.onStringMessage(handleString);
sb.onBooleanMessage(handleBoolean); sb.onBooleanMessage(handleBoolean);
sb.onCustomMessage(handleCustom); sb.onCustomMessage(handleCustom);
// connect to cloud spacebrew server at "sandbox.spacebrew.cc" // connect to cloud spacebrew server at "sandbox.spacebrew.cc"
sb.connect("sandbox.spacebrew.cc"); sb.connect("sandbox.spacebrew.cc");
} }
void loop() { void loop() {
// monitor spacebrew connection for new data // monitor spacebrew connection for new data
sb.monitor(); sb.monitor();
// connected to spacebrew then send a string every 2 seconds // connected to spacebrew then send a string every 2 seconds
if ( sb.connected() ) { if ( sb.connected() ) {
// check if it is time to send a new message // check if it is time to send a new message
if ( (millis() - last) > interval ) { if ( (millis() - last) > interval ) {
String test_str_msg = "testing, testing, "; String test_str_msg = "testing, testing, ";
test_str_msg += counter; test_str_msg += counter;
counter ++; counter ++;
sb.send("string test", test_str_msg); sb.send("string test", test_str_msg);
sb.send("range test", 500); sb.send("range test", 500);
sb.send("boolean test", true); sb.send("boolean test", true);
sb.send("custom test", "youre loco"); sb.send("custom test", "youre loco");
last = millis(); last = millis();
} }
} }
} }
// define handler methods, all standard data type handlers take two appropriate arguments // define handler methods, all standard data type handlers take two appropriate arguments
void handleRange (String route, int value) { void handleRange (String route, int value) {
Serial.print("Range msg "); Serial.print("Range msg ");
Serial.print(route); Serial.print(route);
Serial.print(", value "); Serial.print(", value ");
Serial.println(value); Serial.println(value);
} }
void handleString (String route, String value) { void handleString (String route, String value) {
Serial.print("String msg "); Serial.print("String msg ");
Serial.print(route); Serial.print(route);
Serial.print(", value "); Serial.print(", value ");
Serial.println(value); Serial.println(value);
} }
void handleBoolean (String route, boolean value) { void handleBoolean (String route, boolean value) {
Serial.print("Boolen msg "); Serial.print("Boolen msg ");
Serial.print(route); Serial.print(route);
Serial.print(", value "); Serial.print(", value ");
Serial.println(value ? "true" : "false"); Serial.println(value ? "true" : "false");
} }
// custom data type handlers takes three String arguments // custom data type handlers takes three String arguments
void handleCustom (String route, String value, String type) { void handleCustom (String route, String value, String type) {
Serial.print("Custom msg "); Serial.print("Custom msg ");
Serial.print(route); Serial.print(route);
Serial.print(" of type "); Serial.print(" of type ");
Serial.print(type); Serial.print(type);
Serial.print(", value "); Serial.print(", value ");
Serial.println(value); Serial.println(value);
} }

View File

@ -1,26 +1,26 @@
/* /*
Spacebrew Boolean Spacebrew Boolean
Demonstrates how to create a sketch that sends and receives a Demonstrates how to create a sketch that sends and receives a
boolean value to and from Spacebrew. Every time the buttton is boolean value to and from Spacebrew. Every time the buttton is
pressed (or other digital input component) a spacebrew message pressed (or other digital input component) a spacebrew message
is sent. The sketch also accepts analog range messages from is sent. The sketch also accepts analog range messages from
other Spacebrew apps. other Spacebrew apps.
Make sure that your Yun is connected to the internet for this example Make sure that your Yun is connected to the internet for this example
to function properly. to function properly.
The circuit: The circuit:
- Button connected to Yun, using the Arduino's internal pullup resistor. - Button connected to Yun, using the Arduino's internal pullup resistor.
created 2013 created 2013
by Julio Terra by Julio Terra
This example code is in the public domain. This example code is in the public domain.
More information about Spacebrew is available at: More information about Spacebrew is available at:
http://spacebrew.cc/ http://spacebrew.cc/
*/ */
#include <Bridge.h> #include <Bridge.h>
@ -33,57 +33,59 @@ SpacebrewYun sb = SpacebrewYun("spacebrewYun Boolean", "Boolean sender and recei
int last_value = 0; int last_value = 0;
// create variables to manage interval between each time we send a string // create variables to manage interval between each time we send a string
void setup() { void setup() {
// start the serial port // start the serial port
Serial.begin(57600); Serial.begin(57600);
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
delay(4000); delay(4000);
while (!Serial) { ; } while (!Serial) {
;
}
// start-up the bridge // start-up the bridge
Bridge.begin(); Bridge.begin();
// configure the spacebrew object to print status messages to serial // configure the spacebrew object to print status messages to serial
sb.verbose(true); sb.verbose(true);
// configure the spacebrew publisher and subscriber // configure the spacebrew publisher and subscriber
sb.addPublish("physical button", "boolean"); sb.addPublish("physical button", "boolean");
sb.addSubscribe("virtual button", "boolean"); sb.addSubscribe("virtual button", "boolean");
// register the string message handler method // register the string message handler method
sb.onBooleanMessage(handleBoolean); sb.onBooleanMessage(handleBoolean);
// connect to cloud spacebrew server at "sandbox.spacebrew.cc" // connect to cloud spacebrew server at "sandbox.spacebrew.cc"
sb.connect("sandbox.spacebrew.cc"); sb.connect("sandbox.spacebrew.cc");
pinMode(3, INPUT); pinMode(3, INPUT);
digitalWrite(3, HIGH); digitalWrite(3, HIGH);
} }
void loop() { void loop() {
// monitor spacebrew connection for new data // monitor spacebrew connection for new data
sb.monitor(); sb.monitor();
// connected to spacebrew then send a new value whenever the pot value changes // connected to spacebrew then send a new value whenever the pot value changes
if ( sb.connected() ) { if ( sb.connected() ) {
int cur_value = digitalRead(3); int cur_value = digitalRead(3);
if ( last_value != cur_value ) { if ( last_value != cur_value ) {
if (cur_value == HIGH) sb.send("physical button", false); if (cur_value == HIGH) sb.send("physical button", false);
else sb.send("physical button", true); else sb.send("physical button", true);
last_value = cur_value; last_value = cur_value;
} }
} }
} }
// handler method that is called whenever a new string message is received // handler method that is called whenever a new string message is received
void handleBoolean (String route, boolean value) { void handleBoolean (String route, boolean value) {
// print the message that was received // print the message that was received
Serial.print("From "); Serial.print("From ");
Serial.print(route); Serial.print(route);
Serial.print(", received msg: "); Serial.print(", received msg: ");
Serial.println(value ? "true" : "false"); Serial.println(value ? "true" : "false");
} }

View File

@ -1,27 +1,27 @@
/* /*
Spacebrew Range Spacebrew Range
Demonstrates how to create a sketch that sends and receives analog Demonstrates how to create a sketch that sends and receives analog
range value to and from Spacebrew. Every time the state of the range value to and from Spacebrew. Every time the state of the
potentiometer (or other analog input component) change a spacebrew potentiometer (or other analog input component) change a spacebrew
message is sent. The sketch also accepts analog range messages from message is sent. The sketch also accepts analog range messages from
other Spacebrew apps. other Spacebrew apps.
Make sure that your Yun is connected to the internet for this example Make sure that your Yun is connected to the internet for this example
to function properly. to function properly.
The circuit: The circuit:
- Potentiometer connected to Yun. Middle pin connected to analog pin A0, - Potentiometer connected to Yun. Middle pin connected to analog pin A0,
other pins connected to 5v and GND pins. other pins connected to 5v and GND pins.
created 2013 created 2013
by Julio Terra by Julio Terra
This example code is in the public domain. This example code is in the public domain.
More information about Spacebrew is available at: More information about Spacebrew is available at:
http://spacebrew.cc/ http://spacebrew.cc/
*/ */
#include <Bridge.h> #include <Bridge.h>
@ -34,53 +34,55 @@ SpacebrewYun sb = SpacebrewYun("spacebrewYun Range", "Range sender and receiver"
int last_value = 0; int last_value = 0;
// create variables to manage interval between each time we send a string // create variables to manage interval between each time we send a string
void setup() { void setup() {
// start the serial port // start the serial port
Serial.begin(57600); Serial.begin(57600);
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
delay(4000); delay(4000);
while (!Serial) { ; } while (!Serial) {
;
}
// start-up the bridge // start-up the bridge
Bridge.begin(); Bridge.begin();
// configure the spacebrew object to print status messages to serial // configure the spacebrew object to print status messages to serial
sb.verbose(true); sb.verbose(true);
// configure the spacebrew publisher and subscriber // configure the spacebrew publisher and subscriber
sb.addPublish("physical pot", "range"); sb.addPublish("physical pot", "range");
sb.addSubscribe("virtual pot", "range"); sb.addSubscribe("virtual pot", "range");
// register the string message handler method // register the string message handler method
sb.onRangeMessage(handleRange); sb.onRangeMessage(handleRange);
// connect to cloud spacebrew server at "sandbox.spacebrew.cc" // connect to cloud spacebrew server at "sandbox.spacebrew.cc"
sb.connect("sandbox.spacebrew.cc"); sb.connect("sandbox.spacebrew.cc");
} }
void loop() { void loop() {
// monitor spacebrew connection for new data // monitor spacebrew connection for new data
sb.monitor(); sb.monitor();
// connected to spacebrew then send a new value whenever the pot value changes // connected to spacebrew then send a new value whenever the pot value changes
if ( sb.connected() ) { if ( sb.connected() ) {
int cur_value = analogRead(A0); int cur_value = analogRead(A0);
if ( last_value != cur_value ) { if ( last_value != cur_value ) {
sb.send("physical pot", cur_value); sb.send("physical pot", cur_value);
last_value = cur_value; last_value = cur_value;
} }
} }
} }
// handler method that is called whenever a new string message is received // handler method that is called whenever a new string message is received
void handleRange (String route, int value) { void handleRange (String route, int value) {
// print the message that was received // print the message that was received
Serial.print("From "); Serial.print("From ");
Serial.print(route); Serial.print(route);
Serial.print(", received msg: "); Serial.print(", received msg: ");
Serial.println(value); Serial.println(value);
} }

View File

@ -1,24 +1,24 @@
/* /*
Spacebrew String Spacebrew String
Demonstrates how to create a sketch that sends and receives strings Demonstrates how to create a sketch that sends and receives strings
to and from Spacebrew. Every time string data is received it to and from Spacebrew. Every time string data is received it
is output to the Serial monitor. is output to the Serial monitor.
Make sure that your Yun is connected to the internet for this example Make sure that your Yun is connected to the internet for this example
to function properly. to function properly.
The circuit: The circuit:
- No circuit required - No circuit required
created 2013 created 2013
by Julio Terra by Julio Terra
This example code is in the public domain. This example code is in the public domain.
More information about Spacebrew is available at: More information about Spacebrew is available at:
http://spacebrew.cc/ http://spacebrew.cc/
*/ */
#include <Bridge.h> #include <Bridge.h>
@ -31,54 +31,56 @@ SpacebrewYun sb = SpacebrewYun("spacebrewYun Strings", "String sender and receiv
long last_time = 0; long last_time = 0;
int interval = 2000; int interval = 2000;
void setup() { void setup() {
// start the serial port // start the serial port
Serial.begin(57600); Serial.begin(57600);
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
delay(4000); delay(4000);
while (!Serial) { ; } while (!Serial) {
;
}
// start-up the bridge // start-up the bridge
Bridge.begin(); Bridge.begin();
// configure the spacebrew object to print status messages to serial // configure the spacebrew object to print status messages to serial
sb.verbose(true); sb.verbose(true);
// configure the spacebrew publisher and subscriber // configure the spacebrew publisher and subscriber
sb.addPublish("speak", "string"); sb.addPublish("speak", "string");
sb.addSubscribe("listen", "string"); sb.addSubscribe("listen", "string");
// register the string message handler method // register the string message handler method
sb.onStringMessage(handleString); sb.onStringMessage(handleString);
// connect to cloud spacebrew server at "sandbox.spacebrew.cc" // connect to cloud spacebrew server at "sandbox.spacebrew.cc"
sb.connect("sandbox.spacebrew.cc"); sb.connect("sandbox.spacebrew.cc");
} }
void loop() { void loop() {
// monitor spacebrew connection for new data // monitor spacebrew connection for new data
sb.monitor(); sb.monitor();
// connected to spacebrew then send a string every 2 seconds // connected to spacebrew then send a string every 2 seconds
if ( sb.connected() ) { if ( sb.connected() ) {
// check if it is time to send a new message // check if it is time to send a new message
if ( (millis() - last_time) > interval ) { if ( (millis() - last_time) > interval ) {
sb.send("speak", "is anybody out there?"); sb.send("speak", "is anybody out there?");
last_time = millis(); last_time = millis();
} }
} }
} }
// handler method that is called whenever a new string message is received // handler method that is called whenever a new string message is received
void handleString (String route, String value) { void handleString (String route, String value) {
// print the message that was received // print the message that was received
Serial.print("From "); Serial.print("From ");
Serial.print(route); Serial.print(route);
Serial.print(", received msg: "); Serial.print(", received msg: ");
Serial.println(value); Serial.println(value);
} }

View File

@ -8,26 +8,26 @@
Check out the latest Arduino & Temboo examples and support docs at http://www.temboo.com/arduino Check out the latest Arduino & Temboo examples and support docs at http://www.temboo.com/arduino
A Temboo account and application key are necessary to run all Temboo examples. A Temboo account and application key are necessary to run all Temboo examples.
If you don't already have one, you can register for a free Temboo account at If you don't already have one, you can register for a free Temboo account at
http://www.temboo.com http://www.temboo.com
Since this sketch uses Twilio to retrieve the SMS, you'll also need a valid Since this sketch uses Twilio to retrieve the SMS, you'll also need a valid
Twilio account. You can create one for free at https://www.twilio.com. Twilio account. You can create one for free at https://www.twilio.com.
The sketch needs your Twilio Account SID and Auth Token you get when you The sketch needs your Twilio Account SID and Auth Token you get when you
register with Twilio. Make sure to use the Account SID and Auth Token from register with Twilio. Make sure to use the Account SID and Auth Token from
your Twilio Dashboard (not your test credentials from the Dev Tools panel). your Twilio Dashboard (not your test credentials from the Dev Tools panel).
Normally, Twilio expects to contact a web site you provide to get a response Normally, Twilio expects to contact a web site you provide to get a response
when an SMS message is received for your Twilio number. In this case, we when an SMS message is received for your Twilio number. In this case, we
don't want to send any response (and we don't want to have to set up a web don't want to send any response (and we don't want to have to set up a web
site just to receive SMS messages.) You can use a URL that Twilio provides site just to receive SMS messages.) You can use a URL that Twilio provides
for this purpose. When a message is received and sent to the Twilio "twimlets" for this purpose. When a message is received and sent to the Twilio "twimlets"
URL, it returns a code meaning "no response required." To set this up: URL, it returns a code meaning "no response required." To set this up:
1. Log in to your Twilio account and go to this URL: 1. Log in to your Twilio account and go to this URL:
https://www.twilio.com/user/account/phone-numbers/incoming https://www.twilio.com/user/account/phone-numbers/incoming
2. Select the Twilio number you want to receive SMS messages at. 2. Select the Twilio number you want to receive SMS messages at.
@ -40,7 +40,7 @@
https://www.twilio.com/help/faq/sms/how-can-i-receive-sms-messages-without-responding https://www.twilio.com/help/faq/sms/how-can-i-receive-sms-messages-without-responding
4. Click the "Save Changes" button at the bottom of the page. 4. Click the "Save Changes" button at the bottom of the page.
Your account will now receive SMS messages, but won't send any responses. Your account will now receive SMS messages, but won't send any responses.
@ -48,14 +48,14 @@
to the Internet. to the Internet.
Looking for another API? We've got over 100 in our Library! Looking for another API? We've got over 100 in our Library!
This example code is in the public domain. This example code is in the public domain.
*/ */
#include <Bridge.h> #include <Bridge.h>
#include <Temboo.h> #include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information #include "TembooAccount.h" // contains Temboo account information
// as described in the footer comment below // as described in the footer comment below
@ -85,7 +85,7 @@ unsigned long lastSMSCheckTime = -SMS_CHECK_PERIOD;
// (we only need to process newer messages) // (we only need to process newer messages)
String lastSid; String lastSid;
// we'll be turning the LED built in to the Yun on and off // we'll be turning the LED built in to the Yun on and off
// to simulate controlling some device. That LED is on pin 13. // to simulate controlling some device. That LED is on pin 13.
int LED_PIN = 13; int LED_PIN = 13;
@ -98,7 +98,7 @@ void setup() {
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
delay(4000); delay(4000);
while(!Serial); while (!Serial);
// tell the board to treat the LED pin as an output. // tell the board to treat the LED pin as an output.
pinMode(LED_PIN, OUTPUT); pinMode(LED_PIN, OUTPUT);
@ -109,7 +109,7 @@ void setup() {
// initialize the connection to the Linino processor. // initialize the connection to the Linino processor.
Bridge.begin(); Bridge.begin();
// Twilio will report old SMS messages. We want to // Twilio will report old SMS messages. We want to
// ignore any existing control messages when we start. // ignore any existing control messages when we start.
Serial.println("Ignoring any existing control messages..."); Serial.println("Ignoring any existing control messages...");
checkForMessages(true); checkForMessages(true);
@ -124,15 +124,15 @@ void loop()
// see if it's time to check for new SMS messages. // see if it's time to check for new SMS messages.
if (now - lastSMSCheckTime >= SMS_CHECK_PERIOD) { if (now - lastSMSCheckTime >= SMS_CHECK_PERIOD) {
// it's time to check for new messages // it's time to check for new messages
// save this time so we know when to check next // save this time so we know when to check next
lastSMSCheckTime = now; lastSMSCheckTime = now;
if (numRuns <= maxRuns) { if (numRuns <= maxRuns) {
Serial.println("Checking for new SMS messages - Run #" + String(numRuns++)); Serial.println("Checking for new SMS messages - Run #" + String(numRuns++));
// execute the choreo and don't ignore control messages. // execute the choreo and don't ignore control messages.
checkForMessages(false); checkForMessages(false);
} else { } else {
Serial.println("Already ran " + String(maxRuns) + " times."); Serial.println("Already ran " + String(maxRuns) + " times.");
@ -145,7 +145,7 @@ This function executes the Twilio > SMSMessages > ListMessages choreo
and processes the results. and processes the results.
If ignoreCommands is 'true', this function will read and process messages If ignoreCommands is 'true', this function will read and process messages
updating 'lastSid', but will not actually take any action on any commands updating 'lastSid', but will not actually take any action on any commands
found. This is so we can ignore any old control messages when we start. found. This is so we can ignore any old control messages when we start.
If ignoreCommands is 'false', control messages WILL be acted on. If ignoreCommands is 'false', control messages WILL be acted on.
@ -156,7 +156,7 @@ void checkForMessages(bool ignoreCommands) {
TembooChoreo ListMessagesChoreo; TembooChoreo ListMessagesChoreo;
ListMessagesChoreo.begin(); ListMessagesChoreo.begin();
// set Temboo account credentials // set Temboo account credentials
ListMessagesChoreo.setAccountName(TEMBOO_ACCOUNT); ListMessagesChoreo.setAccountName(TEMBOO_ACCOUNT);
ListMessagesChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME); ListMessagesChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
@ -166,12 +166,12 @@ void checkForMessages(bool ignoreCommands) {
ListMessagesChoreo.setChoreo("/Library/Twilio/SMSMessages/ListMessages"); ListMessagesChoreo.setChoreo("/Library/Twilio/SMSMessages/ListMessages");
// set the choreo inputs // set the choreo inputs
// see https://www.temboo.com/library/Library/Twilio/SMSMessages/ListMessages/ // see https://www.temboo.com/library/Library/Twilio/SMSMessages/ListMessages/
// for complete details about the inputs for this Choreo // for complete details about the inputs for this Choreo
// the first input is a your Twilio AccountSID // the first input is a your Twilio AccountSID
ListMessagesChoreo.addInput("AccountSID", TWILIO_ACCOUNT_SID); ListMessagesChoreo.addInput("AccountSID", TWILIO_ACCOUNT_SID);
// next is your Twilio Auth Token // next is your Twilio Auth Token
ListMessagesChoreo.addInput("AuthToken", TWILIO_AUTH_TOKEN); ListMessagesChoreo.addInput("AuthToken", TWILIO_AUTH_TOKEN);
@ -179,24 +179,24 @@ void checkForMessages(bool ignoreCommands) {
ListMessagesChoreo.addInput("From", FROM_PHONE_NUMBER); ListMessagesChoreo.addInput("From", FROM_PHONE_NUMBER);
// Twilio can return information about up to 1000 messages at a time. // Twilio can return information about up to 1000 messages at a time.
// we're only interested in the 3 most recent ones. Note that if // we're only interested in the 3 most recent ones. Note that if
// this account receives lots of messages in quick succession, // this account receives lots of messages in quick succession,
// (more than 3 per minute in this case), we might miss some control // (more than 3 per minute in this case), we might miss some control
// messages. But if we request too many messages, we might run out of // messages. But if we request too many messages, we might run out of
// memory on the Arduino side of the Yun. // memory on the Arduino side of the Yun.
ListMessagesChoreo.addInput("PageSize", "3"); ListMessagesChoreo.addInput("PageSize", "3");
// We want the response in XML format to process with our // We want the response in XML format to process with our
// XPath output filters. // XPath output filters.
ListMessagesChoreo.addInput("ResponseFormat", "xml"); ListMessagesChoreo.addInput("ResponseFormat", "xml");
// we don't want everything from the output, just the // we don't want everything from the output, just the
// message IDs (the Sids) and the message texts // message IDs (the Sids) and the message texts
ListMessagesChoreo.addOutputFilter("sid", "Sid", "Response"); ListMessagesChoreo.addOutputFilter("sid", "Sid", "Response");
ListMessagesChoreo.addOutputFilter("text", "Body", "Response"); ListMessagesChoreo.addOutputFilter("text", "Body", "Response");
// tell the Choreo to run and wait for the results. The // tell the Choreo to run and wait for the results. The
// return code (returnCode) will tell us whether the Temboo client // return code (returnCode) will tell us whether the Temboo client
// was able to send our request to the Temboo servers // was able to send our request to the Temboo servers
unsigned int returnCode = ListMessagesChoreo.run(); unsigned int returnCode = ListMessagesChoreo.run();
@ -204,7 +204,7 @@ void checkForMessages(bool ignoreCommands) {
if (returnCode == 0) { if (returnCode == 0) {
// Need a string to hold the list of message IDs. // Need a string to hold the list of message IDs.
String messageSids; String messageSids;
// Need a string to hold the texts of the messages. // Need a string to hold the texts of the messages.
String messageTexts; String messageTexts;
@ -214,8 +214,8 @@ void checkForMessages(bool ignoreCommands) {
// lists containing the Sids and texts of the messages // lists containing the Sids and texts of the messages
// from our designated phone number. // from our designated phone number.
while(ListMessagesChoreo.available()) { while (ListMessagesChoreo.available()) {
// output names are terminated with '\x1F' characters. // output names are terminated with '\x1F' characters.
String name = ListMessagesChoreo.readStringUntil('\x1F'); String name = ListMessagesChoreo.readStringUntil('\x1F');
name.trim(); name.trim();
@ -236,46 +236,46 @@ void checkForMessages(bool ignoreCommands) {
// done reading output, close the Choreo to free up resources. // done reading output, close the Choreo to free up resources.
ListMessagesChoreo.close(); ListMessagesChoreo.close();
// parse the comma delimited lists of messages and Sids // parse the comma delimited lists of messages and Sids
processMessages(messageTexts, messageSids, ignoreCommands); processMessages(messageTexts, messageSids, ignoreCommands);
} else { } else {
// a non-zero return code means there was an error // a non-zero return code means there was an error
// read and print the error message // read and print the error message
while(ListMessagesChoreo.available()) { while (ListMessagesChoreo.available()) {
char c = ListMessagesChoreo.read(); char c = ListMessagesChoreo.read();
Serial.print(c); Serial.print(c);
} }
} }
} }
/* /*
This function processes the lists of message texts and Sids. This function processes the lists of message texts and Sids.
If a message contains a comma as part of the If a message contains a comma as part of the
message text, that message will be enclosed in double quotes message text, that message will be enclosed in double quotes
(") in the list. Example: (") in the list. Example:
A message,"Hey, now",Another message text A message,"Hey, now",Another message text
If the message contains double quotes, it will be enclosed in If the message contains double quotes, it will be enclosed in
double quotes AND the internal quotes will be doubled. double quotes AND the internal quotes will be doubled.
Example: Example:
"Hi ""Sam"" the man", Led on "Hi ""Sam"" the man", Led on
NOTE! We are assuming that Twilio returns more recent messages NOTE! We are assuming that Twilio returns more recent messages
first. This isn't officially documented by Twilio, but we've first. This isn't officially documented by Twilio, but we've
not seen any other case. not seen any other case.
'messageTexts' is a String containing a comma separated list of 'messageTexts' is a String containing a comma separated list of
message texts with commas and quotes escaped as described above. message texts with commas and quotes escaped as described above.
'messageSids' is a String containing a comma separated list of 'messageSids' is a String containing a comma separated list of
message Sids. Sids should not contain embedded commas or quotes. message Sids. Sids should not contain embedded commas or quotes.
'ignoreCommands' is a boolean. 'true' means and control messages 'ignoreCommands' is a boolean. 'true' means and control messages
will not be acted upon. 'false' means control messages will be will not be acted upon. 'false' means control messages will be
acted upon in the usual way. acted upon in the usual way.
*/ */
void processMessages(String messageTexts, String messageSids, bool ignoreCommands) { void processMessages(String messageTexts, String messageSids, bool ignoreCommands) {
@ -297,14 +297,14 @@ void processMessages(String messageTexts, String messageSids, bool ignoreCommand
// find the start of the next item in the list // find the start of the next item in the list
i = messageSids.indexOf(',', sidsStart); i = messageSids.indexOf(',', sidsStart);
if (i >= 0) { if (i >= 0) {
//extract a single Sid from the list. //extract a single Sid from the list.
sid = messageSids.substring(sidsStart, i); sid = messageSids.substring(sidsStart, i);
sidsStart = i + 1; sidsStart = i + 1;
// find the start of the next text in the list. // find the start of the next text in the list.
// Note that we have to be prepared to handle embedded // Note that we have to be prepared to handle embedded
// quotes and commans in the message texts. // quotes and commans in the message texts.
// The standard Arduino String class doesn't handle // The standard Arduino String class doesn't handle
// this, so we have to write our own function to do it. // this, so we have to write our own function to do it.
i = quotedIndexOf(messageTexts, ',', textsStart); i = quotedIndexOf(messageTexts, ',', textsStart);
@ -314,12 +314,12 @@ void processMessages(String messageTexts, String messageSids, bool ignoreCommand
text = messageTexts.substring(textsStart, i); text = messageTexts.substring(textsStart, i);
textsStart = i + 1; textsStart = i + 1;
// process the Sid and text to see if it's a // process the Sid and text to see if it's a
// control message. // control message.
ledUpdated = processMessage(sid, text, ignoreCommands); ledUpdated = processMessage(sid, text, ignoreCommands);
} }
} else { } else {
// the last item in the lists won't have a comma at the end, // the last item in the lists won't have a comma at the end,
// so we have to handle them specially. // so we have to handle them specially.
// Since we know this is the last item, we can just // Since we know this is the last item, we can just
@ -333,9 +333,9 @@ void processMessages(String messageTexts, String messageSids, bool ignoreCommand
// keep going until either we run out of list items // keep going until either we run out of list items
// or we run into a message we processed on a previous run. // or we run into a message we processed on a previous run.
} while ((i >=0) && (sid != lastSid)); } while ((i >= 0) && (sid != lastSid));
// print what we've found to the serial monitor, // print what we've found to the serial monitor,
// just so we can see what's going on. // just so we can see what's going on.
if (sid == lastSid) { if (sid == lastSid) {
if (ledUpdated) if (ledUpdated)
@ -359,17 +359,17 @@ A message with the text "LED ON" turns the LED on.
A message with the text "LED OFF" turns the LED off. A message with the text "LED OFF" turns the LED off.
(Case is ignored.) (Case is ignored.)
If 'ignoreCommands' is true, the actions described above will NOT If 'ignoreCommands' is true, the actions described above will NOT
take place. take place.
It also updates the 'lastSid' global variable when It also updates the 'lastSid' global variable when
a control message is processed. a control message is processed.
It returns 'true' if the message was a control message, and It returns 'true' if the message was a control message, and
'false' if it wasn't or if we've already processed this message. 'false' if it wasn't or if we've already processed this message.
*/ */
bool processMessage(String sid, String text, bool ignoreCommands) { bool processMessage(String sid, String text, bool ignoreCommands) {
// a flag to indicate whether this was a control message or not // a flag to indicate whether this was a control message or not
bool ledUpdated = false; bool ledUpdated = false;
@ -377,7 +377,7 @@ bool processMessage(String sid, String text, bool ignoreCommands) {
if (sid != lastSid) { if (sid != lastSid) {
if (text.equalsIgnoreCase("LED ON")) { if (text.equalsIgnoreCase("LED ON")) {
if (!ignoreCommands) { if (!ignoreCommands) {
//turn on the LED //turn on the LED
digitalWrite(LED_PIN, HIGH); digitalWrite(LED_PIN, HIGH);
@ -394,7 +394,7 @@ bool processMessage(String sid, String text, bool ignoreCommands) {
} }
// If the LED state was updated, remember the Sid if this message. // If the LED state was updated, remember the Sid if this message.
if (ledUpdated) if (ledUpdated)
lastSid = sid; lastSid = sid;
} }
return ledUpdated; return ledUpdated;
@ -428,16 +428,16 @@ int quotedIndexOf(String s, char delim, int start) {
by inserting your own Temboo account name and app key information. The contents of the file should by inserting your own Temboo account name and app key information. The contents of the file should
look like: look like:
#define TEMBOO_ACCOUNT "myTembooAccountName" // your Temboo account name #define TEMBOO_ACCOUNT "myTembooAccountName" // your Temboo account name
#define TEMBOO_APP_KEY_NAME "myFirstApp" // your Temboo app key name #define TEMBOO_APP_KEY_NAME "myFirstApp" // your Temboo app key name
#define TEMBOO_APP_KEY "xxx-xxx-xxx-xx-xxx" // your Temboo app key #define TEMBOO_APP_KEY "xxx-xxx-xxx-xx-xxx" // your Temboo app key
You can find your Temboo App Key information on the Temboo website, You can find your Temboo App Key information on the Temboo website,
under My Account > Application Keys under My Account > Application Keys
The same TembooAccount.h file settings can be used for all Temboo SDK sketches. The same TembooAccount.h file settings can be used for all Temboo SDK sketches.
Keeping your account information in a separate file means you can save it once, Keeping your account information in a separate file means you can save it once,
then just distribute the main .ino file without worrying that you forgot to delete your credentials. then just distribute the main .ino file without worrying that you forgot to delete your credentials.
*/ */

View File

@ -1,26 +1,26 @@
/* /*
GetYahooWeatherReport GetYahooWeatherReport
Demonstrates making a request to the Yahoo! Weather API using Temboo from an Arduino Yun. Demonstrates making a request to the Yahoo! Weather API using Temboo from an Arduino Yun.
Check out the latest Arduino & Temboo examples and support docs at http://www.temboo.com/arduino Check out the latest Arduino & Temboo examples and support docs at http://www.temboo.com/arduino
A Temboo account and application key are necessary to run all Temboo examples. A Temboo account and application key are necessary to run all Temboo examples.
If you don't already have one, you can register for a free Temboo account at If you don't already have one, you can register for a free Temboo account at
http://www.temboo.com http://www.temboo.com
This example assumes basic familiarity with Arduino sketches, and that your Yun is connected This example assumes basic familiarity with Arduino sketches, and that your Yun is connected
to the Internet. to the Internet.
Looking for another API to use with your Arduino Yun? We've got over 100 in our Library! Looking for another API to use with your Arduino Yun? We've got over 100 in our Library!
This example code is in the public domain. This example code is in the public domain.
*/ */
#include <Bridge.h> #include <Bridge.h>
#include <Temboo.h> #include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information #include "TembooAccount.h" // contains Temboo account information
// as described in the footer comment below // as described in the footer comment below
// the address for which a weather forecast will be retrieved // the address for which a weather forecast will be retrieved
@ -32,10 +32,10 @@ int maxRuns = 10; // max number of times the Yahoo WeatherByAddress Choreo shou
void setup() { void setup() {
Serial.begin(9600); Serial.begin(9600);
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
delay(4000); delay(4000);
while(!Serial); while (!Serial);
Bridge.begin(); Bridge.begin();
} }
@ -44,13 +44,13 @@ void loop()
{ {
// while we haven't reached the max number of runs... // while we haven't reached the max number of runs...
if (numRuns <= maxRuns) { if (numRuns <= maxRuns) {
// print status // print status
Serial.println("Running GetWeatherByAddress - Run #" + String(numRuns++) + "..."); Serial.println("Running GetWeatherByAddress - Run #" + String(numRuns++) + "...");
// create a TembooChoreo object to send a Choreo request to Temboo // create a TembooChoreo object to send a Choreo request to Temboo
TembooChoreo GetWeatherByAddressChoreo; TembooChoreo GetWeatherByAddressChoreo;
// invoke the Temboo client // invoke the Temboo client
GetWeatherByAddressChoreo.begin(); GetWeatherByAddressChoreo.begin();
@ -58,30 +58,30 @@ void loop()
GetWeatherByAddressChoreo.setAccountName(TEMBOO_ACCOUNT); GetWeatherByAddressChoreo.setAccountName(TEMBOO_ACCOUNT);
GetWeatherByAddressChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME); GetWeatherByAddressChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
GetWeatherByAddressChoreo.setAppKey(TEMBOO_APP_KEY); GetWeatherByAddressChoreo.setAppKey(TEMBOO_APP_KEY);
// set the name of the choreo we want to run // set the name of the choreo we want to run
GetWeatherByAddressChoreo.setChoreo("/Library/Yahoo/Weather/GetWeatherByAddress"); GetWeatherByAddressChoreo.setChoreo("/Library/Yahoo/Weather/GetWeatherByAddress");
// set choreo inputs; in this case, the address for which to retrieve weather data // set choreo inputs; in this case, the address for which to retrieve weather data
// the Temboo client provides standardized calls to 100+ cloud APIs // the Temboo client provides standardized calls to 100+ cloud APIs
GetWeatherByAddressChoreo.addInput("Address", ADDRESS_FOR_FORECAST); GetWeatherByAddressChoreo.addInput("Address", ADDRESS_FOR_FORECAST);
// add an output filter to extract the name of the city. // add an output filter to extract the name of the city.
GetWeatherByAddressChoreo.addOutputFilter("city", "/rss/channel/yweather:location/@city", "Response"); GetWeatherByAddressChoreo.addOutputFilter("city", "/rss/channel/yweather:location/@city", "Response");
// add an output filter to extract the current temperature // add an output filter to extract the current temperature
GetWeatherByAddressChoreo.addOutputFilter("temperature", "/rss/channel/item/yweather:condition/@temp", "Response"); GetWeatherByAddressChoreo.addOutputFilter("temperature", "/rss/channel/item/yweather:condition/@temp", "Response");
// add an output filter to extract the date and time of the last report. // add an output filter to extract the date and time of the last report.
GetWeatherByAddressChoreo.addOutputFilter("date", "/rss/channel/item/yweather:condition/@date", "Response"); GetWeatherByAddressChoreo.addOutputFilter("date", "/rss/channel/item/yweather:condition/@date", "Response");
// run the choreo // run the choreo
GetWeatherByAddressChoreo.run(); GetWeatherByAddressChoreo.run();
// when the choreo results are available, print them to the serial monitor // when the choreo results are available, print them to the serial monitor
while(GetWeatherByAddressChoreo.available()) { while (GetWeatherByAddressChoreo.available()) {
char c = GetWeatherByAddressChoreo.read(); char c = GetWeatherByAddressChoreo.read();
Serial.print(c); Serial.print(c);
} }
GetWeatherByAddressChoreo.close(); GetWeatherByAddressChoreo.close();
@ -101,15 +101,15 @@ void loop()
by inserting your own Temboo account name and app key information. The contents of the file should by inserting your own Temboo account name and app key information. The contents of the file should
look like: look like:
#define TEMBOO_ACCOUNT "myTembooAccountName" // your Temboo account name #define TEMBOO_ACCOUNT "myTembooAccountName" // your Temboo account name
#define TEMBOO_APP_KEY_NAME "myFirstApp" // your Temboo app key name #define TEMBOO_APP_KEY_NAME "myFirstApp" // your Temboo app key name
#define TEMBOO_APP_KEY "xxx-xxx-xxx-xx-xxx" // your Temboo app key #define TEMBOO_APP_KEY "xxx-xxx-xxx-xx-xxx" // your Temboo app key
You can find your Temboo App Key information on the Temboo website, You can find your Temboo App Key information on the Temboo website,
under My Account > Application Keys under My Account > Application Keys
The same TembooAccount.h file settings can be used for all Temboo SDK sketches. The same TembooAccount.h file settings can be used for all Temboo SDK sketches.
Keeping your account information in a separate file means you can share the main .ino file without worrying Keeping your account information in a separate file means you can share the main .ino file without worrying
that you forgot to delete your credentials. that you forgot to delete your credentials.
*/ */

View File

@ -1,33 +1,33 @@
/* /*
ReadATweet ReadATweet
Demonstrates retrieving the most recent Tweet from a user's home timeline Demonstrates retrieving the most recent Tweet from a user's home timeline
using Temboo from an Arduino Yun. using Temboo from an Arduino Yun.
Check out the latest Arduino & Temboo examples and support docs at http://www.temboo.com/arduino Check out the latest Arduino & Temboo examples and support docs at http://www.temboo.com/arduino
A Temboo account and application key are necessary to run all Temboo examples. A Temboo account and application key are necessary to run all Temboo examples.
If you don't already have one, you can register for a free Temboo account at If you don't already have one, you can register for a free Temboo account at
http://www.temboo.com http://www.temboo.com
In order to run this sketch, you'll need to register an application using In order to run this sketch, you'll need to register an application using
the Twitter dev console at https://dev.twitter.com. After creating the the Twitter dev console at https://dev.twitter.com. After creating the
app, you'll find OAuth credentials for that application under the "OAuth Tool" tab. app, you'll find OAuth credentials for that application under the "OAuth Tool" tab.
Substitute these values for the placeholders below. Substitute these values for the placeholders below.
This example assumes basic familiarity with Arduino sketches, and that your Yun This example assumes basic familiarity with Arduino sketches, and that your Yun
is connected to the Internet. is connected to the Internet.
Want to use another social API with your Arduino Yun? We've got Facebook, Want to use another social API with your Arduino Yun? We've got Facebook,
Google+, Instagram, Tumblr and more in our Library! Google+, Instagram, Tumblr and more in our Library!
This example code is in the public domain. This example code is in the public domain.
*/ */
#include <Bridge.h> #include <Bridge.h>
#include <Temboo.h> #include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information #include "TembooAccount.h" // contains Temboo account information
// as described in the footer comment below // as described in the footer comment below
/*** SUBSTITUTE YOUR VALUES BELOW: ***/ /*** SUBSTITUTE YOUR VALUES BELOW: ***/
@ -43,10 +43,10 @@ int maxRuns = 10; // the max number of times the Twitter HomeTimeline Choreo s
void setup() { void setup() {
Serial.begin(9600); Serial.begin(9600);
// For debugging, wait until a serial console is connected. // For debugging, wait until a serial console is connected.
delay(4000); delay(4000);
while(!Serial); while (!Serial);
Bridge.begin(); Bridge.begin();
} }
void loop() void loop()
@ -54,14 +54,14 @@ void loop()
// while we haven't reached the max number of runs... // while we haven't reached the max number of runs...
if (numRuns <= maxRuns) { if (numRuns <= maxRuns) {
Serial.println("Running ReadATweet - Run #" + String(numRuns++)); Serial.println("Running ReadATweet - Run #" + String(numRuns++));
TembooChoreo HomeTimelineChoreo; TembooChoreo HomeTimelineChoreo;
// invoke the Temboo client. // invoke the Temboo client.
// NOTE that the client must be reinvoked, and repopulated with // NOTE that the client must be reinvoked, and repopulated with
// appropriate arguments, each time its run() method is called. // appropriate arguments, each time its run() method is called.
HomeTimelineChoreo.begin(); HomeTimelineChoreo.begin();
// set Temboo account credentials // set Temboo account credentials
HomeTimelineChoreo.setAccountName(TEMBOO_ACCOUNT); HomeTimelineChoreo.setAccountName(TEMBOO_ACCOUNT);
HomeTimelineChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME); HomeTimelineChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
@ -69,8 +69,8 @@ void loop()
// tell the Temboo client which Choreo to run (Twitter > Timelines > HomeTimeline) // tell the Temboo client which Choreo to run (Twitter > Timelines > HomeTimeline)
HomeTimelineChoreo.setChoreo("/Library/Twitter/Timelines/HomeTimeline"); HomeTimelineChoreo.setChoreo("/Library/Twitter/Timelines/HomeTimeline");
// set the required choreo inputs // set the required choreo inputs
// see https://www.temboo.com/library/Library/Twitter/Timelines/HomeTimeline/ // see https://www.temboo.com/library/Library/Twitter/Timelines/HomeTimeline/
// for complete details about the inputs for this Choreo // for complete details about the inputs for this Choreo
@ -78,44 +78,44 @@ void loop()
HomeTimelineChoreo.addInput("Count", "1"); // the max number of Tweets to return from each request HomeTimelineChoreo.addInput("Count", "1"); // the max number of Tweets to return from each request
HomeTimelineChoreo.addInput("AccessToken", TWITTER_ACCESS_TOKEN); HomeTimelineChoreo.addInput("AccessToken", TWITTER_ACCESS_TOKEN);
HomeTimelineChoreo.addInput("AccessTokenSecret", TWITTER_ACCESS_TOKEN_SECRET); HomeTimelineChoreo.addInput("AccessTokenSecret", TWITTER_ACCESS_TOKEN_SECRET);
HomeTimelineChoreo.addInput("ConsumerKey", TWITTER_CONSUMER_KEY); HomeTimelineChoreo.addInput("ConsumerKey", TWITTER_CONSUMER_KEY);
HomeTimelineChoreo.addInput("ConsumerSecret", TWITTER_CONSUMER_SECRET); HomeTimelineChoreo.addInput("ConsumerSecret", TWITTER_CONSUMER_SECRET);
// next, we'll define two output filters that let us specify the // next, we'll define two output filters that let us specify the
// elements of the response from Twitter that we want to receive. // elements of the response from Twitter that we want to receive.
// see the examples at http://www.temboo.com/arduino // see the examples at http://www.temboo.com/arduino
// for more on using output filters // for more on using output filters
// we want the text of the tweet // we want the text of the tweet
HomeTimelineChoreo.addOutputFilter("tweet", "/[1]/text", "Response"); HomeTimelineChoreo.addOutputFilter("tweet", "/[1]/text", "Response");
// and the name of the author // and the name of the author
HomeTimelineChoreo.addOutputFilter("author", "/[1]/user/screen_name", "Response"); HomeTimelineChoreo.addOutputFilter("author", "/[1]/user/screen_name", "Response");
// tell the Process to run and wait for the results. The // tell the Process to run and wait for the results. The
// return code will tell us whether the Temboo client // return code will tell us whether the Temboo client
// was able to send our request to the Temboo servers // was able to send our request to the Temboo servers
unsigned int returnCode = HomeTimelineChoreo.run(); unsigned int returnCode = HomeTimelineChoreo.run();
// a response code of 0 means success; print the API response // a response code of 0 means success; print the API response
if(returnCode == 0) { if (returnCode == 0) {
String author; // a String to hold the tweet author's name String author; // a String to hold the tweet author's name
String tweet; // a String to hold the text of the tweet String tweet; // a String to hold the text of the tweet
// choreo outputs are returned as key/value pairs, delimited with // choreo outputs are returned as key/value pairs, delimited with
// newlines and record/field terminator characters, for example: // newlines and record/field terminator characters, for example:
// Name1\n\x1F // Name1\n\x1F
// Value1\n\x1E // Value1\n\x1E
// Name2\n\x1F // Name2\n\x1F
// Value2\n\x1E // Value2\n\x1E
// see the examples at http://www.temboo.com/arduino for more details // see the examples at http://www.temboo.com/arduino for more details
// we can read this format into separate variables, as follows: // we can read this format into separate variables, as follows:
while(HomeTimelineChoreo.available()) { while (HomeTimelineChoreo.available()) {
// read the name of the output item // read the name of the output item
String name = HomeTimelineChoreo.readStringUntil('\x1F'); String name = HomeTimelineChoreo.readStringUntil('\x1F');
name.trim(); name.trim();
@ -131,13 +131,13 @@ void loop()
author = data; author = data;
} }
} }
Serial.println("@" + author + " - " + tweet); Serial.println("@" + author + " - " + tweet);
} else { } else {
// there was an error // there was an error
// print the raw output from the choreo // print the raw output from the choreo
while(HomeTimelineChoreo.available()) { while (HomeTimelineChoreo.available()) {
char c = HomeTimelineChoreo.read(); char c = HomeTimelineChoreo.read();
Serial.print(c); Serial.print(c);
} }
@ -159,15 +159,15 @@ void loop()
by inserting your own Temboo account name and app key information. The contents of the file should by inserting your own Temboo account name and app key information. The contents of the file should
look like: look like:
#define TEMBOO_ACCOUNT "myTembooAccountName" // your Temboo account name #define TEMBOO_ACCOUNT "myTembooAccountName" // your Temboo account name
#define TEMBOO_APP_KEY_NAME "myFirstApp" // your Temboo app key name #define TEMBOO_APP_KEY_NAME "myFirstApp" // your Temboo app key name
#define TEMBOO_APP_KEY "xxx-xxx-xxx-xx-xxx" // your Temboo app key #define TEMBOO_APP_KEY "xxx-xxx-xxx-xx-xxx" // your Temboo app key
You can find your Temboo App Key information on the Temboo website, You can find your Temboo App Key information on the Temboo website,
under My Account > Application Keys under My Account > Application Keys
The same TembooAccount.h file settings can be used for all Temboo SDK sketches. The same TembooAccount.h file settings can be used for all Temboo SDK sketches.
Keeping your account information in a separate file means you can share the main .ino file without worrying Keeping your account information in a separate file means you can share the main .ino file without worrying
that you forgot to delete your credentials. that you forgot to delete your credentials.
*/ */

View File

@ -5,30 +5,30 @@
Check out the latest Arduino & Temboo examples and support docs at http://www.temboo.com/arduino Check out the latest Arduino & Temboo examples and support docs at http://www.temboo.com/arduino
A Temboo account and application key are necessary to run all Temboo examples. A Temboo account and application key are necessary to run all Temboo examples.
If you don't already have one, you can register for a free Temboo account at If you don't already have one, you can register for a free Temboo account at
http://www.temboo.com http://www.temboo.com
In order to run this sketch, you'll need to register an application using In order to run this sketch, you'll need to register an application using
the Twitter dev console at https://dev.twitter.com. Note that since this the Twitter dev console at https://dev.twitter.com. Note that since this
sketch creates a new tweet, your application will need to be configured with sketch creates a new tweet, your application will need to be configured with
read+write permissions. After creating the app, you'll find OAuth credentials read+write permissions. After creating the app, you'll find OAuth credentials
for that application under the "OAuth Tool" tab. Substitute these values for for that application under the "OAuth Tool" tab. Substitute these values for
the placeholders below. the placeholders below.
This example assumes basic familiarity with Arduino sketches, and that your Yun is connected This example assumes basic familiarity with Arduino sketches, and that your Yun is connected
to the Internet. to the Internet.
Want to use another social API with your Arduino Yun? We've got Facebook, Want to use another social API with your Arduino Yun? We've got Facebook,
Google+, Instagram, Tumblr and more in our Library! Google+, Instagram, Tumblr and more in our Library!
This example code is in the public domain. This example code is in the public domain.
*/ */
#include <Bridge.h> #include <Bridge.h>
#include <Temboo.h> #include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information #include "TembooAccount.h" // contains Temboo account information
// as described in the footer comment below // as described in the footer comment below
/*** SUBSTITUTE YOUR VALUES BELOW: ***/ /*** SUBSTITUTE YOUR VALUES BELOW: ***/
@ -48,7 +48,7 @@ void setup() {
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
delay(4000); delay(4000);
while(!Serial); while (!Serial);
Bridge.begin(); Bridge.begin();
} }
@ -59,18 +59,18 @@ void loop()
if (numRuns <= maxRuns) { if (numRuns <= maxRuns) {
Serial.println("Running SendATweet - Run #" + String(numRuns++) + "..."); Serial.println("Running SendATweet - Run #" + String(numRuns++) + "...");
// define the text of the tweet we want to send // define the text of the tweet we want to send
String tweetText("My Arduino Yun has been running for " + String(millis()) + " milliseconds."); String tweetText("My Arduino Yun has been running for " + String(millis()) + " milliseconds.");
TembooChoreo StatusesUpdateChoreo; TembooChoreo StatusesUpdateChoreo;
// invoke the Temboo client // invoke the Temboo client
// NOTE that the client must be reinvoked, and repopulated with // NOTE that the client must be reinvoked, and repopulated with
// appropriate arguments, each time its run() method is called. // appropriate arguments, each time its run() method is called.
StatusesUpdateChoreo.begin(); StatusesUpdateChoreo.begin();
// set Temboo account credentials // set Temboo account credentials
StatusesUpdateChoreo.setAccountName(TEMBOO_ACCOUNT); StatusesUpdateChoreo.setAccountName(TEMBOO_ACCOUNT);
StatusesUpdateChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME); StatusesUpdateChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
@ -80,26 +80,26 @@ void loop()
StatusesUpdateChoreo.setChoreo("/Library/Twitter/Tweets/StatusesUpdate"); StatusesUpdateChoreo.setChoreo("/Library/Twitter/Tweets/StatusesUpdate");
// set the required choreo inputs // set the required choreo inputs
// see https://www.temboo.com/library/Library/Twitter/Tweets/StatusesUpdate/ // see https://www.temboo.com/library/Library/Twitter/Tweets/StatusesUpdate/
// for complete details about the inputs for this Choreo // for complete details about the inputs for this Choreo
// add the Twitter account information // add the Twitter account information
StatusesUpdateChoreo.addInput("AccessToken", TWITTER_ACCESS_TOKEN); StatusesUpdateChoreo.addInput("AccessToken", TWITTER_ACCESS_TOKEN);
StatusesUpdateChoreo.addInput("AccessTokenSecret", TWITTER_ACCESS_TOKEN_SECRET); StatusesUpdateChoreo.addInput("AccessTokenSecret", TWITTER_ACCESS_TOKEN_SECRET);
StatusesUpdateChoreo.addInput("ConsumerKey", TWITTER_CONSUMER_KEY); StatusesUpdateChoreo.addInput("ConsumerKey", TWITTER_CONSUMER_KEY);
StatusesUpdateChoreo.addInput("ConsumerSecret", TWITTER_CONSUMER_SECRET); StatusesUpdateChoreo.addInput("ConsumerSecret", TWITTER_CONSUMER_SECRET);
// and the tweet we want to send // and the tweet we want to send
StatusesUpdateChoreo.addInput("StatusUpdate", tweetText); StatusesUpdateChoreo.addInput("StatusUpdate", tweetText);
// tell the Process to run and wait for the results. The // tell the Process to run and wait for the results. The
// return code (returnCode) will tell us whether the Temboo client // return code (returnCode) will tell us whether the Temboo client
// was able to send our request to the Temboo servers // was able to send our request to the Temboo servers
unsigned int returnCode = StatusesUpdateChoreo.run(); unsigned int returnCode = StatusesUpdateChoreo.run();
// a return code of zero (0) means everything worked // a return code of zero (0) means everything worked
if (returnCode == 0) { if (returnCode == 0) {
Serial.println("Success! Tweet sent!"); Serial.println("Success! Tweet sent!");
} else { } else {
// a non-zero return code means there was an error // a non-zero return code means there was an error
// read and print the error message // read and print the error message
@ -107,7 +107,7 @@ void loop()
char c = StatusesUpdateChoreo.read(); char c = StatusesUpdateChoreo.read();
Serial.print(c); Serial.print(c);
} }
} }
StatusesUpdateChoreo.close(); StatusesUpdateChoreo.close();
// do nothing for the next 90 seconds // do nothing for the next 90 seconds
@ -124,15 +124,15 @@ void loop()
by inserting your own Temboo account name and app key information. The contents of the file should by inserting your own Temboo account name and app key information. The contents of the file should
look like: look like:
#define TEMBOO_ACCOUNT "myTembooAccountName" // your Temboo account name #define TEMBOO_ACCOUNT "myTembooAccountName" // your Temboo account name
#define TEMBOO_APP_KEY_NAME "myFirstApp" // your Temboo app key name #define TEMBOO_APP_KEY_NAME "myFirstApp" // your Temboo app key name
#define TEMBOO_APP_KEY "xxx-xxx-xxx-xx-xxx" // your Temboo app key #define TEMBOO_APP_KEY "xxx-xxx-xxx-xx-xxx" // your Temboo app key
You can find your Temboo App Key information on the Temboo website, You can find your Temboo App Key information on the Temboo website,
under My Account > Application Keys under My Account > Application Keys
The same TembooAccount.h file settings can be used for all Temboo SDK sketches. The same TembooAccount.h file settings can be used for all Temboo SDK sketches.
Keeping your account information in a separate file means you can share the main .ino file without worrying Keeping your account information in a separate file means you can share the main .ino file without worrying
that you forgot to delete your credentials. that you forgot to delete your credentials.
*/ */

View File

@ -5,17 +5,17 @@
Check out the latest Arduino & Temboo examples and support docs at http://www.temboo.com/arduino Check out the latest Arduino & Temboo examples and support docs at http://www.temboo.com/arduino
A Temboo account and application key are necessary to run all Temboo examples. A Temboo account and application key are necessary to run all Temboo examples.
If you don't already have one, you can register for a free Temboo account at If you don't already have one, you can register for a free Temboo account at
http://www.temboo.com http://www.temboo.com
Since this sketch uses Gmail to send the email, you'll also need a valid Since this sketch uses Gmail to send the email, you'll also need a valid
Google Gmail account. The sketch needs the username and password you use Google Gmail account. The sketch needs the username and password you use
to log into your Gmail account - substitute the placeholders below for these values. to log into your Gmail account - substitute the placeholders below for these values.
This example assumes basic familiarity with Arduino sketches, and that your Yun is connected This example assumes basic familiarity with Arduino sketches, and that your Yun is connected
to the Internet. to the Internet.
Looking for another API to use with your Arduino Yun? We've got over 100 in our Library! Looking for another API to use with your Arduino Yun? We've got over 100 in our Library!
This example code is in the public domain. This example code is in the public domain.
@ -24,7 +24,7 @@
#include <Bridge.h> #include <Bridge.h>
#include <Temboo.h> #include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information #include "TembooAccount.h" // contains Temboo account information
// as described in the footer comment below // as described in the footer comment below
/*** SUBSTITUTE YOUR VALUES BELOW: ***/ /*** SUBSTITUTE YOUR VALUES BELOW: ***/
@ -41,14 +41,14 @@ const String GMAIL_PASSWORD = "xxxxxxxxxx";
const String TO_EMAIL_ADDRESS = "xxxxxxxxxx"; const String TO_EMAIL_ADDRESS = "xxxxxxxxxx";
// a flag to indicate whether we've tried to send the email yet or not // a flag to indicate whether we've tried to send the email yet or not
boolean attempted = false; boolean attempted = false;
void setup() { void setup() {
Serial.begin(9600); Serial.begin(9600);
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
delay(4000); delay(4000);
while(!Serial); while (!Serial);
Bridge.begin(); Bridge.begin();
} }
@ -59,14 +59,14 @@ void loop()
if (!attempted) { if (!attempted) {
Serial.println("Running SendAnEmail..."); Serial.println("Running SendAnEmail...");
TembooChoreo SendEmailChoreo; TembooChoreo SendEmailChoreo;
// invoke the Temboo client // invoke the Temboo client
// NOTE that the client must be reinvoked, and repopulated with // NOTE that the client must be reinvoked, and repopulated with
// appropriate arguments, each time its run() method is called. // appropriate arguments, each time its run() method is called.
SendEmailChoreo.begin(); SendEmailChoreo.begin();
// set Temboo account credentials // set Temboo account credentials
SendEmailChoreo.setAccountName(TEMBOO_ACCOUNT); SendEmailChoreo.setAccountName(TEMBOO_ACCOUNT);
SendEmailChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME); SendEmailChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
@ -74,13 +74,13 @@ void loop()
// identify the Temboo Library choreo to run (Google > Gmail > SendEmail) // identify the Temboo Library choreo to run (Google > Gmail > SendEmail)
SendEmailChoreo.setChoreo("/Library/Google/Gmail/SendEmail"); SendEmailChoreo.setChoreo("/Library/Google/Gmail/SendEmail");
// set the required choreo inputs // set the required choreo inputs
// see https://www.temboo.com/library/Library/Google/Gmail/SendEmail/ // see https://www.temboo.com/library/Library/Google/Gmail/SendEmail/
// for complete details about the inputs for this Choreo // for complete details about the inputs for this Choreo
// the first input is your Gmail email address. // the first input is your Gmail email address.
SendEmailChoreo.addInput("Username", GMAIL_USER_NAME); SendEmailChoreo.addInput("Username", GMAIL_USER_NAME);
// next is your Gmail password. // next is your Gmail password.
SendEmailChoreo.addInput("Password", GMAIL_PASSWORD); SendEmailChoreo.addInput("Password", GMAIL_PASSWORD);
@ -89,17 +89,17 @@ void loop()
// then a subject line // then a subject line
SendEmailChoreo.addInput("Subject", "ALERT: Greenhouse Temperature"); SendEmailChoreo.addInput("Subject", "ALERT: Greenhouse Temperature");
// next comes the message body, the main content of the email // next comes the message body, the main content of the email
SendEmailChoreo.addInput("MessageBody", "Hey! The greenhouse is too cold!"); SendEmailChoreo.addInput("MessageBody", "Hey! The greenhouse is too cold!");
// tell the Choreo to run and wait for the results. The // tell the Choreo to run and wait for the results. The
// return code (returnCode) will tell us whether the Temboo client // return code (returnCode) will tell us whether the Temboo client
// was able to send our request to the Temboo servers // was able to send our request to the Temboo servers
unsigned int returnCode = SendEmailChoreo.run(); unsigned int returnCode = SendEmailChoreo.run();
// a return code of zero (0) means everything worked // a return code of zero (0) means everything worked
if (returnCode == 0) { if (returnCode == 0) {
Serial.println("Success! Email sent!"); Serial.println("Success! Email sent!");
} else { } else {
// a non-zero return code means there was an error // a non-zero return code means there was an error
// read and print the error message // read and print the error message
@ -107,9 +107,9 @@ void loop()
char c = SendEmailChoreo.read(); char c = SendEmailChoreo.read();
Serial.print(c); Serial.print(c);
} }
} }
SendEmailChoreo.close(); SendEmailChoreo.close();
// set the flag showing we've tried // set the flag showing we've tried
attempted = true; attempted = true;
} }
@ -123,15 +123,15 @@ void loop()
by inserting your own Temboo account name and app key information. The contents of the file should by inserting your own Temboo account name and app key information. The contents of the file should
look like: look like:
#define TEMBOO_ACCOUNT "myTembooAccountName" // your Temboo account name #define TEMBOO_ACCOUNT "myTembooAccountName" // your Temboo account name
#define TEMBOO_APP_KEY_NAME "myFirstApp" // your Temboo app key name #define TEMBOO_APP_KEY_NAME "myFirstApp" // your Temboo app key name
#define TEMBOO_APP_KEY "xxx-xxx-xxx-xx-xxx" // your Temboo app key #define TEMBOO_APP_KEY "xxx-xxx-xxx-xx-xxx" // your Temboo app key
You can find your Temboo App Key information on the Temboo website, You can find your Temboo App Key information on the Temboo website,
under My Account > Application Keys under My Account > Application Keys
The same TembooAccount.h file settings can be used for all Temboo SDK sketches. The same TembooAccount.h file settings can be used for all Temboo SDK sketches.
Keeping your account information in a separate file means you can share the main .ino file without worrying Keeping your account information in a separate file means you can share the main .ino file without worrying
that you forgot to delete your credentials. that you forgot to delete your credentials.
*/ */

Some files were not shown because too many files have changed in this diff Show More