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
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.
This example code is in the public domain.
*/

View File

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

View File

@ -1,7 +1,7 @@
/*
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.
*/

View File

@ -1,9 +1,9 @@
/*
Fade
This example shows how to fade an LED on pin 9
using the analogWrite() function.
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
// the setup routine runs once when you press reset:
void setup() {
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
}
// the loop routine runs over and over again forever:
void loop() {
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);
analogWrite(led, brightness);
// change the brightness for next time through the loop:
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) {
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}

View File

@ -2,7 +2,7 @@
ReadAnalogVoltage
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.
This example code is in the public domain.
*/

View File

@ -1,27 +1,27 @@
/* 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
can run at the same time without being interrupted by the LED code.
The circuit:
* LED attached from pin 13 to ground.
* 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.
created 2005
by David A. Mellis
modified 8 Feb 2010
by Paul Stoffregen
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/
// constants won't change. Used here to
// constants won't change. Used here to
// set pin numbers:
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() {
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
pinMode(ledPin, OUTPUT);
}
void loop()
{
// 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
// difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to
// 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
// the LED is bigger than the interval at which you want to
// blink the LED.
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
if (currentMillis - previousMillis > interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW)

View File

@ -1,30 +1,30 @@
/*
Button
Turns on and off a light emitting diode(LED) connected to digital
pin 13, when pressing a pushbutton attached to pin 2.
Turns on and off a light emitting diode(LED) connected to digital
pin 13, when pressing a pushbutton attached to pin 2.
The circuit:
* LED attached from pin 13 to ground
* LED attached from pin 13 to ground
* pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground
* Note: on most Arduinos there is already an LED on the board
attached to pin 13.
created 2005
by DojoDave <http://www.0j0.org>
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
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:
const int buttonPin = 2; // the number of the pushbutton 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() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
pinMode(buttonPin, INPUT);
}
void loop(){
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
}
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
}
else {
// turn LED off:
digitalWrite(ledPin, LOW);
digitalWrite(ledPin, LOW);
}
}

View File

@ -1,33 +1,33 @@
/*
/*
Debounce
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
a minimum delay between toggles to debounce the circuit (i.e. to ignore
noise).
noise).
The circuit:
* LED attached from pin 13 to ground
* pushbutton attached from pin 2 to +5V
* 10K resistor attached from pin 2 to ground
* 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.
created 21 November 2006
by David A. Mellis
modified 30 Aug 2011
by Limor Fried
modified 28 Dec 2012
by Mike Walters
This example code is in the public domain.
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:
const int buttonPin = 2; // the number of the pushbutton 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:
int reading = digitalRead(buttonPin);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited
// long enough since the last press to ignore any noise:
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited
// long enough since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:
@ -78,7 +78,7 @@ void loop() {
}
}
}
// set the LED:
digitalWrite(ledPin, ledState);

View File

@ -1,48 +1,48 @@
/*
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.
The circuit:
* Momentary switch attached from pin 2 to ground
The circuit:
* Momentary switch attached from pin 2 to ground
* Built-in LED on pin 13
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
read HIGH when the switch is open, and LOW when it is closed.
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
read HIGH when the switch is open, and LOW when it is closed.
created 14 March 2012
by Scott Fitzgerald
http://www.arduino.cc/en/Tutorial/InputPullupSerial
This example code is in the public domain
*/
void setup(){
void setup() {
//start serial connection
Serial.begin(9600);
//configure pin2 as an input and enable the internal pull-up resistor
pinMode(2, INPUT_PULLUP);
pinMode(13, OUTPUT);
pinMode(13, OUTPUT);
}
void loop(){
void loop() {
//read the pushbutton value into a variable
int sensorVal = digitalRead(2);
//print out the value of the pushbutton
Serial.println(sensorVal);
// Keep in mind the pullup means the pushbutton's
// 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:
if (sensorVal == HIGH) {
digitalWrite(13, LOW);
}
}
else {
digitalWrite(13, HIGH);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,22 +1,22 @@
/*
Analog input, analog output, serial output
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.
Also prints the results to the serial monitor.
The circuit:
* potentiometer connected to analog pin 0.
Center pin of the potentiometer goes to the analog pin.
side pins of the potentiometer go to +5V and ground
* LED connected from digital pin 9 to ground
created 29 Dec. 2008
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
*/
// 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() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
Serial.begin(9600);
}
void loop() {
// read the analog in value:
sensorValue = analogRead(analogInPin);
sensorValue = analogRead(analogInPin);
// 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:
analogWrite(analogOutPin, outputValue);
analogWrite(analogOutPin, outputValue);
// print the results to the serial monitor:
Serial.print("sensor = " );
Serial.print(sensorValue);
Serial.print("\t output = ");
Serial.println(outputValue);
Serial.print("sensor = " );
Serial.print(sensorValue);
Serial.print("\t output = ");
Serial.println(outputValue);
// wait 2 milliseconds before the next loop
// for the analog-to-digital converter to settle
// after the last reading:
delay(2);
delay(2);
}

View File

@ -1,10 +1,10 @@
/*
Analog Input
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 value obtained by analogRead().
the value obtained by analogRead().
The circuit:
* Potentiometer attached to analog input 0
* center pin of the potentiometer to the analog pin
@ -12,19 +12,19 @@
* the other side pin to +5V
* LED anode (long leg) attached to digital output 13
* 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.
Created by David Cuartielles
modified 30 Aug 2011
By Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/AnalogInput
*/
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() {
// declare the ledPin as an OUTPUT:
pinMode(ledPin, OUTPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
// read the value from the sensor:
sensorValue = analogRead(sensorPin);
sensorValue = analogRead(sensorPin);
// turn the ledPin on
digitalWrite(ledPin, HIGH);
digitalWrite(ledPin, HIGH);
// stop the program for <sensorValue> milliseconds:
delay(sensorValue);
// turn the ledPin off:
digitalWrite(ledPin, LOW);
delay(sensorValue);
// turn the ledPin off:
digitalWrite(ledPin, LOW);
// stop the program for for <sensorValue> milliseconds:
delay(sensorValue);
delay(sensorValue);
}

View File

@ -1,17 +1,17 @@
/*
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.
The circuit:
* LEDs attached from pins 2 through 13 to ground.
created 8 Feb 2009
by Tom Igoe
This example code is in the public domain.
*/
// These constants won't change. They're used to give names
// to the pins used:
@ -21,24 +21,24 @@ const int highestPin = 13;
void setup() {
// set pins 2 through 13 as outputs:
for (int thisPin =lowestPin; thisPin <= highestPin; thisPin++) {
pinMode(thisPin, OUTPUT);
for (int thisPin = lowestPin; thisPin <= highestPin; thisPin++) {
pinMode(thisPin, OUTPUT);
}
}
void loop() {
// 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:
for (int brightness = 0; brightness < 255; brightness++) {
analogWrite(thisPin, brightness);
delay(2);
}
}
// fade the LED on thisPin from brithstest to off:
for (int brightness = 255; brightness >= 0; brightness--) {
analogWrite(thisPin, brightness);
delay(2);
}
}
// pause between LEDs:
delay(100);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,11 +1,11 @@
/*
MIDI note player
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 circuit:
* digital in 1 connected to MIDI jack pin 5
* MIDI jack pin 2 connected to ground
@ -14,12 +14,12 @@
created 13 Jun 2006
modified 13 Aug 2012
by Tom Igoe
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Midi
*/
void setup() {
@ -34,7 +34,7 @@ void loop() {
noteOn(0x90, note, 0x45);
delay(100);
//Note on channel 1 (0x90), some note value (note), silent velocity (0x00):
noteOn(0x90, note, 0x00);
noteOn(0x90, note, 0x00);
delay(100);
}
}

View File

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

View File

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

View File

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

View File

@ -1,18 +1,18 @@
/*
Serial Call and Response
Language: Wiring/Arduino
This program sends an ASCII A (byte of value 65) on startup
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.
Thanks to Greg Shakar and Scott Fitzgerald for the improvements
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
Created 26 Sept. 2005
by Tom Igoe
modified 24 April 2012
@ -38,7 +38,7 @@ void setup()
}
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()
@ -48,17 +48,17 @@ void loop()
// get incoming byte:
inByte = Serial.read();
// 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(10);
// 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
thirdSensor = map(digitalRead(2), 0, 1, 0, 255);
thirdSensor = map(digitalRead(2), 0, 1, 0, 255);
// send sensor values:
Serial.write(firstSensor);
Serial.write(secondSensor);
Serial.write(thirdSensor);
Serial.write(thirdSensor);
}
}
@ -115,15 +115,15 @@ void serialEvent(Serial myPort) {
int inByte = myPort.read();
// if this is the first byte received, and it's an A,
// 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:
if (firstContact == false) {
if (inByte == 'A') {
if (inByte == 'A') {
myPort.clear(); // clear the serial port buffer
firstContact = true; // you've had first contact from the microcontroller
myPort.write('A'); // ask for more
}
}
}
}
else {
// Add the latest byte from the serial port to array:
serialInArray[serialCount] = inByte;

View File

@ -1,31 +1,31 @@
/*
Serial Call and Response in ASCII
Language: Wiring/Arduino
This program sends an ASCII A (byte of value 65) on startup
and repeats that until it gets some data in.
Then it waits for a byte in the serial port, and
sends three ASCII-encoded, comma-separated sensor values,
truncated by a linefeed and carriage return,
Then it waits for a byte in the serial port, and
sends three ASCII-encoded, comma-separated sensor values,
truncated by a linefeed and carriage return,
whenever it gets a byte in.
Thanks to Greg Shakar and Scott Fitzgerald for the improvements
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
Created 26 Sept. 2005
by Tom Igoe
modified 24 Apr 2012
by Tom Igoe and Scott Fitzgerald
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/SerialCallResponseASCII
*/
int firstSensor = 0; // first analog sensor
@ -41,9 +41,9 @@ void setup()
; // wait for serial port to connect. Needed for Leonardo only
}
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()
@ -57,13 +57,13 @@ void loop()
// read second analog input:
secondSensor = analogRead(A1);
// 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:
Serial.print(firstSensor);
Serial.print(",");
Serial.print(secondSensor);
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):
myPort.bufferUntil('\n');
// draw with smooth edges:
smooth();
}
@ -114,22 +114,22 @@ void draw() {
}
// 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():
void serialEvent(Serial myPort) {
void serialEvent(Serial myPort) {
// read the serial buffer:
String myString = myPort.readStringUntil('\n');
// if you got any bytes other than the linefeed:
myString = trim(myString);
// split the string at the commas
// and convert the sections into integers:
int sensors[] = int(split(myString, ','));
// print out the values you got:
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:
println();

View File

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

View File

@ -2,17 +2,17 @@
This example reads three analog sensors (potentiometers are easiest)
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.
The circuit:
* potentiometers attached to analog inputs 0, 1, and 2
http://www.arduino.cc/en/Tutorial/VirtualColorMixer
created 2 Dec 2006
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe and Scott Fitzgerald
This example code is in the public domain.
*/
@ -35,20 +35,20 @@ void loop()
}
/* Processing code for this example
// This example code is in the public domain.
import processing.serial.*;
float redValue = 0; // red value
float greenValue = 0; // green value
float blueValue = 0; // blue value
Serial myPort;
void setup() {
size(200, 200);
// List all the available serial ports
println(Serial.list());
// 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:
myPort.bufferUntil('\n');
}
void draw() {
// set the background color with the color values:
background(redValue, greenValue, blueValue);
}
void serialEvent(Serial myPort) {
void serialEvent(Serial myPort) {
// get the ASCII string:
String inString = myPort.readStringUntil('\n');
if (inString != null) {
// trim off any whitespace:
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:
float[] colors = float(split(inString, ","));
// if the array has at least three elements, you know
@ -126,5 +126,5 @@ ASi6Zyw8.RQi65J8ZsNx3ho93OhGWENtWpowepae4YhCFeLErOLENtXJrOSc
iadi39rf4hwc8xdhHz3gn3dBI7iDRlFe8huAfIZhq
-----------end_max5_patcher-----------
*/

View File

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

View File

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

View File

@ -1,30 +1,30 @@
/*
Conditionals - If statement
This example demonstrates the use of if() statements.
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
regardless of the level.
The circuit:
* potentiometer connected to analog pin 0.
Center pin of the potentiometer goes to the analog pin.
side pins of the potentiometer go to +5V and ground
* LED connected from digital pin 13 to ground
* 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.
created 17 Jan 2009
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/IfStatement
*/
// These constants won't change:
const int analogPin = A0; // pin that the sensor 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 (analogValue > threshold) {
digitalWrite(ledPin, HIGH);
}
}
else {
digitalWrite(ledPin,LOW);
digitalWrite(ledPin, LOW);
}
// print the analog value:

View File

@ -1,29 +1,29 @@
/*
Conditionals - while statement
This example demonstrates the use of while() statements.
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.
This is a variation on the calibrate example.
The circuit:
* photo resistor connected from +5V 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
* pushbutton attached from pin 2 to +5V
* 10K resistor attached from pin 2 to ground
created 17 Jan 2009
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/WhileLoop
*/
@ -50,10 +50,10 @@ void setup() {
void loop() {
// while the button is pressed, take calibration readings:
while (digitalRead(buttonPin) == HIGH) {
calibrate();
calibrate();
}
// signal the end of the calibration period
digitalWrite(indicatorLedPin, LOW);
digitalWrite(indicatorLedPin, LOW);
// read the sensor:
sensorValue = analogRead(sensorPin);

View File

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

View File

@ -1,66 +1,66 @@
/*
Switch statement with serial input
Demonstrates the use of a switch statement. The switch
statement allows you to choose from among a set of discrete values
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.
The characters a, b, c, d, and e, will turn on LEDs. Any other character will turn
the LEDs off.
The circuit:
* 5 LEDs attached to digital pins 2 through 6 through 220-ohm resistors
created 1 Jul 2009
by Tom Igoe
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/SwitchCase2
*/
void setup() {
// initialize serial communication:
Serial.begin(9600);
// initialize the LED pins:
for (int thisPin = 2; thisPin < 7; thisPin++) {
pinMode(thisPin, OUTPUT);
}
Serial.begin(9600);
// initialize the LED pins:
for (int thisPin = 2; thisPin < 7; thisPin++) {
pinMode(thisPin, OUTPUT);
}
}
void loop() {
// read the sensor:
if (Serial.available() > 0) {
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;
// 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:
switch (inByte) {
case 'a':
digitalWrite(2, HIGH);
break;
case 'b':
digitalWrite(3, HIGH);
break;
case 'c':
digitalWrite(4, HIGH);
break;
case 'd':
digitalWrite(5, HIGH);
break;
case 'e':
digitalWrite(6, HIGH);
break;
default:
// turn all the LEDs off:
for (int thisPin = 2; thisPin < 7; thisPin++) {
digitalWrite(thisPin, LOW);
}
}
case 'a':
digitalWrite(2, HIGH);
break;
case 'b':
digitalWrite(3, HIGH);
break;
case 'c':
digitalWrite(4, HIGH);
break;
case 'd':
digitalWrite(5, HIGH);
break;
case 'e':
digitalWrite(6, HIGH);
break;
default:
// turn all the LEDs off:
for (int thisPin = 2; thisPin < 7; thisPin++) {
digitalWrite(thisPin, LOW);
}
}
}
}

View File

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

View File

@ -1,26 +1,26 @@
/* Knock Sensor
This sketch reads a piezo element to detect a knocking sound.
It reads an analog pin and compares the result to a set threshold.
This sketch reads a piezo element to detect a knocking sound.
It reads an analog pin and compares the result to a set threshold.
If the result is greater than the threshold, it writes
"knock" to the serial port, and toggles the LED on pin 13.
The circuit:
* + connection of the piezo attached to analog in 0
* - connection of the piezo attached to ground
* 1-megohm resistor attached from analog in 0 to ground
http://www.arduino.cc/en/Tutorial/Knock
created 25 Mar 2007
by David Cuartielles <http://www.0j0.org>
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
*/
// these constants won't change:
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
void setup() {
pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
Serial.begin(9600); // use the serial port
pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
Serial.begin(9600); // use the serial port
}
void loop() {
// 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 (sensorReading >= threshold) {
// toggle the status of the ledPin:
ledState = !ledState;
// update the LED pin itself:
ledState = !ledState;
// update the LED pin itself:
digitalWrite(ledPin, ledState);
// 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
}

View File

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

View File

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

View File

@ -1,23 +1,23 @@
/*
Row-Column Scanning an 8x8 LED matrix with X-Y input
This example controls an 8x8 LED matrix using two analog inputs
created 27 May 2009
modified 30 Aug 2011
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
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
rows are the anodes
cols are the cathodes
---------
Pin numbers:
Matrix:
* Digital pins 2 through 13,
@ -25,25 +25,27 @@
Potentiometers:
* center pins are attached to analog pins 0 and 1, respectively
* side pins attached to +5V and ground, respectively.
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/RowColumnScanning
see also http://www.tigoe.net/pcomp/code/category/arduinowiring/514 for more
*/
// 2-dimensional array of row pin numbers:
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:
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:
int pixels[8][8];
int pixels[8][8];
// cursor position:
int x = 5;
@ -54,11 +56,11 @@ void setup() {
// iterate over the pins:
for (int thisPin = 0; thisPin < 8; thisPin++) {
// initialize the output pins:
pinMode(col[thisPin], OUTPUT);
pinMode(row[thisPin], OUTPUT);
pinMode(col[thisPin], OUTPUT);
pinMode(row[thisPin], OUTPUT);
// take the col pins (i.e. the cathodes) high to ensure that
// the LEDS are off:
digitalWrite(col[thisPin], HIGH);
// the LEDS are off:
digitalWrite(col[thisPin], HIGH);
}
// initialize the pixel matrix:

View File

@ -1,22 +1,22 @@
/*
LED bar graph
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
uses 10 LEDs, you can use any number by changing the LED count
and the pins in the array.
This method can be used to control any series of digital outputs that
depends on an analog input.
The circuit:
* LEDs from pins 2 through 11 to ground
created 4 Sep 2010
by Tom Igoe
by Tom Igoe
This example code is in the public domain.
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 ledCount = 10; // the number of LEDs in the bar graph
int ledPins[] = {
2, 3, 4, 5, 6, 7,8,9,10,11 }; // an array of pin numbers to which LEDs are attached
int ledPins[] = {
2, 3, 4, 5, 6, 7, 8, 9, 10, 11
}; // an array of pin numbers to which LEDs are attached
void setup() {
// loop over the pin array and set them all to output:
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:
if (thisLed < ledLevel) {
digitalWrite(ledPins[thisLed], HIGH);
}
}
// turn off all pins higher than the ledLevel:
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.
Send any byte and the sketch will tell you about it.
created 29 Nov 2010
modified 2 Apr 2012
by Tom Igoe
This example code is in the public domain.
*/
@ -35,40 +35,40 @@ void loop() {
Serial.println(thisChar);
// analyze what was sent:
if(isAlphaNumeric(thisChar)) {
if (isAlphaNumeric(thisChar)) {
Serial.println("it's alphanumeric");
}
if(isAlpha(thisChar)) {
if (isAlpha(thisChar)) {
Serial.println("it's alphabetic");
}
if(isAscii(thisChar)) {
if (isAscii(thisChar)) {
Serial.println("it's ASCII");
}
if(isWhitespace(thisChar)) {
if (isWhitespace(thisChar)) {
Serial.println("it's whitespace");
}
if(isControl(thisChar)) {
if (isControl(thisChar)) {
Serial.println("it's a control character");
}
if(isDigit(thisChar)) {
if (isDigit(thisChar)) {
Serial.println("it's a numeric digit");
}
if(isGraph(thisChar)) {
if (isGraph(thisChar)) {
Serial.println("it's a printable character that's not whitespace");
}
if(isLowerCase(thisChar)) {
if (isLowerCase(thisChar)) {
Serial.println("it's lower case");
}
if(isPrintable(thisChar)) {
if (isPrintable(thisChar)) {
Serial.println("it's printable");
}
if(isPunct(thisChar)) {
if (isPunct(thisChar)) {
Serial.println("it's punctuation");
}
if(isSpace(thisChar)) {
if (isSpace(thisChar)) {
Serial.println("it's a space character");
}
if(isUpperCase(thisChar)) {
if (isUpperCase(thisChar)) {
Serial.println("it's upper case");
}
if (isHexadecimalDigit(thisChar)) {

View File

@ -1,16 +1,16 @@
/*
Adding Strings together
Examples of how to add strings together
You can also add several different data types to string, as shown here:
created 27 July 2010
modified 2 Apr 2012
by Tom Igoe
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:
@ -59,10 +59,10 @@ void loop() {
// adding a variable long integer to a string:
long currentTime = millis();
stringOne="millis() value: ";
stringOne = "millis() value: ";
stringThree = stringOne + millis();
Serial.println(stringThree); // prints "The millis: 345345" or whatever value currentTime has
// do nothing while true:
while(true);
while (true);
}

View File

@ -1,14 +1,14 @@
/*
Appending to Strings using the += operator and concat()
Examples of how to append different data types to strings
created 27 July 2010
modified 2 Apr 2012
by Tom Igoe
http://arduino.cc/en/Tutorial/StringAppendOperator
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
// do nothing while true:
while(true);
while (true);
}

View File

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

View File

@ -1,14 +1,14 @@
/*
String charAt() and setCharAt()
Examples of how to get and set characters of a String
created 27 July 2010
modified 2 Apr 2012
by Tom Igoe
http://arduino.cc/en/Tutorial/StringCharacters
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:
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);
// add blank space:
Serial.println();
// you can alo set the character of a string. Change the : to a = character
reportString.setCharAt(13, '=');
reportString.setCharAt(13, '=');
Serial.println(reportString);
// 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
created 27 July 2010
modified 2 Apr 2012
by Tom Igoe
http://arduino.cc/en/Tutorial/StringComparisonOperators
This example code is in the public domain.
*/
@ -33,7 +33,7 @@ void setup() {
void loop() {
// two strings equal:
if (stringOne == "this") {
Serial.println("StringOne == \"this\"");
Serial.println("StringOne == \"this\"");
}
// two strings not equal:
if (stringOne != stringTwo) {
@ -49,7 +49,7 @@ void loop() {
// you can also use equals() to see if two strings are the same:
if (stringOne.equals(stringTwo)) {
Serial.println(stringOne + " equals " + stringTwo);
}
}
else {
Serial.println(stringOne + " does not equal " + stringTwo);
}
@ -57,7 +57,7 @@ void loop() {
// or perhaps you want to ignore case:
if (stringOne.equalsIgnoreCase(stringTwo)) {
Serial.println(stringOne + " equals (ignoring case) " + stringTwo);
}
}
else {
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:
stringOne = String("Brown");
if (stringOne < "Charles") {
Serial.println(stringOne + " < Charles");
Serial.println(stringOne + " < Charles");
}
if (stringOne > "Adams") {
Serial.println(stringOne + " > Adams");
Serial.println(stringOne + " > Adams");
}
if (stringOne <= "Browne") {
Serial.println(stringOne + " <= Browne");
Serial.println(stringOne + " <= Browne");
}
if (stringOne >= "Brow") {
Serial.println(stringOne + " >= Brow");
Serial.println(stringOne + " >= Brow");
}
// the compareTo() operator also allows you to compare strings
@ -104,10 +104,10 @@ void loop() {
stringOne = "Cucumber";
stringTwo = "Cucuracha";
if (stringOne.compareTo(stringTwo) < 0 ) {
Serial.println(stringOne + " comes before " + stringTwo);
}
Serial.println(stringOne + " comes before " + stringTwo);
}
else {
Serial.println(stringOne + " comes after " + stringTwo);
Serial.println(stringOne + " comes after " + stringTwo);
}
delay(10000); // because the next part is a loop:
@ -116,16 +116,16 @@ void loop() {
while (true) {
stringOne = "Sensor: ";
stringTwo= "Sensor: ";
stringTwo = "Sensor: ";
stringOne += analogRead(A0);
stringOne += analogRead(A0);
stringTwo += analogRead(A5);
if (stringOne.compareTo(stringTwo) < 0 ) {
Serial.println(stringOne + " comes before " + stringTwo);
}
Serial.println(stringOne + " comes before " + stringTwo);
}
else {
Serial.println(stringOne + " comes after " + stringTwo);
Serial.println(stringOne + " comes after " + stringTwo);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,14 +1,14 @@
/*
String startWith() and endsWith()
Examples of how to use startsWith() and endsWith() in a String
created 27 July 2010
modified 2 Apr 2012
by Tom Igoe
http://arduino.cc/en/Tutorial/StringStartsWithEndsWith
This example code is in the public domain.
*/
@ -29,27 +29,27 @@ void loop() {
String stringOne = "HTTP/1.1 200 OK";
Serial.println(stringOne);
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:
stringOne = "HTTP/1.1 200 OK";
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:
String sensorReading = "sensor = ";
sensorReading += analogRead(A0);
Serial.print (sensorReading);
if (sensorReading.endsWith(0)) {
Serial.println(". This reading is divisible by ten");
}
Serial.println(". This reading is divisible by ten");
}
else {
Serial.println(". This reading is not divisible by ten");
Serial.println(". This reading is not divisible by ten");
}
// do nothing while true:
while(true);
while (true);
}

View File

@ -1,14 +1,14 @@
/*
String substring()
Examples of how to use substring in a String
created 27 July 2010,
created 27 July 2010,
modified 2 Apr 2012
by Zach Eveland
http://arduino.cc/en/Tutorial/StringSubstring
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:
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:
if (stringOne.substring(14,18) == "text") {
Serial.println("It's a text-based file");
}
if (stringOne.substring(14, 18) == "text") {
Serial.println("It's a text-based file");
}
// do nothing while true:
while(true);
while (true);
}

View File

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

View File

@ -1,23 +1,23 @@
/*
Serial RGB controller
Reads a serial input string looking for three comma-separated
integers with a newline at the end. Values should be between
0 and 255. The sketch uses those values to set the color
integers with a newline at the end. Values should be between
0 and 255. The sketch uses those values to set the color
of an RGB LED attached to pins 9 - 11.
The circuit:
* Common-anode RGB LED cathodes attached to pins 9 - 11
* 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,
the lower the brightness.
created 29 Nov 2010
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
@ -52,9 +52,9 @@ void loop() {
}
if (isDigit(inChar)) {
// convert the incoming byte to a char
// convert the incoming byte to a char
// and add it to the string:
inString += (char)inChar;
inString += (char)inChar;
}
// if you get a comma, convert to a number,
@ -63,16 +63,16 @@ void loop() {
if (inChar == ',') {
// do something different for each value of currentColor:
switch (currentColor) {
case 0: // 0 = red
red = inString.toInt();
// clear the string for new input:
inString = "";
break;
case 1: // 1 = green:
green = inString.toInt();
// clear the string for new input:
inString = "";
break;
case 0: // 0 = red
red = inString.toInt();
// clear the string for new input:
inString = "";
break;
case 1: // 1 = green:
green = inString.toInt();
// clear the string for new input:
inString = "";
break;
}
currentColor++;
}
@ -98,7 +98,7 @@ void loop() {
Serial.println(blue);
// clear the string for new input:
inString = "";
inString = "";
// reset the color counter:
currentColor = 0;
}
@ -109,33 +109,33 @@ void loop() {
/*
Here's a Processing sketch that will draw a color wheel and send a serial
string with the color you click on:
// 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
//
// The primaries are red, yellow, and blue. The secondaries are green,
// purple, and orange. The tertiaries are yellow-orange, red-orange,
//
// The primaries are red, yellow, and blue. The secondaries are green,
// purple, and orange. The tertiaries are yellow-orange, red-orange,
// red-purple, blue-purple, blue-green, and yellow-green.
//
//
// Create a shade or tint of the subtractive color wheel using
// SHADE or TINT parameters.
// Updated 29 November 2010.
import processing.serial.*;
int segs = 12;
int steps = 6;
float rotAdjust = TWO_PI / segs / 2;
float radius;
float segWidth;
float interval = TWO_PI / segs;
Serial myPort;
void setup() {
size(200, 200);
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
radius = min(width, height) * 0.45;
segWidth = radius / steps;
// swap which line is commented out to draw the other version
// drawTintWheel();
drawShadeWheel();
// open the first serial port in your computer's list
myPort = new Serial(this, Serial.list()[0], 9600);
}
void drawShadeWheel() {
for (int j = 0; j < steps; j++) {
color[] cols = {
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/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, 0, 0),
color(255-(255/steps)*j, 0, (255/2)-((255/2)/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[] cols = {
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/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, 0, 0),
color(255-(255/steps)*j, 0, (255/2)-((255/2)/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(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, 0),
color(0, 255-(255/steps)*j, (255/2.5)-((255/2.5)/steps)*j),
color(0, 255-(255/steps)*j, 0),
color((255/2)-((255/2)/steps)*j, 255-(255/steps)*j, 0)
};
for (int i = 0; i < segs; 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);
}
radius -= segWidth;
}
}
void drawTintWheel() {
for (int j = 0; j < steps; j++) {
color[] cols = {
color((255/steps)*j, (255/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.5)/steps)*j, 0),
color((255/steps)*j, 0, 0),
color((255/steps)*j, 0, ((255/2)/steps)*j),
color((255/steps)*j, 0, (255/steps)*j),
color(((255/2)/steps)*j, 0, (255/steps)*j),
color[] cols = {
color((255/steps)*j, (255/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.5)/steps)*j, 0),
color((255/steps)*j, 0, 0),
color((255/steps)*j, 0, ((255/2)/steps)*j),
color((255/steps)*j, 0, (255/steps)*j),
color(((255/2)/steps)*j, 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, 0),
color(0, (255/steps)*j, ((255/2.5)/steps)*j),
color(0, (255/steps)*j, 0),
color(((255/2)/steps)*j, (255/steps)*j, 0)
};
for (int i = 0; i < segs; 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);
}
radius -= segWidth;
}
}
void draw() {
// nothing happens here
}
void mouseReleased() {
// get the color of the mouse position's pixel:
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:
myPort.write(colorString );
}
*/

View File

@ -1,30 +1,30 @@
/*
Keyboard logout
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:
On Windows, CTRL-ALT-DEL followed by ALT-l
On Ubuntu, CTRL-ALT-DEL, and ENTER
On OSX, CMD-SHIFT-q
To wake: Spacebar.
To wake: Spacebar.
Circuit:
* Arduino Leonardo or Micro
* wire to connect D2 to ground.
created 6 Mar 2012
modified 27 Mar 2012
by Tom Igoe
This example is in the public domain
http://www.arduino.cc/en/Tutorial/KeyboardLogout
*/
#define OSX 0
#define WINDOWS 1
#define UBUNTU 2
@ -33,13 +33,13 @@
int platform = OSX;
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
// connected to ground:
pinMode(2, INPUT_PULLUP);
Keyboard.begin();
}
void loop() {
while (digitalRead(2) == HIGH) {
// do nothing until pin 2 goes low
@ -48,43 +48,43 @@ void loop() {
delay(1000);
switch (platform) {
case OSX:
Keyboard.press(KEY_LEFT_GUI);
// Shift-Q logs out:
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.press('Q');
delay(100);
Keyboard.releaseAll();
// enter:
Keyboard.write(KEY_RETURN);
break;
case WINDOWS:
// CTRL-ALT-DEL:
Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press(KEY_DELETE);
delay(100);
Keyboard.releaseAll();
//ALT-s:
delay(2000);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press('l');
Keyboard.releaseAll();
break;
case UBUNTU:
// CTRL-ALT-DEL:
Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press(KEY_DELETE);
delay(1000);
Keyboard.releaseAll();
// Enter to confirm logout:
Keyboard.write(KEY_RETURN);
break;
case OSX:
Keyboard.press(KEY_LEFT_GUI);
// Shift-Q logs out:
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.press('Q');
delay(100);
Keyboard.releaseAll();
// enter:
Keyboard.write(KEY_RETURN);
break;
case WINDOWS:
// CTRL-ALT-DEL:
Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press(KEY_DELETE);
delay(100);
Keyboard.releaseAll();
//ALT-s:
delay(2000);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press('l');
Keyboard.releaseAll();
break;
case UBUNTU:
// CTRL-ALT-DEL:
Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press(KEY_DELETE);
delay(1000);
Keyboard.releaseAll();
// Enter to confirm logout:
Keyboard.write(KEY_RETURN);
break;
}
// do nothing:
while(true);
while (true);
}

View File

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

View File

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

View File

@ -1,21 +1,21 @@
/*
/*
Keyboard test
For the Arduino Leonardo, Micro or Due
Reads a byte from the serial port, sends a keystroke back.
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.
The circuit:
* none
created 21 Oct 2011
modified 27 Mar 2012
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/KeyboardSerial
*/
@ -32,7 +32,7 @@ void loop() {
// read incoming serial data:
char inChar = Serial.read();
// Type the next ASCII value from what you received:
Keyboard.write(inChar+1);
}
Keyboard.write(inChar + 1);
}
}

View File

@ -3,38 +3,38 @@
KeyboardAndMouseControl
Controls the mouse from five pushbuttons on an Arduino Leonardo, Micro or Due.
Hardware:
* 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.
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.
created 15 Mar 2012
modified 27 Mar 2012
by Tom Igoe
this code is in the public domain
*/
// set pin numbers for the five buttons:
const int upButton = 2;
const int downButton = 3;
const int upButton = 2;
const int downButton = 3;
const int leftButton = 4;
const int rightButton = 5;
const int mouseButton = 6;
void setup() { // initialize the buttons' inputs:
pinMode(upButton, INPUT);
pinMode(downButton, INPUT);
pinMode(leftButton, INPUT);
pinMode(rightButton, INPUT);
pinMode(upButton, INPUT);
pinMode(downButton, INPUT);
pinMode(leftButton, INPUT);
pinMode(rightButton, INPUT);
pinMode(mouseButton, INPUT);
Serial.begin(9600);
// initialize mouse control:
Mouse.begin();
@ -46,45 +46,45 @@ void loop() {
if (Serial.available() > 0) {
char inChar = Serial.read();
switch (inChar) {
case 'u':
// move mouse up
Mouse.move(0, -40);
break;
case 'd':
// move mouse down
Mouse.move(0, 40);
break;
case 'l':
// move mouse left
Mouse.move(-40, 0);
break;
case 'r':
// move mouse right
Mouse.move(40, 0);
break;
case 'm':
// perform mouse left click
Mouse.click(MOUSE_LEFT);
break;
switch (inChar) {
case 'u':
// move mouse up
Mouse.move(0, -40);
break;
case 'd':
// move mouse down
Mouse.move(0, 40);
break;
case 'l':
// move mouse left
Mouse.move(-40, 0);
break;
case 'r':
// move mouse right
Mouse.move(40, 0);
break;
case 'm':
// perform mouse left click
Mouse.click(MOUSE_LEFT);
break;
}
}
// use the pushbuttons to control the keyboard:
if (digitalRead(upButton) == HIGH) {
Keyboard.write('u');
Keyboard.write('u');
}
if (digitalRead(downButton) == HIGH) {
Keyboard.write('d');
Keyboard.write('d');
}
if (digitalRead(leftButton) == HIGH) {
Keyboard.write('l');
Keyboard.write('l');
}
if (digitalRead(rightButton) == HIGH) {
Keyboard.write('r');
Keyboard.write('r');
}
if (digitalRead(mouseButton) == HIGH) {
Keyboard.write('m');
Keyboard.write('m');
}
}

View File

@ -2,31 +2,31 @@
/*
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.
Hardware:
* 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.
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.
created 15 Mar 2012
modified 27 Mar 2012
by Tom Igoe
this code is in the public domain
*/
// set pin numbers for the five buttons:
const int upButton = 2;
const int downButton = 3;
const int upButton = 2;
const int downButton = 3;
const int leftButton = 4;
const int rightButton = 5;
const int mouseButton = 6;
@ -37,10 +37,10 @@ int responseDelay = 10; // response delay of the mouse, in ms
void setup() {
// initialize the buttons' inputs:
pinMode(upButton, INPUT);
pinMode(downButton, INPUT);
pinMode(leftButton, INPUT);
pinMode(rightButton, INPUT);
pinMode(upButton, INPUT);
pinMode(downButton, INPUT);
pinMode(leftButton, INPUT);
pinMode(rightButton, INPUT);
pinMode(mouseButton, INPUT);
// initialize mouse control:
Mouse.begin();
@ -55,8 +55,8 @@ void loop() {
int clickState = digitalRead(mouseButton);
// calculate the movement distance based on the button states:
int xDistance = (leftState - rightState)*range;
int yDistance = (upState - downState)*range;
int xDistance = (leftState - rightState) * range;
int yDistance = (upState - downState) * range;
// if X or Y is non-zero, move:
if ((xDistance != 0) || (yDistance != 0)) {
@ -67,14 +67,14 @@ void loop() {
if (clickState == HIGH) {
// if the mouse is not pressed, press it:
if (!Mouse.isPressed(MOUSE_LEFT)) {
Mouse.press(MOUSE_LEFT);
Mouse.press(MOUSE_LEFT);
}
}
}
// else the mouse button is not pressed:
else {
// if the mouse is pressed, release it:
if (Mouse.isPressed(MOUSE_LEFT)) {
Mouse.release(MOUSE_LEFT);
Mouse.release(MOUSE_LEFT);
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -1,34 +1,34 @@
/*
Arduino Starter Kit example
Project 5 - Servo Mood Indicator
This sketch is written to accompany Project 5 in the
Arduino Starter Kit
Parts required:
servo motor
10 kilohm potentiometer
servo motor
10 kilohm potentiometer
2 100 uF electrolytic capacitors
Created 13 September 2012
by Scott Fitzgerald
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 <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 potVal; // variable to read the value from the analog pin
int angle; // variable to hold the angle for the servo motor
int potVal; // variable to read the value from the analog pin
int angle; // variable to hold the angle for the servo motor
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
}
@ -38,17 +38,17 @@ void loop() {
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);
// print out the angle for the servo motor
// print out the angle for the servo motor
Serial.print(", angle: ");
Serial.println(angle);
Serial.println(angle);
// set the servo position
// set the servo position
myServo.write(angle);
// wait for the servo to get there
// wait for the servo to get there
delay(15);
}

View File

@ -1,21 +1,21 @@
/*
Arduino Starter Kit example
Project 6 - Light Theremin
This sketch is written to accompany Project 6 in the
Arduino Starter Kit
Parts required:
photoresistor
10 kilohm resistor
10 kilohm resistor
piezo
Created 13 September 2012
by Scott Fitzgerald
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

View File

@ -1,32 +1,32 @@
/*
Arduino Starter Kit example
Project 7 - Keyboard
This sketch is written to accompany Project 7 in the
Arduino Starter Kit
Parts required:
two 10 kilohm resistors
1 Megohm resistor
1 Megohm resistor
220 ohm resistor
4 pushbuttons
piezo
Created 13 September 2012
by Scott Fitzgerald
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
// the numbers below correspond to
// the numbers below correspond to
// the frequencies of middle C, D, E, and F
int notes[] = {262, 294, 330, 349};
void setup() {
//start serial communication
//start serial communication
Serial.begin(9600);
}
@ -35,27 +35,27 @@ void loop() {
int keyVal = analogRead(A0);
// send the value from A0 to the Serial Monitor
Serial.println(keyVal);
// 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
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
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
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
tone(8, notes[3]);
}
else{
else {
// if the value is out of range, play no tone
noTone(8);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,37 +1,37 @@
/*
Arduino Starter Kit example
Project 15 - Hacking Buttons
This sketch is written to accompany Project 15 in the
Arduino Starter Kit
Parts required:
batery powered component
220 ohm resistor
4N35 optocoupler
Created 18 September 2012
by Scott Fitzgerald
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
void setup(){
// make the pin with the optocoupler an output
void setup() {
// make the pin with the optocoupler an output
pinMode(optoPin, OUTPUT);
}
void loop(){
digitalWrite(optoPin, HIGH); // pull pin 2 HIGH, activating the optocoupler
delay(15); // give the optocoupler a moment to activate
digitalWrite(optoPin, LOW); // pull pin 2 low until you're ready to activate again
delay(21000); // wait for 21 seconds
void loop() {
digitalWrite(optoPin, HIGH); // pull pin 2 HIGH, activating the optocoupler
delay(15); // give the optocoupler a moment to activate
digitalWrite(optoPin, LOW); // pull pin 2 low until you're ready to activate again
delay(21000); // wait for 21 seconds
}

View File

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

View File

@ -2,18 +2,18 @@
Simple Audio Player
Demonstrates the use of the Audio library for the Arduino Due
Hardware required :
* 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
* A speaker to connect to the audio amplifier
* A speaker to connect to the audio amplifier
Original by Massimo Banzi September 20, 2012
Modified by Scott Fitzgerald October 19, 2012
This example code is in the public domain
http://arduino.cc/en/Tutorial/SimpleAudioPlayer
*/
@ -44,7 +44,7 @@ void setup()
void loop()
{
int count=0;
int count = 0;
// open wave file from sdcard
File myFile = SD.open("test.wav");
@ -54,7 +54,7 @@ void loop()
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];
Serial.print("Playing");

View File

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

View File

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

View File

@ -1,30 +1,30 @@
/*
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
it receives the character 'H', and turns off the LED when it
receives the character 'L'.
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
and typing
and typing
ssh root@ yourYunsName.local 'telnet localhost 6571'
then pressing enter. When prompted for the password, enter it.
The circuit:
* LED connected from digital pin 13 to ground
created 2006
by David A. Mellis
modified 25 Jun 2013
by Tom Igoe
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/ConsolePixel
*/
#include <Console.h>
@ -37,7 +37,7 @@ void setup() {
Console.begin(); // Initialize Console
// Wait for the Console port to connect
while(!Console);
while (!Console);
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 (incomingByte == 'H') {
digitalWrite(ledPin, HIGH);
}
}
// if it's an L (ASCII 76) turn off the LED:
if (incomingByte == 'L') {
digitalWrite(ledPin, LOW);

View File

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

View File

@ -1,21 +1,21 @@
/*
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.
The circuit:
* analog sensors on analog pins 0, 1 and 2
* SD card attached to SD card slot of the Arduino Yún
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
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
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
the system is writing to it.
created 24 Nov 2010
modified 9 Apr 2012
by Tom Igoe
@ -23,11 +23,11 @@
by Federico Vanzati
modified 21 Jun 2013
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/YunDatalogger
*/
#include <FileIO.h>
@ -38,7 +38,7 @@ void setup() {
Serial.begin(9600);
FileSystem.begin();
while(!Serial); // wait for Serial port to connect.
while (!Serial); // wait for Serial port to connect.
Serial.println("Filesystem datalogger\n");
}
@ -69,12 +69,12 @@ void loop () {
dataFile.close();
// print to the serial port too:
Serial.println(dataString);
}
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
}
delay(15000);
}
@ -83,19 +83,19 @@ void loop () {
String getTimeStamp() {
String result;
Process time;
// date is a command line utility to get the date and the time
// in different formats depending on the additional parameter
// date is a command line utility to get the date and the time
// in different formats depending on the additional parameter
time.begin("date");
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
// read the output of the command
while(time.available()>0) {
while (time.available() > 0) {
char c = time.read();
if(c != '\n')
if (c != '\n')
result += c;
}
return result;
}

View File

@ -1,18 +1,18 @@
/*
Write to file using FileIO classes.
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.
created 7 June 2010
by Cristian Maglie
by Cristian Maglie
This example code is in the public domain.
http://arduino.cc/en/Tutorial/FileWriteScript
*/
#include <FileIO.h>
void setup() {
@ -20,16 +20,16 @@ void setup() {
Bridge.begin();
// Initialize the Serial
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");
// Setup File IO
FileSystem.begin();
// Upload script used to gain network statistics
// Upload script used to gain network statistics
uploadScript();
}
}
void loop() {
// Run stats script every 5 secs.
@ -41,10 +41,10 @@ void loop() {
// to check the network traffic of the WiFi interface
void uploadScript() {
// 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
File script = FileSystem.open("/tmp/wlan-stats.sh", FILE_WRITE);
// Shell script header
// Shell script header
script.print("#!/bin/sh\n");
// shell commands:
// ifconfig: is a command line utility for controlling the network interfaces.
@ -53,7 +53,7 @@ void uploadScript() {
// and extract the line that contains it
script.print("ifconfig wlan0 | grep 'RX bytes'\n");
script.close(); // close the file
// Make the script executable
Process chmod;
chmod.begin("chmod"); // chmod: change mode
@ -69,9 +69,9 @@ void runScript() {
Process myscript;
myscript.begin("/tmp/wlan-stats.sh");
myscript.run();
String output = "";
// read the output of the script
while (myscript.available()) {
output += (char)myscript.read();

View File

@ -1,9 +1,9 @@
/*
Yun HTTP Client
This example for the Arduino Yún shows how create a basic
HTTP client that connects to the internet and downloads
content. In this case, you'll connect to the Arduino
This example for the Arduino Yún shows how create a basic
HTTP client that connects to the internet and downloads
content. In this case, you'll connect to the Arduino
website and download a version of the logo as ASCII text.
created by Tom igoe
@ -21,32 +21,32 @@
void setup() {
// Bridge takes about two seconds to start up
// 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);
digitalWrite(13, LOW);
Bridge.begin();
digitalWrite(13, HIGH);
Serial.begin(9600);
while(!Serial); // wait for a serial connection
while (!Serial); // wait for a serial connection
}
void loop() {
// Initialize the client library
HttpClient client;
// Make a HTTP request:
client.get("http://arduino.cc/asciilogo.txt");
// if there are incoming bytes available
// from the server, read them and print them:
// if there are incoming bytes available
// from the server, read them and print them:
while (client.available()) {
char c = client.read();
Serial.print(c);
}
Serial.flush();
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
using an Arduino Yún.
using an Arduino Yún.
created 5 Jun 2013
by Cristian Maglie
This example code is in the public domain.
http://arduino.cc/en/Tutorial/Process
*/
@ -18,10 +18,10 @@
void setup() {
// Initialize Bridge
Bridge.begin();
// Initialize Serial
Serial.begin(9600);
// Wait until a Serial Monitor is connected.
while (!Serial);
@ -44,7 +44,7 @@ void runCurl() {
// Print arduino logo over the Serial
// A process output can be read with the stream methods
while (p.available()>0) {
while (p.available() > 0) {
char c = p.read();
Serial.print(c);
}
@ -62,7 +62,7 @@ void runCpuInfo() {
// Print command output on the Serial.
// A process output can be read with the stream methods
while (p.available()>0) {
while (p.available() > 0) {
char c = p.read();
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
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.
Then it uses parseInt() to read the wifi signal strength as an integer,
and finally uses that number to fade an LED using analogWrite().
The circuit:
* Arduino Yun with LED connected to pin 9
created 12 Jun 2013
by Cristian Maglie
modified 25 June 2013
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/ShellCommands
*/
#include <Process.h>
@ -28,18 +28,18 @@ void setup() {
Serial.begin(9600); // Initialize the Serial
// Wait until a Serial Monitor is connected.
while(!Serial);
while (!Serial);
}
void loop() {
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
// "Signal:" the result is passed to this sketch:
p.runShellCommand("/usr/bin/pretty-wifi-info.lua | grep Signal");
// 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&":
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
analogWrite(9, signal); // set the brightness of LED on pin 9
Serial.println(result); // print the number as well
}
}
delay(5000); // wait 5 seconds before you do it again
}

View File

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

View File

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

View File

@ -1,27 +1,27 @@
/*
Spacebrew Range
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
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.
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.
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.
created 2013
by Julio Terra
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/
*/
#include <Bridge.h>
@ -34,53 +34,55 @@ SpacebrewYun sb = SpacebrewYun("spacebrewYun Range", "Range sender and receiver"
int last_value = 0;
// create variables to manage interval between each time we send a string
void setup() {
void setup() {
// start the serial port
Serial.begin(57600);
// start the serial port
Serial.begin(57600);
// for debugging, wait until a serial console is connected
delay(4000);
while (!Serial) { ; }
// for debugging, wait until a serial console is connected
delay(4000);
while (!Serial) {
;
}
// start-up the bridge
Bridge.begin();
// start-up the bridge
Bridge.begin();
// configure the spacebrew object to print status messages to serial
sb.verbose(true);
// configure the spacebrew object to print status messages to serial
sb.verbose(true);
// configure the spacebrew publisher and subscriber
sb.addPublish("physical pot", "range");
sb.addSubscribe("virtual pot", "range");
// configure the spacebrew publisher and subscriber
sb.addPublish("physical pot", "range");
sb.addSubscribe("virtual pot", "range");
// register the string message handler method
sb.onRangeMessage(handleRange);
// register the string message handler method
sb.onRangeMessage(handleRange);
// connect to cloud spacebrew server at "sandbox.spacebrew.cc"
sb.connect("sandbox.spacebrew.cc");
}
void loop() {
// monitor spacebrew connection for new data
sb.monitor();
// connected to spacebrew then send a new value whenever the pot value changes
if ( sb.connected() ) {
int cur_value = analogRead(A0);
if ( last_value != cur_value ) {
sb.send("physical pot", cur_value);
last_value = cur_value;
}
}
}
// handler method that is called whenever a new string message is received
void handleRange (String route, int value) {
// print the message that was received
Serial.print("From ");
Serial.print(route);
Serial.print(", received msg: ");
Serial.println(value);
// connect to cloud spacebrew server at "sandbox.spacebrew.cc"
sb.connect("sandbox.spacebrew.cc");
}
void loop() {
// monitor spacebrew connection for new data
sb.monitor();
// connected to spacebrew then send a new value whenever the pot value changes
if ( sb.connected() ) {
int cur_value = analogRead(A0);
if ( last_value != cur_value ) {
sb.send("physical pot", cur_value);
last_value = cur_value;
}
}
}
// handler method that is called whenever a new string message is received
void handleRange (String route, int value) {
// print the message that was received
Serial.print("From ");
Serial.print(route);
Serial.print(", received msg: ");
Serial.println(value);
}

View File

@ -1,24 +1,24 @@
/*
Spacebrew String
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.
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.
The circuit:
- No circuit required
created 2013
by Julio Terra
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/
*/
#include <Bridge.h>
@ -31,54 +31,56 @@ SpacebrewYun sb = SpacebrewYun("spacebrewYun Strings", "String sender and receiv
long last_time = 0;
int interval = 2000;
void setup() {
void setup() {
// start the serial port
Serial.begin(57600);
// start the serial port
Serial.begin(57600);
// for debugging, wait until a serial console is connected
delay(4000);
while (!Serial) { ; }
// for debugging, wait until a serial console is connected
delay(4000);
while (!Serial) {
;
}
// start-up the bridge
Bridge.begin();
// start-up the bridge
Bridge.begin();
// configure the spacebrew object to print status messages to serial
sb.verbose(true);
// configure the spacebrew object to print status messages to serial
sb.verbose(true);
// configure the spacebrew publisher and subscriber
sb.addPublish("speak", "string");
sb.addSubscribe("listen", "string");
// configure the spacebrew publisher and subscriber
sb.addPublish("speak", "string");
sb.addSubscribe("listen", "string");
// register the string message handler method
sb.onStringMessage(handleString);
// register the string message handler method
sb.onStringMessage(handleString);
// connect to cloud spacebrew server at "sandbox.spacebrew.cc"
sb.connect("sandbox.spacebrew.cc");
}
void loop() {
// monitor spacebrew connection for new data
sb.monitor();
// connected to spacebrew then send a string every 2 seconds
if ( sb.connected() ) {
// check if it is time to send a new message
if ( (millis() - last_time) > interval ) {
sb.send("speak", "is anybody out there?");
last_time = millis();
}
}
}
// handler method that is called whenever a new string message is received
void handleString (String route, String value) {
// print the message that was received
Serial.print("From ");
Serial.print(route);
Serial.print(", received msg: ");
Serial.println(value);
// connect to cloud spacebrew server at "sandbox.spacebrew.cc"
sb.connect("sandbox.spacebrew.cc");
}
void loop() {
// monitor spacebrew connection for new data
sb.monitor();
// connected to spacebrew then send a string every 2 seconds
if ( sb.connected() ) {
// check if it is time to send a new message
if ( (millis() - last_time) > interval ) {
sb.send("speak", "is anybody out there?");
last_time = millis();
}
}
}
// handler method that is called whenever a new string message is received
void handleString (String route, String value) {
// print the message that was received
Serial.print("From ");
Serial.print(route);
Serial.print(", received msg: ");
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
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
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
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.
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
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
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
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
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"
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:
https://www.twilio.com/user/account/phone-numbers/incoming
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
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.
@ -48,14 +48,14 @@
to the Internet.
Looking for another API? We've got over 100 in our Library!
This example code is in the public domain.
*/
#include <Bridge.h>
#include <Temboo.h>
#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)
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.
int LED_PIN = 13;
@ -98,7 +98,7 @@ void setup() {
// for debugging, wait until a serial console is connected
delay(4000);
while(!Serial);
while (!Serial);
// tell the board to treat the LED pin as an output.
pinMode(LED_PIN, OUTPUT);
@ -109,7 +109,7 @@ void setup() {
// initialize the connection to the Linino processor.
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.
Serial.println("Ignoring any existing control messages...");
checkForMessages(true);
@ -124,15 +124,15 @@ void loop()
// see if it's time to check for new SMS messages.
if (now - lastSMSCheckTime >= SMS_CHECK_PERIOD) {
// it's time to check for new messages
// save this time so we know when to check next
lastSMSCheckTime = now;
if (numRuns <= maxRuns) {
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);
} else {
Serial.println("Already ran " + String(maxRuns) + " times.");
@ -145,7 +145,7 @@ This function executes the Twilio > SMSMessages > ListMessages choreo
and processes the results.
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.
If ignoreCommands is 'false', control messages WILL be acted on.
@ -156,7 +156,7 @@ void checkForMessages(bool ignoreCommands) {
TembooChoreo ListMessagesChoreo;
ListMessagesChoreo.begin();
// set Temboo account credentials
ListMessagesChoreo.setAccountName(TEMBOO_ACCOUNT);
ListMessagesChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
@ -166,12 +166,12 @@ void checkForMessages(bool ignoreCommands) {
ListMessagesChoreo.setChoreo("/Library/Twilio/SMSMessages/ListMessages");
// 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
// the first input is a your Twilio AccountSID
ListMessagesChoreo.addInput("AccountSID", TWILIO_ACCOUNT_SID);
// next is your Twilio Auth Token
ListMessagesChoreo.addInput("AuthToken", TWILIO_AUTH_TOKEN);
@ -179,24 +179,24 @@ void checkForMessages(bool ignoreCommands) {
ListMessagesChoreo.addInput("From", FROM_PHONE_NUMBER);
// 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
// this account receives lots of messages in quick succession,
// we're only interested in the 3 most recent ones. Note that if
// this account receives lots of messages in quick succession,
// (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.
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.
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
ListMessagesChoreo.addOutputFilter("sid", "Sid", "Response");
ListMessagesChoreo.addOutputFilter("text", "Body", "Response");
// tell the Choreo to run and wait for the results. The
// return code (returnCode) will tell us whether the Temboo client
// tell the Choreo to run and wait for the results. The
// return code (returnCode) will tell us whether the Temboo client
// was able to send our request to the Temboo servers
unsigned int returnCode = ListMessagesChoreo.run();
@ -204,7 +204,7 @@ void checkForMessages(bool ignoreCommands) {
if (returnCode == 0) {
// Need a string to hold the list of message IDs.
String messageSids;
String messageSids;
// Need a string to hold the texts of the messages.
String messageTexts;
@ -214,8 +214,8 @@ void checkForMessages(bool ignoreCommands) {
// lists containing the Sids and texts of the messages
// from our designated phone number.
while(ListMessagesChoreo.available()) {
while (ListMessagesChoreo.available()) {
// output names are terminated with '\x1F' characters.
String name = ListMessagesChoreo.readStringUntil('\x1F');
name.trim();
@ -236,46 +236,46 @@ void checkForMessages(bool ignoreCommands) {
// done reading output, close the Choreo to free up resources.
ListMessagesChoreo.close();
// parse the comma delimited lists of messages and Sids
// parse the comma delimited lists of messages and Sids
processMessages(messageTexts, messageSids, ignoreCommands);
} else {
// a non-zero return code means there was an error
// read and print the error message
while(ListMessagesChoreo.available()) {
while (ListMessagesChoreo.available()) {
char c = ListMessagesChoreo.read();
Serial.print(c);
}
}
}
/*
/*
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
(") in the list. Example:
A message,"Hey, now",Another message text
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:
"Hi ""Sam"" the man", Led on
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.
'messageTexts' is a String containing a comma separated list of
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.
'ignoreCommands' is a boolean. 'true' means and control messages
will not be acted upon. 'false' means control messages will be
'ignoreCommands' is a boolean. 'true' means and control messages
will not be acted upon. 'false' means control messages will be
acted upon in the usual way.
*/
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
i = messageSids.indexOf(',', sidsStart);
if (i >= 0) {
//extract a single Sid from the list.
sid = messageSids.substring(sidsStart, i);
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
// quotes and commans in the message texts.
// quotes and commans in the message texts.
// The standard Arduino String class doesn't handle
// this, so we have to write our own function to do it.
i = quotedIndexOf(messageTexts, ',', textsStart);
@ -314,12 +314,12 @@ void processMessages(String messageTexts, String messageSids, bool ignoreCommand
text = messageTexts.substring(textsStart, i);
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.
ledUpdated = processMessage(sid, text, ignoreCommands);
}
} else {
// the last item in the lists won't have a comma at the end,
// so we have to handle them specially.
// 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
// or we run into a message we processed on a previous run.
} while ((i >=0) && (sid != lastSid));
// print what we've found to the serial monitor,
} while ((i >= 0) && (sid != lastSid));
// print what we've found to the serial monitor,
// just so we can see what's going on.
if (sid == lastSid) {
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.
(Case is ignored.)
If 'ignoreCommands' is true, the actions described above will NOT
take place.
If 'ignoreCommands' is true, the actions described above will NOT
take place.
It also updates the 'lastSid' global variable when
It also updates the 'lastSid' global variable when
a control message is processed.
It returns 'true' if the message was a control message, and
'false' if it wasn't or if we've already processed this message.
*/
bool processMessage(String sid, String text, bool ignoreCommands) {
// a flag to indicate whether this was a control message or not
bool ledUpdated = false;
@ -377,7 +377,7 @@ bool processMessage(String sid, String text, bool ignoreCommands) {
if (sid != lastSid) {
if (text.equalsIgnoreCase("LED ON")) {
if (!ignoreCommands) {
//turn on the LED
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 (ledUpdated)
if (ledUpdated)
lastSid = sid;
}
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
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 "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
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.
*/

View File

@ -1,26 +1,26 @@
/*
GetYahooWeatherReport
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
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
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
http://www.temboo.com
This example assumes basic familiarity with Arduino sketches, and that your Yun is connected
to the Internet.
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.
*/
#include <Bridge.h>
#include <Temboo.h>
#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
@ -32,10 +32,10 @@ int maxRuns = 10; // max number of times the Yahoo WeatherByAddress Choreo shou
void setup() {
Serial.begin(9600);
// for debugging, wait until a serial console is connected
delay(4000);
while(!Serial);
while (!Serial);
Bridge.begin();
}
@ -44,13 +44,13 @@ void loop()
{
// while we haven't reached the max number of runs...
if (numRuns <= maxRuns) {
// print status
Serial.println("Running GetWeatherByAddress - Run #" + String(numRuns++) + "...");
// create a TembooChoreo object to send a Choreo request to Temboo
TembooChoreo GetWeatherByAddressChoreo;
// invoke the Temboo client
GetWeatherByAddressChoreo.begin();
@ -58,30 +58,30 @@ void loop()
GetWeatherByAddressChoreo.setAccountName(TEMBOO_ACCOUNT);
GetWeatherByAddressChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
GetWeatherByAddressChoreo.setAppKey(TEMBOO_APP_KEY);
// set the name of the choreo we want to run
GetWeatherByAddressChoreo.setChoreo("/Library/Yahoo/Weather/GetWeatherByAddress");
// set choreo inputs; in this case, the address for which to retrieve weather data
// the Temboo client provides standardized calls to 100+ cloud APIs
GetWeatherByAddressChoreo.addInput("Address", ADDRESS_FOR_FORECAST);
// add an output filter to extract the name of the city.
GetWeatherByAddressChoreo.addOutputFilter("city", "/rss/channel/yweather:location/@city", "Response");
// add an output filter to extract the current temperature
GetWeatherByAddressChoreo.addOutputFilter("temperature", "/rss/channel/item/yweather:condition/@temp", "Response");
// add an output filter to extract the date and time of the last report.
GetWeatherByAddressChoreo.addOutputFilter("date", "/rss/channel/item/yweather:condition/@date", "Response");
// run the choreo
// run the choreo
GetWeatherByAddressChoreo.run();
// when the choreo results are available, print them to the serial monitor
while(GetWeatherByAddressChoreo.available()) {
char c = GetWeatherByAddressChoreo.read();
while (GetWeatherByAddressChoreo.available()) {
char c = GetWeatherByAddressChoreo.read();
Serial.print(c);
}
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
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 "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
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.
*/

View File

@ -1,33 +1,33 @@
/*
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.
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.
If you don't already have one, you can register for a free Temboo account at
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
http://www.temboo.com
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
app, you'll find OAuth credentials for that application under the "OAuth Tool" tab.
Substitute these values for the placeholders below.
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.
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.
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!
This example code is in the public domain.
*/
#include <Bridge.h>
#include <Temboo.h>
#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: ***/
@ -43,10 +43,10 @@ int maxRuns = 10; // the max number of times the Twitter HomeTimeline Choreo s
void setup() {
Serial.begin(9600);
// For debugging, wait until a serial console is connected.
delay(4000);
while(!Serial);
while (!Serial);
Bridge.begin();
}
void loop()
@ -54,14 +54,14 @@ void loop()
// while we haven't reached the max number of runs...
if (numRuns <= maxRuns) {
Serial.println("Running ReadATweet - Run #" + String(numRuns++));
TembooChoreo HomeTimelineChoreo;
// invoke the Temboo client.
// NOTE that the client must be reinvoked, and repopulated with
// appropriate arguments, each time its run() method is called.
HomeTimelineChoreo.begin();
// set Temboo account credentials
HomeTimelineChoreo.setAccountName(TEMBOO_ACCOUNT);
HomeTimelineChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
@ -69,8 +69,8 @@ void loop()
// tell the Temboo client which Choreo to run (Twitter > Timelines > HomeTimeline)
HomeTimelineChoreo.setChoreo("/Library/Twitter/Timelines/HomeTimeline");
// set the required choreo inputs
// see https://www.temboo.com/library/Library/Twitter/Timelines/HomeTimeline/
// 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("AccessToken", TWITTER_ACCESS_TOKEN);
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);
// 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.
// see the examples at http://www.temboo.com/arduino
// for more on using output filters
// we want the text of the tweet
HomeTimelineChoreo.addOutputFilter("tweet", "/[1]/text", "Response");
// and the name of the author
HomeTimelineChoreo.addOutputFilter("author", "/[1]/user/screen_name", "Response");
// tell the Process to run and wait for the results. The
// return code will tell us whether the Temboo client
// tell the Process to run and wait for the results. The
// return code will tell us whether the Temboo client
// was able to send our request to the Temboo servers
unsigned int returnCode = HomeTimelineChoreo.run();
// a response code of 0 means success; print the API response
if(returnCode == 0) {
// a response code of 0 means success; print the API response
if (returnCode == 0) {
String author; // a String to hold the tweet author's name
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:
// Name1\n\x1F
// Value1\n\x1E
// Name2\n\x1F
// Value2\n\x1E
// Value2\n\x1E
// see the examples at http://www.temboo.com/arduino for more details
// we can read this format into separate variables, as follows:
while(HomeTimelineChoreo.available()) {
while (HomeTimelineChoreo.available()) {
// read the name of the output item
String name = HomeTimelineChoreo.readStringUntil('\x1F');
name.trim();
@ -131,13 +131,13 @@ void loop()
author = data;
}
}
Serial.println("@" + author + " - " + tweet);
} else {
// there was an error
// print the raw output from the choreo
while(HomeTimelineChoreo.available()) {
while (HomeTimelineChoreo.available()) {
char c = HomeTimelineChoreo.read();
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
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 "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
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.
*/

View File

@ -5,30 +5,30 @@
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.
If you don't already have one, you can register for a free Temboo account at
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
http://www.temboo.com
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
read+write permissions. After creating the app, you'll find OAuth credentials
for that application under the "OAuth Tool" tab. Substitute these values for
the placeholders below.
read+write permissions. After creating the app, you'll find OAuth credentials
for that application under the "OAuth Tool" tab. Substitute these values for
the placeholders below.
This example assumes basic familiarity with Arduino sketches, and that your Yun 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!
This example code is in the public domain.
*/
#include <Bridge.h>
#include <Temboo.h>
#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: ***/
@ -48,7 +48,7 @@ void setup() {
// for debugging, wait until a serial console is connected
delay(4000);
while(!Serial);
while (!Serial);
Bridge.begin();
}
@ -59,18 +59,18 @@ void loop()
if (numRuns <= maxRuns) {
Serial.println("Running SendATweet - Run #" + String(numRuns++) + "...");
// define the text of the tweet we want to send
String tweetText("My Arduino Yun has been running for " + String(millis()) + " milliseconds.");
TembooChoreo StatusesUpdateChoreo;
// invoke the Temboo client
// NOTE that the client must be reinvoked, and repopulated with
// appropriate arguments, each time its run() method is called.
StatusesUpdateChoreo.begin();
// set Temboo account credentials
StatusesUpdateChoreo.setAccountName(TEMBOO_ACCOUNT);
StatusesUpdateChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
@ -80,26 +80,26 @@ void loop()
StatusesUpdateChoreo.setChoreo("/Library/Twitter/Tweets/StatusesUpdate");
// 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
// add the Twitter account information
StatusesUpdateChoreo.addInput("AccessToken", TWITTER_ACCESS_TOKEN);
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);
// and the tweet we want to send
StatusesUpdateChoreo.addInput("StatusUpdate", tweetText);
// tell the Process to run and wait for the results. The
// return code (returnCode) will tell us whether the Temboo client
// tell the Process to run and wait for the results. The
// return code (returnCode) will tell us whether the Temboo client
// was able to send our request to the Temboo servers
unsigned int returnCode = StatusesUpdateChoreo.run();
// a return code of zero (0) means everything worked
if (returnCode == 0) {
Serial.println("Success! Tweet sent!");
Serial.println("Success! Tweet sent!");
} else {
// a non-zero return code means there was an error
// read and print the error message
@ -107,7 +107,7 @@ void loop()
char c = StatusesUpdateChoreo.read();
Serial.print(c);
}
}
}
StatusesUpdateChoreo.close();
// 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
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 "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
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.
*/

View File

@ -5,17 +5,17 @@
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.
If you don't already have one, you can register for a free Temboo account at
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
http://www.temboo.com
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
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
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
to the Internet.
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.
@ -24,7 +24,7 @@
#include <Bridge.h>
#include <Temboo.h>
#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: ***/
@ -41,14 +41,14 @@ const String GMAIL_PASSWORD = "xxxxxxxxxx";
const String TO_EMAIL_ADDRESS = "xxxxxxxxxx";
// a flag to indicate whether we've tried to send the email yet or not
boolean attempted = false;
boolean attempted = false;
void setup() {
Serial.begin(9600);
// for debugging, wait until a serial console is connected
delay(4000);
while(!Serial);
while (!Serial);
Bridge.begin();
}
@ -59,14 +59,14 @@ void loop()
if (!attempted) {
Serial.println("Running SendAnEmail...");
TembooChoreo SendEmailChoreo;
// invoke the Temboo client
// NOTE that the client must be reinvoked, and repopulated with
// appropriate arguments, each time its run() method is called.
SendEmailChoreo.begin();
// set Temboo account credentials
SendEmailChoreo.setAccountName(TEMBOO_ACCOUNT);
SendEmailChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
@ -74,13 +74,13 @@ void loop()
// identify the Temboo Library choreo to run (Google > Gmail > SendEmail)
SendEmailChoreo.setChoreo("/Library/Google/Gmail/SendEmail");
// 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
// the first input is your Gmail email address.
// the first input is your Gmail email address.
SendEmailChoreo.addInput("Username", GMAIL_USER_NAME);
// next is your Gmail password.
SendEmailChoreo.addInput("Password", GMAIL_PASSWORD);
@ -89,17 +89,17 @@ void loop()
// then a subject line
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!");
// tell the Choreo to run and wait for the results. The
// return code (returnCode) will tell us whether the Temboo client
// tell the Choreo to run and wait for the results. The
// return code (returnCode) will tell us whether the Temboo client
// was able to send our request to the Temboo servers
unsigned int returnCode = SendEmailChoreo.run();
// a return code of zero (0) means everything worked
if (returnCode == 0) {
Serial.println("Success! Email sent!");
Serial.println("Success! Email sent!");
} else {
// a non-zero return code means there was an error
// read and print the error message
@ -107,9 +107,9 @@ void loop()
char c = SendEmailChoreo.read();
Serial.print(c);
}
}
}
SendEmailChoreo.close();
// set the flag showing we've tried
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
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 "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
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.
*/

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