0

因此,当超声波传感器检测到距离小于一定量时,这就是我想要实现的目标,然后灯应该变绿,允许交通移动 这是电路的图像

这是代码

int pir = 2;
int rojo = 12;
int amarillo = 11;
int verde = 10;
int led = 3;
const int pingPin2 = 9; // Trigger Pin of Ultrasonic Sensor
const int echoPin2 = 8;
void setup() {
  pinMode(pir, INPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  pinMode(verde, OUTPUT); //It declares the green pin as output 
  pinMode(amarillo, OUTPUT); //It declares the yellow pin as output 
  pinMode(rojo, OUTPUT);
}

void loop() {
  int distance2;
  distance2 = calculatedistance(pingPin2, echoPin2);
  if (distance2 <= 0.1) {
    digitalWrite(rojo, LOW);
    digitalWrite(verde, HIGH);
    delay(500);
  }

  digitalWrite(verde, HIGH); //It turns on the green led 
  delay(15000); //wait 15 seconds 
  digitalWrite(verde, LOW); //It turns off the green led 
  delay(250); //wait 0.25 seconds

  digitalWrite(amarillo, HIGH); //It turns on the yellow led 
  delay(3000); //wait 3 seconds 
  digitalWrite(amarillo, LOW); //It turns off the yellow led 
  delay(250); //wait 0.25 seconds
  int val = digitalRead(pir);
  Serial.println(val);
  int val1 = digitalRead(rojo);
  digitalWrite(rojo, HIGH); //It turns the red led 

  unsigned long int redStartTime = millis();
  while (millis() - redStartTime <= 15000) {
    delay(100);
    int val = digitalRead(pir);
    if (val == HIGH) {
      digitalWrite(led, HIGH);

    } else {
      digitalWrite(led, LOW);
    }
  }
  digitalWrite(rojo, LOW);
}

long microsecondsToCentimeters(long microseconds) {
  return microseconds / 29 / 2;
}
int calculatedistance(int pingPin, int echoPin) {
  long duration, inches, cm, meter;
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(pingPin, LOW);

  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);

  cm = microsecondsToCentimeters(duration);
  meter = cm / 100;
  return meter;
}

有人可以帮助我达到预期的结果。还有一个问题,如果我想在这些环境中使用 printf 或类似的东西检查变量的值,我该怎么做?提前致谢

4

1 回答 1

0

怎么看printf?考虑到没有屏幕。假设您有一个文件系统,您可以将输出写入(即记录)文件。

你的问题:看看“空循环”

distance2 = calculatedistance(pingPin2, echoPin2);
if (distance2 <= [CERTAIN_AMOUNT])
{
    digitalWrite(rojo, LOW);
    digitalWrite(verde, HIGH);
    delay(500);
}
于 2020-12-06T07:15:00.097 回答