diff --git a/3-transport/lessons/1-location-tracking/code-gps-decode/pi/gps-sensor/app.py b/3-transport/lessons/1-location-tracking/code-gps-decode/pi/gps-sensor/app.py index a5de919..098e1d8 100644 --- a/3-transport/lessons/1-location-tracking/code-gps-decode/pi/gps-sensor/app.py +++ b/3-transport/lessons/1-location-tracking/code-gps-decode/pi/gps-sensor/app.py @@ -22,10 +22,14 @@ def print_gps_data(line): print(f'{lat},{lon} - from {msg.num_sats} satellites') while True: - line = serial.readline().decode('utf-8') + try: + line = serial.readline().decode('utf-8') + + while len(line) > 0: + print_gps_data(line) + line = serial.readline().decode('utf-8') - while len(line) > 0: - print_gps_data(line) + except UnicodeDecodeError: line = serial.readline().decode('utf-8') time.sleep(1) diff --git a/3-transport/lessons/1-location-tracking/code-gps/pi/gps-sensor/app.py b/3-transport/lessons/1-location-tracking/code-gps/pi/gps-sensor/app.py index 0dfad1e..11963a4 100644 --- a/3-transport/lessons/1-location-tracking/code-gps/pi/gps-sensor/app.py +++ b/3-transport/lessons/1-location-tracking/code-gps/pi/gps-sensor/app.py @@ -9,10 +9,14 @@ def print_gps_data(): print(line.rstrip()) while True: - line = serial.readline().decode('utf-8') + try: + line = serial.readline().decode('utf-8') + + while len(line) > 0: + print_gps_data() + line = serial.readline().decode('utf-8') - while len(line) > 0: - print_gps_data() + except UnicodeDecodeError: line = serial.readline().decode('utf-8') time.sleep(1) diff --git a/3-transport/lessons/1-location-tracking/pi-gps-sensor.md b/3-transport/lessons/1-location-tracking/pi-gps-sensor.md index 01148da..8344dc1 100644 --- a/3-transport/lessons/1-location-tracking/pi-gps-sensor.md +++ b/3-transport/lessons/1-location-tracking/pi-gps-sensor.md @@ -149,13 +149,31 @@ Program the device. $BDGSV,1,1,00*68 ``` - > If you get one of the following errors when stopping and restarting your code, kill the VS Code terminal, then launch a new one and try again. + > If you get one of the following errors when stopping and restarting your code, add a `try - except` block to your while loop. ```output UnicodeDecodeError: 'utf-8' codec can't decode byte 0x93 in position 0: invalid start byte UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1 in position 0: invalid continuation byte ``` + ```python + while True: + try: + line = serial.readline().decode('utf-8') + + while len(line) > 0: + print_gps_data() + line = serial.readline().decode('utf-8') + + # There's a random chance the first byte being read is part way through a character. + # Read another full line and continue. + + except UnicodeDecodeError: + line = serial.readline().decode('utf-8') + + time.sleep(1) + ``` + > 💁 You can find this code in the [code-gps/pi](code-gps/pi) folder. 😀 Your GPS sensor program was a success!