Arduino和pc之间的串行通信问题 [英] serial communication problem between Arduino and pc

查看:84
本文介绍了Arduino和pc之间的串行通信问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下两个代码中,我希望PC打印3。但PC打印如下截图。

为什么这样?我怎么得到3?请帮助我。



Arduino

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


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;
}

推荐答案

您的Arduino代码会发送一个字节(参见 Arduino - 写 [ ^ ]),所以你的PC代码应该读取一个字节并输出它(它可以选择读取多个字节,缓冲区然后输出所有这些),所以正确调用 ReadFile (我几乎不相信你在这么简单的场景中需要 OVERLAPPED 结构)是:

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:
unsigned char c;
DWORD dwRead;
if ( ReadFile( hComm, &c, sizeof(c), &dwRead, NULL) )
{
  if ( dwRead == 1)
    printf("%d\n", (int) c);
}
else
{// handle error
}


这篇关于Arduino和pc之间的串行通信问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆