ผมลองเปลี่ยนโค๊ดภาษาซีที่ไมโครคอนโทรลเลอร์ printf("%3.2f,%3.2f",fTemp_true,fRh_true); แล้วครับค่าที่ส่งมาจะได้ไม่มี T กับ H ข้างหน้า แต่พอรันแล้วโปรแกรมมันค้างครับผมลองเขียนแบบอื่นๆโปรแกรมมันก็ค้างตลอดเลยครับ ไม่ทราบว่าต้องแก้ยังไงครับ
namespace TestSerial
{
public partial class Form1 : Form
{
private System.IO.Ports.SerialPort ComPort;
public Form1()
{
InitializeComponent();
try
{
this.ComPort = new System.IO.Ports.SerialPort("COM6", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
this.ComPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(ComPort_DataReceived);
this.ComPort.Open();
}
catch (System.Exception e)
{
//Error Message e
Console.WriteLine("Exception caught here" + e.ToString());
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
string strData="";
private void ComPort_DataReceived(Object sender,System.IO.Ports.SerialDataReceivedEventArgs e)
{
strData = this.ComPort.ReadExisting();
this.Invoke(new EventHandler(Test));
}
private void Test(object sender,EventArgs e){
string[] strOut = strData.Split(',');
textBox1.Text = strOut[0];
textBox2.Text = strOut[1];
}
โค๊ดนี้ตอนรันโปรแกรมแล้วมันค้างแล้วมีไดอะล็อกเขียนว่า Index was outside the bounds of the array. ครับ ผมลองเขียนอีกแบบนึงตามโค๊ดด้านล่างครับแต่ก็ยังค้างครับคนละที่กัน
namespace TestSerial
{
public partial class Form1 : Form
{
private System.IO.Ports.SerialPort ComPort;
public Form1()
{
InitializeComponent();
try
{
this.ComPort = new System.IO.Ports.SerialPort("COM6", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
this.ComPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(ComPort_DataReceived);
this.ComPort.Open();
}
catch (System.Exception e)
{
//Error Message e
Console.WriteLine("Exception caught here" + e.ToString());
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void ComPort_DataReceived(Object sender, EventArgs e)
{
if (this.InvokeRequired == true)
{
try
{
this.BeginInvoke(new EventHandler<EventArgs>(ComPort_DataReceived), new object[] { sender, e });
}
catch (Exception ex)
{
MessageBox.Show(ex.InnerException.Message);
}
}
else
{
string strData = this.ComPort.ReadExisting();
string[] strOut = strData.Split(',') ;
textBox1.Text = strOut[0] ;
textBox2.Text = strOut[1];
}
โค๊ดนี้ตอนรันแล้วโปรแกรมมันจะค้างที่ไฟล์ Program.cs แล้วมีไดอะล็อกเขียนว่า Exception has been thrown by the target of an invocation. ครับ