【问题标题】:Write to a serial port like with pythons serial lib像 pythons 串行库一样写入串行端口
【发布时间】:2018-04-25 13:54:57
【问题描述】:

我使用 pythons serial lib 将命令写入 USB 端口:

ser = serial.Serial()
ser.port = 'com4'
ser.baudrate = 115200
ser.parity = serial.PARITY_NONE
ser.stopbits = serial.STOPBITS_ONE
ser.bytesize = serial.EIGHTBITS
ser.timeout = None
ser.open()
CMD_MOTOR_DRIVE=[1, 249, 3, 6, 42, 100]
ser.write(CMD_MOTOR_DRIVE_1)

现在我想借助 SerialPort 类在 c# 中做同样的事情:

SerialPort port = new SerialPort();
port.PortName = ports[0]; //"com4"
port.BaudRate = 115200;
port.Parity = Parity.None;
port.StopBits = StopBits.One;
port.DataBits = 8;
port.Open();
//System.Threading.Thread.Sleep(20);
if(port.IsOpen == true)
{
   log.Info("Port has been opened");
}
while(true)
{
   port.Write("1, 249, 3, 6, 11, 100");
}

我可以打开端口,但控制器似乎没有响应 port.Write(string) 函数的命令。我不知道c#中将命令转换为字节数组的对应方式是什么。我想我必须使用 port.Write((Byte[], Int32, Int32)) 函数而不是 port.Write(string) 函数?

【问题讨论】:

    标签: c# python serial-port


    【解决方案1】:

    如预期的那样容易:

    byte[] a = { 1, 249, 3, 6, 11, 100 };
    port.Write(a, 0, 6);
    

    【讨论】:

      猜你喜欢
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-21
      相关资源
      最近更新 更多