#include <REGX52.H>
#include <INTRINS.H>
#include "Timer0.h"
#include "IndivKey.h"
//文件说明
/*
*****************************
*@file main.c
*@author RuiXiong
*@version V1.0.0
*@date 2024/04/01
*@brief 51单片机独立按键控制切换LED灯左/右循环流动
*****************************
*/
static unsigned char leftOrRight;//LED灯左/右流动的选择标志位
int main (void)
{
unsigned char indiKeyLocation;//保存按键的名字
Timer0Init();//定时器T0初始化
P2 = 0x7f;//P2_0~P2_7接LED1~8,共阳极
while (1)
{
indiKeyLocation = PressKey();//有4个按键K1-K4,没按时函数返回0
if (indiKeyLocation == K1)//按下K1,K1为枚举类型,值为1
{
leftOrRight ++;
if (leftOrRight >= 2)
{
leftOrRight = 0;
}
}
}
return 0;
}
void Timer0_isr (void) interrupt 1
{
static unsigned char s_count;
TL0 = 0x66; //1ms@11.0592MHz
TH0 = 0xFC;
s_count ++;
if (s_count >= 1000)//定时1S
{
s_count = 0;
if (leftOrRight == 0)
{
P2=_crol_(P2,1);//循环左移一位
}
if (leftOrRight == 1)
{
P2=_cror_(P2,1);//循环右移一位
}
}
}
问题描述:
运行代码调试时候,在Timer0_isr中断子程序中,在其定时判断语句中输入大于260的值led都不会流动,输入240等较小的数值则会成功。
if (s_count >= 1000)
解决方法:
将中断子程序中s_count的数据类型改为static unsigned int
void Timer0_isr (void) interrupt 1
{
static unsigned int s_count;
TL0 = 0x66; //1ms@11.0592MHz
TH0 = 0xFC;
s_count ++;
if (s_count >= 1000)//定时1S
{
s_count = 0;
if (leftOrRight == 0)
{
P2=_crol_(P2,1);//循环左移一位
}
if (leftOrRight == 1)
{
P2=_cror_(P2,1);//循环右移一位
}
}
}
知识点总结:
char的数值范围是-128~127
而unsigned char的数值范围是0~255
就算我之前一直把unsigned char的数值范围记错了,在调试出小数值成功,大数值失效这个结果后,也应该第一时间想到是数据类型导致的错误,多累积错误经验以后会越来越好!