IoT/Raspberry Pi

[라즈베리파이] UART 비동기 시리얼 통신 해보기 - 3 (양방향 통신)

반나무 2022. 1. 18. 22:35

1번글, 2번글에 이어집니다.

 

단방향으로 테스트를 완료했으니

서로의 회로보며 세팅하고 양방향으로 채팅하는 프로그램을 제작해봅니다.

양방향 채팅 프로그램 (C)

#include <stdio.h>
#include <string.h>
#include <wiringPi.h>
#include <wiringSerial.h>
#include <pthread.h>

#define BAUD 9600

int fd;
char text[100] = {'\0'};

// 받는 스레드
void *thread_from()
{
	printf("1");
	while(1)
	{
		if(serialDataAvail(fd))
		{
			printf("%c", serialGetchar(fd));
			serialFlush(fd);
		}
	}
}

// 보내는 스레드
void *thread_send()
{
	while(1)
	{
		printf("\n send text : ");
		fgets(text, 100, stdin);
		fflush(stdin);
		serialPuts(fd, text);
		delay(100);
	}
}

void main()
{
	// 스레드 선언
	pthread_t thread1, thread2;
	
	// 시리얼 오픈
	if((fd = serialOpen("/dev/serial0", BAUD)) < 0 )
	{
		printf("ERROR");
		return 1;
	}

	printf("CHAT TEST\n");
	
	pthread_create(&thread1, NULL, thread_from, NULL);
	pthread_create(&thread2, NULL, thread_send, NULL);

	while(1);
}

 

반응형