0

I tried to connect the scale and retrieve the weight from visual studio 2013, but it's wire that sometimes I can get the exacted weight and sometimes I couldn't. I was not sure what's wrong with the code. Can someone help? My code is listed below

using System;
using System.IO.Ports;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows;
using System.Data.SqlClient;
using System.Collections;
using System.Threading;

namespace PortDataReceived
{
    class PortData
    {
        public static void Main(string[] args)
        {
            try
            {
                string lineOne = "One";
                string lineTwo = "Two";
                char CarriageReturn = (char)0x0D;
                string final = lineOne + CarriageReturn.ToString() + lineTwo + CarriageReturn.ToString();// define the hexvalues to the printer
                SerialPort mySerialPort = new SerialPort("COM3");//initiate the new object and tell that we r using COM1

                mySerialPort.BaudRate = 9600;
                //mySerialPort.Parity = Parity.Odd;
                //mySerialPort.StopBits = StopBits.Two;
                //mySerialPort.DataBits = 7;
                mySerialPort.Parity = Parity.Odd;
                mySerialPort.StopBits = StopBits.Two;
                mySerialPort.DataBits = 7;
                mySerialPort.Handshake = Handshake.None;
                mySerialPort.ReadTimeout = 20;
                mySerialPort.WriteTimeout = 50;
                mySerialPort.DtrEnable = true;
                mySerialPort.RtsEnable = true;
                //those r all the setting based on the scale requirement

                /*foreach (string port in System.IO.Ports.SerialPort.GetPortNames())
                {
                    Console.WriteLine(port);
                }*/
                while (true)
                {
                    mySerialPort.Open();
                    mySerialPort.Write(final);
                    mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);


                    Console.WriteLine("Press any key to continue...");
                    Console.WriteLine();
                    Console.ReadKey();
                }
                //mySerialPort.Close();
            }
            catch (System.IO.IOException e)
            {
                if (e.Source != null)
                    Console.WriteLine("IOException source: {0}", e.Source);
                throw;
            }
        }

        private static void DataReceivedHandler(
                            object sender,
                            SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string indata = sp.ReadExisting();
            Console.WriteLine("Data Received:");
            Console.Write(indata);
            Console.ReadKey();
        }
    }
}
Shawn Lou
  • 87
  • 1
  • 1
  • 6
  • 4
    Maybe 0.000001% of SO readers will have any knowledge of the device you're talking about. At least point to the doc on how to retrieve data from this - without that, I'm not sure how you're expecting anyone to spot the problem. Also, we need more precision here: "sometimes I can get the exacted weight and sometimes I couldn't. " - what happens when you couldn't? Do you get nothing back, a completely random value, zero, some approximation to the actul wait, an exception, a timeout.... – The Archetypal Paul Jan 14 '15 at 17:19
  • 1
    sorry for not being clear. http://www.perkinsscale.com/files/benchscales/manual1.pdf This is the document I gained the knowledge that how to retrieve the data. And when I could get the data, I could see for example, 150.00 LB on the screen. When I could not get the data, I will get a blank, or just a number like 15 where it should show me 150 LB on it. – Shawn Lou Jan 14 '15 at 17:24
  • 1
    Have you tried larger timeout values? The values are milliseconds. – hatchet - done with SOverflow Jan 14 '15 at 17:26
  • Since you seem to be gettting a truncated response, and since ReadExisting just returns what's available (in fact, it'snot clear if it waits at all), it does look like you're just not waiting long enough. As @hatchet says, try extending the timeouts and making sure you are using a method that does wait that long for something to arrive. – The Archetypal Paul Jan 14 '15 at 17:30
  • I would think a timeout value of 1000 to 5000 would be more appropriate. – hatchet - done with SOverflow Jan 14 '15 at 17:32
  • Yes, I tried 2000, but it was still not working. When I run the code after a while(5 minutes), it could work properly. However if I run it again immediately, it seems that I couldn't retrieve any data from that scale. – Shawn Lou Jan 14 '15 at 17:34
  • Thank you hatchet, I understand what's the problem now. I will fix it. I really appreciated it – Shawn Lou Jan 14 '15 at 17:43
  • Also, you might want to set the port's encoding. See [this question and answers](http://stackoverflow.com/questions/7178655/serialport-encoding-how-do-i-get-8-bit-ascii). – 500 - Internal Server Error Jan 14 '15 at 17:44

1 Answers1

0

Often with serial communication, you have to read multiple times, and concatenate each read, until you finally detect you've read the part that shows you've received it all. Detecting the end may be based on a specific count of bytes received, or it might be looking for a particular byte or sequence of bytes. But it's up to you to make that determination, and to continue reading until that condition is fulfilled. When you first read, there may be characters waiting, but the device has not sent them all yet, so you will have to read again almost immediately after your first read. You're dealing with a stream. The handler event fires when the stream starts, but it doesn't know how long the stream will flow.

This blog post discusses this and some other common serial port issues: http://blogs.msdn.com/b/bclteam/archive/2006/10/10/top-5-serialport-tips-_5b00_kim-hamilton_5d00_.aspx