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. Help with serial data display

Help with serial data display

Scheduled Pinned Locked Moved C#
csharphelptutorialquestion
25 Posts 10 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.
  • OriginalGriffO OriginalGriff

    The first thing which springs to mind is: Don't read the text into a string and invoke a routine to handle it. The only logical reason for doing that is to get the execution onto the GUI thread - which may not execute it immediately. If a single other character arrives in the mean time, it will discard your existing data. Better to get the data in the invoked method instead, or add it to a queue (my preference). Regarding your problem with new lines: Are you sure you are receiving them? Remember that ReadExisting translates according tgo the encoding (Strings are generally Unicode, serial ports are generally ASCII). I would be tempted to either try using ReadLine instead of ReadExisting, or ReadAllBytes and display the data as Hex, at least in the early stages. I also wouldn't want to use a TextBox - a ListBox might be better as it doesn't slow down lots when the strings start to get large.

    Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together.

    T Offline
    T Offline
    turbosupramk3
    wrote on last edited by
    #6

    Hi OG, What do you think about using a rich text box? That would be ideal for me. I do have to preface this that I am new to c# and o.o and changing parameters around sometimes FUBARs everything because I'm new. I am sure I am receiving the (13) because I have a barebones serial reader application that can read them correctly. With this statement "Don't read the text into a string and invoke a routine to handle it. The only logical reason for doing that is to get the execution onto the GUI thread - which may not execute it immediately." How would I add it to a queue, I'm hoping that the data will stream up to the data rate speed without issue. When it is going across the screen it does not appear to be missing bits in the string I am sending.

    OriginalGriffO 1 Reply Last reply
    0
    • T turbosupramk3

      I am trying to read serial data from a microchip. Using the simple serial c# project I am able to read the characters being sent, but I am not able to delineate carriage returns and so the correct data will stream across the screen until the programs input box end and then it will wrap around to the next line and continue to stream, an example would be

      seveneightnineteneleventwelvethirteen
      fourteenfifteensixteenseventeeneighteen

      instead of

      seven
      eight
      nine
      ten
      eleven
      twelve
      thirteen
      fourteen
      fifteen
      sixteen
      seventeen
      eighteen

      Does anyone know how I can recognize the carriage returns? They should come through as an ascii character "13" and the serial data protocol is 8 databits no paraty one stopbit (8N1) at a baudrate between 9600 and 115200 baud. Thanks!

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

      In .NET a new line is triggered by a LF (0x10) or "\n", a preceeding CR (0x13) is optional. Most other systems react on CR and tolerate an optional LF. If your microprocessor isn't sending any LF then all data will be on a continuous line by default. There are many ways to remedy that, here is one you may like: 1. tell your serial port you want LF as NewLine indicator, by setting mySerialPort.NewLine="\r"; 2. now read text lines using mySerialPort.ReadLine() Furthermore, I would avoid the DataReceived event in this case; I'd rather have an explicit thread performing ReadLine() in a loop, and invoking the Control that is going to process it right away. I agree with Griff a ListBox is more suited for long, line-oriented texts; I must add going from a TextBox to a RichTextBox is a step backward, performance wise. It too holds all text in one big string internally (even when you use the AppendText method, which is better than Text=Text+newText). :)

      Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

      Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

      T 2 Replies Last reply
      0
      • L Luc Pattyn

        In .NET a new line is triggered by a LF (0x10) or "\n", a preceeding CR (0x13) is optional. Most other systems react on CR and tolerate an optional LF. If your microprocessor isn't sending any LF then all data will be on a continuous line by default. There are many ways to remedy that, here is one you may like: 1. tell your serial port you want LF as NewLine indicator, by setting mySerialPort.NewLine="\r"; 2. now read text lines using mySerialPort.ReadLine() Furthermore, I would avoid the DataReceived event in this case; I'd rather have an explicit thread performing ReadLine() in a loop, and invoking the Control that is going to process it right away. I agree with Griff a ListBox is more suited for long, line-oriented texts; I must add going from a TextBox to a RichTextBox is a step backward, performance wise. It too holds all text in one big string internally (even when you use the AppendText method, which is better than Text=Text+newText). :)

        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

        Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

        T Offline
        T Offline
        turbosupramk3
        wrote on last edited by
        #8

        Thanks for the reply Luc I will try to get this up and running tonight per your instructions, I thought rich text would be good because of the ability to color format things, but maybe not. Speed would be up to 20 mips per second max, slower than that in reality, probably more like 1 mips in reality. I will setup the newline/readline and if I can get that working, setup the listbox. Thanks :)

        L 1 Reply Last reply
        0
        • T turbosupramk3

          Thanks for the reply Luc I will try to get this up and running tonight per your instructions, I thought rich text would be good because of the ability to color format things, but maybe not. Speed would be up to 20 mips per second max, slower than that in reality, probably more like 1 mips in reality. I will setup the newline/readline and if I can get that working, setup the listbox. Thanks :)

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

          If all you need is homogeneous line coloring (say lots of black lines, a few green or red), then that isn't very hard to do with a ListBox. I have an example here[^]. :)

          Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

          Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

          1 Reply Last reply
          0
          • T turbosupramk3

            Hi OG, What do you think about using a rich text box? That would be ideal for me. I do have to preface this that I am new to c# and o.o and changing parameters around sometimes FUBARs everything because I'm new. I am sure I am receiving the (13) because I have a barebones serial reader application that can read them correctly. With this statement "Don't read the text into a string and invoke a routine to handle it. The only logical reason for doing that is to get the execution onto the GUI thread - which may not execute it immediately." How would I add it to a queue, I'm hoping that the data will stream up to the data rate speed without issue. When it is going across the screen it does not appear to be missing bits in the string I am sending.

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

            Luc seems to have covered it all pretty well in his answer - good luck!

            Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together.

            "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
            • L Luc Pattyn

              In .NET a new line is triggered by a LF (0x10) or "\n", a preceeding CR (0x13) is optional. Most other systems react on CR and tolerate an optional LF. If your microprocessor isn't sending any LF then all data will be on a continuous line by default. There are many ways to remedy that, here is one you may like: 1. tell your serial port you want LF as NewLine indicator, by setting mySerialPort.NewLine="\r"; 2. now read text lines using mySerialPort.ReadLine() Furthermore, I would avoid the DataReceived event in this case; I'd rather have an explicit thread performing ReadLine() in a loop, and invoking the Control that is going to process it right away. I agree with Griff a ListBox is more suited for long, line-oriented texts; I must add going from a TextBox to a RichTextBox is a step backward, performance wise. It too holds all text in one big string internally (even when you use the AppendText method, which is better than Text=Text+newText). :)

              Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

              Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

              T Offline
              T Offline
              turbosupramk3
              wrote on last edited by
              #11

              Hi Luc, I tried what you suggested and it still isn't working, its behavior remains unchanged. I also tried sending the serial data as a "(10)" instead of a "(13)" and that did not work either, it actually wouldn't read anything with the 10. Should I try and send a different ascii character or stick with the 13?

              L 1 Reply Last reply
              0
              • T turbosupramk3

                Hi Luc, I tried what you suggested and it still isn't working, its behavior remains unchanged. I also tried sending the serial data as a "(10)" instead of a "(13)" and that did not work either, it actually wouldn't read anything with the 10. Should I try and send a different ascii character or stick with the 13?

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

                I suggest you validate the incoming bytes somehow. I see basically two ways to do that: 1. use a terminal emulator (such as good old HyperTerminal) and see what comes in. 2. better, use SerialPort class in binary mode, basically something along these lines:

                SerialPort port=new SerialPort();
                // take care of opening and port settings
                ...
                // do whatever is needed to have the peripheral send something
                ...
                // wait for enough data to arrive
                Thread.Sleep(5000);
                // read all of it now
                int DIM=300;
                byte[] bytes=new byte[DIM];
                int n=port.Read(bytes,0,DIM);
                for(int i=0; i<n; i++) {
                byte b=bytes[i];
                char c=b;
                log("bytes["+i+"]=0x"+b.ToString("X2")+"="+c);
                }

                where log is a simple logging method, could be:

                public static void log(string s) {
                Console.WriteLine(s);
                }

                :)

                Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

                T 1 Reply Last reply
                0
                • L Luc Pattyn

                  I suggest you validate the incoming bytes somehow. I see basically two ways to do that: 1. use a terminal emulator (such as good old HyperTerminal) and see what comes in. 2. better, use SerialPort class in binary mode, basically something along these lines:

                  SerialPort port=new SerialPort();
                  // take care of opening and port settings
                  ...
                  // do whatever is needed to have the peripheral send something
                  ...
                  // wait for enough data to arrive
                  Thread.Sleep(5000);
                  // read all of it now
                  int DIM=300;
                  byte[] bytes=new byte[DIM];
                  int n=port.Read(bytes,0,DIM);
                  for(int i=0; i<n; i++) {
                  byte b=bytes[i];
                  char c=b;
                  log("bytes["+i+"]=0x"+b.ToString("X2")+"="+c);
                  }

                  where log is a simple logging method, could be:

                  public static void log(string s) {
                  Console.WriteLine(s);
                  }

                  :)

                  Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                  Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

                  T Offline
                  T Offline
                  turbosupramk3
                  wrote on last edited by
                  #13

                  Hi Luc, Here is what it looks like with the OE program, so it is working correctly. There has to be something I'm missing here? < > http://img221.imageshack.us/img221/4316/serialterminal.png[^] Here is my code after all kinds of tweaks or attempts to get this to work, if you'd like anything else just let me know. Thanks!

                  using System;
                  using System.Collections.Generic;
                  using System.ComponentModel;
                  using System.Data;
                  using System.Drawing;
                  using System.Text;
                  using System.Windows.Forms;
                  using System.IO.Ports;

                  namespace SimpleSerial
                  {
                  public partial class Form1 : Form
                  {
                  // Add this variable

                        string RxString;
                        
                        public Form1()
                        {
                            InitializeComponent();
                            string\[\] theSerialPortNames = System.IO.Ports.SerialPort.GetPortNames();
                            /\*MessageBox.Show(theSerialPortNames\[0\]);
                            MessageBox.Show(theSerialPortNames\[1\]);
                            MessageBox.Show(theSerialPortNames\[2\]);
                            MessageBox.Show(theSerialPortNames\[3\]);\*/
                            //MessageBox.Show(theSerialPortNames\[4\]);
                            //MessageBox.Show(theSerialPortNames\[5\]);
                        }
                  
                  
                        private void buttonStart\_Click(object sender, EventArgs e)
                        {
                            serialPort1.PortName = "COM7";
                            serialPort1.BaudRate = 115200;
                            
                            serialPort1.Handshake = Handshake.None;
                            
                  
                  
                            serialPort1.Open();
                            if (serialPort1.IsOpen)
                            {
                                buttonStart.Enabled = false;
                                buttonStop.Enabled = true;
                                textBox1.ReadOnly = false;
                            }
                        }
                  
                        private void buttonStop\_Click(object sender, EventArgs e)
                        {
                            if (serialPort1.IsOpen)
                            {
                                serialPort1.Close();
                                buttonStart.Enabled = true;
                                buttonStop.Enabled = false;
                                textBox1.ReadOnly = true;
                            }
                  
                        }
                  
                        private void Form1\_FormClosing(object sender, FormClosingEventArgs e)
                        {
                            if (serialPort1.IsOpen) serialPort1.Close();
                  
                  L A 2 Replies Last reply
                  0
                  • T turbosupramk3

                    Hi Luc, Here is what it looks like with the OE program, so it is working correctly. There has to be something I'm missing here? < > http://img221.imageshack.us/img221/4316/serialterminal.png[^] Here is my code after all kinds of tweaks or attempts to get this to work, if you'd like anything else just let me know. Thanks!

                    using System;
                    using System.Collections.Generic;
                    using System.ComponentModel;
                    using System.Data;
                    using System.Drawing;
                    using System.Text;
                    using System.Windows.Forms;
                    using System.IO.Ports;

                    namespace SimpleSerial
                    {
                    public partial class Form1 : Form
                    {
                    // Add this variable

                          string RxString;
                          
                          public Form1()
                          {
                              InitializeComponent();
                              string\[\] theSerialPortNames = System.IO.Ports.SerialPort.GetPortNames();
                              /\*MessageBox.Show(theSerialPortNames\[0\]);
                              MessageBox.Show(theSerialPortNames\[1\]);
                              MessageBox.Show(theSerialPortNames\[2\]);
                              MessageBox.Show(theSerialPortNames\[3\]);\*/
                              //MessageBox.Show(theSerialPortNames\[4\]);
                              //MessageBox.Show(theSerialPortNames\[5\]);
                          }
                    
                    
                          private void buttonStart\_Click(object sender, EventArgs e)
                          {
                              serialPort1.PortName = "COM7";
                              serialPort1.BaudRate = 115200;
                              
                              serialPort1.Handshake = Handshake.None;
                              
                    
                    
                              serialPort1.Open();
                              if (serialPort1.IsOpen)
                              {
                                  buttonStart.Enabled = false;
                                  buttonStop.Enabled = true;
                                  textBox1.ReadOnly = false;
                              }
                          }
                    
                          private void buttonStop\_Click(object sender, EventArgs e)
                          {
                              if (serialPort1.IsOpen)
                              {
                                  serialPort1.Close();
                                  buttonStart.Enabled = true;
                                  buttonStop.Enabled = false;
                                  textBox1.ReadOnly = true;
                              }
                    
                          }
                    
                          private void Form1\_FormClosing(object sender, FormClosingEventArgs e)
                          {
                              if (serialPort1.IsOpen) serialPort1.Close();
                    
                    L Offline
                    L Offline
                    Luc Pattyn
                    wrote on last edited by
                    #14

                    Hi, some comments: 1. as your terminal emulator is working, it would be time to try the binary mode I have shown earlier. It has the advantage of (a) showing the exact bytes you're getting, and (b) you're using your own code (as opposed to the terminal emulator). 2. you should set the port's properties right when you open it, and not in its DataReceived handler, i.e. after having gotten some data already. 3.

                    turbosupramk3 wrote:

                    serialPort1.NewLine = "(13)";

                    that is non-sense. You need a CR character, which is represented by \r in C-like languages. cfr my first reply. 4. I wouldn't use a single TextBox for both input and output, at least until everything works well. I also wouldn't spend all that effort in the GUI stuff until such moment that the serial comm is working fine. I think you're getting closer to the solution! :)

                    Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                    Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

                    T 1 Reply Last reply
                    0
                    • T turbosupramk3

                      I am trying to read serial data from a microchip. Using the simple serial c# project I am able to read the characters being sent, but I am not able to delineate carriage returns and so the correct data will stream across the screen until the programs input box end and then it will wrap around to the next line and continue to stream, an example would be

                      seveneightnineteneleventwelvethirteen
                      fourteenfifteensixteenseventeeneighteen

                      instead of

                      seven
                      eight
                      nine
                      ten
                      eleven
                      twelve
                      thirteen
                      fourteen
                      fifteen
                      sixteen
                      seventeen
                      eighteen

                      Does anyone know how I can recognize the carriage returns? They should come through as an ascii character "13" and the serial data protocol is 8 databits no paraty one stopbit (8N1) at a baudrate between 9600 and 115200 baud. Thanks!

                      D Offline
                      D Offline
                      davidwz
                      wrote on last edited by
                      #15

                      Do you wite firmware on microcomputer? try to change 0x0d to (0x0a 0x0d)

                      1 Reply Last reply
                      0
                      • T turbosupramk3

                        Hi, Here is the guts of it

                              private void Form1\_FormClosing(object sender, FormClosingEventArgs e)
                              {
                                  if (serialPort1.IsOpen) serialPort1.Close();
                              }
                        
                              private void textBox1\_KeyPress(object sender, KeyPressEventArgs e)
                              {
                                 
                                  if(!serialPort1.IsOpen) return;
                        
                                  char\[\] buff = new char\[1\];
                        
                                  buff\[0\] = e.KeyChar;
                        
                                  serialPort1.Write(buff, 0, 1);
                        
                                  e.Handled = true;
                              }
                        
                              private void DisplayText(object sender, EventArgs e)
                              {
                                  textBox1.AppendText(RxString);
                                 
                              }
                        
                              private void serialPort1\_DataReceived
                                (object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
                              {
                                  RxString = serialPort1.ReadExisting();
                                  this.Invoke(new EventHandler(DisplayText));
                              }
                        
                        C Offline
                        C Offline
                        ColinBurnell
                        wrote on last edited by
                        #16

                        I suspect your problem is with how ReadExisting() handles the carriage returns; it may well be expecting a carriage return line feed pair of characters, to indicate a new line. If I am using Serial port for text data, I get the data as a byte array; and then convert it to a string, either using Encoding - Encoding.ASCII.GetString(myByteArrray) or manually processing each character if I need to handle specific bytes individually. Off the top of my head, I can't remember if GetString will convert a striaght carriage return to a new line; but if not you can process each byue of the array in turn, detecting the carriage return and adding Environment.NewLine in it's place to the string. Hope this helps.

                        T 1 Reply Last reply
                        0
                        • C ColinBurnell

                          I suspect your problem is with how ReadExisting() handles the carriage returns; it may well be expecting a carriage return line feed pair of characters, to indicate a new line. If I am using Serial port for text data, I get the data as a byte array; and then convert it to a string, either using Encoding - Encoding.ASCII.GetString(myByteArrray) or manually processing each character if I need to handle specific bytes individually. Off the top of my head, I can't remember if GetString will convert a striaght carriage return to a new line; but if not you can process each byue of the array in turn, detecting the carriage return and adding Environment.NewLine in it's place to the string. Hope this helps.

                          T Offline
                          T Offline
                          turbosupramk3
                          wrote on last edited by
                          #17

                          Hi Colin, Maybe I can send it different characters for a line feed ... do you happen to know what pair of characters is it expecting? With the byte array, are you just filling it up with 8 bits, and then at the stop bit converting it to a string?

                          C 1 Reply Last reply
                          0
                          • T turbosupramk3

                            Hi Luc, Here is what it looks like with the OE program, so it is working correctly. There has to be something I'm missing here? < > http://img221.imageshack.us/img221/4316/serialterminal.png[^] Here is my code after all kinds of tweaks or attempts to get this to work, if you'd like anything else just let me know. Thanks!

                            using System;
                            using System.Collections.Generic;
                            using System.ComponentModel;
                            using System.Data;
                            using System.Drawing;
                            using System.Text;
                            using System.Windows.Forms;
                            using System.IO.Ports;

                            namespace SimpleSerial
                            {
                            public partial class Form1 : Form
                            {
                            // Add this variable

                                  string RxString;
                                  
                                  public Form1()
                                  {
                                      InitializeComponent();
                                      string\[\] theSerialPortNames = System.IO.Ports.SerialPort.GetPortNames();
                                      /\*MessageBox.Show(theSerialPortNames\[0\]);
                                      MessageBox.Show(theSerialPortNames\[1\]);
                                      MessageBox.Show(theSerialPortNames\[2\]);
                                      MessageBox.Show(theSerialPortNames\[3\]);\*/
                                      //MessageBox.Show(theSerialPortNames\[4\]);
                                      //MessageBox.Show(theSerialPortNames\[5\]);
                                  }
                            
                            
                                  private void buttonStart\_Click(object sender, EventArgs e)
                                  {
                                      serialPort1.PortName = "COM7";
                                      serialPort1.BaudRate = 115200;
                                      
                                      serialPort1.Handshake = Handshake.None;
                                      
                            
                            
                                      serialPort1.Open();
                                      if (serialPort1.IsOpen)
                                      {
                                          buttonStart.Enabled = false;
                                          buttonStop.Enabled = true;
                                          textBox1.ReadOnly = false;
                                      }
                                  }
                            
                                  private void buttonStop\_Click(object sender, EventArgs e)
                                  {
                                      if (serialPort1.IsOpen)
                                      {
                                          serialPort1.Close();
                                          buttonStart.Enabled = true;
                                          buttonStop.Enabled = false;
                                          textBox1.ReadOnly = true;
                                      }
                            
                                  }
                            
                                  private void Form1\_FormClosing(object sender, FormClosingEventArgs e)
                                  {
                                      if (serialPort1.IsOpen) serialPort1.Close();
                            
                            A Offline
                            A Offline
                            Adam Yonce
                            wrote on last edited by
                            #18

                            I have had luck writing serial data from a PIC microcontroller to a textbox using the following code in C#:

                            private void serialPort1_DataReceived_1(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
                            {
                            txtToDisplay = serialPort1.ReadExisting();
                            DisplayText();
                            }

                            public void DisplayText()
                            {
                            if (txtIn.InvokeRequired)
                            {
                            this.BeginInvoke(new MethodInvoker(DisplayText));
                            }
                            else
                            {
                            txtIn.AppendText(txtToDisplay);
                            }
                            }

                            Also, I set the comm port parameters in the same place I open the port, rather than the receive event:

                            private void GetComPorts() //populate the comm port list with the available system ports
                            {
                            foreach (string s in SerialPort.GetPortNames() )
                            {
                            lbPort.Items.Add(s);
                            }
                            }

                            private void btnOpen_Click(object sender, EventArgs e)
                            {

                             this.lbPort.SelectedIndex = this.lbPort.TopIndex;          // which port?
                             this.lbRate.SelectedIndex = this.lbRate.TopIndex;          // baud rate?
                             this.lbProtocol.SelectedIndex = this.lbProtocol.TopIndex;  // N,8,1 or N,7,1 (strings in a collection)
                            
                             string crlf = Environment.NewLine;                         // this might be the real trick...
                            
                             serialPort1.BaudRate = Int32.Parse(lbRate.Text);
                             serialPort1.PortName = lbPort.Text;
                            
                             serialPort1.Open();
                            
                             if (serialPort1.IsOpen)
                             {
                                btnOpen.Enabled = false;
                                btnClose.Enabled = true;
                            
                                txtIn.AppendText(string.Format("Port {0} opened successfully." + crlf, serialPort1.PortName));
                                        
                             }
                            

                            }

                            Anyway, this seems to work in my situation. Also, my PIC code is using "\r\n" so I am actually sending a {10} and a {13} pair. Hope this helps, Adam

                            T 2 Replies Last reply
                            0
                            • L Luc Pattyn

                              Hi, some comments: 1. as your terminal emulator is working, it would be time to try the binary mode I have shown earlier. It has the advantage of (a) showing the exact bytes you're getting, and (b) you're using your own code (as opposed to the terminal emulator). 2. you should set the port's properties right when you open it, and not in its DataReceived handler, i.e. after having gotten some data already. 3.

                              turbosupramk3 wrote:

                              serialPort1.NewLine = "(13)";

                              that is non-sense. You need a CR character, which is represented by \r in C-like languages. cfr my first reply. 4. I wouldn't use a single TextBox for both input and output, at least until everything works well. I also wouldn't spend all that effort in the GUI stuff until such moment that the serial comm is working fine. I think you're getting closer to the solution! :)

                              Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                              Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

                              T Offline
                              T Offline
                              turbosupramk3
                              wrote on last edited by
                              #19

                              Hey Luc, I tried \r and \n too :) with no luck then I was trying the string value and I tried Chr(13) as well with no luck. I will try the binary thing tonight and see what bits I am getting

                              N 1 Reply Last reply
                              0
                              • A Adam Yonce

                                I have had luck writing serial data from a PIC microcontroller to a textbox using the following code in C#:

                                private void serialPort1_DataReceived_1(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
                                {
                                txtToDisplay = serialPort1.ReadExisting();
                                DisplayText();
                                }

                                public void DisplayText()
                                {
                                if (txtIn.InvokeRequired)
                                {
                                this.BeginInvoke(new MethodInvoker(DisplayText));
                                }
                                else
                                {
                                txtIn.AppendText(txtToDisplay);
                                }
                                }

                                Also, I set the comm port parameters in the same place I open the port, rather than the receive event:

                                private void GetComPorts() //populate the comm port list with the available system ports
                                {
                                foreach (string s in SerialPort.GetPortNames() )
                                {
                                lbPort.Items.Add(s);
                                }
                                }

                                private void btnOpen_Click(object sender, EventArgs e)
                                {

                                 this.lbPort.SelectedIndex = this.lbPort.TopIndex;          // which port?
                                 this.lbRate.SelectedIndex = this.lbRate.TopIndex;          // baud rate?
                                 this.lbProtocol.SelectedIndex = this.lbProtocol.TopIndex;  // N,8,1 or N,7,1 (strings in a collection)
                                
                                 string crlf = Environment.NewLine;                         // this might be the real trick...
                                
                                 serialPort1.BaudRate = Int32.Parse(lbRate.Text);
                                 serialPort1.PortName = lbPort.Text;
                                
                                 serialPort1.Open();
                                
                                 if (serialPort1.IsOpen)
                                 {
                                    btnOpen.Enabled = false;
                                    btnClose.Enabled = true;
                                
                                    txtIn.AppendText(string.Format("Port {0} opened successfully." + crlf, serialPort1.PortName));
                                            
                                 }
                                

                                }

                                Anyway, this seems to work in my situation. Also, my PIC code is using "\r\n" so I am actually sending a {10} and a {13} pair. Hope this helps, Adam

                                T Offline
                                T Offline
                                turbosupramk3
                                wrote on last edited by
                                #20

                                Hi Adam, Thanks! I will try that at home and see how it works with my uC. I did not try sending a 10 and 13, that might be worth a try as well!

                                1 Reply Last reply
                                0
                                • T turbosupramk3

                                  I am trying to read serial data from a microchip. Using the simple serial c# project I am able to read the characters being sent, but I am not able to delineate carriage returns and so the correct data will stream across the screen until the programs input box end and then it will wrap around to the next line and continue to stream, an example would be

                                  seveneightnineteneleventwelvethirteen
                                  fourteenfifteensixteenseventeeneighteen

                                  instead of

                                  seven
                                  eight
                                  nine
                                  ten
                                  eleven
                                  twelve
                                  thirteen
                                  fourteen
                                  fifteen
                                  sixteen
                                  seventeen
                                  eighteen

                                  Does anyone know how I can recognize the carriage returns? They should come through as an ascii character "13" and the serial data protocol is 8 databits no paraty one stopbit (8N1) at a baudrate between 9600 and 115200 baud. Thanks!

                                  D Offline
                                  D Offline
                                  DarthDana
                                  wrote on last edited by
                                  #21

                                  Try looking for a linefeed (10) character instead. If it's coming from a Unix/Linux box then that's what will be sent.

                                  1 Reply Last reply
                                  0
                                  • A Adam Yonce

                                    I have had luck writing serial data from a PIC microcontroller to a textbox using the following code in C#:

                                    private void serialPort1_DataReceived_1(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
                                    {
                                    txtToDisplay = serialPort1.ReadExisting();
                                    DisplayText();
                                    }

                                    public void DisplayText()
                                    {
                                    if (txtIn.InvokeRequired)
                                    {
                                    this.BeginInvoke(new MethodInvoker(DisplayText));
                                    }
                                    else
                                    {
                                    txtIn.AppendText(txtToDisplay);
                                    }
                                    }

                                    Also, I set the comm port parameters in the same place I open the port, rather than the receive event:

                                    private void GetComPorts() //populate the comm port list with the available system ports
                                    {
                                    foreach (string s in SerialPort.GetPortNames() )
                                    {
                                    lbPort.Items.Add(s);
                                    }
                                    }

                                    private void btnOpen_Click(object sender, EventArgs e)
                                    {

                                     this.lbPort.SelectedIndex = this.lbPort.TopIndex;          // which port?
                                     this.lbRate.SelectedIndex = this.lbRate.TopIndex;          // baud rate?
                                     this.lbProtocol.SelectedIndex = this.lbProtocol.TopIndex;  // N,8,1 or N,7,1 (strings in a collection)
                                    
                                     string crlf = Environment.NewLine;                         // this might be the real trick...
                                    
                                     serialPort1.BaudRate = Int32.Parse(lbRate.Text);
                                     serialPort1.PortName = lbPort.Text;
                                    
                                     serialPort1.Open();
                                    
                                     if (serialPort1.IsOpen)
                                     {
                                        btnOpen.Enabled = false;
                                        btnClose.Enabled = true;
                                    
                                        txtIn.AppendText(string.Format("Port {0} opened successfully." + crlf, serialPort1.PortName));
                                                
                                     }
                                    

                                    }

                                    Anyway, this seems to work in my situation. Also, my PIC code is using "\r\n" so I am actually sending a {10} and a {13} pair. Hope this helps, Adam

                                    T Offline
                                    T Offline
                                    turbosupramk3
                                    wrote on last edited by
                                    #22

                                    Hey Adam, Looks like it was searching for a 10 and 13, but it wanted them as a 13, then a 10. Thanks to everyone who was kind enough to respond and offer help to me. I'll probably have more questions as time goes on and now that I have a baseline I can start to implement the other good pieces of advice in this thread :)

                                    1 Reply Last reply
                                    0
                                    • T turbosupramk3

                                      Hey Luc, I tried \r and \n too :) with no luck then I was trying the string value and I tried Chr(13) as well with no luck. I will try the binary thing tonight and see what bits I am getting

                                      N Offline
                                      N Offline
                                      NedPat
                                      wrote on last edited by
                                      #23

                                      Has the textbox a multiline option?

                                      S 1 Reply Last reply
                                      0
                                      • T turbosupramk3

                                        Hi Colin, Maybe I can send it different characters for a line feed ... do you happen to know what pair of characters is it expecting? With the byte array, are you just filling it up with 8 bits, and then at the stop bit converting it to a string?

                                        C Offline
                                        C Offline
                                        ColinBurnell
                                        wrote on last edited by
                                        #24

                                        I expect it wants a carriage return followed by a line feed - 0x0d 0x0a Reading a byte array is not that low a level; the SerialPort class gives you a method to read byte data - SerialPort.Read Method (Byte[], Int32, Int32). You can use the BytesToRead property to see how many bytes there are in the buffer.

                                        1 Reply Last reply
                                        0
                                        • N NedPat

                                          Has the textbox a multiline option?

                                          S Offline
                                          S Offline
                                          ShafiqA
                                          wrote on last edited by
                                          #25

                                          No. I am only concatenating two string like... string strValue="abc" + ";" + "xyz";

                                          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