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. How to read from Serial (COM) Port? [modified]

How to read from Serial (COM) Port? [modified]

Scheduled Pinned Locked Moved C#
comhelptutorialquestion
5 Posts 3 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.
  • A Offline
    A Offline
    Aghosh Babu
    wrote on last edited by
    #1

    i want to read data from a serial port(where a gsm modem is connected). I want to read the reply from modem when an AT command is send to the modem. i.e for eg. if i send AT to the modem i want to read the reply OK from the modem! I had used the below codes but the application hangs while executing these lines: string data = Convert.ToString(serialPort1.Read(buffer, 0, (int)buffer.Length)); //read using a Stream string data1 = Convert.ToString(serialPort1.BaseStream.Read(buffer, 0, (int)buffer.Length)); I had also tried string data = serialPort1.ReadLine(); Below is my full code section:

    private void button1_Click(object sender, EventArgs e)
    {
    try
    {

                //configuring the serial port
                serialPort1.PortName = "COM6";
                serialPort1.Handshake = Handshake.None;
                serialPort1.BaudRate = 115200;
                serialPort1.DataBits = 8;
                serialPort1.Parity = Parity.None;
                serialPort1.StopBits = StopBits.One;
                serialPort1.DtrEnable = true;
    
                serialPort1.Open();
                
                string c = "AT+CMGS=";
                string c1 = "\\"+6582083412\\"\\r\\n";
                serialPort1.Write(c+c1);
    
    
                string d = "Test message from coded program ";
                //Now send the contents of the message
                serialPort1.Write(d);
                //SerialPortListen();
                char\[\] arr = new char\[1\];
    
                arr\[0\] = (char)26; //ascii value of Ctrl-Z
    
                serialPort1.Write(arr, 0, 1);
                
                //string data = Convert.ToString(serialPort1.Read(buffer, 0, (int)buffer.Length));
                //read using a Stream
                //string data1 = Convert.ToString(serialPort1.BaseStream.Read(buffer, 0, (int)buffer.Length));
               //MessageBox.Show(data + " part 2 is : " + data1);
    
                serialPort1.Close();
    
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
    
    
        }
    

    I would appreciate your help very much, since this is my first time i am trying to communicate with a serial port. Thanks in advance

    modified on Thursday, January 15, 2009 11:48 PM

    L B 2 Replies Last reply
    0
    • A Aghosh Babu

      i want to read data from a serial port(where a gsm modem is connected). I want to read the reply from modem when an AT command is send to the modem. i.e for eg. if i send AT to the modem i want to read the reply OK from the modem! I had used the below codes but the application hangs while executing these lines: string data = Convert.ToString(serialPort1.Read(buffer, 0, (int)buffer.Length)); //read using a Stream string data1 = Convert.ToString(serialPort1.BaseStream.Read(buffer, 0, (int)buffer.Length)); I had also tried string data = serialPort1.ReadLine(); Below is my full code section:

      private void button1_Click(object sender, EventArgs e)
      {
      try
      {

                  //configuring the serial port
                  serialPort1.PortName = "COM6";
                  serialPort1.Handshake = Handshake.None;
                  serialPort1.BaudRate = 115200;
                  serialPort1.DataBits = 8;
                  serialPort1.Parity = Parity.None;
                  serialPort1.StopBits = StopBits.One;
                  serialPort1.DtrEnable = true;
      
                  serialPort1.Open();
                  
                  string c = "AT+CMGS=";
                  string c1 = "\\"+6582083412\\"\\r\\n";
                  serialPort1.Write(c+c1);
      
      
                  string d = "Test message from coded program ";
                  //Now send the contents of the message
                  serialPort1.Write(d);
                  //SerialPortListen();
                  char\[\] arr = new char\[1\];
      
                  arr\[0\] = (char)26; //ascii value of Ctrl-Z
      
                  serialPort1.Write(arr, 0, 1);
                  
                  //string data = Convert.ToString(serialPort1.Read(buffer, 0, (int)buffer.Length));
                  //read using a Stream
                  //string data1 = Convert.ToString(serialPort1.BaseStream.Read(buffer, 0, (int)buffer.Length));
                 //MessageBox.Show(data + " part 2 is : " + data1);
      
                  serialPort1.Close();
      
              }
              catch (Exception ex)
              {
                  MessageBox.Show(ex.Message);
              }
      
      
          }
      

      I would appreciate your help very much, since this is my first time i am trying to communicate with a serial port. Thanks in advance

      modified on Thursday, January 15, 2009 11:48 PM

      L Offline
      L Offline
      lincyang
      wrote on last edited by
      #2

      use the event DataReceived... this is my email :lebron_y@126.com we can discussion then SerialPort communications. regards

      1 Reply Last reply
      0
      • A Aghosh Babu

        i want to read data from a serial port(where a gsm modem is connected). I want to read the reply from modem when an AT command is send to the modem. i.e for eg. if i send AT to the modem i want to read the reply OK from the modem! I had used the below codes but the application hangs while executing these lines: string data = Convert.ToString(serialPort1.Read(buffer, 0, (int)buffer.Length)); //read using a Stream string data1 = Convert.ToString(serialPort1.BaseStream.Read(buffer, 0, (int)buffer.Length)); I had also tried string data = serialPort1.ReadLine(); Below is my full code section:

        private void button1_Click(object sender, EventArgs e)
        {
        try
        {

                    //configuring the serial port
                    serialPort1.PortName = "COM6";
                    serialPort1.Handshake = Handshake.None;
                    serialPort1.BaudRate = 115200;
                    serialPort1.DataBits = 8;
                    serialPort1.Parity = Parity.None;
                    serialPort1.StopBits = StopBits.One;
                    serialPort1.DtrEnable = true;
        
                    serialPort1.Open();
                    
                    string c = "AT+CMGS=";
                    string c1 = "\\"+6582083412\\"\\r\\n";
                    serialPort1.Write(c+c1);
        
        
                    string d = "Test message from coded program ";
                    //Now send the contents of the message
                    serialPort1.Write(d);
                    //SerialPortListen();
                    char\[\] arr = new char\[1\];
        
                    arr\[0\] = (char)26; //ascii value of Ctrl-Z
        
                    serialPort1.Write(arr, 0, 1);
                    
                    //string data = Convert.ToString(serialPort1.Read(buffer, 0, (int)buffer.Length));
                    //read using a Stream
                    //string data1 = Convert.ToString(serialPort1.BaseStream.Read(buffer, 0, (int)buffer.Length));
                   //MessageBox.Show(data + " part 2 is : " + data1);
        
                    serialPort1.Close();
        
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
        
        
            }
        

        I would appreciate your help very much, since this is my first time i am trying to communicate with a serial port. Thanks in advance

        modified on Thursday, January 15, 2009 11:48 PM

        B Offline
        B Offline
        Bharat Jain
        wrote on last edited by
        #3

        Hi Aghosh Babu, It seems like you are try to build an application which send SMS using a connect Phone , and the serial port you are using (COM6) is a virtual serial port (port used to connect to through buletooth or USB ) , so please make sure that you com6 is working , by using Apllication like Hyper Terminal (it comes with windows XP) , try to send AT , and recive OK , if its is working over there , than you can try it in your code (dont forget to disconnect hyper terminal bepore try from you code , other wise it will give error , say port already in use). I have used the following code recive data that arrives on serial port

        private static void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)

        {
        if (_serialPort.BytesToRead > 0)
        {
        int bytesToRead = _serialPort.BytesToRead;
        byte[] dataRead = new byte[bytesToRead];
        string linedata;
        _serialPort.Read(dataRead, 0, bytesToRead);
        linedata = ConvertToString(dataRead);
        }
        }

           private string ConvertToString(IEnumerable ByteArray)
            {
                //This Function converts an Byte Array to string , This we 
                // nned to do because if we directly try to read srting ,
                // From the com port , it take Unicode encoding , we need ASCII encoding
                // Hence we need to 
                string tempStringToReturn = string.Empty;
                foreach (byte bt in ByteArray)
                {
                    tempStringToReturn = tempStringToReturn + Convert.ToChar(bt);
                }
                return tempStringToReturn;
            }
        

        In the above code SerialPortDataReceived is a event of serial port object , this event is raised when there data arrives on the serial port . Try out with above information , see if it helps , i need to move now , let me know if you find any problem regarding the same

        -Regards Bharat Jain bharat.jain.nagpur@gmail.com

        A 1 Reply Last reply
        0
        • B Bharat Jain

          Hi Aghosh Babu, It seems like you are try to build an application which send SMS using a connect Phone , and the serial port you are using (COM6) is a virtual serial port (port used to connect to through buletooth or USB ) , so please make sure that you com6 is working , by using Apllication like Hyper Terminal (it comes with windows XP) , try to send AT , and recive OK , if its is working over there , than you can try it in your code (dont forget to disconnect hyper terminal bepore try from you code , other wise it will give error , say port already in use). I have used the following code recive data that arrives on serial port

          private static void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)

          {
          if (_serialPort.BytesToRead > 0)
          {
          int bytesToRead = _serialPort.BytesToRead;
          byte[] dataRead = new byte[bytesToRead];
          string linedata;
          _serialPort.Read(dataRead, 0, bytesToRead);
          linedata = ConvertToString(dataRead);
          }
          }

             private string ConvertToString(IEnumerable ByteArray)
              {
                  //This Function converts an Byte Array to string , This we 
                  // nned to do because if we directly try to read srting ,
                  // From the com port , it take Unicode encoding , we need ASCII encoding
                  // Hence we need to 
                  string tempStringToReturn = string.Empty;
                  foreach (byte bt in ByteArray)
                  {
                      tempStringToReturn = tempStringToReturn + Convert.ToChar(bt);
                  }
                  return tempStringToReturn;
              }
          

          In the above code SerialPortDataReceived is a event of serial port object , this event is raised when there data arrives on the serial port . Try out with above information , see if it helps , i need to move now , let me know if you find any problem regarding the same

          -Regards Bharat Jain bharat.jain.nagpur@gmail.com

          A Offline
          A Offline
          Aghosh Babu
          wrote on last edited by
          #4

          Hi Bharat, Thanks for the code... i am now able to read data from serial port.. initially i haven't set my handshake property properly...I used serialPort1.ReadExisting(); to read the data from serial port... i think i will redo my code with yours :-D ...i hope your code will automatically initiate the method when a data comes into the port... :-O

          B 1 Reply Last reply
          0
          • A Aghosh Babu

            Hi Bharat, Thanks for the code... i am now able to read data from serial port.. initially i haven't set my handshake property properly...I used serialPort1.ReadExisting(); to read the data from serial port... i think i will redo my code with yours :-D ...i hope your code will automatically initiate the method when a data comes into the port... :-O

            B Offline
            B Offline
            Bharat Jain
            wrote on last edited by
            #5

            Gr8 to know that the code was helpful.

            -Regards Bharat Jain bharat.jain.nagpur@gmail.com

            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