2010年2月3日水曜日

boost::asio で serial通信 (PATLITE)

仕事で、パトライトを制御する事になった。せっかくなので、boost::asio を使ってみた。


#include <boost/asio.hpp>
#include <iostream>
#include <iomanip>

#define PATLITE_COMMAND_

#define PATLITE_CMD_BIT 0x30
#define PATLITE_RED_ON 0x01
#define PATLITE_YELLOW_ON 0x02
#define PATLITE_GREEN_ON 0x04
#define PATLITE_BUZZ_SHORT 0x08
//
#define PATLITE_BUZZ_LONG 0x01
#define PATLITE_RED_BLINK 0x02
#define PATLITE_YELLOW_BLINK 0x04
#define PATLITE_GREEN_BLINK 0x08

void write_hex( const char* p, size_t len ) {
for( size_t i = 0; i < len; ++i ) {
std::cout << ":" << std::hex << std::setw(2) << (int)p[i];
}
}

int main() {
char start_rbuf[ 7 ] = { 0x40, 0x3f, 0x3f, 0x31, PATLITE_CMD_BIT | PATLITE_RED_BLINK | PATLITE_BUZZ_LONG, PATLITE_CMD_BIT, 0x21 };
char start_ybuf[ 7 ] = { 0x40, 0x3f, 0x3f, 0x31, PATLITE_CMD_BIT | PATLITE_YELLOW_BLINK, PATLITE_CMD_BIT | PATLITE_BUZZ_SHORT, 0x21 };
char start_gbuf[ 7 ] = { 0x40, 0x3f, 0x3f, 0x31, PATLITE_CMD_BIT | PATLITE_GREEN_BLINK | PATLITE_BUZZ_LONG, PATLITE_CMD_BIT, 0x21 };
char stop_buf[ 7 ] = { 0x40, 0x3f, 0x3f, 0x30, 0x3f, 0x3f, 0x21 };
char buf[ 8 ];

try {
boost::asio::io_service service;
boost::asio::serial_port port( service );
std::cout << "open COM1" << std::endl;
port.open( "COM1" );
std::cout << "set up baud_rate 9600" << std::endl;
port.set_option( boost::asio::serial_port_base::baud_rate( 9600 ) );
port.set_option( boost::asio::serial_port_base::character_size( 8 ) );
port.set_option( boost::asio::serial_port_base::stop_bits() );
port.set_option( boost::asio::serial_port_base::parity() );
port.set_option( boost::asio::serial_port_base::flow_control() );
std::cout << "write 1"; write_hex( start_rbuf, 7 ); std::cout << std::endl;
port.write_some( boost::asio::buffer( start_rbuf, 7 ) );
std::cout << "read 1" << std::endl;
port.read_some( boost::asio::buffer( buf, 1 ) );
std::cout << "result: " << std::hex << (int)buf[0] << std::endl;
Sleep( 2000 );
std::cout << "write 2"; write_hex( start_ybuf, 7 ); std::cout << std::endl;
port.write_some( boost::asio::buffer( start_ybuf, 7 ) );
std::cout << "read 2" << std::endl;
port.read_some( boost::asio::buffer( buf, 1 ) );
std::cout << "result: " << std::hex << (int)buf[0] << std::endl;
Sleep( 2000 );
std::cout << "write 3"; write_hex( start_gbuf, 7 ); std::cout << std::endl;
port.write_some( boost::asio::buffer( start_gbuf, 7 ) );
std::cout << "read 3" << std::endl;
port.read_some( boost::asio::buffer( buf, 1 ) );
std::cout << "result: " << std::hex << (int)buf[0] << std::endl;
Sleep( 2000 );
std::cout << "write 4"; write_hex( stop_buf, 7 ); std::cout << std::endl;
port.write_some( boost::asio::buffer( stop_buf, 7 ) );
std::cout << "read 4" << std::endl;
port.read_some( boost::asio::buffer( buf, 1 ) );
std::cout << "result: " << std::hex << (int)buf[0] << std::endl;
std::cout << "end" << std::endl;
} catch( std::exception& e ) {
std::cout << e.what() << std::endl;
}
return 0;
}



シリアル通信のオプションは、キッチリ指定しないといけないようです。デフォルトであろうと指定しないと動作しなかった。

0 件のコメント: