lil*_*ess 0 c atmega arduino interrupt led
我一直在尝试通过按下相应的按钮来让我的 Arduino 上的 LED 亮起和熄灭。
我正在使用中断来实现它并且按钮按下确实被注册,但由于某种原因它没有改变全局变量的值(int button_pressed1,...);
应该发生的是,当我按下按钮 1 时,LED 1 应该亮起和熄灭,与按钮 2 和按钮 3 相同。
我真的很感谢你看一看,中断对我来说很新,所以这可能是一个小问题。<3
*我省略了按钮 2 和 3 的代码。如果我能让 LED 点亮按钮 1,我就能让它们点亮其他按钮。
#include <util/delay.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include "usart.h"
#define LED_DDR DDRB
#define LED_PORT PORTB
#define BUTTON_DDR DDRC
#define BUTTON_PORT PORTC
#define BUTTON_PIN PINC
int button_pressed1 = 0; //globale variabele to turn on functions
ISR(PCINT1_vect)
{
if (bit_is_clear(BUTTON_PIN, PC1))
{
_delay_us(500); //debounce
if (bit_is_clear(BUTTON_PIN, PC1))
{
button_pressed1 = 1;
printf("button 1 pressed\n");
}
}
}
int main()
{
LED_DDR |= _BV(PB2) | _BV(PB3) | _BV(PB4); //registrer pins output(bit = 1)
LED_PORT |= _BV(PB2) | _BV(PB3) | _BV(PB4);
BUTTON_DDR &= ~_BV(PC1) & ~_BV(PC2) & ~_BV(PC3); //registrer inputs(bit = 0)
BUTTON_PORT |= _BV(PC1) | _BV(PC2) | _BV(PC3); // pull up ( bit =1 )
PCICR |= _BV(PCIE1); //type pins doorgeven
PCMSK1 |= _BV(PC1) | _BV(PC2) | _BV(PC3); //pin/button doorgeven aan change mask
initUSART();
sei();
while (1)
{ //infinte loop
if (button_pressed1 == 1)
{
LED_PORT &= ~_BV(PB2); //turn led on
_delay_ms(500);
LED_PORT |= _BV(PB2); //turn led off
_delay_ms(500);
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
几个基本问题:
volatile并具有针对竞争条件的保护。有关详细信息,请参阅此内容。