def initialize(): global ser GPIO.setmode(GPIO.BCM) GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(6, GPIO.IN, pull_up_down=GPIO.PUD_UP) lcd.lcd_init() ser.baudrate = 9600
def app_init(): GPIO.setup("P8_12", GPIO.IN) GPIO.add_event_detect("P8_12", GPIO.RISING, callback=button_release, bouncetime=500) lcd_i2c.lcd_init()
def loop(): global power_state global led while True: # lcd초기화 lcd.lcd_init() # 먼지센서 동작 ser = serial.Serial(SERIAL_PORT, Speed, timeout=1) buffer = ser.read(1024) if (dustlib.protocol_chk(buffer)): data = dustlib.unpack_data(buffer) global pm1 global pm25 global pm10 pm1 = int(data[dustlib.DUST_PM1_0_ATM]) pm25 = int(data[dustlib.DUST_PM2_5_ATM]) pm10 = int(data[dustlib.DUST_PM10_0_ATM]) print("PMS 7003 dust data") print("PM 1.0 : %d" % (pm1)) print("PM 2.5 : %d" % (pm25)) print("PM 10.0 : %d" % (pm10)) else: print("data read Err") # 전원 상태에 따른 동작 if power_state == 0: print("전원꺼짐") fan_power(OFF) lcd.LCD_BACKLIGHT = 0x00 lcd.lcd_string(" Power Off ", lcd.LCD_LINE_1) lcd.lcd_string("", lcd.LCD_LINE_2) led.off() if power_state == 1: print("전원켜짐") fan_power(ON) display_dust(pm1, pm25, pm10) if power_state == 2: print("자동모드") if pm10 <= 30 and (pm1 + pm25) <= 15: fan_power(OFF) else: fan_power(ON) display_dust(pm1, pm25, pm10) # powersw.wait_for_press(timeout=2) time.sleep(1)
def main(): # Main program block # Initialise display lcd_i2c.lcd_init() while True: temp = bme280.temperature humidity = bme280.humidity # Send to LCD lcd_i2c.lcd_string("Temperature: " + "{:.1f}".format(temp) + " C", lcd_i2c.LCD_LINE_1) lcd_i2c.lcd_string("Humidity: " + "{:.1f}".format(humidity) + " %", lcd_i2c.LCD_LINE_2) time.sleep(3)
def main(): # First line response = feedparser.parse("https://" + USERNAME + ":" + PASSWORD + "@mail.google.com/gmail/feed/atom") unread_count = int(response["feed"]["fullcount"]) # result = datetime.datetime.today().strftime("%d.%m/%H:%M") + " " result_1 = datetime.datetime.today().strftime("%H:%M") + " " result_1 += "G:" + str(unread_count) + " " observation = owm.weather_at_place('Zmigrod,pl') w = observation.get_weather() result_1 += "T:" + str(int(w.get_temperature('celsius')['temp'])) + "/" # result_1 += "W:" + str(int(w.get_wind()['speed'])) + " " # result_1 += "P:" + str(w.get_pressure()['press']) # result_1 += str(w.get_clouds()) + " " result_1 += str(w.get_humidity()) # Second line # Kudos count kudos_count = 0 for activity in client.get_activities(): # print("{0.name} {0.moving_time} {0.distance}".format(activity)) kudos_count += activity.kudos_count result_2 = "K:" + str(kudos_count) + " " # Followers count result_2 += "F:" + str(athlete.follower_count) + " " # Distance in this week today = datetime.date.today() monday = str(today - datetime.timedelta(days=today.weekday())) monday += "T00:00:00Z" distance = 0 for activity in client.get_activities(after = monday, limit=15): # print("{0.name} {0.moving_time} {0.distance}".format(activity)) distance += float(activity.distance) distance /= 1000 distance = round(distance, 1) result_2 += str(distance) + "km" lcd_i2c.lcd_init() lcd_i2c.lcd_string(result_1, lcd_i2c.LCD_LINE_1) lcd_i2c.lcd_string(result_2, lcd_i2c.LCD_LINE_2)
def main(): global menuList global dispShowInfoState global shiftTimeInterval global shiftStartTime global redrawFlag menuList = getDirsAndFiles(".") lcd_i2c.lcd_init() while True: time.sleep(0.005) drawMenu(menuList, "") encoder.getEncoderState(encUp, encDown, shortClick, longClick) # runnung string #if dispShowInfoState: if (time.time() - shiftStartTime) > shiftTimeInterval: shiftStartTime = time.time() redrawFlag = True
def main(): # Accepted arguments parser = argparse.ArgumentParser() parser.add_argument("gpio", help="Pin num of DHT22 sensor", type=int) parser.add_argument("--led", help="Pin num of LED", type=int) parser.add_argument("--max_temp", help="Maximum acceptable temp, default 70F", type=float) parser.add_argument("--min_temp", help="Minimum acceptable temp, default 32F", type=float) parser.add_argument("--max_rh", help="Maximum acceptable humidity, default 50", type=float) parser.add_argument("--min_rh", help="Minimum acceptable humidity, default 30", type=float) parser.add_argument("--email", help="Email destination for warnings") parser.add_argument("--gsheets", help="Turn on Google Sheets logging, must configure", action='store_true') args = parser.parse_args() try: # get lcd ready lcd.lcd_init() lcd.lcd_string("Starting monitor", lcd.LCD_LINE_1) lcd.lcd_string("script...", lcd.LCD_LINE_2) time.sleep(2) lcd.lcd_string(time.strftime("%x"), lcd.LCD_LINE_1) lcd.lcd_string(time.strftime("%I:%M:%S %p"), lcd.LCD_LINE_2) time.sleep(2) # get led gpio pin ready and flash it if args.led: GPIO.setmode(GPIO.BCM) GPIO.setup(args.led, GPIO.OUT) GPIO.output(args.led, True) time.sleep(.4) GPIO.output(args.led, False) # Get temp/humidity reading humidity, temp_c = dht.read_retry(dht.DHT22, args.gpio) fahr = 9.0 / 5.0 * temp_c + 32 # Send reading to LCD lcd.lcd_string("Temp={0:0.2f}'F".format(fahr), lcd.LCD_LINE_1) lcd.lcd_string("Humidity={0:0.2f}%".format(humidity), lcd.LCD_LINE_2) # Check reading for alarm conditions if email is on: warned = warning_condition(fahr, humidity, email=args.email, max_temp=args.max_temp or 70.00, min_temp=args.min_temp or 32.00, max_rh=args.max_rh or 50.00, min_rh=args.min_rh or 30.00) # Write data to file with open("/home/pi/pem-pi/data/temperature_humidity.txt", "a") as myfile: myfile.write(dt.now().strftime('%Y-%m-%d %H:%M') + "\t" + "{0:.2f}".format(fahr) + "\t" + "{0:.2f}".format(humidity)) myfile.write("\n") # optionally, send data to google sheets if args.gsheets: write_spreadsheet([ dt.now().strftime('%Y-%m-%d %H:%M'), "{0:.2f}".format(fahr), "{0:.2f}".format(humidity) ]) except KeyboardInterrupt: print "Quitting..." lcd.lcd_byte(0x01, lcd.LCD_CMD) finally: # clean up GPIO.cleanup()
fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack(b'256s', ifname[:15].encode('utf-8')))[20:24]) def print_ip(): lcd.lcd_string('eth1:', lcd.LCD_LINE_1) try: lcd.lcd_string(get_ip_address('eth1'), lcd.LCD_LINE_2) except: lcd.lcd_string('Not connected', lcd.LCD_LINE_2) try: lcd.lcd_init() print_cluster_info() time.sleep(DISPLAY_DELAY) while True: print_ip() time.sleep(DISPLAY_DELAY) print_number_of_nodes() time.sleep(DISPLAY_DELAY) print_pods_in_openfaas() time.sleep(DISPLAY_DELAY) except KeyboardInterrupt:
line1 = "User String 1" line2 = "User String 2asdfasdf" scrollDelay = 1 # 1 second per refresh # Padding the strings stringLength = max(len(line1), len(line2)) if (stringLength > 16): stringLength += 8 #add some additional spaces to either side line1 = line1.center(stringLength) line2 = line2.center(stringLength) print("Press CTRL+c to quit") try: lcd_i2c.lcd_init() i = 0 while True: if (stringLength <= 16): lcd_i2c.lcd_string(line1, lcd_i2c.LCD_LINE_1) lcd_i2c.lcd_string(line2, lcd_i2c.LCD_LINE_2) else: lcd_i2c.lcd_string(line1[i:i + 16], lcd_i2c.LCD_LINE_1) lcd_i2c.lcd_string(line2[i:i + 16], lcd_i2c.LCD_LINE_2) if i + 16 >= stringLength: i = 0 else: i += 1 time.sleep(scrollDelay) finally: print("Cleaning up...")
def setup(): lcd_i2c.lcd_init()
def setupLCD(): lcd_i2c.lcd_init()
def __init__(self): lcd_i2c.lcd_init()
def main(): #Bring in constants global BME_ADDR global SMBUSID global INTERVAL global THINGSPEAKKEY global THINGSPEAKURL global errors global I2C_ADDR global LCD_WIDTH global pwm_live #Setup errors = 0 #exception counter GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) #Use BCM numbering for pins GPIO.setup(pushButton, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(PUMP, GPIO.OUT, initial=GPIO.LOW) GPIO.add_event_detect(pushButton, GPIO.BOTH) GPIO.add_event_callback(pushButton, BUTTON) bus = smbus.SMBus(SMBUSID) lcd_i2c.lcd_init() MAX31790.initializeMAX(1) try: sensW = bmp280.bmp280Wrapper() except: print BMP280 init FAIL print("Found BMP280 : (%s)" %hex(sensW.chipID)) sensW.resetSensor() # configuration byte contains standby time, filter, and SPI enable. bmp280Config = sensW.tSb62t5 | sensW.filt4 # measurement byte contains temperature + pressure oversampling and mode. bmp280Meas = sensW.osP16 | sensW.osT2 | sensW.modeNormal # Set sensor mode. sensW.setMode(config = bmp280Config, meas = bmp280Meas) while True: try: #pull data from BME lcd_i2c.lcd_string(" UPDATING ",LCD_LINE_1) #display "updating" during thingspeak update (temperature,pressure,humidity)=bme280.readBME280All(BME_ADDR) temperatureF=temperature*(9)/(5)+32 #send to thingspeak server sendData(THINGSPEAKURL,THINGSPEAKKEY,'field1','field2','field3','field4',temperature,pressure,humidity,temperatureF) sys.stdout.flush() # DO THINGS HERE while Waiting for next ThingsSpeak update for i in range(0,INTERVAL*6): (temperature,pressure,humidity)=bme280.readBME280All(BME_ADDR) temperatureF=temperature*(9)/(5)+32 rpm = MAX31790.readRPM(1) #BMP280 TEST sensW.readSensor() print("Pressure : %s Pa" %sensW.pressure) print("Temperature: %s C" %sensW.temperature) #Fan Speed Control Loop templog = "Temp = {:.2f} F | RPM = {:d}".format(temperatureF,rpm) + " | " if temperatureF > 82: MAX31790.setPWMTargetDuty(1, 30) # MAX fan speed templog = templog + "PWM = 70" pwm_live = 80 print templog elif temperatureF > 80: MAX31790.setPWMTargetDuty(1, 40) templog = templog + "PWM = 60" pwm_live = 60 print templog elif temperatureF > 76: MAX31790.setPWMTargetDuty(1, 50) templog = templog + "PWM = 50" pwm_live = 50 print templog elif temperatureF > 72: MAX31790.setPWMTargetDuty(1, 60) templog = templog + "PWM = 40" pwm_live = 40 print templog else: MAX31790.setPWMTargetDuty(1, 70) # MIN fan speed templog = templog + "PWM = 30" pwm_live = 30 print templog # Refresh LCD screen lcd_i2c.lcd_string("PWM = {:.0f} | [{}]".format(pwm_live, time.strftime("%H:%M")),LCD_LINE_1) #update the time lcd_i2c.lcd_string("Tach = {:d} rpm".format(rpm),LCD_LINE_2) lcd_i2c.lcd_string("Temp = {:.1f} F | {:.0f}C".format(temperatureF,temperature),LCD_LINE_3) lcd_i2c.lcd_string("Hum = {:.2f} %".format(humidity),LCD_LINE_4) time.sleep(10) #Error Handling except : errors += 1 print "err cnt: {:d} , delay 5s -> try again".format(errors) #lcd_i2c.lcd_string(" err = {:d} ERROR".format(errors),LCD_LINE_1) #display that an error occured time.sleep(5) continue
def main(): #Bring in constants global DEVICE global SMBUSID global INTERVAL global THINGSPEAKKEY global THINGSPEAKURL global errors global I2C_ADDR global LCD_WIDTH global pwm_live #Setup errors = 0 #exception counter GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) #Use BCM numbering for pins GPIO.setup(18, GPIO.OUT) #GPIO 18 => Output bus = smbus.SMBus(SMBUSID) pwm = GPIO.PWM(18, 25000) #GPIO 18 PWM @ 25kHz pwm.start(0) #set duty cycle to 0 lcd_i2c.lcd_init() while True: try: #pull data from BME lcd_i2c.lcd_string(" UPDATING ", LCD_LINE_1) #display "updtn in top right (temperature, pressure, humidity) = bme280.readBME280All(DEVICE) temperatureF = temperature * (9) / (5) + 32 chirp_moist = chirp.moist chirp_moistPercent = chirp.moist_percent chirp_temp = chirp.temp #send to thingspeak server sendData(THINGSPEAKURL, THINGSPEAKKEY, 'field1', 'field2', 'field3', 'field4', 'field5', 'field6', 'field7', temperature, pressure, humidity, temperatureF, chirp_moist, chirp_moistPercent, chirp_temp) sys.stdout.flush() # DO THINGS HERE while Waiting for next ThingsSpeak update for i in range(0, INTERVAL * 6): # Trigger the sensors and take measurements. chirp.trigger() chirp_moist = chirp.moist chirp_temp = chirp.temp chirp_moistPercent = chirp.moist_percent chirp_light = chirp.light output = '{:d} {:4.1f}% | {:3.1f}°F | {:d}' output = output.format(chirp_moist, chirp_moistPercent, chirp_temp, chirp_light) (temperature, pressure, humidity) = bme280.readBME280All(DEVICE) temperatureF = temperature * (9) / (5) + 32 print(output) #Fan Speed Control Loop templog = "Temp = {:.2f} F".format(temperatureF) + " | " if temperatureF > 82: pwm.ChangeDutyCycle(100) # MAX fan speed templog = templog + "PWM = 100" pwm_live = 100 print templog elif temperatureF > 80: pwm.ChangeDutyCycle(75) templog = templog + "PWM = 75" pwm_live = 75 print templog elif temperatureF > 76: pwm.ChangeDutyCycle(30) templog = templog + "PWM = 30" pwm_live = 30 print templog elif temperatureF > 72: pwm.ChangeDutyCycle(15) templog = templog + "PWM = 15" pwm_live = 15 print templog else: pwm.ChangeDutyCycle(0) # MIN fan speed templog = templog + "PWM =0" pwm_live = 0 print templog #Pirnt all data to LCD screen lcd_i2c.lcd_string("PWM = {:.0f} [{}]".format( pwm_live, time.strftime("%H:%M")), LCD_LINE_1) #update the time lcd_i2c.lcd_string( "Soil = {:d} | {:3.1f}%".format(chirp_moist, chirp_moistPercent), LCD_LINE_2) lcd_i2c.lcd_string( "Temp = {:.2f} | {:.2f}".format(temperatureF, chirp_temp), LCD_LINE_3) lcd_i2c.lcd_string( "Hum = {:.2f}%| {:d}".format(humidity, chirp_light), LCD_LINE_4) time.sleep(10) #Error Handling except: errors += 1 print "err cnt: {:d} , delay 5s -> try again".format(errors) #lcd_i2c.lcd_string(" err = {:d} ERROR".format(errors),LCD_LINE_1) #display that an error occured time.sleep(5) continue
pump_on_timer() break elif GPIO.input(SW) == False: logging.debug('Input SW(rotenc)') time.sleep(0.1) timer_menu() break elif GPIO.input(GreenButton): logging.debug('Input GreenButton') logging.info('Pump turned on locally') TimeOn = datetime.now() pump_on() break if __name__ == "__main__": try: logging.info('rainmaker started') lcd_init() input() # pump_on_timer() # For LCD testing purposes except RuntimeError as error: print(error.args[0]) logging.exception(error.args[0]) GPIO.input(RedLed, HIGH) except KeyboardInterrupt: print("\nExiting application\n") # exit the applications logging.info('rainmaker stopped') GPIO.cleanup()
fan_state = conf['FAN']['fan_speed'] # 팬속 로드 print("설정파일 팬속도: %s" % fan_state) except: print("설정파일 로드 오류") # pwm변수로 지정 if fan_state == "FULL": fan_pwm.value = 1.0 elif fan_state == "MID": fan_pwm.value = 0.65 elif fan_state == "SLOW": fan_pwm.value = 0.3 else: print("설정파일 로드 오류") lcd.lcd_init() # lcd초기화 def Button_Ctrl(): # 버튼 제어 global power_state global fan_state powersw.when_pressed = powerctrl #파워버튼 누르면 실행 fansw.when_pressed = fan_speedsw #팬속도 조정버튼 누르면 실행 pause() # 누를때까지 대기 # 파워 꺼짐: 0, 켜짐: 1, 자동: 2 def powerctrl(): # 전원버튼 누를때마다 실행 global power_state if power_state == 0: # 전원꺼짐 상태일때 전원켬 power_state = 1
GPIO.setmode(GPIO.BOARD) continue_reading = True current_uid = "0" current_name = "THOMAS LYNN" current_balance = 0.0 login_counter = 69 safety_counter = 69 VALVE_OUT = 15 BUTTON_IN = 16 DELTA_BALANCE = .01 LOGIN_COUNTER_START = 69 SAFETY_COUNTER_START = 69 beer_counter = 0 GPIO.setup(VALVE_OUT,GPIO.OUT) GPIO.setup(BUTTON_IN,GPIO.IN) lcd_init() # Keep beers dranken in a file # beer_percentage = 165 - beers dranken/165 *100 def default_display(): lcd_string(" Michelob Ultra ",LCD_LINE_1) #display beer percentage lcd_string(" ",LCD_LINE_2) # Capture SIGINT for cleanup when the script is aborted def end_read(signal,frame): global continue_reading print "Ctrl+C captured, ending read." lcd_byte(0x01, LCD_CMD) continue_reading = False GPIO.cleanup() dbaccessor.closeConnection()
def rover(full_i2c): # Re-direct our output to standard error, we need to ignore standard out # to hide some nasty print statements from pygame sys.stdout = sys.stderr # Setup the PicoBorg Reverse PBR = PicoBorgRev.PicoBorgRev() # Uncomment and change the value if you have changed the board address # PBR.i2cAddress = 0x44 PBR.Init() if not PBR.foundChip: boards = PicoBorgRev.ScanForPicoBorgReverse() if len(boards) == 0: print('No PicoBorg Reverse found, check you are attached :)') else: print('No PicoBorg Reverse at address %02X,' 'but we did find boards:' % (PBR.i2cAddress)) for board in boards: print(' %02X (%d)' % (board, board)) print('If you need to change the I�C address change the setup' 'line so it is correct, e.g.') print('PBR.i2cAddress = 0x%02X' % (boards[0])) sys.exit() # PBR.SetEpoIgnore(True) # Uncomment to disable EPO latch, # # needed if you do not have a switch / jumper # Ensure the communications failsafe has been enabled! failsafe = False for i in range(5): PBR.SetCommsFailsafe(True) failsafe = PBR.GetCommsFailsafe() if failsafe: break if not failsafe: print('Board %02X failed to report in failsafe mode!' % (PBR.i2cAddress)) sys.exit() PBR.ResetEpo() # Settings for the joystick axisUpDown = 1 # Joystick axis to read for up / down position axisUpDownInverted = False # Set this to True if up and down appear to be swapped axisLeftRight = 0 # Joystick axis to read for left / right position axisLeftRightInverted = False # Set this to True if left and right appear to be swapped buttonResetEpo = 4 # Joystick button number to perform an EPO reset (Start) buttonSlow = 0 # Joystick button number for driving slowly whilst held (L2) slowFactor = 0.5 # Speed to slow to when the drive slowly button is held, e.g. 0.5 would be half speed buttonFastTurn = 2 # Joystick button number for turning fast (R2) interval = 0.10 # Time between updates in seconds, smaller responds faster but uses more processor time # buttonRight = 7 # buttonUp = 6 # buttonLeft = 5 # buttonDown = 4 pitch = 0.0 # pitch_delta = 0.02 direction = 0.0 # direction_delta = 0.02 if (full_i2c): time.sleep(1) UB = UltraBorg.UltraBorg() UB.Init() UB.SetServoPosition1(pitch) UB.SetServoPosition2(direction) time.sleep(1) XLoBorg.Init() time.sleep(1) # Initialise display lcd_i2c.lcd_init() cp = compass.Compass() doCalibration = -1 isCalibrated = 0 delayReadCount = 0 # Power settings voltageIn = 12.0 # Total battery voltage to the PicoBorg Reverse voltageOut = 12.0 * 0.95 # Maximum motor voltage, we limit it to 95% to allow the RPi to get uninterrupted power # Setup the power limits if voltageOut > voltageIn: maxPower = 1.0 else: maxPower = voltageOut / float(voltageIn) # Setup pygame and wait for the joystick to become available PBR.MotorsOff() os.environ[ "SDL_VIDEODRIVER"] = "dummy" # Removes the need to have a GUI window pygame.init() # pygame.display.set_mode((1,1)) print('Waiting for joystick... (press CTRL+C to abort)') while True: try: try: pygame.joystick.init() # Attempt to setup the joystick if pygame.joystick.get_count() < 1: # No joystick attached, toggle the LED PBR.SetLed(not PBR.GetLed()) pygame.joystick.quit() time.sleep(0.5) else: # We have a joystick, attempt to initialise it! joystick = pygame.joystick.Joystick(0) break except pygame.error: # Failed to connect to the joystick, toggle the LED PBR.SetLed(not PBR.GetLed()) pygame.joystick.quit() time.sleep(0.5) except KeyboardInterrupt: # CTRL+C exit, give up print('\nUser aborted') PBR.SetLed(True) sys.exit() print('Joystick found') joystick.init() PBR.SetLed(False) try: print('Press CTRL+C to quit') driveLeft = 0.0 driveRight = 0.0 running = True hadEvent = False upDown = 0.0 leftRight = 0.0 # Loop indefinitely while running: # Get the latest events from the system hadEvent = False events = pygame.event.get() # Handle each event individually for event in events: if event.type == pygame.QUIT: # User exit running = False elif event.type == pygame.JOYBUTTONDOWN: # A button on the joystick just got pushed down hadEvent = True elif event.type == pygame.JOYAXISMOTION: # A joystick has been moved hadEvent = True if hadEvent: # Read axis positions (-1 to +1) if axisUpDownInverted: upDown = -joystick.get_axis(axisUpDown) else: upDown = joystick.get_axis(axisUpDown) if axisLeftRightInverted: leftRight = -joystick.get_axis(axisLeftRight) else: leftRight = joystick.get_axis(axisLeftRight) # Apply steering speeds if not joystick.get_button(buttonFastTurn): leftRight *= 0.5 # Determine the drive power levels driveLeft = -upDown driveRight = -upDown if leftRight < -0.05: # Turning left driveLeft *= 1.0 + (2.0 * leftRight) elif leftRight > 0.05: # Turning right driveRight *= 1.0 - (2.0 * leftRight) # Check for button presses if joystick.get_button(buttonResetEpo): PBR.ResetEpo() if joystick.get_button(buttonSlow): driveLeft *= slowFactor driveRight *= slowFactor pitch = joystick.get_axis(4) direction = -joystick.get_axis(3) # if joystick.get_button(buttonUp): # if pitch < 1.0: # pitch += pitch_delta; # if joystick.get_button(buttonDown): # if pitch > -1.0: # pitch -= pitch_delta; # if joystick.get_button(buttonLeft): # if direction > -1.0: # direction -= direction_delta; # if joystick.get_button(buttonRight): # if direction < 1.0: # direction += direction_delta; if (full_i2c): if joystick.get_button(1): if (doCalibration != 1): lcd_i2c.lcd_string("Calibrating...", lcd_i2c.LCD_LINE_1) lcd_i2c.lcd_string("Drive in circles", lcd_i2c.LCD_LINE_2) time.sleep(2) lcd_i2c.lcd_byte( 0x01, lcd_i2c.LCD_CMD) # 000001 Clear display doCalibration = 1 if joystick.get_button(3): if (doCalibration == 1): lcd_i2c.lcd_string("Calibration", lcd_i2c.LCD_LINE_1) lcd_i2c.lcd_string("stopped", lcd_i2c.LCD_LINE_2) time.sleep(2) lcd_i2c.lcd_byte( 0x01, lcd_i2c.LCD_CMD) # 000001 Clear display doCalibration = 0 cp.calibrate_compass() print("number of samples: %d" % len(cp.rawX)) print("D1 origin: %d, scale %d" % (cp.origin_D1, cp.scale_D1)) print("D2 origin: %d, scale %d" % (cp.origin_D2, cp.scale_D2)) isCalibrated = 1 UB.SetServoPosition1(pitch) UB.SetServoPosition2(direction) # UB.SetServoPosition1(upDown) # UB.SetServoPosition2(leftRight) # Set the motors to the new speeds PBR.SetMotor1(driveRight * maxPower) PBR.SetMotor2(-driveLeft * maxPower) print("joystick up/down: %.2f left/right %.2f" % (upDown, leftRight)) print("direction:%.2f pitch: %.2f" % (direction, pitch)) # Change the LED to reflect the status of the EPO latch PBR.SetLed(PBR.GetEpo()) # Wait for the interval period time.sleep(interval) if (doCalibration == 1): mx, my, mz = XLoBorg.ReadCompassRaw() cp.push_calibration_value(mx, my, mz) # print("Raw data: %d %d %d" % (mx, my, mz)) # lcd_i2c.lcd_string("calibrating...",lcd_i2c.LCD_LINE_1) if (isCalibrated == 1): if (delayReadCount < 10): delayReadCount += 1 else: mx, my, mz = XLoBorg.ReadCompassRaw() heading = cp.get_heading(mx, my, mz) # print("Direction: %d" % heading) lcd_i2c.lcd_string("Direction: %d" % heading, lcd_i2c.LCD_LINE_1) delayReadCount = 0 # Disable all drives PBR.MotorsOff() except KeyboardInterrupt: # CTRL+C exit, disable all drives PBR.MotorsOff() if (full_i2c): UB.SetServoPosition1(0.0) UB.SetServoPosition2(0.0)
def app_init(): lcd_i2c.lcd_init() logging.debug('initializing app ')
if(player): gevent.with_timeout(BASE_STATION_VIDEO_TIMEOUT, play_video_for_user, player) lcd_i2c.display_on() gevent.with_timeout(BASE_STATION_TASK_TIMEOUT, check_win_condition, player) else: gevent.with_timeout(BASE_STATION_VIDEO_TIMEOUT, play_video_for_new_user) lcd_i2c.display_on() name = gevent.with_timeout(BASE_STATION_TASK_TIMEOUT, get_keyboard_entry, keyboard_obj, "Enter your name:", 15) initial_choice_past = gevent.with_timeout(BASE_STATION_VIDEO_TIMEOUT, get_initial_choice, keyboard_obj) player = Player(name=name, uid=rfid_data["uid"], initial_choice_past=initial_choice_past) gevent.with_timeout(BASE_STATION_TASK_TIMEOUT, update_rfid_card, player) gevent.with_timeout(BASE_STATION_TASK_TIMEOUT, add_or_update_player, player) lcd_i2c.lcd_string("Refer to map to", lcd_i2c.LCD_LINE_1) lcd_i2c.lcd_string("continue journey", lcd_i2c.LCD_LINE_2) gevent.sleep(5) lcd_i2c.display_off() if __name__ == "__main__": lcd_i2c.lcd_init() lcd_i2c.display_off() keyboard_obj = keyboard.grab_keyboard() while True: try: play(keyboard_obj) except gevent.Timeout: print('Could not complete in timeout!') exit(1)