Skip to content

Instantly share code, notes, and snippets.

@ringo156
Created October 23, 2018 10:23
Show Gist options
  • Save ringo156/e46e9f48c904e7973030bd9b7c7f063c to your computer and use it in GitHub Desktop.
Save ringo156/e46e9f48c904e7973030bd9b7c7f063c to your computer and use it in GitHub Desktop.
serial communication test for raspberrypi
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#define SERIAL_PORT "/dev/ttyAMA0" /* シリアルインターフェースに対応するデバイスファイル */
#define BAUD_RATE B9600
int main(int argc, char *argv[])
{
int fd; /* ファイルディスクリプタ */
struct termios oldtio, newtio; /* シリアル通信設定 */
fd = open(SERIAL_PORT, O_RDWR); /* デバイスをオープンする */
if (fd < 0) {
printf("open error\n");
return -1;
}
ioctl(fd, TCGETS, &oldtio); /* 現在のシリアルポートの設定を待避させる */
newtio = oldtio; /* ポートの設定をコピー */
newtio.c_cflag += CREAD; // 受信有効
newtio.c_cflag += CLOCAL; // ローカルライン(モデム制御なし)
newtio.c_cflag += CS8; // データビット:8bit
newtio.c_cflag += 0; // ストップビット:1bit
newtio.c_cflag += 0; // パリティ:None
cfsetispeed( &newtio, BAUD_RATE );
cfmakeraw(&newtio); // RAWモード
ioctl(fd, TCSETS, &newtio); /* ポートの設定を有効にする */
printf("connect open\n");
// read(fd, buf, sizeof(buf)); /* デバイスから255バイト読み込み */
// printf(buf);
char buf[20];
sprintf(buf, "test\r\n");
write(fd, buf, sizeof(buf)); /* デバイスへ255バイト書き込み */
ioctl(fd, TCSETS, &oldtio); /* ポートの設定を元に戻す */
close(fd); /* デバイスのクローズ */
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment