-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPython_json_arduino.py
91 lines (69 loc) · 2.35 KB
/
Python_json_arduino.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/python
# -*- coding: utf-8 -*-
# First basic build to read data from Arduino COM port
# We also try to write to csv now
# Initialize
from __future__ import division
import serial
#import sys
import time
#import csv
import json
from saveCSV import * # Custom script for saving CSV
from diagnostics import countPackets, packetContinuity
# Useful variables
mcuFreq = 100 # Microcontroller frequency, in Hz
mcuPeriod = 1 / mcuFreq # Python loop timing, in seconds
# Make serial connection
serial = serial.Serial("COM12", 115200, timeout=0)
if serial:
print('connected')
databuffer = []
dataprior1=0
dataprior2=0
# Run the loop until it crashes
while True:
# for i in range(0,10):connected
data = serial.readline()
# if data:
# print('Reading')
# data = serial.readline().strip('\n\r')
if len(data) > 1: # We only continue if we retrieve a line of data
# Next we should determine if we receive a complete line of data.
# Method one: Verify that string starts and ends with {}
# Method two: verify a specific line length if we know what we're expecting
print(data)
# print('\n')
if ( data[0]=='@') and data[-1] == '%':
# print('\n Complete')
# print(data)
# data = data[1:].strip('\n\r')
print 'valid string'
try:
j = json.loads(data) # Putting this within a try loop is an easy way to reject the mashed data JSON strings that crash the loops
if j:
print(j)
# Regular write method
# csv_success = WriteToCSVAccGyro(j) # Write to a CSV file
# print (csv_success)
# Try Buffer write method
databuffer.append(j) # Add to a buffer
print(len(databuffer))
if len(databuffer) > 100: # If buffer grows we will write to a file
# csv_success = WriteToCSVAccGyro(databuffer) # Write to a CSV file for MPU9250-Uno
csv_success = WriteToCSV(databuffer) # Saving for proto4 device data
print (csv_success)
databuffer = [] # Clear the buffer
else:
print 'JSON load problem'
except:
# This happens if the json file is formatted properly.
# print(data)
print('bad values')
# break # Break is discouraged because it will crash the whole script
# print ('\n')
# time.sleep(.5)
# look at past data values to
# dataprior2 = dataprior1
# dataprior1 = data
time.sleep(mcuPeriod) # Wait some time before reading again