1

I have a a micro controller which is sending data over serial to a python program. However it crashes with the following when I run in terminal:

{"id" : 43 ,"light" : 0, "temperature" : 2778}
Shutdown
Expecting value: line 1 column 1 (char 0)

The C code where it sends over USART:

printf("{\"id\" : %u ,\"Light\" : %u, \"Temperature\" : %u}\n\r", counter++, lightVal, tempVal);

And My python code:

    s = serial.Serial(port = '/dev/tty.usbserial-DA005A79', baudrate = 115200) # Zigduino 

def read_loop(self):
        try:
            t = 0
            output = ''
            print 'starting'
            while self.read_data:
                time.sleep(0.05)
                data = s.read();
                if len(data) > 0:
                    output += data
                    if (data[-1]=='\n'):
                        print output
                        values = simplejson.loads(output)       
                        t += 0.2
                        output = ''
        except Exception, e:
            print "Shutdown"
            print str(e)
            exit()

An example of what it prints if I connect through serial and print (values are fine):

{"id" : 2 ,"light" : 1, "temperature" : 2665}
{"id" : 3 ,"light" : 0, "temperature" : 2665}
{"id" : 4 ,"light" : 0, "temperature" : 2665}
{"id" : 5 ,"light" : 0, "temperature" : 2665}
{"id" : 6 ,"light" : 0, "temperature" : 2778}
{"id" : 7 ,"light" : 0, "temperature" : 2778}
{"id" : 8 ,"light" : 0, "temperature" : 2665}
{"id" : 9 ,"light" : 0, "temperature" : 2665}

I have looked at JSONDecodeError: Expecting value: line 1 column 1 (char 0) and Python - ValueError: Expecting value: line 1 column 1 (char 0) but they haven't really helped. And judging the notation here: http://jsonformatter.curiousconcept.com it should be ok?

EDIT: I have tried with and without the '\r' at the end.

Community
  • 1
  • 1
jnd
  • 754
  • 9
  • 20
  • Why not simply do`s.readline()` in loop? And what is `s` in this context? It could be buffered, so no guarantee, that read() will return string with line boundaries. – myaut Mar 22 '15 at 12:36
  • Oops s is the serial object. I forgot to copt that line – jnd Mar 22 '15 at 20:00
  • Try `print repr(output)`. Based on what you've shown, I can't see how, but you might find an unexpected unprintable character at the beginning of the string. – mhawke Mar 22 '15 at 23:45
  • It prints the following: {"id" : 419 ,"light" : 0, "temperature" : 3117} '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00{"id" : 419 ,"light" : 0, "temperature" : 3117}\n' – jnd Mar 24 '15 at 04:11

0 Answers0