我正在尝试建立一个以 10-20 kHz 的速率传输 16 位数据包的 SerialPort 连接。我在 C++/CLI 中对此进行编程。发送方在收到字母“s”后就进入一个无限循环,并不断发送 2 个字节的数据。
发送方不太可能出现问题,因为更简单的方法可以完美运行但速度太慢(在这种方法中,接收方总是先发送一个“a”,然后得到 1 个包含 2 个字节的包。它会导致速度约 500Hz)。这是这种有效但缓慢的方法的重要部分:
public: SerialPort^ port;
in main:
Parity p = (Parity)Enum::Parse(Parity::typeid, "None");
StopBits s = (StopBits)Enum::Parse(StopBits::typeid, "1");
port = gcnew SerialPort("COM16",384000,p,8,s);
port->Open();
and then doing as often as wanted:
port->Write("a");
int i = port->ReadByte();
int j = port->ReadByte();
这是我现在使用的实际方法:
static int values[1000000];
static int counter = 0;
void reader(void)
{
SerialPort^ port;
Parity p = (Parity)Enum::Parse(Parity::typeid, "None");
StopBits s = (StopBits)Enum::Parse(StopBits::typeid, "1");
port = gcnew SerialPort("COM16",384000,p,8,s);
port->Open();
unsigned int i = 0;
unsigned int j = 0;
port->Write("s"); //with this command, the sender starts to send constantly
while(true)
{
i = port->ReadByte();
j = port->ReadByte();
values[counter] = j + (i*256);
counter++;
}
}
in main:
Thread^ readThread = gcnew Thread(gcnew ThreadStart(reader));
readThread->Start();
计数器以 18472 包/秒的速度快速增加(更多),但值在某种程度上是错误的。这是一个示例:该值应如下所示,最后 4 位随机变化(它是模数转换器的信号):
111111001100111
以下是代码中给出的线程解决方案的一些值:
1110011001100111
1110011000100111
1110011000100111
1110011000100111
所以看起来连接读取了包中间的数据(准确地说:3位太迟了)。我能做些什么?我想避免在读取这样的包时稍后在代码中修复此错误的解决方案,因为我不知道稍后编辑读取代码时移位错误是否会变得更糟,我很可能会这样做。
提前致谢,
尼古拉斯
PS:如果这有帮助,这里是发送方的代码(一个 AtMega168),用 C 语言编写。
uint8_t activate = 0;
void uart_puti16(uint16_t val) //function that writes the data to serial port
{
while ( !( UCSR0A & (1<<UDRE0)) ) //wait until serial port is ready
nop(); // wait 1 cycle
UDR0 = val >> 8; //write first byte to sending register
while ( !( UCSR0A & (1<<UDRE0)) ) //wait until serial port is ready
nop(); // wait 1 cycle
UDR0 = val & 0xFF; //write second byte to sending register
}
in main:
while(1)
{
if(active == 1)
{
uart_puti16(read()); //read is the function that gives a 16bit data set
}
}
ISR(USART_RX_vect) //interrupt-handler for a recieved byte
{
if(UDR0 == 'a') //if only 1 single data package is requested
{
uart_puti16(read());
}
if(UDR0 == 's') //for activating constant sending
{
active = 1;
}
if(UDR0 == 'e') //for deactivating constant sending
{
active = 0;
}
}