PadhaikoAll subjects

Sensor/Actuator interfacing with Atmega328P (Arduino): Analog and…

Instrumentation (ENEX 252)

Open in the Padhaiko app

4.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:

The ADC is configured through key hardware registers:

  1. ADMUX (ADC Multiplexer Selection Register): Selects the voltage reference source (bits REFS1:REFS0), output data justification (ADLAR), and analog channel selection (MUX3:MUX0).
  2. 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 .
  3. 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 ):

LDR Voltage Divider Interfacing to ArduinoText
           +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
         +---+
           |
          GND

The 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.

Arduino C Program: TMP36 Temperature Reading and LCD DisplayC
#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:

Arduino C: Button Input with Software DebounceC
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:

Transistor Driver Circuit with Inductive Flyback ProtectionText
                +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)

Inter-Integrated Circuit ( / TWI)

Serial Peripheral Interface (SPI)

Comparison of Instrumentation Communication Protocols
FeatureUART (TWI)SPI
Number of Wires2 (TX, RX)2 (SDA, SCL)4 (MOSI, MISO, SCK, )
Synchronous / AsynchAsynchronous (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)
TopologyPoint-to-point (2 devices)Multi-master, multi-slaveSingle master, multi-slave
Addressing MechanismNone (direct physical connection)7-bit or 10-bit software addressHardware Slave Select () lines
Distance CapabilityModerate (10–15 m with RS-232/485)Short on-board ()Very short on-board ()
Hardware OverheadModerate; no pull-ups requiredRequires 2 pull-up resistorsRequires 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:

  1. The CPU immediately suspends execution of the main program.
  2. The program counter and CPU status registers are pushed onto the stack.
  3. The CPU branches to the Interrupt Service Routine (ISR).
  4. Upon completing the ISR (RETI instruction), the CPU restores context and resumes the main routine seamlessly.

External interrupts on Arduino Uno

The ATmega328P provides two external hardware interrupt pins:

They are hooked in software using: attachInterrupt(digitalPinToInterrupt(pin), ISR_function, mode); Supported trigger modes include:

Arduino C: Emergency Machine Interlock via External InterruptC
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

Example 1

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.

  1. Determine the analog voltage output by the TMP36.
  2. Calculate the corresponding measured temperature in degrees Celsius ().
  3. 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:

Answer:
  1. Sensor Output Voltage: 0.8008 V ().
  2. Temperature in Celsius: 30.1 C ().
  3. Temperature in Fahrenheit: 86.1 F.
Example 2

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 .

  1. 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 .
  2. 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:

Answer:
  1. Base Current: 3.0 mA; Base Resistor: ().
  2. Duty Cycle: 69.8%; Average Motor Voltage: 6.28 V.
Example 3

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 ().

  1. Calculate the ideal floating-point value for the Baud Rate Register UBRR0 and state the integer value loaded into the register.
  2. Calculate the actual baud rate generated by the hardware with this integer divisor.
  3. 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.

Answer:
  1. Ideal UBRR: 103.17; Integer Loaded: UBRR0 = 103.
  2. Actual Baud Rate: 9615.38 bps.
  3. Baud Rate Error: (well within the tolerance limit).

Exercises

Exercises

Question 1

A precision LM35 temperature sensor produces an output of with at . A TMP36 sensor produces with at . Both are powered from .

  1. Calculate the voltage output of the LM35 at .
  2. If a TMP36 outputs , determine the measured temperature.
  3. If an analog sensor produces , what 10-bit integer count is returned by analogRead()?

Calculating LM35 output:

Calculating TMP36 temperature:

Evaluating ADC integer count:

Answer:
  1. LM35 Voltage at : 0.450 V ().
  2. TMP36 Temperature for : 25.0 C.
  3. ADC Count for : 512.
Question 2

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.

  1. In bright ambient sunlight, the LDR resistance drops to . Calculate the voltage at pin A0 and the corresponding 10-bit ADC reading.
  2. In dark room conditions, the LDR resistance rises to . Calculate the new voltage at pin A0 and the corresponding ADC reading.

Evaluating bright light conditions:

Evaluating dark conditions:

Answer:
  1. Bright Light: 0.455 V, ADC Reading = 93.
  2. Dark Conditions: 4.167 V, ADC Reading = 853.
Question 3

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:

Answer:

The calculated resistance is ; the nearest standard commercial value is (resulting in an operating current of 13.6 mA).

Question 4

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 .
Answer:

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.

Question 5

An ATmega328P operates at . An engineer configures the USART for .

  1. Calculate the ideal UBRR, the integer loaded into UBRR0, and the resulting percentage error in normal asynchronous speed mode ().
  2. In double-speed mode (), the divisor formula becomes . Calculate the integer loaded into UBRR0 and the percentage error.
  3. 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.

Answer:
  1. Normal Mode: UBRR0 = 8, Baud = 111,111 bps, Error = (unacceptable).
  2. Double-Speed Mode: UBRR0 = 16, Baud = 117,647 bps, Error = .
  3. Double-speed mode halves the clock prescaler, doubling register resolution and substantially reducing baud rate error at high communication speeds.
Question 6

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 (SDA data, SCL clock) 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.
Answer:

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).

Question 7

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.

Deterministic 100 Hz Sensor Sampling via Timer1 ISRC
#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
    }
}
Answer:

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.

Past exam questions for Instrumentation

← Microcontrollers (Atmega328, STM32): Architecture, pin configuration…Connectivity Technology in Instrumentation System →