示例#1
0
    def __init__(self,
                 ina,
                 inb,
                 enable,
                 ctrl,
                 enable_pwm=True,
                 gpio=GPIO.get_platform_gpio(),
                 pwm=PWM.get_platform_pwm()):
        # Save GPIO state and pin numbers
        self._en = enable
        self._ina = ina
        self._inb = inb
        self._ctrl = ctrl

        # Save libraries
        self._enable_pwm = enable_pwm
        self._pwm = pwm
        self._gpio = gpio

        # Setup all pins as outputs
        for pin in (ina, inb, enable):
            self._gpio.setup(pin, GPIO.OUT)

        # Setup the PWM speed control
        if (enable_pwm):
            self._pwm.start(ctrl, 0)
        else:
            gpio.setup(ctrl, GPIO.OUT)
            self._gpio.output(ctrl, False)

        # Enable Motor
        self._gpio.output(self._en, True)

        # Initialise the motor (stationary)
        self.setBrake(0)
示例#2
0
 def __init__(self,
              m1ina=VNH_SHIELD_M1INA,
              m1inb=VNH_SHIELD_M1INB,
              m1en=VNH_SHIELD_M1EN,
              m1pwm=VNH_SHIELD_M1PWM,
              m2ina=VNH_SHIELD_M2INA,
              m2inb=VNH_SHIELD_M2INB,
              m2en=VNH_SHIELD_M2EN,
              m2pwm=VNH_SHIELD_M2PWM,
              pwm_enabled=True,
              gpio=GPIO.get_platform_gpio(),
              pwm=PWM.get_platform_pwm()):
     # Initialise Motors
     # Left Motor
     self._M1 = Pololu_VNH5019(m1ina,
                               m1inb,
                               m1en,
                               m1pwm,
                               enable_pwm=pwm_enabled,
                               gpio=gpio,
                               pwm=pwm)
     # Right Motor
     self._M2 = Pololu_VNH5019(m2ina,
                               m2inb,
                               m2en,
                               m2pwm,
                               enable_pwm=pwm_enabled,
                               gpio=gpio,
                               pwm=pwm)
     self.motors = [self._M1, self._M2]
     # Initialise Motors
     self.setBrakes(0, 0)
     self._gpio = gpio
示例#3
0
 def __init__(self, rst=None, address=BNO055_ADDRESS_A, i2c=None, gpio=None,
              serial_port=None, serial_timeout_sec=5, **kwargs):
     # If reset pin is provided save it and a reference to provided GPIO
     # bus (or the default system GPIO bus if none is provided).
     self._rst = rst
     if self._rst is not None:
         if gpio is None:
             import Adafruit_GPIO as GPIO
             gpio = GPIO.get_platform_gpio()
         self._gpio = gpio
         # Setup the reset pin as an output at a high level.
         self._gpio.setup(self._rst, GPIO.OUT)
         self._gpio.set_high(self._rst)
         # Wait a 650 milliseconds in case setting the reset high reset the chip.
         time.sleep(0.65)
     self._serial = None
     self._i2c_device = None
     if serial_port is not None:
         # Use serial communication if serial_port name is provided.
         # Open the serial port at 115200 baud, 8N1.  Add a 5 second timeout
         # to prevent hanging if device is disconnected.
         self._serial = serial.Serial(serial_port, 115200, timeout=serial_timeout_sec,
                                      writeTimeout=serial_timeout_sec)
     else:
         # Use I2C if no serial port is provided.
         # Assume we're using platform's default I2C bus if none is specified.
         if i2c is None:
             import Adafruit_GPIO.I2C as I2C
             i2c = I2C
         # Save a reference to the I2C device instance for later communication.
         self._i2c_device = i2c.get_i2c_device(address, **kwargs)
示例#4
0
文件: BNO055.py 项目: dtbinh/soccer2
 def __init__(self, rst=None, address=BNO055_ADDRESS_A, i2c=None, gpio=None,
              serial_port=None, serial_timeout_sec=5, **kwargs):
     # If reset pin is provided save it and a reference to provided GPIO
     # bus (or the default system GPIO bus if none is provided).
     self._rst = rst
     if self._rst is not None:
         if gpio is None:
             import Adafruit_GPIO as GPIO
             gpio = GPIO.get_platform_gpio()
         self._gpio = gpio
         # Setup the reset pin as an output at a high level.
         self._gpio.setup(self._rst, GPIO.OUT)
         self._gpio.set_high(self._rst)
         # Wait a 650 milliseconds in case setting the reset high reset the chip.
         time.sleep(0.65)
     self._serial = None
     self._i2c_device = None
     if serial_port is not None:
         # Use serial communication if serial_port name is provided.
         # Open the serial port at 115200 baud, 8N1.  Add a 5 second timeout
         # to prevent hanging if device is disconnected.
         self._serial = serial.Serial(serial_port, 115200, timeout=serial_timeout_sec,
                                      writeTimeout=serial_timeout_sec)
     else:
         # Use I2C if no serial port is provided.
         # Assume we're using platform's default I2C bus if none is specified.
         if i2c is None:
             import Adafruit_GPIO.I2C as I2C
             i2c = I2C
         # Save a reference to the I2C device instance for later communication.
         self._i2c_device = i2c.get_i2c_device(address, **kwargs)
 def __init__(self, dc, spi, rst=None, gpio=None, width=ILI9341_TFTWIDTH,
     height=ILI9341_TFTHEIGHT, bgr=False, bit_depth=ILI9341_16BIT):
     """Create an instance of the display using SPI communication.  Must
     provide the GPIO pin number for the D/C pin and the SPI driver.  Can
     optionally provide the GPIO pin number for the reset pin as the rst
     parameter.
     """
     assert bit_depth in (ILI9341_16BIT, ILI9341_18BIT)
     self._dc = dc
     self._rst = rst
     self._spi = spi
     self._gpio = gpio
     self.width = width
     self.height = height
     self.bgr = bgr
     self.bit_depth = bit_depth
     if self._gpio is None:
         self._gpio = GPIO.get_platform_gpio()
     # Set DC as output.
     self._gpio.setup(dc, GPIO.OUT)
     # Setup reset as output (if provided).
     if rst is not None:
         self._gpio.setup(rst, GPIO.OUT)
     # Set SPI to mode 0, MSB first.
     spi.set_mode(0)
     spi.set_bit_order(SPI.MSBFIRST)
     spi.set_clock_hz(64000000)
示例#6
0
 def __init__(self, **kwargs):
     """
     :param int bus_id: the SMBus id (see Raspberry Pi documentation)
     :param kwargs: parameters transmitted to :py:class:`smbus.SMBus` initializer
     """
     JNTBus.__init__(self, **kwargs)
     self._spi_lock = threading.Lock()
     self.load_extensions(OID)
     self._ada_gpio = None
     try:
         self._ada_gpio = GPIO.get_platform_gpio()
     except:
         logger.exception("[%s] - Can't get GPIO", self.__class__.__name__)
     self._ada_spi = None
     try:
         self._ada_spi = SPI
     except:
         logger.exception("[%s] - Can't get SPI", self.__class__.__name__)
     self.export_attrs('_ada_spi', self._ada_spi)
     self.export_attrs('_ada_gpio', self._ada_gpio)
     self.export_attrs('spi_acquire', self.spi_acquire)
     self.export_attrs('spi_release', self.spi_release)
     self.export_attrs('spi_locked', self.spi_locked)
     self.export_attrs('get_spi_device', self.get_spi_device)
     self.export_attrs('get_spi_device_pin', self.get_spi_device_pin)
示例#7
0
    def __init__(self,
                 address=0x28,
                 i2c=None,
                 rst=None,
                 gpio=None,
                 logger=None):
        """
        Initialize the BNO055 class
        :param address: the I2C address
        :param i2c: the i2c device
        :param rst: a reset pin
        :param gpio: a gpio package
        :return: None
        """
        # If reset pin is provided save it and a reference to provided GPIO
        # bus (or the default system GPIO bus if none is provided).
        self._rst = rst
        if self._rst is not None:
            if gpio is None:
                import Adafruit_GPIO as GPIO
                gpio = GPIO.get_platform_gpio()
            self._gpio = gpio
            # Setup the reset pin as an output at a high level.
            self._gpio.setup(self._rst, GPIO.OUT)
            self._gpio.set_high(self._rst)
            # Wait a 650 milliseconds in case setting the reset high reset the chip.
            time.sleep(0.65)

        self._address = address
        self._i2c_device = i2c
        self._mode = OPERATION_MODE_NDOF
        self._logger = logger or Logger()
示例#8
0
 def __init__(self,
              dc,
              spi,
              rst=None,
              gpio=None,
              width=ST7789_WIDTH,
              height=ST7789_HEIGHT):
     """Create an instance of the display using SPI communication.  Must
     provide the GPIO pin number for the D/C pin and the SPI driver.  Can
     optionally provide the GPIO pin number for the reset pin as the rst
     parameter.
     """
     self._dc = dc
     self._rst = rst
     self._spi = spi
     self._gpio = gpio
     self.width = width
     self.height = height
     if self._gpio is None:
         self._gpio = GPIO.get_platform_gpio()
     # Set DC as output.
     self._gpio.setup(dc, GPIO.OUT)
     # Setup reset as output (if provided).
     if rst is not None:
         self._gpio.setup(rst, GPIO.OUT)
     # Set SPI to mode 0, MSB first.
     spi.set_mode(0)
     spi.set_bit_order(SPI.MSBFIRST)
     spi.set_clock_hz(16000000)
     # Create an image buffer.
     self.buffer = Image.new('RGB', (width, height))
示例#9
0
    def __init__(self, relay_pin):
        self._RELAY_PIN = relay_pin
        # addition pin definiteion for power???

        self.gpio = GPIO.get_platform_gpio()

        self.gpio.setup(self._RELAY_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
示例#10
0
        def __init__(self,
                     clk=None,
                     cs=None,
                     miso=None,
                     mosi=None,
                     spi=None,
                     gpio=None):
            """Initialize MAX31855 device with software SPI on the specified CLK,
			CS, and DO pins.  Alternatively can specify hardware SPI by sending an
			Adafruit_GPIO.SPI.SpiDev device in the spi parameter.
			"""
            self._spi = None
            # Handle hardware SPI
            if spi is not None:
                self._spi = spi
            elif clk is not None and cs is not None and miso is not None and mosi is not None:
                # Default to platform GPIO if not provided.
                if gpio is None:
                    gpio = GPIO.get_platform_gpio()
                self._spi = SPI.BitBang(gpio, clk, mosi, miso, cs)
            else:
                raise ValueError(
                    'Must specify either spi for for hardware SPI or clk, cs, miso, and mosi for softwrare SPI!'
                )
            self._spi.set_clock_hz(1000000)
            self._spi.set_mode(0)
            self._spi.set_bit_order(SPI.MSBFIRST)
示例#11
0
    def __init__(self,
                 num_led,
                 global_brightness=MAX_BRIGHTNESS,
                 order='rgb',
                 mosi=10,
                 sclk=11,
                 max_speed_hz=8000000):
        """Initializes the library.
        
        """
        self.num_led = num_led  # The number of LEDs in the Strip
        order = order.lower()
        self.rgb = RGB_MAP.get(order, RGB_MAP['rgb'])
        # Limit the brightness to the maximum if it's set higher
        if global_brightness > self.MAX_BRIGHTNESS:
            self.global_brightness = self.MAX_BRIGHTNESS
        else:
            self.global_brightness = global_brightness

        self.leds = [self.LED_START, 0, 0, 0] * self.num_led  # Pixel buffer

        # MOSI 10 and SCLK 11 is hardware SPI, which needs to be set-up differently
        if mosi == 10 and sclk == 11:
            self.spi = SPI.SpiDev(0, 0, max_speed_hz)  # Bus 0, chip select 0
        else:
            self.spi = SPI.BitBang(GPIO.get_platform_gpio(), sclk, mosi)
示例#12
0
 def __init__(self, count, clk=None, do=None, spi=None, gpio=None):
     """Initialize set of WS2801/SPI-like addressable RGB LEDs.  Must
     specify the count of pixels, and either an explicit clk (clokc) and do
     (data output) line for software SPI or a spi instance for hardware SPI.
     """
     self._spi = None
     if spi:
         # Handle hardware SPI.
         self._spi = spi
     elif clk and do:
         # Handle software SPI.
         # Default to platform GPIO if not provided.
         if not gpio:
             import Adafruit_GPIO as GPIO
             gpio = GPIO.get_platform_gpio()
         self._spi = SPI.BitBang(gpio, clk, do, None, None)
     else:
         raise ValueError('Must specify either spi for for hardware SPI or clk, and do for software SPI!')
     # Setup SPI interface with up to 20mhz speed.
     self._spi.set_clock_hz(1000000)
     self._spi.set_mode(0)
     self._spi.set_bit_order(SPI.MSBFIRST)
     # Setup buffer for pixel RGB data.
     self._count = count
     self._pixels = [0]*(count*3)
示例#13
0
 def __init__(self, cs, sclk=None, mosi=None, miso=None, gpio=None, 
              spi=None):
     """Create an instance of the PN532 class using either software SPI (if 
     the sclk, mosi, and miso pins are specified) or hardware SPI if a
     spi parameter is passed.  The cs pin must be a digital GPIO pin.
     Optionally specify a GPIO controller to override the default that uses 
     the board's GPIO pins.
     """
     # Default to platform GPIO if not provided.
     self._gpio = gpio
     if self._gpio is None:
         self._gpio = GPIO.get_platform_gpio()
     # Initialize CS line.
     self._cs = cs
     self._gpio.setup(self._cs, GPIO.OUT)
     self._gpio.set_high(self._cs)
     # Setup SPI provider.
     if spi is not None:
         logger.debug('Using hardware SPI.')
         # Handle using hardware SPI.
         self._spi = spi
         self._spi.set_clock_hz(1000000)
     else:
         logger.debug('Using software SPI')
         # Handle using software SPI.  Note that the CS/SS pin is not used
         # as it will be manually controlled by this library for better
         # timing.
         self._spi = SPI.BitBang(self._gpio, sclk, mosi, miso)
     # Set SPI mode and LSB first bit order.
     self._spi.set_mode(0)
     self._spi.set_bit_order(SPI.LSBFIRST)
示例#14
0
	def __init__(self, dc, spi, rst=None, gpio=None, width=HX8357_TFTWIDTH,
		height=HX8357_TFTHEIGHT):
		"""Create an instance of the display using SPI communication.  Must
		provide the GPIO pin number for the D#C pin and the SPI driver.  Can
		optionally provide the GPIO pin number for the reset pin as the rst
		parameter.
		"""
		self._dc = dc
		self._rst = rst
		self._spi = spi
		self._gpio = gpio
		self.width = width
		self.height = height
		if self._gpio is None:
			self._gpio = GPIO.get_platform_gpio()
		# Set DC as output.
		self._gpio.setup(dc, GPIO.OUT)
		# Setup reset as output (if provided).
		if rst is not None:
			self._gpio.setup(rst, GPIO.OUT)
		# Set SPI to mode 0, MSB first.
		spi.set_mode(0)
		spi.set_bit_order(SPI.MSBFIRST)
                
                #need to nerf the clock for Minnow
                if(Platform.platform_detect() == 3): 
		    spi.set_clock_hz(16000000)
                    print 'Rate: MAX'
                else:
                    spi.set_clock_hz(64000000)
                    print 'Rate: 64hz'

		# Create an image buffer.
		self.buffer = Image.new('RGB', (width, height))
示例#15
0
    def __init__(self, gpio_pin, low_temp=0, high_temp=100, history_samples=256, history_time=datetime.timedelta(minutes=5).total_seconds(), polltime=.25, onoff_wait=6):
        self.shutdown_requested = False
        self.gpio_pin = gpio_pin
        self.low_temp = low_temp
        self.high_temp = high_temp
        self.history_time = datetime.timedelta(seconds=history_time)
        self.history_samples = history_samples
        self.last_history_time = 0
        self.burn = False
        self.burn_start_time = 0
        self.burn_stop_time = 0
        self.burn_wait = False
        self.burn_deadband = False
        self.burn_total_secs = 0
        self.mode = MODES.OFF
        self.mode_time = time.time()
        self.poll_time = polltime
        self.onoff_wait = onoff_wait
        self.sense_lock = RLock()

        self.sense = Thermocouple.Thermocouple(spiDev=SPI.SpiDev(port=0, device=0), chip=0)
        self.food = Thermocouple.Thermocouple(spiDev=SPI.SpiDev(port=0, device=1), chip=1)

        self.sense_history = collections.deque([], maxlen=history_samples)
        self.sense_last = None
        self.food_history = collections.deque([], maxlen=history_samples)
        self.food_last = None

        self.logger = logging.getLogger("burner")

        self.gpio = GPIO.get_platform_gpio()
        self.gpio.setup(self.gpio_pin, GPIO.OUT)
        self.gpio.output(self.gpio_pin, True)
示例#16
0
	def begin(self, contrast=40, bias=4):
		"""Initialize display."""
		# Default to detecting platform GPIO.
		if self._gpio is None:
			self._gpio = GPIO.get_platform_gpio()
		# Default to bit bang SPI.
		if self._spi is None:
			self._spi = SPI.BitBang(self._gpio, self._sclk, self._din, None, self._cs)
		# Set pin outputs.
		self._gpio.setup(self._dc, GPIO.OUT)
		if self._rst is not None:
			self._gpio.setup(self._rst, GPIO.OUT)
			# Toggle RST low to reset.
			self._gpio.set_low(self._rst)
			time.sleep(0.1)
			self._gpio.set_high(self._rst)
		# Enter extended mode commands.
		self.command(PCD8544_FUNCTIONSET | PCD8544_EXTENDEDINSTRUCTION)
		# Set LCD bias.
		self.command(PCD8544_SETBIAS | bias)
		# Set contrast.
		contrast = max(0, min(contrast, 0x7f)) # Clamp to values 0-0x7f
		self.command(PCD8544_SETVOP | contrast)
		# Set normal display mode.
		self.command(PCD8544_FUNCTIONSET)
		self.command(PCD8544_DISPLAYCONTROL | PCD8544_DISPLAYNORMAL)
示例#17
0
 def __init__(self,
              width=128,
              height=64,
              dc=None,
              sclk=None,
              din=None,
              cs=None,
              gpio=None,
              spi=None):
     self._spi = None
     self.width = width
     self.height = height
     self._pages = height / 8
     self._buffer = [0] * (width * self._pages)
     # Default to platform GPIO if not provided.
     self._gpio = gpio
     if self._gpio is None:
         self._gpio = GPIO.get_platform_gpio()
     # Setup reset pin.
     if spi is not None:
         #self._log.debug('Using hardware SPI')
         self._spi = spi
         self._spi.set_clock_hz(8000000)
     # Handle software SPI
     if self._spi is not None:
         if dc is None:
             raise ValueError('DC pin must be provided when using SPI.')
         self._dc = dc
         self._gpio.setup(self._dc, GPIO.OUT)
示例#18
0
def main():
    print "RUNNING ACCELEROMETER TEST"
    if (detect_device()):
        return
    set_full_res(1)
    set_range(RANGE_8G)
    set_rate(BW_50)
    set_accelerometer_sensitivity()
    device_start()
    calibrate()
    disable_interrupts()
    set_interrupt_level(INT_ACT_LOW)
    gpio = GPIO.get_platform_gpio()

    #checking for the CHIP platform#
    if (5 == Platform.platform_detect()):
        print "CHIP platform running\n"
    else:
        print "Not running on CHIP device\n"
        exit()

    fifo_int_pin = "PWM1"
    #set AP-EINT1n as the interrupt pin#
    gpio.setup(fifo_int_pin, GPIO.IN)
    print "#", gpio.input(fifo_int_pin)
    #add a callback fn() for falling event on fifo_interrupt#
    gpio.add_event_detect(fifo_int_pin, GPIO.FALLING)
    gpio.add_event_callback(fifo_int_pin, fifo_overflow_handle)
    set_interrupt(INT_ENABLE_WATERMARK, 1)
    if (is_interrupt_enable(INT_ENABLE_WATERMARK)):
        print "int enabled"
    enable_fifo_mode(FIFO_STREAM, FIFO_SAMPLES)
    while 1:
        pass
示例#19
0
	def __init__(self, width, height, rst, dc=None, sclk=None, din=None, cs=None, 
				 gpio=None, spi=None, i2c_bus=I2C.get_default_bus(), i2c_address=SSD1306_I2C_ADDRESS):
		self._log = logging.getLogger('Adafruit_SSD1306.SSD1306Base')
		self._spi = None
		self._i2c = None
		self.width = width
		self.height = height
		self._pages = height/8
		self._buffer = [0]*(width*self._pages)
		# Default to platform GPIO if not provided.
		self._gpio = gpio if gpio is not None else GPIO.get_platform_gpio()
		# Setup reset pin.
		self._rst = rst
		self._gpio.setup(self._rst, GPIO.OUT)
		# Handle hardware SPI
		if spi is not None:
			self._log.debug('Using hardware SPI')
			self._spi = spi
		# Handle software SPI
		elif sclk is not None and din is not None and cs is not None:
			self._log.debug('Using software SPI')
			self._spi = SPI.BitBang(self._gpio, sclk, din, None, cs)
		# Handle hardware I2C
		elif i2c_bus is not None:
			self._log.debug('Using hardware I2C')
			self._i2c = I2C.Device(i2c_address, i2c_bus)
		else:
			raise ValueError('Unable to determine if using SPI or I2C.')
		# Initialize DC pin if using SPI.
		if self._spi is not None:
			if dc is None:
				raise ValueError('DC pin must be provided when using SPI.')
			self._dc = dc
			self._gpio.setup(self._dc, GPIO.OUT)
    def __init__(self, rs, spi, rst=None, gpio=None, width=ILI9225_TFTWIDTH, height=ILI9225_TFTHEIGHT):
        """Create an instance of the display using SPI communication. Must
        provide the GPIO pin number for the RS pin and the SPI driver. Can
        optionally provide the GPIO pin number for the reset pin as the rst
        parameter.
        """
        self._rs = rs
        self._rst = rst
        self._spi = spi
        self._gpio = gpio
        self.width = width
        self.height = height

        if self._gpio is None:
            self._gpio = GPIO.get_platform_gpio()

        # set rs as output
        self._gpio.setup(rs, GPIO.OUT)

        # setup reset as output (if provided)
        if rst is not None:
            self._gpio.setup(rst, GPIO.OUT)

        # set spi to mode 0, msb first.
        spi.set_mode(0)
        spi.set_bit_order(SPI.MSBFIRST)
        spi.set_clock_hz(64000000)

        # create an image buffer.
        self.buffer = Image.new('RGB', (width, height))
示例#21
0
    def __init__(self,
                 num_led,
                 global_brightness=100,
                 order='rgb',
                 mosi=10,
                 sclk=11,
                 bus=0,
                 device=0,
                 max_speed_hz=8000000,
                 led_order=None):
        """Initializes the library."""

        rgb_map = RGB_MAP[order.lower()]
        self.pixel_cmd = APA102Cmd(rgb_map, global_brightness)
        self.leds = [Pixel.BLACK] * num_led
        self.led_order = led_order
        self._assert_led_order()
        self.BRIGHTNESS = APA102Cmd.BRIGHTNESS

        if mosi is None or mosi < 0: # Debug output
            # Reset leds_seq so the terminal output makes sense.
            self.led_order = None
            self.spi = debug.DummySPI(rgb_map)
        else:
            import Adafruit_GPIO.SPI as SPI
            # MOSI 10 and SCLK 11 is hardware SPI, which needs to be set-up differently
            if mosi == 10 and sclk == 11:
                self.spi = SPI.SpiDev(bus, device, max_speed_hz)
            else:
                import Adafruit_GPIO as GPIO
                self.spi = SPI.BitBang(GPIO.get_platform_gpio(), sclk, mosi)
示例#22
0
 def __init__(self, **kwargs):
     """
     :param int bus_id: the SMBus id (see Raspberry Pi documentation)
     :param kwargs: parameters transmitted to :py:class:`smbus.SMBus` initializer
     """
     JNTBus.__init__(self, **kwargs)
     self._spi_lock = threading.Lock()
     self.load_extensions(OID)
     self._ada_gpio = None
     try:
         self._ada_gpio = GPIO.get_platform_gpio()
     except :
         logger.exception("[%s] - Can't get GPIO", self.__class__.__name__)
     self._ada_spi = None
     try:
         self._ada_spi = SPI
     except :
         logger.exception("[%s] - Can't get SPI", self.__class__.__name__)
     self.export_attrs('_ada_spi', self._ada_spi)
     self.export_attrs('_ada_gpio', self._ada_gpio)
     self.export_attrs('spi_acquire', self.spi_acquire)
     self.export_attrs('spi_release', self.spi_release)
     self.export_attrs('spi_locked', self.spi_locked)
     self.export_attrs('get_spi_device', self.get_spi_device)
     self.export_attrs('get_spi_device_pin', self.get_spi_device_pin)
示例#23
0
文件: ST7735.py 项目: GuyCarver/raspi
  def __init__( self, aSPI, aDC, aReset = None, aGPIO = None ) :
    """aLoc SPI pin location is either 1 for 'X' or 2 for 'Y'.
       aDC is the DC pin and aReset is the reset pin."""
    self._rotate = 0                            #Vertical with top toward pins.
    self._rgb = True                            #color order of rgb.
    self._on = True
    self._dc  = aDC
    self._rst = aReset
    self._spi = aSPI
    self._gpio = aGPIO
    if self._gpio == None :
      self._gpio = GPIO.get_platform_gpio()

    if self._rst != None :
      self._gpio.setup(self._rst, GPIO.OUT)

    # Set DC as output.
    self._gpio.setup(self._dc, GPIO.OUT)

    self._spi.set_mode(0)
    self._spi.set_bit_order(SPI.MSBFIRST)
    self._spi.set_clock_hz(ST7735.SPI_HZ)

    self._oneData = [0]
    self._windowLocData = [0, 0, 0, 0]

    # Create an image buffer.
    self._buffer = Image.new('RGB', ScreenSize)
示例#24
0
 def __init__(self,
              bus=0,
              device=0,
              dc_pin=25,
              reset_pin=17,
              buffer_rows=128,
              buffer_cols=128,
              rows=128,
              cols=128):
     self.cols = cols
     self.rows = rows
     self.buffer_rows = buffer_rows
     self.mem_bytes = self.buffer_rows * self.cols / 8  # total bytes in SSD1306 display ram
     self.dc_pin = dc_pin
     self.reset_pin = reset_pin
     self.spi = s_SPI.SpiDev(0, 0, max_speed_hz=8000000)
     self._gpio = GPIO.get_platform_gpio()
     self._rst = reset_pin
     self._gpio.setup(self._rst, GPIO.OUT)
     self._dc = dc_pin
     self._gpio.setup(self._dc, GPIO.OUT)
     self.font = font5x8.Font5x8
     self.col_offset = 0
     self.bitmap = self.SimpleBitmap(buffer_cols, buffer_rows)
     self.flipped = False
示例#25
0
	def __init__(self, dc, spi, rst=None, gpio=None, width=ILI9341_TFTWIDTH,
		height=ILI9341_TFTHEIGHT):
		"""Create an instance of the display using SPI communication.  Must
		provide the GPIO pin number for the D/C pin and the SPI driver.  Can
		optionally provide the GPIO pin number for the reset pin as the rst
		parameter.
		"""
		self._dc = dc
		self._rst = rst
		self._spi = spi
		self._gpio = gpio
		self.width = width
		self.height = height
		if self._gpio is None:
			self._gpio = GPIO.get_platform_gpio()
		# Set DC as output.
		self._gpio.setup(dc, GPIO.OUT)
		# Setup reset as output (if provided).
		if rst is not None:
			self._gpio.setup(rst, GPIO.OUT)
		# Set SPI to mode 0, MSB first.
		spi.set_mode(0)
		spi.set_bit_order(SPI.MSBFIRST)
	
                # Clock nerfed for the Minnowboard	
                if(Platform.platform_detect() == 3):
                    spi.set_clock_hz(1000000)
                else:
                    spi.set_clock_hz(64000000)
		
                # Create an image buffer.
		self.buffer = Image.new('RGB', (width, height))
示例#26
0
    def __init__(self,
                 width,
                 height,
                 rst,
                 dc=None,
                 sclk=None,
                 din=None,
                 cs=None,
                 gpio=None,
                 spi=None,
                 i2c_bus=None,
                 i2c_address=SSD1306_I2C_ADDRESS,
                 i2c=None):
        self._log = logging.getLogger('SOLED.SH1106Base')
        self._spi = None
        self._i2c = None
        self.width = width
        self.height = height
        self._pages = height // 8
        self._buffer = [0] * (width * self._pages)
        # Default to platform GPIO if not provided.
        self._gpio = gpio
        if self._gpio is None:
            self._gpio = GPIO.get_platform_gpio()

        # RESET (RST/RES) Pin setup:
        self._rst = rst
        if not self._rst is None:
            self._gpio.setup(self._rst, GPIO.OUT)

        # Handle hardware SPI
        if spi is not None:
            self._log.debug('Using hardware SPI')
            self._spi = spi
            self._spi.set_clock_hz(8000000)

        # Handle software SPI
        elif sclk is not None and din is not None and cs is not None:
            self._log.debug('Using software SPI')
            self._spi = SPI.BitBang(self._gpio, sclk, din, None, cs)

        # Handle hardware I2C
        elif i2c is not None:
            self._log.debug('Using hardware I2C with custom I2C provider.')
            self._i2c = i2c.get_i2c_device(i2c_address)
        else:
            self._log.debug('Using hardware I2C with platform I2C provider.')
            import Adafruit_GPIO.I2C as I2C
            if i2c_bus is None:
                self._i2c = I2C.get_i2c_device(i2c_address)
            else:
                self._i2c = I2C.get_i2c_device(i2c_address, busnum=i2c_bus)

        # Initialize DC pin if using SPI.
        if self._spi is not None:
            if dc is None:
                raise ValueError('DC pin must be provided when using SPI.')
            self._dc = dc
            self._gpio.setup(self._dc, GPIO.OUT)
示例#27
0
 def Init(self):
     if not self.initialized:
         _gpio = GPIO.get_platform_gpio()
         #GPIO = Adafruit_GPIO.RPiGPIOAdapter(_gpio)
         #GPIO.setmode(GPIO.BOARD)
         
         _gpio.setup(11, GPIO.IN)
         _gpio.setup(7, GPIO.OUT)
         self.initialized = True
示例#28
0
    def Init(self):
        if not self.initialized:
            _gpio = GPIO.get_platform_gpio()
            #GPIO = Adafruit_GPIO.RPiGPIOAdapter(_gpio)
            #GPIO.setmode(GPIO.BOARD)

            _gpio.setup(11, GPIO.IN)
            _gpio.setup(7, GPIO.OUT)
            self.initialized = True
示例#29
0
 def start(self, mqttc, trigger_thread_reload_cb=None):
     """Start the bus
     """
     JNTBus.start(self, mqttc, trigger_thread_reload_cb)
     try:
         self.gpio = GPIO.get_platform_gpio()
     except Exception:
         logger.exception("[%s] - Exception when starting GPIO bus", self.__class__.__name__)
     self.update_attrs('gpio', self.gpio)
    def __init__(
        self,
        width,
        height,
        rst,
        dc=None,
        sclk=None,
        din=None,
        cs=None,
        gpio=None,
        spi=None,
        i2c_bus=None,
        i2c_address=SSD1306_I2C_ADDRESS,
        i2c=None,
    ):
        self._log = logging.getLogger("Adafruit_SSD1306.SSD1306Base")
        self._spi = None
        self._i2c = None
        self.width = width
        self.height = height
        self._pages = height / 8
        self._buffer = [0] * (width * self._pages)
        # Default to platform GPIO if not provided.
        self._gpio = gpio
        if self._gpio is None:
            self._gpio = GPIO.get_platform_gpio()
            # Setup reset pin.
        self._rst = rst
        self._gpio.setup(self._rst, GPIO.OUT)
        # Handle hardware SPI
        if spi is not None:
            self._log.debug("Using hardware SPI")
            self._spi = spi
            self._spi.set_clock_hz(8000000)
            # Handle software SPI
        elif sclk is not None and din is not None and cs is not None:
            self._log.debug("Using software SPI")
            self._spi = SPI.BitBang(self._gpio, sclk, din, None, cs)
            # Handle hardware I2C
        elif i2c is not None:
            self._log.debug("Using hardware I2C with custom I2C provider.")
            self._i2c = i2c.get_i2c_device(i2c_address)
        else:
            self._log.debug("Using hardware I2C with platform I2C provider.")
            import Adafruit_GPIO.I2C as I2C

            if i2c_bus is None:
                self._i2c = I2C.get_i2c_device(i2c_address)
            else:
                self._i2c = I2C.get_i2c_device(i2c_address, busnum=i2c_bus)
                # Initialize DC pin if using SPI.
        if self._spi is not None:
            if dc is None:
                raise ValueError("DC pin must be provided when using SPI.")
            self._dc = dc
            self._gpio.setup(self._dc, GPIO.OUT)
示例#31
0
	def __init__(self, dc, rst, sclk=None, din=None, cs=None, gpio=None, spi=None, backlight=None):
		self._sclk = sclk
		self._din = din
		self._dc = dc
		self._cs = cs
		self._rst = rst
		self._gpio = gpio
		self._spi = spi
		self._backlight = backlight
		# Default to detecting platform GPIO.
		if self._gpio is None:
			self._gpio = GPIO.get_platform_gpio()
		if self._rst is not None:
			self._gpio.setup(self._rst, GPIO.OUT)
		if self._backlight is not None:
			self._gpio.setup(self._backlight, GPIO.OUT)
			#Default turn on backlight
			self._gpio.set_high(self._backlight)
		# Default to bit bang SPI.
		if self._spi is None:
			self._spi = SPI.BitBang(self._gpio, self._sclk, self._din, None, self._cs)
		# Set pin outputs.
		self._gpio.setup(self._dc, GPIO.OUT)
		# Initialize buffer to Adafruit logo.
		self._buffer = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFC, 0xFE, 0xFF, 0xFC, 0xE0,
						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8,
						0xF8, 0xF0, 0xF0, 0xE0, 0xE0, 0xC0, 0x80, 0xC0, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x3F, 0x7F,
						0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF, 0xFF,
						0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE7, 0xC7, 0xC7, 0x87, 0x8F, 0x9F, 0x9F, 0xFF, 0xFF, 0xFF,
						0xC1, 0xC0, 0xE0, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0xFC, 0xFC, 0xFC, 0xFE, 0xFE, 0xFE,
						0xFC, 0xFC, 0xF8, 0xF8, 0xF0, 0xE0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x80, 0xC0, 0xE0, 0xF1, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x1F, 0x0F, 0x0F, 0x87,
						0xE7, 0xFF, 0xFF, 0xFF, 0x1F, 0x1F, 0x3F, 0xF9, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xFD, 0xFF,
						0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x3F, 0x0F, 0x07, 0x01, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0xF0, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
						0x7E, 0x3F, 0x3F, 0x0F, 0x1F, 0xFF, 0xFF, 0xFF, 0xFC, 0xF0, 0xE0, 0xF1, 0xFF, 0xFF, 0xFF, 0xFF,
						0xFF, 0xFC, 0xF0, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x01,
						0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x0F, 0x1F, 0x3F, 0x7F, 0x7F,
						0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x7F, 0x1F, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ]
示例#32
0
    def __init__(self, sensor_pin, led_pin):
        self._SENSOR_PIN = sensor_pin
        self._LED_PIN = led_pin

        self.gpio = GPIO.get_platform_gpio()

        self.gpio.setup(self._LED_PIN, GPIO.OUT)
        self.gpio.output(self._LED_PIN, GPIO.HIGH)

        self.gpio.setup(self._SENSOR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
示例#33
0
def testaaGPIOmode():
	# global gpio;
	try:
		if boardNumbering: # jos numerointi pinnien mukaan
			gpio = GPIO.get_platform_gpio(mode=RPi.GPIO.BOARD); # Voidaan pakottaa BOARD-mode;
			RPi.GPIO.setmode(GPIO.BOARD) # pinnit aina samalla paikalla fyysisesti

		if not boardNumbering: # kun BCM-numerointi eli kaytetaan nimettyja GPIO-numeroita
			gpio = GPIO.get_platform_gpio();
			#RPi.GPIO.setmode(GPIO.BCM) # ei turvallinen, kun kaytossa on useita eri laiteversioita
	
		# Test GPIO-mode
		debug("testataan moodi")
		GPIOmode = RPi.GPIO.getmode(); # komento, jos RPi.GPIO
		debug("GPIOhallinta says - GPIO-mode on nyt: " + str(GPIOmode)+" . Jos (10)--> BOARD, jos (11)--> BCM" ) # ollaanko jo BCM-modessa vai BOARD		
	except KeyboardInterrupt:
		debug ("Keskeytetty painamalla ctrl+C");
	except:
		debug ("Keskeytetty jollain muulla tavalla 104");	
    def __init__(self,
                 tc_type=MAX31856_T_TYPE,
                 avgsel=0x0,
                 software_spi=None,
                 hardware_spi=None,
                 gpio=None):
        """
        Initialize MAX31856 device with software SPI on the specified CLK,
        CS, and DO pins.  Alternatively can specify hardware SPI by sending an
        SPI.SpiDev device in the spi parameter.

        Args:
            tc_type (1-byte Hex): Type of Thermocouple.  Choose from class variables of the form
                MAX31856.MAX31856_X_TYPE.
            avgsel (1-byte Hex): Type of Averaging.  Choose from values in CR0 table of datasheet.
                Default is single sample.
            software_spi (dict): Contains the pin assignments for software SPI, as defined below:
                clk (integer): Pin number for software SPI clk
                cs (integer): Pin number for software SPI cs
                do (integer): Pin number for software SPI MISO
                di (integer): Pin number for software SPI MOSI
            hardware_spi (SPI.SpiDev): If using hardware SPI, define the connection
        """
        self._logger = logging.getLogger('Adafruit_MAX31856.MAX31856')
        self._spi = None
        self.tc_type = tc_type
        self.avgsel = avgsel
        # Handle hardware SPI
        if hardware_spi is not None:
            self._logger.debug('Using hardware SPI')
            self._spi = hardware_spi
        elif software_spi is not None:
            self._logger.debug('Using software SPI')
            # Default to platform GPIO if not provided.
            if gpio is None:
                gpio = Adafruit_GPIO.get_platform_gpio()
            self._spi = SPI.BitBang(gpio, software_spi['clk'],
                                    software_spi['di'], software_spi['do'],
                                    software_spi['cs'])
        else:
            raise ValueError(
                'Must specify either spi for for hardware SPI or clk, cs, and do for softwrare SPI!'
            )
        self._spi.set_clock_hz(5000000)
        # According to Wikipedia (on SPI) and MAX31856 Datasheet:
        #   SPI mode 1 corresponds with correct timing, CPOL = 0, CPHA = 1
        self._spi.set_mode(1)
        self._spi.set_bit_order(SPI.MSBFIRST)

        self.cr1 = ((self.avgsel << 4) + self.tc_type)

        # Setup for reading continuously with T-Type thermocouple
        self._write_register(self.MAX31856_REG_WRITE_CR0,
                             self.MAX31856_CR0_READ_CONT)
        self._write_register(self.MAX31856_REG_WRITE_CR1, self.cr1)
示例#35
0
class SSD1306Base(object):
    """Base class for SSD1306-based OLED displays.  Implementors should subclass
    and provide an implementation for the _initialize function.
    """

    def __init__(self, width, height, rst, dc=None, sclk=None, din=None, cs=None,
                 gpio=None, spi=None, i2c_bus=None, i2c_address=SSD1306_I2C_ADDRESS,
                 i2c=None, mcp_rst=None, mcp_address=None):
        self._log = logging.getLogger('Adafruit_SSD1306.SSD1306Base')
        self._spi = None
        self._i2c = None
        self.width = width
        self.height = height
        self._pages = height//8
        self._buffer = [0]*(width*self._pages)
        # Default to platform GPIO if not provided.
        self._gpio = gpio
        # Instantiate MCP if rst pin is in mcp.
        if mcp_rst is not None and mcp_address is not None:
            self.__mcp_rst = mcp_rst
            self.__mcp = MCP.MCP23017(mcp_address, busnum=1)
		    self.__mcp.setup(self.__mcp_rst, MCP.GPIO.OUT)
        
        if self._gpio is None:
            self._gpio = GPIO.get_platform_gpio()
        # Setup reset pin.
        self._rst = rst
        if not self._rst is None and (mcp_rst is None or mcp_address is None):
            self._gpio.setup(self._rst, GPIO.OUT)
        # Handle hardware SPI
        if spi is not None:
            self._log.debug('Using hardware SPI')
            self._spi = spi
            self._spi.set_clock_hz(8000000)
        # Handle software SPI
        elif sclk is not None and din is not None and cs is not None:
            self._log.debug('Using software SPI')
            self._spi = SPI.BitBang(self._gpio, sclk, din, None, cs)
        # Handle hardware I2C
        elif i2c is not None:
            self._log.debug('Using hardware I2C with custom I2C provider.')
            self._i2c = i2c.get_i2c_device(i2c_address)
        else:
            self._log.debug('Using hardware I2C with platform I2C provider.')
            if i2c_bus is None:
                self._i2c = I2C.get_i2c_device(i2c_address)
            else:
                self._i2c = I2C.get_i2c_device(i2c_address, busnum=i2c_bus)
        # Initialize DC pin if using SPI.
        if self._spi is not None:
            if dc is None:
                raise ValueError('DC pin must be provided when using SPI.')
            self._dc = dc
            self._gpio.setup(self._dc, GPIO.OUT)
示例#36
0
def test_pins(pins):
    print('testing pins %r' % pins)
    gpio = GPIO.get_platform_gpio()
    for pin in pins:
        gpio.setup(pin, GPIO.IN, GPIO.PUD_UP)

    i = 0
    while True:
        results = [pin for pin in pins if gpio.input(pin) == 0]
        print('%04d: %r' % (i, results))
        time.sleep(.01)
        i += 1
 def test_101_detect(self):
     self.onlyRasperryTest()
     import Adafruit_GPIO as GPIO
     comp = self.factory[self.component_name]()
     gpio = GPIO.get_platform_gpio()
     comp.setup_pir(gpio, 21, GPIO.RISING, comp.callback_pir, 200)
     time.sleep(5)
     dist = comp.values['status'].data
     print "status", dist
     self.assertNotEqual(dist, None)
     self.assertTrue(comp.check_heartbeat())
     gpio.cleanup()
示例#38
0
    def __init__(self, rs, en, d4, d5, d6, d7, cols, lines, red, green, blue,
                 gpio=GPIO.get_platform_gpio(),
                 invert_polarity=True,
                 enable_pwm=False,
                 pwm=PWM.get_platform_pwm(),
                 initial_color=(1.0, 1.0, 1.0),
                 long_delay_us=DEFAULT_LONG_DELAY_US):
        """Initialize the LCD with RGB backlight.  RS, EN, and D4...D7 parameters
        should be the pins connected to the LCD RS, clock enable, and data line
        4 through 7 connections. The LCD will be used in its 4-bit mode so these
        6 lines are the only ones required to use the LCD.  You must also pass in
        the number of columns and lines on the LCD.

        The red, green, and blue parameters define the pins which are connected
        to the appropriate backlight LEDs.  The invert_polarity parameter is a
        boolean that controls if the LEDs are on with a LOW or HIGH signal.  By
        default invert_polarity is True, i.e. the backlight LEDs are on with a
        low signal.  If you want to enable PWM on the backlight LEDs (for finer
        control of colors) and the hardware supports PWM on the provided pins,
        set enable_pwm to True.  Finally you can set an explicit initial backlight
        color with the initial_color parameter.  The default initial color is
        white (all LEDs lit).

        You can optionally pass in an explicit GPIO class,
        for example if you want to use an MCP230xx GPIO extender.  If you don't
        pass in an GPIO instance, the default GPIO for the running platform will
        be used.
        """
        super(Adafruit_RGBCharLCD, self).__init__(rs, en, d4, d5, d6, d7,
                                                  cols,
                                                  lines,
                                                  enable_pwm=enable_pwm,
                                                  backlight=None,
                                                  invert_polarity=invert_polarity,
                                                  gpio=gpio,
                                                  pwm=pwm,
                                                  long_delay_us=long_delay_us)
        self._red = red
        self._green = green
        self._blue = blue
        # Setup backlight pins.
        if enable_pwm:
            # Determine initial backlight duty cycles.
            rdc, gdc, bdc = self._rgb_to_duty_cycle(initial_color)
            pwm.start(red, rdc)
            pwm.start(green, gdc)
            pwm.start(blue, bdc)
        else:
            gpio.setup(red, GPIO.OUT)
            gpio.setup(green, GPIO.OUT)
            gpio.setup(blue, GPIO.OUT)
            self._gpio.output_pins(self._rgb_to_pins(initial_color))
示例#39
0
 def __init__(self):
     self.csPins = [14, 15, 23, 7]
     self.gpio = GPIO.get_platform_gpio()
     for p in self.csPins:
         self.gpio.setup(p, GPIO.OUT)
     self.disp = TFT.ST7735(DC,
                            rst=RST,
                            spi=SPI.SpiDev(SPI_PORT,
                                           SPI_DEVICE,
                                           max_speed_hz=SPEED_HZ))
     self.selectAllScreens()
     self.disp.begin()
     self.clearAll()
 def test_102_read_distance(self):
     self.onlyRasperryTest()
     import Adafruit_GPIO as GPIO
     comp = self.factory[self.component_name]()
     gpio = GPIO.get_platform_gpio()
     comp.setup_sonic(gpio, 20, 21, GPIO.RISING, comp.callback_echo, 200)
     comp.trigger_sonic(gpio, 20)
     time.sleep(1)
     dist = comp.values['status'].data
     print "distance", dist
     self.assertNotEqual(dist, None)
     self.assertTrue(comp.check_heartbeat())
     gpio.cleanup()
示例#41
0
    def __init__(self, rs, en, d4, d5, d6, d7, cols, lines, red, green, blue,
                 gpio=GPIO.get_platform_gpio(), 
                 invert_polarity=True,
                 enable_pwm=False,
                 pwm=PWM.get_platform_pwm(),
                 initial_color=(1.0, 1.0, 1.0)):
        """Initialize the LCD with RGB backlight.  RS, EN, and D4...D7 parameters 
        should be the pins connected to the LCD RS, clock enable, and data line 
        4 through 7 connections. The LCD will be used in its 4-bit mode so these 
        6 lines are the only ones required to use the LCD.  You must also pass in
        the number of columns and lines on the LCD.

        The red, green, and blue parameters define the pins which are connected
        to the appropriate backlight LEDs.  The invert_polarity parameter is a
        boolean that controls if the LEDs are on with a LOW or HIGH signal.  By
        default invert_polarity is True, i.e. the backlight LEDs are on with a
        low signal.  If you want to enable PWM on the backlight LEDs (for finer
        control of colors) and the hardware supports PWM on the provided pins,
        set enable_pwm to True.  Finally you can set an explicit initial backlight
        color with the initial_color parameter.  The default initial color is
        white (all LEDs lit).

        You can optionally pass in an explicit GPIO class,
        for example if you want to use an MCP230xx GPIO extender.  If you don't
        pass in an GPIO instance, the default GPIO for the running platform will
        be used.
        """
        super(Adafruit_RGBCharLCD, self).__init__(rs, en, d4, d5, d6, d7,
                                                  cols,
                                                  lines, 
                                                  enable_pwm=enable_pwm,
                                                  backlight=None,
                                                  invert_polarity=invert_polarity,
                                                  gpio=gpio, 
                                                  pwm=pwm)
        self._red = red
        self._green = green
        self._blue = blue
        # Setup backlight pins.
        if enable_pwm:
            # Determine initial backlight duty cycles.
            rdc, gdc, bdc = self._rgb_to_duty_cycle(initial_color)
            pwm.start(red, rdc)
            pwm.start(green, gdc)
            pwm.start(blue, bdc)
        else:
            gpio.setup(red, GPIO.OUT)
            gpio.setup(green, GPIO.OUT)
            gpio.setup(blue, GPIO.OUT)
            self._gpio.output_pins(self._rgb_to_pins(initial_color))
示例#42
0
    def __init__(
        self,
        width,
        height,
        rst,
        dc=None,
        sclk=None,
        din=None,
        cs=None,
        gpio=None,
        i2c_bus=None,
        i2c_address=SSD1306_I2C_ADDRESS,
        i2c=None,
    ):
        self._log = logging.getLogger("Adafruit_SSD1306.SSD1306Base")
        self._i2c = None
        self.width = width
        self.height = height
        self._pages = height // 8
        self._buffer = [0] * (width * self._pages)

        # Default to platform GPIO if not provided.
        self._gpio = gpio
        if self._gpio is None:
            self._gpio = GPIO.get_platform_gpio()

        # Setup reset pin.
        self._rst = rst
        if self._rst is not None:
            self._gpio.setup(self._rst, GPIO.OUT)

        # Handle hardware I2C
        elif i2c is not None:
            self._log.debug("Using hardware I2C with custom I2C provider.")
            self._i2c = i2c.get_i2c_device(i2c_address)
        else:
            self._log.debug("Using hardware I2C with platform I2C provider.")

            if i2c_bus is None:
                self._i2c = I2C.get_i2c_device(i2c_address)
            else:
                self._i2c = I2C.get_i2c_device(i2c_address, busnum=i2c_bus)

        # Initialize DC pin if using SPI.
        if self._spi is not None:
            if dc is None:
                raise ValueError("DC pin must be provided when using SPI.")
            self._dc = dc
            self._gpio.setup(self._dc, GPIO.OUT)
示例#43
0
 def __init__(self, lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
              lcd_columns, lcd_rows, lcd_backlight):
     self.lcd = LCD(lcd_rs,
                    lcd_en,
                    lcd_d4,
                    lcd_d5,
                    lcd_d6,
                    lcd_d7,
                    lcd_columns,
                    lcd_rows,
                    lcd_backlight,
                    gpio=aGPIO.get_platform_gpio())
     self.lcd.clear()
     self._columns = lcd_columns
     self._in_progress = None
示例#44
0
  def __init__(self, width, height, rst, dc, spi=None, spi_port=None, spi_device=None, gpio=None):
    """ Initialize the SSD1351

    width: pixel width (128)
    height: pixel height (128)

    rst: reset pin
    dc: dc pin

    spi: SPI device
            spi_port: if SPI object is not passed, then use this spi port
            spi_device: if SPI object is not passed, use this spi device

    gpio: GPIO device. If GPIO is not passed, use the platform gpio

    """

    # Set screen dimensions
    self.width = width
    self.height = height

    # Set up GPIO
    if gpio is not None:
      self._gpio = gpio
    else:
      self._gpio = GPIO.get_platform_gpio()

    # Set up pins
    self._rst = rst
    self._dc = dc
    self._gpio.setup(self._rst, GPIO.OUT)
    self._gpio.setup(self._dc, GPIO.OUT)

    # Set up SPI
    if spi is not None:
      self._spi = spi
    else:
      if spi_port is None or spi_device is None:
        raise ValueError(
            "spi_port and spi_dev must be set if no spi object is passed")
      self._spi = SPI.SpiDev(
          spi_port, spi_device, max_speed_hz=20000000)

    self._spi.set_clock_hz(20000000)

    # Create buffer for images
    self._buffer = [0] * (self.width * self.height)
    self._current_row = 0
示例#45
0
 def __init__(self, bus=0, device=0, dc_pin=25, reset_pin=17, buffer_rows=128, buffer_cols=128, rows=128, cols=128):
     self.cols = cols
     self.rows = rows
     self.buffer_rows = buffer_rows
     self.mem_bytes = self.buffer_rows * self.cols / 8  # total bytes in SSD1306 display ram
     self.dc_pin = dc_pin
     self.reset_pin = reset_pin
     self.spi = s_SPI.SpiDev(0, 0, max_speed_hz=8000000)
     self._gpio = GPIO.get_platform_gpio()
     self._rst = reset_pin
     self._gpio.setup(self._rst, GPIO.OUT)
     self._dc = dc_pin
     self._gpio.setup(self._dc, GPIO.OUT)
     self.font = font5x8.Font5x8
     self.col_offset = 0
     self.bitmap = self.SimpleBitmap(buffer_cols, buffer_rows)
     self.flipped = False
示例#46
0
    def __init__(self, a_pin, b_pin):
        self.a_pin = a_pin
        self.b_pin = b_pin

        self.gpio = GPIO.get_platform_gpio()

        self.gpio.setup(self.a_pin, GPIO.IN)
        self.gpio.setup(self.b_pin, GPIO.IN)

        self.last_delta = 0
        self.r_seq = self.rotation_sequence()

        # steps_per_cycle and remainder are only used in get_cycles which
        # returns a coarse-granularity step count.  By default
        # steps_per_cycle is 4 as there are 4 steps per
        # detent on my encoder, and get_cycles() will return -1 or 1
        # for each full detent step.
        self.steps_per_cycle = 4
        self.remainder = 0
示例#47
0
 def __init__(self, clk=None, cs=None, miso=None, mosi=None, spi=None, gpio=None):
     """Initialize MAX31855 device with software SPI on the specified CLK,
     CS, and DO pins.  Alternatively can specify hardware SPI by sending an
     Adafruit_GPIO.SPI.SpiDev device in the spi parameter.
     """
     self._spi = None
     # Handle hardware SPI
     if spi is not None:
         self._spi = spi
     elif clk is not None and cs is not None and miso is not None and mosi is not None:
         # Default to platform GPIO if not provided.
         if gpio is None:
             gpio = GPIO.get_platform_gpio()
         self._spi = SPI.BitBang(gpio, clk, mosi, miso, cs)
     else:
         raise ValueError('Must specify either spi for for hardware SPI or clk, cs, miso, and mosi for softwrare SPI!')
     self._spi.set_clock_hz(1000000)
     self._spi.set_mode(0)
     self._spi.set_bit_order(SPI.MSBFIRST)
示例#48
0
    def __init__(self, width, height, rst, dc=None, sclk=None, din=None, cs=None, gpio=None,
                 spi=None, i2c_bus=None, i2c_address=SSD1306_I2C_ADDRESS,
                 i2c=None):
        self._spi = None
        self._i2c = None
        self.width = width
        self.height = height
        self._pages = height // 8
        self._buffer = [0] * width * self._pages
        self._cursor = 0

        # Default to platform GPIO if not provided.
        self._gpio = gpio
        if self._gpio is None:
            self._gpio = GPIO.get_platform_gpio()

        # Setup reset pin.
        self._rst = rst
        self._gpio.setup(self._rst, GPIO.OUT)

        # Handle hardware SPI
        if spi is not None:
            self._spi = spi
            self._spi.set_clock_hz(8000000)
        # Handle software SPI
        elif sclk is not None and din is not None and cs is not None:
            self._spi = SPI.BitBang(self._gpio, sclk, din, None, cs)
        # Handle hardware I2C
        elif i2c is not None:
            self._i2c = i2c.get_i2c_device(i2c_address)
        else:
            import Adafruit_GPIO.I2C as I2C

            self._i2c = I2C.get_i2c_device(i2c_address) if i2c_bus is None else I2C.get_i2c_device(i2c_address,
                                                                                                   busnum=i2c_bus)

        # Initialize DC pin if using SPI.
        if self._spi is not None:
            if dc is None:
                raise ValueError('DC pin must be provided when using SPI.')
            self._dc = dc
            self._gpio.setup(self._dc, GPIO.OUT)
示例#49
0
    def __init__(self, width=128, height=64, dc=None, sclk=None, din=None, cs=None,
				 gpio=None, spi=None ):
        self._spi = None
        self.width = width
        self.height = height
        self._pages = height/8
        self._buffer = [0]*(width*self._pages)
        # Default to platform GPIO if not provided.
        self._gpio = gpio
        if self._gpio is None:
            self._gpio = GPIO.get_platform_gpio()
        # Setup reset pin.
        if spi is not None:
            #self._log.debug('Using hardware SPI')
            self._spi = spi
            self._spi.set_clock_hz(8000000)
        # Handle software SPI
        if self._spi is not None:
            if dc is None:
                raise ValueError('DC pin must be provided when using SPI.')
            self._dc = dc
            self._gpio.setup(self._dc, GPIO.OUT)
示例#50
0
文件: apa102.py 项目: tinue/APA102_Pi
    def __init__(self, num_led, global_brightness=MAX_BRIGHTNESS,
                 order='rgb', mosi=10, sclk=11, max_speed_hz=8000000,
                 ce=None):
        """Initializes the library.
        
        """
        self.num_led = num_led  # The number of LEDs in the Strip
        order = order.lower()
        self.rgb = RGB_MAP.get(order, RGB_MAP['rgb'])
        # Limit the brightness to the maximum if it's set higher
        if global_brightness > self.MAX_BRIGHTNESS:
            self.global_brightness = self.MAX_BRIGHTNESS
        else:
            self.global_brightness = global_brightness

        self.leds = [self.LED_START, 0, 0, 0] * self.num_led  # Pixel buffer

        # MOSI 10 and SCLK 11 is hardware SPI, which needs to be set-up differently
        if mosi == 10 and sclk == 11:
            self.spi = SPI.SpiDev(0, 0 if ce is None else ce, max_speed_hz)  # Bus 0
        else:
            self.spi = SPI.BitBang(GPIO.get_platform_gpio(), sclk, mosi, ss=ce)
示例#51
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((900, 600))

    complete = pygame.mixer.Sound('thats-correct.ogg')

    # Trigger the master alarm
    master_alarm = True

    # Generate the display objects
    goal_display = seven_segment_i2c.SevenSegmentDisplay(address=0x71)
    actual_display = seven_segment_i2c.SevenSegmentDisplay(address=0x72)
    parallel_group_display0 = seven_segment_i2c.SevenSegmentDisplay(address=0x73)
    parallel_group_display1 = seven_segment_i2c.SevenSegmentDisplay(address=0x74)
    parallel_group_display2 = seven_segment_i2c.SevenSegmentDisplay(address=0x75)

    # Set up the input pins for the switches
    pins = ["P8_7",  "P8_9",  "P8_11",
            "P8_8",  "P8_10", "P8_12",
            "P8_14", "P8_16", "P8_18"]

    switches = [GPIO.get_platform_gpio()] * len(pins)
    for i in range(len(switches)):
        switches[i].setup(pins[i], GPIO.IN)

    # Set the goal impedance of the circuit
    goal = set_goal(load_combinations())

    # Set a fake actual resistance to get the while loop started
    # actual = 0

    # Display the goal impedance of the circuit
    goal_display.write_int(goal)

    while master_alarm is True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                master_alarm = True

        # Read all the switches.
        switch_states = [0] * len(switches)
        resistance = [0, 0, 0]
        for i in range(len(switches)):
            switch_states[i] = switches[i].input(pins[i])

        # Calculate the resistance of the display groups
        for i in range(0, 3):
            if switch_states[i]:
                resistance[0] += RESISTOR_VALUES[i]  # Calculate the resistance of the first group
        for i in range(3, 6):
            if switch_states[i]:
                resistance[1] += RESISTOR_VALUES[i]  # Calculate the resistance of the second group
        for i in range(6, 9):
            if switch_states[i]:
                resistance[2] += RESISTOR_VALUES[i]  # Calculate the resistance of the third group

        # I'm not sure what this does, I can't remember why I added it. I think it was because the 'resistance' array
        # was not appending properly, although I can't see how this would fix that...
        for i in range(len(resistance)):
            resistance[i] = resistance[i]

        actual = sum(resistance)

        # Display the resistance values
        parallel_group_display0.write_int(resistance[0])
        parallel_group_display1.write_int(resistance[1])
        parallel_group_display2.write_int(resistance[2])
        actual_display.write_int(actual)

        # Check to see if we have solved the puzzle
        if actual == goal:
            master_alarm = False
            complete.play()

            # Flash the 'goal' and 'actual' displays to show they match
            for i in range(3):
                goal_display.clear_display()
                actual_display.clear_display()
                parallel_group_display0.clear_display()
                parallel_group_display1.clear_display()
                parallel_group_display2.clear_display()

                time.sleep(0.15)

                goal_display.write_int(goal)
                actual_display.write_int(actual)
                parallel_group_display0.write_int(resistance[0])
                parallel_group_display1.write_int(resistance[1])
                parallel_group_display2.write_int(resistance[2])

                time.sleep(0.50)

            # Turn off all the displays when the puzzle is solved.
            # I think we should play a sound to reinforce the success
            goal_display.clear_display()
            actual_display.clear_display()
            parallel_group_display0.clear_display()
            parallel_group_display1.clear_display()
            parallel_group_display2.clear_display()

        # Delay for a small amount of time
        time.sleep(0.25)

        # Update the display
        pygame.display.flip()
示例#52
0
def main():
    # Generate the display objects
    goal_display = seven_segment_i2c.SevenSegmentDisplay(address=0x71)
    actual_display = seven_segment_i2c.SevenSegmentDisplay(address=0x72)
    parallel_group_display0 = seven_segment_i2c.SevenSegmentDisplay(address=0x73)
    parallel_group_display1 = seven_segment_i2c.SevenSegmentDisplay(address=0x74)
    parallel_group_display2 = seven_segment_i2c.SevenSegmentDisplay(address=0x75)

    # Set up the input pins for the switches
    pins = ["P8_7",  "P8_9",  "P8_11",
            "P8_8",  "P8_10", "P8_12",
            "P8_14", "P8_16", "P8_18"]

    open_loop_val = "0000"

    switches = [GPIO.get_platform_gpio()] * len(pins)
    for i in range(len(switches)):
        switches[i].setup(pins[i], GPIO.IN)

    goal = int(set_goal(load_combinations()))
    print(goal)
    goal_display.write_int(goal)

    while True:
        # Read all the switches.
        switch_states = [0] * len(switches)
        resistance = [0, 0, 0]
        for i in range(len(switches)):
            # Read the specified ADC channel using the previously set gain value.
            switch_states[i] = switches[i].input(pins[i])

        if ((switch_states[0] or switch_states[1] or switch_states[2]) and  # A closed switch in the first group
                (switch_states[3] or switch_states[4] or switch_states[5]) and  # A closed switch in the second group
                (switch_states[6] or switch_states[7] or switch_states[8])):  # A closed switch in the third group
            # The circuit is complete and we should calculate the impedance
            for i in range(0, 3):
                if switch_states[i]:
                    resistance[0] += 1 / RESISTOR_VALUES[i]  # calculate the resistance of the first group
            for i in range(3, 6):
                if switch_states[i]:
                    resistance[1] += 1 / RESISTOR_VALUES[i]  # calculate the resistance of the second group
            for i in range(6, 9):
                if switch_states[i]:
                    resistance[2] += 1 / RESISTOR_VALUES[i]  # calculate the resistance of the third group
            # Display the resistance values
            for i in range(len(resistance)):
                resistance[i] = int(1 / resistance[i])
            print(resistance)
            print(sum(resistance))
            parallel_group_display0.write_int(resistance[0])
            parallel_group_display1.write_int(resistance[1])
            parallel_group_display2.write_int(resistance[2])
            actual_display.write_int(sum(resistance))
        else:
            # The circuit is NOT complete and we should print the open loop values to the displays
            actual_display.write_int(open_loop_val)
            parallel_group_display0.write_int(open_loop_val)
            parallel_group_display1.write_int(open_loop_val)
            parallel_group_display2.write_int(open_loop_val)

        # Print the ADC values.
        # print('| {0:>1} | {1:>1} | {2:>1} | {3:>6} | {4:>1} | {5:<6} | {6:>1} | {7:>1} | {8:>1} |'.format(*switch_states))
        # Pause for half a second.
        time.sleep(0.5)
示例#53
0
from collections import namedtuple

motor = namedtuple("motor", "step dir")
sensor = namedtuple("sensor", "dev rate")

## parameters - beaglebone
# motor1 = motor(step = "P8_8", dir = "P8_10")
# motor2 = motor(step = "P8_12", dir = "P8_14")
## parameters - minnowboard
motor1 = motor(step = 476, dir = 477)
motor2 = motor(step = 478, dir = 479)
sensor1 = sensor(dev = "/dev/ttyUSB0", rate = 9600)
sensor2 = sensor(dev = "/dev/ttyUSB1", rate = 9600)
## parameters - general
delta = 50
gpio = GPIO.get_platform_gpio()
pos_max = 70
pos_min = -70

## functions
# single step on rising edge
def step (pin):
  gpio.output(pin, GPIO.HIGH)
  time.sleep(1E-3)
  gpio.output(pin, GPIO.LOW)
  time.sleep(1E-3)

# do some steps
def loop (pin_step, pin_dir, num, dir):
  gpio.output(pin_dir, dir)
  for i in range(0, num):
示例#54
0

import time
import sys
import os
from PIL import Image
from pyDrivers.ada_lcd import *
import pyDrivers.ILI9341 as TFT
import Adafruit_GPIO as GPIO
import Adafruit_GPIO.SPI as SPI

if (len(sys.argv) < 2 ):
    print "Usage: python slideshow.py [image directory]"
    exit(1)

myGPIO = GPIO.get_platform_gpio()

myGPIO.setup(12,GPIO.IN)
myGPIO.setup(16,GPIO.IN)

lcd = ADA_LCD()
lcd.clear()

SPI_PORT = 0
SPI_DEVICE = 0
SPEED = 16000000
DC = 10
RST = 14 

imageList = []
rawList = os.listdir(sys.argv[1])
	def test_raspberrypi(self):
		gpio = GPIO.get_platform_gpio()
		self.assertIsInstance(gpio, GPIO.RPiGPIOAdapter)
	def test_beagleboneblack(self):
		gpio = GPIO.get_platform_gpio()
		self.assertIsInstance(gpio, GPIO.AdafruitBBIOAdapter)
示例#57
0
文件: lcd.py 项目: petli/codplayer
 def get_led_controller(self):
     import Adafruit_GPIO as GPIO
     return GPIO_LEDController(GPIO.get_platform_gpio(), self._pin_led, self._get_pwm())
示例#58
0
    def __init__(self, rs, en, d4, d5, d6, d7, cols, lines, backlight=None,
                    invert_polarity=True,
                    enable_pwm=False,
                    gpio=GPIO.get_platform_gpio(),
                    pwm=PWM.get_platform_pwm(),
                    initial_backlight=1.0):
        """Initialize the LCD.  RS, EN, and D4...D7 parameters should be the pins
        connected to the LCD RS, clock enable, and data line 4 through 7 connections.
        The LCD will be used in its 4-bit mode so these 6 lines are the only ones
        required to use the LCD.  You must also pass in the number of columns and
        lines on the LCD.  

        If you would like to control the backlight, pass in the pin connected to
        the backlight with the backlight parameter.  The invert_polarity boolean
        controls if the backlight is one with a LOW signal or HIGH signal.  The 
        default invert_polarity value is True, i.e. the backlight is on with a
        LOW signal.  

        You can enable PWM of the backlight pin to have finer control on the 
        brightness.  To enable PWM make sure your hardware supports PWM on the 
        provided backlight pin and set enable_pwm to True (the default is False).
        The appropriate PWM library will be used depending on the platform, but
        you can provide an explicit one with the pwm parameter.

        The initial state of the backlight is ON, but you can set it to an 
        explicit initial state with the initial_backlight parameter (0 is off,
        1 is on/full bright).

        You can optionally pass in an explicit GPIO class,
        for example if you want to use an MCP230xx GPIO extender.  If you don't
        pass in an GPIO instance, the default GPIO for the running platform will
        be used.
        """
        # Save column and line state.
        self._cols = cols
        self._lines = lines
        # Save GPIO state and pin numbers.
        self._gpio = gpio
        self._rs = rs
        self._en = en
        self._d4 = d4
        self._d5 = d5
        self._d6 = d6
        self._d7 = d7
        # Save backlight state.
        self._backlight = backlight
        self._pwm_enabled = enable_pwm
        self._pwm = pwm
        self._blpol = not invert_polarity
        # Setup all pins as outputs.
        for pin in (rs, en, d4, d5, d6, d7):
            gpio.setup(pin, GPIO.OUT)
        # Setup backlight.
        if backlight is not None:
            if enable_pwm:
                pwm.start(backlight, self._pwm_duty_cycle(initial_backlight))
            else:
                gpio.setup(backlight, GPIO.OUT)
                gpio.output(backlight, self._blpol if initial_backlight else not self._blpol)
        # Initialize the display.
        self.write8(0x33)
        self.write8(0x32)
        # Initialize display control, function, and mode registers.
        self.displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF
        self.displayfunction = LCD_4BITMODE | LCD_1LINE | LCD_2LINE | LCD_5x8DOTS
        self.displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT
        # Write registers.
        self.write8(LCD_DISPLAYCONTROL | self.displaycontrol)
        self.write8(LCD_FUNCTIONSET | self.displayfunction)
        self.write8(LCD_ENTRYMODESET | self.displaymode)  # set the entry mode
        self.clear()