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.


MATLAB
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) = coast


Assigning 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\pi d:


s=θ360∘ πds = \frac{\theta}{360^\circ}\,\pi d


Here dd is wheel diameter, θ\theta is the signed encoder change during the move, and ss is signed travel in the direction corresponding to positive encoder rotation. For a move without reversals, the nonnegative distance travelled is ∣s∣|s|. With d=0.056 md = 0.056\ \text{m} and θ=720∘\theta = 720^\circ:


s=2π(0.056) m≈0.352 ms = 2\pi(0.056)\ \text{m} \approx 0.352\ \text{m}


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 WW, measured between wheel centres. Assuming direct drive and no slipping, a turn of magnitude ϕ\phi requires a wheel-rotation magnitude


θwheel=ϕ Wd\theta_{\text{wheel}} = \phi\,\frac{W}{d}


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∘180^\circ spin with W=0.11 mW = 0.11\ \text{m} and d=0.056 md = 0.056\ \text{m} requires 180∘×0.11/0.056≈354∘180^\circ \times 0.11/0.056 \approx 354^\circ per wheel.


Top view of a two-wheeled robot showing the wheel diameter d, the track width W between wheel centres, and the dashed circle both wheels follow during a spin turn.



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 m0.30\ \text{m}.


MATLAB
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 KpK_p 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∘)πds = (\theta/360^\circ)\pi d.
  • Spin-turn wheel-rotation magnitudes are ϕW/d\phi 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:


C=πd=π(0.062 m)≈0.194779 mC = \pi d = \pi(0.062\ \text{m}) \approx 0.194779\ \text{m}


Divide the required distance by the circumference, then multiply the revolutions by 360°. Use the unrounded circumference in the calculation:


θ=sπd×360∘=0.80π(0.062)×360∘≈1478.6008∘\theta = \frac{s}{\pi d}\times 360^\circ = \frac{0.80}{\pi(0.062)}\times 360^\circ \approx 1478.6008^\circ


Each wheel must turn about 1479∘1479^\circ, 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.


MATLAB
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 coast


The < 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/2W/2, where W=0.120 mW = 0.120\ \text{m}.


A top view shows the left and right wheels at the ends of the axle, their shared circular path about the axle midpoint, the track width, and the left wheel moving backward while the right wheel moves forward.


For a ________ turn, each wheel's travel distance is


swheel=90∘360∘π(0.120 m)≈0.0942478 ms_{\text{wheel}} = \frac{90^\circ}{360^\circ}\pi(0.120\ \text{m}) \approx 0.0942478\ \text{m}


Convert this arc length to wheel rotation, retaining full precision:


θwheel=swheelπd×360∘=90∘0.1200.062≈174.1935∘\theta_{\text{wheel}} = \frac{s_{\text{wheel}}}{\pi d}\times 360^\circ = 90^\circ\frac{0.120}{0.062} \approx 174.1935^\circ


Each wheel therefore rotates through 174∘174^\circ in magnitude. After resetting the encoders, the left count falls toward −174∘-174^\circ and the right count rises toward 174∘174^\circ. 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:


sactual=1530∘360∘π(0.062 m)≈0.8278097 mΔs=sactual−0.80 m≈0.0278097 m=2.78097 cm\begin{aligned} s_{\text{actual}} &= \frac{1530^\circ}{360^\circ}\pi(0.062\ \text{m}) \approx 0.8278097\ \text{m} \\ \Delta s &= s_{\text{actual}} - 0.80\ \text{m} \\ &\approx 0.0278097\ \text{m} = 2.78097\ \text{cm} \end{aligned}


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.

An EV3 brick is connected with ev3 = legoev3('usb'); and a large motor is plugged into output port B. Which code makes that motor run continuously at 45% of full power?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

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.

Match each term
A.

Opens a cable connection to the brick and returns an object representing it

B.

Returns the cumulative encoder angle of the left drive in degrees

C.

Halts the left drive with the brake engaged so the wheel holds position

D.

Sets the left drive encoder count back to zero before a new move

E.

Returns the range to the nearest obstacle ahead, in metres

F.

Returns 1 while the bumper is pressed and 0 otherwise

G.

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)

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

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.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice