树莓派4B 2Pin按钮按键触发 C版

近期需要树莓派做个应用,需要一个按键触发程序启动,简单记录下实现按键功能过程。

1、先安装必要的wiringPi库,该库主要用来操作树莓派的GPIO

pi@raspberrypi:~ $ wget https://project-downloads.drogon.net/wiringpi-latest.deb
pi@raspberrypi:~ $ sudo dpkg -i wiringpi-latest.deb

2、安装完成后,验证下是否已经OK(命令:gpio -v)

3、查看gpio pin脚配置情况(命令:gpio readall)

 4、硬件连接,画个简易的图,PIN14是GND,连接开关按键其中一个引脚;PIN16是GPIO4,连接开关按键的另一个引脚。

 5、编写测试代码

#include <wiringPi.h>
#include <stdio.h>

#define button 4 //板子的pin16对应GPIO4---->wiringPi的4 

int main()
{
	if(wiringPiSetup() == -1) //加载wiringPi
	{
		printf("wiringPi setup fail\r\n");
		return -1;
	}
	pullUpDnControl(button,PUD_UP); //设置pin内部上拉
	
    printf("pro running...\r\n");
	while(1)
	{
		int level = digitalRead(button); //获取pin电平,当按下时为低电平,触发打印
		if(level == 0)
			printf("button touch!\r\n");
		delay(200);
	}
}

 6、验证结果

猜你喜欢

转载自blog.csdn.net/weixin_30072103/article/details/122495719