Exemplo n.º 1
0
def human(w):
    if(w > 250):
        control.append(2)
    elif( w > 200 and w <= 250):
        control.append(1)
    else:
        control.append(0)
    
    if len(control) == 10:
        control.remove(control[0])

    if control.count(2) > 2:
        print("Stop")
        GPIO.output(15, GPIO.HIGH)
        GPIO.output(22, GPIO.HIGH)
    elif control.count(1) > 4:
        print("Caution")
        GPIO.output(15, GPIO.LOW)
        GPIO.output(22, GPIO.HIGH)
    else:
        print("Go")
        GPIO.output(15, GPIO.LOW)
        GPIO.output(22, GPIO.LOW)
Exemplo n.º 2
0
 def off(self):
     for pin in range(4):
         GPIO.output(self.pins[pin], 0)
Exemplo n.º 3
0
def human(w, xm, detections):
    det_hum = False
    for detection in detections:
        if detection[0].decode() == "person":
            det_hum = True  # Human is detected in an image
            print("Human")

    #Classification of Distnace
    if (w > 100 and det_hum):
        print("Very close")
        control.append(2)
    elif (w > 60 and w <= 100 and det_hum):
        print("Close")
        control.append(1)
    else:
        print("Far")
        control.append(0)

    #Set Intervals
    if len(control) == 10:
        control.remove(control[0])
    if len(signal) == 2:
        signal.remove(signal[0])

    #Stop Definition
    if control.count(2) > 2:
        signal.append(2)
        if signal[0] == 0:  # Go
            if xm > 240:
                robot.set_motors(0.1, 0.2)
                time.sleep(0.3)
                print("Stop and left turn")
                for aa in range(10):
                    robot.forward(0.2 - aa * 0.02)
                    time.sleep(0.2)
            else:
                robot.set_motors(0.2, 0.1)
                time.sleep(0.3)
                print("Stop and right turn")
                for ab in range(10):
                    robot.forward(0.2 - ab * 0.02)
                    time.sleep(0.2)
        elif signal[0] == 1:  # Caution
            if xm > 240:
                robot.set_motors(0.1, 0.2)
                time.sleep(0.3)
                print("Stop and left turn")
                for aa in range(10):
                    robot.forward(0.2 - aa * 0.02)
                    time.sleep(0.2)
            else:
                robot.set_motors(0.2, 0.1)
                time.sleep(0.3)
                print("Stop and right turn")
                for ab in range(10):
                    robot.forward(0.2 - ab * 0.02)
                    time.sleep(0.2)
        robot.stop()
        time.sleep(1)
        for i in range(4):
            GPIO.output(31, GPIO.HIGH)
            time.sleep(0.125)
            GPIO.output(31, GPIO.LOW)
            time.sleep(0.125)

    # Caution Definition
    elif control.count(1) > 4:
        signal.append(1)
        print("Caution")
        if signal[0] == 2:  # Stop
            for b in range(10):
                robot.forward(b * 0.02)
                time.sleep(0.2)
        robot.forward(speed=0.2)
        GPIO.output(31, GPIO.HIGH)

    # Go Definition
    else:
        signal.append(0)
        print("Go")
        if signal[0] == 2:  # Stop
            for b in range(10):
                robot.forward(0.02 * b)
                time.sleep(0.2)
        GPIO.output(31, GPIO.LOW)
        robot.forward(0.2)
Exemplo n.º 4
0
 def motorFunc(self, rightCase, leftCase):
     if leftCase == True and rightCase == False:
         GPIO.output(self.rightPin, GPIO.LOW)
         GPIO.output(self.leftPin, GPIO.HIGH)
     elif rightCase == True and leftCase == False:
         GPIO.output(self.leftPin, GPIO.LOW)
         GPIO.output(self.rightPin, GPIO.HIGH)
     else:
         GPIO.output(self.rightPin, GPIO.LOW)
         GPIO.output(self.leftPin, GPIO.LOW)
Exemplo n.º 5
0
def mov_detector(gpio_sensor=0,
                 cm_hole=0,
                 distance_interval=0,
                 start_photo_inference=0,
                 start_photo_check=0,
                 spray_line1=0,
                 spray_line2=0):
    '''
    In this function we will use a disk with 20 or 40 holes and a radius of 5.1 cm,
    the the end of the disk (perpendicular), we will use an infrared sensor to detect interruptions,
    every interruption is a movement.

    It will also be used to check the speed, trigger a photo for inference and checage.
    Parameters:
            gpio_sensor: this is the device port to connect as an input
            cm_hole: it means how many centimeters each hole in the disk has (it's one step in the disk)
            distance_interval: This is the distance in CM to be defined to trigger a photo
            start_photo_inference: the minimal distance to trigger the photo for inference
            start_photo_check: the minimal distance to trigger the check photo (check the spray)
            spray_line1: if KeyBoard interrupt is triggered it turns off the solenoids in the first line
            spray_line2: if KeyBoard interrupt is triggered it turns off the solenoids in the second line
    
    # TODO:
            Use two sensors to detect the direction of the disk
    '''
    # Setting initial time to measure the speed
    global curr_position
    global counter_speed
    global counter_infer_photo
    global counter_check_photo
    global start
    global speed

    try:
        if counter_speed == 0:
            start = datetime.now()

        if GPIO.wait_for_edge(gpio_sensor, GPIO.RISING):
            pass

        if GPIO.wait_for_edge(
                gpio_sensor, GPIO.FALLING):  # Change in signal, counting steps
            curr_position += 1
            counter_speed += 1
            counter_infer_photo += 1
            counter_check_photo += 1

            # Measuring distance travelled
            distance = curr_position * cm_hole  # LOOK AT THIS
            print('[WEEDS] Distance Traveled: ', round(distance / 100, 4),
                  ' meters')

            # Measuring variation on time and distance
            if counter_speed == 10:
                end = datetime.now()
                diff = end - start
                delta_time = diff.seconds + diff.microseconds / 1e6
                delta_distance = counter_speed * cm_hole / 100  #in meters
                speed = delta_distance / delta_time  # m/sec
                counter_speed = 0

            if curr_position > 10:
                print('[WEEDS] Current speed: ', round(speed, 2),
                      ' m/sec or: ', round(speed * 3.6, 2), ' km/h.')
            # Triggering Inference Photo
            if curr_position >= start_photo_inference:
                if counter_infer_photo * cm_hole >= distance_interval:
                    infer_trigger = True
                    counter_infer_photo = 0
                    print('[WEEDS] Inference Photo Triggered')
                else:
                    infer_trigger = False

            # Triggering Check Photo
            if curr_position >= start_photo_check:
                if counter_check_photo * cm_hole >= distance_interval:
                    check_trigger = True
                    counter_check_photo = 0
                    print('[WEEDS] Check Photo Triggered')
                else:
                    check_trigger = False

        print('[WEEDS] Position:', curr_position, ', Infer Trigger:',
              infer_trigger, ', Check Trigger:', check_trigger)

    except KeyboardInterrupt:
        print("[WEEDS] KeyboardInterrupt has been caught.")
        GPIO.output(spray_line1, GPIO.LOW)
        GPIO.output(spray_line2, GPIO.LOW)
        GPIO.cleanup()
        sys.exit()

    return curr_position, infer_trigger, check_trigger
Exemplo n.º 6
0
def digital_read(pin):
    return GPIO.input(BUSY_PIN)
Exemplo n.º 7
0
#!/usr/bin/env python3
import Jetson.GPIO as GPIO
from time import sleep
# Set up du board (reférence n° port)
GPIO.setmode(GPIO.BOARD)

# definition de la pin comme pin d'entrée
GPIO.setup(7, GPIO.IN)
GPIO.setup(11, GPIO.IN)
#GPIO.setup(12, GPIO.OUT)

# initialisation de l'expérience => TEST
#GPIO.output(12, GPIO.LOW)

# Lecture de la Pin
# GPIO.input(7) # GPAIO 4
# GPIO.input(11) # GPAIO 17


def experience():
    GPIO.output(12, GPIO.HIGH)


# Attente de réponse => TODO: test
def tirette():
    Tirrette = [0 for i in range(10)]  # niveau bas = 0
    while 1:
        print("attente tirette")
        for i in range(0, 10):
            if GPIO.input(7) == 0:  # boucle de check tirette relevée
                Tirrette[i] = 0
Exemplo n.º 8
0
# This is a sample Python script.
import Jetson.GPIO as GPIO
from car.car import Car
from directory_manager.dir_manager import DirectoryManager
from mqtt_connection.mqtt_car import MqttCar
from distance_sensor.distance_sensor import DistanceSensor
from camera.car_camera import CarCamera
from led.single_led import SingleLED
import utils.constants as const
import sys
import os
from utils.keyboard_reader import KeyboardReader

# Set Jetson GPIO Mode
GPIO.setmode(GPIO.BCM)
# Create mqtt car class
mqtt = MqttCar()
# Create directory manager class
dir_manager = DirectoryManager()
# Crete keyboard reader class
keyboard_reader = KeyboardReader()
# Create LED class
led = SingleLED(GPIO)
# Create Car class
car = Car(GPIO, 45)
# Create Distance sensor class
distance_sensor = DistanceSensor(GPIO)
# Create car camera class
car_camera = CarCamera(autopilot=False, record_stops=False, video_output=True)

# Set initial values
import Jetson.GPIO as GPIO

valve_pin = 16
GPIO.setmode(GPIO.BOARD)
GPIO.setup(valve_pin, GPIO.OUT)


def gripper_open():
    GPIO.output(valve_pin, GPIO.HIGH)


def gripper_close():
    GPIO.output(valve_pin, GPIO.LOW)


if __name__ == '__main__':
    import time

    while (True):
        gripper_open()
        time.sleep(2)
        gripper_close()
        time.sleep(2)
import Jetson.GPIO as GPIO
import time
import cv2
import numpy as np
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import tensorflow as tf

# Set GPIO
led_pin = [23, 21, 19, 15, 13, 11]
button_pin = 7
all_off = [1, 1, 1, 1, 1, 1]
GPIO.setmode(GPIO.BOARD)
GPIO.setup(led_pin, GPIO.OUT)
GPIO.setup(button_pin, GPIO.IN)
GPIO.output(led_pin, all_off)
button_state = GPIO.input(button_pin)
previous_state = GPIO.input(button_pin)

# Input Model Name
h5name = input('\n\nInput H5 File Name: ')
if h5name[-3:] != '.h5':
    h5name = h5name + '.h5'
try:
    model = tf.keras.models.load_model(h5name)
except Exception as e:
    print('\n\nModel not found!!!')
    print(e)
    exit()

# Set Label Name
Exemplo n.º 11
0
import Jetson.GPIO as GPIO
import time as time

LED_Pin = 11
GPIO.setwarnings(False)


def main():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(LED_Pin, GPIO.OUT, initial=GPIO.HIGH)

    try:
        while True:
            GPIO.output(LED_Pin, GPIO.HIGH)
            time.sleep(0.1)
            GPIO.output(LED_Pin, GPIO.LOW)
            time.sleep(0.1)
    finally:
        GPIO.cleanup()


if __name__ == '__main__':
    main()
Exemplo n.º 12
0
#!/usr/bin/env python
import sys
from time import sleep
sys.path.append('/opt/nvidia/jetson-gpio/lib/python/')
sys.path.append('/opt/nvidia/jetson-gpio/lib/python/GPIO')
import Jetson.GPIO as gpio
import rospy
from funcase_msgs.msg import JoyCmd

gpio.setmode(gpio.BCM)
switch = 18  ## Pin 12
gpio.setup(switch, gpio.OUT, initial=gpio.LOW)
#gpio.setwarnings(False)
swit = False


def callback(data):
    global swit
    joy_cmd = data
    button = joy_cmd.joy[0].encode("hex")
    sum_ = int(button[0]) * 16 + int(button[1]) * 1
    #print(c)

    if sum_ == 4:
        swit = True
        gpio.output(switch, gpio.HIGH)
    if sum_ == 2:
        swit = False
        gpio.output(switch, gpio.LOW)
    print(swit)
Exemplo n.º 13
0
def listener():
    rospy.init_node('arm', anonymous=False)
    rospy.set_param('base_station/drive_mode', 'XboxDrive')
    rospy.Subscriber("/base_station/rjs_raw_ctrl", RawCtrl, RightCallback)
    rospy.Subscriber("/base_station/ljs_raw_ctrl", RawCtrl, LeftCallback)
    rospy.Subscriber("/heartbeat", Empty, HBeatCb)

    GPIO.setmode(GPIO.BOARD)
    GPIO.setwarnings(False)
    GPIO.setup(31, GPIO.OUT)
    while (True):
        global finger_debouncer
        global toggle_finger
        global hbeat_cnt
        global ignore_endstops
        global reset
        global values
        global prev_finger
        rospy.loginfo(ignore_endstops)
        hbeat_cnt += 1
        if False and ((hbeat_cnt > max_hbeat) or (reset == True)):
            hbeat = False
            values = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
            for i in range(0, len(values)):  #Sending stop commands to all
                field = 0x0
                complete_id = (
                    ids[i] << 4) + field  #Embedding ID's with 0 command
                msg = can.Message(
                    arbitration_id=complete_id, data=[],
                    extended_id=False)  #Creating can message to send
                bus.send(msg)
        else:
            for i in range(0, len(values)):
                if (i == 4
                        or i == 6) and (ignore_endstops
                                        == True):  #If on ignore endstops mode
                    field = 0x5
                    if values[i] < 0:
                        field = 0x6
                    value = int(abs(values[i]) * 4095)
                else:  #If not on ignore end_stops mode or not an endeffector one
                    field = 0x3
                    if values[i] < 0:
                        field = 0x4
                    value = int(abs(values[i]) * 4095)
                if (i == 6):
                    if toggle_finger == True:
                        #field = 0x7
                        toggle_finger = False  #Finger toggle debouncer
                        if prev_finger == True:
                            GPIO.output(31, GPIO.LOW)
                            rospy.loginfo("Off")
                            prev_finger = False
                        else:
                            GPIO.output(31, GPIO.HIGH)
                            prev_finger = True
                            rospy.loginfo("On")
                complete_id = (
                    ids[i] << 4
                ) + field  #Embedding ID's with chosen directional PWM command
                if value < 10:
                    value = 0  #Getting rid of off centre
                bit1 = value >> 8 & 0xFF
                bit2 = value & 0xFF
                #rospy.loginfo(value)
                msg = can.Message(arbitration_id=complete_id,
                                  data=[bit1, bit2],
                                  extended_id=False)
                bus.send(msg)
            if finger_debouncer < 15:
                finger_debouncer += 1
        time.sleep(0.1)
Exemplo n.º 14
0
    def __init__(self, wheel_distance=0.6, wheel_diameter=0.4):
        rospy.loginfo("Setting Up the Node...")

        rospy.init_node('scooby_llc')

        GPIO.setmode(GPIO.BCM)

        self.PIN_LIGHT = 5
        self.PIN_HORN = 6
        self.gain = 0.75

        GPIO.setup(self.PIN_LIGHT, GPIO.OUT)
        GPIO.setup(self.PIN_HORN, GPIO.OUT)

        GPIO.output(self.PIN_LIGHT, GPIO.HIGH)
        GPIO.output(self.PIN_HORN, GPIO.HIGH)

        self._wheel_distance = wheel_distance
        self._wheel_radius = wheel_diameter / 2.0

        self.actuators = {}
        self.actuators['left_a'] = ServoConvert(id=1)
        self.actuators['left_b'] = ServoConvert(id=2,
                                                direction=1)  #-- positive left
        self.actuators['right_a'] = ServoConvert(id=3)
        self.actuators['right_b'] = ServoConvert(id=4, direction=1)
        rospy.loginfo("> Actuators corrrectly initialized")

        self._servo_msg = ServoArray()
        #self._imu_data_msg    = Imu()
        self._joint_stat = JointState()
        self._velocity_msg = Float32MultiArray()
        for i in range(4):
            self._servo_msg.servos.append(Servo())

        #--- Create the servo array publisher
        self.ros_pub_velocity_array = rospy.Publisher("/wheel_velocity",
                                                      Float32MultiArray,
                                                      queue_size=1)
        self.ros_pub_servo_array = rospy.Publisher("/servos_absolute",
                                                   ServoArray,
                                                   queue_size=1)
        #self.ros_pub_imu_data       = rospy.Publisher("/imu/data_raw", Imu, queue_size=1)
        self.ros_pub_joint_stat = rospy.Publisher("/joint_stat",
                                                  JointState,
                                                  queue_size=10)

        rospy.loginfo("> Publisher corrrectly initialized")

        #--- Create imu subscriber
        #self.ros_sub_imu            = rospy.Subscriber("/rtimulib_node/imu", Imu, self.send_imu_data_msg)

        #--- Create the Subscriber to Joy commands
        self.ros_sub_joy = rospy.Subscriber("/joy_teleop/joy", Joy,
                                            self.set_actuators_from_joy)

        #--- Create the Subscriber to Twist commands
        self.ros_sub_twist = rospy.Subscriber("/joy_teleop/cmd_vel", Twist,
                                              self.set_actuators_from_cmdvel)

        rospy.loginfo("> Subscriber corrrectly initialized")

        #--- Get the last time e got a commands
        self._last_time_cmd_rcv = time.time()
        self._timeout_s = 5
        self.anglez = 0.00

        rospy.loginfo("Initialization complete")
Exemplo n.º 15
0
import Jetson.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setup(33, GPIO.OUT)
GPIO.output(33, GPIO.HIGH)
time.sleep(5)
GPIO.output(33, GPIO.LOW)
GPIO.cleanup()
def gripper_close():
    GPIO.output(valve_pin, GPIO.LOW)
Exemplo n.º 17
0
def digital_write(pin, value):
    GPIO.output(pin, value)
def gripper_open():
    GPIO.output(valve_pin, GPIO.HIGH)
Exemplo n.º 19
0
def module_init():
    # print("module_init")
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    # print("RST_PIN")
    GPIO.setup(RST_PIN, GPIO.OUT)
    # print("DC_PIN")
    GPIO.setup(DC_PIN, GPIO.OUT)
    # print("CS_PIN")
    GPIO.setup(CS_PIN, GPIO.OUT)
    # print("BUSY_PIN")
    GPIO.setup(BUSY_PIN, GPIO.IN)
    # SPI.max_speed_hz = 2000000
    # SPI.mode = 0b00

    # gpio2.SYSFS_GPIO_Export(15)
    # gpio2.SYSFS_GPIO_Direction(15, 0)

    spi.SYSFS_software_spi_begin()
    return 0
Exemplo n.º 20
0
# This is a simple test of the Jetson.GPIO library
# To understand more about this library, read /opt/nvidia/jetson-gpio/doc/README.txt

import sys

import Jetson.GPIO as GPIO
from periphery import PWM
import time

# set GPIO mode to BOARD
GPIO.setmode(GPIO.BOARD)
mode = GPIO.getmode()
print(mode)

# Open PWM channel 0, pin 32
pins = range(0, 41)
"""
for pin in pins:
	try:
		pwm = PWM(0, pin)
		print("** Channel 0 pin {} works!".format(pin))
	except:
		print("Pin {} does not work".format(pin))
"""
pwm = PWM(0, 2)
pwm = PWM(0, 0)

#Channel 0 pin 2

# Set frequency to 1 kHz
pwm.frequency = 2e3
Exemplo n.º 21
0
def experience():
    GPIO.output(12, GPIO.HIGH)
Exemplo n.º 22
0
        # 초음파 도착 시간 얻기
        time2 = time.time()

        during = time2 - time1
        dist = during * 340 / 2 * 100
        print(during)
        return dist


if __name__ == "__main__":

    try:

        bz = Buzzer.ActiveBuzzer(13)
        sensor = HcSr04(trigpin=11, echopin=12)

        while True:
            distance = sensor.distance()
            print("거리: {}".format(distance))
            if distance <= 30:
                bz.on()
            else:
                bz.off()
            time.sleep(0.3)

    except KeyboardInterrupt:
        print()
    finally:
        GPIO.cleanup()
        print("Program Exit")
Exemplo n.º 23
0
 def __init__(self, leftPin, rightPin):
     self.leftPin = leftPin
     self.rightPin = rightPin
     GPIO.setmode(GPIO.BOARD)
     GPIO.setup(self.leftPin, GPIO.OUT)
     GPIO.setup(self.rightPin, GPIO.OUT)
Exemplo n.º 24
0
"""Tegra T186 pin names"""

import atexit
import Jetson.GPIO as GPIO

GPIO.setmode(GPIO.TEGRA_SOC)
GPIO.setwarnings(False)  # shh!


class Pin:
    """Pins dont exist in CPython so...lets make our own!"""

    IN = 0
    OUT = 1
    LOW = 0
    HIGH = 1
    PULL_NONE = 0
    PULL_UP = 1
    PULL_DOWN = 2

    id = None
    _value = LOW
    _mode = IN

    def __init__(self, bcm_number):
        self.id = bcm_number

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

    def __eq__(self, other):
Exemplo n.º 25
0
 def step(self, wait=0.001):
     for pin in range(4):
         GPIO.output(self.pins[pin],
                     self.seq[self.actual_position % 8][pin])
     time.sleep(wait)
Exemplo n.º 26
0
 def cleanup():
     """Clean up pins"""
     print("Exiting... \nCleaning up pins")
     GPIO.cleanup()
Exemplo n.º 27
0
from ctypes import *
import math
import random
import os
import cv2
import numpy as np
import time
import darknet
import Jetson.GPIO as GPIO
from jetbot import Robot
robot = Robot()
for a in range(10):
    robot.forward(0.02 * a)
    time.sleep(0.2)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(31, GPIO.OUT)

control = []


def convertBack(x, y, w, h):
    xmin = int(round(x - (w / 2)))
    xmax = int(round(x + (w / 2)))
    ymin = int(round(y - (h / 2)))
    ymax = int(round(y + (h / 2)))
    return xmin, ymin, xmax, ymax


signal = []

Exemplo n.º 28
0
def interrupt_handler(sig, frame):
    print("You've pressed Ctrl+C!")
    logging.info("Program ending")
    GPIO.cleanup(output_pin)
    sys.exit(0)
Exemplo n.º 29
0
from __future__ import print_function
import time

try:
    import Jetson.GPIO as GPIO
except ImportError:
    import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)


class Motor(object):
    def __init__(self, pwm_pin, pwm_min, pwm_max, pwm_init_duty_cycle=0,
                 pwm_frequency=50, pwm_neutral=None):
        self.pwm_pin = pwm_pin
        self.pwm_min = pwm_min
        self.pwm_max = pwm_max
        self.pwm_init_duty_cycle = pwm_init_duty_cycle
        self.pwm_frequency = pwm_frequency
        self.pwm = None

        if pwm_neutral is None:
            self.pwm_neutral = (pwm_min + pwm_max) / 2

        self.setup()

    def setup(self):
        GPIO.setup(self.pwm_pin, GPIO.OUT)
        self.pwm = GPIO.PWM(self.pwm_pin, self.pwm_frequency)
        self.pwm.start(self._clip_value(self.pwm_init_duty_cycle))
Exemplo n.º 30
0
from ctypes import *
import math
import random
import os
import cv2
import numpy as np
import time
import darknet
import Jetson.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)
GPIO.setup(15,GPIO.OUT)
GPIO.setup(22,GPIO.OUT)

control=[]
def convertBack(x, y, w, h):
    xmin = int(round(x - (w / 2)))
    xmax = int(round(x + (w / 2)))
    ymin = int(round(y - (h / 2)))
    ymax = int(round(y + (h / 2)))
    return xmin, ymin, xmax, ymax


def human(w):
    if(w > 250):
        control.append(2)
    elif( w > 200 and w <= 250):
        control.append(1)
    else:
        control.append(0)