串口读取 C# 控制台 [英] Serial Port Read C# Console

查看:30
本文介绍了串口读取 C# 控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我是新来的,我听说过很多关于这个网站的信息,它确实对你有帮助.希望您能帮帮我!

Hi to all i am new here and i have heard a lot about this website that it really helps you out. Hope you will be able to help me out!.

我有一个非常简单的程序,它的唯一目的是从串行端口读取并在 C# 的控制台窗口上打印 2000 次.

I have a very simple program which its only aim is to read from a serial port and prints it on the console window in C# for 2000 times.

我只是在微控制器上打开一个可变电阻而已

I am just turning a variable resistor on a micro-controller that's all

下面是代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace Testing_serial_v3._0
{
    class Program
    {
        static void Main(string[] args)
        {

            string buff;


            SerialPort port = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
            port.Open();

            for (int i = 0; i < 2000; i++)
            {


                buff = port.ReadLine();
                Console.WriteLine(buff);
                //Console.ReadLine();
            }
        }
    }
}

但是在这段代码中发生了一件有趣的事情.当控制台 readline 被注释时,如上面的代码所示,当我转动可变电阻器的旋钮时,端口的值会发生变化.所以这意味着它运行良好.另一方面,如果我使 readline 发生,以便在每个值之后我必须按下一个键,端口读取当前值,即使我改变旋钮并再次按下 enter,该值仍将保持第一个,就好像它没有重置一样有吗?

But there is a funny thing happening in this code. When the console readline is commented as shown in the code above the value from the port changes as i turn the knob of the variable resistor. So this means it is working good. On the other hand if i make the readline happen so that after each value i have to press a key the port reads the current value and even though i change the knob and press enter again the value will remain the first as if it is not resetting at all?

是否必须包含任何其他命令行才能重置端口?

Do you have to include any other command lines so that the port will reset?

希望您了解我的问题以及您需要了解的任何其他问题,请不要犹豫,我真的需要尽快解决此问题.非常感谢和问候

Hope you understand my problem and any other questions you need to know please don't hesitate i really need this problem fixed ASAP. Many thanks and regards

推荐答案

您还可以使用任务在单独的线程中读取它并在那里观察它,就像@Marc Gravel 提到的那样.您只需要等到任务完成或按回车键手动取消它.这只是将任务卸载到另一个线程的另一个示例.

You could also use a Task to read it in a separate thread and observe it there, kind of what @Marc Gravel mentions. You just have to wait until the task is finished or press enter to cancel it manually. Just another example of offloading the task to another thread.

这是一个例子:

using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ReadStreamAsyncTask
{
    internal class Program
    {
        private static CancellationToken _cancelTaskSignal;
        private static byte[] _serialPortBytes;
        private static MemoryStream _streamOfBytesFromPort;
        private static CancellationTokenSource _cancelTaskSignalSource;

        private static void Main()
        {
            _serialPortBytes = Encoding.ASCII.GetBytes("Mimic a bunch of bytes from the serial port");
            _streamOfBytesFromPort = new MemoryStream(_serialPortBytes);
            _streamOfBytesFromPort.Position = 0;

            _cancelTaskSignalSource = new CancellationTokenSource();
            _cancelTaskSignal = _cancelTaskSignalSource.Token; // Used to request cancel the task if needed.

            var readFromSerialPort = Task.Factory.StartNew(ReadStream, _cancelTaskSignal);
            readFromSerialPort.Wait(3000); // wait until task is complete(or errors) OR 3 seconds

            Console.WriteLine("Press enter to cancel the task");
            _cancelTaskSignalSource.Cancel();
            Console.ReadLine();
        }

        private static void ReadStream()
        {
            // start your loop here to read from the port and print to console

            Console.WriteLine("Port read task started");

            int bytesToReadCount = Buffer.ByteLength(_serialPortBytes);
            var localBuffer = new byte[bytesToReadCount];

            int bytesRead = 0;

            bool finishedReading = false;

            try
            {
                while (!finishedReading)
                {
                    _cancelTaskSignal.ThrowIfCancellationRequested();

                    bytesRead += _streamOfBytesFromPort.Read(localBuffer, 0, bytesToReadCount);

                    finishedReading = (bytesRead - bytesToReadCount == 0);
                }
            }
            catch (TaskCanceledException)
            {
                Console.WriteLine("You cancelled the task");
            }

            Console.WriteLine(Encoding.ASCII.GetString(localBuffer));
            Console.WriteLine("Done reading stream");
        }
    }
}

这篇关于串口读取 C# 控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆