当前位置: 首页>>代码示例>>C++>>正文


C++ Serial::ReadBlock方法代码示例

本文整理汇总了C++中Serial::ReadBlock方法的典型用法代码示例。如果您正苦于以下问题:C++ Serial::ReadBlock方法的具体用法?C++ Serial::ReadBlock怎么用?C++ Serial::ReadBlock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Serial的用法示例。


在下文中一共展示了Serial::ReadBlock方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: main

int main (void) {
	// Initialize read buffer, and serial port parameters
	int fd;
	const int baud = 9600;
	char serialport[] = "/dev/ttyACM0";

	// Define the delimiters of message
	std::string startChar = "$";
	std::string endChar = "!";
	std::size_t foundStart, foundEnd;
	int chksum = 0;

	// Setup file name for log file
	time_t rawtime;
	struct tm *timeinfo;
	time(&rawtime);
	timeinfo = localtime(&rawtime);
	std::string timestr (asctime(timeinfo));
	std::string logPath = "/home/edward/Documents/DataLogging/log_files/";
	std::string filename = logPath + "log_" + timestr.substr(0,timestr.length()-1) + ".dat";

	// Display file name
	cout << "main: Data is being logged into the file: ";
	cout << filename << endl;

	// Initialize serial port
	Serial serial;
	fd = serial.Initialize(serialport, baud);

	// Read from serial port and write to file
	if (fd > 0) {
		std::ofstream file (filename.c_str());
		if (file.is_open()) {
			cout << "main: File opened successfully, logging data...\n";
			while (1) {
				char buf[127];
				if (serial.ReadBlock(fd, buf) != -1) {
					//file << buf;
					cout << buf;
					//printf("%s", buf);
					//cout << sizeof(buf) << endl;
					// Convert character array into string
					std::string buffer = buf;
					//cout << buffer;
					foundStart = buffer.find_first_of(startChar);
					foundEnd = buffer.find_first_of(endChar, foundStart+1);
					//cout << foundStart << "|" << foundEnd << endl;
					if ((foundStart != std::string::npos) && (foundEnd != std::string::npos)) {
						std::string msg = buffer.substr(foundStart, (foundEnd-foundStart+1));
						std::string::size_type sz;
						int msgChksum = std::stoi(buffer.substr((foundEnd+1), (buffer.length()-foundEnd-2)), &sz);
						chksum = findChksum(msg);
						if (chksum == msgChksum) {
							msg = msg + '\n';
							//file << msg;
							//cout << msg;
						}
					}
				}
			}
		}
		else {
			cout << "main: File failed to open, exiting...\n";
			exit(EXIT_FAILURE);
		}	
	}
	else {
		cout << "main: Initialization failed, exiting...\n";
		exit(EXIT_FAILURE);
	}

	return 0;
}
开发者ID:zhu-edward,项目名称:Serial_Data_Logging,代码行数:73,代码来源:dataLogging.cpp


注:本文中的Serial::ReadBlock方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。