serialport write and read on windows not working
I first tried to use javax.comm to connect to the serial port (COM4). It did not even open the serial port.
Then I tried to use rxtx libraries (rxtx-2.2pre2) to connect. It connects and writes the data but does not read any data from the serial port.
Is there any JDK/platform dependency to use javax.comm or rxtx libraries?
I am using:
- Windows XP SP3,
- JDK 1.6.0_22,
- rxtx-2.2pre2,
- USB to Serial adapter,
- Portmon (by Microsoft) - to monitor activ开发者_开发问答ity on serial ports
- Hyperterminal - to check if the COM port really works.
- http://rxtx.qbang.org/wiki/index.php/Two_way_communcation_with_the_serial_port - sample code used to check read and write
After some digging, I was able to solve this myself, by explicitly setting the flow control mode. Even if you don't require flow control, setting it explicitly to FLOWCONTROL_NONE
helps.
The same call was not required on Linux.
If you are setting the flow control to Hardware, I think it is also required to setRTS explicitly in order to get notifications in this mode. (Not verified).
I tried this code and was successful. You need to have three files with you:
comm.jar
javax.comm.properties
win32com.dll
and you need to put these files in specific directories:
comm.jar
in /java/jre6/lib/ext , /java/jdk_1.6.0.20/jre6/lib/ext , java/jdk_1.6.0.20/lib
win32com.dll
in /java/jre6/bin, /java/jdk_1.6.0.20/bin, /windwos/System32
javax.comm.properties
in /java/jdk_1.6.0.20/lib, java/jre/lib , /java/jdk_1.6.0.20/jre/lib
I would recommend trying out purejavacomm: http://www.sparetimelabs.com/purejavacomm/index.html
It is an implementation of javax.comm written in pure java + JNA, which completely solved the problem of portability between Windows and Linux for me. It should also work on OSX or FreeBSD (haven't tried), and should be easy to port to other OS-es that JNA supports, such as Solaris.
Another benefit is that you don't need to install a DLL like you do with rxtx, and that it doesn't seem to have a certain 100% CPU eating bug that rxtx sometimes has on windows.
精彩评论