#Program to test the "zweibein" Robot with accelerometer and servo movement.
#Run it with:
#python3 zweibeinservotest.py
#The servo connected to servo connector 0 should move back and forth, and the
#printout shows the accelerometer values, they should change if the accelerometer (robot) is moved.
#You can check the I2C addresses of the devices connected to the Raspberry Pi using:
#sudo i2cdetect -y 1
#
#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)
   
   phase=0.0
   speed=0.1;  #phase increment in radiants for servo, speed is forward
   schrittzaehler=0
   
   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))  
      
      #Test Servo 0, it should go back and forth:
      phase+=speed
      
      #makes servos go first to positive, then to negative direction, relative to 90 degrees,
      #servos connected to connector 0 to 15, 1 period for each:
      print("Servo:", schrittzaehler%16)
      kit.servo[schrittzaehler%16].angle = 90+10*np.sin(phase)  
      
      if(phase>= 6.28):
         phase=0.0;
         schrittzaehler += 1;
     
      if(phase<0 ):
         phase=6.28;
         schrittzaehler += 1;
      time.sleep(0.01)
      
