我一直在尝试应用来自串行(波特率9600)的簧片数据并写入文本框,而不是将相同的数据写入图形,但它不起作用。它要么不执行任何操作,要么应用程序冻结,直到我的 RAM 耗尽,从我所看到的那一刻起,我连接到我的 arduino(我检查了 arduino IDE,它正确发送了数据)我的 RAM 使用量从 32-50 变为 1GB而且互联网没有任何解决方案我什至找不到同样的问题
这是我的代码
`using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.Security.Cryptography.X509Certificates;
using System.Data.Common;
using System.Windows.Forms.DataVisualization.Charting;
using System.Web.UI.DataVisualization.Charting;
namespace ArduinoSerial_Teknofest_
{
public partial class ArduinoSerial : Form
{
#region public veriables
public class Globals
{
public static Boolean Connected = false;
public static Boolean İfDisconnected = false;
}
/// To write information to console
public void WriteToConsole(string messege, string TextColor)
{
ConsoleLogs.SelectionColor = Color.FromName(TextColor);
ConsoleLogs.SelectedText += "/// " + messege + Environment.NewLine;
}
#endregion
public ArduinoSerial()
{
InitializeComponent();
// Get a list of serial port names.
PortsCB.Items.AddRange(SerialPort.GetPortNames());
//DataCharts.Series
}
private void ArduinoSerial_Load(object sender, EventArgs e)
{ /*
//Get the resulation of screen
System.Drawing.Rectangle ScreenResulation = Screen.PrimaryScreen.WorkingArea;
//Set size of form to 50% of screen size
this.Size = new System.Drawing.Size(Convert.ToInt32(0.5 * ScreenResulation.Width),Convert.ToInt32(0.5 * ScreenResulation.Height));
this.Location = new System.Drawing.Point(10, 10);
*/
}
public void Scan_click(object sender, EventArgs e)
{
// Get a list of serial port names.
string[] ports = SerialPort.GetPortNames();
PortsCB.Items.Clear();
PortsCB.Items.AddRange(ports);
WriteToConsole("Found PORTS = ", "Green");
foreach (string port in ports)
{
WriteToConsole(port, "Green");
}
}
public void ConnectButton_Click(object sender, EventArgs e)
{
string SelectedBaudRate = BaudRateCB.Text;
string SelectedPort = PortsCB.Text;
if (Device.IsOpen == false)
{
///Try to open the port if cant give an error
try
{
///Get user info
Device.BaudRate = int.Parse(SelectedBaudRate);
Device.PortName = SelectedPort;
Device.Open();
///Check if the port open, if it is disable user input bloccks
if (Device.IsOpen == true)
{
ConnectButton.Text = "Disconnect";
BaudRateCB.Enabled = false;
PortsCB.Enabled = false;
DataMenu.Enabled = true;
WriteToConsole("Connected", "green");
Device.Write("get/device/info");
}
}
catch (System.IO.IOException) { WriteToConsole("Something went wrong", "red"); }
///if post is used by other program output a error
catch (System.UnauthorizedAccessException)
{
WriteToConsole("port busy", "red");
Device.Close();
}
///if port is allready open output an error
catch (System.InvalidOperationException)
{
WriteToConsole("Port is already open", "red");
Device.Close();
}
catch (System.ArgumentNullException)
{
if (PortsCB.Text == "" && BaudRateCB.Text == "") { WriteToConsole("Please select a port and baudrate", "red"); }
else if (PortsCB.Text == "") { WriteToConsole("Please select a port", "red"); }
else if (BaudRateCB.Text == "") { WriteToConsole("Please select a baudrate", "red"); }
}
catch (System.ArgumentException)
{
if (PortsCB.Text == "" && BaudRateCB.Text == "") { WriteToConsole("Please select a port and baudrate", "red"); }
else if (PortsCB.Text == "") { WriteToConsole("Please select a port", "red"); }
else if (BaudRateCB.Text == "") { WriteToConsole("Please select a baudrate", "red"); }
}
catch (System.FormatException)
{
if (PortsCB.Text == "" && BaudRateCB.Text == "") { WriteToConsole("Please select a port and baudrate", "red"); }
else if (PortsCB.Text == "") { WriteToConsole("Please select a port", "red"); }
else if (BaudRateCB.Text == "") { WriteToConsole("Please select a baudrate", "red"); }
}
}
else if (Device.IsOpen == true)
{
WriteToConsole("Disconnected!!", "green");
Device.Close();
ConnectButton.Text = "Connect";
BaudRateCB.Enabled = true; ;
PortsCB.Enabled = true;
DataMenu.Enabled = false;
ConsoleLogs.Clear();
PositionGraph.Series["gyroX"].Points.Clear();
PositionGraph.Series["gyroY"].Points.Clear();
ChartCounter = 0;
}
}
string recivedData;
//List<double> time = new List<double>();
void Parachute_Status(string data)
{
int intData = int.Parse(data);
switch (intData)
{
case 1:
parachute1_Status.Text = "Not triggered";
parachute2_Status.Text = "Not triggered";
break;
case 2:
parachute1_Status.Text = "Triggered";
parachute2_Status.Text = "Not triggered";
break;
case 3:
parachute1_Status.Text = "Not triggered";
parachute2_Status.Text = "Triggered";
break;
case 4:
parachute1_Status.Text = "Triggered";
parachute2_Status.Text = "Triggered";
break;
}
}
private void dataRecived(object sender, SerialDataReceivedEventArgs e)
{
try
{
recivedData = Device.ReadLine();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "hata");
}
this.BeginInvoke(new EventHandler(ProcessData));
}
int ChartCounter;
private void gyroChart(string gyroDataX, string gyroDataY)
{
while (Device.IsOpen == true)
{
ChartCounter++;
PositionGraph.Series["gyroX"].Points.AddXY(double.Parse(gyroDataX), ChartCounter);
PositionGraph.Series["gyroY"].Points.AddXY(double.Parse(gyroDataY), ChartCounter);
}
}
private void ProcessData(object sender, EventArgs e)
{
try
{
string[] splitted_data = recivedData.Split('/');
//gyroChart(splitted_data[0], splitted_data[1]);
WriteToConsole(recivedData, "red");
//irtifa_Box.Text = splitted_data[0];
//GPS_Box.Text = splitted_data[1];
//Enlem_Box.Text = splitted_data[2];
//Boylam_Box.Text = splitted_data[3];
/*YGPS_Box.Text = splitted_data[4];
YEnlem_Box.Text = splitted_data[5];
YBoylam_Box.Text = splitted_data[6];
KGPS_Box.Text = splitted_data[7];
KEnlem_Box.Text = splitted_data[8];
KBoylam_Box.Text = splitted_data[9];
JiroskopX_Box.Text = splitted_data[0];
JiroskopY_Box .Text = splitted_data[1];
JiroskopZ_Box .Text = splitted_data[12];
gyroChart(JiroskopX_Box.Text, JiroskopY_Box.Text);
İvmeX_Box.Text = splitted_data[13];
İvmeY_Box.Text = splitted_data[14];
İvmeZ_Box.Text = splitted_data[15];
Aci_Box.Text = splitted_data[16];
CRC_Box.Text = splitted_data[17];
Parachute_Status(splitted_data[18]);
Heat_Box.Text = splitted_data[19];
*/
}
catch (System.IO.IOException)
{
WriteToConsole("error", "red");
return;
}
catch (System.IndexOutOfRangeException)
{
WriteToConsole("error", "red");
return;
}
catch (System.InvalidOperationException)
{
WriteToConsole("error", "red");
return;
}
} //Evde dock sistemlerine bak ve arayüz gelişimi için açık sayfalara bak
}
}
string[] splitted_data = recivedData.Split('/');
//gyroChart(splitted_data[0], splitted_data[1]);
WriteToConsole(recivedData, "red");
//irtifa_Box.Text = splitted_data[0];
//GPS_Box.Text = splitted_data[1];
//Enlem_Box.Text = splitted_data[2];
//Boylam_Box.Text = splitted_data[3];
/*YGPS_Box.Text = splitted_data[4];
YEnlem_Box.Text = splitted_data[5];
YBoylam_Box.Text = splitted_data[6];
KGPS_Box.Text = splitted_data[7];
KEnlem_Box.Text = splitted_data[8];
KBoylam_Box.Text = splitted_data[9];
JiroskopX_Box.Text = splitted_data[0];
JiroskopY_Box .Text = splitted_data[1];
JiroskopZ_Box .Text = splitted_data[12];
gyroChart(JiroskopX_Box.Text, JiroskopY_Box.Text);
İvmeX_Box.Text = splitted_data[13];
İvmeY_Box.Text = splitted_data[14];
İvmeZ_Box.Text = splitted_data[15];
Aci_Box.Text = splitted_data[16];
CRC_Box.Text = splitted_data[17];
Parachute_Status(splitted_data[18]);
Heat_Box.Text = splitted_data[19];
这部分确实不应该有任何评论。为了进行测试,我决定对它们发表评论
我也相信是导致错误的代码块,因为这部分应该将数据写入文本框等。
我无法给出错误,因为我是土耳其人,并用土耳其语给出了主要错误
我尝试更改波特率,但没有成功,因为这只是我被卡住的想法
using System;
using System.IO.Ports;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ArduinoSerial_Teknofest_
{
public partial class ArduinoSerial : Form
{
private SerialPort Device = new SerialPort();
public ArduinoSerial()
{
InitializeComponent();
Device.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
}
private async void ConnectButton_Click(object sender, EventArgs e)
{
if (!Device.IsOpen)
{
string SelectedBaudRate = BaudRateCB.Text;
string SelectedPort = PortsCB.Text;
try
{
Device.BaudRate = int.Parse(SelectedBaudRate);
Device.PortName = SelectedPort;
Device.Open();
if (Device.IsOpen)
{
ConnectButton.Text = "Disconnect";
BaudRateCB.Enabled = false;
PortsCB.Enabled = false;
DataMenu.Enabled = true;
WriteToConsole("Connected", "green");
// Start reading data asynchronously
await Task.Run(() => StartReadingData());
}
}
catch (Exception ex)
{
WriteToConsole($"Error: {ex.Message}", "red");
}
}
else
{
Device.Close();
ConnectButton.Text = "Connect";
BaudRateCB.Enabled = true;
PortsCB.Enabled = true;
DataMenu.Enabled = false;
ConsoleLogs.Clear();
PositionGraph.Series["gyroX"].Points.Clear();
PositionGraph.Series["gyroY"].Points.Clear();
}
}
private async Task StartReadingData()
{
while (Device.IsOpen)
{
try
{
string receivedData = await Device.ReadLineAsync();
ProcessData(receivedData);
}
catch (Exception ex)
{
WriteToConsole($"Error reading data: {ex.Message}", "red");
}
}
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
// This event will be raised when new data is received,
// but we'll handle data reading asynchronously
}
private void ProcessData(string data)
{
// Process and update UI with received data
this.BeginInvoke(new Action(() => WriteToConsole(data, "red")));
// Update other UI elements as needed
}
private void WriteToConsole(string message, string color)
{
// Write message to console
ConsoleLogs.SelectionColor = Color.FromName(color);
ConsoleLogs.SelectedText += $"/// {message}{Environment.NewLine}";
}
}
}
在此代码中:
当设备成功连接时,ConnectButton_Click 事件处理程序现在开始使用 StartReadingData() 方法异步读取数据。 StartReadingData 方法使用 ReadLineAsync() 方法从串行端口异步连续读取数据。 每当从串行端口接收到新数据时,就会调用 DataReceivedHandler 事件处理程序。在这种情况下,它只是一个占位符,因为我们正在异步处理数据读取。 ProcessData 方法处理接收到的数据并更新 UI。它是使用 BeginInvoke 异步调用的,以从非 UI 线程更新 UI 控件。 WriteToConsole 方法用于将指定颜色的消息写入控制台。