Fixed baud rate switching:

- added missing call of tcsetattr
- handle return values
- adjust timeout correctly
This commit is contained in:
Stefan Wahren
2012-05-15 23:17:49 +02:00
parent f7c644bee6
commit 980bbb1862

View File

@ -75,7 +75,7 @@ mbus_serial_connect(char *device)
// For 2400Bd this means (330 + 11) / 2400 + 0.05 = 188.75 ms (added 11 bit periods to receive first byte). // For 2400Bd this means (330 + 11) / 2400 + 0.05 = 188.75 ms (added 11 bit periods to receive first byte).
// I.e. timeout of 0.2s seems appropriate for 2400Bd. // I.e. timeout of 0.2s seems appropriate for 2400Bd.
handle->t.c_cc[VTIME] = 2; handle->t.c_cc[VTIME] = 2; // Timeout in 1/10 sec
cfsetispeed(&(handle->t), B2400); cfsetispeed(&(handle->t), B2400);
cfsetospeed(&(handle->t), B2400); cfsetospeed(&(handle->t), B2400);
@ -93,39 +93,61 @@ mbus_serial_connect(char *device)
} }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// // Set baud rate for serial connection
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
int int
mbus_serial_set_baudrate(mbus_serial_handle *handle, int baudrate) mbus_serial_set_baudrate(mbus_serial_handle *handle, int baudrate)
{ {
speed_t speed;
if (handle == NULL) if (handle == NULL)
return -1; return -1;
switch (baudrate) switch (baudrate)
{ {
case 300: case 300:
cfsetispeed(&(handle->t), B300); speed = B300;
cfsetospeed(&(handle->t), B300); handle->t.c_cc[VTIME] = 12; // Timeout in 1/10 sec
return 0; break;
case 1200: case 1200:
cfsetispeed(&(handle->t), B1200); speed = B1200;
cfsetospeed(&(handle->t), B1200); handle->t.c_cc[VTIME] = 4; // Timeout in 1/10 sec
return 0; break;
case 2400: case 2400:
cfsetispeed(&(handle->t), B2400); speed = B2400;
cfsetospeed(&(handle->t), B2400); handle->t.c_cc[VTIME] = 2; // Timeout in 1/10 sec
return 0; break;
case 9600: case 9600:
cfsetispeed(&(handle->t), B9600); speed = B9600;
cfsetospeed(&(handle->t), B9600); handle->t.c_cc[VTIME] = 1; // Timeout in 1/10 sec
return 0; break;
default: default:
return -1; // unsupported baudrate return -1; // unsupported baudrate
} }
// Set input baud rate
if (cfsetispeed(&(handle->t), speed) != 0)
{
return -1;
}
// Set output baud rate
if (cfsetospeed(&(handle->t), speed) != 0)
{
return -1;
}
// Change baud rate immediately
if (tcsetattr(handle->fd, TCSANOW, &(handle->t)) != 0)
{
return -1;
}
return 0;
} }