Sensor/Actuator interfacing with Atmega328P (Arduino): Analog and…
Open in the Padhaiko app4.4 Sensor/Actuator interfacing with Atmega328P (Arduino): Analog and digital sensors, implementation of communication protocols, interrupt based interfacing
An instrumentation system interacts with the physical world through two complementary transducers: sensors (which convert physical variables such as temperature, light, and pressure into electrical signals) and actuators (which convert electrical signals into physical action such as motion, heat, or valve position). The ATmega328P (the microcontroller powering the Arduino Uno) provides the mixed-signal peripheral hardware needed to interface, sample, and drive these devices.
4.4.1 Analog sensor interfacing
Analog sensors output continuous voltage or current signals proportional to the measured physical parameter. The ATmega328P digitizes these signals using its internal 10-bit Successive Approximation Analog-to-Digital Converter (ADC).
Internal ADC architecture of ATmega328P
The ATmega328P ADC features:
- 10-bit Resolution: Quantizes analog signals into discrete output levels ( to ).
- 6-Channel Multiplexer (Port C): Channels
ADC0throughADC5(pins 23–28 in PDIP; corresponding to Arduino analog pinsA0toA5). - Sample-and-Hold Circuitry: Freezes the input voltage onto an internal holding capacitor during the conversion phase.
- Reference Voltage Options:
- (tied to nominal).
- Internal bandgap reference (for high-precision low-voltage sensors).
- External reference via the
AREFpin ( to ).
The ADC is configured through key hardware registers:
ADMUX(ADC Multiplexer Selection Register): Selects the voltage reference source (bitsREFS1:REFS0), output data justification (ADLAR), and analog channel selection (MUX3:MUX0).ADCSRA(ADC Control and Status Register A): Controls ADC Enable (ADEN), Start Conversion (ADSC), Auto Trigger Enable (ADATE), Interrupt Flag (ADIF), Interrupt Enable (ADIE), and Prescaler division factors (ADPS2:ADPS0). The successive approximation circuitry requires an input clock between and ; on a Arduino, a prescaler of 128 yields .ADCSRB(ADC Control and Status Register B): Defines trigger sources for auto-triggered conversions (Timer/Counter compare matches, external interrupts, or free-running mode).
Interfacing a Light Dependent Resistor (LDR)
An LDR (photoresistor) changes its electrical resistance inversely with incident light intensity: in complete darkness its resistance exceeds , while in intense light its resistance drops below .
Because the ADC measures voltage rather than resistance, the LDR is placed in a voltage divider circuit with a fixed reference resistor (typically ):
+5V (VCC)
|
+---+
| | R1 = 10 kOhm (Fixed Resistor)
| |
+---+
|
+--------> Analog Pin A0 (ADC0 on ATmega328P)
| Vout = VCC * [ R_LDR / (R1 + R_LDR) ]
+---+
/ / LDR (Photoresistor)
/ / Resistance decreases with light
+---+
|
GNDThe analog output voltage is:
In darkness, (ADC reading near 1023). In bright illumination, (ADC reading near 0).
Interfacing the TMP36 precision temperature sensor
The TMP36 is a low-voltage, precision analog temperature sensor providing a voltage output linearly proportional to Celsius temperature.
- Sensitivity: .
- Output Offset: Exactly () at to permit measurement of negative temperatures down to without a dual-rail power supply.
- Transfer Function:
#include <LiquidCrystal.h>
// RS, E, D4, D5, D6, D7
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int tempPin = A0;
void setup() {
lcd.begin(16, 2);
lcd.clear();
lcd.print("Temp Monitor");
delay(1000);
}
void loop() {
int rawADC = analogRead(tempPin);
// Convert 10-bit ADC reading to voltage (0.0 V - 5.0 V)
float voltage = (float)rawADC * (5.0 / 1024.0);
// Calculate Celsius and Fahrenheit
float tempC = (voltage - 0.5) * 100.0;
float tempF = (tempC * 9.0 / 5.0) + 32.0;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(tempC, 1);
lcd.print(" C");
lcd.setCursor(0, 1);
lcd.print("Volt: ");
lcd.print(voltage, 2);
lcd.print(" V");
delay(1000); // 1-second update rate
}4.4.2 Digital sensor and input interfacing
Digital sensors deliver binary or serial digital signals, eliminating the conversion latency and noise vulnerability of analog lines.
Pushbutton inputs and switch debouncing
A mechanical pushbutton connects a digital pin to ground or . To guarantee a defined logic level when the switch is open, a pull-up or pull-down resistor must be included:
- Internal Pull-Up (
INPUT_PULLUP): Activates the ATmega328P's internal pull-up resistor. When open, the pin readsHIGH; pressing the button pulls the pin to ground (LOW).
const int buttonPin = 7;
const int ledPin = 8;
int ledState = LOW;
int lastButtonState = HIGH;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop() {
int reading = digitalRead(buttonPin);
if (reading == LOW && lastButtonState == HIGH) {
// Transition detected: software debounce delay
delay(20);
if (digitalRead(buttonPin) == LOW) {
ledState = !ledState;
digitalWrite(ledPin, ledState);
}
}
lastButtonState = reading;
}4.4.3 Actuator interfacing and motor driving
Microcontroller pins are low-power logic lines capable of delivering a maximum continuous current of only at . Heavy instrumentation actuators (solenoids, relays, DC motors, and heaters) require amperes of current and voltages from to . Interfacing requires power semiconductor switches and pulse-width modulation (PWM).
Pulse-Width Modulation (PWM) speed control
Pulse-width modulation regulates the average electrical power delivered to a load by rapidly switching supply voltage on and off at a fixed frequency while varying the duty cycle:
On the Arduino Uno, pins 3, 5, 6, 9, 10, and 11 provide hardware PWM via internal timer compare registers. Calling analogWrite(pin, value) accepts an 8-bit integer (), where 0 produces duty cycle () and 255 produces duty cycle ().
DC motor driving with transistor switch and flyback diode
A bipolar power Darlington transistor (such as the TIP120) or an N-channel power MOSFET (such as the IRLZ44N) interfaces the microcontroller's PWM output to a high-current DC motor:
+9V / +12V Motor Power Supply
|
+-------------------+
| |
--- |
/ \ DC Motor +---+
\ / Inductive | | Flyback Diode (1N4001)
--- Load | | (Cathode to +V, Anode to Collector)
| +---+
+-------------------+
|
|/ Collector (C)
Arduino Pin 9 --| TIP120 NPN Darlington
(PWM Output) |\> Emitter (E)
via 1.2k RB |
|
GND (Common Ground between Arduino & Motor Supply)4.4.4 Implementation of serial communication protocols
Instrumentation systems connect distributed sensors and digital meters using standard serial protocols:
Universal Asynchronous Receiver-Transmitter (UART)
- Signal Lines: Point-to-point asynchronous link using two lines:
TX(Transmit) andRX(Receive). - Framing: Data is framed into 1 start bit (logic 0), 8 data bits (LSB first), an optional parity bit, and 1 or 2 stop bits (logic 1).
- Baud Rate Generation: Both transmitter and receiver must share an agreed-upon baud rate. In the ATmega328P, the USART Baud Rate Register (
UBRR0) is loaded according to:
Inter-Integrated Circuit ( / TWI)
- Signal Lines: Synchronous two-wire bus:
SDA(Serial Data onPC4) andSCL(Serial Clock onPC5). Both lines are bidirectional open-drain and require external pull-up resistors (typically to ). - Bus Topology: Multi-master, multi-slave configuration where each peripheral is assigned a unique 7-bit hardware address (supporting up to 127 devices on a single pair of wires).
- Handshaking: Every transmitted 8-bit byte is followed by an Acknowledge (
ACK= low) or Not-Acknowledge (NACK= high) bit generated by the receiving device. - Example: Interfacing digital temperature sensor TC74 or LCD displays using the standard
Wire.hlibrary.
Serial Peripheral Interface (SPI)
- Signal Lines: High-speed synchronous 4-wire bus:
MOSI(Master-Out-Slave-In,PB3)MISO(Master-In-Slave-Out,PB4)SCK(Serial Clock,PB5)- (Slave Select,
PB2, active-low)
- Bus Topology: Single master, multiple slaves. A dedicated Slave Select () line is routed to each peripheral chip.
- Operation: Data exchange occurs via simultaneous shifting between master and slave 8-bit shift registers at rates up to half the CPU clock frequency (up to 8 MHz on Arduino). Used for high-bandwidth sensors (accelerometers, digital gyroscopes, SD memory cards).
| Feature | UART | (TWI) | SPI |
|---|---|---|---|
| Number of Wires | 2 (TX, RX) | 2 (SDA, SCL) | 4 (MOSI, MISO, SCK, ) |
| Synchronous / Asynch | Asynchronous (No clock line) | Synchronous (Shared clock SCL) | Synchronous (Shared clock SCK) |
| Data Rate (Speed) | Low (typically 9.6 to 115.2 kbps) | Moderate (100 kbps to 400 kbps) | Very High (up to 10–50 Mbps) |
| Topology | Point-to-point (2 devices) | Multi-master, multi-slave | Single master, multi-slave |
| Addressing Mechanism | None (direct physical connection) | 7-bit or 10-bit software address | Hardware Slave Select () lines |
| Distance Capability | Moderate (10–15 m with RS-232/485) | Short on-board () | Very short on-board () |
| Hardware Overhead | Moderate; no pull-ups required | Requires 2 pull-up resistors | Requires separate pin lines |
4.4.5 Interrupt-based interfacing
In conventional polling, the CPU constantly interrogates input pins in an infinite loop. This wastes CPU cycles, increases power consumption, and introduces latency if the processor is busy executing calculations.
In interrupt-based interfacing, external sensors or internal timers signal the CPU asynchronously:
- The CPU immediately suspends execution of the main program.
- The program counter and CPU status registers are pushed onto the stack.
- The CPU branches to the Interrupt Service Routine (ISR).
- Upon completing the ISR (
RETIinstruction), the CPU restores context and resumes the main routine seamlessly.
External interrupts on Arduino Uno
The ATmega328P provides two external hardware interrupt pins:
INT0on digital pin 2 (PD2)INT1on digital pin 3 (PD3)
They are hooked in software using: attachInterrupt(digitalPinToInterrupt(pin), ISR_function, mode); Supported trigger modes include:
LOW: Triggers whenever the pin is at logic 0.CHANGE: Triggers on both rising and falling edges.RISING: Triggers on a low-to-high transition.FALLING: Triggers on a high-to-low transition.
const int emergencyButtonPin = 2; // INT0
const int motorControlPin = 9; // Actuator output
volatile bool emergencyStop = false;
void emergencyISR() {
emergencyStop = true;
// Shut off actuator immediately in hardware
digitalWrite(motorControlPin, LOW);
}
void setup() {
pinMode(emergencyButtonPin, INPUT_PULLUP);
pinMode(motorControlPin, OUTPUT);
// Trigger on falling edge when button pulled to ground
attachInterrupt(digitalPinToInterrupt(emergencyButtonPin), emergencyISR, FALLING);
}
void loop() {
if (!emergencyStop) {
// Normal operating routine: run process
digitalWrite(motorControlPin, HIGH);
} else {
// Machine locked in safe shutdown state
while (1) {
// Await manual hardware system reset
}
}
}Worked Examples
1
A TMP36 temperature sensor is powered from and connected to analog input pin A0 of an ATmega328P. During an environmental monitoring run, analogRead(A0) returns an integer count of 164.
- Determine the analog voltage output by the TMP36.
- Calculate the corresponding measured temperature in degrees Celsius ().
- Convert this temperature to degrees Fahrenheit ().
Converting ADC count to analog voltage: The ATmega328P ADC has a 10-bit resolution ( levels) spanning to :
Evaluating Celsius temperature: The TMP36 outputs () at with a scale factor of ():
Converting to Fahrenheit:
- Sensor Output Voltage: 0.8008 V ().
- Temperature in Celsius: 30.1 C ().
- Temperature in Fahrenheit: 86.1 F.
2
A DC motor draws a continuous load current of from an external power supply. It is driven by an Arduino digital pin outputting a PWM signal via a TIP120 Darlington NPN transistor. The TIP120 has a minimum current gain of and a base-emitter saturation voltage .
- To ensure deep saturation, an overdrive factor of 3 is specified for the base current (). Calculate the required base current and the corresponding base current-limiting resistor .
- If
analogWrite(pin, 178)is applied to the base resistor, determine the PWM duty cycle and the effective average voltage supplied to the motor terminals.
Calculating the base resistor : The required saturated base current is:
The Arduino digital pin outputs . Applying Kirchhoff's Voltage Law around the base-emitter loop:
Calculating PWM duty cycle and average motor voltage: The 8-bit timer register maps to :
Neglecting small saturation drops (), the effective average voltage across the motor is:
- Base Current: 3.0 mA; Base Resistor: ().
- Duty Cycle: 69.8%; Average Motor Voltage: 6.28 V.
3
An ATmega328P running at clock frequency is programmed to transmit sensor readings over its hardware USART at a target baud rate of in normal asynchronous mode ().
- Calculate the ideal floating-point value for the Baud Rate Register
UBRR0and state the integer value loaded into the register. - Calculate the actual baud rate generated by the hardware with this integer divisor.
- Compute the percentage baud rate error and verify whether it falls within the acceptable limit for reliable serial transmission.
Evaluating the UBRR formula: In normal speed asynchronous mode (), the baud rate equation is:
Substituting and :
Rounding to the nearest integer gives:
Calculating the actual generated baud rate:
Evaluating the percentage error:
Since , the asynchronous serial link operates with exceptional timing margin and zero framing errors.
- Ideal UBRR: 103.17; Integer Loaded:
UBRR0= 103. - Actual Baud Rate: 9615.38 bps.
- Baud Rate Error: (well within the tolerance limit).
Exercises
Exercises
A precision LM35 temperature sensor produces an output of with at . A TMP36 sensor produces with at . Both are powered from .
- Calculate the voltage output of the LM35 at .
- If a TMP36 outputs , determine the measured temperature.
- If an analog sensor produces , what 10-bit integer count is returned by
analogRead()?
Calculating LM35 output:
Calculating TMP36 temperature:
Evaluating ADC integer count:
- LM35 Voltage at : 0.450 V ().
- TMP36 Temperature for : 25.0 C.
- ADC Count for : 512.
An LDR is configured in a voltage divider circuit with a fixed resistor connected between and analog pin A0, and the LDR connected between A0 and ground.
- In bright ambient sunlight, the LDR resistance drops to . Calculate the voltage at pin
A0and the corresponding 10-bit ADC reading. - In dark room conditions, the LDR resistance rises to . Calculate the new voltage at pin
A0and the corresponding ADC reading.
Evaluating bright light conditions:
Evaluating dark conditions:
- Bright Light: 0.455 V, ADC Reading = 93.
- Dark Conditions: 4.167 V, ADC Reading = 853.
A 5.0 V microcontroller digital pin drives an indicator LED with a forward operating voltage and rated forward current . Calculate the required current-limiting resistor value and select the nearest standard commercial E24 resistor.
Applying Ohm's law to the LED branch:
Selecting the nearest standard commercial E24 resistor value that maintains current safely under the continuous pin limit yields . At , actual current is:
The calculated resistance is ; the nearest standard commercial value is (resulting in an operating current of 13.6 mA).
Explain why a flyback diode must always be connected across an inductive relay coil or DC motor when controlled by a transistor switch, and draw the circuit schematic.
Physical mechanism of inductive flyback: Inductors store energy in a magnetic field (). When the transistor switch turns off, current through the coil is abruptly interrupted (). By Lenz's law and Faraday's law of induction:
The inductor generates a massive reverse voltage spike at the transistor's collector terminal, easily exceeding the collector-emitter breakdown voltage () and destroying the silicon junction.
Role and connection of the flyback diode: A rectifier diode (such as the 1N4001 or 1N4007) is wired in reverse bias directly across the inductive coil (cathode connected to the positive DC power supply rail, anode connected to the transistor collector):
- During normal conduction (transistor ON), the diode is reverse-biased and draws no current.
- Upon turn-off, the inductive kick forces the collector node voltage slightly above the supply rail, forward-biasing the diode. The stored magnetic energy dissipates safely as circulating decay current through the coil resistance, clamping the peak collector voltage to .
The flyback diode clamps hazardous inductive back-EMF voltage spikes () generated during turn-off, redirecting the stored inductive decay current safely through the coil and protecting the switching transistor from overvoltage breakdown.
An ATmega328P operates at . An engineer configures the USART for .
- Calculate the ideal UBRR, the integer loaded into
UBRR0, and the resulting percentage error in normal asynchronous speed mode (). - In double-speed mode (), the divisor formula becomes . Calculate the integer loaded into
UBRR0and the percentage error. - Compare the two modes and state why double-speed mode is necessary for high baud rates at .
Normal speed mode ():
Rounding to the nearest integer gives UBRR0 = 8. Actual baud rate:
An error of exceeds the maximum allowable tolerance (), causing severe framing errors and lost bytes.
Double-speed mode ():
Rounding to the nearest integer gives UBRR0 = 16. Actual baud rate:
While slightly over , using a crystal with exact binary multiples (e.g., or ) achieves error.
- Normal Mode:
UBRR0= 8, Baud = 111,111 bps, Error = (unacceptable). - Double-Speed Mode:
UBRR0= 16, Baud = 117,647 bps, Error = . - Double-speed mode halves the clock prescaler, doubling register resolution and substantially reducing baud rate error at high communication speeds.
Compare the and SPI serial communication protocols across signal wiring, maximum communication speed, bus master/slave addressing, and hardware complexity in instrumentation systems.
Comparing and SPI protocols:
- Signal Lines: requires only 2 shared lines (
SDAdata,SCLclock) for all connected devices. SPI requires 3 common shared lines (MOSI,MISO,SCK) plus 1 dedicated Slave Select line () per peripheral device. - Data Throughput: SPI is a full-duplex synchronous bus supporting clock rates up to 10–50 MHz (ideal for high-bandwidth displays, memories, and accelerometers). is half-duplex and limited to Standard Mode (100 kbps), Fast Mode (400 kbps), or High-Speed Mode (3.4 Mbps).
- Addressing Mechanism: addresses slaves in software using a 7-bit or 10-bit address transmitted in the first byte of every transaction. SPI uses hardware addressing via dedicated physical chip-select lines.
- Hardware Complexity: requires open-drain outputs with pull-up resistors and complex state machine logic for start/stop framing and bit-level acknowledgements (
ACK/NACK). SPI uses simple shift registers without pull-ups, resulting in minimal hardware overhead.
minimizes board traces using 2 open-drain wires and 7-bit software addressing at moderate speeds (up to 400 kbps), while SPI uses 4 wires with dedicated chip-select lines to deliver high-speed full-duplex communication (exceeding 10 Mbps).
Design an Arduino C program to sample an analog sensor connected to pin A0 at a deterministic rate of exactly using ATmega328P Timer1 CTC mode interrupts. Calculate the compare value loaded into OCR1A for a clock with prescaler , and explain why the volatile qualifier is required for the global reading buffer.
Calculating OCR1A for 100 Hz sampling: In CTC mode:
Since , it fits comfortably in the 16-bit register.
Writing the Arduino code and explaining volatile: Variables modified inside an ISR and referenced in the main event loop must be declared as volatile. Without volatile, the compiler's optimizer assumes that the variable is never modified within the sequential flow of the main loop and caches its value in a CPU register, preventing the main loop from detecting fresh sensor updates.
#include <avr/io.h>
#include <avr/interrupt.h>
volatile int sensorSample = 0;
volatile bool newSampleReady = false;
ISR(TIMER1_COMPA_vect) {
sensorSample = analogRead(A0);
newSampleReady = true;
}
void setup() {
Serial.begin(9600);
cli(); // Disable interrupts during configuration
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
OCR1A = 2499; // Set compare match for 100 Hz
TCCR1B |= (1 << WGM12); // CTC mode
TCCR1B |= (1 << CS11) | (1 << CS10); // Prescaler 64
TIMSK1 |= (1 << OCIE1A); // Enable compare interrupt
sei(); // Enable interrupts
}
void loop() {
if (newSampleReady) {
newSampleReady = false;
// Process new sample deterministically
}
}OCR1A is loaded with 2499 (with prescaler ) to generate interrupts at exactly . The volatile qualifier forces the compiler to fetch the sensor buffer directly from SRAM on every read, preventing erroneous register caching of asynchronously updated values.