Hello
I am trying to use a 2 pin toggle switch https://www.amazon.co.uk/dp/B07RQ4ZBQJ?psc=1&ref=ppx_yo2ov_dt_b_product_details to change modes for the programme I am making however i cannot get it to register a change when i flip the switch
const int switchPin = A6;
void setup() {
Serial.begin(9600);
pinMode(switchPin, INPUT_PULLUP); // Enable internal pull-up resistor on A6
}
void loop() {
int switchState = digitalRead(switchPin);
if (switchState == LOW) {
Serial.println("Switch ON");
} else {
Serial.println("Switch OFF");
}
delay(100); // Adjust delay as needed
}
This is the code im using to debug it, i have tried connecting the switch to 5v & A6, Gnd & A6 and A6 & Gnd using a 10k resistor but each time it just reads as switch on.
Any help would be greatly appreciated
Welcome to the forum
const int switchPin = A6;
Which Arduino board are you using ?
If it is a classic Nano then the A6 cannot be used as a digital input
Thanks for the speedy reply!!
ELEGOO Nano Board 340/ATmega Nano328P compatible with offical Nano (pack of 3) https://amzn.eu/d/06e7V3Y6
This is the board I'm using, I assume it's a nano classic?
Yes, it's a Nano classic
A5 and A6 A6 and A7 are analogue only on that board. You could change the code to use analogRead() if you really needed to
EDIT - corrected pin numbers. See reply #6
Would I still be able to use a toggle switch. If not could I potentially use A7 instead?
Sorry completely new to all this so I really appreciate the help
Sorry, I see that I made a mistake in my previous reply
It is pins A6 and A7 that can only be used as analogue inputs
If you change the code a little then you could use analogRead() to detect whether one of those pins is currently HIGH or LOW
HIGH will return a value of close to 1023 and LOW a value close to zero
HIGH will return a value way bigger than 512, and LOW a value way smaller.
But why use analog pins at all? Maybe when you are pinched and have run out, just use digital pins and know that most so-called analog pins work perfectly well with digital read and write.
a7
The only pins I have spare are A6 and A7. The rest are being used by the programme & hardware
So am I right in thinking I connect the toggle switch to A6 and ground and the change the original code switchState = digitalRead(switchPin);
To
switchState = analogRead(switchPin);
No. Read the responses. We may have been hinting too quietly:
switchState = analogRead(switchPin) < 512;
would set switchState true if a pulled-up input pin was connected to ground by your switch closed contacts.
a7