I’ve been trying to do an input for a while now. I know for sure I have everything wired correctly. I can get it to work with a very simple circuit, that only turns an LED on, but when I add to the code, it always acts as if the button is always pressed. Here’s my code:
const int ledControl = 13; //initial variable declarations
const int ledRed = 9;
const int butIn = 2;
int inVar = 0;
int haltOps = 0;
int i = 0;
int j = 0;
void setup() {
pinMode(ledControl, OUTPUT); //pinMode declarations
pinMode(ledRed, OUTPUT);
pinMode(butIn, INPUT);
}
void loop() {
digitalWrite(ledControl, HIGH); //start main light
inVar = digitalRead(butIn); //read button
if(inVar == LOW) { //count up each time button is pressed
haltOps++;
}
if(haltOps = 10) { //button has reached 10 presses
digitalWrite(ledControl, LOW); //stop main light
redBlink(); //blink error light
int haltOps = 0;
digitalWrite(ledControl, HIGH);//restore main light
}
}
void redBlink() { //blink error light
for(j = 0; j < 4; j++) { //get brighter, then dimmer, 4 times
for(i = 0; i < 256; i++) {
analogWrite(ledRed, i);
delay(5);
}
for(i = 256; i > 0; i--) {
analogWrite(ledRed, i);
delay(5);
}
}
}
Hi, I'd say from your code you are pulling an input high to 5V to turn the LED on.
If so then place a 10K resistor between the input and gnd, this will make sure that the input is returning to gnd or LOW when the button is open.
The input pins on the arduino are high impedance and can store a charge on them if left open circuit like you probably have.
at this point you have declared a new local variable called haltOps which is distinct from the global one. That will cause problems. Just remove the "int" from this declaration so that it becomes a simple statement.
if(inVar == LOW) { //count up each time button is pressed
haltOps++;
}
That is not counting how many times the button is pressed. Rather it increments haltOps every time through loop() if the button is held down, ie very frequently.
Look at the state change detection example in the IDE to see how to determine when an input changes from HIGH to LOW, not when it is LOW as you are doing now.
at this point you have declared a new local variable called haltOps which is distinct from the global one. That will cause problems. Just remove the "int" from this declaration so that it becomes a simple statement.
Pete
UKHeliBob:
if(inVar == LOW) { //count up each time button is pressed
haltOps++;
}
That is not counting how many times the button is pressed. Rather it increments haltOps every time through loop() if the button is held down, ie very frequently.
Look at the state change detection example in the IDE to see how to determine when an input [u]changes[/u] from HIGH to LOW, not when it i[u]s[/u] LOW as you are doing now.
I hadn't thought of that. I just added a 250 delay in there.