嵌入式c:实现逻辑

时间:2015-02-16 07:26:42

标签: c arduino embedded

我编写了一个代码来检测颜色,当检测到颜色时,然后读取超声波传感器。

但在目前的代码中,它每次检查颜色传感器,然后测试超声波传感器输出...我的意思是它检查每个读数的颜色传感器... 我实际上只想检查一次颜色传感器的输出,然后开始读取读数而不用担心颜色... 然而,如果在一段时间后再次检测到相同的颜色,那么它应该停止读取...

这是代码:

 int sensorPin=A0;    // select ip which reads from color                       //sensor  to detect blue color
 int sensorValue=0;


const int pingPin = 13; //pin which triggers ultrasonic sound


int inPin = 12;   //pin which delivers time to receive echo 




void setup() {

  Serial.begin(9600);// initialize serial communication


  pinMode(pingPin, OUTPUT); //initializing the pin states
  pinMode(inPin, INPUT);  //setting up the input pin

}

void loop()
{

  sensorValue= analogRead(sensorPin);

  long duration, cm;

      if(sensorValue >= 1 )
        {
           digitalWrite(pingPin, LOW);       //sending the signal, starting with LOW for a clean signal
           delayMicroseconds(2);
           digitalWrite(pingPin, HIGH);
           delayMicroseconds(5);
           digitalWrite(pingPin, LOW);
        } 



     duration = pulseIn(inPin, HIGH);


     cm = microsecondsToCentimeters(duration);// convert the time into a distance

     Serial.print(cm);             //printing readings to serial display
     Serial.print("cm");
     Serial.println();


}


float microsecondsToCentimeters(float microseconds)
{

  return microseconds / 29.0 / 2.0;
}

1 个答案:

答案 0 :(得分:0)

sensorValue  is a global variable.

您需要在if

中清除它
if(sensorValue >= 1 )
{
 sensorValue = 0;
     :
     :
}

编辑: 以上答案基于假设analogRead(sensorPin);函数仅在检测到新输入脉冲时才返回非零值。