Magnetic field measurements using mobile phones: programming and experiments

This article explores the magnetic field sensor embedded in mobile phones, and presents some ways to use it together with straightforward software applications. Measurements are processed with features such as averages, georeferencing coordinates, data exporting, visualization, etc, by means of an open-source tool. Covering the hardware part, the sensor magnitude calibration and also its frequency response are discussed. All materials and elements are affordable and easily available. Results show the high potential of its use in class and also for research applications.


Introduction
Traditionally, teaching of physics and engineering suffers from expensive and sometimes hard to maintain laboratory instrumentation.Some students resent the strong emphasis on theory, missing the practical, handson experience.Fortunately, the overall availability of smart phones has made their use possible for several types of measurements.Magnetic fields, sound pressure, acceleration, orientation, Geo-positioning; all of these are currently available in most mobile phones (MP).In addition to that, there is a strong push towards the development of MP software applications, with free courses, tutorials and tools that focus on easy and quick designs.Therefore, this combination of software and hardware entails a promising tool to motivate students for hands-on activities, which can be carried on using their own equipment and run independently of expensive laboratory instruments and costly software development suites.
Previous works have shown the teaching benefits entailed by mobile phones, in both Physics and Engineering.For instance, sensor applications for helping blind students are analyzed and discussed [1], increasing their inclusion rate into the society.An approach called BYOD (Bring Your Own Devices) is presented, and the variability of results using different MPs is shown, for quantities such as acceleration, sound pressure and light intensity, with overall good results for the sampled highschool students [2].The BOYD system had experimental physics concepts covered and applied throughout a set of practical evaluations, using individual phones, of different models.A comprehensive coverage of some MP sensors used in Physics courses is presented [3], based on free Android applications, downloaded from the appropriate channels.
Addressing the particular question of confidence and reliability of MP magnetic field measurements, a study was performed to acquire the three orthogonal components, later compared with analytical solutions for the cases of a straight wire and a loop, both carrying a steady current.The results approved their use for undergradlevel magnetostatic experiments [4].The type of sensors used in mobile phones varies, from the most-common Hall effect to GMR (giant magnetoresistance), with some cases of MJT (magnetic-tuneling junction) and AMR (anisotropic magnetoresistance) [5].Micro-variations of the Earth magnetic field amplitude were also used to provide a means for indoor localization, running a particle filter approach deployed in an Android tablet [6].A similar purpose indoor localization application was tested using Android MPs and the k-nearest neighbor algorithm [7], showing the potential combination of software and hardware offered by a single phone.In the information security area, MP magnetometers were sensitive enough to provide a covert wireless channel so that data was eavesdropped from a computer to a phone [8].Another mean to extract unauthorized information involved a Near-Field Communication protocol using the magnetic fields emitted by the computer processor, modulated by software loops, and picked up at distance by a MP magnetometer [9].
Besides the use of mobile phones, a low-cost gaussmeter was constructed using a Hall-effect sensor salvaged from an old 5.25 inch floppy disk drive [10], later calibrated with the help of a Helmholtz coil.Another measurement system was based on a manually wound coil (200 turns, AWG 28 wire), whose acquired signal amplitude was further increased (25 dB voltage gain) by an operational amplifier [11].
Earth magnetic field levels vary between 25 µT and 60 µT [12].That imposes a lower bound for measurements, since the amplitude corresponding to the Earth field is always present, acting as a noise level floor.A particular methodology can be used to subtract this local amplitude level from the actual measurement, thereby isolating the device under test emission.For instance, by using the three field components, readings can use the one which has the least influence from the existing ambient magnetic field.
A current concern among the general population involves unintended effects of electromagnetic fields, whether they present some hazard or not.In the specific case of steady (DC, direct current) magnetic fields, ICNIRP (International Commission on Non-Ionizing Radiation Protection) guidelines set the maximum amplitude for general public to be 4000 µT, valid for exposures to any part of the body [13].Specific attention should be taken with patients carrying implanted electronic devices, such as pacemakers, as well as systems which contain ferromagnetic materials.For these cases, another maximum bound of 500 mT is indicated [14].Electric and hybrid vehicles, in particular, are under scrutiny in view of the high-amplitude currents that drive their engines, with open discussions regarding their safety regulations and specific guidelines.In [15], magnetic field measurements are performed in a Mercedes Benz hybrid vehicle, whose emitted levels lied still well below the ICNIRP thresholds, measured across a test track.
This article shows the use of an Android Phone magnetic sensor, using the software resources provided by App Inventor platform to control it and manipulate its acquired data.Different types of real-world applications are shown, all using low cost and readily available materials.The sensor of a particular mobile phone was also subject to test its calibration, against a Helmholtz coil, following the guidelines set elsewhere [10].Results confirmed the wide possibilities of using MPs to afford students and researchers with a way to perform realworld tests involving magnetic fields.

Software
App Inventor is a free, web-based environment that allows Android, and, recently, also IoS (Apple) MP programming.It employs functional blocks for the design, in an intuitive and straightforward way, similar to Labview, from National Instruments, or Simulink, from Matlab.It has two different workspaces; "Designer", intended to create the app interface, with buttons, objects and visualization tools, and the "Blocks", where different methods and events are described.Figure 1 shows the App Inventor interface ("Blocks" canvas) and the screenshot of an actual mobile phone application, after compiled and transferred (by download) to the smart phone.
One of the cases was focused in computing the measurement average, to smooth out sequential readings and eliminate noise fluctuations.The application starts with the Magnetic Field Sensor object, which can output four different values for the measured existing field; X, Y, Z and its magnitude.Two different clock objects were inserted, one delay is responsible for the update measurement interval (named Clock_Measurement) and other implements an average whenever it cycles (Clock_Display), the latter larger than the former as to compute an average over many samples.Several measurements are performed and later, when the updated clock ticks, the average is computed using a procedure, App Inventor jargon to a subroutine within the main program.Both clock intervals are selected by the user using a slider object.Figure 2 shows the building blocks that perform the application.
The initial idea was to save the measured data in the mobile phone memory, not possible due to current Android security levels.Attempts using an SD (secure card were also not successful.Therefore, a Share object was included in the program, so that the overall measured data, saved in a list, can be sent by email, Twitter or saved in some Cloud service (e.g., Google Drive).The received data contain two vectors, one with the magnetic field measurements and other with the respective latitude and longitude of the acquired points, when that is required.
An object (Chart_Maker) plots the measured data, but for that it is necessary Internet access, using either a WiFi connection or 4/5 G channel.In case the MP is offline, the data is still gathered, but the plot is not shown.
The results provided by the App Inventor code, once installed and launched in the MP, can be compared with other applications, available on the proper channels.That guarantees the consistency of the designed app (software), but not the result itself, which in turn requires a calibration or comparison with another hardware.
Besides the mentioned GPS and magnetic, other sensors are possible to be used inside App Inventor, such as sound, presence, gyroscope, accelerometer, etc. Depending on the MP, however, there might be limitations on the type of available sensors.

Hardware
Tests were carried out with a Samsung S20 FE, launched in 2021.Its magnetic sensor is a Hall-effect AK09918, maximum range 4912 µT and nominal resolution of 0.15 µT.Hall-effect magnetometers are cheap but in general have low sensitivities (smaller than 5 mV/mT [9]).The particular magnetometer used in the MP has a sensitivity of 0.15 µT/LSB (least significant bit), with its analog to digital converter employing a 16-bit size number.
It was noticed that in spite of the sensor acquiring the three orthogonal field components, its response is not omnidirectional, i.e., its absolute magnitude depends on the phone orientation.It means that measurements should be performed with the MP always in the same relative position with regard to the field, moving or rotating it influences the reading value.

Calibration
A calibration routine is needed to check whether the amplitude values provided by the MP are correct, to test the hardware part of the system.One such available method is based on the Helmholtz coil [10], shown in Fig. 3.It consists of two similar coils, each with N turns, excited in series by a current source.There is a region of uniform field right at the coil geometric center, whose field expression derivation and construction details are derived elsewhere [16].In theory, it can be excited by either static or time-varying currents.
For this specific test, a 0.2 m radius, 154 turns Helmholtz Coil was employed (maker: PhyWe), part of a didactic kit (Fig. 4).Two commercial Gaussmeters (A: PhyWe and B: MGM-20) measured the field.A DC current source is used for the coil excitation, its amplitude monitored by a multimeter.The use of two gaussmeters, each with its own probe, enabled a better comparison with the existing magnetic field.The coil magnetic field amplitude at its center is defined as: where µ o , N , I and R are respectively the free-space magnetic permeability, number of turns, current and coil radius.Table 1 contains the acquired data, alongside with the analytical expected result.Two different current amplitudes were used to drive the coils.
It can be seen that results showed a good agreement, the worst deviation from the mobile phone is 2.7%, taking it in contrast to the analytical formula.Both gaussmeters had the option of nulling the ambient magnetic field, a feature not implemented in the mobile phone, and it might account for the differences, with the MP always displaying the largest magnitude throughout the tests.
In case a Helmholtz coil is not available, other methods to check the measured amplitude can be used, such as Neodyme magnets, possible to be extracted from old hard-disk drives.They are known by their strong magnetic fields, and once their amplitude is measured with a gaussmeter (or provided by the maker) they can be used as a calibration standard.

Measurements
Three different practical measurement scenarios are presented, exploring the MP magnetic field sensor and different functionalities enabled by the App Inventor suite.

Georeference
Mobile phone and Android processing capabilities offer several possibilities to be used together with the magnetic field measurement.For instance, in this case, the magnetic field was measured and assigned to its local GPS coordinates.Later, the data was exported to be used and visualized in another program.App Inventor GPS object has a property named accuracy, so it was decided to display, on the interface, its current value alongside each measurement.As the exposition to the GPS satellites increase, for instance by moving into open outdoor areas, the precision improves, reaching in the best cases 11 meters, and in the worst cases 50 meters, when obstructed and partially covered areas.
Besides the accuracy, another particular issue with the GPS reader was that when it was made automatic (taking several samples per second), systematic errors were observed, with points lumped together in the wrong locations, therefore missing the current track description.Instead of a continuous smooth display of points along the track, very few positions are shown, with the acquired points grouped around the same few positions.For this reason, instead of automatic georeferrence, a button was inserted to manually acquire the external data, only at this specific event the magnetic and GPS readings are performed (Fig. 5).
Figure 6 shows the obtained results in the Paulista Avenue, Sao Paulo central area.The acquired data   were exported and within Matlab correlated with a georeferenced OpenStreet map.That made possible the data visualization overlayed on top of the region map, in the background.All different elements within the plot share their latitude and longitude information, acting as a kind of spatial synchronism.

Time-dependent series
Both Sao Paulo subway and train systems are electrically driven.Figure 7 shows how the magnetic field fluctuates along a subway trip, across one of its branches.Since the GPS signal amplitude was too faint or non-existent, the horizontal axes depict the time (sampling rate was set to 2 measurements per second) alongside the respective station names.It can be seen that as the train departs the station and accelerates with a fast and large current pulse, it generates a peak in the magnetic amplitude.In between stations, braking pulses are also detected in the magnetic field.It is worth mention that subway trains are remotely controlled, the train conductor only oversees its operation.
A similar measurement procedure was applied to the train trip across the Expressway Turquoise Line, shown in Fig. 8. Since the express way does not stop in every station across the track, several acceleration and brakes peaks are seen.It is worth stressing that train stations are much further apart than those in the subway.It can be seen that amplitude field levels are lower for the train in contrast to the subway, probably due to different voltages and currents (subway: 750 V and train: 3000 V, DC for both cases), as well as their different sizes and speeds.Trains are, in general, larger and heavier than the subway counterpart.Finally, the trains run in a free outdoor environment whereas most subway stations are underground, in steel-reinforced concrete tunnels, which might account for further field attenuation.

Frequency response
Since most domestic appliances which generate stray magnetic fields are excited by mains power (60 Hz or 50 Hz), the sensor response speed needs to be checked if it can accurately respond to this time-varying field.For that evaluation, a clock object was set inside the App inventor program to tick every 5 ms, when it measures the magnetic field and stores the data into a vector, later exported using the share object.A 5 ms interval corresponds to a sampling frequency of 200 Hz, therefore fast enough to sample signals up to 100 Hz, according to the Nyquist Theorem [17], well above the AC fundamental oscillation.For the test, a coil (2.5 turns, 25 cm diameter) was constructed and excited directly by a transformer, whose secondary tap provided 60 V (all values in RMS).The current limit was performed by five series-connected 1 Ω, 20 W ceramic resistors.A 110 V fan was used to refrigerate the resistors, which otherwise overheated due to the 12 A current. Figure 9 displays the used setup.
Results are shown in Fig. 10.It can be seen that the field increases from the ambient level, when the  transformer is connected to the AC plug, stabilizes around 70 µT, and then falls when the power cord is pulled.The slow rise and fall times in the response are due to the magnetic energy stored in the considerable large transformer, salvaged from old UPS (uninterruptible power supply).
For the specific 60 Hz signal, a zoomed-in inset is shown in the plot, where an oscillatory waveform at this frequency is shown together with the respective measurement signal -it can be seen that no oscillatory response is captured by the MP sensor, in spite of its 5 ms sampling frequency.It probably indicates that the sensor itself is not fast enough to provide AC measurements, behaving like an integral operator on these external fields.Nevertheless, the average level of this oscillatory field is captured, therefore investigations on strong AC stray fields can be performed, bearing in mind the results do not follow exactly the expected time waveform of the sampled field.

Conclusion
The article explored different possibilities using smart phones and their embedded magnetic field sensor, with some observed limitations presented and discussed.Combined with software development using the free App Inventor platform, a large number of experiences can be performed.Both hardware and software facilities can be employed to motivate students and expose them to experimental concepts, such as systematic errors, repeatability, sensors frequency response, etc.As the number of physical quantities and overall functionalities increase with newer phone models, other possibilities arise to improve even more their use in self-contained instruments, capable of performing even complex experiments.

Figure 1 : 3 Figure 2 :
Figure 1: App inventor (left) and its actual deployment on the mobile phone (right).

Figure 3 :
Figure 3: Schematic of a Helmholtz coil, excited by a current source with amplitude I.

Figure 4 :
Figure 4: Used gaussmeters (left) and complete setup.The mobile phone and probes are placed on the middle point of the Helmholtz coil.

Figure 5 :
Figure 5: Screenshot of the magnetic field meter.The accuracy is shown in the red box.

Figure 6 :
Figure 6: Measurements along a Paulista Avenue track.

Figure 7 :
Figure 7: Measurements across Sao Paulo Line 2 (green) subway stations, names shown in the plot.

Figure 8 :
Figure 8: Measurements across Expressway Line 10 (Turquoise), station names shown in the plot.

Figure 9 :
Figure 9: Setup to test the AC response of the mobile phone sensor.The plier at the center works as size reference.

Figure 10 :
Figure 10: AC response of the coil.Inset shows a zoomed-in sector, alongside the expected oscillatory curve, not captured by the sensor.

Table 1 :
Summary of the results.Field unit: µT .