Bitkit - Driving
You communicate with the motor controller using the i2c protocol. The way that this has been set up allows us to make a reasonably compact procedure for driving the motors.
The motor controller needs to receive a string of bytes, in the following order.
mode, left_motor_speed, left_motor_direction, right_motor_speed, right_motor_direction
The mode is always set to 1. I can't find any details of any other mode existing and therefore no reason for its existence.
The motor direction is 0 to move forwards and 255 to move backwards.
The motor speed is 0 to 255 with 255 being full speed forwards. When moving backwards, these figures are reversed.
The following code creates a single procedure for controlling both motors.
When you call the procedure, you replace lft and rgt with numbers from -255 to 255, indicating speed and direction. -255 is used for full reverse and 255 for full forwards.
from microbit import * def drive(lft,rgt): ld, rd = 0, 0 if lft<0: ld = 0xff lft += 255 if rgt<0: rd = 0xff rgt += 255 i2c.write(0x28,bytes([1,lft,ld,rgt,rd])) Drive(255,255) sleep(2000) Drive(-255,-255) sleep(2000) Drive(0,0)
The last 5 lines drive both motors full speed forwards for 2 seconds, then full speed backwards for another 2 seconds. The car is then brought to a full stop.