BWS2000倾角传感器c++测试代码_时间延迟与时间同步问题【3】

本文主要是介绍BWS2000倾角传感器c++测试代码_时间延迟与时间同步问题【3】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

详见昨天做的测试代码,代码网址:
BWS2000倾角传感器c++测试代码【2】-CSDN博客文章浏览阅读268次,点赞7次,收藏8次。倾角传感器测试与编写思路https://blog.csdn.net/m0_47489229/article/details/135128748

问题一:新的问题出现---存在时间延缓的问题

昨天的代码今天打开之后,再进行测试出现了一个问题,就是当移动倾角传感器之后,可以见到传感器显示的数值变化是比实际慢很多的,可以明显看出来。

由于昨天的代码存在相应的时间延迟,不方便后面进行传感器的时间同步。我的思路是搞个多线程

由于倾角传感器存在时间延迟的问题,但是厂家给出的软件之中并不存在时间延迟的问题。所以为了解决这个问题我的想法是创建一个线程,进行实时处理传输的接口信息,对于通信接口进行连接判断。连接的瞬间就进行数据处理。

写个测试案例:
首先创建一个线程,实时监督接口与进行数据处理:


void sensorThread()
{std::cout << " " << std::endl;std::cout << "开始采集 " << std::endl;int i = 0;while (1){ReadFile(hSerial, dataReceived, sizeof(dataReceived), &bytesRead, NULL);auto startTime = std::chrono::high_resolution_clock::now();for (int i = 0; i < sizeof(dataReceived); i++) {printf("%02X ", dataReceived[i]);}bool flag1 = false;int flag;for (int i = 0; i < sizeof(dataReceived); i++) {if (dataReceived[i] == 0x77 && dataReceived[i + 1] == 0x10 && dataReceived[i + 2] == 0x00 && dataReceived[i + 3] == 0xFFFFFF84){flag1 = true;flag = i;break;}}std::cout << "" << std::endl;//std::this_thread::sleep_for(std::chrono::milliseconds(4000));if (flag1 == true){//x轴// Given hexadecimal valuesint hexValues[] = { dataReceived[flag + 5] & 0xFF, dataReceived[flag + 6] & 0xFF, dataReceived[flag + 7] & 0xFF };int hexValues1[] = { dataReceived[flag + 9] & 0xFF, dataReceived[flag + 10] & 0xFF, dataReceived[flag + 11] & 0xFF };int numValues = sizeof(hexValues) / sizeof(hexValues[0]);std::stringstream ss;ss << std::setfill('0') << std::setw(2) << std::hex << hexValues[0];for (int i = 1; i < numValues; i++) {ss << "." << std::setw(2) << std::hex << hexValues[i];}std::string resultString = ss.str();std::string inputString = resultString;std::string outputString;size_t firstDotIndex = inputString.find('.');size_t secondDotIndex = inputString.find('.', firstDotIndex + 1);if (firstDotIndex != std::string::npos && secondDotIndex != std::string::npos) {outputString = inputString.substr(0, secondDotIndex) + inputString.substr(secondDotIndex + 1);}else {outputString = inputString;}double resultDouble = std::stod(outputString);if (dataReceived[flag + 4] == 0x00){Sensor_Angle_RX0 = resultDouble;}else{Sensor_Angle_RX0 = -resultDouble;}std::cout << "x轴角度" << Sensor_Angle_RX0 << std::endl;//Y轴int numValues1 = sizeof(hexValues1) / sizeof(hexValues1[0]);std::stringstream ss1;ss1 << std::setfill('0') << std::setw(2) << std::hex << hexValues1[0];for (int i = 1; i < numValues1; i++) {ss1 << "." << std::setw(2) << std::hex << hexValues1[i];}std::string resultString1 = ss1.str();std::string inputString1 = resultString1;std::string outputString1;size_t firstDotIndex1 = inputString1.find('.');size_t secondDotIndex1 = inputString1.find('.', firstDotIndex1 + 1);if (firstDotIndex1 != std::string::npos && secondDotIndex1 != std::string::npos) {outputString1 = inputString1.substr(0, secondDotIndex1) + inputString1.substr(secondDotIndex1 + 1);}else {outputString1 = inputString1;}double resultDouble1 = std::stod(outputString1);if (dataReceived[flag + 8] == 0x00){Sensor_Angle_RY0 = resultDouble1;}else{Sensor_Angle_RY0 = -resultDouble1;}std::cout << "y轴: " << Sensor_Angle_RY0 << std::endl;// 计算执行代码所花费的时间auto endTime = std::chrono::high_resolution_clock::now();auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);// 计算需要延迟的时间int delay = interval - duration.count();//std::cout << delay << std::endl;if (delay == interval){std::cout << "频率正确" << std::endl;}else if (delay > 0) {// 延迟执行std::this_thread::sleep_for(std::chrono::milliseconds(delay));std::cout << "频率正确" << std::endl;}else if (delay < 0){std::cout << "时间不够:(ms)***************************************:" << delay << std::endl;//std::this_thread::sleep_for(std::chrono::milliseconds(200000000));}}}//std::this_thread::sleep_for(std::chrono::milliseconds(2000));}

在主函数函数之中对于接口进行初步的数据处理:


int main()
{// 创建传感器数据读取线程std::thread sensorThreadObj(sensorThread);//CString str123 = strValue1;//CString strA("COM10");//CString strB("\\\\.\\");//strB += strA;//const char* portName = strB.GetString();//strB.ReleaseBuffer();//strA.ReleaseBuffer();wchar_t portName[] = L"\\\\.\\COM10"; // Note the 'L' before the stringhSerial = CreateFile("\\\\.\\COM10", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);if (hSerial == INVALID_HANDLE_VALUE) {if (GetLastError() == ERROR_FILE_NOT_FOUND) {std::cout << "Serial port not available." << std::endl;}return 1;}dcbSerialParams.DCBlength = sizeof(dcbSerialParams);if (!GetCommState(hSerial, &dcbSerialParams)) {std::cout << "Error getting serial port state." << std::endl;CloseHandle(hSerial);return 1;}dcbSerialParams.BaudRate = CBR_9600;dcbSerialParams.ByteSize = 8;dcbSerialParams.StopBits = ONESTOPBIT;dcbSerialParams.Parity = NOPARITY;if (!SetCommState(hSerial, &dcbSerialParams)) {std::cout << "Error setting serial port state." << std::endl;CloseHandle(hSerial);return 1;}timeouts.ReadIntervalTimeout = 500;timeouts.ReadTotalTimeoutConstant = 500;timeouts.ReadTotalTimeoutMultiplier = 100;timeouts.WriteTotalTimeoutConstant = 500;timeouts.WriteTotalTimeoutMultiplier = 100;if (!SetCommTimeouts(hSerial, &timeouts)){std::cout << "Error setting timeouts." << std::endl;CloseHandle(hSerial);return 1;}//默认为9600的时候,进行对话模式char command_R4[] = { 0x77, 0x05, 0x00, 0x0C, 0x00, 0x11 };if (!WriteFile(hSerial, command_R4, sizeof(command_R4), &bytesWritten4, NULL)) {std::cout << "第一次9600的对话模式配置失败" << std::endl;CloseHandle(hSerial);return 1;}if (!ReadFile(hSerial, dataReceived, sizeof(dataReceived), &bytesRead, NULL)) {std::cout << "第一次9600的对话模式数据读取失败." << std::endl;CloseHandle(hSerial);return 1;}std::cout << "第一次初始波特率:" << dcbSerialParams.BaudRate << std::endl;for (int i = 0; i < sizeof(dataReceived); i++) {printf("%02X ", dataReceived[i]);}bool exists = false; // 标志位,记录元素是否存在int falsecount = 0;// 循环遍历数组while (!exists) {for (int i = 0; i < sizeof(dataReceived); i++) {printf("%02X ", dataReceived[i]);}for (int i = 0; i < sizeof(dataReceived); i++) {if (dataReceived[i] == 0x77 && dataReceived[i + 3] == 0xFFFFFF8C) {exists = true; // 元素存在,设置标志位为truestd::cout << falsecount << std::endl;std::cout << "应答模式配置成功!" << std::endl;//std::this_thread::sleep_for(std::chrono::milliseconds(400000));break; // 跳出for循环}}if (exists){break;}if (!exists) {falsecount++;if (falsecount >= 2)//说明原有配置是115200波特率{dcbSerialParams.BaudRate = CBR_115200;dcbSerialParams.ByteSize = 8;dcbSerialParams.StopBits = ONESTOPBIT;dcbSerialParams.Parity = NOPARITY;if (!SetCommState(hSerial, &dcbSerialParams)) {std::cout << "Error setting serial port state." << std::endl;CloseHandle(hSerial);return 1;}timeouts.ReadIntervalTimeout = 500;timeouts.ReadTotalTimeoutConstant = 500;timeouts.ReadTotalTimeoutMultiplier = 100;timeouts.WriteTotalTimeoutConstant = 500;timeouts.WriteTotalTimeoutMultiplier = 100;if (!SetCommTimeouts(hSerial, &timeouts)){std::cout << "Error setting timeouts." << std::endl;CloseHandle(hSerial);return 1;}}if (!WriteFile(hSerial, command_R4, sizeof(command_R4), &bytesWritten4, NULL)) {std::cout << "115200的对话模式配置失败." << std::endl;CloseHandle(hSerial);return 1;}if (!ReadFile(hSerial, dataReceived, sizeof(dataReceived), &bytesRead, NULL)) {std::cout << "115200的对话模式回复失败." << std::endl;CloseHandle(hSerial);return 1;}}}//设置频率为115200char command_R1[] = { 0x77, 0x05, 0x00, 0x0B, 0x04, 0x14 };//115200 if (!WriteFile(hSerial, command_R1, sizeof(command_R1), &bytesWritten1, NULL)){std::cout << "Error writing to serial port." << std::endl;CloseHandle(hSerial);return 1;}if (!ReadFile(hSerial, dataReceived, sizeof(dataReceived), &bytesRead, NULL)){std::cout << "Error reading from serial port." << std::endl;CloseHandle(hSerial);return 1;}exists = false;while (!exists){for (int i = 0; i < sizeof(dataReceived); i++) {printf("%02X ", dataReceived[i]);}for (int i = 0; i < sizeof(dataReceived); i++) {if (dataReceived[i] == 0x77 && dataReceived[i + 3] == 0xFFFFFF8B) {//设置成功exists = true; // 元素存在,设置标志位为truestd::cout << "115200波特率配置成功!" << std::endl;break; // 跳出for循环}}if (exists){break;}if (!exists) {if (!WriteFile(hSerial, command_R1, sizeof(command_R1), &bytesWritten1, NULL)) {std::cout << "Error writing to serial port." << std::endl;CloseHandle(hSerial);return 1;}if (!ReadFile(hSerial, dataReceived, sizeof(dataReceived), &bytesRead, NULL)) {std::cout << "Error reading from serial port." << std::endl;CloseHandle(hSerial);return 1;}std::cout << "重复配置115200波特率" << std::endl;// 可以在这里添加需要执行的语句std::this_thread::sleep_for(std::chrono::milliseconds(4000));}}//00-11:应答模式 05-50Hz 04-25Hz//06-100     05-50     04-25    char command_R3[] = { 0x77, 0x05, 0x00, 0x0C, 0x03, 0x14 };//50Hzif (!WriteFile(hSerial, command_R3, sizeof(command_R3), &bytesWritten3, NULL)) {std::cout << "Error writing to serial port." << std::endl;CloseHandle(hSerial);return 1;}if (!ReadFile(hSerial, dataReceived, sizeof(dataReceived), &bytesRead, NULL)) {std::cout << "Error reading from serial port." << std::endl;CloseHandle(hSerial);return 1;}for (int i = 0; i < sizeof(dataReceived); i++) {printf("%02X ", dataReceived[i]);}exists = false;while (!exists) {for (int i = 0; i < sizeof(dataReceived); i++) {printf("%02X ", dataReceived[i]);}for (int i = 0; i < sizeof(dataReceived); i++) {if (dataReceived[i] == 0x77 && dataReceived[i+3] == 0xFFFFFF8C) {//设置成功exists = true; // 元素存在,设置标志位为truestd::cout << "50Hz配置成功!" << std::endl;break; // 跳出for循环}}if (exists){break;}if (!exists) {if (!WriteFile(hSerial, command_R3, sizeof(command_R3), &bytesWritten3, NULL)) {std::cout << "Error writing to serial port." << std::endl;CloseHandle(hSerial);return 1;}if (!ReadFile(hSerial, dataReceived, sizeof(dataReceived), &bytesRead, NULL)) {std::cout << "Error reading from serial port." << std::endl;CloseHandle(hSerial);return 1;}std::cout << "元素不存在,继续执行某条语句..." << std::endl;// 可以在这里添加需要执行的语句}}//sensorThreadObj.join();return 0;
}

完整代码段:

#include <Windows.h>#include <iostream>
#include <iomanip>
#include <iostream>
#include <chrono>
#include <thread>
#include <iostream>
#include <iomanip> 
#include <iostream>
#include <sstream> 
#include <iomanip>HANDLE hSerial;
DCB dcbSerialParams = { 0 };
COMMTIMEOUTS timeouts = { 0 };
DWORD bytesRead, bytesRead1, bytesWritten, bytesWritten1, bytesWritten2, bytesWritten3, bytesWritten4, bytesWritten5, response_R1;char command_R[] = { 0x77, 0x04, 0x00, 0x04, 0x08 };//读X、Y轴角度 发送命令: 77 04 00 04 08
char response_R[34];
double Sensor_Angle_RX0;
double Sensor_Angle_RY0;char dataReceived[34];
const int interval = 100;void sensorThread()
{std::cout << " " << std::endl;std::cout << "开始采集 " << std::endl;int i = 0;while (1){auto startTime = std::chrono::high_resolution_clock::now();ReadFile(hSerial, dataReceived, sizeof(dataReceived), &bytesRead, NULL);for (int i = 0; i < sizeof(dataReceived); i++) {printf("%02X ", dataReceived[i]);}bool flag1 = false;int flag;for (int i = 0; i < sizeof(dataReceived); i++) {if (dataReceived[i] == 0x77 && dataReceived[i + 1] == 0x10 && dataReceived[i + 2] == 0x00 && dataReceived[i + 3] == 0xFFFFFF84){flag1 = true;flag = i;break;}}std::cout << "" << std::endl;//std::this_thread::sleep_for(std::chrono::milliseconds(4000));if (flag1 == true){//x轴// Given hexadecimal valuesint hexValues[] = { dataReceived[flag + 5] & 0xFF, dataReceived[flag + 6] & 0xFF, dataReceived[flag + 7] & 0xFF };int hexValues1[] = { dataReceived[flag + 9] & 0xFF, dataReceived[flag + 10] & 0xFF, dataReceived[flag + 11] & 0xFF };int numValues = sizeof(hexValues) / sizeof(hexValues[0]);std::stringstream ss;ss << std::setfill('0') << std::setw(2) << std::hex << hexValues[0];for (int i = 1; i < numValues; i++) {ss << "." << std::setw(2) << std::hex << hexValues[i];}std::string resultString = ss.str();std::string inputString = resultString;std::string outputString;size_t firstDotIndex = inputString.find('.');size_t secondDotIndex = inputString.find('.', firstDotIndex + 1);if (firstDotIndex != std::string::npos && secondDotIndex != std::string::npos) {outputString = inputString.substr(0, secondDotIndex) + inputString.substr(secondDotIndex + 1);}else {outputString = inputString;}double resultDouble = std::stod(outputString);if (dataReceived[flag + 4] == 0x00){Sensor_Angle_RX0 = resultDouble;}else{Sensor_Angle_RX0 = -resultDouble;}std::cout << "x轴角度" << Sensor_Angle_RX0 << std::endl;//Y轴int numValues1 = sizeof(hexValues1) / sizeof(hexValues1[0]);std::stringstream ss1;ss1 << std::setfill('0') << std::setw(2) << std::hex << hexValues1[0];for (int i = 1; i < numValues1; i++) {ss1 << "." << std::setw(2) << std::hex << hexValues1[i];}std::string resultString1 = ss1.str();std::string inputString1 = resultString1;std::string outputString1;size_t firstDotIndex1 = inputString1.find('.');size_t secondDotIndex1 = inputString1.find('.', firstDotIndex1 + 1);if (firstDotIndex1 != std::string::npos && secondDotIndex1 != std::string::npos) {outputString1 = inputString1.substr(0, secondDotIndex1) + inputString1.substr(secondDotIndex1 + 1);}else {outputString1 = inputString1;}double resultDouble1 = std::stod(outputString1);if (dataReceived[flag + 8] == 0x00){Sensor_Angle_RY0 = resultDouble1;}else{Sensor_Angle_RY0 = -resultDouble1;}std::cout << "y轴: " << Sensor_Angle_RY0 << std::endl;// 计算执行代码所花费的时间auto endTime = std::chrono::high_resolution_clock::now();auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);// 计算需要延迟的时间int delay = interval - duration.count();//std::cout << delay << std::endl;if (delay == interval){std::cout << "频率正确" << std::endl;}else if (delay > 0) {// 延迟执行std::this_thread::sleep_for(std::chrono::milliseconds(delay));std::cout << "频率正确" << std::endl;}else if (delay < 0){std::cout << "时间不够:(ms)***************************************:" << delay << std::endl;//std::this_thread::sleep_for(std::chrono::milliseconds(200000000));}}}//std::this_thread::sleep_for(std::chrono::milliseconds(2000));}int main()
{// 创建传感器数据读取线程std::thread sensorThreadObj(sensorThread);//CString str123 = strValue1;//CString strA("COM10");//CString strB("\\\\.\\");//strB += strA;//const char* portName = strB.GetString();//strB.ReleaseBuffer();//strA.ReleaseBuffer();wchar_t portName[] = L"\\\\.\\COM10"; // Note the 'L' before the stringhSerial = CreateFile("\\\\.\\COM10", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);if (hSerial == INVALID_HANDLE_VALUE) {if (GetLastError() == ERROR_FILE_NOT_FOUND) {std::cout << "Serial port not available." << std::endl;}return 1;}dcbSerialParams.DCBlength = sizeof(dcbSerialParams);if (!GetCommState(hSerial, &dcbSerialParams)) {std::cout << "Error getting serial port state." << std::endl;CloseHandle(hSerial);return 1;}dcbSerialParams.BaudRate = CBR_9600;dcbSerialParams.ByteSize = 8;dcbSerialParams.StopBits = ONESTOPBIT;dcbSerialParams.Parity = NOPARITY;if (!SetCommState(hSerial, &dcbSerialParams)) {std::cout << "Error setting serial port state." << std::endl;CloseHandle(hSerial);return 1;}timeouts.ReadIntervalTimeout = 500;timeouts.ReadTotalTimeoutConstant = 500;timeouts.ReadTotalTimeoutMultiplier = 100;timeouts.WriteTotalTimeoutConstant = 500;timeouts.WriteTotalTimeoutMultiplier = 100;if (!SetCommTimeouts(hSerial, &timeouts)){std::cout << "Error setting timeouts." << std::endl;CloseHandle(hSerial);return 1;}//默认为9600的时候,进行对话模式char command_R4[] = { 0x77, 0x05, 0x00, 0x0C, 0x00, 0x11 };if (!WriteFile(hSerial, command_R4, sizeof(command_R4), &bytesWritten4, NULL)) {std::cout << "第一次9600的对话模式配置失败" << std::endl;CloseHandle(hSerial);return 1;}if (!ReadFile(hSerial, dataReceived, sizeof(dataReceived), &bytesRead, NULL)) {std::cout << "第一次9600的对话模式数据读取失败." << std::endl;CloseHandle(hSerial);return 1;}std::cout << "第一次初始波特率:" << dcbSerialParams.BaudRate << std::endl;for (int i = 0; i < sizeof(dataReceived); i++) {printf("%02X ", dataReceived[i]);}bool exists = false; // 标志位,记录元素是否存在int falsecount = 0;// 循环遍历数组while (!exists) {for (int i = 0; i < sizeof(dataReceived); i++) {printf("%02X ", dataReceived[i]);}for (int i = 0; i < sizeof(dataReceived); i++) {if (dataReceived[i] == 0x77 && dataReceived[i + 3] == 0xFFFFFF8C) {exists = true; // 元素存在,设置标志位为truestd::cout << falsecount << std::endl;std::cout << "应答模式配置成功!" << std::endl;//std::this_thread::sleep_for(std::chrono::milliseconds(400000));break; // 跳出for循环}}if (exists){break;}if (!exists) {falsecount++;if (falsecount >= 2)//说明原有配置是115200波特率{dcbSerialParams.BaudRate = CBR_115200;dcbSerialParams.ByteSize = 8;dcbSerialParams.StopBits = ONESTOPBIT;dcbSerialParams.Parity = NOPARITY;if (!SetCommState(hSerial, &dcbSerialParams)) {std::cout << "Error setting serial port state." << std::endl;CloseHandle(hSerial);return 1;}timeouts.ReadIntervalTimeout = 500;timeouts.ReadTotalTimeoutConstant = 500;timeouts.ReadTotalTimeoutMultiplier = 100;timeouts.WriteTotalTimeoutConstant = 500;timeouts.WriteTotalTimeoutMultiplier = 100;if (!SetCommTimeouts(hSerial, &timeouts)){std::cout << "Error setting timeouts." << std::endl;CloseHandle(hSerial);return 1;}}if (!WriteFile(hSerial, command_R4, sizeof(command_R4), &bytesWritten4, NULL)) {std::cout << "115200的对话模式配置失败." << std::endl;CloseHandle(hSerial);return 1;}if (!ReadFile(hSerial, dataReceived, sizeof(dataReceived), &bytesRead, NULL)) {std::cout << "115200的对话模式回复失败." << std::endl;CloseHandle(hSerial);return 1;}}}//设置频率为115200char command_R1[] = { 0x77, 0x05, 0x00, 0x0B, 0x04, 0x14 };//115200 if (!WriteFile(hSerial, command_R1, sizeof(command_R1), &bytesWritten1, NULL)){std::cout << "Error writing to serial port." << std::endl;CloseHandle(hSerial);return 1;}if (!ReadFile(hSerial, dataReceived, sizeof(dataReceived), &bytesRead, NULL)){std::cout << "Error reading from serial port." << std::endl;CloseHandle(hSerial);return 1;}exists = false;while (!exists){for (int i = 0; i < sizeof(dataReceived); i++) {printf("%02X ", dataReceived[i]);}for (int i = 0; i < sizeof(dataReceived); i++) {if (dataReceived[i] == 0x77 && dataReceived[i + 3] == 0xFFFFFF8B) {//设置成功exists = true; // 元素存在,设置标志位为truestd::cout << "115200波特率配置成功!" << std::endl;break; // 跳出for循环}}if (exists){break;}if (!exists) {if (!WriteFile(hSerial, command_R1, sizeof(command_R1), &bytesWritten1, NULL)) {std::cout << "Error writing to serial port." << std::endl;CloseHandle(hSerial);return 1;}if (!ReadFile(hSerial, dataReceived, sizeof(dataReceived), &bytesRead, NULL)) {std::cout << "Error reading from serial port." << std::endl;CloseHandle(hSerial);return 1;}std::cout << "重复配置115200波特率" << std::endl;// 可以在这里添加需要执行的语句std::this_thread::sleep_for(std::chrono::milliseconds(4000));}}//00-11:应答模式 05-50Hz 04-25Hz//06-100     05-50     04-25    char command_R3[] = { 0x77, 0x05, 0x00, 0x0C, 0x03, 0x14 };//50Hzif (!WriteFile(hSerial, command_R3, sizeof(command_R3), &bytesWritten3, NULL)) {std::cout << "Error writing to serial port." << std::endl;CloseHandle(hSerial);return 1;}if (!ReadFile(hSerial, dataReceived, sizeof(dataReceived), &bytesRead, NULL)) {std::cout << "Error reading from serial port." << std::endl;CloseHandle(hSerial);return 1;}for (int i = 0; i < sizeof(dataReceived); i++) {printf("%02X ", dataReceived[i]);}exists = false;while (!exists) {for (int i = 0; i < sizeof(dataReceived); i++) {printf("%02X ", dataReceived[i]);}for (int i = 0; i < sizeof(dataReceived); i++) {if (dataReceived[i] == 0x77 && dataReceived[i+3] == 0xFFFFFF8C) {//设置成功exists = true; // 元素存在,设置标志位为truestd::cout << "50Hz配置成功!" << std::endl;break; // 跳出for循环}}if (exists){break;}if (!exists) {if (!WriteFile(hSerial, command_R3, sizeof(command_R3), &bytesWritten3, NULL)) {std::cout << "Error writing to serial port." << std::endl;CloseHandle(hSerial);return 1;}if (!ReadFile(hSerial, dataReceived, sizeof(dataReceived), &bytesRead, NULL)) {std::cout << "Error reading from serial port." << std::endl;CloseHandle(hSerial);return 1;}std::cout << "元素不存在,继续执行某条语句..." << std::endl;// 可以在这里添加需要执行的语句}}//sensorThreadObj.join();return 0;
}

我不知道为啥,程序可以正常运行,但是时间过长的情况下,偶尔会出现下面的这个问题(如果哪个大佬要是知道可以告诉我一下,学习学习):

问题二:界面化设计(简化版)

前面已经完成了对于倾角传感器初步的设定与时间延缓问题的补偿,下一步需要对于倾角传感器的界面进行设计了。不写那么复杂,直接就是连接之后实时显示。

其中,Combo Box的ID我设置为IDC_COMBO1。x轴、y轴控件之间添加变量为m_x11、x_x22。可以见到在.h文件之中生成绑定变量。

在.h之中添加自己想要的变量。

HANDLE hSerial_L;DCB dcbSerialParams_L = { 0 };COMMTIMEOUTS timeouts_L = { 0 };DWORD bytesRead_L, bytesRead_L1, bytesWritten, bytesWritten1, bytesWritten2, bytesWritten3, bytesWritten4, bytesWritten5, response_R1;char dataReceived[34];const int interval = 100;char dataReceived_L[23];

在.cpp的初始化函数OnInit之中添加线程监控与按钮初始化

AfxBeginThread(ReadCom1Thread, this);CComboBox* pCombo_S_L = (CComboBox*)GetDlgItem(IDC_COMBO1);pCombo_S_L->AddString(_T("断开连接"));pCombo_S_L->AddString(_T("COM1"));pCombo_S_L->AddString(_T("COM2"));pCombo_S_L->AddString(_T("COM3"));pCombo_S_L->AddString(_T("COM4"));pCombo_S_L->AddString(_T("COM5"));pCombo_S_L->AddString(_T("COM6"));pCombo_S_L->AddString(_T("COM7"));pCombo_S_L->AddString(_T("COM8"));pCombo_S_L->AddString(_T("COM9"));pCombo_S_L->AddString(_T("COM10"));pCombo_S_L->AddString(_T("COM11"));pCombo_S_L->AddString(_T("COM12"));pCombo_S_L->AddString(_T("COM13"));pCombo_S_L->AddString(_T("COM14"));pCombo_S_L->AddString(_T("COM15"));pCombo_S_L->AddString(_T("COM16"));pCombo_S_L->AddString(_T("COM17"));pCombo_S_L->AddString(_T("COM18"));pCombo_S_L->AddString(_T("COM19"));pCombo_S_L->AddString(_T("COM20"));pCombo_S_L->SetCurSel(0);

线程函数如下所示:


volatile bool bThreadRunning1 = false; // 线程1运行标志
//UINT CMFCApplication1Dlg::ReadCom1Thread(LPVOID pParam)
UINT ReadCom1Thread(LPVOID pParam)
{CMFCApplication1Dlg* pDlg = (CMFCApplication1Dlg*)pParam;CString strText;bThreadRunning1 = true;double LX, LY;std::cout << " " << std::endl;std::cout << "开始采集 " << std::endl;int i = 0;while (1){auto startTime = std::chrono::high_resolution_clock::now();ReadFile(pDlg->hSerial_L, pDlg->dataReceived, sizeof(pDlg->dataReceived), &(pDlg->bytesRead_L), NULL);for (int i = 0; i < sizeof(pDlg->dataReceived); i++) {printf("%02X ", pDlg->dataReceived[i]);}bool flag1 = false;int flag;for (int i = 0; i < sizeof(pDlg->dataReceived); i++) {if (pDlg->dataReceived[i] == 0x77 && pDlg->dataReceived[i + 1] == 0x10 && pDlg->dataReceived[i + 2] == 0x00 && pDlg->dataReceived[i + 3] == 0xFFFFFF84){flag1 = true;flag = i;break;}}std::cout << "" << std::endl;//std::this_thread::sleep_for(std::chrono::milliseconds(4000));if (flag1 == true){//x轴// Given hexadecimal valuesint hexValues[] = { pDlg->dataReceived[flag + 5] & 0xFF, pDlg->dataReceived[flag + 6] & 0xFF, pDlg->dataReceived[flag + 7] & 0xFF };int hexValues1[] = { pDlg->dataReceived[flag + 9] & 0xFF, pDlg->dataReceived[flag + 10] & 0xFF, pDlg->dataReceived[flag + 11] & 0xFF };int numValues = sizeof(hexValues) / sizeof(hexValues[0]);std::stringstream ss;ss << std::setfill('0') << std::setw(2) << std::hex << hexValues[0];for (int i = 1; i < numValues; i++) {ss << "." << std::setw(2) << std::hex << hexValues[i];}std::string resultString = ss.str();std::string inputString = resultString;std::string outputString;size_t firstDotIndex = inputString.find('.');size_t secondDotIndex = inputString.find('.', firstDotIndex + 1);if (firstDotIndex != std::string::npos && secondDotIndex != std::string::npos) {outputString = inputString.substr(0, secondDotIndex) + inputString.substr(secondDotIndex + 1);}else {outputString = inputString;}double resultDouble = std::stod(outputString);if (pDlg->dataReceived[flag + 4] == 0x00){LX = resultDouble;}else{LX = -resultDouble;}//Y轴int numValues1 = sizeof(hexValues1) / sizeof(hexValues1[0]);std::stringstream ss1;ss1 << std::setfill('0') << std::setw(2) << std::hex << hexValues1[0];for (int i = 1; i < numValues1; i++) {ss1 << "." << std::setw(2) << std::hex << hexValues1[i];}std::string resultString1 = ss1.str();std::string inputString1 = resultString1;std::string outputString1;size_t firstDotIndex1 = inputString1.find('.');size_t secondDotIndex1 = inputString1.find('.', firstDotIndex1 + 1);if (firstDotIndex1 != std::string::npos && secondDotIndex1 != std::string::npos) {outputString1 = inputString1.substr(0, secondDotIndex1) + inputString1.substr(secondDotIndex1 + 1);}else {outputString1 = inputString1;}double resultDouble1 = std::stod(outputString1);if (pDlg->dataReceived[flag + 8] == 0x00){LY = resultDouble1;}else{LY = -resultDouble1;}CString strValue;strValue.Format(_T("%.4f°"), LX); // 将 double 值转换成字符串,保留四位小数pDlg->m_x11.ResetContent();pDlg->m_x11.AddString(strValue); // 将字符串添加到 ListBox 中CString strValue1;strValue1.Format(_T("%.4f°"), LY); // 将 double 值转换成字符串,保留四位小数pDlg->m_x22.ResetContent();pDlg->m_x22.AddString(strValue1); // 将字符串添加到 ListBox 中// 计算执行代码所花费的时间auto endTime = std::chrono::high_resolution_clock::now();auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);// 计算需要延迟的时间int delay = pDlg->interval - duration.count();//std::cout << delay << std::endl;if (delay == pDlg->interval){std::cout << "频率正确" << std::endl;}else if (delay > 0) {// 延迟执行std::this_thread::sleep_for(std::chrono::milliseconds(delay));std::cout << "频率正确" << std::endl;}else if (delay < 0){std::cout << "时间不够:(ms)***************************************:" << delay << std::endl;//std::this_thread::sleep_for(std::chrono::milliseconds(200000000));}}}//// 关闭串口1CloseHandle(pDlg->hSerial_L);return 0;
}

双击COM口选择控件,添加如下函数


void CMFCApplication1Dlg::OnCbnSelchangeCombo1()
{// TODO: 在此添加控件通知处理程序代码// TODO: 在此添加控件通知处理程序代码CComboBox* pCombo12 = (CComboBox*)GetDlgItem(IDC_COMBO1);CString strValue1;pCombo12->GetLBText(pCombo12->GetCurSel(), strValue1);CString vl11 = strValue1;CStringA strA(strValue1);CStringA strB("\\\\.\\");strB += strA;const char* portName = strB.GetString();// 释放 portName 的资源strB.ReleaseBuffer();strA.ReleaseBuffer();CString duankai("断开连接");if (vl11 == duankai){MessageBox(L"断开与倾角传感器的连接");}else{CStringW widePortName(portName);hSerial_L = CreateFile(widePortName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);//hSerial = CreateFile(portName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);if (hSerial_L == INVALID_HANDLE_VALUE) {if (GetLastError() == ERROR_FILE_NOT_FOUND) {std::cout << "Serial port not available." << std::endl;}}dcbSerialParams_L.DCBlength = sizeof(dcbSerialParams_L);if (!GetCommState(hSerial_L, &dcbSerialParams_L)) {std::cout << "Error getting serial port state." << std::endl;CloseHandle(hSerial_L);}dcbSerialParams_L.BaudRate = CBR_9600;dcbSerialParams_L.ByteSize = 8;dcbSerialParams_L.StopBits = ONESTOPBIT;dcbSerialParams_L.Parity = NOPARITY;if (!SetCommState(hSerial_L, &dcbSerialParams_L)) {std::cout << "Error setting serial port state." << std::endl;CloseHandle(hSerial_L);}timeouts_L.ReadIntervalTimeout = 500;timeouts_L.ReadTotalTimeoutConstant = 500;timeouts_L.ReadTotalTimeoutMultiplier = 100;timeouts_L.WriteTotalTimeoutConstant = 500;timeouts_L.WriteTotalTimeoutMultiplier = 100;if (!SetCommTimeouts(hSerial_L, &timeouts_L)){std::cout << "Error setting timeouts." << std::endl;CloseHandle(hSerial_L);}//默认为9600的时候,进行对话模式char command_R4[] = { 0x77, 0x05, 0x00, 0x0C, 0x00, 0x11 };if (!WriteFile(hSerial_L, command_R4, sizeof(command_R4), &bytesWritten4, NULL)) {std::cout << "第一次9600的对话模式配置失败" << std::endl;CloseHandle(hSerial_L);}if (!ReadFile(hSerial_L, dataReceived_L, sizeof(dataReceived_L), &bytesRead_L, NULL)) {std::cout << "第一次9600的对话模式数据读取失败." << std::endl;CloseHandle(hSerial_L);}std::cout << "第一次初始波特率:" << dcbSerialParams_L.BaudRate << std::endl;for (int i = 0; i < sizeof(dataReceived_L); i++) {printf("%02X ", dataReceived_L[i]);}bool exists = false; // 标志位,记录元素是否存在int falsecount = 0;// 循环遍历数组while (!exists) {for (int i = 0; i < sizeof(dataReceived_L); i++) {printf("%02X ", dataReceived_L[i]);}for (int i = 0; i < sizeof(dataReceived_L); i++) {if (dataReceived_L[i] == 0x77 && dataReceived_L[i + 3] == 0xFFFFFF8C) {exists = true; // 元素存在,设置标志位为truestd::cout << falsecount << std::endl;std::cout << "应答模式配置成功!" << std::endl;//std::this_thread::sleep_for(std::chrono::milliseconds(400000));break; // 跳出for循环}}if (exists){break;}if (!exists) {falsecount++;if (falsecount >= 2)//说明原有配置是115200波特率{dcbSerialParams_L.BaudRate = CBR_115200;dcbSerialParams_L.ByteSize = 8;dcbSerialParams_L.StopBits = ONESTOPBIT;dcbSerialParams_L.Parity = NOPARITY;if (!SetCommState(hSerial_L, &dcbSerialParams_L)) {std::cout << "Error setting serial port state." << std::endl;CloseHandle(hSerial_L);}timeouts_L.ReadIntervalTimeout = 500;timeouts_L.ReadTotalTimeoutConstant = 500;timeouts_L.ReadTotalTimeoutMultiplier = 100;timeouts_L.WriteTotalTimeoutConstant = 500;timeouts_L.WriteTotalTimeoutMultiplier = 100;if (!SetCommTimeouts(hSerial_L, &timeouts_L)){std::cout << "Error setting timeouts." << std::endl;CloseHandle(hSerial_L);}}if (!WriteFile(hSerial_L, command_R4, sizeof(command_R4), &bytesWritten4, NULL)) {std::cout << "115200的对话模式配置失败." << std::endl;CloseHandle(hSerial_L);}if (!ReadFile(hSerial_L, dataReceived_L, sizeof(dataReceived_L), &bytesRead_L, NULL)) {std::cout << "115200的对话模式回复失败." << std::endl;CloseHandle(hSerial_L);}}}//设置频率为115200char command_R1[] = { 0x77, 0x05, 0x00, 0x0B, 0x04, 0x14 };//115200 if (!WriteFile(hSerial_L, command_R1, sizeof(command_R1), &bytesWritten1, NULL)){std::cout << "Error writing to serial port." << std::endl;CloseHandle(hSerial_L);}if (!ReadFile(hSerial_L, dataReceived_L, sizeof(dataReceived_L), &bytesRead_L, NULL)){std::cout << "Error reading from serial port." << std::endl;CloseHandle(hSerial_L);}exists = false;while (!exists){for (int i = 0; i < sizeof(dataReceived_L); i++) {printf("%02X ", dataReceived_L[i]);}for (int i = 0; i < sizeof(dataReceived_L); i++) {if (dataReceived_L[i] == 0x77 && dataReceived_L[i + 3] == 0xFFFFFF8B) {//设置成功exists = true; // 元素存在,设置标志位为truestd::cout << "115200波特率配置成功!" << std::endl;break; // 跳出for循环}}if (exists){break;}if (!exists) {if (!WriteFile(hSerial_L, command_R1, sizeof(command_R1), &bytesWritten1, NULL)) {std::cout << "Error writing to serial port." << std::endl;CloseHandle(hSerial_L);}if (!ReadFile(hSerial_L, dataReceived_L, sizeof(dataReceived_L), &bytesRead_L, NULL)) {std::cout << "Error reading from serial port." << std::endl;CloseHandle(hSerial_L);}std::cout << "重复配置115200波特率" << std::endl;// 可以在这里添加需要执行的语句}}//00-11:应答模式 05-50Hz 04-25Hz//06-100     05-50     04-25    char command_R3[] = { 0x77, 0x05, 0x00, 0x0C, 0x03, 0x14 };//50Hzif (!WriteFile(hSerial_L, command_R3, sizeof(command_R3), &bytesWritten3, NULL)) {std::cout << "Error writing to serial port." << std::endl;CloseHandle(hSerial_L);}if (!ReadFile(hSerial_L, dataReceived_L, sizeof(dataReceived_L), &bytesRead_L, NULL)) {std::cout << "Error reading from serial port." << std::endl;CloseHandle(hSerial_L);}for (int i = 0; i < sizeof(dataReceived_L); i++) {printf("%02X ", dataReceived_L[i]);}exists = false;while (!exists) {for (int i = 0; i < sizeof(dataReceived_L); i++) {printf("%02X ", dataReceived_L[i]);}for (int i = 0; i < sizeof(dataReceived_L); i++) {if (dataReceived_L[i] == 0x77 && dataReceived_L[i + 3] == 0xFFFFFF8C) {//设置成功exists = true; // 元素存在,设置标志位为truestd::cout << "50Hz配置成功!" << std::endl;break; // 跳出for循环}}if (exists){break;}if (!exists) {if (!WriteFile(hSerial_L, command_R3, sizeof(command_R3), &bytesWritten3, NULL)) {std::cout << "Error writing to serial port." << std::endl;CloseHandle(hSerial_L);;}if (!ReadFile(hSerial_L, dataReceived_L, sizeof(dataReceived_L), &bytesRead_L, NULL)) {std::cout << "Error reading from serial port." << std::endl;CloseHandle(hSerial_L);}std::cout << "元素不存在,继续执行某条语句..." << std::endl;// 可以在这里添加需要执行的语句}}}}

实时读取界面完成。

问题三:时间同步问题

因为在实际的使用过程之中,需要用到的数据不可能只是一个倾角传感器的数据,如何进行多传感器的时间的同步是一个比较重要的问题。

针对于这个时间帧对齐方式,当存在多个传感器的时候,多个传感器的输出频率是不一致的情况下,最佳的方式是将其频率调节到整数倍的情况下。然后使用插值的方式使得其帧率变为一致的情况。

以相机而言,如下所示,可以调用相机的SDK进行人为设置相机的帧率。

可以见到相应的相机的帧率是稳定不变的,以将相机与倾角传感器时间帧进行对齐为例。首先,选定一个参考物也就是所谓的时间的参考物,我是以相机为参考时间的,将倾角传感器的频率设置为100Hz,由于此处我是将receive的长度设置为34,也就是采集长度的二倍,因此实际输出的频率为原来的1/2,也就是50Hz。(这样做的目的是方式出现丢帧的问题)

我的想法是使用时间戳的方式进行对齐,首先将相机的帧率设置为10FPS,需要进行注意的是相机设置为10FPS的过程,相机是逐渐成为10FPS的,有一个时间延迟,延迟一段时间并且记录下此时的时间戳t1。同理,倾角传感器在进行采集的过程之中也是存在相应的时间延迟,延迟之后记录下此时的时间戳t2。

其含义为相机在t1时刻以后以10Hz的频率进行采集,倾角传感器在t2时刻以后以50Hz的频率进行采集。其中10Hz对应100ms/次,50Hz对应20ms/次。其中如何对齐,后面再想。

这篇关于BWS2000倾角传感器c++测试代码_时间延迟与时间同步问题【3】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/525054

相关文章

基于MySQL Binlog的Elasticsearch数据同步实践

一、为什么要做 随着马蜂窝的逐渐发展,我们的业务数据越来越多,单纯使用 MySQL 已经不能满足我们的数据查询需求,例如对于商品、订单等数据的多维度检索。 使用 Elasticsearch 存储业务数据可以很好的解决我们业务中的搜索需求。而数据进行异构存储后,随之而来的就是数据同步的问题。 二、现有方法及问题 对于数据同步,我们目前的解决方案是建立数据中间表。把需要检索的业务数据,统一放到一张M

服务器集群同步时间手记

1.时间服务器配置(必须root用户) (1)检查ntp是否安装 [root@node1 桌面]# rpm -qa|grep ntpntp-4.2.6p5-10.el6.centos.x86_64fontpackages-filesystem-1.41-1.1.el6.noarchntpdate-4.2.6p5-10.el6.centos.x86_64 (2)修改ntp配置文件 [r

好题——hdu2522(小数问题:求1/n的第一个循环节)

好喜欢这题,第一次做小数问题,一开始真心没思路,然后参考了网上的一些资料。 知识点***********************************无限不循环小数即无理数,不能写作两整数之比*****************************(一开始没想到,小学没学好) 此题1/n肯定是一个有限循环小数,了解这些后就能做此题了。 按照除法的机制,用一个函数表示出来就可以了,代码如下

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

【C++ Primer Plus习题】13.4

大家好,这里是国中之林! ❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看← 问题: 解答: main.cpp #include <iostream>#include "port.h"int main() {Port p1;Port p2("Abc", "Bcc", 30);std::cout <<

C++包装器

包装器 在 C++ 中,“包装器”通常指的是一种设计模式或编程技巧,用于封装其他代码或对象,使其更易于使用、管理或扩展。包装器的概念在编程中非常普遍,可以用于函数、类、库等多个方面。下面是几个常见的 “包装器” 类型: 1. 函数包装器 函数包装器用于封装一个或多个函数,使其接口更统一或更便于调用。例如,std::function 是一个通用的函数包装器,它可以存储任意可调用对象(函数、函数

C++11第三弹:lambda表达式 | 新的类功能 | 模板的可变参数

🌈个人主页: 南桥几晴秋 🌈C++专栏: 南桥谈C++ 🌈C语言专栏: C语言学习系列 🌈Linux学习专栏: 南桥谈Linux 🌈数据结构学习专栏: 数据结构杂谈 🌈数据库学习专栏: 南桥谈MySQL 🌈Qt学习专栏: 南桥谈Qt 🌈菜鸡代码练习: 练习随想记录 🌈git学习: 南桥谈Git 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈�

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

06 C++Lambda表达式

lambda表达式的定义 没有显式模版形参的lambda表达式 [捕获] 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 有显式模版形参的lambda表达式 [捕获] <模版形参> 模版约束 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 含义 捕获:包含零个或者多个捕获符的逗号分隔列表 模板形参:用于泛型lambda提供个模板形参的名

购买磨轮平衡机时应该注意什么问题和技巧

在购买磨轮平衡机时,您应该注意以下几个关键点: 平衡精度 平衡精度是衡量平衡机性能的核心指标,直接影响到不平衡量的检测与校准的准确性,从而决定磨轮的振动和噪声水平。高精度的平衡机能显著减少振动和噪声,提高磨削加工的精度。 转速范围 宽广的转速范围意味着平衡机能够处理更多种类的磨轮,适应不同的工作条件和规格要求。 振动监测能力 振动监测能力是评估平衡机性能的重要因素。通过传感器实时监