How to output PWM

Development environment specific, Arduino, Eclipse, VS2013, Em::Blocks etc
Post Reply
narendra.desilva
Posts: 9
Joined: Tue Dec 10, 2024 12:33 am

How to output PWM

Post 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
fpiSTM
Posts: 1944
Joined: Wed Dec 11, 2019 7:11 pm
Answers: 108
Location: Le Mans
Contact:

Re: How to output PWM

Post by fpiSTM »

Which board you used?
It seems PE0 has no timer that's why you don't have pwm.
narendra.desilva
Posts: 9
Joined: Tue Dec 10, 2024 12:33 am

Re: How to output PWM

Post 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
fpiSTM
Posts: 1944
Joined: Wed Dec 11, 2019 7:11 pm
Answers: 108
Location: Le Mans
Contact:

Re: How to output PWM

Post 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
narendra.desilva
Posts: 9
Joined: Tue Dec 10, 2024 12:33 am

Re: How to output PWM

Post by narendra.desilva »

Hi

Thank you very much.

It is great to have this support.

Thanks and regards
ag123
Posts: 1898
Joined: Thu Dec 19, 2019 5:30 am
Answers: 30

Re: How to output PWM

Post 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
Post Reply

Return to “IDE's”