bài 1

mail@pastecode.io avatar
unknown
plain_text
19 days ago
1.3 kB
1
Indexable
Never
//bài 1

#define trigPin 13
#define echoPin 12

int value = 0;
int NUMBER_LED = 5;
int PIN_LED_FIRST = 2;
void setup()
{
  Serial.begin(115200);
  pinMode(A0, INPUT);
  for (int i = PIN_LED_FIRST; i < PIN_LED_FIRST + NUMBER_LED; i++)
  {
    pinMode(i, OUTPUT);
  }

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop()
{

  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;
  if (distance >= 200 || distance <= 0)
  {
    Serial.println("Out of range");
  }
  else
  {
    Serial.print(distance);
    Serial.println(" cm");

    // int numberPin = int(value / 50 * (NUMBER_LED + 1));
    int numberPin = 5;
    if (distance > 25)
    {
      numberPin = 5;
    }
    else
    {
      numberPin = distance / (25 - 11 + 1) / (NUMBER_LED + 1);
    }
    Serial.println("🚀 ~ file: 1.ino:41 ~ voidloop ~ numberPin:", numberPin);
    for (int i = PIN_LED_FIRST; i < PIN_LED_FIRST + numberPin; i++)
    {
      digitalWrite(i, 1);
    }
    for (int i = numberPin; i < PIN_LED_FIRST + NUMBER_LED; i++)
    {
      digitalWrite(i, 0);
    }
  }

  delay(200);
}
Leave a Comment