2016-09-26 65 views
2

我想让柔性传感器弯曲时,LED灯条逐渐点亮。但是我希望柔性传感器为45度时,LED灯条开始点亮。 而且我希望在45度之前关闭led灯条。 这是我在Arduino的代码。如何在aurduino柔性传感器中以45度角开始点亮?

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 

} 

但这并没有工作,所以我想这一个:

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 

} 

而且这并没有工作过。他们从0度开始点亮,随着接近90度而变得更多。但我希望它在45度之前关闭,开始点亮45度,并在接近90度时获得更多。如果你能帮助我,我会非常感激。我非常努力地尝试,并没有去哪里。

回答

3

的一个问题是,你是你的传感器设置为零时,地图功能在460和850这可能有助于改变你的默认传感器值低于45度时,在最低值的范围内期待值预期范围(460)

你也可以删除您若条件,像这样在以后的程序接班:

if (degree < 45) { 
    digitalWrite(ledPin, LOW); 
} 
else { 
    analogWrite(ledPin, degree); 
} 

这也可能是值得注意的是,模拟读出功能的输入之间0使用到255来确定引脚的占空比。这样说,你可以创建另一个变量,并使用它来映射或以其他方式更改度数值,以便更好地利用此范围。即:

int freq = map(degree, 0, 90, 0, 255);