在做項目的時候需要實現這樣一個功能,在網上沒有找到很好的答案,突然有一天誤打誤撞實現了。這裏記錄一下,方便大家也能夠實現。
備註:
1、單片機使用模塊:HC-05藍牙模塊;
2、藍牙通信其實也是利用了串口,所以這裏先介紹一下對串口的讀寫:
3、主要使用API:CreateFile(),WriteFile(),ReadFile()。
代碼展示:
(這裏提供對串口進行讀寫操作的函數定義,可直接移植)
頭函數定義
# ifndef __uart_
#define __uart_
#include<windows.h>
#define RtlZeroMemory(Destination,Length) memset((Destination),0,(Length))
#define ZeroMemory RtlZeroMemory
BOOL Write(char *write_data, DWORD contentLen, DCB &dcb);
BOOL Read(char *read_data, DCB &dcb);
void DCB_init(DCB &dcb);
#endif // !__uart_
.c文件定義
#include "uart.h"
#include <iostream>
void DCB_init(DCB &dcb)
{
dcb.BaudRate = 9600;
dcb.ByteSize = 8;
dcb.Parity = 0;
dcb.StopBits = 1;
}
BOOL Write(char *write_data, DWORD contentLen,DCB &dcb)
{
HANDLE hcom;
char *tmpBuf;
DWORD dwBytesWrite = 0;
int dwBytesToWrite;
hcom = CreateFile(L"COM6", GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hcom == INVALID_HANDLE_VALUE)
{
printf("create file error!\n");
CloseHandle(hcom);
return FALSE;
}
SetupComm(hcom, 1024, 1024);
GetCommState(hcom, &dcb);
SetCommState(hcom, &dcb);
dwBytesToWrite = contentLen;
dwBytesWrite = 0;
tmpBuf = write_data;
do { //循環寫文件,確保完整的文件被寫入
WriteFile(hcom, tmpBuf, dwBytesToWrite, &dwBytesWrite, NULL);
dwBytesToWrite -= dwBytesWrite;
tmpBuf += dwBytesWrite;
} while (dwBytesToWrite > 0);
if (hcom != INVALID_HANDLE_VALUE)
{
CloseHandle(hcom);
hcom = INVALID_HANDLE_VALUE;
}
return TRUE;
}
BOOL Read(char *read_data,DCB &dcb)
{
HANDLE hcom;
DWORD fileSize;
char *buffer;
DWORD dwBytesRead, dwBytesToRead, tmpLen;
hcom = CreateFile(L"COM5", GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hcom == INVALID_HANDLE_VALUE)
{
printf("open file error!\n");
CloseHandle(hcom);
return FALSE;
}
fileSize = GetFileSize(hcom, NULL); //得到文件的大小
buffer = (char *)malloc(fileSize);
ZeroMemory(buffer, fileSize);
dwBytesToRead = fileSize;
dwBytesRead = 0;
read_data = buffer;
do { //循環讀文件,確保讀出完整的文件
ReadFile(hcom, read_data, dwBytesToRead, &dwBytesRead, NULL);
if (dwBytesRead == 0)
break;
dwBytesToRead -= dwBytesRead;
read_data += dwBytesRead;
} while (dwBytesToRead > 0);
// TODO 處理讀到的數據 buffer
free(buffer);
CloseHandle(hcom);
return TRUE;
}
電腦藍牙串口的設置
1、打開電腦藍牙設置界面,勾選更多藍牙選項
2、勾選下面箭頭指向的選項
3、點擊添加
4、設置一個傳入和傳出的虛擬串口
最後記得設置的串口要與上面代碼中CreateFile指定的串口相符!
希望對讀者有所幫助,喜歡的話可以關注一下我的公衆號,我會把學習筆記發在上面,大家可以一起共同學習!