I'm a first time user of Arduino Mega. I'm trying to program a 5-position rotary selector switch with its inputs connected to A0 to A4 of the Mega.
Here's my setup code:
void setup()
{
//Setting A0 to A4 as digital inputs (pins 54 to 58)
for (int doutPin = 54; doutPin <= 58 ; doutPin++)
{
pinMode(doutPin, INPUT_PULLUP);
digitalWrite(doutPin, HIGH);
}
}
I think I have defined A0 and A4 to be digital inputs, but now how do I code the Arduino to detect the change in the switch states? (From position 1, 2, 3, 4, 5)?
How do I detect an input signal has changed from the rotary switch?
Paul__B is right, You should have read the instructions first. So many newbies assume they are just about being nice to other forum members, but actually they are about what you need to do so that other forum members can help you at all.
Anyway, try this. I have not tested it.
void setup()
{
//Setting A0 to A4 as digital inputs (pins 54 to 58)
for (int doutPin = A0; doutPin <= A4 ; doutPin++)
{
pinMode(doutPin, INPUT_PULLUP);
}
Serial.begin(9600);
}
void loop() {
int newValue = A0;
static int oldValue = 0;
while (digitalRead(newValue) == HIGH) newValue++;
if (newValue != oldValue) {
Serial.println(newValue);
oldValue = newValue;
}
}
You did not need the digitalWrite(doutPin, HIGH); in your setup() function. Using INPUT_PULLUP does that for you.
By the way, even though you are using a Mega, it it still very wasteful to use 5 analog inputs for this simple switch. By using just 4 identical resistors, you can read the switch position using only one analog input.