No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

compass.py 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import time
  2. import math
  3. import adafruit_lsm9ds1
  4. import board
  5. import busio
  6. import neopixel
  7. PURPLE = (180, 0, 255)
  8. i2c = busio.I2C(board.SCL, board.SDA)
  9. compass = adafruit_lsm9ds1.LSM9DS1_I2C(i2c)
  10. pixels = neopixel.NeoPixel(board.A1, 16, brightness=0.01, auto_write=False)
  11. # (x, y, z) tuples:
  12. MAG_MIN = (-0.25046, -0.23506, -0.322)
  13. MAG_MAX = (0.68278, 0.70882, 0.59654)
  14. def bearing_to_pixel(bearing, count=16):
  15. pixel = count - int(round((bearing / 360) * count))
  16. if (pixel == 16):
  17. pixel = 0
  18. return pixel
  19. def map_range(x, in_min, in_max, out_min, out_max):
  20. """
  21. Maps a number from one range to another.
  22. :return: Returns value mapped to new range
  23. :rtype: float
  24. """
  25. mapped = (x-in_min) * (out_max - out_min) / (in_max-in_min) + out_min
  26. if out_min <= out_max:
  27. return max(min(mapped, out_max), out_min)
  28. return min(max(mapped, out_max), out_min)
  29. while True:
  30. mag_x, mag_y, mag_z = compass.magnetometer
  31. mag_x = map_range(mag_x, MAG_MIN[0], MAG_MAX[0], -1, 1)
  32. mag_y = map_range(mag_y, MAG_MIN[1], MAG_MAX[1], -1, 1)
  33. mag_z = map_range(mag_z, MAG_MIN[2], MAG_MAX[2], -1, 1)
  34. compass_heading = (math.atan2(mag_y, mag_x) * 180) / math.pi;
  35. if compass_heading < 0:
  36. compass_heading = 360 + compass_heading;
  37. pixel = bearing_to_pixel(compass_heading)
  38. print('Magnetometer: ({0:10.3f}, {1:10.3f}, {2:10.3f})'.format(mag_x, mag_y, mag_z))
  39. print(compass_heading)
  40. print('Lighting pixel: {}'.format(pixel))
  41. pixels.fill((0,0,0))
  42. pixels[pixel] = PURPLE
  43. pixels.show()
  44. time.sleep(0.2)