GIOP输入输出:
其中作为输入,这里写的比较简单,参考一下:
https://blog.csdn.net/qq_41204464/article/details/83446714
https://shumeipai.nxez.com/2016/09/28/rpi-gpio-module-inputs.html
# -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
import time
# 作为输入 接按键 接3.3v 物理引脚1
gpio_1 = 12
# 作为输出 接led 接GND 物理引脚6
gpio_2 = 13
def init():
GPIO.setmode(GPIO.BOARD) # 设置引脚的编码方式
GPIO.setwarnings(False)
GPIO.setup(gpio_1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(gpio_2, GPIO.OUT)
if __name__ == '__main__':
init()
while True:
if GPIO.input(gpio_1):
print('按钮按下灯亮')
GPIO.output(gpio_2, GPIO.HIGH)
else:
print('Input was LOW')
GPIO.output(gpio_2, GPIO.LOW)
time.sleep(1)
然而输入 我这里使用上升沿触发
GPIO.wait_for_edge(channel, GPIO.RISING)
GPIO.add_event_detect(channel, GPIO.RISING)
这些都会出现
RuntimeError: Error waiting for edge
和
RuntimeError: Failed to add edge detection
关于这些错误的资料比较少,网上对于这个的解决很少,解决方法更少,更得的关于GPIO的问题或者权限不足.
其中有一个方法是 在中端检测前加一个延时(我的不行)
后来 我修改了一下自己的代码,检测1000个脉冲
count = 1000
pulse = 0
while pulse < count:
while GPIO.input(channel) != 0:
time.sleep(0.001)
while GPIO.input(channel) == 0:
time.sleep(0.001)
water_pulse += 1
print("脉冲数:", pulse)
import RPi.GPIO as GPIO
import time
gpio_1 = 12
gpio_2 = 13
gpio_3 = 15
gpio_4 = 16
def init():
GPIO.setmode(GPIO.BOARD) # 设置引脚的编码方式
GPIO.setwarnings(False)
GPIO.setup(gpio_1, GPIO.OUT)
GPIO.setup(gpio_2, GPIO.OUT)
GPIO.setup(gpio_3, GPIO.OUT)
GPIO.setup(gpio_4, GPIO.OUT)
def forward(delay):
setStep(1, 0, 0, 0)
time.sleep(delay)
setStep(0, 1, 0, 0)
time.sleep(delay)
setStep(0, 0, 1, 0)
time.sleep(delay)
setStep(0, 0, 0, 1)
time.sleep(delay)
def backward(delay):
setStep(0, 0, 0, 1)
time.sleep(delay)
setStep(0, 0, 1, 0)
time.sleep(delay)
setStep(0, 1, 0, 0)
time.sleep(delay)
setStep(1, 0, 0, 0)
time.sleep(delay)
def setStep(w1, w2, w3, w4):
GPIO.output(gpio_1, w1)
GPIO.output(gpio_2, w2)
GPIO.output(gpio_3, w3)
GPIO.output(gpio_4, w4)
if __name__ == '__main__':
delay = 2 # delay 2ms
init()
print('向前')
for i in range(3000):
forward(int(delay) / 1000.0)
print('向后')
for i in range(5000):
backward(int(delay) / 1000.0)
GPIO.cleanup()
print('运行结束')
控制电机的另外一种写法:刚想出来的
self.__motor_io_list = [13, 15, 16, 18]
def __motor_controler(self, forward):
io_value_list = [0, 0, 0, 0]
for i in range(4):
if forward:
pos_neg = i
else:
pos_neg = 3 - i
io_value_list[pos_neg] = 1
for j in range(4):
GPIO.output(self.__motor_io_list[j], io_value_list[j])
io_value_list[pos_neg] = 0
time.sleep(0.002)
__motor_controler 调用512次转一圈