Skip to content

Instantly share code, notes, and snippets.

@pingswept
Created December 21, 2012 19:27
Show Gist options
  • Select an option

  • Save pingswept/4355165 to your computer and use it in GitHub Desktop.

Select an option

Save pingswept/4355165 to your computer and use it in GitHub Desktop.
C++ program to talk to the open source libftdi driver (http://www.intra2net.com/en/developer/libftdi/) to read data from Sparkfun's USB Weather Board. Ships by default on the Rascal, http://rascalmicro.com
/* weather_usb.cpp
Weather station client using libftdi
compile: g++ -l ftdi -o weather_usb weather_usb.cpp
This program is distributed under the BSD license
*/
#include <ftdi.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include <memory>
int main(int argc, char* argv[])
{
int ret;
//int f = 0;
//char c[4096];
struct ftdi_context ftdic;
std::string accum;
if (ftdi_init(&ftdic) < 0)
{
fprintf(stderr, "ftdi_init failed\n");
return EXIT_FAILURE;
}
if ((ret = ftdi_usb_open(&ftdic, 0x0403, 0x6001)) < 0)
{
fprintf(stderr, "unable to open ftdi device: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
return EXIT_FAILURE;
}
while(1)
{
char c[4096];
memset(c,0,sizeof(c));
int n = ftdi_read_data(&ftdic, (unsigned char*)c, sizeof(c));
accum = accum + c;
//
// erase anything before the last full $...*
//
size_t last_asterisk_pos = accum.find_last_of('*');
if (last_asterisk_pos == std::string::npos) continue;
size_t last_dollar_sign_with_trailing_asterisk = accum.find_last_of('$', last_asterisk_pos);
if (last_dollar_sign_with_trailing_asterisk == std::string::npos) continue;
accum = accum.substr(last_dollar_sign_with_trailing_asterisk);
//
// print out first complete $...* and remove from buffer
//
size_t asterisk_pos = accum.find_first_of('*');
std::string s = accum.substr(0,asterisk_pos+1);
printf("%s\n",s.c_str());
accum = accum.substr(asterisk_pos+1);
//
// this version only prints one line of output
//
break;
}
if ((ret = ftdi_usb_close(&ftdic)) < 0)
{
fprintf(stderr, "unable to close ftdi device: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
return EXIT_FAILURE;
}
ftdi_deinit(&ftdic);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment