Ejemplo n.º 1
0
def test_init_128x64():
    """
    SH1106 OLED with a 128 x 64 resolution works correctly.
    """
    sh1106(serial)
    serial.command.assert_has_calls([
        # Initial burst are initialization commands
        call(174, 32, 16, 176, 200, 0, 16, 64, 161, 166, 168, 63, 164,
             211, 0, 213, 240, 217, 34, 218, 18, 219, 32, 141, 20),
        # set contrast
        call(129, 127),
        # reset the display
        call(176, 2, 16),
        call(177, 2, 16),
        call(178, 2, 16),
        call(179, 2, 16),
        call(180, 2, 16),
        call(181, 2, 16),
        call(182, 2, 16),
        call(183, 2, 16)
    ])

    # Next 1024 are all data: zero's to clear the RAM
    # (1024 = 128 * 64 / 8)
    serial.data.assert_has_calls([call([0] * 128)] * 8)
Ejemplo n.º 2
0
def test_init_128x64():
    """
    SH1106 OLED with a 128 x 64 resolution works correctly.
    """
    sh1106(serial)
    serial.command.assert_has_calls([
        # Initial burst are initialization commands
        call(174, 32, 16, 176, 200, 0, 16, 64, 161, 166, 168, 63, 164, 211, 0,
             213, 240, 217, 34, 218, 18, 219, 32, 141, 20),
        # set contrast
        call(129, 127),
        # reset the display
        call(176, 2, 16),
        call(177, 2, 16),
        call(178, 2, 16),
        call(179, 2, 16),
        call(180, 2, 16),
        call(181, 2, 16),
        call(182, 2, 16),
        call(183, 2, 16)
    ])

    # Next 1024 are all data: zero's to clear the RAM
    # (1024 = 128 * 64 / 8)
    serial.data.assert_has_calls([call([0] * 128)] * 8)
Ejemplo n.º 3
0
	def __init__(self, rows=64, cols=128, spi_device=0, spi_port=0, gpio_DC=24, gpio_RST=25,devicetype=u'ssd1306'):

		
		self.spi_port = spi_port
		self.spi_device = spi_device
		self.gpio_DC = gpio_DC
		self.gpio_RST = gpio_RST

		self.rows = rows
		self.cols = cols

		self.fb = [[]]

		# Initialize the default font
		font = fonts.bmfont.bmfont('latin1_5x8_fixed.fnt')
		self.fp = font.fontpkg

		#serial = i2c(port=spi_port, address=spi_device)
		
		serial = spi (port = spi_port, device = spi_device, gpio_DC = gpio_DC, gpio_RST = gpio_RST)

		if devicetype.lower() == u'ssd1306':
			self.device = ssd1306(serial)
		elif devicetype.lower() == u'sh1106':
			self.device = sh1106(serial)
		elif devicetype.lower() == u'ssd1322':
			self.device = ssd1322(serial)
		elif devicetype.lower() == u'ssd1325':
			self.device = ssd1325(serial)
		elif devicetype.lower() == u'ssd1331':
			self.device = ssd1331(serial)
		else:
			raise ValueError('{0} not a recognized luma device type'.format(devicetype))
Ejemplo n.º 4
0
    def from_config(self, config) -> 'LevelDisplay':
        # Temporary Variables
        active       = config["LevelDisplay"]["active"]
        address      = config["LevelDisplay"]["i2c_address"]
        port         = config["LevelDisplay"]["i2c_port"]
        left         = config["LevelDisplay"]["left"]
        right        = config["LevelDisplay"]["right"]
        if "db_markers" in config["LevelDisplay"].keys():
            db_markers = config["LevelDisplay"]["db_markers"]
            scale      = [db_to_fader(db) for db in db_markers]
        else:
            db_markers = None

        # Set the initial values
        self.active = active
        if self.active:
            self.serial     = i2c(port=port, address=address)
            self.device     = sh1106(self.serial)
            self.font       = ImageFont.truetype("fonts/Inter-Medium.ttf", 10)
            self.font_small = ImageFont.truetype("fonts/Inter-Light.ttf", 7)
            self.left       = left
            self.right      = right
            self.db_markers = db_markers
            self.scale      = scale

            print("Setting up LevelDisplay at i2c address {}".format(address))

        return self
Ejemplo n.º 5
0
def test_display():
    """
    SH1106 OLED screen can draw and display an image.
    """
    device = sh1106(serial)
    serial.reset_mock()

    recordings = []

    def data(data):
        recordings.append({'data': data})

    def command(*cmd):
        recordings.append({'command': list(cmd)})

    serial.command = Mock(side_effect=command, unsafe=True)
    serial.data = Mock(side_effect=data, unsafe=True)

    # Use the same drawing primitives as the demo
    with canvas(device) as draw:
        primitives(device, draw)

    serial.data.assert_called()
    serial.command.assert_called()

    assert recordings == get_json_data('demo_sh1106')
Ejemplo n.º 6
0
 def initDisplay(self, address):
     display = self.getConnectedDisplayData(address,
                                            self._settings.displays2)
     # print("initDisplay")
     # print(display)
     # print(type(display))
     if (display and display['type'] == 'OLED'):
         # if OLED
         serial = i2c(port=1, address=display['address'])
         # substitute ssd1331(...) or sh1106(...) below if using that device
         # device = ssd1306(serial)
         device = sh1106(serial)
         device.clear()
         return device
     if (display and display['type'] == 'LCD'):
         # if LCD
         device = CharLCD(i2c_expander='PCF8574',
                          address=int(display['address'], 0),
                          port=1,
                          cols=display['width'],
                          rows=display['height'],
                          dotsize=8,
                          charmap='A02',
                          auto_linebreaks=True,
                          backlight_enabled=True)
         # substitute ssd1331(...) or sh1106(...) below if using that device
         # device = ssd1306(serial)
         device.clear()
         return device
     return False
Ejemplo n.º 7
0
 def init_display(self, **kwargs):
     """Initializes SH1106 controller. """
     self.rotate = kwargs.pop("rotate", self.default_rotate)
     self.device = sh1106(self.serial,
                          width=self.width,
                          height=self.height,
                          rotate=self.rotate)
Ejemplo n.º 8
0
def test_display():
    """
    SH1106 OLED screen can draw and display an image.
    """
    device = sh1106(serial)
    serial.reset_mock()

    recordings = []

    def data(data):
        recordings.append({'data': data})

    def command(*cmd):
        recordings.append({'command': list(cmd)})

    serial.command = Mock(side_effect=command, unsafe=True)
    serial.data = Mock(side_effect=data, unsafe=True)

    # Use the same drawing primitives as the demo
    with canvas(device) as draw:
        primitives(device, draw)

    serial.data.assert_called()
    serial.command.assert_called()

    # To regenerate test data, uncomment the following (remember not to commit though)
    # ================================================================================
    # from baseline_data import save_reference_data
    # save_reference_data("demo_sh1106", recordings)

    assert recordings == get_reference_data('demo_sh1106')
Ejemplo n.º 9
0
def main():
    cmd = "ps -ef | grep 'show_info.py' | grep -v 'grep' | grep python3 | awk '{print $2}'"
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    output = p.stdout.readlines()
    pids = [int(x.decode()) for x in output]
    pids.remove(os.getpid())
    ppid = os.getppid()
    if ppid in pids:
        pids.remove(os.getppid())
    if len(pids) > 0:
        print("already running...")
        print(pids)
        return

    while True:
        serial = i2c(port=1, address=0x3C)
        device = sh1106(serial)

        with canvas(device) as draw:
            draw.rectangle(device.bounding_box, outline="white", fill="black")
            #draw.text((30, 40), "Hello World", fill="white")
            #draw.text((30, 40), "Hello World", fill="white")
            #draw.text((0, 0), "Hello World", fill="white")
            local_ip = get_ip_address("wlan0")
            draw.text((0, 0), "ip: %s" % local_ip, fill="white")
        time.sleep(10)
Ejemplo n.º 10
0
class SetupClass:

    # setup logs to be used in all python files, reset on each run
    logging.basicConfig(filename='logging.log',
                        filemode='w',
                        encoding='utf-8',
                        level=logging.DEBUG)

    GPIO.setwarnings(False)
    serial = spi(device=0,
                 port=0,
                 bus_speed_hz=8000000,
                 transfer_size=4096,
                 gpio_DC=24,
                 gpio_RST=25)
    device = sh1106(serial, rotate=2)  # sh1106

    GPIO.setmode(GPIO.BCM)

    # key pins defined in constant.py
    GPIO.setup(config.KEY_CANCEL_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(config.KEY_UP_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(config.KEY_SELECT_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(config.KEY_DOWN_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    logging.info("SetupClass Initialized")
Ejemplo n.º 11
0
    def set_address(self, address):
        super(terrariumOLED, self).set_address(address)
        try:
            address = i2c(port=int(self.bus),
                          address=int('0x' + str(self.address), 16))

            if self.get_type() == terrariumOLEDSSD1306.TYPE:
                self.device = ssd1306(address)
            elif self.get_type() == terrariumOLEDSSD1309.TYPE:
                self.device = ssd1309(address)
            elif self.get_type() == terrariumOLEDSSD1322.TYPE:
                self.device = ssd1322(address)
            elif self.get_type() == terrariumOLEDSSD1325.TYPE:
                self.device = ssd1325(address)
            elif self.get_type() == terrariumOLEDSSD1327.TYPE:
                self.device = ssd1327(address)
            elif self.get_type() == terrariumOLEDSSD1331.TYPE:
                self.device = ssd1331(address)
            elif self.get_type() == terrariumOLEDSSD1351.TYPE:
                self.device = ssd1351(address)
            elif self.get_type() == terrariumOLEDSH1106.TYPE:
                self.device = sh1106(address)

        except DeviceNotFoundError as ex:
            print(
                '%s - WARNING - terrariumDisplay     - %s' %
                (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S,%f')[:23],
                 ex))
            self.device = None

        self.init()
Ejemplo n.º 12
0
def test_display():
    """
    SH1106 OLED screen can draw and display an image.
    """
    device = sh1106(serial)
    serial.reset_mock()

    recordings = []

    def data(data):
        recordings.append({'data': data})

    def command(*cmd):
        recordings.append({'command': list(cmd)})

    serial.command = Mock(side_effect=command, unsafe=True)
    serial.data = Mock(side_effect=data, unsafe=True)

    # Use the same drawing primitives as the demo
    with canvas(device) as draw:
        primitives(device, draw)

    serial.data.assert_called()
    serial.command.assert_called()

    assert recordings == get_json_data('demo_sh1106')
Ejemplo n.º 13
0
 def __init__(self, width, height, fontFile, largeFontSize, smallFontSize):
     Video.device = sh1106(spi(),
                           width=width,
                           height=height,
                           mode="1",
                           rotate=2)
     super().__init__(width, height, fontFile, largeFontSize, smallFontSize)
Ejemplo n.º 14
0
	def __init__(self, rows=64, cols=128, i2c_address=0x3d, i2c_port=1, devicetype='ssd1306'):

		self.i2c_address = i2c_address
		self.i2c_port = i2c_port

		self.rows = rows
		self.cols = cols

		self.fb = [[]]

		# Initialize the default font
		font = fonts.bmfont.bmfont('latin1_5x8_fixed.fnt')
		self.fp = font.fontpkg

		serial = i2c(port=i2c_port, address=i2c_address)

		if devicetype.lower() == 'ssd1306':
			self.device = ssd1306(serial)
		elif devicetype.lower() == 'sh1106':
			self.device = sh1106(serial)
		elif devicetype.lower() == 'ssd1322':
			self.device = ssd1322(serial)
		elif devicetype.lower() == 'ssd1325':
			self.device = ssd1325(serial)
		elif devicetype.lower() == 'ssd1331':
			self.device = ssd1331(serial)
		else:
			raise ValueError('{0} not a recognized luma device type'.format(devicetype))
Ejemplo n.º 15
0
    def __init__(self):
        self.busy=False
        self.s4=''
        self.s5=''
        self.s6=''
        # Parse config for display settings
        driver = gv.cp.get(gv.cfg,"OLED_DRIVER".lower())
        RST = gv.cp.getint(gv.cfg,"OLED_RST".lower())
        CS = gv.cp.getint(gv.cfg,"OLED_CS".lower())
        DC = gv.cp.getint(gv.cfg,"OLED_DC".lower())
        port = gv.cp.getint(gv.cfg,"OLED_PORT".lower())
        # Load default font.
        self.font = ImageFont.load_default()
        
        # self.largeFont = ImageFont.truetype("arial.ttf",16)
        # Create blank image for drawing.
        # Make sure to create image with mode '1' for 1-bit color.
        self.width = gv.cp.getint(gv.cfg,"OLED_WIDTH".lower())
        self.height = gv.cp.getint(gv.cfg,"OLED_HEIGHT".lower())
        self.image = Image.new('1', (self.width, self.height))

        # First define some constants to allow easy resizing of shapes.
        self.padding = gv.cp.getint(gv.cfg,"OLED_PADDING".lower())
        self.top = self.padding
        self.bottom = self.height-self.padding
        # Move left to right keeping track of the current x position for drawing shapes.
        self.x = 0
        serial = spi(device=port, port=port, bus_speed_hz = 8000000, transfer_size = 4096, gpio_DC = DC, gpio_RST = RST)
        
        if driver=="SH1106":
            self.device = sh1106(serial, rotate=2)
        else:
            print("Wrong driver")
        self.canvas = canvas(self.device)
Ejemplo n.º 16
0
class sh1106_screen:
    """
    Object for interacting with sh1106 board controlled screen display
    """
    # setup screen display
    # variables are the same for every instance setup, so not inside __init__
    display = sh1106(spi())

    def display_time(self, times: List[datetime.datetime], min_clock_display: int = 0) -> None:
        """
        Pulls in times and pushes the information to the screen display
        :times: list of departure times
        :min_clock_display: the minimum difference in minutes to display on the countdown clock
        """
        # Display times on the SPI sh1106 screen
        with canvas(self.display) as draw:
            draw.rectangle(self.display.bounding_box, outline="white", fill="black")
            draw.text((25, 10), "Schedule: ", fill="white")
            # For up to 3 train times, display their schedule
            for x in range(min(3, len(times))):
                train_num = x + 1
                display_y = (train_num * 10) + 10
                # Display train number and departure time
                draw.text((25, display_y),
                          f"{train_num}: {times[x].strftime('%H:%M')}", fill="white")

    def clear_display(self):
        """
        Creates new instance of display in order to clear the current display
        """
        self.display = sh1106(spi())
Ejemplo n.º 17
0
    def __init__(self, config, core):
        super(oledScreen, self).__init__()
        self.menu = False
        self.core = core
        self.config = config

        if config['oledScreen']['bus'] and config['oledScreen']['address']:
            self.serial = i2c(bus=SMBus(config['oledScreen']['bus']),
                              address=config['oledScreen']['address'])
        else:
            self.serial = i2c(bus=SMBus(2), address=0x3c)
        self.driver = config['oledScreen']['driver']
        if self.driver == 'ssd1306':
            self.device = ssd1306(self.serial)
        elif self.driver == 'ssd1322':
            self.device = ssd1322(self.serial)
        elif self.driver == 'ssd1325':
            self.device = ssd1325(self.serial)
        elif self.driver == 'ssd1331':
            self.device = ssd1331(self.serial)
        elif self.driver == 'sh1106':
            self.device = sh1106(self.serial)
        else:
            self.device = ssd1306(self.serial)

        self.font = self.make_font('Vera.ttf', 26)
        self.fontSmall = self.make_font('Vera.ttf', 15)
        self.set_image('radio.gif')
Ejemplo n.º 18
0
    def __init__(self, statusFunctions=[], framerate: int = 10):

        serial = spi(device=0, port=0)
        self.device = sh1106(serial, rotate=2)

        self.buttons = Buttons()

        if statusFunctions is None:
            statusFunctions = []
        self.statusFunctions = statusFunctions
        self.stopEvent = Event()
        self.frameBuffer = Queue()

        resourcePath = Path(__file__).parent.parent
        resourcePath = resourcePath.joinpath("resources")
        im = Image.open(resourcePath / "coOP_logo.bmp").convert(
            self.device.mode)

        self.frameBuffer.put(Frame(im, True))
        self.lastFrame = None

        self.fullscreenOffset = 10

        self.timeToNextFrame = 1 / framerate

        self.__updateScreen()
Ejemplo n.º 19
0
    def __init__(self):
        self.running = False

        # set the oled screen height
        self.screen_width = SCREEN_WIDTH
        self.screen_height = SCREEN_HEIGHT

        self.btn1Pin = LEFT_BTN_PIN
        self.btn2Pin = RIGHT_BTN_PIN

        # configure interrups for buttons
        GPIO.setup(self.btn1Pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(self.btn2Pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

        # configure screen
        # spi_bus = 0
        # spi_device = 0
        # gpio = gaugette.gpio.GPIO()
        # spi = gaugette.spi.SPI(spi_bus, spi_device)

        serial = i2c(port=1, address=0x3C)
        device = sh1106(serial)

        # Very important... This lets py-gaugette 'know' what pins to use in order to reset the display
        # self.led = gaugette.ssd1306.SSD1306(gpio, spi, reset_pin=OLED_RESET_PIN, dc_pin=OLED_DC_PIN, rows=self.screen_height, cols=self.screen_width) # Change rows & cols values depending on your display dimensions.
        self.led = device
        self.oled_font = ImageFont.truetype('FreeSans.ttf', 12)
        # self.led.begin()
        # self.led.clear_display()
        # self.led.display()
        # self.led.invert_display()
        # time.sleep(0.5)
        # self.led.normal_display()
        time.sleep(0.5)

        # load the pump configuration from file
        self.pump_configuration = Bartender.readPumpConfiguration()
        for pump in self.pump_configuration.keys():
            GPIO.setup(self.pump_configuration[pump]["pin"],
                       GPIO.OUT,
                       initial=GPIO.HIGH)

        # setup pixels:
        self.numpixels = NUMBER_NEOPIXELS  # Number of LEDs in strip

        # Here's how to control the strip from any two GPIO pins:
        datapin = NEOPIXEL_DATA_PIN
        clockpin = NEOPIXEL_CLOCK_PIN
        #self.strip = Adafruit_DotStar(self.numpixels, datapin, clockpin)
        #self.strip.begin()           # Initialize pins for output
        # Limit brightness to ~1/4 duty cycle
        #self.strip.setBrightness(NEOPIXEL_BRIGHTNESS)

        # turn everything off
        # for i in range(0, self.numpixels):
        #     self.strip.setPixelColor(i, 0)
        # self.strip.show()

        print("Done initializing")
Ejemplo n.º 20
0
 def open(self):
     i2c_busio = busio.I2C(board.SCL, board.SDA)
     self.sensor_mag = adafruit_lsm303dlh_mag.LSM303DLH_Mag(i2c_busio)
     self.sensor_accel = adafruit_lsm303_accel.LSM303_Accel(i2c_busio)
     i2c_luma = luma_i2c(port=1, address=0x3c)
     self.lcd = sh1106(i2c_luma, width=128, height=64)
     self.font = ImageFont.truetype("FreeSans.ttf", 16)
     print("Opened interface")
Ejemplo n.º 21
0
    def __init__(self, statusFunctions: Optional[List[Callable[[], bool]]] = []):

        if statusFunctions is None:
            statusFunctions = []
        serial = spi(device=0, port=0)
        self.device = sh1106(serial,rotate=2)
        self.statusFunctions = statusFunctions
        #print logo to device
        self.__initgpio()
Ejemplo n.º 22
0
def init():  #inicializar lcd
    global device
    global font
    serial = i2c(port=1,
                 address=0x3C)  #puerto de raspberry y address del dispositivo
    device = sh1106(serial, rotate=0)  #seleccion del driver del lcd
    font = ImageFont.truetype(
        "/usr/share/fonts/truetype/freefont/FreeSerif.ttf",
        16)  #tipo de letra(direccion) y tamaño
Ejemplo n.º 23
0
def display(a, b="ZZULI"):
    # rev.1 users set port=0
    # substitute spi(device=0, port=0) below if using that interface
    serial = i2c(port=1, address=0x3C)
    # substitute ssd1331(...) or sh1106(...) below if using that device
    device = sh1106(serial)  #这里改ssd1306, ssd1325, ssd1331, sh1106
    with canvas(device) as draw:
        draw.rectangle(device.bounding_box, outline="white", fill="black")
        draw.text((55, 16), b, fill="white")
        draw.text((40, 36), "QRcode:" + a, fill="white")
Ejemplo n.º 24
0
    def __init__(self, init_menu):
        super(Screen, self).__init__()
        self.sleep_timer = None
        self.state = 'OFF'

        self.oled = sh1106(i2c(port=1, address=0x3C)) if is_pi() else pygame(
            width=128, height=64)
        self._welcome()
        time.sleep(1)
        self.draw_menu(init_menu)
        atexit.register(self.cleanup)
Ejemplo n.º 25
0
 def __init__(self):
     self._initialize_buttons()
     self._initialize_button_events()
     self.device = sh1106(spi(device=0, port=0), rotate=2)
     self.device.contrast(255)
     self.automata = Automata(rules_list.current_rule(), self.DIMENSIONS)
     self._repopulate()
     self.start_time = time.time()
     self.paused = False
     self.average_fps = 0
     self.last_measured_time = time.time()
Ejemplo n.º 26
0
def mainscales():
    #setup local OLED screen
    fontname = "ProggyTiny.ttf"
    size = 48  # 48 gives 7chars x 2lines
    font = make_font(fontname, size) if fontname else None
    # if i2c then use i2c()
    serial = spi(device=0, port=0)
    # change device type here if needed, this also rotates display 180 - i.e. if gpio connector on bottom of display
    device = sh1106(serial, rotate=2)
    term = terminal(device, font)
    #    term.clear()
    term.animate = True

    processor = EventProcessor()
    board = Wiiboard(processor, term)
    dispTime = DispTime(term)

    while 1:
        address = Discover(board)
        didwegrabit = True

        if (address != None):
            print "Trying to connect..."
            term.animate = False

            try:
                board.connect(
                    address)  # The wii board must be in sync mode at this time
                board.wait(200)
                board.setLight(False)
                board.wait(500)
                board.setLight(True)
                # go weigh :)
                board.receive()
            except KeyboardInterrupt:
                #time.sleep(5)
                exit()
            except:
                # likely no board connected,
                print "No board connected"
                didwegrabit = False

        # display time during this idle phase
        dispTime.putToScreen()

        # need to sleep for a while to allow BT stack to not be hammered
        # and allow time for board to go into discover mode again
        # if we have a good address, then discovery is quicker, so add a longer sleep
        # if did have sucessfull weighing, then also can add longer sleep
        time.sleep(3)
        if (didwegrabit or (address != None)):
            time.sleep(3)
def main():
    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s -- %(name)s %(levelname)s - %(message)s')

    connection_builder: ISConnectionBuilder = ISConnectionBuilder()
    connection_builder.set_mac_address(get_mac_address())
    connection_builder.set_baseurl(config['Connection']['baseurl'])
    connection_builder.set_url(config['Connection']['url'])

    AttendanceRecorder(OLEDdisplay(sh1106(i2c())), CardReader(),
                       connection_builder.build(), Buzzer(),
                       ButtonController()).start()
Ejemplo n.º 28
0
	def __init__(self, is_debug, callback):
		if is_debug:
			self._image = Image.new("RGB", (self.WIDTH, self.HEIGHT), "BLACK")
			self._draw = ImageDraw.Draw(self._image)
		else:
			from luma.core.interface.serial import i2c, spi
			from luma.core.render import canvas
			from luma.oled.device import sh1106
			serial = spi(device=0, port=0)
			device = sh1106(serial, rotate=2)
			while True:
				with canvas(device) as draw:
					callback(draw)
				sleep(0.05)
Ejemplo n.º 29
0
    def __init__(self):
        rospy.init_node('display')
        rate = rospy.Rate(10)  # 10hz
        self.modeSub = rospy.Subscriber("/mode", String, self.modeCallback)

        self.mode = 'System Check'

    	serial = i2c(port=1, address=0x3c)
    	self.device = sh1106(serial)
        self.font = ImageFont.truetype('Ubuntu-B.ttf', 18)

        while not rospy.is_shutdown():
            with canvas(self.device) as draw:
        	    draw.text((0, 20), self.mode, fill='white', font=self.font)
            rate.sleep()
        rospy.spin()
Ejemplo n.º 30
0
    def __init__(self):
        """Set up Screen object.
        """
        serial = i2c(port=I2C_PORT, address=I2C_ADDRESS)
        if DISPLAY_TYPE == 'sh1106':
            self.oled = sh1106(serial)
        else:
            self.oled = ssd1306(serial)
        self.bar_length = self.oled.width - ((PADDING + TEXT_MARGIN) * 2)
        self.font = ImageFont.truetype(FONT_PATH, FONT_SIZE)

        # Required by daemon runner
        self.pidfile_path = PIDFILE_PATH
        self.pidfile_timeout = PIDFILE_TIMEOUT
        self.stdin_path = STDIN_PATH
        self.stdout_path = STDOUT_PATH
        self.stderr_path = STDERR_PATH
Ejemplo n.º 31
0
def get_device():
    DC = 24
    RST = 25
    try:
        from luma.oled.device import sh1106
        from luma.core.interface.serial import spi
    except ImportError:
        print("Libs needed.")
    except Exception as e:
        print(e)
    serial = spi(device=0,
                 port=0,
                 bus_speed_hz=8000000,
                 transfer_size=4096,
                 gpio_DC=DC,
                 gpio_RST=RST)
    return (sh1106(serial, rotate=0))
Ejemplo n.º 32
0
def cleanup():
    serial = i2c(port=8, address=0x3C)
    device = sh1106(serial)
    GPIO.cleanup(gpio_led)
    GPIO.cleanup(gpio_sw_1)
    GPIO.cleanup(gpio_sw_10)
    GPIO.cleanup(gpio_sw_60)
    GPIO.cleanup(gpio_sw_res)
    GPIO.cleanup(gpio_sw_st)
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(gpio_led, GPIO.OUT)
    GPIO.setup(gpio_sw_1, GPIO.IN)
    GPIO.setup(gpio_sw_10, GPIO.IN)
    GPIO.setup(gpio_sw_60, GPIO.IN)
    GPIO.setup(gpio_sw_res, GPIO.IN)
    GPIO.setup(gpio_sw_st, GPIO.IN)
    GPIO.output(gpio_led, 0)