Lab 4:
Weighting for Maglev

The questions below are due on Friday November 27, 2026; 10:00:00 AM.
 
You are not logged in.

Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.
You are viewing the PRELIMINARY 6.3100 Fall 2026 web site. Please note that information on this page may change throughout the semester, please check back frequently.

Quick Reference

Links

Sketch constants you will edit

LineConstantMeaning
11MODE0: open loop (command = input waveform), 1: PD feedback, 2: state space (later labs)
12–14SensA, SensB, SensCDistance-sensor fit, \Delta y = (a\,x + b)/(c\,x + 1)
15crntSignSign of the field-sensor reading (set in the assembly guide)
17PsmoothInput-step smoothing, 0.0 (none) to 0.999 (very smooth)

Serial plotter send-window indices

Type the index, a space and a value, then click Send (e.g., 3 4 sets K_p to 4).
IndexParameter
0Extra samples for the derivative estimate (ExtraB)
1Derivative gain, K_d
2Integral gain (leave at 0 in this lab)
3Proportional gain, K_p
4Plot spacing (Skips)
5Input frequency (Hz)
6Input amplitude: >0 square wave, <0 sine, 0 none
7Coil-current gain (state space, later labs)
8Reference scaling, K_r (state space, later labs)

Measuring time. The controller runs every 0.1 ms, and adjacent plotted points are (20 + \text{Skips}) \times 0.1 ms apart: 2 ms by default, or 0.5 ms after sending 4 -15.

Task Summary Part A

  1. Build and check the maglev by following the assembly guide (Checkoff 1).
  2. Calibrate the distance sensor, and find a proportional gain that makes the umbrella oscillate (Checkoff 2).
  3. Find a PD controller that floats the umbrella and tracks ±2 mm steps (Checkoff 3).

Introduction

In this lab and the next, you will float a "magnetic umbrella" about 1.5 cm below a three-coil electromagnet. The umbrella is a neodymium magnet in a 3-D printed holder; its top face is a diffuse infrared reflector, and its machine-screw stem keeps it from tilting, like the tail on a kite. An optical sensor measures the distance to the umbrella, a Hall-effect sensor measures the field the coils produce, and the Teensy adjusts the coil currents to keep the umbrella floating.

The video shows a previous term's system toggling the umbrella's position under a lead controller. This week you will build and calibrate the system, and find a PD controller that floats the umbrella. Next week you will model the system and use the model to design a better controller.

Strictly, this is not levitation: the umbrella hangs, it doesn't rise. But "magnetic hanging" doesn't sound nearly as cool.

Rare-earth magnets are dangerous. They are brittle, and when two of them slam together they can send sharp fragments flying. Keep the umbrella away from other magnets and from steel tools.

Build the Maglev

Follow the maglev assembly guide from start to finish. Along the way you will:

  • build the frame, electromagnet and cover bar, and wire both sensors;
  • check with a compass that all three coils point the same way;
  • set crntSign so that the field reading (Crnt) follows the command (Cmd);
  • check the distance sensor's readings at +15 mm and −10 mm.

Checkoff 1:
  1. Show your assembled maglev, and demonstrate with the compass that every coil's needle points north when Cmd is high.
  2. Show that Crnt follows Cmd for a 1 Hz square wave (MODE 0, 6 1, 5 1).
  3. Show your Sensor readings at +15 mm and −10 mm.

Calibrate the Distance Sensor

The optical sensor is a photo-transistor, so its reading x (the Sensor trace, between 0 and 1) grows with the infrared light reflected back from the umbrella. That light falls off steeply with distance, so x is strongly nonlinear in distance. The sketch converts x to the umbrella's displacement from its nominal position, \Delta y in mm, with the rational function

\Delta y = \frac{a\,x + b}{c\,x + 1}.
Positive \Delta y means the umbrella is closer to the electromagnet. You will find a, b and c from three readings, at -10, 0 and +10 mm.

Fitting a, b and c

Multiply both sides by (c\,x + 1), and the fit becomes linear in the three unknowns:

a\,x + b - c\,(x\,\Delta y) = \Delta y.
Three readings (x_i, \Delta y_i) give three equations, which you can write as a matrix equation:
\begin{bmatrix} x_1 & 1 & -x_1 \Delta y_1 \\ x_2 & 1 & -x_2 \Delta y_2 \\ x_3 & 1 & -x_3 \Delta y_3 \end{bmatrix} \begin{bmatrix} a \\ b \\ c \end{bmatrix} = \begin{bmatrix} \Delta y_1 \\ \Delta y_2 \\ \Delta y_3 \end{bmatrix}.
In Python:

import numpy as np
x  = np.array([0.134, 0.280, 0.560])   # readings at -10, 0, +10 mm
dy = np.array([-10.0, 0.0, 10.0])
A  = np.column_stack([x, np.ones(3), -x*dy])
a, b, c = np.linalg.solve(A, dy)

Try it first. With the example readings in the code (x = 0.134, 0.280 and 0.560), find a, b and c, and enter them as a Python list [a, b, c].

[a, b, c] =

Using that fit, what \Delta y does a reading of x = 0.847 give? (That is a typical +15 mm reading.)

\Delta y (mm) =

A fit through −10, 0 and +10 mm still predicts +15 mm well. A straight line through the same three points would not.

Taking your three readings

Set up as for the range test in the assembly guide: MODE 0, amplitude zero (6 0), only the Sensor trace plotted, the potentiometer turned so the electromagnet pulls the umbrella up, and the calibration attachment clipped on.

−10 mm: pulled up against the bottom of the attachment
0 mm: electromagnet off, umbrella resting on the middle ledge
+10 mm: pulled up against the highest ledge
  1. −10 mm: use your reading from the range test.
  2. +10 mm: with the electromagnet still pulling up, hold the umbrella against the attachment's highest ledge, and note the reading.
  3. 0 mm: unplug the high-current (driver) power supply so the electromagnet is off, rest the umbrella on the attachment's middle ledge, and note the reading. Plug the supply back in afterwards.
For each, read the middle of the noisy Sensor trace.

Entering and testing your fit

  1. Solve for your a, b and c, enter them as SensA, SensB and SensC on lines 12–14, and upload again.
  2. Test the fit: remove the attachment, let the electromagnet pull the umbrella up against the sensor bracket (+15 mm), and plot Y. It should read close to 15, even though 15 mm is outside the range you fit.

With the umbrella against the bracket, Y reads (mm): 

Proportional Feedback

With the sensor calibrated, try feedback for the first time.

  1. Set MODE to 1, upload, and set the proportional gain to 0.25 (send 3 0.25).
  2. Hold the umbrella at the 0 mm position, and turn the nominal-command potentiometer until the umbrella feels weightless: the electromagnet's pull should just cancel gravity.
  3. Loosen your grip. The umbrella should oscillate, at least briefly, as in the video below.

If the umbrella does not oscillate, is the electromagnet pulling harder as the umbrella gets closer? That means the feedback sign is wrong. Either flip the umbrella magnet (ask for assistance!!!) or

  1. Swap the last two arguments in ALL THREE hbridgeBipolar calls (lines 208–210).
  2. Then also flip the sign of crntSign on line 15 (-1.0 to 1.0, or the reverse). Reversing the coil commands reverses the field the sensor sees, so without this change Crnt would no longer follow Cmd.
  3. Upload again, and recheck that the current measurement tracks the command with the 1 Hz square wave from "Matching the Field Sensor to the Command" in the assembly guide.

If you have verified that the feedback has the correct sign, but umbrella still does not oscillate, perhaps the proportional gain is too low. Is the electromagnetic pushing back as the umbrella gets closer, but only weakly? If so, then increase the gain (try 0.1, 0.25, 0.5, etc) but do not exceed 1..

Below you will stabilize the controller by adding derivative feedback, but the higher the proportional gain you use, the higher the derivative gain you will need to stabilize the system (making the command noiser). So, lower proportional gain is easier to stabilize (but the tracking will be poorer).

With proportional feedback alone, the umbrella oscillates about its set point (previous term's setup).

Checkoff 2:
  1. Show your three calibration readings, how you solved for a, b and c, and the +15 mm test. Why is the sensor reading nonlinear in distance?
  2. In MODE 1, demonstrate a proportional gain that makes the umbrella oscillate. What gain did you use?
  3. Why does proportional feedback alone make the umbrella oscillate instead of settle?

PD Control

Set MODE to 1, upload, and start from the proportional gain that made the umbrella oscillate. Now add derivative gain K_d (index 1) to damp the oscillation. Find a K_p and K_d that float the umbrella steadily, then test with ±2 mm square-wave steps: send 6 2 (amplitude 2 mm) and 5 0.5 (0.5 Hz). If tracking a square wave is hard, try setting Psmooth on line 17 to 0.95. Expect a noisy command and imperfect tracking; next week's model-based controller does much better.

PD control on a previous term's setup. Note how noisy the command is.

Checkoff 3:
  1. Demonstrate your PD controller floating the umbrella. What are your values of Kp and Kd?
  2. Show the umbrella tracking ±2 mm steps. Are the rising and falling responses the same?
  3. Is the command smooth or noisy? Where does the noise come from?

STOP HERE FOR WEEK A

Part B: State-Space Control

DOUBLECHECK Rods and Sensor Placement. Misplaced Rods cause sideways or backwards umbrella drift. Loose sensor causes measurement inconsistency.

As you discovered in part A of this lab, you can use PD feedback to control the separation distance between the electromagnet and the magnet-embedded "umbrella"of the Maglev system you constructed, but that controller was designed by trial-and-error (perhaps informed by experience and/or hints from the staff), and probably performed poorly (e.g. poor tracking, poor disturbance rejection, noisy commands). In this lab you will design a better-performing state-feedback controller using LQR, a rigorous metric-optimization based approach. In particular, you will start by developing a transfer function model of a linearized maglev system, then you will convert the transfer function model to a state-space model that you will accurately calibrate, and finally, you will combine your model with LQR-base algorithm to design (and then test) a state-feedback controller. For the postlab, you will design a further improved controller by adding an additional state, the integral of position error.

Please model carefully, better matches between model and hardware result in better LQR controllers.

Modeling

To generate an appoximate linear model for our maglev system, we linearize about a nominal magnet-umbrella separation distance, and its associated force-equilibrating coil current. In our case, the nominal separation distance is 15mm, and is set using a calibration clip. The associated nominal coil current is set by adjusting a potentiometer until the umbrella, at its nominal position, feels weightless. Below is a functional diagram showing a mapping between blocks of the maglev control system and the physical hardware, with green circles and arrows emphasizing the connection between the adjustable potentiometer and nominal coil current.

Mapping hardware components to blocks in the controller block diagram.

If we follow signals around the loop in the above diagram, first the reflected-IR sensor measures the umbrella's distance. Second, the Teensy converts the sensor output to a measured displacement from nominal, \Delta y, which it then compares to the desired displacement, \Delta y_d. Third, the Teensy produces a command, c_{nom} + \Delta c by summing a nominal command c_{nom} (set by the green-circled potentiometer) to a correction \Delta c (a function of current and past \Delta y's and \Delta y_d's as determined by the control algorithm). The Teensy converts the command into PWM signals, and sends them to three H-bridge drivers connected to three coils of an iron-core three-pronged solenoid electromagnet. The resulting electromagnet coil current, i_{coil}(c_{nom}) + \Delta i_{coil}(\Delta c), generates an electromagnet field that pushes or pulls on the umbrella's magnet.

In the subsections below, we will convert the above functional diagram description of the maglev hardware into th hardware into a block described ab into to transfer function models, as summerized in the figure below.

Hardware Function(above) and Transfer Function(below) block diagrams for the Maglev System.

Relating Coil Current to Umbrella Motion: H_{i2y}

Forces on the umbrella, and the equation of motion about equilibrium.

Three forces act on the umbrella: gravity, f_g; the attraction between its magnet and the steel rod, f_{fe}(y); and the attraction or repulsion of the electromagnet, f_b(y, i_{coil}). The umbrella floats at the equilibrium position y_{eq} when these forces sum to zero,

f_g + f_{fe}(y_{eq}) + f_b\big(y_{eq}, i_{coil}(c_{nom})\big) = 0.
When you held the umbrella about 15mm below the optical bracket, and then adjusted the potentiometer until the umbrella felt weightless, you were adjusting c_{nom} to make the above sum zero.

Away from equilibrium, the net force is no longer zero, and the umbrella accelerates. For small changes in umbrella distance, | \Delta y | < \epsilon, and coil current, |\Delta i_{coil}| < \epsilon, we can linearize the acceleration-position and acceleration-coil relationships yeilding

\frac{d^2}{dt^2}\Delta y = \gamma_{\frac{da}{dy}}\,\Delta y + \gamma_{\frac{da}{di}}\,\Delta i_{coil},
where \gamma_{\frac{da}{dy}} and \gamma_{\frac{da}{di}} relate perturbations in position and coil current to umbrella acceleration, respectively.

Assuming \Delta y(t) = \Delta Y e^{st} and \Delta i_{coil}(t) = \Delta I_{coil} e^{st}, we can rewite the above second order differential equation as

s^2 \Delta Y = \gamma_{\frac{da}{dy}}\,\Delta Y + \gamma_{\frac{da}{di}}\,\Delta I_{coil},
which can be reorganized as
\Delta Y = \frac{\gamma_{\frac{da}{di}}}{s^2 - \gamma_{\frac{da}{dy}}}\Delta I_{coil} = H_{i2y}(s) \Delta I_{coil}
where we refer to H_{i2y}(s) as the transfer function relating perturbations in coil current to perturbations in umbrella displacement.

Sign of \gamma_{da/dy}?

We will determine numerical values for \gamma_{da/dy} and \gamma_{da/di} below, by matching model and experiment, but we can already determine their signs.

Below are six step responses, four of which are associated with the transfer function

H(s) = \frac{-\gamma}{s^2 - \gamma}
for one of four values of \gamma: 1, -1, 25 or -25. For each plot, give the associated \gamma and the two natural frequencies (in any order) as a Python list. If the plot could not be a step response of H(s), enter [0,0,0].

Note: enter the answer as a Python list, use j = \sqrt{-1}, and use decimals rather than fractions. For example, \frac{7}{8} + \frac{1}{2}j is entered as 0.875+0.5j, and a value for \gamma followed by two natural frequencies would be [17.6, 0.875+0.5j, 0.875-0.5j]. Enter -j and +j as -1j and 1j.

[\gamma, \lambda_1, \lambda_2] =
[\gamma, \lambda_1, \lambda_2] =
[\gamma, \lambda_1, \lambda_2] =
[\gamma, \lambda_1, \lambda_2] =
[\gamma, \lambda_1, \lambda_2] =
[\gamma, \lambda_1, \lambda_2] =

Now think about the umbrella with no feedback. If you hold it just below equilibrium and let go, it falls; just above, it flies up to the electromagnet. Which of the plots above does that resemble, and what does that tell you about the sign of \gamma_{da/dy}?

Updating the Block Diagram

The feedback loop as functional blocks (top) and transfer functions (bottom) (with an explicit formula for H_{i2y}(s)).

Relating Teensy Command to Coil Current: H_{c2i}

Our maglev system uses iron-core solenoid electromagnets to generate the fields needed to attract or repel our rare-earth-magnet-embedded umbrella. And since the fields produced by these electromagnets are directly proportional to their solenoid currents, we can very quickly MEASURE these currents by scaling the output of a fast and inexpensive hall-effect magnetic field sensor (the one you installed in part A of this lab measures the field in less than 100 \mu secs). We can not, however, quickly CHANGE the solenoid current because of the solenoid's high inductance (L_{solenoid} > 50 millihenries) and our low power supply voltage (5v). To see this, recall the constitutive equation for an inductor, \frac{d}{dt}i_{solenoid} = \frac{v_{coil}}{L_{solenoid}} where v_{coil} is the commanded voltage (the voltage generated by our Teensy controller boar) and is bounded by 5v.

When modeling the propeller arm system, we used a parameterized first-order linear differential equation to represent the non-instant relation between commanded motor voltage and propeller thrust, and then used measurements to determine the parameters. We will model the non-instant relation between commanded coil voltage and coil current using a similar approach, though that might seem a counter-intuitive. After all, 6.310 is an EECS class and we have a circuit to model, shouldn't we use circuit analysis techniques? Perhaps, but then we would have to analyze the complicated magnetic interactions generated by the configuration of iron rods used in our electromagnet.

If we assume a parameterized first-order differential equation describes the command-current relationship, we can easily determine the model's parameters using the current measurements mentioned above.

H_{c2i}(s) = \frac{\gamma_{\frac{di}{dc}}\,(-\lambda_E)}{s - \lambda_E}.
where \gamma_{\frac{di}{dc}} and -\lambda_E will be calibrated below.

Updating the Block Diagram

The feedback loop as functional blocks (top) and transfer functions (bottom) (with an explicit formulas for H_{c2i}(s) and H_{i2y}(s)).

Experimental Calibration

Now that we have parameterized transfer functions for our entire system, the next step is to determine numerical values for those parameters by running experiments on our maglev setup. We will start by calibrating the H_{c2i}, for which we do not need a working controller. Then we will need a working controller, which we will use to calibrate the current sensor, and finally to calibrate H_{i2y}.

Measuring \lambda_E and \gamma_{di/dc}

The easiest way to calibrate the H_{c2i}(s) transfer function for your maglev setup is to test it with sinusoids.

  • Remove the umbrella,
  • Set MODE to 0 in the Teensy sketch and upload.
  • Open the serial plotter and plot only Cmd and Crnt.
  • Set the input to a 0.5 amplitude sinusoid (6 -0.5 in the send window).
  • Experiment with various frequency sinusoids (for example, 5 2 in the send window will set the frequency to two Hertz) and various settings for plot point skipping (try 4 -19 in the send window, or 4 -15 or 4 100).
  • Determine the \frac{Crnt}{Cmd} amplitude ratio for a very low frequency sinusoid. What does that ratio tell you about \gamma_{\frac{di}{dc}}?
  • Find the sinusoid frequency for which the Crnt sinusoid lags behind the Cmd sinusoid by forty-five degrees (see the figure below). What does that frequency tell you about \lambda_E. Remember to multiply by 2\pi to convert from hertz to radians per second!

\lambda_E (rad/s):  

\gamma_{di/dc} (Crnt per unit command):  

Zeroing the current sensor offset

We will need to subtract an offset from the current measurement so that it is close to zero when the when the umbrella is at Y = 0.

  1. Set MODE to 1, upload, and float the umbrella at 0 mm with reasonable PD gains (e.g. Kp=0.5, Kd=0.05).
  2. Be sure to plot Crnt, Y and Yd and note the average value while the umbrella floats.
  3. Change crntOffset on line 16 to crntOffset by adding or subtracting (trial and error) Crnt/10, using the value of the Crnt reading you just noted (remember that the y axis is always scaled up by 1000!)
  4. Upload again, float the umbrella, and check that Crnt now averages close to zero. The plots should look like the ones below.

Measuring \gamma_{da/dy} and \gamma_{da/di}

We can use frequency response measurements to calibrate the transfer function relating coil current to umbrella position, H_{i2y}(s), but the procedure is more complicated than the one used to calibrate H_{i2c}(s) because:

  1. In our maglev setup, we can not the directly set the coil current;
  2. Even if we could set the coil current, H_{i2y}(s) describes an UNSTABLE system. Setting a sinusoidally-varying coil current will not result in a measurable sinusoidally-varying umbrella position. The umbrella will just fall to the ground or get stuck to the electromagnet.
  3. And lastly, unlike H_{c2i}(j\omega), the phase of H_{i2y}(j\omega) is not useful for calibration since it is independent of \omega, \gamma_{da/dy}, and \gamma_{da/di}.

We can address problem (1) and (2) by using a PD controller to stabilize the maglev system (preferably a controller with very low noise), and then measure the frequency response of our unstable coil-current-to-umbrella-position subsystem while it is embedded in a stablizing surrounding. That is, we apply sinusoids to the stabilized system's primary input, then measure the resulting sinusoidal steady state behavior of the input and output of our subsystem, the coil current and the umbrella position respectively, and use the amplitude ratio to calibrate |H_{i2y}(j\omega)| .

The above process, often referred to as de-embedding, relies on two key insights. First, transfer functions are valid input-output descriptions regardless of surroundings. And second, when a system is in sinusoidal steady-state, every state is sinusoidally varying at the same frequency, so different states differ only in angle and amplitude (magnitude and phase), as shown pictorially in the diagram below.

In sinusoidal steady state, all states have the same frequency sinusoidal behavior, though not the same phase or amplitude. We can determine magnitude and angle of H_{i2y}(j\omega)) at frequency \omega by noting the amplitude ratio and phase difference of the two sinusoids pointed to by the blue arrow.

Now about problem (3). Note that

H_{i2y}(j\omega) = \frac{\gamma_{\frac{da}{di}}}{(j\omega)^2 - \gamma_{\frac{da}{dy}}} = -\frac{\gamma_{\frac{da}{di}}}{\omega^2 + \gamma_{\frac{da}{dy}}}
is always a negative real number since \gamma_{\frac{da}{di}} > 0 and \gamma_{\frac{da}{dy}} > 0 (a fact we confirmed earlier). So phase is always -180 degrees, and therefore not useful for calibration. Instead, we will measure |H_{i2y}(j \omega)| which, in sinusoidal steady state, is equal to the ratio (umbrella_position_amplitude)/(coil_current_amplitude).

Since |H_{i2y}(j\omega)|=\frac{\gamma_{\frac{da}{di}}}{\omega^2+\gamma_{\frac{da}{dy}}}, for a low enough \omega, |H_{i2y}(j \omega)| \approx \frac{\gamma_{da/di}}{\gamma_{da/dy}}. And if \omega^2 = \gamma_{da/dy}, |H_{i2y}(j \omega)| = \frac{1}{2}\frac{\gamma_{\frac{da}{di}}}{\gamma_{\frac{da}{dy}}}.

We suggest the following approach to collecting the |H_{i2y}(j\omega)| data. The approach uses very low feedback gains, enough to stabilize our unstable subsystem while still keeping noise to a minimum. You might need to ADJUST SOME OF THE VALUES FOR YOUR SYSTEM.

  • Set MODE to 1 in the Teensy sketch and upload.
  • Open the serial plotter and use the send window to set
    • Kp = 0.25 (3 0.25), set low so that stabilizing Kd will be low,
    • Kd = 0.005 (1 0.005), set low to minimize noise,
    • numSkips = 50 (4 50), so plots show low frequency behavior,
    • Frequency = 1 (5 1) to set the input frequency
    • Amplitude = -1 (6 -1) to set a sine wave with amplitude 1.
  • Plot only Y and Y_d , float the umbrella, and adjust the potentiometer to get the best match of Y to Y_d.
  • Plot only Y, Cmd, and Crnt. Check that your plots are similar to the one below.
  • Teensy Output To Check Noise, Y, and Crnt.
  • Determine the Y/Crnt amplitude ratio by plotting Y and Crnt, and then just Crnt, as shown below.
    Teensy Output measure Y amplitude.
    Teensy Output Crnt amplitude.
  • Find the frequency that roughly halves the Y/Crnt amplitude ratio you just measured (the halving frequency should be less that 10 Hertz). TO GET GOOD MEAUSUREMENTS YOU MAY HAVE TO CHANGE THE INPUT AMPLITUDE WITH FREQUENCY. For example, you might use an amplitude 2 sine wave (6 -2) when measuring the Y/Crnt amplitude ratio at one hertz, but maybe (6 -0.5) to measure Y/Crnt at six hertz. Remember you are measuring amplitude ratios and the system is linear(ish)!
  • Given the low frequency amplitude ratio, and the frequency at which the amplitude ratio is halved, you should be able to easily estimate \gamma_{da/dy} and \gamma_{da/di}. Be sure to convert from frequency in Hertz to frequency in radians/second ( \omega = 2 \pi f), before you SQUARE IT!
    DOUBLECHECK Rods and Sensor Placement. Misplaced Rods cause sideways or backwards umbrella drift. Loose sensor causes measurement inconsistency.

    Checkoff 4:
    1. Show how you estimated the electromagnet pole and command-to-current gain.
    2. Show that the coil current measurement is close to zero while the umbrella floats under PD control.
    3. Show how you determined the two Hi2y gammas.

    State-ing the Obvious

    We are using an optical sensor to estimate umbrella position, are using its sample-to-sample variation to estimate time derivatives, and are using a magnetic field sensor to estimate coil currents. Effectively, we are measuring the umbrella's state: its position, its velocity, and its acceleration (coil current is proportional to force, force is proportional to acceleration). Yet we are not using state-space control, we are not even using all the states we are measuring. For example, the coil current is ignored by our PD controller, its measurements are only being used for model calibration.

    As an alternative, consider the system diagrammed below, in which the controller uses measurements of coil current, umbrella velocity and umbrella position to determine command updates to the coil driver.

    We could then use a linear state-space controller, like in the figure below.

    It was difficult enough to design the lead controller when we only had three parameters to determine, s_z, pzRatio, and K_p. And as the above diagram makes clear, we now have four, the three state "gains", K_y, K_v, K_c, and the input scaling, K_r. Luckily for us, there are computational tools that will help us find reasonable values for the K's, once we put the model into a standard state-space form.

    State-Space Briefly

    The standard form for a state-space model is the combination of a differential equation the describes state evolution and an output equation the describes what we can observe,

    \frac{d}{dt} x(t) = A x(t) + B u(t) \;\;\; y(t) = Cx(t)
    where, for the three-state maglev system, A is 3\times3, B is 3\times1, the input u(t) = \Delta cmd(t) is the offset from a nominal Teensy command, C is 1\times3, and y(t) = \Delta y(t) is the optical-sensor-measured offset from the nominal umbrella position (in our case, the nominal position is 15 millimeters below the electromagnet).

    Matrix Representation of Feedback

    In standard state-space feedback, u(t) (which is equal to \Delta cmd(t) in the maglev case) is given by a scaling of a desired output, y_d(t) minus feedback from a weighted combination of the the states, as in

    u(t) = K_r y_d(t) - K x(t)
    where K_r is a scaling of the input and K is (in the maglev case) a 1\times3 matrix of feedback gains.

    The feedback system is described by

    \frac{d}{dt} x(t) = (A - BK)x(t) + BK_r y_d(t)
    where eigenvalues of the matrix A-BK (3\times3 in the maglev case) indicates stability. That is, the feedback system is stable if all the eigenvalues of A-BK have negative real parts. And if the system is stable and y_d(t) goes to a constant value, that is \lim_{t \rightarrow \infty} y_d(t) \equiv y_d(\infty), then the system has a steady state. That is \lim_{t \rightarrow \infty} x(t) \rightarrow x(\infty) exists and is given by
    x(\infty) = -(A-BK)^{-1} BK_r y_d(\infty).
    The output y(t) also has a steady state, given by
    y(\infty) = -C(A-BK)^{-1} BK_r y_d(\infty).
    and if we want the output steady-state to match the desired output's steady state, y(\infty) = y_d(\infty), then for the single-input, single-output case
    K_r = \frac{-1}{C(A-BK)^{-1} B}.

    Block Diagram Representation of Feedback

    For the three-element state vector \mathbf{x} as: x_1(t) = \Delta i_{coil}(t), the coil current; x_2(t) = vel(t), the umbrella velocity; and x_3(t) = \Delta y(t), the umbrella position, we summarize the differential equation system below.

    In standard state-space feedback, u(t) = \Delta cmd(t) is given by a scaling of a desired input, K_r \Delta y_d(t), minus feedback from a weighted combination of the states, -K x(t), as shown in the block diagram below.

    We can represent the block diagram in transfer function form, as shown below.

    Phase Margin

    We can reorganize the state-space description to make its description look more like the feedback loops we have been analyzing with Black's formula, as shown below.

    To analyze a single-input single output system in sinusoidal steady state at frequency \omega, we substitute s = j \omega. Then in our transfer function representation, K(s-IA)^{-1}B becomes

    K(j\omega I-A)^{-1}B,
    and is a complex scalar. Should that complex scalar approach -1 for some frequency \omega, then
    \frac{K(j \omega I-A)^{-1}B}{1 + K(j\omega I-A)^{-1}B}.
    will approach infinity. So, we can examine the magnitude and phase of K(j\omega I-A)^{-1}B as a function of frequency, to see if it approaches -1, and a what frequency. Or more pointedly, we can determine the state-space controller's "phase margin".

    Determining and testing the state-space model.

    We denote the transfer function model for the maglev system (not including any control) as H_{c2y}(s), where the c2y stands for command to y (umbrella position), and H_{c2y}(s)=H_{c2i}(s)H_{i2y}(s). We can generate a state-space model from this transfer function using one of the many automatic procedures for converting transfer functions into state-space models (e.g., controllable canonical, observable canonical, modal, etc). That there are so many conversion algorithms hints at a key issue: while there is only one transfer function associated with a given \{A,B,C,D\} state-space model, there can be an infinite number of state-space models that generate a given transfer function, and an associated infinity in the choice of state variables.

    What we need is a state-space model whose states are consistent with our measurement of umbrella position, umbrella velocity, and coil current. That is, we must find an \{A,B,C,D\} state-space model for our maglev system that satisfies two criteria:

    1. its states are umbrella position, umbrella velocity, and coil current;
    2. its transfer function matches your carefully-calibrated maglev transfer function derived above.

    The First Row

    To start the process of mapping the transfer function into the A and B matrices in the above figure, consider unraveling the H_{c2y}(s) transfer function back into a product of two transfer functions, one from Teensy command to coil current and one from coil current to umbrella position as shown below.

    As noted in the above figure, we now have an explicit \Delta I_{coil} and an explicit \Delta Y that correspond to the first and third states, but we do not have anything explicit relating to velocity. Nevertheless, from H_{c2i}(s) we can determine the differential equation that relates Teensy command to coil current, and map its coefficients into the appropriate matrix elements in the first row of A andB, as shown in the figure below.

    In the above two figures, velocity is missing in the transfer function and H_{i2y}(s) is unused in constructing the state-space model. How might we incorporate this unsed information to fill in the bottom two-thirds of A and B?

    BONUS TIP: There are a few tricks to converting transfer functions to state-space models,reviewed in the prelab question here.

  • The Python Script

    We have provided a Python script with the structure of a state-space model for maglev. To use the script to model your hardware system, you will have transfer parameters from your calibrated model including \lambda_E, \gamma_{da/dy}, \gamma_{da/di} and \gamma_{di/dc}.

    Note that we created a system with multiple outputs, defined by the matrix Cplot in the python script. We did this so that when we used the step (Python), plots of all three states are generated, not just position. But we also want to plot one more quantity. Recall that u = K_r y_d - K x, and that in our case, u = \Delta cmd, and its plot should not exceed 1 by much, or be much smaller than -1 (\Delta cmd will saturate the coil driver if outside the range -1 to 1. The step function will plot u = K_r y_d-K x if we prepend a row to the Cplot matrix and add a single non-zero value to a 4 \times 1 Dplot matrix.

    For state-space models, D is used to represent a direct contribution of system's input to its output. To create a vector for use in plotting, y_{plot}, that includes all the states AND the control, the python script creates

    y_{plot} = C_{plot}x + D_{plot}u.
    Do you see how we modified the 4 \times 1 D_{plot} matrix to generate the K_r y_d term for a plot of the closed-loop u= \Delta cmd = K_r y_d-K x?

    Completing and Testing the Model.

    Please use your insight into state-space modeling, along with the hints above, to find and fix the lines associated with FIX THIS in the Python script linked at the top of this page. For a quick summary of the formulas for computing closed-loop matrices, look here.

    Once you have implemented your state-space model in the python script, set values for K (use the Kman matrix on lines 111, 112, and 113 of the script, and set the flags useKyforKr and useKlpr to false) consistent with a PD controller that produces a "ringing" step response (for example, the Teensy PD controller with Kp=0.5 and a Kd that is low enough to produce ringing, certainly lower than 0.005). After running the script you should see four plots. From top to bottom they are: the Teensy command being sent to the maglev coil drivers, i_{coil}, vel and y.

    Once you have the python script producing reasonable outputs, set MODE to 2 on the Teensy, copy and paste the python-produced #define statements lines from the python command window into the Teensy sketch (after line 24). Plug in both board power supplies, connect your laptop to the Teensy, upload the Teensy sketch, and start the serial plotter. In the Teensy serial plotter, unclick all but \Delta y, \Delta y_d, and Crnt to focus in on matches to the python simulation. If your state-space model is accurate, you should be able to demonstrate matches like the ones below.

    Matching Python Simulation and Measured Umbrella Position.
    Matching Python Simulation and Measured Coil Current.

    If your simulations are very different from your measured responses, check your modeling from checkoff 4 with the staff. If simulations and measurements are close, but could be closer, you can tweak (that is, change by less than twenty-percent) the values of \lambda_E, which mostly effects step response ringing decay (or stability), or \gamma_{da/di}, which mostly effects step response ringing frequency, or \gamma_{dady}, which mostly effects steady-state match, or \gamma_{di/dc}, which affects both the coil current scaling and the ringing frequency. But do not get carried away, the models are approximate, pretty good is good enough!

    Checkoff 5:
    • Show that you fixed all the lines of python code that say fix this.
    • Demonstrate the operation of your maglev system with PD-like control by showing screenshots of step responses of umbrella displacement and coil current.
    • Demonstrate your Python model by showing screenshots of analogous step responses of the model.
    • Is using K_y = K_r = K_p and K_v = K_d make your state-space controller exactly the same as a proportional plus derivative controller with gains K_p and K_d (hint: K_d scales the derivative of the ERROR, does K_v?)?
    • Show comparisons between python simulation and measured data like the images above.

    Pole Placement and LQR

    By providing feedback on all of the states of a plant, state-space controllers can offer significant performance improvements over what can be achieved with PID controllers. However, to realize these potential improvements, we must choose a gain for each state variable in the state vector x.

    As you saw in the prelab, we can easily solve simple second order systems "on paper" and find gains that place the eigenvalues wherever we like (subject to a few constraints such as avoiding repeated eigenvalues). For larger systems, beyond third order, there is no closed form for the eigenvalues, and finding the gains for a given placement is best done computationally. We can rely on numerical approaches for determining K given \textbf{A} and \textbf{B}, such as Ackerman's method and its variants. Python's place command does exactly what we want, provided we do not try to place multiple poles with the same numerical value. However, if the resulting performance has problems (e.g., if the umbrella settles too slowly or if the required commands are too large), it is not always obvious how to change the poles to improve performance. This issue can be addressed by using the LQR algorithm, which specifies gains using a different set of parameters.

    We strongly recommend you review section 3.1 in the "State Space And LQR" question on the prelab here.

    Set the useKlqr flag to true on line 25 of the python script, so that the LQR algorithm is used to find the feedback gains. Also, fix the lines in the python script associated with LQR. Finally, try to find state and input weights (the Q and R matrices in the python script) that give you the "best" step response without violating the physical constraints on the maximum u.

    Checkoff 6:

    Setting Gains with LQR

    • Use the LQR algorithm to find gains so that the mean-squared errors are minimized subject to weights given by Q[1,1] = Q[2,2] = Q[3,3] = 1 and R = 1. Save a screenshot of your results. Determine how long it takes the output y to get halfway to its final value.
    • Forcing all the state variables to zero with the same weight may not give you the best performance. For example, try setting all the Q weights to zero except Q[3,3], and set Q[3,3] to the largest value that keeps the magnitude of simulated command signal less than 1. Try using the resulting gains K on your maglev hardware (by copying and pasting the lines printed by the python script). Compare the simulated step response to the step response of your maglev system, how fast is the response? Does it overshoot?
    • Fix the phase margin calculation in the python code, and calculate the phase margin for your overshooting system. Is the result what you expected?
    • Change the Q weights so that the simulated step response does not overshoot, which weight should you change? Try the resulting gains on your maglev system, how does it perform?
    • With your updated gains, recalculate the phase margin. Does it change? What does that indicate about phase margin as a performance metric?
    • With your updated gains, what is the largest step change in displacement that the resulting system can track?
    • What happens if you add extra pin magnets to the end of the umbrella (try adding four additional pins). After each step, does the umbrella still settle to the desired steady-state? How is that effected by the number of pin magnets you add?

    Adding the Integral term while using LQR

    PLEASE NOTE: The sign pattern used for the integral term in the Teensy code means that your python code should produce NEGATIVE K_int.

    We suggest that you make a copy of the python script, and edit it to use LQR to calculate the gains for the maglev model plus an extra state, the integral of the error. See the last section of the Prelab for more details about adding the integral term, and think carefully about what happens to K_r.

    So how will you set the weight on the integral term? You want it to go to its steady-state value quickly, like all the other states, but is the integral the same scale as the other states? Suppose a sudden disturbance displaces the umbrella a tenth of a millimeter in a millisecond. The measured error in \Delta y will also change by 0.01 in that same millisecond, but what about the integral of the position error? An error of 0.01 would have to persist for a 1000 milliseconds before the integral of the errors rises to 0.01. What does that say about the relative weights for these two states?

    Once you have fixed your script, try computing state gains for all the states, including the integrator, using LQR. Once you have gains that result in good performance in simulation, test them on the maglev system by copying and pasting the output lines from the python script. PLEASE KEEP KINT BELOW 200! The optical distance sensor does not have enough resolution for higher gains. Below are some senarios to try (from a previous term's setup!!), be sure to test your system's disturbance rejection using both extra and fewer pin magnets.

    Checkoff 7:

    Integral Controller

    • How did you pick weights for the integral controller?
    • When using the integral controller, what did you do with Kr and why?
    • Why is the weight on the integrator so much higher?
    • What is the phase margin for your integral controller? How does its phase margin compare to your controller without the integral?
    • What is intMax in the Teensy sketch (line 187), what is it doing?
    • Implement your integral controller on your maglev hardware system. Document performance by saving a screenshot of the step response of the system.
    • Try adding some weight with magnets, how does the performance change? How big a step can you take?