1424 8220 2024v24i2an538
1424 8220 2024v24i2an538
Article
MagnetoShield: A Novel Open-Source Magnetic Levitation
Benchmark Device for Mechatronics Education and Research
Gergely Takács 1 , Jakub Mihalík 1 , Martin Gulan 1,2, * , Anna Vargová 1,2 , Erik Mikuláš 1 and Štepán Ožana 3
Abstract: This article presents an open-source device illustrating the well-known magnetic levitation
experiment. The uniqueness of this particular device lies in its exceptionally small dimensions,
affordability and availability, which makes it a perfect design for take-home experiments for education
but it can also serve as a referential design for testing various control algorithms in research. In
addition, this paper provides a comprehensive hardware design for reproducibility along with the
detailed derivation of the mathematical model, system identification and validation. Moreover, the
introduced hardware comes with an easy-to-use open-source application programming interface in
C/C++ for the Arduino IDE, Simulink and CircuitPython. REXYGEN, another environment similar
to Simulink, had also been used to demonstrate the capabilities of the MagnetoShield.
hardware lies not only in its small dimensions and affordability, but also in its reproducibil-
ity thanks to the open documentation [12] and the support within the ecosystem of the
AutomationShield project.
The current paper builds upon the hardware prototype of the device (see release R2
in Figure 2) introduced in our earlier work [16], and presents an upgraded version of the
MagnetoShield, aimed specifically at enhancing the teaching of automatic control and
mechatronics at both undergraduate and graduate levels.
In terms of hardware advancements of the initial prototype, these relate mainly to the
electronic components. The proposed modifications notably bolster the repeatability of the
experiments on this cost-effective device, and the careful selection of components aims to
facilitate potential home assembly of the device. In addition, the software enhancements
now include an expanded array of available APIs, such as Simulink, thereby simplifying
the device’s integration into educational settings. Furthermore, we examine its versatility
by interfacing with open-source application programming interfaces (APIs) like C/C++,
Arduino IDE, Simulink, CircuitPython, and REXYGEN. By doing so, we highlight both
the strengths and limitations of the MagnetoShield across various software settings and
hardware configurations.
The paper also presents an unconventional model of system dynamics, particularly rel-
evant to devices employing a permanent magnet as a levitating object. Addressing the chal-
lenges in modeling such systems compared to conventional ferromagnetic-based solutions,
we thoroughly explain these intricacies, providing comprehensive insights into the device’s
operation. Finally, the paper presents practical use cases that leverage more advanced
control algorithms, namely model predictive control (MPC), thereby expanding its utility
beyond basic experimentation towards more challenging control engineering applications.
Our intention is not to present yet another variant of this well-known experiment, but
to create an open hardware and software design that allows collaboration in control and
mechatronics education and even research on a budget.
Sensors 2024, 24, 538 4 of 33
(e)
(a)
(c)
(g) (h)
(f1 )
(d) (j1 ) (j2 ) (k2 )
(l) (p)
(r)
(e) (q)
(w) (t) (k1 ) (f2 )
(b) (n)
(c) (s)
(m)
(v) (o2 )
(o1 )
(o3 )
Long stackable headers (i1 –i3 ) connect the device to the pins of an Arduino R3 layout-
compatible microcontroller prototyping device from the bottom, while still leaving a female
header free for connecting external devices at the top, such as oscilloscopes for monitoring
the dynamic signal. The assumption of the Arduino R3 pinout serves a dual role in the
hardware design. First, it establishes the physical location, pitch and count of the header
pins, so that the device can be accepted by a range of compatible prototyping boards.
Second, it precisely defines the electrical and logical behavior of each header pin, so that the
device remains compatible with various microcontrollers even across different architectures
and families.
are connected to the underlying PCB via a corresponding pair of two pin male and female
headers (i4 ) and (i5 ).
2.1.2. Output Paths: Magnetic Flux Sensing, Current and Voltage Measurement
A linear ratiometric Hall effect sensor ((c), U2) connected to the A3 analog pin measures
the proximity of the levitating magnet. The strongest magnetic flux ∼2000 G is measured
when the magnet rests on the surface; thus, the sensor range must be selected accordingly.
Unfortunately, the fairly strong maximal flux limits the selection of available components.
We have chosen a bipolar device with zero flux calibrated at 2.5 V when supplied from the
5 V rail; thus, a 3.3 V Zener diode ((o1 ), D3) is inserted to clip voltages that would possibly
damage the built-in ADC when the magnet polarity is switched. The magnetic flux is
recomputed to distance readings in software, based on an automatic calibration procedure.
The current passing through the electromagnet is an important state variable playing
a role in system identification or online state estimation. An integrated high-side current
monitor ((h), U4) essentially measures and amplifies the voltage drop across a precision
shunt resistor ((p), R8). The current sensor gain is set by a resistor ((q), R9) placed at its
analog output, while another Zener diode ((o2 ), D5) protects the ADC from possible over-
voltage. A ceramic capacitor ((k2 ), C3) filters the supply of the current sensor. The output of
the current sensing IC is then connected to the A2 analog pin of the microcontroller board.
The voltage measured across the electromagnet is another auxiliary output that may be
useful for calibration, modeling and verification purposes. In theory, this shall be equal to
the input voltage u(k) and our verifications show this holds for the purposes of this device.
The voltage output is measured by a 3:1 voltage divider consisting of two resistors ((r), R6
and (s), R7), which is separated from the power circuit by another operational amplifier
stage in an input buffer configuration ((f2 ), U5 .2). The ADC is yet again protected from
possible overvoltage by a Zener ((o3 ), D4) clamp and the signal is fed to the A1 pin of the
microcontroller board.
Figure 5. The printed circuit board of the MagnetoShield device (1:1 scale).
Sensors 2024, 24, 538 8 of 33
(i3 ) (i2 )
(t)
(u) (e) (v) (l)
(j2 ) (j1 ) (f) (g)
(k1 )
(m) (n)
(w)
(p)
(h) (s)
(r)
(A)
(x) (y2 ) (q)
(k2 )
(i2 ) (i1 )
Figure 6. Top view of an assembled MagnetoShield (1.5× scale).
A disc-shaped part (y1 ) surrounds the Hall sensor and it keeps the magnet flat when
resting at its stable position. This part is centered manually by the circle seen on the PCB
silkscreen and then glued to the surface. Commonly available cyanoacrylate glue is not
recommended because of its evaporation; instead, single-component epoxy is suggested.
This base holds a 10 mm high translucent plastic tube (z), which prevents the magnet from
falling out of the apparatus. The main concern is that the magnet flips its polarity and
remains stuck to the magnetized core of the electromagnet, which, due to the small size of
the device, is difficult to remove.
The electromagnet is suspended in the air by an “L”-shaped bracket (y2 ) and is
affixed to the top by a screw that comes as an accessory with the component. The bracket
contains vertical grooves for the electromagnet leads and a gap to accommodate a pair
of male/female header pins to connect said leads to the PCB. The bracket slides into
a column with a square cross-section (y3 ), aiding the correct positioning of the magnet
horizontally over the assembly. Although the bracket is held in place quite firmly by the
sliding mechanism and the header pins, an M4 plastic screw (A) is inserted through the
bracket to the column as well. The bottom of this column slides into a square groove that
Sensors 2024, 24, 538 9 of 33
has been cut into the PCB itself; then, a washer with a corresponding square groove (y4 )
terminates the assembly from the bottom using an M5 plastic machine screw (B).
The bottom of the magnet is finished by an end cap (y5 ). The cap closes the gap with
the tube physically, so the magnet may only fly in an enclosed space and it cannot fall out
of the apparatus during transportation. The cap creates a gap between the surface of the
electromagnet and the levitating magnetic disc so that it does not stick to the magnetized
inner core accidentally. A sectional cut of the assembled magnet-holding superstructure is
shown in Figure 8a, and finally, Figure 8b depicts the front view of the MagnetoShield with
the mechanical assembly.
We have designed this magnet-holding superstructure in AutoCAD Fusion 360 be-
cause this cloud-based software is freely available to students and hobbyists and supports
efficient collaboration. Just like the circuit scheme and the PCB, the 3D mechanical design
files are openly available for further improvement [17]. The components have been printed
on a hobbyist-grade Prusa MK3/S 3D printer from standard ϕ = 1.75 mm PETG filament.
These mechanical components may be printed in less than 2 h.
(y2 )
(b)
(y2 )
(y5 )
(b) (u)
(A)
(l) (z)
(n)
(y5 ) (i3 ) (t) (a) (y1 ) (i2 )
(x)
(y3 ) (i5 )
(z)
(i4 ) (y1 )
(x)
(y4 ) (B)
(a) (b)
Figure 8. Mechanical assembly of the MagnetoShield device (1:1 scale) in a section cut (a) and in the
front view (b).
Table 1. Bill of materials and price list in U.S. dollars for a single device or quantities near ∼100 pieces sorted based on descending price. The small quantity figure
has been optimized for ease of accessibility, while the large quantity for price using a meta-search engine. The includes only direct material price and excludes
postage, equipment, consumables, energy and labor cost.
Name Part Number, Value PCB Pcs. Unit Total Unit Total
Large quantity Small quantity
Current sensor Texas Instruments INA169 (e.g., TI INA169NA/250) U4 (h) 1 1.57 1.57 3.47 3.47
Trimmer 10 kΩ , 250 mW, multi turn, SMD, 10% (e.g., Bourns 3214W-1-103E) R10 (l) 1 0.74 0.74 3.81 3.81
Hall sensor Texas Instruments DRV5055Z4 (e.g., DRV5055Z4QDBZR) U2 (c) 1 0.95 0.95 1.69 1.69
Electromagnet 2.5 kg suction, ϕ20 × 15 mm, 24 V (e.g., Bairun Electric BR-20/15) L1 (b) 1 0.91 0.91 5.53 5.53
Opamp dual, rail-to-rail (e.g., Texas Instruments TLC2272ACD) U5 (f) 1 0.69 0.69 2.18 2.18
DAC Microchip MCP4725 (e.g., MCP4725A0T-E/CH) U3 (e) 1 0.38 0.38 1.15 1.15
PCB 2-layer, FR4, 1.6 mm thick (e.g., JCLPCB) - (x) 1 0.40 0.40 2.91 2.91
3D print 11 g, ϕ = 1.75 mm PETG filament, bright green, at 240 ◦ C (90 ◦ C bed), 2 h - (y1 )–(y5 ) 1 0.39 0.39 2.36 2.36
Trimmer 10 kΩ , 250 mW, single turn, (e.g., ACP CA14NV12,5-10KA2020) POT1 (t) 1 0.19 0.19 0.20 0.20
Screw nylon, M5 × 0.8, Phillips Pan, machine screw (e.g., Essentra 50M050080P010) - (B) 1 0.16 0.16 0.22 0.22
Resistor 3 kΩ , 0805, 0.1% , 0.125 W (e.g., Viking AR05BTCW3001) R6, R9 (q),(r) 2 0.16 0.31 0.48 0.96
Diode generic, DO214AC (e.g., Vishay Semiconductor BYG20J) D1 (n) 1 0.15 0.15 0.44 0.44
Screw nylon, M4 × 0.7, Phillips Pan, machine screw (e.g., Essentra 50M040070D006) - (A) 1 0.12 0.12 0.19 0.19
Header 10 × 1, female, stackable, 0.1" pitch (e.g., SparkFun 474-PRT-10007) - (i3 ) 1 0.09 0.09 0.38 0.38
Magnet NdFeB, disc, ϕ = 9 mm, h = 2 mm, N50 (e.g., OMO Magnets N50D00960020) - (a) 1 0.09 0.09 0.15 0.15
Resistor 1 kΩ , 0805, 0.1%, 0.125 W (e.g., Viking AR05BTCW1001) R7 (s) 1 0.08 0.08 0.23 0.23
Resistor 10 Ω , 0805, 0.1%, 0.1 W (e.g., ROYAL OHM TC0525B0100T5) R8 (p) 1 0.08 0.08 0.48 0.48
Transistor BJT transistor, NPN, SOT-23-3 (e.g., Nexperia BC817K-40HVL) Q1 (g) 1 0.08 0.08 0.30 0.30
Pot shaft For “POT1”, (e.g., ACP CA9MA9005) - (u) 1 0.07 0.07 0.14 0.14
Header 8 × 1, female, stackable, 0.1" pitch (e.g., SparkFun 474-PRT-10007) - (i2 ) 2 0.06 0.12 0.38 0.76
Header 6 × 1, female, stackable, 0.1" pitch (e.g., SparkFun 474-PRT-10007) - (i1 ) 1 0.06 0.06 0.38 0.38
Resistor 4.7 kΩ , 0805, 0.5%, 0.125 W (e.g., Panasonic ERA-6AED472V) R3 (m) 1 0.05 0.05 0.29 0.29
LED 0805, red (e.g., OPTOSUPPLY OSR50805C1E ) D2 (v) 1 0.04 0.04 0.22 0.22
Tube acryl (PMMA), h = 10 mm, ϕ = 12/10 mm (e.g., Bitspower BP-NCCLT12AC) - (z) 1 0.03 0.03 0.51 0.51
Zener diode 3.3 V, SOD323 (e.g., NEXPERIA BZX384-C3V3.115) D3–D5 (o1 )–(o3 ) 3 0.03 0.08 0.05 0.15
Capacitor 0805, ceramic, 0.1 µF (e.g., KEMET C0805C104K3RACTU) C1, C3 (k1 ), (k2 ) 2 0.02 0.05 0.30 0.60
Header 1 × 2 female, 0.1" pitch (e.g., Connfly DS1023-1*2S21) - (i5 ) 1 0.02 0.02 0.11 0.11
Resistor 1 kΩ , 0805, 5%, 0.125 W (e.g., Royal Ohm 0805S8J0102T5E ) R5 (w) 1 0.01 0.01 0.12 0.12
Resistor 10 kΩ , 0805, 5%, 0.125 W (e.g., ROHM Semiconductor SFR10EZPJ103) R1, R2 (j1 ), (j2 ) 2 0.01 0.02 0.14 0.29
Header 1 × 2 male, 0.1" pitch (e.g., Amphenol G800W306018EU) - (i4 ) 1 0.01 0.01 0.12 0.12
Glue Single component epoxy (e.g., Suxun B-7000) - - 0.1 mL 0.01 0.01 0.01 0.01
Postage - - - - - - - 3.23
Total: $7.96 $33.57
Sensors 2024, 24, 538 11 of 33
The prices of components are given for two typical scenarios: (i) a student or hobbyist
completing a single device for individual use or (ii) an educator or technician assembling
several tens of instruments for equipping an entire teaching laboratory or classroom.
In the first case, we assume that components are sourced locally and that the absolute
minimization of cost is not the priority, but rather the convenience of ordering from the
minimal number of part dealers. The cost of one device is in the order of the low tens of
dollars, specifically under USD 35. In the latter case, we have assumed that price is more
of a concern, yet procuring from several sources over a longer time period is not. After
comparing parts in a component meta-search engine, we found that the unit price can be
kept below USD 10. Although the ancillary costs may start to play a more significant role
in the latter case, bulk deals on components or changes in technique (such as employing an
SMD stencil) may offset these costs.
(GUI) of the Arduino IDE; then, this selection is passed to the preprocessor at compile
time as a token, such as ARDUINO_ARCH_AVR. Architecture differences manifest in ADC
reference voltage and resolution settings, the number of I2C buses, etc.
In case of using any compatible Arduino board, these settings will take place auto-
matically in the background. Only for third-party compatible devices (e.g., the ones from
the Adafruit Metro family) some additional steps are needed, namely: the user has to
add the particular board to the GUI [19]. After that, the compiler will setup the correct
configurations, thanks to the fact, the MagnetoShield library is written in a way to handle
these changes too.
Figure 9. Tracking magnetic levitation reference by explicit model predictive control, showing the
requested reference and measured distance in the Serial Plotter tool.
where p1 and p2 are calibration constants. To account for minute differences in the as-
sembly, these parameters are computed by an automatic two-point calibration procedure.
Sensors 2024, 24, 538 13 of 33
Measuring flux Bmax when the magnet rests at the bottom of the device being the farthest
from the electromagnet dmax and then flux Bmin when it is the closest to the electromagnet
dmin gives
log hdmax
min
p1 = , (2)
log BBmax
min
dmax
p2 = . (3)
( Bmin ) p1
The maximal voltage passing through the coil is also measured and stored in a pri-
vate variable that may be accessed by the getVoltageRef () method. There are default
parameters stored in the library for the distance reading function in (1) along with limit mag-
netic flux readings. It is known based on the calibration state stored in the calibrated
variable whether the calibration function has been invoked in the application by the user,
and if not, certain functions default to stored settings.
3.1.2. Input
The voltage in the electromagnet is set by passing a floating point number to the
method
MagnetoShield . actuatorWrite ( u ) ;
where uk (V) is the input ranging from 0 to 10 V. First, this voltage is scaled to corresponding
12-bit DAC levels by the voltageToDAC () private method. Because of the hardware
feedback, this relationship is close to linear for our purposes. However, a slight software
correction is made to compute the DAC levels uDAC(k) by applying the
polynomial, where the coefficients p3 , p4 , p5 , and p6 are calibrated offline. The result is
saturated to prevent possible overflows.
Next, the desired DAC levels are sent to the chip itself by the dacWrite () method.
This accepts the 12-bit uDAC (k) level on its input, addresses the DAC chip on the I2C bus
and separates the payload into two bytes. This function is conditionally compiled based on
the used MCU architecture and DAC chip to preserve compatibility with earlier designs.
Inputs can be expressed in percentual units relative to the maximum coil voltage
as well by invoking the a c t u a t o r W r i t e P e r c e n t s () method. This re-scales them
to input voltage based on the maximum calibrated values measured when the device
was initialized.
3.1.3. Output
Although feedback control design is possible with physical units that are merely
related to the position of the magnet, first-principle and then later grey-box system identifi-
cation and the resulting state feedback are more engaging in direct distance units.
Therefore, at first, the adcToGauss () method reads the ADC levels from pin A3
based on conditional compiling considering the correct ADC resolution and reference
voltage, then returns the flux contingent on the gain and bias supplied by the component
manufacturer. For the Hall sensor considered in this reference design, the zero is at 2.5 V for
a 5 V supply and its sensitivity is 1.25 mV/G. The returned flux is re-mapped to distance
units by the gaussToDistance () method using (2) and the two calibration parameters
obtained at startup.
From the viewpoint of the user, the API simplifies this to
y = MagnetoShield . sensorRead () ;
which returns the distance y(k) = d(k) (mm) of the permanent magnet from the electromag-
net as a floating point number.
Sensors 2024, 24, 538 14 of 33
i = MagnetoShield . auxReadCurrent () ;
method, returning a floating-point number. This method recomputes the ADC levels on
pin A2 to voltage, then shifts it by a linear bias and scales the result by a gain provided by
the manufacturer of the current sensing IC.
Similarly, the voltage potential measured at the electromagnet v(k) (V) on A1 is avail-
able using the
v = MagnetoShield . auxReadVoltage () ;
method, returning a floating point variable. The ADC levels are converted to voltages and
then corrected by the 3:1 gain of the impedance-buffered voltage divider. As has been
pointed out earlier, while the circuit itself renders this largely equal to the desired input uk
supplied to the system, the measurements may be utilized to calibrate a correction curve.
Finally, the position of the onboard potentiometer at the pin A0 may be acquired
by calling
r = MagnetoShield . referenceRead () ;
returning the reference r(k) (%) as a floating point variable. This external reference sup-
ports interaction with the device by allowing for manual tracking, even though it may be
reprogrammed to an alternative role such as controller tuning.
only a handful of references mention CircuitPython in the literature [24,25], while none
demonstrate its utilization for feedback control experiments.
The MagnetoShield API is contained in the MagnetoShield module that shall be
imported in the user application. The module itself imports further libraries to access
hardware functionality, timing and basic mathematics. After including the API module,
identical nomenclature is valid for the Python application as for the Arduino IDE. That
is, the input is sent to the electromagnet by MagnetoShield . actuatorWrite () and
its position can be read by MagnetoShield . sensorRead (), etc. The reader shall refer
to the description given for the Arduino API for a complete list of available functions.
The internal structure and workings of the Python API remains as close to the Arduino
counterpart as possible, except for the CircuitPython and hardware-specific calls.
The CircuitPython source code for the given control application does not even require
a dedicated IDE and may be edited by any standard text editor and uploaded to the
prototyping board which is handled as a drive by the computer. Saving the code online,
accessing the interpreter directly by the read evaluate print loop (REPL) and displaying
live measurements in a graphical output in a free open-source editor such as Mu is also an
option; see Figure 10.
Figure 10. CircuitPython source code for the PID control of magnetic levitation showing the graphical
output of input voltage and distance in the Mu editor.
Similar to the Arduino API, the Python variant offers certain supporting functions for
sampling, PID control, etc.
Limitations
As expected, hard real-time sampling is not achievable. Since Python is an interpreted
language, it has much less predictable performance than compiled languages, such as
C/C++, which is routinely used for embedded systems. The sampling of feedback control
may be unfortunately affected by the memory management mechanism known as “garbage
collection” and background tasks such as USB activity and file operations.
Certain MicroPython ports implement access to hardware timers, but CircuitPython
on Arduino R3-compatible prototyping boards currently does not offer this option. The
Sampling subsystem considered for the MagnetoShield Python API relies only on a built-
in monotonic timer counter, storing its result in a floating-point number. As a consequence,
timer resolution decreases as time passes. Moreover, sample timing is prone to jittering
because of the interpreted nature of the language and the issues mentioned above.
Assuming simple control algorithms, such as PID or LQ with direct state measurement,
the powerful Microchip ATSAMD51 Cortex M4 microcontroller clocked at 120 MHz just
Sensors 2024, 24, 538 16 of 33
barely manages to stabilize the system, while the mid-range Microchip ATSAMD21G18
Cortex M0 MCU running at 48 MHz shows visible degradation in tracking quality.
There are some constraints for data logging; thus, it is recommended to send measure-
ments to an outside terminal program instead of the Mu editor since its graphical plotter
cannot keep up with the data rate in real time. While this may be circumvented by storing
measurements in the internal memory on more powerful models, the M0 family MCU will
not be able to output data to REPL and control magnetic levitation concurrently.
Figure 11. The collection of Simulink blocks constituting the MagnetoShield API.
3.3.1. Outputs
Similarly to the Arduino API, acquiring a distance reading of the flying magnet is
integrated into a single program unit, called the sensorRead block. Here, the user may
select the target device then a desired reading from the onboard sensors: magnet distance,
coil current or voltage and reference from the potentiometer. This block includes functional-
ity equivalent to the sensorRead (), auxReadCurrent () and auxReadVoltage ()
methods in the Arduino and CircuitPython variants of the API.
Sensors 2024, 24, 538 17 of 33
Those wishing to have more control over the direct output and auxiliary sensor readings may
alternatively access the ADC levels at different pins directly by the MagnetoShieldPins
block. This reads the levels as 16-bit unsigned integers and then converts them to a
double-precision floating-point number. The graphical representation of the block changes
according to the selected input type.
The ADC levels may be then converted to physically meaningful units by employing
the OutputConverter block. Here, the target board and the desired measurement and
its units, such as position, voltage, current and percentage, may be selected. Fine-tuning
the conversion is also possible by, e.g., re-defining the parameters of (1) or choosing the
voltage and current measurement gain.
3.3.2. Input
Choosing the actuatorWrite block from the Simulink API is sufficient to send
inputs to the electromagnet. Again, it is possible configure what type of signal is expected
by the block: voltage, percentual values or direct DAC levels. This signal is internally
converted to a 16-bit unsigned integer, then passed to the DAC chip via the I2C bus. In
essence then, this block replaces the actuatorWrite (), a c t u a t o r W r i t e P e r c e n t s
() and dacWrite () methods introduced earlier for the C/C++ and Python versions of
the API.
Should tighter control over the inputs be required, the inputConverter block
provides this option. The GUI allows switching between voltage, percentual mapping or
direct DAC levels.
3.3.4. Limitations
Simulink does not contain a block to switch analog reference levels to external; there-
fore, this must be manually configured in the simulation properties for each example. The
target platform, sampling rate, solver, etc., must also be carefully configured for each exam-
ple; nevertheless, fully functional and pre-configured examples are included in the library.
configuration, all the control algorithms run in real-time on the Raspberry Pi (master part),
and the Arduino only hosts the communication services (slave part).
This setup is conceptually illustrated in Figure 12. The REXYGEN project is developed
on a host PC and then deployed to the Raspberry Pi running the real-time control appli-
cation. In turn, the RPi accesses the MagnetoShield hardware via the physical interface
provided on the Arduino UNO. Note that the two boards communicate via UART; thus,
logic levels must be matched from and to 5 V TTL and 3.3 CMOS for signal compatibility.
Besides development, the host PC can be used for diagnostics and visualization, while a
smartphone or tablet may also be utilized for process visualization.
Figure 12. Block scheme of testing setup and its wiring diagram.
accessed via a web browser, representing the magnet position tracking reacting to the
change in setpoint at three different values.
The visualization part of the project runs on the embedded target itself using a simple
lightweight built-in web server. The entire GUI may be accessed via a standard web
browser without installing any external software components.
0.1
0.08
Execution time (s)
MATLAB
0.06 MATLAB (Due)
Scilab
LabView
0.04 Octave
Target sampling
0.02
0
0 10 20 30 40 50 60 70 80 90 100
Sample (-)
Figure 15. Minimal achievable sampling speeds for reading the ADC and writing to the I2C bus.
Table 2. Execution time for the basic serial communication-based single-input single-output operation
of the MagnetoShield using various software.
4. Demonstration Examples
The hardware of the MagnetoShield itself does not fundamentally limit the gamut of
examples that may be implemented for teaching or research purposes. The fast, nonlinear
and unstable nature of magnetic levitation enables users to explore challenging practical
problems in control and mechatronics. The limiting factor is rather the MCU board from the
viewpoint of (i) computational power, (ii) volatile memory and (iii) non-volatile memory.
In addition to that, the (iv) implementation language can introduce some environment-
specific constraints; especially in the case of interpreted programming frameworks such as
CircuitPython.
The aim of the following discussion is three-fold: to demonstrate the functionality and
closed-loop properties of the proposed hardware, to illustrate a selection of some typical
Sensors 2024, 24, 538 21 of 33
(a) (b)
Figure 16. (a) Dynamic forces acting on the permanent magnet. (b) Representation of the magnetic
fields for the MagnetoShield.
To keep the model simple enough for model-based control, we may approximate this
magnetic force by assuming that the field of both the electromagnet and the permanent
magnet can be represented by an elementary magnetic dipole. In reality, the complex
interaction of the magnetic fields of the solenoid and permanent magnet depends on three
dimensional geometry and would yield an unnecessarily large model for the purposes
of feedback control. Note that in order to the article readable, we will not stick to the
mathematical formalism of (electro)magnetic phenomena.
The time-dependent magnetic moment m(t) of a dipole according to the Ampèrian
model is given by m(t) = i (t)Sr̂, where i (t) is the current passing through a conductor and
S is its area and r̂ is a unit vector perpendicular to the current loop [28–30]. Let us denote
Sensors 2024, 24, 538 22 of 33
the moment of the dipole representing the electromagnet by the lower index a and then
compensate for the number of windings N and reduce the equation to one direction along
the levitation axis as [30,31]
1
mb = MV = Br V, (7)
µ0
where the constant Br is residual flux density or magnetic remanence defining the magnetic
field a material preserves once the external source is removed, while µ0 is the permeability
of free space. Remanence essentially defines the strongest theoretical magnetic field a
permanent magnet can produce at zero gap.
The force acting between the electromagnet and permanent magnet is then approxi-
mated by the force interaction between the two elementary dipoles, given by its scalar form
reduced only to the levitation axis [35–37]
3µ0 ma (t)mb
Fm (t) = − . (8)
2πr (t)4
Let us now substitute for the magnetic moment of electromagnet from Equation (6) and the
permanent magnet from Equation (7) and then summarize the product of all remaining
constants in K to obtain
where
3 SNVBr
K= . (10)
2 π
Next, let us assume that from an electrical viewpoint, our device can be approximated
by a series LR circuit. The voltage U (t) across the electromagnet then consists of ohmic
resistance and the change in current in the inductor,
di (t)
U (t) − Ri (t) − L + ε = 0, (11)
dt
where R is the resistance of the electromagnet and L is its inductance. The final term
on the right ε (V) is the effect of the moving permanent magnet on the electromagnet,
contributing to the overall voltage balance. The voltage balance is illustrated in Figure 17.
The polarity of ε depends on the chosen orientation of the coordinate system, and for
our case, will induce voltage as moves closer to the electromagnet. Models of similar
magnetic levitation devices often completely ignore this effect (e.g., [38,39]), or approximate
it by adjusting the inductance of the coil in distance-dependent terms (e.g., [6,40–42]),
while some simply take a proportional relationship between voltage and current (e.g., [43])
However, even a ferromagnetic steel ball moving in a changing magnetic field affects the
Sensors 2024, 24, 538 23 of 33
voltage in the coil, the ramifications of using a permanent magnet in our design makes this
effect more pronounced.
According to Faraday’s law, this motional electromotive force induced by the changing
magnetic flux is [28,31,33,44]
dΦ(t)
ε=− , (12)
dt
where Φ(t) = B(t)S defines that magnetic flux is magnetic induction (flux density) B(t)
over an area S of loop wire [28,33,37]. Substituting this definition to (12) and compensating
for the number of windings in our electromagnet then yields
dB(t)
ε = − NS . (13)
dt
Although the flux of the permanent magnet could be calculated specifically for the
disk-shaped magnet considered in the MagnetoShield, in order to keep the representation
simple, let us approximate the magnetic flux density of the permanent magnet by an
ideal dipole. The flux density in a distance r (t) along the axis of displacement is reduced
to [45–47]
µ0 2m B µ m
B(t) = 3
= 0 B3 , (14)
4πr (t) 2πr (t)
Substituting for the magnetic moment of the permanent magnet from (7) back to (13)
will give
3SNBr V 1 dr (t)
ε= =K . (16)
2πr (t)4 r (t)4 dt
where the constant K is actually the same as in (10). The final form of the electrical equation
will be
di (t) R 1 1 dr (t)
= − i (t) + U (t) + K . (17)
dt L L Lr (t)4 dt
The final model of the MagnetoShield is expressed by the combination of (9) and (17).
The model may be rewritten in the state-space for natively nonlinear ⊺control
and estimation
⊺
algorithms by choosing state variables as x(t)= x1 (t), x2 (t), x3 (t) = r (t), ṙ (t), i (t) and
assuming the input u(t) = U (t), yielding
Sensors 2024, 24, 538 24 of 33
to obtain
∆ ẋ1 (t) 0 1 0
4Kx03 −c − K ∆x1 (t)
0
∆ ẋ2 (t) = mx5
01
4
mx01
∆x 2 ( t ) + 0 ∆u(t). (19)
∆ ẋ3 (t) 0 K
−LR ∆x 3 ( t ) 1
L
Lx4 01
Table 3. Initial and identified model parameters. (†—measured, ‡—for the mechanical and electrical
equation).
Figure 18. Comparison of the response of linearized model with the experimental data.
Figure 19. Simulation with the proposed nonlinear model using the same PID parameter tuning as
used in experiments.
Table 4. Demonstration examples for various closed-loop control techniques implemented for
different API. † —pseudo real-time, but levitation is attained. ‡ —not possible to implement because
of performance issues. N/A—untested.
These examples have not only been tested across various programming environments
but for different commonly available microcontroller prototyping boards as well; see
Table 5. While traditional feedback methods such as PID and approaches known as
Sensors 2024, 24, 538 27 of 33
“modern control” (e.g., LQ) are fully functional even on the omnipresent Arduino Uno,
hardware-intensive MPC requires boards with higher processor and memory specifications.
Also, the CircuitPython interpreter requires microcontroller-specific porting; thus, is only
compatible to a select group of hardware. There is an enormous selection of microcontroller
prototyping boards that are certainly compatible to the MagnetoShield; however, providing
a comprehensive compatibility list is outside the scope of our discussion.
Table 5. Illustration of the range of feedback control examples on various hardware. Limitations
‡ —memory. ⋆ —untested but hardware implementability assumed to be attainable using at least
one API.
Table 6 lists the recommended minimal sampling periods for various MCU and
control methods. All figures are given for the case of active communication with the design
computer via the serial interface so that monitoring and data acquisition are still possible.
According to our experience, while a sampling time of 5 ms allows stable levitation and
reference tracking, control performance visibly improves with shorter sampling times. The
CircuitPython implementation is a special case because unpredictable memory operations
cannot guarantee strictly real-time operation.
Table 6. Minimum recommended sampling time in ms for various closed-loop control strategies.
The following discussion will not repeat a thorough mathematical description of well-
known control engineering methods. However, in an educational setting, tutorials tailored
to the worked examples may be of value to students.
the MagnetoShield can be as straightforward as employing the pre-built PID block from
the Simulink library and integrating it with the input–output blocks of the MagnetoShield
Simulink API, as depicted in Figure 21.
Figure 21. Simulink scheme for PID control of magnetic levitation using MagnetoShield.
Figure 22. Experiment with pole-placement-based control implemented using Arduino IDE API.
Sensors 2024, 24, 538 29 of 33
Figure 23. Experiment with LQ control implemented using Arduino IDE and Python APIs.
Figure 24. Experiment with explicit MPC implemented on Arduino Due using Simulink API.
5. Conclusions
In this article, we have presented a compact and affordable open-source magnetic
levitation device that can be used for both education and research purposes. The detailed
hardware design and mathematical model derivation, system identification, and validation
provide a solid foundation for anyone who wishes to reproduce or build upon our work. We
still recognize room for improvement regarding either the hardware or software; since the
AutomationShield initiative is driven by the open-source philosophy, anyone is welcome
to contribute and collaborate.
Sensors 2024, 24, 538 31 of 33
The easy-to-use open-source API in C/C++ for the Arduino IDE, Simulink, and
CircuitPython enables users to customize the control algorithms and test different scenarios
with ease. Our calculations demonstrate that the material cost of this device can be less
than USD 34, making it accessible to individuals and institutions with limited budgets.
Looking ahead, we plan to extensively use and examine the capabilities of this device
as an educational tool in control engineering courses. We envision that this device can be
a valuable platform for hands-on experimentation and project-based learning, enabling
students to better understand and apply concepts in control theory. Furthermore, we
anticipate exploring the implementation and testing of additional control algorithms be-
yond the already implemented PID, LQ, and MPC. In summary, this work provides a
comprehensive and accessible approach to magnetic levitation experimentation that can be
used by anyone interested in learning about control engineering or exploring new control
algorithms. The affordability and ease of use make it a valuable tool for students, educators,
and researchers alike.
Author Contributions: Conceptualization, G.T.; methodology, G.T. and M.G.; software, G.T., J.M.,
E.M. and Š.O.; validation, M.G. and E.M.; formal analysis, G.T., M.G. and Š.O.; investigation, G.T.,
J.M. and A.V.; resources, G.T., M.G. and A.V.; data curation, G.T., J.M. and E.M.; writing—original
draft preparation, G.T. and A.V.; writing—review and editing, M.G.; visualization, G.T. and A.V.;
supervision, G.T. and M.G.; project administration, G.T. and M.G; funding acquisition, G.T. and M.G.
All authors have read and agreed to the published version of the manuscript.
Funding: M.G. and A.V. gratefully acknowledge the contribution of the Slovak Research and Devel-
opment Agency under the grants APVV-18-0023 and APVV-22-0436, the Cultural and Educational
Grant Agency of the Ministry of Education of Slovak Republic under the grants 012STU-4/2021
and 027STU-4/2024, and the European Union’s Horizon Europe under the grant no. 101079342.
Š.O. acknowledges the support provided under the project SP2024/021 of Student Grant System at
VSB-TU Ostrava.
Institutional Review Board Statement: Not applicable.
Informed Consent Statement: Not applicable.
Data Availability Statement: The data presented in this study are available on request from the
corresponding author. The data are not publicly available due to privacy.
Conflicts of Interest: The authors declare no conflicts of interest.
References
1. Murray, R. Control in an Information Rich World: Report of the Panel on Future Directions in Control, Dynamics, and Systems; SIAM
Publications Library: Philadelphia, PA, USA, 2003.
2. Rossiter, J. Future Trends for a First Course in Control Engineering. Front. Control. Eng. 2022, 3, 956665. [CrossRef]
3. Brown, M.; McCormack, M.; Reeves, J.; Brook, D.C.; Grajek, S.; Alexander, B.; Bali, M.; Bulger, S.; Dark, S.; Engelbert, N.; et al.
2020 Educause Horizon Report Teaching and Learning Edition. Online. 2020. Available online: https://library.educause.edu/
resources/2020/3/2020-educause-horizon-report-teaching-and-learning-edition (accessed on 20 September 2023).
4. Rezapour Sarabi, M.; Yetisen, A.; Tasoglu, S. Magnetic levitation for space exploration. Trends Biotechnol. 2022, 40, 915–917.
[CrossRef] [PubMed]
5. Zhang, K.; Xu, F.; Xu, X. Observer-based fast nonlinear MPC for multi-DOF maglev positioning system: Theory and experiment.
Control. Eng. Pract. 2021, 114, 104860. [CrossRef]
6. Yu, W.; Li, X. A Magnetic Levitation System for Advanced Control Education. IFAC Proc. Vol. 2014, 47, 9032–9037. [CrossRef]
7. Asato, K.; Teruya, K.; Nagado, T.; Tamaki, S. Development of Magnetic Levitation System for Science and Technology Education:
Magnetic Levitation Control by Using a Hall Element Displacement Sensor with Neural Network. Electr. Eng. Jpn. 2017,
200, 51–60. [CrossRef]
8. Truong, T.N.; Anh Tuan, V.; Kang, H.J. Implementation of an Adaptive Neural Terminal Sliding Mode for Tracking Control of
Magnetic Levitation Systems. IEEE Access 2020, 8, 206931–206941. [CrossRef]
9. Artal-Sevil, J.; Bernal-Ruiz, C.; Bono-Nuez, A.; Penas, M. Design of a Fuzzy-Controller for a Magnetic Levitation System using
Hall-Effect sensors. In Proceedings of the 2020 XIV Technologies Applied to Electronics Teaching Conference (TAEE), Porto,
Portugal, 8–10 July 2020; pp. 1–9.
10. Kalúz, M.; Čirka, L’.; Valo, R.; Fikar, M. ArPi Lab: A Low-Cost Remote Laboratory for Control Education. IFAC Proc. Vol. 2014, 7,
9057–9062. [CrossRef]
Sensors 2024, 24, 538 32 of 33
11. Dormido, S.; Martin, C.; Pastor Vargas, R.; Sanchez, J.; Esquembre, F. Magnetic levitation system: A virtual lab in easy Java
simulation. In Proceedings of the 2004 American Control Conference, Boston, MA, USA, 30 June–2 July 2004; Volume 4,
pp. 3215–3220.
12. AutomationShield. Online. 2023. GitHub Wiki Page. Available online: https://github.com/gergelytakacs/AutomationShield/
wiki (accessed on 2 October 2023).
13. Takács, G.; Mikuláš, E.; Gulan, M.; Vargová, A.; Boldocký, J. AutomationShield: An Open-Source Hardware and Software
Initiative for Control Engineering Education. IFAC-PapersOnLine 2023, 56, 9594–9599. [CrossRef]
14. Zhou, L.; Yoon, J.Y.; Andriën, A.; Nejad, M.I.; Allison, B.T.; Trumper, D.L. FlexLab and LevLab: A Portable Control and
Mechatronics Educational System. IEEE/ASME Trans. Mechatronics 2020, 25, 305–315. [CrossRef]
15. Lilienkamp, K. Low-cost magnetic levitation project kits for teaching feedback system design. In Proceedings of the 2004
American Control Conference, Boston, MA, USA, 30 June–2 July 2004, Volume 2, pp. 1308–1313.
16. Takács, G.; Mihalík, J.; Mikuláš, E.; Gulan, M. MagnetoShield: Prototype of a Low-Cost Magnetic Levitation Device for Control
Education. In Proceedings of the 2020 IEEE Global Engineering Education Conference, Porto, Portugal, 27–30 April 2020.
17. Takács, G.; Mihalík, J.; Gulan, M. MagnetoShield. Online. 2023. Available online: https://github.com/gergelytakacs/
AutomationShield/wiki/MagnetoShield (accessed on 14 September 2023).
18. Mihalík, J. Miniaturizácia Experimentu “Magnetická Levitácia” (Miniaturizing the “Magnetic Levitation” Experiment, in Slovak
Language). Master’s Thesis, Slovak University of Technology in Bratislava, Faculty of Mechanical Engineering, Bratislava,
Slovak, 2018.
19. lady ada. Arduino IDE Setup. Online. 2017. Available online: https://learn.adafruit.com/adafruit-metro-m0-express/arduino-
ide-setup (accessed on 28 August 2023).
20. Plamauer, S.; Langer, M. Evaluation of MicroPython as Application Layer Programming Language on CubeSats. In Proceedings
of the 30th International Conference on Architecture of Computing Systems, Vienna, Austria, 3–6 April 2017; pp. 1–9.
21. George, D.P.; Sokolovsky, P. MicroPython Documentation. Online. 2021. Available online: http://docs.micropython.org/en/
latest/ (accessed on 3 August 2023).
22. MicroPython & CircuitPython Contributors. CircuitPython. Online. 2023. Available online: https://circuitpython.readthedocs.io
(accessed on 3 August 2023).
23. Ionescu, V.M.; Enescu, F.M. Investigating the performance of MicroPython and C on ESP32 and STM32 microcontrollers. In
Proceedings of the 2020 IEEE 26th International Symposium for Design and Technology in Electronic Packaging (SIITME),
Craiova, Romania, 21–24 October 2020; pp. 234–237.
24. Elsevier B.V. ScienceDirect Search Query for “CircuitPython”. Online. 2023. Available online: https://www.sciencedirect.com/
search?qs=CircuitPython (accessed on 3 August 2023).
25. IEEE. IEEEXplore Search Query for “CircuitPython”. Online. 2023. Available online: https://ieeexplore.ieee.org/search/
searchresult.jsp?newsearch=true&queryText=CircuitPython (accessed on 3 August 2023).
26. REX Controls. REXYGEN: Programming Automation Devices without Hand Coding. Online. 2023. Available online:
http://www.rexygen.com (accessed on 29 September 2023).
27. Sobota, J. REXduino (REXYGEN Master and Arduino Slave). Online. 2023. Available online: https://github.com/jaroslavs/
REXduino (accessed on 29 September 2023).
28. Nayfeh M.H., B.M. Electricity and Magnetism; Wiley: Hoboken, NJ, USA, 1985.
29. Bird, J. Electrical Circuit Theory and Technology; Taylor & Francis: London, UK, 2017.
30. Ling, S.J.; Moebs, J.S.W. University Physics Volume 2; Wiley: Hoboken, NJ, USA, 2016.
31. Denny D.; Tang, Y.J.L. Magnetic Memory: Fundamentals and Technology, 1st ed.; Cambridge University Press: Cambridge, UK, 2010.
32. Tewari, K.K. Electricity and Magnetism, 2nd ed.; S Chand & Co.: New Delhi, India, 1995.
33. Cullity, B.; Graham, C. Introduction to Magnetic Materials; Wiley: Hoboken, NJ, USA, 2009.
34. Carlo A. Gonano, R.E.Z.; Mussetta, M. Definition for Polarization P and Magnetization M Fully Consistent. Prog. Electromagn.
Res. B 2015, 64, 83–101.
35. Yung, K.; Landecker, P.; Villani, D.D. An Analytic Solution for the Force Between Two Magnetic Dipoles. Phys. Sep. Sci. Eng. 1998,
9, 39–52. [CrossRef]
36. Gayetsky, L.E.; Caylor, C.L. Measuring the Forces Between Magnetic Dipoles. Phys. Teach. 2007, 45, 348–351. [CrossRef]
37. Furlani, E.P. Permanent Magnet & Electromechanical Devices: Materials, Analysis, and Applications (Electromagnetism), 1st ed.;
Academic Press: Cambridge, MA, USA, 2001.
38. Sadek, U.; Sarjaš, A.; Chowdhury, A.; Svečko, R. Improved adaptive fuzzy backstepping control of a magnetic levitation system
based on Symbiotic Organism Search. Appl. Soft Comput. 2017, 56, 19–33. [CrossRef]
39. Yaseen, M.H.; Abd, H.J. Modeling and control for a magnetic levitation system based on SIMLAB platform in real time. Results
Phys. 2018, 8, 153–159. [CrossRef]
40. Wong, T.H. Design of a Magnetic Levitation Control System: An Undergraduate Project. IEEE Trans. Educ. 1986, E-29, 196–200.
[CrossRef]
41. de Jesús Rubio, J.; Zhang, L.; Lughofer, E.; Cruz, P.; Alsaedi, A.; Hayat, T. Modeling and control with neural networks for a
magnetic levitation system. Neurocomputing 2017, 227, 113–121. [CrossRef]
42. Hurley, W.; Wolfle, W. Electromagnetic design of a magnetic suspension system. IEEE Trans. Educ. 1997, 40, 124–130. [CrossRef]
Sensors 2024, 24, 538 33 of 33
43. Morales, R.; Feliu, V.; Sira-Ramirez, H. Nonlinear Control for Magnetic Levitation Systems Based on Fast Online Algebraic
Identification of the Input Gain. IEEE Trans. Control. Syst. Technol. 2011, 19, 757–771. [CrossRef]
44. Griffiths, D.J. Introduction to Electrodynamics, 3rd ed.; Prentice-Hall: Saddle River, NJ, USA, 1999.
45. Camacho, J.M.; Sosaa, V. Alternative method to calculate the magnetic field of permanent magnets with azimuthal symmetry.
Rev. Mex. Física E 2013, 59, 8–17.
46. Seleznyova, K.; Strugatsky, M.; Kliava, J. Modelling the magnetic dipole. Eur. J. Phys. 2016, 37, 025203. [CrossRef]
47. Jackson, J.D. Classical Electrodynamics, 3rd ed.; Wiley: Hoboken, NJ, USA, 1999.
48. Rossiter, J.A. Model-Based Predictive Control: A Practical Approach, 1st ed.; CRC Press: Boca Raton, FL, USA, 2003.
49. Maciejowski, J.M. Predictive Control with Constraints; Prentice Hall: Upper Saddle River, NJ, USA, 2000.
50. Zometa, P.; Kögel, M.; Findeisen, R. muAO-MPC: A Free Code Generation Tool for Embedded Real-Time Linear Model Predictive
Control. In Proceedings of the 2013 American Control Conference, Washington, DC, USA, 17–19 June 2013; pp. 5340–5345.
51. Herceg, M.; Kvasnica, M.; Jones, C.; Morari, M. Multi-Parametric Toolbox 3.0. In Proceedings of the European Control Conference,
Zurich, Switzerland, 17–19 July 2013; pp. 502–510. Available online: http://control.ee.ethz.ch/~mpt (accessed on 12 May 2023).
52. Takács, G.; Zometa, P.; Findeisen, R.; Rohal’-Ilkiv, B. Embedded model predictive vibration control on low-end 8-bit microcon-
trollers via automatic code generation. In Proceedings of the 23rd International Congress on Sound and Vibration, Athens,
Greece, 10–14 July 2016; pp. 266/1–266/8.
53. Gulan, M.; Takács, G.; Nguyen, N.A.; Olaru, S.; Rodriguez-Ayerbe, P.; Rohal’-Ilkiv, B. Embedded linear model predictive control
for 8-bit microcontrollers via convex lifting. IFAC-PapersOnLine 2017, 50, 10697–10704. [CrossRef]
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual
author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to
people or property resulting from any ideas, methods, instructions or products referred to in the content.