3B Infrastructure home

All subjects

Embedded System 1 (Arduino)

First steps with hardware on an Arduino Uno: blinking an LED, reading sensors, dimming with PWM, and reacting with interrupts. Press play on any sketch to watch it happen.

2 Analog input and PWM

The real world is not just on or off. An ADC turns a voltage into a number, and PWM fakes an in-between output by switching a pin on and off very quickly.

  • analogRead: the Uno has a 10-bit ADC, so 0 V to 5 V becomes 0 to 1023.
  • Voltage: V = reading × 5 / 1023.
  • analogWrite: PWM from 0 to 255 on the pins marked ~.
  • Duty cycle: the share of time the pin is on. 50% looks half as bright.
void loop() {
  int raw = analogRead(A0);                 // 0 to 1023
  int brightness = map(raw, 0, 1023, 0, 255);
  analogWrite(9, brightness);               // PWM on pin 9
}

Signal flow diagram

Knob2.5 VADC0map()0PWM0%LED is off

1/4 Turn the knob halfway. The voltage on A0 is now 2.5 V.

Rule of thumb: Use map() to convert between ranges, such as 0 to 1023 into 0 to 255.

3 Interrupts and debouncing

Polling means checking a button over and over, and a slow loop can miss a quick press. An interrupt makes the hardware stop your code the instant something happens, run a short function, and carry on.

  • attachInterrupt: on the Uno, pins 2 and 3 can trigger an interrupt.
  • ISR: interrupt service routine. Keep it very short, with no delay() or Serial.
  • volatile: marks variables shared with an ISR, so the compiler always reads them fresh.
  • Bouncing: a mechanical button contact chatters for a few milliseconds and looks like many presses.
volatile bool pressed = false;

void onPress() { pressed = true; }

void setup() {
  pinMode(2, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(2), onPress, FALLING);
}

void loop() {
  if (pressed) {
    pressed = false;
    // handle it here
  }
}

Interrupt flow

ButtonISRloop(): busywith a slow jobpressedfalse

1/4 The main loop is busy with a slow job, like updating a display.

Rule of thumb: In an ISR, set a flag and leave. Do the real work in loop().