def __init__(self, parent): if printme: print >>sys.stderr, '__init__' QWidget.__init__(self, parent) self.parent = parent self.ui = parent.ui self.protocol = self.parent.protocol # defaults self.sending = 0 self.eled = led.LED(self.ui.eraseLed) self.tled = led.LED(self.ui.transferLed) self.vled = led.LED(self.ui.verifyLed) self.clearLeds() self.lastTarget = None # default target addresses and menu setup # name, transferObject(parent, filename, target address, header choice, who for) self.targets = [ ['Main Boot', sRecordTransfer(parent, '', MAIN_BOOT, 0, MAIN_CPU, 'little')], ['Main App L', sRecordTransfer(parent, '', MAIN_APP_LEFT, 1, MAIN_CPU, 'little')], ['Main App R', sRecordTransfer(parent, '', MAIN_APP_RIGHT, 1, MAIN_CPU, 'little')] ] for entry in self.targets: self.ui.targetSelect.addItem(entry[0]) entry[1].progress.connect(self.progress) entry[1].done.connect(self.srecordDone) entry[1].eraseFail.connect(self.eled.error) entry[1].transferFail.connect(self.tled.error) entry[1].verifyFail.connect(self.vled.error) entry[1].eraseDone.connect(self.eled.on) entry[1].transferDone.connect(self.tled.on) entry[1].verifyDone.connect(self.vled.on) entry[1].eraseStart.connect(self.eled.blink) entry[1].transferStart.connect(self.tled.blink) entry[1].verifyStart.connect(self.vled.blink) entry[1].starting.connect(self.eled.off) entry[1].starting.connect(self.tled.off) entry[1].starting.connect(self.vled.off) self.ui.targetSelect.setCurrentIndex(0) self.showSrecordValues() # recovery setup self.recovering = 0 self.recover = recover(parent) self.recover.done.connect(self.recoverDone) self.recover.failed.connect(self.recoverDone) # connections for UI self.ui.sendSrecord.pressed.connect(self.sendSrecord) self.ui.fileSelect.pressed.connect(self.selectFile) self.ui.Version.pressed.connect(self.getVersion) self.ui.Recover.pressed.connect(self.selectRecover) self.ui.targetSelect.currentIndexChanged.connect(self.saveSrecordValues) self.ui.reboot.clicked.connect(self.reboot) self.ui.Run.clicked.connect(self.runTarget) self.ui.verifyLed.clicked.connect(self.runVerify)
def init_led(self): number = random.randint(0, 500) if number < 50 and number not in self.active: self.active.add(number) self.led = led.LED(number, led.Color(brightness=0xFF)) self.step = 0 self.offset = 1
def setUp(self): RPi.GPIO.input.return_value = RPi.GPIO.HIGH hwc = controller.GPIOController pins = hwc.PIN self.lid = lid.Lid(pins.PUSH_BUTTON) hwc.add_component(self.lid) self.assertEqual(self.lid.status, self.lid.CLOSED) self.led_yellow = led.LED(pins.YELLOW_LED, led.LED.ON) hwc.add_component(self.led_yellow) RPi.GPIO.output.assert_called_with(self.led_yellow.pin, RPi.GPIO.HIGH) self.led_blue = led.LED(pins.BLUE_LED, led.LED.OFF) hwc.add_component(self.led_blue) RPi.GPIO.output.assert_called_with(self.led_blue.pin, RPi.GPIO.LOW) hwc.add_component(motor.Motor(*pins.MOTOR, enable_timer=False))
def __init__(self): self.__led = led.LED() self.__root = tk.Tk() self.__root.title("GUI") self.__main_frame = ttk.Frame(self.__root, padding=50) self.__main_frame.pack(fill=tk.BOTH, expand=True) self.__root.attributes("-fullscreen", True) self.__btn_capture = tk.Button(self.__main_frame, text="CAPTURE", width=50, height=3, command=self.__capture) self.__btn_capture.pack() self.__btn_view_grains = tk.Button(self.__main_frame, text="VIEW GRAINS", width=50, height=3, state=tk.DISABLED) #self.__btn_view_grains.pack() self.__btn_grade = tk.Button(self.__main_frame, text="GRADE", width=50, height=3, command=self.__grade) self.__btn_grade.pack() self.__btn_log = tk.Button(self.__main_frame, text="LOG", width=50, height=3) #self.__btn_log.pack() self.__btn_LED_ON = tk.Button(self.__main_frame, text="LED ON", width=50, height=3, command=self.__led_on) self.__btn_LED_ON.pack() self.__btn_LED_OFF = tk.Button(self.__main_frame, text="LED OFF", width=50, height=3, command=self.__led_off, state=tk.DISABLED) self.__btn_LED_OFF.pack() self.__btn_shutdown = tk.Button(self.__main_frame, text="SHUTDOWN", width=50, height=3, command=self.__exit) self.__btn_shutdown.pack() self.__root.mainloop()
def main(): logging.basicConfig(level=logging.INFO) ls = light_sensor.LightSensor(LIGHT_SENSOR_I2C_BUS, LIGHT_SENSOR_I2C_ADDRESS) di = display.Display(DISPLAY_PIN_RESET, DISPLAY_PIN_DC, DISPLAY_SPI_PORT, DISPLAY_SPI_DEVICE) tph = bme280.BME280(BME280_I2C_BUS, BME280_I2C_ADDRESS) led0 = led.LED(LED_PIN_RED, LED_PIN_GREEN, LED_PIN_BLUE) while True: ls.start() time.sleep(0.5) visible, infrared = ls.read() temp, _, pressure, humidity = tph.read() di.update(visible, infrared, temp, pressure, humidity) #blue_value = (65535 - visible) / 65535.0 * 100 #logger.info(blue_value) #led0.set_blue(blue_value) led0.set_blue(100) time.sleep(0.01) led0.set_blue(0)
def init_GPIO(): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) leds = [ led.LED(6), led.LED(13), led.LED(12), led.LED(26), led.LED(20), led.LED(21), led.LED(4) ] buttons = [button.Button(16), button.Button(19)] # momentarily flash LEDs to indicate initalization [x.on() for x in leds] time.sleep(1) [x.off() for x in leds] return (buttons, leds)
else: print('[ERROR]\tUnexpected command received:->' + element + '<-') return dataList mainServer.readAll() while (True): try: x = 0 tempDataRaw = mainServer.readAll() # print(tempDataRaw) for dataType, index, data in decodeList(tempDataRaw): if (dataType == 'Z'): pass led.LED(4) elif (dataType == 't' and index == 1): led.LED(3) data_send[0] = data # print(colorama.Fore.GREEN + '[TEMP1]\t' + colorama.Style.RESET_ALL + data) elif (dataType == 't' and index == 2): led.LED(3) data_send[1] = data # print(colorama.Fore.GREEN + '[TEMP2]\t' + colorama.Style.RESET_ALL + data) elif (dataType == 't' and index == 3): led.LED(3) data_send[2] = data # print(colorama.Fore.GREEN + '[TEMP3]\t' + colorama.Style.RESET_ALL + data) elif (dataType == 'i'): led.LED(3) data_send[3] = data
#main import diigit as d import m_ultra as u import m_camera as c import led as l import RPi.GPIO as GPIO disp = d.TM1637(6, 5) ultra = u.ULTRA(20, 21) led = l.LED(27, 18) camera = c.CAMERA() try: while True: dist = ultra.getDistance() print('dist: ',dist) if dist<4: led.redOn() camera.takePicture() elif dist<12: led.redyellowFlashing() disp.set_values("BACK"); elif dist<17: led.yellowFlashing() disp.clear() else: led.lightOff() disp.clear() except KeyboardInterrupt: GPIO.cleanup()
import paho.mqtt.client as mqtt import time import led l = led.LED(27, 18) def on_connect(client, userdata,flags, rc): print("Connected with result code "+str(rc)) client.subscribe("bit/led") #client.subscribe("$SYS/#") def on_message(client, userdata, msg): print(msg.topic+ " " + str(msg.payload)) if str(msg.payload) == 'red': l.redOn() elif str(msg.payload) == 'yellow': l.yellowOn() elif str(msg.payload) == 'both': l.redyellow() else: l.lightOff() addr = "192.168.1.25" client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect(addr, 1883)
def setUp(self, mock_db): pin = controller.GPIOController.PIN.YELLOW_LED self.led = led.LED(pin, led.LED.OFF) self.led.timer = led.LightTimer(self.led) self.assertEqual(self.led.status, self.led.OFF) RPi.GPIO.output.assert_called_once_with(self.led.pin, RPi.GPIO.LOW)
temp_string = lines[1][equals_pos + 2:] temp_c = float(temp_string) / 1000.0 return temp_c while True: try: if (time_new - time_old >= 5000): t1 = str(read_temp()) print('temp1 sent = ' + t1) mainServer.write('t1' + t1 + '\t') t2 = str(read_temp1()) print 'temp2 sent = ' + t2 mainServer.write('t2' + t2 + '\t') t3 = str(read_temp2()) print 'temp3 sent = ' + t3 mainServer.write('t3' + t3 + '\t') time_old = time_new led.LED(1) else: time_new = int(time.time() * 1000) except BaseException as e: print(colorama.Fore.RED + '[ERROR]\t' + colorama.Style.RESET_ALL + e.message) print(colorama.Fore.RED + '[ERROR]\t' + colorama.Style.RESET_ALL + traceback.format_exc()) mainServer.close() led.LED(4) break
import led import time _green = led.LED(5) _yellow = led.LED(17) _red = led.LED(19) def update_state(green, yellow, red): if green: _green.on() else: _green.off() if yellow: _yellow.on() else: _yellow.off() if red: _red.on() else: _red.off() _state = 'green' while True: #print(_state) if _state == 'yellow': update_state(False, False, True)
#!/usr/bin/python -u # -*- coding: utf-8 -*- import smbus2 import time import sys import signal #from PyQt4 import QtGui #import display import led import th02 led = led.LED() th02 = th02.TH02() def exit_handler(siglal, frame): #C-c is finish print("\nExit") time.sleep(0.5) led.clear() sys.exit(0) def main(): #app = QtGui.QApplication(sys.argv) signal.signal(signal.SIGINT, exit_handler) #d = display.display() while True: time.sleep(0.1)
gyro_x = read_raw_data(GYRO_XOUT_H) gyro_y = read_raw_data(GYRO_YOUT_H) gyro_z = read_raw_data(GYRO_ZOUT_H) Ax = float("{0:.2f}".format(acc_x / 16384.0)) Ay = float("{0:.2f}".format(acc_y / 16384.0)) Az = float("{0:.2f}".format(acc_z / 16384.0)) Gx = float("{0:.2f}".format(gyro_x / 131.0)) Gy = float("{0:.2f}".format(gyro_y / 131.0)) Gz = float("{0:.2f}".format(gyro_z / 131.0)) bun = str(Ax) + ',' + str(Ay) + ',' + str(Az) + ',' + str( Gx) + ',' + str(Gy) + ',' + str(Gz) # print bun mainServer.write('i1' + bun + '\t') time_old = time_new led.LED(2) time.sleep(1) else: time_new = int(time.time() * 1000) except BaseException as e: print(colorama.Fore.RED + '[ERROR]\t' + colorama.Style.RESET_ALL + e.message) print(colorama.Fore.RED + '[ERROR]\t' + colorama.Style.RESET_ALL + traceback.format_exc()) mainServer.close() led.LED(4) break
# # GPIOs Example - Showcase the GPIO module import time from hardware import gpio import led ## Create a new led object using the pin 11 led1 = led.LED(11, 1) while True: # Change LED state led1.ON() time.sleep(4000) led1.OFF() time.sleep(1000)
import pwm_calibrate import led import paho.mqtt.client as mqtt from settings import * if __name__ == '__main__': l = led.LED(SERIAL_DEVICE, SERIAL_SPEED) l.set(0, 100, 0) p = pwm_calibrate.PWMCalibrator(calibration_file=CALIBRATION_FILE, smoothing=True) p.load() p_range = p.get_range() p.setPWM(p_range[0]) def on_connect(client, userdata, flags, rc): print('connected to MQTT server') client.subscribe(MQTT_TOPIC_PWM) client.subscribe(MQTT_TOPIC_LED) def on_message(client, userdata, message): print("%s %s" % (message.topic, message.payload)) if message.topic == MQTT_TOPIC_PWM: p = userdata['pwm'] val = max(p_range[0], min(p_range[1], int(message.payload))) p.setPWM(val) elif message.topic == MQTT_TOPIC_LED: l = userdata['led'] rgb = [int(x) for x in message.payload.decode('ascii').split(',')]
import shoulder # create a RoboticArm instance rArm = arm.RobotArm() # open SPI bus spi = spidev.SpiDev() spi.open(0, 0) # create joint and LED instances base_joint = base.Joint(280, 750) shoulder_joint = shoulder.Joint(440, 880) elbow_joint = elbow.Joint(200, 720) wrist_joint = wrist.Wrist(430, 600) grip_claw = claw.Joint(450, 550) light_led = led.LED() # read from SPI function def readADC(channel): adc = spi.xfer2([1, (8 + channel) << 4, 0]) data = ((adc[1] & 3) << 8) + adc[2] return data try: # listen for event objects from read.py for event in read.event_listener(): # check if event object is valid if event.valid == "true": # get command of each joint
# coding:utf-8 Copy Right Atelier Grenouille © 2015 - #import subprocess import importlib import led import RPi.GPIO as GPIO import traceback import sys import getrpimodel # RPi 3 は LED1(赤LED)を操作できない pi3 = True if getrpimodel.model() == "3 Model B" else False l = led.LED() l.use(0) # green pi3 or l.use(1) # red l.off(0) pi3 or l.off(1) l_status = False # GPIO の設定 GPIO.setmode(GPIO.BCM) #def get_gpio(): # p = subprocess.call(gpio_str, stdout=subprocess.PIPE, shell=True) # return p.stdout.readline().strip() def wait(pin): global l GPIO.setup(int(pin), GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
def main(): user = False saveDHTData = True logFile = "logger.txt" # Get the sensors dht22S = dht22.DHT22() hcsr04S = hcsr04.HCSR04() ledS = led.LED() resetPB = push_button.PushButton(dht22S, ledS, 20) # Create the queues for each sensor qDatadht = Q.Queue(1000) qdhtExit = Q.Queue(1) qDataHC = Q.Queue(1000) qhcExit = Q.Queue(1) serverQ = Q.Queue(100) sQExit = Q.Queue(1) # Create locks dhtLock = t.Lock() hcLock = t.Lock() dhtExitL = t.Lock() hcExitL = t.Lock() serverLock = t.Lock() sExitL = t.Lock() # Create the thread for DHT sensor thread1 = sThread.SensorThread(1, "Thread1", qDatadht, dhtLock, qdhtExit, dhtExitL, dht22S) # Create thread for HC-SR04 sensor thread2 = sThread.SensorThread(2, "Thread2", qDataHC, hcLock, qhcExit, hcExitL, hcsr04S) # Thread for the server serverT = server.ServerS(3, "Server", logFile, serverQ, serverLock, sQExit, sExitL) # Start thread1.start() thread2.start() serverT.start() endProcess = False while not endProcess: dht22Data = None # Is there data from DHT22? dhtLock.acquire() if not qDatadht.empty(): dht22Data = qDatadht.get() dhtLock.release() # Is there data from HC-SR04? hcData = None hcLock.acquire() if not qDataHC.empty(): hcData = qDataHC.get() hcLock.release() # Was there a presence? if hcData: pTime = time.asctime() data = ["HC", hcData, pTime] ledS.turnOnLED() writeToFile(logFile, data) # DHT data if saveDHTData: if dht22Data: if dht22Data[0] != None: data = [" DHT", dht22Data[0], dht22Data[1]] writeToFile(logFile, data) # Verify is there are new params data = [] interval = [] serverLock.acquire() # Get the new parameters while not serverQ.empty(): data.append(serverQ.get()) serverLock.release() if not data: continue # Modify params is necessary for d in data: dSplit = d.split(",") value = float(dSplit[1]) if dSplit[0] == "RS" and value == 1: dht22S.setDefaults() ledS.turnOffLED() if dSplit[0] == "LI" and value != -1: interval.append(dSplit[1]) if dSplit[0] == "UI" and value != -1: interval.append(dSplit[1]) if dSplit[0] == "SP" and value != -1: dht22S.setPSampling(float(dSplit[1])) if dSplit[0] == "SV" and value != -1: saveDHTData = bool(int(dSplit[1])) if dSplit[0] == "TF" and value != -1: ledS.turnOffLED() # if len(interval) > 0: dht22S.setSamplingInterval(int(interval[1]), int(interval[2])) if not dht22S.withinInterval(time.time()): saveDHTData = False
prev = which.Power(device['conf']['pins'], on=True) oled.fill(1) oled.show() sleep_ms(1000) oled.fill(0) oled.show() except Exception as e: print('Oled display failed with %s' % e) if not prev is None: which.Power(device['conf']['pins'], on=prev) sys.exit() # found oled, try it and blow RGB led wissle try: import led LED = led.LED() except: raise OSError("Install library led") #button = Pin('P18',mode=Pin.IN, pull=Pin.PULL_DOWN) #led = Pin('P9',mode=Pin.OUT) # #def pressed(what): # # global LED # print("Pressed %s" % what) # LED.blink(5,0.1,0xff0000,False) # #button.callback(Pin.IRQ_FALLING|Pin.IRQ_HIGH_LEVEL,handler=pressed,arg='SLEEP') def display(txt, x, y, clear, prt=True):
def main(input_file, output_file, speed, debug=False): """ Main control flow for Voice Assistant device. """ GPIO.setmode(GPIO.BOARD) button = Button(17) button.hold_time = 2 button.when_held = play_tutorial light = led.LED() # pull last saved speed from json with open('save_state.json', 'r') as saveFile: response = json.load(saveFile) speed = float(response['savedSpeed']) client = avs.connect_to_avs() dialog_req_id = [helpers.generate_unique_id()] audio_process = Processing(input_file, output_file, speed, 15) os.system("mpg321 audio_instrs/startup.mp3") # check if should play tutorial, requires holding for 2 sec time.sleep(5) if IN_TUTORIAL: print("hello in tutorial") time.sleep(78) if speed == 1: os.system("mpg321 " + menu_filenames[int(speed) - 1]) light.flash(led.RED) elif speed == 2: os.system("mpg321 " + menu_filenames[int(speed) - 1]) light.flash(led.GRN) else: os.system("mpg321 " + menu_filenames[int(speed) - 1]) light.flash(led.BLUE) # reset hold time/when_held func to go to menu button.hold_time = 5 button.when_held = partial(launch_menu, button, light, audio_process) try: while True: print("ready for input") light.change_color(led.GRN) # record from mic if input_file == "in.wav": button.wait_for_press() if button.is_pressed: button.wait_for_release() if IN_MENU: while IN_MENU: pass continue rec = Recording(input_file) light.change_color(led.BLU) rec.record(button) light.change_color(led.ALL) if debug: output_file = input_file else: audio_process.apply() # send to avs # outfiles = avs.send_rec_to_avs(output_file, client) outfiles = avs.send_rec_to_avs(output_file, client, dialog_req_id) # play back avs response light.change_color(led.PUR) if not outfiles: light.change_color(led.RED) os.system("mpg321 audio_instrs/alexa-noresponse.mp3") print("Error, no outfiles") time.sleep(1) for of in outfiles: print("playing: " + of) os.system("mpg321 " + of) if input_file == 'in.wav': print("Command completed! Waiting for new input!") else: light.interrupt() break except KeyboardInterrupt: light.interrupt()