c++ - Reading Serial Data from Arduino, Corrupted Data -


i using arduino due , visual studio 2010. programming in c/c++. below see programs , after explanations of going wrong.

this simple code thats on arduino. sending lot of a's pc.

void setup() {   // initialize serial communication @ 9600 bits per second:   serial.begin(9600); }  void loop() {   serial.println('a');   delay(1);        // delay in between reads stability } 

the further code reading serial port found on here: http://playground.arduino.cc/interfacing/cppwindows

and modified version of code @ moment:

header:

#ifndef serialclass_h_included #define serialclass_h_included #define arduino_wait_time 2000  #include <windows.h> #include <stdio.h> #include <stdlib.h>  class serial {     private:         //serial comm handler         handle hserial;         //connection status         bool connected;         //get various information connection         comstat status;         //keep track of last error         dword errors;      public:         //initialize serial communication given com port         serial(char *portname);         //close connection         //nota: reason can't connect again before exiting         //the program , running again         ~serial();         //read data in buffer, if nbchar greater         //maximum number of bytes available, return         //bytes available. function return -1 when nothing         //be read, number of bytes read.         int readdata(char *buffer, unsigned int nbchar);         //writes data buffer through serial connection         //return true on success.         bool writedata(char *buffer, unsigned int nbchar);         //check if connected         bool isconnected(); };  #endif // serialclass_h_included 

cpp:

#include "stdafx.h" #include <stdio.h> #include <tchar.h> #include "serialclass.h" #include <string> #include <windows.h> #include <assert.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <conio.h>   using namespace system; using namespace std;  // serial::serial looks, if serial connection pc device proper , working. sets few parameters , waits serial::serial(char *portname) {     //we're not yet connected     this->connected = false;      //try connect given port throuh createfile     this->hserial = createfilea(portname,             generic_read | generic_write,             0,             null,             open_existing,             file_attribute_normal,             null);      //check if connection successfull     //if not...show error     if(this->hserial==invalid_handle_value)     {         //if not success full display error         if(getlasterror()==error_file_not_found){             //print error if neccessary             printf("error: handle not attached. reason: %s not available.\n", portname);             sleep(2000);         }         else         {printf("error!!!");}     }     // else = connection working, -> continue     else     {         //if connected try set comm parameters         dcb dcbserialparams = {0};          //try current parameters         if (!getcommstate(this->hserial, &dcbserialparams))         {             //if impossible, show error             printf("failed current serial parameters!");         }         else         {             //define serial connection parameters arduino board              dcbserialparams.baudrate=cbr_9600;             dcbserialparams.bytesize=8;             dcbserialparams.stopbits=onestopbit;             dcbserialparams.parity=noparity;                //set parameters , check proper application              if(!setcommstate(hserial, &dcbserialparams))              {                 printf("alert: not set serial port parameters");              }              else              {                  //if went fine we're connected                  this->connected = true;                  //we wait 2s arduino board reseting                  sleep(arduino_wait_time);              }         }     } }   //has if serialport still connected. //if yes, disconnects , closes serial handler. serial::~serial() {     //check if connected before trying disconnect     if(this->connected)     {         //we're no longer connected         this->connected = false;         //close serial handler         closehandle(this->hserial);     } }   // reads data out of serial port int serial::readdata(char *buffer, unsigned int nbchar) {     //number of bytes we'll have read     dword bytesread;     //number of bytes we'll ask read     unsigned int toread;      //use clearcommerror function status info on serial port     clearcommerror(         this->hserial, // handle communications device, createfile function returns value         &this->errors, // pointer variable receives mask indicating type of rror         &this->status);// pointer comstat structure in devices status information returned. if parameter null, no status information returned  //check if there read if(this->status.cbinque>0) // cbinque: number of bytes received serial provider, not yet read readfile operation {     //if there check if there enough data read required number     //of characters, if not we'll read available characters prevent     //locking of application.     if(this->status.cbinque>nbchar)         {toread = nbchar;}     else         {toread = this->status.cbinque;}      //try read require number of chars, , return number of read bytes on success     if(readfile(        this->hserial,   // handle device        buffer,          // pointer buffer receives data read file or device        toread,          // numberofbytestoread: maximum number of bytes read        &bytesread,      // numberofbytesread: pointer variable receives number of bytes read when using synchronours hfile parameter.             null)           // overlapped             && bytesread    // value of bytesread after readfile function             != 0)         {return bytesread;         sleep(1000);}   // returns value of bytesread     }     //if nothing has been read, or error detected return -1     return -1; }    bool serial::isconnected() // returns connection status {     //simply return connection status     return this->connected; } 

main:

// application reads specified serial port , reports collected data int _tmain(int argc, _tchar* argv[])  {      printf("welcome serial test app!\n\n");      serial* sp = new serial("\\\\.\\com3");    // adjust needed       if (sp->isconnected())         printf("we're connected");       // defines how data catched      // don't forget pre-allocate memory          char incomingdata[1025] = "";         incomingdata[1024]='\0';          int datalength = 1024; // maximum length of 1 databit/word         int readresult = 0;          // gives out number! of databits collected/catched         readresult = sp->readdata(incomingdata,datalength);          printf("bytes read: (-1 means no data available) %i\n",readresult);           // transforms char incomingdata string , prints          std::string test(incomingdata);         printf("%s \n", incomingdata);          printf("bytes read: (-1 means no data available) %i\n",readresult);          sleep(10000);    } 

so here problem:

the programm works fine, long amount of bits sending arduino less datalength. (here = 1024) got less bits through setting delay arduino programm quite high (~100ms). have console window output similar this:

a a a ... goes on 

but if arduino sends more 1024 bits (delay ~ 1ms)/ pc receices more bits value of datalength, in serial::readdata loop seems wrong. console output little bit corrupted , bits this:

a ßa  a ... goes on similar this. 

what wrong program? thought be, 1 parameter of readfile() function not right, not know change , not 100% sure this.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -