Skip to content

Instantly share code, notes, and snippets.

@JohanS-bricks
Last active May 13, 2021 17:10
Show Gist options
  • Save JohanS-bricks/d66e3ac287d471d5f08552c2eed81ff2 to your computer and use it in GitHub Desktop.
Save JohanS-bricks/d66e3ac287d471d5f08552c2eed81ff2 to your computer and use it in GitHub Desktop.
Instructions on how to code a Mindstorms 51515 Snake robot in Python

Mindstorms 51515 Snake Python program

In the video https://youtu.be/BaeoT4V_PN4 the Mindstorms 51515 snake is programmed in Python. There is a video on how to program the snake with Word Blocks (Scratch programming language) https://youtu.be/qKI21klIH5U which also adds remote control, but the motion loop is not super-tight.

To get the tightest possible movement one need to program it in Python, in this case we have to give up the remote control so the snake will just move forward but will do so in greater style! There is also the potential to utilize the distance sensor to make a wall-avoiding snake for those who want to take it a step further. Programming in Python requires quite a few lines of code to be written. Luckily Anton from Antons Mindstorms Hacks (https://antonsmindstorms.com/) has provided a library that makes all the heavy lifting and allows for very easy animation of the robots.

Prerequisites

  1. Read the article at https://antonsmindstorms.com/2021/02/20/keyframe-motor-animation-with-python-for-mindstorms-and-spike-robots/ and also take the time to check out the Youtube video where he demonstrates how to animate his Tars model.
  2. Create a new Python project in the Mindstorms App and then copy and past the entire biolerplate code from here: https://github.com/antonvh/mp-robot-tools/blob/master/mechanism.py

Programming

Next step is to modify the "boilerplate control loop" that is found at the very bottom of your Python project. Change it into this:

### Boilerplate control loop here

from mindstorms import DistanceSensor

# Initialize the Distance Sensor.
distance = DistanceSensor('B')
distance.light_up_all()

j1 = hub.port.A.motor
j2 = hub.port.C.motor
j3 = hub.port.F.motor
j4 = hub.port.D.motor

a = 50 # Amplitude
p = 1200 # period
o=36 # offset

# Phase displaced sine_wave functions for each motor
j1_func = sine_wave(amplitude = 20, period=p)
j2_func = sine_wave(amplitude = a, period=p, offset = o)
j3_func = sine_wave(amplitude = a, period=p, offset = 180+2*o)
j4_func = sine_wave(amplitude = a, period=p, offset = 180+3*o)

motors = [j1, j2, j3, j4]
motor_functions = [j1_func, j2_func, j3_func, j4_func]
my_mechanism = Mechanism(motors, motor_functions)
my_mechanism.shortest_path_reset()

timer= AMHTimer()

while timer.time < 30000:
    my_mechanism.update_motor_pwms(timer.time)
    utime.sleep_ms(10)
my_mechanism.stop()

raise SystemExit

Run the program

Download the program to a program slot of your choosing and start it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment