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 main(): HOME = os.path.dirname(os.path.realpath(__file__)) f = file(HOME+'/sensors.cfg') CFG = Config(f) logging.basicConfig(filename=HOME+'/sensors.log', level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M') tz = pytz.timezone(CFG.timezone) date = datetime.now(tz) GPIO.setwarnings(False) m = date.strftime("%Y-%m-%d\n%H:%M:%S") lcd.init() lcd.message(m) if date.hour >= 0 and date.hour <= 5: lcd.backlight(False) else: lcd.backlight(True) d = [] # read sensor data for s in CFG.sensors: if s.id < 0: continue # skip disabled sensors try: if s.name == 'DS18B20': v = w1.readTemp(s.rom_code) elif s.name == 'DHT22' and s.rom_code == 'H': v = dht.readHumidity() elif s.name == 'DHT22' and s.rom_code == 'T': v = dht.readTemperature() else: raise Exception('unknown sensor name') continue except Exception as e: logging.error("| Can't read sensor %d | %s | %s" % (s.id, s.rom_code, str(e))) continue try: db.updateSensor(s.id, v, date) if(s.type == 'H'): d.append('%d%%' % v) else: d.append(v) # print "#%d %s, %s: %.1f" % (s.id, s.rom_code, s.label, v) except Exception as e: logging.error("| Can't update sensor %d | %s | %s" % (s.id, s.rom_code, str(e))) continue m = buildMessage(d, date) lcd.message(m)
def main(): HOME = os.path.dirname(os.path.realpath(__file__)) f = file(HOME+'/sensors.cfg') CFG = Config(f) tz = pytz.timezone(CFG.timezone) date = datetime.now(tz) GPIO.setwarnings(False) lcd.init() lcd.message('Raspberry Pi\n%s' % date.strftime("%Y-%m-%d %H:%M")) lcd.backlight(True)
def main(): sensor = W1ThermSensor() lcd.init() while True: temp = sensor.get_temperature() print(temp) lcd.write("%s" % temp) if temp < desired_temp: switch_on() print("on") lcd.write("on", 2) else: switch_off() print("off") lcd.write("off", 2) sleep(5)
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)
def init(): #Temperature use Analog pin 1 temperature.init() #LED use Digital pin 13 led.init() #Light is on I2C, doesn't use a specific pin light.init() #Sound uses A0 Grove Port sound.init() #LCD is on I2C, doesn't use a specific pin lcd.init() lcd.setRGB(0,255,0) #Air Quality is on Analog Pin 1 air_quality.init() #Led bar is on pin D8, uses pin 8 and 9 led_bar.init()
# Example 1 - LCD Shield Demo # # Note: To run this example you will need a LCD Shield for your OpenMV Cam. # # The LCD Shield allows you to view your OpenMV Cam's frame buffer on the go. import sensor, image, lcd sensor.reset() # Initialize the camera sensor. sensor.set_pixformat(sensor.RGB565) # or sensor.GRAYSCALE sensor.set_framesize(sensor.QQVGA2) # Special 128x160 framesize for LCD Shield. lcd.init() # Initialize the lcd screen. while(True): lcd.display(sensor.snapshot()) # Take a picture and display the image.
def patch(url, **kw): return request("PATCH", url, **kw) def delete(url, **kw): return request("DELETE", url, **kw) headers = {"User-Agent": "MaixPy"} res = get("http://dl.sipeed.com/MAIX/MaixPy/assets/Alice.jpg", headers=headers) print("response:", res.status_code) content = res.content print("get img, length:{}, should be:{}".format( len(content), int(res.headers['Content-Length']))) if len(content) != int(res.headers['Content-Length']): print("download img fail, not complete, try again") else: print("save to /flash/Alice.jpg") f = open("/flash/Alice.jpg", "wb") f.write(content) f.close() del content print("save ok") print("display") img = image.Image("/flash/Alice.jpg") lcd.init() lcd.display(img)
import image import lcd lcd.init(freq=20000000) i = 0 dir = 1 while (True): img = image.Image(copy_to_fb=1) img.clear() img.draw_rectangle(i, 50, 50, 50) lcd.display(img) if dir: i += 5 if i == 270: dir = 0 else: i -= 5 if i == 0: dir = 1
#!/usr/bin/env python #import pcd8544.lcd as lcd import lcd import time import A20_GPIO as GPIO def demo(): lcd.locate(0,0) lcd.text("TEST") if __name__ == "__main__": lcd.init() lcd.backlight(1) demo() GPIO.cleanup()
import sensor, image, time, math, struct, pyb import json from pyb import UART from pyb import Servo from pyb import UART import lcd uart = pyb.UART(3, 115200) #串口3,波特率115200 uart.init(115200, bits=8, parity=None, stop=1) #8位数据位,无校验位,1位停止位 sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) # can be QVGA on M7... sensor.skip_frames(30) sensor.set_auto_gain(False) # must turn this off to prevent image washout... lcd.init() # Initialize the lcd screen. class Line(object): x = 0 line1 = Line() def UART_Sent(): data_pack = bytearray([line1.x]) uart.write(data_pack) #打印所有所需数据 print("OPENMV发送的数据:", data_pack) while (True):
#tested with frimware 5-0.22 import sensor, image, lcd import KPU as kpu lcd.init() sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) sensor.set_windowing((224, 224)) #sensor.set_windowing((320, 240)) #sensor.set_vflip(1) sensor.run(1) classes = ["penguin"] print("BSP initialized") task = kpu.load( 0x200000 ) #change to "/sd/name_of_the_model_file.kmodel" if loading from SD card print("Task loaded from Flash") #a = kpu.set_outputs(task, 0, 7,7,30) #the actual shape needs to match the last layer shape of your model(before Reshape) #a = kpu.set_outputs(task, 1,30,7,7) anchor = (0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828) a = kpu.init_yolo2( task, 0.3, 0.3, 5, anchor ) #tweak the second parameter if you're getting too many false positives print("Yolo initialized") while (True): #img = sensor.snapshot().rotation_corr(z_rotation=90.0) img = sensor.snapshot() a = img.pix_to_ai() code = kpu.run_yolo2(task, img)
import lvgl as lv import lvgl_helper as lv_h import lcd import time from machine import Timer from machine import I2C config_touchscreen_support = True board_m1n = False i2c = I2C(I2C.I2C0, freq=400000, scl=30, sda=31) if not board_m1n: lcd.init() else: lcd.init(type=2, freq=20000000) if config_touchscreen_support: import touchscreen as ts ts.init(i2c) lv.init() disp_buf1 = lv.disp_buf_t() buf1_1 = bytearray(320 * 10) lv.disp_buf_init(disp_buf1, buf1_1, None, len(buf1_1) // 4) disp_drv = lv.disp_drv_t() lv.disp_drv_init(disp_drv) disp_drv.buffer = disp_buf1 disp_drv.flush_cb = lv_h.flush if board_m1n: disp_drv.hor_res = 240 disp_drv.ver_res = 240 else:
# Hello World 例程 # 欢迎使用 Maixpy IDE! # # 1. 将开发板连接到电脑; # 2. 在工具->选择开发板下选择合适的开发板; # 3. 点击连接并选择串口; # 4. 连接成功后点击绿色按钮开始运行! # #翻译和注释:01Studio import sensor, image, time, lcd lcd.init(freq=15000000) #初始化LCD sensor.reset() #复位和初始化摄像头,执行sensor.run(0)停止。 #sensor.set_vflip(1) #将摄像头设置成后置方式(所见即所得) sensor.set_pixformat(sensor.RGB565) # 设置像素格式为彩色 RGB565 (或灰色) sensor.set_framesize(sensor.QVGA) # 设置帧大小为 QVGA (320x240) sensor.skip_frames(time=2000) # 等待设置生效. clock = time.clock() # 创建一个时钟来追踪 FPS(每秒拍摄帧数) while (True): clock.tick() # 更新 FPS 时钟. img = sensor.snapshot() # 拍摄一个图片并保存. lcd.display(img) # 在LCD上显示 print(clock.fps()) # 注意: 当 K210 连接到 IDE 时候,运行速度减 #半,因此当断开 IDE 时 FPS 会提升。
gpsd = gps(mode=WATCH_ENABLE|WATCH_NEWSTYLE) #starting the stream of info self.current_value = None self.running = True #setting the thread running to true result = True except: pass def run(self): global gpsd while gpsp.running: gpsd.next() #this will continue to loop and grab EACH set of gpsd info to clear the buffer #===================================================================================================== #===================================================================================================== if __name__ == '__main__': fd = lcd.init() gpsp = GpsPoller() # create the thread no_gps_fix() try: gpsp.start() # start it up while True: previous_option=IO(previous_option) #It may take a second or two to get good data #print gpsd.fix.latitude,', ',gpsd.fix.longitude,' Time: ',gpsd.utc if gpsd.fix.mode==MODE_3D: fix_flag=True GPIO.output(gps_stat, True) # switch on gps status led if it has a 3d fix #==========================================================calculate sidereal time from gps time gpsNow = gpsd.utc gpsNow = gpsNow.replace('Z', 'UTC') ctLong = gpsd.fix.longitude
def main(): lcd.init() lcd.backlight(1) stats()
else: key_pressed2 = 0 last_key_state2 = val2 def drawConfidenceText(image, rol, classid, value): text = "" _confidence = int(value * 100) if classid == 1: text = 'mask: ' + str(_confidence) + '%' else: text = 'no_mask: ' + str(_confidence) + '%' image.draw_string(rol[0], rol[1], text, color=color_R, scale=2.5) lcd.init() # 初始化lcd sensor.reset() #初始化sensor 摄像头 sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) sensor.set_hmirror(0) #设置摄像头镜像 sensor.set_vflip(1) #设置摄像头翻转 sensor.run(1) #使能摄像头 anchor = (1.889, 2.5245, 2.9465, 3.94056, 3.99987, 5.3658, 5.155437, 6.92275, 6.718375, 9.01025) #anchor for face detect 用于人脸检测的Anchor anchorMsk = (0.1606, 0.3562, 0.4712, 0.9568, 0.9877, 1.9108, 1.8761, 3.5310, 3.4423, 5.6823) dst_point = [ (44, 59), (84, 59), (64, 82), (47, 105), (81, 105) ] #standard face key point position 标准正脸的5关键点坐标 分别为 左眼 右眼 鼻子 左嘴角 右嘴角 a = kpu.init_yolo2(task_fd, 0.5, 0.3, 5, anchor) #初始化人脸检测模型
import nes, lcd from Maix import GPIO from fpioa_manager import fm # AUDIO_PA_EN_PIN = None # Bit Dock and old MaixGo AUDIO_PA_EN_PIN = 32 # Maix Go(version 2.20) # AUDIO_PA_EN_PIN = 2 # Maixduino # open audio PA if AUDIO_PA_EN_PIN: fm.register(AUDIO_PA_EN_PIN, fm.fpioa.GPIO1, force=True) wifi_en = GPIO(GPIO.GPIO1, GPIO.OUT) wifi_en.value(1) lcd.init(freq=15000000) nes.init(nes.KEYBOARD) nes.run("/sd/mario.nes")
# https://gist.github.com/Shinichi-Ohki/a87eaf8383cccbfd9312dd702c12de1d # M5stickVのバックライトを制御する import lcd #for test from machine import I2C i2c = I2C(I2C.I2C0, freq=400000, scl=28, sda=29) lcd.init() #for test lcd.draw_string(100, 100, "hello maixpy", lcd.RED, lcd.BLACK) #for test i2c.writeto_mem(0x34, 0x91, b'\x70') # minimum i2c.writeto_mem(0x34, 0x91, b'\xf0') # maximum
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(): lcd.init() lcd.clear() while(1): stats() sleep(1)