Windows API - Read / Write from the Serial port

3

I'm trying to send an AT command to a 3G module whose response is going to be OK. I want to capture that OK in a buffer for its subsequent treaty. For this I did the following:

1- Abri the port according to:

hSerial = CreateFile("\\.\COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL,
            OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

2- Configured the port:

dcbSerialParams.BaudRate = CBR_115200;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;

SetCommState(hSerial, &dcbSerialParams) 

3- I write the corresponding AT command in the port:

char At[] = "AT\r\n";
WriteFile(hSerial, At, length, &bytes_written, NULL)

4- I represent the answer by the terminal according to:

ReadPort();

where:

void ReadPort()
{
    char output[255];
    int i = 0;

    ReadFile(hSerial, output, sizeof(output), &bytes_read, NULL);
    if (bytes_read)
    {
        fprintf(stderr, "* Start Read Port: \n");

        for (i = 0; i < bytes_read; i++)
        {
            fprintf(stderr, "%c", output[i]);
        }

        fprintf(stderr, "* End Read Port: \n");
    }
}

However, if in that same function I pass a buffer as a parameter, the result represented is different, that is, the OK is sometimes well received, sometimes only the OR, only the K ... without any criteria . What will I be doing wrong? What I do is:

char bufferRead[255];

ReadPort2(bufferRead);


void ReadPort2(char *output)
{

    int i = 0;

    ReadFile(hSerial, output, sizeof(output), &bytes_read, NULL);
    if (bytes_read)
    {
        fprintf(stderr, "* Start Read Port: \n");

        for (i = 0; i < bytes_read; i++)
        {
            fprintf(stderr, "%c", output[i]);
        }

        fprintf(stderr, "* End Read Port: \n");
    }
}

(My idea was to have the pointer to that accessible buffer to do checks of what I get.)

Thank you very much!

Regards,

    
asked by dcom 22.02.2018 в 16:42
source

1 answer

3

I can not verify it, but

ReadFile( hSerial, output, sizeof(output), &bytes_read, NULL );

Look at that sizeof( output ) . No you are passing the size of the buffer , but the type size char * .

If you know previously the size of the buffer you are using, you can indicate it directly; although I would recommend changing the function to

void ReadPort2( char *output, size_t sz ) {
  int i = 0;

  ReadFile( hSerial, output, sz, &bytes_read, NULL );
  if ( bytes_read ) {
    fprintf( stderr, "* Start Read Port: \n" );

    for( i = 0; i < bytes_read; i++ ) {
        fprintf( stderr, "%c", output[i] );
    }

    fprintf( stderr, "* End Read Port: \n" );
  }
}

And call it in your code like this:

char bufferRead[255];

ReadPort2( bufferRead, sizeof( bufferRead ) );
    
answered by 22.02.2018 / 16:53
source