def __init__(self, v1pin = VALVE_1_PIN, v2pin = VALVE_2_PIN): self.valve1 = DigitalOutputDevice(v1pin) self.valve2 = DigitalOutputDevice(v2pin) self.valves = [self.valve1, self.valve2] self.valve1thread = None self.valve2thread = None self.threads = [self.valve1thread, self.valve2thread]
def __init__(self, ain1=None, ain2=None, bin1=None, bin2=None, pwma=None, pwmb=None): print("init") self.ain1 = DigitalOutputDevice(ain1, initial_value=False) self.ain2 = DigitalOutputDevice(ain2, initial_value=False) self.bin1 = DigitalOutputDevice(bin1, initial_value=False) self.bin2 = DigitalOutputDevice(bin2, initial_value=False) self.pwma = PWMOutputDevice(pwma, initial_value=.5) self.pwmb = PWMOutputDevice(pwmb, initial_value=.5)
class Roseluck: #gpizero uses broadcom pin numbers VALVE_1_PIN = 23 VALVE_2_PIN = 24 def __init__(self, v1pin = VALVE_1_PIN, v2pin = VALVE_2_PIN): self.valve1 = DigitalOutputDevice(v1pin) self.valve2 = DigitalOutputDevice(v2pin) self.valves = [self.valve1, self.valve2] self.valve1thread = None self.valve2thread = None self.threads = [self.valve1thread, self.valve2thread] #function to turn off valves, either zone 1 or zone 2 by int. #pass 0 or nothing to turn both valves off. def turnoff(self, valve = 0): if ((valve < 0) or (valve > 2)): print ("Invalid valves in turnoff function") return 1 if ((valve == 1) or (valve == 0)): self.valve1.off() if ((valve == 2) or (valve == 0)): self.valve2.off() return 0 #Turns on the passed valve as long as it's valid def turnon(self, valve): if (valve < 1 or valve > 2): print("Invalid valve in turnon function") return 1 self.valves[valve-1].on() #function to trigger a valve for a duration def runstation(self, valve, duration): if valve < 1 or valve > 2: print ("Invalid valve or duration in runstation") print ("Attempted to run station " + str(valve) + " for " + str(duration) + "seconds.") return 1 if self.threads[valve-1] is not None and self.threads[valve - 1].is_alive(): print ("Valve " + str(valve) + " is already active.") return 2 else: self.threads[valve-1] = ValveWorker(self, valve, duration) #self.threads[valve-1].daemon = True self.threads[valve-1].start() return 0 #function to test the system. Engage each zone for five minutes. def systemtest(self): print ('System test:') print ("Triggering zone 1 for 5 minutes...") self.runstation (1, 300) print ("Triggering zone 2 for 5 minutes...") self.runstation (2, 300) print ("System test complete") print ("____________________")
def __init__(self, din, sclk, dc, rst, cs, contrast=60, inverse=False): super(PCD8544, self).__init__(clock_pin=sclk, mosi_pin=din, miso_pin=9, select_pin=cs) self.DC = DigitalOutputDevice(dc) self.RST = DigitalOutputDevice(rst) self._reset() self._init(contrast, inverse) self.drawer = DisplayGraphics(self) self.clear() self.dispose()
def __init__(self): if env == "prod": log.debug("Using %s configuration" % self.CONTROLLER_BOARD ) self.SERVO_H = AngularServo(self.HEAD_HORIZONTAL_PIN, min_angle=-80, max_angle=80) self.SERVO_V = AngularServo(self.HEAD_VERTICAL_PIN, min_angle=-80, max_angle=80) ##Digital devices self.forward_left_device = None self.forward_right_device = None self.backward_left_device = None self.backward_right_device = None self.wheel_right_step = None self.wheel_left_step = None self.wheel_right_heading = None self.wheel_left_heading = None self.wheel_right_enabled = None self.wheel_left_enabled = None self.pwm_left = None self.pwm_right = None if self.CONTROLLER_BOARD == "v1": self.forward_left_device = DigitalOutputDevice(self.FORWARD_LEFT_PIN, True, False) self.forward_right_device = DigitalOutputDevice(self.FORWARD_RIGHT_PIN, True, False) self.backward_left_device = DigitalOutputDevice(self.BACKWARD_LEFT_PIN, True, False) self.backward_right_device = DigitalOutputDevice(self.BACKWARD_RIGHT_PIN, True, False) self.pwm_left = PWMOutputDevice(self.PWM_LEFT_PIN, True, False, self.FRECUENCY) self.pwm_right = PWMOutputDevice(self.PWM_RIGHT_PIN, True, False, self.FRECUENCY) if self.CONTROLLER_BOARD == "v2": self.wheel_right_step = DigitalOutputDevice(self.WHEEL_RIGHT_STEP, True, False) self.wheel_left_step = DigitalOutputDevice(self.WHEEL_LEFT_STEP, True, False) self.wheel_right_heading = DigitalOutputDevice(self.WHEEL_RIGHT_HEADING, True, False) self.wheel_left_heading = DigitalOutputDevice(self.WHEEL_LEFT_HEADING, True, False) self.wheel_right_enabled = DigitalOutputDevice(self.WHEEL_RIGHT_ENABLED, True, False) self.wheel_left_enabled = DigitalOutputDevice(self.WHEEL_LEFT_ENABLED, True, False) self.current_horizontal_head_pos = 0 self.current_vertical_head_pos = 0 self.center_head() self._counting_steps = 0 self._current_steps = 0 self._stepper_current_step = 0
def __init__(self, name, output_pin, input_pin=None): self.name = name self.state = None self.output_pin = output_pin if input_pin is not None: self.input_pin = input_pin self.output_device = DigitalOutputDevice(output_pin) if input_pin: self.input_device = DigitalInputDevice(input_pin)
class Channel: def __init__(self, name, output_pin, input_pin=None): self.name = name self.state = None self.output_pin = output_pin if input_pin is not None: self.input_pin = input_pin self.output_device = DigitalOutputDevice(output_pin) if input_pin: self.input_device = DigitalInputDevice(input_pin) def set(self, state): """Sets the channel output""" self.state = state if state == 'On': self.output_device.on() elif state == 'Off': self.output_device.off() else: raise NotImplementedError log.info('Channel %s set to %s', self.name, state) def valid(self): """ Checks if the channel output is valid Returns: True, if the output and input pin states match. False, if they don't match. None, if no input pin is defined. """ if self.input_pin is None: return None else: return self.output_device.value == self.input_device.value def status(self): return { 'state': self.state, 'valid': self.valid(), }
class RelayClient(): relay1 = None relay2 = None client = None currentState = 'off' def __init__(self): self.client = mqtt.Client() self.client.on_connect = self.on_connect self.client.on_message = self.on_message def start(self): self.client.connect("localhost", 1883, 60) self.client.loop_forever() # The callback for when the client receives a CONNACK response from the server. def on_connect(self, client, userdata, flags, rc): print("Connected with result code " + str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. self.client.subscribe("/Relays") # The callback for when a PUBLISH message is received from the server. def on_message(self, client, userdata, msg): print(msg.topic + " " + str(msg.payload)) payload = Payload(msg.payload) print("id:" + str(payload.id)) print("state:" + str(payload.state)) if payload.state == 'on': print("turning on") if self.currentState == 'off': self.currentState = 'on' self.relay1 = DigitalOutputDevice(pin=17) self.relay1.on() self.relay2 = DigitalOutputDevice(pin=27) self.relay2.on() if payload.state == 'off': print("turning off") self.currentState = 'off' if self.relay1 != None: self.relay1.close() else: print("self.relay1 is null") if self.relay2 != None: self.relay2.close() else: print("self.relay2 is null")
def __init__(self): self.rstPin = DigitalOutputDevice(self.PIN_NODE_RST) self.btnPin = DigitalInputDevice(self.PIN_START_BTN) self.outPin = DigitalOutputDevice(self.PIN_EXIT_EN, active_high=False) self.snakeOnPin = DigitalOutputDevice(self.PIN_SNAKE_EN, active_high=False) #self.outPin.source = self.btnPin.values return
class ShelfHalf: def __init__(self, halfid, pin): self.halfid = halfid self.pin = DigitalOutputDevice(pin) self.pinnum = pin self.off() self.state = False def on(self): print("Setting pin %d to on" % (self.pinnum)) self.pin.on() self.state = True def off(self): print("Setting pin %d to off" % (self.pinnum)) self.pin.off() self.state = False def setstate(self, state): if state is 1: self.on() else: self.off()
class HardwareControl: """ One instance class to control and setup hardware (LIDAR sensor and motor) Integrates Motor and Lidar control. """ def __init__(self): """ Setups Motor and Lidar """ self.Motor = StepMotor() self.Lidar = LidarSensor() self.Lidar.configure() self.Laser = DigitalOutputDevice(21) #BOARD40 def __del__(self): if self.Laser.value != 0: self.Laser.off() def turnMotor(self, degrees, stepInsteadofDeg=False, steptime=1): """ Steptime is in miliseconds. Turns motor and returns the new angle of the motor. The motor range is limited to 200 degrees both directions. """ if stepInsteadofDeg: stepnum = int(degrees) else: stepnum = int(degrees / self.Motor.STEP_DEGREE) steptime = steptime / 100. motangle = self.Motor.turnbyStep(stepnum) return motangle def calibrateMotor(self): """ Changes the absolute motor angle to the current position of motor """ self.Motor.angle = 0 def getDistance(self): """ returns the distances in a list """ lvalues = self.Lidar.getdata() it = 0 while len(lvalues) == 0 and it < 5: lvalues = self.Lidar.getdata() it = it + 1 return lvalues def toggleLaser(self): if self.Laser.value == 1: self.Laser.off() else: self.Laser.on()
class Fire: def __init__(self, mode="rpi"): if mode == "arduino" or mode == "Arduino": self.arduino_fire = DigitalOutputDevice(pin_fig.fire_led) self.on = self.arduino_fire_on_off self.off = self.arduino_fire_on_off else: self.led_fire = LED(pin_fig.fire_led) self.on = self.rpi_fire_on self.off = self.rpi_fire_off def arduino_fire_on_off(self): self.arduino_fire.on() sleep(0.4) self.arduino_fire.off() # self.arduino_fire.close() def rpi_fire_on(self): self.led_fire.blink(on_time=0.1, off_time=0.1) print("fire on") def rpi_fire_off(self): self.led_fire.off() print("fire off")
class ShiftRegister(object): def __init__(self, data_pin=17, latch_pin=27, clock_pin=22, num_registers=1): self.data = DigitalOutputDevice(pin=data_pin) self.latch = DigitalOutputDevice(pin=latch_pin) self.clock = DigitalOutputDevice(pin=clock_pin) self.num_registers = num_registers self.current_data = None logging.info('Data Pin: {0} Latch Pin: {1} Clock Pin: {2}'.format( self.data.pin, self.latch.pin, self.clock.pin)) def get_current(self): return self.current_data def write(self, byte_array): byte_array = byte_array[0:self.num_registers] if byte_array == self.current_data: return False self.current_data = byte_array self._unlatch() for byte in byte_array: self._shiftout(byte) self._latch() return True def _unlatch(self): self.latch.off() def _latch(self): self.latch.on() def _shiftout(self, byte): for x in range(8): self.data.value = (byte >> x) & 1 self.clock.on() self.clock.off()
def __init__(self): self._speed = 0 self._direction = 0 self._enabled = False self._enabledOutput = DigitalOutputDevice(self._enabledPin) self._speedPwm = PWM(0) # pin 12 self._directionPwm = PWM(1) # pin 13 self._speedPwm.export() self._directionPwm.export() time.sleep(1) # wait till pwms are exported self._speedPwm.period = 20_000_000 self._directionPwm.period = 20_000_000
def setup_hw_interface(cls): """ Sets up the hardware interface with the before set config [set_config(config)]. """ try: if DoorSocketHandler.door is None: DoorSocketHandler.door = DigitalOutputDevice( int(Application.config('gpio.open'))) if DoorSocketHandler.ring is None: DoorSocketHandler.ring = Button(int( Application.config('gpio.ring')), hold_time=0.25) DoorSocketHandler.ring.when_pressed = DoorSocketHandler.handle_ring except NameError: pass
def __init__(self, chain=2): self.chain = chain # number of chips in a row self.registers = [] for i in range(0, self.chain): self.registers.append([0, 0, 0, 0, 0, 0, 0, 0]) self.latch_pin = DigitalOutputDevice(16) self.clock_pin = DigitalOutputDevice(20) self.data_pin = DigitalOutputDevice(21) self.pause = 0
class Escape: def __init__(self): self.motor_escape = DigitalOutputDevice(pin=pin_fig.escape_relayswitch) def on(self): self.motor_escape.on() print("escape on") def off(self): self.motor_escape.off() self.motor_escape.close() print("escape off")
def fan_control(): fan = DigitalOutputDevice(GPIO_PIN) while True: temp = check_temp() if temp > ON_TEMP: fan.on() elif temp < OFF_TEMP: fan.off() sleep(5)
def _init_pins(self, rs, enable, rw, db7, db6, db5, db4): self.db7 = DigitalOutputDevice(db7) self.db6 = DigitalOutputDevice(db6) self.db5 = DigitalOutputDevice(db5) self.db4 = DigitalOutputDevice(db4) #self.db3 = DigitalOutputDevice() #self.db2 = DigitalOutputDevice() #self.db1 = DigitalOutputDevice() #self.db0 = DigitalOutputDevice() self.rs = DigitalOutputDevice(rs) if rw is None: self.rw = None else: self.rw = DigitalOutputDevice(rw) self.enable = DigitalOutputDevice(enable)
def __init__(self, host="", port=1997): print("TCP Server instance created") self.HOST = host self.PORT = port # Create Fake pins if running on windows if platform.system() == "Windows": self.simulate_windows() # init relays for pin in self.relay_pins: self.outRel.append(DigitalOutputDevice(pin, active_high=True, initial_value=False)) # init inputs for i in range(len(self.input_pins)): tempbtn = Button(self.input_pins[i], hold_time=self.polling_time, bounce_time=self.debounce_time) tempbtn.when_pressed = lambda x=i: self.inc_input(x) self.btnInput.append(tempbtn) print(self.btnInput)
def main(): """Run a loop.""" # Wire DC IN to 5V # Wire DC OUT to GND # Wire VCC to GPIO 23 output_pin = 23 relay = DigitalOutputDevice(output_pin) try: while True: relay.on() time.sleep(0.5) relay.off() time.sleep(0.5) except KeyboardInterrupt: pass finally: relay.close()
class Snake: PIN_SNAKE_EN = 2 PIN_EASTER_EN = 3 PIN_SNAKE_DONE = 25 def __init__(self): self.snakeOnPin = DigitalOutputDevice(self.PIN_SNAKE_EN, active_high=False) self.snakeDonePin = DigitalInputDevice(self.PIN_SNAKE_DONE, pull_up=False) self.snakeDonePin.when_activated = self.onDone self.done = False self.enabled = False return def onDone(self): self.done = True self.snakeOnPin.off() def isAlive(self): return True def getDone(self, newValue=None): if (newValue != None): self.done = newValue if self.snakeDonePin.is_active: self.done = True return self.done def getEnabled(self, newValue=None): if (newValue != None): self.enabled = newValue if self.enabled and not self.done: self.snakeOnPin.on() else: self.snakeOnPin.off() return self.enabled def update(self): self.getDone() return def getAllValues(self): values = {} values['done'] = self.done values['alive'] = self.isAlive() return values
def _write_debug_byte(self, data: int): """ Writes a byte on the debug interface. Requires DD to be output when function is called. Args: data - Byte to write """ if data > 255: raise ValueError("The data len is not one byte") with DigitalOutputDevice(pin=self.pin_dd) as dev_dd: for bit in self._get_bit(data): self.dev_dc.on() # Set clock high and put data on DD line if bit: dev_dd.on() else: dev_dd.off() self._wait() self.dev_dc.off() # Set clock low (DUP capture flank) self._wait()
def setup_output(self): """Code executed when Mycodo starts up to initialize the output""" if not self.gpio_pin or not self.host: self.logger.error("Need GPIO pin and host to set up remote GPIO") return try: from gpiozero.pins.pigpio import PiGPIOFactory from gpiozero import DigitalOutputDevice factory = PiGPIOFactory(host=self.host) self.logger.debug( "Setting up remote GPIO pin {pin} on host {host}".format( pin=self.gpio_pin, host=self.host)) self.output_device = DigitalOutputDevice( pin=self.gpio_pin, active_high=self.output_on_state, pin_factory=factory) self.logger.debug("Output set up") self.output_setup = True except Exception: self.logger.exception("Output Setup") self.output_setup = False
def _check_pin(self, pin_number: int) -> bool: try: device = DigitalOutputDevice("GPIO" + str(pin_number), active_high=False) print(f'Found GPIO{pin_number} Pin. Turning on!') device.on() confirm = [{ 'type': 'confirm', 'message': 'Is any device working right now?', 'name': 'working', 'default': False, }] answer = prompt(confirm) device.off() return answer['working'] except GPIOZeroError as exc: print(f'Couldn\'t set up gpio pin: {pin_number}') raise exc
class Relay(): "Simple wrapper for a power relay" def __init__(self, pin: int): self.device = DigitalOutputDevice(pin) @property def value(self) -> bool: return bool(self.device.value) def set(self) -> None: self.device.on() def unset(self) -> None: self.device.off() def toggle(self) -> None: self.device.toggle()
def update_pin_bindings(self): bindings = self._settings.get(["bindings"]) self._logger.error(str(bindings)) for gpio in bindings: pin = int(gpio["gpio"]) if gpio["type"][0] == "OUTPUT": self._logger.error( "Binding DigitalOutputDevice to pin {pin}".format(pin=pin)) self.pins[pin] = DigitalOutputDevice(pin, active_high=True, initial_value=True, pin_factory=MockFactory()) if gpio["type"][0] == "INPUT": self._logger.error( "Binding Button to pin {pin}".format(pin=pin)) self.pins[pin] = Button(pin, active_state=None, pull_up=True, bounce_time=0.01, pin_factory=MockFactory()) if gpio["type"][0] == "PWM": self._logger.error("Binding PWM to pin {pin}".format(pin=pin)) self.pins[pin] = PWMOutputDevice(pin, active_high=True, initial_value=0.0, frequency=100, pin_factory=MockFactory()) if gpio["type"][0] == "SERVO": self._logger.error( "Binding Servo to pin {pin}".format(pin=pin)) self.pins[pin] = Servo(pin, initial_value=0.0, min_pulse_width=1 / 1000, max_pulse_width=2 / 1000, frame_width=20 / 1000, pin_factory=MockFactory())
def __init__(self, din, sclk, dc, rst, cs, contrast=60, inverse=False): self.DC = DigitalOutputDevice(dc) self.RST = DigitalOutputDevice(rst) self.clock_pin = ctypes.c_uint8(sclk) self.data_pin = ctypes.c_uint8(din) self.not_enable = DigitalOutputDevice(cs) #lib = './wiring_bitbang.so' lib = './native_bitbang.so' self.bitbang = ctypes.cdll.LoadLibrary(lib) self.bitbang.init(self.data_pin, self.clock_pin) self._reset() self._init(contrast, inverse) self.drawer = DisplayGraphics(self) self.clear() self.dispose()
class ICAHSensor: rest_dur = 0.01 ping_dur = 0.000001 # s, same as measured for gpiozero speed_of_sound = 343 # m/s at 101325 Pa, 293 K call_num = 0 def __init__(self, trig, echo): self.trig = DigitalOutputDevice(trig) self.echo = DigitalInputDevice(echo) self.hist = [] def get_distance(self): ''' This could be made non-blocking by using a background thread that continually updates the current distance. We should also reject outliers in the distance measurements using the filter() function or similar. ''' self.call_num = self.call_num + 1 #print("Call No " + str(self.call_num)) del (self.hist[:]) for i in range(10): self.trig.off() sleep(self.rest_dur) self.trig.on() sleep(self.ping_dur) self.trig.off() #print("wait for active") self.echo.wait_for_active(timeout=self.rest_dur) t0 = time() #print("wait for inactive") self.echo.wait_for_inactive(timeout=1) dt = time() - t0 dist = dt * ICAHSensor.speed_of_sound / 2 self.hist.append(dist) return sum(self.hist) / len(self.hist)
class RemotePowerModule(BaseServer): def __init__(self, pwr_pin, res_pin, led_pin): super().__init__() self._pwr_sw = DigitalOutputDevice(pwr_pin) self._res_sw = DigitalOutputDevice(res_pin) self._pwr_led = DigitalInputDevice(led_pin) @property def power_status(self) -> Dict: return {"power": "on" if self._pwr_led.value == 1 else "off"} def power_on(self): if self.power_status["power"] == "off": self._pwr_sw.blink(on_time=0.5, n=1) def power_off(self): if self.power_status["power"] == "on": self._pwr_sw.blink(on_time=0.5, n=1) def reset(self): self._res_sw.blink(on_time=0.5, n=1)
from gpiozero import DigitalOutputDevice from time import sleep print("blink.py start") led_pin = DigitalOutputDevice(7) while True: led_pin.on() sleep(1) led_pin.off() sleep(1)
from vlc import EventType import random import pdb import threading #inputs button1 = Button(26, bounce_time=0.2) button2 = Button(13, bounce_time=0.2) button3 = Button(16, bounce_time=0.2) button4 = Button(5, bounce_time=0.2) button5 = Button(6, bounce_time=0.2) buttonOnOff = Button(25, hold_time=5) #outputs led = LED(24) display = DigitalOutputDevice(23) #funny sentences to say hello and good bye hellos = [ 'Coucou !', 'Salut a toi !', 'Toujours en vie ?', 'Comment vas-tu ?', 'Besoin de rien\nEnvie de toi...', 'BlBblblBLbblb !!', 'Pourquoi pas ?', 'Salamalekoum', ':-)' ] byes = [ 'Tchao l\'ami', 'Hasta la vista,\nBaby !', 'Hasta la victoria !', 'A plus \ndans l\'bus !', 'Bisous !' ] context = { 'playerList': vlc.MediaListPlayer(),
class AsyncMotor(CompositeDevice): def __init__(self, open_pin, close_pin, open_time, close_time, active_high=False, pin_factory=None): self.open_door_relay = DigitalOutputDevice( open_pin, active_high=active_high, initial_value=0, pin_factory=pin_factory) self.close_door_relay = DigitalOutputDevice( close_pin, active_high=active_high, initial_value=0, pin_factory=pin_factory) super().__init__(self.open_door_relay, self.close_door_relay) self.open_move_duration = open_time self.close_move_duration = close_time async def open_door(self): self.close_door_relay.off() await asyncio.sleep(1) self.open_door_relay.on() await asyncio.sleep(self.open_move_duration) self.open_door_relay.off() async def close_door(self): self.open_door_relay.off() await asyncio.sleep(1) self.close_door_relay.on() await asyncio.sleep(self.close_move_duration) self.close_door_relay.off()
class OPCN3(object): """ A OPCN3 Object to be used as an SPI slave, uses SPI 0 on pi0 by default (mode 1) :param cs_gpio: Which GPIO pin is the chip select (slave select) for this OPC """ def __init__(self, cs_gpio): self.spi = spidev.SpiDev() self.spi.open(0, 0) self.spi.mode = 1 self.spi.max_speed_hz = 300000 self.cs = DigitalOutputDevice(cs_gpio, initial_value=True) self.cs.on() self.info_string = "" self.serial_string = "" self.bbs_adc = [] self.bbs_um = [] self.bws = [] self.PMd_A_um = 0 self.PMd_B_um = 0 self.PMd_C_um = 0 self.max_ToF = 0 self.AM_sample_interval_count = 0 self.AM_idle_interval_count = 0 self.AM_max_data_arrays_in_file = 0 self.AM_only_save_PM = 0 self.AM_fan_on_idle = 0 self.AM_laser_on_idle = 0 self.ToF_SFR_factor = 0 self.PVP = 0 self.bin_weighting_index = 0 self.hist = [] self.mtof = [] self.period = 0 self.checksum = 0 self.reject_glitch = 0 self.reject_ratio = 0 self.reject_ltof = 0 self.flow_rate = 0 self.temp_degC = 0 self.RH_true = 0 self.PM_A_ugm3 = 0 self.PM_B_ugm3 = 0 self.PM_C_ugm3 = 0 self.reject_range = 0 self.fan_revs = 0 self.laser_status = 0 def command_byte(self, command): self.cs.off() response = 0x00 timeout = 0 while response != 0xF3: timeout += 1 if timeout > 20: raise RuntimeError( "Not receiving correct response from OPC-N3") response = self.spi.xfer2(command)[0] sleep(0.001) def read_info_string(self): self.info_string = "" self.command_byte([0x3F]) for i in range(60): sleep(0.00001) buf = self.spi.xfer2([0x01])[0] self.info_string += chr(buf) self.cs.on() def read_serial_string(self): self.serial_string = "" self.command_byte([0x01]) for i in range(60): sleep(0.00001) buf = self.spi.xfer2([0x01])[0] self.serial_string += chr(buf) self.cs.on() def read_config_vars(self): self.command_byte([0x3C]) self.bbs_adc = [] self.bbs_um = [] raw = [] for i in range(168): sleep(0.00001) buf = self.spi.xfer2([0x01])[0] raw.append(buf) self.cs.on() index = 0 for i in range(25): self.bbs_adc.append(byte_to_int16(raw[index], raw[index + 1])) index += 2 for i in range(25): self.bbs_um.append(byte_to_int16(raw[index], raw[index + 1])) index += 2 for i in range(24): self.bws.append(byte_to_int16(raw[index], raw[index + 1])) index += 2 self.PMd_A_um = byte_to_int16(raw[index], raw[index + 1]) self.PMd_B_um = byte_to_int16(raw[index + 2], raw[index + 3]) self.PMd_C_um = byte_to_int16(raw[index + 4], raw[index + 5]) self.max_ToF = byte_to_int16(raw[index + 6], raw[index + 7]) self.AM_sample_interval_count = byte_to_int16(raw[index + 8], raw[index + 9]) self.AM_idle_interval_count = byte_to_int16(raw[index + 10], raw[index + 11]) self.AM_max_data_arrays_in_file = byte_to_int16( raw[index + 12], raw[index + 13]) self.AM_only_save_PM = raw[index + 14] self.AM_fan_on_idle = raw[index + 15] self.AM_laser_on_idle = raw[index + 16] self.ToF_SFR_factor = raw[index + 17] self.PVP = raw[index + 18] self.bin_weighting_index = raw[index + 19] def read_histogram_data(self): self.command_byte([0x30]) self.hist = [] self.mtof = [] raw = [] index = 0 for i in range(86): sleep(0.00001) buf = self.spi.xfer2([0x01])[0] raw.append(buf) self.cs.on() for i in range(24): self.hist.append(byte_to_int16(raw[i * 2], raw[i * 2 + 1])) index = index + 2 for i in range(4): self.mtof.append(raw[index]) index = index + 1 self.period = byte_to_int16(raw[index], raw[index + 1]) self.flow_rate = byte_to_int16(raw[index + 2], raw[index + 3]) self.temp_degC = byte_to_int16(raw[index + 4], raw[index + 5]) self.RH_true = byte_to_int16(raw[index + 6], raw[index + 7]) self.PM_A_ugm3 = byte_to_float(raw[index + 8], raw[index + 9], raw[index + 10], raw[index + 11]) self.PM_B_ugm3 = byte_to_float(raw[index + 12], raw[index + 13], raw[index + 14], raw[index + 15]) self.PM_C_ugm3 = byte_to_float(raw[index + 16], raw[index + 17], raw[index + 18], raw[index + 19]) self.reject_glitch = byte_to_int16(raw[index + 20], raw[index + 21]) self.reject_ltof = byte_to_int16(raw[index + 22], raw[index + 23]) self.reject_ratio = byte_to_int16(raw[index + 24], raw[index + 25]) self.reject_range = byte_to_int16(raw[index + 26], raw[index + 27]) self.fan_revs = byte_to_int16(raw[index + 28], raw[index + 29]) self.laser_status = byte_to_int16(raw[index + 30], raw[index + 31]) self.checksum = byte_to_int16(raw[index + 32], raw[index + 33]) def start_opc(self): self.command_byte([0x03]) self.spi.xfer2([0x07]) self.cs.on() sleep(1) self.command_byte([0x03]) self.spi.xfer2([0x03]) self.cs.on() sleep(5) def stop_opc(self): self.command_byte([0x03]) self.spi.xfer2([0x06]) self.cs.on() sleep(1) self.command_byte([0x03]) self.spi.xfer2([0x02]) self.cs.on() sleep(5)
# Library Import from gpiozero import DigitalOutputDevice # DIGITALOUTPUTDEVICE is for RELAIS from gpiozero import Button from gpiozero.pins.pigpio import PiGPIOFactory import time import multiprocessing # IPADRES CHANGE THE GREEN TEXT TO CHANGE IP ADRES factory = PiGPIOFactory('192.168.0.112') # Setup Outputs # Relais CH1 = DigitalOutputDevice(17, True, False, pin_factory=factory) CH2 = DigitalOutputDevice(22, True, False, pin_factory=factory) # Setup Inputs # Buttons BTN1 = Button(pin=14, pull_up=False, bounce_time=0.25, pin_factory=factory) BTN2 = Button(pin=15, pull_up=False, bounce_time=0.25, pin_factory=factory) def toggle_led_one(): while True: if BTN1.value == 1: CH1.on() print("CH1 ON") wait_led() print("CH1 OFF") CH1.off()
from gpiozero import DigitalOutputDevice # 21 # 10 # 9 switch = DigitalOutputDevice(10) while True: print(switch.value)
class PCD8544(SPIDevice): """ PCD8544 display implementation. This implementation uses software shiftOut implementation? @author SrMouraSilva Based in 2013 Giacomo Trudu - wicker25[at]gmail[dot]com Based in 2010 Limor Fried, Adafruit Industries https://github.com/adafruit/Adafruit_Nokia_LCD/blob/master/Adafruit_Nokia_LCD/PCD8544.py Based in CORTEX-M3 version by Le Dang Dung, 2011 [email protected] (tested on LPC1769) Based in Raspberry Pi version by Andre Wussow, 2012, [email protected] Based in Raspberry Pi Java version by Cleverson dos Santos Assis, 2013, [email protected] https://www.raspberrypi.org/documentation/hardware/raspberrypi/spi/README.md The SPI master driver is disabled by default on Raspbian. To enable it, use raspi-config, or ensure the line dtparam=spi=on isn't commented out in /boot/config.txt, and reboot. :param int din: Serial data input :param int sclk: Serial clock input (clk) :param int dc: Data/Command mode select (d/c) :param int rst: External reset input (res) :param int cs: Chip Enable (CS/SS, sce) :param contrast :param inverse """ def __init__(self, din, sclk, dc, rst, cs, contrast=60, inverse=False): super(PCD8544, self).__init__(clock_pin=sclk, mosi_pin=din, miso_pin=9, select_pin=cs) self.DC = DigitalOutputDevice(dc) self.RST = DigitalOutputDevice(rst) self._reset() self._init(contrast, inverse) self.drawer = DisplayGraphics(self) self.clear() self.dispose() def _reset(self): self.RST.off() time.sleep(0.100) self.RST.on() def _init(self, contrast, inverse): # H = 1 self._send_command(SysCommand.FUNC | Setting.FUNC_H) self._send_command(SysCommand.BIAS | Setting.BIAS_BS2) self._send_command(SysCommand.VOP | contrast & 0x7f) # H = 0 self._send_command(SysCommand.FUNC | Setting.FUNC_V) self._send_command( SysCommand.DISPLAY | Setting.DISPLAY_D | Setting.DISPLAY_E * (1 if inverse else 0) ) def _send_command(self, data): self.DC.off() self._spi.write([data]) def _send_data_byte(self, x, y, byte): self._set_cursor_x(x) self._set_cursor_y(y) self.DC.on() self._spi.write([byte]) def set_contrast(self, value): self._send_command(SysCommand.FUNC | Setting.FUNC_H) self._send_command(SysCommand.VOP | value & 0x7f) self._send_command(SysCommand.FUNC | Setting.FUNC_V) def write_all(self, data): self._set_cursor_x(0) self._set_cursor_y(0) self.DC.on() self._spi.write(data) def _set_cursor_x(self, x): self._send_command(SysCommand.XADDR | x) def _set_cursor_y(self, y): self._send_command(SysCommand.YADDR | y) def clear(self): self._set_cursor_x(0) self._set_cursor_y(0) self.drawer.clear() @property def width(self): return DisplaySize.WIDTH @property def height(self): return DisplaySize.HEIGHT @property def value(self): return 0 def close(self): super(PCD8544, self).close() @property def draw(self): return self.drawer.draw def dispose(self): self.drawer.dispose()
class Robot(object): SPEED_HIGH = int(config.get("robot.speed","speed_high")) SPEED_MEDIUM = int(config.get("robot.speed","speed_medium")) SPEED_LOW = int(config.get("robot.speed","speed_low")) ##Define the arc of the turn process by a tuple wheels speed (left, right) LEFT_ARC_CLOSE = eval(config.get("robot.speed","left_arc_close")) LEFT_ARC_OPEN = eval(config.get("robot.speed","left_arc_open")) RIGHT_ARC_CLOSE = eval(config.get("robot.speed","right_arc_close")) RIGHT_ARC_OPEN = eval(config.get("robot.speed","right_arc_open")) #Pin pair left FORWARD_LEFT_PIN = int(config.get("robot.board.v1","forward_left_pin")) BACKWARD_LEFT_PIN = int(config.get("robot.board.v1","backward_left_pin")) #Pin pair right FORWARD_RIGHT_PIN = int(config.get("robot.board.v1","forward_right_pin")) BACKWARD_RIGHT_PIN = int(config.get("robot.board.v1","backward_right_pin")) #PWM PINS PWM_LEFT_PIN = int(config.get("robot.board.v1","pwm_left_pin")) PWM_RIGHT_PIN = int(config.get("robot.board.v1","pwm_right_pin")) #Frecuency by hertz FRECUENCY = int(config.get("robot.board.v1","frecuency")) # Cycles fits for pwm cycles LEFT_CYCLES_FIT = int(config.get("robot.board.v1","left_cycles_fit")) RIGHT_CYCLES_FIT = int(config.get("robot.board.v1","right_cycles_fit")) #Pin settings for head control HEAD_HORIZONTAL_PIN = int(config.get("robot.board.v1","head_pwm_pin_horizontal_axis")) HEAD_VERTICAL_PIN = int(config.get("robot.board.v1","head_pwm_pin_vertical_axis")) HEAD_HORIZONTAL_RANGE = config.get("robot.board.v1","head_horizontal_range").split(",") HEAD_VERTICAL_RANGE = config.get("robot.board.v1","head_vertical_range").split(",") RIGHT_WHEEL_SENSOR = int(config.get("robot.board.v1","right_wheel_sensor")) LEFT_WHEEL_SENSOR = int(config.get("robot.board.v1", "left_wheel_sensor")) CONTROLLER_BOARD = config.get("robot.controller", "board") #v2 WHEEL_LEFT_ENABLED = int(config.get("robot.board.v2", "wheel_left_enabled")) WHEEL_LEFT_HEADING = int(config.get("robot.board.v2", "wheel_left_heading")) WHEEL_LEFT_STEP = int(config.get("robot.board.v2", "wheel_left_step")) WHEEL_RIGHT_ENABLED = int(config.get("robot.board.v2", "wheel_right_enabled")) WHEEL_RIGHT_HEADING = int(config.get("robot.board.v2", "wheel_right_heading")) WHEEL_RIGHT_STEP = int(config.get("robot.board.v2", "wheel_right_step")) SERVO_V = None SERVO_H = None head_vertical_current_position = None head_horizontal_current_position = None def __init__(self): if env == "prod": log.debug("Using %s configuration" % self.CONTROLLER_BOARD ) self.SERVO_H = AngularServo(self.HEAD_HORIZONTAL_PIN, min_angle=-80, max_angle=80) self.SERVO_V = AngularServo(self.HEAD_VERTICAL_PIN, min_angle=-80, max_angle=80) ##Digital devices self.forward_left_device = None self.forward_right_device = None self.backward_left_device = None self.backward_right_device = None self.wheel_right_step = None self.wheel_left_step = None self.wheel_right_heading = None self.wheel_left_heading = None self.wheel_right_enabled = None self.wheel_left_enabled = None self.pwm_left = None self.pwm_right = None if self.CONTROLLER_BOARD == "v1": self.forward_left_device = DigitalOutputDevice(self.FORWARD_LEFT_PIN, True, False) self.forward_right_device = DigitalOutputDevice(self.FORWARD_RIGHT_PIN, True, False) self.backward_left_device = DigitalOutputDevice(self.BACKWARD_LEFT_PIN, True, False) self.backward_right_device = DigitalOutputDevice(self.BACKWARD_RIGHT_PIN, True, False) self.pwm_left = PWMOutputDevice(self.PWM_LEFT_PIN, True, False, self.FRECUENCY) self.pwm_right = PWMOutputDevice(self.PWM_RIGHT_PIN, True, False, self.FRECUENCY) if self.CONTROLLER_BOARD == "v2": self.wheel_right_step = DigitalOutputDevice(self.WHEEL_RIGHT_STEP, True, False) self.wheel_left_step = DigitalOutputDevice(self.WHEEL_LEFT_STEP, True, False) self.wheel_right_heading = DigitalOutputDevice(self.WHEEL_RIGHT_HEADING, True, False) self.wheel_left_heading = DigitalOutputDevice(self.WHEEL_LEFT_HEADING, True, False) self.wheel_right_enabled = DigitalOutputDevice(self.WHEEL_RIGHT_ENABLED, True, False) self.wheel_left_enabled = DigitalOutputDevice(self.WHEEL_LEFT_ENABLED, True, False) self.current_horizontal_head_pos = 0 self.current_vertical_head_pos = 0 self.center_head() self._counting_steps = 0 self._current_steps = 0 self._stepper_current_step = 0 def _set_left_forward(self): if self.CONTROLLER_BOARD == "v1": self.forward_left_device.on() self.backward_left_device.off() def _set_left_backward(self): if self.CONTROLLER_BOARD == "v1": self.forward_left_device.off() self.backward_left_device.on() def _set_left_stop(self): if self.CONTROLLER_BOARD == "v1": self.forward_left_device.on() self.backward_left_device.on() def _set_right_forward(self): if self.CONTROLLER_BOARD == "v1": self.forward_right_device.on() self.backward_right_device.off() def _set_right_backward(self): if self.CONTROLLER_BOARD == "v1": self.forward_right_device.off() self.backward_right_device.on() def _set_right_stop(self): if self.CONTROLLER_BOARD == "v1": self.forward_right_device.on() self.backward_right_device.on() def set_forward(self): log.debug("setting movement to forward") if env == "prod": self._set_left_forward() self._set_right_forward() def set_backward(self): log.debug("setting movement to backward") if env == "prod": self._set_left_backward() self._set_right_backward() def set_rotate_left(self): log.debug("setting movement to rotate left") if env == "prod": self._set_left_backward() self._set_right_forward() def set_rotate_right(self): log.debug("setting movement to rotate right") if env == "prod": self._set_right_backward() self._set_left_forward() def stop(self): log.debug("stopping") if env == "prod": if self.CONTROLLER_BOARD == "v1": self.pwm_left.off() self.pwm_right.off() def move(self, speed=None, arc=None, steps=100, delay=0.7, heading=1): if self.CONTROLLER_BOARD == "v1": self._move_dc(speed, arc) elif self.CONTROLLER_BOARD == "v2": self._move_steppers_bipolar(steps=steps, delay=delay, heading=heading) def _move_dc(self, speed, arc): log.debug("Moving using DC motors") if (speed and arc): print("Error: speed and arc could not be setted up at the same time") return if env == "prod": self.pwm_left.on() self.pwm_right.on() if (speed): log.debug("moving on " + str(speed)) log.debug("aplying fit: left " + str(self.LEFT_CYCLES_FIT) + " right " + str(self.RIGHT_CYCLES_FIT)) aditional_left_clycles = self.LEFT_CYCLES_FIT if ((speed + self.LEFT_CYCLES_FIT) <= 100.00) else 0.00 aditional_right_clycles = self.RIGHT_CYCLES_FIT if ((speed + self.RIGHT_CYCLES_FIT) <= 100.00) else 0.00 if env == "prod": self.pwm_left.value = (speed + aditional_left_clycles) / 100.00 self.pwm_right.value = (speed + aditional_right_clycles) / 100.00 if (arc): cycle_left, cycle_right = arc log.debug("turning -> left wheel: " + str(cycle_left) + " right wheel: " + str(cycle_right)) if env == "prod": self.pwm_left.value = cycle_left / 100.00 self.pwm_right.value = cycle_right / 100.00 def _move_steppers_bipolar(self, steps, heading, delay): """ Currently it would take 4 steps to complete a whole wheel turn """ log.debug("Moving steppers bipolars . Steps " + str(steps) + " delay " + str(delay)) steps_left = abs(steps) if env == "prod": self.wheel_left_enabled.off() self.wheel_right_enabled.off() while(steps_left!=0): log.debug("Current step: " + str(steps_left)) if env == "prod": if heading: self.wheel_left_heading.on() self.wheel_right_heading.off() else: self.wheel_left_heading.off() self.wheel_right_heading.on() self.wheel_left_step.off() self.wheel_right_step.off() sleep(delay/1000.00) self.wheel_left_step.on() self.wheel_right_step.on() sleep(delay/1000.00) steps_left -= 1 if env == "prod": self.wheel_left_enabled.on() self.wheel_right_enabled.on() def center_head(self): log.debug("centering head") self.head_horizontal_current_position = 0 self.head_vertical_current_position = 0 if env == "prod": self.SERVO_H.mid() self.SERVO_V.mid() sleep(0.2) self.SERVO_H.detach() self.SERVO_V.detach() def _angle_to_ms(self,angle): return 1520 + (int(angle)*400) / 45 def move_head_horizontal(self, angle): log.debug("horizontal limits: " + self.HEAD_HORIZONTAL_RANGE[0] +" "+ self.HEAD_HORIZONTAL_RANGE[1]) log.debug("new horizontal angle: " + str(angle)) if angle > int(self.HEAD_HORIZONTAL_RANGE[0]) and angle < int(self.HEAD_HORIZONTAL_RANGE[1]): log.debug("moving head horizontal to angle: " + str(angle)) self.head_horizontal_current_position = angle if env == "prod": self.SERVO_H.angle = angle sleep(0.2) self.SERVO_H.detach() def move_head_vertical(self, angle): log.debug("vertical limits: " + self.HEAD_VERTICAL_RANGE[0] +" "+ self.HEAD_VERTICAL_RANGE[1]) log.debug("new vertical angle: " + str(angle)) if angle > int(self.HEAD_VERTICAL_RANGE[0]) and angle < int(self.HEAD_VERTICAL_RANGE[1]): log.debug("moving head vertical to angle: " + str(angle)) self.head_vertical_current_position = angle if env == "prod": self.SERVO_V.angle = angle sleep(0.2) self.SERVO_V.detach() #Used for encoders def steps(self, counting): self._current_steps = counting self.move(speed=self.SPEED_HIGH) self.move(speed=self.SPEED_MEDIUM) rpio.add_interrupt_callback(RIGHT_WHEEL_SENSOR, self._steps_callback, threaded_callback=True) rpio.add_interrupt_callback(LEFT_WHEEL_SENSOR, self._steps_callback, threaded_callback=True) rpio.wait_for_interrupts(threaded=True) def _steps_callback(self, gpio_id, value): self._counting_steps += 1 if self._counting_steps > self._current_steps: self._counting_steps = 0 self._current_steps = 0 rpio.stop_waiting_for_interrupts()
def collector(sample_length=45, dout=LOAD_CELL_DOUT, sck=LOAD_CELL_SCK, gain=LOAD_CELL_GAIN, loadcell_threshold=-200000, fsr_threshold=0.5): start_time = time() d_out = DigitalInputDevice(pin=dout, pull_up=True) sck = DigitalOutputDevice(pin=sck) adc = MCP3008(channel=0) load_cell_results = [] fsr_results = [] sck.off() timeout = 2 while time() - start_time < sample_length: # Retrieve data from MCP3008 fsr_results.append(adc.value) # Retrieve data from HX711 loop_start_time = time() while not d_out.is_active: if time() - loop_start_time > timeout: break data = 0 for j in range(24): data = data << 1 sck.on() sck.off() if d_out.value == 0: data = data + 1 #print("data", data, hex(data), convert_twos_complement(data)) # load_cell_results.append(data) load_cell_results.append((hex(data), convert_twos_complement(data))) # 25th pulse sck.on() sck.off() # 128 pulses for i in range(gain): sck.on() sck.off() # Process data loadcell_data = ','.join(str(e) for e in load_cell_results) fsr_data = ','.join(str(e) for e in fsr_results) loadcell_results = [e[1] for e in load_cell_results if e[0] != '0xffffff'] loadcell_result = 1 if data_processor(loadcell_results, loadcell_threshold) else 0 fsr_result = 1 if data_processor(fsr_results, fsr_threshold) else 0 final_result = 1 if fsr_result == 1 or loadcell_result == 1 else 0 # Send data to remote server # firebase_values = { # 'isSitting': final_result, # 'datetime': datetime.fromtimestamp(start_time, get_localzone()), # 'timestamp': int(start_time) # } # sender.sendToFirebase(firebase_values=firebase_values) resp = send(final_result, datetime.fromtimestamp(start_time, get_localzone())) print(resp) # Save data into local database db.insert((int(start_time), fsr_data, fsr_result, loadcell_data, loadcell_result, final_result)) adc.close() d_out.close() sck.close() return (load_cell_results, fsr_results)
class Motor: def __init__(self, ain1=None, ain2=None, bin1=None, bin2=None, pwma=None, pwmb=None): print("init") self.ain1 = DigitalOutputDevice(ain1, initial_value=False) self.ain2 = DigitalOutputDevice(ain2, initial_value=False) self.bin1 = DigitalOutputDevice(bin1, initial_value=False) self.bin2 = DigitalOutputDevice(bin2, initial_value=False) self.pwma = PWMOutputDevice(pwma, initial_value=.5) self.pwmb = PWMOutputDevice(pwmb, initial_value=.5) def stop(self): print("stop") self.ain1.off() self.ain2.off() self.bin1.off() self.bin2.off() def forward(): print("forward") self.ain1.on() self.ain2.off() self.bin1.on() self.bin2.off() def backward(): print("backward") self.ain1.off() self.ain2.on() self.bin1.off() self.bin2.on() def turn_left(): print("turn_left") self.ain1.off() self.ain2.on() self.bin1.on() self.bin2.off() def turn_right(): print("turn_right") self.ain1.on() self.ain2.off() self.bin1.off() self.bin2.on()