-1

I need help. I my form to receive data from my Arduino through Serial Communication. But when I try to read data, I always get NullReferenceException. My system is a simple counter. Before the number in the screen gets incremented, it needs to see how many times the button was pressed from the Arduino and sends it to Visual Studio. I don't know what I am doing wrong.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using WMPLib;

namespace ComputerToArduino
{
    public partial class Form2 : Form
    {
        static SerialPort myPort;
        int CECSTnumber = 0;//number on screen
        int CEBMnumber = 0;
        int CECSTLastTicket = 0;//Amount of numbers this button was pressed
        int CEBMLastTicket = 0;//Amount of numbers this button was pressed
        string LastButtonPressed = "";//what button was last pressed?

        public Form2(SerialPort port)
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
        }

        private void Form2_Load(object sender, EventArgs e) { }

        public void CheckLastButton()//Check how many times the buttons were pressed
        {
            LastButtonPressed = myPort.ReadExisting();//NullReferenceException points here

            if (LastButtonPressed == "a")//if CECST button was pressed
            {
                CECSTLastTicket++;
            }
            else if (LastButtonPressed == "b")//if CEBM
            {
                CEBMLastTicket++;
            }
        }

        private void button3_Click(object sender, EventArgs e)//play movie
        {
            axWindowsMediaPlayer1.URL = @"D:\Movies\Movie.mp4";
        }

        private void axWindowsMediaPlayer1_Enter(object sender, EventArgs e) { }

        private void axWindowsMediaPlayer1_ErrorEvent(object sender, EventArgs e) { }

        private void axWindowsMediaPlayer1_MediaError(object sender, AxWMPLib._WMPOCXEvents_MediaErrorEvent e)
        {
            try
            // If the Player encounters a corrupt or missing file, 
            // show the hexadecimal error code and URL.
            {
                IWMPMedia2 errSource = e.pMediaObject as IWMPMedia2;
                IWMPErrorItem errorItem = errSource.Error;
                MessageBox.Show("Error " + errorItem.errorCode.ToString("X") + " in " + errSource.sourceURL);
            }
            catch (InvalidCastException)
            // In case pMediaObject is not an IWMPMedia item.
            {
                MessageBox.Show("Error.");
            }
        }

        private void button2_Click(object sender, EventArgs e) //CECSTincrement
        {
            CheckLastButton();
            if (CECSTnumber > CECSTLastTicket)
            {
                //do nothing
            }
            else
            {
                //CECSTnumber++;
                //CECSTlabel.Text = CECSTnumber.ToString("D3");
                CECSTlabel.Text = Convert.ToString(CECSTLastTicket);
            }
        }

        private void CEBMbutton_Click(object sender, EventArgs e) //CEBMincrement
        {
            CheckLastButton();
            if (CEBMLastTicket > CEBMnumber)
            {
                //do nothing
            }
            else
            {
                CEBMnumber++;
                CEBMlabel.Text = CEBMnumber.ToString("D3");
            }
        }

        public void setSerialPort(SerialPort port)
        {
            myPort = port;
        }
    }
}

I will reply as fast as possible if my question is not clear. Thank you in advance.

Presto
  • 806
  • 9
  • 24
Dan
  • 3
  • 1
  • How do you set `myPort`? `setSerialPort` isn't used and the other place is commented out. – Imantas Jan 17 '19 at 10:00
  • It's because you commented this part `//myPort = port; ` – Renatas M. Jan 17 '19 at 10:11
  • I already set my connection on the first form. Should I post the code for the other form? Also, there is another myPort = port near the bottom. I commented it out because its already there. – Dan Jan 17 '19 at 10:15

1 Answers1

0

It seems that myPort is null. It is never initialized. It is only every initialized in setSerialPort() which is never called. Just make sure you have instantiated myPort with a proper port and then try again.

In case you want to know about Serial Port communication: You need to know following information about the serial port you are looking for to communicate with it: - name of port (like, COM1, COM2, COM3, etc) - Baud rate (aka, bits per second), parity, databits, stop bits. etc

Where to find this information (Windows only): You can get this information by opening "Device Manager" then expand "Ports (COM & LPT)" node, and under it you will find the device you want to communicate with, lets say it is "Communications Port (COM1)". Right click it and select Properties. then go to "Port Settings" tab. There you can see all the required information.

Example usage: In my case the Port name is COM1, buad rate is 9600, data bits 8, parity None, and stop bits 1. so i would do: myPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);

and then use it to get data.

Hope this solves your problem.

  • Thank you. so myPort.readExisting() is the one who is null? I already set a connection from the form1. – Dan Jan 17 '19 at 10:36
  • myPort is null. that is why readExisting() cannot be called on it. Please place a breakpoint on the line containing myPort.readExisting. then debug you application to check if myPort is null or not. and make sure this variable is getting value at some point prior to reading. – Jahangir Shah Jan 17 '19 at 10:43