在更深入的学习之前,先来做一个练习题。
题目是:
1. 打开串口设备,输入一行指令,每条指令在128字节以内,
2. 将输入的指令尾部添加'\r'字符,发送给串口,
3. 等待串口的返回数据,打印到标准输出,存储在vector中,保存在程序中。
代码如下:
//============================================================================
// Name : SerialTest.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <fcntl.h>
#include <termio.h>
#include <memory.h>
#include <unistd.h>
#include <string.h>
using namespace std;
#define MAX_LEN 128
int main(int argc, char *argv[])
{
if (argv[1] == nullptr) {
cerr << "Please input a device." << endl;
return -1;
}
if (argv[2] == nullptr) {
cerr << "Please input a file name." << endl;
return -1;
}
string dev = argv[1];
string file = argv[2];
int fd = ::open(dev.c_str(), O_RDWR | O_NONBLOCK);
if (fd < 0) {
cerr << "Cannot open device[" << dev.c_str() << "]" << endl;
return -1;
}
cout << "Device[" << dev.c_str() << "] opened successfully." << endl;
termios attr;
memset(&attr, 0, sizeof(attr));
attr.c_iflag = IGNPAR;
attr.c_cflag = B115200 | HUPCL | CS8 | CREAD | CLOCAL;
attr.c_cc[VMIN] = 1;
if (tcsetattr(fd, TCSANOW, &attr) != 0) {
cout << "Cannot set termios for device." << endl;
return -1;
}
cout << "Device[" << dev.c_str() << "] termios setting successfully." << endl;
char rbuf[MAX_LEN];
string rstr;
string sstr;
vector<string> vec;
ofstream fout(file);
while (getline(cin, sstr)) {
cout << "Send: " << sstr << endl;
sstr += "\r";
if (::write(fd, sstr.c_str(), sstr.size()) < 0) {
cerr << "Send Error!" << endl;
return -1;
}
usleep(20000);
memset(rbuf, 0, sizeof(rbuf));
::read(fd, rbuf, MAX_LEN) ;
rstr = rbuf;
cout << "=> " << rstr << flush;
vec.push_back(rstr);
fout << rstr << flush;
}
cout << "End of File." << endl;
cout << "Data Received: [" << vec.size() << "]" << endl;
for (auto &str : vec)
cout << str << flush;
fout.close();
::close(fd);
cout << "Bye bye!" << endl;
return 0;
}
对于C语言来说很复杂的功能,用C++却能简单的实现。
面向对象编程,是C++的特点,也是它的优势!
文章评论(0条评论)
登录后参与讨论