Hi to all.
Let me explain my problem first.
I have to read certain values from the serial port (double data type) and use it in the main program.
I am a newbie when it comes to serial configuration and interfacing.
I have found the following code on the web and tried to alter it for my needs.
Note that where there is ////MARK/// i only use the writeline just to see what is the output but strangly the output is always 0.Code:#region Namespace Inclusions using System; using System.IO.Ports; using System.Threading; #endregion namespace SerialConsoleExample { class SerialPortProgram { public static double x = 0; // Create the serial port with basic settings private SerialPort port = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One); [STAThread] static void Main(string[] args) { // Instatiate this class new SerialPortProgram(); Thread.Sleep(700); //////MARK////////// Console.WriteLine("Resistance: {0}", x); Console.ReadLine(); } private SerialPortProgram() { string get; // Begin communications if (port.IsOpen) { port.Close(); } port.Open(); port.DtrEnable = true; port.NewLine = "\n"; Console.WriteLine(port.ToString()); Console.WriteLine(port.PortName); Console.WriteLine(port.NewLine.ToString()); Console.WriteLine(port.IsOpen.ToString()); Console.WriteLine(port.ReadExisting()); // Attach a method to be called when there // is data waiting in the port's buffer port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); get = port.ReadExisting(); double.TryParse(get, out x); port.Close(); } private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { // Show all the incoming data in the port's buffer //Console.WriteLine(port.ReadExisting()); } } }
When i use the actual program for the device it gives me values which means that there is no problem from where i am getting the values.
And another thing if the writeline is put where it is read from serial right after the values appear but my need is to pass it to the main program.
I thing i have a problem with the variable.
Can you please help me out or maybe there is a simple code to read and use the value from serial.
Regards
Combinu


Reply With Quote
Bookmarks