I modified the standard line_follow.py script as follows:
The script works fine when I call it from command prompt with [python myline_follow.py and it nicely follows a black line on a white cardboard.
To use it from within Scratch I added a block in GoPiGoScratch.py (block shown below) and defined it in line-sensor.py file accordingly as follows.
When I issue a broadcast command from within Scratch [broadcast FOLLOW LINE] it gives an error that ‘module’ object has no attribute ‘follow_line’
I have attached the scratch file to this post as well. If anybody could help me out I will be extremely grateful.
Thank you very much
<<---------------->>
line-sensor.py
<<---------------->>
def follow_line():
curr=get_sensorval()
diff_val=list(map(operator.sub, curr, white))
curr_pos=0
percent_black_line=[0]*5
for i in range(5):
percent_black_line[i]=diff_val[i]*100/range_col[i]
curr_pos+=percent_black_line[i]*multp[i]
print curr_pos
if curr_pos <-15000:
print "r"
if gpg_en:
gopigo.right()
elif curr_pos >15000:
print "l"
if gpg_en:
gopigo.left()
else:
print "f"
if gpg_en:
gopigo.fwd()
time.sleep(.1)
<<---------------->>
GoPiGoScratch.py block
<<---------------->>
elif msg.lower()=="FOLLOW LINE".lower():
if en_line_sensor:
print "FOLLOW LINE!"
try:
followline=l.follow_line()
except:
if en_debug:
e = sys.exc_info()[1]
print "EXCEPTION: line following module..." + str(e)
if en_debug:
print "Debug message: Line following module."
#-# if en_gpg:
#-# s.sensorupdate({‘follow line’:followline})
<<--------------->>
< myline_follow.py >
<<--------------->>
import line_sensor
import time
import operator
import gopigo
#time.sleep(10)
#Get a value which does have -1
def get_sensorval():
while True:
val=line_sensor.read_sensor()
if val[0]<>-1:
return val
else:
#Read once more to clear buffer and remove junk values
val=line_sensor.read_sensor()
#Add a multipler to each sensor
multp=[-500,-100,0,100,500]
#TRAIN for the first time
#reading when all sensors are at white
white=[60,77,54,63,59]
#reading when all sensors are black
black=[947,971,948,948,934]
#difference between black and white
range_col=list(map(operator.sub, black, white))
gpg_en=1
#-# set motor speeds to calibrate
gopigo.set_left_speed(80)
gopigo.set_right_speed(90)
turn=0
while turn<100:
turn=turn+1
curr=get_sensorval()
#Get current difference bwtween white and line
diff_val=list(map(operator.sub, curr, white))
#find how much black line each sensor is able to get
#find the position of the bot
# -98000 -> extreme left
# 0 -> centre
# 104000 -> extreme right
curr_pos=0
percent_black_line=[0]*5
for i in range(5):
percent_black_line[i]=diff_val[i]*100/range_col[i]
curr_pos+=percent_black_line[i]*multp[i]
print curr_pos
if curr_pos <-10000:
print "turn right"
if gpg_en:
gopigo.right()
elif curr_pos >10000:
print "turn left"
if gpg_en:
gopigo.left()
else:
print "go straight"
if gpg_en:
gopigo.fwd()
time.sleep(.1)
gopigo.stop()