Raspberry Pi + = Ultrasonic Ranging

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_45380951/article/details/100074384

Ultrasonic Ranging module implemented with Raspberry Pi

1, write your program in a virtual machine

#include<stdio.h>
#include<wiringPi.h>
#include<sys/time.h>
#define Trig  28
#define Echo 29
void ultraInit(void){
 	   pinMode(Echo,INPUT);		//pinMode()函数。
 	   pinMode(Trig,OUTPUT);
 }
float disMeasure(void){
   struct timeval tv1;
   struct timeval tv2;
   long start,stop;
   float dis;
   digitalWrite(Trig,LOW);
   delay(100);		//亦可用delayMicroseconds()函数代替
   digitalWrite(Trig,HIGH);		//设置脉冲
   delay(300);
   digitalWrite(Trig,LOW);
    while(!(digitalRead(Echo)==1));
    gettimeofday(&tv1,NULL);		//获取当前时间
    while(!(digitalRead(Echo)==0));
 	gettimeofday(&tv2,NULL);		//获取时间
 	start=tv1.tv_sec*1000000+tv1.tv_usec;  		//微妙级的时间,更精准
 	stop=tv2.tv_sec*1000000+tv2.tv_usec;
 	dis =(float)(stop-start)/1000000*3400/2;		//求出距离
    return dis;
}
 	
int main(){
 	    float dis;
 	    if(wiringPiSetup()==-1){
 	        printf("setuo wiringPi failed!");
 	        return 1;
 	    }
 	    ultraInit();
 	    while(1){
 	        dis=disMeasure();
 	        printf("distance = %0.2f cm\n",dis);
 	        delay(1000);    
 	    }
 	    return 0;
 	}

Note:

pinMode () function

the pinMode (I, MODE);
I: the pin to be configured;
MODE: mode setting input INPUT, output OPUTPUT;

digitalWrite () function

digitalWrite (PIN, value);
PIN: setting pin;
value: output level, a high level HIGH, the LOW LOW;
prior to use OUTPUT pin digitalWrite talk mode;

2, copied to the Raspberry Pi

scp ultra.c [email protected]:~		//ultra.c:需要拷贝的文件名,172.20.10.13:树莓派的IP
Why use scp? ?

The reason: scp for network copy, copy across computers, but there are a prerequisite: the Raspberry Pi IP virtual machine to be bridged on the same network segment.

3, wiring, operation
Here Insert Picture Description
results

Guess you like

Origin blog.csdn.net/weixin_45380951/article/details/100074384