Example #1
0

signal.signal(signal.SIGINT, signal_handler)
#################
#  NETWORK SETUP
#################

SERVER = 0
CONNECTION_MADE = 0
ALERT_PRINTED = 0

################
#  OLED DISPLAY
################
time.sleep(1)
disp = Adafruit_SSD1306.SSD1306_128_32(0)
disp.clear()
disp.display()
disp.begin()
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
font = ImageFont.load_default()
resultstring = resultstring + 'Signal Handler Started'


##################
# OFF BUTTON CODE
##################
def shutdown():
    LCD1602.write(0, 0, '                ')
Example #2
0
#!/usr/bin/env python

import datetime
import subprocess
import time

import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

disp = Adafruit_SSD1306.SSD1306_128_64(rst=None)
disp.begin()

cmd = "iwgetid -r"
SSID = subprocess.check_output(cmd, shell=True)
cmd = "hostname -I | cut -d\' \' -f1"
IP = subprocess.check_output(cmd, shell=True)

while 1:
    image = Image.new('1', (disp.width / 3, disp.height / 3))
    draw = ImageDraw.Draw(image)
    font = ImageFont.load_default()

    disp.clear()

    now = datetime.datetime.utcnow()
    doy = (now.date() - datetime.date(now.year, 1, 1)).days + 1
    dec = (now.year % 100, '+' if doy >= 14 * 26 else chr(65 + doy / 14),

def read_temp():
    lines = temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        sleep(0.2)
        lines = temp_raw()
    temp_output = lines[1].find('t=')
    if temp_output != -1:
        temp_string = lines[1].strip()[temp_output + 2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c  #, temp_f


disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
disp.begin()

width = disp.width
height = disp.height

disp.clear()
disp.display()

image = Image.new('1', (width, height))

font1 = ImageFont.truetype('FreeSans.ttf', 16)
font2 = ImageFont.truetype('FreeSans.ttf', 16)
font3 = ImageFont.truetype('FreeSans.ttf', 11)

draw = ImageDraw.Draw(image)
Example #4
0
    def test(self):
        """randomly making points bright in order to test whether the led display can be correctly read or not"""
        test_array = np.array(np.zeros(64 * 128))
        test_array.shape = (64, 128)
        for i in range(0, 64, 2):
            for j in range(0, 128, 2):
                test_array[i][j] = int(np.random.randint(0, 2, size=1))

        RST = 24
        # 128x64 display with hardware I2C:
        disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)

        # 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.
        self.width = disp.width
        self.height = disp.height
        image_1 = Image.new('1', (self.width, self.height))

        # Get drawing object to draw on image.
        draw = ImageDraw.Draw(image_1)

        # Draw a black filled box to clear the image.
        draw.rectangle((0, 0, self.width, self.height), outline=0, fill=0)

        for i in range(0, self.height):
            for j in range(0, self.width):
                if int(test_array[i][j]) == 1:
                    draw.point([(j, i)], fill=255)  # x,y

        disp.image(image_1)
        disp.display()

        # Now get the pixel data

        camera = picamera.PiCamera()
        camera.resolution = (2592, 1944)
        camera.start_preview()
        camera.led = False
        time.sleep(2)
        camera.capture('test.jpg')
        camera.stop_preview()
        image = 'test.jpg'
        self.crop(image, (1020, 620, 1800, 1050), 'test_crop.jpg')
        image = 'test_crop.jpg'
        img = Image.open(image)
        pixels = list(img.getdata())
        pixels2 = []
        for pixel in pixels:
            total = 0
            for x in pixel:
                total += x
            total = int(total / 3)
            pixels2.append((total, total, total))

        filtered_list = self.filter(120, pixels2)
        img = Image.new('RGB', Image.open('test_crop.jpg').size)
        img.putdata(filtered_list)
        img.save('test_filter.jpg')
        img = cv2.imread('test_filter.jpg')

        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        gray = cv2.erode(gray, None, iterations=1)

        result_array = np.array(np.zeros(64 * 128))
        result_array.shape = (64, 128)

        for i in range(64):
            for j in range(128):
                if gray[int(self.all_points_array[i][j][0])][int(
                        self.all_points_array[i][j][1])] == 0:
                    result_array[i][j] = 0
                else:
                    result_array[i][j] = 1

        errors_list = []
        errors = 0
        for i in range(0, 64, 4):
            for j in range(0, 128, 2):
                if (abs(result_array[i][j] - test_array[i][j])) > 0.1:
                    errors += 1
                    errors_list.append((i, j))

        print('errors', errors)
        print(len(errors_list))

        camera.close()
Example #5
0
    def test_1(self, num):
        """ randomly selecting as many pixels as num to brighten up"""
        test_list = []
        for r in range(num):
            test_list.append((int(np.random.randint(0, 64, size=1)),
                              int(np.random.randint(0, 128, size=1))))

        RST = 24
        # 128x64 display with hardware I2C:
        disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)

        # 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.
        self.width = disp.width
        self.height = disp.height
        image_1 = Image.new('1', (self.width, self.height))

        # Get drawing object to draw on image.
        draw = ImageDraw.Draw(image_1)

        # Draw a black filled box to clear the image.
        draw.rectangle((0, 0, self.width, self.height), outline=0, fill=0)

        for point in test_list:
            draw.point([(point[1], point[0])], fill=255)

        disp.image(image_1)
        disp.display()

        # Now get the pixel data

        camera = picamera.PiCamera()
        camera.resolution = (2592, 1944)
        camera.start_preview()
        camera.led = False
        time.sleep(2)
        camera.capture('test.jpg')
        camera.stop_preview()
        image = 'test.jpg'
        self.crop(image, (1020, 620, 1800, 1050), 'test_crop.jpg')
        image = 'test_crop.jpg'
        img = Image.open(image)
        pixels = list(img.getdata())
        pixels2 = []
        for pixel in pixels:
            total = 0
            for x in pixel:
                total += x
            total = int(total / 3)
            pixels2.append((total, total, total))

        filtered_list = self.filter(125, pixels2)
        img = Image.new('RGB', Image.open('test_crop.jpg').size)
        img.putdata(filtered_list)
        img.save('test_filter.jpg')
        img = cv2.imread('test_filter.jpg')

        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        gray = cv2.erode(gray, None, iterations=2)
        result_list = []
        for i in range(64):
            for j in range(128):
                if not (gray[int(self.all_points_array[i][j][0])][int(
                        self.all_points_array[i][j][1])] == 0):
                    result_list.append((i, j))

        print('test_value', test_list, 'result_value', result_list)
        camera.close()
Example #6
0
def setupDisplay(pin):
    return Adafruit_SSD1306.SSD1306_128_64(rst=pin)
Example #7
0
def oled():

    global now_time
    global pa_sw
    global stop_sw
    global cnt_time

    RST = None
    Dc = 23
    SPI_PORT = 0
    SPI_DEVICE = 0

    disp = Adafruit_SSD1306.SSD1306_128_32(rst=None, i2c_address=0x3C)
    disp.begin()
    disp.clear()
    disp.display()
    width = disp.width
    height = disp.height
    image = Image.new('1', (width, height))
    draw = ImageDraw.Draw(image)

    draw.rectangle((0, 0, width, height), outline=0, fill=0)
    padding = -2
    top = padding
    bottom = height - padding

    x = 0
    font = ImageFont.load_default()
    #font2 = ImageFont.truetype('digital-7.mono.ttf', 28)
    dateString = '%A %d %B %Y'

    try:

        while True:
            now_time = time.time()
            cnt_time = now_time - first_time

            m = (cnt_time / 60) / 10
            mm = (cnt_time / 60) % 10
            h = (m / 60) / 10
            hh = (h / 60) % 10

            strDate = datetime.datetime.now().strftime(dateString)

            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), strDate, font=font, fill=255)
            draw.line((0, top + 12, 127, top + 12), fill=100)
            draw.text((x + 20, top + 14),
                      '{0:0.0f}'.format(int(h)),
                      font=font,
                      fill=255)
            draw.text((x + 35, top + 14),
                      '{0:0.0f} '.format(int(hh)),
                      font=font,
                      fill=255)
            draw.text((x + 50, top + 14), ':', font=font, fill=255)
            draw.text((x + 65, top + 14),
                      '{0:0.0f}'.format(int(m)),
                      font=font,
                      fill=255)
            draw.text((x + 80, top + 14),
                      '{0:0.0f}'.format(int(mm)),
                      font=font,
                      fill=255)
            disp.image(image)
            disp.display()
            time.sleep(0.1)
            if stop_sw == 1:
                print("oled  end")
                break
            if pa_sw == 1:
                print("oled pause")
                while True:
                    time.sleep(0.001)
                    if pa_sw == 2:
                        break
    except KeyboardInterrupt:
        print("oled stop")
        GPIO.cleanup()
Example #8
0
    # initialize variables
    is_thinger = True
    is_display = True
    SSD1306_I2C_Address = 0x3C

    # initialize Air sensor
    air_sensor = CCS811(debug=False)
    air_sensor.begin()

    # Initialize Environment sensor
    env_sensor = BME280(debug=True)
    env_sensor.begin()
    env_sensor.readData()

    # Initialize display
    disp = Adafruit_SSD1306.SSD1306_128_64(rst=None,
                                           i2c_address=SSD1306_I2C_Address)
    disp.begin()
    disp.clear()
    disp.display()

    air_sensor.setEnvironmentalData(env_sensor.Temperature,
                                    env_sensor.Humidity)

    image = Image.new('1', (disp.width, disp.height))
    draw = ImageDraw.Draw(image)
    draw.rectangle((0, 0, disp.width, disp.height), outline=0, fill=0)
    font = ImageFont.truetype('./font/KH-Dot-Kodenmachou-16.ttf',
                              16,
                              encoding='unic')

    tick = 1
Example #9
0
import subprocess

# set full puth for incling libs below
full_path = os.path.dirname(os.path.abspath(__file__)) + "/"

# Raspberry Pi pin configuration:
RST = None  # on the PiOLED this pin isnt used
# Note the following are only used with SPI:
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0

# Rev 2 Pi, Pi 2 & Pi 3 uses bus 1
# Rev 1 Pi uses bus 0
# Orange Pi Zero uses bus 0 for pins 1-5 (other pins for bus 1 & 2)
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_bus=bus_number)

# 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.
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont


###########################################Stuff for Display ##################################################

# Raspberry Pi pin configuration:
RST = None     # on the PiOLED this pin isnt used
# Note the following are only used with SPI:
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0

# 128x32 display with hardware I2C:
jukebox_display = Adafruit_SSD1306.SSD1306_128_32(rst=RST)

# Initialize library.
jukebox_display.begin()

# Clear display.
jukebox_display.clear()
jukebox_display.display()

# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
display_width = jukebox_display.width
display_height = jukebox_display.height
image = Image.new('1', (display_width, display_height))

# Get drawing object to draw on image.
Example #11
0
def telemetrySetup():
#telemetry streams
ut = conn.add_stream(getattr, conn.space_center, 'ut')
#orbital parameters
altitude = conn.add_stream(getattr, vessel.flight(), 'mean_altitude')
apoapsis = conn.add_stream(getattr, vessel.orbit, 'apoapsis_altitude')
periapsis = conn.add_stream(getattr, vessel.orbit, 'periapsis_altitude')
#flight parameters
#pressure / atmosphere / radar alt / surface temps?
#liquid fuel / oxidiser / electricity
#air / food / waste 



#init encoder
GPIO.setmode(GPIO.BCM)
left_encoder = RotaryEncoder(22, 23, callback=handle_rotation)
right_encoder = RotaryEncoder(17, 18, callback=handle_rotation)
#init oled
RST = None
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
disp.begin()
clearScreen()
posx = int(2)
font = ImageFont.load_default()
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
draw = ImageDraw.Draw(image)
line_height = 8

#init mcp23017
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_UP)
MCP01 = 0x20
MCP02 = 0x21
global port_capture
port_capture = None
global port_data_1A
global port_data_1B
global port_data_2A
global port_data_2B
bus = smbus.SMBus(1)
bus.write_byte_data(MCP01, 0x00, 0xFF)
bus.write_byte_data(MCP01, 0x01, 0xFF)
bus.write_byte_data(MCP01, 0x0c, 0xFF)
bus.write_byte_data(MCP01, 0x0d, 0xFF)
bus.write_byte_data(MCP01, 0x04, 0xFF)
bus.write_byte_data(MCP01, 0x05, 0xFF)
bus.write_byte_data(MCP01, 0x0a, 0x5)
bus.write_byte_data(MCP01, 0x0b, 0x5)
port_data_1A = bus.read_byte_data(MCP01, 0x12)
port_data_1B = bus.read_byte_data(MCP01, 0x13)
GPIO.add_event_detect(24, GPIO.FALLING, callback=mcpInterrupt)
GPIO.add_event_detect(25, GPIO.FALLING, callback=mcpInterrupt)

#init menu
global cancelFlag, selectFlag, runMode, menuIndex1, menuIndex2, menuBounds1, menuBounds2, instructionQueue, menuList
cancelFlag = 0
selectFlag = 0
menuList = {}
menuIndex1 = 0
menuIndex2 = 0
menuBounds1 = [0,0]
menuBounds2 = [0,0]
instructionQueue = []
EVENT = threading.Event()




try:
    conn = krpc.connect(name='Mission Control', address='192.168.0.5', rpc_port=5000, stream_port=5001)
    vessel = conn.space_center.active_vessel
    mainMenu()


except KeyboardInterrupt: # Ctrl-C to terminate the program
        disp.clear()
        disp.display()
		GPIO.cleanup()
Example #12
0
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

# Pins for the HC-SR04 sensor
iTriggerPin = 21
iEchoPin = 20

# Pins 23 and 24 are connected to the OLED display
disp = Adafruit_SSD1306.SSD1306_128_64(rst=24,
                                       dc=23,
                                       spi=SPI.SpiDev(0,
                                                      0,
                                                      max_speed_hz=8000000))

GPIO.setup(iTriggerPin, GPIO.OUT)
GPIO.setup(iEchoPin, GPIO.IN)

GPIO.output(iTriggerPin, False)
time.sleep(0.5)

disp.begin()
font = ImageFont.truetype('NovaMono.ttf', 26)

while True:
    GPIO.output(iTriggerPin, True)
    time.sleep(0.0001)
Example #13
0
OLED_WIDTH = 128
OLED_HEIGHT = 64

RST = 24
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0

DEFAULT_FONT = '/usr/share/fonts/truetype/fonts-japanese-gothic.ttf'
FONT_SIZE = 14

jpfont = ImageFont.truetype(DEFAULT_FONT, FONT_SIZE, encoding='unic')

spi = SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000)
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, dc=DC, spi=spi)

gyou = ['本日は晴天なり。', '本日は曇天なり。', '本日は雨天なり。', 'ABCABC123']


def draw_gyou():
    global gyou
    global jpfont
    global disp

    image = Image.new("1", (OLED_WIDTH, OLED_HEIGHT), 0)
    draw = ImageDraw.Draw(image)
    for i, j in enumerate(gyou):
        draw.text((0, 16 * i), j, font=jpfont, fill=1)
    disp.image(image)
    disp.display()
Example #14
0
def main():
    print("stats starting:")

    lc = lcm.LCM("udpm://239.255.76.67:7667?ttl=2")
    lc.subscribe(OLED_CHANNEL, oled_message_handler)
    lc.subscribe(EXPLORATION_STATUS_CHANNEL, exploration_status_handler)

    thread.start_new_thread(handle_lcm, (lc, ))

    mod_count = 0
    mod_max = 1

    # 128x32 display with hardware I2C:
    disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)

    def cleanup(*args):
        print("SIGTERM CALLED")

        disp.clear()
        disp.display()
        sys.exit()

    signal.signal(signal.SIGTERM, cleanup)

    # 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
    top = padding
    bottom = height - padding

    # Load default font.
    #font = ImageFont.load_default()

    # Alternatively load a TTF font.  Make sure the .ttf font file is in the same directory as the python script!
    # Some other nice fonts to try: http://www.dafont.com/bitmap.php
    font = ImageFont.truetype('arial.ttf', 10)

    try:
        while True:

            # Draw a black filled box to clear the image.
            draw.rectangle((0, 0, width, height), outline=0, fill=0)

            # Shell scripts for system monitoring from here : https://unix.stackexchange.com/questions/119126/command-to-display-memory-usage-disk-usage-and-cpu-load
            #cmd = "hostname -I | cut -d\' \' -f1"
            cmd = "ifconfig | grep \"inet addr:35.0\" | awk '{ print $2 }' | cut -b 6-"

            try:
                IP = subprocess.check_output(cmd, shell=True)

                if (len(IP) == 0):
                    IP = "initializing..."
                else:
                    IP = IP[0:len(IP) - 1]
            except:
                IP = "initializing..."

#averaged over the past minute
            cmd = "top -bn1 | grep load | awk '{printf \"C: %.2f\", $(NF-2)}'"
            CPU = subprocess.check_output(cmd, shell=True)

            cmd = "free -m | awk 'NR==2{printf \"M: %sMB %.2f%%\", $3,$3*100/$2 }'"
            MemUsage = subprocess.check_output(cmd, shell=True)

            #print(lines)

            # Write two lines of text.
            lines[0] = IP
            lines[1] = CPU + " " + MemUsage

            for n in range(0, 4):

                if disp_max < draw.textsize(lines[n], font=font)[0]:
                    offset_max[n] = disp_max - draw.textsize(
                        lines[n], font=font)[0] - offset_pad
                else:
                    offset_max[n] = 0

                draw.text((x[n], top + 8 * n), lines[n], font=font, fill=255)

                if offset_max[n] < 0:
                    if x[n] < offset_max[n]:
                        x[n] = 0
                    elif mod_count == 1:
                        x[n] -= V

            mod_count += 1
            if mod_count > mod_max:
                mod_count = 0

            # Display image.
            disp.image(image)
            disp.display()
            time.sleep(.1)

    except KeyboardInterrupt:
        print("main exception!")
        disp.clear()
        disp.display()
Example #15
0
def disp_init():
    disp = Adafruit_SSD1306.SSD1306_128_32(rst=None)
    [getattr(disp, x)() for x in ('begin', 'clear', 'display')]
    return disp
Example #16
0
def setup_display(addr):
    disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, i2c_address=addr)
    disp.begin()
    return disp
Example #17
0
 def _init_display():
     display = Adafruit_SSD1306.SSD1306_128_64(rst=24)
     display.begin()
     display.clear()
     display.display()
     return display
Example #18
0
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306  #import oled module

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

import Adafruit_LSM303  #import accelerometer module

lsm303 = Adafruit_LSM303.LSM303()  #create a LSM303 instance (accelerometer)

RST = 24
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0
disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)
disp = Adafruit_SSD1306.SSD1306_128_64(
    rst=RST, i2c_address=0x3d
)  #my i2c address in 0x3d, someone else's might be different
disp.begin()
disp.clear()
disp.display()
width = disp.width  #setting the width of the screen
height = disp.height  #setting the height of the screen
image = Image.new('1', (width, height))

draw = ImageDraw.Draw(image)
draw.rectangle((0, 0, width, height), outline=0, fill=0)

padding = 2  #some variables to help with positioning text on the display
top = padding
Example #19
0
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

import subprocess

RST = 17
DC = 27

SPI_PORT = 0
SPI_DEVICE = 0

# 128x64 display with hardware SPI:
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST,
                                       dc=DC,
                                       spi=SPI.SpiDev(SPI_PORT,
                                                      SPI_DEVICE,
                                                      max_speed_hz=8000000))

# Initialize library.
disp.begin()

# Clear display.
disp.clear()
disp.display()

# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
Example #20
0
# 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))

#128x64 display with hardware SPI:
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, dc=DC, sclk=11, din=10, cs=8)
# 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')
import time
import sys
import os
from datetime import datetime

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

import Adafruit_SSD1306

FONT_SIZE = 13
EMULATE_HX711 = False
referenceUnit = 426.88

disp = Adafruit_SSD1306.SSD1306_128_32(rst=0)

disp.begin()
disp.clear()
disp.display()

width = disp.width
height = disp.height

image = Image.new('1', (width, height))
draw = ImageDraw.Draw(image)

font = ImageFont.truetype("/home/pi/Desktop/fonts/NotoSans-Black.ttf",
                          FONT_SIZE)

if not EMULATE_HX711:
Example #22
0
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

par_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
font_path = par_dir + '/cache/Roboto-Regular.ttf'
data_path = par_dir + '/data/Block'
runFlag_path = par_dir + '/cache/runFlag'

runFlag_file = open(runFlag_path, 'r')
runFlag = int(runFlag_file.read())
if not runFlag:
    sys.exit()

RST = 24
disp = displib.SSD1306_128_64(rst=RST)


def disp_setup():
    disp.begin()
    disp.clear()
    disp.display()


def disp_block():
    width = disp.width
    height = disp.height
    image = Image.new('1', (width, height))

    draw = ImageDraw.Draw(image)
    font_small = ImageFont.truetype(font_path, 15)
Example #23
0
    def start(self):
        """ In order to initialise the self.all_points_array """
        # Raspberry Pi pin configuration:
        RST = 24
        # 128x64 display with hardware I2C:
        disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)

        disp.begin()
        disp.clear()
        disp.display()

        self.width = disp.width
        self.height = disp.height
        image_1 = Image.new('1', (self.width, self.height))

        # Get drawing object to draw on image.
        draw = ImageDraw.Draw(image_1)

        # Draw a black filled box to clear the image.
        draw.rectangle((0, 0, self.width, self.height), outline=0, fill=0)

        for i in range(0, self.height, 4):
            for j in range(0, self.width, 2):
                draw.point([(j, i)], fill=255)  # x,y

        disp.image(image_1)
        disp.display()

        # Now get the pixel data

        camera = picamera.PiCamera()
        camera.resolution = (2592, 1944)
        camera.start_preview()
        camera.led = False
        time.sleep(2)
        camera.capture('full_multi_point_2.jpg')
        camera.stop_preview()
        image = 'full_multi_point_2.jpg'
        self.crop(image, (1020, 620, 1800, 1050), 'full_multi_crop_2.jpg')
        image = 'full_multi_crop_2.jpg'
        img = Image.open(image)
        pixels = list(img.getdata())
        pixels2 = []
        for pixel in pixels:
            total = 0
            for x in pixel:
                total += x
            total = int(total / 3)
            pixels2.append((total, total, total))

        filtered_list = self.filter(140, pixels2)
        img = Image.new('RGB', Image.open('full_multi_crop_2.jpg').size)
        img.putdata(filtered_list)
        img.save('full_multi_filter_2.jpg')

        start_time = time.time()

        image = cv2.imread('full_multi_filter_2.jpg')

        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        gray = cv2.erode(gray, None, iterations=1)

        new_image = Image.fromarray(gray)
        new_image.save('cv_proc_mult.png')

        labels = measure.label(gray, neighbors=8, background=0)
        mask = np.zeros(gray.shape, dtype="uint8")

        for label in np.unique(labels):
            # if this is the background label, ignore it
            if label == 0:
                continue

            # otherwise, construct the label mask and count the
            # number of pixels
            labelMask = np.zeros(gray.shape, dtype="uint8")
            labelMask[labels == label] = 255

            # if the number of pixels in the component is sufficiently
            # large, then add it to our mask of "large blobs"
            mask = cv2.add(mask, labelMask)

        # find the contours in the mask, then sort them from left to
        # right

        pixel_point = []
        cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
                                cv2.CHAIN_APPROX_SIMPLE)
        cnts = cnts[0] if imutils.is_cv2() else cnts[1]
        cnts = contours.sort_contours(cnts)[0]
        # loop over the contours
        for (i, c) in enumerate(cnts):
            ((cX, cY), radius) = cv2.minEnclosingCircle(c)
            pixel_point.append((int(cY), int(cX)))  # got the center points

        # show the output image
        new_image = Image.fromarray(image)
        new_image.save('full_cv_proc_mult_2.jpg')

        # arranging and interpolation
        pixel_point_sort = sorted(pixel_point, key=lambda y: y[0])
        new_pixel_point = []
        for i in range(16):
            new_pixel_point.append(
                sorted(pixel_point_sort[64 * i:64 * (i + 1)],
                       key=lambda z: z[1]))

        new_pixel_array = np.array([y for x in new_pixel_point for y in x])
        new_pixel_array.shape = (16, 64, 2)

        self.all_points_array = np.array(np.zeros(64 * 128 * 2))
        self.all_points_array.shape = (64, 128, 2)
        for i in range(0, 16):
            for j in range(0, 64):
                self.all_points_array[60 -
                                      4 * i][126 - 2 *
                                             j][0] = new_pixel_array[i][j][0]
                self.all_points_array[60 -
                                      4 * i][126 - 2 *
                                             j][1] = new_pixel_array[i][j][1]

        for i in range(0, 61, 4):
            for j in range(1, 127, 2):
                if j % 2 == 1:
                    self.all_points_array[i][j][0] = int(
                        (self.all_points_array[i][j - 1][0] +
                         self.all_points_array[i][j + 1][0]) / 2)
                    self.all_points_array[i][j][1] = int(
                        (self.all_points_array[i][j - 1][1] +
                         self.all_points_array[i][j + 1][1]) / 2)

        for i in range(61):
            for j in range(127):
                if i % 4 == 1:
                    self.all_points_array[i][j][0] = int(
                        (3 * self.all_points_array[i - 1][j][0] +
                         self.all_points_array[i + 3][j][0]) / 4)
                    self.all_points_array[i][j][1] = int(
                        (3 * self.all_points_array[i - 1][j][1] +
                         self.all_points_array[i + 3][j][1]) / 4)
                elif i % 4 == 2:
                    self.all_points_array[i][j][0] = int(
                        (2 * self.all_points_array[i - 2][j][0] +
                         2 * self.all_points_array[i + 2][j][0]) / 4)
                    self.all_points_array[i][j][1] = int(
                        (2 * self.all_points_array[i - 2][j][1] +
                         2 * self.all_points_array[i + 2][j][1]) / 4)
                elif i % 4 == 3:
                    self.all_points_array[i][j][0] = int(
                        (self.all_points_array[i - 3][j][0] +
                         3 * self.all_points_array[i + 1][j][0]) / 4)
                    self.all_points_array[i][j][1] = int(
                        (self.all_points_array[i - 3][j][1] +
                         3 * self.all_points_array[i + 1][j][1]) / 4)

        # Draw a black filled box to clear the image.
        draw.rectangle((0, 0, self.width, self.height), outline=0, fill=0)

        i = 63
        for j in range(0, self.width, 2):
            draw.point([(j, i)], fill=255)  # x,y

        disp.image(image_1)
        disp.display()

        # Now get the pixel data

        camera.start_preview()
        camera.led = False
        time.sleep(2)
        camera.capture('last_row_disp.jpg')
        camera.stop_preview()

        image = 'last_row_disp.jpg'
        self.crop(image, (1020, 620, 1800, 1050), 'last_row_crop.jpg')

        image = 'last_row_crop.jpg'
        img = Image.open(image)
        pixels = list(img.getdata())
        pixels2 = []
        for pixel in pixels:
            total = 0
            for x in pixel:
                total += x
            total = int(total / 3)
            pixels2.append((total, total, total))

        filtered_list = self.filter(140, pixels2)
        img = Image.new('RGB', Image.open(image).size)
        img.putdata(filtered_list)
        img.save('last_row_filter.jpg')

        image = cv2.imread('last_row_filter.jpg')

        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        gray = cv2.erode(gray, None, iterations=1)

        labels = measure.label(gray, neighbors=8, background=0)
        mask = np.zeros(gray.shape, dtype="uint8")

        # loop over the unique components
        for label in np.unique(labels):
            # if this is the background label, ignore it
            if label == 0:
                continue

            # otherwise, construct the label mask and count the
            # number of pixels
            labelMask = np.zeros(gray.shape, dtype="uint8")
            labelMask[labels == label] = 255

            # if the number of pixels in the component is sufficiently
            # large, then add it to our mask of "large blobs"
            mask = cv2.add(mask, labelMask)

        # find the contours in the mask, then sort them from left to
        # right

        pixel_point = []
        cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
                                cv2.CHAIN_APPROX_SIMPLE)
        cnts = cnts[0] if imutils.is_cv2() else cnts[1]
        cnts = contours.sort_contours(cnts)[0]
        # loop over the contours
        for (i, c) in enumerate(cnts):
            ((cX, cY), radius) = cv2.minEnclosingCircle(c)
            pixel_point.append((int(cY), int(cX)))

        pixel_point_sort = sorted(pixel_point, key=lambda z: z[1])

        for j in range(64):
            self.all_points_array[63][126 - 2 * j][0] = pixel_point_sort[j][0]
            self.all_points_array[63][126 - 2 * j][1] = pixel_point_sort[j][1]
            self.all_points_array[62][
                126 -
                2 * j][0] = (2 * pixel_point_sort[j][0] +
                             self.all_points_array[60][126 - 2 * j][0]) / 3
            self.all_points_array[62][
                126 -
                2 * j][1] = (2 * pixel_point_sort[j][1] +
                             self.all_points_array[60][126 - 2 * j][1]) / 3
            self.all_points_array[61][
                126 -
                2 * j][0] = (pixel_point_sort[j][0] +
                             2 * self.all_points_array[60][126 - 2 * j][0]) / 3
            self.all_points_array[61][
                126 -
                2 * j][1] = (pixel_point_sort[j][1] +
                             2 * self.all_points_array[60][126 - 2 * j][0]) / 3

        draw.rectangle((0, 0, self.width, self.height), outline=0, fill=0)

        j = 127
        for i in range(0, self.width, 3):
            draw.point([(j, i)], fill=255)  # x,y

        disp.image(image_1)
        disp.display()

        # Now get the pixel data

        camera.start_preview()
        camera.led = False
        time.sleep(2)
        camera.capture('last_col_disp.jpg')
        camera.stop_preview()
        image = 'last_col_disp.jpg'
        self.crop(image, (1020, 620, 1800, 1050), 'last_col_crop.jpg')
        image = 'last_col_crop.jpg'
        img = Image.open(image)
        pixels = list(img.getdata())
        pixels2 = []
        for pixel in pixels:
            total = 0
            for x in pixel:
                total += x
            total = int(total / 3)
            pixels2.append((total, total, total))

        filtered_list = self.filter(140, pixels2)
        img = Image.new('RGB', Image.open(image).size)
        img.putdata(filtered_list)
        img.save('last_col_filter.jpg')

        image = cv2.imread('last_col_filter.jpg')

        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        gray = cv2.erode(gray, None, iterations=1)

        labels = measure.label(gray, neighbors=8, background=0)
        mask = np.zeros(gray.shape, dtype="uint8")

        # loop over the unique components
        for label in np.unique(labels):
            # if this is the background label, ignore it
            if label == 0:
                continue

            # otherwise, construct the label mask and count the
            # number of pixels
            labelMask = np.zeros(gray.shape, dtype="uint8")
            labelMask[labels == label] = 255

            # if the number of pixels in the component is sufficiently
            # large, then add it to our mask of "large blobs"
            mask = cv2.add(mask, labelMask)

        # find the contours in the mask, then sort them from left to
        # right

        pixel_point = []
        cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
                                cv2.CHAIN_APPROX_SIMPLE)
        cnts = cnts[0] if imutils.is_cv2() else cnts[1]
        cnts = contours.sort_contours(cnts)[0]
        # loop over the contours
        for (i, c) in enumerate(cnts):
            ((cX, cY), radius) = cv2.minEnclosingCircle(c)
            pixel_point.append((int(cY), int(cX)))

        # show the output image

        pixel_point_sort = sorted(pixel_point, key=lambda z: z[0])
        for j in range(64):
            if j % 3 == 0:
                self.all_points_array[j][127][0] = pixel_point_sort[int(21 -
                                                                        j /
                                                                        3)][0]
                self.all_points_array[j][127][1] = pixel_point_sort[int(21 -
                                                                        j /
                                                                        3)][1]
            elif j % 3 == 1:
                self.all_points_array[j][127][0] = (
                    2 * pixel_point_sort[21 - int((j - 1) / 3)][0] +
                    pixel_point_sort[21 - int((j + 2) / 3)][0]) / 3
                self.all_points_array[j][127][1] = (
                    2 * pixel_point_sort[21 - int((j - 1) / 3)][0] +
                    pixel_point_sort[21 - int((j + 2) / 3)][0]) / 3
            elif j % 3 == 2:
                self.all_points_array[j][127][0] = (
                    2 * pixel_point_sort[21 - int((j + 1) / 3)][0] +
                    pixel_point_sort[21 - int((j - 2) / 3)][0]) / 3
                self.all_points_array[j][127][1] = (
                    2 * pixel_point_sort[21 - int((j + 1) / 3)][0] +
                    pixel_point_sort[21 - int((j - 2) / 3)][0]) / 3

        print(time.time() - start_time)
        camera.close()
Example #24
0
import time
import Adafruit_SSD1306
from PIL import Image, ImageDraw, ImageFont
import Adafruit_BMP.BMP085 as BMP085
disp = Adafruit_SSD1306.SSD1306_128_64(rst=None, i2c_address=0x3c)

disp.begin()

disp.clear()
disp.display()

width = disp.width
height = disp.height
image = Image.new('1', (width, height))
draw = ImageDraw.Draw(image)
draw.rectangle((0, 0, width, height), outline=0, fill=0)
padding = -2
top = padding
bottom = height - padding
x = 0
font = ImageFont.load_default()
sensor = BMP085.BMP085()

while True:

    temp = sensor.read_temperature()
    pressure = sensor.read_pressure()
    altitude = sensor.read_altitude()

    print('Temp={0:0.2f} *C'.format(temp))
    print('Pressure = {0:0.2f} Pa'.format(pressure))
# connect VCC with Pin 1
# connect SCL or SDK with Pin 5
# connect SDA with Pin 3




import Adafruit_SSD1306          # importing Modules
import time                      
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

RST = 24

disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)     # declaring variable disp

disp.begin()            # initializing diplay

disp.clear()            # clearing display
                           
disp.display()          # displaying on display

image = Image.new('1', (128, 32))    # generating new image

draw = ImageDraw.Draw(image)         # drawing on image

font = ImageFont.load_default()      # loading font

draw.text((13, 10), "Hello World!", font=font, fill=255)   # printing text on display
Example #26
0
import argparse

from time import sleep

import Adafruit_SSD1306
import RPi.GPIO as GPIO

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import subprocess

display = Adafruit_SSD1306.SSD1306_128_32(rst=None)

parser = argparse.ArgumentParser()
parser.add_argument('--ssd',
                    type=float,
                    default=0.1,
                    help='this determines the scroll speed of the display')
parser.add_argument('--fs',
                    type=int,
                    default=8,
                    help='this determines the font size in pixels')
myargs = parser.parse_args()


def get_scroll_range(scroll_height):
    scroll_range = []

    for i in range(1, scroll_height - 4 + 1):
        scroll_range.append(i)
Example #27
0
def main():
    node_id = "oled-{0:x}".format(getnode())

    try:
        client = mqtt.Client(node_id)
        client.connect(MQTT_HOST, port=1883, keepalive=60, bind_address="")
    except Exception as e:
        print("Error connecting to MQTT: {}".format(e))

    disp = Adafruit_SSD1306.SSD1306_128_32(rst=None)
    disp.begin()
    width = disp.width
    height = disp.height
    image = Image.new('1', (width, height))

    try:
        data = lte_stats.get_dongle_info()
    except Exception as e:
        print(e)
        data = None

    if data:
        for i in data:
            log.info("{}:{}".format(i, data[i]))
            if client:
                client.publish("/{}/{}".format("4ginternet", i),
                               payload=data[i])

        font = ImageFont.load_default()

        #draw = ImageDraw.Draw(image)
        #draw.rectangle((0,0,width,height), outline=0, fill=0)

        image = draw_signal(image, data['SignalStrength'])
        image = draw_carrier(image, data['FullName'],
                             data['CurrentNetworkType'])
        image = draw_sms(image, data['UnreadMessage'])

        if data['ConnectionStatus'] == "Connected" and data[
                'ExternalIPAddress'] != None:
            image = draw_status(image, data['ExternalIPAddress'])
            setled(GREEN)
        elif data['ConnectionStatus'] == "Connecting":
            setled(BLUE)
        else:
            image = draw_status(image, data['ConnectionStatus'])
            setled(RED)

        image = draw_speed(image, data['UploadSpeed'], data['DownloadSpeed'])

        #draw.text((x, top+25), "hello", font=font, fill=255)
    else:
        image = draw_dongleerror(image)

        setled(RED)
        try:
            os.remove("/tmp/ipCacheFile")
            os.remove("/tmp/speedTestCache.txt")
        except:
            pass

#draw.text((x, top+25), "", font=font, fill=255)

    disp.image(image)
    disp.display()
Example #28
0
# Return a float representing the percentage of GPU in use.
# On the Jetson Nano, the GPU is GPU0


def get_gpu_usage():
    GPU = 0.0
    with open("/sys/devices/gpu.0/load", encoding="utf-8") as gpu_file:
        GPU = gpu_file.readline()
        GPU = int(GPU) / 10
    return GPU


# 128x32 display with hardware I2C:
# setting gpio to 1 is hack to avoid platform detection
disp = Adafruit_SSD1306.SSD1306_128_32(rst=None, i2c_bus=1, gpio=1)

# 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.
Example #29
0
#!/usr/bin/env python3
import time

import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

# Raspberry Pi pin configuration:
RST = 4

# 128x64 display with hardware I2C:
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C)

# 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)
Example #30
0
def oled():
    
    RST = None    
    
    DC = 23
    SPI_PORT = 0
    SPI_DEVICE = 0

    disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)


    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
    top = padding
    bottom = height-padding
# Move left to right keeping track of the current x position for drawing shapes.
    x = 0


# Load default font.
    font = ImageFont.load_default()


    global barcode_value
    barcode_value=""
    while True:

    # Draw a black filled box to clear the image.
        draw.rectangle((0,0,width,height), outline=0, fill=0)

    # Write two lines of text.
        
        barcode_value=bar()
        
        draw.text((x, top), "CART: ", font=font, fill=255)
        if barcode_value == "":
            draw.text((x, top+8), "GOODS: ", font=font, fill=255)
        else :
            draw.text((x, top+8), "GOODS: "+barcode_value, font=font, fill=255)
        draw.text((x, top+16), "PRICE: ",  font=font, fill=255)
        draw.text((x, top+25), "TOTAL: ",  font=font, fill=255)
            

        # Display image.
        disp.image(image)
        disp.display()
        time.sleep(.1)