Hello everybody !
New forum member here, altough I've read and learned a lot for a year from this forum
My background: 20+ years of software development, but a noob in electronics.
Anyway, here's my problem...
My goal:
I want to use the same digital pin on an arduino (mega) as an input with a switch and as an output with an LED, both "at the same time".
By "at the same time", I mean that the pin would be configured as an output to light (or not) an LED to show a status, then configured as an input to check if a momentary switch is pressed, then configured back as an output, and so on.
Why am I doing this ?
Well I've got some normally-open momentary switches already connected and working (home automation), but I would like to add some status LEDs near the switches (but not logically related to the switches), without adding wires (long distance, and it was a pain to pull all those wires through the walls and ceilings in my home, I don't want to add a bunch of additional wires).
What I've got so far:
I rigged everything up on a breadbord.
shematic:
GND -----------[ resistor ]-----+-------[ LED ] --------+----- [ switch ]--------- io Pin
+ +
+-----[ capacitor ]-----+
The capacitor is here to avoid the LED to be dimly lit while the pin is configured as an input.
code:
Most of the time the pin is an output pin, and 10 times a second we use it as an input pin to check the switch.
No debounce is handled in this test program.
#define ioPin 12
short myStatus;
unsigned long lastReading;
void setup (void)
{
pinMode (ioPin, OUTPUT);
myStatus = HIGH; // note: as this is a test program, status would be updated by some other logic inside loop(). here it is set to HIGH all the time.
lastReading = 0;
Serial.begin (9600);
}
void loop (void)
{
short reading;
// update LED
digitalWrite (ioPin, myStatus);
// 100 ms have passed ?
if (millis () - lastReading > 100)
{
lastReading = millis ();
// read switch
pinMode (ioPin, INPUT);
digitalWrite (ioPin, HIGH); // use pullup resistor
reading = digitalRead (ioPin);
pinMode (ioPin, OUTPUT);
Serial.println (reading, DEC);
}
}
What I need:
I can read the switch fine. That part seems to be ok.
But the status is reflected on the LED only when the button is pressed obviously, since I'm using a normally-open momentary switch.
I need a way to let the current go trough the circuit so the status is always shown on the LED when nobody uses the switch. So I could use a normally-closed momentary switch, but unfortunately these are not available by the maker of my switches (Legrand in France)… mine are regular (altough temporary) 220v wall mounting switches, but connected on the arduino instead of the mains.
I've got space left on the arduino end to add electronics, and some space on the switch + LED end, but can not add additional wires between the arduino and the other end.
I hope all this makes sense ? Fell free to ask for more details
EDIT:
corrected schematic, thanks Mike for pointing that out !