Working on a little "game", to test reaction speed, got stuck on the first step of the whole project. I have an led that blinks every 2 seconds, and a buzzer that makes a sound if the button is pressed while the led is on. The problem is, pin 2 only reads when the led is on. I cannot figure out what's causing that. If I completely remove the code for the led, it works, the delay should not effect the code for the button since it's in a seperate void, I don't understand.
const int button = digitalRead(2);
const int greenLed = digitalRead(8);
void setup(){
Serial.begin(9600);
pinMode(2, INPUT);
pinMode(8, INPUT);
pinMode(4, OUTPUT);
pinMode(7, OUTPUT);
}
void loop(){
led();
buttonPress();
}
void led(){
digitalWrite(4,HIGH);
delay(500);
digitalWrite(4,LOW);
delay(2000);
}
void buttonPress(){
Serial.print(button);
if(button == HIGH && greenLed == HIGH){
tone(7,300,20);
}
}
const int button = digitalRead(2);
does not mean that the pin is continuously read by the software.
You need to read the button in loop() or buttonPress(); simplified example below
const int button = 2;
...
...
void setup()
{
pinMode(button, INPUT);
...
...
}
void loop()
{
...
...
}
void buttonPress()
{
byte val = digitalread(button);
Serial.print(val);
if(val == HIGH)
{
tone(7,300,20);
}
}
sterretje:
const int button = digitalRead(2);
does not mean that the pin is continuously read by the software.
You need to read the button in loop() or buttonPress(); simplified example below
const int button = 2;
...
...
void setup()
{
pinMode(button, INPUT);
...
...
}
tried it, still got the same problem
void loop()
{
...
...
}
void buttonPress()
{
byte val = digitalread(button);
Serial.print(val);
if(val == HIGH)
{
tone(7,300,20);
}
}
since it's in a seperate void
It's called a function, not a void. Void is the return type of the function. Means the function returns nothing. Other functions return different types and they would have that type instead of void.