在Visual Studio 2008下如何用SerialPort完成串口通讯,求详解析
展开全部
网上搜得
//打开串口的方法
67 public void OpenPort()
68 {
69 try
70 {
71 port1.Open();
72 }
73 catch { }
74 if (port1.IsOpen)
75 {
76 Console.WriteLine("the port is opened!");
77 }
78 else
79 {
80 Console.WriteLine("failure to open the port!");
81 }
82 }
83
84 //关闭串口的方法
85 public void ClosePort()
86 {
87 port1.Close();
88 if (!port1.IsOpen)
89 {
90 Console.WriteLine("the port is already closed!");
91 }
92 }
93
94 //向串口发送数据
95 public void SendCommand(string CommandString)
96 {
97 byte[] WriteBuffer = Encoding.ASCII.GetBytes(CommandString);
98 port1.Write(WriteBuffer, 0, WriteBuffer.Length);
99 }
100
101 //调用实例
102 private void btnOpen_Click(object sender, RoutedEventArgs e)
103 {
104 //我现在用的COM1端口,按需要可改成COM2,COM3
105 InitCOM("COM1");
106 OpenPort();
107 }
//打开串口的方法
67 public void OpenPort()
68 {
69 try
70 {
71 port1.Open();
72 }
73 catch { }
74 if (port1.IsOpen)
75 {
76 Console.WriteLine("the port is opened!");
77 }
78 else
79 {
80 Console.WriteLine("failure to open the port!");
81 }
82 }
83
84 //关闭串口的方法
85 public void ClosePort()
86 {
87 port1.Close();
88 if (!port1.IsOpen)
89 {
90 Console.WriteLine("the port is already closed!");
91 }
92 }
93
94 //向串口发送数据
95 public void SendCommand(string CommandString)
96 {
97 byte[] WriteBuffer = Encoding.ASCII.GetBytes(CommandString);
98 port1.Write(WriteBuffer, 0, WriteBuffer.Length);
99 }
100
101 //调用实例
102 private void btnOpen_Click(object sender, RoutedEventArgs e)
103 {
104 //我现在用的COM1端口,按需要可改成COM2,COM3
105 InitCOM("COM1");
106 OpenPort();
107 }
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询