我正在编写一个与设备c#
应用程序通信的c
应用程序。
我正在尝试通过串行端口将数据从c#
应用程序写入c
应用程序,反之亦然。
我正在尝试使用以下代码编写一些示例数据。
C#
using PORT = System.IO.Port.SerialPort;
PORT p = new PORT("COM4", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
string data="HELLO";
//String to byte[] conversion
byte[] byt_buff = new byte[data.Length];
byt_buff = Encoding.ASCII.GetBytes(data);
p.Open();
p.DiscardOutBuffer();
p.Write(byt_buff, 0, byt_buff.Length);
p.Close();
在设备上运行的c
应用程序具有以下代码。
C
#include<stdio.h>
#include <poll.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include<stdint.h>
#include<string.h>
#define USB_DEV_NODE "usb.dat"
#define MAX_SIZE 20
int main()
{
int fd;
int ret_poll;
int ret_read;
struct pollfd pollfd;
char buf[MAX_SIZE];
int i = 0;
pollfd.events = POLLIN;
fd = open(USB_DEV_NODE, O_RDWR | O_NOCTTY);
pollfd.fd = fd;
while (1)
{
ret_poll = poll( &pollfd, 1, -1);
if( ret_poll == -1 )
{
printf("Gpio_poll poll failed\r\n");
close(fd);
}else{
if (pollfd.revents & POLLIN )
{
ret_read = read(fd, buf, MAX_SIZE);
buf[ret_read]=0;
if(ret_read > 0)
{
for(i=0;i<ret_read ; i++)
{
printf("BUF[%d]=%c\n",i,buf[i]);
}
}
}
}
}
return 0;
}
但是我没有收到写为byte[]
的数据,没有收到数据。相反,如果我使用 p.WriteLine(“ HELLO”); 以string
的形式写入数据,则会被接收。
请帮忙。