Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

winapi - Serial Communication read serial is very low in C

I am trying serial communication with my Arduino by C using win32api. I can write and read data but reading is very slowly (Actually after Characters Received message). After characters received the message it takes 7-8 seconds to show the result (this program send a number to Arduino and get square).

Initial/Setup codes:

#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <conio.h>
#include <string.h>


int main(int argc, char *argv[]) {

HANDLE hComm;                       // Handle to the Serial port
char ComPortName[] = "\\.\COM4"; // Name of the Serial port(May Change) to be opened,
BOOL Status;
DWORD dwEventMask;  
char TempChar; 
DWORD NoBytesRead; 
char SerialBuffer[256]; 
int i = 0;

/*----------------------------------- Opening the Serial Port --------------------------------------------*/

hComm = CreateFile(ComPortName,                  // Name of the Port to be Opened
                   GENERIC_READ | GENERIC_WRITE, // Read/Write Access
                   0,                            // No Sharing, ports cant be shared
                   NULL,                         // No Security
                   OPEN_EXISTING,                // Open existing port only
                   0,                            // Non Overlapped I/O
                   NULL);                        // Null for Comm Devices
                   
/*if (hComm == INVALID_HANDLE_VALUE)
    printf("
   Error! - Port %s can't be opened", ComPortName);
else
    printf("
   Port %s Opened
 ", ComPortName);*/

/*------------------------------- Setting the Parameters for the SerialPort -----------------------*/

DCB dcbSerialParams = {0}; // Initializing DCB structure
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);

Status = GetCommState(hComm, &dcbSerialParams); //retreives  the current settings

/*if (Status == FALSE)
    printf("
   Error! in GetCommState()");*/

dcbSerialParams.BaudRate = CBR_9600;   // Setting BaudRate = 9600
dcbSerialParams.ByteSize = 8;          // Setting ByteSize = 8
dcbSerialParams.StopBits = ONESTOPBIT; // Setting StopBits = 1
dcbSerialParams.Parity = NOPARITY;     // Setting Parity = None

Status = SetCommState(hComm, &dcbSerialParams); //Configuring the port according to settings in DCB

/*if (Status == FALSE)
{
    printf("
   Error! in Setting DCB Structure");
}
else
{
    printf("
   Setting DCB Structure Successfull
");
    printf("
       Baudrate = %d", dcbSerialParams.BaudRate);
    printf("
       ByteSize = %d", dcbSerialParams.ByteSize);
    printf("
       StopBits = %d", dcbSerialParams.StopBits);
    printf("
       Parity   = %d", dcbSerialParams.Parity);
}*/

/*------------------------------------ Setting Timeouts --------------------------------------------------*/

COMMTIMEOUTS timeouts;

timeouts.ReadIntervalTimeout = 0;
timeouts.ReadTotalTimeoutConstant = 0;
timeouts.ReadTotalTimeoutMultiplier = 1;
timeouts.WriteTotalTimeoutConstant = 0;
timeouts.WriteTotalTimeoutMultiplier = 0;

/*if (SetCommTimeouts(hComm, &timeouts) == FALSE)
    printf("
   Error! in Setting Time Outs");
else
    printf("

   Setting Serial Port Timeouts Successfull");*/
    

Body codes:

char squareNumber[10];
int clickedCount;

while(1){

printf("Enter number to find square : ");
scanf("%s",&squareNumber);                 // get number from user
int count = strlen(squareNumber);

writeData(squareNumber,Status,hComm,count);  // send data func
            
getData(Status , hComm , dwEventMask, TempChar,NoBytesRead,SerialBuffer,I);  // get data func

getch(); 

}

writeData func:

void writeData(char data[] , BOOL Status , HANDLE hComm , int count){
/*----------------------------- Writing a Character to Serial Port--------------------------------*/

char lpBuffer[count];    // lpBuffer should be  char or byte array, otherwise write wil fail
memcpy(lpBuffer, data,count);   
DWORD dNoOFBytestoWrite;     // No of bytes to write into the port
DWORD dNoOfBytesWritten = 0; // No of bytes written to the port

dNoOFBytestoWrite = sizeof(lpBuffer); // Calculating the no of bytes to write into the port

Status = WriteFile(hComm,              // Handle to the Serialport
                   lpBuffer,           // Data to be written to the port
                   dNoOFBytestoWrite,  // No of bytes to write into the port
                   &dNoOfBytesWritten, // No of bytes written to the port
                   NULL);

/*if (Status == TRUE)
    printf("

    %s - Written to %s", lpBuffer, ComPortName);
else
    printf("

   Error %d in Writing to Serial Port", GetLastError());*/

}

getData func:

void getData(BOOL Status , HANDLE hComm, DWORD dwEventMask , char TempChar, DWORD NoBytesRead, char 
SerialBuffer[],int i){

/*------------------------------------ Setting Receive Mask --------------------------------------*/

Status = SetCommMask(hComm, EV_RXCHAR); //Configure Windows to Monitor the serial device for 
Character Reception

if (Status == FALSE)
    printf("

    Error! in Setting CommMask");
else
    printf("

    Setting CommMask successfull");

/*------------------------------------ Setting WaitComm() Event   --------------------------------*/

printf("

    Waiting for Data Reception");

Status = WaitCommEvent(hComm, &dwEventMask, NULL); //Wait for the character to be received

/*-------------------------- Program will Wait here till a Character is received ------------------------*/

if (Status == FALSE)
{
    printf("
    Error! in Setting WaitCommEvent()");
}
else 
    //If  WaitCommEvent()==True Read the RXed data using ReadFile();
{
    printf("

    Characters Received");
    do
    {
        Status = ReadFile(hComm, &TempChar, sizeof(TempChar), &NoBytesRead, NULL);
        SerialBuffer[i] = TempChar; 
        i++;
    } while (NoBytesRead > 0);    //!!!Probably bug is here
        
    /*------------Printing the RXed String to Console----------------------*/

    printf("

");
    int j = 0;
    for (j = 0; j < i - 1; j++) // j < i-1 to remove the dupliated last character
        printf("%c", SerialBuffer[j]);
}

}

Arduino codes:

void setup() {
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  Serial.begin(9600);
  Serial.setTimeout(1000);

  }

void loop() {
    if (Serial.available() > 0) {
       incomingByte = Serial.read();

       int variable = Serial.parseInt();
       Serial.print("Square : ");
       Serial.print(variable*variable);

       }
   }
question from:https://stackoverflow.com/questions/65835829/serial-communication-read-serial-is-very-low-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...