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

Use consistent line wrapping in built-in example comments

This commit is contained in:
per1234 2017-07-14 12:34:00 -07:00 committed by Cristian Maglie
parent 2570383db9
commit 18b5327da0
60 changed files with 352 additions and 432 deletions

View File

@ -6,8 +6,9 @@
Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO
it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to
the correct LED pin independent of which board is used. the correct LED pin independent of which board is used.
If you want to know what pin the on-board LED is connected to on your Arduino model, check If you want to know what pin the on-board LED is connected to on your Arduino
the Technical Specs of your board at https://www.arduino.cc/en/Main/Products model, check the Technical Specs of your board at:
https://www.arduino.cc/en/Main/Products
modified 8 May 2014 modified 8 May 2014
by Scott Fitzgerald by Scott Fitzgerald

View File

@ -1,14 +1,12 @@
/* /*
Fade Fade
This example shows how to fade an LED on pin 9 This example shows how to fade an LED on pin 9 using the analogWrite()
using the analogWrite() function. function.
The analogWrite() function uses PWM, so if The analogWrite() function uses PWM, so if you want to change the pin you're
you want to change the pin you're using, be using, be sure to use another PWM capable pin. On most Arduino, the PWM pins
sure to use another PWM capable pin. On most are identified with a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.
Arduino, the PWM pins are identified with
a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.
This example code is in the public domain. This example code is in the public domain.

View File

@ -1,17 +1,18 @@
/* /*
Blink without Delay Blink without Delay
Turns on and off a light emitting diode (LED) connected to a digital Turns on and off a light emitting diode (LED) connected to a digital pin,
pin, without using the delay() function. This means that other code without using the delay() function. This means that other code can run at the
can run at the same time without being interrupted by the LED code. same time without being interrupted by the LED code.
The circuit: The circuit:
- Use the onboard LED. - Use the onboard LED.
- Note: Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO - Note: Most Arduinos have an on-board LED you can control. On the UNO, MEGA
it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to and ZERO it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN
the correct LED pin independent of which board is used. is set to the correct LED pin independent of which board is used.
If you want to know what pin the on-board LED is connected to on your Arduino model, check If you want to know what pin the on-board LED is connected to on your
the Technical Specs of your board at https://www.arduino.cc/en/Main/Products Arduino model, check the Technical Specs of your board at:
https://www.arduino.cc/en/Main/Products
created 2005 created 2005
by David A. Mellis by David A. Mellis
@ -48,10 +49,9 @@ void setup() {
void loop() { void loop() {
// here is where you'd put code that needs to be running all the time. // here is where you'd put code that needs to be running all the time.
// check to see if it's time to blink the LED; that is, if the // check to see if it's time to blink the LED; that is, if the difference
// difference between the current time and last time you blinked // between the current time and last time you blinked the LED is bigger than
// the LED is bigger than the interval at which you want to // the interval at which you want to blink the LED.
// blink the LED.
unsigned long currentMillis = millis(); unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) { if (currentMillis - previousMillis >= interval) {

View File

@ -1,8 +1,8 @@
/* /*
Button Button
Turns on and off a light emitting diode(LED) connected to digital Turns on and off a light emitting diode(LED) connected to digital pin 13,
pin 13, when pressing a pushbutton attached to pin 2. when pressing a pushbutton attached to pin 2.
The circuit: The circuit:
- LED attached from pin 13 to ground - LED attached from pin 13 to ground
@ -22,8 +22,7 @@
http://www.arduino.cc/en/Tutorial/Button http://www.arduino.cc/en/Tutorial/Button
*/ */
// constants won't change. They're used here to // constants won't change. They're used here to set pin numbers:
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin const int ledPin = 13; // the number of the LED pin
@ -41,8 +40,7 @@ void loop() {
// read the state of the pushbutton value: // read the state of the pushbutton value:
buttonState = digitalRead(buttonPin); buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) { if (buttonState == HIGH) {
// turn LED on: // turn LED on:
digitalWrite(ledPin, HIGH); digitalWrite(ledPin, HIGH);

View File

@ -2,17 +2,16 @@
Debounce Debounce
Each time the input pin goes from LOW to HIGH (e.g. because of a push-button Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
press), the output pin is toggled from LOW to HIGH or HIGH to LOW. There's press), the output pin is toggled from LOW to HIGH or HIGH to LOW. There's a
a minimum delay between toggles to debounce the circuit (i.e. to ignore minimum delay between toggles to debounce the circuit (i.e. to ignore noise).
noise).
The circuit: The circuit:
- LED attached from pin 13 to ground - LED attached from pin 13 to ground
- pushbutton attached from pin 2 to +5V - pushbutton attached from pin 2 to +5V
- 10 kilohm resistor attached from pin 2 to ground - 10 kilohm resistor attached from pin 2 to ground
- Note: On most Arduino boards, there is already an LED on the board - Note: On most Arduino boards, there is already an LED on the board connected
connected to pin 13, so you don't need any extra components for this example. to pin 13, so you don't need any extra components for this example.
created 21 Nov 2006 created 21 Nov 2006
by David A. Mellis by David A. Mellis
@ -28,8 +27,7 @@
http://www.arduino.cc/en/Tutorial/Debounce http://www.arduino.cc/en/Tutorial/Debounce
*/ */
// constants won't change. They're used here to // constants won't change. They're used here to set pin numbers:
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin const int ledPin = 13; // the number of the LED pin
@ -38,8 +36,8 @@ int ledState = HIGH; // the current state of the output pin
int buttonState; // the current reading from the input pin int buttonState; // the current reading from the input pin
int lastButtonState = LOW; // the previous reading from the input pin int lastButtonState = LOW; // the previous reading from the input pin
// the following variables are unsigned longs because the time, measured in milliseconds, // the following variables are unsigned longs because the time, measured in
// will quickly become a bigger number than can be stored in an int. // milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers
@ -56,8 +54,8 @@ void loop() {
int reading = digitalRead(buttonPin); int reading = digitalRead(buttonPin);
// check to see if you just pressed the button // check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited // (i.e. the input went from LOW to HIGH), and you've waited long enough
// long enough since the last press to ignore any noise: // since the last press to ignore any noise:
// If the switch changed, due to noise or pressing: // If the switch changed, due to noise or pressing:
if (reading != lastButtonState) { if (reading != lastButtonState) {
@ -66,8 +64,8 @@ void loop() {
} }
if ((millis() - lastDebounceTime) > debounceDelay) { if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer // whatever the reading is at, it's been there for longer than the debounce
// than the debounce delay, so take it as the actual current state: // delay, so take it as the actual current state:
// if the button state has changed: // if the button state has changed:
if (reading != buttonState) { if (reading != buttonState) {
@ -83,7 +81,6 @@ void loop() {
// set the LED: // set the LED:
digitalWrite(ledPin, ledState); digitalWrite(ledPin, ledState);
// save the reading. Next time through the loop, // save the reading. Next time through the loop, it'll be the lastButtonState:
// it'll be the lastButtonState:
lastButtonState = reading; lastButtonState = reading;
} }

View File

@ -1,16 +1,16 @@
/* /*
Input Pull-up Serial Input Pull-up 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
digital input on pin 2 and prints the results to the Serial Monitor. input on pin 2 and prints the results to the Serial Monitor.
The circuit: The circuit:
- momentary switch attached from pin 2 to ground - momentary switch attached from pin 2 to ground
- built-in LED on pin 13 - built-in LED on pin 13
Unlike pinMode(INPUT), there is no pull-down resistor necessary. An internal Unlike pinMode(INPUT), there is no pull-down resistor necessary. An internal
20K-ohm resistor is pulled to 5V. This configuration causes the input to 20K-ohm resistor is pulled to 5V. This configuration causes the input to read
read HIGH when the switch is open, and LOW when it is closed. HIGH when the switch is open, and LOW when it is closed.
created 14 Mar 2012 created 14 Mar 2012
by Scott Fitzgerald by Scott Fitzgerald
@ -35,9 +35,8 @@ void loop() {
//print out the value of the pushbutton //print out the value of the pushbutton
Serial.println(sensorVal); Serial.println(sensorVal);
// Keep in mind the pull-up means the pushbutton's // Keep in mind the pull-up means the pushbutton's logic is inverted. It goes
// logic is inverted. It goes HIGH when it's open, // HIGH when it's open, and LOW when it's pressed. Turn on pin 13 when the
// and LOW when it's pressed. Turn on pin 13 when the
// button's pressed, and off when it's not: // button's pressed, and off when it's not:
if (sensorVal == HIGH) { if (sensorVal == HIGH) {
digitalWrite(13, LOW); digitalWrite(13, LOW);

View File

@ -1,8 +1,8 @@
/* /*
State change detection (edge detection) State change detection (edge detection)
Often, you don't need to know the state of a digital input all the time, Often, you don't need to know the state of a digital input all the time, but
but you just need to know when the input changes from one state to another. you just need to know when the input changes from one state to another.
For example, you want to know when a button goes from OFF to ON. This is called For example, you want to know when a button goes from OFF to ON. This is called
state change detection, or edge detection. state change detection, or edge detection.
@ -12,8 +12,8 @@
The circuit: The circuit:
- pushbutton attached to pin 2 from +5V - pushbutton attached to pin 2 from +5V
- 10 kilohm resistor attached to pin 2 from ground - 10 kilohm resistor attached to pin 2 from ground
- LED attached from pin 13 to ground (or use the built-in LED on - LED attached from pin 13 to ground (or use the built-in LED on most
most Arduino boards) Arduino boards)
created 27 Sep 2005 created 27 Sep 2005
modified 30 Aug 2011 modified 30 Aug 2011
@ -51,29 +51,25 @@ void loop() {
if (buttonState != lastButtonState) { if (buttonState != lastButtonState) {
// if the state has changed, increment the counter // if the state has changed, increment the counter
if (buttonState == HIGH) { if (buttonState == HIGH) {
// if the current state is HIGH then the button // if the current state is HIGH then the button went from off to on:
// went from off to on:
buttonPushCounter++; buttonPushCounter++;
Serial.println("on"); Serial.println("on");
Serial.print("number of button pushes: "); Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter); Serial.println(buttonPushCounter);
} else { } else {
// if the current state is LOW then the button // if the current state is LOW then the button went from on to off:
// went from on to off:
Serial.println("off"); Serial.println("off");
} }
// Delay a little bit to avoid bouncing // Delay a little bit to avoid bouncing
delay(50); delay(50);
} }
// save the current state as the last state, // save the current state as the last state, for next time through the loop
// for next time through the loop
lastButtonState = buttonState; lastButtonState = buttonState;
// turns on the LED every four button pushes by // turns on the LED every four button pushes by checking the modulo of the
// checking the modulo of the button push counter. // button push counter. the modulo function gives you the remainder of the
// the modulo function gives you the remainder of // division of two numbers:
// the division of two numbers:
if (buttonPushCounter % 4 == 0) { if (buttonPushCounter % 4 == 0) {
digitalWrite(ledPin, HIGH); digitalWrite(ledPin, HIGH);
} else { } else {

View File

@ -31,8 +31,7 @@ void setup() {
// iterate over the notes of the melody: // iterate over the notes of the melody:
for (int thisNote = 0; thisNote < 8; thisNote++) { for (int thisNote = 0; thisNote < 8; thisNote++) {
// to calculate the note duration, take one second // to calculate the note duration, take one second divided by the note type.
// divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc. //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 1000 / noteDurations[thisNote]; int noteDuration = 1000 / noteDurations[thisNote];
tone(8, melody[thisNote], noteDuration); tone(8, melody[thisNote], noteDuration);

View File

@ -29,8 +29,8 @@ void loop() {
Serial.println(sensorReading); Serial.println(sensorReading);
// map the analog input range (in this case, 400 - 1000 from the photoresistor) // map the analog input range (in this case, 400 - 1000 from the photoresistor)
// to the output pitch range (120 - 1500Hz) // to the output pitch range (120 - 1500Hz)
// change the minimum and maximum input numbers below // change the minimum and maximum input numbers below depending on the range
// depending on the range your sensor's giving: // your sensor's giving:
int thisPitch = map(sensorReading, 400, 1000, 120, 1500); int thisPitch = map(sensorReading, 400, 1000, 120, 1500);
// play the pitch: // play the pitch:

View File

@ -1,8 +1,8 @@
/* /*
Analog input, analog output, serial output Analog input, analog output, serial output
Reads an analog input pin, maps the result to a range from 0 to 255 Reads an analog input pin, maps the result to a range from 0 to 255 and uses
and uses the result to set the pulse width modulation (PWM) of an output pin. the result to set the pulse width modulation (PWM) of an output pin.
Also prints the results to the Serial Monitor. Also prints the results to the Serial Monitor.
The circuit: The circuit:
@ -20,8 +20,7 @@
http://www.arduino.cc/en/Tutorial/AnalogInOutSerial http://www.arduino.cc/en/Tutorial/AnalogInOutSerial
*/ */
// These constants won't change. They're used to give names // These constants won't change. They're used to give names to the pins used:
// to the pins used:
const int analogInPin = A0; // Analog input pin that the potentiometer is attached to const int analogInPin = A0; // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; // Analog output pin that the LED is attached to const int analogOutPin = 9; // Analog output pin that the LED is attached to
@ -47,8 +46,7 @@ void loop() {
Serial.print("\t output = "); Serial.print("\t output = ");
Serial.println(outputValue); Serial.println(outputValue);
// wait 2 milliseconds before the next loop // wait 2 milliseconds before the next loop for the analog-to-digital
// for the analog-to-digital converter to settle // converter to settle after the last reading:
// after the last reading:
delay(2); delay(2);
} }

View File

@ -3,8 +3,8 @@
Demonstrates analog input by reading an analog sensor on analog pin 0 and Demonstrates analog input by reading an analog sensor on analog pin 0 and
turning on and off a light emitting diode(LED) connected to digital pin 13. turning on and off a light emitting diode(LED) connected to digital pin 13.
The amount of time the LED will be on and off depends on The amount of time the LED will be on and off depends on the value obtained
the value obtained by analogRead(). by analogRead().
The circuit: The circuit:
- potentiometer - potentiometer
@ -15,8 +15,8 @@
anode (long leg) attached to digital output 13 anode (long leg) attached to digital output 13
cathode (short leg) attached to ground 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
to pin 13 on the board, the LED is optional. board, the LED is optional.
created by David Cuartielles created by David Cuartielles
modified 30 Aug 2011 modified 30 Aug 2011

View File

@ -15,8 +15,7 @@
http://www.arduino.cc/en/Tutorial/AnalogWriteMega http://www.arduino.cc/en/Tutorial/AnalogWriteMega
*/ */
// These constants won't change. They're used to give names // These constants won't change. They're used to give names to the pins used:
// to the pins used:
const int lowestPin = 2; const int lowestPin = 2;
const int highestPin = 13; const int highestPin = 13;

View File

@ -1,15 +1,14 @@
/* /*
Calibration Calibration
Demonstrates one technique for calibrating sensor input. The Demonstrates one technique for calibrating sensor input. The sensor readings
sensor readings during the first five seconds of the sketch during the first five seconds of the sketch execution define the minimum and
execution define the minimum and maximum of expected values maximum of expected values attached to the sensor pin.
attached to the sensor pin.
The sensor minimum and maximum initial values may seem backwards. The sensor minimum and maximum initial values may seem backwards. Initially,
Initially, you set the minimum high and listen for anything you set the minimum high and listen for anything lower, saving it as the new
lower, saving it as the new minimum. Likewise, you set the minimum. Likewise, you set the maximum low and listen for anything higher as
maximum low and listen for anything higher as the new maximum. the new maximum.
The circuit: The circuit:
- analog sensor (potentiometer will do) attached to analog input 0 - analog sensor (potentiometer will do) attached to analog input 0

View File

@ -1,9 +1,9 @@
/* /*
Smoothing Smoothing
Reads repeatedly from an analog input, calculating a running average Reads repeatedly from an analog input, calculating a running average and
and printing it to the computer. Keeps ten readings in an array and printing it to the computer. Keeps ten readings in an array and continually
continually averages them. averages them.
The circuit: The circuit:
- analog sensor (potentiometer will do) attached to analog input 0 - analog sensor (potentiometer will do) attached to analog input 0
@ -18,10 +18,10 @@
http://www.arduino.cc/en/Tutorial/Smoothing http://www.arduino.cc/en/Tutorial/Smoothing
*/ */
// Define the number of samples to keep track of. The higher the number, // Define the number of samples to keep track of. The higher the number, the
// the more the readings will be smoothed, but the slower the output will // more the readings will be smoothed, but the slower the output will respond to
// respond to the input. Using a constant rather than a normal variable lets // the input. Using a constant rather than a normal variable lets us use this
// us use this value to determine the size of the readings array. // value to determine the size of the readings array.
const int numReadings = 10; const int numReadings = 10;
int readings[numReadings]; // the readings from the analog input int readings[numReadings]; // the readings from the analog input

View File

@ -37,9 +37,9 @@ int thisByte = 33;
// int thisByte = '!'; // int thisByte = '!';
void loop() { void loop() {
// prints value unaltered, i.e. the raw binary version of the // prints value unaltered, i.e. the raw binary version of the byte.
// byte. The Serial Monitor interprets all bytes as // The Serial Monitor interprets all bytes as ASCII, so 33, the first number,
// ASCII, so 33, the first number, will show up as '!' // will show up as '!'
Serial.write(thisByte); Serial.write(thisByte);
Serial.print(", dec: "); Serial.print(", dec: ");
@ -62,8 +62,7 @@ void loop() {
Serial.print(thisByte, OCT); Serial.print(thisByte, OCT);
Serial.print(", bin: "); Serial.print(", bin: ");
// prints value as string in binary (base 2) // prints value as string in binary (base 2) also prints ending line break:
// also prints ending line break:
Serial.println(thisByte, BIN); Serial.println(thisByte, BIN);
// if printed last visible character '~' or 126, stop: // if printed last visible character '~' or 126, stop:

View File

@ -1,10 +1,10 @@
/* /*
Dimmer Dimmer
Demonstrates sending data from the computer to the Arduino board, Demonstrates sending data from the computer to the Arduino board, in this case
in this case to control the brightness of an LED. The data is sent to control the brightness of an LED. The data is sent in individual bytes,
in individual bytes, each of which ranges from 0 to 255. Arduino each of which ranges from 0 to 255. Arduino reads these bytes and uses them to
reads these bytes and uses them to set the brightness of the LED. set the brightness of the LED.
The circuit: The circuit:
- LED attached from digital pin 9 to ground. - LED attached from digital pin 9 to ground.
@ -56,15 +56,14 @@ void loop() {
// if using Processing 2.1 or later, use Serial.printArray() // if using Processing 2.1 or later, use Serial.printArray()
println(Serial.list()); println(Serial.list());
// Uses the first port in this list (number 0). Change this to // Uses the first port in this list (number 0). Change this to select the port
// select the port corresponding to your Arduino board. The last // corresponding to your Arduino board. The last parameter (e.g. 9600) is the
// parameter (e.g. 9600) is the speed of the communication. It // speed of the communication. It has to correspond to the value passed to
// has to correspond to the value passed to Serial.begin() in your // Serial.begin() in your Arduino sketch.
// Arduino sketch.
port = new Serial(this, Serial.list()[0], 9600); port = new Serial(this, Serial.list()[0], 9600);
// If you know the name of the port used by the Arduino board, you // If you know the name of the port used by the Arduino board, you can specify
// can specify it directly like this. // it directly like this.
//port = new Serial(this, "COM1", 9600); //port = new Serial(this, "COM1", 9600);
} }

View File

@ -1,17 +1,16 @@
/* /*
Graph Graph
A simple example of communication from the Arduino board to the computer: A simple example of communication from the Arduino board to the computer: The
the value of analog input 0 is sent out the serial port. We call this "serial" value of analog input 0 is sent out the serial port. We call this "serial"
communication because the connection appears to both the Arduino and the communication because the connection appears to both the Arduino and the
computer as a serial port, even though it may actually use computer as a serial port, even though it may actually use a USB cable. Bytes
a USB cable. Bytes are sent one after another (serially) from the Arduino are sent one after another (serially) from the Arduino to the computer.
to the computer.
You can use the Arduino Serial Monitor to view the sent data, or it can You can use the Arduino Serial Monitor to view the sent data, or it can be
be read by Processing, PD, Max/MSP, or any other program capable of reading read by Processing, PD, Max/MSP, or any other program capable of reading data
data from a serial port. The Processing code below graphs the data received from a serial port. The Processing code below graphs the data received so you
so you can see the value of the analog input changing over time. can see the value of the analog input changing over time.
The circuit: The circuit:
- any analog input sensor attached to analog in pin 0 - any analog input sensor attached to analog in pin 0
@ -34,8 +33,8 @@ void setup() {
void loop() { void loop() {
// send the value of analog input 0: // send the value of analog input 0:
Serial.println(analogRead(A0)); Serial.println(analogRead(A0));
// wait a bit for the analog-to-digital converter // wait a bit for the analog-to-digital converter to stabilize after the last
// to stabilize after the last reading: // reading:
delay(2); delay(2);
} }
@ -44,9 +43,9 @@ void loop() {
// Graphing sketch // Graphing sketch
// This program takes ASCII-encoded strings // This program takes ASCII-encoded strings from the serial port at 9600 baud
// from the serial port at 9600 baud and graphs them. It expects values in the // and graphs them. It expects values in the range 0 to 1023, followed by a
// range 0 to 1023, followed by a newline, or newline and carriage return // newline, or newline and carriage return
// Created 20 Apr 2005 // Created 20 Apr 2005
// Updated 24 Nov 2015 // Updated 24 Nov 2015
@ -67,8 +66,8 @@ void loop() {
// if using Processing 2.1 or later, use Serial.printArray() // if using Processing 2.1 or later, use Serial.printArray()
println(Serial.list()); println(Serial.list());
// I know that the first port in the serial list on my Mac // I know that the first port in the serial list on my Mac is always my
// is always my Arduino, so I open Serial.list()[0]. // Arduino, so I open Serial.list()[0].
// Open whatever port is the one you're using. // Open whatever port is the one you're using.
myPort = new Serial(this, Serial.list()[0], 9600); myPort = new Serial(this, Serial.list()[0], 9600);

View File

@ -2,8 +2,8 @@
MIDI note player MIDI note player
This sketch shows how to use the serial transmit pin (pin 1) to send MIDI note data. This sketch shows how to use the serial transmit pin (pin 1) to send MIDI note data.
If this circuit is connected to a MIDI synth, it will play If this circuit is connected to a MIDI synth, it will play the notes
the notes F#-0 (0x1E) to F#-5 (0x5A) in sequence. F#-0 (0x1E) to F#-5 (0x5A) in sequence.
The circuit: The circuit:
- digital in 1 connected to MIDI jack pin 5 - digital in 1 connected to MIDI jack pin 5
@ -37,8 +37,8 @@ void loop() {
} }
} }
// plays a MIDI note. Doesn't check to see that // plays a MIDI note. Doesn't check to see that cmd is greater than 127, or that
// cmd is greater than 127, or that data values are less than 127: // data values are less than 127:
void noteOn(int cmd, int pitch, int velocity) { void noteOn(int cmd, int pitch, int velocity) {
Serial.write(cmd); Serial.write(cmd);
Serial.write(pitch); Serial.write(pitch);

View File

@ -1,14 +1,12 @@
/* /*
Physical Pixel Physical Pixel
An example of using the Arduino board to receive data from the An example of using the Arduino board to receive data from the computer. In
computer. In this case, the Arduino boards turns on an LED when this case, the Arduino boards turns on an LED when it receives the character
it receives the character 'H', and turns off the LED when it 'H', and turns off the LED when it receives the character 'L'.
receives the character 'L'.
The data can be sent from the Arduino Serial Monitor, or another The data can be sent from the Arduino Serial Monitor, or another program like
program like Processing (see code below), Flash (via a serial-net Processing (see code below), Flash (via a serial-net proxy), PD, or Max/MSP.
proxy), PD, or Max/MSP.
The circuit: The circuit:
- LED connected from digital pin 13 to ground - LED connected from digital pin 13 to ground
@ -53,9 +51,8 @@ void loop() {
// mouse over serial // mouse over serial
// Demonstrates how to send data to the Arduino I/O board, in order to // Demonstrates how to send data to the Arduino I/O board, in order to turn ON
// turn ON a light if the mouse is over a square and turn it off // a light if the mouse is over a square and turn it off if the mouse is not.
// if the mouse is not.
// created 2003-4 // created 2003-4
// based on examples by Casey Reas and Hernando Barragan // based on examples by Casey Reas and Hernando Barragan
@ -81,9 +78,9 @@ void loop() {
rectMode(RADIUS); rectMode(RADIUS);
// List all the available serial ports in the output pane. // List all the available serial ports in the output pane.
// You will need to choose the port that the Arduino board is // You will need to choose the port that the Arduino board is connected to
// connected to from this list. The first port in the list is // from this list. The first port in the list is port #0 and the third port
// port #0 and the third port in the list is port #2. // in the list is port #2.
// if using Processing 2.1 or later, use Serial.printArray() // if using Processing 2.1 or later, use Serial.printArray()
println(Serial.list()); println(Serial.list());

View File

@ -45,8 +45,7 @@ void loop() {
// do it again: // do it again:
int blue = Serial.parseInt(); int blue = Serial.parseInt();
// look for the newline. That's the end of your // look for the newline. That's the end of your sentence:
// sentence:
if (Serial.read() == '\n') { if (Serial.read() == '\n') {
// constrain the values to 0 - 255 and invert // constrain the values to 0 - 255 and invert
// if you're using a common-cathode LED, just use "constrain(color, 0, 255);" // if you're using a common-cathode LED, just use "constrain(color, 0, 255);"

View File

@ -2,9 +2,8 @@
Serial Call and Response Serial Call and Response
Language: Wiring/Arduino Language: Wiring/Arduino
This program sends an ASCII A (byte of value 65) on startup This program sends an ASCII A (byte of value 65) on startup and repeats that
and repeats that until it gets some data in. until it gets some data in. Then it waits for a byte in the serial port, and
Then it waits for a byte in the serial port, and
sends three sensor values whenever it gets a byte in. sends three sensor values whenever it gets a byte in.
The circuit: The circuit:
@ -92,8 +91,8 @@ void establishContact() {
// if using Processing 2.1 or later, use Serial.printArray() // if using Processing 2.1 or later, use Serial.printArray()
println(Serial.list()); println(Serial.list());
// I know that the first port in the serial list on my Mac // I know that the first port in the serial list on my Mac is always my FTDI
// is always my FTDI adaptor, so I open Serial.list()[0]. // adaptor, so I open Serial.list()[0].
// On Windows machines, this generally opens COM1. // On Windows machines, this generally opens COM1.
// Open whatever port is the one you're using. // Open whatever port is the one you're using.
String portName = Serial.list()[0]; String portName = Serial.list()[0];
@ -110,9 +109,8 @@ void establishContact() {
void serialEvent(Serial myPort) { void serialEvent(Serial myPort) {
// read a byte from the serial port: // read a byte from the serial port:
int inByte = myPort.read(); int inByte = myPort.read();
// if this is the first byte received, and it's an A, // if this is the first byte received, and it's an A, clear the serial
// clear the serial buffer and note that you've // buffer and note that you've had first contact from the microcontroller.
// had first contact from the microcontroller.
// Otherwise, add the incoming byte to the array: // Otherwise, add the incoming byte to the array:
if (firstContact == false) { if (firstContact == false) {
if (inByte == 'A') { if (inByte == 'A') {

View File

@ -2,12 +2,10 @@
Serial Call and Response in ASCII Serial Call and Response in ASCII
Language: Wiring/Arduino Language: Wiring/Arduino
This program sends an ASCII A (byte of value 65) on startup This program sends an ASCII A (byte of value 65) on startup and repeats that
and repeats that until it gets some data in. until it gets some data in. Then it waits for a byte in the serial port, and
Then it waits for a byte in the serial port, and sends three ASCII-encoded, comma-separated sensor values, truncated by a
sends three ASCII-encoded, comma-separated sensor values, linefeed and carriage return, whenever it gets a byte in.
truncated by a linefeed and carriage return,
whenever it gets a byte in.
The circuit: The circuit:
- potentiometers attached to analog inputs 0 and 1 - potentiometers attached to analog inputs 0 and 1
@ -88,10 +86,10 @@ void establishContact() {
// if using Processing 2.1 or later, use Serial.printArray() // if using Processing 2.1 or later, use Serial.printArray()
println(Serial.list()); println(Serial.list());
// I know that the first port in the serial list on my Mac // I know that the first port in the serial list on my Mac is always my
// is always my Arduino board, so I open Serial.list()[0]. // Arduino board, so I open Serial.list()[0].
// Change the 0 to the appropriate number of the serial port // Change the 0 to the appropriate number of the serial port that your
// that your microcontroller is attached to. // microcontroller is attached to.
myPort = new Serial(this, Serial.list()[0], 9600); myPort = new Serial(this, Serial.list()[0], 9600);
// read bytes into a buffer until you get a linefeed (ASCII 10): // read bytes into a buffer until you get a linefeed (ASCII 10):
@ -108,8 +106,8 @@ void establishContact() {
ellipse(xpos, ypos, 20, 20); ellipse(xpos, ypos, 20, 20);
} }
// serialEvent method is run automatically by the Processing applet // serialEvent method is run automatically by the Processing applet whenever
// whenever the buffer reaches the byte value set in the bufferUntil() // the buffer reaches the byte value set in the bufferUntil()
// method in the setup(): // method in the setup():
void serialEvent(Serial myPort) { void serialEvent(Serial myPort) {
@ -118,8 +116,7 @@ void establishContact() {
// if you got any bytes other than the linefeed: // if you got any bytes other than the linefeed:
myString = trim(myString); myString = trim(myString);
// split the string at the commas // split the string at the commas and convert the sections into integers:
// and convert the sections into integers:
int sensors[] = int(split(myString, ',')); int sensors[] = int(split(myString, ','));
// print out the values you got: // print out the values you got:

View File

@ -2,14 +2,13 @@
Serial Event example Serial Event example
When new serial data arrives, this sketch adds it to a String. When new serial data arrives, this sketch adds it to a String.
When a newline is received, the loop prints the string and When a newline is received, the loop prints the string and clears it.
clears it.
A good test for this is to try it with a GPS receiver A good test for this is to try it with a GPS receiver that sends out
that sends out NMEA 0183 sentences. NMEA 0183 sentences.
NOTE: The serialEvent() feature is not available on the NOTE: The serialEvent() feature is not available on the Leonardo, Micro, or
Leonardo, Micro, or other ATmega32U4 based boards. other ATmega32U4 based boards.
created 9 May 2011 created 9 May 2011
by Tom Igoe by Tom Igoe
@ -40,10 +39,9 @@ void loop() {
} }
/* /*
SerialEvent occurs whenever a new data comes in the SerialEvent occurs whenever a new data comes in the hardware serial RX. This
hardware serial RX. This routine is run between each routine is run between each time loop() runs, so using delay inside loop can
time loop() runs, so using delay inside loop can delay delay response. Multiple bytes of data may be available.
response. Multiple bytes of data may be available.
*/ */
void serialEvent() { void serialEvent() {
while (Serial.available()) { while (Serial.available()) {
@ -51,8 +49,8 @@ void serialEvent() {
char inChar = (char)Serial.read(); char inChar = (char)Serial.read();
// add it to the inputString: // add it to the inputString:
inputString += inChar; inputString += inChar;
// if the incoming character is a newline, set a flag // if the incoming character is a newline, set a flag so the main loop can
// so the main loop can do something about it: // do something about it:
if (inChar == '\n') { if (inChar == '\n') {
stringComplete = true; stringComplete = true;
} }

View File

@ -1,23 +1,22 @@
/* /*
SerialPassthrough sketch SerialPassthrough sketch
Some boards, like the Arduino 101, the MKR1000, Zero, or the Micro, Some boards, like the Arduino 101, the MKR1000, Zero, or the Micro, have one
have one hardware serial port attached to Digital pins 0-1, and a hardware serial port attached to Digital pins 0-1, and a separate USB serial
separate USB serial port attached to the IDE Serial Monitor. port attached to the IDE Serial Monitor. This means that the "serial
This means that the "serial passthrough" which is possible with passthrough" which is possible with the Arduino UNO (commonly used to interact
the Arduino UNO (commonly used to interact with devices/shields that with devices/shields that require configuration via serial AT commands) will
require configuration via serial AT commands) will not work by default. not work by default.
This sketch allows you to emulate the serial passthrough behaviour. This sketch allows you to emulate the serial passthrough behaviour. Any text
Any text you type in the IDE Serial monitor will be written you type in the IDE Serial monitor will be written out to the serial port on
out to the serial port on Digital pins 0 and 1, and vice-versa. Digital pins 0 and 1, and vice-versa.
On the 101, MKR1000, Zero, and Micro, "Serial" refers to the USB Serial port On the 101, MKR1000, Zero, and Micro, "Serial" refers to the USB Serial port
attached to the Serial Monitor, and "Serial1" refers to the hardware attached to the Serial Monitor, and "Serial1" refers to the hardware serial
serial port attached to pins 0 and 1. This sketch will emulate Serial passthrough port attached to pins 0 and 1. This sketch will emulate Serial passthrough
using those two Serial ports on the boards mentioned above, using those two Serial ports on the boards mentioned above, but you can change
but you can change these names to connect any two serial ports on a board these names to connect any two serial ports on a board that has multiple ports.
that has multiple ports.
created 23 May 2016 created 23 May 2016
by Erik Nyquist by Erik Nyquist

View File

@ -1,7 +1,7 @@
/* /*
This example reads three analog sensors (potentiometers are easiest) This example reads three analog sensors (potentiometers are easiest) and sends
and sends their values serially. The Processing and Max/MSP programs at the bottom their values serially. The Processing and Max/MSP programs at the bottom take
take those three values and use them to change the background color of the screen. those three values and use them to change the background color of the screen.
The circuit: The circuit:
- potentiometers attached to analog inputs 0, 1, and 2 - potentiometers attached to analog inputs 0, 1, and 2
@ -51,8 +51,8 @@ void loop() {
// if using Processing 2.1 or later, use Serial.printArray() // if using Processing 2.1 or later, use Serial.printArray()
println(Serial.list()); println(Serial.list());
// I know that the first port in the serial list on my Mac // I know that the first port in the serial list on my Mac is always my
// is always my Arduino, so I open Serial.list()[0]. // Arduino, so I open Serial.list()[0].
// Open whatever port is the one you're using. // Open whatever port is the one you're using.
myPort = new Serial(this, Serial.list()[0], 9600); myPort = new Serial(this, Serial.list()[0], 9600);
// don't generate a serialEvent() unless you get a newline character: // don't generate a serialEvent() unless you get a newline character:
@ -71,12 +71,11 @@ void loop() {
if (inString != null) { if (inString != null) {
// trim off any whitespace: // trim off any whitespace:
inString = trim(inString); inString = trim(inString);
// split the string on the commas and convert the // split the string on the commas and convert the resulting substrings
// resulting substrings into an integer array: // into an integer array:
float[] colors = float(split(inString, ",")); float[] colors = float(split(inString, ","));
// if the array has at least three elements, you know // if the array has at least three elements, you know you got the whole
// you got the whole thing. Put the numbers in the // thing. Put the numbers in the color variables:
// color variables:
if (colors.length >=3) { if (colors.length >=3) {
// map them to the range 0-255: // map them to the range 0-255:
redValue = map(colors[0], 0, 1023, 0, 255); redValue = map(colors[0], 0, 1023, 0, 255);

View File

@ -1,12 +1,11 @@
/* /*
Arrays Arrays
Demonstrates the use of an array to hold pin numbers Demonstrates the use of an array to hold pin numbers in order to iterate over
in order to iterate over the pins in a sequence. the pins in a sequence. Lights multiple LEDs in sequence, then in reverse.
Lights multiple LEDs in sequence, then in reverse.
Unlike the For Loop tutorial, where the pins have to be Unlike the For Loop tutorial, where the pins have to be contiguous, here the
contiguous, here the pins can be in any random order. pins can be in any random order.
The circuit: The circuit:
- LEDs from pins 2 through 7 to ground - LEDs from pins 2 through 7 to ground

View File

@ -3,8 +3,8 @@
This example demonstrates the use of if() statements. This example demonstrates the use of if() statements.
It reads the state of a potentiometer (an analog input) and turns on an LED It reads the state of a potentiometer (an analog input) and turns on an LED
only if the potentiometer goes above a certain threshold level. It prints the analog value only if the potentiometer goes above a certain threshold level. It prints the
regardless of the level. analog value regardless of the level.
The circuit: The circuit:
- potentiometer - potentiometer
@ -12,8 +12,8 @@
Side pins of the potentiometer go to +5V and ground. Side pins of the potentiometer go to +5V and ground.
- LED connected from digital pin 13 to ground - LED connected from digital pin 13 to ground
- Note: On most Arduino boards, there is already an LED on the board - Note: On most Arduino boards, there is already an LED on the board connected
connected to pin 13, so you don't need any extra components for this example. to pin 13, so you don't need any extra components for this example.
created 17 Jan 2009 created 17 Jan 2009
modified 9 Apr 2012 modified 9 Apr 2012

View File

@ -4,8 +4,8 @@
This example demonstrates the use of while() statements. This example demonstrates the use of while() statements.
While the pushbutton is pressed, the sketch runs the calibration routine. While the pushbutton is pressed, the sketch runs the calibration routine.
The sensor readings during the while loop define the minimum and maximum The sensor readings during the while loop define the minimum and maximum of
of expected values from the photoresistor. expected values from the photoresistor.
This is a variation on the calibrate example. This is a variation on the calibrate example.

View File

@ -1,13 +1,12 @@
/* /*
Switch statement Switch statement
Demonstrates the use of a switch statement. The switch Demonstrates the use of a switch statement. The switch statement allows you
statement allows you to choose from among a set of discrete values to choose from among a set of discrete values of a variable. It's like a
of a variable. It's like a series of if statements. series of if statements.
To see this sketch in action, put the board and sensor in a well-lit To see this sketch in action, put the board and sensor in a well-lit room,
room, open the Serial Monitor, and move your hand gradually down open the Serial Monitor, and move your hand gradually down over the sensor.
over the sensor.
The circuit: The circuit:
- photoresistor from analog in 0 to +5V - photoresistor from analog in 0 to +5V
@ -22,8 +21,8 @@
http://www.arduino.cc/en/Tutorial/SwitchCase http://www.arduino.cc/en/Tutorial/SwitchCase
*/ */
// these constants won't change. They are the // these constants won't change. They are the lowest and highest readings you
// lowest and highest readings you get from your sensor: // get from your sensor:
const int sensorMin = 0; // sensor minimum, discovered through experiment const int sensorMin = 0; // sensor minimum, discovered through experiment
const int sensorMax = 600; // sensor maximum, discovered through experiment const int sensorMax = 600; // sensor maximum, discovered through experiment
@ -38,8 +37,7 @@ void loop() {
// map the sensor range to a range of four options: // map the sensor range to a range of four options:
int range = map(sensorReading, sensorMin, sensorMax, 0, 3); int range = map(sensorReading, sensorMin, sensorMax, 0, 3);
// do something different depending on the // do something different depending on the range value:
// range value:
switch (range) { switch (range) {
case 0: // your hand is on the sensor case 0: // your hand is on the sensor
Serial.println("dark"); Serial.println("dark");

View File

@ -1,13 +1,13 @@
/* /*
Switch statement with serial input Switch statement with serial input
Demonstrates the use of a switch statement. The switch Demonstrates the use of a switch statement. The switch statement allows you
statement allows you to choose from among a set of discrete values to choose from among a set of discrete values of a variable. It's like a
of a variable. It's like a series of if statements. series of if statements.
To see this sketch in action, open the Serial monitor and send any character. To see this sketch in action, open the Serial monitor and send any character.
The characters a, b, c, d, and e, will turn on LEDs. Any other character will turn The characters a, b, c, d, and e, will turn on LEDs. Any other character will
the LEDs off. turn the LEDs off.
The circuit: The circuit:
- five LEDs attached to digital pins 2 through 6 through 220 ohm resistors - five LEDs attached to digital pins 2 through 6 through 220 ohm resistors
@ -34,10 +34,10 @@ void loop() {
if (Serial.available() > 0) { if (Serial.available() > 0) {
int inByte = Serial.read(); int inByte = Serial.read();
// do something different depending on the character received. // do something different depending on the character received.
// The switch statement expects single number values for each case; // The switch statement expects single number values for each case; in this
// in this example, though, you're using single quotes to tell // example, though, you're using single quotes to tell the controller to get
// the controller to get the ASCII value for the character. For // the ASCII value for the character. For example 'a' = 97, 'b' = 98,
// example 'a' = 97, 'b' = 98, and so forth: // and so forth:
switch (inByte) { switch (inByte) {
case 'a': case 'a':

View File

@ -35,10 +35,10 @@ void setup() {
// initialize the serial communications: // initialize the serial communications:
Serial.begin(9600); Serial.begin(9600);
// Provide ground and power by using the analog inputs as normal // Provide ground and power by using the analog inputs as normal digital pins.
// digital pins. This makes it possible to directly connect the // This makes it possible to directly connect the breakout board to the
// breakout board to the Arduino. If you use the normal 5V and // Arduino. If you use the normal 5V and GND pins on the Arduino,
// GND pins on the Arduino, you can remove these lines. // you can remove these lines.
pinMode(groundpin, OUTPUT); pinMode(groundpin, OUTPUT);
pinMode(powerpin, OUTPUT); pinMode(powerpin, OUTPUT);
digitalWrite(groundpin, LOW); digitalWrite(groundpin, LOW);

View File

@ -3,8 +3,8 @@
This sketch reads a piezo element to detect a knocking sound. This sketch reads a piezo element to detect a knocking sound.
It reads an analog pin and compares the result to a set threshold. It reads an analog pin and compares the result to a set threshold.
If the result is greater than the threshold, it writes If the result is greater than the threshold, it writes "knock" to the serial
"knock" to the serial port, and toggles the LED on pin 13. port, and toggles the LED on pin 13.
The circuit: The circuit:
- positive connection of the piezo attached to analog in 0 - positive connection of the piezo attached to analog in 0

View File

@ -1,10 +1,9 @@
/* /*
Memsic2125 Memsic2125
Read the Memsic 2125 two-axis accelerometer. Converts the Read the Memsic 2125 two-axis accelerometer. Converts the pulses output by the
pulses output by the 2125 into milli-g's (1/1000 of Earth's 2125 into milli-g's (1/1000 of Earth's gravity) and prints them over the
gravity) and prints them over the serial connection to the serial connection to the computer.
computer.
The circuit: The circuit:
- X output of accelerometer to digital pin 2 - X output of accelerometer to digital pin 2
@ -29,8 +28,7 @@ const int yPin = 3; // Y output of the accelerometer
void setup() { void setup() {
// initialize serial communications: // initialize serial communications:
Serial.begin(9600); Serial.begin(9600);
// initialize the pins connected to the accelerometer // initialize the pins connected to the accelerometer as inputs:
// as inputs:
pinMode(xPin, INPUT); pinMode(xPin, INPUT);
pinMode(yPin, INPUT); pinMode(yPin, INPUT);
} }

View File

@ -1,11 +1,10 @@
/* /*
Ping))) Sensor Ping))) Sensor
This sketch reads a PING))) ultrasonic rangefinder and returns the This sketch reads a PING))) ultrasonic rangefinder and returns the distance
distance to the closest object in range. To do this, it sends a pulse to the closest object in range. To do this, it sends a pulse to the sensor to
to the sensor to initiate a reading, then listens for a pulse initiate a reading, then listens for a pulse to return. The length of the
to return. The length of the returning pulse is proportional to returning pulse is proportional to the distance of the object from the sensor.
the distance of the object from the sensor.
The circuit: The circuit:
- +V connection of the PING))) attached to +5V - +V connection of the PING))) attached to +5V
@ -22,8 +21,7 @@
http://www.arduino.cc/en/Tutorial/Ping http://www.arduino.cc/en/Tutorial/Ping
*/ */
// this constant won't change. It's the pin number // this constant won't change. It's the pin number of the sensor's output:
// of the sensor's output:
const int pingPin = 7; const int pingPin = 7;
void setup() { void setup() {
@ -32,8 +30,8 @@ void setup() {
} }
void loop() { void loop() {
// establish variables for duration of the ping, // establish variables for duration of the ping, and the distance result
// and the distance result in inches and centimeters: // in inches and centimeters:
long duration, inches, cm; long duration, inches, cm;
// The PING))) is triggered by a HIGH pulse of 2 or more microseconds. // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
@ -45,9 +43,9 @@ void loop() {
delayMicroseconds(5); delayMicroseconds(5);
digitalWrite(pingPin, LOW); digitalWrite(pingPin, LOW);
// The same pin is used to read the signal from the PING))): a HIGH // The same pin is used to read the signal from the PING))): a HIGH pulse
// pulse whose duration is the time (in microseconds) from the sending // whose duration is the time (in microseconds) from the sending of the ping
// of the ping to the reception of its echo off of an object. // to the reception of its echo off of an object.
pinMode(pingPin, INPUT); pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH); duration = pulseIn(pingPin, HIGH);
@ -65,17 +63,17 @@ void loop() {
} }
long microsecondsToInches(long microseconds) { long microsecondsToInches(long microseconds) {
// According to Parallax's datasheet for the PING))), there are // According to Parallax's datasheet for the PING))), there are 73.746
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per // microseconds per inch (i.e. sound travels at 1130 feet per second).
// second). This gives the distance travelled by the ping, outbound // This gives the distance travelled by the ping, outbound and return,
// and return, so we divide by 2 to get the distance of the obstacle. // so we divide by 2 to get the distance of the obstacle.
// See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
return microseconds / 74 / 2; return microseconds / 74 / 2;
} }
long microsecondsToCentimeters(long microseconds) { long microsecondsToCentimeters(long microseconds) {
// The speed of sound is 340 m/s or 29 microseconds per centimeter. // The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the // The ping travels out and back, so to find the distance of the object we
// object we take half of the distance travelled. // take half of the distance travelled.
return microseconds / 29 / 2; return microseconds / 29 / 2;
} }

View File

@ -7,8 +7,8 @@
http://sigma.octopart.com/140413/datasheet/Lumex-LDM-24488NI.pdf http://sigma.octopart.com/140413/datasheet/Lumex-LDM-24488NI.pdf
for the pin connections. for the pin connections.
For other LED cathode column matrixes, you should only need to change For other LED cathode column matrixes, you should only need to change the pin
the pin numbers in the row[] and column[] arrays. numbers in the row[] and column[] arrays.
rows are the anodes rows are the anodes
cols are the cathodes cols are the cathodes
@ -51,14 +51,12 @@ int x = 5;
int y = 5; int y = 5;
void setup() { void setup() {
// initialize the I/O pins as outputs // initialize the I/O pins as outputs iterate over the pins:
// iterate over the pins:
for (int thisPin = 0; thisPin < 8; thisPin++) { for (int thisPin = 0; thisPin < 8; thisPin++) {
// initialize the output pins: // initialize the output pins:
pinMode(col[thisPin], OUTPUT); pinMode(col[thisPin], OUTPUT);
pinMode(row[thisPin], OUTPUT); pinMode(row[thisPin], OUTPUT);
// take the col pins (i.e. the cathodes) high to ensure that // take the col pins (i.e. the cathodes) high to ensure that the LEDS are off:
// the LEDS are off:
digitalWrite(col[thisPin], HIGH); digitalWrite(col[thisPin], HIGH);
} }
@ -84,8 +82,8 @@ void readSensors() {
// read the sensors for X and Y values: // read the sensors for X and Y values:
x = 7 - map(analogRead(A0), 0, 1023, 0, 7); x = 7 - map(analogRead(A0), 0, 1023, 0, 7);
y = map(analogRead(A1), 0, 1023, 0, 7); y = map(analogRead(A1), 0, 1023, 0, 7);
// set the new pixel position low so that the LED will turn on // set the new pixel position low so that the LED will turn on in the next
// in the next screen refresh: // screen refresh:
pixels[x][y] = LOW; pixels[x][y] = LOW;
} }

View File

@ -2,12 +2,12 @@
LED bar graph LED bar graph
Turns on a series of LEDs based on the value of an analog sensor. Turns on a series of LEDs based on the value of an analog sensor.
This is a simple way to make a bar graph display. Though this graph This is a simple way to make a bar graph display. Though this graph uses 10
uses 10 LEDs, you can use any number by changing the LED count LEDs, you can use any number by changing the LED count and the pins in the
and the pins in the array. array.
This method can be used to control any series of digital outputs that This method can be used to control any series of digital outputs that depends
depends on an analog input. on an analog input.
The circuit: The circuit:
- LEDs from pins 2 through 11 to ground - LEDs from pins 2 through 11 to ground

View File

@ -97,8 +97,8 @@ void loop() {
// the compareTo() operator also allows you to compare Strings // the compareTo() operator also allows you to compare Strings
// it evaluates on the first character that's different. // it evaluates on the first character that's different.
// if the first character of the String you're comparing to // if the first character of the String you're comparing to comes first in
// comes first in alphanumeric order, then compareTo() is greater than 0: // alphanumeric order, then compareTo() is greater than 0:
stringOne = "Cucumber"; stringOne = "Cucumber";
stringTwo = "Cucuracha"; stringTwo = "Cucuracha";
if (stringOne.compareTo(stringTwo) < 0) { if (stringOne.compareTo(stringTwo) < 0) {

View File

@ -25,8 +25,8 @@ void setup() {
} }
void loop() { void loop() {
// indexOf() returns the position (i.e. index) of a particular character // indexOf() returns the position (i.e. index) of a particular character in a
// in a String. For example, if you were parsing HTML tags, you could use it: // String. For example, if you were parsing HTML tags, you could use it:
String stringOne = "<HTML><HEAD><BODY>"; String stringOne = "<HTML><HEAD><BODY>";
int firstClosingBracket = stringOne.indexOf('>'); int firstClosingBracket = stringOne.indexOf('>');
Serial.println("The index of > in the string " + stringOne + " is " + firstClosingBracket); Serial.println("The index of > in the string " + stringOne + " is " + firstClosingBracket);

View File

@ -1,8 +1,8 @@
/* /*
String to Integer conversion String to Integer conversion
Reads a serial input string until it sees a newline, then converts Reads a serial input string until it sees a newline, then converts the string
the string to a number if the characters are digits. to a number if the characters are digits.
The circuit: The circuit:
- No external components needed. - No external components needed.
@ -34,12 +34,10 @@ void loop() {
while (Serial.available() > 0) { while (Serial.available() > 0) {
int inChar = Serial.read(); int inChar = Serial.read();
if (isDigit(inChar)) { if (isDigit(inChar)) {
// convert the incoming byte to a char // convert the incoming byte to a char and add it to the string:
// and add it to the string:
inString += (char)inChar; inString += (char)inChar;
} }
// if you get a newline, print the string, // if you get a newline, print the string, then the string's value:
// then the string's value:
if (inChar == '\n') { if (inChar == '\n') {
Serial.print("Value:"); Serial.print("Value:");
Serial.println(inString.toInt()); Serial.println(inString.toInt());

View File

@ -35,8 +35,7 @@
int platform = OSX; int platform = OSX;
void setup() { void setup() {
// make pin 2 an input and turn on the // make pin 2 an input and turn on the pull-up resistor so it goes high unless
// pull-up resistor so it goes high unless
// connected to ground: // connected to ground:
pinMode(2, INPUT_PULLUP); pinMode(2, INPUT_PULLUP);
Keyboard.begin(); Keyboard.begin();

View File

@ -5,12 +5,10 @@
For Leonardo and Due boards only. For Leonardo and Due boards only.
When you connect pin 2 to ground, it creates a new When you connect pin 2 to ground, it creates a new window with a key
window with a key combination (CTRL-N), combination (CTRL-N), then types in the Blink sketch, then auto-formats the
then types in the Blink sketch, then auto-formats the text text using another key combination (CTRL-T), then uploads the sketch to the
using another key combination (CTRL-T), then currently selected Arduino using a final key combination (CTRL-U).
uploads the sketch to the currently selected Arduino using
a final key combination (CTRL-U).
Circuit: Circuit:
- Arduino Leonardo, Micro, Due, LilyPad USB, or Yún - Arduino Leonardo, Micro, Due, LilyPad USB, or Yún
@ -38,8 +36,7 @@ char ctrlKey = KEY_LEFT_GUI;
void setup() { void setup() {
// make pin 2 an input and turn on the // make pin 2 an input and turn on the pull-up resistor so it goes high unless
// pull-up resistor so it goes high unless
// connected to ground: // connected to ground:
pinMode(2, INPUT_PULLUP); pinMode(2, INPUT_PULLUP);
// initialize control over the keyboard: // initialize control over the keyboard:
@ -60,9 +57,8 @@ void loop() {
// wait for new window to open: // wait for new window to open:
delay(1000); delay(1000);
// versions of the Arduino IDE after 1.5 pre-populate // versions of the Arduino IDE after 1.5 pre-populate new sketches with
// new sketches with setup() and loop() functions // setup() and loop() functions let's clear the window before typing anything new
// let's clear the window before typing anything new
// select all // select all
Keyboard.press(ctrlKey); Keyboard.press(ctrlKey);
Keyboard.press('a'); Keyboard.press('a');

View File

@ -4,8 +4,8 @@
For the Arduino Leonardo, Micro or Due For the Arduino Leonardo, Micro or Due
Reads a byte from the serial port, sends a keystroke back. Reads a byte from the serial port, sends a keystroke back.
The sent keystroke is one higher than what's received, e.g. The sent keystroke is one higher than what's received, e.g. if you send a,
if you send a, you get b, send A you get B, and so forth. you get b, send A you get B, and so forth.
The circuit: The circuit:
- none - none

View File

@ -6,11 +6,11 @@
Hardware: Hardware:
- five pushbuttons attached to D2, D3, D4, D5, D6 - five 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
four pushbuttons, and uses them to set the movement of the mouse. uses them to set the movement of the mouse.
WARNING: When you use the Mouse.move() command, the Arduino takes WARNING: When you use the Mouse.move() command, the Arduino takes over your
over your mouse! Make sure you have control before you use the mouse commands. mouse! Make sure you have control before you use the mouse commands.
created 15 Mar 2012 created 15 Mar 2012
modified 27 Mar 2012 modified 27 Mar 2012

View File

@ -8,11 +8,11 @@
Hardware: Hardware:
- five pushbuttons attached to D2, D3, D4, D5, D6 - five 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,
four pushbuttons, and uses them to set the movement of the mouse. and uses them to set the movement of the mouse.
WARNING: When you use the Mouse.move() command, the Arduino takes WARNING: When you use the Mouse.move() command, the Arduino takes over your
over your mouse! Make sure you have control before you use the mouse commands. mouse! Make sure you have control before you use the mouse commands.
created 15 Mar 2012 created 15 Mar 2012
modified 27 Mar 2012 modified 27 Mar 2012

View File

@ -2,23 +2,23 @@
JoystickMouseControl JoystickMouseControl
Controls the mouse from a joystick on an Arduino Leonardo, Micro or Due. Controls the mouse from a joystick on an Arduino Leonardo, Micro or Due.
Uses a pushbutton to turn on and off mouse control, and Uses a pushbutton to turn on and off mouse control, and a second pushbutton
a second pushbutton to click the left mouse button. to click the left mouse button.
Hardware: Hardware:
- 2-axis joystick connected to pins A0 and A1 - 2-axis joystick connected to pins A0 and A1
- pushbuttons connected to pin D2 and D3 - pushbuttons connected to pin D2 and D3
The mouse movement is always relative. This sketch reads The mouse movement is always relative. This sketch reads two analog inputs
two analog inputs that range from 0 to 1023 (or less on either end) that range from 0 to 1023 (or less on either end) and translates them into
and translates them into ranges of -6 to 6. ranges of -6 to 6.
The sketch assumes that the joystick resting values are around the The sketch assumes that the joystick resting values are around the middle of
middle of the range, but that they vary within a threshold. the range, but that they vary within a threshold.
WARNING: When you use the Mouse.move() command, the Arduino takes WARNING: When you use the Mouse.move() command, the Arduino takes over your
over your mouse! Make sure you have control before you use the command. mouse! Make sure you have control before you use the command. This sketch
This sketch includes a pushbutton to toggle the mouse control state, so includes a pushbutton to toggle the mouse control state, so you can turn on
you can turn on and off mouse control. and off mouse control.
created 15 Sep 2011 created 15 Sep 2011
updated 28 Mar 2012 updated 28 Mar 2012
@ -97,8 +97,8 @@ 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
analog input range to a range from 0 to <range> from 0 to <range>
*/ */
int readAxis(int thisAxis) { int readAxis(int thisAxis) {
@ -108,8 +108,7 @@ int readAxis(int thisAxis) {
// map the reading from the analog input range to the output range: // map the reading from the analog input range to the output range:
reading = map(reading, 0, 1023, 0, range); reading = map(reading, 0, 1023, 0, range);
// if the output reading is outside from the // if the output reading is outside from the rest position threshold, use it:
// rest position threshold, use it:
int distance = reading - center; int distance = reading - center;
if (abs(distance) < threshold) { if (abs(distance) < threshold) {

View File

@ -2,8 +2,7 @@
Arduino Starter Kit example Arduino Starter Kit example
Project 2 - Spaceship Interface Project 2 - Spaceship Interface
This sketch is written to accompany Project 2 in the This sketch is written to accompany Project 2 in the Arduino Starter Kit
Arduino Starter Kit
Parts required: Parts required:
- one green LED - one green LED
@ -20,10 +19,9 @@
This example code is part of the public domain. This example code is part of the public domain.
*/ */
// Create a global variable to hold the // Create a global variable to hold the state of the switch. This variable is
// state of the switch. This variable is persistent // persistent throughout the program. Whenever you refer to switchState, youre
// throughout the program. Whenever you refer to // talking about the number it holds
// switchState, youre talking about the number it holds
int switchstate = 0; int switchstate = 0;
void setup() { void setup() {
@ -39,20 +37,18 @@ void setup() {
void loop() { void loop() {
// read the value of the switch // read the value of the switch
// digitalRead() checks to see if there is voltage // digitalRead() checks to see if there is voltage on the pin or not
// on the pin or not
switchstate = digitalRead(2); switchstate = digitalRead(2);
// if the button is not pressed // if the button is not pressed turn on the green LED and off the red LEDs
// turn on the green LED and off the red LEDs
if (switchstate == LOW) { if (switchstate == LOW) {
digitalWrite(3, HIGH); // turn the green LED on pin 3 on digitalWrite(3, HIGH); // turn the green LED on pin 3 on
digitalWrite(4, LOW); // turn the red LED on pin 4 off digitalWrite(4, LOW); // turn the red LED on pin 4 off
digitalWrite(5, LOW); // turn the red LED on pin 5 off digitalWrite(5, LOW); // turn the red LED on pin 5 off
} }
// this else is part of the above if() statement. // this else is part of the above if() statement.
// if the switch is not LOW (the button is pressed) // if the switch is not LOW (the button is pressed) turn off the green LED and
// turn off the green LED and blink alternatively the red LEDs // blink alternatively the red LEDs
else { else {
digitalWrite(3, LOW); // turn the green LED on pin 3 off digitalWrite(3, LOW); // turn the green LED on pin 3 off
digitalWrite(4, LOW); // turn the red LED on pin 4 off digitalWrite(4, LOW); // turn the red LED on pin 4 off

View File

@ -2,8 +2,7 @@
Arduino Starter Kit example Arduino Starter Kit example
Project 3 - Love-O-Meter Project 3 - Love-O-Meter
This sketch is written to accompany Project 3 in the This sketch is written to accompany Project 3 in the Arduino Starter Kit
Arduino Starter Kit
Parts required: Parts required:
- one TMP36 temperature sensor - one TMP36 temperature sensor
@ -35,8 +34,7 @@ void setup() {
} }
void loop() { void loop() {
// read the value on AnalogIn pin 0 // read the value on AnalogIn pin 0 and store it in a variable
// and store it in a variable
int sensorVal = analogRead(sensorPin); int sensorVal = analogRead(sensorPin);
// send the 10-bit sensor value out the serial port // send the 10-bit sensor value out the serial port
@ -58,8 +56,7 @@ void loop() {
float temperature = (voltage - .5) * 100; float temperature = (voltage - .5) * 100;
Serial.println(temperature); Serial.println(temperature);
// if the current temperature is lower than the baseline // if the current temperature is lower than the baseline turn off all LEDs
// turn off all LEDs
if (temperature < baselineTemp + 2) { if (temperature < baselineTemp + 2) {
digitalWrite(2, LOW); digitalWrite(2, LOW);
digitalWrite(3, LOW); digitalWrite(3, LOW);

View File

@ -2,8 +2,7 @@
Arduino Starter Kit example Arduino Starter Kit example
Project 4 - Color Mixing Lamp Project 4 - Color Mixing Lamp
This sketch is written to accompany Project 3 in the This sketch is written to accompany Project 3 in the Arduino Starter Kit
Arduino Starter Kit
Parts required: Parts required:
- one RGB LED - one RGB LED
@ -71,10 +70,10 @@ void loop() {
Serial.println(blueSensorValue); Serial.println(blueSensorValue);
/* /*
In order to use the values from the sensor for the LED, In order to use the values from the sensor for the LED, you need to do some
you need to do some math. The ADC provides a 10-bit number, math. The ADC provides a 10-bit number, but analogWrite() uses 8 bits.
but analogWrite() uses 8 bits. You'll want to divide your You'll want to divide your sensor readings by 4 to keep them in range
sensor readings by 4 to keep them in range of the output. of the output.
*/ */
redValue = redSensorValue / 4; redValue = redSensorValue / 4;
greenValue = greenSensorValue / 4; greenValue = greenSensorValue / 4;

View File

@ -2,8 +2,7 @@
Arduino Starter Kit example Arduino Starter Kit example
Project 5 - Servo Mood Indicator Project 5 - Servo Mood Indicator
This sketch is written to accompany Project 5 in the This sketch is written to accompany Project 5 in the Arduino Starter Kit
Arduino Starter Kit
Parts required: Parts required:
- servo motor - servo motor

View File

@ -2,8 +2,7 @@
Arduino Starter Kit example Arduino Starter Kit example
Project 6 - Light Theremin Project 6 - Light Theremin
This sketch is written to accompany Project 6 in the This sketch is written to accompany Project 6 in the Arduino Starter Kit
Arduino Starter Kit
Parts required: Parts required:
- photoresistor - photoresistor

View File

@ -2,8 +2,7 @@
Arduino Starter Kit example Arduino Starter Kit example
Project 7 - Keyboard Project 7 - Keyboard
This sketch is written to accompany Project 7 in the This sketch is written to accompany Project 7 in the Arduino Starter Kit
Arduino Starter Kit
Parts required: Parts required:
- two 10 kilohm resistors - two 10 kilohm resistors
@ -21,8 +20,7 @@
*/ */
// create an array of notes // create an array of notes
// the numbers below correspond to // the numbers below correspond to the frequencies of middle C, D, E, and F
// the frequencies of middle C, D, E, and F
int notes[] = {262, 294, 330, 349}; int notes[] = {262, 294, 330, 349};
void setup() { void setup() {

View File

@ -2,8 +2,7 @@
Arduino Starter Kit example Arduino Starter Kit example
Project 8 - Digital Hourglass Project 8 - Digital Hourglass
This sketch is written to accompany Project 8 in the This sketch is written to accompany Project 8 in the Arduino Starter Kit
Arduino Starter Kit
Parts required: Parts required:
- 10 kilohm resistor - 10 kilohm resistor

View File

@ -2,8 +2,7 @@
Arduino Starter Kit example Arduino Starter Kit example
Project 9 - Motorized Pinwheel Project 9 - Motorized Pinwheel
This sketch is written to accompany Project 9 in the This sketch is written to accompany Project 9 in the Arduino Starter Kit
Arduino Starter Kit
Parts required: Parts required:
- 10 kilohm resistor - 10 kilohm resistor

View File

@ -2,8 +2,7 @@
Arduino Starter Kit example Arduino Starter Kit example
Project 10 - Zoetrope Project 10 - Zoetrope
This sketch is written to accompany Project 10 in the This sketch is written to accompany Project 10 in the Arduino Starter Kit
Arduino Starter Kit
Parts required: Parts required:
- two 10 kilohm resistors - two 10 kilohm resistors
@ -59,8 +58,8 @@ void loop() {
// read the value of the direction switch // read the value of the direction switch
directionSwitchState = digitalRead(directionSwitchPin); directionSwitchState = digitalRead(directionSwitchPin);
// read the value of the pot and divide by 4 to get // read the value of the pot and divide by 4 to get a value that can be
// a value that can be used for PWM // used for PWM
motorSpeed = analogRead(potPin) / 4; motorSpeed = analogRead(potPin) / 4;
// if the on/off button changed state since the last loop() // if the on/off button changed state since the last loop()
@ -79,8 +78,8 @@ void loop() {
} }
} }
// change the direction the motor spins by talking // change the direction the motor spins by talking to the control pins
// to the control pins on the H-Bridge // on the H-Bridge
if (motorDirection == 1) { if (motorDirection == 1) {
digitalWrite(controlPin1, HIGH); digitalWrite(controlPin1, HIGH);
digitalWrite(controlPin2, LOW); digitalWrite(controlPin2, LOW);

View File

@ -2,8 +2,7 @@
Arduino Starter Kit example Arduino Starter Kit example
Project 11 - Crystal Ball Project 11 - Crystal Ball
This sketch is written to accompany Project 11 in the This sketch is written to accompany Project 11 in the Arduino Starter Kit
Arduino Starter Kit
Parts required: Parts required:
- 220 ohm resistor - 220 ohm resistor
@ -60,9 +59,8 @@ void loop() {
// compare the switchState to its previous state // compare the switchState to its previous state
if (switchState != prevSwitchState) { if (switchState != prevSwitchState) {
// if the state has changed from HIGH to LOW // if the state has changed from HIGH to LOW you know that the ball has been
// you know that the ball has been tilted from // tilted from one direction to the other
// one direction to the other
if (switchState == LOW) { if (switchState == LOW) {
// randomly chose a reply // randomly chose a reply
reply = random(8); reply = random(8);

View File

@ -2,8 +2,7 @@
Arduino Starter Kit example Arduino Starter Kit example
Project 12 - Knock Lock Project 12 - Knock Lock
This sketch is written to accompany Project 12 in the This sketch is written to accompany Project 12 in the Arduino Starter Kit
Arduino Starter Kit
Parts required: Parts required:
- 1 megohm resistor - 1 megohm resistor
@ -146,11 +145,10 @@ void loop() {
} }
} }
// this function checks to see if a // this function checks to see if a detected knock is within max and min range
// detected knock is within max and min range
boolean checkForKnock(int value) { boolean checkForKnock(int value) {
// if the value of the knock is greater than // if the value of the knock is greater than the minimum, and larger
// the minimum, and larger than the maximum // than the maximum
if (value > quietKnock && value < loudKnock) { if (value > quietKnock && value < loudKnock) {
// turn the status LED on // turn the status LED on
digitalWrite(yellowLed, HIGH); digitalWrite(yellowLed, HIGH);

View File

@ -2,8 +2,7 @@
Arduino Starter Kit example Arduino Starter Kit example
Project 13 - Touch Sensor Lamp Project 13 - Touch Sensor Lamp
This sketch is written to accompany Project 13 in the This sketch is written to accompany Project 13 in the Arduino Starter Kit
Arduino Starter Kit
Parts required: Parts required:
- 1 megohm resistor - 1 megohm resistor
@ -23,8 +22,7 @@
This example code is part of the public domain. This example code is part of the public domain.
*/ */
// import the library (must be located in the // import the library (must be located in the Arduino/libraries directory)
// Arduino/libraries directory)
#include <CapacitiveSensor.h> #include <CapacitiveSensor.h>
// create an instance of the library // create an instance of the library

View File

@ -2,8 +2,7 @@
Arduino Starter Kit example Arduino Starter Kit example
Project 14 - Tweak the Arduino Logo Project 14 - Tweak the Arduino Logo
This sketch is written to accompany Project 14 in the This sketch is written to accompany Project 14 in the Arduino Starter Kit
Arduino Starter Kit
Parts required: Parts required:
- 10 kilohm potentiometer - 10 kilohm potentiometer
@ -27,8 +26,8 @@ void setup() {
} }
void loop() { void loop() {
// read the value of A0, divide by 4 and // read the value of A0, divide by 4 and send it as a byte over the
// send it as a byte over the serial connection // serial connection
Serial.write(analogRead(A0) / 4); Serial.write(analogRead(A0) / 4);
delay(1); delay(1);
} }
@ -62,21 +61,19 @@ void loop() {
// make the window the same size as the image // make the window the same size as the image
surface.setSize(logo.width, logo.height); surface.setSize(logo.width, logo.height);
// print a list of available serial ports to the // print a list of available serial ports to the Processing status window
// Processing status window
println("Available serial ports:"); println("Available serial ports:");
println(Serial.list()); println(Serial.list());
// Tell the serial object the information it needs to communicate // Tell the serial object the information it needs to communicate with the
// with the Arduino. Change Serial.list()[0] to the correct // Arduino. Change Serial.list()[0] to the correct port corresponding to
// port corresponding to your Arduino board. The last // your Arduino board. The last parameter (e.g. 9600) is the speed of the
// parameter (e.g. 9600) is the speed of the communication. It // communication. It has to correspond to the value passed to
// has to correspond to the value passed to Serial.begin() in your // Serial.begin() in your Arduino sketch.
// Arduino sketch.
myPort = new Serial(this, Serial.list()[0], 9600); myPort = new Serial(this, Serial.list()[0], 9600);
// If you know the name of the port used by the Arduino board, you // If you know the name of the port used by the Arduino board, you can
// can specify it directly like this. // specify it directly like this.
// port = new Serial(this, "COM1", 9600); // port = new Serial(this, "COM1", 9600);
} }
@ -91,9 +88,8 @@ void loop() {
println(bgcolor); println(bgcolor);
} }
// Draw the background. the variable bgcolor // Draw the background. the variable bgcolor contains the Hue, determined by
// contains the Hue, determined by the value // the value from the serial port
// from the serial port
background(bgcolor, 255, 255); background(bgcolor, 255, 255);
// draw the Arduino logo // draw the Arduino logo

View File

@ -2,8 +2,7 @@
Arduino Starter Kit example Arduino Starter Kit example
Project 15 - Hacking Buttons Project 15 - Hacking Buttons
This sketch is written to accompany Project 15 in the This sketch is written to accompany Project 15 in the Arduino Starter Kit
Arduino Starter Kit
Parts required: Parts required:
- battery powered component - battery powered component

View File

@ -3,30 +3,30 @@
// If you require a license, see // If you require a license, see
// http://www.opensource.org/licenses/bsd-license.php // http://www.opensource.org/licenses/bsd-license.php
// //
// This sketch turns the Arduino into a AVRISP // This sketch turns the Arduino into a AVRISP using the following Arduino pins:
// using the following Arduino pins:
// //
// Pin 10 is used to reset the target microcontroller. // Pin 10 is used to reset the target microcontroller.
// //
// By default, the hardware SPI pins MISO, MOSI and SCK are used // By default, the hardware SPI pins MISO, MOSI and SCK are used to communicate
// to communicate with the target. On all Arduinos, these pins can be found // with the target. On all Arduinos, these pins can be found
// on the ICSP/SPI header: // on the ICSP/SPI header:
// //
// MISO °. . 5V (!) Avoid this pin on Due, Zero... // MISO °. . 5V (!) Avoid this pin on Due, Zero...
// SCK . . MOSI // SCK . . MOSI
// . . GND // . . GND
// //
// On some Arduinos (Uno,...), pins MOSI, MISO and SCK are the same pins // On some Arduinos (Uno,...), pins MOSI, MISO and SCK are the same pins as
// as digital pin 11, 12 and 13, respectively. That is why many tutorials // digital pin 11, 12 and 13, respectively. That is why many tutorials instruct
// instruct you to hook up the target to these pins. If you find this wiring // you to hook up the target to these pins. If you find this wiring more
// more practical, have a define USE_OLD_STYLE_WIRING. This will work even // practical, have a define USE_OLD_STYLE_WIRING. This will work even when not
// when not using an Uno. (On an Uno this is not needed). // using an Uno. (On an Uno this is not needed).
// //
// Alternatively you can use any other digital pin by configuring software ('BitBanged') // Alternatively you can use any other digital pin by configuring
// SPI and having appropriate defines for PIN_MOSI, PIN_MISO and PIN_SCK. // software ('BitBanged') SPI and having appropriate defines for PIN_MOSI,
// PIN_MISO and PIN_SCK.
// //
// IMPORTANT: When using an Arduino that is not 5V tolerant (Due, Zero, ...) // IMPORTANT: When using an Arduino that is not 5V tolerant (Due, Zero, ...) as
// as the programmer, make sure to not expose any of the programmer's pins to 5V. // the programmer, make sure to not expose any of the programmer's pins to 5V.
// A simple way to accomplish this is to power the complete system (programmer // A simple way to accomplish this is to power the complete system (programmer
// and target) at 3V3. // and target) at 3V3.
// //
@ -43,9 +43,9 @@
#define PROG_FLICKER true #define PROG_FLICKER true
// Configure SPI clock (in Hz). // Configure SPI clock (in Hz).
// E.g. for an ATtiny @ 128 kHz: the datasheet states that both the high // E.g. for an ATtiny @ 128 kHz: the datasheet states that both the high and low
// and low SPI clock pulse must be > 2 CPU cycles, so take 3 cycles i.e. // SPI clock pulse must be > 2 CPU cycles, so take 3 cycles i.e. divide target
// divide target f_cpu by 6: // f_cpu by 6:
// #define SPI_CLOCK (128000/6) // #define SPI_CLOCK (128000/6)
// //
// A clock slow enough for an ATtiny85 @ 1 MHz, is a reasonable default: // A clock slow enough for an ATtiny85 @ 1 MHz, is a reasonable default:
@ -54,8 +54,8 @@
// Select hardware or software SPI, depending on SPI clock. // Select hardware or software SPI, depending on SPI clock.
// Currently only for AVR, for other architectures (Due, Zero,...), // Currently only for AVR, for other architectures (Due, Zero,...), hardware SPI
// hardware SPI is probably too fast anyway. // is probably too fast anyway.
#if defined(ARDUINO_ARCH_AVR) #if defined(ARDUINO_ARCH_AVR)
@ -88,9 +88,8 @@
#endif #endif
// HOODLOADER2 means running sketches on the ATmega16U2 // HOODLOADER2 means running sketches on the ATmega16U2 serial converter chips
// serial converter chips on Uno or Mega boards. // on Uno or Mega boards. We must use pins that are broken out:
// We must use pins that are broken out:
#else #else
#define RESET 4 #define RESET 4
@ -401,10 +400,8 @@ void start_pmode() {
// Reset target before driving PIN_SCK or PIN_MOSI // Reset target before driving PIN_SCK or PIN_MOSI
// SPI.begin() will configure SS as output, // SPI.begin() will configure SS as output, so SPI master mode is selected.
// so SPI master mode is selected. // We have defined RESET as pin 10, which for many Arduinos is not the SS pin.
// We have defined RESET as pin 10,
// which for many Arduinos is not the SS pin.
// So we have to configure RESET as output here, // So we have to configure RESET as output here,
// (reset_target() first sets the correct level) // (reset_target() first sets the correct level)
reset_target(true); reset_target(true);
@ -418,8 +415,8 @@ void start_pmode() {
digitalWrite(PIN_SCK, LOW); digitalWrite(PIN_SCK, LOW);
delay(20); // discharge PIN_SCK, value arbitrarily chosen delay(20); // discharge PIN_SCK, value arbitrarily chosen
reset_target(false); reset_target(false);
// Pulse must be minimum 2 target CPU clock cycles // Pulse must be minimum 2 target CPU clock cycles so 100 usec is ok for CPU
// so 100 usec is ok for CPU speeds above 20 KHz // speeds above 20 KHz
delayMicroseconds(100); delayMicroseconds(100);
reset_target(true); reset_target(true);
@ -431,8 +428,7 @@ void start_pmode() {
void end_pmode() { void end_pmode() {
SPI.end(); SPI.end();
// We're about to take the target out of reset // We're about to take the target out of reset so configure SPI pins as input
// so configure SPI pins as input
pinMode(PIN_MOSI, INPUT); pinMode(PIN_MOSI, INPUT);
pinMode(PIN_SCK, INPUT); pinMode(PIN_SCK, INPUT);
reset_target(false); reset_target(false);
@ -530,8 +526,7 @@ uint8_t write_eeprom(unsigned int length) {
} }
// write (length) bytes, (start) is a byte address // write (length) bytes, (start) is a byte address
uint8_t write_eeprom_chunk(unsigned int start, unsigned int length) { uint8_t write_eeprom_chunk(unsigned int start, unsigned int length) {
// this writes byte-by-byte, // this writes byte-by-byte, page writing may be faster (4 bytes at a time)
// page writing may be faster (4 bytes at a time)
fill(length); fill(length);
prog_lamp(LOW); prog_lamp(LOW);
for (unsigned int x = 0; x < length; x++) { for (unsigned int x = 0; x < length; x++) {