【问题标题】:Why does the green light light up when needed?为什么需要时绿灯亮?
【发布时间】:2020-12-06 04:14:03
【问题描述】:

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

这是代码

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 或类似的东西检查变量的值,我该怎么做? 提前致谢

【问题讨论】:

  • 还有一个问题,如果我想在这些环境中使用 printf 或类似的东西检查变量的值,我该怎么做?您将其值发送到串行端口。 https://www.arduino.cc/reference/en/language/functions/communication/serial/print/ 并查看串口监视器中的值。
  • @drescherjm aahhh 好的,谢谢,我会检查一下
  • @drescherjm 你能帮我解决我尝试在串行监视器上打印距离但显示为 0 的问题吗

标签: c++ c arduino arduino-ultra-sonic tinkercad


【解决方案1】:

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

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

distance2 = calculatedistance(pingPin2, echoPin2);
if (distance2 <= [CERTAIN_AMOUNT])
{
    digitalWrite(rojo, LOW);
    digitalWrite(verde, HIGH);
    delay(500);
}

【讨论】:

  • 问题中的代码和你的答案有什么区别?
猜你喜欢
  • 2021-03-06
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
  • 2014-05-29
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
  • 2012-09-16
相关资源
最近更新 更多