microrobotics

Untitled

Jan 30th, 2026
2,627
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //Analog read pins
  2. const int xPin = 0;
  3. const int yPin = 1;
  4. const int zPin = 2;
  5.  
  6. //The minimum and maximum values that came from
  7. //the accelerometer while standing still
  8. //You very well may need to change these
  9. int minVal = 265;
  10. int maxVal = 402;
  11.  
  12. //to hold the caculated values
  13. double x;
  14. double y;
  15. double z;
  16.  
  17. void setup(){
  18.   Serial.begin(9600);
  19. }
  20.  
  21. void loop(){
  22.  
  23.   //read the analog values from the accelerometer
  24.   int xRead = analogRead(xPin);
  25.   int yRead = analogRead(yPin);
  26.   int zRead = analogRead(zPin);
  27.  
  28.   //convert read values to degrees -90 to 90 - Needed for atan2
  29.   int xAng = map(xRead, minVal, maxVal, -90, 90);
  30.   int yAng = map(yRead, minVal, maxVal, -90, 90);
  31.   int zAng = map(zRead, minVal, maxVal, -90, 90);
  32.  
  33.   //Caculate 360deg values like so: atan2(-yAng, -zAng)
  34.   //atan2 outputs the value of -π to π (radians)
  35.   //We are then converting the radians to degrees
  36.   x = RAD_TO_DEG * (atan2(-yAng, -zAng) + PI);
  37.   y = RAD_TO_DEG * (atan2(-xAng, -zAng) + PI);
  38.   z = RAD_TO_DEG * (atan2(-yAng, -xAng) + PI);
  39.  
  40.   //Output the caculations
  41.   Serial.print("x: ");
  42.   Serial.print(x);
  43.   Serial.print(" | y: ");
  44.   Serial.print(y);
  45.   Serial.print(" | z: ");
  46.   Serial.println(z);
  47.  
  48.   delay(100);//just here to slow down the serial output - Easier to read
  49. }
Advertisement