怎么用C#写程序控制单片机
2个回答
展开全部
c#有个串口控件,你看到没有serialport,给串口发送指令。
public void opencom(SerialPort st, out string msg)
{
if (com_sta == "打开")
{
DataTable tb = ac.tblocal("select * from user_set");
st.PortName =(tb!=null&&tb.Rows.Count>0)?Convert.ToString(tb.Rows[0]["com_set"]) : "COM1";
st.BaudRate = 19200;
st.StopBits = StopBits.One;
st.Parity = Parity.Even;
st.DataBits = 8;
st.Handshake = Handshake.None;
st.ReadTimeout = 1000;
st.ReadBufferSize = 1024;
st.WriteBufferSize = 1024;
try
{
st.Open();
msg = "连接成功!";
com_sta = "关闭";
}
catch
{
msg = "连接失败!";
}
}
else
{
st.Close();
msg = "端口被关闭!";
com_sta = "打开";
}
}
打开你的串口,当然也可以通过蓝牙或者无线接收工具。
向设备发送命令,(MODBUSx16校验10位命令)举例:
public void send_data(SerialPort st, string send_txt, out string msg)
{
if (com_sta == "关闭")
{
byte[] send = new byte[] { 00, 00, 00, 00, 00, 00, 00, 00 };
string[] gam = send_txt.Trim().Split(' ');
for (int i = 0; i < gam.Length; i++)
{
send[i] = Convert.ToByte(gam[i], 16);
}
string yh = modbus.ToModbusCRC16(send_txt, true);
send[gam.Length] = Convert.ToByte(yh.Substring(0, 2), 16);
send[gam.Length + 1] = Convert.ToByte(yh.Substring(2, 2), 16);
string str = "";
foreach (var xs in send)
{
str += Convert.ToString(xs, 16).ToUpper().Length == 1 ? "0" + Convert.ToString(xs, 16).ToUpper() + " " : Convert.ToString(xs, 16).ToUpper() + " ";
}
//发送
try
{
Thread.Sleep(5);
st.Write(send, 0, send.Length);
msg = "准备就绪";
}
catch { msg = "erro"; }
}
else
{
msg = "端口没打开!";
}
}
执行命令,这个事件返回结果。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询