#!/usr/bin/env python # Ported from: # https://github.com/adafruit/Adafruit_Python_SSD1306/blob/master/examples/shapes.py from oled.device import ssd1306, sh1106 from oled.render import canvas from PIL import ImageFont import Adafruit_GPIO as GPIO import Adafruit_GPIO.SPI as SPI font = ImageFont.load_default() device = sh1106(dc=27, spi=SPI.SpiDev(0, 0, max_speed_hz=8000000)) with canvas(device) as draw: # Draw some shapes. # First define some constants to allow easy resizing of shapes. padding = 2 shape_width = 20 top = padding + 9 print device.height bottom = device.height - padding - 1 # Draw a rectangle of the same size of screen draw.rectangle((0, 0, device.width - 1, device.height - 1), outline=255, fill=0) # Move left to right keeping track of the current x position for drawing shapes. x = padding # Draw an ellipse. draw.ellipse((x, top, x + shape_width, bottom), outline=255, fill=0) x += shape_width + padding
def __init__(self): # Hardware SPI configuration: SPI_PORT = 0 SPI_DEVICE = 0 self.mcp = Adafruit_MCP3008.MCP3008( spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
def pid_loop(dummy, state): import sys from time import sleep, time from math import isnan import Adafruit_GPIO.SPI as SPI import Adafruit_MAX31855.MAX31855 as MAX31855 import PID as PID import config as conf sys.stdout = open("pid.log", "a", buffering=0) sys.stderr = open("pid.err.log", "a", buffering=0) def c_to_f(c): return c * 9.0 / 5.0 + 32.0 sensor = MAX31855.MAX31855(spi=SPI.SpiDev(conf.spi_port, conf.spi_dev)) pid = PID.PID(conf.Pc, conf.Ic, conf.Dc) pid.SetPoint = state['settemp'] pid.setSampleTime(conf.sample_time * 5) nanct = 0 i = 0 j = 0 pidhist = [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.] avgpid = 0. temphist = [0., 0., 0., 0., 0.] avgtemp = 0. lastsettemp = state['settemp'] lasttime = time() sleeptime = 0 iscold = True iswarm = False lastcold = 0 lastwarm = 0 try: while True: # Loops 10x/second tempc = sensor.readTempC() if isnan(tempc): nanct += 1 if nanct > 100000: sys.exit continue else: nanct = 0 tempf = c_to_f(tempc) temphist[i % 5] = tempf avgtemp = sum(temphist) / len(temphist) if avgtemp < 100: lastcold = i if avgtemp > 200: lastwarm = i if iscold and (i - lastcold) * conf.sample_time > 60 * 15: pid = PID.PID(conf.Pw, conf.Iw, conf.Dw) pid.SetPoint = state['settemp'] pid.setSampleTime(conf.sample_time * 5) iscold = False if iswarm and (i - lastwarm) * conf.sample_time > 60 * 15: pid = PID.PID(conf.Pc, conf.Ic, conf.Dc) pid.SetPoint = state['settemp'] pid.setSampleTime(conf.sample_time * 5) iscold = True if state['settemp'] != lastsettemp: pid.SetPoint = state['settemp'] lastsettemp = state['settemp'] if i % 10 == 0: pid.update(avgtemp) pidout = pid.output pidhist[i / 10 % 10] = pidout avgpid = sum(pidhist) / len(pidhist) state['i'] = i state['tempf'] = round(tempf, 2) state['avgtemp'] = round(avgtemp, 2) state['pidval'] = round(pidout, 2) state['avgpid'] = round(avgpid, 2) state['pterm'] = round(pid.PTerm, 2) if iscold: state['iterm'] = round(pid.ITerm * conf.Ic, 2) state['dterm'] = round(pid.DTerm * conf.Dc, 2) else: state['iterm'] = round(pid.ITerm * conf.Iw, 2) state['dterm'] = round(pid.DTerm * conf.Dw, 2) state['iscold'] = iscold print time(), state sleeptime = lasttime + conf.sample_time - time() if sleeptime < 0: sleeptime = 0 sleep(sleeptime) i += 1 lasttime = time() finally: pid.clear
import RPi.GPIO as GPIO import time from random import randint import numpy as np # next two libraries must be installed IAW appendix instructions import Adafruit_GPIO.SPI as SPI import Adafruit_MCP3008 global pwmL, pwmR, mcp lightOld = 0 hysteresis = 2 # Hardware SPI configuration: SPI_PORT = 0 SPI_DEVICE = 0 mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) threshold = 25.4 # use the BCM pin numbers GPIO.setmode(GPIO.BCM) # setup the motor control pins GPIO.setup(18, GPIO.OUT) GPIO.setup(19, GPIO.OUT) pwmL = GPIO.PWM(18, 20) # pin 18 is left wheel pwm pwmR = GPIO.PWM(19, 20) # pin 19 is right wheel pwm # must 'start' the motors with 0 rotation speeds pwmL.start(2.8) pwmR.start(2.8) # ultrasonic sensor pins TRIG1 = 23 # an output ECHO1 = 24 # an input TRIG2 = 25 # an output ECHO2 = 27 # an input
seg2 = [ [1,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1], [1,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1] ] # LCD Screen configuration DC = 15 RST = 14 SPI_PORT = 0 SPI_DEVICE = 1 disp = LCD.PCD8544(DC, RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=4000000)) image= Image.new('1', (LCD.LCDWIDTH, LCD.LCDHEIGHT)) disp.begin(contrast=60) disp.clear() disp.display() font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 8) font2 = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 9) draw = ImageDraw.Draw(image) draw.rectangle((0,0,LCD.LCDWIDTH,LCD.LCDHEIGHT), outline = 255, fill=255) # create variables for rfid and plate plate = '' rfid = None def check_json(): # Opening JSON file where plate number is located
class MQ(): # Software SPI #CLK = 23 #MISO = 21 #MOSI = 19 #CS = 24 #mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI) # Hardware SPI SPI_PORT = 0 SPI_DEVICE = 0 mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) RL_VALUE = 5 RO_CLEAN_AIR_FACTOR = 3.62 CALIBARAION_SAMPLE_TIMES = 50 CALIBRATION_SAMPLE_INTERVAL = 500 READ_SAMPLE_INTERVAL = 50 READ_SAMPLE_TIMES = 5 GAS_CO2 = 0 GAS_CO = 1 GAS_NH4 = 2 def __init__(self, Ro=20, analogPin=0): self.Ro = Ro self.MQ_PIN = analogPin self.CO2Curve = [1, 0.38, -0.339] self.COCurve = [1, 0.462, -0.232] self.NH4Curve = [1, 0.423, -0.423] print("Calibrating...") self.Ro = self.MQCalibration(self.MQ_PIN) print("Calibration is done...\n") print("Ro=%f kohm" % self.Ro) def MQPercentage(self): val = {} read = self.MQRead(self.MQ_PIN) val["GAS_CO2"] = self.MQGetGasPercentage(read / self.Ro, self.GAS_CO2) val["GAS_CO"] = self.MQGetGasPercentage(read / self.Ro, self.GAS_CO) val["GAS_NH4"] = self.MQGetGasPercentage(read / self.Ro, self.GAS_NH4) return val def MQResistanceCalculation(self, raw_adc): return float(self.RL_VALUE * (1023.0 - raw_adc) / float(raw_adc)) def MQCalibration(self, mq_pin): val = 0.0 for i in range(self.CALIBARAION_SAMPLE_TIMES): val += self.MQResistanceCalculation(self.mcp.read_adc(mq_pin)) time.sleep(self.CALIBRATION_SAMPLE_INTERVAL / 1000.0) val = val / self.CALIBARAION_SAMPLE_TIMES val = val / self.RO_CLEAN_AIR_FACTOR return val def MQRead(self, mq_pin): rs = 0.0 for i in range(self.READ_SAMPLE_TIMES): rs += self.MQResistanceCalculation(self.mcp.read_adc(mq_pin)) time.sleep(self.READ_SAMPLE_INTERVAL / 1000.0) rs = rs / self.READ_SAMPLE_TIMES return rs def MQGetGasPercentage(self, rs_ro_ratio, gas_id): if (gas_id == self.GAS_CO2): return self.MQGetPercentage(rs_ro_ratio, self.CO2Curve) elif (gas_id == self.GAS_CO): return self.MQGetPercentage(rs_ro_ratio, self.COCurve) elif (gas_id == self.GAS_NH4): return self.MQGetPercentage(rs_ro_ratio, self.NH4Curve) return 0 def MQGetPercentage(self, rs_ro_ratio, pcurve): return (math.pow( 10, (((math.log(rs_ro_ratio) - pcurve[1]) / pcurve[2]) + pcurve[0])))
def __init__(self): super(Clock, self).__init__() self.disp = TFT.ILI9341(17, rst=23, spi=SPI.SpiDev(0, 0, max_speed_hz=64000000)) self.font = ImageFont.truetype('fonts/OpenSans-Bold.ttf', 110) self.disp.begin() self.disp.clear()
# board initialization C12880.Setup() # init spectrometer GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(pin_meas, GPIO.IN) GPIO.setup(pin_black, GPIO.IN) GPIO.setup(pin_led, GPIO.OUT) GPIO.output(pin_led, GPIO.LOW) data = (c_uint * 288)() # data to store spectrum data meas = 1 black = 1 fnameindex = 0 # Display init spi = SPI.SpiDev(SPI_PORT, SPI_CH, max_speed_hz = SPI_SPEED) disp = TFT.ST7735(dc = AOPIN, rst = RSTPIN, spi = spi, width = 128, height = 128) disp.begin() disp.clear() img = Image.new('RGB', TFT_SIZE, COLOR_WHITE) draw = ImageDraw.Draw(img) font = "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf" fontout = ImageFont.truetype(font,11) draw.text((0,LINE1Y), " Mode: Measure", font = fontout, fill = COLOR_BLUE) draw.text((0,LINE2Y), " Bilirubin", font = fontout, fill = COLOR_BLUE) draw.text((0,LINE4Y), " SiO2", font = fontout, fill = COLOR_BLUE) disp.display(img) led1_current = int(sys.argv[1]) led2_current = int(sys.argv[2]) led3_current = int(sys.argv[3])
def write_log(log): log_file = open(LOG, 'a+') s = "" for l in log: s += "%s,%s\n" % l log_file.write(s) log_file.close() GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(RELAY_PIN, GPIO.OUT, initial=GPIO.LOW) sensor = MAX6675.MAX6675(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) log = [] ltime = 0 log_cnt = 0 # try : while True: temp = sensor.readTempC() print "TEMP: %s" % temp log.append((ltime, temp)) log_cnt += 1 time.sleep(1 / FREQUENCY) ltime += (1 / FREQUENCY) if log_cnt > 10:
import sys sys.path.insert(0, 'Cubium/drivers/PythonDrivers') import Adafruit_GPIO.SPI as SPI import Adafruit_MCP3008 import time SPI_PORT = 0 SPI_DEVICE = 0 uv_external = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) ADC_PIN = 1 def handleSpaData(): pass def sendData(): value = uv_external.read_adc(ADC_PIN) return value def init(): pass
# Raspberry Pi configuration. DC = 24 RST = 25 SPI_PORT = 0 SPI_DEVICE = 0 # BeagleBone Black configuration. #DC = 'P9_15' #RST = 'P9_12' #SPI_PORT = 1 #SPI_DEVICE = 0 # Create TFT LCD display class. disp = TFT.ILI9486(DC, rst=RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=64000000)) # Initialize display. disp.begin() # Load an image. print('Loading image...') image = Image.open('vacatronics_320x480.png') # Resize the image and rotate it so it's 240x320 pixels. # image = image.rotate(90).resize((320, 480)) print('Press Ctrl-C to exit') while(True): # Draw the image on the display hardware. print('Drawing image')
def green(self): self.red_led.off() self.green_led.on() self.color = Color.GREEN def red(self): self.green_led.off() self.red_led.on() self.color = Color.RED pigeon = Pigeon() state = State() mcp = MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) power_button = Button(GPIO_POWER_BUTTON) switch_mode_button = Button(GPIO_MODE_BUTTON) rgled = RGLED(LED(22), LED(27)) rgled.red() def calc_cycle_time(slide_state): return ((MAX_CYCLE_LENGTH / MAX_SLIDE_VALUE) * slide_state) + 30 def calc_operating_ratio(slide_state): # Calculate slide state in percent return (100 - (100 / (MAX_SLIDE_VALUE + (SLIDE_MODIFIER * 2))) * \
def main(): # Setup SPI cfg.DISP = LCD.PCD8544(cfg.DC, cfg.RST, spi=SPI.SpiDev(cfg.SPI_PORT, cfg.SPI_DEVICE, max_speed_hz=4000000)) # Initialize library cfg.DISP.begin(contrast=cfg.LCDCONTRAST) # Clear cfg.DISPlay cfg.DISP.clear() cfg.DISP.display() # Get IP address cfg.IP = getip('wlan0') # Setup GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # Switches setup as inputs pulled HIGH by default GPIO.setup(cfg.SWITCH1, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(cfg.SWITCH2, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(cfg.SWITCH3, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Define function to call when switch pressed GPIO.add_event_detect(cfg.SWITCH1, GPIO.FALLING, callback=switch1Callback, bouncetime=300) GPIO.add_event_detect(cfg.SWITCH2, GPIO.FALLING, callback=switch2Callback, bouncetime=300) GPIO.add_event_detect(cfg.SWITCH3, GPIO.FALLING, callback=switch3Callback, bouncetime=300) bus = smbus.SMBus(cfg.SMBUSID) # Initial sensor reading (temperature, pressure) = bmp180.readBmp180(cfg.DEVICE) try: while True: sendData(cfg.THINGSPEAKURL, cfg.THINGSPEAKKEY, 'field1', 'field2', temperature, pressure) sys.stdout.flush() # 2 second loops for i in range(0, cfg.INTERVAL * 30): time.sleep(2) (temperature, pressure) = bmp180.readBmp180(cfg.DEVICE) updateAll(cfg.DISP, temperature, pressure) except: # Reset GPIO settings print "error", sys.exc_info()[0] GPIO.cleanup()
class mindsensorsUI(): ## Constant to specify black color PS_BLACK = (0, 0, 0) ## Constant to specify blue color PS_BLUE = (0, 0, 255) ## Constant to specify red color PS_RED = (255, 0, 0) ## Constant to specify green color PS_GREEN = (0, 255, 0) ## Constant to specify cyan color PS_CYAN = (0, 255, 255) ## Constant to specify magenta color PS_MAGENTA = (255, 0, 255) ## Constant to specify yellow color PS_YELLOW = (255, 255, 0) ## Constant to specify white color PS_WHITE = (255, 255, 255) ## Constant to defualt screen width PS_SCREENWIDTH = 240 ## Constant to defualt screen height PS_SCREENHEIGHT = 320 ### @cond Doxygen_ignore_this ## Constant to specify terminal mode PS_MODE_TERMINAL = 0 ## Constant to specify pop-up mode PS_MODE_POPUP = 1 ## Constant to specify dead mode PS_MODE_DEAD = 2 ## Dictionary of default emnpty terminal buffer terminalBuffer = [""] * 20 ## Variable of default terminal cursor position terminalCursor = 0 ## Variable of default mode currentMode = 0 ## Variable of default rotation currentRotation = 0 ## Instance to initialize the display disp = TFT.ILI9341(24, rst=25, spi=SPI.SpiDev(0, 0, max_speed_hz=64000000)) ## Variable of default button text buttonText = ["OK", "Cancel"] ## Variable of default pop-up text popupText = ["Do you wish to continue?"] ## Variable of default draw arrow state drawArrowsbool = False x = 0 y = 0 ### @endcond ## Initialize the UI device. # @param self The object pointer. # @param name The display title that will appear at the top of the LCD touchscreen. Optional, defaults to "PiStorms" (unused). # @param rotation The rotation of the LCD touchscreen. Optional, defaults to 3 (standard rotation). # @remark # There is no need to use this function directly. To initialize the mindsensorsUI class in your program: # @code # from mindsensorsUI import mindsensorsUI # ... # screen = mindsensorsUI() # @endcode def __init__(self, name="PiStorms", rotation=3): config = ConfigParser.RawConfigParser() config.read("/usr/local/mindsensors/conf/msdev.cfg") if "GRX" in config.get('msdev', 'device'): self.comm = GRXCom else: self.comm = PiStormsCom() # note self.comm is only used to getTouchscreenCoordinates and to getKeyPressCount self.disp.begin() self.clearScreen() self.disp.command(ILI9341_INVOFF) if (rotation in range(4)): self.currentRotation = rotation self.refresh() self.myname = name #self.drawDisplay(name, display=False) ## Dumps the screen buffer # @param self The object pointer. def dumpTerminal(self): self.terminalBuffer = [""] * 20 self.terminalCursor = 0 if (self.getMode() == self.PS_MODE_TERMINAL): self.refresh() ## Sets the mode (Experienced users) # @param self The object pointer. # @param mode The new mode: PS_MODE_TERMINAL, PS_MODE_POPUP, or PS_MODE_DEAD. Optional, defaults to PS_MODE_TERMINAL. def setMode(self, mode=0): if (mode < 0 or mode > 2): self.currentMode = self.PS_MODE_DEAD else: self.currentMode = mode self.refresh() ## Returns the value of the mode (Experienced users) # @param self The object pointer. def getMode(self): return self.currentMode ## Draw a rectangle with rounded edges on the screen (rotated to screen) # @param self The object pointer. # @param x The upper left x coordinate of the rectangle. # @param y The upper left y coordinate of the rectangle. # @param width The width of the rectangle. # @param height The height of the rectangle. # @param radius The arc of the rectangle corners. # @param fill The color of the inside of the rectangle. Optional, defaults to white. # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. def fillRoundRect(self, x, y, width, height, radius, fill=(255, 255, 255), display=True): self.fillRect(x, y + radius, width, height - (radius * 2), fill=fill, display=False) self.fillRect(x + radius, y, width - (radius * 2), height, fill=fill, display=False) self.fillCircle(x + radius, y + radius, radius, fill=fill, display=False) self.fillCircle(x + width - radius, y + radius, radius, fill=fill, display=False) self.fillCircle(x + radius, y + height - radius, radius, fill=fill, display=False) self.fillCircle(x + width - radius, y + height - radius, radius, fill=fill, display=display) ## Calculates the x-coordinate of the screen upon rotation (INTERNAL USE ONLY) # @param self The object pointer. # @param x x value in the current rotation's coordinate system # @param y y value in the current rotation's coordinate system # @return x value for the corresponding point in the display's coordinate system (for writing to TFT) def screenXFromImageCoords(self, x, y): cr = self.currentRotation if (cr == 0): return x if (cr == 1): return self.PS_SCREENWIDTH - y if (cr == 2): return self.PS_SCREENWIDTH - x if (cr == 3): return y ## Calculates the y-coordinate of the screen upon rotation (INTERNAL USE ONLY) # @param self The object pointer. # @param x x value in the current rotation's coordinate system # @param y y value in the current rotation's coordinate system # @return y value for the corresponding point in the display's coordinate system (for writing to TFT) def screenYFromImageCoords(self, x, y): cr = self.currentRotation if (cr == 0): return y if (cr == 1): return x if (cr == 2): return self.PS_SCREENHEIGHT - y if (cr == 3): return self.PS_SCREENHEIGHT - x ## Calculates display x-coordinate from touchscreen values, adjusted for rotation (INTERNAL USE ONLY) # @param self The object pointer. # @param x x value in the touchscreen's coordinate system (read from registers) # @param y y value in the touchscreen's coordinate system (read from registers) # @return x value for the corresponding point in the current rotation's coordinate system def TS_To_ImageCoords_X(self, x, y): cr = self.currentRotation if (cr == 0): return y if (cr == 1): return x if (cr == 2): return self.PS_SCREENWIDTH - y if (cr == 3): return self.PS_SCREENHEIGHT - x ## Calculates display y-coordinate from touchscreen values, adjusted for rotation (INTERNAL USE ONLY) # @param self The object pointer. # @param x x value in the touchscreen's coordinate system (read from registers) # @param y y value in the touchscreen's coordinate system (read from registers) # @return y value for the corresponding point in the current rotation's coordinate system def TS_To_ImageCoords_Y(self, x, y): cr = self.currentRotation if (cr == 0): return x if (cr == 1): return self.PS_SCREENWIDTH - y if (cr == 2): return self.PS_SCREENHEIGHT - x if (cr == 3): return y ## Displays rotated text (INTERNAL USE ONLY) # @param self The object pointer. # @param image The image used for creating text # @param text The text to display on the screen # @param position The position of the text as a set of x and y-coordinates # @param angle The angle at which to rotate the text # @param font The font of the text # @param fill The color of the text. Optional, defaults to white. # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. def draw_rotated_text(self, image, text, position, angle, font, fill=(255, 255, 255), display=True): draw = ImageDraw.Draw(image) width, height = draw.textsize(text, font=font) textimage = Image.new('RGBA', (width, height), (0, 0, 0, 0)) textdraw = ImageDraw.Draw(textimage) textdraw.text((0, 0), text, font=font, fill=fill) if angle == -90: textimage = textimage.transpose(Image.ROTATE_270) if angle == -180: textimage = textimage.transpose(Image.ROTATE_180) if angle == -270: textimage = textimage.transpose(Image.ROTATE_90) image.paste(textimage, position, textimage) if (display): self.disp.display() ## Determines the width of the screen based on rotation (Experienced users) # @param self The object pointer. def screenWidth(self): if (self.currentRotation == 1 or self.currentRotation == 3): return 320 else: return 240 ## Determines the height of the screen based on rotation (Experienced users) # @param self The object pointer. def screenHeight(self): if (self.currentRotation == 1 or self.currentRotation == 3): return 240 else: return 320 ## Prints a large title, intended for terminal mode. # @param self The object pointer. # @param name The display title that will appear at the top of the LCD touchscreen in cyan. # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. def drawDisplay(self, name, display=True): self.drawAutoText(name, 0, 5, fill=(0, 255, 255), size=30, display=display, align="center") ## Draw forward and back arrows on the screen # @param self The object pointer. # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. def drawArrows(self, display=True): self.drawButton(0, 0, width=50, height=40, text="<", display=False) self.drawButton(self.screenWidth() - 50, 0, width=50, height=40, text=">", display=display) ## Determine if either on screen arrow button is pressed # @param self The object pointer. def checkArrows(self): return (self.checkButton(0, 0, 50, 50), self.checkButton(self.screenWidth() - 50, 0, 50, 50)) ## Hide the on screen arrow buttons # @param self The object pointer. # @param refresh Choose to immediately refresh screen. def hideArrows(self, refresh=True): self.drawArrowsbool = False if (refresh): self.refresh() ## Show the on screen arrow buttons # @param self The object pointer. # @param refresh Choose to immediately refresh screen. def showArrows(self, refresh=True): self.drawArrowsbool = True if (refresh): self.refresh() ## Reads the x-coordinate of the touchscreen press # @param self The object pointer. # @remark # To use this function in your program: # @code # ... # x = screen.TS_X() # @endcode def TS_X(self): return self.x ## Reads the y-coordinate of the touchscreen press # @param self The object pointer. # To use this function in your program: # @code # ... # y = screen.TS_Y() # @endcode def TS_Y(self): return self.y ## Detects touchscreen presses and prevents false positives, # updates self.x and self.y if pressed. # @param self The object pointer. # To use this function in your program: # @code # ... # if (screen.isTouched()) # print "Touched at {},{}".format(screen.x, screen.y) # @endcode def isTouched(self): x, y = self.comm.getTouchscreenCoordinates() if x == 0 and y == 0: return False self.x = x self.y = y return True ## Clears the LCD screen to defualt black # @param self The object pointer. # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. # To use this function in your program: # @code # ... # screen.clearScreen() # @endcode def clearScreen(self, display=True): self.disp.clear() if (display): self.disp.display() ## Draw a rectangle on the screen (rotated to screen) # @param self The object pointer. # @param x The upper left x coordinate of the rectangle. # @param y The upper left y coordinate of the rectangle. # @param width The width of the rectangle. # @param height The height of the rectangle. # @param fill The color of inside of the rectangle. Optional, defaults to white. # @param outline The color of the outer edge of the rectangle. Optional, defaults to no outline. # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. # @remark # To use this function in your program: # @code # ... # screen.fillRect(100, 100, 75, 75, fill = (255,0,0), outline = (0,0,0)) # @endcode def fillRect(self, x, y, width, height, fill=(255, 255, 255), outline=None, display=True): draw = self.disp.draw() actx = self.screenXFromImageCoords(x, y) acty = self.screenYFromImageCoords(x, y) actx2 = self.screenXFromImageCoords(x + width, y + height) acty2 = self.screenYFromImageCoords(x + width, y + height) draw.rectangle((actx, acty, actx2, acty2), fill=fill, outline=outline) if (display): self.disp.display() ## Draw a filled circle on the screen (rotated to screen) # @param self The object pointer. # @param x The center x coordinate of the circle. # @param y The center y coordinate of the circle. # @param radius The radius of the circle. # @param fill The color of the inside of the circle. Optional, defaults to white. # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. # @remark # To use this function in your program: # @code # ... # screen.fillCircle(100, 100, 15, fill = (255,0,0)) # @endcode def fillCircle(self, x, y, radius, fill=(255, 255, 255), display=True): draw = self.disp.draw() actx = self.screenXFromImageCoords(x, y) acty = self.screenYFromImageCoords(x, y) draw.ellipse( (actx - radius, acty - radius, actx + radius, acty + radius), fill=fill) if (display): self.disp.display() ## Draw a circle on the screen (rotated to screen) # @param self The object pointer. # @param x The center x coordinate of the circle. # @param y The center y coordinate of the circle. # @param radius The radius of the circle. # @param fill The color of the inside of the circle. Optional, defaults to None # @param outline The color of the outer edge of the circle. Optional, defaults to Black # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. # @remark # To use this function in your program: # @code # ... # red circle with blue outline: # screen.drawCircle(100, 100, 15, fill = (255,0,0), outline=(0,0,255)) # @endcode def drawCircle(self, x, y, radius, fill=None, outline=(0, 0, 0), display=True): draw = self.disp.draw() actx = self.screenXFromImageCoords(x, y) acty = self.screenYFromImageCoords(x, y) draw.ellipse( (actx - radius, acty - radius, actx + radius, acty + radius), fill=fill, outline=outline) if (display): self.disp.display() ## Draw a bitmap image on the screen (.png files rcommended) # @param self The object pointer. # @param x The upper left x coordinate of the image. # @param y The upper left y coordinate of the image. # @param width The width of the image. # @param height The width of the image. # @param path The image file path. Optional, defaults to the popup background image. # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. # @remark # To use this function in your program: # @code # ... # screen.screen.fillBmp(30, 0, 240, 240, path = os.path.join(currentdir, "dog.png")) # @endcode def fillBmp(self, x, y, width, height, path="/usr/local/mindsensors/images/Pane1.png", display=True): buff = self.disp.buffer actx = self.screenXFromImageCoords(x, y) acty = self.screenYFromImageCoords(x, y) # if the caller only provided icon name, assume it is in our system repository if (path[0] != "/"): path = "/usr/local/mindsensors/images/" + path # if the image is missing, use a default X image. if (os.path.isfile(path)): image = Image.open(path) else: image = Image.open("/usr/local/mindsensors/images/missing.png") image = image.resize((width, height), Image.ANTIALIAS) cr = self.currentRotation if (cr == 1): actx -= height image = image.transpose(Image.ROTATE_270) if (cr == 2): acty -= height actx -= width image = image.transpose(Image.ROTATE_180) if (cr == 3): acty -= width image = image.transpose(Image.ROTATE_90) buff.paste(image, (actx, acty)) if (display): self.disp.display() ## Draw a image on the screen using supplied image data # @param self The object pointer. # @param x The upper left x coordinate of the image. # @param y The upper left y coordinate of the image. # @param width The width of the image. # @param height The width of the image. # @param image data # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. # @remark # To use this function in your program: # @code # ... # screen.screen.fillBmp(40, 0, 240, 240, image) # @endcode def fillImgArray(self, x, y, width, height, image, display=True): buff = self.disp.buffer actx = self.screenXFromImageCoords(x, y) acty = self.screenYFromImageCoords(x, y) image = Image.fromarray(image) image = image.resize((width, height), Image.ANTIALIAS) cr = self.currentRotation if (cr == 1): actx -= height image = image.transpose(Image.ROTATE_270) if (cr == 2): acty -= height actx -= width image = image.transpose(Image.ROTATE_180) if (cr == 3): acty -= width image = image.transpose(Image.ROTATE_90) buff.paste(image, (actx, acty)) if (display): self.disp.display() ## Rotates the screen orientation 90 degrees to the right (-90 degrees) # @param self The object pointer. # @remark # To use this function in your program: # @code # ... # screen.rotateRight() # @endcode def rotateRight(self): self.currentRotation += 1 if (self.currentRotation > 3): self.currentRotation = 0 self.refresh() ## Rotates the screen orientation 90 degrees to the left (90 degrees) # @param self The object pointer. # @remark # To use this function in your program: # @code # ... # screen.rotateLeft() # @endcode def rotateLeft(self): self.currentRotation -= 1 if (self.currentRotation < 0): self.currentRotation = 3 self.refresh() ## Displays text on the screen with adjusted position and rotation # @param self The object pointer. # @param text The text to display on the screen # @param x The upper left x coordinate of the text. Optional, defaults to "left". Irrelevant if align is "center" # @param y The upper left y coordinate of the text. # @param fill The color of the text. Optional, defaults to white. # @param size The pixel size of the text. Optional, defaults to 20. # @param align The text alignment, "left" or "center" or "right". Optional, defaults to "left". # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. # @remark # To use this function in your program: # @code # ... # screen.drawAutoText("Wow!", 10, 20, fill = (255,255,255), size = 25) # @endcode def drawAutoText(self, text, x, y, fill=(255, 255, 255), size=20, align="left", display=True): text = str(text) font = ImageFont.truetype( "/usr/share/fonts/truetype/freefont/FreeSans.ttf", size) width, height = ImageDraw.Draw(self.disp.buffer).textsize(text, font=font) tempx = self.screenXFromImageCoords(x, y) tempy = self.screenYFromImageCoords(x, y) cr = self.currentRotation if align == "center": tempy = (self.screenWidth() - width) / 2 if cr == 1 or cr == 2: tempx = self.screenHeight() - height - y if cr == 0 or cr == 2: tempx, tempy = tempy, tempx if cr == 0: tempy = y elif align == "right": if cr == 0: tempx = self.screenWidth() - width - x tempy = y if cr == 1: tempx = self.screenHeight() - height - y tempy = self.screenWidth() - width - x if cr == 2: tempx, tempy = x, self.screenHeight() - height - y if cr == 3: tempy = x else: if cr == 1: tempx -= height if cr == 2: tempy -= height tempx -= width if cr == 3: tempy -= width angletemp = -90 * self.currentRotation self.draw_rotated_text(self.disp.buffer, text, (tempx, tempy), angletemp, font, fill, display=display) ## Set the cursor to a specific line of the of the screen # @param self The object pointer. # @param lineno The line number at which to set the cursor. # @remark # To use this function in your program: # @code # ... # screen.termGotoLine(5) # @endcode def termGotoLine(self, lineno): self.terminalCursor = lineno ## Print to a specific line of the screen # @param self The object pointer. # @param lineno The line number at which to set the cursor. # @param text The text to print to the screen. # @remark # To use this function in your program: # @code # ... # screen.termPrintAt(5, "Printing at line 5") # @endcode def termPrintAt(self, lineno, text): self.terminalCursor = lineno self.fillRect(10, self.terminalCursor * 20 + 42, 320, 19, (0, 0, 0), display=False) self.terminalBuffer[self.terminalCursor] = str(text) self.refreshLine(self.terminalCursor) ## Print to the current line of the screen # @param self The object pointer. # @param text The text to print to the screen. # @remark # To use this function in your program: # @code # ... # screen.termPrint("Regular print, no newline") # @endcode def termPrint(self, text): self.terminalBuffer[self.terminalCursor] += str(text) self.refreshLine(self.terminalCursor) ## Print to the current line and then go to the next line # @param self The object pointer. # @param text The text to print to the screen. # @remark # To use this function in your program: # @code # ... # screen.termPrintln("Hello, world!") # @endcode def termPrintln(self, text): if (self.terminalCursor > 9): self.terminalCursor = 0 self.terminalBuffer = [""] * 20 self.refresh() self.termPrint(text) self.terminalCursor += 1 ## Print new text in place of current line (Low Refresh Rate) # @param self The object pointer. # @param text The text to print to the screen. # @remark # To use this function in your program: # @code # ... # screen.termReplaceLastLine("Replaced!") # @endcode def termReplaceLastLine(self, text): self.terminalBuffer[self.terminalCursor] = "" self.fillRect(10, self.terminalCursor * 20 + 42, 320, 19, (0, 0, 0), display=False) self.termPrint(text) ## Refresh a screen line # @param self The object pointer. # @param lineNum The line number to refresh. # @param display Choose to immediately push the drawing to the screen. # @remark # To use this function in your program: # @code # ... # screen.refreshLine(1) # @endcode def refreshLine(self, lineNum, display=True): if (self.currentMode == self.PS_MODE_TERMINAL): self.drawAutoText(self.terminalBuffer[lineNum], 10, lineNum * 20 + 40, (255, 255, 255), display=display) ## Draw a labeled button on the screen (INTERNAL USE ONLY) # @param self The object pointer. # @param x The upper left x coordinate of the rectangle. # @param y The upper left y coordinate of the rectangle. # @param width The width of the button. # @param height The height of the button. # @param prefix The button images filename prefix. Optional, defaults to "btns_" # @param text The button label. Defaults to "OK" # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. # @param align The alignment for the button's text label. # @param image An optional image to be included on the button, should be 32x32. # @param imageX The x-coordinate of the optional image icon. # @param imageY The y-coordinate of the optional image icon. def drawButton(self, x, y, width, height, prefix="btns_", text="OK", display=True, align="left", image=None, imageX=None, imageY=None): self.fillBmp(x, y, 14, height, prefix + "left.png", display=False) self.fillBmp(x + 14, y, width - 28, height, prefix + "center.png", display=False) self.fillBmp(x + width - 14, y, 14, height, prefix + "right.png", display=False) textX = x + 10 if image: textX += 32 imgY = imageY or y + ((height - 32) / 2) imgX = imageX or x + 4 self.fillBmp(imgX, imgY, 32, 32, image, display=False) self.drawAutoText(text, textX, y + (height / 2) - 10, size=16, fill=(0, 0, 0), display=display, align=align) ## Refresh the screen (Slow) # @param self The object pointer. # @remark # To use this function in your program: # @code # ... # screen.refresh() # @endcode def refresh(self): if (self.currentMode == self.PS_MODE_TERMINAL): self.clearScreen(False) if (self.drawArrowsbool): self.drawArrows(False) for i, _ in enumerate(self.terminalBuffer): self.refreshLine(i, display=False) self.disp.display() if (self.currentMode == self.PS_MODE_POPUP): xbuff = 20 ybuff = 20 try: self.fillBmp(xbuff, ybuff, self.screenWidth() - (2 * xbuff), self.screenHeight() - (2 * ybuff), "dialogbg.png", display=False) except: self.fillRect(xbuff, ybuff, self.screenWidth() - (2 * xbuff), self.screenHeight() - (2 * ybuff), fill=(127, 127, 127), outline=(255, 255, 255)) numButts = len(self.buttonText) spacing = 10 room = self.screenWidth() - (xbuff + ybuff) buttHeight = 50 n = 0 while (n < numButts): self.drawButton( (room / numButts) * n + xbuff + spacing / 2 + 10, self.screenHeight() - (ybuff + spacing + buttHeight), (room / numButts) - spacing - 20, buttHeight, prefix="btns_", text=self.buttonText[n], display=False) """ self.fillBmp((room/numButts)*n + xbuff + spacing/2, self.screenHeight() - (ybuff + spacing + buttHeight), (room/numButts) - spacing, buttHeight, path = "button.png", display = False) self.drawAutoText(self.buttonText[n],(room/numButts)*n + xbuff + spacing, self.screenHeight() - (ybuff + buttHeight), fill = (0,0,0), display = False) """ n += 1 n = 0 offset = 5 if (self.currentRotation % 2 == 0): # portrait offset = 12 while (n < len(self.popupText)): if (n > 0): offset = 10 if (self.currentRotation % 2 == 0): # portrait offset = 24 self.drawAutoText(self.popupText[n], xbuff + 10, ybuff + offset + (20 * n), fill=(0, 0, 0), size=15, display=False) n += 1 self.disp.display() ## Determine if an on screen button is pressed # @param self The object pointer. # @param x The upper left x-coordinate of the button. # @param y The upper left y-coordinate of the button. # @param width The width of the button. # @param height The height of the button. # @remark # To use this function in your program: # @code # ... # button = screen.checkButton(0, 0, 50, 50) # @endcode def checkButton(self, x, y, width, height): if self.isTouched(): tsx = self.TS_To_ImageCoords_X(self.x, self.y) tsy = self.TS_To_ImageCoords_Y(self.x, self.y) if tsx in range(x, x + width) and tsy in range(y, y + height): return True return False ## Determines if button in a pop-up window is pressed (Experienced users) # @param self The object pointer. # @param numButts How many buttons are being shown def checkDialogButtons(self, numButts): # see refresh method for value definitions xbuff = 20 ybuff = 20 spacing = 10 room = self.screenWidth() - (xbuff + ybuff) buttHeight = 50 y = self.screenHeight() - (ybuff + spacing + buttHeight) width = (room / numButts) - spacing - 20 for n in range(numButts): x = (room / numButts) * n + xbuff + spacing / 2 + 10 if self.checkButton(x, y, width, buttHeight): return n return -1 ## Display pop-up of a question on the screen # @param self The object pointer. # @param question The question that will pop-up on the screen. The first string will be the titlebar. # @param options The possible answers to the question. # @param touch Whether to check if the on screen buttons are pressed. Optional, defaults to True. # @param goBtn Whether to check for the GO button to close the question. Optional, defaults to False. # @param wrapText When True, long lines of text will be wrapped to fit in the popup. Optional, default to False. # @code # question = ["Title", "This is a very long line of text which will be wrapped to fit in the dialog box.", "Here's a second line. It will be wrapped, too. What do you think?"] # options = ["No thanks", "Cool!"] # answer = screen.askQuestion(question, options, wrapText=True) # @endcode # @note If goBtn is True, pressing GO will close the dialog and return -1 # @remark # To use this function in your program: # @code # ... # question = ["Color Picker", "Pick a color!"] # options = ["Red", "Green", "Blue"] # answer = screen.askQuestion(question, options) # @endcode def askQuestion(self, question, options, touch=True, goBtn=False, wrapText=False): for i, line in enumerate(question): question[i] = str(line) if wrapText: wrap, maxlines = 48, 5 if (self.currentRotation % 2 == 0): # portrait wrap, maxlines = 30, 9 maxWidth = self.screenWidth( ) - 60 # see fillBpm of dialogbg.png in refresh() getTextSize = ImageDraw.Draw(self.disp.buffer).textsize font = ImageFont.truetype( "/usr/share/fonts/truetype/freefont/FreeSans.ttf", 15) def makeWrappedText(): arr = '\n'.join([ textwrap.fill(t, width=wrap) for t in question[1:] ]).split('\n') self.popupText = [question[0]] + arr[:maxlines] if len(arr) > maxlines: if self.popupText[maxlines][-1] == ".": self.popupText[maxlines] += " ..." else: self.popupText[maxlines] += "..." def widestLine(): return max( [getTextSize(str, font=font)[0] for str in self.popupText]) makeWrappedText() while (widestLine() > maxWidth): wrap -= 1 makeWrappedText() else: self.popupText = question self.buttonText = options oldMode = self.currentMode self.setMode(self.PS_MODE_POPUP) if (len(options) >= 4): print "warning!, buttons may be too small to read" if (len(options) <= 0 and not goBtn): print "warning!, no options will leave this pop-up stuck" if goBtn: keyPressCount = self.comm.getKeyPressCount() while (True): if (goBtn and keyPressCount < self.comm.getKeyPressCount()): self.setMode(oldMode) return -1 if (touch and self.isTouched()): n = self.checkDialogButtons(len(options)) if (n != -1): self.setMode(oldMode) return n ## Display Pop-up of 'Yes' or 'No' question on the screen, returning True or False # @param self The object pointer. # @param question The question that will pop-up on the screen. # @param touch Whether to check if on screen buttons are pressed. Optional, defaults to True. # @param goBtn Whether to check for the GO button to close the question. Optional, defaults to False. # @param wrapText When True, long lines of text will be wrapped to fit in the popup. Optional, default to False. # @code # question = ["Title", "This is a very long line of text which will be wrapped to fit in the dialog box.", "Cool?"] # response = screen.askYesOrNoQuestion(question, wrapText=True) # @endcode # @note If goBtn is True, pressing GO will close the dialog and return False # @remark # To use this function in your program: # @code # ... # question = ["Continue?", "Do you want to continue?"] # response = screen.askYesOrNoQuestion(question) # @endcode def askYesOrNoQuestion(self, question, touch=True, goBtn=False, wrapText=False): return self.askQuestion(question, ["Yes", "No"], touch=touch, goBtn=goBtn, wrapText=wrapText) == 0 ## Display pop-up of a message on the screen with a single option "OK" # @param self The object pointer. # @param message The message that will pop-up on the screen. # @param touch Whether to check if on screen buttons are pressed. Optional, defaults to True. # @param goBtn Whether to check for the GO button to close the question. Optional, defaults to True. # @param wrapText When True, long lines of text will be wrapped to fit in the popup. Optional, default to False. # @code # message = ["Title", "This is a very long line of text which will be wrapped to fit in the dialog box.", "Other lines will be wrapped, too. Press OK to close this popup."] # screen.showMessage(message, wrapText=True) # @endcode # @note If goBtn is True, pressing GO will close the dialog and return False # @remark # To use this function in your program: # @code # ... # message = ["Complete", "The process has completed.", "Status: success"] # screen.showMessage(message) # @endcode def showMessage(self, message, touch=True, goBtn=True, wrapText=False): if type(message) is not list: message = ["Message", message] return self.askQuestion(message, ["OK"], touch=touch, goBtn=goBtn, wrapText=wrapText) == 0 ## Display pop-up of a message on the screen with no exit options. # This function will return right away. You may need to call `screen.setMode(screen.PS_MODE_TERMINAL)` to stop the popup later. # @param self The object pointer. # @param message The message that will pop-up on the screen. # @remark # To use this function in your program: # @code # ... # message = ["Processing", "Processing, please wait..."] # screen.forceMessage(message) # @endcode def forceMessage(self, message): self.popupText = message self.buttonText = [] oldMode = self.currentMode self.setMode(self.PS_MODE_POPUP) ## Draw a line on the screen (rotated to screen) # @param self The object pointer. # @param x1, y1, x2, y2 The x and y coordinates of each endpoint of the line. # @param width The width of the line. Optional, defaults to 0. # @param fill The color of line. Optional, defaults to white. # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. # @remark # To use this function in your program: # @code # ... # screen.drawLine(50, 50, 100, 100, width = 0, fill = (255,0,0)) # @endcode def drawLine(self, x1, y1, x2, y2, width=0, fill=(255, 255, 255), display=True): draw = self.disp.draw() actx1 = self.screenXFromImageCoords(x1, y1) acty1 = self.screenYFromImageCoords(x1, y1) actx2 = self.screenXFromImageCoords(x2, y2) acty2 = self.screenYFromImageCoords(x2, y2) draw.line((actx1, acty1, actx2, acty2), fill=fill, width=width) if (display): self.disp.display() ## Draw a polyline on the screen (rotated to screen) # @param self The object pointer. # @param endpoints [x1, y1, x2, y2...] The x and y coordinates of each endpoint of the polyline. # @param width The width of the polyline. Optional, defaults to 0. # @param fill The color of polyline. Optional, defaults to white. # @param display Choose to immediately push the drawing to the screen. Optional, defaults to True. # @remark # To use this function in your program: # @code # ... # screen.drawLine([50, 50, 100, 50, 100, 100], width = 0, fill = (255,0,0)) # @endcode def drawPolyLine(self, endpoints, width=0, fill=(255, 255, 255), display=True): assert len( endpoints ) % 2 == 0, "endpoints must be an array of even length, containing *pairs* of integers" assert len( endpoints ) >= 4, "endpoints must contain at least two coordinates to draw a line" draw = self.disp.draw() actendpts = [] for (x, y) in [(endpoints[i * 2], endpoints[i * 2 + 1]) for i in range(len(endpoints) / 2) ]: # iterate over each pair of integers actendpts.append(self.screenXFromImageCoords( x, y)) # actual x-coordinate actendpts.append(self.screenYFromImageCoords( x, y)) # actual y-coordinate draw.line(actendpts, fill=fill, width=width) if (display): self.disp.display()
# Simple demo of of the WS2801/SPI-like addressable RGB LED lights. import time import RPi.GPIO as GPIO # Import the WS2801 module. import Adafruit_WS2801 import Adafruit_GPIO.SPI as SPI # Configure the count of pixels: PIXEL_COUNT = 31 # Alternatively specify a hardware SPI connection on /dev/spidev0.0: SPI_PORT = 0 SPI_DEVICE = 0 pixels = Adafruit_WS2801.WS2801Pixels(PIXEL_COUNT, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE), gpio=GPIO) # Define the wheel function to interpolate between different hues. def wheel(pos): if pos < 85: return Adafruit_WS2801.RGB_to_color(pos * 3, 255 - pos * 3, 0) elif pos < 170: pos -= 85 return Adafruit_WS2801.RGB_to_color(255 - pos * 3, 0, pos * 3) else: pos -= 170 return Adafruit_WS2801.RGB_to_color(0, pos * 3, 255 - pos * 3) # Define rainbow cycle function to do a cycle of all hues. def rainbow_cycle_successive(pixels, wait=0.1):
import Adafruit_WS2801 import Adafruit_GPIO.SPI as SPI RED = (255, 0, 0) ORANGE = (255, 50, 0) YELLOW = (255, 130, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) PURPLE = (255, 0, 60) BLACK = (0, 0, 0) WHITE = (255, 255, 255) RAINBOW = [RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE] strip_length = 6 strip = Adafruit_WS2801.WS2801Pixels(strip_length, spi=SPI.SpiDev(0, 0)) def random_flashes(): for _ in range(150): for i in range(strip_length): if random.choice([True, False]): c = random.choice(RAINBOW + [WHITE]) strip.set_pixel_rgb(i, *c) strip.show() sleep(0.1) strip.set_pixels_rgb(*BLACK) strip.show()
yield (xmean) # Uncomment one of the blocks of code below to configure your Pi or BBB to use # software or hardware SPI. # Raspberry Pi software SPI configuration. #CLK = 25 #CS = 24 #DO = 18 #sensor = MAX31855.MAX31855(CLK, CS, DO) # Raspberry Pi hardware SPI configuration. SPI_PORT = 0 SPI_DEVICE = 0 sensor = MAX31855.MAX31855(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) # BeagleBone Black software SPI configuration. #CLK = 'P9_12' #CS = 'P9_15' #DO = 'P9_23' #sensor = MAX31855.MAX31855(CLK, CS, DO) # BeagleBone Black hardware SPI configuration. #SPI_PORT = 1 #SPI_DEVICE = 0 #sensor = MAX31855.MAX31855(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) # Loop printing measurements every second. r = range(PLOTSEC)
import Adafruit_GPIO.SPI as SPI import Adafruit_MCP3008 mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(0, 0)) #895 = OK #638 = LEFT #511 = UP #383 = RIGHT #766 = DOWN #255 = BACK #128 = RESET def tol(input): t = 2 return xrange(input - t, input + t) button_map = { tol(895): 'OK', tol(766): 'DOWN', tol(638): 'LEFT', tol(511): 'UP', tol(383): 'RIGHT', tol(255): 'BACK', tol(128): 'RESET', -1: 'NULL' }
def main(argv): tdachboden = '??.?' taussen = '??.?' tgang = '??.?' hdachboden = '??.?' haussen = '??.?' hgang = '??.?' try: opts, args = getopt.getopt(argv, "ha:g:d:A:G:D:", [ "taussen=", "tgang=", "tdachboden=", "haussen=", "hgang=", "hdachboden=" ]) except getopt.GetoptError: print 'weather display.py -a <Temperatur Aussen> -g <Temperatur Gang> -d <Temperatur Dachboden> -A <Luftfeuchte Aussen> -G <Luftfeuchte Gang> -D <LuftfeuchteDachboden>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'weather display.py -a <Temperatur Aussen> -g <Temperatur Gang> -d <Temperatur Dachboden> -A <Luftfeuchte Aussen> -G <Luftfeuchte Gang> -D <LuftfeuchteDachboden>' sys.exit() elif opt in ("-a", "--taussen"): taussen = arg elif opt in ("-g", "--tgang"): tgang = arg elif opt in ("-d", "--tdachboden"): tdachboden = arg elif opt in ("-A", "--haussen"): haussen = arg elif opt in ("-G", "--hgang"): hgang = arg elif opt in ("-D", "--hdachboden"): hdachboden = arg PITFT_2_8 = 18 PITFT_2_2 = 25 CURRENT_PITFT = PITFT_2_2 # Raspberry Pi configuration. DC = CURRENT_PITFT RST = 23 SPI_PORT = 0 SPI_DEVICE = 0 # BeagleBone Black configuration. # DC = 'P9_15' # RST = 'P9_12' # SPI_PORT = 1 # SPI_DEVICE = 0 # Create TFT LCD display class. disp = TFT.ILI9341(DC, rst=RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=64000000)) # Initialize display. disp.begin() # Clear the display to a red background. # Can pass any tuple of red, green, blue values (from 0 to 255 each). disp.clear((0, 0, 0)) # Alternatively can clear to a black screen by calling: # disp.clear() # Get a PIL Draw object to start drawing on the display buffer. draw = disp.draw() # Draw some shapes. # Draw a blue ellipse with a green outline. #draw.ellipse((10, 10, 110, 80), outline=(0,255,0), fill=(0,0,255)) # Draw a purple rectangle with yellow outline. draw.rectangle((40, 320, 115, 220), outline=(255, 213, 0), fill=(255, 213, 0)) draw.rectangle((40, 210, 115, 110), outline=(24, 255, 0), fill=(24, 255, 0)) draw.rectangle((40, 100, 115, 0), outline=(0, 255, 247), fill=(0, 255, 247)) draw.rectangle((125, 320, 200, 220), outline=(191, 160, 0), fill=(191, 160, 0)) draw.rectangle((125, 210, 200, 110), outline=(18, 191, 0), fill=(18, 191, 0)) draw.rectangle((125, 100, 200, 0), outline=(0, 191, 185), fill=(0, 191, 185)) # Draw a white X. #draw.line((10, 170, 110, 230), fill=(255,255,255)) #draw.line((10, 230, 110, 170), fill=(255,255,255)) # Draw a cyan triangle with a black outline. #draw.polygon([(10, 275), (110, 240), (110, 310)], outline=(0,0,0), fill=(0,255,255)) # Load default font. #font = ImageFont.load_default() # Alternatively load a TTF font. # Some other nice fonts to try: http://www.dafont.com/bitmap.php # Define a function to create rotated text. Unfortunately PIL doesn't have good # native support for rotated fonts, but this function can be used to make a # text image and rotate it so it's easy to paste in the buffer. def draw_rotated_text(image, text, position, angle, font, fill=(255, 255, 255)): # Get rendered font width and height. draw = ImageDraw.Draw(image) width, height = draw.textsize(text, font=font) # Create a new image with transparent background to store the text. textimage = Image.new('RGBA', (width, height), (0, 0, 0, 0)) # Render the text. textdraw = ImageDraw.Draw(textimage) textdraw.text((0, 0), text, font=font, fill=fill) # Rotate the text image. rotated = textimage.rotate(angle, expand=1) # Paste the text into the image, using it as a mask for transparency. image.paste(rotated, position, rotated) # Write two lines of white text on the buffer, rotated 90 degrees counter clockwise. font = ImageFont.truetype('/home/pi/weather/monofonto.ttf', 36) draw_rotated_text(disp.buffer, tdachboden, (55, 10), 90, font, fill=(0, 0, 0)) draw_rotated_text(disp.buffer, tgang, (55, 120), 90, font, fill=(0, 0, 0)) draw_rotated_text(disp.buffer, taussen, (55, 230), 90, font, fill=(0, 0, 0)) draw_rotated_text(disp.buffer, hdachboden, (140, 10), 90, font, fill=(0, 0, 0)) draw_rotated_text(disp.buffer, hgang, (140, 120), 90, font, fill=(0, 0, 0)) draw_rotated_text(disp.buffer, haussen, (140, 230), 90, font, fill=(0, 0, 0)) font = ImageFont.truetype('/home/pi/weather/Quadrit.ttf', 14) draw_rotated_text(disp.buffer, 'Dachboden', (0, 7), 90, font, fill=(255, 255, 255)) draw_rotated_text(disp.buffer, 'Wohnraum', (0, 118), 90, font, fill=(255, 255, 255)) draw_rotated_text(disp.buffer, 'Vorgarten', (0, 230), 90, font, fill=(255, 255, 255)) #draw_rotated_text(disp.buffer, 'Luftfeuchte\nDachboden', (195, 10), 90, font, fill=(0,0,0)) #draw_rotated_text(disp.buffer, 'Luftfeuchte\nGang EG', (195, 120), 90, font, fill=(0,0,0)) #draw_rotated_text(disp.buffer, 'Luftfeuchte\nAussen', (195, 230), 90, font, fill=(0,0,0)) #draw_rotated_text(disp.buffer, 'This is a line of text.', (170, 90), 90, font, fill=(255,255,255)) # Write buffer to display hardware, must be called to make things visible on the # display! disp.display()
class MQ(): CLK = 23 MISO = 21 MOSI = 19 CS = 24 mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI) SPI_PORT = 0 SPI_DEVICE = 0 mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) RL_VALUE = 10 RO_CLEAN_AIR_FACTOR = float(4.4) CALIBARAION_SAMPLE_TIMES = 50 CALIBRATION_SAMPLE_INTERVAL = 50 READ_SAMPLE_INTERVAL = 50 READ_SAMPLE_TIMES = 5 GAS_CH4 = 0 def _init_(self, Ro=10, analogPin=1): self.Ro = Ro self.MQ_PIN = analogPin self.CH4Curve = [2.3, 0.26, -0.36] print("Calibrating...") self.Ro = self.MQCalibration(self.MQ_PIN) print("Calibration is done...\n") print("Ro=%f kohm" % self.Ro) def MQPercentage(self): val = {} read = self.MQRead(self.MQ_PIN) val["GAS_CH4"] = self.MQGetGasPercentage(read / self.Ro, self.GAS_CH4) return val def MQResistanceCalculation(self, raw_adc): return float(self.RL_VALUE * (1023.0 - raw_adc) / float(raw_adc)) def MQCalibration(self, mq_pin): val = 0.0 for i in range(self.CALIBARAION_SAMPLE_TIMES): val += self.MQResistanceCalculation(self.mcp.read_adc(mq_pin)) time.sleep(self.CALIBRATION_SAMPLE_INTERVAL / 1000.0) val = val / self.CALIBARAION_SAMPLE_TIMES val = val / self.RO_CLEAN_AIR_FACTOR return val def MQRead(self, mq_pin): rs = 0.0 for i in range(self.READ_SAMPLE_TIMES): rs += self.MQResistanceCalculation(self.mcp.read_adc(mq_pin)) time.sleep(self.READ_SAMPLE_INTERVAL / 1000.0) rs = rs / self.READ_SAMPLE_TIMES return rs def MQGetGasPercentage(self, rs_ro_ratio, gas_id): if (gas_id == self.GAS_CH4): return self.MQGetPercentage(rs_ro_ratio, self.CH4Curve) def MQGetPercentage(self, rs_ro_ratio, pcurve): return (math.pow( 10, (((math.log10(rs_ro_ratio) - pcurve[1]) / pcurve[2]) + pcurve[0])))
import Adafruit_GPIO.SPI as SPI WIDTH = 128 HEIGHT = 160 SPEED_HZ = 4000000 # Raspberry Pi configuration. DC = 24 RST = 25 SPI_PORT = 0 SPI_DEVICE = 0 # Create TFT LCD display class. disp = TFT.ST7735(DC, rst=RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=SPEED_HZ)) # Initialize display. disp.begin() disp.reset() # Load an image. print('Loading image...') image = Image.open('cat.jpg') # Resize the image and rotate it so matches the display. image = image.rotate(270).resize((WIDTH, HEIGHT)) # Draw the image on the display hardware. print('Drawing image') disp.display(image)
A2 = [0]*50 A3 = [0]*50 #ADS settings values = [0]*4 channel = 0 GAIN = 1 #allg. settings timestr = time.strftime("%Y%m%d_%H%M%S") Dateiname = "/home/pi/ACC/logfile.txt" Startzeit = time.time() #Versuchsstartzeit #Settings z.B.Display, GPIOs GPIO.setmode(GPIO.BCM) spiSettings = SPI.SpiDev(0, 0, max_speed_hz=4000000)#Settings Nokia LCD d = LCD.PCD8544(23, 24, spi=spiSettings) #Settings Nokia LCD image = Image.new('1', (LCD.LCDWIDTH, LCD.LCDHEIGHT)) GPIO.setup(6, GPIO.IN, pull_up_down = GPIO.PUD_UP) # GPIO 6 als Input definieren und Pulldown-Widerstand aktivieren #Tgn GPIO.setup(25, GPIO.IN, pull_up_down = GPIO.PUD_UP) # GPIO 6 als Input definieren und Pulldown-Widerstand aktivieren #Trt GPIO.setup(13, GPIO.IN, pull_up_down = GPIO.PUD_UP) # GPIO 6 als Input definieren und Pulldown-Widerstand aktivieren # TGZ_Vg GPIO.setup(9, GPIO.OUT) GPIO.setup(12, GPIO.OUT) GPIO.setup(16, GPIO.OUT) GPIO.setup(17, GPIO.OUT) GPIO.setup(19, GPIO.OUT) GPIO.setup(20, GPIO.OUT) GPIO.setup(21, GPIO.OUT) GPIO.setup(22, GPIO.OUT)
RST = 24 SPI_PORT = 0 SPI_DEVICE = 0 #red = LED(17) #orange = LED(18) #green = LED(19) #blue = LED(10) button1 = Button(2) button2 = Button(3) wait = 0.5 kp = RPi_GPIO.keypad(columnCount=4) disp = LCD.PCD8544(DC, RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=4000000)) disp.begin(contrast=30) def digit(): r = None while r == None: r = kp.getKey() return r def clearLCD(): #image = Image.new('1', (LCD.LCDWIDTH, LCD.LCDHEIGHT)) #draw = ImageDraw.Draw(image) #draw.rectangle((0,0,LCD.LCDWIDTH,LCD.LCDHEIGHT), outline=0, fill=255)
# https://raspberrytips.nl/ws2801-ledstrip/ # Simple demo script for a WS2801/SPI-like addressable RGB LED lightstrip. import time import RPi.GPIO as GPIO import Adafruit_WS2801 import Adafruit_GPIO.SPI as SPI # Configure the count of pixels: PIXEL_COUNT = 32 # Alternatively specify a hardware SPI connection on /dev/spidev0.0: SPI_PORT = 0 SPI_DEVICE = 0 pixels = Adafruit_WS2801.WS2801Pixels(PIXEL_COUNT, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE), gpio=GPIO) # Define the wheel function to interpolate between different hues. def wheel(pos): if pos < 85: return Adafruit_WS2801.RGB_to_color(pos * 3, 255 - pos * 3, 0) elif pos < 170: pos -= 85 return Adafruit_WS2801.RGB_to_color(255 - pos * 3, 0, pos * 3) else: pos -= 170 return Adafruit_WS2801.RGB_to_color(0, pos * 3, 255 - pos * 3)
def Update_Battery(self): f = open('Ubidots_APIkey.txt', 'r') apikey = f.readline().strip() f.close() api = ApiClient(token=apikey) try: batt = api.get_variable("58d763aa762542260cf36f24") except ValueError: print('Value Error') # Raspberry Pi pin configuration: RST = 32 # 128x32 display with hardware I2C: disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST) # Import SPI library (for hardware SPI) and MCP3008 library. import Adafruit_GPIO.SPI as SPI import Adafruit_MCP3008 # Initialize library. disp.begin() time.sleep(5) width = disp.width height = disp.height # Clear display. disp.clear() disp.display() image = Image.new('1', (width, height)) # Get drawing object to draw on image. draw = ImageDraw.Draw(image) # Load default font. font = ImageFont.load_default() # Alternatively load a TTF font. Make sure the .ttf font file is in the same directory as the python script! # Some other nice fonts to try: http://www.dafont.com/bitmap.php #font = ImageFont.truetype('Minecraftia.ttf', 8) # Hardware SPI configuration: SPI_PORT = 0 SPI_DEVICE = 0 mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) # Main program loop. time.sleep(3) # Draw a black filled box to clear the image. draw.rectangle((0, 0, width, height), outline=0, fill=0) value = mcp.read_adc(0) volts = ((value * 3.3)) / float(1023) #voltage divider voltage volts = volts * 5.7 #actual voltage volts = round(volts, 2) if (volts >= 13.6): batt = 100 print('100% Battery') draw.text((0, 0), 'Battery percent at: ', font=font, fill=255) draw.text((50, 20), str(batt), font=font, fill=255) disp.image(image) disp.display() time.sleep(1) elif (volts > 11.6): batt = round((volts - 11.6) * 50, 1) print(batt, '% Battery') draw.text((10, 0), 'Battery percent at: ', font=font, fill=255) draw.text((45, 20), str(batt), font=font, fill=255) disp.image(image) disp.display() time.sleep(1) else: print('Connection Error') draw.text((55, 10), ':(', font=font, fill=255) disp.image(image) disp.display() # Print the ADC values. # Pause time. time.sleep(1) battery = volts try: batt.save_value({'value': battery}) time.sleep(1) except: print('Unable to connect to Ubidots batt') self.avg_batt.setText('{}%'.format(battery))
def __init__(self, lcd_dev=None, lcd_settings_dict=None): if lcd_dev: self.logger = logging.getLogger("{}_{}".format( __name__, lcd_dev.unique_id.split('-')[0])) self.interface = lcd_dev.interface self.lcd_x_characters = lcd_dev.x_characters self.lcd_type = lcd_dev.lcd_type # I2C self.i2c_address = int(lcd_dev.location, 16) self.i2c_bus = lcd_dev.i2c_bus # SPI self.spi_bus = lcd_dev.spi_bus self.spi_device = lcd_dev.spi_device self.pin_dc = lcd_dev.pin_dc self.pin_reset = lcd_dev.pin_reset self.pin_cs = lcd_dev.pin_cs elif lcd_settings_dict: self.logger = logging.getLogger("{}_{}".format( __name__, lcd_settings_dict["unique_id"].split('-')[0])) self.interface = lcd_settings_dict["interface"] self.lcd_x_characters = lcd_settings_dict["x_characters"] self.lcd_type = lcd_settings_dict["lcd_type"] # I2C self.i2c_address = int(lcd_settings_dict["i2c_address"], 16) self.i2c_bus = lcd_settings_dict["i2c_bus"] # SPI self.spi_bus = lcd_settings_dict["spi_bus"] self.spi_device = lcd_settings_dict["spi_device"] self.pin_dc = lcd_settings_dict["pin_dc"] self.pin_reset = lcd_settings_dict["pin_reset"] self.pin_cs = lcd_settings_dict["pin_cs"] self.disp = None if self.interface == 'I2C': if self.lcd_type == '128x32_pioled_circuit_python': self.disp = adafruit_ssd1306.SSD1306_I2C( 128, 32, ExtendedI2C(self.i2c_bus), addr=int(str(self.i2c_address), 16)) elif self.lcd_type == '128x64_pioled_circuit_python': self.disp = adafruit_ssd1306.SSD1306_I2C( 128, 64, ExtendedI2C(self.i2c_bus), addr=int(str(self.i2c_address), 16)) elif self.interface == 'SPI': if self.lcd_type == '128x32_pioled_circuit_python': import Adafruit_GPIO.SPI as SPI self.disp = adafruit_ssd1306.SSD1306_SPI(128, 32, spi=SPI.SpiDev( self.spi_bus, self.spi_device), dc=self.pin_dc, reset=self.pin_reset, cs=self.pin_cs) elif self.lcd_type == '128x64_pioled_circuit_python': import Adafruit_GPIO.SPI as SPI self.disp = adafruit_ssd1306.SSD1306_SPI(128, 64, spi=SPI.SpiDev( self.spi_bus, self.spi_device), dc=self.pin_dc, reset=self.pin_reset, cs=self.pin_cs) if not self.disp: self.logger.error( "Unable to set up display. Check the LCD settings.")
print "This means that level 1 and initial snake's length = 4" GPIO.setmode(GPIO.BCM) GPIO.setup(23,GPIO.IN,pull_up_down=GPIO.PUD_UP) GPIO.setup(24,GPIO.IN,pull_up_down=GPIO.PUD_UP) try: GPIO.add_event_detect(23,GPIO.RISING,callback=dirTurnLeft,bouncetime=200) GPIO.add_event_detect(24,GPIO.RISING,callback=dirTurnRight,bouncetime=200) # Raspberry Pi pin configuration RST = 17 # Note the following are only used with SPI: DC = 27 SPI_PORT = 0 SPI_DEVICE = 0 # 128x64 display with hardware SPI disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000)) # Initialize library disp.begin() # Clear display disp.clear() disp.display() # Create blank image for drawing. # Make sure to create image with mode '1' for 1-bit color. width = disp.width height = disp.height except KeyboardInterrupt: print "*** GPIO clean up ***" GPIO.cleanup()
class mindsensorsUI(): ## Default Device I2C Address PS_ADDRESS = 0x34 ## Touchscreen X-axis Register. Will return an unsigned integer reading (0-340) PS_TSX = 0xE3 ## Touchscreen Y-axis Register. Will return an unsigned integer reading (0-440) PS_TSY = 0xE5 ## Constant to specify black color PS_BLACK = (0, 0, 0) ## Constant to specify blue color PS_BLUE = (0, 0, 255) ## Constant to specify red color PS_RED = (255, 0, 0) ## Constant to specify green color PS_GREEN = (0, 255, 0) ## Constant to specify cyan color PS_CYAN = (0, 255, 255) ## Constant to specify magenta color PS_MAGENTA = (255, 0, 255) ## Constant to specify yellow color PS_YELLOW = (255, 255, 0) ## Constant to specify white color PS_WHITE = (255, 255, 255) ## Constant to defualt screen width PS_SCREENWIDTH = 240 ## Constant to defualt screen height PS_SCREENHEIGHT = 320 ### @cond #PS_XMIN = 0x5A #PS_XMAX = 0x5C #PS_YMIN = 0x5E #PS_YMAX = 0x60 ## Constant to specify terminal mode PS_MODE_TERMINAL = 0 ## Constant to specify pop-up mode PS_MODE_POPUP = 1 ## Constant to specify dead mode PS_MODE_DEAD = 2 ## Dictionary of default emnpty terminal buffer terminalBuffer = [ "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" ] ## Variable of default terminal cursor position terminalCursor = 0 ## Variable of default mode currentMode = 0 ## Variable of default rotation currentRotation = 0 ## Instance to initialize the display disp = TFT.ILI9341(24, rst=25, spi=SPI.SpiDev(0, 0, max_speed_hz=64000000)) ## Variable of default button text buttonText = ["OK", "Cancel"] ## Variable of default pop-up text popupText = ["Do you wish to continue?"] ## Variable of default draw arrow state drawArrowsbool = False touchIgnoreX = 0 touchIgnoreY = 0 ### @endcond ## Initialize the PiStorms motor and sensor ports # @param self The object pointer. # @param name The display title that will appear at the top of the LCD touchscreen. # @param rotation The rotation of the LCD touchscreen. # @param device The device on which the LCD touchscreen is used. # @remark # There is no need to use this function directly. To initialize the mindsensorsUI class in your program: # @code # from mindsensorsUI import mindsensorsUI # ... # screen = mindsensorsUI() # @endcode def __init__(self, name="PiStorms", rotation=3, device=Dev_PiStorms): if device == Dev_SensorShield: self.PS_ADDRESS = 0x16 self.PS_TSX = 0x56 self.PS_TSY = 0x58 self.i2c = mindsensors_i2c(self.PS_ADDRESS >> 1) self.disp.begin() self.clearScreen() try: self.touchIgnoreX = self.TS_X() self.touchIgnoreY = self.TS_Y() self.calibrateTouched() except: pass if (rotation > 0 and rotation < 4): self.currentRotation = rotation self.refresh() self.myname = name self.drawDisplay(name, display=False) ### @cond ## Dumps the screen buffer # @param self The object pointer. def dumpTerminal(self): self.terminalBuffer = [ "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" ] self.terminalCursor = 0 if (self.getMode() == self.PS_MODE_TERMINAL): self.refresh() ## Sets the mode(Experienced users) # @param self The object pointer. def setMode(self, mode=0): if (mode < 0 or mode > 2): self.currentMode = self.PS_MODE_DEAD else: self.currentMode = mode self.refresh() ## Returns the value of the mode(Experienced users) # @param self The object pointer. def getMode(self): return self.currentMode def calibrateTouched(self): self.touchIgnoreX = self.TS_X() self.touchIgnoreY = self.TS_Y() ## Draw a rectangle with rounded edges on the screen (rotated to screen) # @param self The object pointer. # @param x The upper left x coordinate of the rectangle. # @param y The upper left y coordinate of the rectangle. # @param width The width of the rectangle. # @param height The height of the rectangle. # @param radius The arc of the rectangle corners. # @param fill The color of the inside of the rectangle. # @param display Choose to immediately push the drawing to the screen. def fillRoundRect(self, x, y, width, height, radius, fill=(255, 255, 255), display=True): self.fillRect(x, y + radius, width, height - (radius * 2), fill=fill, display=False) self.fillRect(x + radius, y, width - (radius * 2), height, fill=fill, display=False) self.fillCircle(x + radius, y + radius, radius, fill=fill, display=False) self.fillCircle(x + width - radius, y + radius, radius, fill=fill, display=False) self.fillCircle(x + radius, y + height - radius, radius, fill=fill, display=False) self.fillCircle(x + width - radius, y + height - radius, radius, fill=fill, display=display) ## Calculates the x-coordinate of the screen upon rotation(INTERNAL USE ONLY) # @param self The object pointer. # @param x The x-coordinate. # @param y The y-coordinate. def screenXFromImageCoords(self, x=0, y=0): currentRotation = self.currentRotation if (currentRotation == 0): return x if (currentRotation == 1): return self.PS_SCREENWIDTH - y if (currentRotation == 2): return self.PS_SCREENWIDTH - x if (currentRotation == 3): return y ## Calculates the y-coordinate of the screen upon rotation(INTERNAL USE ONLY) # @param self The object pointer. # @param x The x-coordinate. # @param y The y-coordinate. def screenYFromImageCoords(self, x=0, y=0): cr = self.currentRotation if (cr == 0): return y if (cr == 1): return x if (cr == 2): return self.PS_SCREENHEIGHT - y if (cr == 3): return self.PS_SCREENHEIGHT - x ## Displays rotated text (INTERNAL USE ONLY) # @param self The object pointer. # @param image The image used for creating text # @param text The text to display on the screen # @param position The position of the text as a set of x and y-coordinates # @param angle The angle at which to rotate the text # @param font The font of the text # @param fill The color of the text # @param display Choose to immediately push the drawing to the screen. def draw_rotated_text(self, image, text, position, angle, font, fill=(255, 255, 255), display=True): draw = ImageDraw.Draw(image) width, height = draw.textsize(text, font=font) textimage = Image.new('RGBA', (width, height), (0, 0, 0, 0)) textdraw = ImageDraw.Draw(textimage) textdraw.text((0, 0), text, font=font, fill=fill) rotated = textimage.rotate(angle, expand=1) image.paste(rotated, position, rotated) if (display): self.disp.display() ## Determines the width of the screen based on rotation (experienced users) # @param self The object pointer. def screenWidth(self): if (self.currentRotation == 1 or self.currentRotation == 3): return 320 else: return 240 ## Determines the height of the screen based on rotation (experienced users) # @param self The object pointer. def screenHeight(self): if (self.currentRotation == 1 or self.currentRotation == 3): return 240 else: return 320 ## Prints the name text on the screen # @param self The object pointer. # @param name The display title that will appear at the top of the LCD touchscreen. # @param display Choose to immediately push the drawing to the screen. def drawDisplay(self, name, display=True): self.drawAutoText(name, 50, 0, fill=(0, 255, 255), size=40, display=display) ## Draw a labeled button on the screen # @param self The object pointer. # @param x The upper left x coordinate of the rectangle. # @param y The upper left y coordinate of the rectangle. # @param width The width of the button. # @param height The height of the button. # @param text The button label. # @param display Choose to immediately push the drawing to the screen. # disabled by Deepak #def drawButton(self,x,y,width = 150,height = 50, text = "OK", display = True): # self.fillBmp(x,y,width,height,path = "/usr/local/lib/python2.7/dist-packages/mindsensors_images/button.png", display = False) # self.drawAutoText(text, x + 10,y + 15, fill = (0,0,0), display = display) ## Draw forward and back arrows on the screen # @param self The object pointer. # @param display Choose to immediately push the drawing to the screen. def drawArrows(self, display=True): self.drawButton(0, 0, 50, 40, "<", display=False) self.drawButton(self.screenWidth() - 50, 0, 50, 40, ">", display=display) ## Determine if either on screen arrow button is pressed # @param self The object pointer. def checkArrows(self): return (self.checkButton(0, 0, 50, 50), self.checkButton(self.screenWidth() - 50, 0, 50, 50)) ## Hide the on screen arrow buttons # @param self The object pointer. # @param refresh Choose to immediately refresh screen. def hideArrows(self, refresh=True): self.drawArrowsbool = False if (refresh): self.refresh() ## Show the on screen arrow buttons # @param self The object pointer. # @param refresh Choose to immediately refresh screen. def showArrows(self, refresh=True): self.drawArrowsbool = True if (refresh): self.refresh() ## Determines if button in a pop-up window is pressed (experienced users) # @param self The object pointer. # @param xbuff The x-coordinate buffer. # @param ybuff The y-coordinate buffer. # @param buttHeight The height of the button. def calculateButton(self, xbuff, ybuff, buttHeight): n = 0 while (n < len(self.buttonText)): numButts = len(self.buttonText) room = self.screenWidth() - (xbuff + ybuff) xlb = (room / numButts) * n + xbuff ylb = self.screenHeight() - (ybuff + buttHeight) xub = xlb + (room / numButts) yub = ylb + buttHeight axlb = self.screenXFromImageCoords(xlb, ylb) aylb = self.screenYFromImageCoords(xlb, ylb) axub = self.screenXFromImageCoords(xub, yub) ayub = self.screenYFromImageCoords(xub, yub) if (axub < axlb): tempx = axub axub = axlb axlb = tempx if (ayub < aylb): tempy = ayub ayub = aylb aylb = tempy tsx = self.TS_X() tsy = self.TS_Y() #print str(tsy) + " " + str(aylb) + " " + str(ayub) if (tsx < axub and tsx > axlb and tsy > aylb and tsy < ayub): return n n += 1 return -1 ### @endcond ## Reads the x-coordinate of the touchscreen press # @param self The object pointer. # @remark # To use this function in your program: # @code # ... # x = screen.TS_X() # @endcode def TS_X(self): return self.i2c.readInteger(self.PS_TSY) ## Reads the y-coordinate of the touchscreen press # @param self The object pointer. # To use this function in your program: # @code # ... # y = screen.TS_Y() # @endcode def TS_Y(self): return self.i2c.readInteger(self.PS_TSX) ## Detects touchscreen presses and prevents false positives # @param self The object pointer. # To use this function in your program: # @code # ... # touch = screen.isTouched() # @endcode def isTouched(self): firstTry = self.touchIgnoreX == self.TS_X( ) and self.touchIgnoreY == self.TS_Y() secondTry = self.touchIgnoreX == self.TS_X( ) and self.touchIgnoreY == self.TS_Y() thirdTry = self.touchIgnoreX == self.TS_X( ) and self.touchIgnoreY == self.TS_Y() return (not firstTry) and (not secondTry) and (not thirdTry) ## Clears the LCD screen to defualt black # @param self The object pointer. # @param display Choose to immediately push the drawing to the screen. # To use this function in your program: # @code # ... # screen.clearScreen(True) # @endcode def clearScreen(self, display=True): self.disp.clear() if (display): self.disp.display() ## Draw a rectangle on the screen (rotated to screen) # @param self The object pointer. # @param x The upper left x coordinate of the rectangle. # @param y The upper left y coordinate of the rectangle. # @param width The width of the rectangle. # @param height The height of the rectangle. # @param fill The color of inside of the rectangle. # @param outline The color of the outer edge of the rectangle. # @param display Choose to immediately push the drawing to the screen. # @remark # To use this function in your program: # @code # ... # screen.fillRect(100, 100, 75, 75, fill = (255,0,0), None, True) # @endcode def fillRect(self, x, y, width, height, fill=(255, 255, 255), outline=None, display=True): draw = self.disp.draw() actx = self.screenXFromImageCoords(x, y) acty = self.screenYFromImageCoords(x, y) actx2 = self.screenXFromImageCoords(x + width, y + height) acty2 = self.screenYFromImageCoords(x + width, y + height) draw.rectangle((actx, acty, actx2, acty2), fill=fill, outline=outline) if (display): self.disp.display() ## Draw a circle on the screen (rotated to screen) # @param self The object pointer. # @param x The center x coordinate of the circle. # @param y The center y coordinate of the circle. # @param radius The radius of the circle. # @param fill The color of the inside of the circle. # @param display Choose to immediately push the drawing to the screen. # @remark # To use this function in your program: # @code # ... # screen.fillCircle(100, 100, 15, fill = (255,255,255), True) # @endcode def fillCircle(self, x, y, radius, fill=(255, 255, 255), display=True): draw = self.disp.draw() actx = self.screenXFromImageCoords(x, y) acty = self.screenYFromImageCoords(x, y) draw.ellipse( (actx - radius, acty - radius, actx + radius, acty + radius), fill=fill) if (display): self.disp.display() ## Draw a bitmap image on the screen (.png files rcommended) # @param self The object pointer. # @param x The upper left x coordinate of the image. # @param y The upper left y coordinate of the image. # @param width The width of the image. # @param height The width of the image. # @param path The image file path. # @param display Choose to immediately push the drawing to the screen. # @remark # To use this function in your program: # @code # ... # screen.screen.fillBmp(30, 0, 240, 240, path = currentdir+'/'+"dog.png", True) # @endcode def fillBmp( self, x, y, width, height, path="/usr/local/lib/python2.7/dist-packages/mindsensors_images/Pane1.png", display=True): buff = self.disp.buffer actx = self.screenXFromImageCoords(x, y) acty = self.screenYFromImageCoords(x, y) # if the caller only provided icon name, assume it is in our system repository if (path[0] != "/"): path = "/usr/local/lib/python2.7/dist-packages/mindsensors_images/" + path image = Image.open(path) non_transparent = Image.new('RGBA', image.size, (255, 255, 255, 255)) #changed by Deepak. non_transparent.paste(image, (0, 0)) tempimage = image tempimage = tempimage.resize((width, height), Image.ANTIALIAS) tempimage = tempimage.rotate(-90 * self.currentRotation) cr = self.currentRotation if (cr == 1): actx -= height if (cr == 2): acty -= height actx -= width if (cr == 3): acty -= width #changed by Deepak. buff.paste(tempimage, (actx, acty)) if (display): self.disp.display() ## Rotates the screen orientation 90 degrees to the right (-90 degrees) # @param self The object pointer. # @remark # To use this function in your program: # @code # ... # screen.rotateRight() # @endcode def rotateRight(self): self.currentRotation += 1 if (self.currentRotation > 3): self.currentRotation = 0 self.refresh() ## Rotates the screen orientation 90 degrees to the left (90 degrees) # @param self The object pointer. # @remark # To use this function in your program: # @code # ... # screen.rotateLeft() # @endcode def rotateLeft(self): self.currentRotation -= 1 if (self.currentRotation < 0): self.currentRotation = 3 self.refresh() ## Displays text on the screen with adjusted position and rotation # @param self The object pointer. # @param text The text to display on the screen # @param x The upper left x coordinate of the text. # @param y The upper left y coordinate of the text. # @param fill The color of the text # @param size The pixel size of the text # @param display Choose to immediately push the drawing to the screen. # @remark # To use this function in your program: # @code # ... # screen.drawAutoText(self.terminalBuffer[lineNum], 10, 20, fill = (255,255,255), 25, True) # @endcode def drawAutoText(self, text, x, y, fill=(255, 255, 255), size=20, display=True, align="left"): font = ImageFont.truetype( "/usr/share/fonts/truetype/freefont/FreeSans.ttf", size) linew, lineh = font.getsize(text) width, height = ImageDraw.Draw(self.disp.buffer).textsize(text, font=font) tempx = self.screenXFromImageCoords(x, y) tempy = self.screenYFromImageCoords(x, y) cr = self.currentRotation if (cr == 1): tempx -= height if (cr == 2): tempy -= height tempx -= width if (cr == 3): tempy -= width if (align == "center"): tempy -= linew / 2 angletemp = 0 angletemp -= 90 * self.currentRotation self.draw_rotated_text(self.disp.buffer, text, (tempx, tempy), angletemp, font, fill, display=display) ## Set the cursor to a specific line of the of the screen # @param self The object pointer. # @param lineno The line number at which to set the cursor. # @remark # To use this function in your program: # @code # ... # screen.termGotoLine(5) # @endcode def termGotoLine(self, lineno): self.terminalCursor = lineno ## Print to a specific line of the screen # @param self The object pointer. # @param lineno The line number at which to set the cursor. # @param text The text to print to the screen. # @remark # To use this function in your program: # @code # ... # screen.termPrintAt(5, "Print At Line 5") # @endcode def termPrintAt(self, lineno, text): self.terminalCursor = lineno self.fillRect(10, self.terminalCursor * 20 + 42, 320, 19, (0, 0, 0), display=False) self.terminalBuffer[self.terminalCursor] = str(text) self.refreshLine(self.terminalCursor) ## Print to the current line of the screen # @param self The object pointer. # @param text The text to print to the screen. # @remark # To use this function in your program: # @code # ... # screen.termPrint("Print Now") # @endcode def termPrint(self, text): self.terminalBuffer[self.terminalCursor] = self.terminalBuffer[ self.terminalCursor] + str(text) self.refreshLine(self.terminalCursor) ## Print to the current line of the screen followed by a line feed # @param self The object pointer. # @param text The text to print to the screen. # @remark # To use this function in your program: # @code # ... # screen.termPrintln("Print Now") # @endcode def termPrintln(self, text): if (self.terminalCursor > 9): self.terminalCursor = 0 self.terminalBuffer = [ "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" ] self.refresh() self.termPrint(text) self.terminalCursor += 1 ## Print new text in place of current line (Low Refresh Rate) # @param self The object pointer. # @param text The text to print to the screen. # @remark # To use this function in your program: # @code # ... # screen.termReplaceLastLine("Print Now") # @endcode def termReplaceLastLine(self, text): self.terminalBuffer[self.terminalCursor] = "" #self.fillRect(10,self.terminalCursor*20 + 40,320,self.terminalCursor*20 + 35,(0,0,0), display = False) #self.fillRect(10,self.terminalCursor*15 + 40,320,self.terminalCursor*15 + 35,(0,0,0), display = False) self.fillRect(10, self.terminalCursor * 20 + 42, 320, 19, (0, 0, 0), display=False) self.termPrint(text) ## Refresh a screen line # @param self The object pointer. # @param text The text to print to the screen. # @param display Choose to immediately push the drawing to the screen. # @remark # To use this function in your program: # @code # ... # screen.refreshLine(1,True) # @endcode def refreshLine(self, lineNum, display=True): if (self.currentMode == self.PS_MODE_TERMINAL): self.drawAutoText(self.terminalBuffer[lineNum], 10, lineNum * 20 + 40, (255, 255, 255), display=display) ## drawButton def drawButton(self, x, y, width, height, prefix="btns_", text="OK", display=True, align="left"): self.fillBmp(x, y, 14, height, prefix + "left.png", display=display) self.fillBmp(x + 14, y, width - 28, height, prefix + "center.png", display=display) self.fillBmp(x + width - 14, y, 14, height, prefix + "right.png", display=display) self.drawAutoText(text, x + 10, y + (height / 2) - 10, fill=(0, 0, 0), display=display, align=align) ## Refresh the screen (Slow) # @param self The object pointer. # @remark # To use this function in your program: # @code # ... # screen.refresh() # @endcode def refresh(self): if (self.currentMode == self.PS_MODE_TERMINAL): self.clearScreen(False) self.drawDisplay("", False) if (self.drawArrowsbool): self.drawArrows(False) temp = 0 while (temp < len(self.terminalBuffer)): if (self.terminalBuffer[temp] != ""): self.refreshLine(temp, display=False) temp += 1 self.disp.display() if (self.currentMode == self.PS_MODE_POPUP): xbuff = 20 ybuff = 20 #self.fillRect(xbuff,ybuff,self.screenWidth()-(2*xbuff),self.screenHeight()-(2*ybuff),fill = (127,127,127), outline = (255,255,255)) self.fillBmp(xbuff, ybuff, self.screenWidth() - (2 * xbuff), self.screenHeight() - (2 * ybuff), "dialogbg.png", display=False) numButts = len(self.buttonText) spacing = 10 room = self.screenWidth() - (xbuff + ybuff) buttHeight = 50 n = 0 while (n < numButts): self.drawButton( (room / numButts) * n + xbuff + spacing / 2 + 10, self.screenHeight() - (ybuff + spacing + buttHeight), (room / numButts) - spacing - 20, buttHeight, prefix="btns_", text=self.buttonText[n], display=False) """ self.fillBmp((room/numButts)*n + xbuff + spacing/2, self.screenHeight() - (ybuff + spacing + buttHeight), (room/numButts) - spacing, buttHeight, path = "button.png", display = False) self.drawAutoText(self.buttonText[n],(room/numButts)*n + xbuff + spacing, self.screenHeight() - (ybuff + buttHeight), fill = (0,0,0), display = False) """ n += 1 n = 0 offset = 5 while (n < len(self.popupText)): if (n > 0): offset = 10 self.drawAutoText(self.popupText[n], xbuff + 10, ybuff + offset + (20 * n), fill=(0, 0, 0), size=15, display=False) n += 1 self.disp.display() ## Determine if an on screen button is pressed # @param self The object pointer. # @param x The upper left x-coordinate of the button. # @param y The upper left y-coordinate of the button. # @param width The width of the button. # @param height The height of the button. # @remark # To use this function in your program: # @code # ... # button = screen.checkButton(0,0,50,50) # @endcode def checkButton(self, x, y, width=150, height=50): if (self.isTouched()): axlb = self.screenXFromImageCoords(x, y) aylb = self.screenYFromImageCoords(x, y) axub = self.screenXFromImageCoords(x + width, y + height) ayub = self.screenYFromImageCoords(x + width, y + height) if (axub < axlb): tempx = axub axub = axlb axlb = tempx if (ayub < aylb): tempy = ayub ayub = aylb aylb = tempy tsx = self.TS_X() tsy = self.TS_Y() tsx2 = self.TS_X() tsy2 = self.TS_Y() if (tsx != tsx2): tsx = self.TS_X() if (tsy != tsy2): tsy = self.TS_Y() if (tsx < axub and tsx > axlb and tsy > aylb and tsy < ayub): return True return False ## Display pop-up of a question on the screen # @param self The object pointer. # @param question The question that will pop-up on the screen. # @param options The possible answers to the question. # @remark # To use this function in your program: # @code # ... # answer = screen.askQuestion(["Continue?"],["Yes","No"]) # @endcode def askQuestion(self, question=["Continue?"], options=["Yes", "No"]): self.popupText = question self.buttonText = options oldMode = self.currentMode self.setMode(self.PS_MODE_POPUP) if (len(options) > 5): print "warning!, buttons may be too small to read" while (True): if (self.isTouched()): tempthis = self.calculateButton( 20, 20, 50 ) #check four times in a row, and only return if all four readings were the same tempthis2 = self.calculateButton(20, 20, 50) tempthis3 = self.calculateButton(20, 20, 50) tempthis4 = self.calculateButton(20, 20, 50) if (tempthis != -1 and tempthis == tempthis2 and tempthis2 == tempthis3 and tempthis3 == tempthis4): self.setMode(oldMode) return tempthis ## Display Pop-up of 'Yes' or 'No' question on the screen # @param self The object pointer. # @param question The question that will pop-up on the screen. # @remark # To use this function in your program: # @code # ... # answer = screen.askYesOrNoQuestion(["Continue?"]) # @endcode def askYesOrNoQuestion(self, question=["Continue?"]): return self.askQuestion(question, ["Yes", "No"]) == 0
import time import csv import emergency import statistics as st # Import SPI library (for hardware SPI) and MCP3008 library. import Adafruit_GPIO.SPI as SPI import Adafruit_MCP3008 import os SPI_PORT = 0 SPI_DEVICE = 0 mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) print('Reading MCP3008 values...') print('values') ref = 512 ctr = 0 g = 0 # Main program loop. while True: value = mcp.read_adc(0) if value >= ref or value <= 10: print("Not human") else: with open('values.csv', 'a') as csvfile: writer = csv.writer(csvfile) writer.writerow([value]) print(str(value)) if g == 1 and ctr == 60: g = 0 ctr = 0
def __init__(self, channel): self.curVal = 0.0 self.channel = channel self.mcp = Adafruit_MCP3008.MCP3008( spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))