Exemplo n.º 1
0
class WaterDetector(Sensor):
    """ water detector driver
    """
    def __init__(self, gpio_pin):
        self._gpio_pin = gpio_pin
        self._gpio = None
        self._is_connected = False

    def connect(self):
        self._gpio = GPIO(self._gpio_pin, "in")
        self._is_connected = True
        return True

    def disconnect(self):
        self._is_connected = False
        self._gpio = None
        return True

    def is_connected(self):
        return self._is_connected

    def is_water_full(self):
        """
        Returns:
            bool: return True if detect water full, otherwise return False
        """
        return self._gpio.read()
Exemplo n.º 2
0
def read_GPIOLIST():
    for num in range(7):
        gpio_in = GPIO(GPIO_num_list[num])
        GPIO_directon_list[num] = gpio_in.direction
        GPIO_value_list[num] = gpio_in.read()
        gpio_in.close()

    return GPIO_name_list, GPIO_directon_list, GPIO_value_list
Exemplo n.º 3
0
class config(object):

    DONE_ITS = 100
    CHUNK = 4 * 1024
    DELAY = 10e-3
    MODE = 3

    def __init__(self, ss_pin, cdone_pin, creset_pin, spidev):
        self.ss = GPIO(ss_pin, "out")
        self.cdone = GPIO(cdone_pin, "in")
        self.creset = GPIO(creset_pin, "out")
        self.spidev = spidev

    def sleep(self):
        time.sleep(self.DELAY)

    def set_ss(self, val):
        self.ss.write(val)

    def reset(self, val):
        if val:
            self.creset.write(False)
        else:
            self.creset.write(True)

    def wait_done(self):
        done = 0
        cnt = 0
        while done == 0 and cnt < self.DONE_ITS:
            self.sleep()
            done = self.cdone.read()
            cnt += 1
        return done

    def sram_config(self, image):
        self.reset(True)
        self.sleep()

        self.set_ss(False)
        self.sleep()

        self.reset(False)
        self.sleep()

        for i in range(0, len(image), self.CHUNK):
            self.spidev.transfer(image[i:i + self.CHUNK])

        # extra 49 bits
        self.spidev.transfer(7 * [0])
Exemplo n.º 4
0
    def read_analog_sensor(self):
        """ Reads the Sump Pump sensor.
        :return: Distance to Sump Pump water.
        :rtype: float
        """

        trig=GPIO(23, 'out')
        echo=GPIO(24, 'in')

        # Pulse to trigger sensor
        trig.write(False)
        time.sleep(0.00001)
        trig.write(True)
        time.sleep(0.00001)
        trig.write(False)

        while echo.read()==False:
            pulse_start=time.time()

        while echo.read()==True:
            pulse_end= time.time()

        pulse_duration=pulse_end-pulse_start

        # Quick explaination of the formula:
        # The pulse duration is to the object and back, so the 
        # distance is one half of the pulse duration. The speed of 
        # sound in air is 340 meters/second. There are 100 centimeters 
        # in a meter.
        distance=pulse_duration*340/2*100
        distance=round(distance, 2)

        trig.close()
        echo.close()

        return distance
Exemplo n.º 5
0
def play(device, f):
    periodsize = f.getframerate() // 8
    device = alsaaudio.PCM()
    #Aspetta per farlo partire
    data = f.readframes(periodsize)  #Prebuffering

    #Polling
    gpio4_12 = GPIO("/dev/gpiochip4", 12, "in")
    while (gpio4_12.read() == True):
        a = None

    #Leggi e suona
    while data:
        device.write(data)
        data = f.readframes(periodsize)
Exemplo n.º 6
0
    def read(self, pin):
        """Read bool value from a pin.

        Args:
            pin (int): the pin to read from

        Return:
            bool: value of digital pin reading

        """
        with self._gpio_lock:
            gpio_pin = GPIO(pin, "in")
            value = gpio_pin.read()
            gpio_pin.close()
            self.logger.debug("Read value from GPIO pin {}: {}".format(
                pin, value))
        return bool(value)
Exemplo n.º 7
0
class InputMonitor(threading.Thread):
    def __init__(self, gpio_pin=None):
        threading.Thread.__init__(self)
        self._is_gpio = gpio_pin is not None
        if self._is_gpio:
            self._gpio = GPIO(gpio_pin, 'in')
        self._lock = threading.Lock()
        self._is_key_pressed = False
        self._last_key_pressed_time = time.monotonic()

    def is_key_pressed(self):
        self._lock.acquire()

        if self._is_key_pressed:
            self._is_key_pressed = False
            self._lock.release()
            return True

        self._lock.release()

        return False

    def run(self):
        while True:
            if self._is_gpio:
                v = self._gpio.read()
                diff = time.monotonic() - self._last_key_pressed_time
                if v \
                   and not self._is_key_pressed \
                   and diff > 0.2:
                    self._lock.acquire()
                    self._is_key_pressed = True
                    self._last_key_pressed_time = time.monotonic()
                    self._lock.release()
                time.sleep(0.1)
            else:
                input()
                self._lock.acquire()
                self._is_key_pressed = True
                self._lock.release()
Exemplo n.º 8
0
class UserInputs(object):
    """Tests that values can be written and read from a GPIO pin"""

    def __init__(self, logging):
        self.gpio = None
        if isinstance(self, UserInputOne):
            self.gpio = GPIO(pin=85, direction=OUT)
        elif isinstance(self, UserInputTwo):
            self.gpio = GPIO(pin=86, direction=OUT)
        elif isinstance(self, UserInputThree):
            self.gpio = GPIO(pin=90, direction=OUT)
        self.logging = logging

    def test_high(self):
        """Tests that high values can be written and read from the GPIO pin"""
        return self._test(True)

    def test_low(self):
        """Tests that low values can be written and read from the GPIO pin"""
        return self._test(False)

    def _test(self, level):
        try:
            self.gpio.write(level)
            logging.debug("Value written")
            val = self.gpio.read()
            if val is level:
                self.logging.debug("Value read is the one same as the one written")
                return True
            else:
                message = "Value read is different to the one written: " + str(val) + " != " + str(level)
                self.logging.fatal()
                return False
        except Exception as ex:
            self.logging.fatal(ex)
            return False
Exemplo n.º 9
0
# Toggle LED through GPIO function
# Author: Peter Mankowski

from periphery import GPIO
import time

# GPIO init
gpio = GPIO(138, "low")

# Parameters declarations
count = 0
How_many_counts = 4
sleep_del = 0.1
"""
gpio.write(True)
time.sleep(1)
"""
# Toggle GPIO feature
while (count < How_many_counts):
    count = count + 1
    value = gpio.read()
    gpio.write(not value)
    time.sleep(sleep_del)

gpio.close()
Exemplo n.º 10
0
def getpoint():
    maxHeight = 480
    maxWidth = 640
    capture = cv2.VideoCapture(0)
    capture.set(3, maxWidth)
    capture.set(4, maxHeight)
    gpio_get = GPIO(38, "in")
    while True:
        ret, image = capture.read()
        image = cv2.resize(image, (640, 480), interpolation=cv2.INTER_CUBIC)
        image = cv2.flip(image, 1)
        # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        cv2.imshow('frame', image)
        #         time_in+=1
        k = cv2.waitKey(1)
        value = gpio_get.read()
        if value == False:
            break
    gpio_get.close()
    # 颜色范围
    low_color = np.array([35, 43, 46])
    up_color = np.array([77, 255, 255])
    # 图像处理

    hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
    # 颜色过滤
    mask = cv2.inRange(hsv, low_color, up_color)
    # 边缘检测
    cannyimg = cv2.Canny(mask, 10, 200)

    #     cv2.imshow("img",cannyimg)
    #     cv2.waitKey(0)

    # 闭运算
    print("1")
    kernelX = cv2.getStructuringElement(cv2.MORPH_RECT, (17, 5))
    cannyimg = cv2.morphologyEx(cannyimg, cv2.MORPH_CLOSE, kernelX)

    circles = cv2.HoughCircles(cannyimg,
                               cv2.HOUGH_GRADIENT,
                               1,
                               20,
                               param1=100,
                               param2=5,
                               minRadius=2,
                               maxRadius=13)

    circles = np.uint16(np.around(circles))
    print("2")

    center = [[circles[0][0][0], circles[0][0][1]],
              [circles[0][1][0], circles[0][1][1]],
              [circles[0][2][0], circles[0][2][1]],
              [circles[0][3][0], circles[0][3][1]]]
    print("3")
    n = len(center)
    for i in range(n):
        # Last i elements are already in place
        for j in range(0, n - i - 1):
            if center[j][0] > center[j + 1][0]:
                center[j], center[j + 1] = center[j + 1], center[j]
    if center[0][1] > center[1][1]:
        center[0], center[1] = center[1], center[0]
    if center[2][1] > center[3][1]:
        center[2], center[3] = center[3], center[2]
    center[1], center[2] = center[2], center[1]
    print("4")

    # original pts
    pts_o = np.float32([center[0], center[1], center[2],
                        center[3]])  # 这四个点为原始图片上数独的位置
    pts_d = np.float32([[0, 0], [600, 0], [0, 600], [600,
                                                     600]])  # 这是变换之后的图上四个点的位置
    print("5")
    # get transform matrix
    M = cv2.getPerspectiveTransform(pts_o, pts_d)
    print("6")
    # apply transformation
    dst = cv2.warpPerspective(image, M,
                              (600, 600))  # 最后一参数是输出dst的尺寸。可以和原来图片尺寸不一致。按需求来确定
    print("7")
    image = dst
    #     cv2.imshow("img",image)
    #     cv2.waitKey(0)

    #     low_color2 = np.array([80, 20, 20])
    #     up_color2 = np.array([255, 150, 80])
    low_color2 = np.array([130, 0, 0])
    up_color2 = np.array([255, 150, 100])

    #     print("8")
    n = len(point)
    print(n)
    for index in range(n):
        #         print("xxxxx")
        bgr = image[point[index][0], point[index][1]]
        bgr = np.array(bgr)

        if (low_color2 <= bgr).all() and (up_color2 >= bgr).all():

            if point[index][2] == 0:
                point[index][2] = 1
                #                 print("xxxxxx")
                print(index, type(index))
                return index
Exemplo n.º 11
0
class TM1637:
    I2C_COMM1 = 0x40
    I2C_COMM2 = 0xC0
    I2C_COMM3 = 0x80
    digit_to_segment = [
        0b0111111,  # 0
        0b0000110,  # 1
        0b1011011,  # 2
        0b1001111,  # 3
        0b1100110,  # 4
        0b1101101,  # 5
        0b1111101,  # 6
        0b0000111,  # 7
        0b1111111,  # 8
        0b1101111,  # 9
        0b1110111,  # A
        0b1111100,  # b
        0b0111001,  # C
        0b1011110,  # d
        0b1111001,  # E
        0b1110001  # F
    ]

    def __init__(self, clk, dio):
        self.clk = clk
        self.dio = dio
        self.brightness = 0x0f

        self.gpio_clk = GPIO(self.clk, "out")
        self.gpio_dio = GPIO(self.dio, "out")

    def bit_delay(self):
        sleep(0.001)
        return

    def set_segments(self, segments, pos=0):
        # Write COMM1
        self.start()
        self.write_byte(self.I2C_COMM1)
        self.stop()

        # Write COMM2 + first digit address
        self.start()
        self.write_byte(self.I2C_COMM2 + pos)

        for seg in segments:
            self.write_byte(seg)
        self.stop()

        # Write COMM3 + brightness
        self.start()
        self.write_byte(self.I2C_COMM3 + self.brightness)
        self.stop()

    def start(self):
        self.gpio_clk.write(True)
        self.gpio_dio.write(True)
        self.gpio_dio.write(False)
        self.gpio_clk.write(False)

    def stop(self):
        self.gpio_clk.write(False)
        self.gpio_dio.write(False)
        self.gpio_clk.write(True)
        self.gpio_dio.write(True)

    def write_byte(self, data):
        #print("data={:x}".format(data))
        for i in range(8):
            self.gpio_clk.write(False)
            if data & 0x01:
                self.gpio_dio.write(True)
            else:
                self.gpio_dio.write(False)
            data >>= 1
            self.gpio_clk.write(True)

        self.gpio_clk.write(False)
        self.gpio_dio.write(True)
        self.gpio_clk.write(True)
        self.gpio_dio = GPIO(self.dio, "in")

        while self.gpio_dio.read():
            sleep(0.001)
            if self.gpio_dio.read():
                self.gpio_dio = GPIO(self.dio, "out")
                self.gpio_dio.write(False)
                self.gpio_dio = GPIO(self.dio, "in")
        self.gpio_dio = GPIO(self.dio, "out")
Exemplo n.º 12
0
class SPIComms(object):
    # Message headers defined for this communication protocl
    HEADERS = {"heartbeat": b'\x10', "message": b'\x20', "config": b'\x30'}

    def __init__(self, source):
        self.source = source
        self.data_length = self.source.get_flatten_length()

        # Store heartbeat received from microcontroller
        # Used to make sure that microcontroller is still available
        self.prev_heartbeat_count = 0
        self.heartbeat_count = 0

        # Create the data format message
        # Message is 4 bytes long
        # Defined in communication doc
        self.data_format_message = [0, self.data_length, 0, 0]

        self.spi = None
        self.signal_pin = None
        self.comm_thread = None

        self.max_error_count = 50

        self.data_lock = threading.Lock()
        self.data = np.zeros(shape=(self.data_length, ), dtype=np.float32)

    def start(self):
        # Open spidev0.0 device with mode 0 and max speed 100 kHz
        if (self.spi is None):
            self.spi = SPI("/dev/spidev0.0", 0, 30000)  #, bit_order= "lsb")

        # Open GPIO pin connection
        if (self.signal_pin is None):
            self.signal_pin = GPIO(6, "in")

        if (self.comm_thread is None):
            print("starting comms thread")
            self.comm_thread = threading.Thread(target=self._comm_thread_fn,
                                                daemon=True)
            self.comm_thread.start()

    def set_data(self, data):
        with self.data_lock:
            np.copyto(self.data, data)

    def _comm_thread_fn(self):
        while True:
            # Initialize the communications with the microcontoller
            self._comm_init()
            error_count = 0
            while error_count < self.max_error_count:

                # heartbeat header
                self.prev_heartbeat_count = self.heartbeat_count
                self.heartbeat_count = int.from_bytes(
                    self.spi.transfer(self.HEADERS["heartbeat"]), "little")

                if (self.heartbeat_count <= self.prev_heartbeat_count):
                    print("ERROR")
                    error_count += 1
                else:
                    error_count = 0

                if (self.signal_pin.read()):
                    print("Transferring data")
                    self.spi.transfer(self.HEADERS['message'])
                    with self.data_lock:
                        self.data = self.source.tobytes()
                        self.spi.transfer(self.data)

                time.sleep(0.01)

    def _comm_init(self):
        # Flags to store where in the comm init program is
        init_signal_received = False

        print("Starting init")

        # Create an array storing the responses received from the microcontroller
        responses = [b'\x00', b'\x00', b'\x00']

        # Loop init process
        while not init_signal_received:
            # Pop the first response and append the last response
            responses.pop(0)
            responses.append(self.spi.transfer(b'\xFF'))

            startTime = time.time()

            # Read pin for 100 ms to check for correct response
            # Correct response is high on the signal pin and 0xFF, 0xFE, 0xFD heartbeat sequence
            while time.time() - startTime < 0.1:
                if (self.signal_pin.read()
                        and responses == [b'\xff', b'\xfe', b'\xfd']):
                    init_signal_received = True
                    break

        print("Received signal, waiting for heartbeat")
        self.spi.transfer(self.HEADERS["config"])
        responses = self.spi.transfer(b'\x00\x00\x00\x00')

        # Store the last two heartbeats
        self.prev_heartbeat_count = responses[2]
        self.heartbeat_count = responses[3]
        print("Heartbeat received, successful init!")

        # Wait until we receive request for data
        while (not self.signal_pin.read()):
            time.sleep(0.1)

        print("Received high on pin")
        print("Transmitting format message")
        # Transferring data format message
        self.spi.transfer(self.HEADERS["config"])
        time.sleep(1)

        self.spi.transfer(self.data_format_message)
Exemplo n.º 13
0
from periphery import GPIO
dir(GPIO)
gpio4_12 = GPIO("/dev/gpiochip4", 12, "in")
gpio_green = GPIO("/dev/gpiochip1", 24, "out")
gpio_red = GPIO("/dev/gpiochip1", 25, "out")
gpio_blue = GPIO("/dev/gpiochip2", 23, "out")


while True:
    #value = gpio4_12.read()
    event_gpio = gpio4_12.read()
    print(str(event_gpio))
    #print(str(value))
"""Digital IO (Input/Output) using periphery"""
from periphery import GPIO

# 根据具体板卡的LED灯和按键连接修改使用的Chip和Line
LED_CHIP = "/dev/gpiochip3"
LED_LINE_OFFSET = 19

BUTTON_CHIP = "/dev/gpiochip4"
BUTTON_LINE_OFFSET = 1

led = GPIO(LED_CHIP, LED_LINE_OFFSET, "out")
button = GPIO(BUTTON_CHIP, BUTTON_LINE_OFFSET, "in")

try:
    while True:
        led.write(button.read())
finally:
    led.write(True)
    led.close()
    button.close()
Exemplo n.º 15
0
def main():
    print("initializing")
    pool = ThreadPool(processes=1)
    #Time operator have to push button after product is detected
    IMG_SAVE_DELAY = 500
    #This is used to signal that if operator dont push button then save image to approved folder
    flagPhotoSensor = False
    #Resolution on image
    resolution = (1280, 720)
    #Paths to put images
    path_approved = '/media/storage/good/'
    path_not_approved = '/media/storage/bad/'
    #Create camera object that takes images and store in approved or not approved folder
    camera = Camera(resolution, 'png', path_approved, path_not_approved)
    #GPIO stuff
    on_off = GPIO(7, 'in')
    disallowed_img = GPIO(138, 'in')
    disallowed_img.edge = 'rising'
    photoSensor = GPIO(140, 'in')
    photoSensor.edge = 'rising'
    #Create Display object
    display = Display()
    #Variable to handle debounce on input from photosensor
    lastPhotoSensorValue = False
    #Variable to handle debounce on input from operator button
    lastOperatorBtnValue = False
    #Get time in ms
    currentTime_ms = lambda: int(round(time.time() * 1000))
    #Calculate new time - old time to get time difference between two events
    deltaTime_ms = lambda oldTime_ms: int(round(time.time() * 1000)
                                          ) - oldTime_ms
    #Store time to calculate time difference
    oldTime_ms = currentTime_ms()
    print("initialization done")

    #Run forever
    while True:
        #If system is turned on by switch, run program
        display.off()
        if on_off.read() or True:
            print("System started")
            #Make sure no old values are stored
            flagPhotoSensor = False
            camera.camera.start()
            #Stay in loop as long as system is turned on
            while on_off.read() or True:

                #If there is a product in front of camera, take a picture and record the time
                if photoSensor.read(
                ) and not lastPhotoSensorValue and not flagPhotoSensor:

                    #img = camera.camera.get_image()
                    async_img = pool.apply_async(camera.take_image)
                    oldTime_ms = currentTime_ms()
                    #Save that photo sensor has been high
                    flagPhotoSensor = True

                #If operator push button before IMG_SAVE_DELAY time, save image to not approved folder
                #and blink red light once to inform operator
                while deltaTime_ms(oldTime_ms) <= IMG_SAVE_DELAY:
                    if disallowed_img.read() and not lastOperatorBtnValue:
                        img = async_img.get()
                        threading.Thread(target=display.show_img,
                                         args=(img, False)).start()
                        camera.save_img(img, False)
                        flagPhotoSensor = False

                lastOperatorBtnValue = disallowed_img.read()

                #if operator dont push button before IMG_SAVE_DELAY time run out, save
                #image to approved folder and blink green light.
                if (deltaTime_ms(oldTime_ms) >
                        IMG_SAVE_DELAY) and flagPhotoSensor:
                    img = async_img.get()
                    threading.Thread(target=display.show_img,
                                     args=(img, True)).start()
                    camera.save_img(img, True)
                    flagPhotoSensor = False

            camera.camera.stop()
            lastPhotoSensorValue = photoSensor.read()
Exemplo n.º 16
0
class Pin:
    """Pins dont exist in CPython so...lets make our own!"""

    IN = "in"
    OUT = "out"
    LOW = 0
    HIGH = 1
    PULL_NONE = 0
    PULL_UP = 1
    PULL_DOWN = 2

    id = None
    _value = LOW
    _mode = IN

    def __init__(self, pin_id):
        self.id = pin_id
        if isinstance(pin_id, tuple):
            self._num = int(pin_id[1])
            self._chippath = "/dev/gpiochip{}".format(pin_id[0])
        else:
            self._num = int(pin_id)
            self._chippath = "/dev/gpiochip0"
        self._line = None

    def __repr__(self):
        return str(self.id)

    def __eq__(self, other):
        return self.id == other

    def init(self, mode=IN, pull=None):
        """Initialize the Pin"""
        if mode is not None:
            if mode == self.IN:
                self._mode = self.IN
                if self._line is not None:
                    self._line.close()
                self._line = GPIO(self._chippath, int(self._num), self.IN)
            elif mode == self.OUT:
                self._mode = self.OUT
                if self._line is not None:
                    self._line.close()
                self._line = GPIO(self._chippath, int(self._num), self.OUT)
            else:
                raise RuntimeError("Invalid mode for pin: %s" % self.id)

            if pull is not None:
                if pull == self.PULL_UP:
                    raise NotImplementedError(
                        "Internal pullups not supported in periphery, "
                        "use physical resistor instead!"
                    )
                if pull == self.PULL_DOWN:
                    raise NotImplementedError(
                        "Internal pulldowns not supported in periphery, "
                        "use physical resistor instead!"
                    )
                raise RuntimeError("Invalid pull for pin: %s" % self.id)

    def value(self, val=None):
        """Set or return the Pin Value"""
        if val is not None:
            if val == self.LOW:
                self._value = val
                self._line.write(False)
                return None
            if val == self.HIGH:
                self._value = val
                self._line.write(True)
                return None
            raise RuntimeError("Invalid value for pin")
        return self.HIGH if self._line.read() else self.LOW
Exemplo n.º 17
0
from periphery import GPIO

gpio_get = GPIO(38, "in")

while 1:
    value = gpio_get.read()
    print(value)

gpio_get.close()
Exemplo n.º 18
0
# Robot Code for Tech Garage
# Author: Danny Dasilva
# License: Public Domain

from app.Robot import Controller, Py_Hat
from My_Custom_Code import my_custom_teleop, my_custom_autonomous
from time import sleep
import os

from periphery import GPIO
from time import sleep

gpio_in = GPIO(8, "in")

while True:
    value = gpio_in.read()
    if value == False:
        break
    else:
        print("custom code")
        #my_custom_teleop()
        my_custom_autonomous()
    sleep(.01)

gpio_in.close()

#controller class
controller = Controller()

# initialize Pi Hat
hat = Py_Hat(address=96)
Exemplo n.º 19
0
from periphery import GPIO
enable_switch = GPIO(160, "in")

# === DEBUG ===
flag = False
count = 1

cap = cv2.VideoCapture(0)
# ===
pastAngles = [0, 0]  # used to smooth out
startUp = True
velo = 700  #between 600 and 800 for forwards

while (cap.isOpened()):
    # ON Button code
    while (not enable_switch.read()):
        # We want to pause the program
        pwm.set_pwm(steer, 0, steer_mid)
        pwm.set_pwm(gas, 0, gas_mid)
        time.sleep(1)
        startUp = False

    # Image Capture
    _, frame = cap.read()
    #frame=cv2.imread('obsflipdummy.png')

    saveFrame = frame

    frame = resizeMe(frame, 3)
    #frame = frame[frame.shape[0]/2:frame.shape[0]-1,:,:]
    #frame=np.uint8((frame.astype(float)/16.)**2)