Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. SerialPort DataReceived Event Read Byte ?

SerialPort DataReceived Event Read Byte ?

Scheduled Pinned Locked Moved C#
helpquestion
21 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • I ibrahimayhans

    Hello, I would like to ask you to share information on a subject, I am experiencing a problem related to data transmission and data retrieval on an Indicator device connected to a serial port on a project I am developing. Code I Write For Trial Purpose As Below, SerialPortTLB_DataReceived Event Overflow Should Not Send on Textbox as Byte, How can I print the incoming data as Bytes? I'm Waiting For You About This Issue, Good Work ...

    using DevComponents.DotNetBar.Metro;
    using System;
    using System.Windows.Forms;

    namespace VeriOkuma
    {
    public partial class VeriOkuma : MetroForm
    {
    public VeriOkuma()
    {
    InitializeComponent();
    }

        private void BTNVeriGonder\_Click(object sender, EventArgs e)
        {
            if (!SerialPortTLB.IsOpen)
                SerialPortTLB.Open();
            SerialPortTLB.Write(System.Convert.ToChar(2).ToString() + System.Convert.ToChar(1).ToString() + "DNG" + System.Convert.ToChar(13).ToString());
        }
    
        private void VeriOkuma\_Load(object sender, EventArgs e)
        {
            if (SerialPortTLB.IsOpen)
            {
                SerialPortTLB.Close();
            }
        }
    
        private void SerialPortTLB\_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            if (!SerialPortTLB.IsOpen) SerialPortTLB.Open();
            TXBGelenVeri.Text = SerialPortTLB.ReadExisting();
            SerialPortTLB.Close();
        }
    }
    

    }

    L Offline
    L Offline
    Lost User
    wrote on last edited by
    #4

    Assuming you even hooked up the "data received handler", that "handler" in invoked on an "open" port. The "open / close" logic in the handler (and elsewhere) implies that your whole approach is "faulty"; and that "printing a byte" is the least of your problems. You need to (re)read the VS docs for "Serial port". (Unless it's some weird "virtual" port; then you need to refer to those docs).

    "(I) am amazed to see myself here rather than there ... now rather than then". ― Blaise Pascal

    1 Reply Last reply
    0
    • I ibrahimayhans

      Hello, When we contact with the manufacturer company, we inform you as the status on the screen of the device after Char Characters we send. When the Status Letter arrives, the values are sent correctly. After this, SerialPort.Read as specified in the company's total length of 41 bytes is required. SerialPort.ReadExisting () Returns an Incomplete Result. Features SerialPort.Read Read.

      OriginalGriffO Offline
      OriginalGriffO Offline
      OriginalGriff
      wrote on last edited by
      #5

      ibrahimayhans wrote:

      SerialPort.ReadExisting () Returns an Incomplete Result.

      Well, yes. It will. Serial data is called that because data arrives one bit at a time - a serial stream of data. When seven or eight data bits have been received (together with all appropriate framing characters such as start, stop, and parity bits) the resulkting byte is passed to the input buffer, and the hardware notifies Windows that it is ready. Windows then reads the buffer content, adds it to an internal circular queue, and sends a message to your app which is translated into a DataReceived event. You handler then gets called and reads the data, however much of it there is. Subsequent bytes cause the same process to occur. You do not get a "I've got all the data" event, you get an "I've got at least one character for you" event instead. If you want to receive the whole message, then you need to buffer it yourself, and process it until you have a complete "message" built up in your buffer before you start looking at it.

      Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

      I 1 Reply Last reply
      0
      • OriginalGriffO OriginalGriff

        ibrahimayhans wrote:

        SerialPort.ReadExisting () Returns an Incomplete Result.

        Well, yes. It will. Serial data is called that because data arrives one bit at a time - a serial stream of data. When seven or eight data bits have been received (together with all appropriate framing characters such as start, stop, and parity bits) the resulkting byte is passed to the input buffer, and the hardware notifies Windows that it is ready. Windows then reads the buffer content, adds it to an internal circular queue, and sends a message to your app which is translated into a DataReceived event. You handler then gets called and reads the data, however much of it there is. Subsequent bytes cause the same process to occur. You do not get a "I've got all the data" event, you get an "I've got at least one character for you" event instead. If you want to receive the whole message, then you need to buffer it yourself, and process it until you have a complete "message" built up in your buffer before you start looking at it.

        Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

        I Offline
        I Offline
        ibrahimayhans
        wrote on last edited by
        #6

        I understand State But I am in contact with Producer Company in reply to the query sent in one time 41 byte length is required to be delivered in the value. What Should I Do to Receive 41 Bytes of Data at a Time? Also, SerialPort.Read (byte [] buffer, int, int); Can such an operation be done with this method?

        OriginalGriffO 1 Reply Last reply
        0
        • I ibrahimayhans

          I understand State But I am in contact with Producer Company in reply to the query sent in one time 41 byte length is required to be delivered in the value. What Should I Do to Receive 41 Bytes of Data at a Time? Also, SerialPort.Read (byte [] buffer, int, int); Can such an operation be done with this method?

          OriginalGriffO Offline
          OriginalGriffO Offline
          OriginalGriff
          wrote on last edited by
          #7

          You have to buffer them. You will get upto 41 events - you cannot guarantee exactly how many, it depends on what else is going on in your system.

          Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

          "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
          "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

          I 2 Replies Last reply
          0
          • OriginalGriffO OriginalGriff

            You have to buffer them. You will get upto 41 events - you cannot guarantee exactly how many, it depends on what else is going on in your system.

            Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

            I Offline
            I Offline
            ibrahimayhans
            wrote on last edited by
            #8

            I did not fully understand the Buffering Scheme or I could not. Can I send me the edit code on the code I share in the Read operation?

            OriginalGriffO 1 Reply Last reply
            0
            • OriginalGriffO OriginalGriff

              You have to buffer them. You will get upto 41 events - you cannot guarantee exactly how many, it depends on what else is going on in your system.

              Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

              I Offline
              I Offline
              ibrahimayhans
              wrote on last edited by
              #9

              The Producer Company Specially Says 41-Byte Data Future.

              1 Reply Last reply
              0
              • I ibrahimayhans

                Hello, When we contact with the manufacturer company, we inform you as the status on the screen of the device after Char Characters we send. When the Status Letter arrives, the values are sent correctly. After this, SerialPort.Read as specified in the company's total length of 41 bytes is required. SerialPort.ReadExisting () Returns an Incomplete Result. Features SerialPort.Read Read.

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #10

                So you just need to keep reading until you have all the data. As OriginalGriff points out below, the data does not all arrive at once.

                I 1 Reply Last reply
                0
                • I ibrahimayhans

                  I did not fully understand the Buffering Scheme or I could not. Can I send me the edit code on the code I share in the Read operation?

                  OriginalGriffO Offline
                  OriginalGriffO Offline
                  OriginalGriff
                  wrote on last edited by
                  #11

                  No - we aren't here to do all your work for you. If you don't know what you are doing - and it doesn't sound like you have any idea about communications - then you need to start reading and learn, because this is the really easy stuff! If you don't understand what is happening here, nothing else about this job will make any sense, and I will end up doing it all for you. And trust me, I'd have to charge you for doing your work for you! :laugh:

                  Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                  "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                  "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                  I 1 Reply Last reply
                  0
                  • L Lost User

                    So you just need to keep reading until you have all the data. As OriginalGriff points out below, the data does not all arrive at once.

                    I Offline
                    I Offline
                    ibrahimayhans
                    wrote on last edited by
                    #12

                    Only the manufacturer of 41 bytes will deliver the future in a single time. If it does not come in one go as you have stated, how can I get it in the order of the results? So how do I get to 8 + 8 + 8 + 8 in order of incoming results?

                    L 1 Reply Last reply
                    0
                    • OriginalGriffO OriginalGriff

                      No - we aren't here to do all your work for you. If you don't know what you are doing - and it doesn't sound like you have any idea about communications - then you need to start reading and learn, because this is the really easy stuff! If you don't understand what is happening here, nothing else about this job will make any sense, and I will end up doing it all for you. And trust me, I'd have to charge you for doing your work for you! :laugh:

                      Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                      I Offline
                      I Offline
                      ibrahimayhans
                      wrote on last edited by
                      #13

                      :) In this case you are right, I've searched too much But I did not do what I did, I believe that if I can at least understand the logic of this, I will be able to do so without any problem. On the Yinede You Are So Glad to Help Me in This Concern?

                      OriginalGriffO 1 Reply Last reply
                      0
                      • I ibrahimayhans

                        :) In this case you are right, I've searched too much But I did not do what I did, I believe that if I can at least understand the logic of this, I will be able to do so without any problem. On the Yinede You Are So Glad to Help Me in This Concern?

                        OriginalGriffO Offline
                        OriginalGriffO Offline
                        OriginalGriff
                        wrote on last edited by
                        #14

                        Stop "searching for the solution" and start reading up on how it all works - this is stuff you need to know in order to work with comms effectively.

                        Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                        "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                        1 Reply Last reply
                        0
                        • I ibrahimayhans

                          Hello, I would like to ask you to share information on a subject, I am experiencing a problem related to data transmission and data retrieval on an Indicator device connected to a serial port on a project I am developing. Code I Write For Trial Purpose As Below, SerialPortTLB_DataReceived Event Overflow Should Not Send on Textbox as Byte, How can I print the incoming data as Bytes? I'm Waiting For You About This Issue, Good Work ...

                          using DevComponents.DotNetBar.Metro;
                          using System;
                          using System.Windows.Forms;

                          namespace VeriOkuma
                          {
                          public partial class VeriOkuma : MetroForm
                          {
                          public VeriOkuma()
                          {
                          InitializeComponent();
                          }

                              private void BTNVeriGonder\_Click(object sender, EventArgs e)
                              {
                                  if (!SerialPortTLB.IsOpen)
                                      SerialPortTLB.Open();
                                  SerialPortTLB.Write(System.Convert.ToChar(2).ToString() + System.Convert.ToChar(1).ToString() + "DNG" + System.Convert.ToChar(13).ToString());
                              }
                          
                              private void VeriOkuma\_Load(object sender, EventArgs e)
                              {
                                  if (SerialPortTLB.IsOpen)
                                  {
                                      SerialPortTLB.Close();
                                  }
                              }
                          
                              private void SerialPortTLB\_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
                              {
                                  if (!SerialPortTLB.IsOpen) SerialPortTLB.Open();
                                  TXBGelenVeri.Text = SerialPortTLB.ReadExisting();
                                  SerialPortTLB.Close();
                              }
                          }
                          

                          }

                          L Offline
                          L Offline
                          Lost User
                          wrote on last edited by
                          #15

                          Control.CheckForIllegalCrossThreadCalls = false; Why? :((

                          Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^] "If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.

                          I 1 Reply Last reply
                          0
                          • L Lost User

                            Control.CheckForIllegalCrossThreadCalls = false; Why? :((

                            Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^] "If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.

                            I Offline
                            I Offline
                            ibrahimayhans
                            wrote on last edited by
                            #16

                            I have used the Thread Function, and now Delete

                            OriginalGriffO 1 Reply Last reply
                            0
                            • I ibrahimayhans

                              Only the manufacturer of 41 bytes will deliver the future in a single time. If it does not come in one go as you have stated, how can I get it in the order of the results? So how do I get to 8 + 8 + 8 + 8 in order of incoming results?

                              L Offline
                              L Offline
                              Lost User
                              wrote on last edited by
                              #17

                              Serial devices present their data in "chunks", and each chunk may be anything from a single byte to a complete message. This is a feature of serial IO that the programmer needs to understand and deal with. Your input routine needs to capture however much data is presented each time, and build the message buffer by appending the latest 'chunk' to whatever has already been read in. When you are certain that you have all the available data you can go and process it. If the manufacturer tells you that you will receive 41 bytes, then you must keep reading until your message has received that number of bytes.

                              I 1 Reply Last reply
                              0
                              • L Lost User

                                Serial devices present their data in "chunks", and each chunk may be anything from a single byte to a complete message. This is a feature of serial IO that the programmer needs to understand and deal with. Your input routine needs to capture however much data is presented each time, and build the message buffer by appending the latest 'chunk' to whatever has already been read in. When you are certain that you have all the available data you can go and process it. If the manufacturer tells you that you will receive 41 bytes, then you must keep reading until your message has received that number of bytes.

                                I Offline
                                I Offline
                                ibrahimayhans
                                wrote on last edited by
                                #18

                                The Problem I'm Having Problem With, What's The Value 8 Bytes Coming Up and How Can I Keep Reading the Restored Values? How Do I Write a Code?

                                L 1 Reply Last reply
                                0
                                • I ibrahimayhans

                                  I have used the Thread Function, and now Delete

                                  OriginalGriffO Offline
                                  OriginalGriffO Offline
                                  OriginalGriff
                                  wrote on last edited by
                                  #19

                                  Doesn't matter - the DataReceived event is never fired on the UI thread, so you will get an cross thread exception anyway. See what I mean about needing to know this stuff?

                                  Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                                  "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                                  "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                                  1 Reply Last reply
                                  0
                                  • I ibrahimayhans

                                    The Problem I'm Having Problem With, What's The Value 8 Bytes Coming Up and How Can I Keep Reading the Restored Values? How Do I Write a Code?

                                    L Offline
                                    L Offline
                                    Lost User
                                    wrote on last edited by
                                    #20

                                    ibrahimayhans wrote:

                                    How Do I Write a Code?

                                    First you need to understand the problem.

                                    Set an index to the start of your receive buffer
                                    Do
                                    Read some data using the index to position it at the correct point in the buffer
                                    Add the count of bytes read to the offset index
                                    While index < 41
                                    // when the index reaches 41 you have all the data (bytes 0 to 40)

                                    1 Reply Last reply
                                    0
                                    • I ibrahimayhans

                                      Hello, I would like to ask you to share information on a subject, I am experiencing a problem related to data transmission and data retrieval on an Indicator device connected to a serial port on a project I am developing. Code I Write For Trial Purpose As Below, SerialPortTLB_DataReceived Event Overflow Should Not Send on Textbox as Byte, How can I print the incoming data as Bytes? I'm Waiting For You About This Issue, Good Work ...

                                      using DevComponents.DotNetBar.Metro;
                                      using System;
                                      using System.Windows.Forms;

                                      namespace VeriOkuma
                                      {
                                      public partial class VeriOkuma : MetroForm
                                      {
                                      public VeriOkuma()
                                      {
                                      InitializeComponent();
                                      }

                                          private void BTNVeriGonder\_Click(object sender, EventArgs e)
                                          {
                                              if (!SerialPortTLB.IsOpen)
                                                  SerialPortTLB.Open();
                                              SerialPortTLB.Write(System.Convert.ToChar(2).ToString() + System.Convert.ToChar(1).ToString() + "DNG" + System.Convert.ToChar(13).ToString());
                                          }
                                      
                                          private void VeriOkuma\_Load(object sender, EventArgs e)
                                          {
                                              if (SerialPortTLB.IsOpen)
                                              {
                                                  SerialPortTLB.Close();
                                              }
                                          }
                                      
                                          private void SerialPortTLB\_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
                                          {
                                              if (!SerialPortTLB.IsOpen) SerialPortTLB.Open();
                                              TXBGelenVeri.Text = SerialPortTLB.ReadExisting();
                                              SerialPortTLB.Close();
                                          }
                                      }
                                      

                                      }

                                      L Offline
                                      L Offline
                                      Luc Pattyn
                                      wrote on last edited by
                                      #21

                                      Hi, serial communication can be very hard, and it can be quite easy; it all depends on circumstances: how high the transmission rate is, how big the gap is in between messages, etc. Here are three pointers, assuming the peripheral uses printable text: 1. Always use a terminal emulator to get acquainted with your peripheral's behavior. It will help you in checking the hardware aspects and overall settings of your port, and it will help you in understanding the message flow. 2. the DataReceived event fires whenever it wants, which could be after receiving 1 byte, or 39 bytes, or whatever. It does not care about what you expect as a message, it only knows about individual bytes and several levels of buffering inside Windows. As a result it isn't very useful except in simple cases: If your messages are far apart, which gives you some time to waste, the easiest approach is to get started by the DataReceived event, then wait (with Thread.Sleep) sufficiently long so the entire message should be received by now, and then use ReadExisting. The required delay equals maximum string length * character time, which obviously depends on the baud rate used (say 1 msec at 9600 baud). Warning: Windows timing isn't always very accurate, so add a spare 20 msec or so. 3. The DataReceived event gets handled on an arbitrary thread (actually one from the ThreadPool) but absolutely NOT on the GUI thread (read more: Asynchronous operations run on ThreadPool threads[^]); therefore, you are not allowed to touch any of your GUI Controls inside the DataReceived handler. The proper solution is by using Control.InvokeRequired and Control.Invoke (read more: Invalid cross-thread operations[^]). NEVER use Control.CheckForIllegalCrossThreadCalls In more complex situations I tend to avoid the DataReceived event, instead I'd use an explicit Thread and perform blocking reads and a buffering scheme. Sometimes a BackgroundWokrer can do the job. Hope this helps. :) PS: Don't trust the default settings of SerialPort, always explicitly set properties such as Encoding, NewLine, etc.

                                      1 Reply Last reply
                                      0
                                      Reply
                                      • Reply as topic
                                      Log in to reply
                                      • Oldest to Newest
                                      • Newest to Oldest
                                      • Most Votes


                                      • Login

                                      • Don't have an account? Register

                                      • Login or register to search.
                                      • First post
                                        Last post
                                      0
                                      • Categories
                                      • Recent
                                      • Tags
                                      • Popular
                                      • World
                                      • Users
                                      • Groups