1

I have made this If-Then-Else code, but it doesn't work.

First I tough only the analog code is wrong, but if I take a digital port, the code doesn't work either.

What did I do wrong?

int sensorPin = A0; // select the input pin for the potentiometer
int sensorValue = 0.00001; // variable to
void setup() {
 pinMode(13, OUTPUT); //LED BORD UIT
 pinMode(12, OUTPUT); //LED4
 pinMode(11, OUTPUT); //LED3
 pinMode(10, OUTPUT); //LED2
 pinMode(9, OUTPUT); //LED1
 pinMode(8, OUTPUT); //Elektro Magneet
 pinMode(A0, INPUT);
}
void loop() {
 if (A0 == HIGH) {
 digitalWrite(13, LOW); 
 digitalWrite(12, HIGH); //LED on, magnet off
 digitalWrite(11, HIGH); 
 digitalWrite(10, HIGH); 
 digitalWrite(9, HIGH);
 digitalWrite(8, LOW); 
 } else { 
 digitalWrite(13, LOW); 
 digitalWrite(12, LOW); // LED Off, magnet on
 digitalWrite(11, LOW); 
 digitalWrite(10, LOW); 
 digitalWrite(9, LOW); 
 digitalWrite(8, HIGH); 
 }
}
asked Oct 24, 2014 at 23:23
2
  • Sidenote: Be careful with that electro magnet. Those tend to use quite a bit of current, while the digital pins of the arduino can only source a maximum of 40mA. You don't want to "blow up" you Arduino. Commented Oct 25, 2014 at 13:15
  • To add to what @Gerben said, you'll want to keep current around and under 20mA on any I/O pin and under 100mA on the MCU. Beyond lighting a few LEDs, you'll have to use transistors, darlingtons and relays. Commented Oct 25, 2014 at 15:50

3 Answers 3

9

Replace the line:

 if (A0 == HIGH) {

by this one:

 if (digitalRead(A0) == HIGH) {

If you plan on using the pin back as an analog input, use something like this:

 if (analogRead(A0) > 512) {

The explanation is what Ignacio said: you were comparing the pin "name" A0 directly to HIGH instead of reading from the input named A0. To make it clearer, the two lines are equivalent:

if (A0 == HIGH)
if (0 == HIGH)

Get it?

There's more about what pin names to use with digitalRead() and analogRead() here:

answered Oct 24, 2014 at 23:29
2

You're comparing the pin variable value with HIGH. If you want to get the value at a digital input then you need to use digitalRead().

answered Oct 24, 2014 at 23:27
2

You have defined your pin as

int sensorPin = A0;

Which should be replaced with

#define sensorPin = A0

And then in your code, you need to read the value from the pin in your if statement:

 if (digitalRead(sensorPin) == HIGH) {
answered Nov 10, 2014 at 18:36

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.