Form1.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using S7.Net;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows.Forms;
  11. namespace xicheji
  12. {
  13. public partial class Form1 : Form
  14. {
  15. private Plc plc;
  16. public Form1()
  17. {
  18. InitializeComponent();
  19. }
  20. private void button1_Click(object sender, EventArgs e)
  21. {
  22. try
  23. {
  24. plc = new Plc(CpuType.S7200, "127.0.0.1", 1502, 0, 1);
  25. plc.Open();
  26. richTextBox1.AppendText("连接成功!\n\n");
  27. richTextBox1.ScrollToCaret();
  28. }
  29. catch (Exception ex)
  30. {
  31. MessageBox.Show(ex.Message + ex.StackTrace);
  32. }
  33. }
  34. private void button2_Click(object sender, EventArgs e)
  35. {
  36. if (plc == null || !plc.IsConnected) return;
  37. //plc中类型与c#类型 bool => Bit
  38. //Byte => byte
  39. //word => ushort
  40. //DWord => uint
  41. //Int => short
  42. //DInt => int
  43. //Real => float
  44. //LReal => double
  45. //String => string
  46. //DateTimeLong=>datetime
  47. //s7wstring=>string
  48. try
  49. {
  50. var db = 1;
  51. var start = plc.Read(DataType.DataBlock, db, 0, VarType.Byte, 1);
  52. Log("start:", start);
  53. var length = plc.Read(DataType.DataBlock, db, 1, VarType.Byte, 1);
  54. Log("length:", length);
  55. var mac = plc.Read(DataType.DataBlock, db, 2, VarType.Byte, 6);
  56. Log("mac:", string.Join(":", (mac as byte[]).ToList().ConvertAll(a => "0x" + a.ToString("X2"))));
  57. var val = plc.Read(DataType.DataBlock, db, 10, VarType.Bit, 1, 1);
  58. Log("DB1.DBX10.1的值为:", val);
  59. val = plc.Read(DataType.DataBlock, db, 10, VarType.Bit, 1, 2);
  60. Log("DB1.DBX10.2的值为:", val);
  61. val = plc.Read(DataType.DataBlock, db, 20, VarType.DWord, 1);
  62. Log("读取DB1.DBX20 DWORD的洗车次数值为:", val);
  63. }
  64. catch (Exception ex)
  65. {
  66. MessageBox.Show(ex.Message + ex.StackTrace);
  67. }
  68. }
  69. private void Log(params object[] msgs)
  70. {
  71. richTextBox1.AppendText(string.Join(" ", msgs));
  72. richTextBox1.AppendText("\n\n");
  73. richTextBox1.ScrollToCaret();
  74. }
  75. private void button3_Click(object sender, EventArgs e)
  76. {
  77. plc?.Close();
  78. }
  79. }
  80. }