Arduino Nano + button input

Hello

I’ve connected a switch with built in blue led and I just want to know when button is On.
The switch has 3 pin (led, state, gnd) so I connected Led to supply, state to arduino pin D3 (through 1k resistor) and gnd to GND and I use digitalRead(D3) to know when it’s on and it works good (also the led lights when on) but there’s a problem:
If I supply arduino with battery or its USB port everything works good
If I supply with AC adapter state floats on off at very high frequency

When using AC adapter is 12V but it’s not connected directly to arduino, I place a regulator (either 7805 + capacitors or ams1117 board) which is connected to VIn & GND

It’s some kind of noise due to ac adapter (switching type) ?

There’s a fix ?

Many thanks in advance


Code:

void setup()
{
pinMode(3, INPUT);
pinMode(13, OUTPUT);
}

void loop()
{
digitalWrite ( 13, digitalRead(3) );
}

Ale

sw.png

There's a fix ?

Yes wire up the switch in the correct manor.
See this:- Inputs

sad

Switch is SPST (according to manufacturer) and cannot be replaced
so if it can be fixed with some kind of magic that's fine, otherways it'll just run forever on batteries

this is it: Rocker Switch - Round w/ Blue LED - COM-11155 - SparkFun Electronics

I read it (although I'm not brilliant) but it looked like that could be used with SPDT not SPST
I also tried INPUT_PULLUP but kept 3 wires config
If I understand correctly I should use use INPUT_PULLUP wiring only two wires on the rocker namely the outer silver pin to D3 and middle one to GND right ?

Edit: I'm sure i saw your reply but now it's gone

From the comments of that link

The gold one connects to ground, the first silver one connects to your 12V supply (or 5-12V, but not higher, because the resistor in series with the LED internally is designed for 12V) and the second silver terminal connects to your load +12V rail.

So wire the gold to ground and first silver to 5V. Then the second silver to the input pin, and also to that pin connect a 10k resistor with the other end of the resistor to ground.

The working correctly with batteries is only an illusion, it will be unreliable.

Edit: I'm sure i saw your reply but now it's gone

Yes I deleted it because I changed my mind.

ok so the magic is a second resistor from middle to ground thx
(crossing finger, board must be ready for tomorrow and i cannot afford to kill it today !)