Linux Serial communication code
Linux Serial 통신코드
쉽게 구할수 있는 C code를 class로 묶어쉽게 사용하기 쉽게 해두었지만, 이왕이면 Qt혹은 Boost등에 있는 외부라이브러리를 이용하세요.(그 외 라이브러리도 마찬가지)라이브러리를 사용하는 것이 성능으로나 안정성으로나 개발속도면에서 더 좋습니다.
#include <string.h>
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
#include <iostream>
class Serial
{
public:
Serial()
{
memset(&newtio, 0, sizeof(newtio) );
newtio.c_cflag = B9600; // 통신 속도 115200
newtio.c_cflag |= CS8; // 데이터 비트가 8bit
newtio.c_cflag |= CLOCAL; // 외부 모뎀을 사용하지 않고 내부 통신 포트 사용
newtio.c_cflag |= CREAD; // 쓰기는 기본, 읽기도 가능하게
newtio.c_iflag = IGNPAR; // parity 비트는 없음
newtio.c_oflag = 0;
newtio.c_lflag = 0;
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 1;
tcflush (fd, TCIFLUSH );
tcsetattr(fd, TCSANOW, &newtio ); // 포트에 대한 통신 환경을 설정합니다.
}
int open(std::string device) {
fd = ::open(device.c_str() , O_RDWR | O_NONBLOCK );
}
int setAttr(termios& newtio)
{
tcflush (fd, TCIFLUSH );
tcsetattr(fd, TCSANOW, &newtio ); // 포트에 대한 통신 환경을 설정합니다.
}
int write(std::string str){
::write(fd,str.c_str(),str.size());
}
std::string read() {
char buf[255] = {0};
::read(fd,buf,sizeof buf);
std::string str(buf);
return str;
}
int close(){
::close(fd);
}
private:
int fd;
termios newtio;
};
int main( int argc, char *argv[] )
{
Serial serial;
serial.open("text.txt");
serial.write("aaaaa");
serial.close();
termios newtio;
memset(&newtio, 0, sizeof(newtio) );
newtio.c_cflag = B9600; // 통신 속도 9600
newtio.c_cflag |= CS8; // 데이터 비트가 8bit
newtio.c_cflag |= CLOCAL; // 외부 모뎀을 사용하지 않고 내부 통신 포트 사용
newtio.c_cflag |= CREAD; // 쓰기는 기본, 읽기도 가능하게
newtio.c_iflag = IGNPAR; // parity 비트는 없음
newtio.c_oflag = 0;
newtio.c_lflag = 0;
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 1;
serial.open("text2.txt");
serial.setAttr(newtio);
std::cout << serial.read() <<std::endl;
serial.close();
return 0;
}
댓글
댓글 쓰기