1、继电器
准备工作
硬件:四路继电器,树莓派,杜邦线。
(一路继电器突然坏了。。。血亏)
原理:IN端若有低电平接入公共端(com)与常闭(NC)连接对应哪路的红灯亮。
接线: 继电器 树莓派
VCC—————————————5v
GND—————————————GND
IN1、2、3、4(任选一个)—————GPIO 7
代码编写
注意点:relayin 后面的1、2、3、4表示的是GPIO.1\2\3\4不是板子上针脚的序号
功能:通过输入0/1开控制继电器关/开。
#include<stdio.h>
#include<wiringPi.h>
#define relayin 1
int main(){
int cmd;
if(wiringPiSetup()==-1){
printf("wiringPi setup failed\n");
return 0;
}
pinMode(relayin,OUTPUT);
digitalWrite(relayin,HIGH);
while(1){
printf("请输入0/1:1——打开 0——关闭\n");
scanf("%d",&cmd);
//getchar();
if(cmd==1){
digitalWrite(relayin,LOW);
}
else if(cmd==0){
digitalWrite(relayin,HIGH);
}
else{
printf("cmd input erorr\n");
}
}
}
运行结果:
继电器开关
2、超声波测距
测距原理
这个传感器一共有两只"眼睛",一只眼睛负责发射超声波,一只眼睛负责接收超声波,根据超声波在空中"飞行"的时间,就可以计算出其距离。
超声波传感器:
VCC:接5v
GND:接GND
Trig:发射超声波(10us的方波触发) 接 GPIO.5
Echo:在发射超声波后,输出高电平,接收到超声波后输出低电平。(通过其高电平的时间就可计算出距离)GPIO.4
函数知识补充:gettimeofday()
头文件:sys/time.h
功能:一个时间获取函数
函数原型: int gettimeofday(struct timeval *tv, struct timezone *tz);
参数:参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果(tz一般不使用赋值为NULL):
struct timeval {
time_t tv_sec; // seconds 秒
suseconds_t tv_usec; // microseconds 微秒
};
struct timezone {
int tz_minuteswest; /* minutes west of Greenwich 格林威治时间往西方的时差 */
int tz_dsttime; /* type of DST correction 时间的修正方式*/
};
#include<wiringPi.h>
#include<stdio.h>
#include<sys/time.h>
#define Trig 5
#define Echo 4
void initecho(){
pinMode(Trig,OUTPUT);
pinMode(Echo,INPUT);
}
float dism(){
struct timeval t1;
struct timeval t2;
long start;
long end;
float dis;
digitalWrite(Trig,HIGH);
delayMicroseconds(10);
digitalWrite(Trig,LOW);
while(digitalRead(Echo)==0);
gettimeofday(&t1,NULL);
printf("\n");
while(digitalRead(Echo)==1);
gettimeofday(&t2,NULL);
start=t1.tv_sec*1000000+t1.tv_usec;
end=t2.tv_sec*1000000+t2.tv_usec;
dis=(float)(end-start)/1000000*34000/2;//超声波速度343m/s*时间/2*100将单位换成cm
return dis;
}
int main(){
float dis;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
initecho();
while(1){
dis=dism();
printf("%0.2f cm",dis);
delay(1000);
}
}