Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <sys/time.h>
- #include <netinet/in.h>
- #include <netdb.h>
- #include <stdio.h>
- #include <string.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <termios.h>
- #define BAUD_RATE B9600
- int main (void)
- {
- fd_set read_flags,write_flags; // you know what these are
- struct timeval waitd;
- int thefd; // The socket
- char outbuff[512]; // Buffer to hold outgoing data
- char inbuff[512]; // Buffer to read incoming data into
- int err; // holds return values
- struct termios options;
- memset(&outbuff,0,sizeof(outbuff)); // memset used for portability
- //opening port
- thefd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY | O_ASYNC);
- if (thefd == -1) {
- // could not open port
- fprintf(stderr,"open_port: Unable to open %s\n", "/dev/ttyS0");
- } else {
- fcntl(thefd, F_SETFL, O_NDELAY);
- tcgetattr(thefd, &options);
- // BAUD rate
- cfsetispeed(&options, BAUD_RATE);
- cfsetospeed(&options, BAUD_RATE);
- // enable the receiver and set local mode...
- options.c_cflag |= (CLOCAL | CREAD);
- // no parity (8 in 1)
- options.c_cflag &= ~PARENB;
- options.c_cflag &= ~CSTOPB;
- options.c_cflag &= ~CSIZE;
- options.c_cflag |= CS8;
- // no flow controll
- //options.c_cflag &= ~CRTSCTS; /* Also called CRTSCTS */
- // apply all changes immediately
- tcsetattr(thefd, TCSANOW, &options);
- }
- strcat(outbuff,"jarjam\n"); //Add the string jarjam to the output
- //buffer
- while(1) {
- waitd.tv_sec = 1; // Make select wait up to 1 second for data
- waitd.tv_usec = 0; // and 0 milliseconds.
- FD_ZERO(&read_flags); // Zero the flags ready for using
- FD_ZERO(&write_flags);
- FD_SET(thefd, &read_flags);
- if(strlen(outbuff)!=0) FD_SET(thefd, &write_flags);
- err=select(thefd+1, &read_flags,&write_flags,
- (fd_set*)0,&waitd);
- if(err < 0) continue;
- if(FD_ISSET(thefd, &read_flags)) { //Socket ready for reading
- FD_CLR(thefd, &read_flags);
- memset(&inbuff,0,sizeof(inbuff));
- if (read(thefd, inbuff, sizeof(inbuff)-1) <= 0) {
- close(thefd);
- break;
- }
- else printf("%s",inbuff);
- }
- if(FD_ISSET(thefd, &write_flags)) { //Socket ready for writing
- FD_CLR(thefd, &write_flags);
- write(thefd,outbuff,strlen(outbuff));
- memset(&outbuff,0,sizeof(outbuff));
- }
- // now the loop repeats over again
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement