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;
using System.IO.Ports;
using System.Diagnostics;
namespace WATkey4x4
{
public partial class frmMain : Form
{
// 수신 데이터 보관용 버퍼
List<byte> m_buff = new List<byte>();
// 4x4 배열의 버튼 묶음
List<Button> m_Buttons = new List<Button>();
public frmMain()
{
InitializeComponent();
// 시리얼 통신 초기화
m_sp1 = new SerialPort();
m_sp1.DataReceived += new SerialDataReceivedEventHandler(m_sp1_DataReceived);
// 한번에 처리하기 위해 모든 버튼을 묶음
m_Buttons.Add(this.btnSW1);
m_Buttons.Add(this.btnSW2);
m_Buttons.Add(this.btnSW3);
m_Buttons.Add(this.btnSW4);
m_Buttons.Add(this.btnSW5);
m_Buttons.Add(this.btnSW6);
m_Buttons.Add(this.btnSW7);
m_Buttons.Add(this.btnSW8);
m_Buttons.Add(this.btnSW9);
m_Buttons.Add(this.btnSW10);
m_Buttons.Add(this.btnSW11);
m_Buttons.Add(this.btnSW12);
m_Buttons.Add(this.btnSW13);
m_Buttons.Add(this.btnSW14);
m_Buttons.Add(this.btnSW15);
m_Buttons.Add(this.btnSW16);
}
void m_sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// 수신된 데이터를 처리하자.
int iRecSize = m_sp1.BytesToRead;
if (iRecSize != 0)
{
byte[] buff = new byte[iRecSize];
m_sp1.Read(buff, 0, iRecSize);
foreach (byte by in buff)
{
m_buff.Add(by);
}
}
// STX 찾기
while (true)
{
if (m_buff.Count <= 0) break;
if (m_buff[0] == 0x02) break;
else
{
m_buff.RemoveAt(0);
}
}
if (m_buff.Count >= 8)
{
bool bSame = true;
if (0x02 != m_buff[0]) bSame = false;
if (0x03 != m_buff[7]) bSame = false;
if (true == bSame)
{
// CRC 를 체크해야 하는데 생략 ;;
UInt16 byteData = Convert.ToUInt16(m_buff[2]);
byteData <<= 8;
byteData += Convert.ToUInt16(m_buff[3]);
// 버튼을 하나씩 꺼내서 눌러졌는지 아닌지를 검사하자
foreach (Button btn in m_Buttons)
{
// SW1
if (byteData % 2 == 1)
{
// 눌러졌으면 RED
btn.BackColor = System.Drawing.Color.Red;
}
else
{
// 눌러지지 않았으면 Control(기본색)
btn.BackColor = System.Drawing.SystemColors.Control;
}
byteData >>= 1;
}
// 수신 버퍼에서 지금 처리된 데이터를 제거하자
m_buff.RemoveRange(0, 7);
}
else
{
// 수신 버퍼 초기화
m_buff.Clear();
}
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
// 컴포트 열기
this.btnOpen.Enabled = false;
m_sp1.PortName = txbComNum.Text; // 컴포트명
m_sp1.BaudRate = Convert.ToInt32(txbBaud.Text); // 보레이트
m_sp1.Open();
tmr50mS.Enabled = true;
tmr50mS.Start();
}
private void btnClose_Click(object sender, EventArgs e)
{
// 컴포트 닫기
tmr50mS.Stop();
m_sp1.Close();
this.btnOpen.Enabled = true;
}
private void TmrRequest(object sender, EventArgs e)
{
// 키패드 값을 요청하자
byte[] byteData =new byte[100];
int iLength=0;
byteData[iLength++] = 0x02;
byteData[iLength++] = 0x10;
byteData[iLength++] = 0x00;
byteData[iLength++] = 0x00;
byteData[iLength++] = 0x00;
byteData[iLength++] = 0x00;
byteData[iLength++] = 0xCC; // CRC 체크를 생략한다;
byteData[iLength++] = 0x03;
m_sp1.Write(byteData,0,iLength);
}
}
} |
댓글을 달아 주세요