Click here to Skip to main content
15,888,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, guys

Newbie here. I have question about debugging. My code runs well when I debugging step by step, but show me the different result when I compile it. Anyone could tell me what could be the reason cause this kind of problem. Thanks a lot!

This is a form application that allow me to communicate with a micro controller with serial port.
My thought is to initiate the serial port first, set port number, baud rate, parity, stop bit. Then checking the initial status of an electrical unit, ON or OFF, by sending the command and then check the response from micro controller. After I know the initial status, I can click button, which also sending the command to turn ON or OFF the electrical unit.

For example, I've set the electrical unit ON, so, I suppose to see the "ON" status when I run the program. When I debug the code step by step, I got the right response from the controller and the status of the electrical unit is "ON", which is right. But if I just compile the code or run the *.exe file, the result is different, it show "OFF". I suspect there might be some problem with communication part, but I can't find it.

Let me know if there is anything not clear, I will keep modify it.
It's quite a long reading, so thank you for you time!

Here is the code.

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SerialComm;
using System.Threading;


namespace BasicGUI
{
    public partial class Form1 : Form
    {
        public Form1()
        {

            InitializeComponent();
        
        }

        private void SHUTbutton_Click(object sender, EventArgs e)
        {
            PortChat sendcommand = new PortChat();
            sendcommand.SendCmd("010101000003"); // Open Shutter
            Thread.Sleep(100);
        }

        private void QSWbutton_Click(object sender, EventArgs e)
        {
            //check Qsw status, if Qsw is on, Click turn it OFF, otherwise turn it on
            char[]  tempStatus = new char[60];
            char[] tempStatus1 = new char[60];
            char[] tempStatus2 = new char[60];
            PortChat flagCheck = new PortChat();
            
            tempStatus = flagCheck.SendCmd("00080008");
            
            Thread.Sleep(100);
            flagCheck.flushBuff();
            bool qswBit = flagCheck.bitCheck(tempStatus[5],4);
            //byte qswFlag = (byte)(tempStatus[5] - '0');
            
            //int status = (qswFlag & 0x04);
            if (qswBit == false) // Qsw is OFF
            {
                //PortChat sendcommand1 = new PortChat();
                tempStatus2 = flagCheck.SendCmd("010201000004"); // Turn ON Qswitch 

                Thread.Sleep(100);
                flagCheck.flushBuff();
                QSWbutton.Text = "On";
                String result1 = new String(tempStatus2);

                basicStatus.Text = result1;
               
            }
            else
            {
                //PortChat sendcommand = new PortChat();
                tempStatus1 = flagCheck.SendCmd("010200000003"); // Turn OFF Qswitch 

                Thread.Sleep(100);
                flagCheck.flushBuff();
                QSWbutton.Text = "Off";
                String result = new String(tempStatus1);
                basicStatus.Text = result;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Initialize the COMport
            char[] status = new char[60];

            PortChat ComportInit = new PortChat();
            ComportInit.PortInit();


            //  status check, check the Qsw and Shutter status

            //PortChat CheckStatus = new PortChat();
            status = ComportInit.SendCmd("00080008"); //

            Thread.Sleep(100);
            ComportInit.flushBuff();
            //check Q switch bit status

            bool Qswbit = ComportInit.bitCheck(status[5], 4);
            //byte tempStatus = (byte)(status[5] - '0');
            //int tempStatus = (int)('a' - '0');
            //Byte basicStatus = (byte)(tempStatus);

            //char test = 'f';
            //byte test1 = (byte)(test);
            //int QswStatus = (tempStatus & 0x04); //QswStatus

            if (Qswbit == true) // check Qsw status 0100
            {
                QSWbutton.Text = "ON";

            }
            else
            {
                QSWbutton.Text = "OFF";
            }

            String Basicstatus = new String(status);
            basicStatus.Text = Basicstatus;
        }

            }


}



Here is the communication part

C#
using System;
using System.IO.Ports;
using System.Threading;
namespace SerialComm
{

    public class PortChat
    {
        static SerialPort _serialPort;
        private int num_Response;
        private char[] responseChar = new Char[60];
        // setup baudrate, parity, stopbit
        public void PortInit()
        {
            // Create a new SerialPort object with default settings.
            _serialPort = new SerialPort();
            // Allow the user to set the appropriate properties.
            _serialPort.PortName = "COM4";
            // Console.WriteLine("Serial Port set to COM4");
            _serialPort.BaudRate = 19200;
            // Console.WriteLine("BaudRate set to 19200");
            //_serialPort.Parity = 0;
            _serialPort.Parity = Parity.None;
            //Console.WriteLine("None Parity");
            _serialPort.DataBits = 8;
            // Console.WriteLine("8 data bits");
            //_serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits),"One");
            _serialPort.StopBits = StopBits.One;
            // Console.WriteLine("One stop bit");

            // Set the read/write timeouts
            _serialPort.ReadTimeout = 500;
            _serialPort.WriteTimeout = 500;
            _serialPort.Open();
        }

        //send command and return the response form controller
        public char[] SendCmd(string command)
        {
            //string command;
            char[] commandChar = new Char[60];
            // StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
            // Thread readThread = new Thread(Read);

            //_continue = true;
            // readThread.Start();
            commandChar = command.ToCharArray();
            //commandChar[i] = Console.Read;
            // }
            // System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

            _serialPort.Write(commandChar, 0, commandChar.Length);
            _serialPort.Write("\r"); //send the cartridge return character after the command

            num_Response = _serialPort.Read(responseChar, 0, 60);
           // _serialPort.DiscardInBuffer();
            return responseChar;

            // Console.WriteLine("Length of the response {0}", num_Response);
            //Write the response
            //int i = 0;
            //for (i = 0; i < num_Response; i++) ;
            //     Console.Write(feedbackChar[i]);
            //  Console.WriteLine();
            // }

        }
        // check the bit is 1 or 0
        public bool bitCheck(char charInput, int check)
        {
            int char2int = 0;
            int checkResult = 0;
            if (((charInput) < '9') && ((charInput) > '0')) //charIn is number 0 ~ 9
            {
                char2int = (charInput - 48);
                //Console.WriteLine(char2int);
                checkResult = (char2int & check);
                //Console.WriteLine(checkResult);
            }
            else if (((charInput) > 'A') && ((charInput) < 'F')) //charIn is letter A ~ F
            {
                char2int = (charInput - 55);
                //Console.WriteLine(char2int);
                checkResult = (char2int & check);
                //Console.WriteLine(checkResult);
            }
            if (checkResult > 0)
                return true;  // this bit is 1
            else
                return false; // this bit is 0
        }

        public void flushBuff()
        {
            _serialPort.DiscardInBuffer();
        }

        //public void GetResponse()
        //{
        //    char[] responseChar = new Char[60];
        //    int num_Response;
        //    int i = 0;
        //    num_Response = _serialPort.Read(responseChar, 0, 60); //read response from buffer
        //    for (i = 0; i < num_Response; i++)
        //    {
        //    }

        //}
        //  readThread.Join();
        // _serialPort.Close();
    }
}
//public static void Read()
//{
//    while (_continue)
//    {
//        try
//        {
//            string message = _serialPort.ReadLine();
//            Console.WriteLine(message);
//        }
//        catch (TimeoutException) { }
//    }
//}
//}
Posted
Updated 29-Jun-10 8:10am
v5
Comments
Sandeep Mewara 29-Jun-10 2:02am    
What do you mean by 'show me the different result when it run normally'? Code won't do anything automatically until it's written!
liang306 29-Jun-10 9:48am    
Sorry for the misunderstanding, I mean when I compile it, the result is different from when I debugging it.
William Winner 29-Jun-10 12:15pm    
ok...I'm going to try again...hopefully you don't get two of these comments...

What exactly is the difference between when you compile it and debug it? Is it not writing to the serial port what you are expecting? How do you know it's different?

You provided a lot of code that probably has nothing to do with your problem, so it would help us a lot if you could provide more specific detail into what is different.
liang306 29-Jun-10 13:47pm    
First of all, thank you very much for reply. Really appreciated.
OK, the difference.
For example, I've set the electrical unit ON, so, I suppose to see the "ON" status when I run the program. When I debug the code step by step, then I can see I got the right response from the controller and the status of the electrical unit is "ON", which is right. But if I just compile the code or run the *.exe file, the result is different, it show "OFF". I suspect there might be some problem with communication part, but I can't find it.

My guess would be that because you were debugging, when you stepped through, you provided enough time for the unit at the other end of the serial port to complete it's tasks, but during compile, it doesn't have enough time.

For instance, you write to the serial port and tell it to turn on. Then, right away, you check it's status. (or at least that's what it looks like.

But, in between the two, is only a single cpu cycle, while on the unit, it might take more time.

One thing you might try is to put a sleep call right after

C#
_serialPort.Write("\r"); //send the cartridge return character after the command


in your SendCmd routine.

Start higher, and then slowly cut the time until you are consistently providing enough time for the unit to respond.
 
Share this answer
 
Comments
liang306 29-Jun-10 14:53pm    
My friendo! u know what, U ARE RIGHT!!!
I need a 15 millisecond delay before I read the Serial Input buffer. How could I forgot that.
Anyway, William, thank you very much for helping me out! For all you guys taking time to read this, thank you for your time!
liang306 29-Jun-10 14:55pm    
Reason for my vote of 5
This dude give me the right answer.
It is difficult to give you an answer without looking at your code.
Trying cleaning your solution once by going to build -> clean solution.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900