예제 #1
0
def setupGPIO():
    GPIO.setmode(GPIO.BOARD)  # BOARD pin-numbering scheme
    GPIO.setup(STEP_PIN, GPIO.IN)  # button pin set as input
    GPIO.setup(BUZZ_PIN, GPIO.OUT, initial=GPIO.LOW)
    GPIO.setup(DIR_PIN, GPIO.IN)
    GPIO.setup(ZERO_PIN, GPIO.IN)  # pull_up_down=GPIO.PUD_UP
    GPIO.add_event_detect(ZERO_PIN, GPIO.FALLING, callback=zero_button)
예제 #2
0
def new_execute():
    global recst
    global recbtn
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(recbtn, GPIO.IN)
    GPIO.add_event_detect(recbtn,
                          GPIO.FALLING,
                          callback=btn_th,
                          bouncetime=200)
    phpath = "./data/rec/"
    os.makedirs(phpath, exist_ok=True)

    # Left Camera
    camera0 = nano.Camera(device_id=0, flip=2, width=224, height=224, fps=60)
    # Right Camera
    camera1 = nano.Camera(device_id=1, flip=2, width=224, height=224, fps=60)
    # wait rec button
    print("REC wait ...")
    waitrec()
    # rec start
    print("REC START! ...")
    #    recloop_old(camera0, "./data/apex/", 0.1)
    #    recloopDual_old(camera0,camera1, phpathL,phpathR, 0.1)
    #    recloopStereo_old(camera0,camera1, phpathMx, phpathL,phpathR, 0.1)
    recloopDual(camera0, camera1, phpath, 0.05)
    # testloop()
    print("REC END!! ...")
    camera0.release()
    camera1.release()
    # finish
    del camera0
    GPIO.cleanup()
예제 #3
0
def main():
    # Pin Setup:
    GPIO.setmode(GPIO.BOARD)  # BOARD pin-numbering scheme
    # GPIO.setup([led_pin_1, led_pin_2], GPIO.IN)  # LED pins set as output
    GPIO.setup(12, GPIO.IN)  # button pin set as input
    #GPIO.setup(led_pin_2, GPIO.IN)

    # Initial state for LEDs:
    # GPIO.output(led_pin_1, GPIO.LOW)
    # GPIO.output(led_pin_2, GPIO.LOW)

    GPIO.add_event_detect(12, GPIO.RISING, callback=blink1, bouncetime=10)
    #GPIO.add_event_detect(led_pin_2, GPIO.RISING, callback=blink2, bouncetime=10)

    print("Starting demo now! Press CTRL+C to exit")
    try:
        while True:

            input1 = GPIO.input(led_pin_1)
            #input2 = GPIO.input(led_pin_2)
            # blink LED 1 slowly
            print("Value read from pin {} : {}\n".format(input1, ' pin_1 low'))
            time.sleep(2)
            #print("Value read from pin {} : {}\n".format(input2, '2down'))
            # time.sleep(1)
    finally:
        GPIO.cleanup()  # cleanup all GPIOs
예제 #4
0
 def setup_gpio(self):
     self._button = digitalio.DigitalInOut(board.D23)
     self._button.direction = digitalio.Direction.INPUT
     self._button.pull = digitalio.Pull.DOWN
     self._led = digitalio.DigitalInOut(board.D21)
     self._led.direction = digitalio.Direction.OUTPUT
     GPIO.add_event_detect(board.D23.id,
                           GPIO.BOTH,
                           callback=self.button_callback,
                           bouncetime=10)
예제 #5
0
 def activate(self):
     if self._deactivate is True:
         try:
             self._deactivate = False
             GPIO.add_event_detect(self.button_pin, GPIO.RISING,
                                   self.__callback, self.duration)
             logging.info('door lock started')
         except:
             self._deactivate = True
             logging.error("door lock couldn't start")
     else:
         logging.info('door lock system is still running')
예제 #6
0
    def __init__(self):
        GstBase.BaseTransform.__init__(self)
        self.set_in_place(True)

        self.videoinfo = GstVideo.VideoInfo()

        self.last_gpio_ts = 0
        self.last_buf_ts = 0

        GPIO.setmode(GPIO.BOARD)
        channel = 16
        GPIO.setup(channel, GPIO.IN, pull_up_down=GPIO.PUD_OFF)
        GPIO.add_event_detect(channel, GPIO.FALLING, callback=self.gpio_event)
예제 #7
0
def setup_button(channel):
    print("{}: RESET GPIO {} for push".format(time.time(), channel))
    GPIO.cleanup(channel)
    GPIO.remove_event_detect(channel)
    GPIO.setup(channel, GPIO.OUT)
    GPIO.output(channel, GPIO.LOW)
    GPIO.setup(
        channel, GPIO.IN, pull_up_down=GPIO.PUD_DOWN
    )  # Set pin 10 to be an input pin and set initial value to be pulled low (off)
    #can use GPIO.RISING / FALLING / BOTH
    GPIO.add_event_detect(channel,
                          GPIO.RISING,
                          callback=button_callback,
                          bouncetime=300)  # Setup event on pin 10 rising edge
예제 #8
0
    def __init__(self, start_band=0, end_band=180):
        self.reset = False
        self.start_dir_state = None
        self.running_state = False

        self.start_band = start_band
        self.end_band = end_band

        GPIO.setup(
            [start_left_btn, start_right_btn, begin_track_btn, reset_btn],
            GPIO.IN)
        GPIO.setup([start_left_led, start_right_led, begin_track_led],
                   GPIO.OUT)

        GPIO.add_event_detect(start_left_btn,
                              GPIO.RISING,
                              callback=self.start_left_cb,
                              bouncetime=100)
        GPIO.add_event_detect(start_right_btn,
                              GPIO.RISING,
                              callback=self.start_right_cb,
                              bouncetime=100)
        GPIO.add_event_detect(begin_track_btn,
                              GPIO.RISING,
                              callback=self.begin_tracking_cb,
                              bouncetime=100)
        GPIO.add_event_detect(reset_btn,
                              GPIO.RISING,
                              callback=self.reset_btn_cb,
                              bouncetime=100)
예제 #9
0
    def __init__(self, xEncoder, yEncoder, encoderRotation, address, busNum, motorPos, dirPin, reversedDir, frequency):

        GPIO.add_event_detect(xEncoder, GPIO.RISING,
                              callback=self.xCallback)
        GPIO.add_event_detect(yEncoder, GPIO.RISING,
                              callback=self.yCallback)

        self.encoderRot = encoderRotation

        self.pwmController = Adafruit_PCA9685.PCA9685(
            address=address, busnum=busNum)
        self.pwmController.set_pwm_freq(frequency)

        self.motorPos = motorPos
        self.dirPin = dirPin
        self.reversed = reversedDir
예제 #10
0
파일: main.py 프로젝트: sun3850/FoodMate
	def goingOn(self):  # 여기 callback으로 matchfood 넣을지 고민
		t = Tracker()
		Tracker_thread = Thread(target = t.track_point) 
		Tracker_thread.start()
		while (True):
			if GPIO.event_detected(self.button_pin):

				self.Cx , self.Cy = t.get_track_point()
				# 젓가락의 위치랑 이미지의 픽셀값안에 있나 확인해서 음식명 출력
				print(self.Cx , self.Cy)
				self.answer = self.guess.matchFood(self.Cx, self.Cy, self.board.box_x, self.board.box_y)
				print(self.answer)
				sound = Sound(self.answer)

				GPIO.remove_event_detect(self.button_pin)
				time.sleep(0.3)
				GPIO.add_event_detect(self.button_pin, GPIO.FALLING)
예제 #11
0
    def __init__(self):
        #Subscriber Define
        self.gpio_ctrl_sub_ = rospy.Subscriber("/gpio_on_off",
                                               String,
                                               callback=self.GPIOCtrlCb)
        self.led_ctrl_sub_ = rospy.Subscriber("/led_on_off",
                                              String,
                                              callback=self.LedCtrlCb)
        self.buzzer_ctrl_sub_ = rospy.Subscriber("/buzzer_on_off",
                                                 String,
                                                 callback=self.BuzzerCtrlCb)

        #Publisher Define
        self.button_state_pub_ = rospy.Publisher("/botton_state",
                                                 String,
                                                 queue_size=1)

        #Params
        self.led_ctrl_pin_ = 22
        self.buzzer_ctrl_pin_ = 40
        self.botton_state_pin_ = 26
        self.botton_mode_pin_ = 24

        self.led_on_off_flag_ = False
        self.buzzer_on_off_flag_ = False
        self.gpio_on_off_flag_ = True

        self.pwm_freq_ = 500
        self.sleep_time_ = 0.5 / float(self.pwm_freq_)

        #Initialize
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup([self.led_ctrl_pin_], GPIO.OUT, initial=GPIO.LOW)
        GPIO.setup([self.buzzer_ctrl_pin_], GPIO.OUT, initial=GPIO.LOW)
        GPIO.setup([self.botton_state_pin_, self.botton_mode_pin_], GPIO.IN)

        self.thread_pwm_ = threading.Thread(target=self.PWMOutput)
        self.thread_pwm_.start()

        GPIO.add_event_detect(self.botton_state_pin_,
                              GPIO.RISING,
                              callback=self.BottonStateCb)
        GPIO.add_event_detect(self.botton_mode_pin_,
                              GPIO.RISING,
                              callback=self.BottonModeCb)
예제 #12
0
def prepare():
    # 走行Button
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(recbtn, GPIO.IN)
    GPIO.add_event_detect(gobtn,
                          GPIO.FALLING,
                          callback=btn_thrd,
                          bouncetime=200)

    # Left Camera
    camera0 = nano.Camera(device_id=0, flip=2, width=224, height=224, fps=60)
    # Right Camera
    camera1 = nano.Camera(device_id=1, flip=2, width=224, height=224, fps=60)

    CATEGORIES = ['apex']
    device = torch.device('cuda')
    model = torchvision.models.resnet18(pretrained=False)
    model.fc = torch.nn.Linear(512, 2 * len(CATEGORIES))
    model = model.cuda().eval().half()
    # model.load_state_dict(torch.load('model.pth'))
    model.load_state_dict(torch.load('data/model.pth'))

    data = torch.zeros((1, 3, 224, 224)).cuda().half()
    model_trt = torch2trt(model, [data], fp16_mode=True)
    torch.save(model_trt.state_dict(), 'road_following_model_trt.pth')

    model_trt = TRTModule()
    model_trt.load_state_dict(torch.load('road_following_model_trt.pth'))

    car = NvidiaRacecar()

    STEERING_GAIN = -0.75
    STEERING_BIAS = 0.00

    car.throttle = 0.25
    cnt = 0
    while True:
        image = camera0.read()
        image = preprocess(image).half()
        output = model_trt(image).detach().cpu().numpy().flatten()
        x = float(output[0])
        car.steering = x * STEERING_GAIN + STEERING_BIAS
        print(str(cnt) + ":" + str(x) + ":")
        cnt = cnt + 1
예제 #13
0
def zero_button(channel):
    now = time.time()

    global isStarted
    global start_time
    global buzz_time

    if (not isStarted):
        start_time = now
        buzz_time = now
        GPIO.output(BUZZ_PIN, 1)
        steps.append(300)
        timestamps.append(now)
        isStarted = 1
        GPIO.add_event_detect(STEP_PIN, GPIO.RISING, callback=read_angle)
        time.sleep(0.5)
        GPIO.output(BUZZ_PIN, 0)

    print("------------------ CALIBRATED ----------------------")
예제 #14
0
    def __init__(self,
                 daemon=False,
                 button_pin=BUTTON_PIN,
                 bolt_pin=BOLT_PIN,
                 duration=DURATION_PRESS_OF_BUTTON):
        try:
            GPIO.setmode(GPIO.BOARD)
            self.button_pin = button_pin
            self.bolt_pin = bolt_pin
            self.duration = duration

            GPIO.setup(self.button_pin, GPIO.IN)
            GPIO.setup(self.bolt_pin, GPIO.OUT)
            GPIO.add_event_detect(self.button_pin, GPIO.RISING,
                                  self.__callback, self.duration)
            self._deactivate = False
            logging.info("door lock system started")
        except Exception as ex:
            logging.error('could not start door lock system')
            raise Exception(ex)
예제 #15
0
    def blink(self, channel):

        global clickState
        global firstTime
        global secondTime
        global program_step
        global print_once_flag
        global rising_edge_flag
        global falling_edge_flag
        global click_once

        # print("Blink LED 2, %s"%num)

        if (GPIO.input(channel) == GPIO.LOW):
            if (program_step == 0):
                falling_edge_flag = 1
                program_step = 1

            if (clickState == 0 and program_step == 2):
                firstTime = time.time()
                clickState = 1
                click_once = 1
                # print("state 1")

            if (clickState == 1 and click_once == 0 and program_step == 2
                    and self.showEnd == 1):
                secondTime = time.time()
                clickState = 2
                self.showEnd = 0
                # print("state 2")

        elif (GPIO.input(channel) == GPIO.HIGH):
            if (program_step == 1):
                rising_edge_flag = 1
                program_step = 2

        GPIO.remove_event_detect(channel)
        GPIO.add_event_detect(gpi_grabimage,
                              GPIO.BOTH,
                              callback=self.blink,
                              bouncetime=200)
예제 #16
0
def main():
    GPIO.setmode(GPIO.BOARD)  # BOARD pin-numbering scheme
    GPIO.setup(STEP_PIN, GPIO.IN)  # button pin set as input
    #GPIO.setup(TIM_PIN, GPIO.IN)
    #GPIO.add_event_detect(TIM_PIN, GPIO.RISING, callback=start)
    steps.append(0)
    GPIO.add_event_detect(STEP_PIN, GPIO.RISING, callback=read_angle)
    try:
        while (1):
            pass

    except KeyboardInterrupt:
        GPIO.cleanup()
        time = []
        #for t in timestamps:
        #	time.append(t-timestamps[0])

        #for i in range(1, len(time)):
        #	print(steps[i], " @ ", time[i]-time[i-1])
        for s in steps:
            print(s)
예제 #17
0
    def start(self):
        """ Start listening to GPIO pins to trigger callback functions """

        def on_rotation(channel):
            """ Update rotation state and call user defined callback functions after complete rotation """
            self.rot_state()

            if self.count // self.transitions_per_rotation != 0:
                if self.dir == CLOCKWISE:
                    self.on_clockwise_rotate()
                elif self.dir == COUNTERCLOCKWISE:
                    self.on_counterclockwise_rotate()

                self.count = 0

        def button_pressed(channel):
            """ Call the user defined callback when button is pressed """
            if not GPIO.input(self.BUTTON_PIN):
                self.on_click()

        self.setup()

        # add callback to be called when rotating encoder
        GPIO.add_event_detect(self.PIN_1, GPIO.BOTH, callback=on_rotation, bouncetime=0)
        GPIO.add_event_detect(self.PIN_2, GPIO.BOTH, callback=on_rotation, bouncetime=0)

        # add callback to be called when button is pressed
        GPIO.add_event_detect(
            self.BUTTON_PIN,
            GPIO.FALLING,
            callback=button_pressed,
            bouncetime=BOUNCETIME,
        )
예제 #18
0
파일: gpio.py 프로젝트: Maden23/telecenter
def main():
    GPIO.setwarnings(False)

    GPIO.setmode(GPIO.BOARD)

    # GPIO.setup([stop, rec, menu], GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup([stop, rec, menu], GPIO.IN)

    # # attach callbacks to events
    # GPIO.add_event_detect(stop, GPIO.RISING, callback=stop_cb, bouncetime=200)
    # GPIO.add_event_detect(rec, GPIO.RISING, callback=rec_cb, bouncetime=200)
    # GPIO.add_event_detect(menu, GPIO.RISING, callback=menu_cb, bouncetime=200)

    GPIO.add_event_detect(stop, GPIO.RISING)
    GPIO.add_event_detect(rec, GPIO.RISING)
    GPIO.add_event_detect(menu, GPIO.RISING)

    while True:
        try:
            if GPIO.event_detected(stop):
                stop_cb()
            if GPIO.event_detected(rec):
                rec_cb()
            if GPIO.event_detected(menu):
                menu_cb()
            pass
        except KeyboardInterrupt:
            GPIO.cleanup()
            sys.exit()
예제 #19
0
파일: main.py 프로젝트: sun3850/FoodMate
	def __init__(self):
		self.button_pin = 33

		GPIO.setmode(GPIO.BOARD)
		GPIO.setup(self.button_pin, GPIO.IN) 
		GPIO.add_event_detect(self.button_pin, GPIO.FALLING)
		
		# img 폴더 안에 있던 이미지 모두 삭제
		for file in os.scandir('../data/img'):
			os.remove(file.path)
		for file in os.scandir('../data/board_img'):
			os.remove(file.path)

		# 웹캠 사용해서 식판 스캔
		self.cap = cv2.VideoCapture(-1) 
		self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
		self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
		ret, self.img = self.cap.read()

		cv2.imwrite('../data/board_img/Scanned_image.jpg',self.img, params=[cv2.IMWRITE_JPEG_QUALITY,70])
		self.cap.release()

		# 젓가락의 위치
		self.Cx, self.Cy = 0, 0

		# keras 미리 로딩
		self.guess = Guess()

		# 모든 클래스의 객체생성
		# 1. 급식판 좌표

		self.board = Board()
		self.board.get_target_area()
		self.board.board_frgm_board()

		# 3. keras로 음식 맞추기 
		self.guess.realGuess()  # 일단 급식판에 무슨 음식이 있는지 학습
		self.answer = self.guess.matchFood(self.Cx, self.Cy, self.board.box_x, self.board.box_y)
예제 #20
0
def main():
    # Pin Setup:
    GPIO.setmode(GPIO.BOARD)  # BOARD pin-numbering scheme
    GPIO.setup([led_pin_1, led_pin_2], GPIO.IN)  # LED pins set as output
    #GPIO.setup(but_pin, GPIO.IN)  # button pin set as input

    # Initial state for LEDs:
    #GPIO.output(led_pin_1, GPIO.LOW)
    #GPIO.output(led_pin_2, GPIO.LOW)

    GPIO.add_event_detect(led_pin_1,
                          GPIO.RISING,
                          callback=blink,
                          bouncetime=10)
    print("Starting demo now! Press CTRL+C to exit")
    try:
        while True:
            print("main")
            # blink LED 1 slowly
            #GPIO.output(led_pin_1, GPIO.HIGH)
            time.sleep(2)
            #GPIO.output(led_pin_1, GPIO.LOW)
    finally:
        GPIO.cleanup()  # cleanup all GPIOs
예제 #21
0
    def GPIO_main(self):
        # self.timer.moveToThread(self.GPIOThreadHandle)
        global clickState
        global firstTime
        global secondTime
        global program_step
        global print_once_flag
        global timeEclipse
        global clickFlag
        global click_once
        global time_long_set
        global time_long_long_set
        global falling_edge_flag
        global rising_edge_flag
        global cansel_flag
        global ok_flag

        # Pin Setup:
        GPIO.setmode(GPIO.BOARD)  # BOARD pin-numbering scheme
        # GPIO.setup([led_pin_1, led_pin_2], GPIO.OUT)  # LED pins set as output
        GPIO.setup(gpi_grabimage, GPIO.IN)  # button pin set as input


        GPIO.add_event_detect(gpi_grabimage, GPIO.BOTH, callback=self.blink, bouncetime=200)

        # print("Starting demo now! Press CTRL+C to exit")
        pwm = PCA9685()
        pwm.setPWMFreq(50)
        pwm.setPWM(3, 0, 0)  # 关闭可见激光
        pwm.setPWM(4, 0, 0)  # 关闭红外光源
        pwm.setPWM(5, 0, 0)  # 关闭红外激光

        try:
            while True:

                if (clickState == 1):
                    timeEclipse = time.time() - firstTime
                    if (timeEclipse > time_long_set):
                        ok_flag = 1
                        clickFlag = 1
                        clickState = 0
                        firstTime = 0
                        # print("state 3")

                    else:
                        # time.sleep(0.01)
                        click_once = 0

                if (clickState == 2):
                    timeEclipse = secondTime - firstTime
                    if (timeEclipse < time_long_set):
                        cansel_flag = 1
                        clickFlag = 2
                        secondTime = 0
                        firstTime = 0
                        clickState = 0

                if (clickFlag == 1):
                    # print("this is single click")
                    clickState = 0
                    clickFlag = 0
                elif (clickFlag == 2):
                    # print("this is double click")
                    clickState = 0
                    clickFlag = 0
                if (clickFlag == 3):
                    clickState = 0
                    clickFlag = 0
                    # print("this is changan")

                if (program_step == 1 and print_once_flag == 0):
                    # print("点亮可见激光")
                    # print("点亮不可见激光")
                    # print("点亮光源")
                    pwm.setPWM(3, 0, 4095)  # 点亮可见激光
                    pwm.setPWM(4, 0, 4095)  # 点亮红外光源
                    pwm.setPWM(5, 0, 4095)  # 点亮红外激光
                    print("======================================================================")
                    print_once_flag = 1
                if (program_step == 2 and print_once_flag == 1):


                    print("抓拍一张激光图像")  # 将此句话替换成拍照激光图片的函数即可
                    # set laser exposure
                    current_expo = c_float()
                    self.clientImID = int(round(time.time() * 1000))
                    ret = self.cam.MV_CC_GetFloatValue('ExposureTime', current_expo)
                    if (current_expo.value != self.laser_exposure):
                        ret = self.cam.MV_CC_SetFloatValue('ExposureTime', self.laser_exposure)
                    time.sleep(0.5)
                    self.trigger_laser_img()
                    # print("熄灭光源")
                    pwm.setPWM(4, 0, 0)  # 熄灭红外光源
                    pwm.setPWM(3, 0, 0)  # 熄灭可见激光
                    pwm.setPWM(5, 0, 0)  # 熄灭红外激光
                    print("开始上传激光图像")  # 将此句话替换成上传激光图片的函数即可
                    print("开始上传灰度图像")  # 将此句话替换成上传灰度图片的函数即可
                    self.signal_send_imgs.emit()
                    print("显示轮廓图像")  # 将此句话替换成显示轮廓图片的函数即可
                    print("等待确认回复")
                    print("======================================================================")
                    print_once_flag = 2

                if (program_step == 2 and cansel_flag == 1 and print_once_flag == 2):
                    cansel_flag = 0
                    print("取消重新开始")
                    self.signal_cancel_result.emit()
                    # self.cancel_result()
                    print("======================================================================")
                    print_once_flag = 0
                    program_step = 0

                if (program_step == 2 and ok_flag == 1 and print_once_flag == 2):
                    ok_flag = 0
                    print("确认重新开始")
                    self.signal_confirm_result.emit()
                    # self.confirm_result()
                    print("======================================================================")
                    print_once_flag = 0
                    program_step = 0

        finally:
            GPIO.cleanup()  # cleanup all GPIOs
user_button_pressed = False


def cb(channel):
    global user_button_pressed
    user_button_pressed = True
    GPIO.output(high_pin, GPIO.HIGH)


pin = 'MCLK05'  #'UART1_RTS' #'SOC_GPIO54'
high_pin = 'UART1_RTS'
GPIO.setmode(GPIO.CVM)  #TEGRA_SOC)
GPIO.setup(pin, GPIO.IN)
GPIO.setup(high_pin, GPIO.OUT, initial=GPIO.LOW)
GPIO.add_event_detect(pin, GPIO.RISING, callback=cb, bouncetime=200)
print("GPIO setup finished")

## TODO setup zed camera
init = sl.InitParameters(
    camera_resolution=sl.RESOLUTION.HD720,
    coordinate_units=sl.UNIT.METER,
    coordinate_system=sl.COORDINATE_SYSTEM.RIGHT_HANDED_Y_UP)
zed = sl.Camera()
status = zed.open(init)
if status != sl.ERROR_CODE.SUCCESS:
    print(repr(status))
    exit()

tracking_params = sl.PositionalTrackingParameters(_enable_pose_smoothing=False,
                                                  _set_floor_as_origin=False,
예제 #23
0
#addition
import Jetson.GPIO as GPIO
import os

PLD_PIN = 7

GPIO.setmode(GPIO.BOARD)
print(GPIO.getmode(), GPIO.BOARD)
GPIO.setup(PLD_PIN, GPIO.IN)


def my_callback(channel):
    if GPIO.input(channel):  # if port 6 == 1
        print "---AC Power Loss OR Power Adapter Failure---"
    else:  # if port 6 != 1
        print "---AC Power OK,Power Adapter OK---"


def shutdown():
    os.system('shutdown -h now')


GPIO.add_event_detect(PLD_PIN, GPIO.BOTH, callback=my_callback)

print "1.Make sure your power adapter is connected"
print "2.Disconnect and connect the power adapter to test"
print "3.When power adapter disconnected, you will see: AC Power Loss or Power Adapter Failure"
print "4.When power adapter disconnected, you will see: AC Power OK, Power Adapter OK"

raw_input("Testing Started")
예제 #24
0
    def GPIO_main(self):
        # self.timer.moveToThread(self.GPIOThreadHandle)
        global clickState
        global firstTime
        global secondTime
        global program_step
        global print_once_flag
        global timeEclipse
        global clickFlag
        global click_once
        global time_long_set
        global time_long_long_set
        global falling_edge_flag
        global rising_edge_flag
        global cansel_flag
        global ok_flag

        # Pin Setup:
        GPIO.setmode(GPIO.BOARD)  # BOARD pin-numbering scheme
        #GPIO.setup([led_pin_1, led_pin_2], GPIO.OUT)  # LED pins set as output
        GPIO.setup(gpi_grabimage, GPIO.IN)  # button pin set as input

        # Initial state for LEDs:
        #GPIO.output(led_pin_1, GPIO.LOW)
        #GPIO.output(led_pin_2, GPIO.LOW)

        GPIO.add_event_detect(gpi_grabimage,
                              GPIO.BOTH,
                              callback=self.blink,
                              bouncetime=200)

        # print("Starting demo now! Press CTRL+C to exit")
        pwm = PCA9685()
        pwm.setPWMFreq(50)
        pwm.setPWM(3, 0, 0)  #关闭可见激光
        pwm.setPWM(4, 0, 0)  #关闭红外光源
        pwm.setPWM(5, 0, 0)  #关闭红外激光

        try:
            while True:

                if (clickState == 1):
                    timeEclipse = time.time() - firstTime
                    if (timeEclipse > time_long_set):
                        ok_flag = 1
                        clickFlag = 1
                        clickState = 0
                        firstTime = 0
                        #print("state 3")

                    else:
                        # time.sleep(0.01)
                        click_once = 0

                if (clickState == 2):
                    timeEclipse = secondTime - firstTime
                    if (timeEclipse < time_long_set):
                        cansel_flag = 1
                        clickFlag = 2
                        secondTime = 0
                        firstTime = 0
                        clickState = 0

                if (clickFlag == 1):
                    #print("this is single click")
                    clickState = 0
                    clickFlag = 0
                elif (clickFlag == 2):
                    #print("this is double click")
                    clickState = 0
                    clickFlag = 0
                if (clickFlag == 3):
                    clickState = 0
                    clickFlag = 0
                    #print("this is changan")

                if (program_step == 1 and print_once_flag == 0):
                    #print("点亮可见激光")
                    #print("点亮不可见激光")
                    #print("点亮光源")
                    pwm.setPWM(3, 0, 4095)  #点亮可见激光
                    pwm.setPWM(4, 0, 4095)  #点亮红外光源
                    pwm.setPWM(5, 0, 4095)  #点亮红外激光
                    print(
                        "======================================================================"
                    )
                    print_once_flag = 1
                if (program_step == 2 and print_once_flag == 1):
                    #print("熄灭光源")
                    pwm.setPWM(4, 0, 0)  #熄灭红外光源
                    print("抓拍一张激光图像")  #将此句话替换成拍照激光图片的函数即可
                    self.signal_cap_laserimg.emit()

                    pwm.setPWM(3, 0, 0)  #熄灭可见激光
                    pwm.setPWM(5, 0, 0)  #熄灭红外激光
                    print("抓拍一张heise图像")  #将此句话替换成拍照heise图片的函数即可
                    self.signal_cap_nolightimg.emit()
                    # self.trigger_laser_img()
                    # self.trigger_nolight_img()
                    # time.sleep(0.5)

                    #print("打开光源")
                    #print("熄灭可见激光")
                    #print("熄灭不可见激光")
                    pwm.setPWM(4, 0, 4095)  #打开红外光源
                    pwm.setPWM(3, 0, 0)  #熄灭可见激光
                    pwm.setPWM(5, 0, 0)  #熄灭红外激光
                    print("抓拍一张灰度图像")  #将此句话替换成拍照灰度图片的函数即可
                    self.signal_cap_inferredimg.emit()
                    # self.trigger_inferred_img()
                    print('2222')
                    # time.sleep(0.5)
                    print('3333')
                    pwm.setPWM(4, 0, 0)  #熄灭红外光源
                    print('4444')

                    print("开始上传激光图像")  #将此句话替换成上传激光图片的函数即可
                    print("开始上传灰度图像")  #将此句话替换成上传灰度图片的函数即可
                    # self.signal.emit()
                    self.signal_send_imgs.emit()

                    # self.send_conbine_img()

                    # time.sleep(0.5)
                    print("显示轮廓图像")  #将此句话替换成显示轮廓图片的函数即可
                    print("等待确认回复")
                    print(
                        "======================================================================"
                    )
                    print_once_flag = 2

                if (program_step == 2 and cansel_flag == 1
                        and print_once_flag == 2):
                    cansel_flag = 0
                    print("取消重新开始")
                    self.signal_cancel_result.emit()
                    # self.cancel_result()
                    print(
                        "======================================================================"
                    )
                    print_once_flag = 0
                    program_step = 0

                if (program_step == 2 and ok_flag == 1
                        and print_once_flag == 2):
                    ok_flag = 0
                    print("确认重新开始")
                    self.signal_confirm_result.emit()
                    # self.confirm_result()
                    print(
                        "======================================================================"
                    )
                    print_once_flag = 0
                    program_step = 0

        finally:
            GPIO.cleanup()  # cleanup all GPIOs
예제 #25
0
def main():

    full_scrn = True

    parser = argparse.ArgumentParser(description='Darknet Yolo V4 Python Detector')
    parser.add_argument("-v", "--video", required=False, default="",	help="path to input video file")
    parser.add_argument("-s", "--show_video", required=False, type=str2bool, nargs='?', const=True, default=False,	help="False for faster")
    parser.add_argument("-f", "--save_video", required=False, default="", help="Save Video output as .mp4")

    args = parser.parse_args()

 
    global led_matrix, buzzer_f, buzzer_l, buzzer_r, buzzer_s, buzzer_t
    global metaMain, netMain, altNames
    global fps_time

    configPath = "../trained-weights/reference/yolov4-tiny.cfg"
    weightPath = "../trained-weights/reference/yolov4-tiny.weights"
    metaPath = "../trained-weights/reference/coco.data"
    #configPath = "../track/yolov4-tiny.cfg"
    #weightPath = "../track/yolov4-tiny_final.weights"
    #metaPath = "../track/obj-google.data"
    
    thresh = 0.3
    if not os.path.exists(configPath):
        raise ValueError("Invalid config path `" +
                         os.path.abspath(configPath)+"`")
    if not os.path.exists(weightPath):
        raise ValueError("Invalid weight path `" +
                         os.path.abspath(weightPath)+"`")
    if not os.path.exists(metaPath):
        raise ValueError("Invalid data file path `" +
                         os.path.abspath(metaPath)+"`")
    if netMain is None:
        netMain = darknet.load_net_custom(configPath.encode(
            "ascii"), weightPath.encode("ascii"), 0, 1)  # batch size = 1
    if metaMain is None:
        metaMain = darknet.load_meta(metaPath.encode("ascii"))
    if altNames is None:
        try:
            with open(metaPath) as metaFH:
                metaContents = metaFH.read()
                import re
                match = re.search("names *= *(.*)$", metaContents,
                                  re.IGNORECASE | re.MULTILINE)
                if match:
                    result = match.group(1)
                else:
                    result = None
                try:
                    if os.path.exists(result):
                        with open(result) as namesFH:
                            namesList = namesFH.read().strip().split("\n")
                            altNames = [x.strip() for x in namesList]
                except TypeError:
                    pass
        except Exception:
            pass
    #cap = cv2.VideoCapture(0)

    if ( not args.video == "" ):
        print("Loading: {}". format(args.video))
        cap = cv2.VideoCapture(args.video, cv2.CAP_GSTREAMER)
    else:
        print("Loading: {}". format(GST_STR))
        cap = cv2.VideoCapture(GST_STR, cv2.CAP_GSTREAMER)
        #cap = cv2.VideoCapture("v4l2src io-mode=2 device=/dev/video0 ! video/x-raw, format=YUY2, width=1920, height=1080, framerate=60/1 !  nvvidconv ! video/x-raw(memory:NVMM), format=(string)I420 ! nvvidconv ! video/x-raw, format=(string)BGRx ! videoconvert ! video/x-raw, format=BGR ! appsink sync=false async=false drop=true")

    #cap = cv2.VideoCapture("test.mp4")

    #cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_OPENGL)
    if full_scrn == True:
        cv2.namedWindow(WINDOW_NAME, cv2.WND_PROP_FULLSCREEN) 
        cv2.setWindowProperty(WINDOW_NAME, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
        cv2.moveWindow(WINDOW_NAME, 0, 0)
        cv2.resizeWindow(WINDOW_NAME, 640, 360)
    else:
        cv2.namedWindow(WINDOW_NAME, cv2.WND_PROP_FULLSCREEN) 
        cv2.resizeWindow(WINDOW_NAME, 640, 360)

    #cap.set(3, video_width)
    #cap.set(4, video_height)
    

    ##This will write the code
    if ( not args.save_video == "" ):
        fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
        

        if ( args.show_video == True ):
            out_video = cv2.VideoWriter( args.save_video , fourcc, 30, (video_width, video_height))
        else:
            out_video = cv2.VideoWriter( args.save_video , fourcc, 30, (darknet.network_width(netMain), darknet.network_height(netMain)))


    #out = cv2.VideoWriter(
     #   "output.avi", cv2.VideoWriter_fourcc(*"MJPG"), 30.0,
     #   (darknet.network_width(netMain), darknet.network_height(netMain)))


    print("Starting the YOLO loop...")

    
    buzzer_f = VibratorThread( [27], 2, 0.5)
    buzzer_l = VibratorThread( [17], 2, 0.3)
    buzzer_r = VibratorThread( [18], 2, 0.3)
    buzzer_s = VibratorThread( [27], 2, 1)
    buzzer_t = VibratorThread( [17,18], 2, 2)    
    
    buzzer_f.start()
    buzzer_l.start()
    buzzer_r.start()
    buzzer_s.start()
    buzzer_t.start()



    # Create an image we reuse for each detect

    if ( args.show_video == True ):
        darknet_image = darknet.make_image(video_width,video_height,3)
    else:
        darknet_image = darknet.make_image(darknet.network_width(netMain),
                                        darknet.network_height(netMain),3)

    #faulthandler.enable()



    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    GPIO.remove_event_detect(shutdown_pin)

    print("Starting demo now! Press CTRL+C to exit")

    
    try: 
        print("Setting Shutdown to LOW")
        GPIO.setup(shutdown_pin, GPIO.OUT) 
        GPIO.output(shutdown_pin, GPIO.LOW)
        ##time.sleep(1)
        GPIO.cleanup(shutdown_pin)
        GPIO.setup(shutdown_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Set pin 10 to be an input pin and set initial value to be pulled low (off)
        GPIO.add_event_detect(shutdown_pin, GPIO.BOTH, callback=button_callback) # Setup event on pin 10 rising edge          

    finally:
        pass




    while True:

        
        if cv2.getWindowProperty(WINDOW_NAME, 0) < 0:
            # Check to see if the user has closed the window
            # If yes, terminate the program

            
            #stop the buzzer
            if non_stop_buzzer.isAlive():
                try:
                    non_stop_buzzer.stopit()
                    non_stop_buzzer.join()
                except:
                    pass        
            break            
            
                 
        

        prev_time = time.time()
        ret, frame_read = cap.read()

        
        if ret != True:
            print("Video open failed, run:")
            print("sudo systemctl restart nvargus-daemon")
            break
        

        cv2.imshow(WINDOW_NAME, frame_read)                 
        frame_rgb = cv2.cvtColor(frame_read, cv2.COLOR_BGR2RGB)

        if ( args.show_video == True ):
            darknet.copy_image_from_bytes(darknet_image,frame_rgb.tobytes())
        else:

            frame_resized = cv2.resize(frame_rgb,
                                    (darknet.network_width(netMain),
                                    darknet.network_height(netMain)),
                                    interpolation=cv2.INTER_LINEAR)

            darknet.copy_image_from_bytes(darknet_image,frame_resized.tobytes())
        
        #Printing the detections
        detections = darknet.detect_image(netMain, metaMain, darknet_image, thresh=thresh, debug=False)

        #print(detections)

        ### Edited the code to perform what what ever you need to
              

        if ( args.show_video == True ):             
            image = cvDrawBoxes(detections, frame_rgb)
        else:
            
            image = cvDrawBoxes(detections, frame_resized)
        
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)        

        myCustomActions(detections,image)

        cv2.putText(image,
                    "FPS: {:.2f}" .format( (1.0 / (time.time()-prev_time)) ),
                    (10, 25),  cv2.FONT_HERSHEY_SIMPLEX, 1,
                    (0, 255, 0), 2)

        # resize image
        #dim = (640, 480)        
        #resized = cv2.resize(image, dim, interpolation = cv2.INTER_LINEAR)
    
        cv2.imshow(WINDOW_NAME, image)

        if ( not args.save_video == "" ):
            out_video.write(image)

        print("FPS: {:.2f}".format( 1/(time.time()-prev_time) )  )
        print("**************")


        key = cv2.waitKey(1)
        if key == 27 or key == ord("q"): # ESC 

            try:
                buzzer_f.stopit()
                buzzer_f.join()
                buzzer_l.stopit()
                buzzer_l.join()
                buzzer_r.stopit()
                buzzer_r.join()
                buzzer_s.stopit()
                buzzer_s.join()
                buzzer_t.stopit()
                buzzer_t.join()
            except:
                pass

            #stop the buzzer
            """
            if non_stop_buzzer.isAlive():
                try:
                    non_stop_buzzer.stopit()
                    non_stop_buzzer.join()
                except:
                    pass        
            break
            """

        
    cap.release()
    GPIO.cleanup()


    if ( not args.save_video == "" ):
        out_video.release()
    # Equal: CCW viewed from shaft -> positive angle change
    if value_b == GPIO.HIGH:
        update_angle(1)
    # Not Equal: CW viewed from shaft -> negative angle change
    else:
        update_angle(-1)

    # event_time = time.time() - start
    # if event_time < 0.00001:
    # 	time.sleep(0.00001 - event_time)
    # print("Event time" + str(event_time))


loop = asyncio.get_event_loop()

GPIO.add_event_detect(input_pin_a, GPIO.RISING, callback=rotation_detect)
#
# try:
# 	while True:
# 		start = time.time()
#
# 		# print("Pin value" + str(value))
# 		value_a = GPIO.input(input_pin_a)
# 		value_b = GPIO.input(input_pin_b)
#
# 		if prev_value != value_a:
# 			# update_angle(1)
# 			# Equal: CCW viewed from shaft -> positive angle change
# 			if value_a == value_b:
# 				update_angle(1)
# 			# Not Equal: CW viewed from shaft -> negative angle change
예제 #27
0
def setupGPIO():
    GPIO.setmode(GPIO.BOARD)  # BOARD pin-numbering scheme
    GPIO.setup(INPUT_PIN, GPIO.IN)  # button pin set as input
    GPIO.add_event_detect(INPUT_PIN, GPIO.RISING, callback=read_angle)
예제 #28
0
def main():

    global clickState
    global firstTime
    global secondTime
    global program_step
    global print_once_flag
    global timeEclipse
    global clickFlag
    global click_once
    global time_long_set
    global time_long_long_set
    global falling_edge_flag
    global rising_edge_flag
    global cansel_flag
    global ok_flag

    # Pin Setup:
    GPIO.setmode(GPIO.BOARD)  # BOARD pin-numbering scheme
    #GPIO.setup([led_pin_1, led_pin_2], GPIO.OUT)  # LED pins set as output
    GPIO.setup(gpi_grabimage, GPIO.IN)  # button pin set as input

    # Initial state for LEDs:
    #GPIO.output(led_pin_1, GPIO.LOW)
    #GPIO.output(led_pin_2, GPIO.LOW)

    GPIO.add_event_detect(gpi_grabimage,
                          GPIO.BOTH,
                          callback=blink,
                          bouncetime=200)

    # print("Starting demo now! Press CTRL+C to exit")
    pwm = PCA9685()
    pwm.setPWMFreq(50)
    pwm.setPWM(3, 0, 0)  #关闭可见激光
    pwm.setPWM(4, 0, 0)  #关闭红外光源
    pwm.setPWM(5, 0, 0)  #关闭红外激光

    try:
        while True:

            if (clickState == 1):
                timeEclipse = time.time() - firstTime
                if (timeEclipse > time_long_set):
                    ok_flag = 1
                    clickFlag = 1
                    clickState = 0
                    firstTime = 0
                    #print("state 3")

                else:
                    time.sleep(0.01)
                    click_once = 0

            if (clickState == 2):
                timeEclipse = secondTime - firstTime
                if (timeEclipse < time_long_set):
                    cansel_flag = 1
                    clickFlag = 2
                    secondTime = 0
                    firstTime = 0
                    clickState = 0

            if (clickFlag == 1):
                #print("this is single click")
                clickState = 0
                clickFlag = 0
            elif (clickFlag == 2):
                #print("this is double click")
                clickState = 0
                clickFlag = 0
            if (clickFlag == 3):
                clickState = 0
                clickFlag = 0
                #print("this is changan")

            if (program_step == 1 and print_once_flag == 0):
                #print("点亮可见激光")
                #print("点亮不可见激光")
                #print("点亮光源")
                pwm.setPWM(3, 0, 4095)  #点亮可见激光
                pwm.setPWM(4, 0, 4095)  #点亮红外光源
                pwm.setPWM(5, 0, 4095)  #点亮红外激光
                print(
                    "======================================================================"
                )
                print_once_flag = 1
            if (program_step == 2 and print_once_flag == 1):
                #print("熄灭光源")
                pwm.setPWM(4, 0, 2000)  #熄灭红外光源
                print("抓拍一张混合图像")  #将此句话替换成拍照激光图片的函数即可
                time.sleep(0.5)

                pwm.setPWM(4, 0, 0)  # 熄灭红外光源
                pwm.setPWM(3, 0, 0)  # 熄灭可见激光
                pwm.setPWM(5, 0, 0)  # 熄灭红外激光
                print("开始上传混合图像")  #将此句话替换成上传灰度图片的函数即可

                time.sleep(0.5)
                print("显示轮廓图像")  #将此句话替换成显示轮廓图片的函数即可
                print("等待确认回复")
                print(
                    "======================================================================"
                )
                print_once_flag = 2

            if (program_step == 2 and cansel_flag == 1
                    and print_once_flag == 2):
                cansel_flag = 0
                print("取消重新开始")
                print(
                    "======================================================================"
                )
                print_once_flag = 0
                program_step = 0

            if (program_step == 2 and ok_flag == 1 and print_once_flag == 2):
                ok_flag = 0
                print("确认重新开始")
                print(
                    "======================================================================"
                )
                print_once_flag = 0
                program_step = 0

    finally:
        GPIO.cleanup()  # cleanup all GPIOs
    return


def shutdown():
    print('Delay until shutdown:', POWER_OFF_DELAY)
    time.sleep(POWER_OFF_DELAY)
    print('Shutting down')
    time.sleep(POWER_OFF_DELAY_SECONDARY)
    os.system('shutdown -h now')


def power_status_changed(channel):
    if GPIO.input(channel):
        schedule_shutdown()
    else:
        cancel_shutdown()


GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(PLD_PIN, GPIO.IN)
GPIO.add_event_detect(PLD_PIN, GPIO.BOTH, power_status_changed)

#We don't know if the device is starting with AC power
#initially powered or not. Probe status and schedule
#shutdown if necessary

power_status_changed(PLD_PIN)
raw_input(
    "\x1b[0;37mmonitoring power\n\nPress '\x1b[1;36mEnter'\x1b[0;37m to exit")
#Anyon notice the irony if the button labeled "enter" being used to exit?
예제 #30
0
 def __init__(self, pins):
     self.queue = Circular_Queue(20)
     self.last_dir = -1
     for pin in pins:
         GPIO.setup(pin, GPIO.IN)
         GPIO.add_event_detect(pin, GPIO.FALLING, callback=self.callback)