Skip to content

Instantly share code, notes, and snippets.

@dean-shaff
Created September 21, 2015 03:33
Show Gist options
  • Save dean-shaff/da90b718d1a843fb5a4b to your computer and use it in GitHub Desktop.
Save dean-shaff/da90b718d1a843fb5a4b to your computer and use it in GitHub Desktop.
gravity snake game using arduino pressure sensor
"""
Took the main functionality of this code from https://www.lebsanft.org/?p=48
"""
import serial
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
import time
import sys
import exceptions
def plot_sensor(ymin, ymax, array_size=50, delay=100, test=False):
"""
min and max are the observed min and max values of the sensor.
Here we assume that there is no delay built into arduino system
"""
bot_top_range=[25,40]
yrange = ymax-ymin
plt.ion()
if test == False:
port = '/dev/cu.usbserial-DA01LJJ1'
other_important_number = 9600
ser = serial.Serial(port, other_important_number)
dat_init = None
while dat_init == None:
try:
dat_init = float(ser.readline())
except:
e = sys.exc_info()[0] #want to catch all exceptions, but if we keyobard interrupt, exit!
if e != exceptions.KeyboardInterrupt:
print("Problem getting initial data" + str(e))
elif e == exceptions.ValueError:
pass
else:
sys.exit()
time_interval = time.time()
for i in xrange(delay):
ser.readline()
time_interval = time.time() - time_interval
elif test == True:
dat_init = 0.0
time_interval = 1.0
difficulty = 0.3
bot_width = np.random.randint(bot_top_range[0],bot_top_range[1])
top_width = np.random.randint(bot_top_range[0],bot_top_range[1])
bot_height = np.random.randint(int(yrange*difficulty))
top_height = np.random.randint(int(yrange*difficulty))
y_data = [dat_init]*int(array_size)
y_prime = [0]*int(array_size)
y_bot = [ymin + bot_height]*2*int(array_size)
y_top = [ymax - top_height]*2*int(array_size)
fig = plt.figure(figsize=(16,9))
ax = fig.add_subplot(111)
line, = plt.plot(y_data)
line_prime, = plt.plot(y_prime)
line_bot, = plt.plot(y_bot, lw=3)
line_top, = plt.plot(y_top, lw=3)
line.set_xdata(np.arange(array_size)*time_interval)
line_top.set_xdata(np.arange(2*array_size)*time_interval)
line_bot.set_xdata(np.arange(2*array_size)*time_interval)
plt.xlim([0,2*array_size])
plt.ylim([ymin,ymax])
plt.title("Snake game")
counter_top = 0
counter_bottom = 0
grace_counter = 0
deaths = 0
grace_period = 15
# plt.ylim([10,40])
while True:
if test == False:
data_array = np.arange(delay)
for i in xrange(delay):
try:
val = ser.readline()
# print(val)
data_array[i] = float(val)
except:
e = sys.exc_info()[0] #want to catch all exceptions, but if we keyobard interrupt, exit!
if e != exceptions.KeyboardInterrupt:
print("Problem continuously reading data, Error: " + str(e))
plt.draw()
else:
sys.exit()
if data_array.shape[0] != delay:
print("Looks like there was an error")
elif test == True:
data_array = np.zeros(delay)
time.sleep(0.2)
counter_top += 1
counter_bottom += 1
if counter_bottom == bot_width:
bot_width = np.random.randint(bot_top_range[0],bot_top_range[1])
bot_height = np.random.randint(int(yrange*difficulty))
counter_bottom = 0
if counter_top == top_width:
top_width = np.random.randint(bot_top_range[0],bot_top_range[1])
top_height = np.random.randint(int(yrange*difficulty))
counter_top = 0
data = np.mean(data_array)
if grace_counter < grace_period:
grace_counter += 1
elif grace_counter == grace_period:
if data > (y_top[array_size-1]) or data < (y_bot[array_size-1]):
deaths += 1
plt.title("Snake Game, deaths = {}".format(deaths))
y_data.append(data)
y_data.pop(0)
# y prime data
y_p = (y_data[-1] - y_data[-2]) / time_interval
y_prime.append(y_p)
y_prime.pop(0)
y_top.append(ymax - top_height)
y_top.pop(0)
y_bot.append(ymin + bot_height)
y_bot.pop(0)
line.set_ydata(y_data)
line_top.set_ydata(y_top)
line_bot.set_ydata(y_bot)
# line_prime.set_ydata(y_prime)
plt.draw() # update the plot
if __name__ == '__main__':
plot_sensor(0, 1024, delay=50, test=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment