Reputation: 9
I need to transfer data from AT32 UC3 microcontroller ADC to PC via USB. I check work of ADC and PDCA in MCU of filling the buffer, and it works was perfect without data loosing. But when I send data from USB some bytes are lost. I do not know, why this happens. I write simple programms to send some data from MCU to PC and check this data. In MCU I fill buffer with numbers from 0,1,2.. to 255 continuously, then send buffer via USB to PC, and check content of this buffer. So, some numbers are different from original data. Some bytes are lost. I using EVK1100 in CDC device mode.
AVR code:
#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# code:
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;
}
}
}
The output of my C# program is:
Data Lost. n =257 i=31
Data Lost. n =385 i=31
Data Lost. n =641 i=31
Data Lost. n =257 i=31 and etc.
Please, help me solve the problem.
Upvotes: 0
Views: 377
Reputation: 3010
SerialPort.Read
reads at most N
(32) bytes, it depends on how many bytes are in the input buffer (docs). Read
returns the amount of bytes read.
To read chunk of data of length N
you should buffer yourself the data and only check the content when you reach N
bytes. Eg.
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
}
}
Upvotes: 0