School of Engineering · Playlist

Microcontroller Basics

Microcontroller inputs and programs, digital and analog signals, analog-to-digital conversion, and PWM.

  1. Microcontroller Basics
  2. Digital and Analog Signals
  3. Analog-to-Digital Conversion
  4. Pulse-Width Modulation
Engineering Fundamentals/Electrical Systems

Microcontroller Basics

Read inputs, make decisions in a program, and control outputs using a classic Arduino Uno R3.

A microcontroller reads inputs and controls outputs

A microcontroller reads inputs and controls outputs

A microcontroller is a small computer on a chip, with a processor, memory and connections to the outside world. Its program can read a switch, decide what that input means, and turn an output on or off. The Arduino Uno is a board that supplies the chip with power connections, a USB interface and accessible pins.

This topic uses the classic Uno R3 with an ATmega328P, operating with 5 V logic. Other Arduino boards, including newer Uno models, can have different converters and electrical limits.

Simplified Uno R3 outline: digital pins D0 through D13, PWM on D3 D5 D6 D9 D10 D11, and analog inputs A0 through A5.

The drawing groups functions; it is not a wiring pinout. Check the labels on the actual board. Start with Digital and Analog Signals, then Analog-to-Digital Conversion and Pulse-Width Modulation.

A sketch runs setup once, then repeats loop

A sketch runs setup once, then repeats loop

An Arduino program is called a sketch. It uses C/C++ syntax: rules for names, parentheses, braces and statements. It is a programming language, not ordinary English. Capitalization matters: digitalRead and digitalread are different names.

setup() runs once after startup or reset. loop() repeats while the program runs. This original example turns the built-in LED on for half a second and off for half a second.

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(500);
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
}

delay uses milliseconds and pauses normal progress through the sketch. The braces group the statements belonging to each function.

Choose the pin mode before using the pin

Choose the pin mode before using the pin

Three pin modes
ModeWhat it doesTypical use
INPUTReads a voltage level without enabling the internal pull-up.A sensor that actively drives a compatible signal; do not leave the input floating.
OUTPUTDrives the pin HIGH or LOW.An LED through a current-limiting resistor, or a control signal to a driver.
INPUT_PULLUPReads an input with an internal resistor pulling it toward the logic supply.A button connecting the input to ground.

pinMode(pin, mode) configures the pin. digitalRead(pin) returns HIGH or LOW. On an OUTPUT pin, digitalWrite(pin, HIGH) drives it toward the logic supply; LOW drives it toward ground. These are limited-current signals, not ideal power supplies. On an INPUT pin, digitalWrite instead controls the pull-up.

A button to ground reads LOW when pressed

A button to ground reads LOW when pressed

With INPUT_PULLUP, an open switch reads HIGH. Closing the switch to ground reads LOW. This is called active-low: the action happens when the signal is low.

Internal pull-up resistor from 5 V to the input node, with a normally open button from that node to ground. Open gives HIGH; closed gives LOW.

void setup() {
  pinMode(2, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
  bool pressed = (digitalRead(2) == LOW);
  digitalWrite(LED_BUILTIN, pressed ? HIGH : LOW);
}

The pull-up supplies a small current through the closed switch to ground. The switch sinks that current. A physical switch can bounce between states briefly; counting presses reliably needs debouncing beyond this simple state display.

Supporting detail: Addendum 1 — Pull-up resistance and current.

Use the official IDE and function reference; Checklist; Practice

Use the official IDE and function reference

Get the IDE from Arduino Software. Use the Arduino language reference to check spelling, arguments and return values. The Arduino getting-started guide introduces the programming environment.

  • Confirm the board model and choose its matching board entry in the IDE.
  • Select the port belonging to the connected board.
  • Verify the sketch to catch syntax errors, then upload it.
  • Check that the observed input and output match the program.

Disconnect power before changing wiring. Keep signals within the board's ratings and use a suitable driver for a motor. See Electrical Safety for electrical precautions.

Practice choosing a pin mode

Engineering Fundamentals/Electrical Systems

Digital and Analog Signals

Decide whether a sensor communicates with two logic states, a changing voltage, or the timing of pulses.

Digital uses two states; analog uses a range

Digital uses two states; analog uses a range

A digital input interprets two states: LOW/HIGH, or 0/1. The wire still carries a physical voltage; the receiving circuit decides which logic state it represents. A voltage in the undefined region between valid LOW and HIGH levels is not a useful third state.

An analog signal represents a quantity by a continuous range of values. A potentiometer wired between ground and 5 V can provide a changing voltage at its middle terminal. On a classic Uno R3, the usual analog measurement range is nominally 0–5 V with the default reference. That is not a universal sensor range.

Digital waveform switches between LOW and HIGH; analog waveform changes smoothly through intermediate voltages. Both are plotted against time.

Classify the sensor's output circuit, not just its name

Classify the sensor's output circuit, not just its name

Common examples
Device and connectionSignal at the input
Button or switch with a pull-upDigital open/closed state.
Quadrature encoder with compatible logic outputsTwo digital pulse trains; their order gives direction.
HC-SR04 ultrasonic module, Echo pinA timed digital pulse. Its duration represents distance; its voltage height does not.
Potentiometer connected as a voltage dividerAnalog voltage from its wiper (middle terminal).
Photoresistor in a voltage dividerAnalog voltage as resistance changes with light.
Phototransistor with a load resistorAnalog response to light unless a threshold circuit converts it to digital.
Pressure or proximity sensorDepends on the model: analog voltage, switching output, or digital data. Read its documentation.

A bare resistive sensor does not generate a usable voltage by itself: its surrounding circuit matters. A module may offer both analog and thresholded digital outputs.

Supporting detail: Addendum 2 — Phototransistor circuits can measure light or switch at a threshold.

Supporting detail: Addendum 3 — Why an ultrasonic measurement can be digital.

The ADC reads voltage; PWM controls time; Practice

The ADC reads voltage; PWM controls time

Analog-to-Digital Conversion turns an analog input into a number the program can use. Pulse-Width Modulation switches a digital output on and off for a controlled fraction of each cycle. Neither operation changes the fact that the processor stores and works with digital data.

Practice identifying sensor signals

Engineering Fundamentals/Electrical Systems

Analog-to-Digital Conversion

Relate an Uno R3's 10-bit ADC reading to its reference voltage, step size and approximate sampling time.

Ten bits give 1024 codes, numbered 0 through 1023

Ten bits give 1024 codes, numbered 0 through 1023

An analog-to-digital converter (ADC) samples a voltage and reports a number. The classic Uno R3 has a 10-bit ADC: 210 = 1024 possible codes. analogRead(A0) reads analog input A0 and returns an integer from 0 to 1023.

The reference voltage sets the scale. With an assumed exact 5.000 V reference, one nominal step is 5/1024 = 0.0048828125 V = 4.883 mV, or about 4.9 mV. Resolution describes the step size; it does not guarantee that a real voltage measurement is accurate to that amount.

Supporting detail: Addendum 4 — Arduino's resolution and timing figures.

Use 1024 for the nominal voltage step

Use 1024 for the nominal voltage step

For these exercises, use a clearly defined ideal bin model: divide the 0–5 V span into 1024 equal bins, round down to the bin number, and limit the top code to 1023.

code = min(1023, floor(Vin × 1024 / Vref)). Here floor means round down. At 3.000 V with a 5.000 V reference: floor(614.4) = 614.

To report the nominal voltage represented by a code, use its lower bin edge: V = code × Vref/1024. Code 800 represents 800 × 5/1024 = 3.90625 V. In this model its bin extends up to, but not including, 3.9111328125 V.

Supporting detail: Addendum 5 — Why dividing by 1023 answers a different question.

Explore the steps and check the units; Practice

Explore the steps and check the units

The two-way ADC controls in the PWM and ADC explorer let you enter a voltage or a code. Try nearby voltages within one bin, then cross its boundary. In reverse, code 1023 gives 4.9951171875 V as its lower edge, not proof that the input equals that value.

The same explorer also separates when a voltage is sampled from how its code is calculated. It shows instantaneous raw PWM or settled RC values, the finite mean of the selected point samples, and the mean of their reconstructed lower-edge voltages. Those are different from the waveform's complete-cycle time mean. A held code is the latest point result, not a window average.

Supporting detail: Addendum 6 — Quantize first or average first?.

Practice converting a reading to volts

Practice sampling phase

Engineering Fundamentals/Electrical Systems

Pulse-Width Modulation

Explore duty cycle, frequency, average voltage and RC smoothing, then compare PWM output with ADC input.

Duty cycle is the fraction of each cycle spent HIGH

Duty cycle is the fraction of each cycle spent HIGH

Pulse-width modulation (PWM) repeats a rectangular waveform. The period T is the time for one cycle; frequency f is cycles per second. Duty cycle D is the fraction of the period spent HIGH.

T = 1/f, ton = D × T, and for ideal switching between 0 V and a supply Vs, Vaverage = D × Vs. Convert a percentage to a fraction: 25% means D = 0.25.

Three PWM waveforms with equal periods and duty cycles of 25, 50 and 75 percent. The HIGH time increases while the period stays fixed.

At 500 Hz, T = 0.002 s = 2 ms = 2000 µs. At 25% duty, the on-time is 500 µs and the average of a 0–5 V output is 1.25 V. The pin itself still switches between 0 and 5 V.

The stock Uno R3 uses six PWM pins

The stock Uno R3 uses six PWM pins

Use digital pins 3, 5, 6, 9, 10 and 11. Default PWM is approximately 490 Hz on 3, 9, 10 and 11, and 980 Hz on 5 and 6. These correspond to periods of about 2.04 ms and 1.02 ms.

analogWrite(pin, value) requests duty using values from 0 (always off) to 255 (always on). A useful nominal mapping is value = round(255 × D): 25% gives 64. Hardware timer modes introduce small differences in the exact duty, particularly near the ends of the range.

Supporting detail: Addendum 7 — Official frequency table and timer limitations.

Change duty and frequency, then compare an ADC reading; Interactive

Change duty and frequency, then compare an ADC reading

Print / static comparison: 25% duty at 500 Hz gives a 2 ms period, 0.5 ms HIGH time and a 1.25 V complete-cycle time mean for an ideal 0–5 V waveform. A point sample is one instant, not that average.

The same PWM waveform sampled at different phases
Finite sample setEach raw sampleSelected-sample meanADC code / lower edge
500 samples/s, phase 10%5 V5 V1023 / 4.995117 V
500 samples/s, phase 60%0 V0 V0 / 0 V
2000 samples/s, phases 1%, 26%, 51%, 76%5, 0, 0, 0 V1.25 VMean lower edge 1.248779 V

An unloaded 10 kΩ / 1 µF RC filter has a 10 ms time constant. In the settled repeating response its 25%, 500 Hz ripple runs from about 1.1579 V to 1.3453 V while its cycle mean remains 1.25 V. Changing a control recomputes that settled response; this model does not show startup.

With a separate 5.000 V ADC input, 3.000 V gives code 614; code 800 has lower edge 3.90625 V.

The explorer is a model, not a board connection. Its frequency and sampling controls do not configure an Uno or claim a board throughput. A raw sample uses normalized phase with HIGH on [0, D) and LOW on [D, 1); the stated finite sample count defines the reported sample mean. ADC controls use the ideal bin convention on Analog-to-Digital Conversion; 5.000 V is assumed exact.

Supporting detail: Addendum 8 — Why more samples can still give the wrong mean.

An RC filter smooths PWM but leaves ripple

An RC filter smooths PWM but leaves ripple

Put a resistor in series with the PWM signal and a capacitor from the output node to ground; measure the voltage across the capacitor. This RC low-pass filter slows voltage changes. The capacitor charges while PWM is HIGH and discharges while it is LOW.

The time constant is τ = R × C. A longer time constant relative to the PWM period reduces ripple but makes the output respond more slowly when duty changes. The explorer shows the settled waveform with τ = 10 ms, assuming an ideal source and no load. A load changes the result; the filter is not a motor power supply.

Microchip's AVR131 PWM filtering note explains the tradeoff: the low-pass filter must reject PWM base-frequency ripple without removing the slower signal of interest, and a low-impedance load can discharge the capacitor unless buffered. This explorer deliberately assumes no load.

Supporting detail: Addendum 9 — What the smoothed trace calculates.

PWM changes LED brightness and motor drive; Practice

PWM changes LED brightness and motor drive

Rapid switching changes an LED's average light output while a resistor or driver limits its on-state current. Perceived brightness is not perfectly proportional to duty. For a DC motor, PWM commands a suitable power driver; the board pin does not supply the motor current. The driver must handle the motor and its inductive current.

Increasing duty usually increases the available drive, but motor speed also depends on load. Use DC Motor Torque, Speed, and Power to connect speed, torque and current. See Electrical Safety before wiring.

Practice PWM calculations

Supporting detail

Addendum

Additional evidence, standards context, and background referenced from the main text.

  1. Engineering Fundamentals/Electrical Systems/Analog-to-Digital Conversion

    Addendum 4. Arduino's resolution and timing figures

    The official analogRead reference source gives “5 volts / 1024 units” and “about 100 microseconds (0.0001 s)”. That is roughly 10,000 reads per second on ATmega-based boards using the usual API, not an absolute ADC hardware limit or a guaranteed loop rate. Computation, communication and delays take additional time. The published analogRead reference is the learner's API lookup.

    Back to reference 4

  2. Engineering Fundamentals/Electrical Systems/Analog-to-Digital Conversion

    Addendum 5. Why dividing by 1023 answers a different question

    There are 1024 codes but only 1023 intervals between code labels 0 and 1023. Multiplying by 5/1023 stretches those endpoints to exactly 0 and 5 V; that is endpoint scaling, not the nominal ADC step. The explorer and practice consistently use 1024. Real converters have transition offsets, noise and reference error; their exact thresholds are not predicted by this classroom bin model. A code cannot recover the original voltage exactly.

    Back to reference 5

  3. Engineering Fundamentals/Electrical Systems/Analog-to-Digital Conversion

    Addendum 6. Quantize first or average first?

    ADC conversion floors each individual ideal sample into a bin. Averaging the reconstructed lower edges therefore need not equal converting the analog sample mean. For a 25% raw 0–5 V sequence with one HIGH and three LOW samples, the analog sample mean is 1.25 V; the lower-edge reconstructions average 4.9951171875/4 = 1.248779296875 V. Neither operation recovers information between sample instants.

    Back to reference 6

  4. Engineering Fundamentals/Electrical Systems/Pulse-Width Modulation

    Addendum 7. Official frequency table and timer limitations

    The Uno R3 row of Arduino's analogWrite reference source states “490 Hz (pins 5 and 6: 980 Hz)”. See also the published analogWrite reference. A frequency near 31 kHz requires changing timer configuration; it is not the stock setting. analogWrite sets duty, not frequency. Arduino's Secrets of Arduino PWM explains prescalers and timer modes. Changing timers can also affect other functions and libraries.

    Back to reference 7

  5. Engineering Fundamentals/Electrical Systems/Pulse-Width Modulation

    Addendum 8. Why more samples can still give the wrong mean

    If the sample clock repeatedly lands at the same PWM phase, every point can read HIGH or every point can read LOW even though the full-cycle time mean is 1.25 V. A sample-and-hold output keeps the most recent point value between samples; holding is not averaging. A carefully spaced finite set can match the cycle mean, but a higher rate or larger count alone does not guarantee an unbiased result. This bounded comparison does not claim reconstruction of an unbandlimited switching edge from a Nyquist test.

    Back to reference 8

  6. Engineering Fundamentals/Electrical Systems/Pulse-Width Modulation

    Addendum 9. What the smoothed trace calculates

    During each constant input interval, V(t) = Vtarget + (Vstart − Vtarget)e−t/τ. The model solves for a repeating steady state, then draws the charging and discharging curves. It omits startup, output resistance, component tolerances and loading. At 0% or 100%, the settled output is simply 0 V or 5 V.

    Back to reference 9