Go Down

Topic: byteRead and byteWrite macros (Read 58 times) previous topic - next topic

fog44

Dear all,

Please find below the definitions of byteRead and byteWrite macros, something similar to the bitRead and bitWrite functions, but for bytes.

Hope this helps,

Code: [Select]

// ------------------------------------------------------------------------------------------
// byteRead macro definition. Francois Auger, Universite de Nantes, France, November 19, 2016
#define byteRead(x,n) ( * ( (unsigned char*)(&x) + n) )
// ------------------------------------------------------------------------------------------
// byteWrite macro definition. Francois Auger, Universite de Nantes, France, April 20, 2017
#define byteWrite(x,n,b) *( ( (unsigned char*)(&x)+n) )=b
// ------------------------------------------------------------------------------------------

byte byte0, byte1, byte2, byte3;

void setup() {
  Serial.begin(115200); // serial port initialization
  // while (!Serial) {}   // wait for serial port to connect. Needed for Leonardo only
  
  Serial.println(F("byteRead-byteWriteDemo program started"));
}

void loop() {
 int N1 = 1025, N1copy;
 byte0=byteRead(N1,0); byte1=byteRead(N1,1);
 Serial.print(N1); Serial.print(" = "); Serial.print(byte1); Serial.print("*256 + "); Serial.print(byte0);
 byteWrite(N1copy, 0, byte0); byteWrite(N1copy, 1, byte1); Serial.print("  N1copy = "); Serial.println(N1copy);
 
 word N2 = 1025, N2copy;
 byte0=byteRead(N2,0); byte1=byteRead(N2,1);
 Serial.print(N2); Serial.print(" = "); Serial.print(byte1); Serial.print("*256 + "); Serial.print(byte0);
 byteWrite(N2copy, 0, byte0); byteWrite(N2copy, 1, byte1); Serial.print("  N2copy = "); Serial.println(N2copy);

 long int N3 = 70000, N3copy;
 byte0=byteRead(N3,0); byte1=byteRead(N3,1); byte2=byteRead(N3,2); byte3=byteRead(N3,3);
 Serial.print(N3); Serial.print(" = ");
 Serial.print(byte3); Serial.print("*16777216 + "); Serial.print(byte2); Serial.print("*65536 + ");
 Serial.print(byte1); Serial.print("*256 + "); Serial.print(byte0);
 byteWrite(N3copy, 0, byte0); byteWrite(N3copy, 1, byte1); byteWrite(N3copy, 2, byte2); byteWrite(N3copy, 3, byte3);
 Serial.print("  N3copy = "); Serial.println(N3copy);

 float x=M_PI, xcopy;
 Serial.print(x, 5);
 byte0=byteRead(x,0); byte1=byteRead(x,1); byte2=byteRead(x,2); byte3=byteRead(x,3);
 byteWrite(xcopy, 0, byte0); byteWrite(xcopy, 1, byte1); byteWrite(xcopy, 2, byte2); byteWrite(xcopy, 3, byte3);
 Serial.print("  xcopy = "); Serial.println(xcopy, 5);
 
 Serial.println(); delay(1000);
}

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy