HighInBC

Untitled

Oct 11th, 2022
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. #include <Wire.h>
  2. #define address 0x1E //0011110b, I2C 7bit address of HMC5883
  3.  
  4. void setup(){
  5. //Initialize Serial and I2C communications
  6. Serial.begin(9600);
  7. Wire.begin();
  8. //Put the HMC5883 IC into the correct operating mode
  9. Wire.beginTransmission(address); //open communication with HMC5883
  10. Wire.write(0x02); //select mode register
  11. Wire.write(0x00); //continuous measurement mode
  12. Wire.endTransmission();
  13. }
  14.  
  15. void loop(){
  16.  
  17. int x,y,z; //triple axis data
  18. int xmin,xmax,ymin,ymax,zmin,zmax;
  19. xmin=0; xmax=0; ymax=0; ymin = 0; zmin=0;zmax=0;
  20. //Tell the HMC5883 where to begin reading data
  21. Wire.beginTransmission(address);
  22. Wire.write(0x03); //select register 3, X MSB register
  23. Wire.endTransmission();
  24.  
  25.  
  26. //Read data from each axis, 2 registers per axis
  27. Wire.requestFrom(address, 6);
  28. if(6<=Wire.available()){
  29. x = Wire.read()<<8; //X msb
  30. x |= Wire.read(); //X lsb
  31. z = Wire.read()<<8; //Z msb
  32. z |= Wire.read(); //Z lsb
  33. y = Wire.read()<<8; //Y msb
  34. y |= Wire.read(); //Y lsb
  35. }
  36.  
  37. float heading = atan2(65536-y,65536-z);
  38.  
  39. //Print out values of each axis
  40. Serial.print("x: ");
  41. Serial.print(x);
  42. Serial.print(" y: ");
  43. Serial.print(y);
  44. Serial.print(" z: ");
  45. Serial.print(z);
  46. Serial.print(" Heading: ");
  47. Serial.println(heading);
  48. }
Advertisement
Add Comment
Please, Sign In to add comment