Open 4.3Magnetic field detection.py and click .
'''
* Filename : Magnetic field detection
* Thonny : Thonny 4.1.4
* Auther : http//www.keyestudio.com
'''
from machine import Pin
import time
hall = Pin(8, Pin.IN)
led = Pin(11, Pin.OUT)
while True:
value = hall.value()
print(value, end=' ')
if value == 0:
led.on()
print("A magnetic field")
else:
led.off()
print("There is no magnetic field")
time.sleep(0.1)
Conceive:
When the Hall sensor detects a magnetic field, a low power(0) will be output, and the white LED lights up. If there is no magnetic field, high(1) will be output, and the LED goes off.
Code structure:
Initialization. Set the pins of the Hall sensor and the white LED module.
Loop.
Print the digital value of the power level of the Hall sensor.
Determine whether the value equals 0 (0 means a magnetic field is detected).
value = 0: the white LED lights up.
value ≠ 0: the white LED goes off.