Using the MCP3008 ADC with the Raspberry Pi to Detect Magnetic Fields

Using the MCP3008 with the Raspberry Pi over SPI to detect Magnetic Fields using the OH49E Hall Effect Sensor

Required Components

  • MCP3008 ADC
  • OH49E Hall Effect Sensor
  • Raspberry Pi

Steps

Connect the MCP3008 ADC to the Raspberry Pi as in adafruit's walkthrough . Do not add any potentiometer.

Install required libraries. Ensure that the OS upgrade succeeds before continuing with further commands.

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install python3-pip
sudo pip3 install --upgrade setuptools
cd ~
sudo pip3 install --upgrade adafruit-python-shell
wget https://raw.githubusercontent.com/adafruit/Raspberry-Pi-Installer-Scripts/master/raspi-blinka.py
sudo python3 raspi-blinka.py

Install MCP 3008 library. Do not replace the xxx with your version of the MCP.

sudo pip3 install adafruit-circuitpython-mcp3xxx

Check that SPI is enabled:

ls /dev/spi*
/dev/spidev0.0 /dev/spidev0.1

Run the following in python, and then you can press enter each time you want to read the voltage value from the ADC. With no magnet next to the Hall Effect sensor, the ADC should read around 2.5V. Placing the magnet close to the Hall Effect sensor results in a dramatic deviation from the 2.5V midpoint that the sensor output (lower or higher depends on the direction of applied magnetic field).

import busio
import digitalio
import board
import adafruit_mcp3xxx.mcp3008 as MCP
from adafruit_mcp3xxx.analog_in import AnalogIn
spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)
cs = digitalio.DigitalInOut(board.D5)
mcp = MCP.MCP3008(spi, cs)
channel = AnalogIn(mcp, MCP.P0)
while 1:
    _ = input("")
    print('ADC Voltage: ' + str(channel.voltage) + 'V')

References