Go Down

Topic: Simple question about turning on a led. (Read 1 time) previous topic - next topic

jhacked

Hi guys! How are you? I've a problem and i'm gonna to explain it. I have to turn on a led when i put my finger on the cny70. I know how i can do this, but i've to save the state of the led. I mean that the led, when i raise my finger from the sensor, has to stay on but, putting the finger again on the cny70, the led has to turn off. I wrote this code but it doesn't function very well, i would be very happy if someone of you could give me an hand! :D

Code: [Select]

#define led1 13
#define led2 12
#define sensor A0

int state = 0; 

void setup() {
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(sensor, INPUT);
}

void loop() {
  digitalWrite(led1, HIGH);
  int readsensor = analogRead(sensor);
 
  if (state == 0) { 
    digitalWrite(led2, LOW); 
      if (readsensor < 950) {
        state = 1;
      }
  } else { 
        digitalWrite(led2, HIGH); 
      if (readsensor < 950) {
        state = 1 - state;
      }
  } 
}

johnwasser

The problem is that you aren't keeping track of the previous position of your finger.  The result is that the LED will rapidly alternate between ON and OFF as long as the finger is in position.   You want to change the LED state only when the finger state changes from AWAY to CLOSE.
Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

jhacked

Yeah, i need right that. But i don't know how i can do it. I understand that i should create a variable called "oldstate", but what kind of value i've to give to it? Can you show me a code example?

thank you very much, my friend!

Grumpy_Mike

At the end of the loop() have the following line:-
Code: [Select]

oldstate = state;

Define oldstate just like you defined state in the same place.

jhacked

thx Grumpy. So now i've this and it gives me problem like before, maybe better but not so much.

Code: [Select]


#define led1 13
#define led2 7
#define sensor A0

int state = 0; 
int oldstate = 0;

void setup() {
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(sensor, INPUT);
}

void loop() {
  digitalWrite(led1, HIGH);
  int readsensor = analogRead(sensor);
 
  if (state == 0) { 
    digitalWrite(led2, LOW); 
      if (readsensor > 15) {
        state = 1;
      }
  } else { 
        digitalWrite(led2, HIGH); 
      if (readsensor > 15) {
        state = 1 - state;
      }
  } 
  oldstate = state;
}


Go Up