I am working on UART-RS485. The data is sent in bytes. I have tested with hard-coded code using array
. However, I would like to find out how to use array in a dynamic matter as the data packet size may vary.
Task<UInt32> storeAsyncTask;
byte[] data = { 0xF5, 0x81, 0x66, 0x0F, 0x00, 0x6B };
dataWriteObject.WriteBytes(data);
storeAsyncTask = dataWriteObject.StoreAsync().AsTask();
UInt32 bytesWritten = await storeAsyncTask;
Please help thanks.
Updated:
I recently tried using bitconverter
but it doesn't work. I am not sure where I did wrong.
Task<UInt32> storeAsyncTask;
BitConverter.GetBytes(F5).CopyTo(data, 0);
BitConverter.GetBytes(TxAddress).CopyTo(data, 1);
BitConverter.GetBytes(TxCommand).CopyTo(data, 2);
BitConverter.GetBytes(TxData).CopyTo(data, 3);
BitConverter.GetBytes(~TxData).CopyTo(data, 4);
TxChkSum = 0;
foreach (byte a in data)
{
TxChkSum += a;
}
BitConverter.GetBytes(TxChkSum).CopyTo(data, 5);
dataWriteObject.WriteBytes(data);
storeAsyncTask = dataWriteObject.StoreAsync().AsTask();
UInt32 bytesWritten = await storeAsyncTask;
Update 23-01-2020
I tried using the list
method but by addrange
the data is added in range of 2 bytes(16-bits) instead a one byte (8 bits) where the RS485 communication i am interfacing is transmitted in byte by byte. May I know how to work around it?
2nd issue is that at dataWriteObject.WriteBytes(data.ToArray());
it throw an exception as follow;
"Object reference not set to an instance of an object."
I am not sure what does it mean and how to overcome it.
eg.
byte F5 = 0xF5;
byte TxCommand= 0x66
byte TxData = 0x0F
try
{
List<byte> data = new List<byte>();
data.AddRange(BitConverter.GetBytes(F5));
data.AddRange(BitConverter.GetBytes(TxAdr));
data.AddRange(BitConverter.GetBytes(TxCommand));
data.AddRange(BitConverter.GetBytes(TxData));
data.AddRange(BitConverter.GetBytes(~TxData));
TxChkSum = 0;
foreach (byte a in data)
{
TxChkSum += a;
}
data.AddRange(BitConverter.GetBytes(TxChkSum));
dataWriteObject.WriteBytes(data.ToArray());
Task<UInt32> storeAsyncTask;
storeAsyncTask = dataWriteObject.StoreAsync().AsTask();
UInt32 bytesWritten = await storeAsyncTask;
}
catch (Exception ex)
{
MainStatusDisplay.Text = ex.Message;
}