본문 바로가기
C++ 200제/코딩 IT 정보

C# RS232 시리얼(Serial) 통신 예제 소스 (닷넷 시리얼포트 프로그램)

by vicddory 2018. 5. 23.


구글링해서 얻은 C# 예제 프로젝트인데 UI가 이뻐서 소개합니다. 제목처럼 Serial 통신 프로그램 샘플입니다.


C# RS232 시리얼(Serial) 통신 예제 소스[C# RS232 시리얼(Serial) 통신 예제 소스]


일단, 위의 기본 설정창에서 저장된 사항은 아래 코드를 거쳐 로컬에 저장됩니다.

Config 저장 소스

/// <summary>
/// Write the settings to disk. </summary>
public static void Write()
{
IniFile ini = new IniFile(Application.StartupPath + "\\Termie.ini");
ini.WriteValue("Port", "PortName", Port.PortName);
ini.WriteValue("Port", "BaudRate", Port.BaudRate);
ini.WriteValue("Port", "DataBits", Port.DataBits);
ini.WriteValue("Port", "Parity", Port.Parity.ToString());
ini.WriteValue("Port", "StopBits", Port.StopBits.ToString());
ini.WriteValue("Port", "Handshake", Port.Handshake.ToString());
ini.WriteValue("Option", "AppendToSend", Option.AppendToSend.ToString());
ini.WriteValue("Option", "HexOutput", Option.HexOutput.ToString());
ini.WriteValue("Option", "MonoFont", Option.MonoFont.ToString());
ini.WriteValue("Option", "LocalEcho", Option.LocalEcho.ToString());
ini.WriteValue("Option", "StayOnTop", Option.StayOnTop.ToString());
ini.WriteValue("Option", "FilterUseCase", Option.FilterUseCase.ToString());
}


MSDN에 올라온 예제를 아주 깔끔하게 정리했다는 느낌이네요. 소스도 간결하고 보기에도 좋습니다. 보다 자세한 사항은 첨부 파일을 다운받아 확인해 보시고 주요 소스만 소개합니다. 마음에 들면 다운 받으세요. ^^.


RS232 시리얼 통신 데이터 수신 소스 (Serial Read)

/// <summary>
/// Handle data received event from serial port.
/// </summary>
/// <param name="data">incoming data</param>
public void OnDataReceived(string dataIn)
{
//Handle multi-threading
if (InvokeRequired)
{
Invoke(new StringDelegate(OnDataReceived), new object[] { dataIn });
return;
}
// pause scrolling to speed up output of multiple lines
bool saveScrolling = scrolling;
scrolling = false;
// if we detect a line terminator, add line to output
int index;
while (dataIn.Length > 0 &&
((index = dataIn.IndexOf("\r")) != -1 ||
(index = dataIn.IndexOf("\n")) != -1))
{
String StringIn = dataIn.Substring(0, index);
dataIn = dataIn.Remove(0, index + 1);
logFile_writeLine(AddData(StringIn).Str);
partialLine = null; // terminate partial line
}
// if we have data remaining, add a partial line
if (dataIn.Length > 0)
{
partialLine = AddData(dataIn);
}
// restore scrolling
scrolling = saveScrolling;
outputList_Scroll();
}


C# 시리얼 rs232 통신 소스[Serial 통신 프로그램]

RS232 시리얼 통신 데이터 송신 소스 (Serial Write)

/// <summary>
/// Send command
/// </summary>
private void button5_Click(object sender, EventArgs e)
{
string command = comboBox1.Text;
comboBox1.Items.Add(comboBox1.Text);
comboBox1.Text = "";
comboBox1.Focus();
if (command.Length > 0)
{
command = ConvertEscapeSequences(command);
CommPort com = CommPort.Instance;
com.Send(command);
if (Settings.Option.LocalEcho)
{
outputList_Add(command + "\n", sentColor);
}
}
}



댓글