首页 文章

使用线程在C#中实时显示arduino analogRead()

提问于
浏览
1

我正在制作一个C#程序,就像一台糟糕的示波器 . 我有一个Arduino发送到串口(Serial.write(analogRead(A0)))然后C#有一个线程,当主线程刷新图表时,每个ms读取一个样本 . 我的疑问是,我应该使用Serial.write还是Serial.print?

有可能获得2kS / s?我使用的波特率为115200,这是代码 .

namespace TEST
{
    public partial class Form1 : Form
    {

        static int buffer_size = 1024;

        public static string comboBoxText;
        public static int[] buffer = new int[buffer_size];
        IEnumerable<int> yData;
        static int[] range = Enumerable.Range(0, buffer_size).ToArray();
        IEnumerable<int> xData = range;
        public static bool flag = true;


        public Form1()
        {


            Random rand = new Random();
            InitializeComponent();

            for (int c = 0; c<buffer_size;c++) {
                buffer[c] = 0;
            }



             Thread thread1 = new Thread(fillBuffer);
             thread1.Start();


            comboBox1.Items.Add("Select");
            foreach (string s in SerialPort.GetPortNames())
            {
                comboBox1.Items.Add(s);
            }


         }
        static public void fillBuffer()
        {
            Thread.Sleep(1000);
            SerialPort serialPort1 = new SerialPort();
            serialPort1.PortName = "COM5";
            serialPort1.BaudRate = 115200;
            serialPort1.Open();

            while (true)
            {


            }

        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            yData = buffer;
            chart1.Series[0].Points.DataBindY(yData);

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {


            try {

                comboBoxText = comboBox1.Text;
            }
            catch
            {
                MessageBox.Show("Porta Inválida");
                return;
            }
            comboBox1.Enabled = false;

        }

    }

我有什么办法可以对每个0.5ms进行采样,然后将样本显示为点集合吗?我没有取得好成绩 . 如果有人可以提供帮助,谢谢!

1 回答

  • 1

    在115200的波特率和良好的处理器速度下,您的算法似乎足够快 . 但是可以减慢速度的一个因素是timer1的间隔 . 它应该设置为尽可能低 . 另外,对于Serial.Write和Serial.Print之间的区别,请查看this forum . 使用.net内置的串口事件处理程序也可以为您节省很多压力,也是一种更快,更有效的解决方案 . 你可能想看看here

相关问题