Learn C Language from Scratch: Basics of Microcontroller Programming

Learn C Language from Scratch: Basics of Microcontroller Programming

The C language is the foundational language for microcontroller programming, akin to the brain language of the microcontroller, allowing our hardware devices to “understand” commands and perform operations. In today’s article, we will approach this from the perspective of beginners, introducing you to the basic knowledge of microcontroller programming, focusing on the basic usage of C language and how to control the GPIO ports of the microcontroller. No prior programming experience is necessary; as long as you are interested in microcontrollers, you can follow along!

What is a Microcontroller? Why Use C Language?

A microcontroller can be understood as a small computer chip that contains a CPU (processor), memory, I/O interfaces (input/output ports), and other functional modules. Its role is to help us control hardware through programming, such as turning on a light or reading data from a sensor.

The C language is the most commonly used language in microcontroller programming because it is both close to hardware (can directly manipulate registers) and easy to understand (unlike assembly language, which is obscure). A simple line of C code can make the microcontroller perform a multitude of tasks!

Module 1: GPIO Basics – Making an LED Light Up

1. Explanation of Basic Concepts

GPIO stands for General Purpose Input/Output, which are the input/output ports of the microcontroller. Its function is to receive signals (input) or output signals (control peripherals). For example:

  • Input: Read the status of a button (pressed or not pressed).

  • Output: Light up an LED.

Analogy: GPIO is like the power switch at home. When you press the switch (input), the light bulb turns on (output).

2. Hardware Circuit Diagram

First, let’s design a simple circuit: using the microcontroller to light up an LED.

1 Microcontroller GPIO pin ----- Resistor (220Ω) ----- LED anode
2 LED cathode ----- Ground (GND)

Notes:

  • Resistor is necessary: Driving the LED directly from GPIO may burn out the microcontroller’s pin; a resistor can limit the current.

  • Pay attention to polarity when wiring: The LED has directionality; the anode connects to the resistor, and the cathode connects to ground.

3. C Code Example

The following code uses the most common STM32 microcontroller as an example (GPIO control is similar for other microcontrollers, with slight adjustments). The goal is to make the GPIO output high to light up the LED.

 1 #include "stm32f10x.h" // This is the hardware header file for STM32
 2
 3 void GPIO_Config(void); // GPIO configuration function
 4
 5 int main(void) {
 6     GPIO_Config(); // Initialize GPIO
 7
 8     while (1) {
 9         GPIO_SetBits(GPIOC, GPIO_Pin_13); // Set GPIOC13 to high, light up LED
10         for (int i = 0; i < 1000000; i++); // Simple delay
11         GPIO_ResetBits(GPIOC, GPIO_Pin_13); // Set GPIOC13 to low, turn off LED
12         for (int i = 0; i < 1000000; i++); // Simple delay
13     }
14 }
15
16 void GPIO_Config(void) {
17     GPIO_InitTypeDef GPIO_InitStructure;
18
19     RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE); // Enable GPIOC clock
20
21     GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
22     GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
23     GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; // Configure as push-pull output mode
24     GPIO_Init(GPIOC, &GPIO_InitStructure); // Initialize GPIOC13
25 }

Code Explanation:

Learn C Language from Scratch: Basics of Microcontroller Programming
  • GPIO_SetBits: Sets the pin to output high.

  • GPIO_ResetBits: Sets the pin to output low.

  • GPIO_Mode_Out_PP: Push-pull output mode, suitable for driving an LED.

Notes:

  • Clock Enable: The GPIO module of the microcontroller needs to be “powered on” first; use RCC_APB2PeriphClockCmd to enable the clock.

  • Delay Issue: A simple delay method is used here, which is not precise; later, timers can be used for optimization.

4. Practical Application Case

Using similar code, you can control a buzzer to sound, or light up multiple LEDs through multiple GPIOs, or even make LEDs flash in a specific order (chasing light effect).

Module 2: Using C Language to Control LED with Button

1. Explanation of Basic Concepts

A button is a typical input device. When you press a button, the GPIO pin detects different levels (high or low). We can use C language to implement the function of “lighting up the LED when the button is pressed”.

Analogy: A button is like the switch of a doorbell; pressing it (input signal) makes the doorbell ring (output action).

2. Hardware Circuit Diagram

1 Microcontroller GPIO pin ----- One end of the button
2 The other end of the button ----- Ground (GND)

The connection of the LED is the same as above.

Notes:

  • When connecting the button to ground, add a pull-up resistor to VCC (generally recommended at 10kΩ) to prevent the pin from floating, causing unstable signals.

3. C Code Example

 1 #include "stm32f10x.h"
 2
 3 void GPIO_Config(void);
 4
 5 int main(void) {
 6     GPIO_Config();
 7
 8     while (1) {
 9         if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == 0) { // Button pressed, low level
10             GPIO_SetBits(GPIOC, GPIO_Pin_13); // Light up LED
11         } else {
12             GPIO_ResetBits(GPIOC, GPIO_Pin_13); // Turn off LED
13         }
14     }
15 }
16
17 void GPIO_Config(void) {
18     GPIO_InitTypeDef GPIO_InitStructure;
19
20     // Configure button input GPIOA0
21     RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
22     GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
23     GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; // Pull-up input mode
24     GPIO_Init(GPIOA, &GPIO_InitStructure);
25
26     // Configure LED output GPIOC13
27     RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
28     GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
29     GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; // Push-pull output
30     GPIO_Init(GPIOC, &GPIO_InitStructure);
31 }

Code Explanation:

  • GPIO_Mode_IPU: Pull-up input mode, suitable for connecting buttons.

  • GPIO_ReadInputDataBit: Reads the level status of the GPIO pin.

Learn C Language from Scratch: Basics of Microcontroller Programming

Notes:

  • Button Bounce Issue: When a button is pressed and released, it may bounce, which can trigger multiple times; this can be solved with software debounce or external circuit filtering.

4. Practical Application Case

This button control logic can be applied in smart homes, such as using a button to control light switches, fan starts, etc.

Module 3: Common Problems and Solutions

1. LED Does Not Light Up

  • Check if GPIO is initialized correctly and if it outputs high.

  • Check if the LED polarity is reversed.

  • Ensure the resistor value is appropriate (around 220Ω).

2. Button Does Not Respond

  • Check if a pull-up resistor has been added.

  • Button bounce may cause multiple triggers, which can be resolved with a delay debounce.

3. Program Freezes

  • Ensure clock configuration is correct.

  • Check for infinite loops.

Practical Advice

  1. Practice GPIO Operations: Try using multiple GPIOs to implement chasing lights, buzzer control, etc.

  2. Learn Debugging Tools: For example, use a multimeter to measure the GPIO pin levels and check hardware connections.

  3. Gradually Deepen Knowledge: From simple output control to complex peripheral communication (such as UART, I2C, SPI), gradually improve your skills.

Safety Reminder: Always power off when wiring to prevent short circuits or burning out the microcontroller.

Leave a Comment