''' worker模块包含两个类:Motor和port_enaMotor 前者就是普通的马达,后者多了一个启用的端口。 ''' from time import sleep import RPi.GPIO as GPIO class Motor(): ''' 步进电机 ''' def __init__(self, port_dir, port_pul, degree_per_cycle, steps): self.port_dir = port_dir self.port_pul = port_pul self.degree_per_cycle = degree_per_cycle self.steps = steps GPIO.setup(port_dir, GPIO.OUT, initial=GPIO.HIGH) GPIO.setup(port_pul, GPIO.OUT, initial=GPIO.HIGH) def turn_degree(self, degree, direction): ''' 转动角度 ''' GPIO.output(self.port_dir, direction) cycle = int(degree / self.degree_per_cycle * self.steps) for _ in range(cycle): GPIO.output(self.port_pul, GPIO.LOW) sleep(0.0001) GPIO.output(self.port_pul, GPIO.HIGH) sleep(0.0001) class ENAMotor(Motor): ''' 带有port_ena信号的步进电机 ''' def __init__(self, port_dir, port_pul, degree_per_cycle, steps, port_ena): super(ENAMotor, self).__init__( port_dir, port_pul, degree_per_cycle, steps) self.port_ena = port_ena GPIO.setup(port_ena, GPIO.OUT, initial=GPIO.HIGH) def enable(self): ''' 启用电机 ''' GPIO.output(self.port_ena, GPIO.LOW) def disable(self): ''' 停用电机 ''' GPIO.output(self.port_ena, GPIO.HIGH) class VibratorMotor: '''震动马达''' def __init__(self, port): ''' 初始化 ''' self.port = port GPIO.setup(port, GPIO.OUT, initial=GPIO.LOW) def enable(self): '''开始震动''' GPIO.output(self.port, GPIO.HIGH) def disable(self): '''停止震动''' GPIO.output(self.port, GPIO.LOW) class Servo: '''舵机''' def __init__(self, port): '''初始化''' self.port = port GPIO.setup(port, GPIO.OUT, initial=GPIO.LOW) def degree(self, degree): '''转到某个角度''' dc = (degree / 180 * 2 + 0.5) * 5 p = GPIO.PWM(self.port, 50) p.start(dc) sleep(1) p.stop() class Relay: "继电器" def __init__(self, port): self.port = port GPIO.setup(port, GPIO.OUT, initial=GPIO.LOW) def enable(self): GPIO.output(self.port, GPIO.HIGH) def disable(self): GPIO.output(self.port, GPIO.LOW)