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. serial port writing and reading

serial port writing and reading

Scheduled Pinned Locked Moved C#
database
16 Posts 2 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.
  • K Offline
    K Offline
    khomeyni
    wrote on last edited by
    #1

    I've created a program to send data to a serial port(rs 232,sr 485) every 3 millisecond . and receiving data on the other port. sending works fine but receiving is not logical,see results at the end of this post. codes:

    int _counter = 0;
    public delegate void TimerEventHandler(UInt32 id, UInt32 msg, ref UInt32 userCtx, UInt32 rsv1, UInt32 rsv2);

        \[DllImport("winmm.dll", SetLastError = true, EntryPoint = "timeSetEvent")\]
        static extern UInt32 timeSetEvent(UInt32 msDelay, UInt32 msResolution, TimerEventHandler handler, ref UInt32 userCtx, UInt32 eventType);
    
        \[DllImport("winmm.dll", SetLastError = true)\]
        static extern void timeKillEvent(UInt32 uTimerID);
    
        TimerEventHandler tim;//TimerEventHandler tim = new TimerEventHandler(this.Link);
        public void Link(UInt32 id, UInt32 msg, ref UInt32 userCtx, UInt32 rsv1, UInt32 rsv2)
        {
            \_counter++;
            if ((\_counter % interval) == 0) //if ((\_counter % 10) == 0)
            {
                timer\_Elapsed3();
            }
            if (\_counter > 1000.0\*EndTime)//if (\_counter>EndTime / interval)
            {
                Stop();//timekillevent must be called in Stop
            }
        }
        #endregion 
        public void StartSendingLocations()
        {
            EndIndex = setEndIndex();
            if (port==null)
            {
                port = new SerialPort(portName, rate);
                reader.port = new SerialPort("COM4", rate);//rate is 115200
                reader.port.Open();
    
                writer.port = port;
                if (!port.IsOpen)
                {
                    port.Open();
                }
                reader.mythread.Start();
            }
            tim = new TimerEventHandler(this.Link);
            uint rsv = 0;
            timerId = timeSetEvent(1, 1, tim, ref rsv, 1);
        }
    

    and timerElapsed3:

    void timer_Elapsed3()
    {
    Index++;
    ConstructSignal();
    CreateCommand();
    writer.SendCommand(port, command);

            if (IsChartEnabled)
            {
                 SignalWriter\_DataSent(writer.WSignal);
            }
        
            if (SentFileLogger==null)
            {
                return;
            }
            SentFileLogger.Write(true, writer.WSignal.PitchLocation, writer.WSignal.PitchAngularVelocity,
                writer.WSignal.RollLocation, writer.WSignal.Ro
    
    Richard Andrew x64R 1 Reply Last reply
    0
    • K khomeyni

      I've created a program to send data to a serial port(rs 232,sr 485) every 3 millisecond . and receiving data on the other port. sending works fine but receiving is not logical,see results at the end of this post. codes:

      int _counter = 0;
      public delegate void TimerEventHandler(UInt32 id, UInt32 msg, ref UInt32 userCtx, UInt32 rsv1, UInt32 rsv2);

          \[DllImport("winmm.dll", SetLastError = true, EntryPoint = "timeSetEvent")\]
          static extern UInt32 timeSetEvent(UInt32 msDelay, UInt32 msResolution, TimerEventHandler handler, ref UInt32 userCtx, UInt32 eventType);
      
          \[DllImport("winmm.dll", SetLastError = true)\]
          static extern void timeKillEvent(UInt32 uTimerID);
      
          TimerEventHandler tim;//TimerEventHandler tim = new TimerEventHandler(this.Link);
          public void Link(UInt32 id, UInt32 msg, ref UInt32 userCtx, UInt32 rsv1, UInt32 rsv2)
          {
              \_counter++;
              if ((\_counter % interval) == 0) //if ((\_counter % 10) == 0)
              {
                  timer\_Elapsed3();
              }
              if (\_counter > 1000.0\*EndTime)//if (\_counter>EndTime / interval)
              {
                  Stop();//timekillevent must be called in Stop
              }
          }
          #endregion 
          public void StartSendingLocations()
          {
              EndIndex = setEndIndex();
              if (port==null)
              {
                  port = new SerialPort(portName, rate);
                  reader.port = new SerialPort("COM4", rate);//rate is 115200
                  reader.port.Open();
      
                  writer.port = port;
                  if (!port.IsOpen)
                  {
                      port.Open();
                  }
                  reader.mythread.Start();
              }
              tim = new TimerEventHandler(this.Link);
              uint rsv = 0;
              timerId = timeSetEvent(1, 1, tim, ref rsv, 1);
          }
      

      and timerElapsed3:

      void timer_Elapsed3()
      {
      Index++;
      ConstructSignal();
      CreateCommand();
      writer.SendCommand(port, command);

              if (IsChartEnabled)
              {
                   SignalWriter\_DataSent(writer.WSignal);
              }
          
              if (SentFileLogger==null)
              {
                  return;
              }
              SentFileLogger.Write(true, writer.WSignal.PitchLocation, writer.WSignal.PitchAngularVelocity,
                  writer.WSignal.RollLocation, writer.WSignal.Ro
      
      Richard Andrew x64R Offline
      Richard Andrew x64R Offline
      Richard Andrew x64
      wrote on last edited by
      #2

      I assume you mean that the data received is what is sent on the other COM port. The DataReceived function is invoked any time there is data available, not just when the data is complete. So it is conceivable that it could be raised after each byte is received, hence the greater frequency.

      The difficult we do right away... ...the impossible takes slightly longer.

      K 1 Reply Last reply
      0
      • Richard Andrew x64R Richard Andrew x64

        I assume you mean that the data received is what is sent on the other COM port. The DataReceived function is invoked any time there is data available, not just when the data is complete. So it is conceivable that it could be raised after each byte is received, hence the greater frequency.

        The difficult we do right away... ...the impossible takes slightly longer.

        K Offline
        K Offline
        khomeyni
        wrote on last edited by
        #3

        yes . the data received is what is sent on the other COM port.

        Quote:

        The DataReceived function is invoked any time there is data available, not just when the data is complete. So it is conceivable that it could be raised after each byte is received, hence the greater frequency.

        so how can I change it to be raised every 3 millisecond? I want to create a match between sending and receiving. for example when I depict the chart of both send and receive in realtime, for comparison of data ,the data must be matched.

        Richard Andrew x64R 2 Replies Last reply
        0
        • K khomeyni

          yes . the data received is what is sent on the other COM port.

          Quote:

          The DataReceived function is invoked any time there is data available, not just when the data is complete. So it is conceivable that it could be raised after each byte is received, hence the greater frequency.

          so how can I change it to be raised every 3 millisecond? I want to create a match between sending and receiving. for example when I depict the chart of both send and receive in realtime, for comparison of data ,the data must be matched.

          Richard Andrew x64R Offline
          Richard Andrew x64R Offline
          Richard Andrew x64
          wrote on last edited by
          #4

          One thing you could try is to read from the port using the ReadLine function. This only returns after it reads a newline sequence. Then, in your send function, use the WriteLine function, which will append a newline sequence to each packet. If this does not suit your requirements, then you'll have to implement your own stream scheme to buffer the received data until it is complete, and only then process it.

          The difficult we do right away... ...the impossible takes slightly longer.

          1 Reply Last reply
          0
          • K khomeyni

            yes . the data received is what is sent on the other COM port.

            Quote:

            The DataReceived function is invoked any time there is data available, not just when the data is complete. So it is conceivable that it could be raised after each byte is received, hence the greater frequency.

            so how can I change it to be raised every 3 millisecond? I want to create a match between sending and receiving. for example when I depict the chart of both send and receive in realtime, for comparison of data ,the data must be matched.

            Richard Andrew x64R Offline
            Richard Andrew x64R Offline
            Richard Andrew x64
            wrote on last edited by
            #5

            I just wanted to also mention, you can wrap the SerialPort class in a Stream [^]class to make it easier to read and write.

            The difficult we do right away... ...the impossible takes slightly longer.

            K 1 Reply Last reply
            0
            • Richard Andrew x64R Richard Andrew x64

              I just wanted to also mention, you can wrap the SerialPort class in a Stream [^]class to make it easier to read and write.

              The difficult we do right away... ...the impossible takes slightly longer.

              K Offline
              K Offline
              khomeyni
              wrote on last edited by
              #6

              another problem I've with this code and writing to port: when I see the data which I'm sending in Comwizard ,sometimes I see an interrupt in the data received by comwizard. it is randomly and when I increase the frequency of sending(3 ms to 10ms ...) it appears in longer time and less than before. I checked all things but I cannot find any mistake in my code . is it possible to be relative to serial port class and functions of c#?can you suggest what is the mistake?

              Richard Andrew x64R 1 Reply Last reply
              0
              • K khomeyni

                another problem I've with this code and writing to port: when I see the data which I'm sending in Comwizard ,sometimes I see an interrupt in the data received by comwizard. it is randomly and when I increase the frequency of sending(3 ms to 10ms ...) it appears in longer time and less than before. I checked all things but I cannot find any mistake in my code . is it possible to be relative to serial port class and functions of c#?can you suggest what is the mistake?

                Richard Andrew x64R Offline
                Richard Andrew x64R Offline
                Richard Andrew x64
                wrote on last edited by
                #7

                When you say you increase the frequency from 3ms to 10ms, I don't understand because that sounds like you are decreasing the frequency?

                The difficult we do right away... ...the impossible takes slightly longer.

                K 1 Reply Last reply
                0
                • Richard Andrew x64R Richard Andrew x64

                  When you say you increase the frequency from 3ms to 10ms, I don't understand because that sounds like you are decreasing the frequency?

                  The difficult we do right away... ...the impossible takes slightly longer.

                  K Offline
                  K Offline
                  khomeyni
                  wrote on last edited by
                  #8

                  yes . excuse me. I'm decreasing it. and this is the code for reading bytes:

                  public void ThreadMain()
                  {
                  int i = 0;
                  while (port.IsOpen)//while (port != null && port.IsOpen)
                  {
                  try
                  {
                  var b1 = port.ReadByte();

                                  if (b1 == ReadSignal.STARTByte)
                                  {
                                      //read  location 
                                      b1 = port.ReadByte();
                                      ...
                                      if (b1 == ReadSignal.STOPByte)
                                      {
                  
                                              RSignal.isValid = true;
                                      }
                  
                                  }
                                  if (RSignal.isValid)
                                  {
                                      RSignal.ExtractLocatoins();
                                      if (DataReceived != null)
                                          DataReceived.Invoke(RSignal);
                                  }
                              }
                              catch (Exception ex)
                              {
                                  //MessageBox.Show("1:"+ex.ToString()); 
                              }
                          }
                      }
                  

                  and code for writing:

                  public void SendCommand(SerialPort port,byte[] command)//public void SendCommand(byte[] command)
                  {

                          if (port != null && port.IsOpen)
                          {
                             port.Write(command, 0, command.Length);
                          }
                          else
                          {
                              MessageBox.Show("port is not open!");
                          }
                      }
                  
                  Richard Andrew x64R 2 Replies Last reply
                  0
                  • K khomeyni

                    yes . excuse me. I'm decreasing it. and this is the code for reading bytes:

                    public void ThreadMain()
                    {
                    int i = 0;
                    while (port.IsOpen)//while (port != null && port.IsOpen)
                    {
                    try
                    {
                    var b1 = port.ReadByte();

                                    if (b1 == ReadSignal.STARTByte)
                                    {
                                        //read  location 
                                        b1 = port.ReadByte();
                                        ...
                                        if (b1 == ReadSignal.STOPByte)
                                        {
                    
                                                RSignal.isValid = true;
                                        }
                    
                                    }
                                    if (RSignal.isValid)
                                    {
                                        RSignal.ExtractLocatoins();
                                        if (DataReceived != null)
                                            DataReceived.Invoke(RSignal);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    //MessageBox.Show("1:"+ex.ToString()); 
                                }
                            }
                        }
                    

                    and code for writing:

                    public void SendCommand(SerialPort port,byte[] command)//public void SendCommand(byte[] command)
                    {

                            if (port != null && port.IsOpen)
                            {
                               port.Write(command, 0, command.Length);
                            }
                            else
                            {
                                MessageBox.Show("port is not open!");
                            }
                        }
                    
                    Richard Andrew x64R Offline
                    Richard Andrew x64R Offline
                    Richard Andrew x64
                    wrote on last edited by
                    #9

                    Are you using the ReadLine and Writeline functions? It may be that Comwizard is not waiting for the newline sequence to return the data it sees? Even though there is an interrupt in the data, does the full data come through eventually?

                    The difficult we do right away... ...the impossible takes slightly longer.

                    K 1 Reply Last reply
                    0
                    • Richard Andrew x64R Richard Andrew x64

                      Are you using the ReadLine and Writeline functions? It may be that Comwizard is not waiting for the newline sequence to return the data it sees? Even though there is an interrupt in the data, does the full data come through eventually?

                      The difficult we do right away... ...the impossible takes slightly longer.

                      K Offline
                      K Offline
                      khomeyni
                      wrote on last edited by
                      #10

                      see above edited post. yes data comes eventually.

                      1 Reply Last reply
                      0
                      • K khomeyni

                        yes . excuse me. I'm decreasing it. and this is the code for reading bytes:

                        public void ThreadMain()
                        {
                        int i = 0;
                        while (port.IsOpen)//while (port != null && port.IsOpen)
                        {
                        try
                        {
                        var b1 = port.ReadByte();

                                        if (b1 == ReadSignal.STARTByte)
                                        {
                                            //read  location 
                                            b1 = port.ReadByte();
                                            ...
                                            if (b1 == ReadSignal.STOPByte)
                                            {
                        
                                                    RSignal.isValid = true;
                                            }
                        
                                        }
                                        if (RSignal.isValid)
                                        {
                                            RSignal.ExtractLocatoins();
                                            if (DataReceived != null)
                                                DataReceived.Invoke(RSignal);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        //MessageBox.Show("1:"+ex.ToString()); 
                                    }
                                }
                            }
                        

                        and code for writing:

                        public void SendCommand(SerialPort port,byte[] command)//public void SendCommand(byte[] command)
                        {

                                if (port != null && port.IsOpen)
                                {
                                   port.Write(command, 0, command.Length);
                                }
                                else
                                {
                                    MessageBox.Show("port is not open!");
                                }
                            }
                        
                        Richard Andrew x64R Offline
                        Richard Andrew x64R Offline
                        Richard Andrew x64
                        wrote on last edited by
                        #11

                        Check my comments in the code below:

                        public void ThreadMain()
                        {
                        int i = 0;
                        while (port.IsOpen)
                        {
                        try
                        {
                        var b1 = port.ReadByte(); // <<==What if the STOPByte is read here? Does that confuse the logic?

                                        if (b1 == ReadSignal.STARTByte)
                                        {
                                            //read  location
                                            b1 = port.ReadByte();
                                            ...
                                            if (b1 == ReadSignal.STOPByte)
                                            {
                        
                                                    RSignal.isValid = true;
                                            }
                        
                                        }
                                        if (RSignal.isValid)
                                        {
                                            RSignal.ExtractLocatoins();
                                            if (DataReceived != null)
                                                DataReceived.Invoke(RSignal);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        //MessageBox.Show("1:"+ex.ToString());
                                    }
                                }
                            }
                        

                        The difficult we do right away... ...the impossible takes slightly longer.

                        K 1 Reply Last reply
                        0
                        • Richard Andrew x64R Richard Andrew x64

                          Check my comments in the code below:

                          public void ThreadMain()
                          {
                          int i = 0;
                          while (port.IsOpen)
                          {
                          try
                          {
                          var b1 = port.ReadByte(); // <<==What if the STOPByte is read here? Does that confuse the logic?

                                          if (b1 == ReadSignal.STARTByte)
                                          {
                                              //read  location
                                              b1 = port.ReadByte();
                                              ...
                                              if (b1 == ReadSignal.STOPByte)
                                              {
                          
                                                      RSignal.isValid = true;
                                              }
                          
                                          }
                                          if (RSignal.isValid)
                                          {
                                              RSignal.ExtractLocatoins();
                                              if (DataReceived != null)
                                                  DataReceived.Invoke(RSignal);
                                          }
                                      }
                                      catch (Exception ex)
                                      {
                                          //MessageBox.Show("1:"+ex.ToString());
                                      }
                                  }
                              }
                          

                          The difficult we do right away... ...the impossible takes slightly longer.

                          K Offline
                          K Offline
                          khomeyni
                          wrote on last edited by
                          #12

                          if the STOPByte is read there just poor out the data until new pack of correct data comes.(until STARTByte be found). also notice that I'm sending data in turn so if one pack of data is received then if no noise all data packs can be received in turn.

                          Richard Andrew x64R 1 Reply Last reply
                          0
                          • K khomeyni

                            if the STOPByte is read there just poor out the data until new pack of correct data comes.(until STARTByte be found). also notice that I'm sending data in turn so if one pack of data is received then if no noise all data packs can be received in turn.

                            Richard Andrew x64R Offline
                            Richard Andrew x64R Offline
                            Richard Andrew x64
                            wrote on last edited by
                            #13

                            Yes you are right. If the full data comes eventually, then maybe there is no problem at all.

                            The difficult we do right away... ...the impossible takes slightly longer.

                            K 2 Replies Last reply
                            0
                            • Richard Andrew x64R Richard Andrew x64

                              Yes you are right. If the full data comes eventually, then maybe there is no problem at all.

                              The difficult we do right away... ...the impossible takes slightly longer.

                              K Offline
                              K Offline
                              khomeyni
                              wrote on last edited by
                              #14

                              so what is the cause of the interrupt? is it relative to system(pc) or to serial port or my code? the interrupt (not sending data for some millisecond) can be seen by comwizard , also I must send data for a motor and also the motor shows such interrupt.

                              Richard Andrew x64R 1 Reply Last reply
                              0
                              • Richard Andrew x64R Richard Andrew x64

                                Yes you are right. If the full data comes eventually, then maybe there is no problem at all.

                                The difficult we do right away... ...the impossible takes slightly longer.

                                K Offline
                                K Offline
                                khomeyni
                                wrote on last edited by
                                #15

                                yes. I' work around. Richard Andrew x64,thanks for your attentions.

                                1 Reply Last reply
                                0
                                • K khomeyni

                                  so what is the cause of the interrupt? is it relative to system(pc) or to serial port or my code? the interrupt (not sending data for some millisecond) can be seen by comwizard , also I must send data for a motor and also the motor shows such interrupt.

                                  Richard Andrew x64R Offline
                                  Richard Andrew x64R Offline
                                  Richard Andrew x64
                                  wrote on last edited by
                                  #16

                                  I'm sorry, I do not know. Are you sure your send data is full every time? I'm not there, so I can't see everything you see.

                                  The difficult we do right away... ...the impossible takes slightly longer.

                                  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