如何在 arduino flex 传感器中以 45 度开始点亮?

How to start lighting up at 45 degree in aurduino flex sensor?

我想让 LED 灯带随着柔性传感器的弯曲而逐渐亮起。但我希望当柔性传感器为 45 度时 LED 灯条开始亮起。 我希望 LED 灯带在 45 度之前熄灭。 这是我在 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

}

但这没有用,所以我试了这个:

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 度时点亮更多。如果你能帮助我,我将非常感激。我已经筋疲力尽了,却无处可去。

一个问题是当地图功能期望值在 460 到 850 范围内时,您将传感器设置为零。将低于 45 度时的默认传感器值更改为最低值可能会有所帮助预期范围 (460.)

您也可以删除您的 if 条件并稍后在程序中移动它,如下所示:

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

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

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