Skip to content

Instantly share code, notes, and snippets.

@Bhavithiran97
Created Feb 5, 2021
Embed
What would you like to do?
line follow
import machine
import utime
from motor_driver import * # import motor_driver library
import _thread
Trig = machine.Pin(6,machine.Pin.OUT) # Connect Trig pin to pin 6 and set to OUTPUT
Echo = machine.Pin(7,machine.Pin.IN) # Connect Echo pin to pin 7 and set to INPUT
line = machine.ADC(26) # Set pin 26 as analog INPUT
motor = motor_driver(4,5,2,3) # M1A = 4, M1B = 5, M2A = 2, M2B = 3
global us_trig # Declare global variable
us_trig = False # set false as default value
def read_ultrasonic(): # read ultrasonic function
Trig.value(0)
utime.sleep_us(2)
Trig.value(1)
utime.sleep_us(10)
Trig.value(0)
while Echo.value() == 0:
pulse_start = utime.ticks_us()
while Echo.value() == 1:
pulse_end = utime.ticks_us()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration//58
return distance
def read_line_sensor(): # read line sensor function
return line.read_u16()
def us_reader_thread(): # read ultrasonic thread
global us_trig
while True:
if read_ultrasonic() < 10: # if ultrasonic distance less than 10
us_trig = True # set global variable to True
_thread.start_new_thread(us_reader_thread, ()) # start read ultrasonic thread
while True:
line_value = read_line_sensor()
if us_trig == True: # if ultrasonic triggered
motor.brake() # brake the motor
utime.sleep_ms(500) # sleep 500ms
global us_trig
us_trig = False # set global variable to False
else:
if line_value > 60000: # All line
motor.speed(60,60)
elif line_value > 40000: # S5,S4+S5
motor.speed(60,10)
elif line_value > 34000: # S4,S3+S4
motor.speed(60,30)
elif line_value > 30000: # S3
motor.speed(60,60)
elif line_value > 22000: # S2,S3,+S2
motor.speed(30,60)
elif line_value > 10000: # S1,S2+S1
motor.speed(10,60)
elif line_value > 200: # No line
motor.speed(30,30)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment