I am working on a project for serial communications between Excel and an Arduino. The following is what I have in VBA for the reading of data from the Arduino which is where my problem lies.
Private Declare Function readFromSerialPort Lib "C:PathToDll.dll"(ByRef Buffer As String) As String
And in a looping function within my VBA I have the following which sets a cell value to a string which is my buffer.
BigData.Range("Buf").Value = "B "
Another cell called dataWindow takes in Buf as an argument so it updates when this is called.
=readFromSerialPort(Buf)
And here is the C++ code on the other end in the DLL.
DLL_EXPORT BSTR WINAPI readFromSerialPort(LPBSTR bufferTemp) {
char errorMsg[] = "read failed";
char mbstring[MAX_STRING_SIZE];
BSTR wcstring = *bufferTemp;
int sLen = wcstombs(mbstring,wcstring,MAX_STRING_SIZE);
char charString[MAX_STRING_SIZE];
DWORD dwBytesRead = 0;
if (hSerial == INVALID_HANDLE_VALUE) {
ErrorExit("ReadFile (port not open)");
int wLen2 = mbstowcs(*bufferTemp,errorMsg,strlen(errorMsg));
return *bufferTemp;
}
if(!ReadFile(hSerial, charString, sLen, &dwBytesRead, NULL)) {
ErrorExit("ReadFile");
int wLen2 = mbstowcs(*bufferTemp,errorMsg,strlen(errorMsg));
return *bufferTemp;
}
int wLen2 = mbstowcs(*bufferTemp,charString,sLen);
return *bufferTemp;
}
The issue is that this works when called from a cell but not when I change it to declaring a string in VBA and calling the read from there.