arduino 使用超声波模块 HC-SR04

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int a,b;

void setup() {
  // put your setup code here, to run once:
  pinMode(9, OUTPUT);// trig
  pinMode(10, INPUT);// echo
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  delayMicroseconds(10);

  digitalWrite(9,HIGH);
  delayMicroseconds(10);
  digitalWrite(9,LOW);

  delayMicroseconds(1);   
  a=pulseIn(10,HIGH);
  b=a*340/2;

  Serial.print(a);
  Serial.print(" ");
  Serial.println(b);
}