微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#串口读取数据速度在9600或115200波特率相同

如何解决C#串口读取数据速度在9600或115200波特率相同

我是 C# 的初学者,想要一些有关如何解决以下问题的建议:

我的主要代码包括 2 个线程,第一个线程用于发送和接收数据,第二个线程仅用于绘制图表和计算值的标签

一个线程首先将寄存器 1 的读取命令发送到 ADC 真 FTDI 直接命令并从 ADC 获取 24 位。比我的代码将寄存器 2 的读取命令发送到 ADC 并从 ADC 获取 24 位,然后一切再次循环旋转。第二个线程仅用于绘制带有一些内置延迟的计算值的图表和标签,以便更好地监控。

FTDI 和 ADC 能够以 120000 波特率运行。问题是如果我把波特率设置为9600或115200,读取数据的速度总是一样的。虽然循环仅旋转 40-50 次/秒(我设置了计数器来检测)。我检测到代码中最慢的部分正在等待所有字节(while (numBytesAvailable

FTDI 设置:

         ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList);
        // Open first device in our list by serial number
        if (ftdiDeviceCount != 0) { 
            ftStatus = myFtdiDevice.OpenBySerialNumber(ftdiDeviceList[0].SerialNumber);
            // Set Baud rate to 115200
            ftStatus = myFtdiDevice.SetBaudrate(115200);
            // Set data characteristics - Data bits,Stop bits,Parity
            ftStatus = myFtdiDevice.SetDatacharacteristics(FTDI.FT_DATA_BITS.FT_BITS_8,}

代码Thread1:

        UInt32 numBytesWritten = 0;
        UInt32 numBytesRead = 0;
        UInt32 numBytesAvailable = 0;
        UInt32 numBytesNeed = 3;
while (read_data)
        {
            ftStatus = myFtdiDevice.Write(sync3,sync3.Length,ref numBytesWritten); //set reg1
            ftStatus = myFtdiDevice.Write(sync10,sync10.Length,ref numBytesWritten); //READ command

            //wait for all data 
            do
            {
                ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesAvailable);

            }
            while (numBytesAvailable < numBytesNeed);

            //read data
            byte[] readData1 = new byte[3];
            ftStatus = myFtdiDevice.Read(readData1,numBytesAvailable,ref numBytesRead);
            int left_justified1 = (readData1[2] << 24) | (readData1[1] << 16) | (readData1[0] << 8);
            int result = left_justified1 >> 8;

            v = ((((4.096 / 16777216) * result) / 4) * 250); //calculate voltage

            ftStatus = myFtdiDevice.Write(sync4,sync4.Length,ref numBytesWritten); //set reg2
            ftStatus = myFtdiDevice.Write(sync10,ref numBytesWritten); //READ command

            //wait for all data to read
            do
            {
                ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesAvailable);

            } while (numBytesAvailable < numBytesNeed);

            //read data
            byte[] readData2 = new byte[3];
            ftStatus = myFtdiDevice.Read(readData2,ref numBytesRead);
            int left_justified2 = (readData2[2] << 24) | (readData2[1] << 16) | (readData2[0] << 8);
            result = left_justified2 >> 8;

            a = ((((4.096 / 16777216) * result) / 4) / 0.1); //calculate current
        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。