A0MCUATmega328P0123401USB01010101010101010101std0d1d2d3d4d5d6d7sp1Serial.begin(9600);2int raw = analogRead(A0);3float v = raw / 1023 * 5.0;float v = raw * 5.0 / 1023;4Serial.println(raw);5Serial.println(v);6digitalWrite(13, v > 2.0);SERIAL MONITOR · 9600 baud512512CRLF5120.002.501
Back: the Uno board (knob, microcontroller, LED, TX line, USB chip)Front: the sketch card and the laptop's Serial MonitorTokens: the reading, the printed characters, the bits on the wire and the printed valuesAn Arduino Uno R3: a knob on A0, the ATmega328P with its transmit buffer, an LED on pin 13, and the TX line from pin 1 through the USB chip to the Serial Monitor on a laptop. Serial.println(raw) turns 512 into the bytes '5' '1' '2' CR LF; the UART sends each as 10 bits at 9600 baud. Printing raw (512, right) and v (0.00, wrong) points at line 3: whole-number division. Fixed, v prints 2.50 and the LED lights.

The problem

  1. Our sketch should light the LED when the knob gives more than 2.0 volts. We turn it past half way, and nothing. The code compiles and runs, but the chip has no screen. We cannot see its variables.

How a print travels

Finding the bug

What happens

;; step 1/10 · bug
board   Arduino Uno R3  (ATmega328P)
want    knob voltage > 2.0 V  ->  LED on pin 13 on
got     LED stays off unless the knob is turned all the way
problem the values live inside the chip, out of sight

// Arduino Uno R3: a knob (potentiometer) on A0, an LED on pin 13
void setup() {
  pinMode(13, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int raw = analogRead(A0);
  float v = raw / 1023 * 5.0;   // the bug
  Serial.println(raw);
  Serial.println(v);
  digitalWrite(13, v > 2.0);
  delay(500);
}

The card shows the lines that matter. Line 1 runs once in setup(), next to pinMode(13, OUTPUT); lines 2 to 6 are the body of loop(), which ends with delay(500). The full sketch is in the step notes. Serial.begin(9600) uses the default format, SERIAL_8N1: 8 data bits, no parity bit, 1 stop bit, so every byte costs 10 bits on the wire. When nothing is being sent the TX line rests at 1, and the start bit's drop to 0 tells the receiver a byte is coming.