Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
In both codes following, I expect that PC print "3". but PC print like below screenshot.
Why like this? How do I get "3"? plz help me.

Arduino
int sign;
void setup()
{
  Serial.begin(9600); //시리얼 포트 열기, 속도 9600
}
void loop()
{
  sign=3;
  Serial.write(sign);
  delay (1000);
}

PC
#include<stdio.h>
#include<windows.h>
#include<winbase.h>
int main()
{
 char szPort[15];  
 wsprintf(szPort, "COM%d", 3); 
 HANDLE  m_hComn = NULL;  
 m_hComn = CreateFile(szPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    
 if (m_hComn == INVALID_HANDLE_VALUE)  
 {
  printf("(!) Failed to create a  Comm Device file \n");
  return FALSE;   
 }
 DCB dcb;       
 dcb.DCBlength = sizeof(DCB); 
 GetCommState(m_hComn, &dcb);    
 dcb.BaudRate = 9600;
 dcb.ByteSize = 8;
 dcb.Parity = 0;
 dcb.StopBits = 0;
 SetCommState(m_hComn, &dcb); 

 OVERLAPPED  osRead;
 osRead.Offset = 0;
 osRead.OffsetHigh = 0;
 osRead.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

 int buf ; //

 while (1)
 {
  ReadFile(m_hComn, &buf,sizeof(buf), NULL, &osRead);
  printf("%d \n", buf);
 }
 
 CloseHandle(m_hComn);  
 return 0;
}
Posted
Updated 20-Jan-16 4:18am
v2
Comments
jeron1 20-Jan-16 10:20am    
There is no screen shot, what is the output?

1 solution

Your Arduino code sends a byte at time (see Arduino - Write[^]), so your PC code should read a single byte and output it (it could optionally read multiple bytes, buffer and then output all of them), so the proper call to ReadFile (I hardly believe you need the OVERLAPPED struct in such a simple scenario) is:
C++
unsigned char c;
DWORD dwRead;
if ( ReadFile( hComm, &c, sizeof(c), &dwRead, NULL) )
{
  if ( dwRead == 1)
    printf("%d\n", (int) c);
}
else
{// handle error
}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 20-Jan-16 11:53am    
5ed.
—SA
CPallini 20-Jan-16 12:01pm    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900