Tuesday, February 24, 2009

Poor man's obstacle avoiding spike via python and lego nxt mindstorms

Ok so this script is a python script for the nxt brick, and in particular for the spike configuration. What it does is, looks for obstacles in kind of a cheap way. It checks the ultrasonic sensor and if it's less than 255 then it starts to only use one side to move...IE it turns. So it's kind of a pathetic script but I threw it together last night, mainly because I don't see any custom python code on the net for nxt python. There's some code for the tail commented out btw.

Ok so a caveat for mac users, you need to do this to get it to nxt_python to work:
http://www.cs.wlu.edu/~levy/software/nxt_lightblue_glue/

PC users should be fine assuming the appropriate modules are installed.


#!/usr/bin/env python
import time
import nxt.locator
from nxt.motor import *
from nxt.sensor import *
sock = nxt.locator.find_one_brick()
def moveit(brick):
#m_camera = Motor(brick, PORT_A)
#m_camera.power = 100 # 100% power
#m_camera.mode = MODE_MOTOR_ON
#m_camera.run_state = RUN_STATE_RUNNING
#m_camera.tacho_limit = 80
#m_camera.set_output_state()

m_camerc = Motor(brick, PORT_C)
m_camerc.power = 100 # 100% power
m_camerc.mode = MODE_MOTOR_ON
m_camerc.run_state = RUN_STATE_RUNNING
m_camerc.tacho_limit = 1000
m_camerc.set_output_state()

m_camerb = Motor(brick, PORT_B)
m_camerb.power = 100 # 100% power
m_camerb.mode = MODE_MOTOR_ON
m_camerb.run_state = RUN_STATE_RUNNING
m_camerb.tacho_limit = 1000
m_camerb.set_output_state()

def moveitback(brick):
m_camera = Motor(brick, PORT_A)
m_camera.power = -100 # 100% power
m_camera.mode = MODE_MOTOR_ON
m_camera.run_state = RUN_STATE_RUNNING
m_camera.tacho_limit = 80
m_camera.set_output_state()
def moveitleft(brick):
#m_camera = Motor(brick, PORT_A)
#m_camera.power = 100 # 100% power
#m_camera.mode = MODE_MOTOR_ON
#m_camera.run_state = RUN_STATE_RUNNING
#m_camera.tacho_limit = 80
#m_camera.set_output_state()

m_camerc = Motor(brick, PORT_C)
m_camerc.power = 100 # 100% power
m_camerc.mode = MODE_MOTOR_ON
m_camerc.run_state = RUN_STATE_RUNNING
m_camerc.tacho_limit = 1000
m_camerc.set_output_state()
def test_sensors(b):
print 'Touch:',
if TouchSensor(b, PORT_1).get_sample():
print 'yes'
else:
print 'no'
print 'Sound:', SoundSensor(b, PORT_2).get_sample()
print 'Ultrasonic:', UltrasonicSensor(b, PORT_3).get_sample()
sock = nxt.locator.find_one_brick(host='00:16:53:09:F4:4A', name='NXT')
if sock:
b = sock.connect()
terd = 1
while terd<= 30:
objectd = UltrasonicSensor(b, PORT_3).get_sample()
print objectd
if objectd == 255:
print '255'
moveit(b)
time.sleep(1)
else:
moveitleft(b)
time.sleep(1)
sock.close()
else:
print 'No NXT bricks found'

No comments: