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