Linuxシリアルプログラミング
8388 ワード
まずヒントが必要です.ubuntuの下でシリアルポートを開くにはスーパー権限が必要です.次の2つの方法でシリアルポートを開く権限を得ることができます.方法1:ttyは「dialout」グループに属するため、dialoutユーザーグループにユーザーを加入すればよい.例えば、私のユーザー名はthinkerで、次のように操作します.sudo usermod-aG dialout thinker方法2:etc/udev/rules.dディレクトリの下に20-usb-serialを追加します.rulesのファイルです.内容は次のとおりです.
パソコンをログアウトまたは再起動すればいいです.
二このプログラムが送信するコマンドはグリス立式エアコンの閉鎖コマンドであり、他のエアコンまたは他のコマンドは以下のcomm変数の値を変更する必要がある.main.cpp
InfraredSerial.h,main.cppを同じディレクトリの下に置く
付:10進数を16進数にする
KERNEL=="ttyUSB*" MODE="0666"
パソコンをログアウトまたは再起動すればいいです.
二このプログラムが送信するコマンドはグリス立式エアコンの閉鎖コマンドであり、他のエアコンまたは他のコマンドは以下のcomm変数の値を変更する必要がある.main.cpp
#include "nfraredSerial.h"
#include
#include
#include
#include
#include
#include
int main(int argc, char **argv)
{
char comm[10] = {0};
comm[0] = 0x04;
comm[1] = 0x00;
comm[2] = 0x08;
comm[3] = 0x08;
comm[4] = 0x04;
InfraredSerial infrared_serial;
infrared_serial.uart_send(comm, 5);
char recv[5];
infrared_serial.uart_recv(recv, 10);
return 0;
}
InfraredSerial.h,main.cppを同じディレクトリの下に置く
//
// Created by thinker on 16-7-7.
//
#ifndef FIRST_INFRAREDSERIAL_H
#define FIRST_INFRAREDSERIAL_H
#endif //FIRST_INFRAREDSERIAL_H
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define DEV "/dev/ttyUSB0"
class InfraredSerial {
int serial_fd;
public:
InfraredSerial():serial_fd(0){
serial_fd = open(DEV, O_RDWR | O_NOCTTY | O_NDELAY);
if (serial_fd < 0) {
perror("open");
}
struct termios options;
tcgetattr(serial_fd, &options);
/**2. */
options.c_cflag |= (CLOCAL | CREAD);// , ,
options.c_cflag &= ~CSIZE;// ,
options.c_cflag &= ~CRTSCTS;//
options.c_cflag |= CS8;//8
options.c_cflag &= ~CSTOPB;//1
options.c_iflag |= IGNPAR;//
options.c_oflag = 0; //
options.c_lflag = 0; //
cfsetospeed(&options, B9600);//
cfsetispeed(&options, B9600);
/**3. ,TCSANOW: */
tcflush(serial_fd, TCIFLUSH);// ,
tcsetattr(serial_fd, TCSANOW, &options);
};
// ~InfraredSerial();
int uart_send(char *data, ssize_t datalen);
int uart_recv(char *data, int datalen);
protected:
};
int InfraredSerial::uart_recv(char *data, int datalen)
{
int len=0, ret = 0;
fd_set fs_read;
struct timeval tv_timeout;
FD_ZERO(&fs_read);
FD_SET(serial_fd, &fs_read);
tv_timeout.tv_sec = (10*20/115200+2);
tv_timeout.tv_usec = 0;
ret = select(serial_fd+1, &fs_read, NULL, NULL, &tv_timeout);
printf("ret = %d
", ret);
// 0, timeout , -1
if (FD_ISSET(serial_fd, &fs_read)) {
len = read(serial_fd, data, datalen);
printf("len = %d
", len);
return len;
} else {
perror("select");
return -1;
}
}
int InfraredSerial::uart_send(char *data, ssize_t datalen)
{
ssize_t len = 0;
len = write(serial_fd, data, datalen);//
if(len == datalen) {
return len;
} else {
tcflush(serial_fd, TCOFLUSH);//TCOFLUSH
return -1;
}
}
付:10進数を16進数にする
char comm[10] = {0};
int int_tem = 4;
char *tem;
tem = (char *)&int_tem;
comm[0] = tem[0]&0xff; // , tem[3];
printf("%x", comm[0]); // ,