串行端口在Form3中关闭

  • 本文关键字:Form3 串行端口 c#
  • 更新时间 :
  • 英文 :


我在Form3中写入串行端口时遇到问题。我能够从表1中的串行端口进行写/读操作。我可以连接到表2中的串行端口。但是,当我尝试从3写入串行端口时。我收到一个错误,说串行端口关闭了,这很奇怪,因为我没有关闭串行端口。我一直在互联网上寻找解决方案,但我没有找到有助于我的情况的解决方案。我不能使用静态串行端口,因为我的程序有一个包含所有可用端口的下拉菜单,用户可以选择使用哪个串行端口。

表单1代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using ZedGraph;
using System.Text.RegularExpressions;
namespace ECE
{

public partial class Form1 : Form
{
PointPairList list = new PointPairList();
double temp;
int flag = 1;
double x = 0;
int init = 0;
int digit = 0;
double temp1;


private T_settings t_settings;

private Bluetooth_Settings _setting = new Bluetooth_Settings();
public Form1()
{
InitializeComponent();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{

int text_length = 0;

text_length = richTextBox1.TextLength;
char send_ch = richTextBox1.Text[text_length - 1]; // extracting the last character
char[] ch = new char[1];
ch[0] = send_ch;
if (send_ch == 'n')
{
_setting._serial.Write("r"); // sending carraige return 
}
else
{
_setting._serial.Write(ch, 0, 1); // sending char to microcontroller
}
}
private void blueToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void toolStripProgressBar1_Click(object sender, EventArgs e)
{
}
private void COMPortToolStripMenuItem_Click(object sender, EventArgs e)
{
_setting.Show();                                 
_setting._serial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);                          
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;

if (sp.BytesToRead > 0)
{
byte[] buffer = new byte[sp.BytesToRead];
int count = sp.Read(buffer, 0, sp.BytesToRead);
Extract_each_Character(buffer, count);

}

}
private void Extract_each_Character(byte[] buffer, int count)
{
byte data;
for (int i = 0; i < count; i++)
{
data = buffer[i];
this.Invoke(new EventHandler(update_richtextbox1), new object[] { data });
}
}
private void update_richtextbox1(object sender, EventArgs e)
{


byte data = (byte)sender;
char s = Convert.ToChar(data);
richTextBox1.TextChanged -= new EventHandler(richTextBox1_TextChanged); // removing text changed event 
richTextBox1.AppendText(s.ToString());
SerialPort1_DataReceived(s.ToString());
richTextBox1.TextChanged += new EventHandler(richTextBox1_TextChanged); // adding text changed event

}
private void SerialPort1_DataReceived(string s)
{

if (s.Length != 0)
{
if (s.Contains("Celcuis")) // Celcuius 
{
flag = 1;

}

else if (s.Contains("Fahrenheit")) // Farenhieght
{
flag = 2;                   
}
else if (s.All(char.IsDigit))
{
AddTextToLabel(s);
}

}
}
private void Form1_Load(object sender, EventArgs e)
{
//CreateChart(zedGraphControl1);
}

private void CreateChart(ZedGraphControl zedGraphControl1)
{
// Declare a new GraphPane Object 
GraphPane myPane = zedGraphControl1.GraphPane;
if (init == 0)
{
// Set the titles and axis labels
myPane.Title.Text = "Moffat Omuya Temp. Graph";
myPane.XAxis.Title.Text = "Time, Seconds";
myPane.YAxis.Title.Text = "Temprature in F";
// Make up some data pointw based on the Sine function 
// Note: All data being plotted by zedgraph have to be “Double” format.
// Data should be saved as a PointPairList before plotting.
// So “List.Add()” method should be called after you define or
// change the data that are plotted.
// Generate a red curve with diamond symbols, and "Alpha" in the legend

LineItem myCurve = myPane.AddCurve("Fahrenheight", list, Color.Red);
// Fill the symbols with white
myCurve.Symbol.Fill = new Fill(Color.White);
// Generate a blue curve with circle symbols, and "Beta" in the legend
//Some enhancing setting:
// Show the x axis grid
init = 1;
}
else if (init == 1)
{
myPane.XAxis.MajorGrid.IsVisible = true;
// Make the Y axis scale red
myPane.YAxis.Scale.FontSpec.FontColor = Color.Red;
myPane.YAxis.Title.FontSpec.FontColor = Color.Red;
// Don't display the Y zero line
myPane.YAxis.MajorGrid.IsZeroLine = false;
// Align the Y axis labels so they are flush to the axis
myPane.YAxis.Scale.Align = AlignP.Inside;
// Manually set the axis range
myPane.YAxis.Scale.Min = 0;
myPane.YAxis.Scale.Max = 100;
// Fill the axis background with a gradient
myPane.Chart.Fill = new Fill(Color.White, Color.LightGray, 45.0f);
// Calculate the Axis Scale Ranges
//Note: ZedGraphControl.AxisChange() command keep checking and
// adjusting the display axis setting according to the List changes.
zedGraphControl1.AxisChange();
}

}

public void AddTextToLabel(string str)
{


if (flag == 1) // Celcuis 
{
//list Adding Function 1;
if (digit == 0)
{
temp = Double.Parse(str);
digit++;
}
else if (digit == 1)
{
temp1 = Double.Parse(str);
temp = temp * 10 + temp1;
digit++;
}

else if (digit == 2)
{
double y = temp;
//digit = 0;
temp = 0;
temp1 = 0;
digit =0;
x++;
list.Add(x, y);
zedGraphControl1.Invalidate();
CreateChart(zedGraphControl1);
}

else if (digit == 3)
{
temp1 = Double.Parse(str);
digit++;
}
else if (digit == 4)
{
temp = Double.Parse(str);
temp = temp * 10 + temp1;
digit++;
}
else if (digit == 5)
{
double y = temp;
digit = 0;
temp = 0;
temp1 = 0;

x++;
list.Add(x, y);
zedGraphControl1.Invalidate();
CreateChart(zedGraphControl1);
}

}
if (flag == 2) // Farenheight
{
//List Adding Function 2;
if (digit == 0)
{
temp = Double.Parse(str);
digit++;
}
else if (digit == 1)
{
temp1 = Double.Parse(str);
temp = temp * 10 + temp1;
digit++;
}
else if (digit == 2)
{
double y = temp;
//digit = 0;
temp = 0;
temp1 = 0;
digit++;
x++;
list.Add(x, y);
zedGraphControl1.Invalidate();
CreateChart(zedGraphControl1);
}
else if (digit == 3)
{
temp1 = Double.Parse(str);
digit++;
}
else if (digit == 4)
{
temp = Double.Parse(str);
temp = temp * 10 + temp1;
digit++;
}
else if (digit == 5)
{
double y = temp;
digit = 0;
temp = 0;
temp1 = 0;

x++;
list.Add(x, y);
zedGraphControl1.Invalidate();
CreateChart(zedGraphControl1);
}

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

}
private void Toggle_Click(object sender, EventArgs e)
{
// 2 = F , 1 = C
char[] ch = new char[1];


ch[0] = 'D';

_setting._serial.Write(ch, 0, 1); // sending char to microcontroller


}

private void bluetoothSettingsToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void Settings_Click(object sender, EventArgs e)
{
t_settings = new T_settings();
t_settings.Show();
}
}
}

在Form one中,我有两个函数可以写入名为Toggle_Click和arichTextBox1_TextChanged的sereial端口。

Form2代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports; // added this 
namespace ECE
{
public partial class Bluetooth_Settings : Form
{
public  SerialPort _serial = new SerialPort(); // added this 
public Bluetooth_Settings()
{
InitializeComponent();
_serial.BaudRate = int.Parse(baud_rate.Text); // added this 
foreach (string s in SerialPort.GetPortNames()) // added this 
{
com_port.Items.Add(s);
}
}


private void Bluetooth_Settings_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void connet_button_Click(object sender, EventArgs e)
{
try
{
_serial.PortName = com_port.SelectedItem.ToString();
_serial.BaudRate = Convert.ToInt32(baud_rate.SelectedItem);
_serial.Open();
this.Close();
Form1 _main = new Form1();
foreach (Form1 tmpform in Application.OpenForms)
{
if (tmpform.Name == "Form1")
{
_main = tmpform;
break;
}
}

_main.toolStripStatusLabel1.Text = " Connected: " + _serial.PortName.ToString();
_main.toolStripStatusLabel1.ForeColor = Color.Green;
_main.toolStripProgressBar1.Value = 100;
}
catch
{
MessageBox.Show("Please select COM Port/ Baud Rate");
}            
}
private void Bluetooth_Settings_Load_1(object sender, EventArgs e)
{
}
}
}

在Form 2中,我进行串行端口连接。

表单3代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports; // added this 
namespace ECE
{

public partial class T_settings : Form
{


private Bluetooth_Settings _enter = new Bluetooth_Settings();

public T_settings()
{
InitializeComponent();

}
string Sampling_text;
//Dim COMPort = Form1.COMPort

private void Average_Click(object sender, EventArgs e)
{
}
private void T_settings_Load(object sender, EventArgs e)
{
}

private void Text_Sampling_TextChanged(object sender, EventArgs e)
{
Sampling_text = Text_Sampling.Text;

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

int text_length = 0;
text_length = Sampling_text.Length;
char send_ch = Text_Sampling.Text[text_length - 1]; // extracting the last character
char[] ch = new char[1];
ch[0] = send_ch;
if (send_ch == 'n')
{
_enter._serial.Write("r"); // sending carraige return 
}
else
{
_enter._serial.Write(ch, 0, 1); // sending char to microcontroller
}
char[] enter = new char[1];


}
}
}

中三是我遇到麻烦的表格。在发送采样点击功能中,我收到一个错误,说当我试图写入时,串行端口关闭了。

首先,当您创建实例Bluetooth_Settings时,会出现两个问题。除非您已经在表单中硬编码了默认值,否则不会配置任何设置(文本框值(。

其次,主要问题是当你从form3 写入时,端口没有打开

private Bluetooth_Settings _enter = new Bluetooth_Settings();

基本上它是在form2中工作的,因为您有打开端口和设置其他设置的按钮事件,可能您应该从调用者传递值,并从form3 提供打开端口等的方法

_serial.PortName = com_port.SelectedItem.ToString();
_serial.BaudRate = Convert.ToInt32(baud_rate.SelectedItem);
_serial.Open();

最新更新