Advertisement
l33tllama

CircuitPython Ultrasonic Robot Main Code

Jul 2nd, 2020
867
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. # Write your code here :-)
  2. import board
  3. import pulseio
  4. from digitalio import DigitalInOut, Direction
  5. import adafruit_hcsr04
  6. import time
  7.  
  8. sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.D12, echo_pin=board.D11)
  9.  
  10. EN1_PIN = board.D6
  11. EN2_PIN = board.D5
  12. IN1_PIN = board.D7
  13. IN2_PIN = board.D4
  14. en1 = None
  15. en2 = None
  16. in1 = None
  17. in2 = None
  18. uart = None
  19.  
  20. def motor_1(pwm, reverse=False):
  21.     global en1
  22.     en1.duty_cycle = pwm * 255
  23.     if reverse:
  24.         in1.value = True
  25.     else:
  26.         in1.value = False
  27.  
  28. def motor_2(pwm, reverse=False):
  29.     global en1
  30.     en2.duty_cycle = pwm * 255
  31.     if reverse:
  32.         in2.value = True
  33.     else:
  34.         in2.value = False
  35.  
  36.  
  37. def setup():
  38.     global en1
  39.     global en2
  40.     global in1
  41.     global in2
  42.     en1 = pulseio.PWMOut(EN1_PIN, frequency=5000, duty_cycle=0)
  43.     en2 = pulseio.PWMOut(EN2_PIN, frequency=500, duty_cycle=0)
  44.     in1 = DigitalInOut(IN1_PIN)
  45.     in1.direction = Direction.OUTPUT
  46.     in2 = DigitalInOut(IN2_PIN)
  47.     in2.direction = Direction.OUTPUT
  48.  
  49. setup()
  50.  
  51.  
  52. while True:
  53.     motor_1(255)
  54.     motor_2(255)
  55.  
  56.     distance = 0
  57.  
  58.     try:
  59.        distance = sonar.distance
  60.     except RuntimeError:
  61.         print("Retrying!")
  62.  
  63.     print((distance,))
  64.  
  65.     if distance > 0 and distance < 8:
  66.         motor_1(0)
  67.         motor_2(0)
  68.  
  69.         time.sleep(0.2)
  70.  
  71.         motor_1(255, reverse=True)
  72.         motor_2(255, reverse=True)
  73.  
  74.         time.sleep(0.8)
  75.  
  76.         motor_1(255, reverse=False)
  77.         motor_2(255, reverse=True)
  78.  
  79.         time.sleep(0.5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement