问题描述
- 单片机编程按键与实际按键正好颠倒
-
#include
#define LEDLen 6
#define mode 0x03;
#define CAddr XBYTE[0xe100]/* 控制字地址 /
#define OUTBIT XBYTE[0xe101]/ 位控制口 /
#define CLK164 XBYTE[0xe102]/ 段控制口(接164时钟位) /
#define DAT164 XBYTE[0xe102] / 段控制口(接164数据位) /
#define IN XBYTE[0xe103] / 键盘读入口 */unsigned char LEDBuf[LEDLen]; /* 显示缓冲 /
code unsigned char LEDMAP[] = { / 八段管显示码 */
0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07,
0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71
};void Delay(unsigned char CNT)
{
unsigned char i;while (CNT-- !=0)
for (i=100; i !=0; i--);
}void DisplayLED()
{
unsigned char i, j;
unsigned char Pos;
unsigned char LED;Pos = 0x20; /* 从左边开始显示 /
for (i = 0; i < LEDLen; i++) {
OUTBIT = 0; / 关所有八段管 /
LED = LEDBuf[i];
for (j = 0; j < 8; j++) { / 送164 /
if (LED & 0x80) DAT164 = 1; else DAT164 = 0;
CLK164 = CLK164|0x02;
CLK164 = CLK164&0xfd;
LED <<= 1;
}
OUTBIT = Pos; / 显示一位八段管 /
Delay(1);
Pos >>= 1; / 显示下一位 */
}
}code unsigned char KeyTable[] = { /* 键码定义 */
0x00, 0x01, 0x04, 0x07 ,
0x0f, 0x02, 0x05, 0x08,
0x0e, 0x03, 0x06, 0x09 ,
0x0d, 0x0c, 0x0b, 0x0a ,
0x10,0x11,0x12,0x13,0x14,
0x15,0x16,
};unsigned char TestKey()
{
OUTBIT = 0; /* 输出线置为0 /
return (~IN & 0x0f); / 读入键状态 (高四位不用) */
}unsigned char GetKey()
{
unsigned char Pos;
unsigned char i;
unsigned char k;i = 6;
Pos = 0x20; /* 找出键所在列 */
do {
OUTBIT = ~ Pos;
Pos >>= 1;
k = ~IN & 0x0f;
} while ((--i != 0) && (k == 0));/* 键值 = 列 X 4 + 行 */
if (k != 0) {
i *= 4;
if (k & 2)
i += 1;
else if (k & 4)
i += 2;
else if (k & 8)
i += 3;OUTBIT = 0; do Delay(10); while (TestKey()); /* 等键释放 */ return(KeyTable[i]); /* 取出键码 */
} else return(0xff);
}void main()
{
CAddr = mode;
LEDBuf[0] = 0xff;
LEDBuf[1] = 0xff;
LEDBuf[2] = 0xff;
LEDBuf[3] = 0xff;
LEDBuf[4] = 0x00;
LEDBuf[5] = 0x00;while (1) {
DisplayLED();
if (TestKey()) LEDBuf[5] = LEDMAP[GetKey() & 0x0f];
}
}程序如上 为什么按键会上下颠倒?
解决方案
这个要看你的硬件怎么设计的。
解决方案二:
单片机引脚的高低电平跟你想的不一样
解决方案三:
查看对应的寄存器,设置寄存器值。