Search code examples
pythonfloating-pointintegergpsmultiplication

Issue multiplying a floating value


I am new to python so I appreciate your help! I am writing a simple code to read GPS data and print the speed value. The gps sends serial lines of text like this:

$GNRMC,055945.00,A,3509.40388,N,10642.56412,W,0.080,,060321,,,D*72
$GNVTG,,T,,M,0.080,N,0.148,K,D*3D
$GNGGA,055945.00,3509.40388,N,10642.56412,W,2,12,0.64,1581.1,M,-23.9,M,,0000*4E
$GNGSA,A,3,29,05,18,15,13,20,23,25,51,46,26,16,1.20,0.64,1.02*1E
$GNGSA,A,3,65,87,88,72,66,79,81,,,,,,1.20,0.64,1.02*10

and my code currently looks for the correct line and the correct value using if statements:

import serial
import time

gps = serial.Serial("/dev/serial0", baudrate = 9600)

while True:
       line = gps.readline()
       data = line.decode().split(",")
       if data[0] == "$GNRMC":
               if data[2] == "A":
                       if data[4] == "N":
                               if data[6] =="W":
                                       knotdata = data[7]
                                       mphdata = knotdata * 1.15
                                       print(mphdata)

however I am getting the following error:

Traceback (most recent call last):
File "txgpsreadconv.py", line 15, in <module>
   mphdata = knotdata * 1.15
TypeError: can't multiply sequence by non-int of type 'float'

I have tried many different approaches to rectify the issue with no success. I'm sure the solution is simple and I just don't have enough experience to figure it out, so your help is much appreciated!


Solution

  • The traceback is suggesting that knotdata is a sequence, which is not a data type that can be multiplied by a floating point number.

    Essentially you're trying to multiply a string that represents a numeric value instead of the value itself, so you should do a casting before the operation:

    knotdata = float(data[7])
    

    Also you can improve the structure of your if statements like this:

    if data[0:8:2] == ["$GRNMC", "A", "N", "W"]:
        print(float(data[7]) * 1.15)