我正在做一个项目,它有两个按钮,每个按钮都通过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中的PIND管脚就设置好了。条件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;

关于c - 试图在按下两个按钮时让电动机停止,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53253602/

10-11 19:29