Go Down

Topic: Reading serial data coming from arduino in c++? (Read 930 times) previous topic - next topic

Panglossian_Man


You are allocating memory, but not freeing it.

Why not use a static array?
Code: [Select]
char buf[256];

I am freeing it, just later on in the code (same as when I call the destructor for the Serial class), I haven't pasted my entire code as I felt that that shows the (previously) problematic part.

Is using the static array going to be any different from using malloc? (Apart from having to allocate and free the memory)

For the sake of it, her's the entire main I'm using with the class, guess it would've been easier to just do this from the start (lesson learned).
This code just sends a '1', which turns the LED on pin 13 on and then a '0' which turns the LED off with the arduino replying with LED ON or LED OFF, I think I'm going to move the read and write functions to another class to make it easier to extend and to read and write more than one charater.
Code: [Select]
#include <cstdlib>
#include <iostream>
#include "SerialClass.h"

using namespace std;

void readData();

Serial ard = Serial("COM4");

int main()
{
if( ard.IsConnected() == true )
{
cout << "Done" << endl;
} else
{
cout << "Connection failed, exitting";
return EXIT_FAILURE;
}


//test arduino connection
if( ard.WriteData( "1", 1 ) == true )
{
cout << "Data sent successfully\n";
} else
{
cout << "Data not sent";
}

        readData();

ard.WriteData( "0", 1 );
readData();

        ard.~Serial();

        // Keep the console open to check output.
        // Saves from using a breakpoint
Sleep(20000);
return EXIT_SUCCESS;
}

void readData()
{
        // Check for data coming from arduino
        // If no data is found check 4 more times
char *buf;
int length = 256;
buf = ( char* ) malloc( length );

int num, i = 0;
while( i < 5 ){
num = ard.ReadData( buf, length );
if( num == -1 )
{
cout << "\nNothing to read";
} else
{
cout << "Read: ";
for( int i = 0; i < num; i++ )
{
cout << *(buf + i);
}
cout << "Num: " << num << endl;
break;
}
i++;
Sleep(25);
}
free( buf );
}

PaulS

Code: [Select]
        ard.~Serial();
You should NEVER invoke the destructor directly. Delete the object, and the destructor will be called.

A static array will be faster, and there will be no question about whether the allocation succeeded. With malloc(), it is possible for the allocation to fail. You are not checking for that possibility.

A static array does not have to be freed, so there is no possibility of forgetting to free it, or of the code being revised to provide an alternate return path that bypasses the free() call (such as an exception be thrown).

Go Up