Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1000837
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T07:34:33+00:00 2026-05-16T07:34:33+00:00

I am having a problem with a Serial Port communication between Arduino Nano and

  • 0

I am having a problem with a Serial Port communication between Arduino Nano and C++, even though the problem is in C++ side. Basically I want to send integers (or long,…) from the Arduino to a C++ program to be processed.

First I did a test sending information from the Arduino to the computer using Matlab. The Arduino code is pretty simple:

int i = 0;

void setup() {

   // start serial port at 9600 bps:
   Serial.begin(9600);
   establishContact(); 
}

void loop() {
  Serial.println(i);
  i=i+1;  
  delay(10);
}

void establishContact() {
   while (Serial.available() <= 0) {
     Serial.println('A', BYTE);
     delay(10);
   }
}

The Matlab side is also simple:

clc;
clear all;
numSec=2;
t=[];
v=[];

s1 = serial('COM3');    % define serial port
s1.BaudRate=9600;               % define baud rate
set(s1, 'terminator', 'LF');    % define the terminator for println
fopen(s1);

try                             % use try catch to ensure fclose
                                % signal the arduino to start collection
    w=fscanf(s1,'%s');              % must define the input % d or %s, etc.
    if (w=='A')
        display(['Collecting data']);
        fprintf(s1,'%s\n','A');     % establishContact just wants 
                                    % something in the buffer
    end

    i=0;
    t0=tic;
    while (toc(t0)<=numSec)
        i=i+1;
        t(i)=toc(t0);
        t(i)=t(i)-t(1);
        v(i)=fscanf(s1,'%d');     
    end

    fclose(s1);
    plot(t,v,'*r')   

catch me
    fclose(s1);                
end       

My goal is, with C++, do the same that is done in Matlab using fscanf(s1, ‘%d’).

Here is the current code that I am using (C++ code):

void main()
{
 HANDLE hSerial;
 hSerial = CreateFile(TEXT("COM3"), 
   GENERIC_READ | GENERIC_WRITE, 
   0,
   NULL, 
   OPEN_EXISTING,
   FILE_ATTRIBUTE_NORMAL,//FILE_FLAG_OVERLAPPED, 
   NULL);



if ( hSerial == INVALID_HANDLE_VALUE)
 {
  printf("Error initializing handler");
 } 
 else 
 {

  // Set the parameters of the handler to the serial port.
  DCB dcb = {0};

  dcb.DCBlength = sizeof(dcb);

  if ( !GetCommState(hSerial, &dcb) )
  {
   printf("Error setting parameters");
  }

  FillMemory(&dcb, sizeof(dcb), 0);
  dcb.BaudRate = CBR_9600;
  dcb.ByteSize = 8;
  dcb.StopBits = ONESTOPBIT;
  dcb.Parity = NOPARITY;

  if ( !SetCommState(hSerial, &dcb) )
  {
   // error setting serial port state.
  }

  // Tell the program not to wait for data to show up
  COMMTIMEOUTS timeouts = {0};

  timeouts.ReadIntervalTimeout = 0;//20;
  timeouts.ReadTotalTimeoutConstant = 0;//20;
  timeouts.ReadTotalTimeoutMultiplier = 0;//50;
  timeouts.WriteTotalTimeoutConstant = 0;//100;
  timeouts.WriteTotalTimeoutMultiplier = 0;//100;

  if ( !SetCommTimeouts(hSerial, &timeouts) )
  {
   printf("Error setting the timeouts");

  }

  char szBuff[5] = "";
  DWORD dwBytesRead = 0;
  int i = 0;
  char test[] = "B\n";
  int maxSamples = 10;
  DWORD dwCommStatus;

  WriteFile(hSerial, test, 2, &dwBytesRead, NULL);

  SetCommMask(hSerial,EV_RXCHAR);

  while (i < maxSamples)
  {
   WaitCommEvent (hSerial, &dwCommStatus, 0);

   if (dwCommStatus & EV_RXCHAR) 
   {
    memset(szBuff,0,sizeof(szBuff));
    ReadFile(hSerial, LPVOID(szBuff), 4, &dwBytesRead, NULL);

    cout<<szBuff;
    printf(" - %d - \n", atoi(szBuff));
   }
   i++;     
  }

  scanf("%d", &i);

  CloseHandle(hSerial);
 }
    }

The goal of my code would be something like num = ReadSerialCOM(hSerial, "%d");

My current C++ code reads the information from the buffer, but there is not an accepted end of line, which implies that my numbers (integers) are received cut.

Eg:

I send 8889 from the Arduino, which places it in the COM port. And the command ReadFile saves ’88’ into szBuff. At the next iteration ’89\n’ is saved into sZBuff. Basically I want to avoid to post-process sZBuff to concat ’88’ and ’89\n’.

Anyone?
Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T07:34:33+00:00Added an answer on May 16, 2026 at 7:34 am

    As Hans Passant and dauphic pointed, it doesn’t seem to be a general solution for my question. I am writing, though, the code that I was trying to avoid, just in case somebody finds it useful or face the same problem that I had:

    int i = 0;  
    DWORD dwBytesRead = 0;
    DWORD dwCommStatus = 0;
    char szBuff[2] = "";                
    int maxRead = 20;   
    int sizeNum = 1;    
    int *num    = (int*)malloc(maxRead*sizeof(int)); 
    char *currNum;
    char *pastNum;
    
    // Write something into the Serial Port to start receive 
    // information from the Arduino
    WriteFile(hSerial, (LPCVOID)"A\0", 1, &dwBytesRead, NULL);    
    SetCommMask(hSerial, EV_RXCHAR);
    
    // Start reading from the Serial Port
    while ( i < maxRead )
    {
        WaitCommEvent (hSerial, &dwCommStatus, 0);
    
        if (dwCommStatus & EV_RXCHAR) // if a char is received in the serial port
        {
            ReadFile(hSerial, LPVOID(szBuff), 1, &dwBytesRead, NULL);
    
            if ( szBuff[0] > 47 && szBuff[0] < 58 )
            {
                sizeNum++;
                if (sizeNum ==2)
                {
                    currNum = (char*)malloc(sizeNum*sizeof(char));
                    strcpy(currNum, szBuff);
                } else
                {
                    if (pastNum != NULL)
                        free(pastNum);
                    pastNum = currNum;
                    currNum = (char*)malloc(sizeNum*sizeof(char));
                    strcpy(currNum, pastNum);
                    strcpy(currNum+(sizeNum-2)*sizeof(char), szBuff);
                }
    
                cout << szBuff<<endl;   
            } else if (szBuff[0] == '\n' && sizeNum > 1) // end of number
            {
                num[i] = atoi(currNum);
                i++;                    
    
                sizeNum = 1;
                if (currNum!=NULL)
                    free(currNum);
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm having a problem with a program that communicates over a serial port. One
I am new to the world of C# and Serial communication. Having read a
I am having problem with calling the generated functions in serial. I am using
Having problem with the middle Div not expanding to the width http://acs.graphicsmayhem.com/images/middiv.jpg Ok, how
Im having problem extending the life of my session. I tried //start sessions ini_set('session.gc-maxlifetime',
I'm having problem about web service method with auto increment ID. I have a
We're having problem with a huge number of legacy stored procedures at work. Do
I'm having problem in the following line: rd.PrintOptions.PaperSize = PaperSize.PaperFanfoldStdGerman; it throws an exception
We are having problem with the server migration. We have one application that are
I'm having problem when running my Windows Forms program. In the program, I have

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.