gpt4 book ai didi

c++ - 错误 5 : Access is Denied when using WriteFile to interface Arduino and C++ program

转载 作者:行者123 更新时间:2023-11-28 06:12:12 24 4
gpt4 key购买 nike

我正在开发一个 C++ 控制台程序来连接 Arduino Uno。我需要向 Arduino 板发送一个 key ,以便它可以激活 RFID 传感器并将读取的 UID 发送回程序。

ReadFile 函数工作得~几乎~完美,但是当我尝试向 Arduino 发送一个“a”以便它可以开始运行它的 ReadFromRFID 函数时,我收到了这条消息:

"Error 5: Access is Denied"

有谁知道我做错了什么以及如何做对?

这是我目前的代码:

HANDLE hSerial;

void printErro() {

printf(":: ERRO ::\n");

wchar_t erro[1024];
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), erro, 1024, NULL);
printf("Erro %ld: %ls", GetLastError(), erro);

}

HANDLE conectArduino() {

LPCWSTR porta = L"COM3";

hSerial = CreateFile(porta, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

if (hSerial == INVALID_HANDLE_VALUE){
if (GetLastError() == ERROR_FILE_NOT_FOUND){

printErro();

}
//some other error occurred. Inform user.

printErro();

}

DCB parametros = { 0 };
parametros.DCBlength = sizeof(parametros);
parametros.BaudRate = CBR_9600;
parametros.ByteSize = 8;
parametros.StopBits = ONESTOPBIT;
parametros.Parity = NOPARITY;

if (!SetCommState(hSerial, &parametros)){
//error setting serial port state

printErro();

}

COMMTIMEOUTS timeouts = { 0 };
timeouts.ReadIntervalTimeout = 10000;
timeouts.ReadTotalTimeoutConstant = 1000;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.WriteTotalTimeoutConstant = 100;
timeouts.WriteTotalTimeoutMultiplier = 0;

if (!SetCommTimeouts(hSerial, &timeouts)) {

printErro();

}

return hSerial;

}

void readArduino(HANDLE hSerial) {

printf("RECEBENDO DADOS DO ARDUINO\n\n");

char buffer[12] = { 0 };
DWORD qtdBytesLida = 0;

if (!ReadFile(hSerial, buffer, 11, &qtdBytesLida, NULL)) {

printErro();

}

printf("%d: %*.*s", qtdBytesLida, qtdBytesLida, qtdBytesLida, buffer);

getchar();

printf("\n\n");
printf("----------------------------------------------------------------------");
printf("\n\n");

}

void sendArduino(const char* palavra) {

printf("ENVIANDO DADOS PARA O ARDUINO\n\n");

char buffer[2] = "a";
DWORD qtdBytesEscrita = 0;

HANDLE hSerial = conectArduino();

if (!WriteFile(hSerial, buffer, 1, &qtdBytesEscrita, NULL)) {

printErro();

}
else {

readArduino(hSerial);

}

CloseHandle(hSerial);

getchar();

printf("\n\n");
printf("----------------------------------------------------------------------");
printf("\n\n");

}

最佳答案

您只使用 GENERIC_READ 打开串行端口,这意味着只读访问。如果您希望能够写入,您还需要添加 GENERIC_WRITE

hSerial = CreateFile(porta, GENERIC_READ | GENERIC_WRITE, 0, 0,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

关于c++ - 错误 5 : Access is Denied when using WriteFile to interface Arduino and C++ program,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31038403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com