def main(): """ Основной блок программы Main program block :return: None """ # 10k trim pot connected to adc #1 # Потенциометр подключен на первый вход АЦП potentiometer_adc = 7 last_read = 0 # Переменная отслеживает последнее считанное с потенциометра значение tolerance = 7 # Минимальное изменение значения. Новое значение с потенциометра будем # считывать только тогда, когда разница между текущим и предудущим значением # будет больше tolerance. Необходимо для устранения дребезжания MAX_VALUE = 1023 ##################################################################### # Все порты к дисплею устанавливаем на вывод: GPIO.setup(LCD_E , GPIO.OUT) # E GPIO.setup(LCD_RS, GPIO.OUT) # RS GPIO.setup(LCD_D4, GPIO.OUT) # DB4 GPIO.setup(LCD_D5, GPIO.OUT) # DB5 GPIO.setup(LCD_D6, GPIO.OUT) # DB6 GPIO.setup(LCD_D7, GPIO.OUT) # DB7 # Инциализируем дисплей lcd.init() # Устанавливаем режимы пинов интерфейса SPI # set up the SPI interface pins GPIO.setup(SPIMOSI, GPIO.OUT) GPIO.setup(SPIMISO, GPIO.IN) GPIO.setup(SPICLK, GPIO.OUT) GPIO.setup(SPICS, GPIO.OUT) potentiometer_adc = 7 last_read = 0 # Переменная отслеживает последнее считанное с потенциометра значение tolerance = 7 # Минимальное изменение значения. Новое значение с потенциометра будем # считывать только тогда, когда разница между текущим и предудущим значением # будет больше tolerance. Необходимо для устранения дребезжания while True: user_input = input() if user_input == 'e': break # Считываем очередное значение с АЦП hum_raw_value = adc.readadc(potentiometer_adc, SPICLK, SPIMOSI, SPIMISO, SPICS) hum_value = abs(hum_raw_value - 1023) percent = round(hum_value * 100.0 / MAX_VALUE) lcd.string(' Humidity = {hum}%' .format(hum = percent), LCD_LINE_1)
def tare(): global baseValue global taredWeight lcd.clear() lcd.string("Taring weight...", LINE_1) lcval = lc.read_average_value(10) diff = math.fabs(baseValue - lcval) taredWeight = (diff / 49000.0) * 230.0 #store the calculated weight in variable
def show_choices(names, percentages, primary_keys, display_percentages=True, short_names=True): lcd.clear() print("Options:") options, pks = generate_options(names, percentages, primary_keys, display_percentages, short_names) last_idx = len(options) - 1 print(options) curr_start_idx = 0 key = '' while True: option = options[curr_start_idx] for i in range(0, len(option)): lcd.string(option[i], LINES[i]) time.sleep(0.2) while True: key = kpad.get_key() for i in range(1, len(option) + 1): if key == str(i): time.sleep(0.1) return pks[curr_start_idx][i - 1] if key == '*': lcd.clear() time.sleep(0.1) if curr_start_idx == last_idx: curr_start_idx = 0 elif curr_start_idx < last_idx: curr_start_idx = (curr_start_idx + 1) break if key == '#': lcd.clear() time.sleep(0.1) if curr_start_idx == 0: curr_start_idx = last_idx elif curr_start_idx >= 1: curr_start_idx = (curr_start_idx - 1) break if key == 'A': while True: cropIDAccepted, pk_manual = acceptManualCropID() if cropIDAccepted: return pk_manual else: return show_choices(names, percentages, primary_keys)
def init(): print("Initialization") global baseValue #initialize lcd lcd.lcd_init() lcd.string(" Welcome", LINE_1) lcd.string(" Remove any object", LINE_2) lcd.string(" from the platform.", LINE_3) time.sleep(2) lcd.clear() lcd.string(" Calibrating", LINE_1) lcd.string(" Please wait...", LINE_2) baseValue = lc.base_value()
def init(): "initialization function" global baseValue lcd.string(" Welcome", LINE_1) lcd.string(" Remove any object", LINE_2) lcd.string(" from the platform.", LINE_3) time.sleep(5) lcd.clear() lcd.string(" Welcome", LINE_1) lcd.string(" Please wait...", LINE_2) baseValue = lc.base_value() fetchCropInfoFromServer() fetchTroughInfoFromServer() fetchLocationInfoFromServer()
def storeData(): "fuction to store data in database" global imgName lcd.string("Storing data...", LINE_3) try: #create instance of a database with host, username, password and database name db = sqldb.connect(host, username, password, 'maindb') #create cursor object cursor = db.cursor() img_path = "./images/" + imgName #insert values in database. isoformat() will give mysql compatible datetime object cursor.execute("INSERT INTO data (troughid, cropid, name, date, weight, imagepath, location) VALUES (%s, %s, %s, %s, %s, %s, %s)", (troughID, cropID, cropName, datetime.datetime.now().isoformat(), measuredWeight, img_path, locationName)) db.commit() #commit the changes lcd.clear() #lcd.string("Successfully stored", LINE_1) #lcd.string("in local database", LINE_2) lcd.string(" Success", LINE_2) time.sleep(1) except: lcd.clear() #lcd.string("Failed to store", LINE_1) #lcd.string("in local database", LINE_2) lcd.string(" FAILED", LINE_1) time.sleep(3) db.close()
def show_prediction(names, percentages, primary_keys): lcd.clear() time.sleep(0.1) s = ("Confidence: {:05.2f}".format(percentages[0] * 100)) + '%' lcd.string("A to enter manually", LINE_2) lcd.string(names[0], LINE_1) lcd.string(s, LINE_2) lcd.string("A -> enter manually", LINE_3) lcd.string("*->next, #->change", LINE_4) #lcd.string("# to change", LINE_4) key = "" while True: if key == '*': return primary_keys[0] if key == '#': return show_choices(names, percentages, primary_keys) if key == 'A': while True: cropIDAccepted, pk_manual = acceptManualCropID() if cropIDAccepted: return pk_manual else: return show_prediction(names, percentages, primary_keys) key = kpad.get_key()
def storeData(data): lcd.clear() lcd.string("Storing data...", LINE_1) lcd.string("Weight: " + str(data['weight']), LINE_2) lcd.string("CropID: " + str(data['crop_id']), LINE_3) lcd.string("FarmID: " + str(data['farmid']), LINE_4) f = open(constants.data_offline, 'a') t = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') crops = { 'weight': data['weight'], 'crop_id': data['crop_id'], 'time': t, 'imagename': data['imagename'], 'farmid': data['farmid'] } crop_details = json.dumps(crops) f.write(crop_details + '\n') time.sleep(0.5) print("Done")
def takePicture(): "fucntion to take picture using USB camera" global imgName global pictureTaken lcd.string("Taking picture...", LINE_2) if os.path.exists('/dev/video0'): #create image file name with current date imgName = "image-" + datetime.datetime.now().isoformat() + ".jpg" #capture image and save in images directory. if image file does not exists in folder then retake the image while os.path.isfile("/var/www/data/images/%s" %imgName) == False: os.system("fswebcam -r 640x480 -S 10 --no-banner /var/www/data/images/%s" %imgName) pictureTaken = 1 #if picture is successfully taken then set pictureTaken flag to 1 else: #if camera is not attached display error message lcd.clear() lcd.string(" FAILED", LINE_1) lcd.string("No camera attached", LINE_2) time.sleep(3)
def send_all_data(data): lcd.clear() lcd.string("Sending data...", LINE_1) lcd.string("Weight: " + str(data['weight']), LINE_2) lcd.string("CropID: " + str(data['crop_id']), LINE_3) lcd.string("FarmID: " + str(data['farmid']), LINE_4) time.sleep(1) data['user_id'] = constants.MACHINE_ID data['password'] = constants.PASSWORD data['time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') with open(constants.imagepath + data['imagename'], 'rb') as img: image = img.read() image = str(image, "latin-1") data['image'] = image try: r = requests.post(constants.URL, data=json.dumps(data)) print(r.text) if (r.text != "Done"): storeData(data) return False return True except: storeData(data) return False
def takePicture(): lcd.clear() lcd.string("Taking picture...", LINE_1) if os.path.exists('/dev/video0'): #create image file name with current date imgName = "image-" + datetime.datetime.now().isoformat() + str( constants.USER_ID) + ".jpg" imagepath = "/home/pi/ghfarm/images/%s" % imgName #capture image and save in images directory. if image file does not exists in folder then retake the image while os.path.isfile(imagepath) == False: os.system("fswebcam -r 640x480 -S 10 --no-banner %s" % imagepath) return True, imgName else: #if camera is not attached display error message lcd.clear() lcd.string(" FAILED", LINE_1) lcd.string("No camera attached", LINE_2) time.sleep(2) return False, "NoCamera"
def predict(data): lcd.clear() lcd.string(" Asking", LINE_2) lcd.string(" Nostradamus", LINE_3) lcd.string(" Please wait...", LINE_4) data['user_id'] = constants.MACHINE_ID data['password'] = constants.PASSWORD with open(constants.imagepath + data['imagename'], 'rb') as img: image = img.read() image = str(image, "latin-1") data['image'] = image try: r = requests.post(constants.PREDICT_URL, data=json.dumps(data).encode('utf-8')) print(r.text) with open(constants.crop_offline, "w") as file: file.write(r.text) r = json.loads(r.text) return True, r[0], r[1], r[2] except Exception as e: print(e) return False, e, "", ""
def displayWeight() : "function to display weight on lcd screen" #if there is no weight on the platform display simple message if measuredWeight < 10: lcd.string("Place your object on", LINE_1) lcd.string("the platform", LINE_2) #else prompt user to continue by pressing * button else: lcd.string("Press * button to", LINE_1) lcd.string("continue.", LINE_2) lcd.string("Object weight is:", LINE_3) weight = caculateWeight() #get calculated weight from the calculateWeight function lcd.string(str(weight) + " grams", LINE_4) #display the weight on the lcd
def displayWeight(): lcd.string("Object weight is:", LINE_3) weight = caculateWeight( ) #get calculated weight from the calculateWeight function lcd.string(str(weight) + " grams", LINE_4) #display the weight on the lcd if weight < min_weight: lcd.string("Place your object on", LINE_1) lcd.string("the platform", LINE_2) else: lcd.string("Press * button to", LINE_1) lcd.string("continue.", LINE_2) return weight
def acceptCropID(): "function to accept crop through keypad" global cropID lcd.clear() cropID = "" key = "" time.sleep(0.1) lcd.string("Enter Crop ID", LINE_1) lcd.string("Press * to continue", LINE_2) lcd.string("and # for backspace", LINE_3) #loop until some crop id is entered and * key is pressed. Following loop will run until valid crop id entered while key != "*": lcd.string(cropID, LINE_4) key = kpad.get_key() if key == '*': if len(cropID) <= 0: lcd.clear() lcd.string("Crop ID cant", LINE_1) lcd.string("be null", LINE_2) time.sleep(3) lcd.clear() lcd.string("Enter Crop ID", LINE_1) lcd.string("Press * to continue", LINE_2) lcd.string("and # for backspace", LINE_3) else: break elif key == '#': #for backspacing if len(cropID) > 0: cropID = cropID[:-1] elif key.isdigit(): cropID += key time.sleep(0.2) key = "" #after accepting crop ID fetch crop information from local database fetchCropInfo()
def fetchLocationInfo(): "retrieves location info through locationid info" global locationID global locationName global locationIDExcepted try: lcd.clear() lcd.string("Fetching location...", LINE_1) #create instance of a database with host, username, password and database name db = sqldb.connect("localhost", "root", "firebird", "maindb") #create cursor object cursor = db.cursor() lid = int(locationID) #convert accepted location id into integer sql = "SELECT locationname FROM locationinfo WHERE locationid = %d" % (lid) cursor.execute(sql) data = cursor.fetchone() #if there some location exists with this id if data > 0: locationName = data[0] #then assigh locationname to variable locationIDExcepted = 1 #set locationIDExcepted flag to one #lcd.clear() #lcd.string("Successfully fetched", LINE_1) #lcd.string("location information", LINE_2) #time.sleep(0.5) else: #if no location exists with entered ID lcd.clear() lcd.string("location ID does not", LINE_1) lcd.string("exists!", LINE_2) lcd.string("Enter valid location", LINE_3) lcd.string("ID", LINE_4) time.sleep(3) except: #if database connection Fails lcd.clear() lcd.string(" FAILED", LINE_1) lcd.string("Unable to connect to", LINE_2) lcd.string("local database", LINE_3) lcd.string("Try again later", LINE_4) time.sleep(3) db.close()
def acceptTroughID(): "function to accept troughid through keypad" global troughID global troughIDExcepted lcd.clear() troughID = "" key = "" time.sleep(0.1) lcd.string("Enter Trough ID", LINE_1) lcd.string("Press * to continue", LINE_2) lcd.string("and # for backspace", LINE_3) #loop until some trough id is entered and * key is pressed. Following loop will only break when valid trough ID is entered while key != "*": lcd.string(troughID, LINE_4) key = kpad.get_key() if key == '*': if len(troughID) <= 0: lcd.clear() lcd.string("Trough ID can't", LINE_1) lcd.string("be null", LINE_2) time.sleep(3) lcd.clear() lcd.string("Enter Trough ID", LINE_1) lcd.string("Press * to continue", LINE_2) lcd.string("and # for backspace", LINE_3) else: break elif key == '#': #for backspacing if len(troughID) > 0: troughID = troughID[:-1] elif key.isdigit(): troughID += key time.sleep(0.1) key = "" #check if entered trough ID is valid or not by fetching it from local database fetchTroughInfo()
def display_screen(): weight = 0 while True: key = "E" while key is not '*': weight = displayWeight() key = kpad.get_key() if key == 'D': tare() elif key == 'A': lcd.clear() lcd.string(" System", LINE_2) lcd.string(" Shutting down...", LINE_3) active = 0 os.system("sudo poweroff") lcd.clear() break elif key == 'B': lcd.clear() lcd.string(" Script", LINE_2) lcd.string(" Restarting", LINE_3) lcd.string(" Please wait...", LINE_4) active = 0 GPIO.cleanup() sys.stdout.flush() os.execv(sys.executable, ['python3'] + sys.argv) break elif key == 'C': lcd.clear() lcd.string(" System", LINE_2) lcd.string(" Restarting", LINE_3) lcd.string(" Please wait...", LINE_4) active = 0 os.system("sudo reboot") break if (weight < min_weight): continue else: return weight
def acceptFarmID(): lcd.clear() farmID = "" key = "E" time.sleep(0.1) lcd.string("Enter Farm ID", LINE_1) lcd.string("*- continue", LINE_2) lcd.string("#- clear D- back", LINE_3) #loop until some farm id is entered and * key is pressed. Following loop will only break when valid farm ID is entered while True: while key != "*": lcd.string(farmID, LINE_4) key = kpad.get_key() if key == '*': if len(farmID) == 0: lcd.clear() lcd.string("Farm ID can't", LINE_1) lcd.string("be null", LINE_2) time.sleep(1) lcd.clear() lcd.string("Enter Farm ID", LINE_1) lcd.string("*- continue", LINE_2) lcd.string("#- clear D- back", LINE_3) else: break elif key == '#': #for backspacing if len(farmID) > 0: farmID = farmID[:-1] time.sleep(0.1) elif key == 'D': #return to previous menu return False, "" elif key.isdigit(): farmID += key time.sleep(0.1) key = "" if validateFarmID(): # verify farm id return True, farmID else: lcd.clear() lcd.string("Farm ID is", LINE_1) lcd.string(" Invalid!", LINE_2) lcd.string("Please Try Again", LINE_3) time.sleep(1)
init() #while the program is active while active : #reset the flags troughIDExcepted = cropIDExcepted = pictureTaken = 0 key = kpad.get_key() #read the keypad value #while key pressed is not the * key while key is not '*' : displayWeight() key = kpad.get_key() if key == 'D' : tare() elif key == 'A': lcd.clear() lcd.string(" System", LINE_2) lcd.string(" Shutting down...", LINE_3) active = 0 os.system("sudo poweroff") lcd.clear() break elif key == 'B': lcd.clear() lcd.string(" Script", LINE_2) lcd.string(" Restarting", LINE_3) lcd.string(" Please wait...", LINE_4) active = 0 GPIO.cleanup() sys.stdout.flush() os.execl('/home/pi/Desktop/Final/startup.sh', '') break
pot_adjust = abs(percent - last_read_percent) # Если изменение больше tolerance if pot_adjust > tolerance: # Считаем, что ... hum_changed = True # Если потенциометр повернулся... if ( hum_changed ): lcd.string(' Humidity = {hum}%' .format(hum = percent), LCD_LINE_1) # Сохраняем последнее считанное значение до следующей итерации # save the potentiometer reading for the next loop last_read_percent = percent # Ничего не делаем 1/10-ю секунды # hang out and do nothing for a 1/10th of second time.sleep(0.1) if __name__ == '__main__': try: main() except KeyboardInterrupt: pass finally: lcd.byte(0x01, LCD_CMD) lcd.string("Goodbye!", LCD_LINE_1) GPIO.cleanup()
#initialize lcd lcd.lcd_init() lcd.string(" Welcome", LINE_1) lcd.string(" Remove any object", LINE_2) lcd.string(" from the platform.", LINE_3) time.sleep(2) lcd.clear() lcd.string(" Calibrating", LINE_1) lcd.string(" Please wait...", LINE_2) baseValue = lc.base_value() try: init() print("Started System") lcd.string("Started System", LINE_1) data = {} #Dictionary to store all required data stage = 0 while True: data['weight'] = display_screen() print(data['weight']) while True: if stage == 0: print("Taking Picture") imageAccepted, data['imagename'] = takePicture() if (imageAccepted): stage += 1 else: break if stage == 1: print("Taking FarmID")
def acceptLocationID(): "function to accept locationid through keypad" global locationID global locationIDExcepted lcd.clear() locationID = "" key = "" time.sleep(0.1) lcd.string("Enter Location ID", LINE_1) lcd.string("Press * to continue", LINE_2) lcd.string("and # for backspace", LINE_3) #loop until some location id is entered and * key is pressed. Following loop will only break when valid location ID is entered while key != "*": lcd.string(locationID, LINE_4) key = kpad.get_key() if key == '*': if len(locationID) <= 0: lcd.clear() lcd.string("Location ID can't", LINE_1) lcd.string("be null", LINE_2) time.sleep(3) lcd.clear() lcd.string("Enter Location ID", LINE_1) lcd.string("Press * to continue", LINE_2) lcd.string("and # for backspace", LINE_3) else: break elif key == '#': #for backspacing if len(locationID) > 0: locationID = locationID[:-1] elif key.isdigit(): locationID += key time.sleep(0.1) key = "" #after accepting locationID fetch location info from local database fetchLocationInfo()
def fetchCropInfoFromServer(): "fetch newly added cropinfo such as id and name from the server" updated = 0 removed = 0 lcd.clear() lcd.string(" Welcome", LINE_1) lcd.string("Fetching cropinfo...", LINE_2) try: lcd.string("Connect to database", LINE_3) #connect to server database to fetch information serverdb = sqldb.connect(host = server, user = "******", passwd = "123456789", db = "opencart", connect_timeout = 5) #connect to local databse to store fetched information localdb = sqldb.connect("localhost", "root", "firebird", "maindb") serverc = serverdb.cursor() localc = localdb.cursor() lcd.string(" Connected", LINE_4) serverc.execute("SELECT product_id, name FROM oc_product_description") result = serverc.fetchall() #fetch all crop information form server database for row in result: localc.execute("SELECT * FROM cropinfo WHERE id = %s", (row[0])) #fetch the crop info from local database with selected server crop id count = localc.fetchall() if len(count) == 0: #if crop does not exists in the server then count will be zero so add it in local database localc.execute("INSERT INTO cropinfo(id, name) VALUES (%s, %s)", (row[0], row[1])) updated += 1 localc.execute( "SELECT id FROM cropinfo") #fetch all the local crop information lresult = localc.fetchall() for lrow in lresult: count = 0 for row in result: if lrow[0] == row[0]: #if there is crop which is in both server and local database then this condition will be true. count += 1 if count == 0: #if there is some row in local database wich does not exists in server database then count will be zero then remove the entry from local database localc.execute("DELETE FROM cropinfo WHERE id = %s", (lrow[0])) removed += 1 localdb.commit() lcd.clear() lcd.string(" Success", LINE_2) if updated > 0: msg = " " msg += str(updated) msg += " crop updated" lcd.string(msg, LINE_3) time.sleep(3) if removed > 0: msg = " " msg += str(removed) msg += " crop removed" lcd.string(msg, LINE_3) time.sleep(3) serverdb.close() localdb.close() except: #localdb.rollback() lcd.clear() lcd.string(" Failed to", LINE_2) lcd.string(" fetch cropinfo", LINE_3) time.sleep(3)
def acceptManualCropID(): lcd.clear() cropID = "" key = "" time.sleep(0.1) lcd.string(" Enter Crop ID ", LINE_1) lcd.string(" *- continue ", LINE_2) lcd.string("#- clear,D- back", LINE_3) #loop until some crop id is entered and * key is pressed. Following loop will run until valid crop id entered while True: while key != "*": lcd.string(cropID, LINE_4) key = kpad.get_key() if key == '*': if len(cropID) == 0: lcd.clear() lcd.string("Crop ID cant", LINE_1) lcd.string("be null", LINE_2) time.sleep(1) lcd.clear() lcd.string(" Enter Crop ID ", LINE_1) lcd.string(" *- continue ", LINE_2) lcd.string("#- clear,D- back", LINE_3) else: break elif key == '#': #for backspacing if len(cropID) > 0: cropID = cropID[:-1] time.sleep(0.1) elif key == 'D': #return to previous menu return False, "" elif key.isdigit(): cropID += key time.sleep(0.2) key = "" if validateCropID(): # verify Crop id return True, cropID else: lcd.clear() lcd.string("Crop ID is", LINE_1) lcd.string(" Invalid!", LINE_2) lcd.string("Please Try Again", LINE_3) time.sleep(1)
def fetchTroughInfo(): "checks id entered troughid is valid of not" global troughID global troughIDExcepted try: lcd.clear() lcd.string("Fetching trough id...", LINE_1) #create instance of a database with host, username, password and database name db = sqldb.connect("localhost", "root", "firebird", "maindb") #create cursor object cursor = db.cursor() tid = int(troughID) #convert accepted trough id into integer sql = "SELECT troughid FROM troughinfo WHERE troughid = %d" % (tid) cursor.execute(sql) data = cursor.fetchone() #if entered trough ID is valid if data > 0: troughIDExcepted = 1 #set troughIDExcepted flag to one else: #if no trough id exists with entered ID lcd.clear() lcd.string("trough ID does not", LINE_1) lcd.string("exists!", LINE_2) lcd.string("Enter valid trough", LINE_3) lcd.string("ID", LINE_4) time.sleep(3) except: #if database connection Fails lcd.clear() lcd.string(" FAILED", LINE_1) lcd.string("Unable to connect to", LINE_2) lcd.string("local database", LINE_3) lcd.string("Try again later", LINE_4) time.sleep(3) db.close()
def main(): """ Основной блок программы Main program block :return: None """ # 10k trim pot connected to adc #1 # Потенциометр подключен на первый вход АЦП potentiometer_adc = 7 last_read_percent = 0 # Переменная отслеживает последнее считанное с потенциометра значение tolerance = 7 # Минимальное изменение значения. Новое значение с потенциометра будем # считывать только тогда, когда разница между текущим и предудущим значением # будет больше tolerance. Необходимо для устранения дребезжания MAX_VALUE = 1023 ##################################################################### # Все порты к дисплею устанавливаем на вывод: GPIO.setup(LCD_E , GPIO.OUT) # E GPIO.setup(LCD_RS, GPIO.OUT) # RS GPIO.setup(LCD_D4, GPIO.OUT) # DB4 GPIO.setup(LCD_D5, GPIO.OUT) # DB5 GPIO.setup(LCD_D6, GPIO.OUT) # DB6 GPIO.setup(LCD_D7, GPIO.OUT) # DB7 # Инциализируем дисплей lcd.init() # Устанавливаем режимы пинов интерфейса SPI # set up the SPI interface pins GPIO.setup(SPIMOSI, GPIO.OUT) GPIO.setup(SPIMISO, GPIO.IN) GPIO.setup(SPICLK, GPIO.OUT) GPIO.setup(SPICS, GPIO.OUT) potentiometer_adc = 7 last_read_percent = 0 # Переменная отслеживает последнее считанное с потенциометра значение tolerance = 1 # Минимальное изменение значения. Новое значение с потенциометра будем # считывать только тогда, когда разница между текущим и предудущим значением # будет больше tolerance. Необходимо для устранения дребезжания while True: # Будем считать, что потенциометр не изменил положение # we'll assume that the pot didn't move hum_changed = False # Считываем очередное значение с АЦП hum_raw_value = adc.readadc(potentiometer_adc, SPICLK, SPIMOSI, SPIMISO, SPICS) hum_value = abs(hum_raw_value - 1023) percent = round(hum_value * 100.0 / MAX_VALUE) # Вычисляем разницу между текущим и прошлым значением # how much has it changed since the last read? pot_adjust = abs(percent - last_read_percent) # Если изменение больше tolerance if pot_adjust > tolerance: # Считаем, что ... hum_changed = True # Если потенциометр повернулся... if ( hum_changed ): lcd.string(' Humidity = {hum}%' .format(hum = percent), LCD_LINE_1) # Сохраняем последнее считанное значение до следующей итерации # save the potentiometer reading for the next loop last_read_percent = percent # Ничего не делаем 1/10-ю секунды # hang out and do nothing for a 1/10th of second time.sleep(0.1)
def main(): """ Основной блок программы Main program block :return: None """ # Все порты к дисплею устанавливаем на вывод: GPIO.setup(LCD_E , GPIO.OUT) # E GPIO.setup(LCD_RS, GPIO.OUT) # RS GPIO.setup(LCD_D4, GPIO.OUT) # DB4 GPIO.setup(LCD_D5, GPIO.OUT) # DB5 GPIO.setup(LCD_D6, GPIO.OUT) # DB6 GPIO.setup(LCD_D7, GPIO.OUT) # DB7 # Инциализируем дисплей lcd.init() while True: # Выводим некоторый текст lcd.string("Rasbperry Pi", LCD_LINE_1) lcd.string("16x2 LCD Test", LCD_LINE_2) time.sleep(3) # Задержка на 3 секунды # Send some text lcd.string("1234567890123456", LCD_LINE_1) lcd.string("abcdefghijklmnop", LCD_LINE_2) time.sleep(3) # Задержка на 3 секунды # Выводим некоторый текст lcd.string("RaspberryPi-spy", LCD_LINE_1) lcd.string(".co.uk", LCD_LINE_2) time.sleep(3) # Выводим некоторый текст lcd.string("Follow me on", LCD_LINE_1) lcd.string("Twitter @RPiSpy", LCD_LINE_2) time.sleep(3)