Hello, I am trying to use a momentary switch to do a state change detection in my code, however the arduino isn't noticing the button being pushed. I've tested the button with an led and the button works fine, and yet when I connect it to my arduino it doesn't work. I have my button connected like the bottom configuration (to have the button always illuminated), and the positive to the button is coming from a 12v power supply, and the arduino is powered by the same power supply. Any ideas?
I'm sorry for posting my code this way, but I can't figure out how to post it correctly
int inPin = 2;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;
const int numReadings = 10;
void setup() {
pinMode(inPin, INPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if (buttonState != lastButtonState) {
if (buttonState == HIGH) {
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
} else {
Serial.println("off");
}
delay(50);
}
}
Hello
I´ve found a sketch in my sketch box that might match to your project. You have simply change the I/O pins to your used hardware.
#define ProjectName "Solution for Illuminated momentary switch not working with my code - FORUM -\n"
const int heartBeat {
LED_BUILTIN
};
// make an object for the used button
struct BUTTON {
byte switchPin;
byte ledPin;
bool state;
unsigned long stampTime;
unsigned long debounceTime;
};
// initialize the object
BUTTON button[] {
{A0, 2, 1, 0, 20},
{A1, 3, 1, 0, 20},
{A2, 4, 1, 0, 20},
};
// define the macro for the buttons in use
#define buttonNum unsigned int num=0; num < sizeof(button)/sizeof(BUTTON); num++
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.print("File : "), Serial.println(__FILE__);
Serial.print("Date : "), Serial.println(__DATE__);
Serial.print("Project: "), Serial.println(ProjectName);
pinMode (heartBeat, OUTPUT);
for (buttonNum) pinMode(button[num].switchPin, INPUT_PULLUP), pinMode(button[num].ledPin, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(heartBeat, millis() / 500 % 2);
for (buttonNum) {
if (millis() - button[num].stampTime >= button[num].debounceTime)
{
button[num].stampTime = millis();
bool state = digitalRead(button[num].switchPin);
if (button[num].state != state) {
button[num].state = state;
if (state) digitalWrite ( button[num].ledPin, digitalRead(button[num].ledPin) ^ 1);
}
}
}
}