using System; using System.Threading; using System.IO.Ports; using System.Text; using Microsoft.SPOT; using Microsoft.SPOT.Hardware; namespace MFConsoleApplication1 { public static class DGHPressure { private static char DGHTerminatingChar = '\r'; private static string DGHRxString = ""; private static SerialPort DGHPort = new SerialPort("COM3", 38400, Parity.None, 8, StopBits.One); private static AutoResetEvent DGHReadEvent = new AutoResetEvent(false); public static int init(String PortName) { DGHPort.ReadTimeout = 1000; DGHPort.Open(); DGHPort.DiscardInBuffer(); DGHPort.DiscardOutBuffer(); DGHPort.DataReceived += new SerialDataReceivedEventHandler(DGHPort_DataReceived); DGHPort.ErrorReceived += new SerialErrorReceivedEventHandler(DGHPort_ErrorReceived); return (0); } public static double readPressure() { byte[] DGHTxBytes; string DGHReadCmd = "$1RD\r"; //$1RD terminated with CR is the command to read data from the DGH double pressureDBar = Double.NaN; const double ma2bar = (15.0 / 1.45038) / 16.0; //4-20 ma transducer; 15 psig full scale; 1 dBar = 1.45038 psi const double maOffset = 4.0; EngrLog.writeEvent(Program.DateTimeNowMilliSec() + " ,Sending RD to DGH"); DGHTxBytes = Encoding.UTF8.GetBytes(DGHReadCmd); DGHPort.Write(DGHTxBytes, 0, DGHTxBytes.Length); EngrLog.writeEvent(Program.DateTimeNowMilliSec() + " ,Waiting for DGH RD"); if (DGHReadEvent.WaitOne(1000, false)) //waiting for notification, 1000 mSec timeout { DGHRxString = DGHRxString.Substring(2, 11); pressureDBar = Convert.ToDouble(DGHRxString); pressureDBar = (pressureDBar - maOffset) * ma2bar; EngrLog.writeEvent(Program.DateTimeNowMilliSec() + " ,DGH readPressure got pressure from DGH: " + pressureDBar.ToString()); } else { pressureDBar = Double.NaN; EngrLog.writeEvent(Program.DateTimeNowMilliSec() + " ,DGH RD timed out"); } return (pressureDBar); } static void DGHPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { char rxChar; while (DGHPort.BytesToRead > 0) { rxChar = (char)DGHPort.ReadByte(); Debug.Print(rxChar.ToString()); DGHRxString = DGHRxString + rxChar.ToString(); if (rxChar == DGHTerminatingChar) DGHReadEvent.Set(); } } static void DGHPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e) { //Eventually } } }