Skip to content
Snippets Groups Projects
Commit d035c7ed authored by Seung Hun Han's avatar Seung Hun Han
Browse files

final

parent 69cadc8a
No related branches found
No related tags found
No related merge requests found
Showing
with 1919 additions and 0 deletions
File added
#include <pthread.h> // -lpthread
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <time.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define BUF_SIZE 1024
char msg[32];
void error_handling(char *message);
void remove_spaces(char* str);
static void *recvi(void *arg);
static void *sendmaster(void *arg);
/**
* DESCRIPTION
* This code is attached to the Raspberry Pi #3
* this module establish connection with Raspberry Pi #4(Master's main device) through socket
*
* this device is connected with GPS Module,
* and it receives order from RP #4 to take a photo in this device
*
* In summary,
* RP #3 make an order to this device(RP #4) to take a photo, based on RP #3's heartbeat sensor data
* and if its order has sent to this device through socket,
* Camera Module takes some photos and save'em
*/
int main(int argc, char *argv[])
{
pthread_t p_thread_recv, p_thread_send;
const char server_ip[] = "192.168.219.107";
struct sockaddr_in serv_addr;
time_t current_time;
ssize_t str_len;
int sock, cnt;
char command[256];
char* times;
//socket 설정
sock = socket(PF_INET, SOCK_STREAM, 0);
if(sock == -1) {
error_handling("socket() error");
}
//주소&포트 설정
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(server_ip);
serv_addr.sin_port = htons(atoi("8886"));
//socket 연결
if(connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr) ) == -1 ) {
error_handling("connect() error");
}
pthread_create(&p_thread_recv, NULL, recvi, (void *)&sock);
pthread_create(&p_thread_send, NULL, sendmaster, NULL);
while (true) {
// 사진촬영 명령을 받으면 1초간격으로 5번 사진촬영
if (msg[0] == '1'){ // RF통신용
//if (strcmp(msg, "1") == 0){ // 소켓통신용
cnt=5;
while(cnt--) {
current_time = time(NULL);
times = ctime(&current_time);
times[strlen(times) - 2] = '\0';
strcat(times, ".jpg");
remove_spaces(times);
printf("%s\n",times);
// 현재 시간을 이름으로 picture폴더에 사진 저장
sprintf(command, "raspistill -t 1 -o ./picture/%s", times);
system(command);
sleep(1);
}
}
}
//파일 & 소켓 연결 해제
close(sock);
return(0);
}
//오류 메시지 출력함수
void error_handling(char *message){
fputs(message,stderr);
fputc('\n',stderr);
exit(1);
}
//공백을 _로 바꾸는 함수
void remove_spaces(char* str)
{
for (int i = 0; str[i]; i++) {
if (str[i] == ' ') {
str[i] = '_';
}
}
}
//메인 장치에서 정보를 받아와 변수에 저장
static void *recvi(void *arg)
{
int sock = *(int*)arg;
while(true) {
read(sock, msg, sizeof(msg));
printf("%s\n", msg); // 실행확인용
}
return NULL;
}
// 주인측 장치에 RF통신으로 정보 전송
static void *sendmaster(void *arg)
{
FILE* pipe;
char buffer[BUF_SIZE];
// 심박센서 신호 출력 프로그램 실행&파이프 연결
pipe = popen("sudo ./rf24libs/RF24/examples_linux/gettingstarted", "w");
if (pipe == NULL) {
perror("popen");
return NULL;
}
// 받아온 정보 변수에 저장
while (true) {
sleep(1);
fwrite(msg, sizeof(char), 32, pipe);
fflush(pipe);
}
return NULL;
}
\ No newline at end of file
{
"files.associations": {
"stdbool.h": "c",
"math.h": "c"
}
}
\ No newline at end of file
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <pthread.h> // -lpthread
#include <unistd.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <math.h> // -lm
#define LOW 0
#define HIGH 1
#define BUF_SIZE 1024
#define DIST_THRESHOLD 300
static inline double rad(double x) {
return x * 3.14159265 / 180.0;
}
typedef struct {
double x;
double y;
double z;
}tagPT;
const int VIBRATION_MOTOR_PIN = 23;
const int BUTTON_PIN_IN = 20;
const int BUTTON_PIN_OUT = 21;
static void* recv_from_Slave(void *p_sock);
static void* send_to_rp1(void *arg);
static void* gps(void *arg);
static inline double GetDistance(tagPT pt1, tagPT pt2);
void error_handling(char *msg);
static int buzzerMode = true;
static int vibMode = false;
static int heartbeat = 80;
static int event = 0;
static int tookPhoto = false;
static double curDist = DIST_THRESHOLD;
static tagPT myPos = {127.123,68.56,123.56};
static tagPT dogPos = {127.123,68.56,123.56};
/**
* DESCRIPTION
* This code is attached to the Raspberry Pi #2
* this module establish connection with RP #1(Master's sub device) and RP #4 (Pet's main device)
* it is connected with RF module, and GPS module
*
* this device (RP #2) receives data from RP #4, which is
* 1) tookPhoto, 2) heartbeat rate, and 3) latitude 4)longitude of the Pet
* based on these datas, it caculates the Distance Between Master and Pet (GetDistance func)
*
* And it sends 3 datas to the RP #1, which is
* 1) tookPhoto 2) heartbeat rate, and 3) Distance data
*
* Notice that Master's latitude and longitude data comes from the GPS module
*
* In conclusion,
* this device RP #2 literally play a 'Medium' role between Master and a Pet
*/
int main(int argc, char* argv[])
{
pthread_t thread, send_thread, recv_thread;
struct sockaddr_in serv_adr;
int serv_sock, pet_sock, lcd_sock;
char buf[BUF_SIZE];
int str_len;
//소켓 정보 설정
serv_sock=socket(PF_INET, SOCK_STREAM, 0);
if(serv_sock==-1) {
error_handling("socket() error");
}
//ARGUMENT 활용해서 서버 구성
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family=AF_INET;
serv_adr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_adr.sin_port=htons(atoi("8885"));
//소켓에 주소를 할당
if (bind(serv_sock, (struct sockaddr*)&serv_adr, sizeof(serv_adr)) == -1) {
error_handling("bind() error");
}
//함수를 수동 대기 상태로 설정 함.
//serv_sock 소켓을 사용하여 연결 요청을 대기하고,
//최대 5개의 연결 요청을 대기 큐에 저장할 수 있도록 설정
if (listen(serv_sock, 5) == -1) {
error_handling("listen() error");
}
struct sockaddr_in clnt_adr;
socklen_t clnt_adr_sz = sizeof(clnt_adr);
// pet_sock = accept(serv_sock, (struct sockaddr*)&clnt_adr, &clnt_adr_sz);
// if (pet_sock == -1 ) {
// error_handling("accept() error");
// } else {
// printf("pet connected() ! \n");
// }
struct sockaddr_in clnt_adr2;
lcd_sock = accept(serv_sock, (struct sockaddr*)&clnt_adr2, &clnt_adr_sz);
if (lcd_sock == -1) {
error_handling("accept() error");
} else {
printf("lcd connected() ! \n");
}
printf("Multi-threading start\n");
pthread_create(&thread, NULL, gps, NULL);
//pthread_create(&recv_thread, NULL, recv_from_Slave, &pet_sock); //RF 통신에서는 사용안함
pthread_create(&send_thread, NULL, send_to_rp1, &lcd_sock);
pthread_join(thread, NULL);
pthread_join(send_thread, NULL);
return 0;
}
//pet으로부터 데이터 수신하는 THREAD용 함수
static void* recv_from_Slave(void* p_sock)
{
int sock = *(int*)p_sock;
char buffer[1024];
ssize_t n;
while ((n = read(sock, buffer, sizeof(buffer))) > 0) {
int data_cnt = atoi(buffer);
printf("read buffer : %s\n", buffer);
char* p_delims = "_";
char* p_tok = strtok(buffer, p_delims);
tookPhoto = atoi(p_tok);
p_tok = strtok(NULL, p_delims);
heartbeat = atoi(p_tok);
p_tok = strtok(NULL, p_delims);
dogPos.x = atof(p_tok);
p_tok = strtok(NULL, p_delims);
dogPos.y = atof(p_tok);
curDist = GetDistance(myPos, dogPos);
printf("Dist : %lf\n", curDist);
printf("TookPhoto : %d Heart : %d Position : %lf %lf\n", tookPhoto, heartbeat, dogPos.x, dogPos.y);
}
close(sock); //소켓을 닫아주고
write(STDOUT_FILENO, "[*] session closed\n", 19); //세션이 닫혔다고 print해준다.
exit(0);
}
// GPS module Thread 관련 함수
static void* gps(void *arg)
{
FILE *pipe;
char buffer[BUF_SIZE];
char msg[] = "1";
// gps 정보를 읽어 경도와 위도를 출력하는 프로그램 실행&파이프 연결
pipe = popen("python3 -u gps.py", "r");
if (pipe == NULL) {
perror("popen");
return NULL;
}
// 파이프에서 받은 경도와 위도를 변수에 저장
while (fgets(buffer, BUF_SIZE, pipe) != NULL) {
myPos.y = atof(strtok(buffer, " "));
myPos.x = atof(strtok(NULL, " "));
//실행확인용
printf("Master latitude : %f\n", myPos.x);
printf("Master longitude : %f\n", myPos.y);
}
// 파이프 닫음
if ( pclose(pipe) == -1 ) {
perror("pclose");
return NULL;
}
return NULL;
}
// 두 위치정보를 바탕으로 거리를 계산하는 함수
static inline double GetDistance(tagPT pt1, tagPT pt2 )
{
const int radius = 6371;
double dLat = rad( (pt2.y-pt1.y) );
double dLon = rad( (pt2.x-pt1.x) );
pt1.y = rad( pt1.y );
pt2.y = rad( pt2.y );
double a = sin(dLat/2) * sin(dLat/2) + sin(dLon/2) * sin(dLon/2) * cos(pt1.y) * cos(pt2.y);
double c = 2 * atan2f(sqrtf(a), sqrtf(1-a));
double dDistance = radius * c;
// dDistance*=1000;
return dDistance;
}
// RP #1 (주인측 sub 장치)로 데이터를 보내는 Thread 함수
static void* send_to_rp1(void *arg)
{
int sock = *(int*)arg;
char msg[100];
char str[20];
// 1초마다 정보표시 장치에 정보 보냄
while (true) {
// // 촬영여부
// sprintf(str, "%d", tookPhoto);
// strcpy(msg, str);
// msg[strcspn(msg, "\n")] = 0;
// strcat(msg, "_");
// // 심박수
// sprintf(str, "%d", heartbeat);
// strcat(msg, str);
// msg[strcspn(msg, "\n")] = 0;
// strcat(msg, "_");
// // 거리
// sprintf(str, "%f", curDist);
// strcat(msg, str);
// msg[strcspn(msg, "\n")] = 0;
//경도
sprintf(str, "%.3lf", myPos.y);
strcat(msg, str);
msg[strcspn(msg, "\n")] = 0;
strcat(msg, "_");
//위도
sprintf(str, "%.3lf", myPos.x);
strcat(msg, str);
msg[strcspn(msg, "\n")] = 0;
// 전송
write(sock, msg, strlen(msg));
// rintf("Dist : %lf\n", curDist);
printf("latitude : %lf longitude : %lf\n", myPos.x, myPos.y);
sleep(1);
}
return NULL;
}
//에러 핸들링 용 함수
void error_handling(char *message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
\ No newline at end of file
File added
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#define GPS_MSG_SIZE 128
int main() {
int serial_port;
char *port = "/dev/ttyAMA0";
struct termios options;
serial_port = open(port, O_RDWR | O_NOCTTY | O_NDELAY);
if (serial_port == -1) {
printf("Failed to open the serial port.\n");
return -1;
}
tcgetattr(serial_port, &options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_iflag &= ~(IXON | IXOFF | IXANY);
options.c_oflag &= ~OPOST;
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 5;
tcsetattr(serial_port, TCSANOW, &options);
char gps_msg[GPS_MSG_SIZE];
memset(gps_msg, 0, sizeof(gps_msg));
while (1) {
ssize_t newdata = read(serial_port, gps_msg, sizeof(gps_msg));
if (newdata > 0) {
// Process the GPS data
if (strncmp(gps_msg, "$GPRMC", 6) == 0) {
// printf("%s\n",gps_msg);
char *token;
char *latitude;
char *longitude;
token = strtok(gps_msg, ",");
int token_count = 0;
while (token != NULL) {
if (token_count == 2) {
latitude = token;
} else if (token_count == 4) {
longitude = token;
}
token = strtok(NULL, ",");
token_count++;
}
printf("Latitude: %s\n", latitude);
printf("Longitude: %s\n", longitude);
}
}
memset(gps_msg, 0, sizeof(gps_msg));
usleep(500000);
}
close(serial_port);
return 0;
}
\ No newline at end of file
import serial
import time
import string
import pynmea2
while True:
port="/dev/ttyAMA0"
ser=serial.Serial(port, baudrate=9600, timeout=0.5)
dataout = pynmea2.NMEAStreamReader()
newdata=ser.readline()
#print(newdata)
if newdata[0:6] == b"$GPRMC":
newmsg=pynmea2.parse(newdata.decode('ascii'))
lat=newmsg.latitude
lng=newmsg.longitude
gps = str(round(lat, 12)) + " " + str(round(lng, 12))
print(gps)
\ No newline at end of file
File added
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int fd; // seen by all subroutines
void itoa(int n, char* s);
void reverse(char* s);
void ftoa(float f, char* buf);
/* itoa: convert n to characters in s */
void itoa(int n, char* s)
{
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
void ftoa(float f, char* buf)
{
sprintf(buf, "%f", f);
// return buf;
}
/* reverse: reverse string s in place */
void reverse(char* s)
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
\ No newline at end of file
// 아래 헤더들을 추가해준다
#include <SPI.h>
#include <RF24.h>
// 0 번과 1번 아두이노(nRF모듈)를 나누어서 주고받기위한 용도
// 하나는 0으로, 하나는 1로 설정하고 컴파일 해야 한다
bool radioNumber = 0;
// 7 : CE , 8: CSN
RF24 radio(7,8);
// Pipe Address 를 설정하기 위한 값
byte addresses[][6] = {"1Node","2Node"};
// 누가 Ping 하고 Pong 할 것인지 결정 위함
bool role = 0;
void setup() {
Serial.begin(115200);
Serial.println(F("RF24/examples/GettingStarted"));
Serial.println(F("*** PRESS 'T' to begin transmitting to the other node"));
// RF24 모듈 초기화
radio.begin();
// PA 세기를 LOW 로 한다. 입력 전류 불안정을 감안함
radio.setPALevel(RF24_PA_LOW);
// radioNumber 에 따라 Write Pipe - Read Pipe 쌍의 주소를 지정해서 Open 한다
if(radioNumber){
radio.openWritingPipe(addresses[1]);
radio.openReadingPipe(1,addresses[0]);
}else{
radio.openWritingPipe(addresses[0]);
radio.openReadingPipe(1,addresses[1]);
}
// Reading Pipe 주소의 Listening 을 시작한다
radio.startListening();
}
void loop() {
// Ping 보내는 역할
if (role == 1) {
// Write 를 하기 전에 반드시 Listening 을 Stop 해야한다
radio.stopListening();
Serial.println(F("Now sending"));
unsigned long time = micros();
// 데이터를 Write 한다. 이때 채널 내의 해당 주소로 Listen 하는 녀석이 없으면 Fail 떨어진다
if (!radio.write( &time, sizeof(unsigned long) )){
Serial.println(F("failed"));
}
// 보내고 나서 다시 LIsten 한다
radio.startListening();
unsigned long started_waiting_at = micros();
boolean timeout = false;
// 수신 로직이다. Ping Timeout 을 200ms 로 잡고, Timeout 내에서 수신한다
while ( ! radio.available() ){
if (micros() - started_waiting_at > 200000 ){
timeout = true;
break;
}
}
if ( timeout ){
Serial.println(F("Failed, response timed out."));
}else{
unsigned long got_time;
// Pong 이 왔을 때 데이터를 읽어온다
radio.read( &got_time, sizeof(unsigned long) );
unsigned long time = micros();
// Ping 의 Round-Trip 시간을 계산하여 알려준다
Serial.print(F("Sent "));
Serial.print(time);
Serial.print(F(", Got response "));
Serial.print(got_time);
Serial.print(F(", Round-trip delay "));
Serial.print(time-got_time);
Serial.println(F(" microseconds"));
}
delay(1000);
}
// Pong 쳐주는 역할
if ( role == 0 )
{
unsigned long got_time;
// 데이터가 있으면 데이터를 모두 읽어서 FIFO 버퍼 소진한다
if( radio.available()){
while (radio.available()) {
radio.read( &got_time, sizeof(unsigned long) );
}
// Listening 멈추고 Pong 을 Write 한다
radio.stopListening();
radio.write( &got_time, sizeof(unsigned long) );
radio.startListening();
Serial.print(F("Sent response "));
Serial.println(got_time);
}
}
// Serial 을 통해서 T 와 R 에 따라 역할을 바꾼다
if ( Serial.available() )
{
char c = toupper(Serial.read());
if ( c == 'T' && role == 0 ){
Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK"));
role = 1; // Become the primary transmitter (ping out)
}else
if ( c == 'R' && role == 1 ){
Serial.println(F("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK"));
role = 0; // Become the primary receiver (pong back)
radio.startListening();
}
}
}
\ No newline at end of file
File added
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define IN 0
#define OUT 1
#define LOW 0
#define HIGH 1
#define VALUE_MAX 256
#define BUFFER_MAX 3
#define DIRECTION_MAX 45
static int GPIOExport(int pin);
static int GPIOUnexport(int pin);
static int GPIODirection(int pin, int dir);
static int GPIORead(int pin);
static int GPIOWrite(int pin, int value);
static int PWMWriteDutyCycle(int pwmnum, int value);
static int PWMWritePeriod(int pwmnum, int value);
static int PWMEnable(int pwmnum);
static int PWMUnexport(int pwmnum);
static int PWMExport(int pwmnum);
static int PWMUnable(int pwmnum);
static int GPIOExport(int pin)
{
char buffer[BUFFER_MAX];
ssize_t bytes_written;
int fd;
fd = open("/sys/class/gpio/export", O_WRONLY);
if (-1 == fd){
fprintf(stderr, "Failed to open export for writing!\n");
return(-1);
}
bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pin);
write(fd, buffer, bytes_written);
close(fd);
return(0);
}
static int GPIOUnexport(int pin)
{
char buffer[BUFFER_MAX];
ssize_t bytes_written;
int fd;
fd = open("/sys/class/gpio/unexport", O_WRONLY);
if (-1 == fd){
fprintf(stderr, "Failed to open gpio value for writing!\n");
return (-1);
}
bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pin);
write(fd, buffer, bytes_written);
close(fd);
return(0);
}
static int GPIODirection(int pin, int dir)
{
static const char s_directions_str[] = "in\0out";
char path[DIRECTION_MAX] = "/sys/class/gpio/gpio%d/direction";
int fd;
snprintf(path, DIRECTION_MAX, "/sys/class/gpio/gpio%d/direction", pin);
fd = open(path, O_WRONLY);
if (-1 == fd){
fprintf(stderr, "Failed to open gpio direction for writing!\n");
return(-1);
}
if(-1 == write(fd, &s_directions_str[IN == dir ? 0 : 3], IN == dir ? 2 : 3)){
fprintf(stderr, "Failed to set direction!\n");
// close(fd);
return(-1);
}
close(fd);
return(0);
}
static int GPIORead(int pin)
{
char path[VALUE_MAX];
char value_str[3];
int fd;
snprintf(path, VALUE_MAX, "/sys/class/gpio/gpio%d/value", pin);
fd = open(path, O_RDONLY);
if (-1 == fd){
fprintf(stderr, "Failed to open gpio value for raeding!\n");
return (-1);
}
if (-1 == read(fd, value_str, 3)){
fprintf(stderr, "Failed to read value!\n");
// close(fd);
return(-1);
}
close(fd);
return(atoi(value_str));
}
static int GPIOWrite(int pin, int value)
{
static const char s_values_str[] = "01";
char path[VALUE_MAX];
int fd;
snprintf(path, VALUE_MAX, "/sys/class/gpio/gpio%d/value", pin);
fd = open(path, O_WRONLY);
if (-1 == fd){
fprintf(stderr, "Failed to open gpio value for writing!\n");
return (-1);
}
if (1 != write(fd, &s_values_str[LOW == value ? 0 : 1], 1)){
fprintf(stderr, "Failed to write value!\n");
// close(fd);
return(-1);
}
close(fd);
return(0);
}
static int PWMExport(int pwmnum){
#define BUFFER_MAX 3
char buffer[BUFFER_MAX];
int bytes_written;
int fd;
fd = open("/sys/class/pwm/pwmchip0/export", O_WRONLY);
if(-1==fd){
fprintf(stderr, "Failed to open in export!\n");
return(-1);
}
bytes_written=snprintf(buffer, BUFFER_MAX, "%d", pwmnum);
write(fd, buffer, bytes_written);
close(fd);
sleep(1);
return(0);
}
static int PWMUnexport(int pwmnum)
{
char buffer[BUFFER_MAX];
ssize_t bytes_written;
int fd;
fd = open("/sys/class/pwm/pwmchip0/unexport", O_WRONLY);
if(-1==fd){
fprintf(stderr, "Failed to open in unexport!\n");
return(-1);
}
bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pwmnum);
write(fd, buffer, bytes_written);
close(fd);
sleep(1);
return(0);
}
static int PWMEnable(int pwmnum){
static const char s_unenable_str[] = "0";
static const char s_enable_str[] = "1";
char path[DIRECTION_MAX];
int fd;
snprintf(path, DIRECTION_MAX, "/sys/class/pwm/pwmchip0/pwm%d/enable", pwmnum);
fd=open(path,O_WRONLY);
if(-1==fd){
fprintf(stderr, "Failed to open in enable!\n");
return -1;
}
write(fd,s_unenable_str,strlen(s_unenable_str));
close(fd);
fd=open(path,O_WRONLY);
if(-1==fd){
fprintf(stderr, "Failed to open in enable!\n");
return -1;
}
write(fd,s_enable_str,strlen(s_enable_str));
close(fd);
return 0;
}
static int PWMUnable(int pwmnum){
static const char s_unable_str[] = "0";
char path[DIRECTION_MAX];
int fd;
snprintf(path, DIRECTION_MAX, "/sys/class/pwm/pwmchip0/pwm%d/enable", pwmnum);
fd=open(path,O_WRONLY);
if(-1==fd){
fprintf(stderr, "Failed to open in enable!\n");
return -1;
}
write(fd,s_unable_str,strlen(s_unable_str));
close(fd);
return 0;
}
static int PWMWritePeriod(int pwmnum, int value){
char s_values_str[VALUE_MAX];
char path[VALUE_MAX];
int fd,byte;
snprintf(path, VALUE_MAX, "/sys/class/pwm/pwmchip0/pwm%d/period",pwmnum);
fd=open(path,O_WRONLY);
if(-1==fd){
fprintf(stderr, "Failed to open in period!\n");
return(-1);
}
byte=snprintf(s_values_str,10,"%d",value);
if(-1==write(fd,s_values_str,byte)){
fprintf(stderr, "Failed to write value in period!\n");
close(fd);
return(-1);
}
close(fd);
return(0);
}
static int PWMWriteDutyCycle(int pwmnum, int value){
char path[VALUE_MAX];
char s_values_str[VALUE_MAX];
int fd,byte;
snprintf(path, VALUE_MAX, "/sys/class/pwm/pwmchip0/pwm%d/duty_cycle",pwmnum);
fd=open(path,O_WRONLY);
if(-1==fd){
fprintf(stderr,"Failed to oepn in duty_cycle!\n");
return(-1);
}
byte=snprintf(s_values_str, 10,"%d",value);
if(-1==write(fd,s_values_str,byte)){
fprintf(stderr, "Failed to write value! in duty_cycle\n");
close(fd);
return(-1);
}
close(fd);
return(0);
}
\ No newline at end of file
#include <wiringPiI2C.h>
#include <wiringPi.h> // -lwiringPi
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
// Define some device parameters
#define I2C_ADDR 0x27 // I2C device address
// Define some device constants
#define LCD_CHR 1 // Mode - Sending data
#define LCD_CMD 0 // Mode - Sending command
#define LINE1 0x80 // 1st line
#define LINE2 0xC0 // 2nd line
#define LCD_BACKLIGHT 0x08 // On
// LCD_BACKLIGHT = 0x00 # Off
#define ENABLE 0b00000100 // Enable bit
int fd; // seen by all subroutines
void typeFloat(float myFloat);
void typeInt(int i);
void ClrLcd(void);
void lcdLoc(int line);
void typeChar(char val);
void typeln(const char *s);
void lcd_byte(int bits, int mode);
void lcd_toggle_enable(int bits);
void lcd_init();
void itoa(int n, char* s);
void reverse(char* s);
void ftoa(float f, char* buf);
// float to string
void typeFloat(float myFloat) {
char buffer[20];
sprintf(buffer, "%4.2f", myFloat);
typeln(buffer);
}
// int to string
void typeInt(int i) {
char array1[20];
sprintf(array1, "%d", i);
typeln(array1);
}
// clr lcd go home loc 0x80
void ClrLcd(void) {
lcd_byte(0x01, LCD_CMD);
lcd_byte(0x02, LCD_CMD);
}
// go to location on LCD
void lcdLoc(int line) {
lcd_byte(line, LCD_CMD);
}
// out char to LCD at current position
void typeChar(char val) {
lcd_byte(val, LCD_CHR);
}
// this allows use of any size string
void typeln(const char *s) {
while ( *s ) lcd_byte(*(s++), LCD_CHR);
}
void lcd_byte(int bits, int mode) {
//Send byte to data pins
// bits = the data
// mode = 1 for data, 0 for command
int bits_high;
int bits_low;
// uses the two half byte writes to LCD
bits_high = mode | (bits & 0xF0) | LCD_BACKLIGHT ;
bits_low = mode | ((bits << 4) & 0xF0) | LCD_BACKLIGHT ;
// High bits
wiringPiI2CReadReg8(fd, bits_high);
lcd_toggle_enable(bits_high);
// Low bits
wiringPiI2CReadReg8(fd, bits_low);
lcd_toggle_enable(bits_low);
}
void lcd_toggle_enable(int bits) {
// Toggle enable pin on LCD display
delayMicroseconds(500);
wiringPiI2CReadReg8(fd, (bits | ENABLE));
delayMicroseconds(500);
wiringPiI2CReadReg8(fd, (bits & ~ENABLE));
delayMicroseconds(500);
}
void lcd_init() {
// Initialise display
lcd_byte(0x33, LCD_CMD); // Initialise
lcd_byte(0x32, LCD_CMD); // Initialise
lcd_byte(0x06, LCD_CMD); // Cursor move direction
lcd_byte(0x0C, LCD_CMD); // 0x0F On, Blink Off
lcd_byte(0x28, LCD_CMD); // Data length, number of lines, font size
lcd_byte(0x01, LCD_CMD); // Clear display
delayMicroseconds(500);
}
/* itoa: convert n to characters in s */
void itoa(int n, char* s)
{
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
void ftoa(float f, char* buf) {
sprintf(buf, "%f", f);
// return buf;
}
/* reverse: reverse string s in place */
void reverse(char* s)
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
\ No newline at end of file
WiringPi @ f97a6230
Subproject commit f97a6230160b819e6daea7eb242404afa708e421
File added
File added
#include <wiringPiI2C.h>
#include <wiringPi.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
// Define some device parameters
#define I2C_ADDR 0x27 // I2C device address
// Define some device constants
#define LCD_CHR 1 // Mode - Sending data
#define LCD_CMD 0 // Mode - Sending command
#define LINE1 0x80 // 1st line
#define LINE2 0xC0 // 2nd line
#define LCD_BACKLIGHT 0x08 // On
// LCD_BACKLIGHT = 0x00 # Off
#define ENABLE 0b00000100 // Enable bit
void lcd_init(void);
void lcd_byte(int bits, int mode);
void lcd_toggle_enable(int bits);
// added by Lewis
void typeInt(int i);
void typeFloat(float myFloat);
void lcdLoc(int line); //move cursor
void ClrLcd(void); // clr LCD return home
void typeln(const char *s);
void typeChar(char val);
void itoa(int n, char s[]);
void reverse(char s[]);
int fd; // seen by all subroutines
int buzzerMode = true;
int vibMode = false;
int distance = 100;
int heartbeat = 80;
int event=1;
void* lcd(){
if (wiringPiSetup () == -1) exit (1);
fd = wiringPiI2CSetup(I2C_ADDR);
lcd_init(); // setup LCD
while (1) {
// 처음 시작할 때 LCD 한 번 비우고 감
// 부저모드인지, 진동 모드인지
if(buzzerMode == 1){
lcdLoc(LINE1);
typeln("buzzer Mode");
}
else if(vibMode == 1){
lcdLoc(LINE1);
typeln("vibration mode");
}
// 거리가 나와야하고
lcdLoc(LINE2);
char dis[10];
itoa(distance,dis);
strcat(dis,"M ");
// 심박수가 나와야하고
char htb[100];
itoa(heartbeat,htb);
strcat(dis, htb);
strcat(dis,"bpm");
typeln(dis);
delay(2000);
// 이벤트가 발생하면 화면이 바뀌어야 함
// 특이사항 :
if(event == 1){
// 반려동물이 멀어지면 -> 이탈 경보
ClrLcd();
lcdLoc(LINE1);
typeln("dog is gone");
lcdLoc(LINE2);
typeln("please");
delay(2000);
ClrLcd();
event=0;
}
else if(event==2){
// 사진 촬영하면 -> 촬영했어용
ClrLcd();
lcdLoc(LINE1);
typeln("dog feel happy");
lcdLoc(LINE2);
typeln("taking picture");
delay(2000);
ClrLcd();
event=0;
}
else if(event==3){
// 심박수 측정해서 이상값이 있으면 -> 건강 이상해용
ClrLcd();
lcdLoc(LINE1);
typeln("weird heartbeat");
lcdLoc(LINE2);
typeln("check the heart");
delay(2000);
ClrLcd();
}
}
}
int main() {
// char array1[] = "Hello world!";
// char array2[] = "Smart Class!";
return 0;
}
// float to string
void typeFloat(float myFloat) {
char buffer[20];
sprintf(buffer, "%4.2f", myFloat);
typeln(buffer);
}
// int to string
void typeInt(int i) {
char array1[20];
sprintf(array1, "%d", i);
typeln(array1);
}
// clr lcd go home loc 0x80
void ClrLcd(void) {
lcd_byte(0x01, LCD_CMD);
lcd_byte(0x02, LCD_CMD);
}
// go to location on LCD
void lcdLoc(int line) {
lcd_byte(line, LCD_CMD);
}
// out char to LCD at current position
void typeChar(char val) {
lcd_byte(val, LCD_CHR);
}
// this allows use of any size string
void typeln(const char *s) {
while ( *s ) lcd_byte(*(s++), LCD_CHR);
}
void lcd_byte(int bits, int mode) {
//Send byte to data pins
// bits = the data
// mode = 1 for data, 0 for command
int bits_high;
int bits_low;
// uses the two half byte writes to LCD
bits_high = mode | (bits & 0xF0) | LCD_BACKLIGHT ;
bits_low = mode | ((bits << 4) & 0xF0) | LCD_BACKLIGHT ;
// High bits
wiringPiI2CReadReg8(fd, bits_high);
lcd_toggle_enable(bits_high);
// Low bits
wiringPiI2CReadReg8(fd, bits_low);
lcd_toggle_enable(bits_low);
}
void lcd_toggle_enable(int bits) {
// Toggle enable pin on LCD display
delayMicroseconds(500);
wiringPiI2CReadReg8(fd, (bits | ENABLE));
delayMicroseconds(500);
wiringPiI2CReadReg8(fd, (bits & ~ENABLE));
delayMicroseconds(500);
}
void lcd_init() {
// Initialise display
lcd_byte(0x33, LCD_CMD); // Initialise
lcd_byte(0x32, LCD_CMD); // Initialise
lcd_byte(0x06, LCD_CMD); // Cursor move direction
lcd_byte(0x0C, LCD_CMD); // 0x0F On, Blink Off
lcd_byte(0x28, LCD_CMD); // Data length, number of lines, font size
lcd_byte(0x01, LCD_CMD); // Clear display
delayMicroseconds(500);
}
/* itoa: convert n to characters in s */
void itoa(int n, char* s)
{
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
/* reverse: reverse string s in place */
void reverse(char* s)
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
\ No newline at end of file
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#define IN 0
#define OUT 1
#define LOW 0
#define HIGH 1
#define VALUE_MAX 256
#define BUFFER_MAX 3
#define DIRECTION_MAX 45
static int GPIOExport(int pin);
static int GPIOUnexport(int pin);
static int GPIODirection(int pin, int dir);
static int GPIORead(int pin);
static int GPIOWrite(int pin, int value);
static int PWMWriteDutyCycle(int pwmnum, int value);
static int PWMWritePeriod(int pwmnum, int value);
static int PWMEnable(int pwmnum);
static int PWMUnexport(int pwmnum);
static int PWMExport(int pwmnum);
static int PWMUnable(int pwmnum);
static int GPIOExport(int pin)
{
char buffer[BUFFER_MAX];
ssize_t bytes_written;
int fd;
fd = open("/sys/class/gpio/export", O_WRONLY);
if (-1 == fd){
fprintf(stderr, "Failed to open export for writing!\n");
return(-1);
}
bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pin);
write(fd, buffer, bytes_written);
close(fd);
return(0);
}
static int GPIOUnexport(int pin)
{
char buffer[BUFFER_MAX];
ssize_t bytes_written;
int fd;
fd = open("/sys/class/gpio/unexport", O_WRONLY);
if (-1 == fd){
fprintf(stderr, "Failed to open gpio value for writing!\n");
return (-1);
}
bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pin);
write(fd, buffer, bytes_written);
close(fd);
return(0);
}
static int GPIODirection(int pin, int dir)
{
static const char s_directions_str[] = "in\0out";
char path[DIRECTION_MAX] = "/sys/class/gpio/gpio%d/direction";
int fd;
snprintf(path, DIRECTION_MAX, "/sys/class/gpio/gpio%d/direction", pin);
fd = open(path, O_WRONLY);
if (-1 == fd){
fprintf(stderr, "Failed to open gpio direction for writing!\n");
return(-1);
}
if(-1 == write(fd, &s_directions_str[IN == dir ? 0 : 3], IN == dir ? 2 : 3)){
fprintf(stderr, "Failed to set direction!\n");
// close(fd);
return(-1);
}
close(fd);
return(0);
}
static int GPIORead(int pin)
{
char path[VALUE_MAX];
char value_str[3];
int fd;
snprintf(path, VALUE_MAX, "/sys/class/gpio/gpio%d/value", pin);
fd = open(path, O_RDONLY);
if (-1 == fd){
fprintf(stderr, "Failed to open gpio value for raeding!\n");
return (-1);
}
if (-1 == read(fd, value_str, 3)){
fprintf(stderr, "Failed to read value!\n");
// close(fd);
return(-1);
}
close(fd);
return(atoi(value_str));
}
static int GPIOWrite(int pin, int value)
{
static const char s_values_str[] = "01";
char path[VALUE_MAX];
int fd;
snprintf(path, VALUE_MAX, "/sys/class/gpio/gpio%d/value", pin);
fd = open(path, O_WRONLY);
if (-1 == fd){
fprintf(stderr, "Failed to open gpio value for writing!\n");
return (-1);
}
if (1 != write(fd, &s_values_str[LOW == value ? 0 : 1], 1)){
fprintf(stderr, "Failed to write value!\n");
// close(fd);
return(-1);
}
close(fd);
return(0);
}
static int PWMExport(int pwmnum){
#define BUFFER_MAX 3
char buffer[BUFFER_MAX];
int bytes_written;
int fd;
fd = open("/sys/class/pwm/pwmchip0/export", O_WRONLY);
if(-1==fd){
fprintf(stderr, "Failed to open in export!\n");
return(-1);
}
bytes_written=snprintf(buffer, BUFFER_MAX, "%d", pwmnum);
write(fd, buffer, bytes_written);
close(fd);
sleep(1);
return(0);
}
static int PWMUnexport(int pwmnum)
{
char buffer[BUFFER_MAX];
ssize_t bytes_written;
int fd;
fd = open("/sys/class/pwm/pwmchip0/unexport", O_WRONLY);
if(-1==fd){
fprintf(stderr, "Failed to open in unexport!\n");
return(-1);
}
bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pwmnum);
write(fd, buffer, bytes_written);
close(fd);
sleep(1);
return(0);
}
static int PWMEnable(int pwmnum){
static const char s_unenable_str[] = "0";
static const char s_enable_str[] = "1";
char path[DIRECTION_MAX];
int fd;
snprintf(path, DIRECTION_MAX, "/sys/class/pwm/pwmchip0/pwm%d/enable", pwmnum);
fd=open(path,O_WRONLY);
if(-1==fd){
fprintf(stderr, "Failed to open in enable!\n");
return -1;
}
write(fd,s_unenable_str,strlen(s_unenable_str));
close(fd);
fd=open(path,O_WRONLY);
if(-1==fd){
fprintf(stderr, "Failed to open in enable!\n");
return -1;
}
write(fd,s_enable_str,strlen(s_enable_str));
close(fd);
return 0;
}
static int PWMUnable(int pwmnum){
static const char s_unable_str[] = "0";
char path[DIRECTION_MAX];
int fd;
snprintf(path, DIRECTION_MAX, "/sys/class/pwm/pwmchip0/pwm%d/enable", pwmnum);
fd=open(path,O_WRONLY);
if(-1==fd){
fprintf(stderr, "Failed to open in enable!\n");
return -1;
}
write(fd,s_unable_str,strlen(s_unable_str));
close(fd);
return 0;
}
static int PWMWritePeriod(int pwmnum, int value){
char s_values_str[VALUE_MAX];
char path[VALUE_MAX];
int fd,byte;
snprintf(path, VALUE_MAX, "/sys/class/pwm/pwmchip0/pwm%d/period",pwmnum);
fd=open(path,O_WRONLY);
if(-1==fd){
fprintf(stderr, "Failed to open in period!\n");
return(-1);
}
byte=snprintf(s_values_str,10,"%d",value);
if(-1==write(fd,s_values_str,byte)){
fprintf(stderr, "Failed to write value in period!\n");
close(fd);
return(-1);
}
close(fd);
return(0);
}
static int PWMWriteDutyCycle(int pwmnum, int value){
char path[VALUE_MAX];
char s_values_str[VALUE_MAX];
int fd,byte;
snprintf(path, VALUE_MAX, "/sys/class/pwm/pwmchip0/pwm%d/duty_cycle",pwmnum);
fd=open(path,O_WRONLY);
if(-1==fd){
fprintf(stderr,"Failed to oepn in duty_cycle!\n");
return(-1);
}
byte=snprintf(s_values_str, 10,"%d",value);
if(-1==write(fd,s_values_str,byte)){
fprintf(stderr, "Failed to write value! in duty_cycle\n");
close(fd);
return(-1);
}
close(fd);
return(0);
}
\ No newline at end of file
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include "gpio.h"
#include <wiringPiI2C.h>
#include <wiringPi.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define LOW 0
#define HIGH 1
int VIBRATION_MOTOR_PIN = 23;
int BUTTON_PIN_IN = 20;
int BUTTON_PIN_OUT = 21;
// Define some device parameters
#define I2C_ADDR 0x27 // I2C device address
// Define some device constants
#define LCD_CHR 1 // Mode - Sending data
#define LCD_CMD 0 // Mode - Sending command
#define LINE1 0x80 // 1st line
#define LINE2 0xC0 // 2nd line
#define LCD_BACKLIGHT 0x08 // On
// LCD_BACKLIGHT = 0x00 # Off
#define ENABLE 0b00000100 // Enable bit
void lcd_init(void);
void lcd_byte(int bits, int mode);
void lcd_toggle_enable(int bits);
// added by Lewis
void typeInt(int i);
void typeFloat(float myFloat);
void lcdLoc(int line); //move cursor
void ClrLcd(void); // clr LCD return home
void typeln(const char *s);
void typeChar(char val);
void itoa(int n, char s[]);
void reverse(char s[]);
int fd; // seen by all subroutines
int buzzerMode = true;
int vibMode = false;
int distance = 100;
int heartbeat = 80;
int event=1;
void* lcd(){
if (wiringPiSetup () == -1) exit (1);
fd = wiringPiI2CSetup(I2C_ADDR);
lcd_init(); // setup LCD
while (1) {
// 처음 시작할 때 LCD 한 번 비우고 감
// 부저모드인지, 진동 모드인지
if(buzzerMode == 1){
lcdLoc(LINE1);
typeln("buzzer Mode");
}
else if(vibMode == 1){
lcdLoc(LINE1);
typeln("vibration mode");
}
// 거리가 나와야하고
lcdLoc(LINE2);
char dis[10];
itoa(distance,dis);
strcat(dis,"M ");
// 심박수가 나와야하고
char htb[100];
itoa(heartbeat,htb);
strcat(dis, htb);
strcat(dis,"bpm");
typeln(dis);
delay(2000);
// 이벤트가 발생하면 화면이 바뀌어야 함
// 특이사항 :
if(event == 1 ){
// 반려동물이 멀어지면 -> 이탈 경보
ClrLcd();
lcdLoc(LINE1);
typeln("dog is gone");
lcdLoc(LINE2);
typeln("please");
delay(2000);
ClrLcd();
event=0;
}
else if(event==2){
// 사진 촬영하면 -> 촬영했어용
ClrLcd();
lcdLoc(LINE1);
typeln("dog feel happy");
lcdLoc(LINE2);
typeln("taking picture");
delay(5000);
ClrLcd();
event=0;
}
else if(event==3){
// 심박수 측정해서 이상값이 있으면 -> 건강 이상해용
ClrLcd();
lcdLoc(LINE1);
typeln("weird heartbeat");
lcdLoc(LINE2);
typeln("check the heart");
delay(2000);
ClrLcd();
}
}
}
// float to string
void typeFloat(float myFloat) {
char buffer[20];
sprintf(buffer, "%4.2f", myFloat);
typeln(buffer);
}
// int to string
void typeInt(int i) {
char array1[20];
sprintf(array1, "%d", i);
typeln(array1);
}
// clr lcd go home loc 0x80
void ClrLcd(void) {
lcd_byte(0x01, LCD_CMD);
lcd_byte(0x02, LCD_CMD);
}
// go to location on LCD
void lcdLoc(int line) {
lcd_byte(line, LCD_CMD);
}
// out char to LCD at current position
void typeChar(char val) {
lcd_byte(val, LCD_CHR);
}
// this allows use of any size string
void typeln(const char *s) {
while ( *s ) lcd_byte(*(s++), LCD_CHR);
}
void lcd_byte(int bits, int mode) {
//Send byte to data pins
// bits = the data
// mode = 1 for data, 0 for command
int bits_high;
int bits_low;
// uses the two half byte writes to LCD
bits_high = mode | (bits & 0xF0) | LCD_BACKLIGHT ;
bits_low = mode | ((bits << 4) & 0xF0) | LCD_BACKLIGHT ;
// High bits
wiringPiI2CReadReg8(fd, bits_high);
lcd_toggle_enable(bits_high);
// Low bits
wiringPiI2CReadReg8(fd, bits_low);
lcd_toggle_enable(bits_low);
}
void lcd_toggle_enable(int bits) {
// Toggle enable pin on LCD display
delayMicroseconds(500);
wiringPiI2CReadReg8(fd, (bits | ENABLE));
delayMicroseconds(500);
wiringPiI2CReadReg8(fd, (bits & ~ENABLE));
delayMicroseconds(500);
}
void lcd_init() {
// Initialise display
lcd_byte(0x33, LCD_CMD); // Initialise
lcd_byte(0x32, LCD_CMD); // Initialise
lcd_byte(0x06, LCD_CMD); // Cursor move direction
lcd_byte(0x0C, LCD_CMD); // 0x0F On, Blink Off
lcd_byte(0x28, LCD_CMD); // Data length, number of lines, font size
lcd_byte(0x01, LCD_CMD); // Clear display
delayMicroseconds(500);
}
/* itoa: convert n to characters in s */
void itoa(int n, char* s)
{
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
/* reverse: reverse string s in place */
void reverse(char* s)
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
// INPLEMENTATION
// activate_seconds: 한번 진동이 작동할 때 동작하는 시간 (초 단위)
// interval_seconds: 매 진동 사이의 간격 (초 단위)
// times: 진동을 몇번 수행할지를 결정
void* active_vibration_motor(void* activate_seconds){
GPIOExport(VIBRATION_MOTOR_PIN);
GPIODirection(VIBRATION_MOTOR_PIN, OUT);
GPIOWrite(VIBRATION_MOTOR_PIN, HIGH);
int a = *(int*)activate_seconds;
usleep(a * 1000 * 1000);
GPIOWrite(VIBRATION_MOTOR_PIN, LOW);
GPIOUnexport(VIBRATION_MOTOR_PIN);
return NULL;
}
void* read_button(){
GPIOExport(BUTTON_PIN_IN);
GPIOExport(BUTTON_PIN_OUT);
GPIODirection(BUTTON_PIN_IN, IN);
GPIODirection(BUTTON_PIN_OUT, OUT);
while(1){
GPIOWrite(BUTTON_PIN_OUT,1);
int data = GPIORead(BUTTON_PIN_IN);
printf("BUTTON GPIO Read : %d from pin %d\n", data, BUTTON_PIN_IN);
usleep(1000 * 1000);
}
GPIOUnexport(BUTTON_PIN_IN);
GPIOUnexport(BUTTON_PIN_OUT);
return NULL;
}
void* activate_buzzer(void* activate_seconds){
const int PNUM = 0;
PWMExport(PNUM); //pwm0 == gpio18
PWMWritePeriod(PNUM,20000000);
PWMWriteDutyCycle(PNUM,0);
PWMEnable(PNUM);
int a = *(int*)activate_seconds;
//a *= (1000*1000);
while(a--){
for(int i=0;i<1000;i++){
PWMWriteDutyCycle(PNUM,i*10000);
usleep(1000);
}
for(int i=1000;i>0;i--){
PWMWriteDutyCycle(PNUM,i*10000);
usleep(1000);
}
}
PWMUnable(PNUM);
return NULL;
}
int main(){
pthread_t thread_1, thread_2, thread_3, thread_4;
int a = 1;
pthread_create(&thread_1, NULL, active_vibration_motor, &a);
// pthread_create(&thread_2, NULL, read_button, NULL);
pthread_create(&thread_3, NULL, activate_buzzer, &a);
pthread_create(&thread_4, NULL, lcd, &a);
pthread_join(thread_1, NULL);
// pthread_join(thread_2, NULL);
pthread_join(thread_3, NULL);
pthread_join(thread_4, NULL);
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment