Код: Выделить всё
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 System.Windows.Forms;
using System.IO;
using System.IO.Ports;
namespace ТРМ_138
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
serialPort1.Open();
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Write(ReadHoldingRegister(16, 04, 0007, 0001), 0, 8);
textBox1.Text = serialPort1.ReadByte().ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
//чтение портов доступных в системе
string[] ports = SerialPort.GetPortNames();
//Очистка содержимого бокса
comboBox1.Items.Clear();
//Добавление найденных портов в бокс
comboBox1.Items.AddRange(ports);
}
public static byte[] ReadHoldingRegister(byte id, byte command, byte startAddress, byte length)
{
byte[] data = new byte[8];
byte High, Low;
data[0] = Convert.ToByte(16);
data[1] = Convert.ToByte(4);
byte[] _adr = BitConverter.GetBytes(startAddress);
data[2] =07;
data[3] =00;
byte[] _length = BitConverter.GetBytes(length);
data[4] = 01;
data[5] = 00;
myCRC(data, 6, out High, out Low);
data[6] = Low;
data[7] = High;
//MessageBox.Show(data[6].ToString());
//MessageBox.Show(data[7].ToString());
return data;
}
public static void myCRC(byte[] message, int length, out byte CRCHigh, out byte CRCLow)
{
ushort CRCFull = 0xFFFF;
for (int i = 0; i < length; i++)
{
CRCFull = (ushort)(CRCFull ^ message[i]);
for (int j = 0; j < 8; j++)
{
if ((CRCFull & 0x0001) == 0)
CRCFull = (ushort)(CRCFull >> 1);
else
{
CRCFull = (ushort)((CRCFull >> 1) ^ 0xA001);
}
}
}
CRCHigh = (byte)((CRCFull >> 8) & 0xFFFF);
CRCLow = (byte)(CRCFull & 0xFFFF);
// MessageBox.Show(CRCLow.ToString());
// MessageBox.Show(CRCHigh.ToString());
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// TextBox textBox1 = new TextBox();
//textBox1.Text = serialPort1.ReadExisting().ToString();
}
}
}