Using ESP8266 and Arduino
In this project article, Jeff leverages the concept of magnetic repulsion to levitate an object. To explore the physical properties involved, he starts with some cool old “maglev” vehicle toys. He then implements the project using Espressif’s ESP8266 MCU and Arduino programming.
The Earth is composed of layers having different chemical compositions and different physical properties. Earth’s crust has some permanent magnetization, but it’s the planet’s core that generates its own magnetic field. It’s this magnetic field that we measure at the surface.
The Earth’s core has a temperature of several thousand degrees Celsius, due to radioactive heating and chemical differentiation. This is a bit like a naturally occurring electrical generator, where the convective (kinetic) energy is converted to electrical and magnetic energy. The process is self-sustaining, as long as there is an energy source sufficient to maintain convection.
The Earth spins on an axis we’ve come to know as the North Pole and the South Pole. But, due to a non-spherical core, the magnetic field produced is not aligned with the spin axis. Because this varies over time, maps are regularly tweaked every 5 years or so, to indicate the present declination offset. The declination constant is the number of degrees that a compass’s north reading is off from the north pole axis. This varies with your location on Earth. We have proof that the Earth’s magnetic field has actually totally reversed over time. The last reversal was about 780,000 years ago, and usually happens over a period of hundreds of thousands of years.
The Earth’s magnetic field deflects most of the solar wind, the charged particles of which would otherwise strip away the ozone layer that protects us from harmful ultraviolet radiation. Earth’s magnetic field provides most of us with a way to navigate the world. We use a pivoting magnet or compass to detect this magnetic field and tell direction. Many animals seem to have a built-in compass, which helps them to navigate migration routes.
MOTORS AND MAGNETS
We use the power of magnets to create motors, solenoids, contain plasma and even hold artwork on the refrigerator. Magnets—or the fields they produce—can be used to both attract and repel. All magnets have both a north pole and south pole. If let free, they will naturally attract themselves toward opposite poles—N-to-S and S-to-N. If magnets are held N-to-N or S-to-S, they will repel one another, trying to get away from like poles. This repulsion is an unstable state, but is just as useful as attraction. In fact, when used in a motor, it provides for half the torque, or ability to move. Let’s take a closer look at how magnetic fields are used to produce motion.
Many of us built a motor in a high school physics class. A good video for demonstrating this can be found on YouTube . The motor is made up of a current source (AA cell battery), a coil (loops of insulated wire), a magnet and an armature (paper clips). The armature is actually a combination of the paper clips, which are used as a conducting bearing, and the coil of wire, which has its ends extended in opposition directions, such that they act as an axle extending through the clips. With a paper clip at each end of the battery, the coil is hung between the clips like a hammock, with the magnet stuck to the battery under the coil. Depending on your battery’s makeup, your magnet may need some glue, tape or clay to stay in place.
Because the coil’s wire is insulated, there will be no current flow. Place the coil on a flat surface, and scrape away the insulation from just the top of both ends. Place the coil back in its paper-clip cradle. When the coil is rotated so the bare side of the coil wires comes in contact with the clips, current should flow through the coil, and the magnetic field produced will cause the coil to attract toward or repel from the magnet, producing a torque and rotation. Momentum will cause the coil to continue rotating once the coil’s insulation turns and interrupts the current flow. The motor will get a push each time the uninsulated portion of the coil leads come in contact with the clips again.
There is some important timing between when the current flows and the position of the coil that makes this all happen. The current must be enabled (pulsed) at the appropriate time for continuous movement. Unless the coil’s current is disabled, once the coil’s rotation brings its magnetic field to its closest point of attraction with the stationary magnet, it will attempt to stay there, preventing further rotation.
The simple motor I just described is actually made up of two magnets—a stationary, permanent magnet (mounted on the battery) and an electromagnet made of a coil of wire. The electromagnet can be energized, creating a controllable magnet. This simple example applies the same polarity to the coil once every 360 degrees of rotation. In contrast, more sophisticated motors use a commutator to apply one polarity for the first half revolution and the opposite polarity for the other half revolution. This gives the motor coil two attractions per revolution. Motors can have multiple sets of coils and commutators to provide increased torque, and are categorized as “brushed DC motors.”
While the design of commutator does all the enabling and polarity swapping, it has a wear point—the brushes (wipers) that make and break connections as the shaft spins. We can eliminate this point of wear by swapping the locations of the permanent magnets and electromagnets. With permanent magnets on the spinning armature and the electromagnets stationary, no brushes are needed, and these motors fall into the “brushless” category. However, we need some smart circuitry to handle electronic control of the coils. These motors were used in disk drives, and are now popular in electric airplanes and drones (see my three-part article series “Electronic Speed Control” in Circuit Cellar 336-338 (July through September, 2018 ). Figure 1 shows the placement of the permanent magnets (PM) for brushed and brushless DC motors. If we split the DC motor and flatten it out as in Figure 2, then the rotary motion is turned into linear motion. Note that the stator (outside) and rotor (inside) are interchangeable.
Back in 1990, I wrote about suspending an object in the air (“How to Defy Gravity Without the Use of Black Magic” (Circuit Cellar 18, December 1990/January 1991) ). That project used an electromagnet to attract an object with an embedded magnet, and keep it suspended. This month we’ll flip that idea upside down. Instead of suspending with attraction, we’ll suspend by repulsion. Actually, that part is easy. If we could position a PM atop a PM such that they repelled, one would hover over the other. Unfortunately, without some way to keep them from straying, they will just move off axis.
I love toys. They can provide an inexpensive way to investigate and experiment with physical properties. While looking for some examples of magnetic levitation, I zeroed-in on a couple of “maglev” vehicles. You may have seen instances of maglev trains in China, South Korea or Japan. Some systems have been built for short hauls, such as city-to-airport shuttles. Like all new technology, the costs are very high and few, if any, have been profitable.
I managed to get hold of two maglev toy trains: the OWI Robotikit’s Magnetic Levitation Express (Figure 3a) and the Discovery #Mindblown Levitating Train Set (Figure 3b). Each uses similar principles, but the implementation is slightly different. Hovering is accomplished using a plastic, embedded, magnetic material.
On a side note: You can find Hall-effect pens (Figure 4). This a pen will show N or S (and beep) upon locating a magnetic field. I used this one to determine how various materials were magnetized. Flexible rare earth or ferrite magnets are made by calendaring or extruding magnetic powders in a flexible mixture such as vinyl. Magnetic powder densities affect the manufactured magnetic properties of the final product. This material can be magnetized in many formats (Figure 5). For instance, common refrigerator magnets have these properties on one side only. They are frequently magnetized with alternating poles by dragging a number of strong (neodymium) magnets across their surface, setting up stripes of alternately magnetized material.
I used the magnetic pen and found alternating poles in one direction, with stripes of single poles in the other direction. I experimented by drawing two circles on the material (about the size of a penny). Then using a magnet, I rubbed the surface inside one circle with an N pole and the other circle with the S pole of the magnet. With the magnetic pen, I was able to verify that the area within each circle became magnetized with different poles! Interestingly, the opposite surface of the refrigerator magnet did not show signs of magnetism.
Now, back to the levitating trains. With the magnetic pen, I was able to determine that the magnetic strips used in both kits came in two formats. The first format I’ll call “the hovering strips.” These were magnetized such that each surface was a single pole, with the top surface one pole and the bottom surface the opposite pole. The second format, which I’ll call “the position strips” has an alternating pattern of poles along each surface. The spacing of the poles alternates every 0.5”, which is the same for both kits!
The trains, themselves, have matching hovering magnets along the left and right sides of each car. These are spaced the same distance apart as the hovering magnets in each track segment. The tracks are smooth, with no physical rail. The train cars float over the track from the opposing magnets. But without some method of keeping a car centered, it wants to derail off to one side or the other.
The Discovery train uses hovering magnets of the same pole on each side of the track. This means the car magnets must be both the opposing poles. You can place the car on the track in either direction and it hovers. The OWI train uses opposite hovering magnets, and the train will hover in one direction and attract the roadway in the other. This may seem short-sighted until you see how the systems differ.
The difference lies in how each train is kept centered on its railbed. The Discovery train hovers over the railbed with sides that extend down along the side of the track. Both sides have small wheels that can touch the track’s side and prevent the car from falling laterally off the track. These are not supporting the weight of the car, merely keeping the car centered.
Like the Discovery train, the OWI train also wants to move laterally away from the center of the track. However, it runs slightly off center, such that it is always trying to move latterly to the right. The train has wheels on the right side only. These wheels do not touch the track. Instead, they touch an external side wall that runs along one side of the track, thus keeping the train from derailing.
The two train sets differ not only in how they remain hovered over the railbed, but also in the formats they use for controlling the movement of the trains. Both sets move using the same magnetic principles, but they sense their positions in different ways. The OWI train uses the positioning strips located on the side wall toward which it is being repelled. Twin Hall-effect sensors located in the front and back sides of the locomotive read the positioning magnet’s alternating poles. The spacing between the sensors is not a multiple of the 0.5” alternating poles distance of the position magnets. This means the signals from them will be slightly out of phase with one another. This is exactly like those used to encode wheel movement. They provide both movement and direction detection.
The Discovery train uses an optical system for determining position/movement. The track in this system is more like a traditional train track that has railbed ties. The ties don’t actually hold any physical rail—there are open spaces between the ties in the railbed. The spacing is the same as the position magnets—a 0.5″ opening followed by a 0.5″ tie. An IR (infrared) LED transmitter-receiver pair looks down at the track and signals a reflection when the sensor passes over a tie. I find it interesting that the Discovery train does not use Hall sensors or even two IR sensors. Therefore, it can detect position/movement, but not direction.
Now we get down to the meat and potatoes. The position magnets are used by each train to provide movement, because internal electromagnets can be electronically controlled to give the train a push away from an identical pole or a pull toward an opposing pole. With timing coming from the position sensors, and magnetism coming from driven electromagnets, the resulting force is directed either forward or backward, due to the restraining wheels. Once started, the train’s momentum continues to urge it in the same direction.
While the forces at work are the same, each set uses a different electromagnetic format. As shown in Figure 6, the OWI train uses a single coil wound around an armature that provides three poles located on the train’s side opposite the location magnet. The spacing between poles is 0.5” and matches the N-S-N-S-N-S points on the wall’s position magnet. With a single electromagnet, the controller has limited drive options, but it does have a good sensing system.
The Discovery train has four electromagnets (one hidden under the PCB) along the floor of its locomotive (Figure 7). The magnets are spaced on 0.5” centers. All the windings are in parallel, but they are phased such that they are opposite their neighbor alternating N-S-N-S or S-N-S-N. These exactly match the poles in the positioning magnet located in the center of the railbed. Because the four discrete electromagnets are wired in parallel, the controller has limited drive options, and with limited position sensing, no fancy timing is possible.
Both train sets have microcontrollers (MCUs) to control the operation. Each set has several operating modes. The Discovery train uses a push button (OFF-1-2-3-OFF) with an LED blinking feedback, and the OWI train uses a multi-position slide switch (OFF-1-2) and LED feedback. Modes are merely different timings for switching the electromagnets to create some maximum speed of the train. Since the mode switch is the only control a user has over either train, after it traveled around the loop a few times, I found myself wanting more. What’s a train set without throttle control?
I prefer the features of the Discovery set, because it more closely resembles the actual maglev trains that are in limited use today. To make use of the embedded hardware that already exists, I decided to bring out the track sensor and the coil connections using separate connectors. Since I wanted to keep my added hardware as small and light as possible, I used a Heltec Kit 8, which uses a ESP8266 with on-board OLED. To avoid having to chop up the existing circuitry, I also added a motor driver for the electromagnets. The schematic is shown in Figure 8.
The first thing you’ll notice is that the motor (coil) driver is a dual device, capable of driving two independent coils. Although both sets have a single driver for their respective coil(s), the Discovery set has four individual coils. The “like” pairs can be driven separately, a path that opens up some future experimentation. Even though this MCU has a display, flashing LEDs are nice. Placed on the control inputs to the coil drivers, they allow one to see how each coil pair is being driven. Note that two extra inputs on GPIO1 and GPIO3 are for monitoring the original circuit’s coil driver. Monitoring these allowed some investigatory work to take place before my algorithm development.
Because the ESP8266-based circuit has Wi-Fi capabilities, control in the form of a “virtual joystick“ can be performed from a computer or smartphone. This is done using an awesome server that presents a control to a client through the standard browser interface . This is in the form of an HTML file and a Java Script support file that are stored in a SPIFFs partition on the ESP8266.
The Arduino sketch for this project is available on Circuit Cellar’s article code and files download page. The Arduino program initializes the required library files for the FS (file system) and Wi-Fi server, and implements a callback routine to receive the X and Y coordinates of the virtual joystick . While I allow the system to log onto my home network, you might wish to have it create its own network. I use the OLED to display some Sign On messages and display its IP address when it has connected to my network. Simply point any browser to this address to get the user interface. The photo in Figure 9 shows my computer browser’s screen and the maglev train with my circuit running on a small Li-Ion battery. Note that the joystick’s Y-Y position in the browser is displayed on the OLED!
Although I have access to both x and y values in the Arduino program, only x is being used as the throttle for this project. So how is that value turned into coil drive output? Let’s begin by looking at the coil driver chip. I used Pololu’s DRV8835 Dual Motor Driver Carrier module for its size and less than 1A current rating. It fit snugly between the dual row headers of the Heltec’s ESP8266 board. Each channel has two inputs: phase (1) and enable (2). I used a direction (or phase) to input 1 and a PWM (or enable) to input 2. The direction determines the polarity of the output, and the PWM determines how long that output remains ON or active. At this point, we’re just trying to emulate the original operations, so ON will be 100%. The throttle control will actually change the speed of the pole changes and not the PWM, which would be the average current or magnetic strength of the coil.
The main loop timing determines how often the phase on the coils is changed. The timing is 1,000 – (abs(x) * 9) ms. Since the joystick will return an x from 0 to 100 (percent) for movement to the right, the timing could vary from 1,000ms (1,000 – (0×9)) to 100ms (1,000 – (100×9)). In this loop, if x =0, then we call noGo() otherwise we call go(). noGo() sets the PWM to 0, which stops any drive to the coils. Once the joystick moves from 0, the routine go() is used. This sets the PWM to the maximum 1,023 and allows full power to be applied to the coils. In this, the simplest version, the sensor is not used at all.
PUSH COMES TO SHOVE
It’s a flip of the coin whether either of these sets will actually move when current is applied and they are at rest (not moving). Without some kind of outside intervention, such as a push, they may be happy to just bounce a bit up and down. The OWI set with a single coil has no chance of moving off a pole if it is placed directly on one. While the Discovery set has multiple coils, they are wired together, and the results are the same. These can be easily separated, however, and then driven with this project’s dual drivers. We do have what is needed to achieve guaranteed movement from a steady state.
A few notes on these kits. The OWI kit (eBay) seems to be supported by the manufacturer. The instructions are complete with a parts list order form including prices. The Discovery set had instructions and that’s it, no contact info. In fact, I bought it from the Henry Ford gift shop, but the box had a Kohl’s department store sticker on it and is no longer sold by either company. Recently, I did find a new version of the Discovery set for sale on FAO Schwartz’s website for $35 .
One last thing, I’ve read some reviews of both kits and not many people had anything nice to say. I suspect this is because of the adhesive that comes on the magnetic strips. It just plain doesn’t hold. This was extremely frustrating because the magnets continually fell off or lifted up, making the train derail. After I realized I could stick them on permanently with super glue, everything was fine. It is interesting that both sets had the same issues. The fix was simple—I used the super glue that comes in a bottle with a small brush. I glued the plastic train parts as well, since these were snap-together kits, and with a lot of handling, the parts tended to work themselves loose.
My children are now adults, each (sans one) has their own family, and with many grandkids, I am continually exposed to the latest gadgets when visiting them. I get dirty looks from these kiddos every time I take out my Leatherman screwdriver. They know what’s about to happen. Too much to learn, so little time.
 Video: How to Make a Simple Motor:
Circuit Cellar 336, July 2018
Circuit Cellar 337, August 2018
Circuit Cellar 338, September 2018
 Figure 1 www.rcgeeks.co.uk/blogs/news/what-are-brushless-rc-cars
 Figure 2 https://en.wikipedia.org/wiki/Linear_motor
 “How to Defy Gravity Without the Use of Black Magic” (Circuit Cellar 18, December 1990/January 1991)
 virtual joystick
PUBLISHED IN CIRCUIT CELLAR MAGAZINE • APRIL 2021 #369 – Get a PDF of the issue