STM32 DC Motor Speed Control Tutorial

This note provides a detailed overview of a DC motor speed control system built around an STM32 microcontroller. It explains the circuit design, key components, and how the system reads input from a potentiometer, generates PWM signals to control motor speed, and displays real-time feedback on an I2C LCD. The note also highlights practical applications, such as robotics and small automation projects, and offers insights into the hardware and software implementation for educational and prototyping purposes.

STM32 DC Motor Speed Control Tutorial

This circuit is a DC motor speed control system based on STM32F103C8 microcontroller. It uses a potentiometer to adjust the speed of two DC motors, with the status displayed on an I2C-interfaced LCD.


STM32F103C8 DC Motor Speed Control with I2C LCD Created by ee-diary.net STM32F103C8 ST ee-diary.net VSS VDD BOOT0 NRST PA0-WKUP OSCIN_PD0 OSCOUT_PD1 PB8 PA2 PA1 PA3 PA4 PB9 PA5 PA6 PA7 PA8 PA9 PB10 PA10 PB0 PB1 PB2 PB3 PB11 PB4 PB5 PB6 PB7 PB12 PB13 PB14 PB15 PA11 PA12 PA13 PA14 PA15 PC13_RTC PC14-OSC32_IN PC15-OSC32_OUT VDDA VBAT VSSA VSS_2 VDD_2 VSS_3 VDD_3 U1 STM32F103C8 R1 10k C1 100nF C2 100nF C3 100nF C4 100nF R2 10k C5 100nF C6 1uF R3 330 D1 LED-RED IN1 5 IN2 7 ENA 6 OUT1 2 OUT2 3 ENB 11 OUT3 13 OUT4 14 IN3 10 IN4 12 SENSA 1 SENSB 15 GND 8 VS 4 VCC 9 U2 L298 +5V +9V VSS SCL VDD SDA LCD1 JHD-2X16-I2C R4 4.7k R5 4.7k 57% RV1 10k D2 1N5819 D3 1N5819 D4 1N5819 D5 1N5819 D6 1N5819 D7 1N5819 D8 1N5819 D9 1N5819


Circuit Functionality


  1. Input: A potentiometer (connected to PA0) acts as a voltage divider, providing an analog signal to the STM32's ADC.
  2. Processing: The STM32 reads the ADC value (0–4095) and converts it into a Pulse Width Modulation (PWM) duty cycle.
  3. Output (Motor Control): The PWM signals (PA11 and PA9) drive the L298N motor driver, which controls the speed of two DC motors.
  4. Display: The STM32 sends the calculated speed percentage to an LCD via an I2C interface (PB6/PB7).

Applications


This type of circuit is commonly used in:


Key Components


STM32F103C8 (MCU)

A popular 32-bit ARM Cortex-M3 microcontroller. It is powerful enough to handle high-speed PWM generation, ADC sampling, and communication protocols (like I2C) simultaneously, making it ideal for motor control tasks.


L298N Motor Driver IC

A dual H-bridge driver designed to accept standard TTL logic levels and drive inductive loads such as relays, solenoids, and DC/stepper motors. It allows the MCU to control motor direction and speed (via PWM) while isolating the MCU from the higher voltage/current required by the motors.


Freewheel Diodes

When power is removed from a DC motor, the collapsing magnetic field in its coils creates a high-voltage spike (back-EMF) that can destroy the driver IC.

  • Connection: Diodes (D2-D9) are connected in parallel with the motor outputs, pointing toward the supply voltage. They provide a safe path for the current to circulate and dissipate when the motor is switched off, protecting the L298N.

I2C Interfacing with LCD(JHD-2X16-I2C)

The LCD uses the I2C protocol, which requires only two wires: SDA (Data) and SCL (Clock).

  • Pull-up Resistors (R4, R5): I2C lines are "open-drain." This means the devices can only pull the lines low. Pull-up resistors are mandatory to pull the lines high when no device is actively driving them. Without these, the I2C bus will not function.

STM32F103C8 DC motor control code



#include 
#include 

/*
 * Wiring (unchanged):
 *   PA0  <- -="" pa11="" pot="" wiper=""> IN1 (TIM1_CH4 PWM)   PA10 -> IN2 (low)
 *   PA9  -> IN3 (TIM1_CH2 PWM)   PA8  -> IN4 (low)
 *   PB15 -> ENA, PB14 -> ENB     (held HIGH = always enabled)
 *   PB6 = SCL, PB7 = SDA (LCD, bit-banged)
 * Clock: default HSI 8 MHz (no PLL set up).
 */

// Proteus's STM32 TIM1 output came out inverted (CCR=0 -> pin high, CCR>ARR -> pin low)
// even with PWM mode 1. 1 = invert channel polarity to compensate. Set to 0 if the
// pins are already correct (e.g. on real hardware or another model version).
#define PWM_POLARITY_FIX  1

#define IN1_PIN    11  // PA11
#define IN2_PIN    10  // PA10
#define IN3_PIN    9   // PA9
#define IN4_PIN    8   // PA8

#define LCD_ADDR   0x7C
#define SCL_H()   (GPIOB->BSRR = (1U << 6))
#define SCL_L()   (GPIOB->BRR  = (1U << 6))
#define SDA_H()   (GPIOB->BSRR = (1U << 7))
#define SDA_L()   (GPIOB->BRR  = (1U << 7))
#define SDA_IN()  (GPIOB->IDR & (1U << 7))

// ~1 ms per count at 8 MHz (rough)
void delay_ms(volatile uint32_t count) {
    for (count *= 1000; count > 0; count--);
}

static void i2c_dly(void) { for (volatile int i = 0; i < 10; i++); }

static void i2c_start(void) { SDA_H(); SCL_H(); i2c_dly(); SDA_L(); i2c_dly(); SCL_L(); }
static void i2c_stop(void)  { SDA_L(); i2c_dly(); SCL_H(); i2c_dly(); SDA_H(); i2c_dly(); }

static uint8_t i2c_write(uint8_t b) {
    for (int i = 0; i < 8; i++) {
        if (b & 0x80) SDA_H(); else SDA_L();
        i2c_dly(); SCL_H(); i2c_dly(); SCL_L();
        b <<= 1;
    }
    SDA_H(); i2c_dly(); SCL_H(); i2c_dly();
    uint8_t ack = !SDA_IN();
    SCL_L(); return ack;
}

void I2C_WriteBytes(uint8_t addr, uint8_t *data, uint8_t len) {
    i2c_start();
    if (i2c_write(addr)) { for (uint8_t i = 0; i < len; i++) i2c_write(data[i]); }
    i2c_stop();
}

void LCD_SendCommand(uint8_t cmd) { uint8_t b[2] = {0x80, cmd}; I2C_WriteBytes(LCD_ADDR, b, 2); delay_ms(2); }
void LCD_SendData(uint8_t data)   { uint8_t b[2] = {0x40, data}; I2C_WriteBytes(LCD_ADDR, b, 2); delay_ms(1); }

void LCD_Init(void) {
    delay_ms(50);
    LCD_SendCommand(0x28); LCD_SendCommand(0x0C); LCD_SendCommand(0x01); LCD_SendCommand(0x06);
}

void LCD_Print(const char *str) { while (*str) LCD_SendData((uint8_t)*str++); }

// prints 0..100 as 3 characters, leading zeros replaced by spaces
void LCD_PrintInt(uint8_t val) {
    LCD_SendData(val >= 100 ? (val / 100) + '0' : ' ');
    LCD_SendData(val >= 10  ? ((val / 10) % 10) + '0' : ' ');
    LCD_SendData((val % 10) + '0');
}

void System_Init(void) {
    RCC->APB2ENR |= RCC_APB2ENR_IOPAEN | RCC_APB2ENR_IOPBEN | RCC_APB2ENR_ADC1EN
                 |  RCC_APB2ENR_AFIOEN | RCC_APB2ENR_TIM1EN;

    // PB6/PB7 open-drain 2 MHz (release lines high first);
    // PB14/PB15 push-pull outputs held HIGH -> L298 ENA/ENB always enabled
    GPIOB->BSRR = (1U << 6) | (1U << 7) | (1U << 14) | (1U << 15);
    GPIOB->CRL  = (GPIOB->CRL & ~((0xFU << 24) | (0xFU << 28))) | (0x6U << 24) | (0x6U << 28);
    GPIOB->CRH  = (GPIOB->CRH & ~((0xFU << 24) | (0xFU << 28))) | (0x2U << 24) | (0x2U << 28);

    // PA0 analog input
    GPIOA->CRL = GPIOA->CRL & ~0xFU;
    // PA8 out PP (0x2), PA9 AF PP (0xB), PA10 out PP (0x2), PA11 AF PP (0xB)
    GPIOA->CRH = (GPIOA->CRH & ~0xFFFFU) | 0xB2B2U;
    GPIOA->BRR = (1U << IN2_PIN) | (1U << IN4_PIN);   // IN2, IN4 low

    // TIM1 PWM: CH2 (PA9 = IN3) and CH4 (PA11 = IN1), ~1.95 kHz, duty = CCR/4096
    TIM1->PSC   = 0;
    TIM1->ARR   = 4095;
    TIM1->CCMR1 = (6U << 12) | TIM_CCMR1_OC2PE;       // CH2 PWM mode 1
    TIM1->CCMR2 = (6U << 12) | TIM_CCMR2_OC4PE;       // CH4 PWM mode 1
    TIM1->CCR2  = 0;
    TIM1->CCR4  = 0;
    TIM1->CCER  = TIM_CCER_CC2E | TIM_CCER_CC4E;
#if PWM_POLARITY_FIX
    TIM1->CCER |= TIM_CCER_CC2P | TIM_CCER_CC4P;      // active-low output polarity
#endif
    TIM1->BDTR  = TIM_BDTR_MOE;                       // required on TIM1
    TIM1->EGR   = TIM_EGR_UG;
    TIM1->CR1   = TIM_CR1_ARPE | TIM_CR1_CEN;

    // ADC1 channel 0, long sample time (pot is 10k source impedance)
    ADC1->SMPR2 = 7U;          // 239.5 cycles on channel 0
    ADC1->SQR1  = 0;           // 1 conversion
    ADC1->SQR3  = 0;           // channel 0
    ADC1->CR2  |= ADC_CR2_ADON;
    delay_ms(10);
    ADC1->CR2  |= ADC_CR2_CAL;
    while (ADC1->CR2 & ADC_CR2_CAL);
    ADC1->CR2  |= ADC_CR2_EXTSEL | ADC_CR2_EXTTRIG;   // trigger source = SWSTART
}

int main(void) {
    System_Init();
    LCD_Init();

    while (1) {
        ADC1->CR2 |= ADC_CR2_SWSTART;
        while (!(ADC1->SR & ADC_SR_EOC));
        uint16_t adc = ADC1->DR;            // 0..4095

        // CCR > ARR keeps the output permanently high (true 100% duty).
        // With CCR == ARR the pin still drops low for one timer tick every period.
        uint16_t duty = (adc >= 4090) ? 4096 : adc;
        TIM1->CCR4 = duty;                  // IN1 (motor A forward speed)
        TIM1->CCR2 = duty;                  // IN3 (motor B forward speed)

        LCD_SendCommand(0x80);              // cursor home (no clear -> no flicker)
        LCD_Print("Speed: ");
        LCD_PrintInt((uint8_t)((adc * 100U) / 4095U));
        LCD_Print("%");

        delay_ms(50);
    }
}

Code Briefing

  • System_Init(): Configures GPIO pins for PWM outputs, ADC input, and I2C. Sets up Timer 1 (TIM1) for PWM generation at ~1.95 kHz.
  • I2C_WriteBytes(): A manual "bit-banged" implementation of the I2C protocol to communicate with the LCD.
  • main() loop:

  1. Triggers an ADC conversion.
  2. Reads the potentiometer value and maps it to the PWM duty cycle (TIM1->CCR4 and TIM1->CCR2).
  3. Calculates the speed percentage and updates the LCD display.
  4. Delays briefly before the next cycle to ensure stable readings.

Video Demonstration


In conclusion, this STM32-based DC motor speed control system provides precise and reliable speed regulation for dual motors, with real-time feedback displayed on the LCD. Its modular design, using widely available components like the L298N driver and I2C LCD(JHD-2X16-I2C), makes it suitable for educational purposes, prototyping, and small-scale automation projects.

Other STM32F103 tutorials:







Post a Comment

Previous Post Next Post