Initial commit.
This commit is contained in:
parent
1651f9eb75
commit
2c58f1935b
10 changed files with 968 additions and 0 deletions
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
build
|
||||
*.egg-info
|
||||
*.pyc
|
||||
setuptools-*
|
||||
307
Adafruit_SSD1306/SSD1306.py
Normal file
307
Adafruit_SSD1306/SSD1306.py
Normal file
|
|
@ -0,0 +1,307 @@
|
|||
# Copyright (c) 2014 Adafruit Industries
|
||||
# Author: Tony DiCola
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
# THE SOFTWARE.
|
||||
import logging
|
||||
import time
|
||||
|
||||
import Adafruit_GPIO as GPIO
|
||||
import Adafruit_GPIO.SPI as SPI
|
||||
import Adafruit_GPIO.I2C as I2C
|
||||
|
||||
|
||||
# Constants
|
||||
SSD1306_I2C_ADDRESS = 0x3C # 011110+SA0+RW - 0x3C or 0x3D
|
||||
SSD1306_SETCONTRAST = 0x81
|
||||
SSD1306_DISPLAYALLON_RESUME = 0xA4
|
||||
SSD1306_DISPLAYALLON = 0xA5
|
||||
SSD1306_NORMALDISPLAY = 0xA6
|
||||
SSD1306_INVERTDISPLAY = 0xA7
|
||||
SSD1306_DISPLAYOFF = 0xAE
|
||||
SSD1306_DISPLAYON = 0xAF
|
||||
SSD1306_SETDISPLAYOFFSET = 0xD3
|
||||
SSD1306_SETCOMPINS = 0xDA
|
||||
SSD1306_SETVCOMDETECT = 0xDB
|
||||
SSD1306_SETDISPLAYCLOCKDIV = 0xD5
|
||||
SSD1306_SETPRECHARGE = 0xD9
|
||||
SSD1306_SETMULTIPLEX = 0xA8
|
||||
SSD1306_SETLOWCOLUMN = 0x00
|
||||
SSD1306_SETHIGHCOLUMN = 0x10
|
||||
SSD1306_SETSTARTLINE = 0x40
|
||||
SSD1306_MEMORYMODE = 0x20
|
||||
SSD1306_COLUMNADDR = 0x21
|
||||
SSD1306_PAGEADDR = 0x22
|
||||
SSD1306_COMSCANINC = 0xC0
|
||||
SSD1306_COMSCANDEC = 0xC8
|
||||
SSD1306_SEGREMAP = 0xA0
|
||||
SSD1306_CHARGEPUMP = 0x8D
|
||||
SSD1306_EXTERNALVCC = 0x1
|
||||
SSD1306_SWITCHCAPVCC = 0x2
|
||||
|
||||
# Scrolling constants
|
||||
SSD1306_ACTIVATE_SCROLL = 0x2F
|
||||
SSD1306_DEACTIVATE_SCROLL = 0x2E
|
||||
SSD1306_SET_VERTICAL_SCROLL_AREA = 0xA3
|
||||
SSD1306_RIGHT_HORIZONTAL_SCROLL = 0x26
|
||||
SSD1306_LEFT_HORIZONTAL_SCROLL = 0x27
|
||||
SSD1306_VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL = 0x29
|
||||
SSD1306_VERTICAL_AND_LEFT_HORIZONTAL_SCROLL = 0x2A
|
||||
|
||||
|
||||
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=I2C.get_default_bus()):
|
||||
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(SSD1306_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 _initialize(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def command(self, c):
|
||||
"""Send command byte to display."""
|
||||
if self._spi is not None:
|
||||
# SPI write.
|
||||
self._gpio.set_low(self._dc)
|
||||
self._spi.write([c])
|
||||
else:
|
||||
# I2C write.
|
||||
control = 0x00 # Co = 0, DC = 0
|
||||
self._i2c.write8(control, c)
|
||||
|
||||
def data(self, c):
|
||||
"""Send byte of data to display."""
|
||||
if self._spi is not None:
|
||||
# SPI write.
|
||||
self._gpio.set_high(self._dc)
|
||||
self._spi.write([c])
|
||||
else:
|
||||
# I2C write.
|
||||
control = 0x40 # Co = 0, DC = 0
|
||||
self._i2c.write8(control, c)
|
||||
|
||||
def begin(self, vccstate=SSD1306_SWITCHCAPVCC):
|
||||
"""Initialize display."""
|
||||
# Save vcc state.
|
||||
self._vccstate = vccstate
|
||||
# Reset and initialize display.
|
||||
self.reset()
|
||||
self._initialize()
|
||||
# Turn on the display.
|
||||
self.command(SSD1306_DISPLAYON)
|
||||
|
||||
def reset(self):
|
||||
"""Reset the display."""
|
||||
# Set reset high for a millisecond.
|
||||
self._gpio.set_high(self._rst)
|
||||
time.sleep(0.001)
|
||||
# Set reset low for 10 milliseconds.
|
||||
self._gpio.set_low(self._rst)
|
||||
time.sleep(0.010)
|
||||
# Set reset high again.
|
||||
self._gpio.set_high(self._rst)
|
||||
|
||||
def display(self):
|
||||
"""Write display buffer to physical display."""
|
||||
self.command(SSD1306_COLUMNADDR)
|
||||
self.command(0) # Column start address. (0 = reset)
|
||||
self.command(self.width-1) # Column end address.
|
||||
self.command(SSD1306_PAGEADDR)
|
||||
self.command(0) # Page start address. (0 = reset)
|
||||
self.command(self._pages-1) # Page end address.
|
||||
# Write buffer data.
|
||||
if self._spi is not None:
|
||||
# Set DC high for data.
|
||||
self._gpio.set_high(self._dc)
|
||||
# Write buffer.
|
||||
self._spi.write(self._buffer)
|
||||
else:
|
||||
for i in range(0, len(self._buffer), 16):
|
||||
control = 0x40 # Co = 0, DC = 0
|
||||
self._i2c.writeList(control, self._buffer[i:i+16])
|
||||
|
||||
def image(self, image):
|
||||
"""Set buffer to value of Python Imaging Library image. The image should
|
||||
be in 1 bit mode and a size equal to the display size.
|
||||
"""
|
||||
if image.mode != '1':
|
||||
raise ValueError('Image must be in mode 1.')
|
||||
imwidth, imheight = image.size
|
||||
if imwidth != self.width or imheight != self.height:
|
||||
raise ValueError('Image must be same dimensions as display ({0}x{1}).' \
|
||||
.format(self.width, self.height))
|
||||
# Grab all the pixels from the image, faster than getpixel.
|
||||
pix = image.load()
|
||||
# Iterate through the memory pages
|
||||
index = 0
|
||||
for page in range(self._pages):
|
||||
# Iterate through all x axis columns.
|
||||
for x in range(self.width):
|
||||
# Set the bits for the column of pixels at the current position.
|
||||
bits = 0
|
||||
# Don't use range here as it's a bit slow
|
||||
for bit in [0, 1, 2, 3, 4, 5, 6, 7]:
|
||||
bits = bits << 1
|
||||
bits |= 0 if pix[(x, page*8+7-bit)] == 0 else 1
|
||||
# Update buffer byte and increment to next byte.
|
||||
self._buffer[index] = bits
|
||||
index += 1
|
||||
|
||||
def clear(self):
|
||||
"""Clear contents of image buffer."""
|
||||
self._buffer = [0]*(self.width*self._pages)
|
||||
|
||||
def set_contrast(self, contrast):
|
||||
"""Sets the contrast of the display. Contrast should be a value between
|
||||
0 and 255."""
|
||||
if contrast < 0 or contrast > 255:
|
||||
raise ValueError('Contrast must be a value from 0 to 255 (inclusive).')
|
||||
self.command(SSD1306_SETCONTRAST)
|
||||
self.command(contrast)
|
||||
|
||||
def dim(self, dim):
|
||||
"""Adjusts contrast to dim the display if dim is True, otherwise sets the
|
||||
contrast to normal brightness if dim is False.
|
||||
"""
|
||||
# Assume dim display.
|
||||
contrast = 0
|
||||
# Adjust contrast based on VCC if not dimming.
|
||||
if not dim:
|
||||
if self._vccstate == SSD1306_EXTERNALVCC:
|
||||
contrast = 0x9F
|
||||
else:
|
||||
contrast = 0xCF
|
||||
|
||||
|
||||
class SSD1306_128_64(SSD1306Base):
|
||||
def __init__(self, rst, dc=None, sclk=None, din=None, cs=None, gpio=None,
|
||||
spi=None, i2c_bus=I2C.get_default_bus()):
|
||||
# Call base class constructor.
|
||||
super(SSD1306_128_64, self).__init__(128, 64, rst, dc, sclk, din, cs,
|
||||
gpio, spi, i2c_bus)
|
||||
|
||||
def _initialize(self):
|
||||
# 128x64 pixel specific initialization.
|
||||
self.command(SSD1306_DISPLAYOFF) # 0xAE
|
||||
self.command(SSD1306_SETDISPLAYCLOCKDIV) # 0xD5
|
||||
self.command(0x80) # the suggested ratio 0x80
|
||||
self.command(SSD1306_SETMULTIPLEX) # 0xA8
|
||||
self.command(0x3F)
|
||||
self.command(SSD1306_SETDISPLAYOFFSET) # 0xD3
|
||||
self.command(0x0) # no offset
|
||||
self.command(SSD1306_SETSTARTLINE | 0x0) # line #0
|
||||
self.command(SSD1306_CHARGEPUMP) # 0x8D
|
||||
if self._vccstate == SSD1306_EXTERNALVCC:
|
||||
self.command(0x10)
|
||||
else:
|
||||
self.command(0x14)
|
||||
self.command(SSD1306_MEMORYMODE) # 0x20
|
||||
self.command(0x00) # 0x0 act like ks0108
|
||||
self.command(SSD1306_SEGREMAP | 0x1)
|
||||
self.command(SSD1306_COMSCANDEC)
|
||||
self.command(SSD1306_SETCOMPINS) # 0xDA
|
||||
self.command(0x12)
|
||||
self.command(SSD1306_SETCONTRAST) # 0x81
|
||||
if self._vccstate == SSD1306_EXTERNALVCC:
|
||||
self.command(0x9F)
|
||||
else:
|
||||
self.command(0xCF)
|
||||
self.command(SSD1306_SETPRECHARGE) # 0xd9
|
||||
if self._vccstate == SSD1306_EXTERNALVCC:
|
||||
self.command(0x22)
|
||||
else:
|
||||
self.command(0xF1)
|
||||
self.command(SSD1306_SETVCOMDETECT) # 0xDB
|
||||
self.command(0x40)
|
||||
self.command(SSD1306_DISPLAYALLON_RESUME) # 0xA4
|
||||
self.command(SSD1306_NORMALDISPLAY) # 0xA6
|
||||
|
||||
|
||||
class SSD1306_128_32(SSD1306Base):
|
||||
def __init__(self, rst, dc=None, sclk=None, din=None, cs=None, gpio=None,
|
||||
spi=None, i2c_bus=I2C.get_default_bus()):
|
||||
# Call base class constructor.
|
||||
super(SSD1306_128_32, self).__init__(128, 32, rst, dc, sclk, din, cs,
|
||||
gpio, spi, i2c_bus)
|
||||
|
||||
def _initialize(self):
|
||||
# 128x32 pixel specific initialization.
|
||||
self.command(SSD1306_DISPLAYOFF) # 0xAE
|
||||
self.command(SSD1306_SETDISPLAYCLOCKDIV) # 0xD5
|
||||
self.command(0x80) # the suggested ratio 0x80
|
||||
self.command(SSD1306_SETMULTIPLEX) # 0xA8
|
||||
self.command(0x1F)
|
||||
self.command(SSD1306_SETDISPLAYOFFSET) # 0xD3
|
||||
self.command(0x0) # no offset
|
||||
self.command(SSD1306_SETSTARTLINE | 0x0) # line #0
|
||||
self.command(SSD1306_CHARGEPUMP) # 0x8D
|
||||
if self._vccstate == SSD1306_EXTERNALVCC:
|
||||
self.command(0x10)
|
||||
else:
|
||||
self.command(0x14)
|
||||
self.command(SSD1306_MEMORYMODE) # 0x20
|
||||
self.command(0x00) # 0x0 act like ks0108
|
||||
self.command(SSD1306_SEGREMAP | 0x1)
|
||||
self.command(SSD1306_COMSCANDEC)
|
||||
self.command(SSD1306_SETCOMPINS) # 0xDA
|
||||
self.command(0x02)
|
||||
self.command(SSD1306_SETCONTRAST) # 0x81
|
||||
self.command(0x8F)
|
||||
self.command(SSD1306_SETPRECHARGE) # 0xd9
|
||||
if self._vccstate == SSD1306_EXTERNALVCC:
|
||||
self.command(0x22)
|
||||
else:
|
||||
self.command(0xF1)
|
||||
self.command(SSD1306_SETVCOMDETECT) # 0xDB
|
||||
self.command(0x40)
|
||||
self.command(SSD1306_DISPLAYALLON_RESUME) # 0xA4
|
||||
self.command(SSD1306_NORMALDISPLAY) # 0xA6
|
||||
1
Adafruit_SSD1306/__init__.py
Normal file
1
Adafruit_SSD1306/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
|||
from SSD1306 import *
|
||||
126
examples/animate.py
Normal file
126
examples/animate.py
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
# Copyright (c) 2014 Adafruit Industries
|
||||
# Author: Tony DiCola
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
# THE SOFTWARE.
|
||||
import math
|
||||
import time
|
||||
|
||||
import Adafruit_GPIO.SPI as SPI
|
||||
import Adafruit_SSD1306
|
||||
|
||||
import Image
|
||||
import ImageFont
|
||||
import ImageDraw
|
||||
|
||||
|
||||
# Raspberry Pi pin configuration:
|
||||
RST = 24
|
||||
# Note the following are only used with SPI:
|
||||
DC = 23
|
||||
SPI_PORT = 0
|
||||
SPI_DEVICE = 0
|
||||
|
||||
# Beaglebone Black pin configuration:
|
||||
# RST = 'P9_12'
|
||||
# Note the following are only used with SPI:
|
||||
# DC = 'P9_15'
|
||||
# SPI_PORT = 1
|
||||
# SPI_DEVICE = 0
|
||||
|
||||
# 128x32 display with hardware I2C:
|
||||
disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)
|
||||
|
||||
# 128x64 display with hardware I2C:
|
||||
# disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
|
||||
|
||||
# 128x32 display with hardware SPI:
|
||||
# disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000))
|
||||
|
||||
# 128x64 display with hardware SPI:
|
||||
# disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000))
|
||||
|
||||
# Initialize library.
|
||||
disp.begin()
|
||||
|
||||
# Get display width and height.
|
||||
width = disp.width
|
||||
height = disp.height
|
||||
|
||||
# Clear display.
|
||||
disp.clear()
|
||||
disp.display()
|
||||
|
||||
# Create image buffer.
|
||||
# Make sure to create image with mode '1' for 1-bit color.
|
||||
image = Image.new('1', (width, height))
|
||||
|
||||
# Load default font.
|
||||
font = ImageFont.load_default()
|
||||
|
||||
# Alternatively load a TTF font.
|
||||
# Some nice fonts to try: http://www.dafont.com/bitmap.php
|
||||
# font = ImageFont.truetype('Minecraftia.ttf', 8)
|
||||
|
||||
# Create drawing object.
|
||||
draw = ImageDraw.Draw(image)
|
||||
|
||||
# Define text and get total width.
|
||||
text = 'SSD1306 ORGANIC LED DISPLAY. THIS IS AN OLD SCHOOL DEMO SCROLLER!! GREETZ TO: LADYADA & THE ADAFRUIT CREW, TRIXTER, FUTURE CREW, AND FARBRAUSCH'
|
||||
maxwidth, unused = draw.textsize(text, font=font)
|
||||
|
||||
# Set animation and sine wave parameters.
|
||||
amplitude = height/4
|
||||
offset = height/2 - 4
|
||||
velocity = -2
|
||||
startpos = width
|
||||
|
||||
# Animate text moving in sine wave.
|
||||
print 'Press Ctrl-C to quit.'
|
||||
pos = startpos
|
||||
while True:
|
||||
# Clear image buffer by drawing a black filled box.
|
||||
draw.rectangle((0,0,width,height), outline=0, fill=0)
|
||||
# Enumerate characters and draw them offset vertically based on a sine wave.
|
||||
x = pos
|
||||
for i, c in enumerate(text):
|
||||
# Stop drawing if off the right side of screen.
|
||||
if x > width:
|
||||
break
|
||||
# Calculate width but skip drawing if off the left side of screen.
|
||||
if x < -10:
|
||||
char_width, char_height = draw.textsize(c, font=font)
|
||||
x += char_width
|
||||
continue
|
||||
# Calculate offset from sine wave.
|
||||
y = offset+math.floor(amplitude*math.sin(x/float(width)*2.0*math.pi))
|
||||
# Draw text.
|
||||
draw.text((x, y), c, font=font, fill=255)
|
||||
# Increment x position based on chacacter width.
|
||||
char_width, char_height = draw.textsize(c, font=font)
|
||||
x += char_width
|
||||
# Draw the image buffer.
|
||||
disp.image(image)
|
||||
disp.display()
|
||||
# Move position for next frame.
|
||||
pos += velocity
|
||||
# Start over if text has scrolled completely off left side of screen.
|
||||
if pos < -maxwidth:
|
||||
pos = startpos
|
||||
# Pause briefly before drawing next frame.
|
||||
time.sleep(0.1)
|
||||
BIN
examples/happycat_oled_32.ppm
Normal file
BIN
examples/happycat_oled_32.ppm
Normal file
Binary file not shown.
BIN
examples/happycat_oled_64.ppm
Normal file
BIN
examples/happycat_oled_64.ppm
Normal file
Binary file not shown.
73
examples/image.py
Normal file
73
examples/image.py
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
# Copyright (c) 2014 Adafruit Industries
|
||||
# Author: Tony DiCola
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
# THE SOFTWARE.
|
||||
import time
|
||||
|
||||
import Adafruit_GPIO.SPI as SPI
|
||||
import Adafruit_SSD1306
|
||||
|
||||
import Image
|
||||
|
||||
|
||||
# Raspberry Pi pin configuration:
|
||||
RST = 24
|
||||
# Note the following are only used with SPI:
|
||||
DC = 23
|
||||
SPI_PORT = 0
|
||||
SPI_DEVICE = 0
|
||||
|
||||
# Beaglebone Black pin configuration:
|
||||
# RST = 'P9_12'
|
||||
# Note the following are only used with SPI:
|
||||
# DC = 'P9_15'
|
||||
# SPI_PORT = 1
|
||||
# SPI_DEVICE = 0
|
||||
|
||||
# 128x32 display with hardware I2C:
|
||||
disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)
|
||||
|
||||
# 128x64 display with hardware I2C:
|
||||
# disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
|
||||
|
||||
# 128x32 display with hardware SPI:
|
||||
# disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000))
|
||||
|
||||
# 128x64 display with hardware SPI:
|
||||
# disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000))
|
||||
|
||||
# Initialize library.
|
||||
disp.begin()
|
||||
|
||||
# Clear display.
|
||||
disp.clear()
|
||||
disp.display()
|
||||
|
||||
# Load image based on OLED display height. Note that image is converted to 1 bit color.
|
||||
if disp.height == 64:
|
||||
image = Image.open('happycat_oled_64.ppm').convert('1')
|
||||
else:
|
||||
image = Image.open('happycat_oled_32.ppm').convert('1')
|
||||
|
||||
# Alternatively load a different format image, resize it, and convert to 1 bit color.
|
||||
#image = Image.open('happycat.png').resize((disp.width, disp.height), Image.ANTIALIAS).convert('1')
|
||||
|
||||
# Display image.
|
||||
disp.image(image)
|
||||
disp.display()
|
||||
111
examples/shapes.py
Normal file
111
examples/shapes.py
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
# Copyright (c) 2014 Adafruit Industries
|
||||
# Author: Tony DiCola
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
# THE SOFTWARE.
|
||||
import time
|
||||
|
||||
import Adafruit_GPIO.SPI as SPI
|
||||
import Adafruit_SSD1306
|
||||
|
||||
import Image
|
||||
import ImageDraw
|
||||
import ImageFont
|
||||
|
||||
|
||||
# Raspberry Pi pin configuration:
|
||||
RST = 24
|
||||
# Note the following are only used with SPI:
|
||||
DC = 23
|
||||
SPI_PORT = 0
|
||||
SPI_DEVICE = 0
|
||||
|
||||
# Beaglebone Black pin configuration:
|
||||
# RST = 'P9_12'
|
||||
# Note the following are only used with SPI:
|
||||
# DC = 'P9_15'
|
||||
# SPI_PORT = 1
|
||||
# SPI_DEVICE = 0
|
||||
|
||||
# 128x32 display with hardware I2C:
|
||||
disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)
|
||||
|
||||
# 128x64 display with hardware I2C:
|
||||
# disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
|
||||
|
||||
# 128x32 display with hardware SPI:
|
||||
# disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000))
|
||||
|
||||
# 128x64 display with hardware SPI:
|
||||
# disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000))
|
||||
|
||||
# Initialize library.
|
||||
disp.begin()
|
||||
|
||||
# Clear display.
|
||||
disp.clear()
|
||||
disp.display()
|
||||
|
||||
# Create blank image for drawing.
|
||||
# Make sure to create image with mode '1' for 1-bit color.
|
||||
width = disp.width
|
||||
height = disp.height
|
||||
image = Image.new('1', (width, height))
|
||||
|
||||
# Get drawing object to draw on image.
|
||||
draw = ImageDraw.Draw(image)
|
||||
|
||||
# Draw a black filled box to clear the image.
|
||||
draw.rectangle((0,0,width,height), outline=0, fill=0)
|
||||
|
||||
# Draw some shapes.
|
||||
# First define some constants to allow easy resizing of shapes.
|
||||
padding = 2
|
||||
shape_width = 20
|
||||
top = padding
|
||||
bottom = height-padding
|
||||
# Move left to right keeping track of the current x position for drawing shapes.
|
||||
x = padding
|
||||
# Draw an ellipse.
|
||||
draw.ellipse((x, top , x+shape_width, bottom), outline=255, fill=0)
|
||||
x += shape_width+padding
|
||||
# Draw a rectangle.
|
||||
draw.rectangle((x, top, x+shape_width, bottom), outline=255, fill=0)
|
||||
x += shape_width+padding
|
||||
# Draw a triangle.
|
||||
draw.polygon([(x, bottom), (x+shape_width/2, top), (x+shape_width, bottom)], outline=255, fill=0)
|
||||
x += shape_width+padding
|
||||
# Draw an X.
|
||||
draw.line((x, bottom, x+shape_width, top), fill=255)
|
||||
draw.line((x, top, x+shape_width, bottom), fill=255)
|
||||
x += shape_width+padding
|
||||
|
||||
# Load default font.
|
||||
font = ImageFont.load_default()
|
||||
|
||||
# Alternatively load a TTF font.
|
||||
# Some other nice fonts to try: http://www.dafont.com/bitmap.php
|
||||
#font = ImageFont.truetype('Minecraftia.ttf', 8)
|
||||
|
||||
# Write two lines of text.
|
||||
draw.text((x, top), 'Hello', font=font, fill=255)
|
||||
draw.text((x, top+20), 'World!', font=font, fill=255)
|
||||
|
||||
# Display image.
|
||||
disp.image(image)
|
||||
disp.display()
|
||||
332
ez_setup.py
Normal file
332
ez_setup.py
Normal file
|
|
@ -0,0 +1,332 @@
|
|||
#!/usr/bin/env python
|
||||
"""Bootstrap setuptools installation
|
||||
|
||||
To use setuptools in your package's setup.py, include this
|
||||
file in the same directory and add this to the top of your setup.py::
|
||||
|
||||
from ez_setup import use_setuptools
|
||||
use_setuptools()
|
||||
|
||||
To require a specific version of setuptools, set a download
|
||||
mirror, or use an alternate download directory, simply supply
|
||||
the appropriate options to ``use_setuptools()``.
|
||||
|
||||
This file can also be run as a script to install or upgrade setuptools.
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
import optparse
|
||||
import subprocess
|
||||
import platform
|
||||
import textwrap
|
||||
import contextlib
|
||||
|
||||
from distutils import log
|
||||
|
||||
try:
|
||||
from site import USER_SITE
|
||||
except ImportError:
|
||||
USER_SITE = None
|
||||
|
||||
DEFAULT_VERSION = "3.5.1"
|
||||
DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/"
|
||||
|
||||
def _python_cmd(*args):
|
||||
"""
|
||||
Return True if the command succeeded.
|
||||
"""
|
||||
args = (sys.executable,) + args
|
||||
return subprocess.call(args) == 0
|
||||
|
||||
|
||||
def _install(archive_filename, install_args=()):
|
||||
with archive_context(archive_filename):
|
||||
# installing
|
||||
log.warn('Installing Setuptools')
|
||||
if not _python_cmd('setup.py', 'install', *install_args):
|
||||
log.warn('Something went wrong during the installation.')
|
||||
log.warn('See the error message above.')
|
||||
# exitcode will be 2
|
||||
return 2
|
||||
|
||||
|
||||
def _build_egg(egg, archive_filename, to_dir):
|
||||
with archive_context(archive_filename):
|
||||
# building an egg
|
||||
log.warn('Building a Setuptools egg in %s', to_dir)
|
||||
_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
|
||||
# returning the result
|
||||
log.warn(egg)
|
||||
if not os.path.exists(egg):
|
||||
raise IOError('Could not build the egg.')
|
||||
|
||||
|
||||
def get_zip_class():
|
||||
"""
|
||||
Supplement ZipFile class to support context manager for Python 2.6
|
||||
"""
|
||||
class ContextualZipFile(zipfile.ZipFile):
|
||||
def __enter__(self):
|
||||
return self
|
||||
def __exit__(self, type, value, traceback):
|
||||
self.close
|
||||
return zipfile.ZipFile if hasattr(zipfile.ZipFile, '__exit__') else \
|
||||
ContextualZipFile
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def archive_context(filename):
|
||||
# extracting the archive
|
||||
tmpdir = tempfile.mkdtemp()
|
||||
log.warn('Extracting in %s', tmpdir)
|
||||
old_wd = os.getcwd()
|
||||
try:
|
||||
os.chdir(tmpdir)
|
||||
with get_zip_class()(filename) as archive:
|
||||
archive.extractall()
|
||||
|
||||
# going in the directory
|
||||
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
|
||||
os.chdir(subdir)
|
||||
log.warn('Now working in %s', subdir)
|
||||
yield
|
||||
|
||||
finally:
|
||||
os.chdir(old_wd)
|
||||
shutil.rmtree(tmpdir)
|
||||
|
||||
|
||||
def _do_download(version, download_base, to_dir, download_delay):
|
||||
egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg'
|
||||
% (version, sys.version_info[0], sys.version_info[1]))
|
||||
if not os.path.exists(egg):
|
||||
archive = download_setuptools(version, download_base,
|
||||
to_dir, download_delay)
|
||||
_build_egg(egg, archive, to_dir)
|
||||
sys.path.insert(0, egg)
|
||||
|
||||
# Remove previously-imported pkg_resources if present (see
|
||||
# https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
|
||||
if 'pkg_resources' in sys.modules:
|
||||
del sys.modules['pkg_resources']
|
||||
|
||||
import setuptools
|
||||
setuptools.bootstrap_install_from = egg
|
||||
|
||||
|
||||
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
|
||||
to_dir=os.curdir, download_delay=15):
|
||||
to_dir = os.path.abspath(to_dir)
|
||||
rep_modules = 'pkg_resources', 'setuptools'
|
||||
imported = set(sys.modules).intersection(rep_modules)
|
||||
try:
|
||||
import pkg_resources
|
||||
except ImportError:
|
||||
return _do_download(version, download_base, to_dir, download_delay)
|
||||
try:
|
||||
pkg_resources.require("setuptools>=" + version)
|
||||
return
|
||||
except pkg_resources.DistributionNotFound:
|
||||
return _do_download(version, download_base, to_dir, download_delay)
|
||||
except pkg_resources.VersionConflict as VC_err:
|
||||
if imported:
|
||||
msg = textwrap.dedent("""
|
||||
The required version of setuptools (>={version}) is not available,
|
||||
and can't be installed while this script is running. Please
|
||||
install a more recent version first, using
|
||||
'easy_install -U setuptools'.
|
||||
|
||||
(Currently using {VC_err.args[0]!r})
|
||||
""").format(VC_err=VC_err, version=version)
|
||||
sys.stderr.write(msg)
|
||||
sys.exit(2)
|
||||
|
||||
# otherwise, reload ok
|
||||
del pkg_resources, sys.modules['pkg_resources']
|
||||
return _do_download(version, download_base, to_dir, download_delay)
|
||||
|
||||
def _clean_check(cmd, target):
|
||||
"""
|
||||
Run the command to download target. If the command fails, clean up before
|
||||
re-raising the error.
|
||||
"""
|
||||
try:
|
||||
subprocess.check_call(cmd)
|
||||
except subprocess.CalledProcessError:
|
||||
if os.access(target, os.F_OK):
|
||||
os.unlink(target)
|
||||
raise
|
||||
|
||||
def download_file_powershell(url, target):
|
||||
"""
|
||||
Download the file at url to target using Powershell (which will validate
|
||||
trust). Raise an exception if the command cannot complete.
|
||||
"""
|
||||
target = os.path.abspath(target)
|
||||
cmd = [
|
||||
'powershell',
|
||||
'-Command',
|
||||
"(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)" % vars(),
|
||||
]
|
||||
_clean_check(cmd, target)
|
||||
|
||||
def has_powershell():
|
||||
if platform.system() != 'Windows':
|
||||
return False
|
||||
cmd = ['powershell', '-Command', 'echo test']
|
||||
devnull = open(os.path.devnull, 'wb')
|
||||
try:
|
||||
try:
|
||||
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
|
||||
except Exception:
|
||||
return False
|
||||
finally:
|
||||
devnull.close()
|
||||
return True
|
||||
|
||||
download_file_powershell.viable = has_powershell
|
||||
|
||||
def download_file_curl(url, target):
|
||||
cmd = ['curl', url, '--silent', '--output', target]
|
||||
_clean_check(cmd, target)
|
||||
|
||||
def has_curl():
|
||||
cmd = ['curl', '--version']
|
||||
devnull = open(os.path.devnull, 'wb')
|
||||
try:
|
||||
try:
|
||||
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
|
||||
except Exception:
|
||||
return False
|
||||
finally:
|
||||
devnull.close()
|
||||
return True
|
||||
|
||||
download_file_curl.viable = has_curl
|
||||
|
||||
def download_file_wget(url, target):
|
||||
cmd = ['wget', url, '--quiet', '--output-document', target]
|
||||
_clean_check(cmd, target)
|
||||
|
||||
def has_wget():
|
||||
cmd = ['wget', '--version']
|
||||
devnull = open(os.path.devnull, 'wb')
|
||||
try:
|
||||
try:
|
||||
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
|
||||
except Exception:
|
||||
return False
|
||||
finally:
|
||||
devnull.close()
|
||||
return True
|
||||
|
||||
download_file_wget.viable = has_wget
|
||||
|
||||
def download_file_insecure(url, target):
|
||||
"""
|
||||
Use Python to download the file, even though it cannot authenticate the
|
||||
connection.
|
||||
"""
|
||||
try:
|
||||
from urllib.request import urlopen
|
||||
except ImportError:
|
||||
from urllib2 import urlopen
|
||||
src = dst = None
|
||||
try:
|
||||
src = urlopen(url)
|
||||
# Read/write all in one block, so we don't create a corrupt file
|
||||
# if the download is interrupted.
|
||||
data = src.read()
|
||||
dst = open(target, "wb")
|
||||
dst.write(data)
|
||||
finally:
|
||||
if src:
|
||||
src.close()
|
||||
if dst:
|
||||
dst.close()
|
||||
|
||||
download_file_insecure.viable = lambda: True
|
||||
|
||||
def get_best_downloader():
|
||||
downloaders = [
|
||||
download_file_powershell,
|
||||
download_file_curl,
|
||||
download_file_wget,
|
||||
download_file_insecure,
|
||||
]
|
||||
|
||||
for dl in downloaders:
|
||||
if dl.viable():
|
||||
return dl
|
||||
|
||||
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
|
||||
to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader):
|
||||
"""
|
||||
Download setuptools from a specified location and return its filename
|
||||
|
||||
`version` should be a valid setuptools version number that is available
|
||||
as an egg for download under the `download_base` URL (which should end
|
||||
with a '/'). `to_dir` is the directory where the egg will be downloaded.
|
||||
`delay` is the number of seconds to pause before an actual download
|
||||
attempt.
|
||||
|
||||
``downloader_factory`` should be a function taking no arguments and
|
||||
returning a function for downloading a URL to a target.
|
||||
"""
|
||||
# making sure we use the absolute path
|
||||
to_dir = os.path.abspath(to_dir)
|
||||
zip_name = "setuptools-%s.zip" % version
|
||||
url = download_base + zip_name
|
||||
saveto = os.path.join(to_dir, zip_name)
|
||||
if not os.path.exists(saveto): # Avoid repeated downloads
|
||||
log.warn("Downloading %s", url)
|
||||
downloader = downloader_factory()
|
||||
downloader(url, saveto)
|
||||
return os.path.realpath(saveto)
|
||||
|
||||
def _build_install_args(options):
|
||||
"""
|
||||
Build the arguments to 'python setup.py install' on the setuptools package
|
||||
"""
|
||||
return ['--user'] if options.user_install else []
|
||||
|
||||
def _parse_args():
|
||||
"""
|
||||
Parse the command line for options
|
||||
"""
|
||||
parser = optparse.OptionParser()
|
||||
parser.add_option(
|
||||
'--user', dest='user_install', action='store_true', default=False,
|
||||
help='install in user site package (requires Python 2.6 or later)')
|
||||
parser.add_option(
|
||||
'--download-base', dest='download_base', metavar="URL",
|
||||
default=DEFAULT_URL,
|
||||
help='alternative URL from where to download the setuptools package')
|
||||
parser.add_option(
|
||||
'--insecure', dest='downloader_factory', action='store_const',
|
||||
const=lambda: download_file_insecure, default=get_best_downloader,
|
||||
help='Use internal, non-validating downloader'
|
||||
)
|
||||
parser.add_option(
|
||||
'--version', help="Specify which version to download",
|
||||
default=DEFAULT_VERSION,
|
||||
)
|
||||
options, args = parser.parse_args()
|
||||
# positional arguments are ignored
|
||||
return options
|
||||
|
||||
def main():
|
||||
"""Install or upgrade setuptools and EasyInstall"""
|
||||
options = _parse_args()
|
||||
archive = download_setuptools(
|
||||
version=options.version,
|
||||
download_base=options.download_base,
|
||||
downloader_factory=options.downloader_factory,
|
||||
)
|
||||
return _install(archive, _build_install_args(options))
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
14
setup.py
Normal file
14
setup.py
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
from ez_setup import use_setuptools
|
||||
use_setuptools()
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
setup(name = 'Adafruit_SSD1306',
|
||||
version = '1.0.0',
|
||||
author = 'Tony DiCola',
|
||||
author_email = 'tdicola@adafruit.com',
|
||||
description = 'Python library to use SSD1306-based 128x64 or 128x32 pixel OLED displays with a Raspberry Pi or Beaglebone Black.',
|
||||
license = 'MIT',
|
||||
url = 'https://github.com/adafruit/Adafruit_Python_SSD1306/',
|
||||
dependency_links = ['https://github.com/adafruit/Adafruit_Python_GPIO/tarball/master#egg=Adafruit-GPIO-0.2.0'],
|
||||
install_requires = ['Adafruit-GPIO>=0.2.0'],
|
||||
packages = find_packages())
|
||||
Loading…
Reference in a new issue