예제 #1
0
def main():
    common.init_logging(logger)

    parser = common.init_argparser("Data collection for honey.fitness")
    parser.add_argument("--gpio-pin", default=4, help="Sensor pin number")
    args = parser.parse_args()

    data_path = common.init_local_data_path(args.data_path)
    logger.info(f"Using {data_path} for local data storage")

    minute_timer = RepeatingTimer(60, on_save, args=(data_path, ))
    minute_timer.start()

    sensor = LineSensor(args.gpio_pin)
    sensor.when_line = on_magnet
    logger.info(f"Monitoring GPIO {args.gpio_pin} for rotation counts")

    logger.info("Starting monitor")
    try:
        signal.pause()
    except KeyboardInterrupt:
        pass
    minute_timer.cancel()
    logger.info("Stopped monitor")
예제 #2
0
파일: l.py 프로젝트: DmytroFiliuk2/d
from gpiozero import Robot, LineSensor
from signal import pause
from time import sleep

robot = Robot(left=(7, 8), right=(9, 10))
left_sensor = LineSensor(17)
right_sensor = LineSensor(27)

left_sensor.when_line = function_name_to_call
left_sensor.when_no_line = other_function_name_to_call

#from gpiozero import Robot, LineSensor
#from time import sleep

#robot = Robot(left=(7, 8), right=(9, 10))
#left_sensor = LineSensor(17)
#right_sensor= LineSensor(27)

while True:
    left_detect = int(left_sensor.value)
    right_detect = int(right_sensor.value)
    print(left_detect, right_detect)
예제 #3
0
from gpiozero import LineSensor
from signal import pause
from time import sleep

onLine = False
sensor = LineSensor(4)

sensor.when_line = lambda: getState(True)
sensor.when_no_line = lambda: getState(False)


def getState(data):
    global onLine
    onLine  = data
    if data:
        print("data line")
    else:
        print("data not_line")

i = 0

while True:
    i+=1
    if onLine:
        print("line")
    else:
        print("not_line")
    print ("%d times " % i)
    sleep(1)
예제 #4
0
    delta_sec = time_detected - prev_time
    rpm = 60 / delta_sec
    print(rpm)


async def test(websocket, path):
    old_rpm = 0
    global rpm, count
    while True:
        if rpm == old_rpm:
            count += 1
        else:
            count = 0
        if count > 3:
            rpm = 0
        else:
            old_rpm = rpm
            now = str(rpm)
            await websocket.send(now)
            time.sleep(1)


start_server = websockets.serve(test, '127.0.0.1', 8080)

sensor = LineSensor(15, queue_len=1)
sensor.when_line = lambda: line_detected()
sensor.when_no_line = lambda: print('No line detected')

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
예제 #5
0
    normal_mode = not normal_mode

    if normal_mode:
        set_lcd("Mode: normal")
        sleep(1)
        set_lcd("")
    else:
        set_lcd("Mode: app")
        sleep(1)
        set_lcd("Count: " + str(count))


# Run
reset()
button.when_pressed = switch_mode
ir.when_line = activate


# Webhook
@app.route('/webhook', methods=['POST'])
def respond():
    global count

    if request.json['event_name'] == 'item:completed':
        count += 1
    elif request.json['event_name'] == 'item:uncompleted':
        count -= 1

    if not normal_mode:
        set_lcd("Count: " + str(count))
예제 #6
0
# CamJam EduKit 3 - Robotics
# Worksheet 5 – Line Detection

from gpiozero import LineSensor # Import the LineSensor from the GPIOZero Library
from signal import pause # import pause frm the signal library

#set up the GPIO pin for the line sensor
sensor = LineSensor(25)


sensor.when_line = lambda: print('The sensor is seeing a black surface')
sensor.when_no_line = lambda: print('The sensor is seeing a white surface')
pause()

# If you press CTRL+C, cleanup and stop
except KeyboardInterrupt:
    GPIO.cleanup()
        mqtt_update(0.5, mqtt_topic)
    except:
        logging.warn("Failed to update influxdb")

    meter_lastupdate = now
    logging.info("Updated water meter")


def call1():
    logging.debug("Line detected - {}".format(meter_sensor._queue.queue))
    update()


def call2():
    logging.debug("No line detected - {}".format(meter_sensor._queue.queue))
    update()


# Initiate line sensor from GPIO. We use 20Hz and a queue length of 5, such
# that we have an effective sample rate of 5 Hz (supersampled 5x). Default
# is 100 Hz but this takes more CPU than needed for this slow meter
logging.debug("Initiating linesensor, queue_len 10, sample @ 40Hz")
meter_sensor = LineSensor(4, queue_len=10, sample_rate=40)

meter_sensor.when_line = call1
meter_sensor.when_no_line = call2

# Start waiting loop
logging.info("Starting waiting loop forever")
pause()
예제 #8
0
from gpiozero import LineSensor,LED
from signal import pause

led = LED(12)
sensor = LineSensor(21)
sensor.when_line = led.on
sensor.when_no_line = led.off

pause()
예제 #9
0
#!/usr/bin/env python3
# Test script for debugging gpio interface on e.g. raspberry pir

print('starting script')
import time
from gpiozero import LineSensor
from signal import pause

import gpiozero
print('making sensor')
#pir = MotionSensor(4)
sensor = LineSensor(4)


def call1():
    print("Line detected @ {}".format(time.time()))


def call2():
    print("No line detected @ {}".format(time.time()))


print('registering callbacks')
sensor.when_line = call1
sensor.when_no_line = call2

print('starting handler')
pause()
예제 #10
0
            if rightisoverwhite:
                # Exit the seekline() function returning
                # True - the line was found
                print("Right found")
                return True

        # Increase the seek count
        seekcount += 1

    print("Right lost.")
    rightlinelost = True
    return False


# Tell the program what to do with a white line is seen
linesensorright.when_line = blacknotseenright
# And when no line is seen
linesensorright.when_no_line = blackseenright

# Tell the program what to do with a white line is seen
linesensorleft.when_line = blacknotseenleft
# And when no line is seen
linesensorleft.when_no_line = blackseenleft

try:
    while True:
        if not rightisoverwhite and not rightlinelost:
            seekwhiteright()
            sleep(0.1)
        if not leftisoverwhite and not leftlinelost:
            seekwhiteleft()
예제 #11
0
        line_sensor.wait_for_line(seek_time)
        if line_sensor.value < 0.5:
            ret = True
            break
        else:
            direction = not direction
            if direction:
                seek_count += 1
            continue

    return ret

parser.add_option("-s", "--speed", type="float", dest="speed")
(options, args) = parser.parse_args()
if options.speed != None:
    speed = options.speed

line_sensor.when_line = lambda: move.forward()
line_sensor.when_no_line = lambda: move.stop()

signal.signal(signal.SIGINT, exit_gracefully)

while True:
    move.forward(speed)
    line_sensor.wait_for_no_line()
    if not seek_line():
        print("Can't find any line")
        break

exit_gracefully()
예제 #12
0
from gpiozero import LineSensor, Robot
from time import sleep, time

robot = Robot(left=(7, 8), right=(9, 10))
line = LineSensor(18)

speed = 0.5

def on_line():
    robot.stop()
    sleep(0.2)
    robot.forward(speed)

def find_line():
    robot.stop()
    sleep(0.2)
    robot.right()


line.when_line = on_line
line.when_no_line = find_line
예제 #13
0
 def main(self):
     sensor = LineSensor(14)
     sensor.when_line = lambda: self.eventhandler()
     sensor.when_no_line = lambda: print('No line detected')
     pause()
예제 #14
0
 def main(self):
     sensor = LineSensor(14, queue_len=1)
     sensor.when_line = lambda: self.line_detected()
     sensor.when_no_line = lambda: print('No line detected')
     pause()
예제 #15
0

def linenotseenfront():
    print("No line seen front")


def lineseenback():
    print("Line seen back")


def linenotseenback():
    print("No line seen back")


# Tell the program what to do with a line is seen
sensorFront.when_line = linenotseenfront
# And when no line is seen
sensorFront.when_no_line = lineseenfront

# Tell the program what to do with a line is seen
sensorBack.when_line = linenotseenback
# And when no line is seen
sensorBack.when_no_line = lineseenback

try:
    # Repeat the next indented block forever
    while True:
        time.sleep(10)

# If you press CTRL+C, cleanup and stop
except KeyboardInterrupt:
예제 #16
0
from gpiozero import LineSensor
from signal import pause
import time

sensor = LineSensor(4)

while True:
    sensor.when_line = lambda: print('Line detected')
    sensor.when_no_line = lambda: print('No line detected')

예제 #17
0
from gpiozero import Robot, LineSensor
from signal import pause

robot = Robot(left=(6, 13), right=(21, 20))
left_sensor = LineSensor(4)
right_sensor = LineSensor(26)

robot.forward(0.4)


def movfront():
    robot.forward(0.4)


def leftmove():
    robot.left(0.3)


def rightmove():
    robot.right(0.3)


left_sensor.when_line = leftmove
right_sensor.when_line = rightmove

left_sensor.when_no_line = movfront
right_sensor.when_no_line = movfront

pause()
예제 #18
0
from gpiozero import LineSensor, DigitalInputDevice
from signal import pause
from time import sleep


def found():
    print("Line has been broken")


def nofound():
    print("Line is intact")


sensor = LineSensor(4)

sensor.when_line = nofound
sensor.when_no_line = found

pause()
예제 #19
0
#!/usr/bin/python3
import os
from gpiozero import LineSensor
from signal import pause

# script that uses gpiozero library with the LineSensor 'drivers' and
# functions
# when IR sensor detect somethig between the sensor and her range we save the
# time in line.log
# when IR sensor no detect something between the sensor and her range we save
# the time in noline.log

# este programa usa la libreria gpiozero que usa unas funciones especificas
# para el sensor IR
# cuando el sensor IR detecta que hay algo entre el y su rango de deteccion
# guarda la fecha en line.log
# cuando el sensor detecta que ha dejado de haber algo entre el sensor
# y su rango de alcance guarda la fecha en noline.log

directorio = "/tmp/miriadax/"

sensor = LineSensor(26)
sensor.when_line = lambda: os.system('date +"%s" > ' + directorio + '/line.log'
                                     )
sensor.when_no_line = lambda: os.system('date +"%s" >' + directorio +
                                        '/noline.log')
pause(
)  # it wait for another signal from sensor // se mantiene a la espera de otra señal del sensor
예제 #20
0
counter = 0


def zaehler():
    global counter
    counter = counter + 1
    #print(counter,"x")
    if counter == 12:
        global kwh
        kwh = kwh + 1
        zeile = str(
            datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S,")) + str(
                kwh / 10) + "\n"
        #print(zeile)
        f = open(datetime.datetime.now().strftime("%Y-%W") + ".csv", 'a+')
        f.write(zeile)
        f.close()
        global counter
        counter = 0
    if datetime.datetime.now().strftime("%w") == 1 and kwh > 250:
        global kwh
        kwh = 0


sensor = LineSensor(4)

sensor.when_line = zaehler

pause()
예제 #21
0
# CamJam EduKit 3 - Robotics
# Line Follower GPIO Zero version (untested)
# by Neil Bizzell (@PiVangelist)

from gpiozero import LineSensor, CamJamKitRobot  # import LineSensor and CamJamKit Robot objects from GPIO Zero library
from signal import pause  # import pause from signal library

#define sensor as instance of LineSensor Class and define pin as Pin 25
sensor = LineSensor(25)
#Define robot as instance of CamJamKit Robot Class
robot = CamJamKitRobot()


def left():
    robot.value(1, 0)


def right():
    robot.value(0, 1)


sensor.when_line = left()
sensor.when_no_line = right()
pause()
        # The robot has not found the black line yet, so stop
        robot.stop()

        # Increase the seek count
        seekcount += 1

    # The line wasn't found, so return False
    robot.stop()
    print("The left line has been lost - relocate your robot")
    linelost = True
    return False


# Tell the program what to do with a line is seen
linesensorright.when_line = lineseenright
# And when no line is seen
linesensorright.when_no_line = linenotseenright

# Tell the program what to do with a line is seen
linesensorleft.when_line = lineseenleft
# And when no line is seen
linesensorleft.when_no_line = linenotseenleft

try:
    # repeat the next indented block forever
    robot.value = motorforward
    while True:
        if rightisoverblack and not linelost:
            seeklineright()
        if leftisoverblack and not linelost:
예제 #23
0
from gpiozero import LED, LineSensor
from time import sleep

red = LED(17)
lsensor = LineSensor(23)
rsensor = LineSensor(16)

lsensor.when_line = lambda: red.on()
lsensor.when_no_line = lambda: red.off()

while True:
    sleep(0.02)
예제 #24
0
from gpiozero import LineSensor
from signal import pause

sensor = LineSensor(21)
sensor.when_line = lambda: print('Object Detected')
sensor.when_no_line = lambda: print('Object Not Detected')

pause()
예제 #25
0
#LineSensor test

from gpiozero import LineSensor
from time import sleep
from signal import pause

def lineDetected():
    print('line detected')


def noLineDetected():
    print('no line detected')

sensor = LineSensor(14)

sensor.when_line = lineDetected
sensor.when_no_line = noLineDetected

pause()

sensor.close()
from gpiozero import Robot, LineSensor
from signal import pause

robot = Robot(left=(7, 8), right=(9, 10))
left_sensor = LineSensor(17)
right_sensor = LineSensor(27)

left_sensor.when_line = robot.left
right_sensor.when_line = robot.right
left_sensor.when_no_line = robot.forward
right_sensor.when_no_line = robot.forward

pause()
예제 #27
0
        # Increase the seek count
        seekcount += 1

        # Change direction
        direction = not direction

    # The line wasn't found, so return False
    robot.stop()
    print("The line has been lost - relocate your robot")
    linelost = True
    return False


# Tell the program what to do with a line is seen
linesensor.when_line = lineseen
# And when no line is seen
linesensor.when_no_line = linenotseen

try:
    # repeat the next indented block forever
    robot.value = motorforward
    while True:
        if not isoverblack and not linelost:
            seekline()


# If you press CTRL+C, cleanup and stop
except KeyboardInterrupt:
    exit()
예제 #28
0
from robot import Robot
from time import sleep
from gpiozero import LineSensor

r = Robot()

lsensor = LineSensor(23, pull_up=True)
rsensor = LineSensor(16, pull_up=True)

lsensor.when_line = r.stop_motors
rsensor.when_line = r.stop_motors

r.set_left(60)
r.set_right(60)
while True:
    sleep(0.02) 
예제 #29
0
from robot import Robot
from time import sleep
from gpiozero import LineSensor

r=Robot()

lsensor=LineSensor(23)
rsensor=LineSensor(16)

lsensor.when_line=r.turnOffMotors
rsensor.when_line=r.turnOffMotors

r.set_left(-40)
r.set_right(-40)

while True:
    sleep(0.02)
예제 #30
0
factory = None
led     = None
alt_in  = None

if hostpi is not None:
    factory = PiGPIOFactory(host=hostpi)

loop = LineSensor(estop_pin, pin_factory=factory, threshold=threshold, sample_rate=sample_rate, queue_len=queue_len, pull_up=False)

def do_stop():
    stop()


if signal_pin is not None:
    led = LED(signal_pin, pin_factory=factory)
    loop.when_no_line = led.off
    loop.when_line = led.on

if estop_pin_alt is not None:
    alt_in = Button(estop_pin_alt, pin_factory=factory, bounce_time=0.01, pull_up=True)
    alt_in.when_pressed = do_stop

rospy.loginfo('estop_loop watching pin ' + str(estop_pin) + ' for broken loop')

while not rospy.is_shutdown():
    if not loop.value:
        do_stop()
    sleep(0.05)