我正在做一个项目,在这个项目中,我试图为一个膜键盘编写自己的功能。我希望将16个关键状态存储在一个uint16_t
变量中,因此我只有一个变量。代码编译。
问题是它不能正确地显示关键状态。当我按下1键时,它会告诉我更多的按键被按下。它还会显示按键被按下,根本不碰东西。
键盘的5-8引脚连接到PORTD,4-7销连接在Nano上.键盘上的引脚1-4连接到PORTB,在Nano上有0-3引脚.
这是密码。
uint16_t keys = 0;
void setup() {
// put your setup code here, to run once:
DDRD |= 0xF0; //Set bit 4-7 as output on PORTD
DDRB &= 0xF0; //Set bit 0-3 as input on PORTB
Serial.begin(9600);
}
void loop() {
getKeys(&keys);
Serial.println("-----------------------");
delay(100);
}
void getKeys(uint16_t* keys){
*keys = 0; //Clear keys variable
for(int rows = 0; rows < 4; rows++){ //Loop through every row
PORTD &= 0x0F; //Turn pin 4-7 on PORTD off
PORTD |= (16 << rows); //Turn on pin.
Serial.print(String(PORTD) + String(" : ")); //Print current selected bit(row)
uint16_t temp = (PINB & 0x000F); //Take bit 0-3 from PORTB
Serial.println(temp, BIN); //Print the PINB values as binary
*keys |= (temp << (rows*4)); //Shift the PORTB values into keys.
}
}
这是串行监视器中的输出。
16 : 0
32 : 0
64 : 0
128 : 0
-----------------------
16 : 0
32 : 0
64 : 0
128 : 1
-----------------------
16 : 0
32 : 0
64 : 0
128 : 11
-----------------------
16 : 0
32 : 1000
64 : 10
128 : 1111
-----------------------
16 : 1000
32 : 1110
64 : 1110
128 : 1111
-----------------------
16 : 1000
32 : 1110
64 : 1110
128 : 1111
-----------------------
16 : 0
32 : 0
64 : 0
128 : 0
-----------------------
16 : 0
32 : 0
64 : 0
128 : 0
-----------------------
发布于 2017-12-12 03:34:57
当所有键都没有按下时,您的输入就不会连接到任何东西。它们只是“漂浮在空中”,可以接受外界的任何电力干扰。
键盘应该以其他方式工作。
DDRB &= 0xF0; PORTB |= 0x0F
.那么,现在所有的输入都应该读为逻辑1,例如。1111
。1110, 1101, 1011, 0111
。~
),您可以反转读取数字,例如temp = PINB; temp ~= temp; temp &= 0x0F
或仅temp = (~PINB) & 0x0F
。同样的方式,你可以在输出前使用按位而不是运算器,例如PORTD = (~(16 << rows)) & 0x0F
。
这样,您在PINB上的输入将始终连接到某个源-通过AVR芯片内的拉出电阻连接到VCC (+5V),或者当您在PORTD的输出引脚上设置逻辑0时,连接到GND。你也不会收到任何电气噪音。
https://stackoverflow.com/questions/47754751
复制相似问题