找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 387|回复: 1
打印 上一主题 下一主题
收起左侧

新手求解,STM8单片机按键控制输出频率

[复制链接]
跳转到指定楼层
楼主
ID:792289 发表于 2024-2-18 11:37 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
#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

/**
  * @}
  */


/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享淘帖 顶 踩
回复

使用道具 举报

沙发
ID:883242 发表于 2024-2-20 19:29 | 只看该作者
主循环里面只有key(),这个函数又没有改动PWM,到底意欲何为?
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|51黑电子论坛 |51黑电子论坛6群 QQ 管理员QQ:125739409;技术交流QQ群281945664

Powered by 单片机教程网

快速回复 返回顶部 返回列表