I`m trying to make emulation of sinus signal with pwm on stm32f4-discovery board.
Here is my code:
Code: Select all
#include "ch.h"
#include "hal.h"
#include math.h
static PWMConfig pwmcfg = {
10000000, /* 10Mhz PWM clock frequency */
220, /* PWM period 220 duty cycles */
NULL,
{
{PWM_OUTPUT_DISABLED, NULL},
{PWM_OUTPUT_DISABLED, NULL},
{PWM_OUTPUT_DISABLED, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
},
0
};
int main(void){
float s = 0; // holds sin() value
int c = 0; //angle for sin() cycle counter
int cc = 0; //direction -> 1 increment/ 0 decrement
halInit();
chSysInit();
palSetPadMode(GPIOD, GPIOD_LED6, PAL_MODE_ALTERNATE(2));
pwmStart(&PWMD4, &pwmcfg);
pwmEnableChannel(&PWMD4, 3, 0);
while(1){
if (c>=90){
cc=0;
}
if (c <=0 ){
cc=1;
}
if (cc==0) c-=1;
if (cc==1) c+=1;
s= sin(c)*220;
pwmEnableChannel(&PWMD4, 3, s);
chThdSleepMilliseconds(100);
}
}Works fine, but there must be more intelligent ways to do the same outside the main() loop by putting this into separate thread or use timers or interrupts to increment/decrement duty cycles... this one sample will be sessitive to chip load by other tasks, and inaccurate signal can`t be used as source for power elements.
Pls post here more intelligent solutions for this purpose with guarateed accuracy of signal.
Thanks!