Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

error while sending data over serial com port

i want to send data over particular COM port, that is selected by track-bar, once its selected, data have to transmit over that COM port only. while doing this i am not getting proper output, please help me... thanks in advance!!!

find below code!!! /----------------------------main.cpp---------------------/

include "opencv2/opencv.hpp"

include "opencv2/imgproc/imgproc.hpp"

include "opencv2/highgui/highgui.hpp"

using namespace std; using namespace cv;

include <iostream>

include <stdio.h>

include <tchar.h>

include <string>

include "SerialClass.h"

char COM[4]; unsigned char dataLength=1; //Serial* SP = new Serial (COM);

void CallBackFunc (int event, int x,int y, int flags,void* userdata) { Serial* SP = new Serial (COM); //Serial* SP = new Serial ("COM7"); //bool WriteData(char buffer, unsigned int nbChar);

if (event == EVENT_LBUTTONDOWN)

{
            if ( x > 230 and x < 365 and y < 132 and y > 40)
                {
                  cout << "FORWARD" << endl;
                  //char send[2] = "F";
                  SP->WriteData("F",dataLength);
                  //SP->WriteData('F',dataLength);
                }

            else if ( x > 230 and x < 365 and y < 380 and y > 290)
                {
                  cout << "BACKWARD" << endl;
                  //char send[2] = "B";
                  SP->WriteData("B",dataLength);
                  //SP->WriteData('B',dataLength);
                }

            else if ( x > 40 and x < 175 and y < 260 and y > 165)
                {
                  cout << "LEFT" << endl;
                  //char send[2] = "L";
                  SP->WriteData("L",dataLength);
                  //SP->WriteData('L',dataLength);
                }

            else if ( x > 425 and x < 560 and y < 260 and y > 165)
                {
                  cout << "RIGHT" << endl;
                  //char send[2] = "R";
                  SP->WriteData("R",dataLength);
                  //SP->WriteData('R',dataLength);
                }
            else if ( x > 230 and x < 365 and y < 260 and y > 165)
                {
                  cout << "STOP" << endl;
                  //char send[2] = "S";
                  SP->WriteData("S",dataLength);
                  //SP->WriteData('S',dataLength);
                }
            else
                {
                 cout << "STOP" << endl;
                 //char send[2] = "S";
                 SP->WriteData("S",dataLength);
                 //SP->WriteData('S',dataLength);
                }
        }

}

int main(int argc, char** argv) { int i=0; int Selected_COM; char COM[5];

namedWindow("COM Selection",1);
resizeWindow("COM Selection",400,45);
createTrackbar("COM","COM Selection",&i,20);

if (waitKey(0))
{
Selected_COM = getTrackbarPos("COM","COM Selection");
//printf("%d",Selected_COM);
    if (Selected_COM == 1)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='1';
        COM[4]='\0';
    }
    else if (Selected_COM == 2)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='2';
        COM[4]='\0';
    }
    else if (Selected_COM == 3)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='3';
        COM[4]='\0';
    }
    else if (Selected_COM == 4)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='4';
        COM[4]='\0';
    }
    else if (Selected_COM == 5)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='5';
        COM[4]='\0';
    }
    else if (Selected_COM == 6)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='6';
        COM[4]='\0';
    }
    else if (Selected_COM == 7)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='7';
        COM[4]='\0';
    }
    else if (Selected_COM == 8)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='8';
        COM[4]='\0';
    }
    else if (Selected_COM == 9)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='9';
        COM[4]='\0';
    }

    Serial* SP = new Serial (COM);

    /*if (SP->IsConnected())
    {
        printf("We'r connected");
    }*/

    if (SP->IsConnected())
    {
        Mat img = imread("bot.jpg");
        namedWindow("My Window",1);
        setMouseCallback("My Window", CallBackFunc, NULL);
        //setMouseCallback("My Window", NULL);
        imshow("My Window", img);
        waitKey(0);
    }
    else
        {
        //printf("false");
        //namedWindow("ERROR",1);
        Mat output = Mat::zeros(50, 210, CV_8UC3);
        putText(output,"ERROR!!!", cvPoint(8,40), FONT_HERSHEY_PLAIN, 3, cvScalar(64,128,255,128),2);
        imshow("ERROR", output);
        waitKey(0);
        }
    //printf("%s",COM);

    /*Mat img = imread("bot.jpg");
    namedWindow("My Window",1);
    //setMouseCallback("My Window", CallBackFunc, NULL);
    setMouseCallback("My Window", NULL);
    imshow("My Window", img);
    waitKey(0);*/

}

}

/---------------------serial.cpp----------------------------------/

include "SerialClass.h"

Serial::Serial(char *portName) { //We're not yet connected this->connected = false;

//Try to connect to the given port throuh CreateFile
this->hSerial = CreateFile(portName,
        GENERIC_READ | GENERIC_WRITE,
        0,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

//Check if the connection was successfull
if(this->hSerial==INVALID_HANDLE_VALUE)
{
    //If not success full display an Error
    if(GetLastError()==ERROR_FILE_NOT_FOUND){

        //Print Error if neccessary
        printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName);

    }
    else
    {
        printf("ERROR!!!");
    }
}
else
{
    //If connected we try to set the comm parameters
    DCB dcbSerialParams = {0};

    //Try to get the current
    if (!GetCommState(this->hSerial, &dcbSerialParams))
    {
        //If impossible, show an error
        printf("failed to get current serial parameters!");
    }
    else
    {
        //Define serial connection parameters for the arduino board
        dcbSerialParams.BaudRate=CBR_9600;
        dcbSerialParams.ByteSize=8;
        dcbSerialParams.StopBits=ONESTOPBIT;
        dcbSerialParams.Parity=NOPARITY;

         //Set the parameters and check for their proper application
         if(!SetCommState(hSerial, &dcbSerialParams))
         {
            printf("ALERT: Could not set Serial Port parameters");
         }
         else
         {
             //If everything went fine we're connected
             this->connected = true;
             //We wait 2s as the arduino board will be reseting
             Sleep(ARDUINO_WAIT_TIME);
         }
    }
}

}

Serial::~Serial() { //Check if we are connected before trying to disconnect if(this->connected) { //We're no longer connected this->connected = false; //Close the serial handler CloseHandle(this->hSerial); } }

int Serial::ReadData(char *buffer, unsigned int nbChar) { //Number of bytes we'll have read DWORD bytesRead; //Number of bytes we'll really ask to read unsigned int toRead;

//Use the ClearCommError function to get status info on the Serial port
ClearCommError(this->hSerial, &this->errors, &this->status);

//Check if there is something to read
if(this->status.cbInQue>0)
{
    //If there is we check if there is enough data to read the required number
    //of characters, if not we'll read only the available characters to prevent
    //locking of the application.
    if(this->status.cbInQue>nbChar)
    {
        toRead = nbChar;
    }
    else
    {
        toRead = this->status.cbInQue;
    }

    //Try to read the require number of chars, and return the number of read bytes on success
    if(ReadFile(this->hSerial, buffer, toRead, &bytesRead, NULL) && bytesRead != 0)
    {
        return bytesRead;
    }

}

//If nothing has been read, or that an error was detected return -1
return -1;

}

bool Serial::WriteData(char *buffer, unsigned int nbChar) { DWORD bytesSend;

//Try to write the buffer on the Serial port
if(!WriteFile(this->hSerial, (void *)buffer, nbChar, &bytesSend, 0))
{
    //In case it don't work get comm error and return false
    ClearCommError(this->hSerial, &this->errors, &this->status);

    return false;
}
else
    return true;

}

bool Serial::IsConnected() { //Simply return the connection status return this->connected; }

/------------------------SerialClass.h--------------------------/

ifndef SERIALCLASS_H_

define SERIALCLASS_H_

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 about the connection COMSTAT status; //Keep track of last error DWORD errors;

public:
    //Initialize Serial communication with the given COM port
    Serial(char *portName);
    //Close the connection
    //NOTA: for some reason you can't connect again before exiting
    //the program and running it again
    ~Serial();
    //Read data in a buffer, if nbChar is greater than the
    //maximum number of bytes available, it will return only the
    //bytes available. The function return -1 when nothing could
    //be read, the number of bytes actually read.
    int ReadData(char *buffer, unsigned int nbChar);
    //Writes data from a buffer through the Serial connection
    //return true on success.
    bool WriteData(char *buffer, unsigned int nbChar);
    //Check if we are actually connected
    bool IsConnected();

};

endif //SERIALCLASS_H_

error while sending data over serial com port

i want to send data over particular COM port, that is selected by track-bar, once its selected, data have to transmit over that COM port only. while doing this i am not getting proper output, please help me... thanks in advance!!!

find below code!!! /----------------------------main.cpp---------------------/

include "opencv2/opencv.hpp"

include "opencv2/imgproc/imgproc.hpp"

include "opencv2/highgui/highgui.hpp"

using namespace std; using namespace cv;

include <iostream>

include <stdio.h>

include <tchar.h>

include <string>

include "SerialClass.h"

char COM[4]; unsigned char dataLength=1; //Serial* SP = new Serial (COM);

void CallBackFunc (int event, int x,int y, int flags,void* userdata) { Serial* SP = new Serial (COM); //Serial* SP = new Serial ("COM7"); //bool WriteData(char buffer, unsigned int nbChar);

if (event == EVENT_LBUTTONDOWN)

{
            if ( x > 230 and x < 365 and y < 132 and y > 40)
                {
                  cout << "FORWARD" << endl;
                  //char send[2] = "F";
                  SP->WriteData("F",dataLength);
                  //SP->WriteData('F',dataLength);
                }

            else if ( x > 230 and x < 365 and y < 380 and y > 290)
                {
                  cout << "BACKWARD" << endl;
                  //char send[2] = "B";
                  SP->WriteData("B",dataLength);
                  //SP->WriteData('B',dataLength);
                }

            else if ( x > 40 and x < 175 and y < 260 and y > 165)
                {
                  cout << "LEFT" << endl;
                  //char send[2] = "L";
                  SP->WriteData("L",dataLength);
                  //SP->WriteData('L',dataLength);
                }

            else if ( x > 425 and x < 560 and y < 260 and y > 165)
                {
                  cout << "RIGHT" << endl;
                  //char send[2] = "R";
                  SP->WriteData("R",dataLength);
                  //SP->WriteData('R',dataLength);
                }
            else if ( x > 230 and x < 365 and y < 260 and y > 165)
                {
                  cout << "STOP" << endl;
                  //char send[2] = "S";
                  SP->WriteData("S",dataLength);
                  //SP->WriteData('S',dataLength);
                }
            else
                {
                 cout << "STOP" << endl;
                 //char send[2] = "S";
                 SP->WriteData("S",dataLength);
                 //SP->WriteData('S',dataLength);
                }
        }

}

int main(int argc, char** argv) { int i=0; int Selected_COM; char COM[5];

namedWindow("COM Selection",1);
resizeWindow("COM Selection",400,45);
createTrackbar("COM","COM Selection",&i,20);

if (waitKey(0))
{
Selected_COM = getTrackbarPos("COM","COM Selection");
//printf("%d",Selected_COM);
    if (Selected_COM == 1)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='1';
        COM[4]='\0';
    }
    else if (Selected_COM == 2)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='2';
        COM[4]='\0';
    }
    else if (Selected_COM == 3)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='3';
        COM[4]='\0';
    }
    else if (Selected_COM == 4)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='4';
        COM[4]='\0';
    }
    else if (Selected_COM == 5)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='5';
        COM[4]='\0';
    }
    else if (Selected_COM == 6)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='6';
        COM[4]='\0';
    }
    else if (Selected_COM == 7)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='7';
        COM[4]='\0';
    }
    else if (Selected_COM == 8)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='8';
        COM[4]='\0';
    }
    else if (Selected_COM == 9)
    {
        COM[0]='C';
        COM[1]='O';
        COM[2]='M';
        COM[3]='9';
        COM[4]='\0';
    }

    Serial* SP = new Serial (COM);

    /*if (SP->IsConnected())
    {
        printf("We'r connected");
    }*/

    if (SP->IsConnected())
    {
        Mat img = imread("bot.jpg");
        namedWindow("My Window",1);
        setMouseCallback("My Window", CallBackFunc, NULL);
        //setMouseCallback("My Window", NULL);
        imshow("My Window", img);
        waitKey(0);
    }
    else
        {
        //printf("false");
        //namedWindow("ERROR",1);
        Mat output = Mat::zeros(50, 210, CV_8UC3);
        putText(output,"ERROR!!!", cvPoint(8,40), FONT_HERSHEY_PLAIN, 3, cvScalar(64,128,255,128),2);
        imshow("ERROR", output);
        waitKey(0);
        }
    //printf("%s",COM);

    /*Mat img = imread("bot.jpg");
    namedWindow("My Window",1);
    //setMouseCallback("My Window", CallBackFunc, NULL);
    setMouseCallback("My Window", NULL);
    imshow("My Window", img);
    waitKey(0);*/

}

}

/---------------------serial.cpp----------------------------------/

include "SerialClass.h"

Serial::Serial(char *portName) { //We're not yet connected this->connected = false;

//Try to connect to the given port throuh CreateFile
this->hSerial = CreateFile(portName,
        GENERIC_READ | GENERIC_WRITE,
        0,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

//Check if the connection was successfull
if(this->hSerial==INVALID_HANDLE_VALUE)
{
    //If not success full display an Error
    if(GetLastError()==ERROR_FILE_NOT_FOUND){

        //Print Error if neccessary
        printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName);

    }
    else
    {
        printf("ERROR!!!");
    }
}
else
{
    //If connected we try to set the comm parameters
    DCB dcbSerialParams = {0};

    //Try to get the current
    if (!GetCommState(this->hSerial, &dcbSerialParams))
    {
        //If impossible, show an error
        printf("failed to get current serial parameters!");
    }
    else
    {
        //Define serial connection parameters for the arduino board
        dcbSerialParams.BaudRate=CBR_9600;
        dcbSerialParams.ByteSize=8;
        dcbSerialParams.StopBits=ONESTOPBIT;
        dcbSerialParams.Parity=NOPARITY;

         //Set the parameters and check for their proper application
         if(!SetCommState(hSerial, &dcbSerialParams))
         {
            printf("ALERT: Could not set Serial Port parameters");
         }
         else
         {
             //If everything went fine we're connected
             this->connected = true;
             //We wait 2s as the arduino board will be reseting
             Sleep(ARDUINO_WAIT_TIME);
         }
    }
}

}

Serial::~Serial() { //Check if we are connected before trying to disconnect if(this->connected) { //We're no longer connected this->connected = false; //Close the serial handler CloseHandle(this->hSerial); } }

int Serial::ReadData(char *buffer, unsigned int nbChar) { //Number of bytes we'll have read DWORD bytesRead; //Number of bytes we'll really ask to read unsigned int toRead;

//Use the ClearCommError function to get status info on the Serial port
ClearCommError(this->hSerial, &this->errors, &this->status);

//Check if there is something to read
if(this->status.cbInQue>0)
{
    //If there is we check if there is enough data to read the required number
    //of characters, if not we'll read only the available characters to prevent
    //locking of the application.
    if(this->status.cbInQue>nbChar)
    {
        toRead = nbChar;
    }
    else
    {
        toRead = this->status.cbInQue;
    }

    //Try to read the require number of chars, and return the number of read bytes on success
    if(ReadFile(this->hSerial, buffer, toRead, &bytesRead, NULL) && bytesRead != 0)
    {
        return bytesRead;
    }

}

//If nothing has been read, or that an error was detected return -1
return -1;

}

bool Serial::WriteData(char *buffer, unsigned int nbChar) { DWORD bytesSend;

//Try to write the buffer on the Serial port
if(!WriteFile(this->hSerial, (void *)buffer, nbChar, &bytesSend, 0))
{
    //In case it don't work get comm error and return false
    ClearCommError(this->hSerial, &this->errors, &this->status);

    return false;
}
else
    return true;

}

bool Serial::IsConnected() { //Simply return the connection status return this->connected; }

/------------------------SerialClass.h--------------------------/

ifndef SERIALCLASS_H_

define SERIALCLASS_H_

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 about the connection COMSTAT status; //Keep track of last error DWORD errors;

public:
    //Initialize Serial communication with the given COM port
    Serial(char *portName);
    //Close the connection
    //NOTA: for some reason you can't connect again before exiting
    //the program and running it again
    ~Serial();
    //Read data in a buffer, if nbChar is greater than the
    //maximum number of bytes available, it will return only the
    //bytes available. The function return -1 when nothing could
    //be read, the number of bytes actually read.
    int ReadData(char *buffer, unsigned int nbChar);
    //Writes data from a buffer through the Serial connection
    //return true on success.
    bool WriteData(char *buffer, unsigned int nbChar);
    //Check if we are actually connected
    bool IsConnected();

};

endif //SERIALCLASS_H_