Hi there! Still terribly unfamiliar with Arduino, but would like some help with a simple project to better my understanding. I'm trying to code a touch sensor-activated light that, instead of turning on immediately, fades on and fades off when the hand leaves the sensor. I've so far figured out the on/off part:
here was my attempt for the fade code. I tried to put the for loop code into my touch code but it doesn't work that well.
const int analogInPin = A0; // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; // Analog output pin that the LED is attached to
int sensorValue = 0;
int fadeValue = 0;
void setup() {
pinMode(analogOutPin, OUTPUT); // declare LED as output
}
Are you trying to implement a touch-on/touch-off kind of functionality? That would require a state change detection. Right now the output just tracks the input. You need to specify what you expect, and what you are seeing. "Doesn't work that well" doesn't help us understand your problem.
There are four states - off, on, fading up and fading down. Work out what should trigger
transitions between them and when. For instance do you want to respond to input during
a fade or let the fade complete? Draw out all the possibilities and make them explicit in
your thinking.
Following on from MarkT. I like to set global variables like...
enum states {TS_ON, TS_FADING_OFF, TS_OFF, TS_FADING_ON} switchState = TS_OFF
and then in loop you can use a switch statement like....
void loop() {
int sensorValue=analogRead(analogInPin);
switch (switchState){
case TS_ON:
if (sensorValue>50){
//set switchState=TS_FADING_OFF
//do stuff to start fading off
}
break;
case TS_FADING_OFF:
//fad off
//when off set switchState=TS_OFF
break;
case TS_OFF:
if (sensorValue>50){
//set switchState=TS_FADING_ON
//do stuff to start fading on
}
break;
case TS_FADING_ON:
//fad on
//when on set switchState=TS_ON
break;
}
}