first commit

This commit is contained in:
pandacraft 2025-03-21 16:04:17 +01:00
commit a5a0434432
1126 changed files with 439481 additions and 0 deletions

View file

@ -0,0 +1,74 @@
import serial, time
import smbus
import math
import RPi.GPIO as GPIO
import struct
import sys
ser = serial.Serial('/dev/ttyAMA0', 9600, timeout = 0) #Open the serial port at 9600 baud
ser.flush()
def readlineCR():
rv = ""
while True:
time.sleep(0.001) # This is the critical part. A small pause
# works really well here.
ch = ser.read()
rv += ch
if ch=='\r' or ch=='':
return rv
class GPS:
#The GPS module used is a Grove GPS module http://www.seeedstudio.com/depot/Grove-GPS-p-959.html
inp=[]
# Refer to SIM28 NMEA spec file http://www.seeedstudio.com/wiki/images/a/a0/SIM28_DATA_File.zip
GGA=[]
#Read data from the GPS
def read(self):
while True:
# GPS.inp=ser.readline()
GPS.inp = readlineCR().strip()
if GPS.inp[:6] =='$GPGGA': # GGA data , packet 1, has all the data we need
break
time.sleep(0.1)
try:
ind=GPS.inp.index('$GPGGA',5,len(GPS.inp)) #Sometimes multiple GPS data packets come into the stream. Take the data only after the last '$GPGGA' is seen
GPS.inp=GPS.inp[ind:]
except ValueError:
print ""
GPS.GGA=GPS.inp.split(",") #Split the stream into individual parts
return [GPS.GGA]
#Split the data into individual elements
def vals(self):
time=GPS.GGA[1]
lat=GPS.GGA[2]
lat_ns=GPS.GGA[3]
long=GPS.GGA[4]
long_ew=GPS.GGA[5]
fix=GPS.GGA[6]
sats=GPS.GGA[7]
alt=GPS.GGA[9]
return [time,fix,sats,alt,lat,lat_ns,long,long_ew]
g=GPS()
f=open("gps_data.csv",'w') #Open file to log the data
f.write("name,latitude,longitude\n") #Write the header to the top of the file
ind=0
while True:
try:
x=g.read() #Read from GPS
[t,fix,sats,alt,lat,lat_ns,long,long_ew]=g.vals() #Get the individial values
print "Time:",t,"Fix status:",fix,"Sats in view:",sats,"Altitude",alt,"Lat:",lat,lat_ns,"Long:",long,long_ew
s=str(t)+","+str(float(lat)/100)+","+str(float(long)/100)+"\n"
f.write(s) #Save to file
time.sleep(2)
except IndexError:
print "Unable to read"
except KeyboardInterrupt:
f.close()
print "Exiting"
sys.exit(0)
except:
print "Raw String appears to be empty."

View file

@ -0,0 +1,74 @@
## Using the [Grove GPS Module](http://www.seeedstudio.com/depot/Grove-GPS-p-959.html?cPath=25_130) with the GrovePi
### Setting It Up
On newer versions of the Raspberry Pi, the hardware serial port `/dev/ttyAMAO` which is used in our library, is actually set to be used by the bluetooth module, leaving the software implementation `/dev/ttyS0` (aka mini UART) to the actual pins of the serial line.
The problem with this mini UART is that it's too slow for what we need, so we have to switch them so that the hardware serial points to our serial pins.
To do that, add/modify these lines to `/boot/config.txt`
```bash
dtoverlay=pi3-miniuart-bt
dtoverlay=pi3-disable-bt
enable_uart=1
```
Next, remove the 2 console statements from `/boot/cmdline.txt`.
Initially, `/boot/cmdline.txt` might look this way:
```
dwc_otg.lpm_enable=0 console=serial0,115200 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes root wait
```
After you remove the 2 statements, it should be like this:
```
dwc_otg.lpm_enable=0 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes root wait
```
Once you've done these 2 steps from above, a reboot will be required. Do it now, and then proceed to the next section.
For more information on how the serial ports are set up, you can [read this article](https://spellfoundry.com/2016/05/29/configuring-gpio-serial-port-raspbian-jessie-including-pi-3/#Disabling_the_Console).
### Running it
To run the GPS script, you need to have followed the instructions in the previous section and have connected the [Grove GPS Module](http://www.seeedstudio.com/depot/Grove-GPS-p-959.html?cPath=25_130) to the **RPIser** port of the GrovePi.
The script can be either launched with Python 2 or Python 3.
```bash
sudo python dextergps.py
```
or
```bash
sudo python3 dextergps.py
```
The output of any of these 2 commands looks this way:
```bash
['$GPGGA', '150954.000', '4520.7858', 'N', '02557.6659', 'E', '1', '5', '2.84', '76.9', 'M', '36.1', 'M', '', '*6E']
['$GPGGA', '150955.000', '4520.7859', 'N', '02557.6655', 'E', '1', '5', '2.84', '77.0', 'M', '36.1', 'M', '', '*6A']
['$GPGGA', '150956.000', '4520.7861', 'N', '02557.6652', 'E', '1', '5', '2.85', '77.0', 'M', '36.1', 'M', '', '*64']
['$GPGGA', '150957.000', '4520.7861', 'N', '02557.6645', 'E', '1', '4', '2.90', '77.1', 'M', '36.1', 'M', '', '*67']
['$GPGGA', '150958.000', '4520.7861', 'N', '02557.6645', 'E', '1', '4', '2.90', '77.1', 'M', '36.1', 'M', '', '*68']
['$GPGGA', '150959.000', '4520.7861', 'N', '02557.6645', 'E', '1', '4', '2.90', '77.1', 'M', '36.1', 'M', '', '*69']
['$GPGGA', '151000.000', '4520.7861', 'N', '02557.6645', 'E', '1', '4', '2.90', '77.1', 'M', '36.1', 'M', '', '*6D']
['$GPGGA', '151001.000', '4520.7861', 'N', '02557.6645', 'E', '1', '4', '2.90', '77.1', 'M', '36.1', 'M', '', '*6C']
['$GPGGA', '151002.000', '4520.7863', 'N', '02557.6618', 'E', '1', '4', '2.90', '77.5', 'M', '36.1', 'M', '', '*61']
['$GPGGA', '151003.000', '4520.7864', 'N', '02557.6612', 'E', '1', '4', '2.90', '77.6', 'M', '36.1', 'M', '', '*6E']
['$GPGGA', '151004.000', '4520.7865', 'N', '02557.6606', 'E', '1', '4', '2.90', '77.6', 'M', '36.1', 'M', '', '*6D']
['$GPGGA', '151005.000', '4520.7865', 'N', '02557.6597', 'E', '1', '4', '2.90', '77.6', 'M', '36.1', 'M', '', '*67']
['$GPGGA', '151006.000', '4520.7865', 'N', '02557.6588', 'E', '1', '4', '2.90', '77.6', 'M', '36.1', 'M', '', '*6A']
```
### Regarding the Library
**gps.lat** and **gps.NS** go hand in hand, so do **gps.lon** and **gps.EW**
**gps.latitude** and **gps.longitude** are calculated to give you a Google Map appropriate format and make use of negative numbers to indicate either South or West
*Note*:
You would only get good data when fix is 1 and you have 3 or more satellites in view. You might have to take the module near a window with access to open sky for good results
### Old GPS Scripts
`dextergps.py` is the new go-to script for getting values off of the Grove GPS module. The old ones that are no longer used but are kept in here for legacy reasons are:
* [grove_gps_data.py](grove_gps_data.py)
* [grove_gps_hardware_test.py](grove_gps_hardware_test.py)
* [GroveGPS.py](GroveGPS.py)

View file

@ -0,0 +1,168 @@
# Released under the MIT license (http://choosealicense.com/licenses/mit/).
# For more information see https://github.com/DexterInd/GrovePi/blob/master/LICENSE
import grovepi
import serial, time, sys
import re
en_debug = False
def debug(in_str):
if en_debug:
print(in_str)
patterns=["$GPGGA",
"/[0-9]{6}\.[0-9]{2}/", # timestamp hhmmss.ss
"/[0-9]{4}.[0-9]{2,/}", # latitude of position
"/[NS]", # North or South
"/[0-9]{4}.[0-9]{2}", # longitude of position
"/[EW]", # East or West
"/[012]", # GPS Quality Indicator
"/[0-9]+", # Number of satellites
"/./", # horizontal dilution of precision x.x
"/[0-9]+\.[0-9]*/" # altitude x.x
]
class GROVEGPS():
def __init__(self, port='/dev/ttyAMA0', baud=9600, timeout=0):
self.ser = serial.Serial(port, baud, timeout=timeout)
self.ser.flush()
self.raw_line = ""
self.gga = []
self.validation =[] # contains compiled regex
# compile regex once to use later
for i in range(len(patterns)-1):
self.validation.append(re.compile(patterns[i]))
self.clean_data()
# self.get_date() # attempt to gete date from GPS.
def clean_data(self):
'''
clean_data:
ensures that all relevant GPS data is set to either empty string
or -1.0, or -1, depending on appropriate type
This occurs right after initialisation or
after 50 attemps to reach GPS
'''
self.timestamp = ""
self.lat = -1.0 # degrees minutes and decimals of minute
self.NS = ""
self.lon = -1.0
self.EW = ""
self.quality = -1
self.satellites = -1
self.altitude = -1.0
self.latitude = -1.0 #degrees and decimals
self.longitude = -1.0
self.fancylat = "" #
# def get_date(self):
# '''
# attempt to get date from GPS data. So far no luck. GPS does
# not seem to send date sentence at all
# function is unfinished
# '''
# valid = False
# for i in range(50):
# time.sleep(0.5)
# self.raw_line = self.ser.readline().strip()
# if self.raw_line[:6] == "GPZDA": # found date line!
# print (self.raw_line)
def read(self):
'''
Attempts 50 times at most to get valid data from GPS
Returns as soon as valid data is found
If valid data is not found, then clean up data in GPS instance
'''
valid = False
for _ in range(50):
time.sleep(0.5)
self.raw_line = self.ser.readline()
try:
self.line = self.raw_line.decode('utf-8')
self.line = self.line.strip()
except:
self.line = ""
debug(self.line)
if self.validate(self.line):
valid = True
break
if valid:
return self.gga
else:
self.clean_data()
return []
def validate(self, in_line):
'''
Runs regex validation on a GPGAA sentence.
Returns False if the sentence is mangled
Return True if everything is all right and sets internal
class members.
'''
if in_line == "":
return False
if in_line[:6] != "$GPGGA":
return False
self.gga = in_line.split(",")
debug (self.gga)
#Sometimes multiple GPS data packets come into the stream. Take the data only after the last '$GPGGA' is seen
try:
ind=self.gga.index('$GPGGA', 5, len(self.gga))
self.gga=self.gga[ind:]
except ValueError:
pass
if len(self.gga) != 15:
debug ("Failed: wrong number of parameters ")
debug (self.gga)
return False
for i in range(len(self.validation)-1):
if len(self.gga[i]) == 0:
debug ("Failed: empty string %d"%i)
return False
test = self.validation[i].match(self.gga[i])
if test == False:
debug ("Failed: wrong format on parameter %d"%i)
return False
else:
debug("Passed %d"%i)
try:
self.timestamp = self.gga[1]
self.lat = float(self.gga[2])
self.NS = self.gga[3]
self.lon = float(self.gga[4])
self.EW = self.gga[5]
self.quality = int(self.gga[6])
self.satellites = int(self.gga[7])
self.altitude = float(self.gga[9])
self.latitude = self.lat // 100 + self.lat % 100 / 60
if self.NS == "S":
self.latitude = - self.latitude
self.longitude = self.lon // 100 + self.lon % 100 / 60
if self.EW == "W":
self.longitude = -self.longitude
except ValueError:
debug( "FAILED: invalid value")
return True
if __name__ =="__main__":
gps = GROVEGPS()
while True:
time.sleep(1)
in_data = gps.read()
if in_data != []:
print (in_data)

View file

@ -0,0 +1,192 @@
#!/usr/bin/env python
#
# GrovePi Example for using the Grove GPS Module http://www.seeedstudio.com/depot/Grove-GPS-p-959.html?cPath=25_130
#
# The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
#
# Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
#
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
# History
# ------------------------------------------------
# Author Date Comments
# Karan 21 Aug 14 Initial Authoring
# Karan 10 June 15 Updated the code to reflect the decimal GPS coordinates (contributed by rschmidt on the DI forums: http://www.dexterindustries.com/forum/?topic=gps-example-questions/#post-5668)
# Karan 18 Mar 16 Updated code to handle conditions where no fix from satellite
#
#
#####################################################
#
# GPS SENSOR GOES INTO RPISER PORT
#
#####################################################
#
import serial, time
import smbus
import math
import RPi.GPIO as GPIO
import struct
import sys
import ir_receiver_check
enable_debug=1
enable_save_to_file=0
if ir_receiver_check.check_ir():
print("Disable IR receiver before continuing")
exit()
ser = serial.Serial('/dev/ttyAMA0', 9600, timeout = 0) #Open the serial port at 9600 baud
ser.flush()
def cleanstr(in_str):
out_str = "".join([c for c in in_str if c in "0123456789.-" ])
if len(out_str)==0:
out_str = "-1"
return out_str
def safefloat(in_str):
try:
out_str = float(in_str)
except ValueError:
out_str = -1.0
return out_str
class GPS:
#The GPS module used is a Grove GPS module http://www.seeedstudio.com/depot/Grove-GPS-p-959.html
inp=[]
# Refer to SIM28 NMEA spec file http://www.seeedstudio.com/wiki/images/a/a0/SIM28_DATA_File.zip
GGA=[]
#Read data from the GPS
def read(self):
while True:
GPS.inp=ser.readline()
if GPS.inp[:6] =='$GPGGA': # GGA data , packet 1, has all the data we need
break
time.sleep(0.1) #without the cmd program will crash
try:
ind=GPS.inp.index('$GPGGA',5,len(GPS.inp)) #Sometimes multiple GPS data packets come into the stream. Take the data only after the last '$GPGGA' is seen
GPS.inp=GPS.inp[ind:]
except ValueError:
print ("")
GPS.GGA=GPS.inp.split(",") #Split the stream into individual parts
return [GPS.GGA]
#Split the data into individual elements
def vals(self):
if enable_debug:
print(GPS.GGA)
time=GPS.GGA[1]
if GPS.GGA[2]=='': # latitude. Technically a float
lat =-1.0
else:
lat=safefloat(cleanstr(GPS.GGA[2]))
if GPS.GGA[3]=='': # this should be either N or S
lat_ns=""
else:
lat_ns=str(GPS.GGA[3])
if GPS.GGA[4]=='': # longitude. Technically a float
long=-1.0
else:
long=safefloat(cleanstr(GPS.GGA[4]))
if GPS.GGA[5]=='': # this should be either W or E
long_ew=""
else:
long_ew=str(GPS.GGA[5])
fix=int(cleanstr(GPS.GGA[6]))
sats=int(cleanstr(GPS.GGA[7]))
if GPS.GGA[9]=='':
alt=-1.0
else:
# change to str instead of float
# 27"1 seems to be a valid value
alt=str(GPS.GGA[9])
return [time,fix,sats,alt,lat,lat_ns,long,long_ew]
# Convert to decimal degrees
def decimal_degrees(self, raw_degrees):
try:
degrees = float(raw_degrees) // 100
d = float(raw_degrees) % 100 / 60
return degrees + d
except:
return raw_degrees
if __name__ == "__main__":
g=GPS()
if enable_save_to_file:
f=open("gps_data.csv",'w') #Open file to log the data
f.write("name,latitude,longitude\n") #Write the header to the top of the file
ind=0
while True:
time.sleep(0.01)
try:
x=g.read() #Read from GPS
[t,fix,sats,alt,lat,lat_ns,longitude,long_ew]=g.vals() #Get the individial values
# Convert to decimal degrees
if lat !=-1.0:
lat = g.decimal_degrees(safefloat(lat))
if lat_ns == "S":
lat = -lat
if longitude !=-1.0:
longitude = g.decimal_degrees(safefloat(longitude))
if long_ew == "W":
longitude = -longitude
# print ("Time:",t,"Fix status:",fix,"Sats in view:",sats,"Altitude",alt,"Lat:",lat,lat_ns,"Long:",long,long_ew)
try:
print("Time\t\t: %s\nFix status\t: %d\nSats in view\t: %d\nAltitude\t: %s\nLat\t\t: %f\nLong\t\t: %f") %(t,fix,sats,alt,lat,longitude)
except:
print("Time\t\t: %s\nFix status\t: %s\nSats in view\t: %s\nAltitude\t: %s\nLat\t\t: %s\nLong\t\t: %s") %(t,str(fix),str(sats),str(alt),str(lat),str(longitude))
s=str(t)+","+str(safefloat(lat)/100)+","+str(safefloat(longitude)/100)+"\n"
if enable_save_to_file:
f.write(s) #Save to file
time.sleep(2)
except IndexError:
print ("Unable to read")
except KeyboardInterrupt:
if enable_save_to_file:
f.close()
print ("Exiting")
sys.exit(0)

View file

@ -0,0 +1,85 @@
#!/usr/bin/env python
########################################################################
# This example is for is the simplest GPS Script. It reads the
# raw output of the GPS sensor on the GoPiGo or GrovePi and prints it.
#
# GPS SENSOR GOES INTO RPISER PORT
#
#####################################################
#
# http://www.dexterindustries.com/GoPiGo/
# http://www.dexterindustries.com/GrovePi/
# History
# ------------------------------------------------
# Author Date Comments
# John 2/25/2015 Initial Authoring
# John 6/17/2016 Add some comments.
#
# These files have been made available online through a Creative Commons Attribution-ShareAlike 3.0 license.
# (http://creativecommons.org/licenses/by-sa/3.0/)
#
########################################################################
import serial, time
import smbus
import math
import RPi.GPIO as GPIO
import struct
import sys
import ir_receiver_check
if ir_receiver_check.check_ir():
print("Disable IR receiver before continuing")
exit()
ser = serial.Serial('/dev/ttyAMA0', 9600, timeout = 0) #Open the serial port at 9600 baud
ser.flush()
def readlineCR():
rv = ""
while True:
time.sleep(0.01) # This is the critical part. A small pause
# works really well here.
ch = ser.read()
rv += ch
if ch=='\r' or ch=='':
return rv
while True:
#readlineCR()
x=readlineCR()
print(x)
########################################################################
#
# The output should look like something below.
#
#
########################################################################
'''
$GPGGA,001929.799,,,,,0,0,,,M,,M,,*4C
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
$GPGSV,1,1,00*79
$GPRMC,001929.799,V,,,,,0.00,0.00,060180,,,N*46
$GPGGA,001930.799,,,,,0,0,,,M,,M,,*44
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
$GPGSV,1,1,00*79
$GPRMC,001930.799,V,,,,,0.00,0.00,060180,,,N*4E
$GPGGA,001931.799,,,,,0,0,,,M,,M,,*45
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
$GPGSV,1,1,00*79
$GPRMC,001931.799,V,,,,,0.00,0.00,060180,,,N*4F
$GPGGA,001932.799,,,,,0,0,,,M,,M,,*46
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
$GPGSV,1,1,00*79
$GPRMC,001932.799,V,,,,,0.00,0.00,060180,,,N*4C
$GPGGA,001933.799,,,,,0,0,,,M,,M,,*47
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
$GPGSV,1,1,00*79
$GPRMC,001933.799,V,,,,,0.00,0.00,060180,,,N*4D
$GPGGA,001934.799,,,,,0,0,,,M,,M,,*40
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
$GPGSV,1,1,00*79
$GPRMC,001934.799,V,,,,,0.00,0.00,060180,,,N*4A
$GPGGA,001935.799,,,,,0,0,,,M,,M,,*41
'''