Raspberry Pi GPIO port controls two-color LED lights

Table of contents

1. First load the library

2. Set coding standards

3. Remove the GPIO port warning

4. Perform detailed programming

5. Program source code


GPIO ( General Purpose I/O Ports ) means general-purpose input / output ports through which high and low levels can be output or the state of the pin can be read through them (either high or low).

The Raspberry Pi's GPIO operation is mainly based on the RPi.GPIO library , which comes with the Raspberry Pi system.

1. First load the library

import RPi.GPIO as GPIO

2. Set coding standards

GPIO.setmode(mode) , the commonly used parameters of mode have two values, GPIO.BOARD and GPIO.BCM. Note that it is all caps .

1 ) BOARD : left to right, top to bottom: left base, right even: 1-40 . It is to tell the program to find the GPIO head (or channel ) according to the physical location. The advantage is that it is easy to find.

2 ) BCM : The numbering focuses on the CPU registers. According to the GPIO register number of BCM2835 , according to the GPIO number, the advantage is that it is convenient for the program to run on different Raspberry Pi versions.

3 ) wpi : The numbering focuses on the implementation of logic , and the extended GPIO ports are numbered from 0 , which is convenient for programming. The development language of this library is C language, and we generally use python , so it is generally not used

The specific schematic diagram is as follows:

If we want to see the schematic diagram of the GPIO port of our board, we have the following methods:

  1- "gpio -v" to see the built-in version of our Raspberry Pi.

  2- Type " gpio readall" to see the definition of our interface number.

We will not take screenshots here, we can enter commands to see for ourselves.

3. Remove the GPIO port warning

GPIO.setwarnings(False)

This step is optional, if not added, we may encounter a warning during the debugging process, the content of the warning is roughly as follows:

RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.

出现这个警告并不影响程序的执行,主要是因为检测到12号管脚被占用了。我们也可以通过代码禁掉这个警告。

四、进行详细编程

首先是设置GPIO口的输出模式 ,再创建两个PWM实例,p_Rp_G

下面是PWM波中常用的几个函数:

创建一个 PWM 实例:

p = GPIO.PWM(channel, frequency),参数为:GPIO口、频率。

启用 PWM

p.start(dc) # dc 代表占空比(范围:0.0 <= dc >= 100.0)

更改频率:

p.ChangeFrequency(freq) # freq 为设置的新频率,单位为 Hz

更改占空比:

p.ChangeDutyCycle(dc) # 范围:0.0 <= dc >= 100.0

停止 PWM

p.stop()

注意,如果实例中的变量“p”超出范围,也会导致 PWM 停止。

五、程序源码

实现目的:颜色识别和GPIO口交互  与前面那篇博文相结合,上一篇博文链接:

opencv--可选颜色物体追踪函数_Haohao fighting!的博客-CSDN博客

This time, the coding specification is applied to the BCM coding specification. We change the pin of the GPIO port by changing the value of redLed . We connect the GPIO port 21 on the board . So the value of redLed is 21. ( In the BCM coding specification, What is the pin number on the board, we let the value of redLed be)

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

# import the necessary packages
from __future__ import print_function
from imutils.video import VideoStream
import argparse
import imutils
import time
import cv2
import RPi.GPIO as GPIO

# initialize GPIO
redLed = 21
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(redLed, GPIO.OUT)

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--picamera", type=int, default=-1,
	help="whether or not the Raspberry Pi camera should be used")
args = vars(ap.parse_args())

# initialize the video stream and allow the camera sensor to warmup
print("[INFO] waiting for camera to warmup...")
vs = VideoStream(usePiCamera=args["picamera"] > 0).start()
time.sleep(2.0)

# define the lower and upper boundaries of the object
# to be detected in the HSV color space
colorLower = (24, 100, 100) 
colorUpper = (44, 255, 255) 

# Start with LED off
print("\n Starting..... ==> Press 'q' to quit Program \n")
GPIO.output(redLed, GPIO.LOW)
ledOn = False

# loop over the frames from the video stream
while True:
	# grab the next frame from the video stream, Invert 180o, resize the
	# frame, and convert it to the HSV color space
	frame = vs.read()
	frame = imutils.resize(frame, width=500)
	frame = imutils.rotate(frame, angle=0)
	hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

	# construct a mask for the obect color, then perform
	# a series of dilations and erosions to remove any small
	# blobs left in the mask
	mask = cv2.inRange(hsv, colorLower, colorUpper)
	mask = cv2.erode(mask, None, iterations=2)
	mask = cv2.dilate(mask, None, iterations=2)

	# find contours in the mask and initialize the current
	# (x, y) center of the object
	cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
		cv2.CHAIN_APPROX_SIMPLE)
	cnts = cnts[0] if imutils.is_cv2() else cnts[1]
	center = None

	# only proceed if at least one contour was found
	if len(cnts) > 0:
		# find the largest contour in the mask, then use
		# it to compute the minimum enclosing circle and
		# centroid
		c = max(cnts, key=cv2.contourArea)
		((x, y), radius) = cv2.minEnclosingCircle(c)
		M = cv2.moments(c)
		center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))

		# only proceed if the radius meets a minimum size
		if radius > 10:
			# draw the circle and centroid on the frame,
			# then update the list of tracked points
			cv2.circle(frame, (int(x), int(y)), int(radius),
				(0, 255, 255), 2)
			cv2.circle(frame, center, 5, (0, 0, 255), -1)

			# if the led is not already on, turn the LED on
			if not ledOn:
				GPIO.output(redLed, GPIO.HIGH)
				ledOn = True

	# if the object is not detected, turn the LED off
	elif ledOn:
		GPIO.output(redLed, GPIO.LOW)
		ledOn = False

	# show the frame to our screen
	cv2.imshow("Frame", frame)
	key = cv2.waitKey(1) & 0xFF

	# if the 'q' key is pressed, stop the loop
	if key == ord("q"):
		break

# do a bit of cleanup
print("\n Exiting Program and cleanup stuff \n")
GPIO.cleanup()
cv2.destroyAllWindows()
vs.stop()

Guess you like

Origin blog.csdn.net/ChenWenHaoHaoHao/article/details/130231876