目前我不关心输出的细节,它是一个神奇的低级协议。我每2秒收到一些字节。
另一方面: 如果使用C#程序,我没有得到任何输出:
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ComTest
{
class Program
{
static void Main(string[] args)
{
SerialPort sp = new SerialPort("COM7", 9600, Parity.None, 8, StopBits.One);
//sp.Handshake = Handshake.None;
sp.Handshake = Handshake.XOnXOff;
sp.Open();
sp.DataReceived += (s, e) => Console.WriteLine("Data received.");
sp.ErrorReceived += (s, e) => Console.WriteLine("Data received.");
try
{
byte[] buffer = new byte[2];
while (true)
{
string buf = sp.ReadExisting();
if (buf.Length > 0)
{
Console.WriteLine(buf.Length);
Console.Write(buf);
}
Thread.Sleep(20);
}
}
finally
{
sp.Close();
}
}
}
}
我也试过使用Java,但也没有输出可见。有什么区别?我玩了参数,但我从来没有得到任何输出(在C#和Java)。
非常感谢
-edit -
我刚刚玩了一个虚拟的Linux。 C#代码在Windows上没有任何作用,但bash-script有效。它将串行端口配置更改为:
XXX@ubuntu:~/tmp/vol$ sudo stty -F /dev/ttyUSB0 -a
speed 9600 baud; rows 0; columns 0; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 5;
-parenb -parodd cs8 -hupcl -cstopb cread clocal -crtscts
ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl -ixon -ixoff -iuclc -ixany -imaxbel -iutf8
-opost -olcuc -ocrnl -onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
-isig -icanon -iexten -echo -echoe -echok -echonl -noflsh -xcase -tostop -echoprt -echoctl -echoke
XXX@ubuntu:~/tmp/vol$
不幸的是,我不知道如何更改C#代码以获得相同的配置。
-edit -
Hans Passant解决了我的问题(见评论):只需要设置CtrEnable=true
和RtsEnable=true
。
工作代码:
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ComTest
{
class Program
{
static void Main(string[] args)
{
SerialPort sp = new SerialPort("COM6", 9600, Parity.None, 8, StopBits.One);
//sp.Handshake = Handshake.None;
sp.Handshake = Handshake.RequestToSend;
sp.RtsEnable = true;
sp.DtrEnable = true;
sp.Open();
sp.DataReceived += (s, e) => Console.WriteLine("Data received.");
sp.ErrorReceived += (s, e) => Console.WriteLine("Data received.");
try
{
byte[] buffer = new byte[2];
while (true)
{
string buf = sp.ReadExisting();
if (buf.Length > 0)
{
Console.WriteLine(buf.Length);
Console.Write(buf);
}
Thread.Sleep(20);
}
}
finally
{
sp.Close();
}
}
}
}