(一)认识树莓派wiringPi库
1 wiringPi库:包含的API接口有GPIO控制口,中断,多线程等。
2 查看GPIO引脚编号表:
命令:gpio readall
(二)使用wiringPi库对树莓派引脚编程
1 针对gpio7引脚的高低电平编程
命令:vi gpio1.c
#include <wiringPi.h>
#include <stdio.h>
int main()
{
int cmd;
if(wiringPiSetup()==-1) //wiringPiSetup():对硬件接口进行初始化;
{
printf("int wiringPiSetup() failed\n");
return -1;
}
pinMode(7,OUTPUT);
digitalWrite(7,HIGH);
while(1)
{
printf("please enable open_1 or close_0\n");
scanf("%d",&cmd);
getchar(); //吸收键盘中的Enter键
if(cmd==1)
{
digitalWrite(7,LOW); //键盘输入1为低电平
}else if(cmd==0)
{
digitalWrite(7,HIGH); //键盘输入0为高电平
}else
{
printf("input command is error\n");
}
cmd=100; //对cmd变量重新赋值,可有可无
}
}
编译命令 :gcc gpio1.c -o gpio1 -lwiringPi
运行命令:./gpio1
2 针对gpio26/27/28/29引脚的高低电平编程
命令:vi gpio2.c
#include <wiringPi.h>
#include <stdio.h>
#include <string.h>
int main()
{
char cmd[12]={'\0'};
if(wiringPiSetup()==-1)
{
printf("wiringPiSetup() is failed\n");
return -1;
}
pinMode(26,OUTPUT);
pinMode(27,OUTPUT);
pinMode(28,OUTPUT);
pinMode(29,OUTPUT);
digitalWrite(26,HIGH);
digitalWrite(27,HIGH);
digitalWrite(28,HIGH);
digitalWrite(29,HIGH);
while(1)
{
memset(cmd,'\0',sizeof(cmd));
printf("please input 1/2/3/4on_open or off_close\n");
//scnaf("%s",cmd);
//getchar(); //注释掉的部分错误原因不明,会提示警告
gets(cmd);
if(strcmp(cmd,"1 on")==0)
{
digitalWrite(26,LOW);
}else if(strcmp(cmd,"1 off")==0)
{
digitalWrite(26,HIGH);
}else if(strcmp(cmd,"2 on")==0)
{
digitalWrite(27,LOW);
}else if(strcmp(cmd,"2 off")==0)
{
digitalWrite(27,HIGH);
}else if(strcmp(cmd,"3 on")==0)
{
digitalWrite(28,LOW);
}else if(strcmp(cmd,"3 off")==0)
{
digitalWrite(28,HIGH);
}else if(strcmp(cmd,"4 on")==0)
{
digitalWrite(29,LOW);
}else if(strcmp(cmd,"4 off")==0)
{
digitalWrite(29,HIGH);
}else
{
printf("please input true command\n");
}
}
}
编译命令 gcc gpio2.c -o gpio2 -lwiringPi
运行命令 ./gpio2