2 * PCAN-LIN, RS-232 to CAN/LIN converter control application
13 #define UART_SPEED B2400
15 #define LIN_HDR_SIZE 2
16 #define LIN_PKT_MAX_SIZE 16 /* FIXME */
17 struct termios term_attr;
18 /* ------------------------------------------------------------------------ */
19 static void reset_input_mode(int tty)
21 tcsetattr(tty, TCSANOW, &term_attr);
24 static void set_input_mode(int tty, speed_t speed)
29 /* Flush input and output queues. */
30 if (tcflush(tty, TCIOFLUSH) != 0) {
35 /* Fetch the current terminal parameters. */
37 fprintf(stderr, "Not a terminal.\n");
41 /* Save settings for later restoring */
42 tcgetattr(tty, &term_attr);
45 tcgetattr(tty, &tattr);
46 tattr.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP
47 | INLCR | IGNCR | ICRNL | IXON);
48 tattr.c_oflag &= ~OPOST;
49 tattr.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
50 tattr.c_cflag &= ~(CSIZE | PARENB);
54 tattr.c_cc[VTIME] = 0;
56 /* Set TX, RX speed */
57 cfsetispeed(&tattr, speed);
58 cfsetospeed(&tattr, speed);
60 status = tcsetattr(tty, TCSANOW, &tattr);
62 perror("tcsetattr()");
67 int send_header(int tty)
71 buff[0] = 0x00; /* Sync byte */
72 buff[1] = 0x55; /* Sync byte */
73 buff[2] = 0xC1; /* LIN ID: 1 */
76 /* Decrease speed to send BREAK (simulated with 0x00 data frame)*/
77 tcgetattr(tty, &tattr);
78 cfsetospeed(&tattr, B1200);
79 tcsetattr(tty, TCSADRAIN, &tattr);
81 write(tty, &buff[0], 1);
83 cfsetospeed(&tattr, UART_SPEED);
84 tcsetattr(tty, TCSADRAIN, &tattr);
86 //tcsendbreak(tty, 1); /* Break */
87 //usleep((useconds_t) 50); /* Break Delimiter */
88 write(tty, &buff[1], 1); /* Sync Byte Field */
89 write(tty, &buff[2], 1); /* PID -- Protected Identifier Field */
93 int read_header(int tty)
95 int p0, p1; /* Parity bits */
96 int par_rec; /* Parity received as a part of a packet */
97 int par_calc; /* Calculated parity */
99 uint8_t buff[LIN_HDR_SIZE];
100 memset(buff, '\0', sizeof(buff));
103 received = read(tty, &buff[0], 1);
107 if (buff[0] != 0x55) /* Sync byte field */
110 received = read(tty, &buff[1], 1);
117 p0 = (buff[1] ^ (buff[1] >> 1) ^ (buff[1] >> 2) ^ (buff[1] >> 4)) & 0x1;
118 p1 = ~(((buff[1] >> 1) ^ (buff[1] >> 3) ^ (buff[1] >> 4) ^ (buff[1] >> 5))) & 0x1;
120 printf("%02X ", buff[0]);
121 printf("%02X ", buff[1]);
123 par_rec = (buff[1] & 0xc0) >> 6;
124 par_calc = p0 | (p1 << 1);
125 printf("| LIN id: %02X ", buff[1] & 0x3f);
126 //printf("| par_rec: %X; par_calc: %X ", par_rec, par_calc);
127 if (par_rec == par_calc)
128 printf("| parity OK");
136 int main(int argc, char* argv[])
142 fprintf(stderr, "Device is missing\n");
143 fprintf(stderr, "Usage: %s DEVICE\n", argv[0]);
147 strncpy((char*)&dev, argv[1], 32);
148 tty = open(dev, O_RDWR);
155 set_input_mode(tty, UART_SPEED);
162 reset_input_mode(tty);