I want to make the led strips gradually lights up as the flex sensor bends. But I want the led strips start to light up when the flex sensor is 45 degree. And I want the led strips to be off before 45 degree. Here is my code which is in Arduino.
const int ledPin = 3; //pin 3 has PWM funtion
const int flexPin = A0; //pin A0 to read analog input
int degree; //save analog value
int sensor;
void setup(){
pinMode(ledPin, OUTPUT); //Set pin 3 as 'output'
Serial.begin(9600); //Begin serial communication
}
void loop(){
sensor = analogRead(flexPin); //Read and save analog value from potentiometer
degree = map(sensor, 460, 850, 45, 90);
Serial.print("analog input: ");
Serial.print(sensor,DEC);
Serial.print(" degrees: ");
Serial.println(degree,DEC);
Serial.print(" ---------------------------------- ");
analogWrite(ledPin, degree); //Send PWM value to led
delay(50); //Small delay
}
but this did not worked, so I tried this one:
const int ledPin = 3; //pin 3 has PWM funtion
const int flexPin = A0; //pin A0 to read analog input
int degree; //save analog value
int sensor;
void setup(){
pinMode(ledPin, OUTPUT); //Set pin 3 as 'output'
Serial.begin(9600); //Begin serial communication
}
void loop(){
sensor = analogRead(flexPin); //Read and save analog value from potentiometer
if(degree<45){
(sensor = 0);
}
degree = map(sensor, 460, 850, 0, 90);
Serial.print("analog input: ");
Serial.print(sensor,DEC);
Serial.print(" degrees: ");
Serial.println(degree,DEC);
Serial.print(" ---------------------------------- ");
analogWrite(ledPin, degree); //Send PWM value to led
delay(50); //Small delay
}
And this did not worked as well. They start lighting up from the 0 degree and gets more as it goes closer to 90 degree. But I want it to be off before 45 degree, start to light up at 45 degree and get more as it gets closer to 90 degree. I will be so thankful if you could help me. I am so exhausted trying and getting to no where.
One problem is that you are setting your sensor to zero when the map function is expecting a value in the range of 460 and 850. It may help to change your default sensor value when below 45 degrees to the lowest value in the expected range (460.)
You could also remove your if condition and shift it later in the program like so:
if (degree < 45) {
digitalWrite(ledPin, LOW);
}
else {
analogWrite(ledPin, degree);
}
It may also be worth noting that the analog read function uses in input between 0 to 255 to determine the duty cycle of the pin. With that said, you could create another variable and use it to map or otherwise change the degree value so it better utilizes this range. i.e:
int freq = map(degree, 0, 90, 0, 255);