【求指教】树莓派3b控制八路继电器

Ky13 2021-12-07754 次点击
我用的是树莓派3b,想控制一个5v八路继电器,代码逻辑是让八个继电器依次切换为高电平,以这个图的顺序循环。
但是我接好线后,继电器的两个小灯长亮
运行脚本,只听得到另外六个继电器的打开和关闭的哒哒声,而且只能控制一轮,之后就会失效,也无法控制后续电路工作。

https://ibb.co/gvJ2LRM

https://ibb.co/PQLxQcX

以下为代码
```
import RPi.GPIO as GPIO
import time
import numpy as np

# Set the BPM (speed) here
bpm = 120

# Each line represents a beat. Each 0 or 1 is a solenoid
sequence = [
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
]

gpio_map = [2, 3, 4, 17, 27, 22, 10, 9]

# The Lenth of time each solenoid should be activated
active_duration = 0.01

############################################# The main script#############################################

# Sets pin number to BCM mode
GPIO.setmode(GPIO.BCM)

# Calculate the time period between the solenoid being deactivated and the next beat starting
beat_gap = (float(60) / float(bpm)) - float(active_duration)


# Generator to infinitely loop around the sequence
def infinite_generator(n):
i = 0
while True:
if i >= len(n):
i = 0

yield n[i]
i = i + 1

# Loop through each pin and set the mode and state to 'low'
for i in gpio_map:
GPIO.setup(i, GPIO.OUT)
GPIO.output(i, GPIO.HIGH)

# Run the infinite loop
try:
for beat in infinite_generator(sequence):
# Get active drum numbers
active = np.where(beat)[0]
# Get pin numbers for active drums
pins = [gpio_map[i] for i in active]

print('Activating Pins ', pins)
GPIO.output(pins, GPIO.LOW)
time.sleep(active_duration)
GPIO.output(pins, GPIO.HIGH)
print('Sleep ', beat_gap)
time.sleep(beat_gap)

# End
except KeyboardInterrupt:
print ('Quit')
# Reset GPIO settings
GPIO.cleanup()
```
收藏 ♥ 感谢
Spoony 小组长 2021-12-08 
看代码的话只看到一次循环
如果要自动循环多次就在 for beat in infinite_generator(sequence): 这个前面加一个 while True

登录注册 后可回复。




› 相关内容关注微信公众号