winform 三菱plc FX3U-30MR读写
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace man_machine
{
public partial class HMitsubishiPLC : Form
{
public HMitsubishiPLC()
{
InitializeComponent();
// 初始化串口
string portName = "COM7";
int baudRate = 38400;
serialPort = new SerialPort(portName, baudRate, Parity.None, 8, StopBits.One);
serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
serialPort.Open();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//string command = txtCommand.Text; // 从文本框获取指令
byte[] command = new byte[1];
command[0] = (byte)0;
//byte[] asciiBytes = Encoding.ASCII.GetBytes(command); // 将字符串转换为 ASCII 码
WriteToPLC(command);
Console.WriteLine("命令发送到PLC成功");
}
catch (Exception ex)
{
Console.WriteLine("发生错误: " + ex.Message);
}
}
// 向PLC写入 ASCII 格式数据
private void WriteToPLC(byte[] data)
{
serialPort.Write(data, 0, data.Length);
}
// 从PLC读取数据
private void ReadFromPLC()
{
try
{
string receivedData = serialPort.ReadExisting();
string hexString = BitConverter.ToString(Encoding.Default.GetBytes(receivedData)).Replace("-", " ");
// 更新UI,显示接收到的数据
BeginInvoke(new Action(() =>
{
Console.WriteLine("接收返回数据(十六进制):" + hexString);
}));
}
catch (Exception ex)
{
Console.WriteLine("接收返回异常:" + ex.Message);
}
}
/// <summary>
/// 接收返回参数
///
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
ReadFromPLC();
}
// 当窗体关闭时关闭串口连接
private void HMitsubishiPLC_FormClosed(object sender, FormClosedEventArgs e)
{
if (serialPort.IsOpen)
{
serialPort.Close();
}
}
}
}
请问如何向三菱plc读写