본문으로 바로가기

C# 모드버스 RTU 시리얼통신 구현하기

category C# 2019. 8. 5. 15:19
반응형

 

안녕하세요~ 

시리얼 통신도 TCP/IP 모드버스 프로토콜과 차이가 많이나지 않습니다!

Send Receive 기본틀도 둘다 비슷하구요

단지 요청프로토콜에 앞 헤더를 제외하고 뒤에 CRC가 추가되는 점이 조금 다르죠!

 

 시리얼 통신용 기본 요청 프로토콜 입니다.

 

 public static byte[] W_buff =
         {
                0x01,        //ID
                0x04,        //FunctionCode
                0x00, 0x01,  //시작주소 
                0x00, 0x40,  //데이터 길이(64)  
                0x73, 0xFB   //CRC 값 계산필요!
         };

 

CRC 값 구하는 부분은 밑에 링크로 올려두었습니다.

시리얼포트 기본소스입니다.

 

iniPort 메서드는 는 ini파일을 이용하여 가져온 시리얼 포트 연결속성을 설정하는 부분입니다.

통신포트, 속도, 패리티비트, 데이타비트, 스탑비트..

 

나머지 메서드는 메서드 이름과 같은 동작을 하구요!

 

SerialDataReceivedEventHandler 이벤트는 데이터를 읽기위해 필수적인 이벤트입니다.

후에 추가적으로 더 올리도록 하겠습니다 Receive 부분 포함해서요!

궁금한점은 댓글로..

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class TSerialPort
    {
 
        public SerialPort serialport = new SerialPort();
 
        //===========================================================//
        /// <summary>
        /// 시리얼 통신 설정 값 설정 메서드
        /// </summary>
        /// <param name="com"></param>
        /// <param name="baudrate"></param>
        /// <param name="parity"></param>
        /// <param name="data"></param>
        /// <param name="stop"></param>
        public void fn_iniPort(string com, int baudrate, string parity, int data, int stop)
        {
            serialport.PortName = com;
            serialport.BaudRate = baudrate;
            if (parity == "N"serialport.Parity = Parity.None;
            else if (parity == "O"serialport.Parity = Parity.Odd;
            else if (parity == "E"serialport.Parity = Parity.Even;
 
            serialport.DataBits = data;
            if (stop == 1) serialport.StopBits = StopBits.One;
            else if (stop == 2) serialport.StopBits = StopBits.Two;
        }
 
        //=================================================================//
        /// <summary>
        /// 시리얼 포트 오픈
        /// </summary>
        /// <param name="fn_OnDataReceived"></param>
        /// <returns></returns>
        //=================================================================//
        public int fn_Open(SerialDataReceivedEventHandler fn_OnDataReceived)
        {
            int iret = 1;
            serialport.DataReceived += fn_OnDataReceived;
            try
            {
                serialport.Open();
            }
            catch(Exception e)
            {
                iret = -1;
            }
            return iret;
        }
 
        //=====================================================================//
        //시리얼 포트 연결 종료
        //=====================================================================//
        public void fn_Close(SerialDataReceivedEventHandler fn_OnDataReceived)
        {
            if (serialport.IsOpen)
            {
                serialport.Close();
                serialport.DataReceived -= fn_OnDataReceived ;
            }
        }
 
        //=====================================================================//
        //데이터 요청
        //=====================================================================//
        public void fn_Send(byte[] buffer, int offset, int count)
        {
            //보낼데이터(버퍼값), 번지수, 데이터 개수)
            serialport.Write(buffer, offset, count);
        } 
    }
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

[C#] - C# 모드버스 RTU 시리얼통신 구현하기2 (주석 추가, 소스 공개)

 

C# 모드버스 RTU 시리얼통신 구현하기2 (주석 추가, 소스 공개)

안녕하세요 모드버스 시리얼 통신에 대해 소스 요청이 많아 테스트로 작성한 코드입니다. 블로그에 기존에 작성된 소스를 기반으로 작성했으며 클래스를 상속하여 오버라이딩한 부분도 같습니

dodo1054.tistory.com

[C#] - C# 모드버스 RTU 시리얼통신 구현하기 (주석 추가, 소스 공개)

 

C# 모드버스 RTU 시리얼통신 구현하기(주석 추가, 소스 공개)

메인 클래스에서 참조(상속)하고 있는 시리얼통신을 위한 기본소스(중요) using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO.Ports; using System.Threadi..

dodo1054.tistory.com

[C#] - C# 모드버스 RTU 시리얼통신 구현 폼 (주석 추가, 소스 공개)

 

C# 모드버스 RTU 시리얼통신 구현 폼 (주석 추가, 소스 공개)

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using Syste..

dodo1054.tistory.com

[C#] - C# 모드버스 RTU 시리얼통신 구현 소스 파일 첨부

 

C# 모드버스 RTU 시리얼통신 구현 소스 파일 첨부

>>> 구성요소 <<< MainConnect.cs Form.cs <공용으로 쓰는 lib> cConversion.cs (데이터 컨버전 클래스) cLog.cs (로그 생성 클래스) cModbusRTU.cs (CRC 생성) cSerialProt.cs (통신 함수) ~ 기타 ~ (2개)

dodo1054.tistory.com

[C#] - C# Modbus RTU CRC 구하기

[C#] - C# ini 파일 이용하기

[C#] - C# TCP/IP Client Part.1 [기본소스]

[C#] - C# TCP/IP Client Part.2

[C#] - C# TCP/IP Client Part.3

 

반응형

'C#' 카테고리의 다른 글

C# 날짜 Log 파일 만들기  (0) 2019.08.21
C# 모드버스 RTU 시리얼통신 구현하기2  (2) 2019.08.06
C# Modbus RTU CRC 구하기  (0) 2019.07.29
C# ini 파일 이용하기  (0) 2019.07.19
C# Byte 배열로 형변환 하기  (0) 2019.07.15