Go Down

Topic: Turning on and off LED according to the toggle switch state (Read 171 times) previous topic - next topic

toomer

I am trying to turn on and off LED using toggle switch. But for some reason, the LED only respond to the toggle switch state once. For example, when toggle switch is flip to "ON" LED is on but when toggle switch is flip to "OFF" the LED still remain on. Is it my coding issue or my connection? and how do I resolve it? Thanks

Code: [Select]
#define Port 3
#define LED 2


void setup()
{
  pinMode(Port, INPUT);
  pinMode(LED, OUTPUT);
}

void loop()
{
   if (digitalRead (Port) == 0)
   digitalWrite (LED, LOW);
  
   else
   digitalWrite (LED,HIGH);
}




PaulRB

Your input pin is floating.

Your led has no series resistor.

Your '328 chip has no bypass cap.

Why are you using an Arduino for this?

toomer

I am trying to simulate water level sensor. like using 2 pieces of wire to detect water level after that is successful i will do the water float switch

PaulRB


toomer

the switch will be the water sensor. LED wise no change. so yeah is a simulation of a real circuit

toomer

look like i need to a resistor between the pin and ground and it works  thanks for your reply

Paul__B

look like i need to a resistor between the pin and ground and it works  thanks for your reply
Except that is a bad way to arrange things.

Connect your switch between an input pin and ground.  Either provide a resistor (10k) to 5 V, or set pinMode as INPUT_PULLUP (or doing both will not hurt!).  Obviously the input will now read LOW when the switch is closed and HIGH otherwise, so you write your sketch accordingly.

Connecting input switches to 5 V is a bad idea since you really do not want to expose your power line to outside parts.  You run a risk of shorting it to ground if a fault occurs and that aside if you submerge it in water where some other part of the plumbing is grounded, you will suffer electrolytic damage.

Actually, electrolysis is a concern whenever you propose to put sensor probes in water.  The preferred way to do so is to have a ground reference electrode in the water (such as the copper piping itself) and a sensor electrode of the same metal connected to an Arduino input through a (ceramic or polystyrene) capacitor and 220 Ohm series resistor.  The capacitor prevents any electrolytic current to flow; you normally define the Arduino pin as an OUTPUT and LOW, whenever you want to read the conductivity, you set it to INPUT_PULLUP immediately before reading it.

Go Up