LEGO Robot Programming with MATLAB
MATLAB Robot Control
A LEGO MINDSTORMS EV3 robot can be driven directly from MATLAB. Scripts send motor commands and read sensors as numbers. In engineering labs, these operations let a robot travel a set distance, turn through an angle or stop before an obstacle. The engineering task is to translate each physical goal into commands and a stopping rule.
Connecting to the brick and running motors
With the MATLAB Support Package for LEGO MINDSTORMS EV3 Hardware installed, create an object for the brick and objects for its motors and sensors.
ev3 = legoev3('usb'); % connect over USB
mL = motor(ev3, 'B'); % left wheel motor on port B
mR = motor(ev3, 'C'); % right wheel motor on port C
mL.Speed = 50; mR.Speed = 50; % command range: -100 to 100
start(mL); start(mR);
pause(2); % drive for approximately 2 s
stop(mL, 1); stop(mR, 1); % 1 = brake, 0 (default) = coastAssigning Speed to a newly created, stopped motor does not start it; call start. Changing Speed while the motor is running changes its command immediately. The sign sets the rotation direction. Whether positive means forward depends on mounting, so check directions with the robot propped up on blocks.
Measuring motion with the encoder
Each motor contains an encoder, a sensor measuring motor-shaft rotation. readRotation(m) returns the signed cumulative angle in degrees since resetRotation(m).
Assume straight motion, wheels driven directly by the motor shafts, and rolling without slipping. Each full wheel turn moves the robot one circumference, πd:
Here d is wheel diameter, θ is the signed encoder change during the move, and s is signed travel in the direction corresponding to positive encoder rotation. For a move without reversals, the nonnegative distance travelled is ∣s∣. With d=0.056 m and θ=720∘:
In a spin turn, the wheels roll equal distances in opposite directions, rotating the robot about its axle midpoint. Each wheel follows a circle whose diameter is the track width W, measured between wheel centres. Assuming direct drive and no slipping, a turn of magnitude ϕ requires a wheel-rotation magnitude
Both angles use degrees. The two wheel rotations have equal magnitudes and opposite signs under a convention where positive wheel rotation drives forward. A 180∘ spin with W=0.11 m and d=0.056 m requires 180∘×0.11/0.056≈354∘ per wheel.
Closing the loop with sensors
A timed move never checks what happened; battery level, floor friction and load affect the result. Closed-loop control repeatedly reads a sensor, compares its reading with the goal and updates the command.
Stopping rule | What MATLAB checks | Typical weakness |
|---|---|---|
Fixed time | Nothing: pause, then stop | Distance varies with battery and surface |
Encoder target | Rotation against a degree target | Wheel slip and overshoot |
Sensor feedback | Distance, touch or another reading | Sensor noise and loop delay |
Proportional control makes the command proportional to the error. For this example, the ultrasonic sensor faces the wall, and positive commands drive both wheels toward it. Assume the robot stays perpendicular to the wall and receives valid distance readings. readDistance returns metres; the target is 0.30 m.
us = sonicSensor(ev3);
target = 0.30; Kp = 200; % command percent per metre
mL.Speed = 0; mR.Speed = 0;
start(mL); start(mR);
while readButton(ev3, 'center') == 0
u = Kp*(readDistance(us) - target);
u = max(min(u, 100), -100); % clamp the command
mL.Speed = u; mR.Speed = u;
pause(0.05);
end
stop(mL, 1); stop(mR, 1);When sufficiently far away, the positive command saturates at 100. Near the target, it shrinks, slowing the robot. Too close, the negative error commands motion away from the wall. Increasing Kp strengthens the response but can cause oscillation.
What to remember
- Create brick, motor and sensor objects. Set Speed within -100 to 100, then call start.
- For straight, direct-drive rolling, signed travel is s=(θ/360∘)πd.
- Spin-turn wheel-rotation magnitudes are ϕW/d, with opposite wheel directions.
- Reset encoders or subtract starting readings.
- Read feedback repeatedly and clamp motor commands to their allowed range.
Example: Programming a drive-and-turn move with encoder targets
A two-wheeled EV3 robot has wheels of diameter 62 mm and a track width of 120 mm, measured between the wheel centres. Each motor drives its wheel directly. The left motor is on port B and the right motor is on port C, and positive Speed drives the robot forward. The robot must drive 0.80 m straight ahead, stop, and then spin 90° to the left in place. Assume the wheels roll without slipping.
a) How many degrees must each wheel rotate to cover 0.80 m? Round to the nearest whole degree.
One wheel revolution moves the robot one circumference:
Divide the required distance by the circumference, then multiply the revolutions by 360°. Use the unrounded circumference in the calculation:
Each wheel must turn about 1479∘, a little over ________ revolutions. Direct drive makes this wheel angle equal to the motor encoder angle.
b) Write MATLAB code that drives the robot forward at 40% power and brakes when the left encoder reaches the target from part a.
Reset both encoders so the counts start at zero, start both motors, and then poll the encoder in a loop. The loop body waits briefly between readings.
ev3 = legoev3('usb');
mL = motor(ev3, 'B'); mR = motor(ev3, 'C');
target = 1479; % degrees, from part a
resetRotation(mL); resetRotation(mR);
mL.Speed = 40; mR.Speed = 40;
start(mL); start(mR);
while readRotation(mL) < target
pause(0.01);
end
stop(mL, 1); stop(mR, 1); % brake rather than coastThe < test makes the loop exit on the first reading at or past 1479°. Using stop(m, 1) applies electromagnetic braking rather than allowing the motor to coast. The stopping decision uses only the left encoder, so unequal wheel motion can still affect the robot's path.
c) For the 90° left spin turn, what sign should each motor's Speed have, and how many degrees must each wheel rotate? Round to the nearest whole degree.
To turn left in place, the left wheel runs backward and the right wheel runs forward with equal magnitude, for example mL.Speed = -30 and mR.Speed = 30. The robot rotates about the axle midpoint, so each wheel follows a circle of radius W/2, where W=0.120 m.
For a ________ turn, each wheel's travel distance is
Convert this arc length to wheel rotation, retaining full precision:
Each wheel therefore rotates through 174∘ in magnitude. After resetting the encoders, the left count falls toward −174∘ and the right count rises toward 174∘. A left-encoder stopping loop can use abs(readRotation(mL)) < 174, followed by braking both motors.
d) After the straight run in part b, readRotation(mL) returns 1530. How far did the robot travel past 0.80 m? Give the distance in centimetres to one decimal place, and suggest two changes that would reduce this error.
Assuming both wheels travelled equally, convert the measured rotation to distance and subtract the requested 0.80 m:
The robot overshot by 2.8 cm. The loop detects the target crossing only at its next reading, and communication and braking take time. Two changes that can reduce overshoot are:
- Slow down near the target, for example by dropping to 15% power for the last 100° before stopping.
- Stop early by subtracting the overshoot in encoder degrees measured over repeated test runs from the target, then retest.
A shorter pause can also reduce polling delay, although communication with the brick limits how quickly readings can be obtained.
A MATLAB script for a LEGO EV3 robot uses the calls below. The left drive motor object is mL, the touch sensor object is bump and the ultrasonic sensor object is sonic. Match each call to the job it performs in the script.
Opens a cable connection to the brick and returns an object representing it
Returns the cumulative encoder angle of the left drive in degrees
Halts the left drive with the brake engaged so the wheel holds position
Sets the left drive encoder count back to zero before a new move
Returns the range to the nearest obstacle ahead, in metres
Returns 1 while the bumper is pressed and 0 otherwise
Creates an object for the actuator plugged into output port B
resetRotation(mL)
readRotation(mL)
readDistance(sonic)
legoev3('usb')
motor(ev3,'B')
stop(mL,1)
readTouch(bump)
An EV3 robot has wheels of diameter 43.2 mm. After a straight run, readRotation on one drive motor returns 1250, which is the motor's rotation in degrees since its encoder was reset. The motor drives the wheel directly, and the wheels roll without slipping. How far did the robot travel? Give your answer in centimetres to one decimal place.