Skip to main content
Graduate
July 27, 2024
Question

PWM generation error

  • July 27, 2024
  • 3 replies
  • 1195 views

I tried generating PWM on my stm32g070rb but when I connected my PA7 and GND to my oscilloscope, the output I got does not look like a pwm signal in any way, I have verified my connections and now I think the error is from my code.WhatsApp Image 2024-07-27 at 01.19.34_3d2da966.jpg

 

    This topic has been closed for replies.

    3 replies

    Super User
    July 27, 2024

    I don't see anything wrong with that code.

    Plain blinky (i.e. setting PA7 as GPIO Output, and then toggling it in a loop using a loop-delay) works?

    JW

    PS. You can post code using the </> icon at the top of editor.

    Super User
    July 27, 2024

    You should learn about, how to use/set a scope first.

    -> set probes to 10:1 and adjust them.

    Graduate II
    July 27, 2024

    Next bare metal musician. You know what RISC exactly mean?

    And debuger peripheral view ? And your code for better reading

    void GPIOA_Init(void) {
     // Enable the clock for GPIOA
     RCC->IOPENR |= RCC_IOPENR_GPIOAEN;
     // Set PA7 to alternate function mode (AF1 for TIM3_CH2)
     GPIOA->MODER &= ~GPIO_MODER_MODE7_Msk;
     GPIOA->MODER |= GPIO_MODER_MODE7_1; // Alternate function mode
     // Set the alternate function to AF1 (TIM3_CH2)
     GPIOA->AFR[0] &= ~GPIO_AFRL_AFSEL7_Msk;
     GPIOA->AFR[0] |= (1 << GPIO_AFRL_AFSEL7_Pos); // AF1
    }
    void TIM3_Init(void) {
     // Enable the clock for Timer 3
     RCC->APBENR1 |= RCC_APBENR1_TIM3EN;
     // Reset and configure Timer 3
     TIM3->CR1 = 0; // Reset the control register
     TIM3->PSC = 15999; // Prescaler value (assuming a 16 MHz clock, this gives a 1 kHz timer clock)
     TIM3->ARR = 250; // Auto-reload value (for 1 kHz PWM frequency)
     // Set PWM mode 1 on channel 2 and enable preload
     TIM3->CCMR1 &= ~TIM_CCMR1_OC2M_Msk;
     TIM3->CCMR1 |= (6 << TIM_CCMR1_OC2M_Pos); // PWM mode 1
     TIM3->CCMR1 |= TIM_CCMR1_OC2PE; // Enable preload
     // Set the compare value (duty cycle, here 50%)
     TIM3->CCR2 = 125;
     // Enable capture/compare on channel 2
     TIM3->CCER |= TIM_CCER_CC2E;
     // Enable auto-reload preload
     TIM3->CR1 |= TIM_CR1_ARPE;
     // Enable the counter
     TIM3->CR1 |= TIM_CR1_CEN;
     // Generate an update event to reload the prescaler value immediately
     TIM3->EGR = TIM_EGR_UG;
    }
    
    
    int main(void) {
     SystemClock_Config(); // Configure the system clock
     GPIOA_Init(); // Initialize GPIOA
     TIM3_Init(); // Initialize Timer 3
    
     while (1) {
     // Main loop does nothing, PWM signal is generated by the timer
     }
    }