Translate

2015/09/09

C#, シリアル通信の実装

こちらを参考に受信処理を作成。
http://homepage2.nifty.com/nonnon/SoftSample/CS.NET/SampleRs232c.html


// C#.NETのサンプル
// SerialPortコントロールをフォームに貼り付けています
public partial class Form1 : Form
{
    private void Form1_Load(
        object sender, EventArgs e)
    {
        // シリアルポートのオープン
        serialPort1.PortName = "COM11";
        // シリアルポートの通信速度指定
        serialPort1.BaudRate = 9600;
        // シリアルポートのパリティ指定
        serialPort1.Parity = System.IO.Ports.Parity.None;
        // シリアルポートのビット数指定
        serialPort1.DataBits = 8;
        // シリアルポートのストップビット指定
        serialPort1.StopBits = System.IO.Ports.StopBits.One;
        // シリアルポートのオープン
        serialPort1.Open();
    }

    private void Form1_FormClosed(
        object sender, FormClosedEventArgs e)
    {
        // シリアルポートのクローズ
        serialPort1.Close();
    }
 private void serialPort1_DataReceived(
        object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        // シリアルポートからデータ受信
        Byte[] dat = new Byte[serialPort1.BytesToRead];
        serialPort1.Read(dat, 0, dat.GetLength(0));
        MessageBox.Show(
            System.Text.Encoding.GetEncoding("SHIFT-JIS").GetString(dat));
    }

0 件のコメント:

コメントを投稿