Title |
Toggle the DTR and RTS lines on a serial port from a C program |
Ref. No. |
QNX.000009291 |
Category(ies) |
Character I/O |
Issue |
Using a C function, we'd like to toggle the DTR and RTS lines on our serial port. Problem is, we can't seem to find a way to do this. Can we actually toggle these from within a program?
|
Solution |
The function qnx_ioctl() will accomplish this. To see which serial lines can be toggled by this function, look at /usr/include/sys/qioctl.h. Some serial lines are read-only, which means that only the retrieve status information may be read. RTS and DTR, however, are both read/write, so they are free to be toggled.
Here's an example of how to raise and lower these lines:
#include <sys/types.h> #include <sys/qioctl.h> #include <sys/stat.h> #include <errno.h> #include <fcntl.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h>
#define SERDEV1 "/dev/serl"
main(){
x09int file_des; x09long oldbits,newbits[2]={0,0};
x09if ((file_des = open (SERDEV1,0_RDWR))==-1){ x09x09printf("Unable to open %s:%s:,SERDEV1,sterror(errno));exit(1);
x09}
// The send buffer (newbits) consists of 8 bytes organized as two // longs (bits,mask). The return buffer (oldbits) consist of 4 bytes. // // The ioctl returns the state of the device control bits as they // were found BEFORE the call was made (oldbits). The device control bits //are then modified using the rule: // newbits = (oldbits & ~mask) | (bits & mask)
printf("Raising DTR and RTSn");
// From the qioctl.h header file we find that DTR is bit 0 and // RTS is bit 1. WE want to raise RTS and DTR therefore the mask // is 0x0003 and the bits will be 0x0003
x09newbits[0]=0x0003; x09newbits[1]=0x0003; x09if (qnx_ioctl(file_des, QCTL_DEV_CTL,&newbits, 8, &oldbits, 4)=-1) x09x09printf("qnx_ioctl failed:%xn",strerror(errno));
// set mask to zero, we simply want to read the status of DTR and RTS
x09newbits[1]=0x0000; x09if (qnx_ioctl(file_des,QCTL_DEV_CTL, &newbits, 8, &oldbits, 4)=-1) x09x09printf("qnx_ioctl failed:%xn",strerror(errno));
x09printf("Serial State:"); x09printf("%cDTR", (oldbits & 0x0001L)?'+':'-'); x09printf("%cRTS", (oldbits & 0x0002L)?'+':'-'); x09printf("n");
printf("lowering DTR and RTSn");
// here we wish to lower DTR and RTS. We set up the // mask to 0x0003 and set the bits to 0x0000
x09newbits[0]=0x0000; x09newbits[1]=0x0003; x09if (qnx_ioctl(file_des,QCTL_DEV_CTL,&newbits,8,&oldbits,4)=-1 x09x09printf(qnx_ioctl failed: "%sn", strerror(errno));
// again set mask to zero, we simply want to read the status of DTR and RTS
x09newbits[1]=0x0000; x09if (qnx_ioctl(file_des,QCTL_DEV_CTL, &newbits, 8, &oldbits, 4)=-1) x09x09printf("Serial State:"); x09printf("%cDTR", (oldbits & 0x0001L)? '+': '-'); x09printf("%cRTS", (oldbits & 0x0002L)? '+': '-'); x09printf("n"); x09close(file_des); }
|
|