Lab 8 - Analog Output and Sensors with Arduino
In questa pagina 12
Continuation of Lab 7 - Programming ArduinoLaboratory 7 introduces Arduino programming with setup and loop, the basic instructions and data types, the Blink sketch with LED resistor sizing, push buttons and a three-LED selector sketch.Lab 7 - Programming Arduino → 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).
Digital pin behaviour (recap from the slide)
pinMode(pin, OUTPUT): withdigitalWrite()HIGH the pin is at 5 V, with LOW at 0 V.pinMode(pin, INPUT):digitalRead()returns LOW if the voltage is less than 2 V.pinMode(pin, INPUT_PULLUP): the internal pull-up resistor is activated and the value on the pin is set at 5 V (when nothing pulls it down).
Analog write: PWM
- The PWM (Pulse Width Modulation) technique makes a pin go from HIGH to LOW continuously, with a frequency of many cycles per second: 490 Hz for some pins and 980 Hz for others.
- It is used to "simulate" an analog value on a digital pin (e.g. a fading effect on an LED), with the instruction
analogWrite(pin, value)- The technique uses different duty cycles, i.e. the ratio between the time the signal is high and the duration of the period:
Figure of the slide (waveforms between 0 V and 5 V, same period):
| Duty cycle | Call | Waveform |
|---|---|---|
| 0 % | analogWrite(0) |
always 0 V |
| 25 % | analogWrite(64) |
high for a quarter of each period |
| 50 % | analogWrite(127) |
high for half of each period |
| 75 % | analogWrite(191) |
high for three quarters of each period |
| 100 % | analogWrite(255) |
always 5 V |
valueranges from 0 to 255; 255 means the pin is always HIGH. It represents the ratio between the duration of the HIGH and LOW signals.- PWM pins of the UNO: 3, 5, 6, 9, 10 and 11 (marked "PWM" or "~" on the board).
Fading
Materials: Arduino, LED, 220 ohm resistor. Wiring: digital pin 9 -> 220 ohm resistor -> LED -> GND (schematic: D9, 220 ohm, LED1, GND).
Sketch (shown over two slides):
/*
Fading
This example shows how to fade an LED using the analogWrite() function.
The circuit:
* LED attached from digital pin 9 to ground.
*/
int ledPin = 9; // LED connected to digital pin 9
void setup() {
// nothing happens in setup
}
void loop() {
// fade in from min to max in increments of 5 points:
for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
// fade out from max to min in increments of 5 points:
for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}Exercise: check the operation of the sketch on the breadboard; change the values in the sketch to obtain other effects.
Analog read
- Digital HIGH/LOW values are often not enough to read sensors: a finer level of information is needed.
- The UNO microcontroller has a 6-channel ADC connected to pins A0-A5, with a resolution of 10 bits: an electrical quantity is represented with values in 0-1023. (For the general theory of A/D conversion see Analog-to-Digital ConversionAnalog-to-digital conversion consists of sampling (sample-and-hold), uniform quantization with step Delta and error uniformly distributed in plus or minus Delta over 2, and binary coding; flash, successive-approximation and integrating converters trade speed against resolution.Analog-to-Digital Conversion →; for resolution and quantization of a sensor chain see Non-Idealities in a Control Loopmodels and control consequences of the main non-idealities of a feedback loop, namely sensor bias, noise, quantization and limited bandwidth, actuator saturation and limited bandwidth, time delays with Pade approximations, disturbances and parameter or model uncertainties.Non-Idealities in a Control Loop →.)
- Instruction:
analogRead(pin), whose only parameter is the pin to read; it returns the converted value of the read voltage. - Conversion to volts used in the example (reference 5 V, 1023 full-scale code):
so one count corresponds to (computed from the formula of the slide).
ReadAnalogVoltage sketch
/*
ReadAnalogVoltage
Reads an analog input on pin 0, converts it to voltage, a[...]
Graphical representation is available using serial plotter (Tools > Serial Plotter menu).
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
This example code is in the public domain.
*/
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
}(The end of the second comment line is hidden behind a callout on the slide; the rest of the listing is as shown. The first comment lines carry the standard text of the IDE example.)
Remarks from the slide callouts:
- The
Serialinstruction is used to communicate with the PC or other devices: communication between Arduino and external devices goes through the USB port or through pins 0 (RX) and 1 (TX), which therefore cannot be used as digital inputs and outputs. - On the IDE's Serial Monitor random values appear when the pin is left unconnected: the Arduino analog pins have high impedance, so if left empty they give fluctuating values.
- Quick test of the correct operation: connect A0 to the 3.3 V pin, the 5 V pin or GND and check that the output gives precisely that value.
Trimmer (potentiometer)
Exercise: use a 10 kOhm potentiometer connected as in the schematic: one end to 5 V, the other end to GND, the wiper (middle terminal) to A0; read the value while the resistance varies.
Trimmer - LED and map
Exercise: control an LED with the trimmer, using the new instruction
map(sensorValue, minValIn, maxValIn, minValOut, maxValOut)map converts data from one range of values to another, e.g. when the analog pins give 0-1023 while the PWM pins accept 0-255. It has 5 parameters:
- the value to convert,
- the lower limit of the input values,
- the upper limit of the input values,
- the lower limit of the output values,
- the upper limit of the output values.
(The wiring on the slide: LED with series resistor on a PWM pin and GND; potentiometer on 5 V, GND and an analog pin. No sketch is given.)
Photoresistor - LED (on/off)
- A photoresistor has a resistance inversely proportional to the amount of light hitting it. The current through it is also related to the light intensity, which makes it a "potentiometer" actuated by light instead of mechanical force or electrical signals.
- Materials/connections from the slide: photoresistor -> 5 V and the resistor; 10 kOhm resistor -> A0 and GND; LED -> GND and pin 13. That is a voltage divider: 5 V, photoresistor, node on A0, 10 kOhm, GND. As light increases the photoresistor's resistance falls and the voltage at A0 rises (derived from the divider, not stated on the slide).
Sketch (comments in Italian on the slide, kept as shown):
#define fotoresistenza A0
#define led 13
void setup()
{
pinMode(A0,INPUT);
pinMode(13,OUTPUT);
Serial.begin(9600); // Inizializzo la comunicazione seriale
}
void loop()
{
int val = analogRead(fotoresistenza); // salvo il valore fotoresistenza dentro alla variabile val
Serial.println(val, DEC); // Scrivo il valore della fotoresistenza, espresso in numeri decimali
if(val<800) //se il valore letto dalla fotoresistenza (luminosità) è basso, accendo il led
digitalWrite(led,HIGH);
else
digitalWrite(led,LOW); //altrimenti lo spengo (o lo lascio spento)
}(Italian comments: "I initialize serial communication"; "I save the photoresistor value in the variable val"; "I write the photoresistor value, expressed in decimal numbers"; "if the value read by the photoresistor (brightness) is low, I switch the LED on"; "otherwise I switch it off (or leave it off)".)
Photoresistor - LED (PWM)
Exercise: set up the sketch, very similar to the trimmer-LED case. The difference with the on/off case is that, using PWM, the LED has intermediate degrees of brightness. Wiring: LED with series resistor on a PWM pin, photoresistor and 10 kOhm resistor as divider on A0.
Photoresistor - LED (Optimization): calibration and constrain
- The mapping is carried out between two minimum and maximum values (here 140 and 810) detected in real operating conditions: it is a calibration.
constrain()after the mapping makes sure that data outside the experimentally identified range do not generate out-of-scale values.
Reading and calibration sketch:
/*
Lettura e taratura di una fotoresistenza
*/
const int sensorPin = A0; // il pin di input
// del sensore
// dichiarazione delle variabili:
int sensorValue = 0; // variabile per memorizzare
// i dati in ingresso
int parsedValue = 0; // variabile per memorizzare
// il dato ripulito
void setup( ) {
// inizializzazione comunicazione seriale
Serial. begin(9600) ;
}
void loop( ) {
// lettura del valore dal sensore
sensorValue = analogRead( sensorPin) ;
// mappatura della lettura
parsedValue = map(sensorValue, 140, 810, 0, 255) ;
parsedValue = constrain(parsedValue, 0, 255) ;
// comunicazione su seriale
Serial. println( parsedValue) ;
// delay per la stabilità del programma
delay(1) ;
}Analog input with calibration and PWM output:
/*
Input analogico con taratura e output PWM
*/
// dichiarazione costanti:
const int sensorPin = A0; // pin di input del sensore
const int ledPin = 9; // il pin di output PWM per il LED
// dichiarazione variabili:
int sensorValue = 0; // per memorizzare i dati in ingresso
int ledValue = 0; // per il valore della luminosità
void setup( ) {
pinMode( ledPin, OUTPUT); // impostazione del pin in output
Serial. begin( 9600) ; //comunicazione seriale
}
void loop( ) {
sensorValue = analogRead( sensorPin) ;
ledValue = map(sensorValue, 140, 810, 0, 255) ;
ledValue = constrain(ledValue, 0, 255) ;
analogWrite(ledPin, ledValue) ;
Serial.print( sensorValue) ;
Serial.print( "\t") ;
Serial.println(ledValue) ;
// delay per la stabilità del programma
delay( 1) ;
}The mapping of the numbers: 140 maps to 0 and 810 maps to 255; since map does not clip, a reading below 140 would give a negative value and one above 810 a value larger than 255, which constrain(value, 0, 255) brings back into range.
LM35 temperature sensor
A widely used analog temperature sensor:
- 3 terminals: supply, output, GND. The text of the slide gives the supply as 4 to 20 V; the pinout figure on the same slide labels it "anywhere between 4 to 30 Vdc" (the two values disagree on the slide).
- Output: 10 mV for each degree Celsius (sensitivity).
- Accuracy ±0.5 degC.
- , (the LM35DZ, more common on the market, only operates above zero).
Exercise: read the temperature and plot it on the Serial Monitor. (Derived reading chain, not written on the slide: with analogRead and the 5 V reference, and , so one ADC count is about 0.49 degC, comparable to the sensor accuracy.)
Additional exercise: LED control with adjustable hysteresis
Aim: a light-activated system that avoids the flickering caused by small fluctuations of the sensor readings.
- Use the photoresistor to measure ambient light and the potentiometer to set the user-defined switching threshold.
- Instead of switching with a single threshold, use hysteresis: two different thresholds for switching on and off.
- The potentiometer sets the central threshold; the program computes two derived values, one slightly above and one slightly below it.
- When the light level falls below the lower threshold, the LED turns on; when it rises above the upper threshold, the LED turns off.
- Result: stable behaviour even when the light changes rapidly or the signal contains electrical noise.
Additional exercise II: manual data logger controlled by a potentiometer
Aim: a data-logging system whose sampling rate is controlled in real time by a potentiometer.
- One of the two sensors (LM35 or LDR) is read periodically and the measurements are sent to the Serial Monitor in a structured, time-stamped format.
- The potentiometer defines the operating mode:
- turned left: acquisition stopped;
- near the centre: slow logging, one measurement per second;
- turned right: fast logging, around ten measurements per second.
- The program uses
millis()for non-blocking timing and to attach a timestamp to each sample.
(No solutions are given on the slides.)
Versione ripasso
- Digital pin behaviour:
- OUTPUT with
digitalWriteHIGH gives 5 V, LOW gives 0 V; - INPUT:
digitalReadreturns LOW when the voltage is below 2 V; INPUT_PULLUP: activates the internal pull-up, so the pin reads 5 V when nothing pulls it down.
- OUTPUT with
- PWM (Pulse Width Modulation): the pin switches HIGH and LOW many times per second (490 Hz on some pins, 980 Hz on others), simulating an analog level.
analogWrite(pin, value); // value 0-255- duty cycle ;
value0, 64, 127, 191, 255 gives 0, 25, 50, 75, 100 %; - PWM pins on the UNO: 3, 5, 6, 9, 10, 11 (marked "~").
- Fading: LED with a 220 ohm resistor on pin 9 to GND. The loop ramps
fadeValuefrom 0 to 255 and back, in steps of 5, withdelay(30)between writes. - Analog input: 6 channels A0-A5 with a 10-bit ADC (values 0-1023). Theory: Analog-to-Digital ConversionAnalog-to-digital conversion consists of sampling (sample-and-hold), uniform quantization with step Delta and error uniformly distributed in plus or minus Delta over 2, and binary coding; flash, successive-approximation and integrating converters trade speed against resolution.Analog-to-Digital Conversion →; resolution and quantization of the sensor chain: Non-Idealities in a Control Loopmodels and control consequences of the main non-idealities of a feedback loop, namely sensor bias, noise, quantization and limited bandwidth, actuator saturation and limited bandwidth, time delays with Pade approximations, disturbances and parameter or model uncertainties.Non-Idealities in a Control Loop →.
int sensorValue = analogRead(A0);
float voltage = sensorValue * (5.0 / 1023.0); // 1 count = about 4.9 mV- pins 0 (RX) and 1 (TX) are used by the USB serial link, so they cannot be used as I/O;
- a floating analog pin has high impedance and gives random values: test with A0 tied to 3.3 V, 5 V or GND and check the value;
Serial.begin(9600)andSerial.println(...)feed the Serial Monitor or Serial Plotter.- Trimmer: 10 kOhm potentiometer, ends on 5 V and GND, wiper on A0.
mapconverts a range to another:map(sensorValue, minValIn, maxValIn, minValOut, maxValOut), e.g. 0-1023 to 0-255 for PWM.- Photoresistor: resistance falls as light increases. Divider with a 10 kOhm resistor from A0 to GND, 5 V on the other side.
- on/off version: the LED on pin 13 is on when
val<800, off otherwise; - PWM version: intermediate brightness.
- on/off version: the LED on pin 13 is on when
- Photoresistor divider: the voltage at A0 rises with light, because the photoresistor resistance falls.
- Hysteresis logic: below the lower threshold the LED turns on, above the upper one it turns off; in between it keeps its state.
- Calibration: the readings in real conditions go from 140 to 810.
parsedValue = map(sensorValue, 140, 810, 0, 255);
parsedValue = constrain(parsedValue, 0, 255);mapdoes not clip:constrainbrings out-of-range values back into 0-255.- LM35: analog temperature sensor, 3 pins (supply, output, GND).
- output 10 mV per degree Celsius; accuracy degC; range -55 to 150 degC (LM35DZ only above zero);
- the text gives the supply as 4 to 20 V, the figure as 4 to 30 V.
- Reading chain (derived, not on the slide): degC, so one count is about 0.49 degC.
- Exercise, hysteresis: photoresistor for light, potentiometer for the threshold; two thresholds (a bit above and below the pot value). LED on when light falls below the lower threshold, off when it rises above the upper one. Stable with noisy signals.
- Exercise, data logger: LM35 or LDR read periodically, time-stamped output to the serial monitor. The potentiometer sets the mode: left = stopped, centre = one sample per second, right = about ten per second. Use
millis()for non-blocking timing and timestamps. - Typical mistakes:
- using pins 0 and 1 as I/O while the serial link is active;
analogWriteon a non-PWM pin;- no
constrainaftermap; - a single threshold instead of hysteresis, which causes flicker.