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.