import smbus
import time
import serial
import pygame
import time

bus = smbus.SMBus(1)

address = 0x04

pygame.init()
j = pygame.joystick.Joystick(0)
j.init()
global speedr
global speedl
global directionr
global directionl
i=0
    
try:
    while True:
        
        pygame.event.pump()
        time.sleep(0.1)
        
        if j.get_axis(0) != 0.0 or j.get_axis(1) != 0.0:
            if j.get_axis(1) != 0.0 :
                value = j.get_axis(1)
                values = j.get_axis(0)
                if  value < -0.02 : 
                    directionr = 0
                    directionl = 0  
                    if values < 0.00:
                        speedr = 255 - ( values * -255)
                        speedl = 255
                    elif values > 0.00:
                        speedl = 255 - ( values * 255)
                        speedr = 255
                    else :
                        speedl = 255
                        speedr = 255
                    #print " Achse 1" , + value
                    #print "speed front" , + int(speedl)
                elif value > 0.00:
                    directionr = 1
                    directionl = 1
                    if values < 0.00:
                        speedr = 255 - ( values * -255)
                        speedl = 255
                    elif values > 0.00:
                        speedr = 255
                        speedl = 255 - ( values * 255)
                    else :
                        speedr = 255
                        speedl = 255
                elif value >= -0.02 and value <= 0.00 and values != 0.00:
                    if values > 0.0:
                        speedr = 255
                        speedl = 0
                    elif values < 0.00:
                        speedr = 0
                        speedl = 255
                    else:
                        continue
                    #print "speed back" , + int(speedl)
                else :
                    speedr = 0
                    speedl = 0
                    
            else:                 continue
              
        else:
            speedr = 0
            speedl = 0
            directionr = 1
            directionl = 1
        
        
        bus.write_i2c_block_data(address,directionr,[directionl,int(speedr),int(speedl)])
        #time.sleep(1)

except KeyboardInterrupt:
     j.quit()
