How to use servo motor with TFMini Distance Sensor in python script? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to use servo motor with TFMini Distance Sensor in python script? (/thread-14520.html) |
How to use servo motor with TFMini Distance Sensor in python script? - programerguy - Dec-04-2018 I am using Adafruit TFmini distance sensor, with servo motor. I want the servo motor to move when distance sensor senses a certain distance. My code makes the servo motor move continuously, like crazy. Credits: TfMini distance sensor code is taken from tfmini GitHub, and servo motor code is from raspberry pi tutorials. # -*- coding: utf-8 -* import serial import math import time import RPi.GPIO as GPIO servoPIN = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(servoPIN, GPIO.OUT) fire_gun = GPIO.PWM(servoPIN, 50) #GPIO 5 for PWM with 50Hz fire_gun.start(2.5) #Initialization """ def gunRight(): #fire_gun = GPIO.PWM(servoPIN, 50) #GPIO 5 for PWM with 50Hz #fire_gun.start(2.5) #Initialization print "Shot Fire The First Net Gun" fire_gun.ChangeDutyCycle(4.9) time.sleep(0.4) fire_gun.ChangeDutyCycle(7.2) time.sleep(0.4) print "Servo Motor Back To Rest Position" fire_gun.stop() """ ser = serial.Serial("/dev/ttyUSB0", 115200) def getTFminiData(): while True: count = ser.in_waiting if count > 8: recv = ser.read(9) ser.reset_input_buffer() if recv[0] == 'Y' and recv[1] == 'Y': # 0x59 is 'Y' low = int(recv[2].encode('hex'), 16) high = int(recv[3].encode('hex'), 16) distance = low + high * 256 #My unit conversion starts here dist = float(distance) /100 print(distance) print "Distance to object is:",dist,"Meters" #GPIO.setup(TRIG, GPIO.OUT) #GPIO.setup(ECHO, GPIO.IN) #if dist <= 0.70: #GPIO.output(5, True) try: if ser.is_open == False: ser.open() for i in range(500): getTFminiData() if dist <= 0.70: fire_gun.ChangeDutyCycle(4.9) time.sleep(0.4) GPIO.cleanup() except KeyboardInterrupt: # Ctrl+C if ser != None: #GPIO.cleanup() ser.close() RE: How to use servo motor with TFMini Distance Sensor in python script? - Larz60+ - Dec-04-2018 This package does half of what you want: https://github.com/adafruit/Adafruit_CircuitPython_TFmini perhaps you can easily figure out how to drive servo motor using this for sensor. |