Reputation: 53
I know there are a lot of examples for this, but NONE of them are working. pPtr is a pointer to a temporary log of this type
typedef struct
{
TIMESTAMP_TYPE oTimeStamp;
ASSERT_ID_TYPE ucAssertID;
Int16 iData1;
Int16 iData2;
UInt16 uiChecksum;
}
LOG_ENTRY_TYPE;
where I dequeue my log when there is one I want to store off to EEEPROM.
oTimestamp is of type
typedef struct
{
UInt32 ulSecond;
UInt16 usMilliSecond;
UInt16 usPowerCycleCount;
}
TIMESTAMP_TYPE;
All of the other accesses and writes work, even for milliseconds, but I cannot get the seconds timestamp value broken down into 4 bytes.
Here is what I have tried (obviously with only one version uncommented out):
UChar tmpByteHigh;
UChar tmpByteLow;
//Attempt1
tmpByteHigh = (pPtr->oTimeStamp.ulSecond >> 24) & 0x000000FF;
SPIwrite(tmpByteHigh);
tmpByteLow = (pPtr->oTimeStamp.ulSecond >> 16) & 0x000000FF;
SPIwrite(tmpByteLow);
tmpByteHigh = (pPtr->oTimeStamp.ulSecond >> 8) & 0x000000FF;
SPIwrite(tmpByteHigh);
tmpByteLow = (pPtr->oTimeStamp.ulSecond) & 0x000000FF;
SPIwrite(tmpByteLow);
//Attempt 2
tmpByteHigh = (pPtr->oTimeStamp.ulSecond & 0xFF000000UL) >> 24;
SPIwrite(tmpByteHigh);
tmpByteLow = (pPtr->oTimeStamp.ulSecond & 0x00FF0000UL) >> 16;
SPIwrite(tmpByteLow);
tmpByteHigh = (pPtr->oTimeStamp.ulSecond & 0x0000FF00UL) >> 8;
SPIwrite(tmpByteHigh);
tmpByteLow = (pPtr->oTimeStamp.ulSecond) & 0x000000FFUL;
SPIwrite(tmpByteLow);
//Attempt 3
//get msw from 32 bit value and write the 2 msB from it
tmpWord = (pPtr->oTimeStamp.ulSecond >> 16) & 0x0000FFFF;
tmpByteHigh = (tmpWord >> 8) & 0x00FF;
SPIwrite(tmpByteHigh);
tmpByteLow = tmpWord & 0x00FF;
SPIwrite(tmpByteLow);
//get lsw from 32 bit value and write the 2 lsB from it
tmpWord = pPtr->oTimeStamp.ulSecond & 0x0000FFFF;
tmpByteHigh = (tmpWord >> 8) & 0x00FF;
SPIwrite(tmpByteHigh);
tmpByteLow = tmpWord & 0x00FF;
SPIwrite(tmpByteLow);
//Attempt 4
UChar* myPointer = (UChar*)&pPtr->oTimeStamp.ulSecond;
UChar myArray[4];
myArray[0]=myPointer[0];
myArray[1]=myPointer[1];
myArray[2]=myPointer[2];
myArray[3]=myPointer[3];
SPIwrite(myArray[0]);
SPIwrite(myArray[1]);
SPIwrite(myArray[2]);
SPIwrite(myArray[3]);
Each and every time I get 0x00 0x00 0x00 0x80 sent over SPI. Any thoughts? Be easy on me I am not a great programmer.
Upvotes: 4
Views: 272
Reputation: 18950
Use an union and you can access the same data in multiple ways:
typedef union
{
struct {
UInt32 ulSecond;
UInt16 usMilliSecond;
UInt16 usPowerCycleCount;
};
UInt8 byte[8];
}
TIMESTAMP_TYPE;
int main() {
TIMESTAMP_TYPE T;
T.ulSecond = 1;
T.usMilliSecond = 2;
T.usPowerCycleCount = 3;
printf("sizeof(T) = %ld\n", sizeof(T));
for(int i = 0; i < 8; i++)
printf("T[%d] = 0x%2.2X\n", i, T.byte[i]);
return 0;
}
prints:
sizeof(T) = 8
T[0] = 0x01
T[1] = 0x00
T[2] = 0x00
T[3] = 0x00
T[4] = 0x02
T[5] = 0x00
T[6] = 0x03
T[7] = 0x00
Beware that the bytes array has native endianness. If that is not the desired endianness you will have to swap bytes around.
Upvotes: 2