01:#include <sys/types.h>
02:#include <sys/stat.h>
03:#include <sys/ioctl.h>
04:#include <fcntl.h>
05:#include <termios.h>
06:#include <unistd.h>
07:#include <stdio.h>
08:#include <stdlib.h>
09:#include <string.h>
10:
11:/* シリアルインターフェースに対応するデバイスファイル */
12:#define SERIAL_PORT "/dev/ttyAM1"
13:
14:int main(){
15:
16: /* シリアルインターフェースのオープン */
17: /* O_RDWR: 入出力用にオープン */
18: /* O_NOCTTY: ノイズ等による不意のctrl-cを防ぐため,tty制御なし */
19: /* シリアルインターフェースをint型変数"fd"の名前で扱えるように */
20: int fd;
21: fd = open(SERIAL_PORT, O_RDWR | O_NOCTTY);
22: if(fd < 0){
23: printf("%s doesn't open it\n",SERIAL_PORT);
24: return -1;
25: }
26:
27: /* シリアルポートの設定を行う変数を宣言 */
28: struct termios oldtio, newtio;
29: /* 現在の設定を oldtio に保存 */
30: tcgetattr(fd, &oldtio);
31: /* 今回使用する設定 newtio に現在の設定 oldtio をコピー */
32: newtio = oldtio;
33:
34: /* 入出力スピードの設定 */
35: /* 以下の方法1または方法2で設定.どちらかでよいので方法2を有効にしている */
36:
37: /* 方法1 */
38: /* cfsetispeed(&newtio, B115200); /* 入力スピード設定 */
39: /* cfsetospeed(&newtio, B115200); /* 出力スピード設定 */
40:
41: /* 方法2 */
42: cfsetspeed(&newtio, B115200); /* 入出力スピード設定 */
43:
44: /* 27行目-42行目までの設定を有効にする */
45: tcflush(fd, TCIFLUSH);
46: tcsetattr(fd, TCSANOW, &newtio); /* 設定を有効に */
47:
48: /* ここからがユーザ固有の処理:例として文字列 hello を送信(write関数).受信はread関数 */
49: char buf[20];
50: strcpy(buf,"hello");
51: write(fd, buf , sizeof(buf)); /* write関数:送信処理 */
52:
53: /* デバイスの設定を戻す */
54: tcsetattr(fd, TCSANOW, &oldtio);
55: close(fd);
56: return 0;
57:}