Microcontroller Programming

Microcontroller programming turns input signals into decisions and output actions. You might read an object detector, count detected objects, and switch on an indicator when the count reaches a target. Arduino provides a practical environment for writing these programs in C++. The central skill is following execution: which statement runs next, what information it changes, and which information remains available during the next pass.

Organize initialization and repeated work

An Arduino sketch is the program you compile and upload to a compatible board. A basic sketch contains two functions: setup() and loop(). After startup or reset, setup() runs once. After it finishes, loop() runs repeatedly.


Function

Execution pattern

Typical responsibility

setup()

Once after startup or reset

Configure pin modes and establish initial outputs

loop()

Repeatedly after setup finishes

Read inputs, make decisions, and update outputs


A program initializes once and then repeatedly reads inputs, updates state, and writes outputs.


Statements normally execute from top to bottom. Braces group statements into a function or branch, and most individual statements end with a semicolon. Names are case sensitive: digitalRead and digitalread are different names. Compiling checks whether the code follows the language rules; uploading transfers the compiled program to the board. Successful compilation does not establish that the program makes the intended decisions.

Read a signal and choose an action

Use pinMode(pin, INPUT) for an externally driven digital input and pinMode(pin, OUTPUT) for an output. digitalRead(pin) returns HIGH or LOW; digitalWrite(pin, value) sets a configured output to one of those states.


The meaning of a state comes from the connected device. A detector might indicate an object with HIGH, while another device indicates an object with LOW. Establish that meaning before writing a condition. An input also needs a defined electrical state; an unconnected input can produce unpredictable readings.


In a condition, == compares values. The assignment operator = stores a value. An if statement runs its branch when its condition is true, and an else branch supplies the alternative action.



Keep information between passes

Persistent state is information retained between repeated passes of the program. For example, a counter needs its previous total before it can add a new event. A variable declared outside the functions can retain that total between calls to loop(). An ordinary local variable initialized inside loop() starts again on every call.


For a counter that adds one for each newly detected event, the governing update is


ck+1=ck+ek,ek∈{0,1}.c_{k+1}=c_k+e_k,\qquad e_k\in\{0,1\}.


Here, ckc_k is the stored count before pass kk, and eke_k is one when that pass detects a new event and zero otherwise.


A sustained HIGH reading may last for many passes. To count its start once, compare the current reading with the previous reading:


C++
const int sensorPin = 4;
const int indicatorPin = 9;
int count = 0;
bool previousHigh = false;

void setup() {
  pinMode(sensorPin, INPUT);
  pinMode(indicatorPin, OUTPUT);
  digitalWrite(indicatorPin, LOW);
}

void loop() {
  bool isHigh = (digitalRead(sensorPin) == HIGH);
  if (isHigh && !previousHigh) {
    count++;
  }
  previousHigh = isHigh;
  digitalWrite(indicatorPin, count >= 6 ? HIGH : LOW);
}


Assume the detector initially reads LOW, each object produces one HIGH interval, and each interval and intervening LOW are sampled. Also assume this counting session stays below 1000 objects. The operator && requires both conditions to be true, while ! means logical NOT. Update previousHigh after the comparison so it still describes the preceding pass during the test. The final expression selects HIGH when the count reaches six and LOW otherwise.

Trace state and arithmetic

Trace a program by recording each input, the branch taken, the updated variables, and the final output. Include boundary cases: just below a target, exactly at it, and above it. A variable holding the result of a comparison stores that result; it does not automatically change when another variable changes.


Arithmetic types matter too. Integer division discards the fractional part: 9 / 12 produces zero. To calculate a percentage, use floating-point arithmetic, such as 100.0f * 9 / 12, which produces 75.0. Choose variable types that can hold the intended range.



What to remember

  • Initialize hardware in setup() and perform repeated decisions in loop().
  • Match conditions to the stated meaning of HIGH and LOW.
  • Retain previous values when a decision depends on history.
  • Trace statements in order, including arithmetic and output updates.

Example: Counting objects at a collection tray

A collection-tray detector drives digital pin 6 with a stable HIGH while an object is detected and LOW otherwise. An indicator interface on digital pin 10 turns on for HIGH and off for LOW. You want the indicator to turn on after three objects have been counted and remain on until the controller resets.


Assume the detector initially reads LOW, each object produces one HIGH interval, and the program samples every interval and the LOW between intervals. The counting session ends before 1000 objects. Treat the detector and indicator interfaces as already connected correctly.


The detector sends a digital signal to pin 6 of the microcontroller, which commands the indicator through pin 10.


a) Write the pin declarations and setup() function so the detector is an input and the indicator starts off.


Use named constants for the two pin numbers. The detector supplies a signal to the controller, so its pin is an input. The indicator receives a command from the controller, so its pin is an output. Explicitly writing LOW establishes the requested initial off state.


C++
const int sensorPin = 6;
const int indicatorPin = 10;

void setup() {
  pinMode(sensorPin, INPUT);
  pinMode(indicatorPin, OUTPUT);
  digitalWrite(indicatorPin, LOW);
}


After setup finishes, pin 6 is configured for reading and pin 10 has been commanded to LOW.


b) Add persistent variables and a loop() function that counts each new HIGH interval once and controls the indicator.


The program needs two values to survive between passes: the cumulative count and whether the previous reading was HIGH. Initialize the count to zero and the previous-state flag to false because the detector initially reads LOW.


A new event requires a current HIGH and a previous LOW. Increment the count only when both conditions hold. Then save the current state for the next pass and select the output from the updated count.


C++
int count = 0;
bool previousHigh = false;

void loop() {
  bool isHigh = (digitalRead(sensorPin) == HIGH);

  if (isHigh && !previousHigh) {
    count++;
  }

  previousHigh = isHigh;
  digitalWrite(indicatorPin, count >= 3 ? HIGH : LOW);
}


Place these variable declarations outside both functions. After the first HIGH sample, previousHigh becomes true, so further HIGH samples from the same interval do not increase the count. A later LOW sample makes the flag false again, preparing the program to detect the next event.


c) Starting from reset, trace these eight detector readings: LOW, HIGH, HIGH, LOW, HIGH, LOW, HIGH, HIGH. Find the final count and the first pass that turns the indicator on.


Start with a count of zero and previousHigh equal to false. On each pass, compare the current reading with the saved preceding reading before updating that saved value. Only a transition from a sampled LOW to a sampled HIGH adds an object.

  1. Pass 1 reads LOW: no new event. The count stays at 0, and the indicator command is LOW.
  2. Pass 2 reads HIGH after LOW: a new event increases the count to ________. The indicator command is LOW.
  3. Pass 3 reads HIGH after HIGH: no new event. The count stays at ________, and the indicator command is LOW.
  4. Pass 4 reads LOW: no new event. The count stays at 1, and the indicator command is LOW.
  5. Pass 5 reads HIGH after LOW: a new event increases the count to ________. The indicator command is LOW.
  6. Pass 6 reads LOW: no new event. The count stays at ________, and the indicator command is LOW.
  7. Pass 7 reads HIGH after LOW: a new event increases the count to 3. The indicator command becomes HIGH.
  8. Pass 8 reads HIGH after HIGH: no new event. The count stays at 3, and the indicator command remains HIGH.

Adding the eight event contributions to the initial count gives


cfinal=0+(0+1+0+0+1+0+1+0)=3 objects.c_{\text{final}}=0+(0+1+0+0+1+0+1+0)=3\ \text{objects}.


The count first reaches the target on pass 7, so that is the first pass that commands the indicator on. The final HIGH reading belongs to the same detected interval as the preceding reading, so it does not add a fourth object. The final count is 3 objects, and the indicator remains on.

A microcontroller uses an Arduino sketch to control a classroom model. Its setup() function configures the digital pins, and its loop() function reads a detector and updates an indicator. Assume both functions finish normally and the board remains powered without resetting. Which execution pattern occurs?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

An Arduino test sketch must configure digital pin 10 as an output and then command it LOW. The constant indicatorPin already equals 10. Complete the function names using their exact Arduino capitalization.


The function called with arguments indicatorPin, OUTPUT to configure the pin is . The function then called with arguments indicatorPin, LOW to command its level is .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A controller receives a stable, externally driven fault signal on digital pin 5: LOW means a fault is present, and HIGH means normal operation. An indicator interface on digital pin 11 turns on for HIGH and off for LOW. The sketch has already configured pin 5 as INPUT and pin 11 as OUTPUT.


Which code makes the indicator turn on during a fault and turn off during normal operation on every pass?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice