Управляем контактами gpio из c# .net 5 в linux на одноплатном компьютере banana pi m64 (arm64) и cubietruck (arm32)



The cover platform allows you to use a Raspberry Pi to control your cover such as Garage doors.

It uses two pins on the Raspberry Pi.

  • The will detect if the cover is closed, and
  • the will trigger the cover to open or close.

Although you do not need Andrews Hilliday’s software controller when you run Home Assistant, he has written clear instructions on how to hook your garage door and sensors up to your Raspberry Pi, which can be found .

Looking for your configuration file?

relay_time float (Optional, default: 0.2)

The time that the relay will be on for in seconds.

invert_relay boolean (Optional, default: false)

Invert the relay pin output so that it is active-high (True).

state_pull_mode string (Optional, default: UP)

The direction the State pin is pulling. It can be UP or DOWN.

invert_state boolean (Optional, default: false)

Invert the value of the State pin so that 0 means closed.

covers list Required

List of your doors.

relay_pin integer Required

The pin of your Raspberry Pi where the relay is connected.

state_pin integer Required

The pin of your Raspberry Pi to retrieve the state.

name string (Optional)

The name to use in the frontend.

That’s all!

In Will’s original post the tutorial ended with a homework assignment where he challenges you to modify the PWM script to monitor the CPU temperature and set the speed of the fan accordingly. If you want to give it ago and see more information head over to his blog and read on.

Now you’re done and, hopefully, you’ve had a chance to play around with GPIO on Ubuntu on Raspberry Pi. If this tutorial helped you and you go on to make things using GPIO on Ubuntu on a Pi, whatever it may be, let us know. Either comment below on this tutorial or find your way over to the Raspberry Pi forum, we lurk over there too.

If you do end up building a project off the back of this tutorial and you would like to share it with the Ubuntu community as a blog post or even as a tutorial for this very site, reach out to a member of the Ubuntu Community team and we’ll get something going!

Was this tutorial useful?

Thank you for your feedback.

Альтернативные функции

В то время как многие проекты могут уживаться с выводами питания и ввода, иногда от Pi требуются разные способности. К счастью, некоторые выводы GPIO удваиваются как интерфейсы I2C, SPI и UART. Pi 4 расширил возможности многих выводов, поддерживая эти интерфейсы на большем количестве из них, чем в Raspberry Pi 3b+ и до неё. Ниже приведем краткое описание по каждому интерфейсу.


I2C, или протокол Inter-Integrated Circuit, позволяет вашему Raspberry Pi управлять несколькими датчиками и компонентами, известными как ведомые (slave, подчиненные). Связь осуществляется через SDA (вывод данных) и SCL (вывод тактовой частоты). Каждое ведомое устройство создается с уникальным адресом, чтобы обеспечить быструю связь со многими устройствами. Контакты ID_EEPROM также являются I2C, но используются для связи с дополнительными платами, а не подчиненными компонентами.


SPI, или последовательный периферийный интерфейс, также используется для управления компонентами с отношениями мастер-ведомый (ведущий-ведомый), хотя он не такой компактный. Для работы требуются часы (SCLK), контакты Master Out Slave In (MOSI) и Master In Slave Out. Выводы выполняют то, что подразумевают их названия, с помощью SCLK, регулирующего скорость передачи данных, MOSI используется для отправки указаний от Pi на подключенные устройства, а MISO делает наоборот.


Если вы раньше работали с Arduino, возможно, вы уже слышали о UART или Serial (последовательная связь). Универсальный асинхронный приемник/передатчик используется для подключения плат Arduino к компьютерам, которые их программируют, а также для связи между другими устройствами с приемными и передающими контактами. Эти контакты могут использоваться для управления вашим Pi через другой компьютер, если последовательная консоль включена в raspi-config, или для прямого управления Arduino, если вы не можете использовать кабель USB для своего проекта.

По теме: Как подключить Raspberry Pi к Ардуино?


Наряду с другими функциями все контакты поддерживают программный ШИМ, а GPIO12, GPIO13, GPIO18, GPIO19 — аппаратную широтно-импульсную модуляцию.

C (WiringPi) Example

The intention of WiringPi is to make your I/O code look as Arduino-ified as possible. However, keep in mind that we’re no longer existing in the comfy confines of Arduino — there’s no or , just .

Follow along here as we create an example C file, incorporate the WiringPi library, and compile and run that program.

Create blinker.c

Using the terminal, make a folder of your choice.

Navigate to a folder of your choice.

Create a new file named «blinker.c».

Then open that file in a text editor (Nano or MousePad/Leafpad are included with Raspbian).

Note: Previously, Leafpad was the default GUI text editor for Raspberry Pi Images. It is now replaced by Mousepad. You can find Mousepad under the Raspberry Pi Start Menu under Accessories > Text Editor. You can still install leafpad manually with the command. Once installed, you can specify the text editor to open up the file.

The last command above will open your «blinker.c» file in Mousepad/Leafpad, while leaving your terminal functioning — in-directory — in the background.


Here’s an example program that includes a little bit of everything we talked about on the last page. Copy and paste, or write it yourself to get some extra reinforcement.

Once you’ve finished, Save and return to your terminal.

Compile and Execute!

Unlike Python, which is an interpreted language, before we can run our C program, we need to build it.

To compile our program, we’ll invoke gcc. Enter this into your terminal, and wait a second for it to finish compiling:

That command will create an executable file — «blinker». The «-l wiringPi» part is important, it loads the wiringPi library. A successful compilation won’t produce any messages; if you got any errors, try to use the messages to track them down.

Type this to execute your program:

The blinker program should begin doing it’s thing. Make sure you’ve set up the circuit just as modeled on the hardware setup page. Press the button to blink the LED, release to have it turn off. The PWM-ing LED will be brightest when the button is released, and dim when the button is pressed.

Basic Steps

If your system has a suitable sysfs driver loaded, you will see the GPIO hardware exposed in the file system under /sys/class/gpio. On a Raspberry Pi it might look something like this:

$ ls /sys/class/gpio/
export*  gpiochip0@  gpiochip100@  gpiochip504@  unexport*

We’ll look at how to use this interface next. Note that the device names starting with «gpiochip» are the GPIO controllers and we won’t directly use them.

The basic steps to use a GPIO pin from the sysfs interface are the following:

  1. Export the pin.
  2. Set the pin direction (input or output).
  3. If an output pin, set the level to low or high.
  4. If an input pin, read the pin’s level (low or high).
  5. When done, unexport the pin.

To export a pin, we write the pin name/number to the pseudo file /sys/class/gpio/export. This indicates that we want to use a specific GPIO pin and makes it visible in the sysfs file system hierarchy. Later when we are done, we can unexport the pin. Needing to explicitly export a pin can help prevent errors where one might inadvertently attempt to access the wrong pin.

As an example, we can export GPIO pin 24 (which corresponds to physical pin number 18 on the GPIO connector of the Raspberry Pi) with this shell command:

$ echo 24 >/sys/class/gpio/export

We will now see a gpio24 device appear under /sys/class gpio that was not there before:

$ ls /sys/class/gpio
export*  gpio24@  gpiochip0@  gpiochip100@  gpiochip504@  unexport*

This is a symbolic link to a directory which has a number of files in it:

$ ls /sys/class/gpio/gpio24/
active_low*  device@  direction*  edge*  power/  subsystem@  uevent*  value*

Step 2 is to set the pin to be either an input or an output. This is done by writing either «in», or «out» to the direction file we saw above. For example, to set gpio24 as an input we would do:

$ echo in >/sys/class/gpio/gpio24/direction

Or to set it as an output:

$ echo out >/sys/class/gpio/gpio24/direction

The file can be read back if you want to check the current status:

$ cat /sys/class/gpio/gpio24/direction 

While this may not be true for all hardware, a GPIO pin will generally default to being an input as this is always safe to do at the hardware level.

If we are configuring an output pin, we can now set it’s level. You write the value 0 or 1 (corresponding to low or high) to the value file for the pin. Continuing our example this could be done with:

$ echo 0 >/sys/class/gpio/gpio24/value

to set it low, or 

$ echo 1 >/sys/class/gpio/gpio24/value

to set it high.

If we had configured the pin as an input and tried to do this, we would get an error because it is not valid to set the value of an input pin:

bash: echo: write error: Operation not permitted

If it had been configured as an input pin, we can read its value using the same file:

$ cat /sys/class/gpio/gpio24/value

In this case 0 or low.

You may be wondering if it is valid to read the value of an output pin, and the answer is yes. The value you read back depends on the actual hardware. On the Raspberry Pi you should see the same value that was output, but on some hardware it may reflect the actual signal level, which may be different if external hardware is driving it high or low.

The final step, if you are finished using the GPIO pin, is to unexport it. To do this, just write the pin name to the unexport file, i.e.

$ echo 24 >/sys/class/gpio/unexport

After doing this, the entry for gpio24 will no longer appear in sysfs:

$ ls /sys/class/gpio
export*  gpiochip0@  gpiochip100@  gpiochip504@  unexport*


Libgpiod (Library General Purpose Input/Output device)  provides both API calls for use in your own programs and the following six user-mode applications to manipulate GPIO lines:

  • gpiodetect – list all gpiochips present on the system, their names, labels and number of GPIO lines
  • gpioinfo – list all lines of specified gpiochips, their names, consumers, direction, active state and additional flags
  • gpioget – read values of specified GPIO lines
  • gpioset – set values of specified GPIO lines, potentially keep the lines exported and wait until timeout, user input or signal
  • gpiofind – find the gpiochip name and line offset given the line name
  • gpiomon – wait for events on GPIO lines, specify which events to watch, how many events to process before exiting or if the events should be reported to the console

To cross-compile Libgpiod for the Raspberry PI on your Ubuntu 18.04 host, first install the following prerequisites:

sudo apt-get install autoconf autoconf-archive libtool libkmod-dev pkg-config

Then download, cross-compile and install.

wget https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/snapshot/libgpiod-1.1.1.tar.gz 
tar -xzf libgpiod-1.1.1.tar.gz 
cd libgpiod-1.1.1/ 
./autogen.sh --enable-tools=yes --host=arm-linux-gnueabi --prefix=/home/<home dir>/export/rootfs ac_cv_func_malloc_0_nonnull=yes 
make install

Setting ac_cv_func_malloc_0_nonnull=yes will prevent an undefined reference to `rpl_malloc’ error at linking.

Attaching the Traffic Lights

The Low Voltage Labs traffic lights connect to the Pi using four pins. One of these needs to be ground, the other three being actual GPIO pins used to control each of the individual LEDs.

Before powering up the Pi, attach the traffic lights so that the pins connect to the GPIO pins highlighted in red:

When you’re done it’s going to look something like this… (an easy way to make sure you have it right is to locate the lights on the left hand row of pins as you look at the Pi with the USB ports to the bottom, then count 8 pins up and attach the lights there).

Don’t turn the Pi on yet, you’ll need to prepare an operating system image for it first…

Дополнительные утилиты для работы с GPIO

Для удобства можно установить дополнительное ПО, которое позволит более эффективно взаимодействовать с интерфейсом «Малины». Например, некоторые из них позволяют работать с GPIO без соответствующих привилегий.

К таким утилитам, в частности, относятся: quck2wire-gpio-admin и WiringPi GPIO utility. Первая из них является более функциональной.

Если требуется прямой доступ к портам, также можно инсталлировать еще и PRIO. Расписывать принцип его работы и вышеуказанных программ нет смысла, так как всю необходимую информацию возможно получить из официальной документации.

Следует отметить, что любые из указанных программ возможно легко найти в репозитории Raspbian.


As you can see, it is quite easy to use http.server to create a simple web server and integrate your plain Raspberry Pi code with the http.server implementation. Our customised BaseHTTPRequestHandler implementation MyServer class can be easily modified to integrate whatever GET or POST requests that you need to get information from Raspberry Pi, or control GPIO via a web site based on your Raspberry Pi project. No Flask web framework is required and no installation of LAMP is required, at least, not for simple IoT project like this one.

The complete codes two python examples available at my github.

Getting data from Raspberry Pi and control Raspberry Pi GPIO

Before we discuss http.server, let’s assumed that we have a little python script that read Raspberry Pi’s GPU temperature from the Raspberry Pi, and it also control an LED connected to the Raspberry Pi. Just like every new Raspberry Pi user has experienced when they got their Raspberry Pi the fist time.

Reading GPU temperature is used to demonstrate of getting some data from Raspberry Pi, I choose to read the GPU temperature because it is kind of unique to Raspberry Pi and is available on all versions of Raspberry Pi, whether it is early version of the Raspberry Pi or the latest Raspberry Pi zero W. Raspberry Pi’s GPU temperature can be read using a bash shell command:

/opt/vc/bin/vcgencmd measure_temp

We will use python function to execute the shell system command within the python environment and display the result. The data return from the shell command is a string in the form of , and we are only interested in the actual numeric value of temperature reading, so we will use python slicing to get extract the value.

We will ask user to input either 1 or 0 to turn On or Off the LED that is connected to Raspberry Pi GPIO 18 (Raspberry Pi header P1 pin 12).


import RPi.GPIO as GPIO
import os

# Read data from Raspberry Pi (specifically read GPU temperature)
temp = os.popen("/opt/vc/bin/vcgencmd measure_temp").read()
print("GPU temperature is {}".format(temp))

# GPIO setup

# Turn on/off LED based on user input
    while True:
        user_input = input("Turn LED On or Off with 1 or 0 (Ctrl-C to exit): ")
        if user_input is "1":
            print("LED is on")
        elif user_input is "0":
            print("LED is off")
except KeyboardInterrupt:

Raspberry Pi GPIO Projects

Now that you’ve seen how easy it is to get started with Raspberry Pi GPIO using Grove, we couldn’t possibly leave you hanging without some project recommendations, could we? With a plethora of projects available thanks to the endless possibilities that GPIO pins offer, I’ll just be providing a few of my favourites today! For a comprehensive list of Raspberry Pi Projects, click here!

1. Raspberry Pi Smart Clock

Want to build a smart clock with your Raspberry Pi that shows time on an OLED display? This project not only does that but also reads out the time to you at different intervals! All software configurations are done with Python.

Hardware & Software Needed

  • Raspberry Pi 3 Model B
  • RGB Diffused Common Cathode
  • Speaker: 0.25W, 8 ohms
  • Jumper Wires (Generic)
  • Raspberry Pi OS on Raspberry Pi
  • Python GPIO Library installed on the RPi
  • Python SSD OLED Library

Interested to find out more? Visit the full tutorial with Python Code by Ashwini Kumr Sinha on Hackster!

2. Raspberry Pi Driven Robot Arm

This really cool project was developed by our Seeed R&D team. By using the 3D Gesture Tracking Shield that interfaces with the Raspberry Pi via its GPIO header, you can control a robot arm for picking up objects!

Hardware & Software Needed

  • Raspberry Pi 3B+
  • Seeed 3D Gesture & Tracking Shield for Raspberry Pi (MGC3130)
  • Seeed uArm metal
  • Raspberry Pi OS on Raspberry Pi

Want to learn more more? Check out the full tutorial by Seeed on Hackster!

3. Smart Raspberry Pi Fan Control

Worry about the thermal issues present in the Rasberry Pi 4, yet only want the fans to turn on when the processor really needs it? This project implements a Python script to adjust fan speeds based on the RPi’s CPU temperatures! Now you can cool your Raspberry Pi and learn Python at the same time!

Hardware & Software Needed

  • Raspberry Pi 4 Computer Model B 4GB
  • Seeed Armor Aluminum Metal Case with Dual Fans for Raspberry Pi
  • General Purpose Transistor NPN
  • Resistor 330 ohm
  • Breadboard
  • Jumper wires
  • ThingSpeak API

Interested to find out more? You can check out the full tutorial by Nurgaliyev Shakhizat on Hackster!

How to Configure Raspberry Pi GPIO, I2C, and SPI Pins

Now that we know more about the Raspberry Pi’s GPIO, it’s time to get started with physical computing! Similar to other electrical components, we first have to configure the GPIO pins before using them. The configuration guide below will be run on Raspberry Pi OS.

Configuring GPIO

If you’re running the latest version of Raspberry Pi OS, you can skip these steps and get straight into programming with GPIO!

Otherwise, you’ll have to run the following commands in the serial terminal to update your RPI:

If for any reason you don’t have the GPIO package installed, you can run the following command for installation:

Configuring Raspberry Pi I2C / SPI Pins

To enable I2C or SPI for hardware communication, we’ll use the Raspi-Config tool by entering the following command:

In the menu that shows up, navigate to Advanced Options > I2C and select yes. For SPI, navigate to Advanced Options > SPI instead. Once complete, reboot your RPi and your I2C pins will be enabled. To ensure that I2C communication is working properly with your RPi, connect your modules and enter the command below:

For SPI, run the following command instead:

In each case, the command line should then return a list indicating the modules that you’re running through the I2C / SPI pins.

C (WiringPi) API

On this page we’ll discuss some of the most useful functions provided by the WiringPi library. It’s tailored to look a lot like Arduino, so if you’ve done any Arduino programming some of this may look familiar.

Setup Stuff

To begin, you’ll need to include the library. At the beginning of your program, type:

After you’ve included the library, your first steps should be to initialize it. This step also determines which pin numbering scheme you’ll be using throughout the rest of your program. Pick one of these function calls to initialize the library:

WiringPi’s simplified number system introduces a third pin-numbering scheme. We didn’t show it in the table earlier, if you want to use this scheme, check out their pins page for an overview.

Pin Mode Declaration

To set a pin as either an input or output, use the function. Mode can be either , , or .

For example, to set pin 22 as an input, 23 as an output, and 18 as a PWM, write:

Keep in mind that the above example uses the Broadcom GPIO pin-numbering scheme.

Digital Output

The function can be used to set an output pin either HIGH or LOW. Easy enough, if you’re an Arduino user.

To set pin 23 as HIGH, for example, simply call:

PWM («Analog») Output

For the lone PWM pin, you can use to set it to a value between 0 and 1024. As an example…

…will set pin 18 to a duty cycle around 70%.

Digital Input

If you’re an Arduino veteran, you probably know what comes next. To read the digital state of a pin, is your function. For example…

…will print the status of pin 22. The function returns 1 if the pin is HIGH and 0 if it’s LOW.

Pull-Up/Down Resistors

Need some pull-up or pull-down resistors on your digital input? Use the function to pull your pin.

For example, if you have a button on pin 22 and need some help pulling it up, write:

That comes in handy if your button pulls low when it’s pressed.


Slowing down those blinking LEDs is always useful — assuming you actually want to differentiate between on and off. WiringPi includes two delay functions to choose from: and .
The standard delay will halt the program flow for a specified number of milliseconds. If you want to delay for 2 seconds, for example, write:

Or you can use to get a more precise, microsecond-level delay.

A few applications with Raspberry Pi GPIO interrupts

Here are 3 more code example to show you different ways to use GPIO interrupts on your Raspberry Pi.

First, let’s add a LED to our circuit.

Connect the shorter leg to the ground, and in between add a resistor (330 Ohm here). Then connect the longer leg of the LED to GPIO 20.

RPi.GPIO interrupts application example #1

Goal: power on the LED when the button is pressed, power off the LED when the button is released (you might have to tweak the bouncetime if you press the button very fast).

#!/usr/bin/env python3          
import signal                   
import sys
import RPi.GPIO as GPIO


def signal_handler(sig, frame):

def button_callback(channel):
    if GPIO.input(BUTTON_GPIO):
        GPIO.output(LED_GPIO, GPIO.LOW)
        GPIO.output(LED_GPIO, GPIO.HIGH) 

if __name__ == '__main__':
    GPIO.setup(BUTTON_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(LED_GPIO, GPIO.OUT)   

    GPIO.add_event_detect(BUTTON_GPIO, GPIO.BOTH, 
            callback=button_callback, bouncetime=50)
    signal.signal(signal.SIGINT, signal_handler)

We use GPIO.BOTH to get both rising and falling interrupts. In the function we check the current button’s state (so, right after the interrupt has been triggered) and power on/off the LED accordingly.

Note: if you do this with the polling method it will also work, but won’t be as precise/reactive.

RPi.GPIO interrupts application example #2

Goal: change the LED’s state every time you press the button.

#!/usr/bin/env python3          
import signal                   
import sys
import RPi.GPIO as GPIO


last_LED_state = 0

def signal_handler(sig, frame):

def button_pressed_callback(channel):
    global last_LED_state
    GPIO.output(LED_GPIO, not last_LED_state)
    last_LED_state = not last_LED_state

if __name__ == '__main__':
    GPIO.setup(BUTTON_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    GPIO.add_event_detect(BUTTON_GPIO, GPIO.FALLING, 
            callback=button_pressed_callback, bouncetime=200)
    signal.signal(signal.SIGINT, signal_handler)

Here we only care about when the user presses the button, so we use GPIO.FALLING for the interrupt (remember, since there is a pull up resistor, the default button’s state is HIGH, and goes LOW when pressed).

We also need a global variable, so we can use it in the callback function and keep the state between two interrupt triggers. Inside the callback, we simply change the LED’s state to the opposite of the previous one, and then save this new state into the global variable.

The bouncetime here is 200 milliseconds. By increasing it a little bit you have more chances of not getting unwanted triggers, and since you only care about pressing – not releasing – the button, it’s OK (but “OK” really depends on what you want in your application, it’s up to you to decide).

RPi.GPIO interrupts application example #3

The LED is blinking on its own. Goal: start/stop blinking LED when button is released.

#!/usr/bin/env python3          
import signal                   
import sys
import time
import RPi.GPIO as GPIO


should_blink = False

def signal_handler(sig, frame):

def button_released_callback(channel):
    global should_blink
    should_blink = not should_blink  

if __name__ == '__main__':
    GPIO.setup(BUTTON_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(LED_GPIO, GPIO.OUT)   

    GPIO.add_event_detect(BUTTON_GPIO, GPIO.RISING, 
            callback=button_released_callback, bouncetime=200)
    signal.signal(signal.SIGINT, signal_handler)
    while True:
        if should_blink:
            GPIO.output(LED_GPIO, GPIO.HIGH) 
        if should_blink:
            GPIO.output(LED_GPIO, GPIO.LOW)  

Here we use the GPIO.RISING option since we only care about when the user releases the button. It’s similar to a computer mouse interaction. When you click on a button with your mouse, the action is only validated once you release.

As you can notice, there is no anymore. We’ll use the main function to make the LED blink. In order to know if we should blink the LED or not, we use a global variable that can be modified inside the interrupt callback.


Из википедии: GPIO или Интерфейс ввода/вывода общего назначения (англ. general-purpose input/output, GPIO) — интерфейс для связи между компонентами компьютерной системы, к примеру микропроцессором и различными периферийными устройствами. Контакты GPIO могут выступать как в роли входа, так и в роли выхода — это, как правило, конфигурируется. GPIO контакты часто группируются в порты.

Во многих отношениях Raspberry Pi 4 улучшает возможности более ранних моделей Pi. Одноплатный компьютер поддерживает не только больший объем оперативной памяти, более высокую скорость процессора и расширенные периферийные устройства, но выводы GPIO сохраняют свои стандартные функции, установленные предыдущими моделями, наряду с дополнительными функциями для существующих выводов. Давайте посмотрим, что делают стандартные 40 контактов на Raspberry Pi, а затем рассмотрим каждую из этих функций подробнее.

Как я написал ранее, GPIO — это Интерфейс ввода/вывода общего назначения.

Универсальный интерфейс ввода/вывода — это, собственно, то, что означает GPIO и прекрасно описывает работу контактов плат Raspberry Pi. Они очень похожи на штыревые порты Arduino, так как их можно настроить для чтения входов или записи выходов. Эти контакты позволяют вашему Pi взаимодействовать с различными компонентами, такими как кнопки, потенциометры и зуммеры.

По теме: Управление GPIO Raspberry Pi через Node.js

Есть две схемы именования, с которыми вы должны ознакомиться: нумерация WiringPi и Broadcom. Последняя — это то, как официально называют каждый пин, отображен зеленым цветом на изображении выше. WiringPi, библиотека интерфейса GPIO, которую вы, скорее всего, будете использовать. Имеет собственную аппаратно-независимую систему нумерации. Не забывайте проверять, с какому выводом вы на самом деле работаете при программировании Pi.

Команды для режима «/sys/class/gpio»

  • gpio export <pin> in/out

    Экспортирует указанный контакт (по схеме BCM_GPIO) как входной или выходной, а также делает его доступным для пользовательской программы, запущенной тем же пользователем.

  • gpio unexport <pin>

    Удаляет экспорт для указанного контакта.

  • gpio unexportall

    Удаляет все экспортированные контакты из «/sys/class/gpio».

  • gpio exports

    Печатает список всех GPIO-контактов, которые были экспортированы через интерфейс «/sys/class/gpio» и его режимы.

  • gpio edge <pin> rising/falling/both/none

    Это включает на указанном контакте прерывание, которое можно запустить на убывающем фронте импульса (falling), на возрастающем фронте импульса (rising) или на обоих (both). Чтобы выключить прерывание, впишите none.

Примечание: Номера контактов в системном режиме – это всегда контакты по распиновке BCM_GPIO.

Распиновка тестовых точек на RaspberryPi

Ниже приведен список контрольных точек, которые можно найти на малине Pi 2, 3, а некоторые также на B+, Zero.

Благодаря использованию мультиметра эти контрольные точки могут помочь в устранении проблем с оборудованием.

Raspberry Pi 3 B

Raspberry Pi Zero

PIN Назначение
PP7 5V after polyfuse после загрузки
PP8 3V3
PP9 1V8
PP10 Переход от 3V3 до 2V при отключении
PP11  DAC_2V5 (для ЦАП с комбинированным видеосигналом)
PP12  AUD_2V5 (для аудио-драйверов PWM)
PP13  Переход от 3V3 до 2V по активности ACT
PP19  SD_DAT13
PP20  H5V
PP21  Сигнал RUN (сброс)
PP22  Переход от 3V3 до 2V по активности зеленого (link) Ethernet-разъема LED
PP23  Переход от 3V3 до 2V на активность желтого (speed) Ethernet-разъема LED
PP27  VBUS (USB 5V power)
PP28  ETH_CLK (25.000 MHz)
PP35  GPIO6 of LAN9514
PP36  GPIO7 of LAN9514
PP39  SCL0
PP40  SDA0

How to program Raspberry Pi GPIO Pins with Python?

What’s unique of running Python on Raspberry Pi instead of the typical PC is that you can run codes specifically to control hardware components through its GPIO pins! In today’s tutorial, we’ll learn how to use GPIO to blink an LED.

You’ll need the following hardware components:

  • Raspberry Pi 4 (4GB / 8GB)
  • Grove Base Hat for Raspberry Pi
  • Grove – Purple LED (3mm)

Hardware Assembly and Configuration

  1. Plug the Grove Base Hat into Raspberry Pi
  2. Select any GPIO port on the Base Hat and connect the Purple LED to it
  3. Connect the Raspberry Pi to PC through USB cable

For step 2, you can connect it to the Grove Port as well, which would result in the pairing to look like this:

Software Configurations with Python

Step 1: Ensure that your development environment is up to date. This should have been done in our earlier steps.

Step 2: Next, download the source file by cloning the grove.py library with the following commands.

Step 3: Execute the following command. Take note to replace port_number with the GPIO port number that your LED is connected to.

If your port number is 12, your command should look like this:

That’s it! You should now be able to see the LED blink!

Alternative – Using Node-RED

: When I wrote this almost a year ago, I never expect this article became one of the most popular posts. The reason that I wrote this post was to demonstrate that you probably don’t need to install a web framework and a full feature web server for simple project like control an LED. But this may probably not scalable for complex GPIO project, for that, you probably need a proper web framework, or alternatively, for those came from hardware background or new to programming, you should look into how to control Raspberry Pi GPIO using node-RED which achieves the same result with almost no programming required.

Что следует учитывать при работе с GPIO

Можно подключать любые устройства в Raspberry 2, 3 т.д. пины. Однако на GPIO есть специальные порты, которые применять не по назначению возможно, но не рекомендуется. К ним относятся BCM 0 и BCM 1, которые в схеме имеют номера 27 и 28 соответственно. Эти порты предназначены специально для поверхностного монтажа – HAT-устройств, которые, по сути, являются платами расширения.

Также тем, кто планирует работать с GPIO «Малины» рекомендуется следить за силой тока. Максимально через все пины может подаваться электричество в 50мА. При неправильном использовании такая сила может повредить не только внешнее устройство, но и вывести из строя процессор Raspberry.

What is GPIO and How does it work?

GPIO, short for General Purpose Input Output is a standard interface found on microcontrollers and SBCs that enables digital input and output. It allows these devices to control external components like motors & infrared transmitters (output), as well as to receive data from sensor modules and switches (input). In essence, GPIO allows our Raspberry Pi to interface with a variety of external components, which makes it suitable for a wide variety of projects ranging from a weather station to a self-driving robot.

Raspberry Pi 4 40 Pin GPIO Header

For GPIO pins to work, software configurations will be required. Fret not, for beginner-friendly Python libraries such as GPIOzero are available to make physical computing more accessible for all users. For more experienced programmers who prefer C or C++, GPIO access libraries such as wiringPI are also available!