Modify ultrasonic sensor distance calculation

Measure distance 5 times, ignore zero data, and calculate the average
distance.
This commit is contained in:
jinyuan.weng 2017-09-22 14:30:56 +08:00
parent ca60ff2889
commit c4bcf16d48

54
main.ts
View File

@ -102,15 +102,30 @@ namespace grove {
{
let duration = 0;
let RangeInCentimeters = 0;
let buf: number [] = [0, 0, 0, 0, 0];
let num = 0;
pins.digitalWritePin(pin, 0);
control.waitMicros(2);
pins.digitalWritePin(pin, 1);
control.waitMicros(5);
pins.digitalWritePin(pin, 0);
for(let i = 0; i < 5; i ++)
{
pins.digitalWritePin(pin, 0);
control.waitMicros(2);
pins.digitalWritePin(pin, 1);
control.waitMicros(5);
pins.digitalWritePin(pin, 0);
duration = pins.pulseIn(pin, PulseValue.High);
buf[i] = pins.pulseIn(pin, PulseValue.High, 100000); // Max duration 100 ms
}
for(let i = 0; i < 5; i ++)
{
if(buf[i] != 0)
{
duration = duration + buf[i];
num ++;
}
}
duration = duration / num;
RangeInCentimeters = duration * 153 / 29 / 2 / 100;
return RangeInCentimeters;
@ -125,15 +140,30 @@ namespace grove {
{
let duration = 0;
let RangeInCentimeters = 0;
let buf: number [] = [0, 0, 0, 0, 0];
let num = 0;
pins.digitalWritePin(pin, 0);
control.waitMicros(2);
pins.digitalWritePin(pin, 1);
control.waitMicros(5);
pins.digitalWritePin(pin, 0);
for(let i = 0; i < 5; i ++)
{
pins.digitalWritePin(pin, 0);
control.waitMicros(2);
pins.digitalWritePin(pin, 1);
control.waitMicros(5);
pins.digitalWritePin(pin, 0);
duration = pins.pulseIn(pin, PulseValue.High);
buf[i] = pins.pulseIn(pin, PulseValue.High, 100000); // Max duration 100 ms
}
for(let i = 0; i < 5; i ++)
{
if(buf[i] != 0)
{
duration = duration + buf[i];
num ++;
}
}
duration = duration / num;
RangeInCentimeters = duration * 153 / 74 / 2 / 100;
return RangeInCentimeters;