首页 > 解决方案 > 按下两个按钮时试图让电机停止

问题描述

我正在做一个项目,它有两个按钮,每个按钮都通过 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;
        }
    }
}

标签: cembeddedmicrocontrolleravr

解决方案


假设当你按下一个按钮时,1 << PD2pin 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;

推荐阅读