Serial Port Programming on Linux (Ubuntu 12.04, Eclipse C) :: Horizontal Grays S2

블루투스를 이용해서 Main PC와 통신을 해야해서 시리얼 프로그래밍이 필요하다.


그래서 검색해봤더니 (http://blog.naver.com/PostView.nhn?blogId=buniel1&logNo=60065576523&redirect=Dlog&widgetTypeCall=true)


오.. 뭐 이리 복잡해 --;


여기서 비동기 입력 방식을 처음에 채택..

예제를 보면 signal_handler_IO는 흔히 펌웨어에서의 Interrupt와 같은 개념

프로그래밍 하고 동작은 잘 하는데... 

문제는 signal_handler_IO가 Receive 할 때 뿐 아니고 Send 할 때도 발생한다.


그래서 다시 검색해서 가장 원론적인 문서(http://www.cmrr.umn.edu/~strupp/serial.html) 에 의해 다시 프로그래밍


소스는 캠으로 받은 영상을 모니터에 출력해주면서 블루투스를 통해 날아온 데이터를 읽어 콘솔에 뿌려주고 Echo하는 것..  설명은 생략


* 예제는 별거 없슴 UART Setting 하고 블루투스를 통해 날아오는 수신데이터 ReadSerialPort로 읽고 Write로 Sending 

   수신만 signal_handler_IO를 이용할 수 있었다면 참 좋았을텐데~ 


//============================================================================

// Name        : 140320_UARTTEST.cpp

// Author      : 

// Version     :

// Copyright   : Your copyright notice

// Description : Hello World in C++, Ansi-style

//============================================================================


#include <iostream>

#include <stdio.h>

#include <sys/time.h>


#include <termios.h>

#include <unistd.h>

#include <fcntl.h>

#include <sys/signal.h>

#include <sys/types.h>


#include <stdlib.h>




#include "opencv2/opencv.hpp"



#define BAUDRATE B115200


#define MODEMDEVICE "/dev/rfcomm0"

#define _POSIX_SOURCE 1

#define FALSE 0

#define TRUE 1


volatile int STOP=FALSE;



using namespace std;


int fd,c, res;

struct termios oldtio,newtio;

struct termios oldkey,newkey;

char rbuff[255];


int ReadSeralPort(void)

{

int retval;

res = read(fd,rbuff,255);

retval = res;

return retval;

}

int main() {


struct timeval start_time;

struct timeval end_time;

double elapsed_time;

float fps;

double total_fps = 0.0,average_fps = 0.0;

int cnt=1;

int key;

int i;

int ReadPort;

char buffer[25];

IplImage* img;

CvFont font;

cvInitFont(&font,CV_FONT_HERSHEY_SIMPLEX,0.5,0.5);

string Sstring;

pid_t pid;


long DATABITS, STOPBITS, PARITYON, PARITY;

DATABITS = CS8;

STOPBITS = 0;

PARITYON = 0;

PARITY = 0;


//Shell command

//Change permission


int ret = system("sudo chmod a+rw /dev/rfcomm0");

if(ret == -1) printf("chmod Fail %d\n",ret);

else printf("chmod OK %d\n",ret);


fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY | O_NDELAY);

if (fd <0) { perror(MODEMDEVICE); exit(-1); }


fcntl(fd, F_SETFL, 0);


tcgetattr(fd,&oldtio); // save current port settings


// canonical 입력처리를 위한 포트 세팅 */

newtio.c_cflag = BAUDRATE | CRTSCTS | DATABITS | STOPBITS | PARITYON | PARITY |  CLOCAL | CREAD;

newtio.c_iflag = IGNPAR | IGNCR ; //IGNPAR | ICRNL;

newtio.c_iflag &= ~(IXON | IXOFF | IXANY);

newtio.c_oflag &= ~OPOST;

newtio.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); //ICANON;

newtio.c_cc[VMIN]=0;

newtio.c_cc[VTIME]=0;

tcflush(fd, TCIFLUSH);

tcsetattr(fd,TCSANOW,&newtio);


write( fd, "Test String from jslee", 22);



CvCapture* capture = cvCaptureFromCAM(0);

cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, 640);

cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, 480);

cvSetCaptureProperty( capture, CV_CAP_PROP_FPS, 65);


while(1)

{

gettimeofday(&start_time,NULL);

sprintf(rbuff,"");

ReadPort = ReadSeralPort();

if(ReadPort)

{


printf("Receive String = ");


for(i=0;i<ReadPort;i++)

{

printf("%c",rbuff[i]);

//printf("%c",buffer[i]);


}

printf(" [res = %d]\n",ReadPort);

write( fd, rbuff, ReadPort);


}




cvGrabFrame(capture);

img = cvRetrieveFrame(capture);

cvPutText(img,rbuff,cvPoint(20,20),&font,CV_RGB(255,255,255));



cvNamedWindow( "PreviewImage", 1 );

cvShowImage( "PreviewImage", img );

cvMoveWindow("PreviewImage",200,400);




key = cvWaitKey(1);

if(key > 10) break;


gettimeofday(&end_time, NULL);



elapsed_time = (double)(end_time.tv_sec) + (double)(end_time.tv_usec)/1000000.0 - (double)(start_time.tv_sec) - (double)(start_time.tv_usec)/1000000.0;

fps = 1.0 / elapsed_time;

total_fps += fps;

average_fps = total_fps / (double)(cnt);

cnt++;

if(cnt == 100)

{

cnt = 1;

total_fps = 0.0;

}

elapsed_time *= 1000.0;


//printf("Elapsed T = %2.3f ms, Frame = %2.3f (fps), Avrg Frame Rate = %2.3f\n",elapsed_time,fps,average_fps);


}

cvReleaseImage(&img);

cvReleaseCapture( &capture );

// restore old port settings

tcsetattr(fd,TCSANOW,&oldtio);

printf("Close and Quit\n");

close(fd);

// cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!



return 0;

}



+ Recent posts