简体   繁体   中英

read data from serialport

I am new to C# and programming in general.

I am trying to communicate with a ohmmeter which is conneted via usb to my computer.

I am able to configurate the device and even recieve data. But i can not acces this data. I can just print it on to the console. (Was inspired by the code on the microsoft site)

Here is the constructer of my "communication"-class where i configurate the port:

public SCPI_Commands()
    {
        _SerialPort.PortName = SetPortName(_SerialPort.PortName);
        _SerialPort.BaudRate = 115200;
        _SerialPort.Parity = Parity.None;
        _SerialPort.DataBits = 8;
        _SerialPort.StopBits = StopBits.One;
        _SerialPort.Handshake = Handshake.None;
        _SerialPort.ReadTimeout = 500;
        _SerialPort.WriteTimeout = 500;
        _SerialPort.Open();
        _SerialPort.DataReceived += _serialPort_DataReceived;
    }

Here is my function which sends a query to the device (The constant Measurment_Value represents a scpi command which is understood by my ohmmeter) :

public void get_measurement()
    {
        _SerialPort.WriteLine(Measurment_Value);
    }

And here is the private function which checks if the device is sending data and printing it on the console (not sure how this function works) :

private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        Console.WriteLine(_SerialPort.ReadLine());
    }

Unfortunately i am not able to return the data as a string. My goal is to do some calculations with the received data. Does someone has any ideas ?

Greetings from Germany.

Luke

You can read from buffer to temp byte array and then get it as string, see the below example. Put this in _serialPort_DataReceived

    // this the read buffer
    byte[] buff = new byte[9600];
    int readByteCount = _serialPort.BaseStream.Read(buff, 0, _serialPort.BytesToRead);
    // you can specify other encodings, or use default
    string response = System.Text.Encoding.UTF8.GetString(buff);

Side Note

If you want to keep your sanity while working with SerialPort, always send and receive as byte array. Then, get the equivalent string using Encoding .

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