Raspberry pi 3 b+ pinout with gpio functions, schematic and specs in detail

Содержание

Как устроено GPIO на RPi3?

Теперь можно перейти к вопросу, который касается того, какая распиновка GPIO имеется на Raspberry Pi 3. В первую очередь необходимо сказать, что общее количество пинов на соответствующей панели равняется 40. Каждый из них имеет свой номер.

Все они подразделяются на 3 группы. К первой относятся питающие (на англоязычных схемах маркируются как Power) – они подают электричество в 3,3 и 5 Вольт. При этом у разных контактов данного назначения различное напряжение. Это обязательно следует учитывать при подключении модулей.

Ко второй – заземляющие (могут именоваться RND или Ground). Они нужны, чтобы отводить электричество, тем самым обеспечивая безопасное использование.

К третьей – порты (имеют обозначение BCM). Именно они служат теми контактами, которые могут принимать и отправлять сигналы. Пользователь может подключать модули к любым из них. Самое главное – чтобы было удобно обеспечивать питание подсоединённых компонентов.

Разобравшись с тем, какие типы контактов присутствуют в GPIO, можно перейти непосредственно к тому, какие из них конкретно за что отвечают. Самый простой способ освоить распиновку – это изучить схему. Но если такой возможности нет, можно обойтись и описанием.

Предположим, что плата расположена горизонтально таким образом, что GPIO на ней находится в левом верхнем углу. В таком случае номера портов будут располагаться так:

  • левый нижний – 1;
  • левый верхний – 2;
  • нижний во втором ряду – 3;
  • верхний во втором ряду – 4 и т.д.

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

Питающие на 3,3 Вольта – 1 и 17, а на 5 Вольт – 2 и 4 (они находятся рядом). Заземляющие внизу – 9, 25 и 39, заземляющие вверху – 6, 14, 20, 30 и 34. Все остальные контакты – это порты (BCM).

Особенности нумерации GPIO

Чтобы начать использование GPIO в Raspberry Pi 3, необходимо знать какие существуют особенности нумерации контактов у данного интерфейса

Важно понимать, что в процессоре «Малины» не записаны номера пинов, которые не работают на вход/выход, то есть не являются портами

Поэтому при управлении GPIO на Raspberry Pi 3 необходимо знать нумерацию BCM. Она в значительной степени отличается от той, которая рассмотрена в разделе выше. Так, 3 контакт (он является портом) имеет номер BCM2. Именно такой следует указывать при написании кода.

Понятно, что из-за этого может возникнуть путаница. Ввиду этого на Raspberry Pi 3 рекомендуется использовать Wiring Pi. Это специальная библиотека, которая имеет собственную нумерацию. Так, например, 3 порт (который является BCM 2) определяется как WiringPi 8. Возможно, это покажется еще более нелогичным. Но после ознакомления с соответствующей схемой все встанет на свои места.

Что нужно знать о GPIO RPI3?

Модули возможно подключать к абсолютно любым портам GPIO «Малины», и они будут нормально работать

Но важно знать, что в системе есть пара контактов, которые зарезервированы системой для особых целей. Ими являются BCM 0 и BCM 1 (их номера на обычной схеме – 27 и 28)

Они предназначаются специально для установки плат расширения. Поэтому при возможности их не нужно использовать для подключения других модулей.

Еще один важный момент – осторожное использование питания через GPIO Raspberry Pi 3. Ток на внешние устройства через «Малину» может подаваться с силой до 50 мА

Это достаточно много для столь небольшого девайса. Поэтому подавать ток под такой силой нужно только по крайней необходимости. В противном случае можно не только испортить модуль, но и процессор самой RPi.

What is GPIO?

GPIO stands for General Purpose Input Output.

The Raspberry Pi has two rows of GPIO pins, which are connections between the
Raspberry Pi
, and the real world.

Output pins are like switches that the Raspberry Pi can turn on or off (like
turning on/off a LED light). But it can also send a signal to another device.

Input pins are like switches that you can turn on or off from the outside
world (like a on/off light switch). But it can also be a data from a sensor, or
a signal from another device.

That means that you can interact with the real world, and control devices and
electronics using the Raspberry PI and its GPIO pins!

Breaking changes

Version > 0.24.0

Version ≥ 0.18.0

In the beginning, RaspberryIO was built around WiringPi library and all our classes, properties, enums, etc. was based on those ones used in WiringPi too.

Now, we are working on a more general version of RaspberryIO (Abstractions) that, could use any core library (WiringPi, PiGpio or even new ones). So, it was necessary to change certain properties and enums for more general ones.

Pinout numbering system

A breaking change in this new general version is the pinout numbering system. As we already explained above, RaspberryIO was using the WiringPi pinout numbering system, but now it uses the .

Note: The pin numbers are totally different in both systems, so we recommend you to double check carefully the physical pins where you connect any device.

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

BUTTON_GPIO = 16
LED_GPIO = 20

def signal_handler(sig, frame):
    GPIO.cleanup()
    sys.exit(0)

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

if __name__ == '__main__':
    GPIO.setmode(GPIO.BCM)
    
    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)
    signal.pause()

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

BUTTON_GPIO = 16
LED_GPIO = 20

last_LED_state = 0

def signal_handler(sig, frame):
    GPIO.cleanup()
    sys.exit(0)

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.setmode(GPIO.BCM)
    
    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.FALLING, 
            callback=button_pressed_callback, bouncetime=200)
    
    signal.signal(signal.SIGINT, signal_handler)
    signal.pause()

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

BUTTON_GPIO = 16
LED_GPIO = 20

should_blink = False

def signal_handler(sig, frame):
    GPIO.cleanup()
    sys.exit(0)

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

if __name__ == '__main__':
    GPIO.setmode(GPIO.BCM)
    
    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) 
        time.sleep(0.5)
        if should_blink:
            GPIO.output(LED_GPIO, GPIO.LOW)  
        time.sleep(0.5)

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.

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!

License

(The MIT License)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Zynq

  • 54 GPIO signals for device pins
    • Routed through the MIO multiplexer.
    • Outputs are 3-state capable.
  • 192 GPIO signals between the PS and PL via the EMIO interface
    • 64 Inputs
    • 128 Outputs(64 true outputs and 64 output enables).
  • The function of each GPIO can be dynamically programmed on an individual or group basis.
  • Enable, bit or bank data write, output enable and direction controls.
  • Programmable interrupts on individual GPIO basis
    • Status read of raw and masked interrupt.
    • Selectable sensitivity: Level-sensitive (High or Low) or edge-sensitive (positive,negative, or both).

Missing Features, Known Issues and Limitations

Gpio driver have a dependency on pin-controller driver. Because of this dependency the GPIO driver probe was deferred from the 2017.1 release.If any drivers have a dependency on GPIO driver that driver should have defer the probe.

Kernel Configuration

To enable GPIO in the kernel, the following configuration options need to be enabled:

CONFIG_GPIO_SYSFS=y
CONFIG_SYSFS=y
CONFIG_GPIO_ZYNQ=y

Devicetree

 gpio@e000a000 {
                #gpio-cells = <2>;
                #interrupt-cells = <2>;
                compatible = "xlnx,zynq-gpio-1.0";
                clocks = <&clkc 42>;
                gpio-controller;
                interrupt-controller;
                interrupt-parent = <&intc>;
                interrupts = <0 20 4>;
                interrupt-controller;
                #interrupt-cells = <2>;
                reg = <0xe000a000 0x1000>;
        };
 

Обзор плат Raspberry Pi

Raspberry Pi – это миниатюрный одноплатный компьютер, который с лёгкостью поместится на ладони взрослого человека. Несмотря на свои скромные размеры, плата имеет высокую производительность, что позволяет ей выйти на один уровень со стационарными ПК. Изначально Raspberry Pi была разработана, как учебное пособие по информатике. Но сама идея оказалась настолько удачной, что за несколько лет мини-компьютер стал популярен в очень широких кругах. С течением времени Raspberry Pi пережила несколько модификаций, каждая из которых отличалась от предшественника каким-либо параметром. Такой подход позволил регулировать стоимость изделия в зависимости от потребностей пользователя, что также положительно сказалось на популярности устройства. Вся линейка Raspberry Pi применяет процессоры с АРМ-архитектурой, которая зарекомендовала себя с лучшей стороны. На рисунке №1 показан внешний вид одной из популярных плат Raspberry Pi В+.

Рисунок №1 – обзор составных элементов Raspberry Pi 

На сегодняшний день (период 2012-2019гг.) существует 11 разновидностей Raspberry Pi. Последние версии оснащены беспроводными WiFi и Bluetooth модулями, расширяющими границы применения мини-пк в области Ethernet-технологий. Ниже приведена сравнительная таблица, в которой отражены особенности каждой модификации с указанием некоторых технических данных.

Модификация

Процессор

Тактовая частота

Количество ядер

Объём ОЗУ

Количество GPIO

Количество USB

Поддержка Ethernet

Поддержка WiFi

Поддержка Bluetooth

Год выпуска

В

ARM1176JZ-F

700 МГц

1

512 МБ

26

2

2012

А

ARM1176JZ-F

700 МГц

1

256 МБ

26

1

2013

В+

ARM1176JZ-F

700 МГц

1

512 МБ

40

4

2014

А+

ARM1176JZ-F

700 МГц

1

256 МБ

40

1

2014

ARM Cortex-A7

900 МГц

4

1 ГБ

40

4

2015

Zero

ARM1176JZ-F

1 ГГц

1

512 МБ

40

1

2015

3B

Cortex-A53 (ARM v8)

1,2 ГГц

4

1 ГБ

40

4

802.11n

4.1

2016

Zero W

ARM1176JZ-F

1 ГГц

1

512 МБ

40

1

802.11n

4.0

2017

3B+

Cortex-A53 (ARM v8)

1,4 ГГц

4

1 ГБ

40

4

802.11n

4.2

2018

3A+

Cortex-A53 (ARM v8)

1,4 ГГц

4

512 МБ

40

1

802.11n

4.2

2018

4B

Cortex-A72 (ARM v8)

1,5 ГГц

4

1, 2, 4 ГБ

40

4

802.11n

5.0

2019

Как видно из вышеприведенной таблицы, даже самая младшая модель в линейке имеет вполне серьёзные характеристики, учитывая то, что это одноплатный компьютер размером чуть больше кредитной карты.

На рисунке №2 изображена последняя на момент написания статьи модификация Raspberry Pi 4В, запущенная в продажу в июне 2019г. Она оснащена дополнительным графическим процессором VideoCore VI (OpenGL ES 3.x), а также аппаратным декодером 4Kp60 для воспроизведения HEVC видео. Два порта microHDMI с возможностью пропускать сигнал до 4К, позволяют подключить одновременно два монитора. 

Рисунок №2 – внешний вид Raspberry Pi 4В

Основной отличительной чертой Raspberry Pi от обычных компьютеров, является наличие программируемых портов ввода-вывода GPIO. С помощью них можно управлять различными устройствами и принимать телеметрию с различного рода датчиков.

Exporting from Kernel code¶

Kernel code can explicitly manage exports of GPIOs which have already been
requested using gpio_request():

/* export the GPIO to userspace */
int gpiod_export(struct gpio_desc *desc, bool direction_may_change);

/* reverse gpio_export() */
void gpiod_unexport(struct gpio_desc *desc);

/* create a sysfs link to an exported GPIO node */
int gpiod_export_link(struct device *dev, const char *name,
              struct gpio_desc *desc);

After a kernel driver requests a GPIO, it may only be made available in
the sysfs interface by . The driver can control whether the
signal direction may change. This helps drivers prevent userspace code
from accidentally clobbering important system state.

This explicit exporting can help with debugging (by making some kinds
of experiments easier), or can provide an always-there interface that’s
suitable for documenting as part of a board support package.

After the GPIO has been exported, allows creating
symlinks from elsewhere in sysfs to the GPIO sysfs node. Drivers can
use this to provide the interface under their own device in sysfs with
a descriptive name.

gpio.pulse¶

This covers a set of APIs that allow generation of pulse trains with accurate timing on
multiple pins. It is similar to the API, but can handle multiple pins and has better
timing control.

The basic idea is to build a object and then control it with methods on that object. Only one
object can be active at a time. The object is built from an array of tables where each inner table represents
an action to take and the time to delay before moving to the next action.

One of the uses for this is to generate bipolar impulse for driving clock movements where you want (say) a pulse on Pin 1 on the even
second, and a pulse on Pin 2 on the odd second. and can be used to keep the pulse synchronized to the
RTC clock (that is itself synchronized with NTP).

Attention

This sub module is disabled by default. Uncomment in before building the firmware to enable it.

To make use of this feature, decide on the sort of pulse train that you need to generate — hopefully it repeats a number of times.
Decide on the number of GPIO pins that you will be using. Then draw up a chart of what you want to happen, and in what order. Then
you can construct the table struct that you pass into . For example, for the two out of phase square waves, you might do:

Step Pin 1 Pin 2 Duration (μS) Next Step
1 High Low 100,000 2
2 Low High 100,000 1

This would (when built and started) just runs step 1 (by setting the output pins as specified), and then after 100,000μS, it changes to step 2i. This
alters the output pins
and then waits for 100,000μS before going back to step 1. This has the effect of outputting to Pin 1 and Pin 2 a 5Hz square wave with the pins being out of phase. The frequency will be
slightly lower than 5Hz as this is software generated and interrupt masking can delay the move to the next step. To get much closer to 5Hz,
you want to allow the duration of each step to vary slightly. This will then adjust the length of each step so that, overall, the output is
at 5Hz.

Step Pin 1 Pin 2 Duration (μS) Range Next Step
1 High Low 100,000 90,000 — 110,000 2
2 Low High 100,000 90,000 — 110,000 1

When turning this into the table structure as described below, you don’t need to specify anything
special when the number of the next step is one more than the current step. When specifying an out of order
step, you must specify how often you want this to be performed. The number of iterations can be up to around 4,000,000,000 (actually any value that fits into
an unisgned 32 bit integer). If this isn’t enough repeats, then loops can be nested as below:

The loop/count in step 2 will cause 1,000,000,000 pulses to be output (at 1kHz). This is around 11 days. At this point, it will continue onto step 3 which triggers the
11 days of
1kHz. THis process will repeat for 1,000,000,000 times (which is roughly 30 Million years).

The looping model is that associated with each loop there is a hidden variable which starts at the value and decrements on each iteration until it gets to zero
when it then proceeds to the next step. If control reaches that loop again, then the hidden variable is reset to the value of again.

API Reference¶

The functions listed in this section are deprecated. The GPIO descriptor based
API should be used in new code.

int (unsigned gpio, unsigned long flags, const char * label)

request a single GPIO with initial configuration

Parameters

the GPIO number
GPIO configuration as specified by GPIOF_*
a literal description string of this GPIO
int (const struct gpio * array, size_t num)

request multiple GPIOs in a single call

Parameters

array of the ‘struct gpio’
how many GPIOs in the array
void (const struct gpio * array, size_t num)

release multiple GPIOs in a single call

Parameters

array of the ‘struct gpio’
how many GPIOs in the array

Specifications of Model 3B+ :

  • Quad-Core 1.4GHz Broadcom BCM2837B0 64bit CPU
  • 1GB LPDDR2 SDRAM
  • Dual-channel 2.4GHz and 5GHz IEEE 802.11.b/g/n/ac wireless LAN, Bluetooth 4.2, BLE
  • Gigabit Ethernet over USB 2.0 with throughput limited to 300 Mbit/s (3 times faster than model B)
  • Extended 40-pin GPIO header
  • Full-size HDMI
  • 4 USB 2.0 ports
  • Full-size HDMI CSI (Camera Serial Interface) camera port for connecting a camera
  • DSI (Display Serial Interface) display port for connecting a touchscreen display
  • 4-pole stereo output and composite video port
  • Micro SD port
  • 5V/2.5A DC power input
  • Power-over-Ethernet (PoE) support (requires separate PoE HAT)

Usage

Aliased to

Makes available for use.

  • : The pin number to make available. Remember, is the physical pin number on the Pi.
  • : (Optional) Should be a string, such as or . You can specify whether the pin direction should be or (or or ). You can additionally set the internal pullup / pulldown resistor by sepcifying or (or or ). If options isn’t provided, it defaults to . If a direction ( or ) is not specified (eg. only ), then the direction defaults to .
  • : (Optional) Will be called when the pin is available for use. May receive an error as the first argument if something went wrong.

Aliased to

Closes .

  • : The pin number to close. Again, is the physical pin number on the Pi.
  • : (Optional) Will be called when the pin is closed. Again, may receive an error as the first argument.

Changes the direction from to or vice-versa.

  • : As usual.
  • : Either or or or .
  • : Will be called when direction change is complete. May receive an error as usual.

Gets the direction of the pin. Acts like a getter for the method above.

  • : As usual
  • : Will be called when the direction is received. The first argument could be an error. The second argument will either be or .

Reads the current value of the pin. Most useful if the pin is in the direction.

  • : As usual.
  • : Will receive a possible error object as the first argument, and the value of the pin as the second argument. The value will be either or (numeric).

Example:

gpio.read(16,function(err,value){if(err)throw err;console.log(value);});

Writes to . Will obviously fail if the pin is not in the direction.

  • : As usual.
  • : Should be either a numeric or . Any value that isn’t or will be coerced to be boolean, and then converted to 0 (false) or 1 (true). Just stick to sending a numeric 0 or 1, will you? 😉
  • : Will be called when the value is set. Again, might receive an error.

Raspberry Pi 4 GPIO Pinout:

This section is solely dedicated to the Raspberry Pi 4 GPIO Pinout:

Raspberry Pi 4 GPIO Pinout

Raspberry Pi GPIO stands for General Purpose Input Output pins. These pins are used to connect the Raspberry pi board to external input/output peripheral devices.

This model B consists of a 40-pin GPIO header. Out of these 40 pins, 26 pins are GPIO pins.

Raspberry Pi 4 GPIO header
A standard interface for connecting a single-board computer or microprocessor to other devices is through General-Purpose Input/Output (GPIO) pins.

Since GPIO pins do not have any specific function, these pins can be customized using the software.

Power Pins on Raspberry Pi 4:

The raspberry pi 4 model B board consists of two 5V pins, two 3V3 pins, and 7 ground pins (0V).

Power Pins on Raspberry Pi 4

5V: The 5v pin outputs the 5 volts coming from the USB Type-C port.

3.3V: The 3v pin is used to provide a stable 3.3v supply to external components.

GND: The ground pin is commonly referred to as GND.

R-Pi 4 Global Input/Outputs pins:

A pin that can be set as an input or output and is controlled in run time is called a GPIO pin.

A GPIO pin set as input allows the signal transmitted by any external device (connected to this pin) to be received by the Raspberry Pi.

Input voltage between 1.8V and 3.3V is read as HIGH by the Raspberry pi. And when the input voltage is lower than 1.8V, it is read as LOW.

Note: Do not connect an external device with an output voltage above 3.3V to any of the GPIO pins, or else it will fry your Raspberry Pi board.

A GPIO pin set as output delivers HIGH/3.3V or LOW/0V.

Apart from Input/Output, the GPIO pins can also perform a variety of other functions like PWM. Some of these functions/pins are:

PWM (pulse-width modulation) pins:

PWM stands for “Pulse Width Modulation”. It means that an analog value is being modulated on a digital signal.

Software PWM is available on all pins.

Hardware PWM is available on these pins only: GPIO12, GPIO13, GPIO18, GPIO19

SPI pins on RPi 4:

SPI (Serial Peripheral Interface) is a type of serial communication protocol. It is used by the Raspberry Pi for master-slave communication to quickly communicate between one or more peripheral devices.

SPI pins on Raspberry Pi 4

The data is synchronized using a clock (SCLK at GPIO11) from the master (RPi).

The Pi sends this data to an SPI device using MOSI (Master Out Slave In) pin. And when the SPI device needs to communicate back to the Raspberry Pi, it sends the data back through the MISO (Master In Slave Out) pin.

5 pins are required for SPI communication:

  • GND: Connect the GND pin from all the slave components and the Raspberry Pi 4 board together.
  • SCLK: Clock for SPI communication.
  • MOSI: It stands for Master Out Slave In. This pin is used to send data from the master to a slave.
  • MISO: It stands for Master In Slave Out. This pin is used to receive data from a slave to the master.
  • CE: It stands for Chip Enable. We need to connect one CE pin per slave (or peripheral devices) in our circuit. By default, we have two CE pins but we can configure more CE pins from the other available GPIO pins.

SPI pins on Raspberry Pi:

SPI0: GPIO9 (MISO), GPIO10 (MOSI), GPIO11 (SCLK), GPIO8 (CE0), GPIO7 (CE1)

SPI1: GPIO19 (MISO), GPIO20 (MOSI), GPIO21 (SCLK), GPIO18 (CE0), GPIO17 (CE1), GPIO16 (CE2)

I2C Pins on RPi 4:

Raspberry Pi 4 I2C pins

I2C pins on the Raspberry Pi board are used to communicate with peripheral devices that are compatible with Inter-Integrated Circuit (a low-speed two-wire serial communication protocol).

This serial communication protocol requires master-slave roles between both, the board and the peripheral devices.

I2C protocol requires two connections: SDA (Serial Data) and SCL (Serial Clock). They work by transmitting data using the SDA connection, and the speed of data transfer is controlled via the SCLK pin.

Data: (GPIO2), Clock (GPIO3)

EEPROM Data: (GPIO0), EEPROM Clock (GPIO1)

UART pins on RPi 4:

The UART (Universal Asynchronous Receiver / Transmitter) is an asynchronous protocol that provides a way to communicate between two microcontrollers or devices.

TX pin transmits the serial data to the RX pin of another device and RX pin receives the serial data coming from TX pin of the other device.

TX : GPIO14

RX : GPIO15

Summary

That wraps up today’s guide on how to use the Raspberry Pi’s GPIO PINs with Python! I hope you’ve gotten a better understanding of the different uses of GPIO and how to use it to interface with sensors and modules for building your own electronics projects.

For more Raspberry Pi resources, please visit the following links:

  • How To: 3 Methods to Configure Raspberry Pi WiFi
  • 28 Raspberry Pi Linux Commands: A Quick Guide to Use the Command Line for Raspberry Pi
  • Build a Raspberry Pi Security Camera using Raspberry Pi Camera!
  • Build a Raspberry Pi Line Following Robot!
  • Top 35 Raspberry Pi 4 Projects That You Must Try Now

Please follow and like us:

Raspberry Pi 4 Board Layout:

The Raspberry Pi 4 board layout shows some major differences between the new RPI 4 and RPI 3B+: More memory, two micro HDMI port that supports 4K resolution, USB C power port, etc. 

Parts of Raspberry Pi 4

CPU: It consists of a Broadcom BCM2711 chip which contains a 1.5GHz 64-bit quad-core ARM Cortex-A53 processor (using an ARMv8-architecture core).

GPU: Broadcom VideoCore VI @ 500 MHz  was released in 2009. It is capable of BluRay quality video playback, H.265 (4Kp60 decode); H.264 (1080p60 decode, 1080p30 encode); OpenGL ES, 3.0 graphics.

RAM: It comes with 2GB, 4GB, and 8GB (depends on different versions) variants of LPDDR4 SDRAM.

USB port: It consists of two USB 3.0 and two USB 2.0 ports to connect it to an external keyboard, mouse, or other peripheral devices.

USB power port: It consists of a 5.1V, 3A USB type-C power port.

Ethernet Port: It comes with true Gigabit Ethernet capable of sending Ethernet frames at a rate of one gigabit per second (1 billion bits per second).

Composite Video Output: Both the audio output socket and the video composite socket reside in a single 4-pole 3.5mm socket.

SD card Slot: A micro-SD card slot is used for booting up the operating system and storage purposes. 

Raspberry Pi 4 sd card slot

Note: The SD card slot is given at the back of the Raspberry Pi 4 board

I2C, SPI and UART: Which Do You Use?

We’ll get into the specific differences between I2C, SPI and UART below, but if you’re wondering which one you need to use to connect to given device, the short answer is to check the spec sheet. For example, one tiny LED screen might require SPI and another might use I2C (almost nothing uses UART). If you read the documentation that comes with a product (provided it has some), it will usually tell you which Pi pins to use.

For Raspberry Pi 4 users note that there are now many more I2C, SPI and UART pins available to you. These extra interfaces are activated using device tree overlays and can provide four extra SPI, I2C and UART connections.  

Timing and Threading

Timing

System calls to provide various timing and sleeping functions.

Getting the number of microseconds or milliseconds since system boot:

Pausing program execution for a certain number of microseconds or milliseconds.

Threading

Allows the creation of a thread which is another function in your program that runs concurrently with your main program. An example may be to have this function wait for an interrupt while your program carries on doing other tasks. The thread can indicate an event, or action by using global variables to communicate back to the main program, or other threads.

Basic thread creation:

Passing data to a thread:

Note: Not all underlying libraries support all methods for creating threads. WiringPi, for example, does only support basic thread creation.

Итог: что понадобится для работы с GPIO

В завершении следует резюмировать все вышесказанное. Если вы хотите работать с GPIO, то вам потребуется следующее:

  • сама «Малина»;
  • установленная на ней Raspbian;
  • внешнее устройство, управление которым вас интересует;
  • умение работать с документацией.

Даже с нуля и без знания ЯП в GPIO Raspberry возможно более или менее освоиться за пару вечеров. Работать с интерфейсом «Малины» очень просто. Это связано с тем, что данный одноплатник создавался, в том числе с целью обучения людей взаимодействия с компьютерами на уровне железа. Конечно, ничего сложного без глубоких знаний сделать не получится. Но так происходит всегда в процессе обучения. Со временем, с приобретением знаний и опыта можно будет реализовывать все более и более интересные вещи.