Write string to serial port ?
Hello! Thanks all, who help me build up this attached VI !!!
Small problem.
In a few words: I received date from serial port, my VI work with it, and I want pass string “sting I need write to port” to serial port. (see attached VI).
Data all time read from port and write to port.
I know, how work serial VISA, but I don’t know, how connect wire.
And second question: how insert subVI in VI from .llb?
Thanks!
Mikhail.
Attachments:
string_to_serial_port.vi 170 KB
Hi Dai!
Thanks for answer.
I did as you said, but something I did wrong.
Please, look at my VI. What is wrong?
Mikhail.
Attachments:
string_to_serial_port.vi 171 KB
Similar Messages
-
Write data to serial port every two minutes
Hi,
I use VISA-Write to write data to serial port. I want to write a byte every two minutes. What should I do?
Thanks!hengfo,
that question is not connected to LV nor to VISA. Its more a systematic question....
So let's view at this a bit more abstract:
You want to "toogle" between two different messages sent to your interface. So you have to know:
- What was the last state i sent?
- When do i have top send the new state?
Even more abstract:
- How can i switch between the states?
Since the states are known before your program is executed, you can insert them into an array. Next, you have to read out the appropriate index from the array which contains your new state. Send the state and go to the next state. Propably you want to change timing, but that's easy too.
See attached screenshot for a possible solution:
hope this helps,
NorbertMessage Edited by Norbert B on 09-11-2007 07:57 AM
CEO: What exactly is stopping us from doing this?
Expert: Geometry
Marketing Manager: Just ignore it.
Attachments:
StateSwitching.PNG 8 KB -
Hi. Too long I can’t solve my problem. (Please see attached VI)
I need you help again.
I want send to serial port array of numbers (from 0 to 255 decimal). My VI do not want do it. In FOR loop I make my array, but it is don’t write to port sequentially.
I did something wrong?
Thank you!
Message Edited by Mihalis on 07-28-2005 01:17 PM
Attachments:
write_string_to_serial_port.vi 86 KBHi,
Your while loop will only start after the for loop finishes, so you're not sending 0, 1, ..., 255. When your for loop ends (256 seconds) you will convert the array to a string with 256 bytes from ascii 0 to 255.
I changed your vi to send "0", then "1", ... , then "255". Hpe this is what you need.
Paulo
Attachments:
write_string_to_serial_port.vi 82 KB -
How to read and write from the serial port using java
can anyone tel me how to capture data from a serial port and display on the screen and also store it in a database.
Java Comm API, JDBC
-
Problem communicating via serial port in Linux
Hello,
I am trying to transfer data via serial port, in Linux.
But it is impossible till now!
I get Runtime exception.
Here is my code:
public class Main {
public Main() {
int num=5;
int[] array = new int[5];
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
array[0]=1;
array[1]=2;
array[2]=3;
array[3]=4;
array[4]=5;
new ParallelCommunication(num,array);
import java.io.*;
import java.util.*;
import javax.comm.*; // for SUN's serial/parallel port libraries
//import gnu.io.*; // for rxtxSerial library
public class ParallelCommunication implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static CommPortIdentifier saveportId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
static OutputStream outputStream;
static boolean outputBufferEmptyFlag = false;
int num;
int[] array;
public ParallelCommunication(int this_num,int[] this_array) {
boolean portFound = false;
String defaultPort;
num = this_num;
array=new int[this_array.length];
array = this_array;
// determine the name of the serial port on several operating systems
String osname = System.getProperty("os.name","").toLowerCase();
if ( osname.startsWith("windows") ) {
// windows
defaultPort = "COM1";
} else if (osname.startsWith("linux")) {
// linux
defaultPort = "/dev/ttyS0";
} else {
System.out.println("Sorry, your operating system is not supported");
return;
// if (args.length > 0) {
// defaultPort = args[0];
System.out.println("Set default port to "+defaultPort);
// parse ports and if the default port is found, initialized the reader
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(defaultPort)) {
System.out.println("Found port: "+defaultPort);
portFound = true;
// init reader thread
initialize();
break;
if (!portFound) {
System.out.println("port " + defaultPort + " not found.");
public void initwritetoport() {
// initwritetoport() assumes that the port has already been opened and
// initialized by "public void initialize()"
try {
// get the outputstream
outputStream = serialPort.getOutputStream();
} catch (IOException e) {}
try {
// activate the OUTPUT_BUFFER_EMPTY notifier
serialPort.notifyOnOutputEmpty(true);
} catch (Exception e) {
System.out.println("Error setting event notification");
System.out.println(e.toString());
System.exit(-1);
public void writetoport(int counter) {
try {
// write string to serial port
outputStream.write(String.valueOf(array[counter]).getBytes());
} catch (IOException e) {}
public void initialize() {
// initalize serial port
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {System.out.println("Port In Use.");} //******Here is the Exception******
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
// activate the DATA_AVAILABLE notifier
serialPort.notifyOnDataAvailable(true);
try {
// set port parameters
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
// start the read thread
readThread = new Thread(this);
readThread.start();
public void run() {
// first thing in the thread, we initialize the write operation
initwritetoport();
for(int i=0; i<=num_of_inputs; i++) {
// write string to port, the serialEvent will read it
writetoport(i);
serialPort.close();
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
// we get here if data has been received
byte[] readBuffer = new byte[20];
try {
// read data
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
// print data
String result = new String(readBuffer);
System.out.println("Read: "+result);
} catch (IOException e) {}
break;
}...and the outcome is :
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException:
Error opening "/dev/ttyS0"
tcgetattr(): Input/output error
at com.sun.comm.LinuxDriver.getCommPort(LinuxDriver.java:66)
at javax.comm.CommPortIdentifier.open(CommPortIdentifier.java:369)
at ParallelCommunication.initialize(ParallelCommunication.java:128)
I have searched a lot and I couldn't find a solution.
Thank you.I'm having the same problem this helped somewhat debug the problem
http://bloggerdigest.blogspot.com/2006/11/linux-serial-com-port-diagnostic-test.html
I'm running Suse 10.3 and apparently it does not recognize my serial ports. So before
you can test your Java code you have to figure out how to make linux see the ports.
If I find a solution I'll let you know but if you find one first let me know. Thanks. -
RxtxSerial library multiple serial ports listener
Hello All,
I am using rxtxSerial library (import gnu.io.*; compatible with previousely available from Sun import javax.comm.*;) for my bridge application. Th example provided in the library's web site with nulltest.java employs only one serial port. It is powerful since it is threaded and detects incomming/outgoing streams.
However, I would like to bridge between servers so multiple ports will be employed. Do you heave any suggestion how to obtain multiple port handling (reading/writing) within the same class. The null test code is presented as follows. Simplest idea is to use arrays, but more details are required.
// derived from SUN's examples in the javax.comm package
import java.io.*;
import java.util.*;
//import javax.comm.*; // for SUN's serial/parallel port libraries
import gnu.io.*; // for rxtxSerial library
public class nulltest implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static CommPortIdentifier saveportId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
static String messageString = "AT";
static OutputStream outputStream;
static boolean outputBufferEmptyFlag = false;
public static void main(String[] args) {
boolean portFound = false;
String defaultPort;
// determine the name of the serial port on several operating systems
String osname = System.getProperty("os.name","").toLowerCase();
if ( osname.startsWith("windows") ) {
// windows
defaultPort = "COM5";
} else if (osname.startsWith("linux")) {
// linux
defaultPort = "/dev/ttyS0";
} else if ( osname.startsWith("mac") ) {
// mac
defaultPort = "????";
} else {
System.out.println("Sorry, your operating system is not supported");
return;
if (args.length > 0) {
defaultPort = args[0];
System.out.println("Set default port to "+defaultPort);
// parse ports and if the default port is found, initialized the reader
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(defaultPort)) {
System.out.println("Found port: "+defaultPort);
portFound = true;
// init reader thread
nulltest reader = new nulltest();
if (!portFound) {
System.out.println("port " + defaultPort + " not found.");
public void initwritetoport() {
// initwritetoport() assumes that the port has already been opened and
// initialized by "public nulltest()"
try {
// get the outputstream
outputStream = serialPort.getOutputStream();
} catch (IOException e) {}
try {
// activate the OUTPUT_BUFFER_EMPTY notifier
serialPort.notifyOnOutputEmpty(true);
} catch (Exception e) {
System.out.println("Error setting event notification");
System.out.println(e.toString());
System.exit(-1);
public void writetoport() {
System.out.println("Writing \""+messageString+"\" to "+serialPort.getName());
try {
// write string to serial port
outputStream.write(messageString.getBytes());
} catch (IOException e) {}
public nulltest() {
// initalize serial port
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
// activate the DATA_AVAILABLE notifier
serialPort.notifyOnDataAvailable(true);
try {
// set port parameters
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
// start the read thread
readThread = new Thread(this);
readThread.start();
public void run() {
// first thing in the thread, we initialize the write operation
initwritetoport();
try {
while (true) {
// write string to port, the serialEvent will read it
writetoport();
Thread.sleep(1000);
} catch (InterruptedException e) {}
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
// we get here if data has been received
byte[] readBuffer = new byte[20];
int numBytes = 0;
try {
// read data
while (inputStream.available() > 0) {
numBytes = inputStream.read(readBuffer);
// print data
String result = new String(readBuffer);
System.out.println("Bytes read: "+numBytes+", Read contents: "+result);
} catch (IOException e) {}
break;
}Kujtim
Edited by: Kujtim on Jul 12, 2009 1:41 PM
Edited by: Kujtim on Jul 12, 2009 1:43 PM
Edited by: Kujtim on Jul 13, 2009 1:57 PMAs an off the wall suggestion, check the usb "power save settings" under "control Panelower Options:Edit Plan Settings:Advanced Settings:USB settings" You want the USB selective suspend setting to be Disabled. Another possible idagnostic tool might be to do a Power Efficiency Diagnostics Report which we have found has occasionally pointed us to usb hanging issues.
Using the same type usb-serial adapters doesn't guarantee anything, but I have run into issues where a vendor's driver was implemented incorrectly. It ended up being a wrapper around the FTDI driver, and the wrapper dll wasn't correctly made multi-threaded safe. I browbeat the vendor (I was working at a LARGE corporation, with a prospective LARGE purchase of the devices) into telling me what calls their wrapper made. I then used the FTDI dll directly, not using the "simplified interface" of the vendor's dll. FTDI's dll was thread safe, no more random lockups/BSOD.
Good Luck, these are incredibly painful!
Putnam
Certified LabVIEW Developer
Senior Test Engineer
Currently using LV 6.1-LabVIEW 2012, RT8.5
LabVIEW Champion -
Write to Serial Port without splitting string data
Hi, all, thank you for your help in advance.
Problem:
I am trying to write to the serial port with VISA write module. Somehow the string I tried to send was splitted before it was sent. For example, if I want to send "127", it sends "7', "2", "1". I don't know if there's anyway to configure the module so that it sends out the whole string at once. I use the return count to indicate how many times it spits the data. So "127" now returns "3" (sent three times. I would like to have it to return "1" so that "127" was sent in whole).
Project:
I am working on an application where a DC motor is controlled by a controller talking to the PC's serial port. "127" stands for its maximum power. The controller devides the power into 128 steps. Therefore I need to input number from 0 to 127 to command the speed.
Any help or suggestion will be appreciated!Thanks for the prompt replies.
About Number/ASCII
I am using the Atmega128-Controller Chip to read in the signals sent from the computer serial port. Then it sends signals to the motor controller. The Atmega chip reads the ASCII string and converts it to hexadecimal number, sending that number to the motor controller. I can program the Atmega chip so that it either translates the ASCII string into hex as mentioned or accepts as it is. Either way, I want it to read two byte information at once (00 to 7F).
If the VISA serial write can send only one byte at a time, then I may have to program the chip so that it buffers the readings. I have tried using number/hex converter and number/string converter, either case, the fact that VISA Write spits one byte at a time hinders the programming. For example: I defined numbers 1 to 5 represents 20% to 100% power output with 20% increment Then I defined "10" as "90%" power, but it reads "1" "0" seperately, so the actual out put is "20%" then "0%".
I used the example VI provided by NI : advanced serial write/read. For convenience, attached here. Not all modification I made is saved. -
Write to serial port and digital port at the same time
hello,
I need to write to the digital port and the serial port at the same time. Right now I have the two vi's (to write to the serial port, write to the digital port) in the sequence structure. First I write the digital port, then write the serial port. Using the oscilloscope, the interval between these two executions is 10 ms; and I need to reduce this interval to as small as possible. I would appreciate help in any way. Thank you.Hello;
This is a little tricky. Since the transition from one sequence to another is completely Software timed, and windows manages all tasks that are running at one given time, there isn't a method to reduce that transition time.
The most you can do is try to optimize your code so all the time expent on the transition is due only to the task management.
Hope this helps.
Filipe A.
Applications Engineer
National Instruments -
Serial Port - Linux OK, Windows No Way
I have been trying to write to my serial port with hardware flowcontrol under windows XP all weekend. With no flow control all is well. I was about to give up on my serial port program when I decided to try my sample app under Linux Redaht 8 using the RXTX commapi. To my surprise, the code that would not work under windows worked just fine under Linux! I'm happy and confused at the same time. Here's the code snippet that processes the serial events. Does anyone have any insight into why this simple write with flow control would not work under windows XP? I have LED's connected to the serial lines and can see the CTS line doing what it's supposed to. I have administrative rights on XP. A few observations that probably mean nothing. Windows XP repors outputbuffersize=0, yet Linux returns a value. The API notes say it is advisory and may not report a value so I don't think it means anything.
ANY help you have would be greatly appreciated.
Thank You!
public void serialEvent(SerialPortEvent event) {
long timein,timeout;
switch(event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
if(boolDataforWriting & event.getNewValue()){
//Write data
timein=System.currentTimeMillis();
try {
// ########## LINE THAT PRODUCES ERROR IN WINDOWS BUT NOT LINUX ###########
streamSerialOut.write(strDataForWriting.getBytes());
} catch (IOException e) {
e.printStackTrace();
}//end catch
System.out.println("-->Done writing " +strDataForWriting.length()+" Bytes. Resetting str");
timeout=System.currentTimeMillis();
System.out.println("--->Time to write="+ (timeout-timein) + " ms");
//reset flags for next write operation
strDataForWriting="";
boolDataforWriting=false;
}//end if
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
try {
byte[] readBuffer = new byte[100]; //create byte array
char c;
int numBytes=0;
while (streamSerialIn.available() > 0) {
numBytes = streamSerialIn.read(readBuffer);
} catch (IOException e) {}
break;
String strtemp=(new String(readBuffer)).trim();
}//end serialeventI've had this very same problem and there is a solution.
Interestiingly I found that the same code worked on Win98 but not WinXP.
The problem seems to lie in the JavaComm implementation. I'm guessing but your probably running with the javacomm20-win32.zip that you downloaded from Sun. I've also tried using the implementation javacom that IBM provide with there download of java1.3 and it has the same problem. So you should have a look at http://www.rxtx.org I've had success running this implementation on WinXP and Linux. To save you some time compiling there is a reasonably recent binary version at this location http://www.jcontrol.org/html/en/download.html (scroll to the bottom of the page) -
Hi,
I'm able to read/write data over serial port using Java Comm APIs in Linux.
Can anybody please tell me how to write/read a file over Serial port?
Is it similar to sending a file over network?
An early response is appreciated...Same stream I/O as used over the port works from a file. Dead simple.
Also dead slow. If you want to do large amounts of data, use a RandomAccessFile and read a big chunk at a time into a byte array. Then send the byte array. -
This question has gone unanswered several times on this forum in the past but I thought I would try it once more.
Is there any Java API that is in, or will work with J2ME to allow direct read and write to the serial port similar to the functionality that javax.comm provides for j2se.
This would be useful for a project where a palmos device is used to communicate with equipment used to monitor industrial processes.Some MIDP 1.0 devices support access to the Serial
Port.
I have done it with Motorola i85, i50 (iDen) and
Motorola T720i.
I think 95cl also supports it. I'm ALSO having problems with serial port access on
my T-Mobile Moto T720i phone. I've had MUCH success
with the Nextel i85, i50, i95cl, etc phones, but the
same code isn't running on the T720i.
What do I need to do differently???
Thanks,
-Tim -
Asserting the RTS signal for serial ports
I've posted a few times, about asserting the DTR signal line for the serial
ports.
To start off with, i have now come to the realization that I was STUPIDLY
trying to set the wrong thing... I needed to set the RTS, not the DTR!!!
Most of the replies I got said to use the IN PORT and OUT PORT vi's, from
the advanced, memory/portI/O palette.
When i had a fiddle around with these, and looked them up in more depth, I
found a few things...
1. I have read a few times, that these are not portable, because of machine
dependancy... Can anyone tell me how portable they are? Such as, are they
fine for all Intel based architechure's, or what
2. I found that if I initialize the serial port, using the Serial Port
Init.vi, and then use
the Out Port.vi, to set the RTS, by addressing the
register at 0x2FC, for COM 2, the next thing I did, which was write to the
serial port, hung. When I highlighted execution, it was stuck in the Serial
Write.vi Can anybody tell me what I'm doing wrong?
Your help would be greatly appreciated!
Slade Squire
Programmer
Rectifier Technologies Pacific
Melbourne, Australia
[email protected]You should read replies to your posts more carefully since Craig Graham have
pointed out that VI to use to assert RTS and DTR lines of a serial port. You
also should search this group for the RS485 and RTS/DTR topic; it is a
recurrent question and there are some pitfalls on toggling RS485 direction
in LabVIEW.
As for RTS flow control, you will see something only when the input buffer
of the serial port is full, in which case RTS is asserted to signal the
transmitter to pause transmission.
Jean-Pierre Drolet
"Slade Squire" a �crit dans le message de news:
[email protected]...
> Something else I forgot to mention....
>
> When I try and set RTS in the flow control parameter of Serial Port
Init.vi,
> it doesn't do anything!
> Why?
> (I know it doesn't do anything, because I have an oscilliscope set up on
the
> end of the com cable, wired to the RTS pin)
>
> "Slade Squire" wrote in message
> news:[email protected]...
> > I've posted a few times, about asserting the DTR signal line for the
> serial
> > ports.
> > To start off with, i have now come to the realization that I was
STUPIDLY
> > trying to set the wrong thing... I needed to set the RTS, not the
DTR!!!
> >
> > Most of the replies I got said to use the IN PORT and OUT PORT vi's,
from
> > the advanced, memory/portI/O palette.
> >
> > When i had a fiddle around with these, and looked them up in more depth,
I
> > found a few things...
> >
> > 1. I have read a few times, that these are not portable, because of
> machine
> > dependancy... Can anyone tell me how portable they are? Such as, are
they
> > fine for all Intel based architechure's, or what
> >
> > 2. I found that if I initialize the serial port, using the Serial Port
> > Init.vi, and then use the Out Port.vi, to set the RTS, by addressing the
> > register at 0x2FC, for COM 2, the next thing I did, which was write to
the
> > serial port, hung. When I highlighted execution, it was stuck in the
> Serial
> > Write.vi Can anybody tell me what I'm doing wrong?
> >
> > Your help would be greatly appreciated!
> >
> > --
> > Slade Squire
> > Programmer
> > Rectifier Technologies Pacific
> > Melbourne, Australia
> > [email protected]
> >
> >
> >
>
>
LabVIEW, C'est LabVIEW -
Slow Baud Rate serial port (VISA)
The last version of LabVIEW, 7.1, has the serial functions incorporated on VISA Resources, and it doesn´t possible to work with baud rate lower than 110 bps. I have a big stuff of applications that works with 5 bps. It´s a serial protocol that send a byte, e.g AA (hex) via serial line, with 5 bps, and after the rate is increased.
I tried to use dll (CIN Function) but I think is impossible, cause the resource declared at the c code, so Im thiking to use a dedicated COM Dll, and use Call library Function)
I´d like to know if somebody has a tip or similar problem.
Thanks in advance
Fabrizio
Test EngineerMatthias Müller writes:
> Hello,
> I'm using LabView to controll a spektrometer through the serial port. I
> use VISA for the communication with the device. Unfortunately, the
> device is always in 9600baud mode after power on. So I have to change
> the baud-rate each time by a command i send to the device. So I open a
> VISA session in 9600 mode and communicate with the divice to set it to
> 57600baud. After that, i have to reset my local serial port to the same
> baud-rate. I do this with an property-node, where i change 'Serial Baud
> Rate'.
> Unfortunately, after I did this, the vi's that want to communicate after
> the reset of the baud-rate stop with an error:
> -1073807298
> VI_ERROR_IO
> Could not perform read/write operation
because of I/O error.
>
> (I try to write to the serial port after change of the baud-rate)
>
> I would be very glad, if someone could give me an advice, why it doesn't
> work, or how to make it work.
> Thank you a lot.
> Matthias
Matthias,
my first approach would be to close the first VISA session after the
property node. Data dependency is achieved by the error cluster feed
into a new session with the new properties.
IMHO you've discovered another bug in serial VISA.
HTH,
Johannes Nieß
P.S:What brand/modell of spectrometer are you programming for? -
Problem while reading data from Serial Port
Hi All,
I am facing some problem while reading data from Serial Port.
As per the requirement I am writing the data on Serial Port and waiting for response of that data.
Notification for data availabilty is checked with method public void serialEvent(SerialPortEvent event) of javax.comm.SerialPortEventListener.
When we are writing data on the port one thread i.e. "main" thread is generated and when data availability event occures another thread "Win32SerialPort Notification thread" is generated. This creates problem for me as we can't control thread processing.
So can anybody pls explain me how to overcome this problem?
Regards,
NehaMy Problem is:-
I am simoultaneouly wrting data on port & reading data from port.
First I write data on port using outputStream.write() method. Now when target side sends me response back for the request on serial port DATA_AVAILABLE of SerialPortEventListner event occured,we are reading data from serial port.Now till the time we didn't get the response from target next command can't be written on the serial port. When we are writing data on port main thread is executed.Now my problem starts when DATA_AVAILABLE event occured.At this point another thread is created.Due to this my program writes data of next command without reading response of previous command.To solve this prob. I have used wait() & notify() methods as follows.But again due to this my pc hangs after execution of 2 commands. (PC hang in while loop in a code provided below.)
From SOPs I could figure it out that after 2 commands we are not able to write data on serial port so DATA_AVAILABLE event doesn't occure n pro. goes in wait state.
Can anybody help me to solve this issue.
Neha.
Code:
public void serialEvent(SerialPortEvent event)
switch (event.getEventType())
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
try
dataThread = Thread.currentThread();
dataThread.setPriority(10);
dataAvailable = true;
byte[] tempArray=new byte[availableBytes];
inputStream.read(tempArray);
catch (IOException io)
SOP(io, "Error in serialEvent callback call for event DATA_AVAILABLE");
public void writetoPort(byte[] data) throws IOException
outputStream.write(data);
while(finalTimeOut >= actualTime)
if( ! dataAvailable)
actualTime = System.currentTimeMillis();
else
synchronized (mainThread)
mainThread = Thread.currentThread();
mainThread.wait();
public void sendDatatoUser(byte[] b) throws Exception, HWCCSystemFailure
obj.returnData(b);
synchronized(mainThread)
mainThread.notify();
-
Reading 2 serial port in a same time
i want to monitor 2 type of data in a same time
1- i have 6 sensor and i send them from micro avr and packed in this format >>
printf("%4d%4d%4d%4d%4d%2d@%4.2f\r\n",a,b,d,c,e,p,f);
i want to recive all 30 data bytes in one port then unpacked them...
2- i have a gyro sensor that sends data very slow every 500ms thats data like this >>
x+40.2\s\s\Y+42.3\r\n
i want recive all 16 data byte in another port and send feed back (write serial) too.
i recive gyro sensor data recive in fix 16 byte and dont have any problem .
but i have problem that i dont recive fix data from 30 data(from micro) its hangs or recive lower.
its becuse i use 2port in same time if i use it alone there is no problem.i recive it fix.
plz help me.
also im sory im not good at english.
Attachments:
8-28-2012 8-07-41 PM.jpg 289 KB
read and write in 2 serial port.vi 28 KBHey,
I would first add some error handling to your loops. The way you have it setup, the loops could be running in error and you will never know about it. The code I have attached will stop the loop if an error occurs.
Does it throw any errors when you run it?
Lewis Gear CLD
Check out my LabVIEW UAV
Attachments:
read and write in 2 serial portv2.vi 28 KB
Maybe you are looking for
-
Gnome 3 starting in fallbackmode
Hi all. I've a Inspiron 9400 with a Radeon Mobility X1400 card. Gnome 3 starts in fallback it says that card have no accelerated support, but when I try a Fedora Live with Gnome 3 it starts correctly in standard mode. I'm not using t xorg.conf file a
-
Creation of a Z copy of the tcode S_ALR_87100186
Hi, I need to make a z copy of the the standard tcode S_ALR_87100186 and do the following changes: 1. Add version & fiscal year to selection screen ( Currently it is defaulted to zero ) 2. Display the output based on the version and fiscal year enter
-
"This copy of iTunes is corrupted or is not installed correctly
Have just zero out adn formatted HD and installed OS from a DVD I have just purchased from the Apple store version 10.6.3. Once DVD as installed 10.6.3.I go to software update - one of which is iTunes 10. When the update as downloaded and installed i
-
Setting listener password in oracle 8i
i have some very old windows databases that are 8.1.0.7. I am not able to upgrade these. I am trying to set a password. 1. go to command line 2. lsnrctl 3. set password <password> LSNRCTL> set password l1stener1$ The command completed successfully LS
-
[svn] 1063: ImplementationCompiler abstract syntax tree generation
Revision: 1063 Author: [email protected] Date: 2008-04-02 08:31:38 -0700 (Wed, 02 Apr 2008) Log Message: ImplementationCompiler abstract syntax tree generation work-in-progress. Most of the methods for the equivalent Velocity macros in ClassDef.vm an