c# 控制台485串口连接

串口连接,串口名称com1,波特率115200,数据位8,停止位1,校验位0;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
namespace ConsoleApplication1
{
    class Program
    {
        public static void Main()
        {     
            //StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;

            SerialPort _serialPort = new SerialPort(); //创建端口
            _serialPort.PortName = "COM1";//端口名称,波特率,检验位,数据位,停止位
            _serialPort.BaudRate = 115200;
            _serialPort.Parity =0; 
            _serialPort.DataBits = 8;
            _serialPort.StopBits = StopBits.One;
            // _serialPort.Handshake =Handshake.None;
   
            _serialPort.Open();
            if (_serialPort.IsOpen)
            {
                Console.WriteLine("连接成功");
                Byte[] TxData = { 0x04, 0x03, 0x00, 0x03, 0x00, 0x01, 0x74, 0x5f }; //定义通讯指令 ,0x04设备地址为4,0x03功能码为3, 0x00, 0x03是通讯地址吗,0x00, 0x01是寄存器数量,0x74, 0x5f是CRC校验
                _serialPort.Write(TxData, 0, 8);//发送指令

                byte[] recData = new byte[7];
                _serialPort.Read(recData, 0, 7);//接收数据
             
            }
            _serialPort.Close();//关闭端口

        }
    }
}

 

你可能感兴趣的:(小白入门)