Page 1 of 1

How to output PWM

Posted: Tue Dec 17, 2024 3:05 pm
by narendra.desilva
Hi

Could someone please help me run PWM? I am using the code

#define LED_BUILTIN PE0

void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
analogWrite(LED_BUILTIN, 100);

}

The LED does not get dim but above 125 it is off and below 125 it is on.

Could somebody please help me to understand what is wrong and how to correct it.

Regards

Re: How to output PWM

Posted: Tue Dec 17, 2024 3:14 pm
by fpiSTM
Which board you used?
It seems PE0 has no timer that's why you don't have pwm.

Re: How to output PWM

Posted: Tue Dec 17, 2024 3:18 pm
by narendra.desilva
Hi
I am sorry I forgot to mention the Board. It is STM32F407VG diyMore Black.

PE0 is the BUILTIN_LED pin. I am trying to experiment PWM by checking the brightness of the LED.

regards

Re: How to output PWM

Posted: Tue Dec 17, 2024 3:37 pm
by fpiSTM
So PE0 has no TIM capability so no PWM. In that case analogWrite use it as a simple GPIO (0-127 LOW /128-256 HIGH).
Use one of those pins without '_' (PY_n -->PYn): https://github.com/stm32duino/Arduino_C ... #L117-L186

Re: How to output PWM

Posted: Tue Dec 17, 2024 3:42 pm
by narendra.desilva
Hi

Thank you very much.

It is great to have this support.

Thanks and regards

Re: How to output PWM

Posted: Sun Dec 22, 2024 5:29 am
by ag123
another way is to use the HardwareTimer directly

Code: Select all

HardwareTimer *MyTim = new HardwareTimer(TIM3);
const uint8_t channel = 1;

void tim_callback() {
	digitalWrite(LED_BUILTIN, ! digitalRead(LED_BUILTIN)); // toggle led
}

void setup() {
	pinMode(LED_BUILTIN, OUTPUT);
	
	MyTim->pause();
	MyTim->setOverflow(1000, HERTZ_FORMAT); // 1 kHz
	MyTim->setCaptureCompare(channel, 500, MICROSEC_COMPARE_FORMAT); // 500 microseconds 
	MyTim->attachInterrupt(channel, tim_callback); //duty cycle
	MyTim->attachInterrupt(tim_callback); //update event
	MyTim->refresh();
	MyTim->resume();
}

void loop() {
	// wait for systick 1ms or any other interrupt, this runs cooler as the cpu is mostly in sleep mode
	asm("wfi"); 
}

timers can drive gpio pins directly, for that refer to the ref manual and api ref
ref:
https://github.com/stm32duino/Arduino_C ... er-library
there is also a shortcut for all that setup using MyTim->setPWM() for all those configs