#include "STM8S.h"
unsigned char a=20;
signed long int pwm_duty;
void delay_ms (int ms) //延时函数
{
for (int i=0; i<=ms; i++)
for (int j=0; j<120; j++); // Nop = Fosc/4
}
void KEY(void)
{
GPIO_DeInit(GPIOC);//D口默认状态
GPIO_Init(GPIOC, GPIO_PIN_5, GPIO_MODE_IN_FL_NO_IT);
GPIO_Init(GPIOC, GPIO_PIN_4, GPIO_MODE_IN_FL_NO_IT);
if (GPIO_ReadInputPin(GPIOC,GPIO_PIN_5) == 0) //加1按键有效
{
delay_ms(20);
//延时去抖 一般10-20ms
if (GPIO_ReadInputPin(GPIOC,GPIO_PIN_5) == 0)
{
while (GPIO_ReadInputPin(GPIOC,GPIO_PIN_5) == 0);
if (a < 41)
a = a+1;
}
}
if (GPIO_ReadInputPin(GPIOC,GPIO_PIN_4) == 0) //减1按键有效
{
delay_ms(20);
if (GPIO_ReadInputPin(GPIOC,GPIO_PIN_4) == 0)
{
while (GPIO_ReadInputPin(GPIOC,GPIO_PIN_4) == 0)
if (a > 1)
a =a-1;
}
}
}
void PWM(void)
{
pwm_duty=2000000/a/30;
CLK_HSIPrescalerConfig(CLK_PRESCALER_HSIDIV1);// 有些硬件会自动八分频 导致后面的计算出现错误
CLK_HSICmd(ENABLE); //打开内部的时钟函数
TIM2_DeInit(); //TIM2回复默认
GPIO_Init(GPIOD,GPIO_PIN_4,GPIO_MODE_OUT_PP_LOW_FAST);//设置 Timer2 D4口输出PWM模式
TIM2_OC1Init(TIM2_OCMODE_PWM1, TIM2_OUTPUTSTATE_ENABLE,pwm_duty/2,TIM2_OCPOLARITY_HIGH);
TIM2_TimeBaseInit(TIM2_PRESCALER_8,pwm_duty);//16M晶振
TIM2_OC2PreloadConfig(ENABLE);
TIM2_Cmd(ENABLE);//启用Timer2定时器
}
void main(void)
{
PWM();
while(1)
{
KEY();
}
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t* file, uint32_t line)
{
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* Infinite loop */
while (1)
{
}
}
#endif
/**
* @}
*/
代码如上,百思不得其解!求大佬帮忙看看
|