none
UWP C# UART Data Buffer Using Array RRS feed

  • Question

  • 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;

    I 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;

    Wednesday, January 22, 2020 2:12 AM

All replies

  • Maybe the checksum is incorrect. Try this:

    TxChkSum = 0;

    for( int i = 0; i < 5; ++i)

    {

       byte a = data[i];

       TxChkSum += a;

    }

    data[5] = TxChkSum; // or maybe ‘TxChkSum & 0x7F’

    dataWriteObject.WriteBytes(data);

    . . .

    Check if the contents of data array is valid.


    • Edited by Viorel_MVP Wednesday, January 22, 2020 5:59 AM
    Wednesday, January 22, 2020 5:56 AM