備忘使用。
你所需要的網(wǎng)站建設(shè)服務(wù),我們均能行業(yè)靠前的水平為你提供.標(biāo)準(zhǔn)是產(chǎn)品質(zhì)量的保證,主要從事網(wǎng)站制作、成都網(wǎng)站制作、企業(yè)網(wǎng)站建設(shè)、移動(dòng)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)、品牌網(wǎng)站設(shè)計(jì)、網(wǎng)頁制作、做網(wǎng)站、建網(wǎng)站。創(chuàng)新互聯(lián)建站擁有實(shí)力堅(jiān)強(qiáng)的技術(shù)研發(fā)團(tuán)隊(duì)及素養(yǎng)的視覺設(shè)計(jì)專才。
- #include
- #include
- #include
- using boost::asio::io_service;
- using boost::system::error_code;
- using boost::asio::serial_port;
- using boost::asio::deadline_timer;
- using boost::asio::buffer;
- class MyCom
- {
- public:
- MyCom(void)
- {
- _pSerialPort= new serial_port(_ios);
- _pTimer = new deadline_timer(_ios);
- }
- ~MyCom(void)
- {
- if (_pTimer != NULL)
- {
- delete _pTimer;
- _pTimer = NULL;
- }
- if (_pSerialPort != NULL)
- {
- delete _pSerialPort;
- _pSerialPort = NULL;
- }
- }
- void Open(const string& comName);
- {
- _pSerialPort->open(comName);
- _pSerialPort->set_option(serial_port::flow_control(serial_port::flow_control::none)); //流量控制為none
- _pSerialPort->set_option(serial_port::parity(serial_port::parity::none)); //奇偶檢驗(yàn)為none
- _pSerialPort->set_option(serial_port::stop_bits(serial_port::stop_bits::one)); //停止位為1
- _pSerialPort->set_option(serial_port::character_size(8)); //字符大小(數(shù)據(jù)位)為8
- _pSerialPort->set_option(serial_port::baud_rate(115200));//波特率
- }
- void Send(const string& data)
- {//同步發(fā)數(shù)據(jù)
- _mutex.lock();
- _pSerialPort->write_some(buffer(data, data.size()));
- _mutex.unlock();
- }
- string Recv()
- {//異步收數(shù)據(jù)
- _mutex.lock();
- memset(_buf, 0, sizeof(_buf));
- _pSerialPort->async_read_some(buffer(_buf, 256),
- boost::bind(&MyCom::RecvHandle, this,
- boost::asio::placeholders::error,//傳送錯(cuò)誤碼
- boost::asio::placeholders::bytes_transferred//傳送字節(jié)數(shù)
- ));
- _mutex.unlock();
- _pTimer->expires_from_now(boost::posix_time::millisec(SLEEP_TIME));
- _pTimer->async_wait(boost::bind(&serial_port::cancel, _pSerialPort));
- _ios.run();//異步情況下使用詞句才開始執(zhí)行
- _ios.reset();//還原狀態(tài)
- return string(_buf, _ret);
- }
- void Close()
- {
- _mutex.lock();
- if (_pSerialPort->is_open())
- _pSerialPort->close();
- _mutex.unlock();
- }
- protected:
- void RecvHandle(const error_code& error, size_t bytes_transferred)
- {
- if (!error)
- _pTimer->cancel();//沒有錯(cuò)誤就結(jié)束定時(shí)器
- _ret = bytes_transferred;
- }
- private:
- boost::asio::io_service _ios;
- serial_port* _pSerialPort;
- deadline_timer* _pTimer;
- char _buf[256];
- size_t _ret;
- boost::mutex _mutex;
- };