def call_sonar(TRIG, ECHO): GPIO.setmode(GPIO.BOARD) GPIO.setup(TRIG,GPIO.OUT) GPIO.setup(ECHO,GPIO.IN) GPIO.output(TRIG, GPIO.LOW) GPIO.output(TRIG,GPIO.HIGH) time.sleep(0.00001) GPIO.output(TRIG, GPIO.LOW) pulse_start = time.time() pulse_end = time.time() count = 0 flag = 0 while GPIO.input(ECHO)==0: pulse_start = time.time() count = count + 1 if count >= 5: print ("I break") flag = 1 break while GPIO.input(ECHO)==1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start distance = pulse_duration * 17150 distance = round(distance,2) if flag == 1 or distance < 0: distance = 0 return distance
def getDistance(self): # pins setup GPIO.setup(self.trig, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(self.echo, GPIO.IN) # set Trigger to HIGH for 10 us GPIO.output(self.trig, GPIO.HIGH) time.sleep(0.00001) # 10 us GPIO.output(self.trig, GPIO.LOW) # start counting time at Echo rising edge GPIO.wait_for_edge(self.echo, GPIO.RISING, timeout=100) # 100 ms startTime = time.time() # stop counting time at Echo falling edge GPIO.wait_for_edge(self.echo, GPIO.FALLING, timeout=100) # 100 ms elapsedTime = time.time() - startTime # in seconds distance = -1 # check if the measurement succeeded if elapsedTime < 0.1: # get the distance in cm using sonic speed (aprox. 34300 cm/s) distance = (elapsedTime * 34300) / 2 GPIO.cleanup([self.trig, self.echo]) return distance
def __init__(self, trigger_pin, echo_pin, invert_echo_pin=False, max_timeout=10, callback=None, args=[]): Thread.__init__(self) self._stopped = Event() self._startSignal = Event() self._oneRunFinished = Event() self._process = _INIT self._echo_pin = echo_pin self._trigger_pin = trigger_pin self._invert_echo_pin = invert_echo_pin self._echo_times = np.array([0.0, 0.0]) self._time_diff = 0.0 self._response_after_trig_timeout = 0.005 #ms self._max_timeout = self._response_after_trig_timeout + max_timeout self._call_back_fn = callback self._call_back_args = args GPIO.setmode(GPIO.BOARD) GPIO.setup(self._echo_pin, GPIO.IN) GPIO.setup(self._trigger_pin, GPIO.OUT, initial=GPIO.HIGH)
def main(): GPIO.setmode(GPIO.BOARD) GPIO.setup(output_pin, GPIO.OUT, initial=GPIO.HIGH) #cv2.imshow('test', img) #cv2.waitKey() #time.sleep(20) thread2 = ThreadWatchDog(1) thread2.start() try: #img = np.zeros((800, 800)) start_lidar() i2c.LidarOn() #wait for started time.sleep(1) lidar.connect() health = lidar.get_health() print(health) iterator = lidar.iter_scans() thread1 = Thread1(1) thread1.start() while True: #run_lidar() #detector(img) cv2.imshow("test", img) cv2.waitKey(1) finally: stop_lidar()
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()
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
def main(argv): global output_pin, frequency, state_flag, perma_state, random_flag, random_size, times if len(argv) == 1: print( 'Using default values of: Output Pin = Board 12, Frequency = 30 Hz' ) try: opts, args = getopt.getopt( argv, "hs:r:f:t:", ["state=", "random=", "frequency=", "times="]) except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt == '-h': usage() sys.exit() elif opt in ('-s', '--state'): state_flag = True perma_state = get_perma_state(arg) elif opt in ('-f', '--freq'): frequency = int(arg) elif opt in ('-r', '--random'): random_flag = True random_size = int(arg) elif opt in ('-t', '--times'): times = int(arg) signal.signal(signal.SIGINT, interrupt_handler) if state_flag: GPIO.setmode(GPIO.BOARD) GPIO.setup(output_pin, GPIO.OUT, initial=perma_state) GPIO.output(output_pin, perma_state) print('Output set to permanent state: {0}'.format(perma_state)) GPIO.cleanup(output_pin) elif random_flag: # logging config # ToDo: Change the filename here if in the future our datasets change logging.basicConfig( filename='DataLog/TXDATA/transmitter_{0}Hz_{1}_cycles-{2}_bits.log' .format(frequency, times, random_size), level=logging.INFO, format='%(asctime)s %(message)s') random_bits = generate_random_bitstream(random_size) logging.info("Generated bitstream: {0}".format(random_bits)) transmission = create_transmission(random_bits, times) f = open( 'DataLog/TXDATA/raw_bitsream_{0}Hz_{1}_cycles-{2}_bits.txt'.format( frequency, times, random_size), "w+") f.write(transmission) print("Transmitting") logging.info("Starting Transmission") transmit(transmission) logging.info("Transmisssion Ended") else: print('No flags set, exiting') GPIO.output(output_pin, GPIO.LOW) usage() sys.exit(0)
def __init__(self): super().__init__('status_light') self.sample_received = False self.light_on = False # Init GPIO GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(7, GPIO.OUT, initial=GPIO.LOW) GPIO.output(7, GPIO.LOW) # Create QOS for subscriber qos_klr_v = QoSProfile(history=QoSHistoryPolicy.RMW_QOS_POLICY_HISTORY_KEEP_LAST, depth=1, reliability=QoSReliabilityPolicy.RMW_QOS_POLICY_RELIABILITY_RELIABLE, durability=QoSDurabilityPolicy.RMW_QOS_POLICY_DURABILITY_VOLATILE) # Create subscriber self.sub = self.create_subscription( msg_type=UInt32, topic='camera_trigger', callback=self.listener_callback, qos_profile=qos_klr_v ) # Setup timer timer_period_secs = 0.2 self.timer = self.create_timer( timer_period_secs, self.timer_callback )
def output_operation(pin, state): """ Perform the OUTPUT operation """ GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, state) GPIO.cleanup()
def __init__(self, init_angle=0): GPIO.setmode(GPIO.BOARD) self.a_pin = 18 self.b_pin = 16 GPIO.setup([self.a_pin, self.b_pin], GPIO.IN) self.e = multiprocessing.Event() self.angle_queue = multiprocessing.Queue() # self.angle_queue.put(None) self.angle_store_time = None self.a_prev = None self.b_prev = None if init_angle == 0: self.count = 0 else: self.count = int(180 * (360 / 1024)) self.encoder_process = multiprocessing.Process( target=self.read_Encoder, args=(self.e, )) # self.encoder_process.start() print("Started encoder child process")
def main(): # Pin Setup: # Board pin-numbering scheme GPIO.setmode(GPIO.BOARD) # set pin as an output pin with optional initial state of LOW GPIO.setup(trig_output_pin, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(echo_input_pin, GPIO.IN) #value = GPIO.input(echo_input_pin) #print("Value read from pin {} : {}".format(echo_input_pin,value_str)) print("Starting Measure now! Press CTRL+C to exit") try: while True: # Toggle the output every second GPIO.output(trig_output_pin, GPIO.HIGH) time.sleep(0.00001) GPIO.output(trig_output_pin, GPIO.LOW) pulse_start = time.time() while GPIO.input(echo_input_pin)==0: pulse_start = time.time() pulse_end = time.time() while GPIO.input(echo_input_pin)==1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start distance = pulse_duration * 17150 distance = round(distance, 2) print ("Distance" , distance) finally: GPIO.cleanup()
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)
def __init__(self, stepper_name, pins, sensor_pin, negate_sensor, reverse, max): self.stepper_name = stepper_name self.pins = pins self.sensor_pin = sensor_pin self.negate_sensor = negate_sensor self.reverse = reverse self.actual_position = 0 self.backsteps = 1000 #If sensor is pressed move this steps back self.seq = [[1, 0, 0, 0], [1, 1, 0, 0], [0, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1], [1, 0, 0, 1]] self.direction = -1 #1:CounterClockwise -1:Clockwise self.min = 0 #Min is 0 when hit the sensor self.max = max #Max value to turn #Use board layout to set pin name GPIO.setmode(GPIO.BOARD) #Configure GPIO for pin in self.pins: GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, 0) GPIO.setup(sensor_pin, GPIO.IN) #GPIO.setup(sensor_pin,GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #Init position stepper self.init_position()
def __init__(self, dout_pin, pd_sck_pin, gain=128, channel='A'): """ :param dout_pin: number of the GPIO DOUT is connectedt to :type dout_pin: int :param pd_sck_pin: number of the GPIO SCK is connectedt to :type int :param gain: gain :type gain: int :param channel: selected channel :type channel: str """ if (isinstance(dout_pin, int) and isinstance( pd_sck_pin, int)): # just check of it is integer self._pd_sck = pd_sck_pin # init pd_sck pin number self._dout = dout_pin # init data pin number else: raise TypeError('dout_pin and pd_sck_pin have to be pin numbers.\nI have got dout_pin: ' \ + str(dout_pin) + \ ' and pd_sck_pin: ' + str(pd_sck_pin) + '\n') GPIO.setmode(GPIO.BCM) # set GPIO pin mode to BCM numbering GPIO.setup(self._pd_sck, GPIO.OUT) # pin _pd_sck is output only GPIO.setup(self._dout, GPIO.IN) # pin _dout is input only self.channel = channel self.channel_a_gain = gain
def __init__(self, is_right, period = 0.20, sensor_state_manager = None, sensor_key = ''): global RIGHT_CHANNEL global LEFT_CHANNEL if GPIO.getmode() != GPIO.TEGRA_SOC: GPIO.setmode(GPIO.TEGRA_SOC) # Initialization of GPIO pin identification mode self.period = period # Sampling time period (each measurement is taken at every <period>). Default set to 1 millisecond self.current_time = 0.0 # Used to store current time in UTC ms from epoch (1/1/1970 00:00) self.channel = RIGHT_CHANNEL # Left or right channel identification for left/right wheel self.he_value = 0.0 #Measured value is instantaneous angular velocity (approximation) self.measured_value = [0.0, 0.0, 0.0] if is_right: GPIO.setup(self.channel, GPIO.IN) else: self.channel = LEFT_CHANNEL GPIO.setup(self.channel, GPIO.IN) self.he_value = GPIO.input(self.channel) #Initialize hall effect sensor value self.is_ready = True self.sensor_key = sensor_key self.sensor_state_manager = sensor_state_manager
def __init__(self, dout, pd_sck, gain=32): self.PD_SCK = pd_sck self.DOUT = dout GPIO.setmode(GPIO.BOARD) GPIO.setup(self.PD_SCK, GPIO.OUT) GPIO.setup(self.DOUT, GPIO.IN) self.GAIN = 0 self.REFERENCE_UNIT = 1 # The value returned by the hx711 that corresponds to your reference unit AFTER dividing by the SCALE. self.OFFSET = 1 self.lastVal = 0 self.LSByte = [2, -1, -1] self.MSByte = [0, 3, 1] self.MSBit = [0, 8, 1] self.LSBit = [7, -1, -1] self.byte_range_values = self.LSByte self.bit_range_values = self.MSBit self.set_gain(gain) time.sleep(1)
def __init__(self, GPIO_mode: str, GPIO_pinout: int, active_artwork_file_path: str, image_directory: str, loop_sleep_sec: float = 1.0) -> None: try: mode = GPIO_MODES[GPIO_mode] GPIO.setmode(mode) GPIO.setup(GPIO_pinout, GPIO.IN) self.GPIO_pinout = GPIO_pinout except Exception as e: print(e.message) sys.exit(1) if ('.jpg' in active_artwork_file_path) and ( os.path.isfile(active_artwork_file_path)): self.active_artwork_file_path = active_artwork_file_path else: raise ValueError( 'Active arwork file is not a .jpg or does not exist.') if os.path.isdir(image_directory): self.image_directory = image_directory self.loop_sleep_sec = loop_sleep_sec
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()
def init_gpio(self): GPIO.setmode(GPIO.BOARD) for i_num in range(0, self.i_size): GPIO.setup(self.pin_index_i, GPIO.IN) for o_num in range(0, self.o_size): GPIO.setup(self.pin_index_o, GPIO.OUT)
def drive(): pwm = PCA9685() pwm.setPWMFreq(50) pwm.setRotationAngle(CAM_X, 180) pwm.setRotationAngle(CAM_Y, 180) pwm.setServoPulse(LEFT_MOTOR, 1501) pwm.setServoPulse(RIGHT_MOTOR, 1501) GPIO.setmode(GPIO.BOARD) GPIO.setup(LEFT_ENABLE, GPIO.OUT, initial=GPIO.HIGH) GPIO.setup(RIGHT_ENABLE, GPIO.OUT, initial=GPIO.HIGH) listen_addr = ('127.0.0.1', 10008) conn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) conn.bind(listen_addr) while True: data, _ = conn.recvfrom(BUF_SIZE) left_x = int.from_bytes(data[:1], byteorder='little', signed=True) left_y = int.from_bytes(data[1:2], byteorder='little', signed=True) right_x = int.from_bytes(data[2:3], byteorder='little', signed=True) right_y = int.from_bytes(data[3:], byteorder='little', signed=True) left_motor, right_motor = electric_differential(left_x, left_y) # according to motor setting, need to reserve left motor pwm.setServoPulse(LEFT_MOTOR, 3000 - left_motor) pwm.setServoPulse(RIGHT_MOTOR, right_motor) pwm.setRotationAngle(CAM_X, 160 - (right_x / 128.0 * 70 + 90)) pwm.setRotationAngle(CAM_Y, min(right_y / 128.0 * 70 + 120, 180))
def fanFunction(): # From left to right the inputs of RGB LED are R, Ground, G, B fanPin = 19 # pin 35 GPIO.setup(fanPin, GPIO.OUT, initial=GPIO.LOW) GPIO.output(fanPin, GPIO.HIGH) #deadline = 200 # in miliseconds # ENSURE DEADLINE MET, IDK HOW TO DO THIS IN PYTHON return 1
def remove_air_sprays(front_sprayer=None, back_sprayer=None, time_interval=8): try: # Quantity of sprayers sprayers = len(front_sprayer) # Setting initial values for sprayers GPIO.setup(front_sprayer, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(back_sprayer, GPIO.OUT, initial=GPIO.LOW) # Initiating spray from the last one until the closest to the bar print( f'[WEEDS] OPENING the pin {front_sprayer[-1]} of the blue sprayer') print( f'[WEEDS] OPENING the pin {back_sprayer[-1]} of the red sprayer\n') GPIO.output(front_sprayer[-1], GPIO.HIGH) GPIO.output(back_sprayer[-1], GPIO.HIGH) sleep(time_interval) for index in range(1, sprayers): print( f'[WEEDS] CLOSING the pin {front_sprayer[-index]} of the blue sprayer' ) print( f'[WEEDS] CLOSING the pin {back_sprayer[-index]} of the red sprayer\n' ) GPIO.output(front_sprayer[-index], GPIO.LOW) GPIO.output(back_sprayer[-index], GPIO.LOW) sleep(time_interval) print( f'[WEEDS] OPENING the pin {front_sprayer[-index - 1]} of the blue sprayer' ) print( f'[WEEDS] OPENING the pin {back_sprayer[-index - 1]} of the red \n' ) GPIO.output(front_sprayer[-index - 1], GPIO.HIGH) GPIO.output(back_sprayer[-index - 1], GPIO.HIGH) sleep(time_interval) print( f'[WEEDS] CLOSING the pin {front_sprayer[-sprayers]} of the blue sprayer' ) print( f'[WEEDS] CLOSING the pin {back_sprayer[-sprayers]} of the red sprayer\n' ) GPIO.output(front_sprayer[-sprayers], GPIO.LOW) GPIO.output(back_sprayer[-sprayers], GPIO.LOW) except KeyboardInterrupt: print("[WEEDS] Turning off the sprayers.") GPIO.output(front_sprayer, GPIO.LOW) GPIO.output(back_sprayer, GPIO.LOW) GPIO.cleanup() sys.exit()
def setup(): GPIO.setup(DIR, GPIO.OUT) GPIO.setup(STEP, GPIO.OUT) GPIO.setup(ENABLE, GPIO.OUT) GPIO.setup(MS1, GPIO.OUT) GPIO.setup(MS2, GPIO.OUT) reset_pins() # Open Serial connection for debugging print("Begin motor control")
def __init__(self): GPIO.setmode(GPIO.BCM) self.motor_lx = Motor(26, 21) self.motor_rx = Motor(16, 19) self.enable_lx = 13 self.enable_rx = 20 GPIO.setup(self.enable_lx, GPIO.OUT, initial=GPIO.HIGH) GPIO.setup(self.enable_rx, GPIO.OUT, initial=GPIO.HIGH)
def __init__(self, trigpin=None, echopin=None): self.__trigpin = trigpin self.__echopin = echopin GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(trigpin, GPIO.OUT) GPIO.setup(echopin, GPIO.IN)
def __init__(self, out1, out2, pca9685, pwm): self.__out1 = out1 self.__out2 = out2 GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(out1, GPIO.OUT, initial= GPIO.LOW) GPIO.setup(out2, GPIO.OUT, initial=GPIO.LOW) self.__pca9685 = pca9685 self.__pwm = pwm
def __init__(self, control_pins = DEFAULT_CONTROL_PINS, step_time = DEFAULT_STEP_TIME): self.control_pins = control_pins self.step_time = step_time #GPIO.setmode(GPIO.BCM) GPIO.setmode(GPIO.TEGRA_SOC) for pin in self.control_pins: GPIO.setup(pin, GPIO.OUT) self._output(IDLE_PATTERN)
def __blink(self): GPIO.setmode(self.__pin_type) GPIO.setup(self.__output_pin, GPIO.OUT, initial=GPIO.HIGH) curr_value = GPIO.HIGH try: GPIO.output(self.__output_pin, curr_value) curr_value ^= GPIO.HIGH finally: GPIO.cleanup()
def __init__(self, pos, neg, conv, nconv, mode=GPIO.BOARD): GPIO.setmode(mode) GPIO.setup((pos, neg, conv, nconv), GPIO.OUT) self.pos = pos self.neg = neg self.conv = conv self.nconv = nconv logger.debug( f"GPIO module initialized as pos:{pos}, neg:{neg}, conv:{conv}, nconv:{nconv} @mode: {mode}" )
def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = uic.loadUi("widget.ui") self.ui.setWindowTitle("GPIO test") self.ui.show() GPIO.setmode(GPIO.BOARD) GPIO.setup(led_pin, GPIO.OUT) # set as output GPIO.output(led_pin, GPIO.LOW) self.ui.btn_up.clicked.connect(self.light_on) self.ui.btn_down.clicked.connect(self.light_off)