How can I read a string from OpenNETCF.IO.Ports.SerialPort?

爱⌒轻易说出口 提交于 2019-12-06 15:37:40

The first thing I notice is that you're using a class called SerialPort which means you're using code from SDF 1.x which dates to circa 2005 at the most recent. Not sure I'd be overly enthused about that. I created an open source library that contains just a Port class after that code but it works way different - it was modeled after the VB6 serial port object model. I honestly don't even recall who wrote the code in SDF 1.x - might have been me, might not have. I think not just judging by the code style I see.

I was going to question why you didn't just use the built-in CF serial stuff, but if you're using SDF 1.x, you're likely using a CF version that pre-dates inclusion of a serial port API.

As for the one you're using now, I would think that it somewhat depends on how the data coming back is expected, but the pseudocode would look something like this:

var port = new SerialPort;
port.Settings = whateverPortSettingsYouNeed;
port.Open();

....
// send the command
port.Send(myCommand);

// get a synchronous, newline-delimited response
var response = new StringBuilder();
char c;
do
{
    c = (char)port.ReadByte();
    // see if it actually read anything
    if(c == '\0')
    {
        // wait a little bit, then try again - you will want to put in a timeout here
        Thread.Sleep(10);
        continue;
    } 
    response.Append(c);
    // you may want to check for response "reasonableness" here
} while(c != \n');

DoSomethingWithResponse(response);

It is reading bytes. The buffer is where the bytes are read into (as modified by the offset and count), while the return value is the number of bytes read. Typical stream-type stuff.

The docos are here: http://msdn.microsoft.com/en-us/library/ms143549(v=vs.90).aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!