1

I am communicating via PC with RS232 cable.

Data received by me: ?\u0011\u0001\u0012?

Sending back this incoming code I need to run the led but when I post the code there is no effect. How can I return this code, which comes in Unicode UTF-8?

private void btnGonder_Click(object sender, EventArgs e) //Send  Button
    {
        try
        {
            if (serialPort1 == null)
            {
                MessageBox.Show("Please check your COM port.");
            }
            else
            {
                string strToUni = txtSendedCommand.Text;
                byte[] buf = System.Text.Encoding.Unicode.GetBytes(strToUni);
                serialPort1.Write(buf, 0, buf.Length);
                
              //  var decoded = System.Text.Encoding.Unicode.GetString(buf);
              //  txtReceived.Text = decoded;

                txtSendedCommand.Clear();
                lstBxDurum.Items.Add("Data is Send.");
            }

        }
        catch
        {
            lstBxDurum.Items.Add("WARNİNG!Data Not Send.");
        }
    }

Data Receive Code

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
       string newLine = Environment.NewLine;
       string buffer = "";
       buffer=serialPort1.ReadExisting();
       
       txtReceived.Text = txtReceived.Text +buffer ;
       txtReceived.Text = txtReceived.Text + serialPort1.ReadExisting();
       txtReceived.Select(txtReceived.Text.Length, 0);

    }
  • SerialPort already has handy methods to read and write strings: you don't need to write your own – canton7 Aug 03 '21 at 11:03
  • you might have to change `System.Text.Encoding.Unicode.GetBytes` to `System.Text.Encoding.UTF8.GetBytes` – Ben Aug 03 '21 at 11:04
  • ... Or just use [`SerialPort.Write(string)`](https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.write#System_IO_Ports_SerialPort_Write_System_String_), which uses ASCII. You can set the encoding that SerialPort uses to UTF8 with `serialPort.Encoding = Encoding.UTF8` – canton7 Aug 03 '21 at 11:05
  • @canton7 I'm on this road – Muhammed Emin Kılınç Aug 03 '21 at 11:56
  • These articles will be helpful. [How to apply encoding when reading from a serial port](https://stackoverflow.com/q/2714533/9014308), [ReadExisting serial port to bytes using C#](https://stackoverflow.com/q/45058398/9014308), [SerialPort.Encoding Property](https://docs.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.encoding?view=dotnet-plat-ext-5.0) The default is ASCIIEncoding. `The Encoding property was set to an encoding that is not ASCIIEncoding, UTF8Encoding, UTF32Encoding, UnicodeEncoding, one of the Windows single byte encodings, or one of the Windows double byte encodings.` – kunif Aug 03 '21 at 12:35

0 Answers0