Skip to content

Instantly share code, notes, and snippets.

@ypelletier
Created August 29, 2023 13:55
Show Gist options
  • Save ypelletier/d98a2a93be34902e785d5c8365f76343 to your computer and use it in GitHub Desktop.
Save ypelletier/d98a2a93be34902e785d5c8365f76343 to your computer and use it in GitHub Desktop.
Magnétomètre - Boussole HMCV5883L relié à un Raspberry Pi Pico Une boussole indiquant le nord est dessinée sur un écran OLED SPI.
'''
Magnétomètre - Boussole HMCV5883L relié à un Raspberry Pi Pico
Une boussole indiquant le nord est dessinée sur
un écran OLED SPI.
'''
from hmc5883l import HMC5883L
import time
import math
from ssd1306 import SSD1306_SPI
from machine import Pin, SPI
boussole = HMC5883L()
#initialisation spi pour l'écran OLED
spi = SPI(0, baudrate=20000000, polarity=0, phase=0, sck=Pin(6), mosi=Pin(7), miso=Pin(4))
# initialisation oled
oled = SSD1306_SPI(128, 64, spi, Pin(15), Pin(14), Pin(5))
# déclinaison magnétique en degrés là où vous êtes
# https://www.magnetic-declination.com/
declinaison = -12.8
# routine de calibration
oled.text("Calibration",5,5)
oled.text("Tournez",5,20)
oled.text("la boussole",5,35)
oled.show()
debut = time.time()
x, y, z = boussole.read()
xmin = x
xmax = x
ymin = y
ymax = y
while (time.time() - debut) < 8: # pendant 8 secondes
x, y, z = boussole.read()
if x < xmin:
xmin = x
if x > xmax:
xmax = x
if y < ymin:
ymin = y
if y > ymax:
ymax = y
while True:
x, y, z = boussole.read()
# transformation des données brutes
xcal = (x-(xmax+xmin)/2)*(200)/(xmax-xmin)
ycal = (y-(ymax+ymin)/2)*(200)/(ymax-ymin)
# calcul de l'angle entre x et le nord (en radians)
if xcal != 0:
angle = math.atan(ycal/xcal) + declinaison * math.pi/180
if xcal < 0:
if ycal >= 0:
angle = angle + math.pi
else:
angle = angle - math.pi
# On remplit l'écran de noir (pour effacer)
oled.fill(0)
# tracé du repère cartésien
oled.line(34, 32, 90, 32, 1)
oled.line(64, 5, 64, 60, 1)
oled.text('x',92,28,1)
oled.text('y',60,0,1)
# tracé de l'aiguille de la boussole
oled.line(64,32,64+int(25*math.cos(angle)),32-int(25*math.sin(angle)),1)
oled.show()
time.sleep_ms(200)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment