我设置时钟为24.5MHZ,波特率为9600,键盘是给串口发送数据的。但是我加了键盘扫描程序就出问题,感觉很不兼容,我改了时钟或者波特率都不行,一下是键盘读不出;一下是键盘读出了,我按了确定键,串口会自己连续发一会才停下,要么收到的是乱码,我之前不加键盘是显示正常的。我极其郁闷和苦恼,恳求哪位高手能帮我解决,万分感谢!!!
以下是我的程序:
#include <c8051f410.h> // SFR declarations
#include <stdio.h>
#define uchar unsigned char
#define uint unsigned int
#define SYSCLK 24500000 // SYSCLK frequency in Hz
#define BAUDRATE 9600 // Baud rate of UART in bps
void SYSCLK_Init (void);
void UART0_Init (void);
void PORT_Init (void);
void delay(int);
void SendData(uchar);
uchar code Table[]="07110003235\n"; //发送的字符串
uchar *Send=Table;
uchar a,b,c;
uchar j;//控制发数据
uchar k;//接收数据中间变量
const uchar tab[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};//数码管显示 0~9
const uchar tab1[]={0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x61,0x62,0x63,0x64,0x65,0x66};//assicii
void KeyScan(); //键盘扫描
void delay()
{
int i=0;
for(i=0;i<1000;i++) {}
}
void PORT_Init (void)
{
P0MDOUT |= 0x10; // Enable UTX as push-pull output
XBR0 = 0x01; // Enable UART on P0.4(TX) and P0.5(RX)
XBR1 = 0x40; // Enable crossbar and weak pull-ups
}
void SYSCLK_Init (void)
{
OSCICN |= 0x87; // configure internal oscillator for
// 24.5MHz
RSTSRC = 0x04; // enable missing clock detector
}
void UART0_Init (void)
{
SCON0 = 0x10; // SCON0: 8-bit variable bit rate
// level of STOP bit is ignored
// RX enabled
// ninth bits are zeros
// clear RI0 and TI0 bits
if (SYSCLK/BAUDRATE/2/256 < 1) {
TH1 = -(SYSCLK/BAUDRATE/2);
CKCON |= 0x08; // T1M = 1; SCA1:0 = xx
} else if (SYSCLK/BAUDRATE/2/256 < 4) {
TH1 = -(SYSCLK/BAUDRATE/2/4);
CKCON &= ~0x0B; // T1M = 0; SCA1:0 = 01
CKCON |= 0x01;
} else if (SYSCLK/BAUDRATE/2/256 < 12) {
TH1 = -(SYSCLK/BAUDRATE/2/12);
CKCON &= ~0x0B;
// T1M = 0; SCA1:0 = 00
} else if (SYSCLK/BAUDRATE/2/256 < 48) {
TH1 = -(SYSCLK/BAUDRATE/2/48);
CKCON &= ~0x0B; // T1M = 0; SCA1:0 = 10
CKCON |= 0x02;
} else {
while (1); } // Error. Unsupported baud rate
TL1 = TH1; // init Timer1
TMOD &= ~0xf0; // TMOD: timer 1 in 8-bit autoreload
TMOD |= 0x20;
TR1 = 1; // START Timer1启动定时器1
TI0 = 0; // Indicate TX0 ready 初始化TX0
EA=1;//开放中断
ES0=0;//允许 UART0 中断
RI0=0;//RX0
}
void KeyScan()
{
P1=0x0f;
a=P1;
delay();
P1=0xf0;
b=P1;
delay();
c=a+b;
if(c==0xee)P2=tab[0];//0
if(c==0xde)P2=tab[1];//1
if(c==0xbe)P2=tab[2];//2
if(c==0x7e)P2=tab[3];//3
if(c==0xed)P2=tab[4];//4
if(c==0xdd)P2=tab[5];//5
if(c==0xbd)P2=tab[6];//6
if(c==0x7d)P2=tab[7];//7
if(c==0xeb)P2=tab[8];//8
if(c==0xdb)P2=tab[9];//9
if(c==0x77)j=0;//确定发送
}
void SendData(uchar *q)
{
uchar p;
for(p=0;*q!='\0';p++){
SBUF0=*q;
while(!TI0);
TI0=0;
q++;
}
q=0;
}
void main (void) {
PCA0MD &= ~0x40; // WDTE = 0 (clear watchdog timer enable)
PORT_Init(); // Initialize Port I/O
SYSCLK_Init (); // Initialize Oscillator
UART0_Init();
P2=0X00;
while(1)
{ KeyScan();
if(j==0)//发送
{SendData(Send);
j=1;
}
}
} |