小弟请教,用51系单片机的定时器,产生100HZ-10KHZ频率可调的方波,最好通过变量来实现,因为要接上位机

用C51语言编写
2024-12-17 06:27:37
推荐回答(2个)
回答1:

#include“reg2.h”
#define FOSC 12000000L //晶振12MHz
#define uchar unsigned char
#define uint unsigned int

uint tempHz = 0;

uchar TH1H = tempHz / 256;//默认的是100Hz
uchar TH1L = tempHz % 256;

sbit LED = P1^0; //输出波形,也是闪烁灯
sbit key_up = P2^0;//按键IO口
sbit key_down = P2^1;

void Init_Timer1(void)
{
TMOD |= 0x10; //模式1
TH1=TH1H; //给初值,65535溢出
TL1=TH1L;
EA=1; //总中断打开
ET1=1; //定时器中断打开
TR1=1; //定时器开关打开
}

void main()
{
uint j;
Init_Timer1();
while(1)
{
if(key_up == 0 || key_down == 0)
{
j = 1000;
while(j--);
if(key_up == 0)tempHz ++;
if(tempHz >= 65515)tempHz = 65515;
if(key_down == 0)tempHz --;
if(tempHz <= 0)tempHz = 0;
}
}
}

void Timer1_isr(void) interrupt 3
{
TH1=TH1H;
TL1=TH1L;

LED=~LED; //输出波形,也是闪烁灯

}

回答2:

如果是带pwm的stc系列比较好实现,如果是普通单片机到了10k不好做