【英文】树莓派操作GPIO引脚

Introduction

Operating GPIO pins with Raspberry Pi

Installing gpio command

1
sudo apt-get install wiringpi

Troubleshooting

  • Error “Oops - unable to determine board type… model: 17” occurred while using gpio readall to view pin codes.

Cause

  • The original author of the project has not updated it for a long time, resulting in incompatibility with the new version of Raspberry Pi.

Solution

  • Install the updated version by another author.
1
2
3
cd /tmp
wget https://project-downloads.drogon.net/wiringpi-latest.deb
sudo dpkg -i wiringpi-lastest.deb

Controlling pins with gpio command

Setting the pin output mode

Set as BCM coding

1
gpio -g mod 4 out

Set as wiringpi coding

1
gpio mod 4 out

Reading the pin status

  • 0 for low level, 1 for high level
1
gpio -g read 4

Setting the pin status

1: Set as high level
0: Set as low level

1
gpio -g write 4 1

Controlling pins with Linux kernel

Accessing the GPIO directory

1
cd /sys/class/gpio

Exposing the interface to the desired pin

  • Expose the GPIO pin interface that needs to be accessed from kernel space to user space.

<bcm_num>: BCM code of the pin to be operated

1
echo <bcm_num> > export

Accessing the pin directory

<bcm_num>: The suffix of the directory name is the BCM number of the pin.

1
cd gpio<bcm_num>

Setting the pin direction as output

1
echo out > direction

Setting the pin status

1: Set as high level
0: Set as low level

1
echo 1 > value

Unexporting GPIO pins

1
2
cd ..
echo <bcm_num> > unexport

Controlling GPIO pins with Python3

  • Using the RPI.GPIO module

<bcm_num>: BCM code of the pin to be operated

1
2
3
4
5
6
7
8
9
10
11
12
13
import RPI.GPIO as GPIO
from time import sleep

# Set BCM mode
GPIO.setmode(GPIO.BCM)
# Set as output mode
GPIO.setup(<bcm_num>, GPIO.OUT)
# Set as high level
GPIO.output(<bcm_num>, GPIO.HIGH)
# Set as low level
GPIO.output(<bcm_num>, GPIO.LOW)
# Unexport GPIO pins
GPIO.cleanup()

Controlling GPIO pins with C

  • Using the wiringPi.h header file

<wiringpi_num>: wiringPi code of the pin to be operated

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <wiringPi.h>
#define Pin <wiringpi_num>

int main()
{
if (wiringPiSetup() < 0)
{
return 1;
}

// Set as output mode
pinMode(Pin, OUTPUT);
// Set as high level
digitalWrite(Pin, 1);
// Set as low level
digitalWrite(Pin, 0);

return 0;
}

Compilation

1
gcc filename.c -lwiringPi

Completion

References

Bilibili - Raspberry Pi Tutorials