树莓派控制GPIO输入输出,控制步进电机
程序员文章站
2024-02-23 22:42:58
...
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)
控制步进电机:
步进电机:
代码:
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('运行结束')