写入32位的int类型数据,代码如下:
- public bool WriteSingle32(string address, int value)//写入32位的int数据
- {
- try
- {
- var tempByte = BitConverter.GetBytes(value);
- var temp = new short[2];
- temp[0] = BitConverter.ToInt16(tempByte, 0);
- temp[1] = BitConverter.ToInt16(tempByte, 2);
- plcs.WriteBlock16(address, temp);
- return true;
- }
- catch (Exception ex)
- {
- return false;
- }
- }
写入字符串到PLC,代码如下:
- private void button3_Click(object sender, EventArgs e)
- {
- WriteMachineName();
- }
- SvMitsubishiMC3E plcs = new SvMitsubishiMC3E("192.168.1.38:8088");
- private void WriteMachineName()
- {
- string value = textBox3.Text;
- string input = "";
- if (value.Length==19)
- {
- input = value;
- }
- else if(value.Length < 19)
- {
- input = value.ToString().PadRight(20, ' ');
- }
- else
- {
- input = value.Substring(0, 20);
- }
- int aaa = input.Length;
- plcs.Initial();
- WriteString("R32210", input);
- plcs.Close();
- MessageBox.Show("寫入成功!");
- }
- public bool WriteString(string address, string value)//写入 value的长度为偶数
- {
- try
- {
- byte[] tempByte = System.Text.Encoding.ASCII.GetBytes(value);
- // var temp = tempByte.Select(x => Convert.ToInt16(x)).ToArray();
- var temp = new short[tempByte.Length/2];
- for(int i = 0; i < temp.Length; i++)
- {
- temp[i] = BitConverter.ToInt16(tempByte, 2*i);
- }
- plcs.WriteBlock16(address, temp);
- return true;
- }
- catch (Exception ex)
- {
- return false;
- }
- }
其中WriteString(string address, string value)value的长度为偶数
另一种方式读取字符串数据,代码如下:
- CsPlcMC PLC = new CsPlcMC();
- private void ReadMachineName(string IP, int Port)
- {
- if (PLC.Connect(IP, Convert.ToInt16(Port.ToString().Trim())))
- {
- short[] READ = new short[10];
- if (PLC.ReadBlocks(CsPlcMC.eAddress.R, 32210, ref READ))//地址
- {
- byte[] READ1 = new byte[20];
- //將數據轉換成machine名稱,
- for (int i = 0; i < 20; i = i + 2)
- {
- //READ1[i] = (byte)READ[i];
- string qw = READ[i / 2].ToString("X4");
-
- READ1[i] = Convert.ToByte(qw.Substring(2, 2), 16);
- READ1[i + 1] = Convert.ToByte(qw.Substring(0, 2), 16);
- }
- textBox3.Text = (Convert.ToString(System.Text.Encoding.ASCII.GetString(READ1))).Trim();
- PLC.Disconnect();
- }
- }
- }
写入int数据,代码如下:
- int y, mon, d, h, min, s;
- private void WriteTime(String IP, int Port)
- {
- y = DateTime.Now.Year;
- mon = DateTime.Now.Month;
- d = DateTime.Now.Day;
- h = DateTime.Now.Hour;
- min = DateTime.Now.Minute;
- s = DateTime.Now.Second;
- if (PLC.Connect(IP, Convert.ToInt16(Port.ToString().Trim())))
- {