Raspberry Pi-5-GPIO application

[Raspberry Pi 4B learning] 1. Environment
setup , booting and logging into Raspberry Pi 4B [Raspberry Pi 4B learning] 2. Raspberry Pi 4B introduction and some necessary software installation and configuration
[Raspberry Pi 4B learning] 3. Connecting Enter the USB camera and build the Python2.7.16+OpenCV3.2.0 development environment
[Raspberry Pi 4B learning] 4. Use USB camera and motion to realize monitoring
[Raspberry Pi 4B learning] 5. Raspberry Pi 4B's OpenCV basic operation
[Raspberry Pi 4B learning] Six, Raspberry Pi 4B OpenCV video/camera basic operation
[Raspberry Pi 4B learning] Seven, Raspberry Pi 4B GPIO basic operation

1 wiringPi and BCM and BOARD coding

1.1 Pin information

The Raspberry Pi provides a set of GPIO (General Purpose Input Output, that is, general purpose input/output) interfaces. These interfaces can be used to do some electronic-related experiments: control some hardware devices, such as the most common light-emitting diodes, motors, etc., Or read the status of some signals, such as switches, sensors, etc. It should be noted here that the GPIO in the Raspberry Pi only supports digital input and output, that is, 1 and 0 correspond to a high level of 3.3V and a low level of 0V, so digital-to-analog conversion may be required when necessary.

Execute in the Raspberry Pi:
$gpio readall gets the information about the Raspberry Pi pins
Insert picture description here
RXD is the pin for Receive Data to receive data
TXD is the pin for Transmit Data to send data

For example, pin 37 in BOARD code is coded
in wiringPi as pin 25,
and coded in BCM is pin 26.
Their functions are all GPIO.25 (General Purpose Input and Output Pin 25)

In wiringPi, you want to use GPIO. 25, you have to drive 25.
In BCM, you want to use GPIO. 25 , you have to drive 26
Insert picture description here

1.2 Use occasions

BOARD coding and BCM are generally used in python libraries.

import RPi.GPIO as GPIO  //引入RPi.GPIO库
GPIO.setmode(GPIO.BCM) //设置引脚编号为BCM编码方式;
GPIO.setmode(GPIO.BOARD) //设置GPIO引脚为BOARD编码方式。

WiringPi is generally used on platforms such as C++.

LIBS += -lwiringPi
#include "wiringPi.h"
wiringPiSetup();

1.3 I2C bus

I2C Bus Introduction
Insert picture description here
SDA----Serial Data Line----Serial Data Line 
SCL-----Serial Control Line----Serial Control Line 
controls the high and low level timing of SCL and SDA lines to Generate the signals required by the I2C bus protocol for data transfer. When the bus is in idle state, these two lines are generally pulled high by the pull-up resistor connected above, and maintain a high level.

SDA jumps from high to low during the high level of SCL, and then the host sends a byte of data. After the data is transmitted, the host sends a stop signal, and SDA jumps from low to low during the high level of SCL Change to high level.

1.4 SPI bus

SPI explains in detail
SPI, which is the abbreviation of English Serial Peripheral interface, as the name implies, is the serial peripheral interface.

(1) MISO-Master Input Slave Output, master device data input, slave device data output; (2) MOSI-Master Output Slave Input, master device data output, slave device data input;

2 RPI.GPIO

Insert picture description here
Insert picture description here

2.1 SDK

Help on package RPi.GPIO in RPi:

NAME
    RPi.GPIO - Copyright (c) 2012-2019 Ben Croston

DESCRIPTION
    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.

PACKAGE CONTENTS
CLASSES
    builtins.object
        PWM

    class PWM(builtins.object)
     |  Pulse Width Modulation class
     |
     |  Methods defined here:
     |
     |  ChangeDutyCycle(...)
     |      Change the duty cycle
     |      dutycycle - between 0.0 and 100.0
     |
     |  ChangeFrequency(...)
     |      Change the frequency
     |      frequency - frequency in Hz (freq > 1.0)
     |
     |  __init__(self, /, *args, **kwargs)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |
     |  start(...)
     |      Start software PWM
     |      dutycycle - the duty cycle (0.0 to 100.0)
     |
     |  stop(...)
     |      Stop software PWM
     |
     |  ----------------------------------------------------------------------
     |  Static methods defined here:
     |
     |  __new__(*args, **kwargs) from builtins.type
     |      Create and return a new object.  See help(type) for accurate signature.
FUNCTIONS
    add_event_callback(...)
        Add a callback for an event already defined using add_event_detect()
        channel      - either board pin number or BCM number depending on which mode is set.
        callback     - a callback function

    add_event_detect(...)
        Enable edge detection events for a particular GPIO channel.
        channel      - either board pin number or BCM number depending on which mode is set.
        edge         - RISING, FALLING or BOTH
        [callback]   - A callback function for the event (optional)
        [bouncetime] - Switch bounce timeout in ms for callback

    cleanup(...)
        Clean up by resetting all GPIO channels that have been used by this program to INPUT with no pullup/pulldown and no event detection
        [channel] - individual channel or list/tuple of channels to clean up.  Default - clean every channel that has been used.

    event_detected(...)
        Returns True if an edge has occurred on a given GPIO.  You need to enable edge detection using add_event_detect() first.
        channel - either board pin number or BCM number depending on which mode is set.

    getmode(...)
        Get numbering mode used for channel numbers.
        Returns BOARD, BCM or None

    gpio_function(...)
        Return the current GPIO function (IN, OUT, PWM, SERIAL, I2C, SPI)
        channel - either board pin number or BCM number depending on which mode is set.
    input(...)
        Input from a GPIO channel.  Returns HIGH=1=True or LOW=0=False
        channel - either board pin number or BCM number depending on which mode is set.

    output(...)
        Output to a GPIO channel or list of channels
        channel - either board pin number or BCM number depending on which mode is set.
        value   - 0/1 or False/True or LOW/HIGH

    remove_event_detect(...)
        Remove edge detection for a particular GPIO channel
        channel - either board pin number or BCM number depending on which mode is set.

    setmode(...)
        Set up numbering mode to use for channels.
        BOARD - Use Raspberry Pi board numbers
        BCM   - Use Broadcom GPIO 00..nn numbers

    setup(...)
        Set up a GPIO channel or list of channels with a direction and (optional) pull/up down control
        channel        - either board pin number or BCM number depending on which mode is set.
        direction      - IN or OUT
        [pull_up_down] - PUD_OFF (default), PUD_UP or PUD_DOWN
        [initial]      - Initial value for an output channel

    setwarnings(...)
        Enable or disable warning messages

    wait_for_edge(...)
        Wait for an edge.  Returns the channel number or None on timeout.
        channel      - either board pin number or BCM number depending on which mode is set.
        edge         - RISING, FALLING or BOTH
        [bouncetime] - time allowed between calls to allow for switchbounce
        [timeout]    - timeout in ms

DATA
    BCM = 11
    BOARD = 10
    BOTH = 33
    FALLING = 32
    HARD_PWM = 43
    HIGH = 1
    I2C = 42
    IN = 1
    LOW = 0
    OUT = 0
    PUD_DOWN = 21
    PUD_OFF = 20
    PUD_UP = 22
    RISING = 31
    RPI_INFO = {
    
    'MANUFACTURER': 'Sony', 'P1_REVISION': 3, 'PROCESSOR': 'BC...
    RPI_REVISION = 3
    SERIAL = 40
    SPI = 41
    UNKNOWN = -1
    VERSION = '0.7.0'

FILE
    /usr/lib/python3/dist-packages/RPi/GPIO/__init__.py

2.2 Two-color LED lamp experiment

Raspberry Pi study notes 1: python control two-color LED light
Raspberry Pi basic experiment 1: two-color LED light experiment

The red and green LED lights are flashing alternately, and the interval is 2 seconds.
Note: GPIO output High level is 3.3v.
Insert picture description here
Board11–R
Intermediate ground
Board12–G

# encoding=utf-8
import RPi.GPIO as GPIO
import time

pins = {
    
    'pin_R':11, 'pin_G':12}  #引脚字典
sleep_time =2

GPIO.setmode(GPIO.BOARD)       # Numbers GPIOs by physical location
for i in pins:
	GPIO.setup(pins[i], GPIO.OUT)   # Set pins' mode is output
	GPIO.output(pins[i], GPIO.LOW) # Set pins to low(0V) to off led

def loop():	
	while True:
            GPIO.output(pins['pin_R'], GPIO.HIGH)   # give high
            time.sleep(sleep_time)
            GPIO.output(pins['pin_R'], GPIO.LOW)  # give low
            
            GPIO.output(pins['pin_G'], GPIO.HIGH)  # give high
            time.sleep(sleep_time)
            GPIO.output(pins['pin_G'], GPIO.LOW)
def destroy():
	for i in pins:
		GPIO.output(pins[i], GPIO.LOW)    # Turn off all leds
	GPIO.cleanup()

if __name__ == "__main__":
	try:
		loop()
	except KeyboardInterrupt:
		destroy()

Interrupt ctrl+c.

2.3 Temperature sensor DS18b20

Refer to Raspberry Pi + temperature sensor to realize indoor temperature monitoring

Insert picture description here
(1) Allow single bus interface

$ sudo raspi-config
进入interfacing options
enable one-wire interface
重启

(2) Complete the wiring
The module uses a single-bus digital temperature sensor DS18B20, and the external power supply voltage ranges from 3.0 V to 5.5 V, without a backup power supply.
The measurement temperature range is -55°C to +125°C, and Fahrenheit is equivalent to 67°F to 257°F.
The accuracy in the range of -10 °C to +85 °C is ±0.5 °C.

GND-----Board----9
DQ-------Board----7
VCC-----Board----1

(3) Upgrade the kernel
$ sudo apt-get update
$ sudo apt-get upgrade

2.4 Temperature and humidity sensor DHT11

DHT11 temperature and humidity sensor programming ideas and code realization
DHT11 temperature and humidity sensor control program under Raspberry Pi (python)

Use Raspberry Pi to connect DHT11 to read temperature and humidity.
DHT11 is a digital sensor that consists of two different sensors in a package. The sensor contains an NTC (negative temperature coefficient) temperature sensor, a resistive humidity sensor and an 8-bit microcontroller to convert the analog signals from these sensors and generate a digital output.

NTC (Negative Temperature Coefficient) refers to the thermistor phenomenon and material whose resistance decreases exponentially as the temperature rises and has a negative temperature coefficient.

DHT11 is a temperature and humidity sensor with calibrated digital signal output. Its precision humidity is ±5%RH, temperature is ±2℃, range humidity is 20-90%RH, and temperature is 0~50℃.

(2) DHT11 and RaspberryPi wiring diagram
Connect the VCC and GND pins of the DHT11 sensor to the +5V and GND of the RaspberryPi, and then connect the data output of the sensor to GPIO4, which is the physical pin 7 of the RaspberryPi.

Insert picture description here

3 Abnormalities and solutions

(1) Raspberry Pi 4B gpio readall appears Oops-unable to determine board type... model: 17 The
GPIO interface used by Raspberry Pi is based on wiringPi.
Insert picture description hereSolution:
$wget https://project-downloads.drogon.net/wiringpi-latest.deb
#sudo dpkg -i wiringpi-latest.deb
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_20466211/article/details/114135350