当前位置:首页 » 编程语言 » c语言串口

c语言串口

发布时间: 2023-04-16 19:33:57

c语言串口通讯过程

分接收端和发送端。
接收端:
1·打开com1端口
fd=fopen("/dev/ttys0",方式);
2·取得当前串口值,保存到结构体变量oldtio
tcgetattr(fd,&oldtio);
3·串口结构体变量newtio清0.
bzero(&newtio,sizeof(newtio))
4·设置串口参数
主要设置比特率、是否忽略奇偶校验错误,启用正规模式等等。
接收端
1·打开com端口
2·取得当前串口值
3·串口结构体变量清0
4·设置串口参数。

② C语言变成实现串口收发数据

#include <reg51.h>

#include <intrins.h>

unsigned char key_s, key_v, tmp;

char code str[] = "welcome!www.willar.com ";

void send_str();

bit scan_key();

void proc_key();

void delayms(unsigned char ms);

void send_char(unsigned char txd);

sbit K1 = P1^4;

main()

{

TMOD = 0x20; // 定时器1工作于8位自动重载模式, 用于产生波特率

TH1 = 0xFD; // 波特率9600

TL1 = 0xFD;

SCON = 0x50; // 设定串行口工作方式

PCON &= 0xef; // 波特率不倍增

TR1 = 1; // 启动定时器1

IE = 0x0; // 禁止任何中断

while(1)

{

if(scan_key()) // 扫描按键

{

delayms(10); // 延时去抖动

if(scan_key()) // 再次扫描

{

key_v = key_s; // 保存键值

proc_key(); // 键处理

}

}

if(RI) // 是否有数据到来

{

RI = 0;

tmp = SBUF; // 暂存接收到的数据

P0 = tmp; // 数据传送到P0口

send_char(tmp); // 回传接收到的数据

}

}

}

bit scan_key()

// 扫描按键

key_s = 0x00;

key_s |= K1;

return(key_s ^ key_v);

}

void proc_key()

// 键处理

{

if((key_v & 0x01) == 0)

{ // K1按下

send_str(); // 传送字串"welcome!...

}

}

void send_char(unsigned char txd)

// 传送一个字符

{

SBUF = txd;

while(!TI); // 等特数据传送


TI = 0; // 清除数据传送标志

}

void send_str()

// 传送字串

{

unsigned char i = 0;

while(str[i] != '')

{

SBUF = str[i];

while(!TI); // 等特数据传送

TI = 0; // 清除数据传送标志

i++; // 下一个字符

}

}

void delayms(unsigned char ms)

// 延时子程序

{

unsigned char i;

while(ms--)

{

for(i = 0; i < 120; i++);

}

}

拓展资料

C语言是一门通用计算机编程语言,应用广泛。C语言的设计目标是提供一种能以简易的方式编译、处理低级存储器、产生少量的机器码以及不需要任何运行环境支持便能运行的编程语言。

尽管C语言提供了许多低级处理的功能,但仍然保持着良好跨平台的特性,以一个标准规格写出的C语言程序可在许多电脑平台上进行编译,甚至包含一些嵌入式处理器(单片机或称MCU)以及超级电脑等作业平台。

二十世纪八十年代,为了避免各开发厂商用的C语言语法产生差异,由美国国家标准局为C语言制定了一套完整的美国国家标准语法,称为ANSI C,作为C语言最初的标准。目前2011年12月8日,国际标准化组织(ISO)和国际电工委员会(IEC)发布的C11标准是C语言的第三个官方标准,也是C语言的最新标准,该标准更好的支持了汉字函数名和汉字标识符,一定程度上实现了汉字编程。



③ c语言怎么实现串口通信

编程原理
程序1为查询通信方式接口程序,为一典型的数据采集例程。其中bioscom()函数初始化COM1(此函数实际调用BIOS
INT
14H中断0号功能)。这样在程序中就避免了具体设置波特率因子等繁琐工作,只需直接访问发送/接收寄存器(3F8H)和线路状态寄存

④ windows下C语言怎么对串口进行读写操作

windows下对串口的操作可以通过WindowsAPI进行,也可以通过Linux下的read什么的直接操作,但是这种情况需要了解电路结构,比较麻烦,第三种有第三方提供的库,但是大多数针对C++,所以可能比较难找到顺手的第三方库.
那么,接下来就见要介绍一下串口通信用WindowsAPI通信的方式.

我们会发现,在文件名的位置填上"comX" X表示com口号,超过十的com口号需要另外的书写方式,这里不说了,因为网上一抓一大把,接下来,我们要对串口进行一系列的明确设置,这里就用到了一个结构体DCB结构,是专门用来描述一个com口的工作方式的,由于次结构体有28个成员,非常多,而且大部分的设置都是全世界通用的,所以,我们偷个懒,在打开一个com口之后,建立DCB结构体,接下来调用一个函数GetCommState用这个函数把现在com口的数据都写到DCB里,这样,比较通用的com口设置就已经弄好了,我们一般情况下只需要改一下DCB的波特率就好了,改好后马上用SetCommState把刚改好的结构体再写回去,这样串口就设置好了,现在还有点麻烦,串口设置好了,我们要它干什么呢?废话,读写数据呗,嘟~~~~~~可不能用fwrite和fread因为这个com口句柄不是文件句柄,是内核句柄,要用ReadFile和WriteFile来进行读写,又出麻烦了,我们怎么知道单片机什么时候发数据过来,就算我们知道,计算机什么时候知道啊?所以,一般的情况下,用ReadFile一直在哪检查,又是麻烦,通常情况下,一个com口的ReadFile设置是阻塞函数,影响编程啊!!!!!!

怎么办,很简单,你不阻塞吗,打通你呗,我们再建立里一个结构体COMMTIMEOUTS这个结构体描述里一个com口的相关超时设置,我们用GetCommTimeouts把数据读回来,具体的设置方法在网上也有,但是要注意,有一个MAXDWORD用它来设置读间隔超时设置就可以使ReadFile向kbhit()函数一样完全非阻塞了.
经过一些列的设置,事实上,现在已经可以通信了,要是有人觉得缓存不舒服,用SetupComm函数来重设缓存大小,对于传输速度比较快的通信,要把缓存设置的大些.

⑤ C语言串口收发数据

你波特率 没设置正确吧 是否SMOD寄存器置1把波特率加倍了?

⑥ c 获取串口号 c 自动获取串口号

用C怎么写获取串口的内容

看驱动程序的接口啊

一般是是open(“口名”)

用C/C++写一扒游个小程序读取串口接收到贺此销的数据

你太幸运了,刚好我有一个,你在禅游vc++6.0下测试一下。

/* serrecv.c */

/* Receives and saves a file over a serial port */

/* Last modified: Septemeber 21, 2005 */

/* [goman89] */

#include

#include

#include

/* Function to print out usage information */

void usage(void);

/* Function to set up the serial port settings with the specified baud rate,

no parity, and one stop bit */

void set_up_serial_port(HANDLE h, long baud);

/* Function to receive and save file from serial port */

void get_file_from_serial_port(HANDLE h, char *file_name, unsigned long file_length);

int main(int argc, char **argv)

{

HANDLE serial_port; /* Handle to the serial port */

long baud_rate = 9600; /* Baud rate */

char port_name[] = "COM1:"; /* Name of serial port */

unsigned long file_size; /* Size of file to receive in bytes */

unsigned long bytes_received; /* Bytes received from serial port */

unsigned long file_name_size; /* Size of file name in bytes */

char file_name[256]; /* Name of file to receive */

/* Check mand line */

if (argc == 3)

{

/* Read in baud rate */

if (argv[1][1] != 'b' || sscanf(argv[2], "%ld", &baud_rate) != 1)

{

usage;

exit(0);

}

}

else if (argc != 1)

{

usage;

exit(0);

}

/* Open up a handle to the serial port */

serial_port = CreateFile(port_name, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

/* Make sure port was opened */

if (serial_port == INVALID_HANDLE_VALUE)

{

fprintf(stderr, "Error opening port ");

CloseHandle(serial_port);

exit(0);

}

/* Set up the serial port */

set_up_serial_port(serial_port, baud_rate);

/* Receive file name size from serial port */

ReadFile(serial_port, (void *)&file_name_size, sizeof(unsigned long), &bytes_received, NULL);

if (bytes_received != sizeof(unsigned long))

{

fprintf(stderr, "Error getting file name size. ");

CloseHandle(serial_port);

exit(0);

}

/* Receive file name from serial port */

ReadFile(serial_port, (void *)file_name, file_name_size, &bytes_received, NULL);

if (bytes_received != file_name_size)

{

fprintf(stderr, "Error retrieving file name. ");

CloseHandle(serial_port);

exit(0);

}

/* Append NULL terminator to end of string */

file_name[bytes_received] = ''

/* Receive file size from serial port */

ReadFile(serial_port, (void *)&file_size, sizeof(unsigned long), &bytes_received, NULL);

if (bytes_received != sizeof(unsigned long))

{

fprintf(stderr, "Error getting file size. ");

CloseHandle(serial_port);

exit(0);

}

/* Get the file from the serial port */

get_file_from_serial_port(serial_port, file_name, file_size);

/* Print out success information */

printf(" %lu bytes successfully received and saved as %s ", file_size, file_name);

/* Close handle */

CloseHandle(serial_port);

return 0;

}

void usage(void)

{

fprintf(stderr, "Usage: ");

fprintf(stderr, " serrecv [-b baud rate] ");

fprintf(stderr, " Default baud rate is 9600 ");

fprintf(stderr, "tSupported baud rates: 1200, 2400, 4800, 9600, 14400, 19200 ");

return;

}

void set_up_serial_port(HANDLE h, long baud)

{

DCB properties; /* Properties of serial port */

/* Get the properties */

GetmState(h, &properties);

/* Set the baud rate */

switch(baud)

{

case 1200:

properties.BaudRate = CBR_1200;

break;

case 2400:

properties.BaudRate = CBR_2400;

break;

case 4800:

properties.BaudRate = CBR_4800;

break;

case 9600:

properties.BaudRate = CBR_9600;

break;

case 14400:

properties.BaudRate = CBR_14400;

break;

case 19200:

properties.BaudRate = CBR_19200;

break;

case 38400:

properties.BaudRate = CBR_38400;

break;

default:

fprintf(stderr, "Invalid baud rate: %ld ", baud);

usage;

exit(0);

break;

}

/* Set the other properties */

properties.Parity = NOPARITY;

properties.ByteSize = 8;

properties.StopBits = ONESTOPBIT;

SetmState(h, &properties);

return;

}

void get_file_from_serial_port(HANDLE h, char *file_name, unsigned long file_length)

{

FILE *data_file; /* File to create */

unsigned long bytes_left = file_length; /* Bytes left to receive */

unsigned long bytes_received_total = 0; /* Total bytes received */

unsigned long bytes_to_receive; /* Number of bytes to receive */

unsigned long bytes_received; /* Number of bytes receive */

char buffer[200]; /* Buffer to store data */

/* Open the file */

data_file = fopen(file_name, "wb");

/* Quit if file couldn't be opened */

if (data_file == NULL)

{

fprintf(stderr, "Could not create file %s ", file_name);

CloseHandle(h);

exit(0);

}

while (1)

{

/* Determine how many bytes to read */

if (bytes_left == 0)

{

break;

}

else if (bytes_left < 200)

{

bytes_to_receive = bytes_left;

}

else

{

bytes_to_receive = 200;

}

/* Receive data over serial cable */

ReadFile(h, (void *)buffer, bytes_to_receive, &bytes_received, NULL);

if (bytes_received != bytes_to_receive)

{

fprintf(stderr, "Error reading file. ");

CloseHandle(h);

exit(0);

}

/* Save buffer to file */

fwrite((void *)buffer, 1, bytes_received, data_file);

/* Decrement number of bytes left */

bytes_left -= bytes_received;

/* Increment number of bytes received */

bytes_received_total += bytes_received;

/* Print out progress */

printf(" %5lu bytes received.", bytes_received_total);

}

fclose(data_file);

return;

}

C语言变成实现串口收发数据

#include

#include

intmain(void)

{

FILE*fp;

chartemp;

charbuf[100];

if((fp=fopen("3","r"))==NULL)

puts("thiswaydoesn'twork! ");

else

puts("thiswayworks! ");

while(1)

{

temp=0;

fscanf(fp,"%c",&temp);

if(temp!=0)

putchar(temp);

else

Sleep(100);

}

fclose(fp);

return0;

}

以前弄的,好久没看了,不知到对不对。

还有下面这段:

#include

#include

HANDLEh;

intmain(void)

{

h=CreateFile(TEXT("COM3"),//COM1口

GENERIC_READ|GENERIC_WRITE,//允许读和写

0,//独方式

NULL,

OPEN_EXISTING,//打开而不是创建

0,//同步方式

NULL);

if(h==(HANDLE)-1)

{

printf("打开COM失败! ");

returnFALSE;

}

else

{

printf("COM打开成功! ");

}

Setupm(h,1024,1024);//输入缓冲区和输出缓冲区大小都是1024

COMMTIMEOUTSTimeOuts;

//设读超时

TimeOuts.ReadIntervalTimeout=1000;

TimeOuts.ReadTotalTimeoutMultiplier=500;

TimeOuts.ReadTotalTimeoutConstant=5000;

//设定写超时

TimeOuts.WriteTotalTimeoutMultiplier=500;

TimeOuts.WriteTotalTimeoutConstant=2000;

SetmTimeouts(h,&TimeOuts);//设置超时

DCBdcb;

GetmState(h,&dcb);

dcb.BaudRate=9600;//波特率为9600

dcb.ByteSize=8;//每个字节有8位

dcb.Parity=NOPARITY;//无奇偶校验位

dcb.StopBits=ONE5STOPBITS;//两个停止位

SetmState(h,&dcb);

DWORDwCount;//读取的节数

BOOLbReadStat;

while(1)

{

Purgem(h,PURGE_TXCLEAR|PURGE_RXCLEAR);//清缓冲区

charstr[9]={0};

printf("%s ",str);

bReadStat=ReadFile(h,str,9,&wCount,NULL);

if(!bReadStat)

{

printf("

怎么通过串口读取51单片机某个地址的数据?请用C语言写出来。

*

授人以鱼,不如授人以渔

*

首先,你要明确在C语中读取内存址是基于指针。

3.比如读取内存地址0x22中的数据

C语言中对于内存的访是基于指,这个毋庸置疑,具体操如下

unsigned int *p= (unsigned int*)0x22 ;//定义针,并且使指针指向了0x22这个 内存地址;

那么*p就是最终你要读取的数据了。

4.至于如何通过串口显示到电脑我就不多了(这不是难点),据你都知道了,写到串口 缓冲区,在串口调试助手下就可以看到。

5.虽然没有贴出具体代码,但这里面的思想可以让你解决

标签:作文经典 上一篇:描写毛毛虫的词语 描写毛毛虫行动的词语 下一篇:成语误用褒贬的例子 褒贬误用的成语

Linux下如何使用c/c++实现检测新增串口,并读取串口号

Linux下面有设文件

串口装好驱动后 会显示在dev下

然后对这个

C语言中如何对串口进行操作

C语言会有操作串口的库函数的,按照串口库数标识实现调

电脑上的串口号是什么意思

串口叫做串行接口,也串行通信接口,按电气标准及协议来分包括RS-232-C、RS-422、RS485、USB等。 RS-232-C、RS-422与RS-485标准对接口的电气特性做出规定,不涉及接插件、电缆或协议。USB是近几年发展起来的新型接口标准,主要应用于速数据传输域。 RS-232-C:也称标准串口,是目前最常用的一种串行通讯接口。它是在1970年由美国电子工业协会(EIA)联合贝尔系统、 调制解调器厂家及计算机终端生产厂共同制定的用于串行通讯的标 准。它的名是“数据终端设备(DTE)和数据通讯设备(DCE)之间 行二进制数据交换接口技术标准”。传统的RS-232-C接口标准有22根线,采用标准25芯D型插头座。后来的PC上使用简化了的9芯D插座。现在应用中25芯插头已很少采用。现在的电脑般有两个串行口:COM1和COM2,你到计算机后面能看到9针D形接口就是了。现在有很多手数据线或者物流接收器都采用COM

如何用C语言写一个读、写串口的程序?

大致过程就是

配置串口通信,包串口号、波特、验位、停止位这些信息;

打开串口,和打开文件一样,在Linux是这样,Windows下没试过,估计也差不多;

发送数据,即写串口,就跟写文件类似;

读取

编写单片机串口收发数据的完整程序(C语言编写)

我用的新唐芯片,8051内核,跟51差不多,望采纳

void UART_Initial (void)

{

P02_Quasi_Mode; //Setting UART pin as Quasi mode for tran *** it

P16_Quasi_Mode; //Setting UART pin as Quasi mode for tran *** it

SCON_1 = 0x50; //UART1 Mode1,REN_1=1,TI_1=1

T3CON = 0x08; //T3PS2=0,T3PS1=0,T3PS0=0(Prescale=1), UART1 in MODE 1

clr_BRCK;

RH3 = HIBYTE(65536 - (1000000/u32Baudrate)-1); /*16 MHz */

RL3 = LOBYTE(65536 - (1000000/u32Baudrate)-1); /*16 MHz */

set_TR3; //Trigger Timer3

}

以上是初始化的

void Send_Data_To_UART1(UINT8 c)

{

TI_1 = 0;

SBUF_1 = c;

while(TI_1==0);

}

这个是发送

void UART_isr (void) interrupt 4 //

怎样在WINDOWS下用C语言编写串口接收数据程序

#include

#include

int main(void)

{

FILE *fp;

char temp;

char buf[100];

if((fp = fopen("3","r")) == NULL)

puts("this way doesn't work! ");

else

puts("this way works! ");

while(1)

{

temp = 0;

fscanf(fp,"%c",&temp);

if(temp != 0)

putchar(temp);

else

Sleep(100);

}

fclose(fp);

return 0;

}

以前的,好久看,不知到对不对。

还下面这段:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

#include

#include

HANDLE h;

int main(void)

{

h=CreateFile(TEXT("COM3"),//COM1口

GENERIC_READ|GENERIC_WRITE, //允许读和写

0, //独占方式

NULL,

OPEN_EXISTING, //打开而不是建

0, //同步式

NULL);

if(h==(HANDLE)-1)

{

printf("打开COM失败! ");

return FALSE;

}

else

{

printf("COM打开成功! ");

}

Setupm(h,1024,1024); //输入缓冲区和输出缓冲区的大小都是1024

COMMTIMEOUTS TimeOuts;

//定读超时

TimeOuts.ReadIntervalTimeout=1000;

TimeOuts.ReadTotalTimeoutMultiplier=500;

TimeOuts.ReadTotalTimeoutConstant=5000;

//设定写超时

TimeOuts.WriteTotalTimeoutMultiplier=500;

TimeOuts.WriteTotalTimeoutConstant=2000;

SetmTimeouts(h,&TimeOuts); //设置超时

DCB dcb;

GetmState(h,&dcb);

dcb.BaudRate=9600; //波特率为9600

dcb.ByteSize=8; //每个字节有8位

dcb.Parity=NOPARITY; //无奇偶校验位

dcb.StopBits=ONE5STOPBITS; //两个停止位

SetmState(h,&dcb);

DWORD wCount;//读取的字节

BOOL bReadStat;

while(1)

{

Purgem(h,PURGE_TXCLEAR|PURGE_RXCLEAR); //清空缓冲区

char str[9]={0};

printf("%s ",str);

bReadStat=ReadFile(h,str,9,&wCount,NULL);

if(!bReadStat)

{

printf("读串口

标签:作文经典 上一篇:描写毛毛虫的词语 描写毛毛虫行动的词语 下一篇:成语误用褒贬的例子 褒贬误用的成语

⑦ 如何用C语言控制计算机串口

基本方法是使用CreateFile来建立一个串口文件,然后用overlap的方式进行读写

#define SERAIL_PORT_BUF_MAX (1024*8)
typedef HRESULT (*PFN_CMD_PARSE_DATA)(HANDLE hParseApp, LPCSTR szRspCmd, int nCmdLen);

class CUsbSrvApp// : public CWinApp
{
public:
CUsbSrvApp();
~CUsbSrvApp();
BOOL OnSendData(const char *szBuf, int nLen);// 发送数据
int ComConnect(CString strPort); // 连接COM口
HANDLE OpenComPort(CString strPort, int nBaudRate, int nDataBits, int nStopBits, int nParity, int nFlowCtrlType); // 打开串口
void Close(); // 关闭串口

HANDLE m_hCom;
BOOL m_bConnected;
OVERLAPPED m_OverlappedRead;
OVERLAPPED m_OverlappedWrite;
CWinThread *m_pThread;

PFN_CMD_PARSE_DATA m_pRspCmdFunc; // 用来处理接受数据的CALLBACK
HANDLE m_hParseApp;
};

CUsbSrvApp::CUsbSrvApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
m_bConnected = false;
m_hCom = NULL;
m_pRspCmdFunc = NULL;
}

CUsbSrvApp::~CUsbSrvApp()
{
}
//打开串口通信,并返回串口句柄
HANDLE CUsbSrvApp::OpenComPort(CString strPortName,
int nBaudRate,
int nDataBits,
int nStopBits,
int nParity,
int nFlowCtrlType)
{
DCB dcb;
COMMTIMEOUTS CommTimeOuts ;
COMMCONFIG ComConfig;
HANDLE hComPort;

CString strPort;
strPort.Format("\\\\.\\%s",strPortName); // COM口的文件名应该是 \\.\COMXX

//打开窗口其实就是创建一个文件
hComPort = CreateFile(strPort,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,
NULL);

if (INVALID_HANDLE_VALUE == hComPort)
return INVALID_HANDLE_VALUE;

// 设置一些COM口通讯参数和OVERLAP
CommTimeOuts.ReadIntervalTimeout = -1;
CommTimeOuts.ReadTotalTimeoutConstant = 0;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0;
CommTimeOuts.WriteTotalTimeoutConstant = 0;
CommTimeOuts.WriteTotalTimeoutMultiplier = 0x1388;
SetCommTimeouts( m_hCom, &CommTimeOuts ) ;

SetDefaultCommConfig(strPortName, &ComConfig, sizeof(COMMCONFIG));
GetCommState(m_hCom, &dcb ) ;

dcb.BaudRate = nBaudRate;
dcb.ByteSize = nDataBits;
dcb.StopBits = nStopBits;
dcb.fParity = (NOPARITY != nParity);
dcb.Parity = nParity;
//set the receive char
dcb.EvtChar = 0x0D;

switch(nFlowCtrlType)
{
case 0: //no flow control
break;

case 1://HARD_FLOW_CTRL:

dcb.fOutxCtsFlow = TRUE;
dcb.fOutxDsrFlow = TRUE;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcb.fDsrSensitivity = TRUE;
dcb.fRtsControl = RTS_CONTROL_TOGGLE;
break;

case 2://SOFT_FLOW_CTRL:
dcb.fOutX = TRUE;
dcb.fInX = TRUE;
break;
}
BuildCommDCB(_T("baud=115200 parity=N data=8 stop=1"),&dcb);
SetCommState(hComPort, &dcb ) ;
SetCommMask(hComPort, 0);
SetCommMask(hComPort, EV_RXCHAR|EV_CTS|EV_DSR|EV_RLSD|EV_RING);
SetupComm( hComPort, SERAIL_PORT_BUF_MAX,SERAIL_PORT_BUF_MAX) ;
//clear read and write buffer
PurgeComm( hComPort, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR );

return hComPort;
}

void CUsbSrvApp::Close()
{
if(m_bConnected)
{
m_bConnected = false;
CloseHandle(m_hCom);
m_hCom = NULL;
}
}

// 这个线程是监视串口数据,一旦有数据则读取并调用CALLBACK通知客户端
UINT ReceiveComData(LPVOID pParam)
{
CUsbSrvApp *pUsbSrv = (CUsbSrvApp *)pParam;
HANDLE hComPort = pUsbSrv->m_hCom;

DWORD dwEvtMask=0;
DWORD dwErrorFlags;

SetCommMask( hComPort, EV_RXCHAR);
OVERLAPPED osRead;
osRead.hEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
DWORD dwTransfer = 0;
while(pUsbSrv->m_bConnected)
{
if( !WaitCommEvent( hComPort, &dwEvtMask,&osRead))
{
if( GetLastError()== ERROR_IO_PENDING)
{
WaitForSingleObject(osRead.hEvent, INFINITE);
if(dwEvtMask&EV_RXCHAR==EV_RXCHAR)
{
COMSTAT ComStat={0} ;
DWORD dwReadLen = 0;
DWORD dwBytesRead = 0;
DWORD dwTotalLen = 0;
ClearCommError(hComPort, &dwErrorFlags, &ComStat );
dwTotalLen = ComStat.cbInQue;
dwReadLen = (SERAIL_PORT_BUF_MAX > dwTotalLen)?dwTotalLen:SERAIL_PORT_BUF_MAX;

BYTE *pBuf = new BYTE[dwTotalLen+1];
memset(pBuf, 0 , dwTotalLen+1);
DWORD nReadBufLen=0;
while(dwTotalLen>0)
{

if(FALSE == ReadFile( hComPort, pBuf+nReadBufLen,dwReadLen, &dwBytesRead,&pUsbSrv->m_OverlappedRead))
{
if(GetLastError() == ERROR_IO_PENDING)
{
GetOverlappedResult(hComPort,&osRead, &dwTransfer, TRUE );
}
break;
}

nReadBufLen +=dwBytesRead;
dwTotalLen -=dwBytesRead;
dwReadLen -= dwBytesRead;
dwReadLen = (SERAIL_PORT_BUF_MAX>dwReadLen)?dwReadLen:SERAIL_PORT_BUF_MAX;
}
if(pUsbSrv->m_pRspCmdFunc!=NULL&&nReadBufLen!=0)
{
pUsbSrv->m_pRspCmdFunc(pUsbSrv->m_hParseApp, (char*)pBuf,nReadBufLen);
}

delete pBuf;

ClearCommError(hComPort, &dwErrorFlags, &ComStat );
int len =0;//= m_retList.GetSize();
}//endif if(dwEvtMask&EV_RXCHAR==EV_RXCHAR)
}//endif if( GetLastError()== ERROR_IO_PENDING)
}//endif if( !WaitCommEvent( hComPort, &dwEvtMask,&o))
else
{
if(GetLastError() == ERROR_IO_PENDING) {
GetOverlappedResult(hComPort, &osRead, &dwTransfer, TRUE ); // sleep thread
}
}
Sleep(1);
} //endwhile while(m_bConnected)
return 0;
}

int CUsbSrvApp::ComConnect(CString strPort)
{
int nBaudRate = 115200;
int nDataBits = 8;
int nStopBits = 1;
int nParity = 0;
int nFlowCtrl = 1;

if (NULL != m_hCom || m_bConnected)
{
return 0;
}
m_hCom = OpenComPort(strPort,nBaudRate,nDataBits,nStopBits,nParity,nFlowCtrl);
if( INVALID_HANDLE_VALUE == m_hCom)
{
m_hCom = NULL;
return 0;
}
memset( &m_OverlappedRead, 0, sizeof( OVERLAPPED ) );
memset( &m_OverlappedWrite, 0, sizeof( OVERLAPPED ) );
m_OverlappedRead.hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
m_OverlappedWrite.hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );

m_pThread = AfxBeginThread( ReceiveComData,(void*)this,THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED ,NULL );

if( NULL == m_pThread )
{
CloseHandle( m_hCom );
m_hCom = NULL;
return FALSE;
}
else
{
m_bConnected = TRUE;
m_pThread->ResumeThread( );
}

return TRUE;
}

int CUsbSrvApp::OnSendData(const char *szBuf, int nLen)
{
BOOL bWriteStat;
BOOL bWrite = TRUE;
DWORD dwBytesWrite = 0;
DWORD dwBytesWritten = 0;
int dwByteswrittenTotal = 0;

if (NULL == m_hCom)
return 0;

int nSentTimes=0;

while(dwByteswrittenTotal<nLen&&nSentTimes<10)
{
nSentTimes++;
dwBytesWrite = nLen-dwByteswrittenTotal;
bWriteStat = WriteFile( m_hCom, szBuf+dwByteswrittenTotal, dwBytesWrite, &dwBytesWritten, &m_OverlappedWrite );

if( !bWriteStat)
{
if ( GetLastError() == ERROR_IO_PENDING )
{
dwBytesWritten = 0;
bWrite = FALSE;
}
}
if (!bWrite)
{
bWrite = TRUE;

bWriteStat = GetOverlappedResult(m_hCom, // Handle to COMM port
&m_OverlappedWrite, // Overlapped structure
&dwBytesWritten, // Stores number of bytes sent
TRUE); // Wait flag
//deal with the error code
}
dwByteswrittenTotal += dwBytesWritten;
}
if(dwByteswrittenTotal<nLen)
return 0;
else
return 1;
}

热点内容
华为ftp在哪 发布:2024-11-01 22:36:33 浏览:288
java数组包含字符串 发布:2024-11-01 22:31:15 浏览:791
服务器和家用电脑质量 发布:2024-11-01 22:28:29 浏览:488
sqlserver默认实例 发布:2024-11-01 22:23:42 浏览:959
sort排序java 发布:2024-11-01 22:23:26 浏览:47
解压后的apk无法安装 发布:2024-11-01 22:22:10 浏览:666
公司的pop服务器地址 发布:2024-11-01 22:22:07 浏览:119
朵唯m30手机配置是真的吗如何 发布:2024-11-01 22:16:56 浏览:681
梦幻西游怎么清理缓存 发布:2024-11-01 22:15:52 浏览:345
如何配置fcm 发布:2024-11-01 22:08:15 浏览:854