Rất đơn giản thôi bạn ah, trên C bạn dùng struct lưu 3 số integer 16 bit để chứa dữ liệu
Code:
typedef struct{
unsigned int16 ADC0;
unsigned int16 ADC1;
unsigned int16 ADC2;
} USBAdc;
Khi gởi qua cổng USB thì chuyển kiểu sang dạng mảng byte bình thường.
Còn trên C# bạn làm việc ngược lại, khai báo 1 struct hoặc class tương ứng nhưng nhớ dùng thêm chỉ thị alignment từng byte 1(để đảm bảo đúng thứ tự dữ liệu):
Code:
using System.Runtime.InteropServices;
...
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public class USBAdc
{
public UInt16 ADC0;
public UInt16 ADC1;
public UInt16 ADC2;
....
static public USBAdc FromByteArray(byte[] byte_Array)
{
USBAdc ret;
GCHandle handle = GCHandle.Alloc(byte_Array, GCHandleType.Pinned);
ret = (USBAdc)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(USBAdc));
handle.Free();
return ret;
}
}
Chú ý: FromByteArray là 1 phương thức static có chức năng chuyển 1 mảng Byte nhận được từ USB sang class USBAdc:
Code:
USBAdc adc= USBAdc.FromByteArray(usb_array_data);
...
adc.ADC0
adc.ADC1
adc.ADC2
Regards