Arduino控制器和带C#的串口,通过串口拉出奇怪的字符

时间:2016-08-04 13:22:01

标签: c# arduino

我试图用C#serialport类读取端口COM3。

从串口读取时偶尔会有奇怪的字符从串口拉出来?

为什么会出现这个问题?

enter image description here

            foreach (USBDeviceInfo info in devices)
            {
                if (info.Description.Contains("Arduino"))
                {
                    Name = info.Description;
                    if (info.PnpDeviceID.Contains("(COM"))
                    {
                        ComPort = info.PnpDeviceID.Split('(')[1].Split(')')[0];
                        using (SerialPort Port = new SerialPort())
                        {
                            Port.BaudRate = 9600;
                            Port.PortName = ComPort;

                            //rt.DataReceived += Port_DataReceived;
                            try
                            {
                                if (!Port.IsOpen)
                                    Port.Open();
                                string output = Port.ReadTo("end");

                                Value = output;
                                Port.Close();
                            }
                            catch (Exception ex)
                            {
                                Value = ex.Message;
                            }
                            // this.SetText(message);
                        }
                        break;
                    }
                }

控制器代码

    #include <OneWire.h>

 int SensorPin = 7;


 OneWire ds(SensorPin);

 void setup(void) {
    Serial.begin(9600);
 }

void loop(void) {
    float temp = getTemp();

    Serial.println(temp);
    Serial.println("end");

    delay(100);

}


float getTemp(){


    byte data[12];
    byte addr[8];

    if (!ds.search(addr)) {
        //no more sensors on chain, reset search
        ds.reset_search();
        return -1000;
    }

    if (OneWire::crc8(addr, 7) != addr[7]) {
        Serial.println("CRC is not valid!");


return -1000;
}

if (addr[0] != 0x10 && addr[0] != 0x28) {
    Serial.print("Device is not recognized");
    return -1000;
}

ds.reset();
ds.select(addr);
ds.write(0x44, 1);

byte present = ds.reset();
ds.select(addr);
ds.write(0xBE);


for (int i = 0; i < 9; i++) {
    data[i] = ds.read();
}

ds.reset_search();

byte MSB = data[1];
byte LSB = data[0];

float TRead = ((MSB << 8) | LSB);
float Temperature = TRead / 16;

return Temperature;

}

0 个答案:

没有答案