How to read serial data from bluetooth port? C ++

I created a program to read serial data from a COM port using C ++, however, due to changes in my project, I need to read data from a BT port. Since I am using a bluetooth adapter to connect my computer to the device, I expected the reading process to be the same, but apparently it is not. Since Im using Window OS to do this task, GetLastError () returns 2, which means the specified file was not found. However, when I use an Arduino serial monitor, the data is read just fine. Does anyone know how to read from a BT port in C ++? I am using Windows 8 by the way, here is my code:

#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
///-----------------------------Open port-----------------------------------------------------------------

// Name of port where device is found
LPCWSTR port = L"COM40";

// Open port for reading
HANDLE hComm = ::CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

// Check if port has been opened succesfully
if (hComm == INVALID_HANDLE_VALUE) std::cout << "Failed to open " << port << " error: " << GetLastError() << std::endl;
else std::cout << port << " has been opened succesfully\n";

///-----------------------------Configure port------------------------------------------------------------

// Create DCB structure 
DCB dcb = { 0 };

// Get Comm state
if (!::GetCommState(hComm, &dcb)) std::cout << "Failed to get Comm state, error: " << GetLastError() << std::endl;

// Configure strcutre
dcb.DCBlength = sizeof(DCB);

// Set Baud rate
dcb.BaudRate = CBR_9600;
// Set number of bytes in bits that are recieved through the port
dcb.ByteSize = 8;
dcb.StopBits = ONESTOPBIT;

// Check if port has been configured correctly
if (!::SetCommState(hComm, &dcb)) std::cout << "\nFailed to set Comm State, error: " << GetLastError();
else std::cout << "Comm state has been set succesfully\n";

///-----------------------------Read data-------------------------------------------------------------------

char buffer;
DWORD maxBytes = 1;
if (!::ReadFile(hComm, &buffer, maxBytes, NULL, NULL)) std::cout << "\nFailed to read from " << port << " error: " << GetLastError() << std::endl;
else std::cout << "File has been read succesfully\n";

///-----------------------------Write to text file----------------------------------------------------------

std::fstream file;
int counter = 0;
// Writing to text file will be done later
while (ReadFile(hComm, &buffer, maxBytes, NULL, NULL))
{
    std::cout << buffer;
}

///-----------------------------Close port------------------------------------------------------------------

CloseHandle(hComm);
file.close();

std::cout << "\nCOM40 has been closed!\n";
return 0; 
}

      

+3


source to share





All Articles