Turning ID into Unique Sound with FFMPEG - audio

I want to turn my UUID into unique sounds using FFMPEG, but I am unsure how to do this.
So right now I have UUID that look like this: '1e859915-bcdf-4862-8af2-bb43f04e2158'
Like UUID are unique, I want to make them all each into unique 1-2 second audio files. Can FFMPEG do this or is there a different route? Is something the the SINE function in FFMPEG would do or something else?

Here's an attempt to turn each nibble in the GUID into a tone in the range A4-C6.
It outputs unsigned 8-bit PCM in WAVE, no ffmpeg required. The code is for illustrative purposes only, feel free to add proper validation etc.
#include <stdio.h>
#include <inttypes.h>
#include <math.h>
int main(void) {
FILE* out;
int duration = 2; // [s]
int32_t rate = 44100; // [Hz]
uint8_t guid[] = {0x1e, 0x85, 0x99, 0x15, 0xbc, 0xdf, 0x48, 0x62, 0x8a, 0xf2, 0xbb, 0x43, 0xf0, 0x4e, 0x21, 0x58};
int32_t samples_per_nibble = (float) duration / 32 * rate;
int32_t total_samples = samples_per_nibble * 32;
int16_t c16;
int32_t c32;
if ((out = fopen("test.wav", "wb")) == NULL) {
return 1;
}
// WAV header
// ChunkID
fputs("RIFF", out);
// ChunkSize
c32 = 36 + total_samples;
fwrite(&c32, 4, 1, out);
// Format
fputs("WAVE", out);
// Subchunk1ID
fputs("fmt ", out);
// Subchunk1Size
c32 = 16;
fwrite(&c32, 4, 1, out);
// AudioFormat
c16 = 1;
fwrite(&c16, 2, 1, out);
// NumChannels
c16 = 1;
fwrite(&c16, 2, 1, out);
// SampleRate
c32 = rate;
fwrite(&c32, 4, 1, out);
// ByteRate
c32 = rate;
fwrite(&c32, 4, 1, out);
// BlockAlign
c16 = 1;
fwrite(&c16, 2, 1, out);
// BitsPerSample
c16 = 8;
fwrite(&c16, 2, 1, out);
// Subchunk2ID
fputs("data", out);
// Subchunk2Size
c32 = total_samples;
fwrite(&c32, 4, 1, out);
// Data
for (int b = 0; b < 16; b++) {
// for each byte in the GUID
for (int n = 0; n < 2; n++) {
// for each nibble
uint8_t nibble = (n ? guid[b] >> 4 : guid[b]) & 0x0f;
// go nibble steps above A4
float frequency = 440.0 * pow(1.059463094359, nibble);
// write the samples
for (int s = 0; s < samples_per_nibble; s++) {
int sample = (sin(frequency * 2 * M_PI * s / rate) + 1) * 0.5 * 255;
fputc(sample, out);
}
}
}
fclose(out);
return 0;
}

Related

i2c read register on /dev/i2c

I have written a small test program that reads a temperature register on a LSM6DSO chip and display the temperature correctly after reading the /dev/i2c (IOCTL call) so far so good but whilst reading the chip through iio_generic_buffer() (which relies on the sysfs filesystem) correctly updates the register and returns slightly different values at each read, my program keeps on displaying the same value over and
over.
So question is: What am I missing? And why doesn't the register updates itself with the next temperature?
int main()
{
...
for (i = 0; i <= 100; i++) {
i2c_read_1_byte(0x6a, 0xf, result); // reading 1 byte of register 0xf (WHO_AM_I)
printf("Read %#02X\n", result[0]);
i2c_read_1_byte(0x6a, 0x20, result);
templ = result[0];
i2c_read_1_byte(0x6a, 0x21, result);
temph = result[0];
printf("Read temph %#02X\n", temph);
printf("Read templ %#02X\n", templ);
res = (((unsigned short)temph << 8) & 0xFF00) | templ;
printf("res: 0x%x\n", res);
}
int i2c_read_1_byte(unsigned char slave_addr, unsigned char reg, unsigned char *result)
{
unsigned char outbuf[1], inbuf[1];
struct i2c_msg msgs[2];
struct i2c_rdwr_ioctl_data msgset[1];
msgs[0].addr = slave_addr;
msgs[0].flags = 0;
msgs[0].len = 1;
msgs[0].buf = outbuf;
msgs[1].addr = slave_addr;
msgs[1].flags = I2C_M_RD | I2C_M_STOP;
msgs[1].len = 1;
msgs[1].buf = inbuf;
msgset[0].msgs = msgs;
msgset[0].nmsgs = 2;
outbuf[0] = reg;
inbuf[0] = 0;
*result = 0;
if (ioctl(i2c_fd, I2C_RDWR, &msgset) < 0) {
perror("ioctl(I2C_RDWR) in i2c_read");
return -1;
}
*result = inbuf[0];
return 0;
}
Solved, was a timing problem, so started with usleep and ended polling the DTA_RDY register ...

FFMPEG- Duration of audio file is inaccurate

I have video file (mp4). I want to detach audio stream (AAC format) from that file and save in PC.
With below code, Generated aac file canplay now on KM player, but can not play on VLC player. Information of duration displays on player is wrong.
Please help me with this problem.
err = avformat_open_input(input_format_context, filename, NULL, NULL);
if (err < 0) {
return err;
}
/* If not enough info to get the stream parameters, we decode the
first frames to get it. (used in mpeg case for example) */
ret = avformat_find_stream_info(*input_format_context, 0);
if (ret < 0) {
av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
return ret;
}
/* dump the file content */
av_dump_format(*input_format_context, 0, filename, 0);
for (size_t i = 0; i < (*input_format_context)->nb_streams; i++) {
AVStream *st = (*input_format_context)->streams[i];
if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
*input_codec_context = st->codec;
*input_audio_stream = st;
FILE *file = NULL;
file = fopen("C:\\Users\\MyPC\\Downloads\\Test.aac", "wb");
AVPacket reading_packet;
av_init_packet(&reading_packet);
while (av_read_frame(*input_format_context, &reading_packet) == 0) {
if (reading_packet.stream_index == (int) i) {
uint8_t adts_header[7];
unsigned int obj_type = 0;
unsigned int num_data_block = (reading_packet.size)/1024;
int rate_idx = st->codec->sample_rate, channels = st->codec->channels;
uint16_t frame_length;
// include the header length also
frame_length = reading_packet.size + 7;
/* We want the same metadata */
/* Generate ADTS header */
if(adts_header == NULL) return -1;
/* Sync point over a full byte */
adts_header[0] = 0xFF;
/* Sync point continued over first 4 bits + static 4 bits
* (ID, layer, protection)*/
adts_header[1] = 0xF1;
/* Object type over first 2 bits */
adts_header[2] = obj_type << 6;
/* rate index over next 4 bits */
adts_header[2] |= (rate_idx << 2);
/* channels over last 2 bits */
adts_header[2] |= (channels & 0x4) >> 2;
/* channels continued over next 2 bits + 4 bits at zero */
adts_header[3] = (channels & 0x3) << 6;
/* frame size over last 2 bits */
adts_header[3] |= (frame_length & 0x1800) >> 11;
/* frame size continued over full byte */
adts_header[4] = (frame_length & 0x1FF8) >> 3;
/* frame size continued first 3 bits */
adts_header[5] = (frame_length & 0x7) << 5;
/* buffer fullness (0x7FF for VBR) over 5 last bits*/
adts_header[5] |= 0x1F;
/* buffer fullness (0x7FF for VBR) continued over 6 first bits + 2 zeros
* number of raw data blocks */
adts_header[6] = 0xFA;
adts_header[6] |= num_data_block & 0x03; // Set raw Data blocks.
fwrite(adts_header, 1, 7, file);
fwrite(reading_packet.data, 1, reading_packet.size, file);
}
av_free_packet(&reading_packet);
}
fclose(file);
return 0;
}
}
Object type and sample rate index must be set to the real, correct values. Both values can be parsed out of the audio specific config in the extradata field in the codec context. All the information you need is here: http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio

Capturing latency data with Core Audio

I wrote this code to create an audio file sine.aif using Audio ToolBox framework.
I'm interested in capturing the data latency of this file without running it my phone, just running it on the command line and capturing the time. Is this possible? I do not have much knowledge with Core Audio.
Here is the code:
#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioToolbox.h>
#define SAMPLE_RATE 44100
#define DURATION 5.0
#define FILENAME_FORMAT #"%0.3f-sine.aif"
int main(int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc]init];
if(argc < 2) {
printf("Usage:CAToneFileGenerator 261.526\n");
return -1;
}
double hz = atof(argv[1]);
assert (hz > 0);
NSLog (#"generating %f hz tone", hz);
NSString *fileName = [NSString stringWithFormat:FILENAME_FORMAT, hz];
NSString *filePath = [[[NSFileManager defaultManager]currentDirectoryPath]stringByAppendingPathComponent:fileName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
//Prepare the format
AudioStreamBasicDescription asbd;
memset(&asbd, 0, sizeof(asbd));
asbd.mSampleRate = SAMPLE_RATE;
asbd.mFormatID = kAudioFormatLinearPCM;
asbd.mFormatFlags = kAudioFormatFlagIsBigEndian | kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
asbd.mBitsPerChannel = 16;
asbd.mChannelsPerFrame = 1;
asbd.mFramesPerPacket = 1;
asbd.mBytesPerFrame = 2;
asbd.mBytesPerPacket = 2;
//Set up the file
AudioFileID audioFile;
OSStatus audioErr = noErr;
audioErr = AudioFileCreateWithURL((CFURLRef)fileURL, kAudioFileAIFFType, &asbd, kAudioFileFlags_EraseFile, &audioFile);
assert(audioErr == noErr);
//Start writing samples
long maxSampleCount = SAMPLE_RATE * DURATION;
//NSLog (#"maxSampleCount %long", maxSampleCount);
long sampleCount = 0;
UInt32 bytesToWrite = 2;
double wavelengthInSamples = SAMPLE_RATE / hz;
NSLog (#"wavelengthInSamples %f", wavelengthInSamples);
while (sampleCount < maxSampleCount) {
for (int i=0; i < wavelengthInSamples; i++) {
// sine wave
SInt16 sample = CFSwapInt16HostToBig ((SInt16)SHRT_MAX * sin(2 * M_PI * (i / wavelengthInSamples)));
audioErr = AudioFileWriteBytes(audioFile, false, sampleCount*2, &bytesToWrite, &sample);
assert(audioErr == noErr);
sampleCount++;
}
}
audioErr = AudioFileClose(audioFile);
assert(audioErr == noErr);
NSLog (#"wrote %d samples", sampleCount);
[pool drain];
return 0;
}

Convert .m4a to PCM using libavcodec

I'm trying to convert a .m4a file to raw PCM file so that I can play it back in Audacity.
According to the AVCodecContext it is a 44100 Hz track using the sample format AV_SAMPLE_FMT_FLTP which, to my understanding, when decodeded using avcodec_decode_audio4, I should get two arrays of floating point values (one for each channel).
I'm unsure of the significance of the AVCodecContext's bits_per_coded_sample = 16
Unfortunately Audacity plays the result back as if I have the original track is mixed in with some white noise.
Here is some sample code of what I've been done. Note that I've also added a case for a track that uses signed 16bit non-interleaved data (sample_format = AC_SAMPLE_FMT_S16P), which Audacity plays back fine.
int AudioDecoder::decode(std::string path)
{
const char* input_filename=path.c_str();
av_register_all();
AVFormatContext* container=avformat_alloc_context();
if(avformat_open_input(&container,input_filename,NULL,NULL)<0){
printf("Could not open file");
}
if(avformat_find_stream_info(container, NULL)<0){
printf("Could not find file info");
}
av_dump_format(container,0,input_filename,false);
int stream_id=-1;
int i;
for(i=0;i<container->nb_streams;i++){
if(container->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO){
stream_id=i;
break;
}
}
if(stream_id==-1){
printf("Could not find Audio Stream");
}
AVDictionary *metadata=container->metadata;
AVCodecContext *ctx=container->streams[stream_id]->codec;
AVCodec *codec=avcodec_find_decoder(ctx->codec_id);
if(codec==NULL){
printf("cannot find codec!");
}
if(avcodec_open2(ctx,codec,NULL)<0){
printf("Codec cannot be found");
}
AVSampleFormat sfmt = ctx->sample_fmt;
AVPacket packet;
av_init_packet(&packet);
AVFrame *frame = avcodec_alloc_frame();
int buffer_size = AVCODEC_MAX_AUDIO_FRAME_SIZE+ FF_INPUT_BUFFER_PADDING_SIZE;;
uint8_t buffer[buffer_size];
packet.data=buffer;
packet.size =buffer_size;
FILE *outfile = fopen("test.raw", "wb");
int len;
int frameFinished=0;
while(av_read_frame(container,&packet) >= 0)
{
if(packet.stream_index==stream_id)
{
//printf("Audio Frame read \n");
int len=avcodec_decode_audio4(ctx, frame, &frameFinished, &packet);
if(frameFinished)
{
if (sfmt==AV_SAMPLE_FMT_S16P)
{ // Audacity: 16bit PCM little endian stereo
int16_t* ptr_l = (int16_t*)frame->extended_data[0];
int16_t* ptr_r = (int16_t*)frame->extended_data[1];
for (int i=0; i<frame->nb_samples; i++)
{
fwrite(ptr_l++, sizeof(int16_t), 1, outfile);
fwrite(ptr_r++, sizeof(int16_t), 1, outfile);
}
}
else if (sfmt==AV_SAMPLE_FMT_FLTP)
{ //Audacity: big endian 32bit stereo start offset 7 (but has noise)
float* ptr_l = (float*)frame->extended_data[0];
float* ptr_r = (float*)frame->extended_data[1];
for (int i=0; i<frame->nb_samples; i++)
{
fwrite(ptr_l++, sizeof(float), 1, outfile);
fwrite(ptr_r++, sizeof(float), 1, outfile);
}
}
}
}
}
fclose(outfile);
av_close_input_file(container);
return 0;
}
I'm hoping I've just done a naive conversion (most/less significant bit issues), but at present I've been unable to figure it out. Note that Audacity can only import RAW float data if its 32bit or 64 bit float (big or little endian).
Thanks for any insight.
I think problem is in "nb_samples". It's not exactly you need. It's better to try with "linesize[0]".
Example:
char* ptr_l = (char*)frame->extended_data[0];
char* ptr_r = (char*)frame->extended_data[1];
size_t size = sizeof(float);
for (int i=0; i<frame->linesize[0]; i+=size)
{
fwrite(ptr_l, size, 1, outfile);
fwrite(ptr_r, size, 1, outfile);
ptr_l += size;
ptr_r += size;
}
It's for "float", and repeat the same for "int16_t". But "size" will be "sizeof(int16_t)"
You must use a converter of AV_SAMPLE_FMT_FLTP in AC_SAMPLE_FMT_S16P
How to convert sample rate from AV_SAMPLE_FMT_FLTP to AV_SAMPLE_FMT_S16?
Here is a working example (in pAudioBuffer you have pcm data within white nose):
SwrContext *swr;
swr=swr_alloc();
av_opt_set_int(swr,"in_channel_layout",2,0);
av_opt_set_int(swr, "out_channel_layout", 2, 0);
av_opt_set_int(swr, "in_sample_rate", codecContext->sample_rate, 0);
av_opt_set_int(swr, "out_sample_rate", codecContext->sample_rate, 0);
av_opt_set_sample_fmt(swr, "in_sample_fmt", AV_SAMPLE_FMT_FLTP, 0);
av_opt_set_sample_fmt(swr, "out_sample_fmt", AV_SAMPLE_FMT_S16P, 0);
swr_init(swr);
int16_t * pAudioBuffer = (int16_t *) av_malloc (AUDIO_INBUF_SIZE * 2);
while(av_read_frame(fmt_cntx,&readingPacket)==0){
if(readingPacket.stream_index==audioSteam->index){
AVPacket decodingPacket=readingPacket;
while(decodingPacket.size>0){
int gotFrame=0;
int result=avcodec_decode_audio4(codecContext,frame,&gotFrame,&decodingPacket);
if(result<0){
av_frame_free(&frame);
avformat_close_input(&fmt_cntx);
return null;
}
if(result>=0 && gotFrame){
int data_size=frame->nb_samples*frame->channels;
swr_convert(swr,&pAudioBuffer,frame->nb_samples,frame->extended_data,frame->nb_samples);
jshort *outShortArray=(*pEnv)->NewShortArray(pEnv,data_size);
(*pEnv)->SetShortArrayRegion(pEnv,outShortArray,0,data_size,pAudioBuffer);
(*pEnv)->CallVoidMethod(pEnv,pObj,callBackShortBuffer,outShortArray,data_size);
(*pEnv)->DeleteLocalRef(pEnv,outShortArray);
decodingPacket.size -= result;
decodingPacket.data += result;
}else{
decodingPacket.size=0;
decodingPacket.data=NULL;
}}
av_free_packet(&decodingPacket);
}

How to send a text file and append it using Arduino

I'm working on a GPS logger project. I have an Arduino Mega set up with a transmitter and receiver and GPS and GSM modules. I also have an Arduino Uno with a transmitter, receiver and buzzer.
When the two devices go too far from each other, the GPS data is pulled and sent to my web server using the GSM module. When I send my file to the server it creates a text file and when I move to another location it overwrites the previous location.
I'm trying to figure out how to append the text file instead of overwriting it. I found a lot of stuff using an SD card shield but nothing without it.
#define GPS_PIN_1 9 // GPS serial pin RX
#define GPS_PIN_2 8 // GPS serial pin TX
#define CHECKPIN 13 // Pin that lights up when things are checked
#define GPSRATE 4800 // GPS baud rate
#include <SoftwareSerial.h>
#include <Flash.h>
#include <Streaming.h>
// How many bytes of input to buffer from the GPS?
#define BUFFERSIZE 100
#define ENDLN
int rx1Pin=31;
int txPin=30;
int tx1Pin=11;
int onModulePin = 2;
int rxPin=12;
SoftwareSerial mySerial = SoftwareSerial(GPS_PIN_1, GPS_PIN_2); //(rx,tx)
SoftwareSerial txSerial = SoftwareSerial(rxPin, txPin);
SoftwareSerial rxSerial = SoftwareSerial(rx1Pin, tx1Pin);
char sendChar ='H';
char incomingChar = 0;
int counter=0;
//GPS variables
int numSats = 0;
int fixType = 0;
int time[] = {
0, 0, 0};
double latitude = 0.0;
double longitude = 0.0;
long altitude = 0;
long maxAlt = 0;
int speed = 0;
int txCount = 0;
int ExOnce = 0;
int FalcomCheck = 0;
int LogCheck =0;
unsigned long GpsOffTime = 0;
unsigned long SmsStart = 0; // SMS-time
char buffer[BUFFERSIZE];
void switchModule(){ // Function to switch the module ON;
digitalWrite(onModulePin,HIGH);
delay(2000);
digitalWrite(onModulePin,LOW);
delay(2000);
}
void setup(){
pinMode(rxPin, INPUT);
pinMode(txPin,OUTPUT);
pinMode(rx1Pin, INPUT);
pinMode(tx1Pin,OUTPUT);
pinMode(GPS_PIN_1, INPUT);
pinMode(GPS_PIN_2, OUTPUT);
pinMode(7, OUTPUT);
pinMode(13, OUTPUT);
digitalWrite(7, HIGH);
pinMode(onModulePin, OUTPUT);
txSerial.begin(4800);
rxSerial.begin(4800);
mySerial.begin(4800);
Serial.begin(19200); // The GPRS baud rate
switchModule(); // Switch the module ON
for (int i=0;i<2;i++){ // Wait 20 sec for connection
delay(10000);
}
}
void loop(){
txSerial.println(sendChar);
Serial.println(sendChar);
for(int i=0; i<6; i++) {
incomingChar = rxSerial.read(); //Read incoming message from TX.
if (incomingChar =='L') {
GPS();//Serial.println("It Works");
}
}
}
void GPS(){
Serial.flush();
// Get a GGA string from the GPS, and
// check if it's a valid fix, and extract the data.
getNMEA("$GPGGA");
delay(100);
numSats = getSats();
fixType = getFixType();
// Make sure we have a valid fix
if (fixType != 0) {
getTime(time);
latitude = getLat();
longitude = getLong();
altitude = getAlt();
// Keep track of the maximum altitude
}
// Convert latitude and longitude into strings.
char latString[12];
char longString[12];
doubleToString(latitude, 4, latString);
doubleToString(longitude, 4, longString);
sprintf(buffer, "%02d:%02d:%02d,%s,%s,%ld",
time[0], time[1], time[2], latString, longString, altitude);
Serial.println(buffer);
if (fixType > 0) {
if (ExOnce==0){
digitalWrite(13, HIGH);
//ExOnce=1;
sendsms();
logftp();
// for (int i=0; i<3; i++) { // Wait 30 sec for a connection.
// delay(10000);
// }
}
}
delay(200);
}
void sendsms(){
Serial.println("AT+CMGF=1"); // Set the SMS mode to text.
delay(500);
Serial.print("AT+CMGS="); // Send the SMS the number.
Serial.print(34,BYTE); // Send the " char.
Serial.print("**********"); // Send the number change *********
// by the actual number.
Serial.println(34,BYTE); // Send the " char.
delay(1500);
Serial.print("Hi this is the General text testing."); // The SMS body
delay(500);
Serial.print(0x1A,BYTE); // End of message command 1A (hex)
delay(20000);
}
void logftp(){
Serial.println("AT&k3"); // Flow activate
delay(1000);
Serial.print("AT+KCNXCFG=0,"); // Connect to GPRS
Serial.print(34,BYTE);
Serial.print("GPRS");
Serial.print(34,BYTE);
Serial.print(",");
Serial.print(34,BYTE);
//Serial.print("wap.cingular");
Serial.print("epc.tmobile.com");
Serial.print(34,BYTE);
Serial.print(",");
Serial.print(34,BYTE);
Serial.print(34,BYTE);
Serial.print(",");
Serial.print(34,BYTE);
Serial.println(34,BYTE);
delay(1000);
Serial.println("AT+KCNXTIMER=0,60,2,70"); // Set timers
delay(1000);
Serial.println("AT+CGATT=1"); // Network check
delay(1000);
Serial.print("AT+KFTPCFG=0,"); //FTP configuration/connect
Serial.print(34,BYTE);
Serial.print("ftp.insertaddress.com"); //FTP address
Serial.print(34,BYTE);
Serial.print(",");
Serial.print(34,BYTE);
Serial.print("username"); //Username
Serial.print(34,BYTE);
Serial.print(",");
Serial.print(34,BYTE);
Serial.print("password"); //Password
Serial.print(34,BYTE);
Serial.println(",21,0"); //Port
delay(500);
Serial.print("AT+KPATTERN=");
Serial.print(34,BYTE);
Serial.print("--EOF--Pattern--");
Serial.println(34,BYTE);
delay(500);
Serial.print("AT+KFTPSND=0,,");
Serial.print(34,BYTE);
Serial.print("log"); //Directory folder of FTP
Serial.print(34,BYTE);
Serial.print(",");
Serial.print(34,BYTE);
Serial.print("pol.txt"); //Text file
Serial.print(34,BYTE);
Serial.println(",0");
delay(12000);
Serial.print(buffer);
Serial.println("--EOF--Pattern--");
delay(12000);
Serial.println("AT+KTCPCLOSE=1,1");
delay(1000);
}
// ------- GPS Parsing ----------
// Reads a line from the GPS NMEA serial output
// Give up after trying to read 1000 bytes (~2 seconds)
int readLine(void) {
char c;
byte bufferIndex = 0;
boolean startLine = 0;
byte retries = 0;
while (retries < 20) {
c = mySerial.read();
if (c == -1) {
delay(2);
continue;
}
if (c == '\n') continue;
if (c == '$') startLine = 1;
if ((bufferIndex == BUFFERSIZE-1) || (c == '\r')) {
if (startLine) {
buffer[bufferIndex] = 0;
return 1;
}
}
if (startLine)
buffer[bufferIndex++] = c;
//}
else {
retries++;
delay(50);
}
}
return 0;
}
// Returns a specific field from the buffer
void getField(int getId, char *field, int maxLen) {
byte bufferIndex = 0;
byte fieldId = 0;
byte i = 0;
while (bufferIndex < sizeof(buffer)) {
if (fieldId == getId) {
// End of string, or string overflow
if (buffer[bufferIndex] == ',' || i > (maxLen - 2)) {
field[i] = 0; // Null terminate
return;
}
// Buffer chars to field
field[i++] = buffer[bufferIndex++];
}
else {
// Advance field on comma
if (buffer[bufferIndex] == ',') {
bufferIndex++; //Advance in buffer
fieldId++; // Increase field position counter
}
else {
bufferIndex++; // Advance in buffer
}
}
}
// Null terminate incase we didn't already..
field[i] = 0;
}
// Polls for an NMEA sentence of type requested
// Validates checksum, silently retries on failed checksums
int getNMEA(char *getType) {
char type[7];
byte retries = 0;
while (retries < 2) {
if (readLine() && validateChecksum()) {
;
getField(0, type, sizeof(type));
if (strcmp(type, getType) == 0) {
return 1;
}
}
else {
retries++;
}
}
Serial.println("Failed to read GPS");
return 0;
}
// Validates the checksum on an NMEA string
// Returns 1 on valid checksum, 0 otherwise
int validateChecksum(void) {
char gotSum[2];
gotSum[0] = buffer[strlen(buffer) - 2];
gotSum[1] = buffer[strlen(buffer) - 1];
// Check that the checksums match up
if ((16 * atoh(gotSum[0])) + atoh(gotSum[1]) == getCheckSum(buffer))
return 1;
else
return 0;
}
// Calculates the checksum for a given string
// returns as integer
int getCheckSum(char *string) {
int i;
int XOR;
int c;
// Calculate checksum ignoring any $'s in the string
for (XOR = 0, i = 0; i < strlen(string); i++) {
c = (unsigned char)string[i];
if (c == '*') break;
if (c != '$') XOR ^= c;
}
return XOR;
}
// Returns the groundspeed in km/h
int getSpeed(void) {
char field[10];
getField(7, field, sizeof(field));
int speed = atoi(field);
return speed;
}
// Return the fix type from a GGA string
int getFixType(void) {
char field[5];
getField(6, field, sizeof(field));
int fixType = atoi(field);
return fixType;
}
// Return the altitude in meters from a GGA string
long getAlt(void) {
char field[10];
getField(9, field, sizeof(field));
long altitude = atol(field);
return altitude;
}
// Returns the number of satellites being tracked from a GGA string
int getSats(void) {
char field[3];
getField(7, field, sizeof(field));
int numSats = atoi(field);
return numSats;
}
// Read the latitude in decimal format from a GGA string
double getLat(void) {
char field[12];
getField(2, field, sizeof(field)); // read the latitude
double latitude = atof(field); // convert to a double (precise)
int deg = (int) latitude / 100; // extract the number of degrees
double min = latitude - (100 * deg); // work out the number of minutes
latitude = deg + (double) min/60.0; // convert to decimal format
getField(3, field, sizeof(field)); // get the hemisphere (N/S)
// sign the decimal latitude correctly
if (strcmp(field, "S") == 0)
latitude *= -1;
return latitude;
}
// Read the longitude in decimal format from a GGA string
double getLong(void) {
char field[12];
getField(4, field, sizeof(field)); // read the longitude
double longitude = atof(field); // convert to a double
int deg = (int) longitude / 100; // extract the number of degrees
double min = longitude - (100 * deg); // work out the number of minutes
longitude = deg + (double) min/60.00; // convert to decimal format
getField(5, field, sizeof(field)); // get the E/W status
// sign decimal latitude correctly
if (strcmp(field, "W") == 0)
longitude *= -1;
return longitude;
}
// Converts UTC time to the correct timezone
void convertTime(int *time) {
// How many hours off GMT are we?
float offset = -5;
long sectime = ((long)(time[0]) * 3600) + (time[1] * 60) + time[2];
sectime += (offset * 3600.0);
// Did we wrap around?
if (sectime < 0) sectime += 86400;
if (sectime > 86400) sectime -= 86400;
// Convert back to time
time[0] = (int)(sectime / 3600);
time[1] = (int)((sectime % 3600) / 60);
time[2] = (int)((sectime % 3600) % 60);
}
// Parses a time field from a GGA string
void parseTime(char *field, int *time) {
char tmp[3];
tmp[2] = 0; // Init tmp and null terminate
tmp[0] = field[0];
tmp[1] = field[1];
time[0] = atoi(tmp); // Hours
tmp[0] = field[2];
tmp[1] = field[3];
time[1] = atoi(tmp); // Minutes
tmp[0] = field[4];
tmp[1] = field[5];
time[2] = atoi(tmp); // Seconds
}
// Gets the hours, minutes and seconds from a GGA string
void getTime(int *time) {
char field[12];
getField(1, field, sizeof(field));
parseTime(field, time);
convertTime(time);
}
// ------ MISC ----------
// Returns a string with a textual representation of a float
void doubleToString(double val, int precision, char *string){
// Print the int part
sprintf(string, "%d", (int)(val));
if(precision > 0) {
// Print the decimal point
strcat(string, ".");
unsigned long frac;
unsigned long mult = 1;
int padding = precision -1;
while (precision--) {
mult *=10;
}
if (val >= 0)
frac = (val - (int)(val)) * mult;
else
frac = ((int)(val)- val ) * mult;
unsigned long frac1 = frac;
while (frac1 /= 10) {
padding--;
}
while (padding--) {
strcat(string, "0");
}
// Convert and print the fraction part
sprintf(string+strlen(string), "%d", (int)(frac));
}
}
// Converts a HEX string to an int
int atoh(char c) {
if (c >= 'A' && c <= 'F')
return c - 55;
else if (c >= 'a' && c <= 'f')
return c - 87;
else
return c - 48;
}
If the server is where the text file is received via SMS/GSM, that server program controls how the file is written or appended. Your posted Arduino code would not need to be changed. On the server, where you now open the file - first check if the file exists and if it does, change the open function to add append mode. Exactly how depends on the OS/language of your server program. But you should be able to figure it out from reading the documentation on the open call.

Resources