none
Exception thrown: Object reference not set to an instance of an object RRS feed

  • Question


  • namespace trial

    { class serial_function { Form1 p_form; List<byte> Stepper_Respone_buffer = new List<byte>(1024); //1 page of memory is allocated by default, and the limit is always allowed to exceed List<string> Stepper_Prase_buffer = new List<string>(10); int received_count = 0; string strPath = Application.StartupPath; public static string cmd_backup; public static string current_position = "0"; public int current_pos_backup = -1; public static string Scaning_Runing_cmd; public static string Scaning_gozero_cmd; public static string Scaning_goposition_cmd; public int count_get_current_position = 0; public bool _isReceiving = false; public bool _isbusy = false; public int ini_step = 0; public int need_send_scanning_cmd = 0; public int need_send_gosposition_cmd = 0; public int need_stop = 0; public int need_gotohome = 0; public static int gozero_still_flag = 0; static string s; public enum Data_type { No_Prase, Prase_Status1, Prase_Status2, Prase_Status3, Prase_Status, Prase_Vaule, Prase_Next_Value, } public Data_type Set_Data_type = Data_type.No_Prase; public void Set_Cur_Data_type_Vaule() { Set_Data_type = Data_type.Prase_Vaule; } public void Set_Cur_Data_type_None() { Set_Data_type = Data_type.No_Prase; } public void Set_Cur_Data_type_Next_Value() { Set_Data_type = Data_type.Prase_Next_Value; } public void Set_Scaning_Run_Ntime(string cmd) { Set_Data_type = Data_type.Prase_Next_Value; Scaning_Runing_cmd = cmd; need_send_scanning_cmd = 1; } public void Set_Scaning_Go_Zero(string cmd) { Set_Data_type = Data_type.Prase_Next_Value; Scaning_gozero_cmd = cmd; need_send_scanning_cmd = 1; } public void Set_Scaning_Go_sposition(string cmd) { Set_Data_type = Data_type.Prase_Next_Value; Scaning_goposition_cmd = cmd; need_send_gosposition_cmd = 1; } public void Set_Form(Form1 form) { p_form = form; } /* * Get the serial port list of this machine */ public void GetComList() { try { RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm"); if (keyCom != null) { string[] sSubKeys = keyCom.GetValueNames(); //p_form.comboBox1.Items.Clear(); foreach (string sName in sSubKeys) { string sValue = (string)keyCom.GetValue(sName); //cb.Items.Add(sValue); p_form.comboBox1.Items.Add(sValue); } if (p_form.comboBox1.Items.Count >= 1) p_form.comboBox1.SelectedIndex = 0; } } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } } /* * Open serial port */ public void Serial_Port_Open(string portname) { try { if (p_form.btn_connect.Text == "Connect") { p_form.serialPort1.PortName = portname; p_form.serialPort1.BaudRate = 9600; p_form.serialPort1.DataBits = 8; p_form.serialPort1.StopBits = StopBits.One; p_form.serialPort1.Parity = Parity.None; p_form.serialPort1.WriteTimeout = 1000; p_form.serialPort1.ReadTimeout = 1000; p_form.serialPort1.ReadBufferSize = 256; if (!p_form.serialPort1.IsOpen) { p_form.serialPort1.Open(); p_form.serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived); p_form.serialPort1.ReceivedBytesThreshold = 1; //Get_Stepper_Respone_Thread = new Thread(Get_Stepper_Respone_Function); // Get_Stepper_Respone_Thread.IsBackground = true; // Get_Stepper_Respone_Thread.Start(); Set_Data_type = Data_type.Prase_Status3; Serial_Port_Send_Cmd("/" + Prase_Calibration_file.Add.ToString() + "m" + Prase_Calibration_file.MoveCrnt.ToString() + "h" + Prase_Calibration_file.HoldCrnt.ToString() + "f" + Prase_Calibration_file.OptoFlag.ToString() + "R\r"); } else { Set_Data_type = Data_type.Prase_Status3; Serial_Port_Send_Cmd("/" + Prase_Calibration_file.Add.ToString() + "h" + Prase_Calibration_file.HoldCrnt.ToString() + "f" + Prase_Calibration_file.OptoFlag.ToString() + "R\r"); } } else { p_form.btn_connect.Text = "Connect"; p_form.status_check.Text = "Not connected"; p_form.status_check.ForeColor = Color.Red; Serial_Port_Close(); } } catch (Exception ex) { Serial_Port_Close(); MessageBox.Show("Com Port \n" + portname + "\" Open Failed!\r\n" + ex.Message, "Open", MessageBoxButtons.OK, MessageBoxIcon.Error); } } /* * Close the serial port */ public void Serial_Port_Close() { p_form.serialPort1.DataReceived -= serialPort1_DataReceived; //Exception thrown int i = Environment.TickCount; while (Environment.TickCount - i < 2000 && _isReceiving == true) Application.DoEvents(); p_form.serialPort1.Close(); } /* * Serial port receiving data entry */ public void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { _isReceiving = true; p_form.send_cmd_count = 0; try { Thread.Sleep(50); int n = p_form.serialPort1.BytesToRead; if (n <= 0) return; byte[] readBuffer = new byte[n]; p_form.serialPort1.Read(readBuffer, 0, n); received_count += n;//Increase the receive count //1.Cache data Stepper_Respone_buffer.AddRange(readBuffer); //2.Integrity judgment for (int i = 0; i < Stepper_Respone_buffer.Count; i++) { Stepper_Prase_buffer.Add(Stepper_Respone_buffer[i].ToString("X2")); } s = string.Join(" ", Stepper_Prase_buffer.ToArray()); if (Prase_Calibration_file.Logstatusflag == 1) { p_form.loginfo.Loginfo(strPath + "/Logs/Log", "receive data " + s); } if (Stepper_Respone_buffer[3] == 0x60) //0x60= 96 p_form.Statusready(Prase_Calibration_file.Add.ToString()); else p_form.Statusbusy(Prase_Calibration_file.Add.ToString()); Stepper_Prase_buffer.Clear(); while (Stepper_Respone_buffer.Count >= 6) { int index = Stepper_Respone_buffer.FindIndex((delegate(byte d) { return d == 0x03; })); if (Stepper_Respone_buffer[0] == 0xFF && Stepper_Respone_buffer[1] == 0x2F && index > 3 && Stepper_Respone_buffer[index + 1] == 0x0D && Stepper_Respone_buffer[index + 2] == 0x0A) { byte[] readdata = new byte[index + 3]; Stepper_Respone_buffer.CopyTo(0, readdata, 0, index + 3); Serial_Data_Prase(readdata, index + 3); Stepper_Respone_buffer.RemoveRange(0, index + 3); received_count -= index + 3; } else { Thread.Sleep(150); Serial_Port_Send_Cmd("/" + Prase_Calibration_file.Add.ToString() + "?0\r"); Set_Data_type = Data_type.Prase_Vaule; break; } } Stepper_Respone_buffer.RemoveRange(0, received_count);//Receiving an erroneous data also requires removing the data from the cache. received_count = 0; _isReceiving = false; } catch { Stepper_Respone_buffer.RemoveRange(0, received_count);//Receiving an erroneous data also requires removing the data from the cache received_count = 0; _isReceiving = false; } } /* * Send commands to the motor drive */ public void Serial_Port_Send_Cmd(string cmd) { try { p_form.send_cmd_count++; cmd_backup = cmd; if (Prase_Calibration_file.Logstatusflag == 1) { p_form.loginfo.Loginfo(strPath + "/Logs/Log", "sent cmd" + cmd_backup + "\n"); } p_form.serialPort1.WriteLine(cmd); } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } }


    This code block is  to open and connect to a COM port and make the stepper motor to drive through PC. I have this code for a different application and i am using this the same code for another similar application. While i changed the code in the application working part, this code remains untouched since it is to get serial port and make a connection. However exception is thrown and i have no idea where it is wrong. Thank you in Advance.
    Friday, July 26, 2019 2:00 PM

All replies

  • Hello,

    What line of code is the exception being thrown on?


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Friday, July 26, 2019 2:28 PM
    Moderator
  • As Karen mentioned, it would be better to know where exactly the error is thrown. I see one potential problem that could cause it: in several places you are calling methods on p_Form. If p_Form is not initialized, you will get the "Object reference not set..." error. But p_Form is only initialized from the Set_Form method. So if you call any of the other methods before calling Set_Form you will see this error. This may be the reason why the (unchanged) code was working in your other projects: maybe these other projects called Set_Form, but you forgot to call Set_Form in the project that is throwing the error.
    Sunday, July 28, 2019 12:58 PM
    Moderator