Esempio n. 1
0
  def init(self, args):
    global disp, image, image_hor, image_ver, draw
    driver = args['driver']
    interface = args['interface']
    self.mode = '1'
    self.bits = 1
    
    if interface == 'I2C':
      if driver == 'SSD1306_128_64':
        disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_bus=args['i2c_bus'], i2c_address=args['i2c_address'])
      elif driver == 'SSD1306_128_32':
        disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, i2c_bus=args['i2c_bus'], i2c_address=args['i2c_address'])
      elif driver == 'ssd1309_128_64':
        self.backend = 'luma.oled'
        disp = ssd1309(i2c(port=args['i2c_bus'], address=args['i2c_address']))
      #elif driver == 'ssd1322_256_64':
      #  self.backend = 'luma.oled'
      #  disp = ssd1322(i2c(port=args['i2c_bus'], address=args['i2c_address']))
      #elif driver == 'ssd1325_128_64':
      #  self.backend = 'luma.oled'
      #  disp = ssd1325(i2c(port=args['i2c_bus'], address=args['i2c_address']))
      elif driver == 'SSD1327_128_128':
        self.backend = 'luma.oled'
        self.mode = 'RGB'
        self.bits = 8
        disp = ssd1327(i2c(port=args['i2c_bus'], address=args['i2c_address']))
      #elif driver == 'SSD1331_96_64': #
      #  self.backend = 'luma.oled'
      #  self.bits = 16
      #  disp = ssd1331(i2c(port=args['i2c_bus'], address=args['i2c_address']))
      #elif driver == 'SSD1351_128_96': #
      #  self.backend = 'luma.oled'
      #  self.bits = 16
      #  disp = ssd1351(i2c(port=args['i2c_bus'], address=args['i2c_address']))
      elif driver == 'SSH1106_128_64':
        self.backend = 'luma.oled'
        disp = ssh1106(i2c(port=args['i2c_bus'], address=args['i2c_address']))
    elif interface == 'SPI':
      if driver == 'SSD1306_128_64':
        disp = Adafruit_SSD1306.SSD1306_128_64(rst=args['spi_rst_pin'], dc=args['spi_dc_pin'], spi=SPI.SpiDev(args['spi_port'], args['spi_device']), max_speed_hz=args['spi_hz'])
      elif driver == 'SSD1306_128_32':
        disp = Adafruit_SSD1306.SSD1306_128_32(rst=args['spi_rst_pin'], dc=args['spi_dc_pin'], spi=SPI.SpiDev(args['spi_port'], args['spi_device']), max_speed_hz=args['spi_hz'])
      elif driver == 'ssd1309_128_64':
        self.backend = 'luma.oled'
        disp = ssd1309(spi(device=args['spi_device'], port=args['spi_port']))
      elif driver == 'ssd1322_256_64':
        self.backend = 'luma.oled'
        disp = ssd1322(spi(device=args['spi_device'], port=args['spi_port']))
      elif driver == 'ssd1325_128_64':
        self.backend = 'luma.oled'
        disp = ssd1325(spi(device=args['spi_device'], port=args['spi_port']))
      elif driver == 'SSD1327_128_128':
        self.backend = 'luma.oled'
        self.mode = 'RGB'
        self.bits = 8
        disp = ssd1327(spi(device=args['spi_device'], port=args['spi_port']))
      elif driver == 'SSD1331_96_64': #
        self.backend = 'luma.oled'
        self.bits = 16
        disp = ssd1331(spi(device=args['spi_device'], port=args['spi_port']))
      elif driver == 'SSD1351_128_96': #
        self.backend = 'luma.oled'
        self.bits = 16
        disp = ssd1351(spi(device=args['spi_device'], port=args['spi_port']))
      elif driver == 'SSH1106_128_64':
        self.backend = 'luma.oled'
        disp = ssh1106(spi(device=args['spi_device'], port=args['spi_port']))
    
    self.maxValue = 1
    if 'RGB' == self.mode:
      self.maxValue = 255
    
    if 'adafruit' == self.backend:
      disp.begin()
    
    self.rotate({})
    width = self.getOutputWidth()
    height = self.getOutputHeight()
    #image_hor = Image.new('1', (width, height))
    #image_ver = Image.new('1', (width, width))
    image = Image.new(self.mode, (width, width))
    
    images['default'] = image;

    # Get drawing object to draw on image.
    draw = ImageDraw.Draw(image)
    
    #start()
    
    """f = open("out.txt", "a")
Esempio n. 2
0
async def socketHandler(websocket, path):

    pixelCount = PIXEL_COUNT

    try:
        while True:
            cmdLine = await websocket.recv()
            cmdList = cmdLine.split(" ")
            command = cmdList.pop(0)
            if DEBUG:
                print("> Received command:", cmdLine)

            # Process the command
            if command == "init":
                # Initialize the led strip.
                if DEBUG:
                    print(">> Initializing WS2801 strip...")
                pixels = Adafruit_WS2801.WS2801Pixels(PIXEL_COUNT,
                                                      spi=SPI.SpiDev(
                                                          SPI_PORT,
                                                          SPI_DEVICE),
                                                      gpio=GPIO)

                # Clear all the pixels to turn them off.
                if DEBUG:
                    print(">> Clearing all", PIXEL_COUNT, "pixels...")
                pixels.clear()
                pixels.show(
                )  # Make sure to call show() after changing any pixels!

                # By default, we will automatically show what was sent. This can be overridden with the autoshow command.
                autoShow = True

                # The init command replies with the number of pixels on the strip.
                await websocket.send(str(pixels.count()))

            elif command == "clear":
                if DEBUG:
                    print(">> Handling clear command")
                pixels.clear()
                if autoShow:
                    pixels.show()

            elif command == "setpixel":
                if DEBUG:
                    print(">> Handling setpixel command")
                pix = int(cmdList.pop(0))
                red = int(cmdList.pop(0))
                green = int(cmdList.pop(0))
                blue = int(cmdList.pop(0))
                if pixelCount < PIXEL_COUNT:
                    # Handle virtual split into multiple strips
                    while pix < PIXEL_COUNT:
                        if COLOR_ORDER == "RGB":
                            pixels.set_pixel_rgb(pix, red, green, blue)
                        else:
                            pixels.set_pixel_rgb(pix, red, blue, green)
                        pix = pix + pixelCount
                else:
                    if COLOR_ORDER == "RGB":
                        pixels.set_pixel_rgb(pix, red, green, blue)
                    else:
                        pixels.set_pixel_rgb(pix, red, blue, green)
                if autoShow:
                    pixels.show()

            elif command == "setpixels":
                if DEBUG:
                    print(">> Handling setpixels command")
                red = int(cmdList.pop(0))
                green = int(cmdList.pop(0))
                blue = int(cmdList.pop(0))
                if COLOR_ORDER == "RGB":
                    color = Adafruit_WS2801.RGB_to_color(red, green, blue)
                else:
                    color = Adafruit_WS2801.RGB_to_color(red, blue, green)
                pixels.set_pixels(color)
                if autoShow:
                    pixels.show()

            elif command == "shift":
                if DEBUG:
                    print(">> Handling shift command")
                direction = cmdList.pop(0)
                if direction == "left":
                    if DEBUG:
                        print(">> Shifting left...")
                    leftmostPixelColor = pixels.get_pixel(0)
                    if pixelCount < PIXEL_COUNT:
                        if DEBUG:
                            print(">>Handling virtual pixels for", pixelCount,
                                  "virtual pixels over", PIXEL_COUNT,
                                  "real pixels")
                        nrIterations = PIXEL_COUNT // pixelCount
                        for i in range(0, nrIterations):
                            for pix in range(1, pixelCount):
                                color = pixels.get_pixel(i * pixelCount + pix)
                                pixels.set_pixel(i * pixelCount + pix - 1,
                                                 color)
                            pixels.set_pixel((i + 1) * pixelCount - 1,
                                             leftmostPixelColor)
                        if PIXEL_COUNT % pixelCount > 0:
                            i = 0
                            for pix in range(nrIterations * pixelCount,
                                             PIXEL_COUNT):
                                color = pixels.get_pixel(i)
                                pixels.set_pixel(pix, color)
                                i = i + 1
                    else:
                        for pix in range(1, pixels.count()):
                            color = pixels.get_pixel(pix)
                            pixels.set_pixel(pix - 1, color)
                        pixels.set_pixel(pixels.count() - 1,
                                         leftmostPixelColor)
                    if autoShow:
                        pixels.show()
                elif direction == "right":
                    if DEBUG:
                        print(">> Shifting right...")
                    rightmostPixelColor = pixels.get_pixel(pixelCount - 1)
                    if pixelCount < PIXEL_COUNT:
                        if DEBUG:
                            print(">>Handling virtual pixels for", pixelCount,
                                  "virtual pixels over", PIXEL_COUNT,
                                  "real pixels")
                        nrIterations = PIXEL_COUNT // pixelCount
                        if PIXEL_COUNT % pixelCount > 0:
                            for pix in reversed(
                                    range(nrIterations * pixelCount,
                                          PIXEL_COUNT)):
                                color = pixels.get_pixel(pix - 1)
                                pixels.set_pixel(pix, color)
                        for i in range(0, nrIterations):
                            for pix in reversed(range(1, pixelCount)):
                                color = pixels.get_pixel(i * pixelCount + pix -
                                                         1)
                                pixels.set_pixel(i * pixelCount + pix, color)
                            pixels.set_pixel(i * pixelCount,
                                             rightmostPixelColor)
                    else:
                        for pix in reversed(range(1, pixels.count())):
                            color = pixels.get_pixel(pix - 1)
                            pixels.set_pixel(pix, color)
                        pixels.set_pixel(0, rightmostPixelColor)
                    if autoShow:
                        pixels.show()
                else:
                    print(">> Unknown shift direction:", direction)

            elif command == "dim":
                if DEBUG:
                    print(">> Handling dim command")
                step = int(cmdList.pop(0))
                for i in range(pixels.count()):
                    red, green, blue = pixels.get_pixel_rgb(i)
                    red = int(max(0, red - step))
                    green = int(max(0, green - step))
                    blue = int(max(0, blue - step))
                    pixels.set_pixel(
                        i, Adafruit_WS2801.RGB_to_color(red, green, blue))
                if autoShow:
                    pixels.show()

            elif command == "autoshow":
                if DEBUG:
                    print(">> Handling autoshow command")
                state = cmdList.pop(0)
                if state == "on":
                    autoShow = True
                elif state == "off":
                    autoShow = False
                else:
                    print(">> Unknown state for autoshow:", state)

            elif command == "show":
                if DEBUG:
                    print(">> Handling show command")
                pixels.show()

            elif command == "getpixelcount":
                if DEBUG:
                    print(">> Handling getpixelcount command")
                    print(">> Returning pixel count", pixels.count())
                await websocket.send(str(pixels.count()))

            elif command == "setVirtualPixels":
                if DEBUG:
                    print(">> Handling setVirtualPixels")
                nrPixels = int(cmdList.pop(0))
                pixelCount = nrPixels

            else:
                print(">> Unknown command:", command)

    except websockets.exceptions.ConnectionClosed:
        if DEBUG:
            print("> Disconnected.")
    except:
        print("> Unknown exception encountered.")
        raise
CURRENT_PITFT = PITFT_2_8

# Raspberry Pi configuration.
DC = CURRENT_PITFT
RST = 23
SPI_PORT = 0
SPI_DEVICE = 0

# BeagleBone Black configuration.
# DC = 'P9_15'
# RST = 'P9_12'
# SPI_PORT = 1
# SPI_DEVICE = 0

# Create TFT LCD display class.
disp = TFT.ILI9341(DC, rst=RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=64000000))

# Initialize display.
disp.begin()

# Clear the display to a red background.
# Can pass any tuple of red, green, blue values (from 0 to 255 each).
disp.clear((255, 0, 0))

# Alternatively can clear to a black screen by calling:
# disp.clear()

# Get a PIL Draw object to start drawing on the display buffer.
draw = disp.draw()

# Draw some shapes.
Esempio n. 4
0
WIDTH = 128
HEIGHT = 128
SPEED_HZ = 8000000

# Raspberry Pi configuration.
DC = 24
RST = 25
SPI_PORT = 0
SPI_DEVICE = 0

# BeagleBone Black configuration.
#DC = 'P9_15'
#RST = 'P9_12'
#SPI_PORT = 1
#SPI_DEVICE = 0

# Create TFT LCD display class.
disp = TFT.ST7735(DC,
                  rst=RST,
                  spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=SPEED_HZ))

# Initialize display.
disp.begin()

# Load an image.
image = Image.open('test.png')

#display image
disp.display(image)
Esempio n. 5
0
MQTT_SERVER = "192.168.43.130" #for Litty
#MQTT_SERVER = "192.168.0.135" #for Naruto
listen_path = "topic/serene"
send_path = "topic/init_loc"
MY_ID = ""
LAST_WILL = ""
INITIALIZED = False
MY_CURRENT_LIGHTING = ""

# Configure the count of pixels:
PIXEL_COUNT = 8
# Alternatively specify a hardware SPI connection on /dev/spidev0.0:
SPI_PORT   = 0
SPI_DEVICE = 0
pixels = Adafruit_WS2801.WS2801Pixels(PIXEL_COUNT, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE), gpio=GPIO)

def on_connect(client, userdata, flags, rc):
		print("Connected: result code " + str(rc))
		client.subscribe(listen_path)

def on_message(client, userdata, msg):
		statement = msg.payload
		print("RPi received")
		print(msg.topic + " " + str(statement))
		# Get IMU reading
		tiltHeading = Compass.readCompass(Compass.IMU)
		tiltHeading = Compass.readCompass(Compass.IMU)
		tiltHeading = Compass.readCompass(Compass.IMU)
		tiltHeading = Compass.readCompass(Compass.IMU)
		tiltHeading = Compass.readCompass(Compass.IMU)
Esempio n. 6
0
 def test_write_assert_deassert_ss_false(self):
     gpio = MockGPIO()
     device = SPI.BitBang(gpio, 1, 2, 3, 4)
     device.write([0x1F], assert_ss=False, deassert_ss=False)
     self.assertListEqual(gpio.pin_written[4], [1])
Esempio n. 7
0
 def test_invalid_bit_order_fails(self):
     gpio = MockGPIO()
     device = SPI.BitBang(gpio, 1, 2, 3, 4)
     self.assertRaises(ValueError, device.set_bit_order, -1)
     self.assertRaises(ValueError, device.set_bit_order, 2)
Esempio n. 8
0
 def read(MCP3008,pin_num):
     values = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(0,0)).read_adc(pin_num)
     return values
def setup():
    global mcp
    mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
Esempio n. 10
0
    def __init__(self):
        # Initialisation de l'interface
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)

        SPI_PORT = 0
        SPI_DEVICE = 0
        self.mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))

        # Définition des paramètres
        self.margin = None

        # Création des dictionnaires des types et sous types de capteurs et actionneurs
        self.sensorDict = {"Position": ["Sélection 1", "Sélection 2", "Engagement 1", "Engagement 2", "Embrayage 1", "Embrayage 2"],
                           "Pression": ["Robot"],
                           "Vitesse": ["Boîte de vitesses"]}

        self.actuatorDict = {"Electrovanne": ["Sélection +", "Sélection -", "Engagement +", "Engagement -", "Embrayage +"],
                             "Moteur_électrique": ["Sélection +", "Sélection -", "Engagement +", "Engagement -", "Embrayage +"],
                             "Electro_pompe": ["Robot"]}

        self.pinDict = {"Position Sélection 1": ('A', 0), "Position Sélection 2": ('A', 1),
                        "Position Engagement 1": ('A', 2), "Position Engagement 2": ('A', 3),
                        "Position Embrayage 1": ('A', 4), "Position Embrayage 2": ('A', 5),
                        "Pression Robot": ('A', 6),
                        "Vitesse Boîte de vitesses": ('A', 7),
                        "Electrovanne Sélection +": ('D', 17), "Electrovanne Sélection -": ('D', 4),
                        "Electrovanne Engagement +": ('D', 5), "Electrovanne Engagement -": ('D', 27),
                        "Electrovanne Embrayage +": ('D', 22),
                        "Moteur_électrique Sélection +": ('D', 17), "Moteur_électrique Sélection -": ('D', 4),
                        "Moteur_électrique Engagement +": ('D', 5), "Moteur_électrique Engagement -": ('D', 27),
                        "Moteur_électrique Embrayage +": ('D', 22),
                        "Electro_pompe Robot": ('D', 13)}

        self.pinMotor = 26

        # Création de la liste des types
        self.sensorList = []
        for key in self.sensorDict:
            self.sensorList.append(key)
        self.actuatorList = []
        for key in self.actuatorDict:
            self.actuatorList.append(key)

        # Création du dictionnaire des classes de capteurs
        self.sensorClass = {}
        for category in self.sensorDict:
            self.sensorClass[category] = {}
            for subCategory in self.sensorDict[category]:
                self.sensorClass[category][subCategory] = Sensor(category, subCategory, self.pinDict[category+" "+subCategory], self)
        self.actuatorClass = {}
        for category in self.actuatorDict:
            self.actuatorClass[category] = {}
            for subCategory in self.actuatorDict[category]:
                self.actuatorClass[category][subCategory] = Actuator(category, subCategory, self.pinDict[category+" "+subCategory], self)

        # Création du dictionnaire de valeurs capteur
        self.sensorValue= {}
        for category in self.sensorDict:
            for subCategory in self.sensorDict[category]:
                self.sensorValue[category + ' ' + subCategory] = 0

        self.GPIOReset()

        _thread.start_new_thread(self.SensorThread, ())
        _thread.start_new_thread(self.SpeedSensorThread, ())
 def __init__(self):  #analog read is controlled by SPI hardware interface
     self.SPI_PORT = 0
     self.SPI_DEVICE = 0
     self.meas = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(0, 0))
Esempio n. 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)
    GPIO.output(iTriggerPin, False)
Esempio n. 13
0
import time, sys
import Image
import ImageDraw
import ImageFont
import Adafruit_ILI9341 as TFT
import Adafruit_GPIO.SPI as SPI

#
# provide quoted strings for title and message.
# limit title to: 20 chars
# limit message to 30 chars

TEXT_TITLE =   str(sys.argv[1])
TEXT_MSG   =   str(sys.argv[2])

disp = TFT.ILI9341(24, rst=25, spi=SPI.SpiDev(0,0,max_speed_hz=64000000))
disp.begin()
disp.clear()

image = disp.buffer
fill = (255,255,255)
angle = 90

font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSans.ttf", 30)
draw = ImageDraw.Draw(image)
t_width, t_height = draw.textsize(TEXT_TITLE, font=font)
textimage = Image.new('RGBA', (t_width, t_height), (0,0,0,0))
textdraw = ImageDraw.Draw(textimage)
textdraw.text((0,0), TEXT_TITLE, font=font, fill=fill)
rotated = textimage.rotate(angle, expand=1)
x_pos = 280
Esempio n. 14
0
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008

# Software SPI configuration:
# CLK  = 18
# MISO = 23
# MOSI = 24
# CS   = 25
# mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)

# Hardware SPI configuration:
SPI_PORT = 0
SPI_DEVICE0 = 0  # 0
SPI_DEVICE1 = 1  # 0

mcp1 = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE0))
mcp2 = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE1))

print('Reading MCP3008 values, press Ctrl-C to quit...')
# Print nice channel column headers.
print(
    '| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'
    .format(*range(8)))
print('-' * 57)
# Main program loop.
while True:
    # Read all the ADC channel values in a list.
    values = [0] * 16
    for i in range(8):
        # The read_adc function will get the value of the specified channel (0-7).
        values[i] = mcp1.read_adc(i)
Esempio n. 15
0
 def test_read_assert_deassert_ss_false(self):
     gpio = MockGPIO()
     device = SPI.BitBang(gpio, 1, 2, 3, 4)
     gpio.pin_read[3] = [0, 0, 0, 1, 1, 1, 1, 1]
     result = device.read(1, assert_ss=False, deassert_ss=False)
     self.assertListEqual(gpio.pin_written[4], [1])
Esempio n. 16
0
import json
import logging
import time
import math
import RPi.GPIO as GPIO

import Adafruit_DHT
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
from w1thermsensor import W1ThermSensor
from hx711 import HX711

logger = logging.getLogger("api_beez")
mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(0, 0))


class MyPi(object):
    # 'magic method' propre à toutes les classes (ca commence et finit par '__').
    # En l'occurence init prend des parametres et permet de les relier à l'instance via self
    def __init__(self):
        self.config = json.load(open("config_settings.json", "r"))
        self.sensors = self.sensor_matches(self.config['raspberry']['sensors'])

    # Décorateur qui permet de faire des méthodes classe et non d'instance
    @classmethod
    def sensor_matches(cls, sensor_config):
        matches = {
            "DS18B20": {
                "mesure": "temperature",
                "class": DS18B20Sensor
            },
Esempio n. 17
0
 def test_ss_set_high_after_initialization(self):
     gpio = MockGPIO()
     device = SPI.BitBang(gpio, 1, 2, 3, 4)
     self.assertListEqual(gpio.pin_written[4], [1])
Esempio n. 18
0
class MQ():

    CLK = 23
    MISO = 21
    MOSI = 19
    CS = 24
    mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)

    SPI_PORT = 0
    SPI_DEVICE = 0
    mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))

    MQ_PIN = 0
    RL_VALUE = 10
    RO_CLEAN_AIR_FACTOR = float(4.4)

    CALIBARAION_SAMPLE_TIMES = 50
    CALIBRATION_SAMPLE_INTERVAL = 50

    READ_SAMPLE_INTERVAL = 50
    READ_SAMPLE_TIMES = 5

    GAS_CH4 = 0

    def _init_(self, Ro=10, analogPin=0):
        self.Ro = Ro
        self.MQ_PIN = analogPin

        self.CH4Curve = [2.3, 0.26, -0.36]

        print("Calibrating...")
        self.Ro = self.MQCalibration(self.MQ_PIN)
        print("Calibration is done...\n")
        print("Ro=%f kohm" % self.Ro)

    def MQPercentage(self):
        val = {}
        read = self.MQRead(self.MQ_PIN)
        val["GAS_CH4"] = self.MQGetGasPercentage(read / self.Ro, self.GAS_CH4)
        return val

    def MQResistanceCalculation(self, raw_adc):
        return float(self.RL_VALUE * (1023.0 - raw_adc) / float(raw_adc))

    def MQCalibration(self, MQ_PIN):
        val = 0.0
        for i in range(self.CALIBARAION_SAMPLE_TIMES):
            val += self.MQResistanceCalculation(self.mcp.read_adc(MQ_PIN))
            time.sleep(self.CALIBRATION_SAMPLE_INTERVAL / 1000.0)

        val = val / self.CALIBARAION_SAMPLE_TIMES

        val = val / self.RO_CLEAN_AIR_FACTOR

        return val

    def MQRead(self, MQ_PIN):
        rs = 0.0

        for i in range(self.READ_SAMPLE_TIMES):
            rs += self.MQResistanceCalculation(self.mcp.read_adc(MQ_PIN))
            time.sleep(self.READ_SAMPLE_INTERVAL / 1000.0)

        rs = rs / self.READ_SAMPLE_TIMES

        return rs

    def MQGetGasPercentage(self, rs_ro_ratio, gas_id):
        if (gas_id == self.GAS_CH4):
            return self.MQGetPercentage(rs_ro_ratio, self.CH4Curve)

    def MQGetPercentage(self, rs_ro_ratio, pcurve):
        return (math.pow(
            10,
            (((math.log10(rs_ro_ratio) - pcurve[1]) / pcurve[2]) + pcurve[0])))
Esempio n. 19
0
 def test_write_lsbfirst(self):
     gpio = MockGPIO()
     device = SPI.BitBang(gpio, 1, 2, 3, 4)
     device.set_bit_order(SPI.LSBFIRST)
     device.write([0x1F])
     self.assertListEqual(gpio.pin_written[2], [1, 1, 1, 1, 1, 0, 0, 0])
Esempio n. 20
0
 def __init__(self):
     self.mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(0, 0))
Esempio n. 21
0
import Adafruit_GPIO.SPI as SPI
from AD56x8 import AD56x8

DAC_CH = [
    'DAC_A', 'DAC_B', 'DAC_C', 'DAC_D', 'DAC_E', 'DAC_F', 'DAC_G', 'DAC_H'
]

# BeagleBone Black hardware SPI configuration.
SPI_PORT = 1
SPI_DEVICE = 0
dac = AD56x8.AD56x8('AD5628-1', spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))

dac.reset()
dac.internal_ref_mode('ON')

# Configure all channels for SW LDAC
for ch in DAC_CH:
    dac.LDAC_mode('SW', ch)

counter = 0

while True:
    for ch in DAC_CH:
        dac.write_to_Input_Reg(ch, counter)
        dac.update_DAC_Reg(ch)

    voltage = 2 * (dac.VREF) * (counter / (2**dac.DATA_WIDTH))
    counter = (counter + 1) % ((2**dac.DATA_WIDTH) - 1)
    print("DAC Voltage:", round(voltage, 3))
Esempio n. 22
0
#Define a function to convert Celsius to Fahrenheit.
def c_to_f(c):
    return c * 9.0 / 5.0 + 32.0


#Function for reading the thermocouple temperature
def readTemp():
    temp = sensor.readTempC()
    internal = sensor.readInternalC()
    return temp


# Raspberry Pi hardware SPI configuration.
SPI_PORT = 0
SPI_DEVICE = 0
sensor = MAX31855.MAX31855(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))

#Setting up GPIO pins
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
#pin for activating pump relay currently set to 17 but may need to be changed later
GPIO.setup(26, GPIO.OUT)
#pin for activating solenoid valve
GPIO.setup(12, GPIO.OUT)

#---------USER DEFINED VARIABLES FROM THE UI ARE DECLARED HERE----------------------------------------------
#after some searching, the way python reads variables from C# is with sys.argv[]
#in this program, I am assuming sys.argv[1] is the destination temperature and sys.argv[2] is a boolean for isF
#In the C# front end, make sure to order the argv[] variables in the same way when you call the function

#variable to keep track of whether the user entered in Fahrenheit
Esempio n. 23
0
DC = 23
RST = 24
SPI_PORT = 0
SPI_DEVICE = 0

# Raspberry Pi software SPI config:
# SCLK = 4
# DIN = 17
# DC = 23
# RST = 24
# CS = 8

# Hardware SPI usage:
disp = LCD.PCD8544(DC,
                   RST,
                   spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=4000000))

# Software SPI usage (defaults to bit-bang SPI interface):
#disp = LCD.PCD8544(DC, RST, SCLK, DIN, CS)

# Initialize library.
disp.begin(contrast=60)

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

# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
image = Image.new('1', (LCD.LCDWIDTH, LCD.LCDHEIGHT))
Esempio n. 24
0
import Adafruit_SSD1306
from PIL import Image, ImageFont, ImageDraw
import StringIO
import pygame
import zipfile
import os, sys

# Ports used for fthe Display. You may have to change them to yours
RST = 25
DC = 24

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=16000000))

# Initialize library.
disp.begin()

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

# Get display width and height.
width = disp.width
height = disp.height

# Create image buffer.
# Make sure to create image with mode '1' for 1-bit color.
image = Image.new('1', (width, height))
Esempio n. 25
0
#Jason Millette
#11/23/18

#uses information from the website to display
#then create an 128x128 image for display on an SPI device

import requests
import Image
import ImageDraw
import sys
import ST7735 as TFT
import Adafruit_GPIO.SPI as SPI

#Getting weather data


#Creating weather image for SPI display
image = Image.new('RGB', (128,128), (0, 0, 255))    #RGB, size, color
draw = ImageDraw.Draw(image)                        #creates image
draw.text((10,9), sys.argv[1], fill=(0, 0, 0))#(x,y), text, (R, G, B)
#draw.text((35, 18), 'sys.argv[2]', fill=(0, 0, 0))

#displaying images to spi devices
DC = 24
RST = 25

#Displaying website data
display2 = TFT.ST7735(DC, rst=RST, spi=SPI.SpiDev(0, 1, max_speed_hz=8000000)) # display initalized in initDisplay.py
display2.display(image) #displays image

Esempio n. 26
0
from PIL import ImageDraw
from PIL import ImageFont
import json
import requests
import _thread

# -- Setup Pi GPIO Numbers --
GPIO.setmode(GPIO.BCM)

# -- Setup Nokia 5110 LCD SPI Config --
DC = 5  # data/control (GPIO5 pin29)
RST = 6  # reset (GPIO6 pin31)
SPI_PORT = 0  # SPI port 0
SPI_DEVICE = 1  # CS1 (GPIO7 pin26)
# Hardware SPI usage:
disp = LCD.PCD8544(DC, RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=4000000))
image = Image.new('1', (LCD.LCDWIDTH, LCD.LCDHEIGHT))

# -- Setup ADC SPI --
spi = spidev.SpiDev()  # create spi object
spi.open(0, 0)  # SPI port 0, device CS0 (GPIO8 pin24)
spi.max_speed_hz = (1000000)

# -- Setup Nokia 5110 LCD Settings --
# Initialize library
disp.begin(contrast=50)
# Clear display
disp.clear()
disp.display()
# Load default font
font = ImageFont.load_default()
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
import RPi.GPIO as GPIO
import spidev

# Software SPI configuration:
#CLK  = 18
#MISO = 23
#MOSI = 24
#CS   = 25
#mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)

# Hardware SPI configuration:
SPI_PORT = 0
SPI_DEVICE = 0
mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))

# Choose channel
an_chan = 1  # channel 8 (numbered 0-7)

# choose GPIO pin
ledPin = 18

GPIO.setmode(GPIO.BCM)
GPIO.setup(ledPin, GPIO.OUT)

samplingTime = 280.0
deltaTime = 40.0
sleepTime = 9680.0

# Main program loop.
Esempio n. 28
0
 def __init__(self):
     """
     Initialize the MCP3008 hardware interface used by this class
     """
     self.mcp = MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
Esempio n. 29
0
# Simple demo of of the WS2801/SPI-like addressable RGB LED lights.
import time
import RPi.GPIO as GPIO

# Import the WS2801 module.
import Adafruit_WS2801
import Adafruit_GPIO.SPI as SPI

# Configure the count of pixels:
PIXEL_COUNT = 9

# Alternatively specify a hardware SPI connection on /dev/spidev0.0:
SPI_PORT = 0
SPI_DEVICE = 0
pixels = Adafruit_WS2801.WS2801Pixels(PIXEL_COUNT,
                                      spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE),
                                      gpio=GPIO)


# Define the wheel function to interpolate between different hues.
def wheel(pos):
    if pos < 85:
        return Adafruit_WS2801.RGB_to_color(pos * 3, 255 - pos * 3, 0)
    elif pos < 170:
        pos -= 85
        return Adafruit_WS2801.RGB_to_color(255 - pos * 3, 0, pos * 3)
    else:
        pos -= 170
        return Adafruit_WS2801.RGB_to_color(0, pos * 3, 255 - pos * 3)

Esempio n. 30
0
def collect_data(interval, runtime, pin_num, filename):
    '''
       params
       interval in seconds can be an int or float
       runtime how long you want to collect data (if runtime = -1 it will continue until you C-c out)

       data will only be collected if interval < runtime, interval > 0, and runtime != -1

       ret
       data is interval at idx 0 then collected data is at data[1:]
       if data is not collected retruns -1
       '''
    # We can either use Software SPI or Hardware SPI. For software SPI we will
    # use regular GPIO pins. Hardware SPI uses the SPI pins on the Raspberry PI
    # Set the following variable to either HW or SW for Hardware SPI and Software
    # SPI respectivly.

    # PIN IS 6 AS A PARAMETER
    SPI_TYPE = 'HW'
    # dly = .5  # Delay of 1000ms (1 second) original
    dly = .5 * interval

    # Software SPI Configuration
    CLK = 18  # Set the Serial Clock pin
    MISO = 23  # Set the Master Input/Slave Output pin
    MOSI = 24  # Set the Master Output/Slave Input pin
    CS = 25  # Set the Slave Select

    # Hardware SPI Configuration
    HW_SPI_PORT = 0  # Set the SPI Port. Raspi has two.
    HW_SPI_DEV = 0  # Set the SPI Device

    # Instantiate the mcp class from Adafruit_MCP3008 module and set it to 'mcp'.
    if (SPI_TYPE == 'HW'):
        # Use this for Hardware SPI
        mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(HW_SPI_PORT, HW_SPI_DEV))
    elif (SPI_TYPE == 'SW'):
        # Use this for Software SPI
        mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)

    analogPort = pin_num
    print('Reading MCP3008 values on pin: %d' % analogPort)

    data = [interval]
    try:
        if runtime == -1:
            while True:
                # Read the value from the MCP3008 on the pin we specified in analogPort
                val = mcp.read_adc(analogPort)
                # print out the value
                print(val)
                # Sleep for dly
                sleep(dly)
        else:
            t = 0
            i = 0
            while t < runtime:
                # Read the value from the MCP3008 on the pin we specified in analogPort
                val = mcp.read_adc(analogPort)
                # print out the value
                print(val)
                data.append(val)
                os.system("fswebcam " + filename + str(i) + ".jpg")
                # Sleep for dly
                sleep(dly)
                t += interval
                i += 1
    except KeyboardInterrupt:
        sys.exit()
    return data