Analog Joystick
# Module Import
import LocoIOT
import time
def map_to_range( x, in_min, in_max, out_min, out_max ):
if (x > in_max):
x = in_max
elif(x < in_min):
x = in_min
sensor_range = in_max - in_min
new_range = out_max - out_min
new_value = (((x - in_min) * new_range) / sensor_range) + out_min
return new_value
# Class Instances Creation
loco_iot = LocoIOT.LocoIOT()
msg = LocoIOT.IOT_Codes()
# Compute The Average From A List Of Elements
def get_average(data_list):
# Initilize Local Variable
sumVal = 0
# Sum The Elements In The List
for i in range(len(data_list)):
sumVal = sumVal + data_list[i]
# Compute The Average
sumVal = sumVal / len(data_list)
# Return The Value Stored In The Local Variable
return sumVal
# Initiate Connection to the Microcontroller
loco_iot.connect()
### Add Hardware Enable(s) Here
# Enable Joystick Hardware Configuration
loco_iot.enable(msg.SUBTYPE_JOYSTICK)
# Instruct the Microcontroller to Start Listening for Control/Request Messages
loco_iot.start()
# Initilize Empty Lists
x_data = []
y_data = []
start_time = time.time()
while (time.time() - start_time) < 40:
# Request Joystick Data
joystick_dict = loco_iot.getData(msg.SUBTYPE_JOYSTICK)
x = -10
y = +10
x_data.append(joystick_dict["X Value"])
y_data.append(joystick_dict["Y Value"])
# Remove Oldest Value From Start Of The List
x_data.pop(0)
y_data.pop(0)
# Compute The List Average
x_avg = get_average(x_data)
y_avg = get_average(y_data)
# Print Joystick Dictionary
print(joystick_dict)
time.sleep(1)
print(x_avg)
time.sleep(1)
print(y_avg)
# Arbitrary Short Delay
time.sleep(0.1)
# Close Connection to the Microcontroller
loco_iot.close()