Lab 7 - Programming Arduino
In questa pagina 7
Board: Arduino PlatformArduino is a family of open single-board microcontroller boards built on Atmel AVR chips (UNO, Mega, Micro), extended with stackable shields and programmed through its own IDE.Arduino Platform → (UNO). Sketches are written and uploaded from the Arduino IDE.
Structure of an Arduino program
Any program has two mandatory parts:
void setup()contains the code that initializes all the board's settings and instructions (the INPUTs and OUTPUTs) before the main loop starts; it runs once.void loop()contains the main code: a series of instructions repeated one after the other until the board is turned off.
void setup()
{
// istruzioni da eseguire una sola volta
}
void loop()
{
// istruzioni da eseguire ciclicamente
}(The comments are in Italian on the slide: "instructions to run only once" and "instructions to run cyclically".)
Basic instructions
| Command | Meaning |
|---|---|
// |
single-line comment, e.g. // This is my first Arduino program |
/* |
multi-line comment, e.g. /* This is my first Arduino program */ |
*/ |
closing of a multi-line comment |
void |
function declaration providing no outputs: the function performs operations but returns no value |
setup() |
basic (mandatory) function of every Arduino program |
loop() |
basic (mandatory) function of every Arduino program |
int |
declaration of an integer variable; also used to declare functions that return integer values |
pinMode(pin,mode) |
configures an Arduino pin so that it can be used as INPUT or as OUTPUT |
digitalWrite(pin,level) |
sends an output command on the selected digital pin, therefore 0 or 1; the constants LOW (0) and HIGH (1) can replace 0 and 1 |
delay(milliseconds) |
introduces a delay between one instruction and the next; the parameter is in thousandths of a second |
Data types
Boolean, Char, String, Byte (or unsigned char), Int, Word (or unsigned int), Long, Unsigned long, Float, Double.
const can be used in a variable declaration: it tells the compiler that the value will never be modified during execution.
Blink
Most Arduino/Genuino boards have a built-in LED connected directly to pin 13. An external LED can also be connected to pin 13; additional materials needed: one LED and one 220 ohm resistor.
Listing (the IDE example "Blink"):
/*
Blink
Turns an LED on for one second, then off for one second, repeatedly.
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
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 the Technical Specs of your board at:
https://www.arduino.cc/en/Main/Products
modified 8 May 2014
by Scott Fitzgerald
modified 2 Sep 2016
by Arturo Guadalupi
modified 8 Sep 2016
by Colby Newman
This example code is in the public domain.
https://www.arduino.cc/en/Tutorial/BuiltInExamples/Blink
*/
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}Wiring of the external LED (schematic on the slide): pin D13 -> 220 ohm resistor -> LED anode; LED cathode -> GND.
Why the resistor is needed
- LEDs can tolerate only a maximum current (e.g. red LEDs: 20 mA).
- Reference formula from the slide:
Worked check with values from the slides (computed here from the slide formula and the junction-voltage table below): with (the pin level of a digital output set HIGH, see Lab 8 - Analog Output and Sensors with ArduinoLaboratory 8 covers digital input modes, PWM analog output with analogWrite (LED fading), the 10-bit analogRead input, the map and constrain functions, trimmer and photoresistor exercises, the LM35 temperature sensor and two additional exercises (hysteresis and potentiometer-controlled data logger).Lab 8 - Analog Output and Sensors with Arduino →), a red LED with and gives . The 220 ohm resistor used in the lab is above this minimum: , below 20 mA.
LED junction voltages
The operating voltage depends on the LED colour, and the operating current must also be known (between 10 and 30 mA).
| LED type | Junction voltage (V) |
|---|---|
| Infrared | 1.3 |
| Red | 1.8 |
| Yellow | 1.9 |
| Green | 2.0 |
| Orange | 2.0 |
| Blue/White flash | 3.0 |
| Blue | 3.5 |
Push button switch
The slide shows a 4-leg tactile switch with legs A, B, C, D (symbol: two contacts between A and B).
- Rest position: contacts separated, circuit open (no current flows); only A is connected to D and B to C.
- Pressed: the button activates the contact and closes the circuit; now A-B and D-C are also connected.
- Released: the spring pushes the button up and separates the contacts.
LED driven by the button (no microcontroller)
- The button is inserted in the previous LED circuit, between the resistor and the jumper going to the digital power pin (or between the LED and the jumper going to GND: it makes no difference).
- While the button is pressed the LED is on; when released it is off. It is not convenient to keep the LED on only while the button is held.
- This circuit could be built without Arduino: a common battery is enough (choosing the resistor from the battery voltage).
LED driven by the microcontroller
- The microcontroller makes the circuit "smarter": the information that a button was pressed is used without having to keep it pressed.
- The LED circuit is separated from the button circuit, and a sketch manages the button.
- Breadboard: the button is connected to 5 V and ground (GND) through a 10 kOhm resistor; to detect whether the button is pressed or released a connection goes to pin 6 (the LED has its own 220 ohm resistor).
Blink with buttons (three LEDs, two buttons)
Circuit (figure): three LEDs, each with a series resistor, on pins 11, 12 and 13 (common return to GND), and two push buttons on pins 2 (up) and 3 (down).
Sketch, as on the slides:
/*
This Example shows how to select LED to turn on with two
buttons Up and Down
*/
// Pin definition:
int led1 = 11;
int led2 = 12;
int led3 = 13;
int buttonUp = 2;
int buttonDown = 3;
// Variables definition
int led = 1; //LED to tur no
void setup() {
// Set pins as output
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
// Set pins as input
pinMode(buttonUp, INPUT);
pinMode(buttonDown, INPUT);
// Enabling internal pull-up resistors on the input pins.
// Such interal resistors have very high impedence vales.
// They are needed to avoid electromagnetic interferences
// whenver open circuits (e.g., pins without LEDs). Such
// intereferences may cause unwanted swithing of the outputs
}
void loop() {
if(digitalRead(buttonUp)==0){ // buttonUp is pressed
led++; // increment the LED variable
if(led>3){ // if the LED variable is bigger than 3
led = 1; // set it to 1
}
delay(500); // pause for debouncing
}
if(digitalRead(buttonDown)==0){ // buttonDown is pressed
led--; // decrement the LED variable
if(led<1){ // if the LED variable is less than 1
led = 3; // set it to 3
}
delay(500); // pause for debouncing
}
if(led==1){
digitalWrite(led1, HIGH); // turn on LED 1
digitalWrite(led2, LOW); // turn off LED 2
digitalWrite(led3, LOW); // turn off LED 3
}
if(led==2){
digitalWrite(led1, LOW); // turn off LED 1
digitalWrite(led2, HIGH); // turn on LED 2
digitalWrite(led3, LOW); // turn off LED 3
}
if(led==3){
digitalWrite(led1, LOW); // turn off LED 1
digitalWrite(led2, LOW); // turn off LED 2
digitalWrite(led3, HIGH); // turn on LED 3
}
}Reading the sketch:
- A button press is detected as
digitalRead(...)==0: the code treats a LOW level as "pressed". ledis a counter that wraps around: 1 -> 2 -> 3 -> 1 with buttonUp, and 3 -> 2 -> 1 -> 3 with buttonDown.delay(500)after a press is a pause for debouncing, i.e. it ignores the contact bounce and avoids counting the same press several times (and also fixes the maximum step rate to two per second).- The comment in
setup()talks about enabling the internal pull-up resistors, but the listing as shown sets the pins withINPUTand noINPUT_PULLUPordigitalWrite(pin, HIGH)line. The statement "internal pull-up enabled" is therefore not implemented in the code shown; the external 10 kOhm resistor of the button circuit takes that role. Pull-up modes are covered in Lab 8 - Analog Output and Sensors with ArduinoLaboratory 8 covers digital input modes, PWM analog output with analogWrite (LED fading), the 10-bit analogRead input, the map and constrain functions, trimmer and photoresistor exercises, the LM35 temperature sensor and two additional exercises (hysteresis and potentiometer-controlled data logger).Lab 8 - Analog Output and Sensors with Arduino → (INPUT_PULLUP).
Additional exercise: counter with buttons
Build a circuit with three buttons and an LED:
- each time the first button is pressed and released, an internal counter is incremented by 1;
- when a second button is pressed, the counter is reset to zero;
- when a third button is pressed, the LED flashes a number of times equal to the counter value.
(No solution is given on the slides.)
Versione ripasso
- Program structure:
void setup()runs once and configures the pins (INPUT or OUTPUT);void loop()repeats until power-off. Sketches are written and uploaded from the Arduino IDE on the Arduino PlatformArduino is a family of open single-board microcontroller boards built on Atmel AVR chips (UNO, Mega, Micro), extended with stackable shields and programmed through its own IDE.Arduino Platform → UNO. - Basic instructions:
//and/* */comments;void(no return value);int(also for functions returning an integer);pinMode(pin, mode): INPUT or OUTPUT;digitalWrite(pin, level): 0 or 1,LOWandHIGHcan replace them;delay(ms): pause in thousandths of a second.
- Data types: Boolean, Char, String, Byte (unsigned char), Int, Word (unsigned int), Long, Unsigned long, Float, Double.
constmeans the value is never modified. - Blink: most boards have an on-board LED on pin 13 (
LED_BUILTIN).
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // LED on
delay(1000);
digitalWrite(LED_BUILTIN, LOW); // LED off
delay(1000);
}- External LED: pin 13, then a 220 ohm resistor, then the LED anode; cathode to GND.
- Resistor sizing:
- red LED: maximum 20 mA, junction voltage 1.8 V; operating current between 10 and 30 mA;
- with : minimum; 220 ohm gives about 14.5 mA;
- junction voltages: infrared 1.3 V, red 1.8, yellow 1.9, green 2.0, orange 2.0, blue/white flash 3.0, blue 3.5.
- Push button (4 legs A, B, C, D): at rest A-D and B-C are connected and A-B is open; pressed, A-B and D-C also connect.
- Button without microcontroller: the LED is on only while the button is held; a battery is enough.
- Button with microcontroller: button between 5 V and GND through 10 kOhm, sense pin 6; the LED has its own 220 ohm resistor. The program keeps the information that a press happened.
- Blink with buttons: LEDs on pins 11, 12, 13 (each with a series resistor), buttons on pins 2 (up) and 3 (down).
- a press is detected as
digitalRead(buttonUp)==0, so LOW means pressed; ledis a counter that wraps: 1, 2, 3, 1 going up and 3, 2, 1, 3 going down;delay(500)after a press is a debounce pause: it ignores contact bounce and limits the rate to two presses per second;- each
if(led==...)block turns on only the selected LED and turns the other two off. - The comment in
setup()says the internal pull-up is enabled, but the code only usesINPUT(noINPUT_PULLUP): the 10 kOhm external resistor does that job. Pull-up modes: Lab 8 - Analog Output and Sensors with ArduinoLaboratory 8 covers digital input modes, PWM analog output with analogWrite (LED fading), the 10-bit analogRead input, the map and constrain functions, trimmer and photoresistor exercises, the LM35 temperature sensor and two additional exercises (hysteresis and potentiometer-controlled data logger).Lab 8 - Analog Output and Sensors with Arduino →.
- a press is detected as
- Exercise: three buttons and one LED. Button 1 increments a counter on each press and release; button 2 resets it to zero; button 3 makes the LED flash as many times as the counter. No solution is given on the slides.
- Typical mistakes:
- LED with no series resistor;
- floating input pins (random readings);
- relying on the pull-up comment without
INPUT_PULLUP; - no debounce pause after a press.