RFduino not pulling NMEA strings from GPS - gps

I'm having trouble using the TinyGPS library to parse Lat and Lon. Is this library compatible with the RFduino? I can read NMEA strings by loading a blank sketch to the RFduino and then just opening the Serial Monitor, so I know that the GPS data is going through the serial port, but when I try to get the Lat or Lon into a variable, it fills the variable with 999999999. I'm sending this data through BLE to an android. If I don't try to get GPS data, I can send any value I want in the lat or lon variables and it appears in my custom Android App. I read somewhere that the softserial library doesn't work on rfduino. Is this true? If not, I would be able to print my data through the hard serial port, making troubleshooting much easier. Below I've attached the code I'm using on my RFduino. Any advice would be appreciated.
// CODE //
#include <RFduinoBLE.h>
#include <TinyGPS.h>
TinyGPS gps;
long lat = 5; //Load lat/lon with junk value for testing
long lon = 6;
char latBuf[20];
char lonBuf[20];
void setup() {
// this is the data we want to appear in the advertisement
// (if the deviceName and advertisementData are too long to fix into the 31 byte
// ble advertisement packet, then the advertisementData is truncated first down to
// a single byte, then it will truncate the deviceName)
RFduinoBLE.advertisementData = "ledbtn";
// start the BLE stack
RFduinoBLE.begin();
Serial.begin(9600);//For GPS Communication
}
void loop(){
char c = byte(Serial.read());
gps.encode(c);
gps.get_position(&lat,&lon); // get latitude and longitude
// send position as char[]
String latString = String(lat);
String lonString = String(lon);
latString.toCharArray(latBuf, 20);
lonString.toCharArray(lonBuf, 20);
RFduinoBLE.send(lonBuf, 20);
}
void RFduinoBLE_onDisconnect()
{
}
void RFduinoBLE_onReceive(char *data, int len)
{
RFduinoBLE.send(lonBuf, 20);
}

One problem I see: the loop() is trying to read out the GPS coordinates every time loop is executed. This approach has two problems: 1) the loop doesn't wait until serial data is ready, and 2) the loop doesn't wait until the received GPS data is valid.
From reading http://arduino.cc/en/Tutorial/ReadASCIIString and http://arduiniana.org/libraries/tinygps/ I recommend rewriting loop() to something like this:
loop() {
char c;
float fLat, fLon;
unsigned long fix_age;
static unsigned long previous_fix_age = 0;
// If nothing to read; do nothing.
// Read as many characters as are available.
while (Serial.available() > 0) {
// Tell the GPS library about the new character.
c = Serial.read();
gps.encode(c);
gps.f_get_position(&flat, &flon, &fix_age);
if (fix_age != TinyGPS::GPS_INVALID_AGE && fix_age != previous_fix_age) {
// new GPS data is valid, new, and ready to be printed
previous_fix_age = fix_age; // remember that we've reported this data.
String latString = String(lat);
...the rest of the code you already have to print the lat and lon.
}
}
}
The code about previous_fix_age is there so that the loop prints coordinates only when a new fix has been received from the GPS.

Related

STM32 reading variables out of Received Buffer with variable size

I am not really familiar with programming in STM32. I am using the micro controller STM32F303RE.
I am receiving data via a UART connection with DMA.
Code:
HAL_UARTEx_ReceiveToIdle_DMA(&huart2, RxBuf, RxBuf_SIZE);
__HAL_DMA_DISABLE_IT(&hdma_usart2_rx, DMA_IT_HT);
I am writing the value into a Receiving Buffer and then transfer it into a main buffer. This function and declaration is down before the int main(void).
#define RxBuf_SIZE 100
#define MainBuf_Size 100
uint8_t RxBuf[RxBuf_SIZE];
uint8_t MainBuf[MainBuf_Size];
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart,uint16_t Size){
if( huart -> Instance == USART2){
memcpy (MainBuf, RxBuf, Size);
HAL_UARTEx_ReceiveToIdle_DMA(&huart2, RxBuf, RxBuf_SIZE);
}
for (int i = 0; i<Size; i++){
if((MainBuf[i] == 'G') && (MainBuf[i+1] == 'O')){
RecieveData();
HAL_UART_DMAStop(&huart2);
}
}
}
I receive know the data into a buffer and it stops as soon as "GO" is transmitted. Until this point it is working. The function ReceiveData() should then transform this buffer to the variables. But it isn't working for me.
Now I want to transform this received data with "breakpoints" into variables.
So I want to send: "S2000S1000S1S10S2GO".
I always have 5 variables. (in this case: 2000, 1000, 1, 10, 2) I want to read the data out of the string and transform it into an uint16_t to procude. The size/ length of the variables could be changed. That's why I tried to use like some breakpoint.

random corrupted data in serial Arduino

I have issue to read serial data from Arduino Uno in UWP C#. Sometimes when I start app I get corrupted data.
But in arduino monitor always is good.
Corrupted data is like this:
57
5
But should be 557.
Arduino codes:
String digx, digx2, digx3, digx1 ;
void setup() {
delay(500);
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(A1);
sensorValue = map(sensorValue, 0, 1024, 0, 999);
digx1 = String(sensorValue % 10);
digx2 = String((sensorValue / 10) % 10);
digx3 = String((sensorValue / 100) % 10);
digx = (digx3 + digx2 + digx1);
Serial.println(digx);
Serial.flush();
delay(100);
}
And windows universal codes:
public sealed partial class MainPage : Page
{
public DataReader dataReader;
public SerialDevice serialPort;
private string data;
private async void InitializeConnection()
{
var aqs = SerialDevice.GetDeviceSelectorFromUsbVidPid(0x2341, 0x0043);
var info = await DeviceInformation.FindAllAsync(aqs);
serialPort = await SerialDevice.FromIdAsync(info[0].Id);
Thread.Sleep(100);
serialPort.DataBits = 8;
serialPort.BaudRate = 9600;
serialPort.Parity = SerialParity.None;
serialPort.Handshake = SerialHandshake.None;
serialPort.StopBits = SerialStopBitCount.One;
serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
Thread.Sleep(100);
dataReader = new DataReader(serialPort.InputStream);
while (true)
{
await ReadAsync();
}
}
private async Task ReadAsync()
{
try
{
uint readBufferLength = 5;
dataReader.InputStreamOptions = InputStreamOptions.Partial;
//dataReader.UnicodeEncoding = UnicodeEncoding.Utf8;
var loadAsyncTask = dataReader.LoadAsync(readBufferLength).AsTask();
var ReadAsyncBytes = await loadAsyncTask;
if (ReadAsyncBytes > 0)
{
data = dataReader.ReadString(ReadAsyncBytes);
serialValue.Text = data;
}
}
catch (Exception e)
{
}
}
}
My idea was if it happened, Program skip that data. I tried different buffer length but more or less than 5 will always receive incorrect.
Thanks for any help.
Two methods that can fix your problem.
Method1: Make your UART communication robust
That there is no chance of an error but this is a tricky and time-consuming task in the case of windows software communicating with Arduino.
But still have some tricks which can help you because I have tried them and some of them work but please don't ask for the reason why it works.
Change your UART baud rate from 9600 to something else (mine if works perfect at 38400).
Replace Serial.begin(9600); to Serial.begin(38400,SERIAL_8N1)where 8 is data bit, 1 is stop bit and N is parity none in SERIAL_8N1. And you can also try different settings in data bit, stop bit, and parity. check here
don't send data after converting it into a string Serial.println(digx);. Send data in form of bytes array use Serial.write(digx,len);. check here
Method2: Add CRC Packet
At the end of each data packet and then send. When it reaches the windows software first fetch all UART data then calculate CRC from that data and then just compare calculated CRC and received CRC.If CRC matches then the data is correct and if not then ignore data and wait for new data.
you can check for CRC calculation its direct formula base implement and for little head start check this library by vinmenn.
I used two things to fix the problem,
1. In Windows codes added SerialDevice.IsDataTerminalReadyEnabled = true property to read bytes with correct order. From Microsoft docs
Here's a link!
2. As dharmik helped, I used array and send it with Serial.write(array, arrayLength) in Arduino and read them with dataReader.ReadBytes(array[]) and right buffer size in Windows app.
And result is so stable even with much lower Delays.

Arduino - Reading Serial Data

I am trying to send information to an Arduino Mega 2560 using serial data in order to control both LED Pixel Strips and conventional christmas light strings. I am also using VIXEN lighting software.
I can control one strip of LED pixels from Vixen using this code in the Arduino loop() function;
Serial.readBytes((char*)leds, NUM_LEDS * 3);//buffer to store things in, length (number of bytes to read)
FastLED.show();//refresh the pixel LED's
I can also control a relay (or multiple relays) for the conventional lights using this code;
#define CHANNEL_01 7 //Pin #7 on the Arduino Mega board
void setup()
{
// Begin serial communication
Serial.begin(BAUD_RATE);
#define CHANNEL_COUNT 1
int channels[] = {CHANNEL_01}
int incomingByte[16];
// Define baud rate. This figure must match that of your profile configuration in Vixen!
#define BAUD_RATE 9600
// Set up each channel as an output
for(int i = 0; i < CHANNEL_COUNT; i++)
{
pinMode(channels[i], OUTPUT);
}
}
void loop()
{
if (Serial.available() >= CHANNEL_COUNT)
{
// Read data from Vixen, store in array
for (int i = 0; i < CHANNEL_COUNT; i++)
{
incomingByte[i] = Serial.read();
}
// Write data from array to a pin on Arduino
for (int i = 0; i < CHANNEL_COUNT; i++)
{
digitalWrite(channels[i], incomingByte[i]);
}
}
}
The problem is that I cannot do both of these things. I can either assign the 150 bytes of LED data to the LED strip and it works fine, OR, I can run the relays and they work fine. I have not been able to figure out how to chop up the bytes from the serial data and send it to the appropriate pin. For example, maybe I want to control a relay using pin 7 and a strip of LED pixels using pin 6.
The strip of pixel LED's consumes the first 150 bytes of data from the serial data. But how can I get the next one byte that controls a relay that turns on and off the conventional christmas light string? The byte that controls the light string would be the 151'st in the serial data. Is there a way to specify the 151'st byte? Serial.read() does nothing more than read the first byte (I think). How can a user iterate through the bytes of serial data and select only the ones they want?
When you do the Serial.readBytes((char*)leds, NUM_LEDS * 3); you read the first 150 bytes, assuming you have 50 LEDs. So the next byte pending in the serial buffer would be the 151'st byte, therefore if you call Serial.read() after Serial.readBytes((char*)leds, NUM_LEDS * 3); you would get that byte.
Note that you can use one byte to controle 8 relays if you want, one bit per relay, by using bitRead()
An example.
bool relayState[8];
Serial.readBytes((char*)leds, NUM_LEDS * 3);
byte relays = Serial.read();
for(byte i=0;i<8;i++){
relayState[i] = bitRead(relays, i);
}
for(byte i=0;i<8;i++) {
digitalWrite(relay[i], relayState[i]);
}
Then a value of 1 would turn on relay 0, a value of 2 would turn on relay 1, a value of 3 would turn on relay 0 and relay 1, etc.
To solve this problem I bought an Arduino Uno to run the standard (non-LED) lights separate from the LED lights which run off an Arduino MEGA 2560. The non-LED lights are run on one controller in the Vixen Lights software. The controller has 4 outputs (channels), one for each of the non-LED light sets. Each channel will control one line on a solid state relay. The Arduino Uno runs the relays using this code;
#define PIN1 7 //Pin number seven
#define PIN2 6 //Pin number six
#define PIN3 5 //Pin number five
#define PIN4 4 //Pin number four
#define BAUD_RATE 9600 //just running 4 relay switches so we don't need much speed
#define CHANNEL_COUNT 4 //there are 4 channels coming from the Vixen controller
int bt[4]; //a variable we will use in the loop section of code
int x; //another variable we will use in the loop section of code
void setup() {
delay(1000); //a little delay to give Uno some time on startup
Serial.begin(BAUD_RATE); //set the baud rate of the serial stream
pinMode(PIN1, OUTPUT); //set the four pins on the Arduino Uno to output
pinMode(PIN2, OUTPUT);
pinMode(PIN3, OUTPUT);
pinMode(PIN4, OUTPUT);
}
void loop() {
if (Serial.available() >= CHANNEL_COUNT) {
for (X = 0; x < CHANNEL_COUNT; x++) { //for every channel...
bt[x] = Serial.read(); //we read a byte from the serial stream buffer and store it in an array for later use
}
digitalWrite(PIN1, bt[0]); //we tell the pins on the arduino what to do...
digitalWrite(PIN2, bt[1]); //using the array of integers that holds the byte values from the serial stream...
digitalWrite(PIN3, bt[2]);
digitalWrite(PIN4, bt[3]);
}
}
The LED's run off a second controller in the Vixen Lights software. I have two 12 volt, 50 pixel LED strips of type WS2811. The Arduino uses the FastLED library that can be downloaded for free from FastLED.io. What I found was that there is one byte of garbage data that comes in the serial stream for the LED strips and I had to move past that byte of data in order for the LED's to receive the correct bytes of data to control their color, position etc. I use this code to run my LED's off the Arduino MEGA 2560;
#include <FastLED.h> //include the FastLED library in the Arduino project
#define LED_PIN1 7 //I am going to run one strip of 50 LEDs off of pin 7 on the MEGA
#define LED_PIN2 6 //I am going to run a second strip of 50 LEDs off of pin 6 on the MEGA
#define BAUD_RATE 115200
#define NUM_LEDS 50
//It took me some time to figure out that my two pixel strips are set
//to different color codes. Why? I don't know, but they are.
#define RGB_ORDER RGB //one of my pixel strips is set to use RGB color codes
#define BRG_ORDER BRG //the second strip came from the factory with BRG color codes
#define LED_TYPE WS2811 //what type of LEDs are they? Mine are WS2811, yours may be different.
//create an array to hold the FastLED CRBG code for each of the 50 pixels in the
//first strip.
CRGB leds1[NUM_LEDS];
//create another array to hold the FastLED CRBG codes for each of the 50 pixels in
//the second strip.
CRGB leds2[NUM_LEDS];
int g; //a variable we will use in the loop section
int bufferGarbage[1]; //THIS IS THE KEY TO MAKING THIS WHOLE THING WORK. WE NEED TO
//GET PAST THE FIRST MYSTERY BYTE THAT IS SENT TO THE ARDUINO MEGA FROM THE VIXEN
//LIGHTS SOFTWARE. So we create a variable we will use in the loop section of code.
void setup() {
delay(1000);
Serial.begin(BAUD_RATE);
pinMode(LED_PIN1, OUTPUT); //set our pins to output. PIN1 is pin 6 on the Arduino board.
pinMode(LED_PIN2, OUTPUT); //set our pins to output. PIN2 is pin 7 on the Arduino board.
//This line sets up the first pixel strip to run using FastLED
FastLED<LED_TYPE, LED_PIN1, RGB_ORDER>(leds1, NUM_LEDS).setCorrection(TypicalLEDStrip);
//This line sets up the second pixel strip to run using FastLED
FastLED<LED_TYPE, LED_PIN2, BRG_ORDER>(leds2, NUM_LEDS).setCorrection(TypicalLEDStrip);
}
void loop() {
if (Serial.available() >= 0) { //if there is data in the serial stream
//bufferGarbage is to capture the first byte of garbage that comes across.
//Without this the LED's are out of sync.
//In my case if I didn't capture this byte the first pixel on my
//second LED strip would match the color code that should be on the last
//pixel of the first strip. We don't do anything with this byte.
//but we need to read it from the serial stream so we can move to the
//next byte in the stream.
bufferGarbage[0] = Serial.read();
//then we need to populate the leds1 array so FastLED can tell the pixels what to do.
//We have 50 pixels in the strip and each pixel has a CRGB property that uses
//a red, green, and blue attribute. So for each LED we need to capture 3
//bytes from the serial stream. 50 LEDs * 3 bytes each means we need to read
//150 bytes of data from the serial stream.
for (g = 0; g < NUM_LEDS; g++) {
Serial.readBytes( ( char*)(&leds1[g], 3);
}
for (g = 0; g < NUM_LEDS; g++) {//then we read the next 150 bytes for the second strip of LEDs
Serial.readBytes( ( char*)(&leds2[g], 3);
}
FastLED.show(); //then we tell FastLED to show the pixels!
}
}

Compilation error in connecting Arduino Uno with SKYNAV skm53 GPS module

I am trying to connect Arduino Uno with skm53 GPS module, however before uploading the sketch with the Arduino software, I verified it and found the following error.
Error: #error NewSoftSerial has been moved into the Arduino core as of version 1.0. Use SoftwareSerial instead.
I have included the libraries TinyGPS and NewSoftSerial in the libraries directory of the Arduino tool, I have searched and found that almost all code are the same as mine.
#include <TinyGPS.h>
#include <NewSoftSerial.h>
unsigned long fix_age;
NewSoftSerial GPS(2,3);
TinyGPS gps;
void gpsdump(TinyGPS &gps);
bool feedgps();
void getGPS();
long lat, lon;
float LAT, LON;
void setup(){
GPS.begin(9600);
//Serial.begin(115200);
}
void loop(){
long lat, lon;
unsigned long fix_age, time, date, speed, course;
unsigned long chars;
unsigned short sentences, failed_checksum;
// Retrieves +/- latitude/longitude in 100000ths of a degree.
gps.get_position(&lat, &lon, &fix_age);
getGPS();
Serial.print("Latitude : ");
Serial.print(LAT/100000,7);
Serial.print(" :: Longitude : ");
Serial.println(LON/100000,7);
}
void getGPS(){
bool newdata = false;
unsigned long start = millis();
// Every 1 seconds we print an update.
while (millis() - start < 1000)
{
if (feedgps ()){
newdata = true;
}
}
if (newdata)
{
gpsdump(gps);
}
}
bool feedgps(){
while (GPS.available())
{
if (gps.encode(GPS.read()))
return true;
}
return 0;
}
void gpsdump(TinyGPS &gps)
{
//byte month, day, hour, minute, second, hundredths;
gps.get_position(&lat, &lon);
LAT = lat;
LON = lon;
{
feedgps(); // If we don't feed the GPS during this long
//routine, we may drop characters and get
//checksum errors.
}
}
You might be looking at older examples (pre Arduino 1.0 and pre inclusion of softwwareserial).
Those examples would have worked with Arduino .23 and earlier.
Just change your first four lines of code like this and it will compile ok:
#include <TinyGPS.h>
#include <SoftwareSerial.h>
unsigned long fix_age;
SoftwareSerial GPS(2,3);
Then you can delete the NewSoftLibrary to avoid future problems.
Also a suggestion: having two variables named the same but with different case, is very confusing.
Better to use more descriptive and distinquishing names to quickly identify them. Probably a better choice might be ssGPS for the serial software connection interface and tlibGPS for the tiny GPS library.

How to get array of float audio data from AudioQueueRef in iOS?

I'm working on getting audio into the iPhone in a form where I can pass it to a (C++) analysis algorithm. There are, of course, many options: the AudioQueue tutorial at trailsinthesand gets things started.
The audio callback, though, gives an AudioQueueRef, and I'm finding Apple's documentation thin on this side of things. Built-in methods to write to a file, but nothing where you actually peer inside the packets to see the data.
I need data. I don't want to write anything to a file, which is what all the tutorials — and even Apple's convenience I/O objects — seem to be aiming at. Apple's AVAudioRecorder (infuriatingly) will give you levels and write the data, but not actually give you access to it. Unless I'm missing something...
How to do this? In the code below there is inBuffer->mAudioData which is tantalizingly close but I can find no information about what format this 'data' is in or how to access it.
AudioQueue Callback:
void AudioInputCallback(void *inUserData,
AudioQueueRef inAQ,
AudioQueueBufferRef inBuffer,
const AudioTimeStamp *inStartTime,
UInt32 inNumberPacketDescriptions,
const AudioStreamPacketDescription *inPacketDescs)
{
static int count = 0;
RecordState* recordState = (RecordState*)inUserData;
AudioQueueEnqueueBuffer(recordState->queue, inBuffer, 0, NULL);
++count;
printf("Got buffer %d\n", count);
}
And the code to write the audio to a file:
OSStatus status = AudioFileWritePackets(recordState->audioFile,
false,
inBuffer->mAudioDataByteSize,
inPacketDescs,
recordState->currentPacket,
&inNumberPacketDescriptions,
inBuffer->mAudioData); // THIS! This is what I want to look inside of.
if(status == 0)
{
recordState->currentPacket += inNumberPacketDescriptions;
}
// so you don't have to hunt them all down when you decide to switch to float:
#define AUDIO_DATA_TYPE_FORMAT SInt16
// the actual sample-grabbing code:
int sampleCount = inBuffer->mAudioDataBytesCapacity / sizeof(AUDIO_DATA_TYPE_FORMAT);
AUDIO_DATA_TYPE_FORMAT *samples = (AUDIO_DATA_TYPE_FORMAT*)inBuffer->mAudioData;
Then you have your (in this case SInt16) array samples which you can access from samples[0] to samples[sampleCount-1].
The above solution did not work for me, I was getting the wrong sample data itself.(an endian issue) If incase someone is getting wrong sample data in future, I hope this helps you :
-(void)feedSamplesToEngine:(UInt32)audioDataBytesCapacity audioData:(void *)audioData {
int sampleCount = audioDataBytesCapacity / sizeof(SAMPLE_TYPE);
SAMPLE_TYPE *samples = (SAMPLE_TYPE*)audioData;
//SAMPLE_TYPE *sample_le = (SAMPLE_TYPE *)malloc(sizeof(SAMPLE_TYPE)*sampleCount );//for swapping endians
std::string shorts;
double power = pow(2,10);
for(int i = 0; i < sampleCount; i++)
{
SAMPLE_TYPE sample_le = (0xff00 & (samples[i] << 8)) | (0x00ff & (samples[i] >> 8)) ; //Endianess issue
char dataInterim[30];
sprintf(dataInterim,"%f ", sample_le/power); // normalize it.
shorts.append(dataInterim);
}