#Program to test the "zweibein" Robot Balance, with accelerometer and servo movement.
#Run it with:
#python3 zweibeinbalancetest.py
#
#Includes a
#function to read accelerometer sensor MMA8452Q from the Raspberry Pi I2C port.
#See: http://ozzmaker.com/guide-to-interfacing-a-gyro-and-accelerometer-with-a-raspberry-pi/
#Based on:
#https://github.com/ControlEverythingCommunity/MMA8452Q/blob/master/Python/MMA8452Q.py
#Connections:
#http://www.pibits.net/code/mma8452q-accelerometer-and-raspberry-pi-example.php
#
#Data Sheet of MMA8452Q:
#https://www.robotshop.com/media/files/pdf/triple-axis-accelerometer-breakout-board-mma8452q-headers-datasheet.pdf
#Activate I2C bus on Raspi with "sudo raspi-config"
#Then:
#sudo apt-get install build-essential libi2c-dev i2c-tools python-dev libffi-dev
#sudo pip install cffi smbus2 (for python2, for python3 it should be smbus and pip3)
#Gerald Schuller, April 2019

#import smbus2 as smbus #for Python2
import smbus   #for Python3
import time

# Get I2C bus
bus = smbus.SMBus(1)
#For the servos:
from adafruit_servokit import ServoKit

#Test MMA8452Q address after connecting it with (it shows in the table):
#sudo i2cdetect -y 1
#For Velleman VMA208 accelerometer it should be 0x1D, for others other addresses
MMA8452Q= 0x1D
#Setup:
# Select Control register, 0x2A(42)
#		0x00(00)	StandBy mode
bus.write_byte_data(MMA8452Q, 0x2A, 0x00)
# MMA8452Q address, 0x1C(28)
# Select Control register, 0x2A(42)
#		0x01(01)	Active mode
bus.write_byte_data(MMA8452Q, 0x2A, 0x01)
# MMA8452Q address, 0x1C(28)
# Select Configuration register, 0x0E(14)
#		0x00(00)	Set range to +/- 2g
bus.write_byte_data(MMA8452Q, 0x0E, 0x00)
time.sleep(0.1)

def readaccelerometer():
   #Read current accelerometer values
   #returns:
   #List of 3 float acceleration-values, [x,y,z]
   
   # Read data back from 0x00(0), 7 bytes
   # Status register, X-Axis MSB, X-Axis LSB, Y-Axis MSB, Y-Axis LSB, Z-Axis MSB, Z-Axis LSB
   data = bus.read_i2c_block_data(MMA8452Q, 0x00, 7)

   # Convert the data
   xAccl = (data[1] * 256 + data[2]) / 16
   if xAccl > 2047 :
      xAccl -= 4096
   #normalize to value range of -1.0...1.0:
   X=xAccl/1024.0
      
   yAccl = (data[3] * 256 + data[4]) / 16
   if yAccl > 2047 :
      yAccl -= 4096
   #normalize to value range of -1.0...1.0:
   Y=yAccl/1024.0

   zAccl = (data[5] * 256 + data[6]) / 16
   if zAccl > 2047 :
      zAccl -= 4096 
   #normalize to value range of -1.0...1.0:
   Z=zAccl/1024.0

   return (X,Y,Z)

#Testing:
if __name__ == '__main__':
   import numpy as np
   
   # Set channels to the number of servo channels on your kit.
   # 8 for FeatherWing, 16 for Shield/HAT/Bonnet.
   kit = ServoKit(channels=16)
   huefterechts=kit.servo[0]
   huefterechts.angle=90.0-60
   hueftelinks=kit.servo[1]
   hueftelinks.angle=90.0+60
   knierechts=kit.servo[2]
   knierechts.angle=90.0+1
   knielinks=kit.servo[3]
   knielinks.angle=90.0-1
   fussrechts=kit.servo[14]
   fussrechts.angle=90.0
   fusslinks=kit.servo[15]
   fusslinks.angle=90.0
   
   timestep=0.01 #time step in seconds
   phase=0.0
   speed=0.02;  #phase increment in radiants for servo, speed is forward
   schrittzaehler=0
   #PID controller:
   ydist=0.0;
   zdist=0.0;
   omega=2*3.14*20.0/100; #normalized frequency of oscillation for 100 hz sampling (10ms delay)
   #Q=0.5;
   Q=0.005 #without artifical factor 100
   k1=2*Q*np.cos(omega); #
   k2=Q**2; #
   verttilt=0.15  #Starting Vertical tilt of robot
   hortilt=0.0    #starting horizontal tilt
   yold=0.0
   zold=0.0
   ampRH=0.0;ampLH=0.0; ampLK=0.0; ampRK=0.0 #amplitudes for the steps
   
   
   while True:
      #test if accelerometer works, move accelerometer, the printed values should change:
      (X,Y,Z)=readaccelerometer()
      #print("Accelerometer X,Y,Z=", round(X,2),round(Y,2),round(Z,2))  
      
      #ydist+= (Y-verttilt)*(timestep*100);        #integral values (distance traveled, with artificial factor 100)
      #zdist+= (Z-hortilt)*(timestep*100);
      ydist+= (Y-verttilt)*(timestep);        #integral values (distance traveled, without artificial factor 100)
      zdist+= (Z-hortilt)*(timestep);
      ydist=np.clip(ydist,-50,50);
      zdist=np.clip(zdist,-50,50);
      
      #yspeed=(Y-yold)/(timestep*100);  #differential values (speed, with artificial factor 100)
      #zspeed=(Z-zold)/(timestep*100);
      yspeed=(Y-yold)/(timestep);  #differential values (speed, without artificial factor 100)
      zspeed=(Z-zold)/(timestep);
      yold=Y;
      zold=Z;
      #frontbalance = 1.5*(ydist + k1*(Y-verttilt) -k2*yspeed);
      #sidebalance = -1.7*(zdist + k1*(Z-hortilt) -k2*zspeed); #horloopgain=1.5
      
      #frontbalance = 1.5*180/3.14*(100*3.14/180)*(ydist + k1*(Y-verttilt) -k2*yspeed); #without artificial factor 100 for yspeed and ydist, k1-> k1/100, k2-> k2/(100**2), hence Q-> Q/100
      #shorter, with conversion Radiants-> Degrees:
      frontbalance = 180/3.14* 2.6*(ydist + k1*(Y-verttilt) -k2*yspeed); #without artificial factor 100
      sidebalance = -180/3.14* 2.9*(zdist + k1*(Z-hortilt) -k2*zspeed); #without artificial factor 100
      
      sidebalance=np.clip(sidebalance,-50,50);
      
      
      #This should make the roboto tilt forth and back, observe the printout at which values it can balances on its own:
      #verttilt=(np.sin(phase)**2)*0.5
      #print("vertical tilt=", verttilt) 
      #Choose a stable middle verttilt value:
      verttilt=0.45
      #Then this should make the robot tilt sideways, observe the printout at which values it can still stand:
      hortiltoffset=0.0
      if (schrittzaehler>0):
         hortiltoffset=0.05*np.sin(phase)
      hortilt=-0.05+hortiltoffset
      #hortilt=-0.05 #somewhat to the right
      print("horizontal tilt=", hortilt) 
      #use the maximum hortilt value for the steps
      angle=np.clip(int(-frontbalance+90+1*ampRH),0, 180);
      huefterechts.angle=angle;
      angle=np.clip(int(frontbalance+90+10+1*ampLH),0,180);
      hueftelinks.angle=angle;
      angle=np.clip(int(sidebalance+90-5-ampRK),0,180);
      knierechts.angle=angle;
      angle=np.clip(int(sidebalance+90+5-ampLK),0,180);
      knielinks.angle=angle; 
      
      fussrechts.angle=90.0-100*np.clip(hortiltoffset,0,1)
      fussrechts.angle=90.0-100*np.clip(hortiltoffset,-1,0)
      
      phase+=speed
      #print("phase=", phase)
      if(phase>= 6.28):
         phase=0.0;
         schrittzaehler += 1;
         print("schrittzaehler=", schrittzaehler)
     
      if(phase<0 ):
         phase=6.28;
         schrittzaehler += 1;
      time.sleep(timestep)
      
