def setup(): GPIO.setmode(GPIO.BCM) red_segment = SevenSegment.SevenSegment(address=0x70) green_segment = SevenSegment.SevenSegment(address=0x72) red_segment.begin() green_segment.begin() return red_segment, green_segment
def __init__(self): """ Initializes the hardware """ tlu_hardwarebase.__init__(self) if fakeIO: self.segment = SevenSegment(address=self.led_7seg_address) else: self.segment = SevenSegment.SevenSegment(address=self.led_7seg_address) self.segment.begin() self.segment.clear() self.segment.write_display()
def __init__(self, address='0x70', brightness='15', decimal_digits='2', justify_right='True', invert='False'): """Create an instance of the seven segment display widget. Can pass in the following optional parameters to control the widget (note all parameters are strings as they are parsed from config files): - address: I2C address, default is 0x70 - brightness: Brightness of the display, can be a value from 0 to 15 with 15 being the brightest. The default is 15. - decimal_digits: Number of digits to show after decimal point, default is 0. - justify_right: Justify numeric display to the right side if true (the default). Set to false to justify to the left side. - invert: Vertically flip the display if true. Default is false. Note that when flipped the decimal points will be at the top! """ # Setup display and initial state. self._display = SevenSegment.SevenSegment(address=int(address, 0)) self._display.begin() self._display.set_brightness(int(brightness)) if self.parse_bool(invert): self._display.set_invert(True) self._decimal_digits = int(decimal_digits) self._justify_right = self.parse_bool(justify_right) # Clear the display self._display.clear() self._display.write_display()
def Clock(): segment = SevenSegment.SevenSegment(address=0x70) # Continually update the time on a 4 char, 7-segment display try: now = datetime.now() hour = now.hour minute = now.minute second = now.second segment.clear() # Set hours segment.set_digit(0, int(hour / 10)) # Tens segment.set_digit(1, hour % 10) # Ones # Set minutes segment.set_digit(2, int(minute / 10)) # Tens segment.set_digit(3, minute % 10) # Ones # Toggle colon segment.set_colon(second % 2) # Toggle colon at 1Hz # Write the display buffer to the hardware. This must be called to # update the actual display LEDs. segment.write_display() # Wait a quarter second (less than 1 second to prevent colon blinking getting$ time.sleep(0.25) except KeyboardInterrupt: segment.clear() segment.write_display()
def __init__(self, numberCallback): """ Init of GPIO Pin """ GPIO.setmode(GPIO.BCM) GPIO.setup(NUMBER_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(DAIL_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(POWER_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(NUMBER_PIN, GPIO.FALLING, callback=self.numberPassesCallback, bouncetime=80) GPIO.add_event_detect(DAIL_PIN, GPIO.BOTH, callback=self.dailCallback, bouncetime=20) # Var init self.numberCallback = numberCallback self.numberIter = 0 self.numberDisplay = ['', '', '', ''] self.numberDisplayOld = ['', '', '', ''] self.lookFlag = False # Timer initialization self.t = threading.Timer(10.0, self.timeoutTimmer) # Create display instance on default I2C address (0x70) and bus number and clear Display self.display = SevenSegment.SevenSegment() self.display.begin() self.display.print_number_str(' ') self.display.write_display() self.display.clear() # Test Blinking function self.dispDrive = HT16K33.HT16K33() self.dispDrive.begin()
def updateDisplays(args): dotDisplay = Matrix8x8.Matrix8x8(address=0x71, busnum=1) dotDisplay.begin() dotDisplay.clear() if '+r' in args: printLetterQuadrant(dotDisplay, 0, 0, R_4x4) if '+c' in args: printLetterQuadrant(dotDisplay, 0, 4, C_4x4) if '+o' in args: printLetterQuadrant(dotDisplay, 4, 4, O_4x4) if '-t' in args: t = int(args['-t']) if t >= 1 and t <= 16: printTimeQuadrant(dotDisplay, 0, 4, t); clockDisplay = SevenSegment.SevenSegment() clockDisplay.begin() clockDisplay.clear() if '-gt' in args: gameTime = int(args['-gt']) printClockTimeSec(clockDisplay, gameTime) # Flush to both displays at the same time dotDisplay.write_display() clockDisplay.write_display() return;
def main(): """ Sets up periferals and then begins loop """ # Setup Display segment = SevenSegment.SevenSegment(address=0x70) display = HT16K33.HT16K33(address=0x70) # Initialize the display. Must be called once before using the display. segment.begin() # Setup GPIO Button # pin12 --- button button_pin = 12 # Numbers GPIOs by physical location GPIO.setmode(GPIO.BOARD) # Set button_pin's mode as input GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Initialize the philips bridge bridge = Bridge('192.168.0.10') # Initialise the bedroom light light = Light(bridge, 'Bedroom') loop(display, segment, light, button_pin)
def RunClock(): from Adafruit_LED_Backpack import SevenSegment # =========================================================================== # Clock Example # =========================================================================== segment = SevenSegment.SevenSegment(address=0x70) segment.begin() while (True): now = datetime.datetime.now() hour = now.hour minute = now.minute second = now.second segment.clear() # Set hours segment.set_digit(0, int(hour / 10)) # Tens segment.set_digit(1, hour % 10) # Ones # Set minutes segment.set_digit(2, int(minute / 10)) # Tens segment.set_digit(3, minute % 10) # Ones # Toggle colon segment.set_colon(second % 2) # Toggle colon at 1Hz # Write the display buffer to the hardware. This must be called to # update the actual display LEDs. segment.write_display() # Wait a quarter second (less than 1 second to prevent colon blinking getting$ time.sleep(0.25)
def __init__(self): self.segment = SevenSegment.SevenSegment(address=0x70) self.segment.begin() self.segment.set_brightness(7) self.segment.clear() self.segment.write_display() self.isThread = False
def __init__(self): ### SETUP DISPLAYS ################# self.currentLapDisplay = SevenSegment.SevenSegment(address=0x72) self.currentLapDisplay.begin() self.currentLapDisplay.clear() self.previousLapDisplay = SevenSegment.SevenSegment(address=0x73) self.previousLapDisplay.begin() self.previousLapDisplay.clear() self.multiDisplay = AlphaNum4.AlphaNum4(address=0x70) self.multiDisplay.begin() self.multiDisplay.clear() #################################### self.displayTime(0, 0) self.textIndex = 0
def enableSevenSegmentDisplay() : global use_i2c_display global seven_segment_display if use_i2c_display: seven_segment_display = SevenSegment.SevenSegment(address=0x70) # Initialize the display. Must be called once before using the display. seven_segment_display.begin()
def SevenSegSetup(SevSeg): ''' This checks if the seven segment desplay is on I2C bus address and return true if it was able to set it up. If the i2cdetect is not available or address 70 is not detected then return false ''' import subprocess # if we find the command and we have a device with address on it ... got_display = False # detection binary i2c_cmd = "/usr/sbin/i2cdetect" if ( os.path.isfile(i2c_cmd) ): # file exists see if we have a device address 70 on it p = subprocess.Popen([i2c_cmd, '-y','1'],stdout=subprocess.PIPE,) # should get back something like this if there are three LCD backpacks: ''' 0 1 2 3 4 5 6 7 8 9 a b c d e f 00: -- -- -- -- -- -- -- -- -- -- -- -- -- 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 70: 70 71 72 -- -- -- -- -- ''' # cmdout = str(p.communicate()) # look for the addresses of the displays and put the address (in hex ) on the LED # nine line of output .... for i in range(0,9): line = str(p.stdout.readline()) # look for the pattern in each line for i in range(0,len(device)-1): # need the LED display number, the hex address of the I2C bus and # the pattern to find in the i2c output that says it is there disp = device[i]['disp'] addr = device[i]['addr'] pat = device[i]['pat'] # look for the devices in the i2cdetect output for match in re.finditer(pat, line): SevSeg[disp] = SevenSegment.SevenSegment(address=addr,busnum=1) SevSeg[disp].begin() SevSeg[disp].clear() SevSeg[disp].print_hex(addr ) SevSeg[disp].write_display() #SevSeg[disp].set_brightness(15) SevSeg[disp].set_brightness(1) got_display = True return got_display
def uptime(): args = sys.argv[1:] if len(args) != 1: raise Exception('systemd unit name as argument required') display = SevenSegment.SevenSegment() display.begin() sysbus = dbus.SystemBus() systemd1 = sysbus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1') manager = dbus.Interface(systemd1, 'org.freedesktop.systemd1.Manager') while True: display.clear() unit = manager.GetUnit(args[0]) unit_object = sysbus.get_object('org.freedesktop.systemd1', unit) prop_unit = dbus.Interface(unit_object, 'org.freedesktop.DBus.Properties') active_timestamp = prop_unit.Get('org.freedesktop.systemd1.Unit', 'ActiveEnterTimestamp') # interrogate unit, get time clock_value, value_unit = display_duration(active_timestamp / 1e6) if not value_unit: sleep_time = 3 for ix in range(4): display.set_digit(ix, '-') elif value_unit == 'SECONDS': sleep_time = .35 display.print_float(clock_value, decimal_digits=0, justify_right=False) else: sleep_time = 10 display.print_number_str(str(clock_value), justify_right=False) if value_unit == 'HOURS': display.set_digit_raw(3, 0x74) elif value_unit == 'DAYS': display.set_digit_raw(3, 0x5E) else: print('Unknown clock value unit {}'.format(value_unit), file=sys.stderr) print('{}'.format(clock_value)) display.write_display() time.sleep(sleep_time)
def __init__(self, num_digits=4, address=None): """ Sets up one physical display per 4 digits. If no address is specified, auto-increments address from 0x70.""" self.num_digits = num_digits if not address: address = SevenSegDisplay.next_addr self.seg = [] for i in range(num_digits / 4): self.seg += [SevenSegment.SevenSegment(address=address)] address += 1 SevenSegDisplay.next_addr = address self.start()
def outResetDisp(): for i in dictDisplays: try: objDisp_i = SevenSegment.SevenSegment(address=dictDisplays[i]) objDisp_i.begin() for ii in range(0, 4, 1): objDisp_i.set_digit_raw(ii, 0x40) objDisp_i.write_display() except IOError as e: logger.error("The display caused an error for lane " + str(i)) except: logger.info("There was an error writing to display " + str(lane)) logger.exception(str(sys.exc_info()[0]))
def outRankDisp(lane): global dictDisplays global dictLaneRank i = lane try: objDisp_i = SevenSegment.SevenSegment(address=dictDisplays[i]) objDisp_i.begin() objDisp_i.print_number_str(str(dictLaneRank[i]) + " ") objDisp_i.write_display() except IOError as e: logger.error("The display caused an error for lane " + str(i)) except: logger.error("There was an error writing to display " + str(lane)) logger.exception(str(sys.exc_info()[0]))
async def main(is_test): if is_test: import FakeSevenSegment display = FakeSevenSegment.FakeSevenSegment() else: # Create display instance on default I2C address (0x70) and bus number. from Adafruit_LED_Backpack import SevenSegment display = SevenSegment.SevenSegment() # Initialize the display. Must be called once before using the display. display.begin() display.clear() display.write_display() await update_time(display)
def __init__(self, name, address): """ Initalize a seven segment display with i2c """ self.name = name self._address = address self._initialized = False self._led = SevenSegment.SevenSegment(address=self._address) try: self._led.begin() self.clear() self._initialized = True except IOError: msg = "Could not connect to %s LED at I2C address %s" % ( self.name, hex(self._address)) print(msg)
def _get_clock(self): if self.clock == None: try: logger.info("creating {} at address {}".format( self.name, self.address)) logger.info("running i2cdetect -y 1") logger.info("i2cdetect -y 1\n{}".format(i2cdetect())) logger.info("finished i2cdetect -y 1") self.clock = SevenSegment.SevenSegment(address=self.address) self.clock.begin() logger.debug("new clock named {} for address {}".format( self.name, self.address)) except: self.clock = None logger.error("could not start clock", exc_info=True) return self.clock
def main(is_test): if is_test: import FakeSevenSegment display = FakeSevenSegment.FakeSevenSegment() else: # Create display instance on default I2C address (0x70) and bus number. from Adafruit_LED_Backpack import SevenSegment display = SevenSegment.SevenSegment() # Initialize the display. Must be called once before using the display. display.begin() display.clear() display.write_display() # Read the certificate/key pair. repo_root = common.find_repo_root() certs_dir = os.path.join(repo_root, 'certs') with open(os.path.join(certs_dir, 'server.key')) as f: private_key = f.read() with open(os.path.join(certs_dir, 'server.crt')) as f: certificate_chain = f.read() server_credentials = grpc.ssl_server_credentials((( private_key, certificate_chain, ), )) server = grpc.server(futures.ThreadPoolExecutor(max_workers=1)) servicer = SevenSegmentDisplayServicer(display) segment7_pb2_grpc.add_SevenSegmentDisplayServicer_to_server( servicer, server) config = common.read_config() _, port = config.get_segment7_host() address = '[::]:%d' % port server.add_secure_port(address, server_credentials) server.start() print('PID=%d Server started on %s' % (os.getpid(), address)) try: while True: signal.pause() except KeyboardInterrupt: pass servicer.shutdown() server.stop(0)
def check_alarm_button(self): input = self.gpio.read(13) if not input: print("button pressed") # show alarm time on display segment = SevenSegment.SevenSegment(address=0x70) segment.begin() segment.set_brightness(0) if self.get_alarmtime().minute == 0: minutes_formatted = "00" segment.print_number_str("{}{}".format(self.get_alarmtime().hour, minutes_formatted)) segment.set_colon(True) segment.write_display() time.sleep(1)
def outDispSetup(): logger.info("Quick test to make sure the displays work") testDispSetup = ( 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x3f, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x3f) for y in range(len(testDispSetup)): for i in dictDisplays: try: objDisp_i = SevenSegment.SevenSegment(address=dictDisplays[i]) objDisp_i.begin() for ii in range(0,4,1): objDisp_i.set_digit_raw(ii, testDispSetup[y]) objDisp_i.write_display() except IOError as e: logger.error("The display caused an error for lane " + str(i)) except: logger.exception("An unknown error happened" + str(sys.exc_info()[0])) time.sleep(.02)
def __init__(self): self.display = SevenSegment.SevenSegment() self.display.begin() self.is_heating = False self.previous_target = 0.0 self.target_temp = 0.0 self.display_duration = DISPLAY_INTERVAL self.loop_counter = 0 self.skip_first_message = True self.finish_in_minutes = 0.0 self.message = 0 # Button + LED Setup GPIO.setup(LED_PIN, GPIO.OUT) GPIO.output(LED_PIN, GPIO.LOW) monitor_thread = threading.Thread(target=self.start_monitoring) monitor_thread.start()
def __init__(self, sensor_pin, led_i2c_address): self.pir_sensor = MotionSensor(sensor_pin) self.seven_segment = SevenSegment.SevenSegment( address=led_i2c_address) self.seven_segment.set_brightness(5) self.last_time = None self.lc = None # LoopingCall def when_motion(): self.start_clock() def when_no_motion(): self.stop_clock() self.pir_sensor.when_motion = when_motion self.pir_sensor.when_no_motion = when_no_motion if self.pir_sensor.motion_detected: self.start_clock() else: self.stop_clock()
def __init__(self): self.segment = SevenSegment.SevenSegment(address=0x70) self.segment.begin() self.kill_received = False self.screen_on = True self.admin_received = False self.admin_received_token_consumed = False self.admin_expired = False self.admin_expired_token_consumed= False self.countdown_passed_through_treshold = False self.countdown_passed_through_treshold_token_consumed = False self.sig_admin_mode = False self.sig_admin_mode_read = True self.sig_countdown_low = False self.sig_countdown_low_read = True self.temporary_on = -1
def __init__(self, rotation=None, i2c_address=None, i2c_busnum=None): super().__init__() display_kwargs = {} if rotation is not None: display_kwargs['rotation'] = rotation if i2c_address is not None: display_kwargs['address'] = i2c_address if i2c_busnum is not None: display_kwargs['busnum'] = i2c_busnum # Create display instance on default I2C address (0x70) and bus number. self.display = CustomBicolorMatrix8x8(**display_kwargs) # Initialize the display. Must be called once before using the display. self.display.begin() self.display.clear() self.display.write_display() self.seven_segment = SevenSegment.SevenSegment(address=0x71) self.seven_segment.begin() self.seven_segment.write_display()
def shutdown(self): # long press button to shut down for i in range(10): time.sleep(0.1) if GPIO.input(shutdown_pin_nr) == 1: # button not held down return print("Shutting down...") GPIO.cleanup() # kill clock script os.system( "sudo pkill -f 'python /var/www/html/Python-Alarm-Clock/7segment_clock.py'" ) # clear display display = SevenSegment.SevenSegment(address=0x70) display.begin() display.set_brightness(0) # display 'OFF' display.set_digit_raw(0, 0) display.set_digit_raw(1, 63) display.set_digit_raw(2, 113) display.set_digit_raw(3, 113) display.write_display() time.sleep(1) display.clear() display.write_display() # remove alarm_set if there is one if os.path.isfile("alarm_set"): os.remove("alarm_set") print("Shutdown: alarm_set removed") os.system("sudo shutdown -h now")
#!/usr/bin/python import time import datetime from Adafruit_LED_Backpack import SevenSegment # =========================================================================== # Clock Example # =========================================================================== segment = SevenSegment.SevenSegment(address=0x70) # Initialize the display. Must be called once before using the display. segment.begin() print "Press CTRL+Z to exit" # Continually update the time on a 4 char, 7-segment display try: while(True): now = datetime.datetime.now() hour = now.hour minute = now.minute second = now.second segment.clear() # Set hours segment.set_digit(0, int(hour / 10)) # Tens segment.set_digit(1, hour % 10) # Ones # Set minutes segment.set_digit(2, int(minute / 10)) # Tens
def __init__(self): states = [ 'normal', 'low', {'name': 'warn_reboot', 'timeout': 60, 'on_timeout': 'warn_expired'}, 'rebooting', ] transitions = [ { 'trigger': 'update', 'source': 'normal', 'dest': 'low', 'conditions': 'can_go_low', }, { 'trigger': 'update', 'source': 'low', 'dest': 'warn_reboot', 'conditions': 'can_go_low', }, { 'trigger': 'warn_expired', 'source': 'warn_reboot', 'dest': 'rebooting', 'after': 'reboot' }, { 'trigger': 'update', 'source': ['low', 'normal', 'warn_reboot'], 'dest': 'normal', 'conditions': 'can_go_normal', }, { 'trigger': 'button_pressed', 'source': ['low', 'warn_reboot'], 'dest': 'normal', 'after': 'reboot_cancelled' }, { 'trigger': 'button_held', 'source': ['low', 'normal'], 'dest': 'rebooting', 'after': 'reboot' }, ] super(SpeedTestRebooter, self).__init__( states=states, transitions=transitions, initial='normal', ignore_invalid_triggers=True ) GPIO.setmode(GPIO.BCM) self.config = self.read_config() self.router = DigitalOutputDevice(self.config['Main']['ROUTER_PIN'], initial_on=True, on_high_logic=True) self.modem = DigitalOutputDevice(self.config['Main']['MODEM_PIN'], initial_on=True, on_high_logic=True) self.normal_led = LED(self.config['Main']['NORMAL_LED_PIN']) self.slow_led = LED(self.config['Main']['SLOW_LED_PIN']) self.rebooting_led = LED(self.config['Main']['REBOOTING_LED_PIN']) self.button = Button(self.config['Main']['BUTTON_PIN'], self.button_pressed, hold_seconds=self.config['Main']['MANUAL_REBOOT_SECONDS'], held_callback=self.button_held) self.buzzer = Buzzer(self.config['Main']['BUZZER_PIN'], 10000, self.config['Main']['QUIET_HOURS_RANGE']) self.invalid_speed = 888.8 # visual cue for no real download speed info available self.download_speed = self.invalid_speed self.speedtest = None self.display = SevenSegment.SevenSegment(address=0x70) self.display.begin() self.display_speed() self.to_normal() log.info('Initialized')
INT_1B_PIN = 19 # 6 INT_2A_PIN = 5 #13 INT_2B_PIN = 6 #19 GPIO.setup(INT_1A_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(INT_1A_PIN, GPIO.FALLING) GPIO.add_event_callback(INT_1A_PIN, self.my_callback) GPIO.setup(INT_1B_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(INT_1B_PIN, GPIO.FALLING) GPIO.add_event_callback(INT_1B_PIN, self.my_callback) GPIO.setup(INT_2A_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(INT_2A_PIN, GPIO.FALLING) GPIO.add_event_callback(INT_2A_PIN, self.button_callback) m = GPIOListener() display = SevenSegment.SevenSegment() display.begin() display.clear() lastProg = int(m.r.get('prog')) display.print_float(lastProg + 1, decimal_digits=0, justify_right=True) display.write_display() while True: newProg = int(m.r.get('prog')) if newProg != lastProg: display.clear() display.print_float(newProg + 1, decimal_digits=0, justify_right=True) display.write_display() lastProg = newProg time.sleep(0.1)