Sie sind auf Seite 1von 7

27/06/2015

Howtoopenserialport(usingrxtx)|EmbeddedFreaks..

EmbeddedFreaks..

August8,2008

Howtoopenserialport(usingrxtx)
Filedunder:javaTags:java,javaserialport,rxtxkunilkuda@7:36am
Ok.SoheresabriefexplanationofhowtoopenserialportinJavausingrxtx.
Firstofall,youneedtogettheserialportsID
1
2

CommPortIdentifierportId=
CommPortIdentifier.getPortIdentifier("/dev/ttyUSB0");

Then,youllneedtoasktheOStogivetheserialportownershiptoyou.
1
2

SerialPortserialPort=
(SerialPort)portId.open("Demoapplication",5000);

TheDemoapplicationstringistheapplicationsname.TherxtxwillpassthisvaluetoOSas
theapplicationnamewhoasktheserialportownership(IthinktheressomeUnixcommandto
viewwhichapplicationholdwhichsystemresource..Ineedtodigmoreonthisuselsof
/dev/<yourserialdevice>toseewhichapplicationthatholdsit.ButIshouldremindyou
thatDemoapplicationstringwontcomeupusinglsoforpsax).
The5000valueisthetimeoutvaluethatisgiventothesystemtoreleasetheport(5000ms=5
seconds).Ifthecurrentowneroftheserialportdoesntreleasetheserialportwithin5seconds,
rxtxwillthrowanIOException.
Ifyourelucky(thecurrentserialportownerwillingtogivetheserialporttoyou,ornobody
ownsitcurrently),youcansettheserialportparameters.
1
2
3
4
5
6
7
8

intbaudRate=57600;//57600bps
try{
//Setserialportto57600bps8N1..myfavourite
serialPort.setSerialPortParams(
baudRate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);

https://embeddedfreak.wordpress.com/2008/08/08/howtoopenserialportusingrxtx/

1/7

27/06/2015

9
10
11

Howtoopenserialport(usingrxtx)|EmbeddedFreaks..

}catch(UnsupportedCommOperationExceptionex){
System.err.println(ex.getMessage());
}

Dontforgettosetitsflowcontrol
1
2
3
4
5
6
7
8
9
10
11

try{
serialPort.setFlowControlMode(
SerialPort.FLOWCONTROL_NONE);
//OR
//IfCTS/RTSisneeded
//serialPort.setFlowControlMode(
//SerialPort.FLOWCONTROL_RTSCTS_IN|
//SerialPort.FLOWCONTROL_RTSCTS_OUT);
}catch(UnsupportedCommOperationExceptionex){
System.err.println(ex.getMessage());
}

Lastly,beforeyoucanreadorwritetoserialport.Youllneeditsinputstreamand
outputstream.
1
2

OutputStreamoutStream=serialPort.getOutputStream();
InputStreaminStream=serialPort.getInputStream();

So,heresthecompleteexampleofthemethodtoopentheserialport
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

publicclassSerialPortHandler{
privateSerialPortserialPort;
privateOutputStreamoutStream;
privateInputStreaminStream;

publicvoidconnect(StringportName)throwsIOException{
try{
//ObtainaCommPortIdentifierobjectfortheportyouwantto
CommPortIdentifierportId=
CommPortIdentifier.getPortIdentifier(portName);

//Gettheport'sownership
serialPort=
(SerialPort)portId.open("Demoapplication",5000);

//Settheparametersoftheconnection.
setSerialPortParameters();

//Opentheinputandoutputstreamsfortheconnection.Ifth
//open,closetheportbeforethrowinganexception.
outStream=serialPort.getOutputStream();
inStream=serialPort.getInputStream();
}catch(NoSuchPortExceptione){
thrownewIOException(e.getMessage());
}catch(PortInUseExceptione){
thrownewIOException(e.getMessage());
}catch(IOExceptione){
serialPort.close();
throwe;
}
}

https://embeddedfreak.wordpress.com/2008/08/08/howtoopenserialportusingrxtx/

2/7

27/06/2015

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

Howtoopenserialport(usingrxtx)|EmbeddedFreaks..

/**
*Gettheserialportinputstream
*@returnTheserialportinputstream
*/
publicInputStreamgetSerialInputStream(){
returninStream;
}

/**
*Gettheserialportoutputstream
*@returnTheserialportoutputstream
*/
publicOutputStreamgetSerialOutputStream(){
returnoutStream;
}

/**
*Setstheserialportparameters
*/
privatevoidsetSerialPortParameters()throwsIOException{
intbaudRate=57600;//57600bps

try{
//Setserialportto57600bps8N1..myfavourite
serialPort.setSerialPortParams(
baudRate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);

serialPort.setFlowControlMode(
SerialPort.FLOWCONTROL_NONE);
}catch(UnsupportedCommOperationExceptionex){
thrownewIOException("Unsupportedserialportparameter");
}
}
}
About these ads

Comments(14)
https://embeddedfreak.wordpress.com/2008/08/08/howtoopenserialportusingrxtx/

3/7

27/06/2015

Howtoopenserialport(usingrxtx)|EmbeddedFreaks..

14Comments
1. Ithelpedmesucceddinopeningupmyserialcomproject
Thankyou
CommentbyNarenderSeptember20,2008@12:52pm
2. Yourewelcome.
Itsahonourtometootoknowmypostworthsomething=)
CommentbykunilkudaSeptember20,2008@1:22pm
3. Thanksfortutorial.Isthereaway(oranyinformation)onhowtosetflowcontrolas
XON/XOFF?
fromhyperterm,itisonlyworkedinxonxoffmode,butwhenIsetflowControlas
XON|XOFFitdidnotseemtobeworked.
thanks.
CommentbyonculkDecember15,2008@7:41pm
4. Replace
1
2
3

serialPort.setFlowControlMode(
SerialPort.FLOWCONTROL_RTSCTS_IN|
SerialPort.FLOWCONTROL_RTSCTS_OUT);

with:
1
2
3

serialPort.setFlowControlMode(
SerialPort.FLOWCONTROL_XONXOFF_IN|
SerialPort.FLOWCONTROL_XONXOFF_OUT);

TheXON/XOFFcode(decoding/encoding)shouldbeembeddedinsidethemessagethats
transmitted.BothrxtxandJavaCommdontprovidemethodstoparseit(ie.doityourself
inyourprogram).RefertoSoftwareflowcontrol.
HypertermworksforbothCTS/RTSandXON/XOFF,butnotDTR/DSR.CTS/RTSand
DTR/DSRarehardwarebasedflowcontrol.Sobotharemutuallyexclusive(chooseoneof
it).XON/XOFFissoftwarebasedflowcontrol.Itcanbeenabledwhilehardwarebasedflow
controlisenabled(butitllberedundanttohavebothhardwareandsoftwareflowcontrol
atthesametime).
CommentbykunilkudaDecember16,2008@1:07pm
5. Hi
Problem:
Ihadah/wdeviceconnectedtoCOMM4portthisdevisewillsendsomedataafterahour
https://embeddedfreak.wordpress.com/2008/08/08/howtoopenserialportusingrxtx/

4/7

27/06/2015

Howtoopenserialport(usingrxtx)|EmbeddedFreaks..

butwhenirestartorstartthecomputertheportwillchangetoCOMM1sothatCOMM4
wontdetectedwhatistheproblemtocomputerorasimplejavaprogramisheretodetect
theportsavailableinthesystemhowcanienabletheCOMM4andaccessthedataifthe
computerrestartedbyjavaprogramorifCOMM1isonlydetectedthenchangeitto
COMM4byjava
ihasacodetodetecttheports
packagecom;
importjava.io.IOException;
importjava.util.Enumeration;
importgnu.io.*;
publicclassGetPorts{
staticCommPortIdentifierportId;
staticEnumerationportList;
publicstaticvoidmain(String[]args){
portList=CommPortIdentifier.getPortIdentifiers();
while(portList.hasMoreElements()){
portId=(CommPortIdentifier)portList.nextElement();
//if(portId.getPortType()==CommPortIdentifier.PORT_PARALLEL){
//if(portId.getName().equals(COM1)){
System.out.println(portId.getName()++portId.getPortType()+portId.);
//}
//}
}
}
}
itshowsalltheenabledportinmysystembutcanichangetheportfromcomm1tocomm4
isthiscanbedoneplshelpmethanksinadvance
CommentbySalishAugust3,2009@4:13pm
6. Idontunderstandthequestion,butitseemslikeprobleminOSconfigurationratherthan
Java(WindowsIguess..becauseLinuxneverchangesthehardwarenumbering,even
thoughitsUSB).
No..IdontthinkyoucanchangeUSB1toUSB4withinJava.ItsbeyondJavasreach,unless
youusesomekindofJNItointerfacewithWindowsControlPanel.Heresthelinktofix
theserialportmappingonyourwindowsmachine:
https://www.patientecare.com/ser_port_doc/WinPorts.html(Checktheremappingaserial
portsection).
Tryitonyourownrisk
CommentbykunilkudaAugust5,2009@10:32pm
7. imrunningwindows.
https://embeddedfreak.wordpress.com/2008/08/08/howtoopenserialportusingrxtx/

5/7

27/06/2015

Howtoopenserialport(usingrxtx)|EmbeddedFreaks..

whenidothis:
inStream=serialPort.getInputStream();
igetnullpointerexception..anytips?
CommentbyAdixMarch13,2010@5:08am
8. Pleasesir,
RegardingtohardwareflowcontrolFLOWCONTROL_RTSCTS_OUT,Iunderstoodthatit
uses2pinsintheserialporttosendcontroldata,amIright?
ShouldIbesurethatthedevicethatisconnectedtotheserialportsupportsRTS/CRS?And
HOWdoIknowthat?
Thankyou
CommentbysmrMarch15,2010@11:44pm
9. Pleasesir,
Regardingtoflowcontrol,howcanIknowthatthedevicethatisconnectedtotheserial
portsupportsRTS/CTS?RTSCTSare2pinsinusedforflowcontroldata,amIright?
Thankyou
CommentbysmrMarch16,2010@12:17am
10. WhenItrytoconnectIgetanerrorsaying
SEVERE:null
java.io.IOException:UnknownApplication
whatcausesthis?
IfithelpsIusenetbeansonamacosxfordevelopment.
Thanksinadvancebecauseyoursiteisawesome.
CommentbyGeorgeEricksonJuly22,2010@12:22am
11. []https://embeddedfreak.wordpress.com/2008/08/08/howtoopenserialportusingrxtx/
[]
PingbackbySerialCommunicationinJavawithExampleProgramHenryPoonsBlog
January2,2011@9:46am
12. Iamarun.Ihaveaproblemwithoneofmyproject.Ihavealoadcellfromloadstarwhichis
interfacedthroughUSB.
WhenIconnectittotheubuntusystem,in/devttyUSB0comes.ButwhenIexecutedthe
code
CommPortIdentifierportId=CommPortIdentifier.getPortIdentifier(/dev/ttyUSB0);
itisshowingtheNoSuchPortException.Kindlyhelpmetofigureouttheproblem.Igave
fullpermissionsto/dev/ttyUSB0file.Butexceptionremainsthere.
CommentbyarunkumarvMarch2,2011@2:37pm
https://embeddedfreak.wordpress.com/2008/08/08/howtoopenserialportusingrxtx/

6/7

27/06/2015

Howtoopenserialport(usingrxtx)|EmbeddedFreaks..

13. HelloKunil,
IhaveaserialxyplotterforwhichIwroteasmalljavaprogramtohandleit.Isenditafile
(ascii)wichtherightcommandstodrawafigure.Italmostworks,butafterawhileon
plottingthefile,itdoeserraticmovementsanddrawings.Itsurelookslikeflowcontrol
issues.Ihavetriedallcombinationsofdipswitchessettingsandcablingtonoavail.The
bestresultisproducedwhenIsetflowcontroltoxonxoff,
(serialPort.setFlowControlMode(serialPort.FLOWCONTROL_XONXOFF_IN|
serialPort.FLOWCONTROL_XONXOFF_OUT)
Butitstillfailssigh
Myquestion:doIhavetoprovideafunctiontoreadwhentheplottersendstheXOFF
character?OrthatisalreadytakencarebytheAPIinatransparentwayforthedeveloper?
Thankyouverymuch,andbestregards,
Andres
CommentbyAndresFebruary2,2012@1:34pm
14. Itsveryusefulverynicetutorialthankusoooomuch
CommentbyashApril15,2012@6:10pm
RSS(ReallySimpleSyndication)feedforcommentsonthispost.TrackBackURI(Uniform
ResourceIdentifier)
TheSilveristheNewBlackTheme.BlogatWordPress.com.
Follow

FollowEmbeddedFreaks..
BuildawebsitewithWordPress.com

https://embeddedfreak.wordpress.com/2008/08/08/howtoopenserialportusingrxtx/

7/7