當前位置:首頁 » 編程語言 » 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;
}

熱點內容
s21更新了安卓12怎麼降級 發布:2024-11-02 00:35:11 瀏覽:99
編程要軟體嗎 發布:2024-11-02 00:34:59 瀏覽:235
androidcursor遍歷 發布:2024-11-02 00:27:40 瀏覽:767
網易我的世界地皮伺服器大全 發布:2024-11-02 00:24:20 瀏覽:964
光宇國際服怎麼安卓轉ios 發布:2024-11-02 00:14:23 瀏覽:170
魔獸世界單機資料庫 發布:2024-11-01 23:37:11 瀏覽:698
配置vlan後如何配置電腦ip 發布:2024-11-01 23:21:16 瀏覽:546
中鐵盾構機密碼是多少 發布:2024-11-01 23:07:21 瀏覽:708
工規存儲 發布:2024-11-01 22:59:33 瀏覽:802
無法識別加密狗 發布:2024-11-01 22:47:03 瀏覽:599