2021年8月17日 星期二

HCSR04

 





const int trigPin = 12;

const int echoPin = 13;

long duration;

int distance;

int range=20;

int num_val=(range/10);//距離是20,分10等分num_val=2

void setup() 

{

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output

  pinMode(echoPin, INPUT); // Sets the echoPin as an Input

  Serial.begin(9600); // Starts the serial communication

  for(int i=2;i<12;i++)

  {

    pinMode(i,OUTPUT);

  }

}

void loop()

{

  digitalWrite(trigPin, LOW);// Clears the trigPin

  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);// Sets the trigPin on HIGH state for 10 micro seconds

  delayMicroseconds(10);

  digitalWrite(trigPin, LOW);// Reads the echoPin, returns the sound wave travel time in microseconds

  duration = pulseIn(echoPin, HIGH);// Calculating the distance

  distance= duration*0.034/2;// Prints the distance on the Serial Monitor

  Serial.print("Distance: ");

  Serial.println(distance);

//--------------------------------------

  for(int i=2;i<12;i++)//每次把led關掉

  {

    digitalWrite(i,LOW);

  }

  if(distance<=range)//量出20才做這件事,距離18/2=9等分亮9個燈,愈靠近燈亮愈多

  {

    for(int j=2;j<(11-(distance/num_val))+2;j++)//(20/2)=10變(11-10)+2=3,因為從2開始

    {//(11-2)+1共10等分, 2<3, 只亮pin2 ,if distance=0 2<13

       digitalWrite(j,HIGH);//為什麼從2,因為led從pin 2開始

    }

  }

}

沒有留言:

張貼留言

algorithm

 #include <iostream> #include <string.h> using namespace std; int main(int argc, char** argv)  { for(int j=2;j<=100;j++)//j...