单片机STC8A8K64D4通过串口传输来设置PWM占空比的程序
时间: 2024-01-07 07:04:20 浏览: 96
下面是STC8A8K64D4通过串口传输设置PWM占空比的示例代码:
```c
#include "stc8.h"
#define FOSC 24000000UL
#define BAUD 115200UL
#define TIMER_PRESCALER 12
#define PWM_PRESCALER 2
sbit LED = P1^0;
void UART_Init(void)
{
SCON = 0x50;
TMOD &= 0x0F;
TMOD |= 0x20;
TL1 = TH1 = -(FOSC/12/BAUD);
TR1 = 1;
}
void Timer1_Init(void)
{
TMOD &= 0xF0;
TMOD |= 0x01;
TH1 = (65536 - FOSC/12/TIMER_PRESCALER/1000) >> 8;
TL1 = (65536 - FOSC/12/TIMER_PRESCALER/1000) & 0xFF;
ET1 = 1;
TR1 = 1;
}
void PWM_Init(void)
{
P_SW2 &= ~0x80;
P1M1 |= 0x01;
P1M0 &= ~0x01;
PWMCKS = PWM_PRESCALER;
PWMCFG |= 0x80;
PWMCR = 0x00;
PWMIF = 0;
PWMIE = 1;
}
void PWM_SetDutyCycle(unsigned int duty)
{
PWM0H = (unsigned char)(duty >> 8);
PWM0L = (unsigned char)duty;
}
void main(void)
{
UART_Init();
Timer1_Init();
PWM_Init();
EA = 1;
while(1);
}
void Timer1_Isr(void) interrupt 3
{
static unsigned char buf[4];
static unsigned char cnt = 0;
if(RI)
{
RI = 0;
buf[cnt++] = SBUF;
if(cnt == 4)
{
unsigned int duty = (buf[0] << 8) | buf[1];
unsigned int period = (buf[2] << 8) | buf[3];
PWM_SetDutyCycle(duty);
TH1 = (65536 - period) >> 8;
TL1 = (65536 - period) & 0xFF;
cnt = 0;
}
}
}
void PWM_Isr(void) interrupt 12
{
PWMIF = 0;
LED = !LED;
}
```
该程序通过串口接收4个字节的数据,前两个字节表示PWM占空比,后两个字节表示PWM周期,然后设置PWM占空比和PWM周期,并在PWM中断中切换LED状态以示波形输出。需要注意的是,该程序使用了定时器1来控制PWM周期,因此需要根据实际情况调整定时器1的分频系数。
阅读全文