// adrport.c - Serial Port Handler // Copyright MMI, MMII by Sisusypro Incorporated // Permission is hereby granted to freely copy, // modify, utilize and distribute this example in // whatever manner you desire without restriction. #include #include #include #include #include #include #include #include static int fd = 0; // closes the serial port void CloseAdrPort() { if (fd > 0) { close(fd); } } // end CloseAdrPort // opens the serial port // return code: // > 0 = fd for the port // -1 = open failed int OpenAdrPort() { // make sure port is closed CloseAdrPort(); /* O_RDWR = read/write, O_NOCTTY = If pathname refers to a terminal device -- see tty(4) -- it will not become the process's controlling terminal even if the process does not have one O_NDELAY = The file is opened in non-blocking mode. Neither the open nor any subsequent operations on the file descriptor which is returned will cause the calling process to wait. */ fd = open("/dev/ttyS0", O_RDWR); if (fd < 0) { printf("Error opening /dev/ttyS0: %d %s\n", errno, strerror(errno)); } else { struct termios my_termios; /* gets the parameters associated with the object referred by fd and stores them in the termios structure */ tcgetattr(fd, &my_termios); /* flushes data received but not read */ tcflush(fd, TCIFLUSH); /* 2400bps, 8 bit data, enable receive, ignore modem control lines lower modem control after last process leaves the device */ my_termios.c_cflag = CREAD | CLOCAL | CS8; // | PARENB | PARODD; /* sets transmission speed to 2400bps */ cfsetospeed(&my_termios, B2400); cfsetospeed(&my_termios, B2400); /* sets the parameters associated with the terminal. TCSANOW = the change occurs immediately. */ tcsetattr(fd, TCSANOW, &my_termios); } return fd; } // end OpenAdrPort // writes zero terminated string to the serial port // return code: // >= 0 = number of characters written // -1 = write failed int WriteAdrPort(unsigned char* output,int length) { int k; for (k = 0; k < length; k++) { printf("Valor: %d\n", ((int)output[k])); } int iOut; if (fd < 1) { printf("Write error: port is not open.\n"); return -1; } /* the number of bytes written are returned */ iOut = write(fd, output, length); if (iOut < 0) { printf("Write error: %d %s\n", errno, strerror(errno)); } else { printf("Wrote %d chars.\n", iOut); } return iOut; } // end WriteAdrPort // read string from the serial port // return code: // >= 0 = number of characters read // -1 = read failed int ReadAdrPort(unsigned char* psResponse, int& length, int iMax) { int iIn; if (fd < 1) { printf("Read error: port is not open.\n"); return -1; } //sleep(1); iIn = read(fd, psResponse, iMax-1); if (iIn < 0) { if (errno == EAGAIN) { return 0; // assume that command generated no response } else { printf("Read error: %d %s\n", errno, strerror(errno)); } } else { printf("Read %d bytes.\n", iIn); } length = iIn; return iIn; } // end ReadAdrPort