from gpiozero import DigitalInputDevice

rain_sensor = DigitalInputDevice(6)
BUCKET_SIZE = 0.2794
count = 0

def bucket_tipped():
  global count
  count = count + 1
  print (count * BUCKET_SIZE)


rain_sensor.when_activated = bucket_tipped
Example #2
0
from gpiozero import DigitalInputDevice
from time import sleep
import math

# Connect windspeed on one side to GND and another to GPIO pin
# No resistor needed... Detection on LOW/FALSE
pinReadSpeed = 26       # GPIO Pin for input
count = 0               # Rotation Counter
radius_cm = 9.0		# Radius of the anemometer
interval = 1.0     	# Duration to report on speed
ADJUSTMENT = 2   	# Adjustment for weight of cups

CM_IN_A_KM = 100000.0
SECS_IN_AN_HOUR = 3600

wind_speed_sensor = DigitalInputDevice(pinReadSpeed,pull_up=True)

def calculate_speed(time_sec):
    global count
    circumference_cm = (2 * math.pi) * radius_cm
    rotations = count / 2.0
    dist_km = (circumference_cm * rotations) / CM_IN_A_KM
    km_per_sec = dist_km / time_sec
    km_per_hour = km_per_sec * SECS_IN_AN_HOUR

    return km_per_hour * ADJUSTMENT

def spin():
    global count
    count = count + 1
def main():
    pi = np.math.pi
    i = 0
    rightIRSensor = DigitalInputDevice(12)
    leftIRSensor = DigitalInputDevice(16)

    # IR_tracer      8   L
    #               7   R
    rightIRTracerSensor = DigitalInputDevice(7)
    leftIRTracerSensor = DigitalInputDevice(8)

    # DisatanceSensor pin   21 T
    #                      20 E
    distanceSensor = DistanceSensor(21, 20)

    # Motors
    motor_left = Motor(18, 23)
    motor_right = Motor(24, 25)

    forwardpin = False

    def getDistance():
        return distanceSensor.distance

    def forward(left=1.0, right=1.0):
        motor_left.forward(left)
        motor_right.forward(right)

    def back(left=1.0, right=1.0):
        motor_left.backward(left)
        motor_right.backward(right)

    def turnRight(x=1.0, y=1.0):
        motor_left.forward(x)
        motor_right.backward(y)

    def turnLeft(back=1.0, forward=1.0):
        motor_left.backward(back)
        motor_right.forward(forward)

    def stop():
        motor_left.stop()
        motor_right.stop()

    def lIRsensor():
        return rightIRSensor.value

    def rIRsensor():
        return leftIRSensor.value

    def rIRTracerSensor():
        return rightIRTracerSensor.value

    def lIRTracerSensor():
        return leftIRTracerSensor.value

    def saveframe(name, frame):
        cv2.imwrite(str(name) + '/png', frame)

    def halfRightTurn():
        turnRight(1, 0.5)
        time.sleep(0.6)
        stop()

    def hougeline(frame, i=0):
        kernel = np.ones((3, 3), np.uint8)
        localfram = frame
        # frame = cv2.dilate(frame, kernel,iterations=3)
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
        # blur = cv.GaussianBlur(frame, (5, 5), 0)
        blur = cv2.medianBlur(frame, 5)
        canny = cv2.Canny(blur, 150, 150, apertureSize=3)
        cv2.imshow('canny', canny)
        lines = cv2.HoughLines(canny, 1, pi / 180, 50)  # srn=80, stn=200)

        if lines is not None:
            print("Len of lines:", len(lines))

        if lines is not None:
            # sumtheta = 0
            sumx1 = 0
            sumx2 = 0
            sumy1 = 0
            sumy2 = 0
            counter = len(lines)
            for line in lines:
                # print(line)

                rho, theta = line[0]
                # print(theta/pi*180)
                if line is not None:
                    a = np.cos(theta)
                    b = np.sin(theta)
                    x0 = a * rho
                    y0 = b * rho
                    scalar = 1000
                    x1 = int(x0 + scalar * (-b))
                    y1 = int(y0 + scalar * (a))

                    x2 = int(x0 - scalar * (-b))
                    y2 = int(y0 - scalar * (a))
                    if abs(y2 - y1) < scalar / 10:
                        counter -= 1
                        continue
                    if abs(x2 - x1) < scalar / 20:
                        counter -= 1
                        continue
                    sumy1 += y1
                    sumx1 += x1
                    sumx2 += x2
                    sumy2 += y2
                    cv2.line(localfram, (x1, y1), (x2, y2), (0, 0, 255), 2, 4)

            try:
                dely = (sumy2 - sumy1) / counter
                delx = (sumx2 - sumx1) / counter

                cv2.line(localfram, (int(sumx1 / counter), int(sumy1 / counter)),
                         (int(sumx2 / counter), int(sumy2 / counter)), (0, 255, 0), 2, 4)
                print('dely=', dely)
                print('delx=', delx)
                font = cv2.FONT_HERSHEY_PLAIN
                cv2.putText(localfram, str(dely), (0, 50), font, 4, (255, 0, 0), 4)
                cv2.putText(localfram, str(delx), (0, 100), font, 4, (255, 255, 0), 4)
                angel = (np.math.asin(dely / delx) / (pi / 2) * 180)
                cv2.putText(localfram, str(angel), (0, 150), font, 4, (0, 255, 255), 4)

                i += 1

                """WRITE TO FILE"""
                # cv2.imwrite((str(i) + '.png'), localfram)
                print(str(i) + '.png')
            except OSError as err:
                print("OS error: {0}".format(err))
            except ValueError:
                print("Could not convert data to an integer.")
            except:
                print("Unexpected error:", sys.exc_info()[0])
            # time.sleep(0.1)

        cv2.imshow('output', localfram)
        return localfram, i

    def hougelinep(frame, i=0):
        kernel = np.ones((3, 3), np.uint8)
        localfram = frame
        # frame = cv2.dilate(frame, kernel,iterations=3)
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
        # blur = cv.GaussianBlur(frame, (5, 5), 0)
        canny = cv2.Canny(frame, 200, 150, apertureSize=3)
        cv2.imshow('canny', canny)
        lines = cv2.HoughLinesP(canny, 1, pi / 180, 10, minLineLength=5, maxLineGap=5)  # srn=80, stn=200)

        if lines is not None:
            print("Len of lines:", len(lines))

        if lines is not None:
            sumx1 = 0
            sumx2 = 0
            sumy1 = 0
            sumy2 = 0
            counter = len(lines)
            for line in lines:
                if line is not None:
                    x1, y1, x2, y2 = line[0]
                    sumy1 += y1
                    sumx1 += x1
                    sumx2 += x2
                    sumy2 += y2
                    cv2.line(localfram, (x1, y1), (x2, y2), (0, 0, 255), 2, 4)
            try:
                cv2.line(localfram, (int(sumx1 / counter), int(sumy1 / counter)),
                         (int(sumx2 / counter), int(sumy2 / counter)), (0, 255, 0), 2, 4)
                i += 1
            except OSError as err:
                print("OS error: {0}".format(err))
            except ValueError:
                print("Could not convert data to an integer.")
            except:
                print("Unexpected error:", sys.exc_info()[0])

        # print('delx=', delx)

        # print(sumtheta / counter)
        # time.sleep(0.5)
        # pprint.pprint(lines)
        # time.sleep(1)
        time.sleep(0.1)
        cv2.imshow('output', localfram)
        return localfram, i

    # The video feed is read in as a VideoCapture object
    # cap = cv2.VideoCapture("outcpp.avi")
    red_val = 0
    green_val = 65

    stream = io.BytesIO()
    my_file = open('my_image.jpg', 'wb')

    cap = cv2.VideoCapture(0)
    with picamera.PiCamera() as camera:
        camera.resolution = (1920, 1080)
        camera.framerate = 32
        camera.start_preview()
        time.sleep(2)
        # camera.capture(my_file)
        camera.capture(stream, format='jpeg')
        # define range of RED color in HSV
    halfRightTurn()

    while (True):
        # Capture frame-by-frame
        data = np.fromstring(stream.getvalue(), dtype=np.uint8)
        ret, frame = cap.read(data)

        try:
            frame2 = frame
            frame = cv2.resize(frame, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_CUBIC)
            width, height = frame.shape[:2]
            frame = frame[int(width / 2):width, 0:height]
        except:
            continue

        hougelinefram, i = hougeline(frame, i)
        cv2.imshow('original', frame2)
        if cv2.waitKey(10) & 0xFF == ord('q'):
            cv2.waitKey(0)
        if cv2.waitKey(10) & 0xFF == ord('w'):
            print('w')
    cv2.waitKey(1)
    cv2.destroyAllWindows()

    cap.release()
Example #4
0
if not PUMP_CALIBRATION:
    # get the session information (timeout, ratio, nexratio, etc...) from 'session_configuration.csv' file under python directory
    sessioninfo = get_sessioninfo(RatID)

    while (len(sessioninfo) == 0):
        RatID = input("command ID not found please rescan the id: ")[-8:]
        sessioninfo = get_sessioninfo(RatID)

    sessioninfo = sessioninfo[0]

    mover = PumpMove()
    forwardbtn = Button("GPIO5")
    backwardbtn = Button("GPIO27")

    BACKWARD_LIMIT_BTN = "GPIO23"
    BACKWARD_LIMIT = DigitalInputDevice(BACKWARD_LIMIT_BTN)

    def forward():
        while forwardbtn.value == 1:
            mover.move("forward")

    def backward():
        while BACKWARD_LIMIT.value != 1:
            mover.move("backward")

    forwardbtn.when_pressed = forward
    backwardbtn.when_pressed = backward

    #push syringe to wet spout
    mover.move("forward")
    mover.move("forward")
Example #5
0
if __name__ == "__main__":
    # Tunables
    fps = 10

    # Video Reader Initial Setup
    cap = cv2.VideoCapture(0)  # Create video capture object with 0th camera
    frame_size = (int(cap.get(3)), int(cap.get(4)))

    # Video Writer Initial Setup
    fourcc = cv2.VideoWriter_fourcc(
        *'MJPG')  # Create VideoWriter format object with smallest file size

    # PIR Setup
    PIRPinNum = 26
    PIR = DigitalInputDevice(PIRPinNum, pull_up=False)

    # LED Setup
    LEDPinNum = 19
    LED = OutputDevice(LEDPinNum)

    INACTIVE_THRESHOLD = 10 * fps  # frames
    inactive_time = 10 * fps  # frames
    rolling = False

    while (cap.isOpened()):

        # if there is movement and we're not rolling
        if PIR.is_active and not rolling:
            inactive_time = 0
            rolling = True
Example #6
0
    def __init__(self, pin):
        self._value = 0

        self.encoder = DigitalInputDevice(pin)
        self.encoder.when_activated = self._increment
        self.encoder.when_deactivated = self._increment
Example #7
0
    def __init__(self, nursery: trio.Nursery):
        self._nursery = nursery  # type: trio.Nursery
        self._operation_mode = None
        self._system_state = None
        self._sensor_data = {
            'temperature': None,
            'pressure': None,
            'humidity': None,
            'slope': None,
            'num_satellites': None,
            'latitude': None,
            'longitude': None,
            'altitude': None,
            'message': None,
            'rssi': None,
            'session_state': None,
            'session_substate': None,
            'battery': None,
            'motor_current': None
        }

        # Traction system ----------------
        self._tractor = TractionSystem(  # type: TractionSystem
            forward_r=MOTOR_R_FORWARD_PIN,
            backward_r=MOTOR_R_BACKWARD_PIN,
            enable_r=MOTOR_R_ENABLE_PIN,
            forward_l=MOTOR_L_FORWARD_PIN,
            backward_l=MOTOR_L_BACKWARD_PIN,
            enable_l=MOTOR_L_ENABLE_PIN,
            enable_global=DRIVER_ENABLE_PIN)

        # ADC -----------------------------
        alert_ready = DigitalInputDevice(ALERT_READY_PIN, pull_up=True)
        bus = smbus.SMBus(DEVICE_BUS)
        self._adc = ADS1015(bus,
                            DEVICE_ADDRESS,
                            alert_ready,
                            channel=RADIO_CHANNEL)  # type: ADS1015

        # Radio System -------------------
        self._radio_system = RadioDetection(
            self._adc,
            self._nursery,
            notification_callbacks=[self.radio_listener])
        self._radio_system.subscribe(notification_callbacks=[radio_printer
                                                             ])  # DEBUG ONLY

        # SenseHat ------------------------
        self._sensors = SenseHatWrapper(nursery, data=self._sensor_data)

        # GPS -----------------------------
        # Lat/long/alt data is updated automatically, the satellite list is not used for now
        self._gps = GPS(GPS_PORT, nursery, data=self._sensor_data)

        # Transceiver --------------------
        self._transceiver = ReceptorSystem(
            RX_INTERRUPTION_PIN,
            TX_DEVICE,
            nursery,
            notification_callbacks=[self.transceiver_listener],
            data=self._sensor_data)

        # Battery & current measurements -----------
        self._battery = BatteryMeasure(nursery,
                                       self._adc,
                                       BATTERY_CHANNEL,
                                       data=self._sensor_data)
        self._battery.subscribe(notification_callbacks=[self.battery_listener])
        self._current_meas = CurrentMeasure(nursery,
                                            self._adc,
                                            CURRENT_CHANNEL,
                                            data=self._sensor_data)
        self._current_meas.subscribe(
            notification_callbacks=[self.current_listener])

        # Server -------------------------
        self._server = Server(SERVER_ADDRESS,
                              SERVER_PORT,
                              self._sensor_data,
                              ROVER_ID,
                              nursery,
                              error_callbacks=[self.server_error])

        # Command system -----------------
        self._commands = CommandSystem(
            COMMAND_PORT,
            nursery,
            notification_callbacks=[self.command_listener])

        # --------------- Start in idle mode ------------
        self._change_mode(self.MODE_IDLE)