MainForm.cs 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using S7.Net;
  2. using System.Windows.Forms;
  3. namespace xicheji
  4. {
  5. public partial class MainForm : Form
  6. {
  7. private Plc? plc = null;
  8. public MainForm()
  9. {
  10. InitializeComponent();
  11. }
  12. private void button1_Click(object sender, EventArgs e)
  13. {
  14. try
  15. {
  16. plc = new Plc(CpuType.S7200, "127.0.0.1", 1502, 0, 1);
  17. plc.Open();
  18. richTextBox1.AppendText("���ӳɹ���\n\n");
  19. richTextBox1.ScrollToCaret();
  20. }
  21. catch (Exception ex)
  22. {
  23. MessageBox.Show(ex.Message + ex.StackTrace);
  24. }
  25. }
  26. private void button2_Click(object sender, EventArgs e)
  27. {
  28. if (plc == null || !plc.IsConnected) return;
  29. //plc��������c#���� bool => Bit
  30. //Byte => byte
  31. //word => ushort
  32. //DWord => uint
  33. //Int => short
  34. //DInt => int
  35. //Real => float
  36. //LReal => double
  37. //String => string
  38. //DateTimeLong=>datetime
  39. //s7wstring=>string
  40. //PLCAddress.Parse
  41. //1��DB100.DBB0 һ���ֽ���8��λ���ֱ�Ϊ0-- - 7������0.0----0.7��8λ --Byte,byte
  42. //2��DB100.DBW0һ�����������ֽڣ��ֱ�Ϊ DB100.DBB0�� DB100.DBB1 --Word,ushort
  43. //3��DB100.DBD0һ��˫���������֣��ֱ�Ϊ DB100.DBW0�� DB100.DBW2 --DWord,uint
  44. //4��DB100.DBX0.0 һ��λ��������С��λ --Bit,bool
  45. try
  46. {
  47. var db = 1;
  48. var start = plc.Read(DataType.DataBlock, db, 0, VarType.Byte, 1);
  49. Log("start:", start);
  50. var start2 = plc.Read("DB1.DBB0");
  51. Log("start2:", start2);
  52. var length = plc.Read(DataType.DataBlock, db, 1, VarType.Byte, 1);
  53. Log("length:", length);
  54. var length2 = plc.Read("DB1.DBB1");
  55. Log("length2:", length2);
  56. var mac = plc.Read(DataType.DataBlock, db, 2, VarType.Byte, 6);
  57. Log("mac:", string.Join(":", (mac as byte[]).ToList().ConvertAll(a => "0x" + a.ToString("X2"))));
  58. var val = plc.Read(DataType.DataBlock, db, 10, VarType.Bit, 1, 1);
  59. Log("DB1.DBX10.1��ֵΪ:", val);
  60. val = plc.Read(DataType.DataBlock, db, 10, VarType.Bit, 1, 2);
  61. Log("DB1.DBX10.2��ֵΪ:", val);
  62. val = plc.Read(DataType.DataBlock, db, 20, VarType.DWord, 1);
  63. Log("��ȡDB1.DBX20 DWORD��ϴ������ֵΪ:", val);
  64. var bbb = (bool)plc.Read("DB1.DBX10.1");
  65. Log("bbb:", bbb);
  66. var ccc = plc.Read("DB1.DBD20");
  67. Log("ccc:", ccc);
  68. //DWord.FromByteArray
  69. }
  70. catch (Exception ex)
  71. {
  72. MessageBox.Show(ex.Message + ex.StackTrace);
  73. }
  74. }
  75. private void Log(params object[] msgs)
  76. {
  77. richTextBox1.AppendText(string.Join(" ", msgs));
  78. richTextBox1.AppendText("\n\n");
  79. richTextBox1.ScrollToCaret();
  80. }
  81. private void button3_Click(object sender, EventArgs e)
  82. {
  83. plc?.Close();
  84. }
  85. }
  86. }