def get_GPS_array(): com = UART(1,pins=(config.TX, config.RX), baudrate=9600) my_gps = MicropyGPS() time.sleep(2) if com.any(): my_sentence = com.readline() for x in my_sentence: my_gps.update(chr(x)) gps_array = convert_latlon(my_gps.latitude[0] + (my_gps.latitude[1] / 60), my_gps.longitude[0] + (my_gps.longitude[1] / 60)) return gps_array
def start_GPS(): com = UART(1,pins=("P11","P12"), baudrate=9600) my_gps = MicropyGPS() if config.LOG == 1: mount_sd() my_gps.start_logging('/sd/log.txt') my_gps.write_log('Restarted logging') while True: if com.any(): my_sentence = com.readline() for x in my_sentence: my_gps.update(chr(x)) print('Latitude: ' + my_gps.latitude_string() + ' Longitude: ' + my_gps.longitude_string() + ' Altitude: ' + str(my_gps.altitude)) print('Lat / Lon: ' + str(my_gps.latitude[0] + (my_gps.latitude[1] / 60)) + ', ' + str(my_gps.longitude[0] + (my_gps.longitude[1] / 60)))
def gps(): new_data = False # Callback Function def pps_callback(line): global new_data # Use Global to trigger update new_data = True # Instantiate the micropyGPS object my_gps = MicropyGPS() # Setup the connection to your GPS here # This example uses UART 3 with RX on pin Y10 # Baudrate is 9600bps, with the standard 8 bits, 1 stop bit, no parity # Also made the buffer size very large (1000 chars) to accommodate all the characters that stack up # each second uart = pyb.UART(sys_config['pmod']['p3']['uart'], 9600, read_buf_len=1000) # Release Reset reset = pyb.Pin(sys_config['pmod']['p3']['reset'], pyb.Pin.OUT_PP) reset.high() # Create an external interrupt on pin X8 pps_pin = pyb.Pin(sys_config['pmod']['p3']['one_pps'], pyb.Pin.IN, pull=pyb.Pin.PULL_UP) extint = pyb.ExtInt(pps_pin, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, pps_callback) # Main Infinite Loop while 1: # Do Other Stuff Here....... # Update the GPS Object when flag is tripped if new_data: while uart.any(): my_gps.update( chr(uart.readchar()) ) # Note the conversion to to chr, UART outputs ints normally #print('UTC Timestamp:', my_gps.timestamp) print('Date:', my_gps.date_string('long')) print('Latitude:', my_gps.latitude_string()) print('Longitude:', my_gps.longitude_string()) print('Horizontal Dilution of Precision:', my_gps.hdop) print('Satellites in use:', my_gps.satellites_in_use) print() new_data = False # Clear the flag
def test_gsa_sentences(): my_gps = MicropyGPS() sentence = '' print('') for sentence_count, GSA_sentence in enumerate(test_GSA): for y in GSA_sentence: sentence = my_gps.update(y) if sentence: assert sentence == "GPGSA" print('Parsed a', sentence, 'Sentence') assert my_gps.gps_segments == gsa_parsed_strings[sentence_count] print('Parsed Strings', my_gps.gps_segments) assert my_gps.crc_xor == gsa_crc_values[sentence_count] print('Sentence CRC Value:', hex(my_gps.crc_xor)) assert my_gps.satellites_used == gsa_sats_used[sentence_count] print('Satellites Used', my_gps.satellites_used) assert my_gps.fix_type == 3 print('Fix Type Code:', my_gps.fix_type) assert my_gps.hdop == gsa_hdop[sentence_count] print('Horizontal Dilution of Precision:', my_gps.hdop) assert my_gps.vdop == gsa_vdop[sentence_count] print('Vertical Dilution of Precision:', my_gps.vdop) assert my_gps.pdop == gsa_pdop[sentence_count] print('Position Dilution of Precision:', my_gps.pdop) assert my_gps.clean_sentences == len(test_GSA) assert my_gps.parsed_sentences == len(test_GSA) assert my_gps.crc_fails == 0
def test_vtg_sentences(): my_gps = MicropyGPS() sentence = '' sentence_count = 0 print('') for VTG_sentence in test_VTG: for y in VTG_sentence: sentence = my_gps.update(y) if sentence: assert sentence == "GPVTG" print('Parsed a', sentence, 'Sentence') assert my_gps.gps_segments == [ 'GPVTG', '232.9', 'T', '', 'M', '002.3', 'N', '004.3', 'K', 'A', '01' ] print('Parsed Strings', my_gps.gps_segments) assert my_gps.crc_xor == 0x1 print('Sentence CRC Value:', hex(my_gps.crc_xor)) assert my_gps.speed == (2.3, 2.6473, 4.2596) print('Speed:', my_gps.speed) assert my_gps.course == 232.9 print('Course', my_gps.course) assert my_gps.compass_direction() == 'SW' print('Compass Direction:', my_gps.compass_direction()) sentence_count += 1 assert my_gps.clean_sentences == len(test_VTG) assert my_gps.parsed_sentences == len(test_VTG) assert my_gps.crc_fails == 0
def run(): """Run the program.""" uart = UART(1) uart.init(config.baudrate, bits=8, parity=None, stop=1, rx=config.rx, tx=config.tx) gps = MicropyGPS() s = screen.Screen() kph = None start = utime.ticks_ms() while kph is None and utime.ticks_diff(utime.ticks_ms(), start) < 1000: if uart.any(): try: stat = gps.update(chr(uart.read(1)[0])) except: pass if stat == 'GNRMC': print(stat) kph = gps.speed[2] if kph is not None: s.update(kph) machine.deepsleep(5000)
def test_rmc_sentences(): my_gps = MicropyGPS() sentence = '' print('') for sentence_count, RMC_sentence in enumerate(test_RMC): for y in RMC_sentence: sentence = my_gps.update(y) if sentence: assert sentence == "GPRMC" print('Parsed a', sentence, 'Sentence') assert my_gps.gps_segments == rmc_parsed_strings[sentence_count] print('Parsed Strings:', my_gps.gps_segments) assert my_gps.crc_xor == rmc_crc_values[sentence_count] print('Sentence CRC Value:', hex(my_gps.crc_xor)) assert my_gps.longitude == rmc_longitude[sentence_count] print('Longitude:', my_gps.longitude) assert my_gps.latitude == rmc_latitude[sentence_count] print('Latitude', my_gps.latitude) assert my_gps.timestamp == rmc_utc[sentence_count] print('UTC Timestamp:', my_gps.timestamp) assert my_gps.speed == rmc_speed[sentence_count] print('Speed:', my_gps.speed) assert my_gps.date == rmc_date[sentence_count] print('Date Stamp:', my_gps.date) assert my_gps.course == rmc_course[sentence_count] print('Course', my_gps.course) assert my_gps.valid print('Data is Valid:', my_gps.valid) assert my_gps.compass_direction() == rmc_compass[sentence_count] print('Compass Direction:', my_gps.compass_direction()) assert my_gps.clean_sentences == len(test_RMC) assert my_gps.parsed_sentences == len(test_RMC) assert my_gps.crc_fails == 0
def __init__(self, uart_channel: int): """ Begin reading data from the GPS over UART. :param uart_channel: The UART channel that the GPS is connected to. """ self.gps = MicropyGPS(location_formatting="dd") asyncio.create_task(self.uart_rx(uart_channel))
def __init__(self): self._gps_uart = machine.UART(1, 9600) self.cfg = ConfigRepository() self._gps_uart.init(tx=self.cfg.get("gps_uart_tx"), rx=self.cfg.get("gps_uart_rx")) self._gps = MicropyGPS() self._model = None
def __init__(self): #initialize state from saved file try: file = open('state.csv', 'r') s = file.read().strip(',') if len(s) == 6: for i in range(len(s)): s[i] = eval(s[i]) file.close() except: self.X = np.array([0, 0, 0, 0, 0, 0]).reshape([6, 1]) self.P = np.ones([6, 6]) * 1000 self.Y = np.array([0, 0, 0, 0, 0, 0]).reshape([6, 1]) self.time = 0 self.alt = 0 self.dt = 1 self.burstCount = 0 self.burst = False self.windSpeed = [] for i in range(1, 311): #wind vector: [alt, vx, vy, sum_vx, sum_vy, N] self.windSpeed.append([i * 100, 0, 0, 0, 0, 0]) #initialize IMU and GPS objects self.mpu = MPU9250.MPU9250() self.gps = MicropyGPS( -6) #-6 for Central Time; input is time zone offset #destination coordinates self.target = csvReadMat('target.csv').reshape([2]) #set instrument variance self.R = csvReadMat('instVariance.csv')
def read_next(self): buf = ['\0'] var = True iNeedDollar = '$' while iNeedDollar != self._fd.read(): pass #buf.append(iNeedDollar) buf = [iNeedDollar] + buf while var: #buf[len(buf)-1]=iNeedDollar buf[len(buf) - 1] = self._fd.read() if buf[len(buf) - 1] == '\r': buf[len(buf) - 1] = '\n' buf.append('\0') if (len(buf) > 2 and buf[len(buf) - 2] == '\n' and buf[len(buf) - 3] == '\n'): self._my_gps = MicropyGPS() my_sentence = ''.join(buf) for x in my_sentence: self._my_gps.update(x) var = False #print(self._fd.read()) print(''.join(buf))
def test_gga_sentences(): my_gps = MicropyGPS() sentence = '' print('') for sentence_count, GGA_sentence in enumerate(test_GGA): for y in GGA_sentence: sentence = my_gps.update(y) if sentence: assert sentence == "GPGGA" print('Parsed a', sentence, 'Sentence') assert my_gps.gps_segments == gga_parsed_strings[sentence_count] print('Parsed Strings', my_gps.gps_segments) assert my_gps.crc_xor == gga_crc_xors[sentence_count] print('Sentence CRC Value:', hex(my_gps.crc_xor)) assert my_gps.longitude == gga_longitudes[sentence_count] print('Longitude', my_gps.longitude) assert my_gps.latitude == gga_latitudes[sentence_count] print('Latitude', my_gps.latitude) assert my_gps.timestamp == gga_timestamps[sentence_count] print('UTC Timestamp:', my_gps.timestamp) assert my_gps.fix_stat == gga_fixes[sentence_count] print('Fix Status:', my_gps.fix_stat) assert my_gps.altitude == gga_altitudes[sentence_count] print('Altitude:', my_gps.altitude) assert my_gps.geoid_height == gga_geoid_heights[sentence_count] print('Height Above Geoid:', my_gps.geoid_height) assert my_gps.hdop == gga_hdops[sentence_count] print('Horizontal Dilution of Precision:', my_gps.hdop) assert my_gps.satellites_in_use == gga_satellites_in_uses[sentence_count] print('Satellites in Use by Receiver:', my_gps.satellites_in_use) assert my_gps.clean_sentences == len(test_GGA) assert my_gps.parsed_sentences == len(test_GGA) assert my_gps.crc_fails == 0
def test_gll_sentences(): my_gps = MicropyGPS() sentence = '' print('') for sentence_count, GLL_sentence in enumerate(test_GLL): for y in GLL_sentence: sentence = my_gps.update(y) if sentence: assert sentence == "GPGLL" print('Parsed a', sentence, 'Sentence') assert my_gps.gps_segments == gll_parsed_string[sentence_count] print('Parsed Strings', my_gps.gps_segments) assert my_gps.crc_xor == gll_crc_values[sentence_count] print('Sentence CRC Value:', hex(my_gps.crc_xor)) assert my_gps.longitude == gll_longitude[sentence_count] print('Longitude:', my_gps.longitude) assert my_gps.latitude == gll_latitude[sentence_count] print('Latitude', my_gps.latitude) assert my_gps.timestamp == gll_timestamp[sentence_count] print('UTC Timestamp:', my_gps.timestamp) assert my_gps.valid == gll_valid[sentence_count] print('Data is Valid:', my_gps.valid) assert my_gps.clean_sentences == len(test_GLL) assert my_gps.parsed_sentences == len(test_GLL) assert my_gps.crc_fails == 0
def __init__(self,num_sentences=3,timeout=5): p_pwr2.value(1) # turn on power to the GPS p_pwr3.value(1) # the GPS requires power from multiple GPIOs p_pwr4.value(1) self.num_sentences=num_sentences self.timeout=timeout self.my_gps = MicropyGPS() # create GPS parser object
class GpsSensor(Sensor): """ A GPS sensor implementing NMEA-0183 connected via UART, such as the u-blox NEO 6M. """ def __init__(self, uart_channel: int): """ Begin reading data from the GPS over UART. :param uart_channel: The UART channel that the GPS is connected to. """ self.gps = MicropyGPS(location_formatting="dd") asyncio.create_task(self.uart_rx(uart_channel)) async def uart_rx(self, uart_channel: int): """ Read and load data from the GPS over UART. """ uart = UART(uart_channel, baudrate=9600) stream_reader = asyncio.StreamReader(uart) while True: res = await stream_reader.readline() for char in res: self.gps.update(chr(char)) def read(self): """ Get the most recently stored GPS data. :return: An array containing the GPS sensor dictionary. `value` in this dictionary contains spacial, quality of service and time information. """ # gps.latitude[1] will be "N" if north of equator, otherwise "S" if south. # gps.longitude[1] is similar. The [0] component is always positive. latitude = self.gps.latitude[0] * (1 if self.gps.latitude[1] == "N" else -1) longitude = self.gps.longitude[0] * (1 if self.gps.longitude[1] == "E" else -1) # ISO 8601 datetime format datetime = "20{:02d}-{:02d}-{:02d}T{:02d}:{:02d}:{:02.0f}".format( self.gps.date[2], self.gps.date[1], self.gps.date[0], *self.gps.timestamp ) kph_to_mps = 1 / 3.6 return [ { "type": "gps", "value": { "satellites": self.gps.satellites_in_use, "pdop": self.gps.pdop, "latitude": latitude, "longitude": longitude, "altitude": self.gps.altitude, "speed": self.gps.speed[2] * kph_to_mps, "course": self.gps.course, "datetime": datetime, }, } ]
class GPS: def __init__(self): self.gps = MicropyGPS(9, "dd") self.s = serial.Serial('/dev/serial0', 9600, timeout=10) def rungps(self): for x in self.s.readline().decode('utf-8'): self.gps.update(x) def read(self): self.rungps() return (self.gps.latitude[0], self.gps.longitude[0])
def test_gsv_sentences(): my_gps = MicropyGPS() sentence = '' print('') for sentence_count, GSV_sentence in enumerate(test_GSV): for y in GSV_sentence: sentence = my_gps.update(y) if sentence: assert sentence == "GPGSV" print('Parsed a', sentence, 'Sentence') assert my_gps.gps_segments == gsv_parsed_string[sentence_count] print('Parsed Strings', my_gps.gps_segments) assert my_gps.crc_xor == gsv_crc_values[sentence_count] print('Sentence CRC Value:', hex(my_gps.crc_xor)) assert my_gps.last_sv_sentence == gsv_sv_setence[sentence_count] print('SV Sentences Parsed', my_gps.last_sv_sentence) assert my_gps.total_sv_sentences == gsv_total_sentence[sentence_count] print('SV Sentences in Total', my_gps.total_sv_sentences) assert my_gps.satellites_in_view == gsv_num_sats_in_view[sentence_count] print('# of Satellites in View:', my_gps.satellites_in_view) assert my_gps.satellite_data_updated() == gsv_data_valid[sentence_count] data_valid = my_gps.satellite_data_updated() print('Is Satellite Data Valid?:', data_valid) if data_valid: print('Complete Satellite Data:', my_gps.satellite_data) print('Complete Satellites Visible:', my_gps.satellites_visible()) else: print('Current Satellite Data:', my_gps.satellite_data) print('Current Satellites Visible:', my_gps.satellites_visible()) assert my_gps.satellite_data == gsv_sat_data[sentence_count] assert my_gps.satellites_visible() == gsv_sats_in_view[sentence_count] assert my_gps.clean_sentences == len(test_GSV) assert my_gps.parsed_sentences == len(test_GSV) assert my_gps.crc_fails == 0
def __init__(self): self.timestamp = [0, 0, 0.0] self.timestamp_string = '' self.latitude = 0.0 self.longitude = 0.0 self.altitude = 0.0 self.speed = [] self.course = 0.0 self.satellites_used = [] self.satellite_data = {} self.gps = MicropyGPS(9, 'dd') self.gpsthread = threading.Thread(target=self.runGps, args=()) self.gpsthread.daemon = True self.gpsthread.start()
def set_date_time(): com = UART(1,pins=(config.TX, config.RX), baudrate=9600) my_gps = MicropyGPS() time.sleep(2) if com.any(): my_sentence = com.readline() for x in my_sentence: my_gps.update(chr(x)) date = my_gps.date timestamp = my_gps.timestamp hour = timestamp[0] hour = hour + config.TIMEZONE if config.DAYLIGHT == 1: hour = hour + 1 rtc = RTC(datetime=(int(date[2])+2000, int(date[1]), int(date[0]), int(timestamp[0]), int(timestamp[1]), int(timestamp[2]), 0, None)) return rtc
def __init__(self, module): super().__init__(module, 9) # 9 byte data packet self.param = { # must be params 'NAME': PNAME, 'ENABLE': False, 'TIMER': 0, 'PORT': '', # instance specific params 'RespVarPos': 'GPS.Position', 'RespVarLat': 'GPS.Latitude', 'RespVarLon': 'GPS.Longitude', 'RespVarCrs': 'GPS.Course', 'RespVarAlt': 'GPS.Altitude', 'RespVarSpd': 'GPS.Speed', } self._gps = MicropyGPS(local_offset=0, location_formatting='ddm')
def __init__(self): self.timestamp = [0, 0, 0.0] self.timestamp_string = "" self.latitude = 0.0 self.longitude = 0.0 self.altitude = 0.0 self.speed = [] self.course = 0.0 self.satellites_used = [] self.satellite_data = {} try: self.serial = Serial("/dev/serial0", 9600, timeout=10) except: self.serial = Serial("/dev/ttyACM0", 9600, timeout=10) print( "Exception occurred in receiving GPS data. Switching to another serial port." ) self.gps = MicropyGPS(9, "dd") self.gpsthread = threading.Thread(target=self.run_gps, args=()) self.gpsthread.daemon = True self.gpsthread.start()
def test_gga_sentences(): my_gps = MicropyGPS() sentence = '' sentence_count = 0 print('') for GGA_sentence in test_GGA: for y in GGA_sentence: sentence = my_gps.update(y) if sentence: assert sentence == "GPGGA" print('Parsed a', sentence, 'Sentence') assert my_gps.gps_segments == [ 'GPGGA', '180050.896', '3749.1802', 'N', '08338.7865', 'W', '1', '07', '1.1', '397.4', 'M', '-32.5', 'M', '', '0000', '6C' ] print('Parsed Strings', my_gps.gps_segments) assert my_gps.crc_xor == 0x6c print('Sentence CRC Value:', hex(my_gps.crc_xor)) assert my_gps.longitude == [83, 38.7865, 'W'] print('Longitude', my_gps.longitude) assert my_gps.latitude == [37, 49.1802, 'N'] print('Latitude', my_gps.latitude) assert my_gps.timestamp == [18, 0, 50.896] print('UTC Timestamp:', my_gps.timestamp) assert my_gps.fix_stat == 1 print('Fix Status:', my_gps.fix_stat) assert my_gps.altitude == 397.4 print('Altitude:', my_gps.altitude) assert my_gps.geoid_height == -32.5 print('Height Above Geoid:', my_gps.geoid_height) assert my_gps.hdop == 1.1 print('Horizontal Dilution of Precision:', my_gps.hdop) assert my_gps.satellites_in_use == 7 print('Satellites in Use by Receiver:', my_gps.satellites_in_use) sentence_count += 1 assert my_gps.clean_sentences == len(test_GGA) assert my_gps.parsed_sentences == len(test_GGA) assert my_gps.crc_fails == 0
def parse_log_file(self, filename): # instances of a class gnss_nmea_sentence = MicropyGPS() glo_nmea_sentence = MicropyGPS() bdo_nmea_sentence = MicropyGPS() # open file as utf8 with open(filename, encoding="utf8") as f: for line in f: if "# Version:" in line: self.parse_info_line(line) # This section below is commented because non of our log files had enough raw data for computation # gnss solution. Only one smartphone has it, and it was analysed by gnss-measurement-tool by Google(c) # elif "Raw" in line: # raw_list = (line.split(',')) # del raw_list[0] # if raw_list[-1] == '\n': # raw_list[-1] = '' # if not raw_data: # emp = raw._make(raw_list) # print("first") # for fld in emp._fields: # if (not getattr(emp, fld)) or (float(getattr(emp, fld)) == 0.0): # bad_cal.append(fld) # else: # good_col.append(fld) # raw_fixed = namedtuple('raw_fixed', good_col) # for i, list in enumerate(raw_list): # if not list or float(list) == 0.0: # del_list.append(i) # raw_list = [v for i, v in enumerate(raw_list) if i not in del_list] # emp = raw_fixed._make(raw_list) # raw_data.append(emp) elif "Fix" in line: fix_list = (line.split(',')) del fix_list[0] if fix_list[-1] == '\n': del fix_list[-1] emp = fix._make(fix_list) self.fix_data.append(emp) elif "NMEA" in line: timestamp_local = gnss_nmea_sentence.timestamp if line[6:8] == 'GP' or line[6:8] == 'GN': for y in line[5:-1]: gnss_nmea_sentence.update(y) # This section below is commented because not all logs files have equal nmea string format # Because of this not all constellations can be parsed. Either you except some log files # (for us it was PIE log file) and uncomment section below or you leave it commented # elif line[6:8] == 'GL': # for y in line[5:-1]: # glo_nmea_sentence.update(y) # elif line[6:8] == 'BD': # for y in line[5:-1]: # bdo_nmea_sentence.update(y) if gnss_nmea_sentence.timestamp != timestamp_local: self.gnss_data.append(deepcopy(gnss_nmea_sentence)) self.glo_data.append(deepcopy(glo_nmea_sentence)) self.bdo_data.append(deepcopy(bdo_nmea_sentence)) return self
class BasicGPSController(GPSController): def __init__(self): self._gps_uart = machine.UART(1, 9600) self.cfg = ConfigRepository() self._gps_uart.init(tx=self.cfg.get("gps_uart_tx"), rx=self.cfg.get("gps_uart_rx")) self._gps = MicropyGPS() self._model = None def run(self): # TODO: Why do we need to constantly update the GPS values here? while True: try: self._update_gps() except Exception as e: logging.info(e) time.sleep(1) def get_status(self) -> GPSStatus: return self._model def _update_gps(self): g_sentence = self._gps_uart.readline() while g_sentence: g_sentence = g_sentence.decode("ascii") for g_word in g_sentence: self._gps.update(g_word) self._model = GPSStatus( self._gps.valid, self._gps.latitude, self._gps.longitude, self._gps.altitude, self._gps.speed, self._gps.course, self._gps.timestamp, ) g_sentence = self._gps_uart.readline()
def setup(): global gps global uart global x1 global x2 global y1 global y2 gps = MicropyGPS() uart = serial.Serial("/dev/ttyS0", baudrate=9600, timeout=30) x1 = gps.longitude[1] y1 = gps.latitude[1] x2 = float(input("Enter Latitude")) y2 = float(input("Enter Longitude"))
def gps(): new_data = False # Callback Function def pps_callback(line): global new_data # Use Global to trigger update new_data = True # Instantiate the micropyGPS object my_gps = MicropyGPS() # Setup the connection to your GPS here # This example uses UART 3 with RX on pin Y10 # Baudrate is 9600bps, with the standard 8 bits, 1 stop bit, no parity # Also made the buffer size very large (1000 chars) to accommodate all the characters that stack up # each second uart = pyb.UART(sys_config['pmod']['p3']['uart'], 9600, read_buf_len=1000) # Release Reset reset = pyb.Pin(sys_config['pmod']['p3']['reset'], pyb.Pin.OUT_PP) reset.high() # Create an external interrupt on pin X8 pps_pin = pyb.Pin(sys_config['pmod']['p3']['one_pps'], pyb.Pin.IN, pull=pyb.Pin.PULL_UP) extint = pyb.ExtInt(pps_pin, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, pps_callback) # Main Infinite Loop while 1: # Do Other Stuff Here....... # Update the GPS Object when flag is tripped if new_data: while uart.any(): my_gps.update(chr(uart.readchar())) # Note the conversion to to chr, UART outputs ints normally #print('UTC Timestamp:', my_gps.timestamp) print('Date:', my_gps.date_string('long')) print('Latitude:', my_gps.latitude_string()) print('Longitude:', my_gps.longitude_string()) print('Horizontal Dilution of Precision:', my_gps.hdop) print('Satellites in use:', my_gps.satellites_in_use) print() new_data = False # Clear the flag
def pps_callback(line): print("Updated GPS Object...") global new_data # Use Global to trigger update new_data = True print('GPS Interrupt Tester') # Instantiate the micropyGPS object my_gps = MicropyGPS() # Setup the connection to your GPS here # This example uses UART 3 with RX on pin Y10 # Baudrate is 9600bps, with the standard 8 bits, 1 stop bit, no parity # Also made the buffer size very large (1000 chars) to accommodate all the characters that stack up # each second uart = UART(3, 9600, read_buf_len=1000) # Create an external interrupt on pin X8 pps_pin = pyb.Pin.board.X8 extint = pyb.ExtInt(pps_pin, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, pps_callback) # Main Infinite Loop while 1: # Do Other Stuff Here....... # Update the GPS Object when flag is tripped if new_data: while uart.any(): my_gps.update(chr(uart.readchar())) # Note the conversion to to chr, UART outputs ints normally print('UTC Timestamp:', my_gps.timestamp) print('Date:', my_gps.date_string('long')) print('Latitude:', my_gps.latitude_string()) print('Longitude:', my_gps.longitude_string()) print('Horizontal Dilution of Precision:', my_gps.hdop) print() new_data = False # Clear the flag
from machine import Pin, I2C import time import ssd1306 import machine from micropyGPS import MicropyGPS com = machine.UART(2, 9600, timeout=10) #定义uart2 my_gps = MicropyGPS(8) #东八区的修正 my_gps.local_offset gps_values = 'abc' rtc = 'efg' def get_GPS_values(): global gps_values, rtc #定义两个全局变量 time.sleep(2) cc = com.readline() print(cc) for x in cc: my_gps.update(chr(x)) #lat&long print(my_gps.latitude[0]) gps_values = str(my_gps.latitude[0] + (my_gps.latitude[1] / 60)) + ',' + str(my_gps.longitude[0] + (my_gps.longitude[1] / 60)) #datetime date = my_gps.date timestamp = my_gps.timestamp hour = timestamp[0]
# Global Flag to Start GPS data Processing new_data = False # Callback Function def pps_callback(line): print("Updated GPS Object...") global new_data # Use Global to trigger update new_data = True print('GPS Interrupt Tester') # Instantiate the micropyGPS object my_gps = MicropyGPS() # Setup the connection to your GPS here # This example uses UART 3 with RX on pin Y10 # Baudrate is 9600bps, with the standard 8 bits, 1 stop bit, no parity # Also made the buffer size very large (1000 chars) to accommodate all the characters that stack up # each second uart = UART(3, 9600, read_buf_len=1000) # Create an external interrupt on pin X8 pps_pin = pyb.Pin.board.X8 extint = pyb.ExtInt(pps_pin, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, pps_callback) # Main Infinite Loop while 1:
class Gps: _fd = -1 _my_gps = None def __init__(self): self.configure_serial() """if self._fd != -1: serialClose(self._fd)""" def read_next(self): buf = ['\0'] var = True iNeedDollar = '$' while iNeedDollar != self._fd.read(): pass #buf.append(iNeedDollar) buf = [iNeedDollar] + buf while var: #buf[len(buf)-1]=iNeedDollar buf[len(buf) - 1] = self._fd.read() if buf[len(buf) - 1] == '\r': buf[len(buf) - 1] = '\n' buf.append('\0') if (len(buf) > 2 and buf[len(buf) - 2] == '\n' and buf[len(buf) - 3] == '\n'): self._my_gps = MicropyGPS() my_sentence = ''.join(buf) for x in my_sentence: self._my_gps.update(x) var = False #print(self._fd.read()) print(''.join(buf)) def longitude(self): return self._my_gps.longitude def latitude(self): return self._my_gps.latitude def configure_serial(self): self._fd = serial.Serial( port='/dev/ttyS0', baudrate=9600 #, #parity=serial.PARITY_ODD, #stopbits=serial.STOPBITS_TWO, #bytesize=serial.SEVENBITS ) optionFlag = termios.tcgetattr(self._fd) optionFlag[2] &= ~termios.PARENB optionFlag[2] &= ~termios.CSTOPB optionFlag[2] &= ~termios.CSIZE optionFlag[2] |= termios.CS8 optionFlag[3] &= ~(termios.ICANON | termios.ECHO | termios.ECHOE | termios.ISIG) optionFlag[1] &= ~termios.OPOST optionFlag[2] |= (termios.CLOCAL | termios.CREAD) #cfsetispeed(&options, B9600) #cfsetospeed(&options, B9600) termios.tcsetattr(self._fd, termios.TCSANOW, optionFlag) message = "$PMTK314,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*%x\r\n" #print(self.crc(message)) buffer = message % self.crc(message) #buffer = message%18 print(buffer) print(" Sended Bytes :" + str(self._fd.write(str.encode(buffer)))) # TODO à vérifier #print(" Sended Bytes :" + str(self._fd.write(buffer))) # TODO à vérifier def crc(self, message): res = 0 #res = np.array([0], dtype='uint8') i = 1 while message[i] != '*': res ^= ord(message[i]) i += 1 return res
# Correct for heading 'wrap around' to find shortest turn if course_error > 180: course_error -= 360 elif course_error < -180: course_error += 360 # record the turn direction - mainly for debugging if course_error > 0: turn_direction = 1 # Turn right elif course_error < 0: turn_direction = -1 # Turn left else: turn_direction = 0 # Stay straight return course_error, turn_direction, current_heading, desired_heading my_gps = MicropyGPS() gps_uart = UART(6, 9600, read_buf_len=1000) xbee_uart = UART(2, 9600) Razor_IMU = IMU.Razor(3, 57600) # Razor_IMU.set_angle_output() Razor_IMU.set_all_calibrated_output() # while True: # a,b,c = Razor_IMU.get_one_frame() # print(a,b,c) # Countdown Timer start = pyb.millis() backup_timer = 5400000
from micropyGPS import MicropyGPS # Global Flag to Start GPS data Processing new_data = False # Callback Function def pps_callback(line): print("Updated GPS Object...") global new_data # Use Global to trigger update new_data = True print('GPS Interrupt Tester') # Instantiate the micropyGPS object my_gps = MicropyGPS() # Setup the connection to your GPS here # This example uses UART 3 with RX on pin Y10 # Baudrate is 9600bps, with the standard 8 bits, 1 stop bit, no parity # Also made the buffer size very large (1000 chars) to accommodate all the characters that stack up # each second uart = UART(3, 9600, read_buf_len=1000) # Create an external interrupt on pin X8 pps_pin = pyb.Pin.board.X8 extint = pyb.ExtInt(pps_pin, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, pps_callback) # Main Infinite Loop while 1: # Do Other Stuff Here.......
def run_tests(): sentence_count = 0 test_RMC = ['$GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62\n', '$GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A\n', '$GPRMC,225446,A,4916.45,N,12311.12,W,000.5,054.7,191194,020.3,E*68\n', '$GPRMC,180041.896,A,3749.1851,N,08338.7891,W,001.9,154.9,240911,,,A*7A\n', '$GPRMC,180049.896,A,3749.1808,N,08338.7869,W,001.8,156.3,240911,,,A*70\n', '$GPRMC,092751.000,A,5321.6802,N,00630.3371,W,0.06,31.66,280511,,,A*45\n'] test_VTG = ['$GPVTG,232.9,T,,M,002.3,N,004.3,K,A*01\n'] test_GGA = ['$GPGGA,180050.896,3749.1802,N,08338.7865,W,1,07,1.1,397.4,M,-32.5,M,,0000*6C\n'] test_GSA = ['$GPGSA,A,3,07,11,28,24,26,08,17,,,,,,2.0,1.1,1.7*37\n', '$GPGSA,A,3,07,02,26,27,09,04,15,,,,,,1.8,1.0,1.5*33\n'] test_GSV = ['$GPGSV,3,1,12,28,72,355,39,01,52,063,33,17,51,272,44,08,46,184,38*74\n', '$GPGSV,3,2,12,24,42,058,33,11,34,053,33,07,20,171,40,20,15,116,*71\n', '$GPGSV,3,3,12,04,12,204,34,27,11,324,35,32,11,089,,26,10,264,40*7B\n', '$GPGSV,3,1,11,03,03,111,00,04,15,270,00,06,01,010,00,13,06,292,00*74\n', '$GPGSV,3,2,11,14,25,170,00,16,57,208,39,18,67,296,40,19,40,246,00*74\n', '$GPGSV,3,3,11,22,42,067,42,24,14,311,43,27,05,244,00,,,,*4D\n', '$GPGSV,4,1,14,22,81,349,25,14,64,296,22,18,54,114,21,51,40,212,*7D\n', '$GPGSV,4,2,14,24,30,047,22,04,22,312,26,31,22,204,,12,19,088,23*72\n', '$GPGSV,4,3,14,25,17,127,18,21,16,175,,11,09,315,16,19,05,273,*72\n', '$GPGSV,4,4,14,32,05,303,,15,02,073,*7A\n', '$GPGSV,3,1,12,13,65,002,50,02,61,098,47,39,60,352,,05,56,183,49*70\n', '$GPGSV,3,2,12,15,35,325,50,29,32,229,49,06,25,070,44,30,16,096,38*70\n', '$GPGSV,3,3,12,19,08,022,35,07,07,122,,12,06,316,49,25,03,278,36*7D\n'] test_GLL = ['$GPGLL,3711.0942,N,08671.4472,W,000812.000,A,A*46\n', '$GPGLL,4916.45,N,12311.12,W,225444,A,*1D\n', '$GPGLL,4250.5589,S,14718.5084,E,092204.999,A*2D\n', '$GPGLL,0000.0000,N,00000.0000,E,235947.000,V*2D\n'] my_gps = MicropyGPS() my_gps.start_logging('test.txt', mode="new") my_gps.write_log('micropyGPS test log\n') sentence = '' for RMC_sentence in test_RMC: sentence_count += 1 for y in RMC_sentence: sentence = my_gps.update(y) if sentence: break print('Parsed a', sentence, 'Sentence') print('Parsed Strings:', my_gps.gps_segments) print('Sentence CRC Value:', hex(my_gps.crc_xor)) print('Longitude:', my_gps.longitude) print('Latitude', my_gps.latitude) print('UTC Timestamp:', my_gps.timestamp) print('Speed:', my_gps.speed) print('Date Stamp:', my_gps.date) print('Course', my_gps.course) print('Data is Valid:', my_gps.valid) print('Compass Direction:', my_gps.compass_direction()) print('') for GLL_sentence in test_GLL: sentence_count += 1 for y in GLL_sentence: sentence = my_gps.update(y) if sentence: break print('Parsed a', sentence, 'Sentence') print('Parsed Strings', my_gps.gps_segments) print('Sentence CRC Value:', hex(my_gps.crc_xor)) print('Longitude:', my_gps.longitude) print('Latitude', my_gps.latitude) print('UTC Timestamp:', my_gps.timestamp) print('Data is Valid:', my_gps.valid) print('') for VTG_sentence in test_VTG: sentence_count += 1 for y in VTG_sentence: sentence = my_gps.update(y) if sentence: break print('Parsed a', sentence, 'Sentence') print('Parsed Strings', my_gps.gps_segments) print('Sentence CRC Value:', hex(my_gps.crc_xor)) print('Speed:', my_gps.speed) print('Course', my_gps.course) print('Compass Direction:', my_gps.compass_direction()) print('') for GGA_sentence in test_GGA: sentence_count += 1 for y in GGA_sentence: sentence = my_gps.update(y) if sentence: break print('Parsed a', sentence, 'Sentence') print('Parsed Strings', my_gps.gps_segments) print('Sentence CRC Value:', hex(my_gps.crc_xor)) print('Longitude', my_gps.longitude) print('Latitude', my_gps.latitude) print('UTC Timestamp:', my_gps.timestamp) print('Fix Status:', my_gps.fix_stat) print('Altitude:', my_gps.altitude) print('Height Above Geoid:', my_gps.geoid_height) print('Horizontal Dilution of Precision:', my_gps.hdop) print('Satellites in Use by Receiver:', my_gps.satellites_in_use) print('') for GSA_sentence in test_GSA: sentence_count += 1 for y in GSA_sentence: sentence = my_gps.update(y) if sentence: break print('Parsed a', sentence, 'Sentence') print('Parsed Strings', my_gps.gps_segments) print('Sentence CRC Value:', hex(my_gps.crc_xor)) print('Satellites Used', my_gps.satellites_used) print('Fix Type Code:', my_gps.fix_type) print('Horizontal Dilution of Precision:', my_gps.hdop) print('Vertical Dilution of Precision:', my_gps.vdop) print('Position Dilution of Precision:', my_gps.pdop) print('') for GSV_sentence in test_GSV: sentence_count += 1 for y in GSV_sentence: sentence = my_gps.update(y) if sentence: break print('Parsed a', sentence, 'Sentence') print('Parsed Strings', my_gps.gps_segments) print('Sentence CRC Value:', hex(my_gps.crc_xor)) print('SV Sentences Parsed', my_gps.last_sv_sentence) print('SV Sentences in Total', my_gps.total_sv_sentences) print('# of Satellites in View:', my_gps.satellites_in_view) data_valid = my_gps.satellite_data_updated() print('Is Satellite Data Valid?:', data_valid) if data_valid: print('Complete Satellite Data:', my_gps.satellite_data) print('Complete Satellites Visible:', my_gps.satellites_visible()) else: print('Current Satellite Data:', my_gps.satellite_data) print('Current Satellites Visible:', my_gps.satellites_visible()) print('') print("Pretty Print Examples:") print('Latitude:', my_gps.latitude_string()) print('Longitude:', my_gps.longitude_string()) print('Speed:', my_gps.speed_string('kph'), 'or', my_gps.speed_string('mph'), 'or', my_gps.speed_string('knot')) print('Date (Long Format):', my_gps.date_string('long')) print('Date (Short D/M/Y Format):', my_gps.date_string('s_dmy')) print('Date (Short M/D/Y Format):', my_gps.date_string('s_mdy')) print() print('### Final Results ###') print('Sentences Attempted:', sentence_count) print('Sentences Found:', my_gps.clean_sentences) print('Sentences Parsed:', my_gps.parsed_sentences) print('CRC_Fails:', my_gps.crc_fails)
# -*- coding: utf-8 -*- from pyb import UART from micropyGPS import MicropyGPS import os # somehow used to make open() work # Setup the connection to your GPS here # This example uses UART 3 with RX on pin Y10 # Baudrate is 9600bps, with the standard 8 bits, 1 stop bit, no parity uart_gps = UART(6, 9600) uart_bt = UART(1,9600) pyb.repl_uart(uart_bt) # REPL to bluetooth uart, useful for debuging with the phone # Instatntiate the micropyGPS object my_gps = MicropyGPS() def print_out(string): print(string) #uart_bt.write(string) try: log = open('/sd/log.txt','a') log.write(string+'\n') log.close() except: print('SD Error') #uart_bt.write('SD Error\n') # Continuous Tests for characters available in the UART buffer, any characters are feed into the GPS # object. When enough char are feed to represent a whole, valid sentence, stat is set as the name of the # sentence and printed
# Global Flag to start GPS data Processing new_data = False xbee = UART(1, 115200) start = pyb.millis() # Callback Function def pps_callback(line): # print("Updated GPS Object...") global new_data # Use Global to trigger update new_data = True # Instantiate the micropyGPS object my_gps = MicropyGPS() # Setup the connection to your GPS here uart = UART(6, 9600, read_buf_len=1000) # Create an external interrupt on pin X8 pps_pin = pyb.Pin.board.X8 extint = pyb.ExtInt(pps_pin, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, pps_callback) # Create relay object relay = Pin('Y5', Pin.OUT_PP) # Setup rtc timer to wake up pyboard every 30 seconds during standby to check # conditions # rtc = pyb.RTC()
from time import sleep from micropyGPS import MicropyGPS ######################### # Prerequisites # ######################### #create BMP180 object bmp180 = BMP180('X') bmp180.oversample_sett = 3 #0=low accuracy, 3=high accuracy bmp180.baseline = 101325 #pressure at main sea level #create GPS object my_gps = MicropyGPS() #set up transceiver to send data to ground station x3_pin = Pin('X3', Pin.OUT_PP) x3_pin.high() #create transceiver object on UART4 hc12 = UART(4, 9600) #create gps object on UART3 uart = UART(3, 9600) #feedback-pyboard on and working green = LED(2) green.on()
""" return (lat_NS[0] + lat_NS[1] / 60) * (1.0 if lat_NS[2] == 'N' else -1.0) blueLED = pyb.LED(4) # create object of blue LED # This example uses UART 3 with RX on pin Y10 # Baudrate is 9600bps, with the standard 8 bits, 1 stop bit, no parity uart = pyb.UART(3, 9600) # We can also have finer control over the serial communication uart.init(9600, bits=8, parity=None, stop=1, read_buf_len = 512) # Set up the GPS instance gps = MicropyGPS() blueLED.on() # turn on blue LED as indicator of logging # open file to write data - /sd/ is the SD-card, /flash/ is the internal memory with open('/sd/GPS_log.csv', 'w') as log: log.write('Time (ms), Longitude, Latitude, Heading, \ Speed (m/s), Number of Satellites\n') # write heading to file # Now we can read the data for until control-c is pressed start_time = pyb.millis() while pyb.elapsed_millis(start_time) < 60000: # log data for 60 seconds if uart.any(): valid_sentence_received = gps.update(chr(uart.readchar())) # Note the conversion to to chr, UART outputs ints normally if valid_sentence_received:
# micropyGPS Sentence Test # When properly connected to working GPS module, # will print the names of the sentences it receives # If you are having issues receiving sentences, use UART_test.py to ensure # your UART is hooked up and configured correctly from pyb import UART from micropyGPS import MicropyGPS # Setup the connection to your GPS here # This example uses UART 3 with RX on pin Y10 # Baudrate is 9600bps, with the standard 8 bits, 1 stop bit, no parity uart = UART(3, 9600) # Instatntiate the micropyGPS object my_gps = MicropyGPS() # Continuous Tests for characters available in the UART buffer, any characters are feed into the GPS # object. When enough char are feed to represent a whole, valid sentence, stat is set as the name of the # sentence and printed while True: if uart.any(): stat = my_gps.update(chr(uart.readchar())) # Note the conversion to to chr, UART outputs ints normally if stat: print(stat) stat = None
from pyb import UART from micropyGPS import MicropyGPS uart = UART(3, 9600) my_gps = MicropyGPS() # Reads 300 sentences and reports how many were parsed and if any failed the CRC check sentence_count = 0 while True: if uart.any(): stat = my_gps.update(chr(uart.readchar())) if stat: print(stat) stat = None sentence_count += 1 if sentence_count == 300: break; print('Sentences Found:', my_gps.clean_sentences) print('Sentences Parsed:', my_gps.parsed_sentences) print('CRC_Fails:', my_gps.crc_fails)