def loop(): dht = DHT.DHT(DHTPin) #create a DHT class object sumCnt = 0 #number of reading times Blink.setup_led() while (True): sumCnt += 1 #counting number of reading times chk = dht.readDHT11( ) #read DHT11 and get a return value. Then determine whether data read is normal according to the return value. print("The sumCnt is : %d, \t chk : %d" % (sumCnt, chk)) if ( chk is dht.DHTLIB_OK ): #read DHT11 and get a return value. Then determine whether data read is normal according to the return value. print("DHT11,OK!") elif (chk is dht.DHTLIB_ERROR_CHECKSUM): #data check has errors print("DHTLIB_ERROR_CHECKSUM!!") elif (chk is dht.DHTLIB_ERROR_TIMEOUT): #reading DHT times out print("DHTLIB_ERROR_TIMEOUT!") else: #other errors print("Other error!") dht.temperature = dht.temperature * (9 / 5) + 32 print("Humidity : %.2f, \t Temperature : %.2f \n" % (dht.humidity, dht.temperature)) time.sleep(2) Blink.flash_led() LCD.run_lcd(dht.temperature)
def manager_command(): """This function displays a menu on the LCD and based on the selection calls a management function.""" # command = screen.input_lcd("Enter cmd (1-4):") commands = ["Display-Times", \ "Add-Employee", \ "Remove-Employee", \ "Clear-Time Data", \ "Clear-Employee Data",\ "Change-Pin"] selected = screen.input_select_command_list(commands) if selected == commands[3]: confirm = screen.input_lcd("Clear? . cancel") if confirm == "": clear_time_data() elif selected == commands[4]: clear_employee_table() elif selected == commands[1]: confirm = screen.input_lcd("add? . cancel") if confirm == "": add_employee() elif selected == commands[2]: confirm = screen.input_lcd("Remove? . cancel") if confirm == "": remove_employee() elif selected == commands[5]: confirm = screen.input_lcd("Change? . cancel") if confirm == "": change_pin() elif selected == commands[0]: display_times()
class Main(object): _instance = None _motor_control = None _lcd = None _temperature = None _compass = None _light = None _list = None _disabled = False _distance = None def __new__(self): if self._instance is None: self._instance = super(Main, self).__new__(self) self._motor_control = MotorControl() # print(self._motor_control) self._lcd = LCD() self._lcd.start() self._temperature = temperature() self._light = light() self._distance = Distance() self._compass = compass(declination=(1, 19)) return self._instance def disable(self): self._disabled = True def enable(self): self._disabled = False def is_disabled(self): return self._disabled
def remove_employee(): """This function removes an employee from the ID.txt file. This effectively removes them from the system. (their data will still be available in dictionary however)""" # identifier = screen.input_lcd_text("Employee: ") f = open(IDPATH, "r") txt = f.read() f.close() data = txt.split("\n") employees = [] for line in data: e = line.split(":") if len(e) == 3: employees.append(e[2]) identifier = screen.input_select_command_list(employees) confirm = screen.input_lcd("Remove? . confirm") if confirm == ".": for line in data: e = line.split(":") for item in e: if item == str(identifier): data.remove(line) screen.print_lcd("Removed!", 1) time.sleep(2) newdata = [i for i in data if i] f = open(IDPATH, "w") f.write("\n".join(newdata) + "\n") f.close()
def loop(): b = False clear_LCD() count = 3 while True: time.sleep(1) dis = distance() if dis < 100: print('Distance: {} cm'.format(int(dis))) if b: print('Detected, recognizing...') continue wait_LCD() data = {'operation': 200} response = requests.post(URL, json=data) if response.status_code == 201: b = True data = json.loads(response.text) user = str(data['user']) print('{}: {}'.format(user, 'IN' if data['inout'] else 'OUT')) LCD.lcd_string(user, 0x80) animate_inout(data['inout']) else: wait_LCD(retry=True) print('Unknown user') else: count = count - 1 if count == 0: clear_LCD() count = 5 b = False
def setup(): global dht GPIO.setmode(GPIO.BOARD) GPIO.setup(irrigationPin, GPIO.OUT, initial=GPIO.LOW) #Setup relay GPIO.setup(pirPin, GPIO.IN) #Setup pir dht = DHT.DHT(dhtPin) #Setup dht LCD.lcd_setup() #Setup lcd
def processKey(key): state = 0 #State of system code = "" if (len(passcode) == 0): print("Please enter passcode: ") if (len(passcode) < 4 and key != "#"): passcode.append(key) #Appends key to passcode array print(passcode) code = code.join(passcode) #Turns array into string lcd.display_msg(code) #Displays string to LCD if (key == "*"): #If * is pressed it deletes array del passcode[:] lock.append(key) #Appends * to lock array else: del lock[:] if (len(lock) == 3): #If lock length is 3 then put servo down servo1.servo_lock() if (key == "#"): #"#" is the enter button if (Check_Passcode(passcode) == 1 ): #If passcode is true, it sets system state to 2 state = 2 print("Correcct Passcode!!!") lcd.check_pwd_msg(True) #Displays passcode is correct message else: state = 1 #Sets system to 1 if passcode incrorrect print("Incorrect Passcode...") lcd.check_pwd_msg(False) #Displays that passcode is false else: state = 0 if (state == 0): pass if (state == 1): del passcode[:] #Deletes passcode array if system state is 1 if (state == 2): lcd.fingerprint_msg() #Calls fingerprint message finger_print_scan = fingerprint.fingerprint_scan( ) #Returns value based on fingerprint scan if (finger_print_scan == True): #If the scan is true servo1.servo_unlock() #Move servo up, display Access Message, #and delete passcode array print("Access Granted!!") lcd.Access_Msg(True) del passcode[:] else: #If scan is false print("Invalid Fingerprint...") lcd.Access_Msg(False) #Display message and delete passcode array del passcode[:]
def clear_time_data(): """This function clears the time table dictionary for a fresh start""" confirm = screen.input_lcd("clear? . = yes") if confirm == ".": global time_tables time_tables = {} save_time_table() print("data cleared!") sys.stdout.flush() screen.print_lcd("Cleared!", 1) time.sleep(2)
def loop(): space = ' ' greetings = 'Thank you for buying SunFounder Sensor Kit for Raspberry! ^_^' greetings = space + greetings while True: tmp = greetings for i in range(0, len(greetings)): LCD.write(0, 0, tmp) tmp = tmp[1:] time.sleep(0.8) LCD.clear()
def clear_employee_table(): """This function clears the ID.txt file which contains all the emplyees with their pins""" confirm = screen.input_lcd("Confirm? . = yes") if confirm == ".": f = open(IDPATH, "w") f.write("") f.close() screen.print_lcd("Cleared", 1) screen.print_lcd("Employees", 2) time.sleep(2)
def __new__(self): if self._instance is None: self._instance = super(Main, self).__new__(self) self._motor_control = MotorControl() # print(self._motor_control) self._lcd = LCD() self._lcd.start() self._temperature = temperature() self._light = light() self._distance = Distance() self._compass = compass(declination=(1, 19)) return self._instance
def main(): spi = SPI(sck=Pin(18), mosi=Pin(23), miso=Pin(19)) lcd = LCD.LCD(spi, cs=Pin(26), rs=Pin(17), rst=Pin(16), led=Pin(13)) lcd.lcd_clear(lcd.color_white) lcd.set_back_color(lcd.color_blue) lcd.set_point_color(lcd.color_red) lcd.lcd_show_string(0, 0, 12, 'Hello MicroPython', 1)
def display_times(): """This function displays the times of each employee on the lcd. Navigation is done with the arrow keys""" f = open(IDPATH, "r") txt = f.read() f.close() data = txt.split("\n") employees = [] ids = {} for line in data: e = line.split(":") if len(e) == 3: employees.append(e[2]) ids[e[2]] = e[0] name = screen.input_select_command_list(employees) print(time_tables) sys.stdout.flush() try: shift = time_tables[(int(ids[name]), name)][0][1] io = ["In", "Out"] timelist = time_tables[(int(ids[name]), name)] timelist = [str(i[0].strftime("%H:%M:%S")) for i in timelist] timelist = [ i + " " + str(io[ind % 2] + " " + str(ind + 1) + " " + shift) for ind, i in enumerate(timelist) ] screen.input_select_command_list(timelist) except: screen.print_lcd("Error!", 1) screen.print_lcd("No Data", 2) time.sleep(2)
def getPlateInfo(): try: plate = request.form['plate'] data = firestore.getInfoByPlate(plate) Servo.servo() LCD.LCD(plate) response = app.response_class(status=200, response=json.dumps(data), mimetype='application/json') return response except Exception as identifier: LCD.LCD('Ban chua dang ki') print("get errors") print(identifier) return app.response_class(status=500, response=json.dumps( {'message': 'Internal server error'}), mimetype='application/json')
def main(): lcd = LCD() airmon = Airmon("wlan0") airmon.start() main_airdump = Airodump(lcd) main_airdump.start() for x in xrange(100): print str(x) time.sleep(1) main_airdump.stop() print "done"
def get_data(): current = starting_hour hours = 0 #loop until 24 hours while (hours < 24): avg_temp = 0 avg_humidity = 0 for i in range(0, 60, 1): #get one hour of data get_time = time.time() local_humidity = get_dht_humidity() local_temperature = get_dht_temp() avg_temp = avg_temp + local_temperature avg_humidity = avg_humidity + local_humidity console_msg1("DHT data #" + str(i + 1) + ": Temp = " + str(local_temperature) + " Humidity = " + str(local_humidity)) LCD.display_local_data(i + 1, local_temperature, local_humidity) get_time = time.time() - get_time if i is not 59: time.sleep(60 - get_time) #wait one minute avg_temp = avg_temp / 60 avg_humidity = avg_humidity / 60 #calculate average of hourly data and store in array for tracking/display console_msg1("Computing hourly local averages...") print("Avg Temp = " + str(round(avg_temp, 1)) + " Avg Humidity = " + str(round(avg_humidity))) LCD.display_average_data(current, avg_temp, avg_humidity) temp_array[current] = avg_temp humidity_array[current] = avg_humidity print("Local temperature averages: " ) #display all hourly DHT temperature averages print(temp_array) print("Local humidity averages: " ) #display all hourly DHT humidity averages print(humidity_array) time.sleep(60 - get_time) current = (current + 1) % 24 hours = hours + 1
def check_pin(ID, name): """this function asks for the user to enter a pin, if it matches with the pin on file, we return True else we return false""" # Pin = input("Enter Pin: ") Pin = screen.input_lcd("Pin " + str(name)) if Pin == "*": return -1 f = open(IDPATH, "r") txt = f.read() f.close() txt = txt.split("\n") for line in txt: data = line.split(":") if str(ID) == data[0] and Pin == data[1] and name == ''.join( data[2].split()): return 1 return 0
def Archive(self): mylcd = LCD.lcd() db = self._db.dbConnect() Cursor = db.cursor() Cursor.execute( "SELECT DATE_FORMAT(poll_name,'%Y %m %d %H %i %s'),yes_votes,no_votes FROM Polls WHERE closed = 'closed'" ) result = Cursor.fetchall() currDay = datetime.now() with open("Archive", "w") as archive: archive.write("Copy created: {}\n".format(currDay)) archive.write("Date\t\t\t YES\tNO\n") for row in result: archive.write(str(row) + "\n") mylcd.lcd_clear() mylcd.lcd_display_string("Backup DONE", 1) db.close()
def animate_inout(inout): if inout: for i in range(1, 8): start = '{}{}'.format(('>' * i), (' ' * (7 - i))) end = '{}{}'.format((' ' * (7 - i)), ('<' * i)) LCD.lcd_string('{}IN{}'.format(start, end), 0xC0) time.sleep(0.2) else: for i in range(1, 7): end = '{}{}'.format(('>' * i), (' ' * (7 - i))) start = '{}{}'.format((' ' * (7 - i)), ('<' * i)) LCD.lcd_string('{}OUT{}'.format(start, end), 0xC0) time.sleep(0.2) LCD.lcd_string('<<<<<<<OUT>>>>>>', 0xC0)
canTemperature = True while True: data = ser.readline() if(data[1:5] == "DATA"): usrNFC = data[55:62] print(usrNFC) for user in users: if (usrNFC in user.tag): AddNFCEntry(usrNFC) CPrint("An authentificated user has pass his RFID Tag") if("1" in getStateAlarm()): CPrint("!!!! Requested alarm to shut down") modifyAlarm("0") grovepi.digitalWrite(buzzer, 0) LCD.setAll("Alarme desactivee", "green") elif ("0" in getStateAlarm()): CPrint("!!!! Requested alarm to turn on in 15 seconds") LCD.setAll("L'alarm va s'enclencher dans 15s", "orange") time.sleep(15) modifyAlarm("1") LCD.setAll("Alarme activee", "red") time.sleep(2) elif(data[1:5] == "NULL"): AddNFCEntry("0") LCD.setAll("Aucun id associe. Incident enregistre", "red") ''' elif len(data) >= 4: if data[0:2] == "49": #Motion PIR if "1" in getStateAlarm():
class myConfig(object): logger = '' display = LCD.display() device = 1 restTime = 0.05 timeout = 30 encoder_conv = 0.00049126 # encoder to inch conversion, update from json linuxPath = os.path.dirname(__file__) myPlatform = False logPath = '/log/' # log files storage path sysPath = '/system/' # system files storage path hwcfg = '/hwcfg/' # library of all json configurations usbPath = '/media/usb0/' usb_logpath = 'log/' # usb file path excel = 'log.csv' logfile = linuxPath + logPath settingsFile = linuxPath + sysPath + "settings.json" log = "event.log" test_completed = -1 grillType = 0 # load from SIB jsonFile = linuxPath + hwcfg + str(grillType) + ".json" loadReg_enable = [ 1, 1, 1, 1 ] # load register function, 1 for enable [motionPID, heaterPID, level sensors] test_enable = [0, 0, 0, 0, 0, 0, 0] # selection for test execution customer = 1 # 1 description = "unknown" # load from json file sync_role = 0 # storage json_test_config = '' voltage_config = '' platen_config = '' actuator_config = '' switch_config = '' phase_status = '' supply_voltage = '' switch = [0, 0] time_elapse = [0, 0] killsw_enc = [0, 0] magnet = [0, 0, 0] sensor = [0, 0] ZDBF = -0 gap = [0, 0] grill_plate = 0 error = [0, 0, 0, 0, 0, 0, 0, 0] motor_range = [0, 0, 0] motor_limit = [0, 0, 0, 0, 0] newZDBF = 0 def updateJSON(self, grillType): self.jsonFile = self.linuxPath + self.hwcfg + str(grillType) + ".json" def updateSettings(self): timestr = time.strftime("%Y%m%d-%H%M%S") if platform == "linux" or platform == "linux2": # linux self.myPlatform = True self.logger.info("Script running on Linux platform, LCD enabled") elif platform == "darwin": # OS X self.myPlatform = False self.logger.info("Script running on OS X platform, LCD disabled") elif platform == "win32" or platform == "cygwin": # Windows... self.myPlatform = False self.logger.info( "Script running on windows platform, LCD disabled") if self.myPlatform == False: return if os.path.exists(self.linuxPath + self.sysPath + 'image') == True: os.popen('rm ' + self.linuxPath + self.sysPath + 'image') if os.path.exists(self.usbPath + self.excel) == True: if os.path.exists(self.logfile + self.excel) == True: self.logger.info("Previous log.csv file copied to USB path...") self.display.fb_long_print( "Previous log.csv file copied to USB path...", 0) os.popen('mv ' + self.logfile + self.excel + ' ' + self.usbPath + timestr + '-' + self.excel) os.popen('cp ' + self.usbPath + self.excel + ' ' + self.logfile + self.excel) if os.path.exists(self.usbPath + 'settings.json') == True: os.popen('cp ' + ' ' + self.usbPath + 'settings.json' + ' ' + self.settingsFile) self.logger.info("EOL settings updated...") self.display.fb_clear() self.display.fb_long_print("EOL settings updated...", 0) if os.path.exists(self.usbPath + 'hwcfg/*.json') == True: os.popen('cp ' + ' ' + '-u' + ' ' + self.usbPath + 'hwcfg/*.json' + ' ' + self.linuxPath + 'hwcfg/') self.logger.info("json files updated...") self.display.fb_clear() self.display.fb_long_print("json files updated...", 0) else: self.logger.info("No updated required...") self.display.fb_clear() self.display.fb_long_print("No updated required...", 0) def copyLog(self): timestr = time.strftime("%Y%m%d-%H%M%S") if os.path.isfile(self.logfile + self.log) == True: os.popen('mv ' + self.logfile + self.log + ' ' + self.linuxPath + self.logPath + timestr + '-' + str(self.grillType) + '.log') if os.path.exists(self.usbPath + self.usb_logpath) == True: try: self.logger.info("Test logs copy to USB path") except AttributeError: pass os.popen('mv ' + self.logfile + '*.log' + ' ' + self.usbPath + self.usb_logpath) self.display.fb_println("Test logs copied to USB path", 0) else: try: self.logger.info("USB log path not found") except AttributeError: pass self.display.fb_println("USB log path not found", 0) os.popen('mv ' + self.logfile + self.log + ' ' + self.linuxPath + self.logPath + timestr + '-' + str(self.grillType) + '.log') def writeToCSV(self): datestr = time.strftime('%Y/%m/%d') timestr = time.strftime('%H:%M:%S') with open(self.logfile + self.excel, 'a') as test: fieldnames = ('date', 'time', 'grill_type', 'linel', 'line2', 'line3', '24supply', '12supply', '5supply', '3_3supply', 'timeUpwards', 'timeDownwards', 'grill_plate', 'lift_sw', 'home_sw', 'up_killsw', 'down_killsw', 'dist_up', 'dist_dwn', 'max_drift', 'rear_sensor', 'front_sensor', 'zdbf', 'lvl_motor_pos', 'lvl_motor_upper_range', 'lvl_motor_lower_range', 'new_zdbf', 'test_completed') targetWriter = csv.DictWriter(test, delimiter=',', lineterminator='\n', fieldnames=fieldnames) headers = dict((n, n) for n in fieldnames) #targetWriter.writerow(headers) targetWriter.writerow({ 'date': datestr, 'time': timestr, 'grill_type': self.grillType, 'linel': str(self.supply_voltage[4] / 10.0), 'line2': str(self.supply_voltage[5] / 10.0), 'line3': str(self.supply_voltage[6] / 10.0), '24supply': str(float(self.supply_voltage[0]) / 100), '12supply': str(float(self.supply_voltage[1]) / 100), '5supply': str(float(self.supply_voltage[2]) / 100), '3_3supply': str(float(self.supply_voltage[3]) / 100), 'timeUpwards': str(round(self.time_elapse[0], 3)), 'timeDownwards': str(round(self.time_elapse[1], 3)), 'grill_plate': str(self.grill_plate), 'lift_sw': str(self.switch[0]), 'home_sw': str(self.switch[1]), 'up_killsw': str(self.killsw_enc[0]), 'down_killsw': str(self.killsw_enc[1]), 'dist_up': str(self.magnet[0]), 'dist_dwn': str(self.magnet[1]), 'max_drift': str(self.magnet[2]), 'rear_sensor': str(round(commonFX.baumerToThou(self.sensor[0]), 3)), 'front_sensor': str(round(commonFX.baumerToThou(self.sensor[1]), 3)), 'zdbf': str(self.ZDBF), 'lvl_motor_pos': str(round(self.motor_limit[0], 3)), 'lvl_motor_upper_range': str(round(self.motor_limit[1], 3)), 'lvl_motor_lower_range': str(round(self.motor_limit[2], 3)), 'new_zdbf': str(self.newZDBF), 'test_completed': str(self.test_completed) }) test.close() def report(self): self.logger.info("< Test Results >") self.logger.info("Line 1 (V): %r" % (self.supply_voltage[4] / 10.0)) self.logger.info("Line 2 (V): %r" % (self.supply_voltage[5] / 10.0)) self.logger.info("Line 3 (V): %r" % (self.supply_voltage[6] / 10.0)) self.logger.info("24V supply (V): %r" % (float(self.supply_voltage[0]) / 100)) self.logger.info("12V supply (V): %r" % (float(self.supply_voltage[1]) / 100)) self.logger.info("5V supply (V): %r" % (float(self.supply_voltage[2]) / 100)) self.logger.info("3.3V supply (V): %r" % (float(self.supply_voltage[3]) / 100)) self.display.fb_clear() self.display.fb_println("< Test Results > ", 1) self.display.fb_println( "Line 1 (V): %r" % (self.supply_voltage[4] / 10.0), 0) self.display.fb_println( "Line 2 (V): %r" % (self.supply_voltage[5] / 10.0), 0) self.display.fb_println( "Line 3 (V): %r" % (self.supply_voltage[6] / 10.0), 0) # self.display.fb_println("24V supply (V): %r" % (float(self.supply_voltage[0]) / 100), 0) # self.display.fb_println("12V supply (V): %r" % (float(self.supply_voltage[1]) / 100), 0) # self.display.fb_println("5V supply (V): %r" % (float(self.supply_voltage[2]) / 100), 0) # self.display.fb_println("3.3V supply (V): %r" % (float(self.supply_voltage[3]) / 100), 0) if self.test_enable[0] == 1 or self.test_enable[1] == 1: self.logger.info("Time elapse upwards (sec): %r" % round(self.time_elapse[0], 3)) self.logger.info("Time elapse downwards (sec): %r" % round(self.time_elapse[1], 3)) self.display.fb_println( "Time elapse upwards (sec): %r" % round(self.time_elapse[0], 3), 0) self.display.fb_println( "Time elapse downwards (sec): %r" % round(self.time_elapse[1], 3), 0) if self.error[0] == 0: self.display.fb_println( "Grill plate to Home (inch): %r" % self.grill_plate, 0) else: self.display.fb_println( "Grill plate to Home (inch): %r >tolerance" % self.grill_plate, 0) if self.error[1] != 1: self.display.fb_println( "Lift switch location (inch): %r" % self.switch[0], 0) else: self.display.fb_println( "Lift switch location (inch): %r >tolerance" % self.switch[0], 1) if self.error[2] != 1: self.display.fb_println( "Home switch location (inch): %r" % self.switch[1], 0) else: self.display.fb_println( "Home switch location (inch): %r >tolerance" % self.switch[1], 1) if self.error[3] != 1: self.display.fb_println( "Upper killsw location(inch): %r" % self.killsw_enc[0], 0) else: self.display.fb_println( "Upper killsw location(inch): %r >tolerance" % self.killsw_enc[0], 1) if self.error[4] != 1: self.display.fb_println( "Lower killsw location(inch): %r" % self.killsw_enc[1], 0) else: self.display.fb_println( "Lower killsw location(inch): %r >tolerance" % self.killsw_enc[1], 1) if self.test_enable[2] == 1: self.logger.info("Distance moving down (count): %r" % self.magnet[0]) self.logger.info("Distance moving up (count): %r" % self.magnet[1]) self.logger.info("Max Drift count (count): %r" % self.magnet[2]) self.display.fb_println( "Distance moving down (count): %r" % self.magnet[0], 0) self.display.fb_println( "Distance moving up (count): %r" % self.magnet[1], 0) self.display.fb_println( "Max Drift count (count): %r" % self.magnet[2], 0) if self.test_enable[4] == 1: self.logger.info("Rear sensors gap (mil) %r" % round(commonFX.baumerToThou(self.sensor[0]), 3)) self.logger.info("Front sensors gap (mil) %r" % round(commonFX.baumerToThou(self.sensor[1]), 3)) self.display.fb_println( "Rear sensors gap (mil) %r" % round(commonFX.baumerToThou(self.sensor[0]), 3), 0) self.display.fb_println( "Front sensors gap (mil) %r" % round(commonFX.baumerToThou(self.sensor[1]), 3), 0) if self.test_enable[5] == 1: self.logger.info("ZDBF: %r" % self.ZDBF) self.display.fb_println( "ZDBF: %r" % self.ZDBF, 0) if self.test_enable[6] == 1: up_limit = round( commonFX.baumerToThou(self.motor_range[0]) - self.platen_config[6][1], 3) low_limit = round( commonFX.baumerToThou(self.motor_range[0]) + self.platen_config[6][1], 3) self.logger.info("Level motor position (mil): %r" % round(self.motor_limit[0], 3)) self.display.fb_println( "Level motor position (mil): %r" % round(self.motor_limit[0], 3), 0) if self.error[5] == 1: self.logger.info("upper travel range (mil): %r > %r" % (round(self.motor_limit[1], 3), up_limit)) self.display.fb_println( "upper travel range (mil): %r > %r" % (round(self.motor_limit[1], 3), up_limit), 1) else: self.logger.info("upper travel range (mil): %r" % round(self.motor_limit[1], 3)) self.display.fb_println( "upper travel range (mil): %r" % round(self.motor_limit[1], 3), 0) if self.error[6] == 1: self.logger.info("lower travel range (mil): %r < %r" % (round(self.motor_limit[2], 3), low_limit)) self.display.fb_println( "lower travel range (mil): %r < %r" % (round(self.motor_limit[2], 3), low_limit), 1) else: self.logger.info("lower travel range (mil): %r" % round(self.motor_limit[2], 3)) self.display.fb_println( "lower travel range (mil): %r" % round(self.motor_limit[2], 3), 0) self.logger.info("New ZDBF: %r " % self.newZDBF) self.display.fb_println( "New ZDBF: %r " % self.newZDBF, 0) if 1 in self.error: self.test_completed = 0 self.logger.info("Tolerances not in range, adjustment required") self.display.fb_long_print( "Tolerances not in range, adjustment required", 1) else: self.test_completed = 1 self.logger.info("< Equipment passed all test requirements >") self.display.fb_println( "< Equipment passed all test requirements >", 1) self.writeToCSV() def calculate(self): error = [0, 0, 0, 0, 0, 0, 0, 0] if self.test_enable[0] == 1 or self.test_enable[1] == 1: home_sw = commonFX.encToInch(self.switch[1], self.encoder_conv) grill_plate = home_sw - commonFX.encToInch(self.gap[0]) lift_sw = home_sw - commonFX.encToInch(self.switch[0], self.encoder_conv) killsw_high = home_sw - commonFX.encToInch(self.killsw_enc[0], self.encoder_conv) killlsw_low = home_sw - commonFX.encToInch(self.killsw_enc[1], self.encoder_conv) self.logger.info("Raw output:{%r, %r, %r, %r, %r}" % (self.gap[0], self.switch[0], self.switch[1], self.killsw_enc[0], self.killsw_enc[1])) self.logger.info("grill plate to home sw (inch): %r" % grill_plate) self.logger.info("lift switch location (inch): %r" % lift_sw) self.logger.info("home switch location (inch): %r" % home_sw) self.logger.info("upper killsw location (inch): %r" % killsw_high) self.logger.info("lower killsw location (inch): %r" % killlsw_low) if commonFX.rangeCheck(round(grill_plate, 3), self.switch_config[1], self.switch_config[0]) != True: self.logger.info( "grill plate to home distance not in range, target: %r +/- %r%%" % (self.switch_config[1], self.switch_config[0] * 100)) error[0] = -1 if commonFX.rangeCheck(round(lift_sw, 3), self.switch_config[2], self.switch_config[0]) != True: self.logger.info( "lift switch location not in range, target: %r +/- %r%%" % (self.switch_config[2], self.switch_config[0] * 100)) error[1] = 1 if commonFX.rangeCheck(round(home_sw, 1), self.switch_config[3], self.switch_config[0]) != True: self.logger.info( "home switch location not in range, target: %r +/- %r%%" % (self.switch_config[3], self.switch_config[0] * 100)) error[2] = 1 if commonFX.rangeCheck(round(killsw_high, 3), self.switch_config[4], self.switch_config[0]) != True: self.logger.info( "upper kill switch location not in range, target: %r +/- %r%%" % (self.switch_config[4], self.switch_config[0] * 100)) error[3] = 1 if commonFX.rangeCheck(round(killlsw_low, 3), self.switch_config[5], self.switch_config[0]) != True: self.logger.info( "lower kill switch location not in range, target: %r +/- %r%%" % (self.switch_config[5], self.switch_config[0] * 100)) error[4] = 1 self.grill_plate = round(grill_plate, 3) self.switch = [round(lift_sw, 3), round(home_sw, 3)] self.killsw_enc = [round(killsw_high, 3), round(killlsw_low, 3)] if self.test_enable[6] == 1: position = commonFX.baumerToThou(self.motor_range[0]) upper_limit = position - self.platen_config[6][0] lower_limit = position + self.platen_config[6][1] if commonFX.baumerToThou( self.motor_range[1] ) <= upper_limit and commonFX.baumerToThou( self.motor_range[2]) >= lower_limit: self.logger.info("level motor position in range") if commonFX.baumerToThou(self.motor_range[1]) > upper_limit: self.logger.info("upper travel limit not in range of %r" % round(upper_limit, 3)) error[5] = 1 else: self.logger.info("upper travel limit within range of %r" % round(upper_limit, 3)) if commonFX.baumerToThou(self.motor_range[2]) < lower_limit: self.logger.info("lower travel limit not in range of %r" % round(lower_limit, 3)) error[6] = 1 else: self.logger.info("lower travel limit within range of %r" % round(lower_limit, 3)) self.error = error
t_DHT = None print("starting DHT thread") t_DHT = threading.Thread(target=DHT.loop) t_DHT.daemon = True t_DHT.start() t_LCD = None print("starting LCD Thread") t_LCD = threading.Thread(target=LCD.display_cimis) t_LCD.daemon = True t_LCD.start() while (True): #function loops forever time.sleep(0.1) def destroy(): GPIO.output(relayPin, True) GPIO.output(ledPin, GPIO.LOW) GPIO.cleanup() # main function to start program if __name__ == '__main__': print("Program starting...") setup() try: loop() except KeyboardInterrupt: LCD.destroy() destroy() exit()
import LCD import time import RPi.GPIO as GPIO print("Hello") temp = LCD.HD44780() temp.message("Hello\nWorld!") time.sleep(5) temp.clear() GPIO.cleanup()
import LCD from machine import freq, SPI, Pin, PWM, ADC, Timer import time from flaglib import * freq(160000000) spi = SPI(1, baudrate=40000000, polarity=0, phase=0) lcd = LCD.LCD(spi, 15, 5, 0) lcd.init() lcd.setRotation(4) lcd.clearLCD() adc = ADC(0) button = Pin(4, Pin.IN, Pin.PULL_UP) buzzer = PWM(Pin(12)) left_pixels_1 = (b" 1 1 11 " b" 11 11 11 " b" 111111111 1 " b" 11 111 11 11 " b"111 111 11111 1 11 " b" 1111 1111 11 1 111 " b"1111 111111111111 " b" 1111111 111111111 " b" 1111111111 " b" 111111111111 " b" 11 11 ") left_pixels_2 = (b" 1 1 11 " b" 11 11 11 " b" 111111111 1 "
GPIO.setup(25, GPIO.IN) #in GPIO.setup(22, GPIO.IN) #servo track = 0 status = False while True: sensorIn = GPIO.input(25) sensorTracking = GPIO.input(22) if sensorIn == 0 and track == 0: print("F**k") plate = detect.get_plate() if plate != "": status = firestore.getInfoByPlate(plate) if status != False: moneyBack = status["money"] - 5000 firestore.updateDB(plate, moneyBack, status["status"]) sleep(0.1) Servo.openServo() LCD.LCD(plate) track = track + 1 else: LCD.LCD("Bien so ko hop le") else: LCD.LCD("Bien so ko hop le") if sensorTracking == 0 and track == 1: track = 0 if sensorIn == 1 and sensorTracking == 1 and track == 0: Servo.closeServo() print("This is 0") sleep(0.1)
while True: try: if ("1" in getStateAlarm()): #Alarm is on a = grovepi.digitalRead(alarm) i = i + 1 if (a == 1): t = t +1 if(i > 50): t = 0 i = 0 if (t > 4): t = 0 #Movement detected CPrint("!!!! Movement detected. Waiting 10 sec for desactivating") LCD.setAll("Passez votre tag", "purple") time.sleep(waitingTime) #Is alarm still on ? if ("1" in getStateAlarm()): #Yes CPrint("!!!! Intruder in the building !") #grovepi.digitalWrite(buzzer, 1) if(debugMode): nowDate = time.strftime('%d/%m a %H:%S') send.sendSMSToStaff("Alarme declenche a " + nowDate) else: timeshot = time.time() insertMov(alarm, timeshot) addTimeshot(timeshot) os.kill(int(camera), signal.SIGUSR1)
import bluetooth import servo1 #Imports servo code that uses pigpio library import LCD as lcd #Imports LCD code server_socket=bluetooth.BluetoothSocket( bluetooth.RFCOMM ) #Sets server socket to Radio Frequency Communication server_socket.bind(("",1)) #Binds socket to channel 1 server_socket.listen(1) #Listens to channel 1 client_socket,address = server_socket.accept() #Waits until a connection is established until #code continues to execute. print "Accepted connection from ",address #Prints the addres lcd.connection() #Calls a function from the LCD code to #display the phone has been connected. #Continously receives data from the client socket while 1: data = client_socket.recv(1024) print "Received: %s" % data #Prints the data if(data == "1"): servo1.servo_unlock() #If 1 is received calls servo_unlock to move the servo up lcd.unlock() #Displays to LCD that door is unlocked if(data == "0"): servo1.servo_lock() #If 0 is received calls servo_lock to move the servo down lcd.lock() #Displays to LCD that door is locked client_socket.close() #Closes client socket connection server_socket.close() #Turns off the bluetooth server
def __init__(self): self.lcd = LCD() self.rogue_aps = []
def clear_LCD(): LCD.lcd_string("---- HELLO -----", 0x80) LCD.lcd_string("________________", 0xC0)
#!/usr/bin/env python from imapclient import IMAPClient import time import RPi.GPIO as GPIO import LCD import SimpleMFRC522 import re reader = SimpleMFRC522.SimpleMFRC522() lcd = LCD.lcd() HOSTNAME = "imap.gmail.com" USERNAME = "" PASSWORD = "" MAILBOX = "" DEBUG = True NEWMAIL_OFFSET = 1 MAIL_CHECK_FREQ = 10 def loop(): global USERNAME, PASSWORD, MAILBOX, HOSTNAME, lcd lcd.lcd_clear() lcd.lcd_display_string('Please tap your card', 1) id, text = reader.read() if id == 142668869250:
def Adafruit_CharLCDBackpack(address): return LCD() def __init__(self): pass
def wait_LCD(retry=False): LCD.lcd_string(' Retrying...' if retry else ' Recognizing..', 0x80) LCD.lcd_string(' Please Wait..', 0xC0)
# @description: Tweeno deamon functions # import twitter import time # - project spesifict import import config import functions import LCD import fetch c = config.Config() t = fetch.tweet(c) #d = LCD.p160_128(c.s_port, 57600) d = LCD.p400_240(c.s_port, 115200) oldMessage = None while True: data = t.fetchNewMessage() asciiMessage = t.asciiMe(data[0]) if not asciiMessage == oldMessage: print asciiMessage + "\nBy @:" + data[1] oldMessage = asciiMessage d.clear() d.send(asciiMessage) d.byline(data[1]) d.end() time.sleep(30)
def main(): # This is the main bit of the program that runs all of the above in the correct order # It also prints helpful messages at each stage of the process or error messages if something goes wrong mySettings = getSettings() print 'Capturing... \nInterval = %s ms \nDuration = %s ms \n' % (mySettings[0], mySettings[1]) LCD.colour([0,1,0]) LCD.display("TIMELAPSE.PY\nI:%ss D:%ss" % (mySettings[0]/1000, mySettings[1]/1000)) if capture(mySettings[0], mySettings[1]) == True: print 'Capture complete' LCD.display("TIMELAPSE.PY\nCompiling video") list() print 'Compiling... (this may take some time)\n' if mencoder() == True: print '\nCompile successful' LCD.display("TIMELAPSE.PY\nVideo ready") time.sleep(1) if delete == True: print 'Deleting frames...' os.system('sudo rm %s*' % filename) os.system('sudo rm stills.txt') print 'Done!' LCD.display("TIMELAPSE.PY\nExit program") time.sleep(1) else: print 'ERROR: Compile unsuccessful, problem with MEncoder' LCD.display("TIMELAPSE.PY\nMEncoder error") else: print 'ERROR: Capture unsuccessful, problem with raspistill' LCD.display("TIMELAPSE.PY\nRaspistill error") LCD.off()
class MenuSystem: iwconfig_bin = "/sbin/iwconfig" def __init__(self): self.lcd = LCD() self.rogue_aps = [] def wlan_menu(self): wireless_cards = [] current_pointer = 0 wlan = subprocess.Popen([self.iwconfig_bin], stdout=subprocess.PIPE, stderr=subprocess.PIPE) while True: line = wlan.stdout.readline() if not line: break elif "wlan" in line: wireless_cards.append(line.split(" ")[0]) if wireless_cards > 0: self.lcd.display("Select wlan:\n{0}".format(wireless_cards[current_pointer])) while True: result = self.lcd.get_button_press() if result == "Up": current_pointer -= 1 if abs(current_pointer) == len(wireless_cards): current_pointer = 0 self.lcd.display("Select wlan:\n{0}".format(wireless_cards[current_pointer])) elif result == "Down": current_pointer += 1 if abs(current_pointer) == len(wireless_cards): current_pointer = 0 self.lcd.display("Select wlan:\n{0}".format(wireless_cards[current_pointer])) elif result == "Select": self.lcd.display("Starting\nDetection") self.airmon = Airmon(wireless_cards[current_pointer]) self.airmon.start() self.airodump_main = Airodump(self.lcd) self.airodump_main.start() break def main_menu(self): list = ['View Rogues','Update Whitelist','Backup Files','Clear Rogues','Restart Monitoring'] current_pointer = 0 secret_counter = 0 tone = FrequencyGenerator() while True: self.lcd.display("Main Menu:\n{0}".format(list[current_pointer])) result = self.lcd.get_button_press() if result == "Up": current_pointer -= 1 if abs(current_pointer) == len(list): current_pointer = 0 elif result == "Down": current_pointer += 1 if abs(current_pointer) == len(list): current_pointer = 0 elif result == "Left": secret_counter += 1 if secret_counter == 3: self.lcd.set_color("green") tone.zelda_secret() secret_counter = 0 elif result == "Select": if list[current_pointer] == 'Update Whitelist': result = self.airodump_main.update_whitelist() self.lcd.display(result, 2) elif list[current_pointer] == 'Backup Files': result = self.airodump_main.backup_files() self.lcd.display(result, 2) elif list[current_pointer] == 'View Rogues': self.networks_menu() elif list[current_pointer] == 'Clear Rogues': self.airodump_main.clear_rogues() self.lcd.display("Rogues cleared", 2) elif list[current_pointer] == 'Restart Monitoring': self.lcd.display("Restarting") self.airmon.restart() self.airodump_main.restart() self.lcd.display("Restarted", 2) def networks_menu(self): rogue_aps = self.airodump_main.rogue_aps if len(rogue_aps) < 1: self.lcd.display("No Rogue APs", 2) return current_pointer = 0 self.lcd.display("Potential Target\n{0}".format(rogue_aps[current_pointer][0])) while True: rogue_aps = self.airodump_main.rogue_aps result = self.lcd.get_button_press() if result == "Up": current_pointer -= 1 if abs(current_pointer) == len(rogue_aps): current_pointer = 0 self.lcd.display("Potential Target\n{0}".format(rogue_aps[current_pointer][0])) elif result == "Down": current_pointer += 1 if abs(current_pointer) == len(rogue_aps): current_pointer = 0 self.lcd.display("Potential Target\n{0}".format(rogue_aps[current_pointer][0])) elif result == "Left": break elif result == "Select": self.airodump_main.stop() target_airodump = Airodump(self.lcd, rogue_aps[current_pointer][0], rogue_aps[current_pointer][1], rogue_aps[current_pointer][2]) target_airodump.locate() self.lcd.display("Potential Target\n{0}".format(rogue_aps[current_pointer][0])) self.airodump_main.start()
from machine import ADC, SPI, PWM, Pin, freq from FlagArcade import * import LCD # 螢幕初始設定 spi = SPI(1, baudrate=40000000) screen = LCD.LCD(spi, 15, 5, 0) screen.init() screen.clearLCD() # 按鈕腳位設定 adc = ADC(0) # 蜂鳴器腳位與強度設定 buzzer = PWM(Pin(4)) amp = 512 # 設計遊戲音效 def ding(): buzzer.freq(988) buzzer.duty(amp) time.sleep(.05) buzzer.duty(0) def toot(): buzzer.freq(494) buzzer.duty(amp) time.sleep(.01) buzzer.duty(0)
#print "LCD.func1() output:" #print lightsDebug #print numbersDebug #print boxesDebug #print "Program initializes" loopExecutions = 1 while loopExecutions != 0: #DEBUGGING: lighting = 0 numArrays = 4 numSpeakPerArray = 8 lighting, numArrays, numSpeakPerArray = LCD.func1() if True: #print "Beginning scan" #print "currentPhysicalPan = ", currentPhysicalPan stops = 9 stopsIncr = 0 while(stopsIncr != stops): # 9 executions, covering 20 - 340 degrees, in 40 degree increments # Start scanning at 20 degrees clockwise (looking down from top) if(stopsIncr == 0): targetPan += 20 #print "Moving to my first starting position of targetPan = ", targetPan howMuchPanned = targetPan - currentPhysicalPan #print "Moving ", howMuchPanned, " to targetPan = ", targetPan #UNCOMMENT OUT THE FOLLOWING 1 LINE WHEN YOU'RE READY currentPhysicalPan = SetTargetPosition(targetPan, currentPhysicalPan, motorPan)