Nota Arduino
Nota Arduino
1 Blink
In most programming languages, the first program you write prints "hello world" to the screen. Since
an Arduino board doesn't have a screen, we blink an LED instead.
The boards are designed to make it easy to blink an LED using digital pin 13. Some (like the Diecimila
and LilyPad) have the LED built-in to the board. On most others (like the Mini and BT), there is a 1 KB
resistor on the pin, allowing you to connect an LED directly. (To connect an LED to another digital
pin, you should use an external resistor.)
LEDs have polarity, which means they will only light up if you orient the legs properly. The long leg is
typically positive, and should connect to pin 13. The short leg connects to GND; the bulb of the LED
will also typically have a flat edge on this side. If the LED doesn't light up, trying reversing the legs
(you won't hurt the LED if you plug it in backwards for a short period of time).
Circuit
Code
The example code is very simple, credits are to be found in the comments. /* Blinking LED * -----------
* * turns on and off a light emitting diode(LED) connected to a digital * pin, in intervals of 2
seconds. Ideally we use pin 13 on the Arduino * board because it has a resistor attached to it,
needing only an LED
void loop() { digitalWrite(ledPin, HIGH); // sets the LED on delay(1000); // waits for a
second digitalWrite(ledPin, LOW); // sets the LED off delay(1000); // waits for a second }
Edit Page | Page History | Printable View | All Recent Site Changes
Arduino
Sometimes you need to blink an LED (or some other time sensitive function) at the same time as
something else (like watching for a button press). That means you can't use delay(), or you'd stop
everything else the program while the LED blinked. Here's some code that demonstrates how to
blink the LED without using delay(). It keeps track of the last time it turned the LED on or off. Then,
each time through loop() it checks if a sufficient interval has passed - if it has, it turns the LED off if it
was on and vice-versa.
Code
int ledPin = 13; // LED connected to digital pin 13 int value = LOW; // previous value
of the LED long previousMillis = 0; // will store last time LED was updated long interval = 1000;
// interval at which to blink (milliseconds)
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, is the difference // between the current time
and last time we blinked the LED bigger than // the interval at which we want to blink the LED. if
(millis() - previousMillis > interval) { previousMillis = millis(); // remember the last time we blinked
the LED
// if the LED is off turn it on and vice-versa. if (value == LOW) value = HIGH; else value =
LOW;
digitalWrite(ledPin, value); } }
Edit Page | Page History | Printable View | All Recent Site Changes
Arduino
The pushbutton is a component that connects two points in a circuit when you press it. The example
turns on an LED when you press the button.
We connect three wires to the Arduino board. The first goes from one leg of the pushbutton through
a pull-up resistor (here 2.2 KOhms) to the 5 volt supply. The second goes from the corresponding leg
of the pushbutton to ground. The third connects to a digital i/o pin (here pin 7) which reads the
button's state.
When the pushbutton is open (unpressed) there is no connection between the two legs of the
pushbutton, so the pin is connected to 5 volts (through the pull-up resistor) and we read a HIGH.
When the button is closed (pressed), it makes a connection between its two legs, connecting the pin
to ground, so that we read a LOW. (The pin is still connected to 5 volts, but the resistor in-between
them means that the pin is "closer" to ground.)
You can also wire this circuit the opposite way, with a pull-down resistor keeping the input LOW, and
going HIGH when the button is pressed. If so, the behavior of the sketch will be reversed, with the
LED normally on and turning off when you press the button.
If you disconnect the digital i/o pin from everything, the LED may blink erratically. This is because the
input is "floating" that is, it will more-or-less randomly return either HIGH or LOW. That's why you
need a pull-up or pull-down resister in the circuit.
Circuit
Code int ledPin = 13; // choose the pin for the LED int inPin = 2; // choose the input pin (for a
pushbutton) int val = 0; // variable for reading the pin status
void setup() { pinMode(ledPin, OUTPUT); // declare LED as output
void loop(){ val = digitalRead(inPin); // read input value if (val == HIGH) { // check if the input is
HIGH (button released) digitalWrite(ledPin, LOW); // turn LED OFF } else { digitalWrite(ledPin,
HIGH); // turn LED ON } }
Edit Page | Page History | Printable View | All Recent Site Changes
This example makes use of a Piezo Speaker in order to play melodies. We are taking advantage of
the processors capability to produde PWM signals in order to play music. There is more information
about how PWM works written by David Cuartielles here and even at K3's old course guide
A Piezo is nothing but an electronic device that can both be used to play tones and to detect tones.
In our example we are plugging the Piezo on the pin number 9, that supports the functionality of
writing a PWM signal to it, and not just a plain HIGH or LOW value.
The first example of the code will just send a square wave to the piezo, while the second one will
make use of the PWM functionality to control the volume through changing the Pulse Width.
The other thing to remember is that Piezos have polarity, commercial devices are usually having a
red and a black wires indicating how to plug it to the board. We connect the black one to ground and
the red one to the output. Sometimes it is possible to acquire Piezo elements without a plastic
housing, then they will just look like a metallic disc.
/* Play Melody * ---------- * * Program to play a simple melody * * Tones are created by quickly
pulsing a speaker on and off * using PWM, to create signature frequencies.
* * Each note has a frequency, created by varying the period of * vibration, measured in
microseconds. We'll use pulse-width * modulation (PWM) to create that vibration.
* We calculate the pulse-width to be half the period; we pulse * the speaker HIGH for 'pulse-width'
microseconds, then LOW * for 'pulse-width' microseconds. * This pulsing creates a vibration of the
desired frequency. * * (cleft) 2005 D. Cuartielles for K3 * Refactoring and comments 2006
[email protected] * See NOTES in comments at end for possible improvements */
// Set overall tempo long tempo = 10000; // Set length of pause between notes int pause = 1000; //
Loop variable to increase Rest length int rest_count = 100; //<-BLETCHEROUS HACK; See NOTES
if (tone > 0) { // if this isn't a Rest beat, while the tone has // played less long than 'duration',
pulse speaker HIGH and LOW while (elapsed_time < duration) {
// Keep track of how long we pulsed elapsed_time += (tone); } } else { // Rest beat; loop
times delay for (int j = 0; j < rest_count; j++) { // See NOTE on rest_count
delayMicroseconds(duration); } } }
/* * NOTES * The program purports to hold a tone for 'duration' microseconds. * Lies lies lies! It
holds for at least 'duration' microseconds, _plus_ * any overhead created by incremeting
elapsed_time (could be in excess of * 3K microseconds) _plus_ overhead of looping and two
digitalWrites() * * As a result, a tone of 'duration' plays much more slowly than a rest * of
'duration.' rest_count creates a loop variable to bring 'rest' beats * in line with 'tone' beats of the
same length. * * rest_count will be affected by chip architecture and speed, as well as * overhead
from any program mods. Past behavior is no guarantee of future * performance. Your mileage may
vary. Light fuse and get away. * * This could use a number of enhancements: * ADD code to let the
programmer specify how many times the melody should
* loop before stopping * ADD another octave * MOVE tempo, pause, and rest_count to #define
statements * RE-WRITE to include volume, using analogWrite, as with the second program at *
http://www.arduino.cc/en/Tutorial/PlayMelody * ADD code to make the tempo settable by pot or
other input device * ADD code to take tempo or volume settable by serial communication *
(Requires 0005 or higher.) * ADD code to create a tone offset (higer or lower) through pot etc *
REPLACE random melody with opening bars to 'Smoke on the Water' */
/* Play Melody * ---------- * * Program to play melodies stored in an array, it requires to know *
about timing issues and about how to play tones. * * The calculation of the tones is made following
the mathematical * operation: * * timeHigh = 1/(2 * toneFrequency) = period / 2 * * where the
different tones are described as in the table: * * note frequency period PW (timeHigh) * c
261 Hz 3830 1915 * d 294 Hz 3400 1700 * e 329 Hz 3038 1519
*f 349 Hz 2864 1432 * g 392 Hz 2550 1275 * a 440 Hz 2272
1136 * b 493 Hz 2028 1014 * C 523 Hz 1912 956 * * (cleft) 2005 D.
Cuartielles for K3 */
int ledPin = 13; int speakerOut = 9; byte names[] = {'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C'}; int tones[] =
{1915, 1700, 1519, 1432, 1275, 1136, 1014, 956}; byte melody[] =
"2d2a1f2c2d2a2d2c2f2d2a2c2d2a1f2c2d2a2a2g2p8p8p8p"; // count length: 1 2 3 4 5 6 7 8 9 0 1 2 3
4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 // 10 20 30 int count = 0; int
count2 = 0; int count3 = 0; int MAX_COUNT = 24; int statePin = LOW;
void loop() { analogWrite(speakerOut, 0); for (count = 0; count < MAX_COUNT; count++) {
statePin = !statePin; digitalWrite(ledPin, statePin); for (count3 = 0; count3 <= (melody[count*2] -
48) * 30; count3++) {
Edit Page | Page History | Printable View | All Recent Site Changes
3.2
/*
*/
int bluePin = 9;
//#define COMMON_ANODE
void setup()
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
void loop()
delay(1000);
delay(1000);
delay(1000);
delay(1000);
delay(1000);
setColor(0, 255, 255); // aqua
delay(1000);
#ifdef COMMON_ANODE
#endif
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);