How to configure visa to adquire dat from serial port and then converted to numeric value from a home embedded device
I already stablish communication with my serial port using VISA, selecting COM1 as the resoure name.
After that, I tried to read the data from the port (as we know the data was in string format )but I need to convert the data to numeric value to hadle it (no arrays).
Another main thing is that I'm develoing a new based Embedded design and tthe info that will trhow out from the device to the PC is binary.
How can I solved the problem, and if I want to make bidirectional communication with my system how can I do it? The VISA intructions as *IDN? and so forthetc can be recognize by the external system if the COM1 port is recognized by NI Max as ADSRL1::I
NSTR1?
Hello,
For an example of bidirectional serial communication in LabVIEW, please see the shipping example LabVIEW <-> Serial.vi. This can be found from LabVIEW by going to Help >> Find Examples. From the example finder, select Hardware Input and Output >> Serial >> LabVIEW <-> Serial.vi.
Once you are able to read the string data in, you can use the VIs in the String/Number Conversion palette to convert the data to numeric format. To access these, right-click on the block diagram >> All Functions >> String >> String/Number Conversion.
Let me know if this does not help.
Regards,
Sean C.
Applications Engineer
National Instruments
Similar Messages
-
ipone5 screen became curved so you can show filter lighting internal slightly from both sides and then taking the bend is growing even split-screen device by 2 mm from the top screen still works, even though it is no longer adjacent to the device, but from the bottom with the appearance of a blue line longitudinally as a result of the curvature of the screen is also a button home-does not function well will not make my device and search for a solution with my friends interested in the technology, because I am embarrassed by the form of the device after the holidays where it seemed like device industry is poor and I am writing to Mtabaana that the iPhone is the best among "smart phones" unwillingness on the label and I have reasons as he have many ideas Perhaps the first is to install the replacement screen with adhesive to Atsamad in front of the machine heat from the inside and the outside of the hot weather in another way Macaianikiholas latest device that will not require recharging,,, NOTE: void wrought screen contributed to increase the signal network and wifi is erase
ipone5 screen became curved so you can show filter lighting internal slightly from both sides and then taking the bend is growing even split-screen device by 2 mm from the top screen still works, even though it is no longer adjacent to the device, but from the bottom with the appearance of a blue line longitudinally as a result of the curvature of the screen is also a button home-does not function well will not make my device and search for a solution with my friends interested in the technology, because I am embarrassed by the form of the device after the holidays where it seemed like device industry is poor and I am writing to Mtabaana that the iPhone is the best among "smart phones" unwillingness on the label and I have reasons as he have many ideas Perhaps the first is to install the replacement screen with adhesive to Atsamad in front of the machine heat from the inside and the outside of the hot weather in another way Macaianikiholas latest device that will not require recharging,,, NOTE: void wrought screen contributed to increase the signal network and wifi is erase
-
Hi everyone,
I'm building a heart rate monitor as a final year project with my lab partner using the NI USB-6009 and Labview 2009. We have managed to obtain a signal using a photo transciever, smooth it out and count the events, however the count is incremental.
We wish to count the number of pulses we obtain for a few seconds (5-10 for example) and then use this value to obtain a pulse rate in beats per minute (e.g. 10 pulses in the first 10 seconds would give an estimated BPM of 60 etc etc).
Does anybody have ides on how we could implement this? We have tried timed loops, elapsed time VI's and other things but nothing gives us what we need.
Thanks in advance for any help that is offered.
Jeshua Graham.We are very new to Labview. We are taking a raw signal from our DAQ and then using VIs to filter and then trigger counts on rising edges. I have attached our vi file to this post for you to look at (I hope that is what you mean by code).
Attachments:
TCRT-1010DAQ_jeshua1.vi 367 KB -
How do you save your DVD to your Hard Drive, and then convert to iPod?
Hello everyone, I was wondering how you save your DVD to your hard drive and then convert it to the iPod Video.
Please respond.
P.S.
I know that it's been discussed all the time, but none of the posts are useful for me.
ThanksHi,
The best option is to pull the card out and plug to your computer UNLESS your computer does not have a card reader. If your computer did not have a card reader, you need to map the cardreader on your printer to your network using the following method:
http://h10025.www1.hp.com/ewfrf/wc/document?lc=en&dlc=en&cc=us&docname=c00149194
Regards.
BH
**Click the KUDOS thumb up on the left to say 'Thanks'**
Make it easier for other people to find solutions by marking a Reply 'Accept as Solution' if it solves your problem. -
Hi !
I have received a set of datas via rs232 and it contains picture messages. I have to decode the datas first and then display them on a canvas.
I have known several functions that may be used . Such as
int SetBitmapData (int bitmapID, int bytesPerRow, int pixelDepth, int colorTable[], unsigned char bits[], unsigned char mask[]);
int CanvasDrawBitmap (int panelHandle, int controlID, int bitmapID, Rect sourceRectangle, Rect destinationRectangle);
However,I don't know how to set the following parameters according to the actual pixel values and color values.
int bytesPerRow, int pixelDepth, int colorTable[], unsigned char bits[], unsigned char mask[]
What's more,I have no idea how to decode the datas.
The attachment is a incomplete project. I will be very appreciated if anyone could help me .
Best regards.
xiepei
I wouldn't care success or failure,for I will only struggle ahead as long as I have been destined to the distance.
Attachments:
Decode and display image.zip 212 KBWell, things are getting a bit clearer now.
1. Your image is actually 240x240 pixel (not 320x240 as you told before). The size of image data is 57600 bytes which corresponds to that frmat (I was puzzled by such a data size compared with larger image dimensions!)
2. The image is a 8-bits-per-pixel one; this means that you must provide a color palette to create the bitmap
3. You cannot simply copy image data into bitmap fields in CVI: CreateBitmap always produce an image with pixeldepth matched with display colour depth (normally 24 or 32 bpp)
All that means that you must:
1. Create the appropriate color palette with 256 colors: it may be a grayscale or color palette depending on camera characteristics. Grayscale palette can be found in my sample project, while sample colour palettes can be found here (here the description of a "standard" 8-bpp color palette)
2. Create the bits array correctly dimensioned for the color depth of your monitor
3. Get each pixel value from the camera, lookup in the color palette for the appropriate colour and create the RGB informations into the bits array in memory
4. Display the bitmap on the canvas
As a first step, I would configure my system for 256-color display setting, create a bitmap and simply copy image data into it: you should be able to get the correct image back to your screen.
Proud to use LW/CVI from 3.1 on.
My contributions to the Developer Zone Community
If I have helped you, why not giving me a kudos? -
Efficient optimized way to read from serial port and GPS data display using map
Hi,
I have a custom h/w which reads the data from GPS Rx and after parsing send it to PC over RS232.
Each second it sends 201 bytes to PC. I have developed a VI to read the GPS data and display it. Project file is attached.
Fulctionality of different loops are as following:
1. LOOP 1: 1.1 Reads the serial data from com port.
1.2 Synclonize the frame using start bytes "a" and "z".
1.3 Reads next 4 bytes containg receiving error information.
1.4 Reads next 195 bytes. in which initial 80 byes are GPS data. rest are others.
2. LOOP 2: 2.1 Extarcts the GPS information and put them in an array.
2.2 Extarcts the receive error infor and counts the total error by incrimenting the variable using shift reg.
3. LOOP 3:3: 3.1 Displays the GPS data in chart and log the data in a file.
4. FLOW : Uses the GMAP .NET based API to creat a MAP and display.
Problem statement:
1. Functionality acheived.
2. However in between data set is being missed by the programm.
Quesitions:
1. Is the developed VI is efficient in terms of using queue loacl variables etc.
2. What are the improvments I can do to solve the problem.
Any other suggestions|
Thank you
jayant
jayant
Attachments:
Telemetry_Receiver_v2.zip 3075 KBOne of the most common problems in serial communication is the need for an adequate timing: how much time is expected your device to spend before answering? Have you put and adequate pause in your code before reading from the serial port?
Hope this helps
Roberto
Proud to use LW/CVI from 3.1 on.
My contributions to the Developer Zone Community
If I have helped you, why not giving me a kudos? -
Reading ascii codes from serial port and plotting them
Hello
I am trying to build a VI that reads data (ascii values) from the serial port.
I am trying to build a wireless phonocardiogram. I have a microphone that acquires heart sounds. these signals are amplified and sent to a A/D converter to digitize them. the digital signal are sent to a base unit. The digitals signals received at the base unit have to be sent to a computer (over a serial port to view them).
I would like build a VI to plot ascii data received over the serial port.
I would like to plot those values so that the plot just looks like a analog signal (the one I had before A/D conversion).
Can anyone provide me some help?
Thanks in advance.....
Solved!
Go to Solution.Hi chaitu209
What is your transmission speed, samplerate, and bandwidth needed in your project? The bandwidth of the serial port is somewhat limited. Let me give you an example
Say you are using 115200 Kbit per second as transmission speed, one start bit/stop bit and parity bit, and 8 bit data. This will give you 115200/11 bytes pr second as the maximum theoretical transfer rate/sample rate. But if you are using up to 16 bit AD your maximum samplerate will be 115200/(2x11). So my advise to you is to use a binary transfer protocol not ASCII based protocol. This is not a problem in Labview with serial transmission.
Besides which, my opinion is that Express VIs Carthage must be destroyed deleted
(Sorry no Labview "brag list" so far) -
So when i turn on my ATV2 now, and go to computers, it doesnt recognize my computer anymore. I didnt touch anything from the previous day after it last worked, so im not sure why it suddenly stopped working. I've tried turning off/on homesharing, siging in with a different account but still using my appleid..i've reset the ATV2 to it factory settings and then reinstalled the recent update but nothing seems to be working. Whenever i turn on homesharing on my macbook pro, it akknowledges that its on, but then the little logo for homesharing goes away as soon as i click done. Not sure if that is normal or not. Im assuming this is a prb with itunes because my photostream works off ATV2, receiving pics from my comp,but i cant seem to stream movies etc. The airplay icon is also no longer on my mac screen. I have no idea whats going on. Any ideas?
thanksSo when i turn on my ATV2 now, and go to computers, it doesnt recognize my computer anymore. I didnt touch anything from the previous day after it last worked, so im not sure why it suddenly stopped working. I've tried turning off/on homesharing, siging in with a different account but still using my appleid..i've reset the ATV2 to it factory settings and then reinstalled the recent update but nothing seems to be working. Whenever i turn on homesharing on my macbook pro, it akknowledges that its on, but then the little logo for homesharing goes away as soon as i click done. Not sure if that is normal or not. Im assuming this is a prb with itunes because my photostream works off ATV2, receiving pics from my comp,but i cant seem to stream movies etc. The airplay icon is also no longer on my mac screen. I have no idea whats going on. Any ideas?
thanks -
I bought a factory unlocked iPhone 4S from an Apple store in the U.S. and I am in Guatemala. I want to use it now but later on I will move to New Zealand. Can I activate it with a SIM card from Guatemala and then use it with a SIM card from New Zealand? I am just wondering if it will get locked with the Guatemalan SIM card. Or does it just need a SIM from any supported carrier and then it remains unlocked to use with any other carrier? Thanks
David,
As I (mis)understand it, you may:
1) Copy one orange gradient path to the magenta gradient path document;
2) Select the two magenta gradient paths and change the Fill to None;
3) Select the orange gradient path;
4) Select the two magenta gradient paths and change the Fill to Gradient.
That should give you the desired replacement. For multiple use of the same gradient, you may consider a gradient swatch. -
How could I choose some bytes from HEX string and then convert it to a decimal value?
Hi I am working with an OMRON E5EN temperature controller using VISA serial to get data, I send the Read from Variable Area command and get this string in hexa 0230 3130 3030 3030 3130 3130 3030 3030 3030 3030 3041 3203 71 or .01000001010000000000A2.q in ASCII this string means:
02 STX
3031 3030 Node and subadress
3030 End Code Normal Completion
3031 3031 Command Read from Variable Area
3030 3030 respt code Normal completion
3030 3030 3030 4132 Hexadecimal A2 = 162 (this is the temperature data that I want to show in decimal)
03 ETX
71 Block Check Character
I want to choose the eight bytes for the temperature data and convert it to a decimal number. I have seen the examples to convert a Hexa string to decimal but I do not know how to choose the specifics bytes that I need.
I have look for a driver but i didn´t find any. I am a beginner so please include especific topics for me to study in your answer.
Thanks
Carlos Fuentes Silva Queretaro MexicoIf the response always has the temperature starting with byte 15 and is always 8 bytes in length, you can use the String Subset function to get those bytes out of the string. Then use Hex String to Number to convert to a decimal number.
Well someone already beat me to the solution:
Message Edited by tbob on 01-04-2008 04:42 PM
- tbob
Inventor of the WORM Global
Attachments:
HexStr2Decimal.png 7 KB -
I send the frame by a microcontroller ( 8bits) the fram contains 6 bytes, 2bytes conform a long variable, I want to decode the frame and make operations with these long variables and then plot them
Hey jpvans,
I would first suggest using NI-VISA to talk to the serial port. Then, you can use the LabVIEW Type Cast or the Flatten to String and UnFlatten From String VIs to convert the data.
You can setup the read so that it reads just two characters at a time to form an individual long or you can set the read up to read it all and then use the string functions like String Subset to cut the information into chunks.
I hope this helps out.
JoshuaP -
How to get data from serial port to GUI textArea
From Serial Port.....
Messages from base (always 5 bytes):
0xAA, 0, 0, 0, 0xBB - IDLE Mode
0xAA, 0, 0x80, 0x80, 0xBB - Question Mode
messages from terminal (always 6 bytes):
0xAA, a, b, c, chksum, 0xBB
where chksum = a+b+c;
a = address (0-250)
the 2 MSB's of b represenet the answer:
0 0 - A
0 1 - B
1 0 - C
1 1 - D
the 6LSB's of b and 8bits of c is the time for answer, in milliseconds.
(0-16384 milliseconds)
I have VB Code for that but I want the same thing in Java ...
Can any one help me?
Here's VB Code..
VERSION 5.00
Object = "{648A5603-2C6E-101B-82B6-000000000014}#1.1#0"; "MSCOMM32.OCX"
Begin VB.Form Form1
BorderStyle = 1 'Fixed Single
Caption = "Aakar GUI"
ClientHeight = 4665
ClientLeft = 60
ClientTop = 375
ClientWidth = 6105
LinkTopic = "Form1"
MaxButton = 0 'False
MinButton = 0 'False
ScaleHeight = 311
ScaleMode = 3 'Pixel
ScaleWidth = 407
StartUpPosition = 3 'Windows Default
Begin VB.CommandButton cmdPort
Caption = "Open Port"
Height = 375
Left = 120
TabIndex = 4
Top = 600
Width = 1455
End
Begin VB.ComboBox cmbPort
Height = 315
ItemData = "Form1.frx":0000
Left = 120
List = "Form1.frx":0016
Style = 2 'Dropdown List
TabIndex = 3
Top = 120
Width = 2895
End
Begin VB.CommandButton cmdEnd
Caption = "End"
Height = 495
Left = 1560
TabIndex = 2
Top = 1320
Width = 1215
End
Begin VB.CommandButton cmdStart
Caption = "Start"
Height = 495
Left = 120
TabIndex = 1
Top = 1320
Width = 1215
End
Begin VB.TextBox txtMessage
Height = 2040
Left = 119
MultiLine = -1 'True
ScrollBars = 3 'Both
TabIndex = 0
Top = 2475
Width = 5848
End
Begin VB.Timer tmrRead
Enabled = 0 'False
Interval = 1
Left = 2040
Top = 600
End
Begin MSCommLib.MSComm MSComm1
Left = 3120
Top = 360
_ExtentX = 1164
_ExtentY = 1164
_Version = 393216
DTREnable = 0 'False
ParityReplace = 45
SThreshold = 1
End
Begin VB.Label Label5
Caption = "Result Data:"
Height = 375
Left = 120
TabIndex = 5
Top = 2115
Width = 1320
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Dim PortIsOpen As Boolean
Dim Answers(4) As String
Dim RejectKeystroke As Boolean
Private Sub cmbPort_Change()
Debug.Print cmbPort.ListIndex
End Sub
Private Sub cmbPort_Validate(Cancel As Boolean)
'Cancel = True
End Sub
Private Sub cmdEnd_Click()
MSComm1.Output = "e"
txtMessage.Text = ""
End Sub
Private Sub cmdPort_Click()
On Error GoTo ErrorHandler
If cmbPort.ListIndex < 0 Then Exit Sub
If PortIsOpen Then
cmbPort.Enabled = True
MSComm1.PortOpen = False
PortIsOpen = False
cmdPort.Caption = "Open Port"
cmdStart.Enabled = False
cmdEnd.Enabled = False
Else
MSComm1.CommPort = cmbPort.ListIndex + 1
cmbPort.Enabled = False
MSComm1.PortOpen = True
PortIsOpen = True
cmdPort.Caption = "Close Port"
cmdStart.Enabled = True
cmdEnd.Enabled = True
End If
Exit Sub
ErrorHandler:
Debug.Print Err.Number
Debug.Print Err.Description
MsgBox Err.Description, vbExclamation Or vbOKOnly, "Error opening port"
cmbPort.Enabled = True
PortIsOpen = False
cmdPort.Caption = "Open Port"
cmdStart.Enabled = False
cmdEnd.Enabled = False
End Sub
Private Sub cmdStart_Click()
MSComm1.Output = "s"
txtMessage.Text = ""
End Sub
Private Sub Form_Initialize()
Dim tmp As Variant
tmp = InitCommonControls
End Sub
Private Sub Form_Load()
Answers(0) = "A"
Answers(1) = "B"
Answers(2) = "C"
Answers(3) = "D"
'MSComm1.Settings = "9600,n,8,1"
''MSComm1.Settings = "115200,n,8,1"
'MSComm1.PortOpen = True
On Error GoTo ErrorHandler1
MSComm1.CommPort = 1 ' comm port 1
MSComm1.RThreshold = 1 ' use 'on comm' event processing
MSComm1.Settings = "9600,n,8,1" ' baud, parity, data bits, stop bits
MSComm1.SThreshold = 1 ' allows us to track Tx LED
MSComm1.InputMode = comInputModeText 'comInputModeBinary ' binary mode, you can also use
' comInputModeText for text only use
PortIsOpen = False
cmbPort.ListIndex = 0
' open the port
MSComm1.PortOpen = True
cmbPort.Enabled = False
PortIsOpen = True
cmdPort.Caption = "Close Port"
cmdStart.Enabled = True
cmdEnd.Enabled = True
Exit Sub
ErrorHandler1:
Debug.Print Err.Description
PortIsOpen = False
cmbPort.Enabled = True
cmdPort.Caption = "Open Port"
cmdStart.Enabled = False
cmdEnd.Enabled = False
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
If MSComm1.PortOpen Then MSComm1.PortOpen = False
End Sub
Private Sub lblOption_Click()
End Sub
Private Sub MSComm1_OnComm()
' Synopsis: Handle incoming characters, 'On Comm' Event
' Description: By setting MSComm1.RThreshold = 1, this event will fire for
' each character that arrives in the comm controls input buffer.
' Set MSComm1.RThreshold = 0 if you want to poll the control
' yourself, either via a TImer or within program execution loop.
' In most cases, OnComm Event processing shown here is the prefered
' method of processing incoming characters.
Dim i As Long
Dim sBuff As String ' buffer for holding incoming characters
Const MTC As String = vbCrLf ' message terminator characters (ususally vbCrLf)
Const LenMTC As Long = 2 ' number of terminator characters, must match MTC
Dim iPtr As Long ' pointer to terminatior character
' OnComm fires for multiple Events
' so get the Event ID & process
Select Case MSComm1.CommEvent
' Received RThreshold # of chars, in our case 1.
Case comEvReceive
' read all of the characters from the input buffer
' StrConv() is required when using MSComm in binary mode,
' if you set MSComm1.InputMode = comInputModeText, it's not required
'sBuff = sBuff & StrConv(MSComm1.Input, vbUnicode)
'If Len(txtMessage.Text) > 4096 Then txtMessage.Text = ""
sBuff = MSComm1.Input
Dim ch As String
Dim PacketStart As Boolean
Dim PacketLength As Integer
Dim Packet() As String
PacketStart = False
PacketLength = 0
While (Len(sBuff) > 0)
ch = Left(sBuff, 1)
If (ch = Chr(&HAA)) Then PacketStart = True
If (ch = Chr(&HBB)) Then PacketStart = False
If (ch <> Chr(&HAA) And ch <> Chr(&HBB)) Then
PacketLength = PacketLength + 1
ReDim Preserve Packet(PacketLength)
Packet(PacketLength) = ch
End If
'txtMessage.Text = txtMessage.Text + Format(Hex(Asc(ch)), " @@")
sBuff = Right(sBuff, Len(sBuff) - 1)
Wend
If (PacketLength = 3) Then
Debug.Print "Command packet recieved"
'txtMessage.Text = txtMessage.Text + vbCrLf + "Address =" + Str(Asc(Packet(1)))
'txtMessage.Text = txtMessage.Text + vbCrLf + "Address =" + Str(Asc(Packet(2)))
End If
If (PacketLength = 4) Then
Debug.Print "Response packet recieved"
txtMessage.Text = txtMessage.Text + "Address =" + Str(Asc(Packet(1))) + _
" Answer = " + Answers((Asc(Packet(2)) And &HC0) / 64) + _
" Time =" + Str((Asc(Packet(2)) And &H3F) * 256 + (Asc(Packet(3)))) + "mS" + vbCrLf
'txtMessage.Text = txtMessage.Text + vbCrLf + "Address =" + Str(Asc(Packet(1)))
'txtMessage.Text = txtMessage.Text + vbCrLf + "Option =" + Str((Asc(Packet(2)) And &HC0) / 64)
'txtMessage.Text = txtMessage.Text + vbCrLf + "Time =" + Str((Asc(Packet(2)) And &H3F) * 256 + (Asc(Packet(3))))
End If
If (PacketLength <> 4 And PacketLength <> 3) Then Debug.Print "Unknown packet of length" + Str(PacketLength) + " recieved"
txtMessage.Text = txtMessage.Text + vbCrLf
' An EOF charater was found in the input stream
Case comEvEOF
DoEvents
' There are SThreshold number of characters in the transmit buffer.
Case comEvSend
DoEvents
' A Break was received.
Case comEventBreak
DoEvents
' Framing Error
Case comEventFrame
DoEvents
' Data Lost.
Case comEventOverrun
DoEvents
' Receive buffer overflow.
Case comEventRxOver
DoEvents
' Parity Error.
Case comEventRxParity
DoEvents
' Transmit buffer full.
Case comEventTxFull
' Unexpected error retrieving DCB]
Case comEventDCB
DoEvents
End Select
End Sub
Private Sub tmrRead_Timer()
'MSComm1.Output = vbCrLf + vbCrLf
'MSComm1.Output = Chr(128)
End Sub
Private Sub txtMessage_KeyDown(KeyCode As Integer, Shift As Integer)
If Shift = 2 Or Shift = 4 Then RejectKeystroke = False Else RejectKeystroke = True
End Sub
Private Sub txtMessage_KeyPress(KeyAscii As Integer)
If RejectKeystroke Then
KeyAscii = 0
End If
End SubThanks in advance..I want to replicate the entire VB program as Java Program.
This has to be included in my project which i am doing in java. -
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 a char array from Serial port
Need help!
Hi, I've got the following problem - I wanna read a input stream from serial port and I use at the moment the following method (reading bytewise):
public String receiveText (){
byte ch;
fStrBuf.delete(0,fStrBuf.length()); //clearing the buffer
try{
do {
ch = (byte) fPortInStream.read();
fStrBuf.append( (char) ch);
while ( (byte) ch != 0x03); //The end of frame byte
}catch(IOException ioe) {};
return fStrBuf.toString();It works pretty well, but disadvantage is that it's too slow to use it in the thread (at least I think so)
How can I change it to read all available data from the port (or simply faste). I don't need event listeners, because it's a request-responde communication.
I tried smth. like this
byte[] readBuffer = new byte[20];
try {
while (fPortInStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
fStrBuf.append(readBuffer);
} catch (IOException e) {}
return fStrBuf.toString();But it doesn't seem to work :-(May I suggest that you use StringBuilder rather than StringBuffer. It has less overhead because it is not threadsafe. I do synchronous serial port stuff with Opto 22, and i have no listeners enabled.
Appending to the String(Builder/Buffer) directly from the byte buffer mangles it. So I use a string (ugh). With the Opto22 brain boards, i am looking for a carriage return as a term char. It either finds it or times out.
This is the best i have come up with so far:
StringBuilder response = new StringBuilder();
String data = new String();
long msTimeOut = 2000;
public void getResponse () throws IOException {
byte[] readBuff = {0};
int charAvail;
response.delete(0,response.length());
long ts = Calendar.getInstance().getTimeInMillis();
try {
while ( readBuff[readBuff.length-1] != '\r' ) {
charAvail = inputStream.available();
if ( charAvail > 0 ) {
readBuff = new byte[charAvail];
inputStream.read(readBuff);
response.append(new String(readBuff));
if ( Calendar.getInstance().getTimeInMillis() > (ts + msTimeOut) ) {
response.delete(0,response.length());
response.append("TIMEOUT");
break;
} catch (IOException e) { e.printStackTrace(); throw e; }
data = response.substring(0);
} I just starting writing Java about 4 days ago, so caveat emptor. -
Using substring to pick the numeric value from a string failing
Hi,
I have a string like fffd_1234.com from this I need to pick the numeric value from which is in between the _ and . , for that I have wriiten the expression as
Reverse(SUBSTRING( REVERSE( "fgfg_asdd.com" ),
FINDSTRING(Reverse( "fgfg_asdd.com" ), ".", 1 )+1 ,findstring(
Reverse( "fgfg_asdd.com" ),"_",1 )-FINDSTRING(Reverse("fgfg_asdd.com"
), ".", 1 )-1))
This is throwing me the error or its giving me with the result with _123.Why all the "reverse" calls? Do you expect underscores or periods to occur more than once in the file name?
This should work:
SUBSTRING("fffd_1234.com", FINDSTRING("fffd_1234.com", "_", 1) + 1, FINDSTRING("fffd_1234.com", ".", 1) - FINDSTRING("fffd_1234.com", "_", 1) - 1)
Talk to me now on
Maybe you are looking for
-
Need to configure different SSIDs on same VLAN on 1142
We're having a problem with interference in the B/G range due to the large number of access points owned by other companies in a fairly small area. The various laptops keep deauthenticating, which is causing problems with applications. I'd like to co
-
How can i transfer songs from another itunes other than mine
how can i transfer songs from another itunes other than mine
-
Problem alt-tabing some wine applications in openbox
I have problem alt-tabing from SOME wine fullscreen games (like Frozen Throne and CS, but no problem with Fahrenheit) when I'm under openbox (The game appears to have alt-tabed - I see the desktop for a split second and then back to the game... the d
-
How do I banish the blue circle with the magnifying glass inside it?
Too often when I click on a site, up comes some ad instead. Firefox is indeed slow to scroll down
-
Why won't GB open anymore after the 10.7.4 update?
I recenty updated the software to 10.7.4 & now GarageBand won't open. I try to open a project with it but it gives me an error message saying something about MIDI...I have no idea what to do and i'm guessing it really is because of the update. If any