Created
December 2, 2022 09:51
-
-
Save mrmabs/79b807e5f7e90fa28a8ee53b3eaf7be0 to your computer and use it in GitHub Desktop.
I2C ublox GPS/GNSS in MicroPython
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # I could not find any useful examlpes of getting a ublox GNSS working | |
| # in Micropython, so I wrote this one. My model is the SAM-M8Q and this | |
| # code might also work with other ublox I2C GNSS modules. | |
| # | |
| # In this example I am using micropyGPS.py to parse the NMEA sentences. | |
| # https://github.com/inmcm/micropyGPS | |
| # | |
| # Code is MIT licence | |
| # | |
| import machine, time | |
| from ubinascii import unhexlify | |
| from micropyGPS import MicropyGPS | |
| #my_gps = MicropyGPS() | |
| my_gps = MicropyGPS(location_formatting='dd') | |
| # Create I2C object | |
| i2c = machine.I2C(1, scl=machine.Pin(3), sda=machine.Pin(2), freq=400000) | |
| # Print out any addresses found | |
| devices = i2c.scan() | |
| if devices: | |
| for d in devices: | |
| print(hex(d)) | |
| gps = 0x42 # i2c address | |
| bufmsb = unhexlify("fd") # bytes in buffer, | |
| data = unhexlify("ff") # data stream | |
| def read_reg(dev, reg, length): | |
| i2c.writeto(dev, reg, False) | |
| return i2c.readfrom(dev, length) | |
| while True: | |
| buflen = int.from_bytes(read_reg(gps, bufmsb, 2), "big") | |
| #print(buflen) | |
| try: | |
| if buflen > 0: | |
| nmeas = read_reg(gps, data, buflen).decode().splitlines() | |
| for nmea in nmeas: | |
| for x in nmea: | |
| my_gps.update(x) | |
| print(my_gps.latitude, my_gps.longitude, my_gps.date, my_gps.timestamp) | |
| break | |
| except UnicodeError: # if stray \xff chars make it into the buffer, don't crash | |
| pass | |
| except IndexError: # if data is not transferred properly, don't crash | |
| pass | |
| time.sleep(0.1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment