我买的一个小板子,上面有两个按钮,如下图所示
注意,按钮的PIN脚的序号是13,15,这个会在程序中用到。
不要和旁边标注的GPIO脚的序号GPIO22, GPIO27搞混淆了。
1. Python 开发GPIO
需要安装python-dev 和 RPi.GPIO
pi@raspberrypi ~ $ sudo apt install python-dev
pi@raspberrypi ~/workspace $ tar xvzf RPi.GPIO-0.5.5.tar.gz
pi@raspberrypi ~/workspace $ cd RPi.GPIO-0.5.5/
pi@raspberrypi ~/workspace/RPi.GPIO-0.5.5 $ sudo python setup.py install
pi@raspberrypi ~/workspace $ vim button.py
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
# need to set up every channel which are using as an input or an output
GPIO.setup(13, GPIO.IN)
GPIO.setup(15, GPIO.IN)
count = 0
while True:
key_button1 = GPIO.input(13)
key_button2 = GPIO.input(15)
if (key_button1 == 0):
count = count + 1
print("The key_button1 is 0")
else:
print("The key_button1 is 1")
time.sleep(1)
if (key_button2 == 0):
count = count + 1
print("The key_button2 is 0")
else:
print("The key_button2 is 1")
time.sleep(1)
最后,测试结果如下
The key_button1 is 0
The key_button2 is 0
The key_button1 is 0
The key_button2 is 1
The key_button1 is 0
The key_button2 is 1
...
2. C 开发GPIO
需要安装 BCM2835 C Library
pi@raspberrypi ~/workspace $ wget http://www.airspayce.com/mikem/bcm2835/bcm2835-1.35.tar.gz
pi@raspberrypi ~/workspace $ tar xzf bcm2835-1.35.tar.gz
pi@raspberrypi ~/workspace $ cd bcm2835-1.35/
pi@raspberrypi ~/workspace/bcm2835-1.35 $ ./configure
pi@raspberrypi ~/workspace/bcm2835-1.35 $ make
pi@raspberrypi ~/workspace/bcm2835-1.35 $ sudo make check
pi@raspberrypi ~/workspace/bcm2835-1.35 $ sudo make install
pi@raspberrypi ~/workspace $ vim button.c
#include <stdio.h>
#include <bcm2835.h>
#define BUTTON1 RPI_V2_GPIO_P1_13 // = 27, ///< Version 2, Pin P1-13
#define BUTTON2 RPI_V2_GPIO_P1_15 // = 22, ///< Version 2, Pin P1-15
int main(int argc, char **argv)
{
uint8_t data = 0;
uint8_t btn_counter1 = 0;
uint8_t btn_counter2 = 0;
if (!bcm2835_init())
return 1;
// Set the pin to be an input
bcm2835_gpio_fsel(BUTTON1, BCM2835_GPIO_FSEL_INPT);
bcm2835_gpio_fsel(BUTTON2, BCM2835_GPIO_FSEL_INPT);
// Reading
while (1)
{
data = bcm2835_gpio_lev(BUTTON1);
printf("Reading button1: %d\n", data);
if (data)
btn_counter1++;
bcm2835_delay(1000);
data = bcm2835_gpio_lev(BUTTON2);
printf("Reading button2: %d\n", data);
if (data)
btn_counter2++;
bcm2835_delay(1000);
printf("--- The btn_counter1 is %d, btn_counter2 is %d ---\n",
btn_counter1, btn_counter2);
}
bcm2835_close();
return 0;
}
编译,执行,运行结果如下
$ gcc -o button button.c -lbcm2835
$ sudo ./button
Reading button1: 0
Reading button2: 0
--- The btn_counter1 is 0, btn_counter2 is 0 ---
Reading button1: 1
Reading button2: 0
--- The btn_counter1 is 1, btn_counter2 is 0 ---
Reading button1: 0
Reading button2: 0
--- The btn_counter1 is 1, btn_counter2 is 0 ---
Reading button1: 0
Reading button2: 0
--- The btn_counter1 is 1, btn_counter2 is 0 ---
Reading button1: 0
Reading button2: 1
--- The btn_counter1 is 1, btn_counter2 is 1 ---
Reading button1: 0
Reading button2: 1
--- The btn_counter1 is 1, btn_counter2 is 2 ---