简体   繁体   中英

Serial ReadLine in C# for Arduino doesn't work properly

I want to send a serial data from Arduino to an app using C# IDE Visual Studio. I will send 40 character with 9600 baudrate. The connection between Arduino in C# is good, the problem is when I send the data to C# using ReadLine command. I don't get the whole data, and always some first data loss, for an example if I send 123456789, in C#, it reads just 456789 or 89 or 3456789.

#define TC1 A0
#define TC2 A1
#define TC3 A2
#define TC4 A3
#define TC5 A4
#define TC6 A5
#define TC7 A6
#define TC8 A7
//#define TC9 A8
//#define TC10 A9

float K1 = 1;
float K2 = 1;
float K3 = 1;
float K4 = 1;
float K5 = 1;
float K6 = 1;
float K7 = 1;
float K8 = 1;
float K9 = 1;
float K10 = 1;

int n = 10;
int temp[10];

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int x = 100;
  temp[0]=analogRead(TC1)*K1*x*5/1023;
  temp[1]=analogRead(TC2)*K2*x*5/1023;
  temp[2]=analogRead(TC3)*K3*x*5/1023;
  temp[3]=analogRead(TC4)*K4*x*5/1023;
  temp[4]=analogRead(TC5)*K5*x*5/1023;
  temp[5]=analogRead(TC6)*K6*x*5/1023;
  temp[6]=analogRead(TC7)*K7*x*5/1023;
  temp[7]=analogRead(TC8)*K8*x*5/1023;
  temp[8]=analogRead(TC8)/5*200*K9;
  temp[9]=analogRead(TC8)/5*200*K10;

//  temp[0] = 1101;
//  temp[1] = 2327;
//  temp[2] = 114;
//  temp[3] = 6753;
//  temp[4] = 50;
//  temp[5] = 1;
//  temp[6] = 24;
//  temp[7] = 123;
//  temp[8] = 1269;
//  temp[9] = 3;


  for (int i = 0; i <= n - 1; i++) {
    char buff[] = {'0', '0', '0', '0'};
    int length_temp = String(temp[i]).length();

    for (int j = length_temp - 1; j >= 0; j--) {
      buff[j] = String(temp[i])[length_temp - j - 1];
    }

    for (int j = 0; j <= 3; j++) {
      Serial.write(buff[3 - j]);
    }

  }
  Serial.write('\n');
}

That is my Arduino code, and here the entire my C# code

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

namespace Display_data
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }


        private void start_Click(object sender, EventArgs e)
        {

        }

        private void stop_Click(object sender, EventArgs e)
        {
            //myport.Close();
            //textbox.Text = "Koneksi diputus!";
        }

        private void makefile_Click(object sender, EventArgs e)
        {
            //String simpan = @"C:\"; //Alamat penyimpanan
            //string nama_file = "Data.txt";
            //System.IO.File.WriteAllText(simpan + nama_file, (ch1.Text+','+ ch2.Text + ',' + ch3.Text + ',' + ch4.Text + ',' + ch5.Text + ',' + ch6.Text + ',' + ch7.Text + ',' + ch8.Text + ',' + ch9.Text + ',' + ch10.Text ));
            //MessageBox.Show("Data telah tersimpan di " + simpan + nama_file);

            //string nama_gambar = "Data.png";
            //this.grafik.SaveImage(simpan + nama_gambar, System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Png);
            //MessageBox.Show("Gambar telah tersimpan di " + simpan + nama_gambar);
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void Port_SelectedIndexChanged(object sender, EventArgs e)
        {

        }



        private void connect_Click(object sender, EventArgs e)
        {
            myport = new SerialPort();
            myport.BaudRate = 9600;
            myport.PortName = Port.Text;
            myport.DataReceived += receive;
            try
            {
                myport.Open();
                textbox.Text = "Connected";
            }
            catch (Exception)
            {
                textbox.Text = "Connection Failed!";
            }


        }

        int j;

        void receive(object sender, SerialDataReceivedEventArgs e)
        {
            string data = myport.ReadLine();
            int CHa;
            int CHb;
            int CHc;
            int CHd;
            int CHe;
            int CHf;
            int CHg;
            int CHh;
            int CHi;
            int CHj;

            j++;
            int delay = 500;

            CHa = Int32.Parse(data.Substring(0, 4));
            CHb = Int32.Parse(data.Substring(4, 4));
            CHc = Int32.Parse(data.Substring(8, 4));
            CHd = Int32.Parse(data.Substring(12, 4));
            CHe = Int32.Parse(data.Substring(16, 4));
            CHf = Int32.Parse(data.Substring(20, 4));
            CHg = Int32.Parse(data.Substring(24, 4));
            CHh = Int32.Parse(data.Substring(28, 4));
            CHi = Int32.Parse(data.Substring(32, 4));
            CHj = Int32.Parse(data.Substring(36, 4));


            //ch1.Text = data.Substring(0, 4);
            //ch2.Text = data.Substring(4, 4);
            //ch3.Text = data.Substring(8, 4);
            //ch4.Text = data.Substring(12, 4);
            //ch5.Text = data.Substring(16, 4);
            //ch6.Text = data.Substring(20, 4);
            //ch7.Text = data.Substring(24, 4);
            //ch8.Text = data.Substring(28, 4);
            //ch9.Text = data.Substring(32, 4);
            //ch10.Text = data.Substring(36, 4);


            ch1.Text = CHa.ToString();
            ch2.Text = CHb.ToString();
            ch3.Text = CHc.ToString();
            ch4.Text = CHd.ToString();
            ch5.Text = CHe.ToString();
            ch6.Text = CHf.ToString();
            ch7.Text = CHg.ToString();
            ch8.Text = CHh.ToString();
            ch9.Text = CHi.ToString();
            ch10.Text = CHj.ToString();

            this.grafik.Series["Ch 1"].Points.AddXY(j * delay, CHa);
            this.grafik.Series["Ch 2"].Points.AddXY(j * delay, CHb);
            this.grafik.Series["Ch 3"].Points.AddXY(j * delay, CHc);
            this.grafik.Series["Ch 4"].Points.AddXY(j * delay, CHd);
            this.grafik.Series["Ch 5"].Points.AddXY(j * delay, CHe);
            this.grafik.Series["Ch 6"].Points.AddXY(j * delay, CHf);
            this.grafik.Series["Ch 7"].Points.AddXY(j * delay, CHg);
            this.grafik.Series["Ch 8"].Points.AddXY(j * delay, CHh);
            this.grafik.Series["Ch 9"].Points.AddXY(j * delay, CHi);
            this.grafik.Series["Ch 10"].Points.AddXY(j * delay, CHj);
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void label11_Click(object sender, EventArgs e)
        {

        }
    }
}

So what is the problem? Do I need to latch the open port command?

Ok I don't quite know but if you write '\\n' to the Serial port as line ending and then use ReadLine in c# (I think you use windows?) it caused problems for me. I used my own "Line ending cahr". Just use something like '!' and then always read only one char and compare it to '!'.

pseudocode:

string msg = ""
char read = readchar()
if(read == '!')
    //stop reading
else
    //add char to string
    msg += read

Solved guys, my problem is the first line of the serial data from arduino is not exactly like what i'm trying to send, but for the second line and after that it's normal just like what i print to serial. i still don't know why but my method is just skip my first line incoming data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM