Skip to content

Instantly share code, notes, and snippets.

@MartinRGB
Last active November 14, 2023 17:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MartinRGB/c4bc275f3086d43ce3586a70a88c2178 to your computer and use it in GitHub Desktop.
Save MartinRGB/c4bc275f3086d43ce3586a70a88c2178 to your computer and use it in GitHub Desktop.

reference:

https://github.com/tobozo/Rotatey_Cube

https://wokwi.com/projects/328271658006610514

// simple project with rotating 3D cube using Arduino UNO and Transparent 128x64 OLED Display, 
// created by upir, 2022
// youtube channel: https://www.youtube.com/upir_upir
// full tutoral is here: https://youtu.be/kBAcaA7NAlA

// Turbo pressure gauge tutorial: https://youtu.be/JXmw1xOlBdk
// Transparent OLED tutorial: https://youtu.be/hIFDcksXgBk
// Knob + OLED tutorial: https://youtu.be/NPfaLKKsf_Q

// useful links:
// u8g documentation: https://github.com/olikraus/u8glib/wiki/userreference
// Wokwi starting project: https://wokwi.com/arduino/projects/300867986768527882
// Arduino UNO: http://store.arduino.cc/products/arduino-uno-rev3
// Arduino UNO MINI: https://store.arduino.cc/products/uno-mini-le
// Multidimensional arrays: https://www.tutorialspoint.com/arduino/arduino_multi_dimensional_arrays.htm
// 2D Rotation: https://en.wikipedia.org/wiki/Rotation_(mathematics)
// Normal OLED Display: https://www.aliexpress.com/item/4001051535838.html
// Transparent OLED Display: https://a.aliexpress.com/_mKGmhKg
// Big OLED Display: https://www.aliexpress.com/item/1005003091769556.html
// Arduino breadboard prototyping shield: https://www.adafruit.com/product/2077



#include "U8glib.h" // u8g library, note there is a newer version u8g2, please use the older one

// uncomment the correct connection - fast I2C, slow I2C, SPI
U8GLIB_SSD1309_128X64 u8g( 13, 11, 10, 9, 8 );
//U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_DEV_0 | U8G_I2C_OPT_NO_ACK); // slow I2C / TWI     -- I had to use "slow I2C" in my case
//U8GLIB_SSD1306_128X64 u8g(13, 11, 8, 9, 10); // SPI connection  - SCL = 13, SDA = 11, RES = 10, DC = 9, CS = 8

int points[8][2]; // eight 2D points for the cube, values will be calculated in the code

int orig_points [8][3] = {  // eight 3D points - set values for 3D cube
  {-1,-1, 1},
  {1,-1,1},
  {1,1,1},
  {-1,1,1},
  {-1,-1,-1},
  {1,-1,-1},
  {1,1,-1},
  {-1,1,-1}
};

float rotated_3d_points [8][3];   // eight 3D points - rotated around Y axis
float angle_deg = 60.0;           // rotation around the Y axis
float z_offset = -6.0;            // offset on Z axis
float cube_size = 70.0;           // cube size (multiplier)
float time_frame;                 // ever increasing time value

long fps = 0;
long lastMillis = 0;
  
void setup() {
  Serial.begin(115200);
  u8g.setColorIndex(1); // set color to white
  lastMillis = millis();
}

void loop() {

  time_frame++;                                // increase the time frame value by 1
  //cube_size = 50 + sin(time_frame * 0.2)*20;   // oscilate cube size between values 30 - 70

  //z_offset =  -2.0;    // 
  //cube_size = 18.0;    // uncomment those two lines for a "wide angle camera" -- bigger perspective distort

  // increase the angle by 5° increments
  if (angle_deg < 90-5) {
    angle_deg = angle_deg + 5;
  } else {
    angle_deg = 0;
  }


  // calculate the points
  for (int i=0; i<8; i++) {
    // rotate 3d points around the Y axis (rotating X nad Z positions)
    // rotated_3d_points [i][0] = orig_points [i][0] * cos(radians(angle_deg)) - orig_points [i][2] * sin(radians(angle_deg));
    // rotated_3d_points [i][1] = orig_points [i][1];
    // rotated_3d_points [i][2] = orig_points [i][0] * sin(radians(angle_deg)) + orig_points [i][2] * cos(radians(angle_deg)) + z_offset;

    // rotate 3d points around the X axis (rotating Y nad Z positions)
    //rotated_3d_points [i][0] = orig_points [i][1];
    //rotated_3d_points [i][1] = orig_points [i][0] * cos(radians(angle_deg)) - orig_points [i][2] * sin(radians(angle_deg));
    //rotated_3d_points [i][2] = orig_points [i][0] * sin(radians(angle_deg)) + orig_points [i][2] * cos(radians(angle_deg)) + z_offset;

    // rotate 3d points around the Z axis (rotating Y nad X positions)
    //rotated_3d_points [i][0] = orig_points [i][0] * cos(radians(angle_deg)) - orig_points [i][2] * sin(radians(angle_deg));
    //rotated_3d_points [i][1] = orig_points [i][0] * sin(radians(angle_deg)) + orig_points [i][2] * cos(radians(angle_deg));
    //rotated_3d_points [i][2] = orig_points [i][1] + z_offset;  

    // Orig Box
    //rotated_3d_points [i][0] = orig_points [i][0] ;
    //rotated_3d_points [i][1] = orig_points [i][1] ;
    //rotated_3d_points [i][2] = orig_points [i][2] + z_offset;  

    points[i][0] = round(64 + rotated_3d_points [i][0] / rotated_3d_points [i][2] * cube_size);
    points[i][1] = round(32 + rotated_3d_points [i][1] / rotated_3d_points [i][2] * cube_size); 
    
  }

  
  lastMillis = millis() - lastMillis;
  
  u8g.setHiColorByRGB(255,255,255);
  u8g.setFont(u8g_font_5x8);

  u8g.firstPage();
  do {
      // connect the lines between the individual points
      

      u8g.drawLine(points[ 0 ][ 0 ], points[ 0 ][ 1 ] , points[ 1 ][ 0 ] , points[ 1 ][ 1 ] );  // connect points 0-1
      u8g.drawLine(points[ 1 ][ 0 ], points[ 1 ][ 1 ] , points[ 2 ][ 0 ] , points[ 2 ][ 1 ] );  // connect points 1-2  
      u8g.drawLine(points[ 2 ][ 0 ], points[ 2 ][ 1 ] , points[ 3 ][ 0 ] , points[ 3 ][ 1 ] );  // connect points 2-3      
      u8g.drawLine(points[ 3 ][ 0 ], points[ 3 ][ 1 ] , points[ 0 ][ 0 ] , points[ 0 ][ 1 ] );  // connect points 3-0      

      u8g.drawLine(points[ 4 ][ 0 ], points[ 4 ][ 1 ] , points[ 5 ][ 0 ] , points[ 5 ][ 1 ] );  // connect points 4-5
      u8g.drawLine(points[ 5 ][ 0 ], points[ 5 ][ 1 ] , points[ 6 ][ 0 ] , points[ 6 ][ 1 ] );  // connect points 5-6  
      u8g.drawLine(points[ 6 ][ 0 ], points[ 6 ][ 1 ] , points[ 7 ][ 0 ] , points[ 7 ][ 1 ] );  // connect points 6-7      
      u8g.drawLine(points[ 7 ][ 0 ], points[ 7 ][ 1 ] , points[ 4 ][ 0 ] , points[ 4 ][ 1 ] );  // connect points 7-4  

      u8g.drawLine(points[ 0 ][ 0 ], points[ 0 ][ 1 ] , points[ 4 ][ 0 ] , points[ 4 ][ 1 ] );  // connect points 0-4
      u8g.drawLine(points[ 1 ][ 0 ], points[ 1 ][ 1 ] , points[ 5 ][ 0 ] , points[ 5 ][ 1 ] );  // connect points 1-5  
      u8g.drawLine(points[ 2 ][ 0 ], points[ 2 ][ 1 ] , points[ 6 ][ 0 ] , points[ 6 ][ 1 ] );  // connect points 2-6      
      u8g.drawLine(points[ 3 ][ 0 ], points[ 3 ][ 1 ] , points[ 7 ][ 0 ] , points[ 7 ][ 1 ] );  // connect points 3-7                 

      
      u8g.drawStr(36,9,"MPU6050 CUBE");
      
  
  } while ( u8g.nextPage() );   // u8g library specific, has to be there

  
}
@MartinRGB
Copy link
Author

MartinRGB commented Nov 14, 2023

with EC11

reference:

https://howtomechatronics.com/tutorials/arduino/rotary-encoder-works-use-arduino/

https://github.com/tobozo/Rotatey_Cube

https://lastminuteengineers.com/rotary-encoder-arduino-tutorial/

/*
  
  3D Rotatey-Cube is placed under the MIT license
  
  Copyleft (c+) 2016 tobozzo 
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
  
  This project is heavily inspired from the work of GoblinJuicer https://www.reddit.com/user/GoblinJuicer 
  who developed and implemented the idea.
  Started from this sub https://www.reddit.com/r/arduino/comments/3vmw1k/ive_been_playing_with_a_gyroscope_and_an_lcd/
  The code is mainly a remix to make it work with u8glib and mpu6050

  Deps:
    U8glib library grabbed from: https://github.com/olikraus/u8glib
    I2Cdev library grabbed from: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/I2Cdev
    MPU650 library grabbed from: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050
  
  Pinout OLED and MPU (shared)
    VCC => 5V
    GND => GND
    SCL => A5
    SDA => A4
  
  Pinout MPU
    AD0 => GND
    INT => D2

 */

#include "U8glib.h"
#include "MPU6050_6Axis_MotionApps20.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

#define CLK 2
#define DT 3
#define SW 4
unsigned long lastButtonPress = 0;
int counter = 0; 
int aState;
int aLastState;  
bool scaleMode = true;

#define DEBUG true

int btnVarState = 0;

// Accel and gyro data
int16_t  ax, ay, az, gx, gy, gz;
double MMPI = 1000*M_PI;

long int timeLast = -100, period = 1;
// Overall scale and perspective distance
double sZ = 4, scale = 16;
// screen center
uint8_t centerX = 64;
uint8_t centerY = 32;

// Initialize cube point arrays
double C1[] = {  1,  1,  1 };
double C2[] = {  1,  1, -1 };
double C3[] = {  1, -1,  1 };
double C4[] = {  1, -1, -1 };
double C5[] = { -1,  1,  1 };
double C6[] = { -1,  1, -1 };
double C7[] = { -1, -1,  1 };
double C8[] = { -1, -1, -1 };

// Initialize cube points coords
uint8_t P1[] = { 0, 0 };
uint8_t P2[] = { 0, 0 };
uint8_t P3[] = { 0, 0 };
uint8_t P4[] = { 0, 0 };
uint8_t P5[] = { 0, 0 };
uint8_t P6[] = { 0, 0 };
uint8_t P7[] = { 0, 0 };
uint8_t P8[] = { 0, 0 };

U8GLIB_SSD1309_128X64 u8g( 13, 11, 10, 9, 8 );

MPU6050 mpu;


void setup() {
  
  // assign default color value
  
  if ( u8g.getMode() == U8G_MODE_R3G3B2 ) {
    u8g.setColorIndex(255);     // white
  }
  else if ( u8g.getMode() == U8G_MODE_GRAY2BIT ) {
    u8g.setColorIndex(3);         // max intensity
  }
  else if ( u8g.getMode() == U8G_MODE_BW ) {
    u8g.setColorIndex(1);         // pixel on
  }
  else if ( u8g.getMode() == U8G_MODE_HICOLOR ) {
    u8g.setHiColorByRGB(255,255,255);
  }
  
  // join I2C bus (I2Cdev library doesn't do this automatically)
  #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
      Wire.begin();
      TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
  #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
      Fastwire::setup(400, true);
  #endif

  #if DEBUG == true
      // initialize serial communication
      Serial.begin(115200);
  #endif

  mpu.initialize();

  if (mpu.dmpInitialize() == 0) {
      // turn on the DMP, now that it's ready
      mpu.setDMPEnabled(true);
      // supply your own gyro offsets here, scaled for min sensitivity
      mpu.setXGyroOffset(161);
      mpu.setYGyroOffset(48);
      mpu.setZGyroOffset(43);
      mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
  }

  pinMode (CLK,INPUT);
  pinMode (DT,INPUT);
  pinMode(SW, INPUT_PULLUP);
  aLastState = digitalRead(CLK);   

}


void loop() {
  u8g.firstPage();  
  do {
    cubeloop();
  } 
  while( u8g.nextPage() );  
}



void cubeloop() {

   aState = digitalRead(CLK); // Reads the "current" state of the outputA
   // If the previous and the current state of the outputA are different, that means a Pulse has occured
   if (aState != aLastState){     
     // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
     if (digitalRead(DT) != aState) { 
       counter ++;
     } else {
       counter --;
     }
     Serial.print("Position: ");
     Serial.println(counter);
   } 

	// Read the button state
	int btnState = digitalRead(SW);

	//If we detect LOW signal, button is pressed
	if (btnState == LOW) {
		//if 50ms have passed since last LOW pulse, it means that the
		//button has been pressed, released and pressed again
		if (millis() - lastButtonPress > 50) {
			Serial.println("Button pressed!");
      if(btnVarState < 3){
        btnVarState ++;
      }
      else{
        btnVarState = 0;
      }
      counter = 0;
		}

		// Remember last button press event
		lastButtonPress = millis();
	}
  aLastState = aState; // Updates the previous state of the outputA with the current state


  switch (btnVarState) {
    case 0:  // your hand is on the sensor
      scale = 16 + counter*0.5;
      u8g.setFont(u8g_font_4x6);
      u8g.drawStr(8,16,"Scale: ");
      u8g.setPrintPos(8, 28);
      u8g.print(scale);
      break;
    case 1:  // your hand is close to the sensor
      sZ = 4 + counter *0.5;
      u8g.setFont(u8g_font_4x6);
      u8g.drawStr(8,16,"Perspec: ");
      u8g.setPrintPos(8, 28);
      u8g.print(sZ);
      break;
    case 2:  // your hand is a few inches from the sensor
      centerX = 64 + counter;
      u8g.setFont(u8g_font_4x6);
      u8g.drawStr(8,16,"cX: ");
      u8g.setPrintPos(8, 28);
      u8g.print(centerX);
      break;
    case 3:  // your hand is nowhere near the sensor
      centerY = 32 + counter;
      u8g.setFont(u8g_font_4x6);
      u8g.drawStr(8,16,"cY: ");
      u8g.setPrintPos(8, 28);
      u8g.print(centerY);
      break;
  }
  // switch(btnVarState) ​{
  //     case 0:
  //       scale = 16 + counter*0.5;
  //       u8g.setFont(u8g_font_4x6);
  //       u8g.drawStr(8,16,"Scale: ");
  //       u8g.setPrintPos(8, 28);
  //       u8g.print(scale);
  //       break;

  //     case 1:
  //       sZ = 4 + counter *0.5;

  //       u8g.setFont(u8g_font_4x6);
  //       u8g.drawStr(8,16,"Perspec: ");
  //       u8g.setPrintPos(8, 28);
  //       u8g.print(sZ);
  //       // statements
  //       break;
  //     case 2:
  //       // statements
  //       break;
  //     case 3:
  //       break;
  //     default:
  //       // default statements
  // }

  period = millis()- timeLast;
  timeLast = millis(); 
  // precalc
  double MMPI_TIME = MMPI*period;

  //Read gyro, apply calibration, ignore small values
  mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

  // ignore low values (supply uour own values here, based on Serial console output)
  if(abs(gx)<10){
    gx = 0;
  }
  if(abs(gy)<30){
    gy = 0;
  }
  if(abs(gz)<12){
    gz = 0;
  }

  // scale angles down, rotate
  vectRotXYZ((double)gy/MMPI_TIME, 1); // X
  vectRotXYZ((double)-gx/MMPI_TIME, 2); // Y
  vectRotXYZ((double)gz/MMPI_TIME, 3); // Z

  #if DEBUG == true
    // Serial.print(scale);
    // Serial.print("\t");  
    // Serial.print(ax);
    // Serial.print("\t");
    // Serial.print(ay);
    // Serial.print("\t");
    // Serial.print(az);
    // Serial.print("\t");
    // Serial.print((uint8_t) gx);
    // Serial.print("\t");
    // Serial.print((uint8_t) gy);
    // Serial.print("\t");
    // Serial.println((uint8_t) gz);
  #endif

  // calculate each point coords
  P1[0] = centerX + scale/(1+C1[2]/sZ)*C1[0]; P1[1] = centerY + scale/(1+C1[2]/sZ)*C1[1];
  P2[0] = centerX + scale/(1+C2[2]/sZ)*C2[0]; P2[1] = centerY + scale/(1+C2[2]/sZ)*C2[1];
  P3[0] = centerX + scale/(1+C3[2]/sZ)*C3[0]; P3[1] = centerY + scale/(1+C3[2]/sZ)*C3[1];
  P4[0] = centerX + scale/(1+C4[2]/sZ)*C4[0]; P4[1] = centerY + scale/(1+C4[2]/sZ)*C4[1];
  P5[0] = centerX + scale/(1+C5[2]/sZ)*C5[0]; P5[1] = centerY + scale/(1+C5[2]/sZ)*C5[1];
  P6[0] = centerX + scale/(1+C6[2]/sZ)*C6[0]; P6[1] = centerY + scale/(1+C6[2]/sZ)*C6[1];
  P7[0] = centerX + scale/(1+C7[2]/sZ)*C7[0]; P7[1] = centerY + scale/(1+C7[2]/sZ)*C7[1];
  P8[0] = centerX + scale/(1+C8[2]/sZ)*C8[0]; P8[1] = centerY + scale/(1+C8[2]/sZ)*C8[1];

  // draw each cube edge
  u8g.drawLine(P1[0], P1[1], P2[0], P2[1]); //1-2
  u8g.drawLine(P1[0], P1[1], P3[0], P3[1]); //1-3
  u8g.drawLine(P1[0], P1[1], P5[0], P5[1]); //1-5
  u8g.drawLine(P2[0], P2[1], P4[0], P4[1]); //2-4
  u8g.drawLine(P2[0], P2[1], P6[0], P6[1]); //2-6
  u8g.drawLine(P3[0], P3[1], P4[0], P4[1]); //3-4
  u8g.drawLine(P3[0], P3[1], P7[0], P7[1]); //3-7
  u8g.drawLine(P4[0], P4[1], P8[0], P8[1]); //4-8
  u8g.drawLine(P5[0], P5[1], P6[0], P6[1]); //5-6
  u8g.drawLine(P5[0], P5[1], P7[0], P7[1]); //5-7
  u8g.drawLine(P6[0], P6[1], P8[0], P8[1]); //6-8
  u8g.drawLine(P7[0], P7[1], P8[0], P8[1]); //7-8

}


void vectRotXYZ(double angle, int axe) { 
  int8_t m1; // coords polarity
  uint8_t i1, i2; // coords index
  
  switch(axe) {
    case 1: // X
      i1 = 1; // y
      i2 = 2; // z
      m1 = -1;
    break;
    case 2: // Y
      i1 = 0; // x
      i2 = 2; // z
      m1 = 1;
    break;
    case 3: // Z
      i1 = 0; // x
      i2 = 1; // y
      m1 = 1;
    break;
  }

  double t1 = C1[i1];
  double t2 = C1[i2];
  C1[i1] = t1*cos(angle)+(m1*t2)*sin(angle);
  C1[i2] = (-m1*t1)*sin(angle)+t2*cos(angle);
  
  t1 = C2[i1]; 
  t2 = C2[i2];
  C2[i1] = t1*cos(angle)+(m1*t2)*sin(angle);
  C2[i2] = (-m1*t1)*sin(angle)+t2*cos(angle);

  t1 = C3[i1]; 
  t2 = C3[i2];
  C3[i1] = t1*cos(angle)+(m1*t2)*sin(angle);
  C3[i2] = (-m1*t1)*sin(angle)+t2*cos(angle);

  t1 = C4[i1]; 
  t2 = C4[i2];
  C4[i1] = t1*cos(angle)+(m1*t2)*sin(angle);
  C4[i2] = (-m1*t1)*sin(angle)+t2*cos(angle);

  t1 = C5[i1]; 
  t2 = C5[i2];
  C5[i1] = t1*cos(angle)+(m1*t2)*sin(angle);
  C5[i2] = (-m1*t1)*sin(angle)+t2*cos(angle);

  t1 = C6[i1]; 
  t2 = C6[i2];
  C6[i1] = t1*cos(angle)+(m1*t2)*sin(angle);
  C6[i2] = (-m1*t1)*sin(angle)+t2*cos(angle);

  t1 = C7[i1]; 
  t2 = C7[i2];
  C7[i1] = t1*cos(angle)+(m1*t2)*sin(angle);
  C7[i2] = (-m1*t1)*sin(angle)+t2*cos(angle);

  t1 = C8[i1]; 
  t2 = C8[i2];
  C8[i1] = t1*cos(angle)+(m1*t2)*sin(angle);
  C8[i2] = (-m1*t1)*sin(angle)+t2*cos(angle);

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment