我需要通过 USB 将数据从 AT32 UC3 微 Controller ADC 传输到 PC。我检查了MCU中ADC和PDCA填充缓冲区的工作,它工作得很完美,没有数据丢失。但是当我从 USB 发送数据时,一些字节会丢失。我不知道,为什么会发生这种情况。 我编写简单的程序将一些数据从 MCU 发送到 PC 并检查这些数据。在MCU中,我连续用从0,1,2..到255的数字填充缓冲区,然后通过USB将缓冲区发送到PC,并检查该缓冲区的内容。因此,有些数字与原始数据不同。一些字节丢失。我在 CDC 设备模式下使用 EVK1100。
AVR代码:
#include <asf.h>
#include "conf_usb.h"
#define BUF_SIZE 32
int main(void){
irq_initialize_vectors();
cpu_irq_enable();
sysclk_init();
udc_start();
udc_attach();
char pbuf[BUF_SIZE];
for(int i=0; i<BUF_SIZE; i++){
pbuf[i] = (char)i;
}
while (true) {
udi_cdc_write_buf(pbuf, BUF_SIZE);
}
}
C# 代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
namespace acc_tester
{
class Program
{
static void Main(string[] args) {
Console.WriteLine("Start");
int N = 32;
SerialPort serialPort = new SerialPort();
serialPort.PortName = "COM6";
serialPort.Open();
byte[] buf = new byte [N];
for (int n = 0; n < 10000; n++) {
serialPort.Read(buf, 0, N);
for (int i = 0; i < N; i++) {
if (buf[i] != (byte)(buf[0] + i)) {
Console.WriteLine("Data Lost. n =" + n.ToString() + " i=" + i.ToString());
return;
}
}
}
serialPort.Close();
Console.WriteLine("Stop");
return;
}
}
}
我的 C# 程序的输出是:
数据丢失。 n =257 i=31
数据丢失。 n =385 i=31
数据丢失。 n =641 i=31
数据丢失。 n =257 i=31 等等
请帮我解决这个问题。
最佳答案
SerialPort.Read
读取最多 N
(32) 个字节,这取决于输入缓冲区中有多少字节 ( docs ) 。 Read
返回读取的字节数。
要读取长度为 N
的数据 block ,您应该自己缓冲数据,并且仅在达到 N
字节时才检查内容。例如。
while (true) {
var bytesInBuffer = 0;
bytesInBuffer += serialPort.Read(buf, bytesInBuffer, N - bytesInBuffer);
if (bytesInBuffer == N) {
// Here the buffer is ready
bytesInBuffer = 0; // reset the counter
}
}
关于c# - AVR32 UC3 USB 在 cdc 设备模式下数据丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39054077/