Write to serial port asyncronously

I am trying to write a commands to a serial port but my problem is that the operation is tedious so it is freezing up my UI. What makes it more complicated is that I must call this procedure when the form loads I want to ask if anyone can provide an alternative
way to get the same or better result I was thinking of running it asynchronously but I don't know how to?
This is the code I am calling on load
If lblConnected.Text = "" Then
MsgBox("Please connect to port.", MsgBoxStyle.OkOnly, "Validation")
Exit Sub
End If
RichTextBox1.Text = ""
Try
With SerialPort1
rcvdata = ""
.Write("AT" & vbCrLf)
Threading.Thread.Sleep(1)
.Write("AT+CMGF=1" & vbCrLf)
Threading.Thread.Sleep(1)
.Write("AT+CPMS=""SM""" & vbCrLf)
Threading.Thread.Sleep(1)
.Write("AT+CMGL=""ALL""" & vbCrLf)
Threading.Thread.Sleep(1)
.Write("AT+CNUM" & vbCrLf)
Threading.Thread.Sleep(2000)
Dim lineoftext As String
Dim arytextfile() As String
Dim myString As String
lineoftext = rcvdata.ToString
arytextfile = Split(lineoftext, "Your number is", CompareMethod.Text)
myString = "Your number is"
lineoftext = lineoftext.Substring(lineoftext.IndexOf("Your number is"), 40)
lineoftext = lineoftext.Replace("Your number is", "")
lineoftext = lineoftext.Substring(0, 13)
txtDonglePhoneNumber.Text = LTrim(lineoftext)
End With
Catch ex As Exception
MsgBox(ex.Message)
End Try
I am trying to extract the phone number from this whole routine  and it works but its freezing up my UI. How can I run from another thread.
If you think it you can achieve it

Imports System.IO.Ports
Imports System.Threading
Public Class Form1
Private comport As SerialPort
Private sending As Boolean
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
sending = False
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
comport = CreateComport(comport)
If sending = False AndAlso OpenComport(comport) = True Then
Dim t As Threading.Thread = New Threading.Thread(AddressOf SendData)
t.IsBackground = True
t.Start(comport)
End If
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
CloseComport(comport)
End Sub
Private Function CreateComport(ByVal port As SerialPort) As SerialPort
If port Is Nothing Then
port = New SerialPort("COM4", 9600, Parity.None, 8, StopBits.One)
End If
Return port
End Function
Private Function OpenComport(ByVal port As SerialPort) As Boolean
Try
If (Not port Is Nothing) AndAlso (port.IsOpen = False) Then
port.Open()
End If
Return True
Catch ex As Exception
MessageBox.Show(String.Format("Exception :{0}", ex.ToString()))
Return False
End Try
End Function
Private Sub CloseComport(ByVal port As SerialPort)
Try
If (sending = False) AndAlso (Not port Is Nothing) AndAlso (port.IsOpen) Then
port.Close()
MessageBox.Show("Port closed")
End If
Catch ex As Exception
MessageBox.Show(String.Format("Exception :{0}", ex.ToString()))
End Try
End Sub
Private Sub SendData(ByVal port As Object)
Dim buffer(1023) As Byte
For i As Int32 = 0 To buffer.Length - 1
buffer(i) = i Mod 256
Next
sending = True
Try
DirectCast(port, SerialPort).Write(buffer, 0, buffer.Length)
Catch ex As Exception
CloseComport(DirectCast(port, SerialPort))
MessageBox.Show(String.Format("Exception :{0}", ex.ToString()))
Finally
sending = False
End Try
End Sub
End Class
在現實生活中,你和誰在一起的確很重要,甚至能改變你的成長軌跡,決定你的人生成敗。 和什麼樣的人在一起,就會有什麼樣的人生。 和勤奮的人在一起,你不會懶惰; 和積極的人在一起,你不會消沈; 與智者同行,你會不同凡響; 與高人為伍,你能登上巔峰。

Similar Messages

  • 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

  • Info about read or write a serial port with forms 6.0.5

    Anybody can give some info. on read or write a serial port using form (Developer 6.0.5).
    Thanks
    MM
    null

    One option you can try is to develop a DLL
    function to read/write serial port,
    and then write a ORA_FFI procedure to call the DLL function.
    Peter Ng
    Calgary, Canada
    null

  • Cannot write to serial port

    Hi,
    I am using jdk 1.3.1, forte ce 3.0 and j2me 1.0.3 beta.
    I wrote a midlet that should write and read strings to and from the serial port.
    Using the Emulator I have the reading working, but the writing freezes the execution.
    Any ideas?
    Debbie

    Thanx for your reply (I have been asking this question everywhere for 2 weeks and no one has answered...).
    I am using the Motorola i85s. It is specifially stated in the "i85s & i50sx Release 2 J2ME Developers' Guide Addendum" that the serial communications SHOULD work.
    As I said - reading from the port (using the i85s Emulator) works - but writing to the port - freezes the execution. So this means that my connection is up and running - just the write is not working.
    I would love to be able to load my midlet to my phone - since maybe on the phone it WILL miraculously work. But in this direction I am stuck with the fact that the JAL Lite does not load "network capable apps" - whereas I cannot get my hands on the Web JAL (which DOES load network capable apps) - since I have not succeeded to get thorugh the 100 steps that you must go through in order to use it... see for yourself at https://idenonline.motorola.com/ideveloper/program/program_jal.cfm).
    Help...?

  • 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.

  • Esc Command to serial Port

    I'd like to send an esc command to the serial port in my LV-application. how I can do that ??
    I tried to use write to serial port and \1b as string but it not worked.
    In a terminal programm it works with the ESC key and with ALT+027.

    Hi,
    You have to be careful with the kind of datas that you send...
    You told that you sent \1b or something like this, but did you sent this in Ascii mode or \ mode... It's very different for the device...
    Maybe you have to write as a constant in \ mode the code \1b, and after that convert this string type to ascii mode using the roght button on the constant and then send the character to the device

  • Pc to h/w communication by using serial port

    I have write a serial port codding but thre is problem in accessing the javax.comm.*' packege.
    I had downloaded that package on my pc but its not working.
    Could anybody help me?

    Hmm. Urgent. When is your project due? What have you tried so far? Whats not working? First you need to verify that all your hardware is connected properly and the UART is properly configured on teh 8051. Then you need to make sure that the software on both the PC and the 8051 are both working properly. Just curious, what class is this project for?

  • Serial Port Sniffer

    Hi all,
    I want to write a Serial Port Sniffer based on the proxy design pattern. Can I use the socket API for this purpose?
    Thanks
    Jean

    No, Sockets deal with TCP/IP. For serial ports you need to use javax.comm.

  • Problems reading the serial port with labview 5.1.

    I open the example serial.vi , I select write to serial port, run the programm, I don`t have any problem. But when I select read serial port, I get the error code 16392and hex code error x4008. I need to know what can I do? Thanks a lot

    Any time you get an error in LV you can right click on the error cluster indicator and do a "Explain Error".
    If you do this for the error code you reported, the explanation says that it was a framing error.
    In serial communications, a framing error indicates that the hardware was not able to detect a start bit, data then the stop bits that comprise a frame.
    This prompts me to suggest that you check you port setting on the serial port. You want to make sure you are setting the port for the correct;
    Number of start/stop bits,
    Baud rate
    data bits
    parity (just for good measure)
    and hardware handshaking.
    I hope this helps,
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • How can I use the output value from SIMPLE PID to write something to the serial port?

    I am working on my Senior Design Project that requires the use of incoming compressed air, propotional valves, continuous servo motors, and a serial servo motor microcontroller.  I have figured out how to send byte sequences to the microcontroller through LabVIEW using the VISA serial write function.  The motors are attached to the valves to control the flow rate.  I have created my own simple feedback system using a bunch of case structures but I realized that I am basically trying to recreate the wheel (I basically was writing my own PID VI).   I have an older version of LabVIEW (7.0 Express) and theres no way to upgrade or buy the PID toolkit, so I am stuck using the Simple PID VI.  Also, the only way the motor works is sending an array of bytes to tell it to turn on/off, direction, and speed.  Is there any way I can use the Simple PID VI in conjunction with the VISA SERIAL write function, or is there any other way I can communicate with the serial port using this pid vi?  Any information would be appreciated.

    Hi gpatel,
    you know how to communicate to serial port, but you don't know how to send a value from SimplePID to serial port???
    You know how to communicate, but then you don't know how to communicate???
    You should explain this in more detail...
    Edit:
    From you first post you know what values your motor driver is expecting. You know which values the PID.vi is providing. Now all you need is a formula to reshape the values from PID to the motor. It's up to you to make such a formula. Unless you provide any details we cannot give more precise answers...
    Message Edited by GerdW on 02-28-2010 08:35 PM
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Urgent!!! Need help in file read/write data to a serial port

    Hi,
    I really need someone's help in order for me to complete my project. I have attached a vi which I have taken from an example and integrate to my project. In the vi, I have managed to get the encoder counts using Ni 9411. I need to read/write that data from ni9411 to ni9870 without using any serial port as they are connected to a NI 9104 chasis. May I know whether I am correct in writing the data to my ni9870 port using the vi I have attached? Does anyone know how i can convert the number of counts to a 8-bit data/byte so that I can send the data through the RS232 port? I really need someone's help as I need to finished in 2 weeks time.
    I have also attached an vi on controlling the epos2 controller using instrument driver. Does anyone know how can i integrate this vi to the fpga vi (the one which I need to read/write data to 9870) as I need to send those data to control my epos2 controller.
    Please help me!!!
    Attachments:
    Encoder Position & Velocity (FPGA).vi ‏23 KB
    SINGLEMOTORMODIFIED.vi ‏17 KB

    Afai,
    As I allready suggested you here, call your local NI Office and ask for assistance!
    You really need assistence in a higher level that we can provide via the forums. Otherwise I don't see a chance for you to finish your project in time.
    1. Convert I32 to U8 to write it to the 9870 could be done like this:
    2. The vi to control the epos2.
    There is NO way ( absolutely NO way) to port this vi to FPGA. It's based on VISA calls, uses an event-structure, both are not available at the FPGA.
    The only thing you could do is to analyze the VI, the instruction set and design an FPGA vi which handles the specific instructions you would need.
    I have no experience with epos2 and I'm not 100% sure if this would work as you would like to use it. And doing this needs deep knowledge of LabVIEW, VISA, Instrument Drivers, the epos hardware, FPGA programming, and so on... 
    Christian

  • 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

  • Write array to serial port

    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 KB

    Hi,
    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

  • 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

  • Closing a serial port after executing a for loop of write and reads.

    Hello,
    Labview is opening and then closing each write to the port. I have tried to leave the close outside of the for loop, but labview wont allow it. What do I need to change to make all the writes and reads execute on 1 open and close of the serial port.?
    Thanks.
    Attachments:
    Controller.vi ‏27 KB

    J_es--
         The program that you posted looks to be ok for the most part, you might consider putting an open after your configure (but that's trivial). The other thing that is a minor issue is the loop tunnel coming out of your for loop is currently being auto-indexed.  This function is used to index data for each interation of the loop.  You are using a static address (not an array) and so you don't need this.  If you right-click and remove the auto-index the broken wire will go away. Other than that it should be ok.
         I would suggest looking at one of the shipping examples that come with LabVIEW.  "Basic Serial Read and Write" is essentially the same thing that you are doing and is tested here and might save you a bit of time.  Anyway, take a look if you have a second. Best of luck with your application!
    John H.
    Applications Engineer
    National Instruments
    http://www.ni.com/support

Maybe you are looking for

  • Dropped lumia 520 in water and it wont turn on

    One week ago I dropped my phone in fresh water and it was completely submersed for about 2-3 minutes. I put it in a bag of uncooked rice for a couple of days and when I took it out it worked perfectly fine. However when it died I could not charge the

  • 0  SUBMITTED, 0  SUCCESS, 0  FAIL.

    Hi All, Version: BPC 7.0 I am facing the issue in balance carry forward. I am running the data package for Carry forward but everytime I am getting "0  SUBMITTED, 0  SUCCESS, 0"  FAIL and no records gets selected. I have setup every property mentione

  • Can Employee submit Complaints electronically in ESS portal(Urgent)

    Hello, Could any one please answer this question, The client wants the Employees to submit their Grievance(complaints) electronically through ESS? Is any functionality available in ESS so that EE can enter complaints and send or do we need to customi

  • Multi Condition step

    Hi, I am changing the approval custom worflow. In my workflw intial two step are  MULTI CONDITION for  plant   and  condition types. previously we have used different approval procedure for different plant. now all plants are having the same procediu

  • Some question for experts !! Urgent

    I have following queries: 1) When a copy fucntion fails, if i get an error message saying a variable could not be determined. Can i change the text for the same to make it user friendly. 2) If i have a fucntion geeting executed before display of layo