using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
// user include----------------------------
using System.IO.Ports;
namespace rs232v2
{
public partial class Form1 : Form
{
public SerialPort serialPort = new SerialPort();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// button 設定
this.button1.Text = "Open COM";
this.button2.Text = "Send";
this.button2.Enabled = false;
// 事件初始化
this.button1.Click += new EventHandler(Rs232PortDoor);
this.button2.Click += new EventHandler(SendPhone);
// rs232 door key
rs232Key = true;
}
bool rs232Key;
// button1 事件處理
// 初始PORT & 打開 button2
private void Rs232PortDoor(object sender, EventArgs e)
{
if (rs232Key)
{
this.button1.Text = "Close Port";
// 打開 button2
this.button2.Enabled = true;
// 設定使用的 PORT
this.serialPort.PortName = "COM4";
// 檢查 PORT 是否關閉
if (!serialPort.IsOpen)
this.serialPort.Close();
// 初始化 PORT
this.serialPort.BaudRate = 9600; // baud rate = 9600
this.serialPort.Parity = Parity.None; // Parity = none
this.serialPort.StopBits = StopBits.One; // stop bits = one
this.serialPort.DataBits = 8; // data bits = 8
// 設定 PORT 接收事件
serialPort.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceived);
// 打開 PORT
serialPort.Open();
// 清空 serial port 的緩存
serialPort.DiscardInBuffer(); // RX
serialPort.DiscardOutBuffer(); // TX
rs232Key = false;
}
else
{
this.button1.Text = "Open Port";
// 清空 serial port 的緩存
serialPort.DiscardInBuffer(); // RX
serialPort.DiscardOutBuffer(); // TX
// 關閉 PORT
this.serialPort.Close();
// 關閉 button2
this.button2.Enabled = false;
rs232Key = true;
}
}
// button2 事件處理
// 傳送三組電話過去
private void SendPhone(object sender, EventArgs e)
{
char[] textBuf;
textBuf = this.textBox1.Text.ToCharArray();
rs232Output(textBuf);
textBuf = this.textBox2.Text.ToCharArray();
rs232Output(textBuf);
textBuf = this.textBox3.Text.ToCharArray();
rs232Output(textBuf);
}
// 經由RS232 字串傳送
private void rs232Output(char[] phoneNum)
{
for (int i = 0; i < phoneNum.Length; i++)
{
serialPort.Write(phoneNum, i, 1);
//serialPort.Write("A");
}
// 傳送 Enter 的 ascii code
byte[] commEnter = new byte[] {0x0D, 0x0A};
for (int i = 0; i < 2; i++)
{
serialPort.Write(commEnter, i, 1);
}
Console.WriteLine("output Phone Number" + phoneNum.ToString());
}
// PORT 接收事件
void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte RB = Byte.Parse(serialPort.ReadByte().ToString());
//SetText(RB.ToString());
SetText(textBox4.Text + RB.ToString() + " ");
}
// TextBox2 跨執行續執行
delegate void SetTextCallback(string text);
private void SetText(string text)
{
if (this.textBox2.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox4.Text = text;
}
}
}
}
如果把資料接收的函式委派出去
但是在處理事件時是和主 Process 不是同一條
所以會有 存取的問題
所以要再把 輸出也委派出去
給他call
留言列表