WPF內實現與串口發送數據和接收數據
阿新 • • 發佈:2018-10-22
encoding sage del app dem ace 同時 發送數據 textbox 原文:WPF內實現與串口發送數據和接收數據
與串口發送數據和接收數據,在此作一個簡單的Demo.此Demo可以實現按下硬件按鈕,燈亮,發送燈狀態數據過來。並且可以實現幾個燈同時亮,發送燈的狀態數據過來。PC端實現點擊按鈕讓硬件燈亮。
此處為4個燈,發送過來的數據:0代表暗,1代表亮。列如:1010代表1號燈和3號燈亮,2號和4號燈暗。
發送過去的數據:0代表1號燈亮,1代表1號燈滅、2代表2號燈亮,3代表2號燈滅、4代表3號燈亮,5代表3號燈滅、6代表4號燈亮,7代表4號燈滅。
布局代碼:
<Grid >
<TextBox HorizontalAlignment="Left" Height="23" Margin="112,59,0,0" TextWrapping="Wrap" Name="txtSend" VerticalAlignment="Top" Width="120"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="112,113,0,0" TextWrapping="Wrap" Name="txtReceive" VerticalAlignment="Top" Width="120" />
<Button Content="發送" Name="btnSend" HorizontalAlignment="Left" Margin="83,271,0,0" VerticalAlignment="Top" Width="35" Click="btnSend_Click"/>
<Button Content="發送" Name="btnSend1" HorizontalAlignment="Left" Margin="143,271,0,0" VerticalAlignment="Top" Width="35" Click="btnSend1_Click" />
<Button Content="發送" Name="btnSend2" HorizontalAlignment="Left" Margin="203,271,0,0" VerticalAlignment="Top" Width="35" Click="btnSend2_Click"/>
<Button Content="發送" Name="btnSend3" HorizontalAlignment="Left" Margin="263,271,0,0" VerticalAlignment="Top" Width="35" Click="btnSend3_Click"/>
<Label Name="one" Background="Red" HorizontalAlignment="Left" Margin="84,190,0,0" VerticalAlignment="Top" Height="24" Width="28"/>
<Label Name="two" Background="Red" HorizontalAlignment="Left" Margin="144,190,0,0" VerticalAlignment="Top" Height="24" Width="28"/>
<Label Name="three" Background="Red" HorizontalAlignment="Left" Margin="204,190,0,0" VerticalAlignment="Top" Height="24" Width="28"/>
<Label Name="four" Background="Red" HorizontalAlignment="Left" Margin="264,190,0,0" VerticalAlignment="Top" Height="24" Width="28"/>
</Grid>
後臺代碼:
先
private SerialPort Sp = new SerialPort();
public delegate void HandleInterfaceUpdataDelegate(string text);
private HandleInterfaceUpdataDelegate interfaceUpdataHandle;
String[] arr = { "0", "0", "0", "0" };//用於存儲硬件上面燈狀態
其次在Loaded事件添加用於更改串口參數:
//更改參數
Sp.PortName = "COM3";
Sp.BaudRate = 115200;
Sp.Parity = Parity.None;
Sp.StopBits = StopBits.One;
編寫監聽和發送數據事件:
private void Serial()
{
Sp.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived);
if (!Sp.IsOpen)
{
Sp.Open();
}
//用字節的形式發送數據
SendBytesData(Sp);
}
//發送二進制數據
private void SendBytesData(SerialPort Sp)
{
byte[] bytesSend = System.Text.Encoding.Default.GetBytes(txtSend.Text);
Sp.Write(bytesSend, 0, bytesSend.Length);
}
public void Sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
/* byte[] readBuffer = new byte[Sp.ReadBufferSize];
Sp.Read(readBuffer, 0, readBuffer.Length);
//Dispatcher.Invoke(interfaceUpdataHandle, new string[]{ Encoding.UTF8.GetString(readBuffer)});
Dispatcher.Invoke(interfaceUpdataHandle, new string[] { Encoding.ASCII.GetString(readBuffer) });
//Dispatcher.Invoke(interfaceUpdateHandle, new string[] { Encoding.ASCII.GetString(buf) });*/
SerialPort serialPort = (SerialPort)(sender);
System.Threading.Thread.Sleep(100);//延緩一會,用於防止硬件發送速率跟不上緩存數據導致的緩存數據雜亂
int n = serialPort.BytesToRead;//先記錄下來,避免某種原因,人為的原因,操作幾次之間時間長,緩存不一致
byte[] buf = new byte[n];//聲明一個臨時數組存儲當前來的串口數據
//received_count += n;//增加接收計數
serialPort.Read(buf, 0, n);//讀取緩沖數據
//因為要訪問ui資源,所以需要使用invoke方式同步ui
interfaceUpdataHandle = new HandleInterfaceUpdataDelegate(UpdateTextBox);//實例化委托對象
// Dispatcher.Invoke(interfaceUpdateHandle, new string[] { Encoding.ASCII.GetString(buf) });
Dispatcher.Invoke(interfaceUpdataHandle, new string[] { Encoding.ASCII.GetString(buf) });
//serialPort.Close();
}
private void UpdateTextBox(string text)
{
txtReceive.Text = text;
String Receive = Convert.ToString(text);
if (Receive != "")
{
// MessageBox.Show("receive", Receive);
String Receive1 = Receive.Substring(0, 1);
String Receive2 = Receive.Substring(1, 1);
String Receive3 = Receive.Substring(2, 1);
String Receive4 = Receive.Substring(3, 1);
if (Receive1 == 1.ToString())
{
one.Background = new SolidColorBrush(Colors.MediumAquamarine);
arr[0] = 1.ToString();
}
else
{
one.Background = new SolidColorBrush(Colors.Red);
arr[0] = 0.ToString();
}
if (Receive2 == 1.ToString())
{
two.Background = new SolidColorBrush(Colors.MediumAquamarine);
arr[1] = 1.ToString();
}
else
{
two.Background = new SolidColorBrush(Colors.Red);
arr[1] = 0.ToString();
}
if (Receive3 == 1.ToString())
{
three.Background = new SolidColorBrush(Colors.MediumAquamarine);
arr[2] = 1.ToString();
}
else
{
three.Background = new SolidColorBrush(Colors.Red);
arr[2] = 0.ToString();
}
if (Receive4 == 1.ToString())
{
four.Background = new SolidColorBrush(Colors.MediumAquamarine);
arr[3] = 1.ToString();
}
else
{
four.Background = new SolidColorBrush(Colors.Red);
arr[3] = 0.ToString();
}
//String abc = Convert.ToString(arr);
//MessageBox.Show("abc", abc);
// MessageBox.Show("arr", arr);
}
}
最後button點擊事件添加:
private void btnSend_Click(object sender, RoutedEventArgs e)
{
if (arr[0] == 0.ToString())
{
txtSend.Text = "0";
Serial();
}
else
{
txtSend.Text = "1";
Serial();
}
}
private void btnSend1_Click(object sender, RoutedEventArgs e)
{
if (arr[1] == 0.ToString())
{
txtSend.Text = "2";
Serial();
}
else
{
txtSend.Text = "3";
Serial();
}
}
private void btnSend2_Click(object sender, RoutedEventArgs e)
{
if (arr[2] == 0.ToString())
{
txtSend.Text = "4";
Serial();
}
else
{
txtSend.Text = "5";
Serial();
}
}
private void btnSend3_Click(object sender, RoutedEventArgs e)
{
if (arr[3] == 0.ToString())
{
txtSend.Text = "6";
Serial();
}
else
{
txtSend.Text = "7";
Serial();
}
}
要想在程序開始時就可以監聽數據,在其Loaded裏面添加上: Serial();
完整後臺代碼:
public partial class MainWindow : Window
{
private SerialPort Sp = new SerialPort();
public delegate void HandleInterfaceUpdataDelegate(string text);
private HandleInterfaceUpdataDelegate interfaceUpdataHandle;
String[] arr = { "0", "0", "0", "0" };//用於存儲硬件上面燈狀態
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//更改參數
Sp.PortName = "COM3";
Sp.BaudRate = 115200;
Sp.Parity = Parity.None;
Sp.StopBits = StopBits.One;
Serial();
}
private void btnSend_Click(object sender, RoutedEventArgs e)
{
if (arr[0] == 0.ToString())
{
txtSend.Text = "0";
Serial();
}
else
{
txtSend.Text = "1";
Serial();
}
}
private void btnSend1_Click(object sender, RoutedEventArgs e)
{
if (arr[1] == 0.ToString())
{
txtSend.Text = "2";
Serial();
}
else
{
txtSend.Text = "3";
Serial();
}
}
private void btnSend2_Click(object sender, RoutedEventArgs e)
{
if (arr[2] == 0.ToString())
{
txtSend.Text = "4";
Serial();
}
else
{
txtSend.Text = "5";
Serial();
}
}
private void btnSend3_Click(object sender, RoutedEventArgs e)
{
if (arr[3] == 0.ToString())
{
txtSend.Text = "6";
Serial();
}
else
{
txtSend.Text = "7";
Serial();
}
}
private void Serial()
{
Sp.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived);
if (!Sp.IsOpen)
{
Sp.Open();
}
//用字節的形式發送數據
SendBytesData(Sp);
}
//發送二進制數據
private void SendBytesData(SerialPort Sp)
{
byte[] bytesSend = System.Text.Encoding.Default.GetBytes(txtSend.Text);
Sp.Write(bytesSend, 0, bytesSend.Length);
}
public void Sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
/* byte[] readBuffer = new byte[Sp.ReadBufferSize];
Sp.Read(readBuffer, 0, readBuffer.Length);
//Dispatcher.Invoke(interfaceUpdataHandle, new string[]{ Encoding.UTF8.GetString(readBuffer)});
Dispatcher.Invoke(interfaceUpdataHandle, new string[] { Encoding.ASCII.GetString(readBuffer) });
//Dispatcher.Invoke(interfaceUpdateHandle, new string[] { Encoding.ASCII.GetString(buf) });*/
SerialPort serialPort = (SerialPort)(sender);
System.Threading.Thread.Sleep(100);//延緩一會,用於防止硬件發送速率跟不上緩存數據導致的緩存數據雜亂
int n = serialPort.BytesToRead;//先記錄下來,避免某種原因,人為的原因,操作幾次之間時間長,緩存不一致
byte[] buf = new byte[n];//聲明一個臨時數組存儲當前來的串口數據
//received_count += n;//增加接收計數
serialPort.Read(buf, 0, n);//讀取緩沖數據
//因為要訪問ui資源,所以需要使用invoke方式同步ui
interfaceUpdataHandle = new HandleInterfaceUpdataDelegate(UpdateTextBox);//實例化委托對象
// Dispatcher.Invoke(interfaceUpdateHandle, new string[] { Encoding.ASCII.GetString(buf) });
Dispatcher.Invoke(interfaceUpdataHandle, new string[] { Encoding.ASCII.GetString(buf) });
//serialPort.Close();
}
private void UpdateTextBox(string text)
{
txtReceive.Text = text;
String Receive = Convert.ToString(text);
if (Receive != "")
{
// MessageBox.Show("receive", Receive);
String Receive1 = Receive.Substring(0, 1);
String Receive2 = Receive.Substring(1, 1);
String Receive3 = Receive.Substring(2, 1);
String Receive4 = Receive.Substring(3, 1);
if (Receive1 == 1.ToString())
{
one.Background = new SolidColorBrush(Colors.MediumAquamarine);
arr[0] = 1.ToString();
}
else
{
one.Background = new SolidColorBrush(Colors.Red);
arr[0] = 0.ToString();
}
if (Receive2 == 1.ToString())
{
two.Background = new SolidColorBrush(Colors.MediumAquamarine);
arr[1] = 1.ToString();
}
else
{
two.Background = new SolidColorBrush(Colors.Red);
arr[1] = 0.ToString();
}
if (Receive3 == 1.ToString())
{
three.Background = new SolidColorBrush(Colors.MediumAquamarine);
arr[2] = 1.ToString();
}
else
{
three.Background = new SolidColorBrush(Colors.Red);
arr[2] = 0.ToString();
}
if (Receive4 == 1.ToString())
{
four.Background = new SolidColorBrush(Colors.MediumAquamarine);
arr[3] = 1.ToString();
}
else
{
four.Background = new SolidColorBrush(Colors.Red);
arr[3] = 0.ToString();
}
//String abc = Convert.ToString(arr);
//MessageBox.Show("abc", abc);
// MessageBox.Show("arr", arr);
}
}
}
這樣可以實現btn和硬件本身按鈕同時控制燈亮燈滅。
若轉載請註明轉載處。
WPF內實現與串口發送數據和接收數據