.net串口通信

时间:2021-07-09 16:09:22

背景:
  前一段时间需要写一个向蓝牙模块发消息的功能。
  对蓝牙的机制不太了解,所以一直在查资料,
  但始终没找到我需要的东西,还误以为需要配套的一套开发模板和开发包,
  

  偶然间发现只需要简单的串口通信,并且.net已经集成好相关的函数。大雾
  实际上对方已经告诉我要做串口了,一直没往那个方向查

  

  再细看参数,发现都是微机课上学的,巨简单(当初上课还以为没什么用)

代码:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Configuration; namespace MorrisSpace
{
class SerialPortSample
{
static SerialPort spConnector=null; public static void SetSerialPort()
{
string portName = "COM5";
int baudRate = ;
int dataBits = ;
parity = Parity.None; break;
stopBits = StopBits.One; break;
try
{
spConnector = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
}
catch (IOException e)
{
System.Windows.MessageBox.Show(e.ToString());
}
} public static void SendString(String str)
{
if (spConnector == null)
{
SetSerialPort();
}
byte[] bytedata = Encoding.UTF8.GetBytes(str);
try
{
spConnector.Open();
spConnector.Write(bytedata, , bytedata.Length);
spConnector.Close();
}
catch (IOException e)
{
System.Windows.MessageBox.Show(e.ToString());
}
}
}
}

--------

这里只是演示  串口参数是固定的