cpp_uart - 8BitsCoding/RobotMentor GitHub Wiki

LinuxSerialExam

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <termios.h>
#include <fcntl.h>

int main( void)
{
   int fd;
   // ํ†ต์‹  ํฌํŠธ๋ฅผ ํŒŒ์ผ ๊ฐœ๋…์œผ๋กœ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•œ ๋””์Šคํฌ๋ฆฝํ„ฐ ์ž…๋‹ˆ๋‹ค.
   // ์ด ํŒŒ์ผ ๋””์Šคํฌ๋ฆฝํ„ฐ๋ฅผ ์ด์šฉํ•˜์—ฌ ํ‘œ์ค€ ์ž…์ถœ๋ ฅ ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 

   struct termios newtio;
   // ๋ณด์˜ค์œจ์ด๋‚˜ stop bit ํฌ๊ธฐ ๋“ฑ์˜ ์‹œ๋ฆฌ์–ผ ํ†ต์‹  ํ™˜๊ฒฝ์„ ์„ค์ •ํ•˜๊ธฐ ์œ„ํ•ด
   // termios ๊ตฌ์กฐ์ฒด๋ฅผ ์„ ์–ธํ–ˆ์Šต๋‹ˆ๋‹ค. 

   fd = open( "/dev/ttyS0", O_RDWR ยฆ O_NOCTTY ยฆ O_NONBLOCK );

   // /dev/ttyS0๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด open()ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.
   // O_RDWR์€ ํŒŒ์ผ ๋””์Šคํฌ๋ฆฝํ„ฐ์ธ fd๋ฅผ ์ฝ๊ธฐ์™€ ์“ฐ๊ธฐ ๋ชจ๋“œ๋กœ ์—ด๊ธฐ ์œ„ํ•œ ์ง€์ •์ด๋ฉฐ
   // O_NOCCTY์™€ O_NONBLOCK๋Š” ์‹œ๋ฆฌ์–ผ ํ†ต์‹  ์žฅ์น˜์— ๋งž์ถ”์–ด ์ถ”๊ฐ€ํ–ˆ์Šต๋‹ˆ๋‹ค.

   memset( &newtio, 0, sizeof(newtio) );

   // ์‹œ๋ฆฌ์–ผ ํ†ต์‹ ํ™˜๊ฒฝ ์„ค์ •์„ ์œ„ํ•œ ๊ตฌ์กฐ์ฒด ๋ณ€์ˆ˜ newtio ๊ฐ’์„ 0 ๋ฐ”์ดํŠธ๋กœ ๊นจ๋—์ด ์ฑ„์›๋‹ˆ๋‹ค. 

   newtio.c_cflag = B115200;   // ํ†ต์‹  ์†๋„ 115200 
   newtio.c_cflag ยฆ= CS8;      // ๋ฐ์ดํ„ฐ ๋น„ํŠธ๊ฐ€ 8bit 
   newtio.c_cflag ยฆ= CLOCAL;   // ์™ธ๋ถ€ ๋ชจ๋Ž€์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ๋‚ด๋ถ€ ํ†ต์‹  ํฌํŠธ ์‚ฌ์šฉ 
   newtio.c_cflag ยฆ= CREAD;    // ์“ฐ๊ธฐ๋Š” ๊ธฐ๋ณธ, ์ฝ๊ธฐ๋„ ๊ฐ€๋Šฅํ•˜๊ฒŒ 
   newtio.c_iflag = 0;         // 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 );   // ํฌํŠธ์— ๋Œ€ํ•œ ํ†ต์‹  ํ™˜๊ฒฝ์„ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค. 
   
   write( fd, "forum.falinux.com", 17);
   // ํ‘œ์ค€ ์ž…์ถœ๋ ฅ ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์—ฌ ์‹œ๋ฆฌ์–ผ ํฌํŠธ๋กœ 17์ž์˜ ๋ฌธ์ž์—ด์„ ์ „์†กํ•ฉ๋‹ˆ๋‹ค.
   
   close( fd);
   // ํ†ต์‹  ํฌํŠธ๋ฅผ ๋‹ซ์•„ ์‚ฌ์šฉ์„ ์ค‘์ง€ํ•ฉ๋‹ˆ๋‹ค. 
   
   return 0; 
}
โš ๏ธ **GitHub.com Fallback** โš ๏ธ