MASARYK UNIVERSITY FACULTY OF INFORMATICS Measurement and visualization of static magnetic fields BACHELOR'S THESIS Oldřich Pecák Brno, Spring 2020 MASARYK UNIVERSITY FACULTY OF INFORMATICS Measurement and visualization of static magnetic fields BACHELOR'S THESIS Oldřich Pecák Brno, Spring 2020 This is where a copy of the official signed thesis assignment and a copy of the Statement ofan Author is located in the printed version of the document. Declaration Hereby I declare that this paper is my original authorial work, which I have worked out on my own. All sources, references, and literature used or excerpted during elaboration of this work are properly cited and listed in complete reference to the due source. Oldřich Pecák Advisor: RNDr. Zdeněk Matěj, Ph.D. i Acknowledgements I would like to thank my advisor RNDr. Zdenek Matej, Ph.D., for the consulting and his excellent suggestions about the project. I also have to give thanks to the laboratory of digital systems, namely the people involved in it for enduring my rubber duck debugging methods and letting me occupy the space required by the project. Lastly, I need to acknowledge all the remaining unnamed people1 who supported this endeavour of mine. 1. If you are not sure if you are included, ask the author. ii Abstract This thesis presents Cube, a prototype of an open-source system for measuring and visualizing static magnetic fields. The system has two major components: (1) hardware for data acquisition and (2) software for control and visualization. The hardware consists of a C N C machine mechanically similar to 3D printers built from standard parts and accompanying control electronics. Measurement is done using a common 3-axis magnetometer sensor. The software provides a simple control interface and visualization capabilities. Emphasis was on using already existing visualization toolkits rather than creating new ones. Although the prototype is currently relatively simple and lacks certain desirable features, the results show good quality and potential for future work, using this prototype as a base and expanding it further. The prototype shows that we can use common parts and software toolkits to produce data and visualizations that are usable for basic scientific work with slight limitations. iii Keywords magnetic field, data acquisition, vector field, visualization, measurement, magnetometer, sensor, motion platform iv Contents 1 Introduction 1 2 Preliminaries 3 2.1 Magnetic field 3 2.1.1 Maxwell's equations 3 2.1.2 Field lines 5 2.1.3 Permanentmagnets 7 2.1.4 Units 7 2.1.5 Measurement 8 2.2 Existing solutions 9 2.2.1 Commercial 10 2.2.2 Non-commercial 10 3 Prototype goals 12 4 Hardware 13 4.1 Sensor 13 4.2 Motion platform 15 4.2.1 CoreXY mechanics 17 4.3 Electronics 18 4.3.1 Stepper motor control 19 4.3.2 Control signal generation 19 4.3.3 Connectivity 20 4.3.4 Power 21 4.3.5 Printed Circuit Board 21 5 Firmware 23 5.1 Firmware architecture 23 5.2 Motion planner 25 5.3 Communication protocol 26 5.4 Instruction set 28 5.5 Drivers 30 v 6 Software 31 6.1 cube_comm.pylibrary 31 6.2 Interactive console 31 6.3 Measurement tool 32 6.3.1 Configuration 33 6.3.2 Measurement procedure 34 6.3.3 Data output 34 6.4 Visualization 36 6.4.1 Vector field visualization methods 38 6.4.2 Launcher script 42 6.4.3 Limitations 42 7 Examples 43 8 Conclusion 49 8.1 Future work 49 Bibliography 51 A Attached files 53 B Visualization launch guide 54 C PCB Schematic and Drawing 55 vi List of Figures 1.1 Magnetic field visualization tools 1 2.1 Ampere's law 4 2.2 Faraday's law 4 2.3 Magnetic field around a bar magnet 6 2.4 Magnetic field around a coil and perfect dipole 6 2.5 Hall effect 9 4.1 The sensor development kit 14 4.2 Cube motion platform 16 4.3 Sensor mount 16 4.4 CoreXY diagram 17 4.5 Electronics block schematic 18 4.6 Step and direction signals 19 4.7 Shield PCB 22 4.8 K64F-FRDM development kit 22 5.1 Firmware architecture 24 5.2 Schema file of command message 27 5.3 Communication protocol packet 27 6.1 Interactive console 32 6.2 Example configuration file 33 6.3 Scanning path 35 6.4 Output file format example 35 6.5 Mayavi user interface 37 6.6 Quiver plot example 38 6.7 Streamlines example 39 6.8 Isosurfaces example 40 6.9 Scalar visualization example 41 vii 1 Introduction Magnetic field is a long-known and relatively well-understood physics phenomenon. Together with the electric field, they create the electromagnetic field, which we exploit greatly in modern technology. It is vital in many engineering areas, such as electric motor design, electronics, magnetic resonance imaging and more. Although the magnetic field is so widely exploited, we will always have a problem visualizing it in real life, as it is invisible to human eyes. That slows us down in understanding the field and how it interacts with the environment around it. We do have tools to help us visualize it, but they have severe limitations. They are usually limited to a single point or a 2D plane and thus do not provide a sufficient overview of the field. That limits their usefulness for understanding complex fields and their interactions with the environment and materials. Figure 1.1: Various tools for visualizing magnetic field. From top left clockwise: magnetic film [1], iron shavings [2], compass [3]. 1 i . INTRODUCTION This visualization problem is not present in simulated magnetic fields, as we can use various methods of scientific visualization to explore it. The logical next step is to use the same toolkits to explore data measured from the physical magnetic field. Commercial tools already exist, but they are usually designed more for verification and quality assurance testing, rather than visualization. Those products are also often out of reach for students, amateurs and many organizations due to their price. This thesis proposes and builds a prototype of an open-source system for both measuring and visualizing magnetic fields in 3D space. The emphasis is on using common materials, parts and components, to lower the cost and complexity of the system. This emphasis also extends to the software part of the system, where we use common scientific visualization tools for volumetric datasets. Current results show that the prototype can be used even for more complex measurements and visualizations with some limitations. According to our research, it is the only available non-commercial solution that is both open-source and is in state that allows for practical usage. The prototype is called Cube1 . The name can be often encountered in the source files. We introduce basic understanding of the magnetic field in the preliminaries, where we also give overview of already existing solutions. Prototype goals are then discussed in chapter Goals. Following chapters describe the hardware,firmware and software of the prototype. Lastly, we provide examples that show the capabilites of the prototype and discuss the results and possible future work in the conclusion. 1. Inspired by the final hardware shape. 2 2 Preliminaries As we want to measure and visualize the magnetic field, we need to have at least a basic understanding of it. We present sufficient fundamentals in this chapter. That includes the basic definition, units and measurement tools. Furthermore, similar systems that serve the same purpose as our prototype already exist. Thus we need to give an overall context for our work. To better understand where our prototype fits in, we give a brief overview of already existing solutions. 2.1 Magnetic field Magnetic field is a vector field most often associated with magnets and wires carrying current. When an electric charge moves through the field, a force acts on the charge. Similarly, when a magnet is placed in the field, it tries to orient itself in the same direction as the field. As it is a vector field, we can define its direction and strength at any point. This is in contrast to the electric field, which only gives a scalar potential at any point. Magnetism often works with the concept of north and south pole. Using a compass needle (which is a magnet), their definition is simple [4, p. 378]: North (seeking) pole is the end that turns towards the Earth's geographic north pole (Earth's magnetic south pole) South (seeking) pole is the end that turns towards the Earth's geographic south pole (Earth's magnetic north pole) The conventional way of defining and describing the behaviour magnetic fields involves Maxwell's equations, which describe the electromagnetic field. The electric and magnetic fields in the equations are tightly coupled together and affect each other. We will also use the basic description of Maxwell's equations to introduce how the magnetic field behaves. As we only need a conceptual understanding of magnetic field, we will not try to understand the mathematical formulations fully, and they are only noted for the sake of completeness. 2.1.1 Maxwell's equations Maxwell's equations were first described by James Clerk Maxwell in 1864 as a set of nine equations [5]. In modern formulations, they are a set of four coupled partial differential equations. They can also be written in the form 3 2 . PRELIMINARIES of integral equations. In the following equations, we use B for magnetic field and E for electric field. u$ and £o are the vacuum permeability and vacuum permittivity constants. Ampere's law with Maxwell's addition states that change in electric field (e.g. electric current) creates a magnetic field [6, p. 290-291]. This is the source of all magnetic fields, including permanent magnets. It also gives us the first equation that describes the relationship between electric and magnetic field. V x B = fi0e0— + fi0J Figure 2.1: When a current I flows through the conductor, the compass needle aligns itself with the magnetic field that is created around the conductor. This is caused by the Ampere's law. Faraday's law states that a change in the magnetic field induces a change in the electric field [6, p. 356-357]. This gives us the second equation that describes the relationship between the two fields. Figure 2.2: When a magnet is moved through the coil, a current I flows through the conductor. This is caused by the Faraday's law. 4 2 . PRELIMINARIES Gauss's law for magnetism states that flux of magnetic field enclosed by a surface is equal to zero [6, p. 437]. This implies that magnetic monopoles, or magnetic charges, do not exist. V - B = 0 Gauss's law states that net flux of electric field through a surface is proportional to the net electric charge enclosed by the surface [6, p. 23-26]. This describes the relationship between electric charges and the electric field created by them. £o The four equations are also often accompanied by the definition of Lorentz force, which describes the force acting upon a charge in electromagnetic field [7, p. 30]. The Lorentz force is defined as: F = q(E + v x B) where q is the charge and v is it's velocity vector. 2.1.2 Field lines Although Maxwell's equations are the conventional way of introducing and describing magnetic fields, they are often problematic to grasp, as they are purely mathematical. One of the earliest and most visual ways in describing magnetic fields are field lines. Field lines follow the vector field and are identical to streamlines in steady fluid flow. They are directional, exiting the north pole of a dipole and entering the south pole. They are solenoidal, forming either closed loops or extending to infinity. These properties can be seen in figure 2.3. The advantage of using field lines is that many laws of electromagnetism and the standard units can be translated directly to using field lines as a unit. If we use a single field line as the elementary unit, we can express the total strength of the magnetic field as the total number of field lines. Similarly, we can express the magnetic flux of a surface. It is the total number of field lines passing through the surface. Magnetic flux density is the number of field lines per unit area[4, p. 384]. Perhaps the most beautiful interpretation is that of the Gauss's law for magnetism. Translated to field lines, it states that for every volume enclosed by a surface, the same amount of field lines has to enter and leave through the surface. 5 2 . PRELIMINARIES Figure 2.3: Magnetic field lines around a bar magnet [8]. Figure 2.4: Magnetic field around a coil and perfect dipole. By reducing the size of the coil infinitely, we will achieve the same magnetic field as the one around a dipole [8]. 6 2 . PRELIMINARIES 2.1.3 Permanent magnets Ampere's law only accounts for electric currents and changing electric field. This definition excludes permanent magnets which seemingly have no current flowing through them, yet they create a magnetic field. The topic of magnetization and magnetic materials is out of the scope of this thesis. We will proceed with only a basic explanation. First, we need to understand that a large permanent magnet can be divided into a group of elementary magnetic dipoles. Then, we can show that elementary magnetic dipole is identical to an infinitesimal current loop. This principle is illustrated graphically in figure 2.4. The current in the elementary dipole is the movement of elementary atomic particles, such as electrons [7, p. 25-28]. 2.1.4 Units We use SI units in the thesis. Table 2.1: Electromagnetism related units [9]. Quantity Symbol Unit Symbol Electric charge «7 Coulomb C Electric field strength E volt per metre V / m Magnetic flux O B weber Wb Magnetic flux density B tesla T Magnetic field strength H ampere per metre A / m As noted in the section about field lines, we can use field lines as the basic unit. Then a single field line equals 1 Weber. We should also highlight that B and E in Maxwell's equations correspond to the ones in the table above. There is usually a confusion on which quantity is the magnetic field. The magnetic flux density B and the magnetic field strength H are often both called magnetic field. As Maxwell's equations in this thesis are written using B, when we refer to the magnetic field, we mean the magnetic flux density. 7 2 . PRELIMINARIES 2.1.5 Measurement Instruments for measuring magnetic fields are called magnetometers. Depending on which quantity we want to measure, there are many different methods for measuring magnetic fields. We divide them into two categories. Scalar magnetometer can measure only the total strength of the magnetic field Vector magnetometer can measure both the direction and strength of the magnetic field Examples of scalar magnetometers are the proton precision magnetometers and optically pumped magnetometers [10]. They are rather uninteresting for us, as they cannot provide enough information about the field. Vector magnetometers are more common nowadays, and there are many different types. The simplest vector magnetometer is the induction coil, which uses Faraday's law to detect changes in the magnetic field. It cannot measure static magnetic field. One of the more common low range (in the order of hundreds of uT) magnetometers is the fluxgate magnetometer. The sensor uses the magnetic properties of materials in combination with Faraday's law to detect changes in magnetic flux density [10]. It is a vector magnetometer. Another type of magnetometer used in laboratories is the SQUID (Superconducting Quantum Interference Device) magnetometer. It requires operating temperatures near absolute zero [10]. It is the most sensitive vector magnetometer type currently available. Most common, commercial vector magnetometers used in smartphones as a digital compass and in various solutions noted in the following section are Hall effect magnetometers. Hall effect was discovered by E. H . Hall in 1879 [6, p. 317]. When a perpendicular magnetic field is applied to a conductor carrying a current, small voltage can be measured over the width of the conductor. This voltage is called the Hall voltage. Without the magnetic field, the measured voltage would otherwise be zero. The effect is caused by the deflection of charge carriers by the magnetic field. It is directional. Figure 2.5 shows the effect visually. As the Hall effect can be measured using a normal conductor, we can create a semi-conductor based magnetometers that operate at room temperatures. By using arrays of plates to measure the Hall voltage in three perpendicular axes, we can obtain the exact vector of the magnetic field at the point of measurement. Hall effect magnetometers also have a high range of 8 2 . PRELIMINARIES Figure 2.5: Presence of the magnetic field B causes a measurable voltage difference between points flo and d\ on the width of the conductor carrying current I. measurement (up to tens of tesla), which makes them particularly suited for measurement of common magnetic fields around a wide variety of sources. 2.2 Existing solutions Many solutions for measurement and visualization of magnetic fields already exist. They can be divided into two categories: commercial and noncommercial. We can divide existing solutions by other types, but that would lead to higher fragmentation. Commercial solutions are most often designed as a quality control and verification tool. Thus they focus on significant precision and accuracy of both the probe and motion platform. That comes with a substantial increase in price and puts them out of reach for most hobbyists and even many institutions. The visualization tools also often lack in features. Most non-commercial solutions are academic. They are usually just a single-time purpose-built devices for the task at hand and are not the main subject of the work. The documentation, source code or guides to replicating the devices is usually not available. That means that we cannot quickly build our version of the device without investing the time needed to develop it. There are little to none hobbyist or amateur projects. 9 2 . PRELIMINARIES 2.2.1 Commercial Few companies focus on magnetic field measurement systems. Magcam1 offers unique sensors called MiniCube. Those sensors are "magnetic field cameras". They consist of a dense array of Hall effect sensors (128 x 128 array with a resolution of 0.1 millimetres). The Hall effect sensors are either ID or 3D, depending on the MiniCube variant. The company also offers 3D motion platforms for scanning and working with the sensors. The sensors and motion platforms are intended to be used as inspection and quality assurance tools. Their visualization software is limited to 2D plane visualizations. Senis AG2 is a Swiss company that produces various products for magnetic and current measurement. They offer several versions and sizes of magnetic field mappers. Their primary objective is high precision and accuracy of both the motion platforms and the sensors. The sensors they use are developed inhouse. The company also offers various complementary equipment, such as calibration tools. There are more companies with products that can measure magnetic fields, but either little info is provided, or the systems are custom solutions built to specification. 2.2.2 Non-commercial Few notable academic efforts stand out. The first one is work done by Tumanski and Liszka [11]. They describe a design of a "magnetovision" system. The system can scan the magnetic field over a volume and visualize the acquired data. Both motion platform design and probe design are discussed in great detail. Several designs for the probe array are presented, with focus on either speed or quality of measurement. The visualization is only done as 2D slices of the scanned volume. The paper by Bergsma et al. [12] describes the build of a large scale measuring system for scanning large magnet assemblies at CERN. The hardware is built with high precision as the primary focus. The scan volume is rather large at 1 x 1 x 2 meters. The paper focuses only on the hardware and describes the mechanical construction, probe construction and calibration, and control. Off the shelf motion control and data acquisition modules are used. There are no mentions of visualizing the acquired data. 1. https://www.magcam.com/ 2. https://www.senis.ch/ 10 2 . PRELIMINARIES Mikolanda et al. [13] developed a system for scanning magnetic fields in a 2D plane. Purpose of the system is to verify simulation data. The system uses a 3D hall probe for measuring the field. Several methods of visualizing the acquired data are presented, and the advantages of each method are discussed. The paper by Huber et al. should also be noted [14]. The paper's focus is on 3D printing magnets, but they also use a 3D printer to scan and verify the created magnet. They discuss the calibration method, but the overall information on the scanning process and visualization is not mentioned. The most notable non-commercial effort is the project by Yapo [15]. This is the only hobbyist project that shows any results. His work focuses on using commonly available hall effect magnetometers in combination with a 3D printer to acquire the data. The usage of a 3D printer as a mechanical base is similar as in work by Huber et al. [14]. This approach lowers the overall cost of the system considerably, and from the showcased results, it does not significantly lower the quality of output. The importance of this project is mostly the research and notes written by Yapo during the development. The project logs describe calibration and tests of various magnetometers, various thoughts on the scanning process and on processing the measured data. The visualization tools are developed from scratch and are not as fully featured as some already existing solutions. As of time of writing this thesis, no available source code or documentation to replicate the project's results has been released. 11 3 Prototype goals We need to set clear goals for our prototype. They will help us during the development of the prototype, as we can use them to decide what should we prioritize. We can also use them as criteria for the evaluation of the prototype after the development is finished. • If suitable tools already exist, use them if possible. They can drastically shorten the development time, but they also might require extensive modifications or their setup can take a non-trivial amount of time. For this reason, each existing tool has to be evaluated before being used. • The prototype should use common, easily sourceable components. Expensive, proprietary components should not be used, even if it would make a task easier. Using them also makes building the prototype and using it possible for a larger group of individuals and organizations. • A l l documentation and if possible, source code should be available online. It reduces the research and development time required when building a copy or developing a new system. Most existing solutions do not provide resources needed to replicate them, so building the same system requires investing a non-trivial amount of time. • The documentation and source code provided should be of reasonably high quality, even though it is a prototype. This goes together with the previous goal. The quality should be high enough that it does not reduce value of the resources. • The prototype should be simple and straightforward to use. That includes both the hardware, data acquisition and visualization. A hard to use system limits the number of people who can work with it, and it may require more time-consuming training. When the system is hard to use, it can lower usage frequency, as the time of setup and processing needed for a single task is so high that it is not profitable. 12 4 Hardware The hardware serves as the foundation upon which we build the rest of the prototype. Because of that, design decisions done here heavily influence the firmware and the software. We describe the process of choosing our sensor and discuss the design of hardware for our prototype in this chapter. 4.1 Sensor Because the sensor is the most critical hardware component, we must take great care when selecting one. The goals we set up for our prototype limit us to sensors that are aimed as components for consumer electronics, rather than scientific instrumentation. Most of these sensors are Hall effect sensors. With Hall effect sensors, we have two options on sensor construction. As a single sensor is only sensitive in a single axis, we have to use three sensors in orthogonal orientation to measure all vector components of the magnetic field. We can either use three separate sensors or use a 3D Hall effect sensor, which integrates the three sensors in a single chip. The first method can result in better sensor selection, but it requires complex calibration and careful mechanical construction to keep the separate sensors orthogonal. There is a rather large selection of 3D Hall effect sensors on the market. They are used as digital compasses or for detecting the orientation of magnets (e.g. in joysticks). The sensor we decided to use is Melexis MLX90393. We chose the sensor because of several reasons. • It is designed for reading magnet orientation in joysticks and similar devices. Thus it has a high dynamic range compared to Hall effect sensors used as digital compasses. • There several development kits for the sensor from multiple companies. We use the development kit from Melexis. • It is reasonably well documented and supported by the maker community, with several drivers for different frameworks available. • The technical parameters of the sensor are well suited for our purposes. It has selectable sensitivity and filtering. There is also a new sensor from Sera's AG1 , the SENM3Dx. It is their custom, in-house developed 3D Hall effect sensor which they use in their magnetic mappers. According to the datasheet, it has excellent parameters for 1. https://www.senis.ch/ 13 4- HARDWARE our prototype, and it would be better suited than MLX90393. As of the time of writing this thesis, it is not yet available, and there is no information on the price. Table 4.1: Selected MLX90393 specs [16]. Communication I2 C and SPI Sensitivity 0.15 - 9.68 }iT/LSB 2 Dynamic range 5 - 5 0 m T Maximum measurement frequency 717 Hz II Figure 4.1: The sensor development kit used. 2. Least Significant Digit 14 4- HARDWARE 4.2 Motion platform We need a motion platform to position the sensor in the scanned magnetic field. As our sensor can only measure at a single point, we need a 3D motion system to be able to position the sensor where we need to. Modern, hobby focused 3D printers are relatively cheap and have decent accuracy and precision, high enough that we can use them as our motion platform. A similar approach has already been used in work by Yapo and Huber et al. [15,14]. We decided not to use and modify existing 3D printer platform, but to design our own. We made this decision to gain in-depth knowledge of the mechanics and design of the platform. Our design shares a lot of common traits with a 3D printer platform, and it can be used as one. 3D printers such as HyperCube[17] and HyperCube Evolution[18] heavily influenced our design. The structural parts are constructed from standard extruded aluminium profiles, forming a rigid box. This box serves as the main structure onto which everything mounts. All motion happens on linear ball bearings riding on steel rails with a diameter of 8 mm. Horizontal(XY axes) motion is beltdriven via GT2 belts and two NEMA17 stepper motors. The mechanical arrangement of the horizontal motion is CoreXY and is discussed in detail later in section 4.2.1. Vertical(Z-axis) motion is driven via T8 leadscrews, powered by NEMA17 stepper motors. The size of the working area is approximately 235 x 270 x 270 mm. No limit switches are installed, only homing switches at one end of each axis. All parts that require custom fabrication(such as rail holders, motor mounts or motion carriages) are designed as 3D printable parts. The current version is shown in figure 4.2. It also describes the axes. In practical testing, our system achieved mechanical precision and accuracy of around 0.2mm The sensor is mounted on the XY axis (figure 4.3). It is centered, hanging under the carriage via a 3D printed mount and can cover the whole working area. The sample to be scanned is placed on a mounting plate attached to the Z-axis, built from Totem construction system3 . We use Totem because it is plastic and highly modular, which allows for quick and simple jigs. This arrangement, where the sample moves, might not be ideal, as it can slightly affect the measurement results. All source files for parts and documentation of the motion platform are available online4 with an open-source license. 3. https://totemmaker.net/ 4. https://gitlab.fi.muni.cz/xpecak/cube_mechanical 15 4- HARDWARE Figure 4.2: Cube motion platform. View from front-left. The X-axis is left and right, with positive direction to the right. The Y-axis is is back and forth, with positive to the back. The Z-axis is up and down, with positive down. Figure 4.3: Sensor mounted on carriage. 16 4- HARDWARE 4.2.1 CoreXY mechanics CoreXY is a mechanical arrangement for belt-driven 2D motion. It is a parallel manipulator system, meaning the motors are stationary [19]. The stationary motors have two advantages. We introduce smaller inertia into the system, which allows us to either increase movement speeds or have a lighter construction. With the motors static, we can easily characterize the external magnetic fields and account for them in measurement. There are also disadvantages to this arrangement. The belt paths are rather long, require good tensioning and might introduce accuracy errors because of stretching. The belts also cross over at one point, but that can be solved by having the belts on two planes. Figure 4.4: Diagram of CoreXY mechanics. Because each motor can move the carriage only diagonally, the equations of motion are not as trivial as some other designs and are as follows [20]. A X = - ( A A + AB) AY = ^ ( A A - A B ) A A = A X + A Y AB = A X - A Y 17 4- HARDWARE 4.3 Electronics We first evaluated the possibility of using 3D printer control electronics for controlling our motion platform and interfacing with the sensor. After testing with an older board based on 8bit microcontroller, we concluded that we would have to make modifications to both the board and the firmware. 3D printer control boards have a lot of features that we do not need, including some protections that would have to be disabled. The firmware running on those boards would require slight modifications. We would need to disable internal protections and add support for communication with our sensor. We decided to create our simple electronics, as we only need stepper drivers in addition to a microcontroller. To reduce development time, we used the FRDM-K64F development kit (figure 4.8) from N X P as the core. This kit is based on N X P MK64FN microcontroller, which uses an A R M Cortex-M4 core, providing more performance than required. We designed a custom board to interface the development kit with the stepper motors and sensors. It acts as a breakout board to simplify connecting the sensor, homing switches and stepper motors. It also includes few auxiliary, currently unused connections for debugging or expansion purposes. Figure 4.5 shows simple block diagram of the electronics. The full schematics and PCB design drawings are in the appendix. All source files and documentation are available online5 , under an open-source license. Shield Stepper K64F-FRDM SPI TMC429 Motion Controller Step/Dir GPIO GPIO (through shield) I2C (through shield) motors STSPIN820 ( )Driver ( ) STSPIN820 ( )Driver j ( ) STSPIN820 Driver ( ) STSPIN820 Driver ( ) STSPIN820 Driver ( ) STSPIN820 Driver ( ) MLX90393 Homing Sensor Switches Figure 4.5: Block schematic of electronics. 5. https://gitlab.fi.muni.cz/xpecak/cube_board 18 4- HARDWARE 4.3.1 Stepper motor control Compared to typical electric motors, steppers motors do not rotate in continuous motion when power is applied to their coils; instead, they lock into a position determined by the combination of powered coils. A change in the combination causes the motor to "step" to another position. To control the motors, we use stepper drivers, which take simple input signals and control the motor coils. Drivers are usually controlled with two signals, step and direction. Direction signal determines the direction of the motor. Every pulse of step signal advances the motor by one step in the determined direction. Most modern stepper drivers also support micro-stepping, which divides every full step into smaller steps, and have configurable drive current for the coils. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 / \ / \ 1 \ 1 \ 1 \ 1 \/ / 1/ / 11 3 steps in one direction X 3 steps in opposite direction Figure 4.6: Example of step and direction signals. Our board has STMicroelectronics STSPIN820 drivers to control the motors. This driver provides a micro-stepping resolution of up to 256 micro-steps per step. Maximum rated driving current is 1.5 A. The micro-stepping resolution is configured with three inputs, which can be either controlled by a microcontroller or manually with jumpers. The driving current is controllable via P W M 6 signal or a potentiometer. It has step and direction interface to control the motor motion. The board has four identical stepper driver blocks, two of which share the same input. Each block has a separate potentiometer for current control and jumpers for configuring micro-stepping resolution. The stepper motors are connected via a standard four-pin 2.54 mm header. 4.3.2 Control signal generation Although the stepper drivers already make controlling the motors easier, we still need to take care of calculating the required steps and generating 6. Pulse Width Modulation 19 4- HARDWARE suitable signals. The generated signals need to have appropriate frequencies so that we achieve desired movement speed. We also have to account for acceleration, which is done by changing the frequency with a suitable ramp profile. This is a nontrivial task to implement that can eat up a large amount of development time. For simplifying the generation of the required control signals for the drivers, the board includes Trinamic TMC429 motion controller. It can generate all the step and direction signals, including acceleration ramps for the stepper drivers, for three axes. Each axis has many separately configurable parameters, notably maximum speed, acceleration and the mode of motion. The controller has two main modes of motion: • Velocity mode - The stepper motor rotates at target speed, and the controller generates all the necessary acceleration ramps according to the configured parameters. • Position mode - The controller moves the stepper motor to the target position. The motion complies with the configured parameters. The base unit of the controller is a single step of the motor. All other units are derived from that. The units for the speed parameters are steps per second for velocity, and the position targets are in steps. The controller uses SPI to communicate with the main microcontroller. It has full control over the step and direction signals of the stepper drivers, but their remaining signals are either controlled manually or connected to the microcontroller. 4.3.3 Connectivity Apart from controlling the stepper motors, the board only acts as a breakout board for the FRDM-K64F kit. There are three connectivity groups on the board that interact with the hardware: • A four-pin, 2.54 mm header for connecting the sensor. We use I2 C protocol to communicate with the sensor. The connector has the required SDA and SCL data lines. Two pins are used for power. Because the sensor is quite far away from the board, we use a shielded cable with four conductors. The shielding is to reduce the interference from the stepper motors. • Three two-pin, 2.54 mm headers for connecting the homing switches. They are pulled high by default, expecting the switch to close them to 20 4- HARDWARE ground when closed. Both normally-open and normally-closed switches can be connected. • A n auxiliary eight-pin, 2.54 mm header for expansion. This header breaks out a few otherwise unused pins of the microcontroller. The primary purpose is debugging and expansion purposes. The communication with a computer is realized with a virtual serial port over USB. The onboard debugging probe can act as a serial to USB bridge. It is connected to one of the UART peripherals of the microcontroller. We use the virtual serial port provided by the probe for communication. 4.3.4 Power The electronics do not have any unordinary power requirements. Most of the requirements can be fulfilled by the power pins available on the development kit headers. The kit is powered from the debug USB connector and has onboard regulators for 3.3 V and 5 V power rails, which are present on the headers. The board uses the 3.3 V power rail from the headers for the sensor, motion controller and limit switches. The stepper motor drivers require 7 - 45 V operating voltage and substantial current for regular operation. Because of this, a dedicated power rail is used. It is powered from an external power source via a connector. The prototype does not currently have a permanent source for the power rail. It is powered from an external lab power supply instead, usually at 12 V. 4.3.5 Printed Circuit Board The board is designed as a shield for the FRDM-K64F kit. It plugs into the pin headers on the kit, sitting on top of the kit. In order to simplify the design process and time required, the board has four copper layers. Two internal layers act as the power planes. The signals are routed on the two outer layers. The only part of the board that requires a more careful design is the stepper driver layout. The drivers produce waste heat, which has to be removed during continuous operation. The board has exposed copper pads on the bottom for cooling purposes. Each pad is directly under a driver and is connected to the top layer with thermal vias. They can act as a heatsink on their own, or a bigger heatsink can be attached to the pad. 21 4- HARDWARE Figure 4.7: The asembled PCB. i S s r k i if I **J 1 I d > . ^ r l ö l t ö l T O » S S M . — t e n Lifts»*.:** ,-; sain o R ".-ä-S. 5?& i»äll[:•: i n f e r s H ? "tilts -v-^i Figure 4.8: K64F-FRDM development kit used. 22 5 Firmware We have two options for the firmware considering that we use custom electronics. We can either port over and modify existing suitable firmware or create our own. There are many open-source motion controller firmware options, usually designed for 3D printers and other small C N C machines. Some of them are Marlin1 , Smoothieivare2 or GRBL3 . They accept G-Code, which is a universal language for control of C N C machines. Implementing support for reading data from our sensor does not pose a problem, as most have a modular architecture that allows an easy extension. However, they are often tightly coupled to specific hardware. Porting it to our hardware would require extensive modifications to the firmware. We would also only use a minimal subset of the G-Code commands the controllers offer. Consequently, we decided to implement our custom firmware. It offers a small set of features that provide basic functionality for the prototype. We focused on modularity, extensibility and quality of the firmware rather than the number of features. Performance is a non-issue, as the firmware runs on powerful 32bit microcontroller. It is written in C++ with features from C++17 and it is available online4 under an open-source license. The firmware also includes drivers for both the MLX90393 sensor and the TMC429 motion controller chip. Both are written such that they are easily portable and do not depend on any manufacturer's SDK. With some slight modifications, we can release them as standalone open-source software. 5.1 Firmware architecture From an external point of view, the firmware acts controller that listens for commands on a serial port and executes them. This is the same as with the available motion controllers, but our firmware does not accept G-Code, but a custom instruction set. We describe the instruction set in section 5.4. Most of the instructions map one-to-one to basic G-Code commands, so a basic G-Code program can be theoretically translated to our format. 1. https://marlinfw.org/ 2. http: //smoothieware. org/ 3. https://github.com/grbl/grbl 4. https://gitlab.fi.muni.cz/xpecak/cube_fw 23 5- FIRMWARE The firmware has a highly modular architecture which uses classes for encapsulation of functionality. We can split the classes into four groups by function: drivers, core functionality, reactor and configuration. • Drivers provide communication with the hardware, namely the MLX90393 sensor, TMC429 motion controller and the serial ports. They are described in detail later in the chapter. • Core functionality is the common data structures, the command parsing and encoding return data, CoreXY motion planning. • Reactor acts as the instruction execution unit. It leverages the drivers and core functionality groups to execute incoming commands. • Configuration provides the configuration parameters for the three previous function groups. Firmware Reactor > > f f f Drivers Core > f f / \ Serial Sender ^ ) Serial Buffer \ J \ / Planner ^ J > f f / \ s TMC429 Driver J r MLX90393 Driver \ / Serial Encoder ^ J Serial Decoder > f f > f > f f> Cube Config f> f > f MCUXpresso SDK HAL Hardware Figure 5.1: Firmware architecture diagram. 24 5- FIRMWARE The diagram in figure 5.1 gives an overview of the architecture. The firmware relies on NXP's MCUXpresso SDK for interaction with the hardware, as it runs on an N X P microcontroller. Nevertheless, as the firmware is highly modular, porting, modifying and extending it is reasonably straightforward. Most of the reactor and core functionality can be easily tested on desktop architectures, as there is a high level of abstraction in the command handling. Internally, the firmware mostly uses a super-loop approach. The only exception is the command receiving and parsing, which is interrupt-driven and uses a state machine for parsing. The process of handling a new command is as follows. 1. The new command is received in an encoded packet in bytes. With every byte received on interrupt, the parsing class parses the new byte. When the command is fully received, it is placed into a ring buffer in the encoded representation. The buffering allows the firmware to store multiple new commands while executing a long instruction. 2. If the buffer with received commands is not empty, a single command is retrieved and decoded. The decoded command and optional data are forwarded to the reactor for execution. If the buffer is empty, a NOP (no operation) instruction is sent to the reactor. 3. The reactor executes the instruction. The execution is blocking, which means that the reactor can execute only a single instruction at once. Only the interrupt-driven command receive can happen simultaneously to the instruction execution. Each instruction execution is described in detail later in section 5.4. 4. The results of the instruction are encoded and sent back over the serial line. 5.2 Motion planner Although our machine is cartesian, we cannot directly use the cartesian coordinates. The motion platform uses steppers motors, whose rotary motion is mechanically translated to linear motion. Thus we need to translate the cartesian input coordinates into step coordinates for the motion controller. For the Z-axis, the calculation is rather simple, as the required cartesian position is multiplied by a constant that can be calculated from the leadscrew pitch, stepper and micro-stepping resolution. In the case of X and Y axes, the CoreXY mechanics also have to be taken into account. Apart from 25 5- FIRMWARE the constant calculated similarly as for Z-axis, we also need to follow the formulas noted in the previous section 4.2.2 to calculate the step coordinates. We implement this functionality in a motion planner in the firmware. Aside from the required calculations, it also supports relative coordinates and has protections for out of bounds coordinates. The planner works in relative coordinates at all times, but on startup and after homing the machine, the relative zero coordinate is the same as the absolute zero (origin). As we require both the step coordinates relative to previous position and also the absolute step coordinates to properly execute the movement, the planner does calculate both for each move. 5.3 Communication protocol The firmware and the software run on two different architectures. We need to have a common way to exchange commands and data between the two that adheres to a protocol so that no data is lost or misinterpreted during the transfer. The protocol has to have defined messages and their content (a schema). Furthermore, we need to know how to transform the message to and from binary data for transfer (serialization). For serialization of the data and defining the schema of the messages, we use Protocol Buffers5 (further only protobuf). Protobuf is a mechanism for data serialization by Google. The messages and their structure are defined in a schema file - example of such file is in figure 5.3. This file has to be translated into an implementation dependant source code. Protobuf itself does not provide an implementation of the serialization, only a compiler that compiles the schema file into an intermediate representation. There are various implementations for most programming languages that adhere to the mechanisms defined by protobuf. We use the Nanopb6 implementation in the firmware. It is written in C and designed for use in small targets, such as embedded devices. Our protocol has only two messages, command and return. The firmware always receives command and always sends return. Command always contains the required instruction that should be executed and optionally a position data if the execution requires it. Return has the acknowledged instruction, error status and optional position and measured data. Both position and measured data are also messages that are nested inside the main message types. The position has cartesian X Y Z co- 5. https://developers.google.com/protocol-buffers 6. https://jpa.kapsi.fi/nanopb/ 26 5- FIRMWARE ordinates in float, units being millimetres. The measured message has X Y Z components of the measured magnetic field vector. The units are uT. enum Commands { UNKNOWN = 0; STATUS = 1; M0VET0 = 2; MEASURE = 3; GET_REL_P0S GET_ABS_P0S SET_ZER0_P0S HOME = 7; } message Command_msg { required Commands o p t i o n a l P o s i t i o n } message Position_msg { required f l o a t x = 1 required f l o a t y = 2 required f l o a t z = 3 } Figure 5.2: Schema file of command message. = 4; = 5; = 6; command = 1; msg p o s i t i o n = 2; Figure 5.3: Communication protocol packet. Note the variable length and Magic number sequence in the header. 27 5- FIRMWARE The data serialized by protobuf does not include any headers, only the raw binary data. It still needs to be encapsulated in a packet for a transfer. We use a simple packet with a header and the data itself. The header includes a magic number to identify the start of the packet and data size. Because only one type of message gets send each way, we do not need any indication of message type in the header. The format of the packet can be seen in detail in figure 5.3. 5.4 Instruction set The firmware currently has rather small instruction set with only ten instructions. They provide only the basic required functionality and lack support for non-required, utility functions such as on-the-fly configuration of sensor sensitivity or changing motion controller parameters. status This instruction is meant to report the current status of the hardware and any fault states of the firmware, such as faults from stepper drivers or invalid motion planning positions. In the current implementation, it only reports faults in TMC429 and MLX90393 driver configuration. moveTo Moves the carriage to specified position. It requires additional target position data for execution. The target position is assumed to be relative to the current relative zero position. First, the motion planner calculates the required position in steps for the motion controller. Appropriate velocity parameters are then calculated and uploaded to the motion controller. The parameters have to be adjusted so that the motion is a straight move from one point to other. This calculation is currently only done with maximum velocity in mind and does not account for acceleration, so the final motion is not a perfect straight move. After the setup for motion is done, the motors turn on. The motion controller then moves to the new target position. When the motion controller reaches the target position, the motors are turned off. A success return message follows if the move did not fail. When an error occurs during the execution, the firmware returns an error message. measure Measures the magnetic field at the current position with the sensor. The motors are turned off during the measurement to reduce their influence. If the measurement is successful, the firmware responds with a return message containing the current relative position and the measured data. In 28 5- FIRMWARE case an error occurs, the return message contains the error status and does not include the additional data. getRelativePosition, GetAbsolutePosition Reports back the current relative or absolute position of the motion planner. setZeroPosition Sets the current absolute position as the new relative zero position for the motion planner. home Executing this instruction carries out the homing procedure, which is used to reset the position of the carriages to a defined origin. First, the planner relative zero is set to the current position. The motors are then turned on. Then the carriage is moved to position {10,10,10}, so that all the homing switches are inactive. Following that, the motion controller switches to constant velocity mode and the axes are homed in the following order: Y-axis, X-axis, Z-axis. The hardware design dictates this order. Each axis slowly moves in the direction of the homing switch, until the switch closes, then the axis is stopped. After all three axes finish homing, the positions of the motion planner and motion controller chip are reset to zero and the motion controller switches back to position mode. Lastly, the motors are turned off. A n error message is sent back when any error occurs during the instruction execution. nop No Operation instruction, does nothing. It is included because of simplicity and for completeness of the set. unknown Used when the parsed command has an instruction that is not in the instruction set or the parsing was not successful. The firmware responds with an error message. raiseDecodeError This instruction indicates that the decoding of the command failed. Execution of this instruction returns an error message. The protocol schema does not include all the instructions. Instructions nop and raiseDecodeError are internal only, as they would serve no purpose when invoked by an external command. 29 5- FIRMWARE 5.5 Drivers Two larger drivers had to be written for the firmware so that it could run on our electronics: TMC429 motion controller driver and MLX90393 sensor driver. The drivers act as an abstraction layer for interaction with the sensor and motion controller. They facilitate communication by providing a simple interface for the user. Drivers for the serial port were also written, but these are simple and do not require any detailed description. The TMC429 driver supports almost all features of the chip. Currently, only the limit switch capabilities of the controller are not supported. Otherwise, the driver supports both velocity and position mode, independent control of all three axes and configuration of all motion parameters. Furthermore, it enforces proper usage of the controller, disallowing the user from causing unexpected controller behaviour. The driver can be easily ported to a new platform, as it only requires rewriting a single function that provides the SPI transfer capabilities. Because the controller has a large number of configurable parameters, the configuration is done via a struct that holds all the required parameters, rather than having individual parameters. The MLX90393 driver only supports the single measurement mode of the sensor. A l l parameters that affect measurement can be configured at the startup of the driver and between measurements. A configuration struct holds all the parameters for easier handling. Because many parameters affect the conversion constants and even the conversion algorithm itself, the driver also provides functionality for data conversion. The user of the driver does not have to remember the current setting of the sensor to convert the data properly, the driver does it for him. As with the TMC429 driver, this driver only requires rewriting an I2C transfer function when porting it to a new platform. 30 6 Software We developed a suite of applications for controlling the hardware, automating data acquisition and visualizing the collected data. We also created a simple library to facilitate communication with the hardware. The applications are written with Unix philosophy in mind - rather than writing a single monolithic application, we developed multiple small tools. Each tool is easy to maintain, extend, and they are designed such that outputs of one tool can be used as an input for another one where possible. We chose Python (version 3.5 or higher) as the primary language for the software, mainly for easy portability of the software between different operating systems and for the extensive library of available packages. Just like the firmware, the software is available online1 and has an open-source license. 6.1 cube_comm. py library Communication with the hardware requires handling serial ports and implementing the communication protocol. That also includes serialization and deserialization. To simplify the interaction with hardware, we developed a simple python library. It provides an abstraction layer above the hardware and handles all the communication details. The library provides a Python class that represents the hardware. The only configuration required before interacting with the hardware is specifying the path to the serial port of the connected hardware. Internally, the library uses the pySerial2 module for handling the serial port. It also handles all the required serialization operations, using the Python implementation of Protocol Buffers. The class has public methods that map one-to-one to the commands specified by the communication protocol. All the methods are blocking, waiting for the return message from the hardware. We could add support for asynchronous operations, but it was not necessary at this stage of the prototype. Further documentation is available in the source code. 6.2 Interactive console A simple terminal application was developed to allow for manual control of the hardware. It works as a console into which the user can input the com- 1. https://gitlab.fi.muni.cz/xpecak/cube_sw 2. https://pythonhosted.org/pyserial/ 31 6. SOFTWARE mands that are executed by the hardware. The console application's main file is cube_console .py in the source files. It uses the cube_comm. py library to communicate with the hardware and currently supports all the commands provided by the library. The application has internal help command, which can print all available commands and also usage manual for each. Received data from the firmware are parsed by the app and printed in a human-readable format. The application supports redirected input and output. Running simple procedures can be done by writing the commands in a text file and piping the file to the standard input for the console application. This can be used for interaction with the hardware in languages other than Python. However, using it for this purpose has an impact on performance, as it requires running a separate Python interpreter in a shell. A Jbuntj X + v - • X ryzek@host-pc:~/Cube_SWj python3 cube..console.py /dev/ttySI Cube Control Console type 'help' or '?' -for help. » move 110 50 23 moved successfully » measure Relative XYZ:C110.0, 50.0, 23.0) Measured XYZ:(103.20000457763672 -39 0r 16U.802001953125) » status status OK » 1 Figure 6.1: Interactive console application running on Windows Subsystemfor Linux. 6.3 Measurement tool We created a simple terminal application for simplifying the data acquisition process and making it repeatable and configurable. It loads the configuration data and guides the user through the process, requiring confirmation before any step that can cause dangerous behaviour of the hardware. The application currently only supports scanning a volume defined by a uniform grid of scan points. During the measurement itself, the application displays a status bar with status messages, the most recent measured values, current position and a progress bar with time elapsed and estimated time left. They can be switched off and replaced by more verbose output with an argument 32 6. SOFTWARE during launch. The current output is not suitable for automated processing. Corresponding file in the source is the measure_tool .py file. 6.3.1 Configuration The tool currently supports the following parameters to be configured: • The name or description of the measurement. It can be used for notes or details of the measurement. • The output file to save the measured data to. • Whether to do a calibration scan before the actual measurement. It can help remove the offset of the natural background for weak magnetic fields. The calibration data can be subtracted from the measured data, as the magnetic field is additive. In some cases, the calibration is not required, as the measured field is strong enough that the background strength is insignificant compared to the measured field. • Start position of the measurement grid. The expected unit is millimetres. It is a cartesian position relative to the current relative zero coordinate of the hardware. • The size of the measurement grid. It is specified as the number of points per each axis of the grid. • The spacing between the points. The unit is in millimetres. It is also independent for each axis. Because the amount of the configurable parameters is rather large, the application loads the configuration from a JSON file. Having all the parameters as arguments when launching the app would be cumbersome. Example of the configuration file is shown in figure 6.2. { "name": "bar_magnet", "output": "bar_magnet_detail.csv", " c a l i b r a t i o n " : t r u e , " s t a r t " : [107.5 , 130 , 7] , "steps " : [21 , 11, 11] , " s t e p _ s i z e " : [1, 1, 1] } Figure 6.2: Example configuration file. 33 6. SOFTWARE 6.3.2 Measurement procedure Before the measurement, the app asks the user to confirm the loaded parameters. After confirmation, the procedure itself starts. If the calibration is required, it is the first operation done. The user is asked to remove all magnetic field sources from the scan area and confirm. Calibration data is measured for each point in the XY-plane at the starting Z coordinate. The scan is done only in XY-plane, as moving the mechanical Z-axis the hardware does not affect the measured values, according to our testing. After the optional calibration, confirmation is again required from the user. The application asks the user to return all the magnetic sources. The defined measurement grid is then scanned. At each point, the calibration data is subtracted from the measured data, if it is available. For both the calibration and measurement, the grid is scanned axis by axis, starting with the X-axis. The carriage first goes through all the points on the X-axis, then advances one step on the Y-axis, goes back to the first point on the X-axis and repeats. When the end of the XY-plane is reached, the carriage returns to the first point in the XY-plane and moves one step on the Z-axis. It is not the fastest scanning pattern, as we waste some time on returning to the starting point after scanning each line. Figure 6.3 shows the scanning path. 6.3.3 Data output We save the acquired data to a plain text C S V 3 file. There is a simple header at the start of the file with metadata about the measurement. It is currently merely the output of str function applied to the Python dictionary holding the measurement configuration. Besides the configuration data, a timestamp is also added to the dictionary before the measurement. The actual data are after the header. The first three columns are the cartesian (XYZ) coordinates (units being millimetres) followed by three vector components (again the order XYZ) in fiT. Each line is a single measurement taken. Example of the output file is in the figure 6.4 3. Comma-Separated Values 34 6. SOFTWARE Figure 6.3: The scanning path used by the measurement tool. Grey points are the measurement points. METADATA: {'name': ' coil_500mA ' , 'output': 'data/coil_500mA' , ' c a l i b r a t i o n ' : True, ' s t a r t ' : [117, 136.5, 6 ] , 'steps': [21, 21, 2 1 ] , ' s t e p _ s i z e ' : [1, 1, 1 ] , 'datetime': ' 2020-05-02_17 -08 '} 117.0: 118.0: 119.0: 120.0: 121.0, 122.0, 123.0, 124.0 . 125.0, 126.0, 127.0, 128.0, 129.0 , 130.0, 131.0, 132.0 , 136.5, 136.5, 136.5, 136.5, 136.5, 136.5, 136.5, 136.5, 136.5, 136.5, 136.5, 136.5, 136.5, 136.5, 136.5, 136.5, 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , o, o, o, o, o, o, I. 9500, 5.8499, 7.6500, I I . 8499 , 17.1000 , 19.2000 , 21.3000 , 20.5500 , 15.1500 , 4.2000, -15.0000, -37.3500, -56.7000, -68.8500, -69.7500, -63.9000. •4.9500 •4.8082 •5 . 1089 -5.4090, -6.0069, -5.8075, -5.5500, -5.7000, -5.8499, •4.6500, -4.1999, -3.7500, -2.4000 , . 0500 , -0.6000, -0 . 7500, -1. -6.7759 -7.2599 -7.7439 -9.9219 -15.0040 -21.0539 -32.1860 -44.5280 -60.7420 -75.7459 , -85.9100 -86.3940 -76.9560 -57.1120 -36.0580 -15.7300 Figure 6.4: Output file format example. 35 6. SOFTWARE 6.4 Visualization Writing our visualization software from the ground up would require a significant time investment and gaining extensive knowledge of graphics, mathematics and data processing. It also goes against our goal of using existing tools where possible. As we use Python, the first possibility is using matplotlib, which is commonly used data visualization library. Its 3D capabilities are rather limited and it is not designed for fully interactive visualization. We need to select a different toolkit, designed for 3D data. The most common visualization toolkit for 3D data is VTK (Visualization Toolkit)41 by Kitware. It is an extensive toolkit for processing and visualizing 3D data, written in C++. The toolkit is widely used in various industries, ranging from scientific and medical to computational fluid dynamics visualizations. Many visualization applications are built on top of VTK, such as Paraview5 . The main advantage of the toolkit are interactive capabilities, as it does not generate a static visualization, but uses OpenGL for displaying the result. Bindings for other languages other than the native C++ exist, notably Python bindings. As there are not many other toolkits for visualization, we chose to use V T K in the prototype. We can either use the bindings directly or use one of the available Python libraries that act as an abstraction layer above the Python bindings. Notable ones are PyVista6 , vtkplotter7 and Mayavi8 . We decided to use Mayavi. It has extensive documentation and is designed as an already standalone application for visualization with Python scripting capabilities. The Python interface is very similar to Matlab's graphing interface and is easy to use. As it is a standalone application, we do not need to implement our own visualization manipulation and setup GUI. From the noted tools, it is the most straightforward one to use for the user and setting up the visualization is rather quick. 4. https://vtk.org/ 5. https://www.paraview.org/ 6. https://www.pyvista.org/ 7. https://github.com/marcomusy/vtkplotter 8. https://docs.enthought.com/mayavi/mayavi/ 36 6. SOFTWARE Mayavi Scene 1 • X a y e ! Mayavi Scene 1 E3 VectorField v ^ Extra ctVectorNorm •"* ^ Colors and leg. Streamline v ^ Colors-and legends •t Vectors |HJdd... f»V Outline ScalarField ^ Add module orfil,. StalarField ~Q Add module orfil.. ScalarField ~Q> Add module orfil.. Glyph Actor Masking Glyph Glyph Source Color mode: color_by_yettor v Clamping: 0 Fill cell data: • Generate pointids: [~J •rient: 0 Scaling: 0 Cos1 node: :o oi _bv_ Indes mode: off Vector mode: use Output points precision; Pointids r Scale factoi [inputPointlda FO: |u.u Fl: 95.Ö1S3SS51674305 Figure 6.5: Mayavi user interface. Main visualization window(top) and configuration window (bottom). 37 6. SOFTWARE 6.4.1 Vector field visualization methods Visualizing vector fields is not a simple task, as they contain a large amount of information. Mayavi provides most of the modules that are included in VTK for visualizing vector data. We give a brief overview and examples of available methods that can be used in Mayavi. Quiver plot The easiest method for visualization. Each vector in the field is drawn as a discrete arrow with the according direction and size. This works best for sparse data so that the vectors are not drawn too close together. Using a quiver plot with densely populated grids results in chaotic visualization that is hard to understand. To remedy this, we can only show 2D planes of the vectors or draw every n-th vector, thus reducing the number of drawn arrows. Figure 6.6: Quiver plot on sparse grid with arrows sized according to total vector magnitude. 38 6. SOFTWARE Streamlines This method is perhaps the most visually attractive. Streamlines are paths that follow the vector field - the path is tangent to the vector field at all its points. In static magnetic fields, streamlines are identical to the field lines. However, they are the hardest method for setup and computation, as the field has to be integrated and the common integrators have a rather large amount of parameters. We also have to supply the source points for the streamlines, although there are methods for generating the source automatically. The integrators used also have limitations specifically concerning the magnetic fields. Those are discussed later in the chapter. Figure 6.7: Streamlines in a vector field above two coils carrying current. 39 6. SOFTWARE Isosurfaces They are a method that is on the boundary between vector and scalar visualization methods. Iso surface is a continuous surface whose normal vectors are the vector field, and all points of the surface have the same magnitude. As there is an infinite amount of these in any given 3D vector field, we have to select which ones are shown. We can use this method to show boundaries of regions of selected strength of the magnetic field. It is also useful for displaying complex fields, as it can easily show complex shapes. Figure 6.8: Isosurfaces above a coil carrying a current. 40 6. SOFTWARE Scalar visualization We can also visualize either the components of the vector or only the field magnitude with methods for scalar data visualization. Those methods include volumetric clouds and 2D slices. The obvious limitation is that we are limiting the amount of visualized data to only a single value. Figure 6.9: A 2D slice in the XY and Y Z plane of magnetic field strength above permanent magnet. Each method has its limitations. Thus they are often combined when visualizing complex fields to give a better insight. We can also use various filtering methods to improve the visualization, such as thresholding or averaging. 41 6. SOFTWARE 6.4.2 Launcher script We need to load the data saved in the CSV file into a format suitable for the Mayavi toolkit. To facilitate this process, we wrote a simple terminal application to launch the visualization. Apart from data loading, it also has launch arguments for quickly adding various modules to the visualization to speed up the setup. It can add quiver plots, streamlines, isosurfaces and various slices. The visualization parameters still have to be tweaked manually. Setting up the parameters cannot be automated because each dataset is unique and requires a different set of visualization methods and parameters. The script file is named vis_launch. py in the source files. 6.4.3 Limitations In general, noise is a limiting factor in the visualization. Some of the visualization methods are more susceptible to noise, with streamlines and isosurfaces being the most affected. Both methods produce unusable, randomlooking visualizations when the source data is noisy. The Mayavi, and subsequently V T K have one significant limitation specific for magnetic fields. The visualization algorithms use linear interpolation heavily during most visualization methods. This works fine for general vector fields, but magnetic fields cannot be interpolated linearly. As the field is defined with Maxwell's equations, the interpolation also has to follow them. This has also been noted by Yapo [15]. The most prominent artifact of using linear interpolation is that field lines produce structures that look like magnetic monopoles, which do not exist. A minor issue is also the fact that streamlines do not show their direction. Recently, a paper by Ramon [21] has been published. A Maxwellian interpolation method is described. The paper also presents an algorithm which is suited for interpolating magnetic field data in regular grids using this method. Implementing this interpolation method in V T K requires a significant amount of time and it is out of the scope for our prototype. 42 7 Examples We chose a set of five examples that show both capabilities of the hardware and the visualization. A table accompanies each example with crucial details of the example, such as scanned object size and scan details. A photo of the scanned object is also provided for each example. As the visualization is interactive, it is hard to show the capabilities with static pictures fully. Each example thus contains the name of the data file and the launch parameters. We provide a tutorial on how to launch the visualization in the appendix. All examples require further manual tweaking after launch with the defined flags to achieve the shown visualizations. The chosen examples are: • A simple coil. This was the first test object we used. We chose it because of the predictable field which is created around a coil. • Double coil setup with opossing windings. These coils were used to visualize the interaction between two magnetic field sources. • Solenoid to try approximating the field around a bar magnet. It has a rectangular shape, rather than circular. • A n ordinary permanent magnet. This example showcases the capability of the prototype to measure and visualize rather complex fields. The magnet is internally composed of smaller magnets joined together, and we can easily see it in the visualization. • A wire. We used this example to showcase the capability to measure very low strength magnetic fields. 43 y. EXAMPLES y. EXAMPLES Double coil Coil size 14 x 4 mm, 8 turns Coil current 100 m A Scan Resolution 1 mm Scan size 10 x 10 x 10 mm File double.csv Launch flags -s zz -s yy -s y 45 y. EXAMPLES Solenoid Coil size 6 x 6 x 15 mm Coil current 500 m A Scan Resolution 2 mm Scan size 50 x 50 x 20 mm File solenoid.csv Launch flags -s zs -s ys -f 46 y. EXAMPLES 47 y. EXAMPLES 48 8 Conclusion We presented a prototype for measurement and visualization of magnetic fields. Although the prototype is in an early stage of development, it is already highly usable for practical measurement. The measured data is already usable, but cannot be currently used for precise scientific measurement, as the used sensor is not calibrated against any known reference. The prototype fullfills all the requirements noted in the Goals chapter. It uses existing toolkits where possible. A l l components used in hardware are readily available from common suppliers. The source code and documentation are all available online under open-source licenses. The prototype is also easy to use, and the process of measuring and visualizing the data is straightforward. Overall, the prototype shows great promise. We will continue developing it further. 8.1 Future work There are two main directions of future development for the prototype as a whole: • Continue developing the system as a tool strictly for magnetic field scanning and visualization. This is a fairly obvious choice, where we can optimize and modify the system only for a single goal. There is a potential spot in the open-source scientific instrumentation field, which our prototype can fill in. • Create a universal platform for scanning any data in 3D space. During the development, we noticed that we could use all the developed tools to measure and visualize any scalar or vector physical quantity. Keeping such a universal system easy and quick to use is difficult. Developing it also is more complicated than a single-purpose system. We did not yet decide on which direction the system will take. For now, we can continue developing the individual parts, as almost all parts of the prototype can be improved upon. We should also present the prototype online, to reach wider audience and gather valuable information about the potentional interest. The motion platform is currently the most finished part of the prototype. Nevertheless, it can be improved to be easier to assemble. Furthermore, we can also make improvements to the precision and accuracy of the motion 49 8. CONCLUSION system. In later revisions, We can redesign the motion platform such that it can be enclosed with acrylic or similar panels. The mounting of the sensor should be improved, as we currently use the MLX90393 development kit, which is large compared to the size of the sensor. It limits how close we can get the probe to a surface. The electronics and the firmware can be further developed into a universal motion platform controller. Adding support for other motion mechanics than CoreXY is trivial. The biggest current issue of the electronics is the dependency on the FRDM-K64F development kit. A new revision should be a single board with the microcontroller integrated. In following revisions, the electronics together with the firmware can serve as an alternative motion controller for use cases, where using G-Code controllers would be overkill. The software components have the most substantial potential for further development. Currently, the most significant drawback is the lack of graphical user interface for the control applications, as many users are unfamiliar with using terminal applications. The visualization software has the limitations of using linear interpolation, but that requires either modification or writing our custom visualization toolkit, which is an arduous task. First few revisions should focus on adding a graphical interface and streamlining the measurement and visualization process further. 50 Bibliography 1. MICHAELFREY. Magnetic field viewing film [online]. 2019 [visited on 2020-04-19]. Available from: https: //commons. wikimedia. org/wiki/ File:Magnetic_field_viewing_film_on_rectangular_Refrigerator_ magnet.jpg. 2. BLACK, Newton Henry. The magneticfield of a bar magnet revealed by iron filings on paper, [online]. 1913 [visited on 2020-04-19]. Available from: https://commons.wikimedia.org/wiki/File:Magnet0873.png. 3. DWIVEDI, Suyash. Compass big [online]. 2011 [visited on 2020-04-19]. Available from: https : / / commons . wikimedia . org / wiki / F i l e : Compass_big.jpg. 4. SCHULTZ, Mitchel E.; GROB, Bernard. Grob's Basic Electronics. 11th ed. New York, N Y : McGraw-Hill, 2011. ISBN 978-0-07-351085-9. 5. ROTHWELL, Edward J.; C L O U D , Michael J. Electromagnetics. Boca Raton, Fla: CRC Press, 2001. Electrical engineering textbook series. ISBN 978-0-8493-1397-4. 6. PURCELL, Edward M . ; MORIN, David J. Electricity and Magnetism. 3rd ed. Cambridge: Cambridge University Press, 2013. ISBN 978-1-107-01402- 2. 7. COEY, J. M . D. Magnetism and Magnetic Materials. 1st ed. Cambridge: Cambridge University Press, 2010. ISBN 978-0-521-81614-4. 8. GEEK3. VectorFieldPlot [online]. 2010 [visited on 2020-04-19]. Available from: https://commons.wikimedia.org/wiki/User:Geek3/VectorFieldPlot. 9. INTERNATIONAL BUREAU OF WEIGHTS A N D MEASURES. The International System of Units (SI). 2019. 10. WEBSTER, John G. The Measurement, Instrumentation and Sensors Handbook. 1st ed. Boca Raton, Fla: CRC Press, 1998. ISBN 978-0-8493-8347-2. 11. TUMANSKI, S.; LISZKA, A . The methods and devices for scanning of magnetic fields. Journal of Magnetism and Magnetic Materials. 2002, vol. 242-245, pp. 1253-1256. ISSN 0304-8853. Available from DOI: 10 . 1016/S0304-8853(01)01023-X. 51 BIBLIOGRAPHY 12. BERGSMA, E ; B L A N C , P. H.; GARNIER, E ; GIUDICI, P. A. A High Precision 3D Magnetic Field Scanner for Small to Medium Size Magnets. IEEE Transactions on Applied Superconductivity. 2016, vol. 26, no. 4, pp. 1-4. ISSN 1051-8223, 1558-2515. ISSN 1051-8223,1558-2515. Available from DOI: 10.1109/TASC. 2016.2520204. 13. M I K O L A N D A , T; KOSEK, M ; RICHTER, A . 3D Magnetic Field Measurement, Visualisation and Modelling. In: MEASUREMENT 2009, Proceedings of the 7th International Conference. Smolenice, Slovakia, 2009, p. 4. 14. HUBER, C. et al. 3D print of polymer bonded rare-earth magnets, and 3D magnetic field scanning with an end-user 3D printer. Applied Physics Tetters. 2016, vol. 109, no. 162401. ISSN 0003-6951,1077-3118. ISSN 0003- 6951,1077-3118. Available from DOI: 10.1063/1.4964856. 15. YAPO, Ted. 3 D Magnetic Field Scanner [online] [visited on 2020-03-31]. Available from: https: //hackaday. io/project/11865-3d-magneticfield-scanner. Library Catalog: hackaday.io. 16. MELEXIS. MLX90363 Magnetometer IC Datasheet. 2016, pp. 62. 17. TECH2C. HyperCube 3D Printer/CNC [online] [visited on 2020-05-12]. Available from: https : / /www . thingiverse . com /thing : 1752766. Library Catalog: www.thingiverse.com. 18. SCOTT_3D. HyperCube Evolution [online] [visited on 2020-05-12]. Available from: https : //www. thingiverse . com/thing: 2254103. Library Catalog: www.thingiverse.com. 19. CoreXY- RepRap [online] [visited on 2020-05-12]. Available from: https: //reprap.org/wiki/CoreXY. 20. CoreXY Cartesian Motion Platform [online] [visited on 2020-05-12]. Available from: https: //corexy. com/theory. html. 21. R A M O N , Jose Luis Rodrigo. Maxwellian Interpolation of Magnetic Fields on a Grid. 2018, pp. 70. 52 A Attached files We attach the following files: • Snapshot of Cube_Mechanical repository, which contains the parts and documentation for the motion platform • Snapshot of Cube_Board repository, which contains the K i C A D project for the developed K64F-FRDM shield board • Snapshot of Cube_FW repository, which contains the source files of the firmware • Snapshot of Cube_SW repository, which contains the source files of the tools we developed • Original measured data files of the provided examples 53 B Visualization launch guide Python version 3.5 or higher is required, 64bit version. 1. Install packages numpy, VTK, PyQT5, Mayavi with pip: $ p i p i n s t a l l numpy VTK PyQT5 Mayavi 2. Extract the file vis_launch. py or the whole Cube_SW repo to a folder. 3. Extract the attached data files to a folder. 4. Use the launch script to run the visualization of desired file: $ python vis_launch.py PATH_T0_DATAFILE LAUNCH_FLAGS for example: $ python vis_launch.py solenoid.csv -s zs -s ys - f 5. Tweak the visualization parameters as required. Settings can be accessed by the top left button in the main Mayavi screen. 54 C PCB Schematic and Drawing We attach the following schematics and PCB drawings: • Main schematic • Schematic of one stepper driver block, the other 3 are identical appart from part identifiers • PCB Drawing of the outer signal layers - red is top, green is bottom • PCB Drawing of the inner power layer - only one is shown, as ground layer is a full layer copper pour Full source materials are available in the attached flies. 55 J5 K64FJ2 _LI2C_SCL _3_I2C_SDA 5 7 9 SPLSCK 11 SPLMISC 13_SPLM0SI 15 SPI CS 17 SDOZ C 19 X stepper I2C_5DA 1 I—I I2CLSCL 2 +3V3 J3 K64F_1 Z2_FAULT 2 Zl_FAULT_ft_ X_FAULT 6 Y FAULT 8 10 12 Y ENABLE ljj X ENABLE 16 f K64F_ z li 4 6 e 10 12 II 1 < ( 16 I CLK 20 3 X LIMIT 5 7 Z1_ENABLE 9 II Z2_ENABLE 13 Y_LIMIT 15 ZJJMIT GND +3V3 J10 Sensor +3V3 fee U l TMC429-LI P _LC 3 Í00nTÍ70n GND CLK_20 SPLSCK SPLMOSI. SPLCS 7 SPLMISO. SDOZ_C. 12 12 14 V5 V5 V33 n.c. CLK SCK_C SDLC nSCS_C SDOZ_C nlNT_SDO_ TEST POSCMP GND \7 GND Jl +3V3 AUX t J6 _1. J K64F_ ? PTB2 2 1 3 5 7 9 11 PTB3 1 3 5 7 9 11 PTB10 6 1 3 5 7 9 11 5 PTB11 8 1 3 5 7 9 11 6 PTC11 10 1 3 5 7 9 117 PTC10 12 1 3 5 7 9 11 8 1 3 5 7 9 11 8 ZJJMIT REF1 REFR1 REF2 REFR2 REF3 REFR3 SD0_S_S1 SCK_S_D1 nSCS_S_S2 SD0_S_D2 nSCS2_S3 nSCS3_D3 GND GND GND GND(Pad) 31 2 •<7 GND X_FAULT_ X_ENABLE_ MOT_RST_ +24V >V_MOT >STEP >DIR >FAULT >ENABLE >RESET stepper_driver.sch qtepppr VDD<- 3V3 J Y.FAULT Y.ENABLE. MOT.RST X7 GND >V_MQT VI >STEP >DIR >FAULT >ENABLE >RESET 24y stepper_dnver.scri 71 stepper +3V3 Z1_FAULT_ Z1_ENABLE_ MOT_RST_ +24V >V_MOT VI >STEP >DIR >FAULT >ENABLE >RESET stepper_dnver.sch 77 stppppr + 3V3 Z2_FAULT_ Z2_ENABLE_ MOT_RST_ >V_MOT >STEP >DIR > FAULT >ENABLE >RESET stepper_driver.scri Oldřich Pecák Fl MUNI Sheet: / File: Cube_Board.sch Title: Cube Control Board Size: A4 Date: 2 0 1 9 - 1 2 - 0 5 Rev: 1 KiCad E.D.A. 4 kicad (5.1.2)-2 Id: 1/5 X U2 5TSPIN820 RVI [ R_POT_Smalll Rfi-10 GND V D D D - f - o o « 7 22 o J P 2 23 JP3 1 9 20 úR5 itK7 REF TOFF DECAY M0DE1 M0DE2 M0DE3 STCK DIR STBY/RESET EN/FAULT GND GND GND(Pad) \7 GND VS vs 0UTA1 0UTA2 0UTB2 OUTB1 SNSA SENSEA1 SENSEA2 SENSEB2 SENSEB1 SNSB T7I. C6 V00 "J CI lOOu J l l Motor Oldřich Pecák Fl MUNI Sheet: /X_stepper/ File: stepper_driver.sch Title: Cube Control Board - Stepper driver Size: A4 | Date: 2 0 1 9 - 1 2 - 0 5 Rev: 2 KiCad E.D.A. kicad ( 5 . 1 . 2 ) - 2 Id: 2 / 5 a T/T : PI Z-(Z'T'g) P"!>l 'Va'3 PB3!> T'T : A 3 y 0 T - S 0 - 0 Z 0 3 :a»BQ | w -az'S p j e o g a q r Q qDd~pBDi>|-pjeog aqn3 :a)ij NI1N Id )|eD3d i p u p i o 9 I S 1 - 7 I £ I Z I T ®®®®®®®K ®®®®®® ®®®®©®Cd® ®®®®®B ®®®®®®®a ® ® ® % a a a f a •••••••®®® ®K ® ® ® ® ® ® ® | S ) ®®®®®®®®®a ®K ®K ®K ®« ®« ®« Oldřich Pecák Fl MUNI Sheet: File: Cube_Board.kicad_pcb Title: Cube Control Board Size: Date: 2 0 2 0 - 0 5 - 1 0 Rev: 1. KiCad E.D.A. kicad (5.1.2)-2 *> l ~ Id: 1/1