c - 按下两个按钮时试图让电机停止
问题描述
我正在做一个项目,它有两个按钮,每个按钮都通过 H 桥将电机转向一个方向(时钟/逆时针方向),但是当我单击两个按钮时,我试图让电机停止按按钮。一切正常,但我无法获得两个按钮部分......
这是我的尝试:
#include "motor.h"
#include <avr/io.h>
#include <util/delay.h>
int flag=0;
int main(void)
{
DDRD &= ~(1<<PD2);
DDRD &= ~(1<<PD3);
DDRB |= (1<<PB0);
DDRB |= (1<<PB1);
PORTB &= ~(1<<PB0);
PORTB &= ~(1<<PB1);
while(1)
{
if (PIND & (1<<PD2))
{
flag = 1;
}
else if (PIND & (1<<PD3))
{
flag = 2;
}
else if (PIND & (1<<PD3 ) && (1<<PD2))
{
flag = 3;
}
switch (flag)
{
case 1:
DC_MOTOR_PORT |= (1<<DC_MOTOR_PIN1);
DC_MOTOR_PORT &= ~(1<<DC_MOTOR_PIN2);
break;
case 2:
DC_MOTOR_PORT |= (1<<DC_MOTOR_PIN2);
DC_MOTOR_PORT &= ~(1<<DC_MOTOR_PIN1);
break;
case 3:
DC_MOTOR_PORT=0x00;
break;
}
}
}
解决方案
我假设当你按下一个按钮时,1 << PD2
pin inPIND
被设置。条件PIND & (1 << PD2)
变为真,if
分支被采用,代码不会费心去测试其他条件(因为它们在else
子句中)。
此外,&&
是一个逻辑运算。(1<<PD3 ) && (1<<PD2)
总是产生true
,因此该else
子句将有效地测试PING & 1
. 不完全是你想要的。
改为考虑
button_state = PIND & ((1 << PD2) | (1 << PD3)); // Mask out pins of interest
switch (button_state) {
case 0: // Nothing pressed
....
break;
case 1 << PD2: // One button pressed
....
break;
case 1 << PD3: // Another button pressed
....
break;
case (1 << PD2) | (1 << PD3): // Both pressed
....
break;
推荐阅读
- postgresql - Postgres ALTER TABLE ...应用多项更改时出现意外性能
- python-3.x - 如何解决python moduleNotFoundError
- java - 如何在 netbeans 12 中创建 i18n Web 应用程序?
- android - 如何为列表视图中的按钮列表分配索引?
- web3 - Web3:验证 sendTransaction 值
- linux - linux sed用env变量替换字符串
- javascript - 每次使用命令时,如何让不和谐机器人从 Google 表格中提取随机单元格?
- google-sheets - Sumproduct 行到另一列的最后一个空白单元格
- ruby - RSpec:如何按对象身份比较 have_received 参数?
- python - 如何在 Tkinter 中用 n 段画一条线?