函式 說明
pulseIn(pin, value)
pulseIn(pin, value, timeout)
Parameters
pin: the number of the pin on which you want to read the pulse. (int)
value: type of pulse to read: either HIGH or LOW. (int)
timeout (optional): the number of microseconds to wait for the pulse to start;
default is one second (unsigned long)
Returns
the length of the pulse (in microseconds)
or 0 if no pulse started before the timeout (unsigned long)
測試 unsigned long 多少BYTE
unsigned long ul;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(sizeof(ul));
delay(1000);
}
//4 byte
應用
#define trigPin 7
#define echoPin 8
unsigned long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT);
//pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
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;
Serial.print("Distance: ");
Serial.println(distance);
delay(100);
}