def main(): # generate_graph('test1_3cm.csv') GDX = gdx() # new instance of gdx class GDX.open_usb() GDX.select_sensors() with open('rubberband2.csv', 'w', newline='') as my_data_file: # The commented-out code below would be used if you want to hard-code in an absolute file path for the location of the csv file... #with open('C:/full/path/to/your/documents/folder/csvexample2.csv', 'w', newline='') as my_data_file: csv_writer = csv.writer(my_data_file) GDX.start(period=10) column_headers = GDX.enabled_sensor_info() csv_writer.writerow(column_headers) for i in range(0,1000): measurements = GDX.read() if measurements == None: break csv_writer.writerow(measurements) # print(measurements) GDX.stop() GDX.close() # # If you did not hard-code in an absolute path, this is where the file should be found. print("location of current working directory = ", os.getcwd())
def stop(self): ''' Terminates the data collection process and closes the sensor ''' # Terminate data collection process self.dataproc.terminate() # Close sensor gdx = gd.gdx() gdx.stop() gdx.close()
def __init__(self, logger=None): self._logger = logger if logger == None: self._logger = Logger("V_CO2", Logger.INFO) self._gdx = gdx() self._gdx.open_usb() #self._headers = self._gdx.enabled_sensor_info(self._gdx) self._headers = self._gdx.enabled_sensor_info() self._info = self._gdx.sensor_info() self._logger.info("Initialized V_CO2")
def collect_data(dataq, timeq): # Open sensor gdx = gd.gdx() gdx.open_usb() gdx.select_sensors(sensors=[1]) gdx.start_fast(period=8) ts = time.time() while (True): try: chunk = gdx.read_chunk( ) #returns a list of measurements from the sensors selected. data = np.asarray(chunk) data = data.flatten() dataq.put(data) timeq.put(time.time() - ts) except (KeyboardInterrupt, SystemExit): print("Exit") raise
def run_test(csv_filepath: str) -> None: GDX = gdx() GDX.open_usb() GDX.select_sensors([1]) # now will automatically select the corret sensor print(f"Writing to {csv_filepath}") with open(csv_filepath, 'w', newline='') as target_file: writer = csv.writer(target_file) GDX.start(period=10) column_headers = GDX.enabled_sensor_info() writer.writerow(column_headers) countdown() for i in range(0, 1000): measurements = GDX.read() if measurements == None: break else: writer.writerow(measurements) GDX.stop() GDX.close() print("Finishing up with the sensor")
def collect_data(self, dataq, timeq, sensor, period): ''' Collects data within it's own process Call this function within its own process to collect chunks of data in the background. The function pushes chunks to a Queue that is accessible from the main process. This is an infinite process and must be terminated manually Args: dataq: The multiprocessing Queue() object to push the chunks of data to timeq: The multiprocessing Queue() object to push the corresponding timestamps to sensor (int): The number identifier for the sensor to collect data from period (int): The sampling period (in milliseconds) to start the sensor with ''' # Open sensor gdx = gd.gdx() gdx.open_usb() # Select and Start Sensors gdx.select_sensors(sensors=sensor) gdx.start_fast(period=period) # Get Start Time ts = time.time() while (True): try: chunk = gdx.read_chunk( ) #returns a list of measurements from the sensors selected. # Turn data into numpy array data = np.asarray(chunk) #data = data.flatten() # Push data and a timestamp to respective queue's dataq.put(data) timeq.put(time.time() - ts) except (KeyboardInterrupt, SystemExit): print("Exit") raise
from tkinter import * from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import gdx, matplotlib.pyplot as plt, numpy as np, pygatt as pg gdx = gdx.gdx() pygatt = pg.pygatt() gdx.open_ble() pg.connect() gdx.select_sensors() root = Tk() def start_recording(): seconds = int(seconds_entry.get()) samples = int(samples_entry.get()) axis = np.arange(0, seconds, 1 / samples) gdx.start(1000 // samples) red = [] green = [] blue = [] # fig, ax = plt.subplots(1,1) ax.cla() for _ in range(seconds * samples): # print(gdx.read()) vals = gdx.read() if vals == None: break r, g, b = vals red.append(r) green.append(g)
import gdx as gd #the gdx function calls are from a gdx.py file inside the gdx folder import matplotlib.pyplot as plt import time import numpy as np # Open sensor gdx = gd.gdx() gdx.open_usb() # Print sensor info device_info = gdx.device_info() battery_level = device_info[2] charger_state = device_info[3] print("battery level % = ", battery_level) print("charger state = ", charger_state) gdx.select_sensors() gdx.start_fast() ts = time.time() recording1 = [] recording2 = [] chunked = [] for i in range(0, 100): chunk = gdx.read_chunk( ) #returns a list of measurements from the sensors selected. data = np.squeeze(chunk) recording1.append(data) #recording2.append(data[1]) if chunk == None: break
from tkinter import * import gdx, numpy as np grip_sensor = gdx.gdx()
def start_game(): global game_over global font # start initializing objects pygame.init() screen = pygame.display.set_mode([640,680]) font = pygame.font.SysFont("comicsansms", 30) pygame.display.set_caption('Lunar Lander') pygame.key.set_repeat(50,50) # Set key repeat (delay,interval) background = pygame.image.load('background.png') lander = Lander([random.randint(0,640-25),0]) # creates a lander object at random x, y=0 moon = Moon([0,530]) # creates a moon at [x 0, y 530] score_label = font.render("Score: 0", 1, (255,255,255)) # Make a surface out of the base font # create a group to add any objects that need to be detected for collision to end the game # this only contains the moon object for now, but more objects can be added to it to end the game collision_group = pygame.sprite.Group() collision_group.add(moon) # create a group to add sensors that the lander can collect during the game collection_group = pygame.sprite.Group() sensor_1 = add_sensor(collection_group) sensor_2 = add_sensor(collection_group) sensor_3 = add_sensor(collection_group) sensor_4 = add_sensor(collection_group) sensor_5 = add_sensor(collection_group) # add / display objects on the screen screen.blit(background,[0,0]) # In pygame, blit means copy so copy the background surface to [x 0 ,y 0] screen.blit(lander.image,lander.rect) # Copy the lander image to coords defined in its rect screen.blit(moon.image,moon.rect) # Blit the moon screen.blit(score_label, [480,600]) screen.blit(sensor_1.image,sensor_1.rect) # Blit the random Sensor screen.blit(sensor_2.image,sensor_2.rect) screen.blit(sensor_3.image,sensor_3.rect) screen.blit(sensor_4.image,sensor_4.rect) screen.blit(sensor_5.image,sensor_5.rect) pygame.display.flip() # In pygame we draw (blit) onto the screen then we 'flip' to the screen we drew on, so it all appears at once # set up gdx sensor my_gdx = gdx.gdx() # object to be used with the Vernier sensor my_gdx.open_usb() my_gdx.select_sensors([1,3]) # hand dynamometer ch1 = force, and ch3 = y axis accel my_gdx.start(period=200) # set the frequency of sensor data retrieval to every half 200 ms print("enabled_sensor_info:", my_gdx.enabled_sensor_info()) # calibrate/baseline the force sensor measurements = my_gdx.read() f0 = measurements[0] f1 = measurements[0] #Main game loop while not game_over: screen.fill([255,255,255]) # Fill the screen, (to wipe out everything else) for event in pygame.event.get(): # Get all events if event.type == pygame.QUIT: # if x button clicked on the window my_gdx.stop() my_gdx.close() sys.exit() # then quit the program # if no pygame events are detected, then use gdx to get the sensor values measurements = my_gdx.read() print(measurements) if (measurements != None): # read the Y-axis tilt that affects the xspeed of the sprite (left/right movement) xspeed = measurements[1] * 5 # calculate the change in force, if any. this will determine the yspeed of the sprite f0 = f1 f1 = measurements[0] print("Change in force: ", f1-f0) # only change the vertical speed if the change in > 1, i.e. only when pressing, not releasing the grip! # compare the change to 1, rather than 0, allowing for small margin of sensor error (simply holding it can cause a small change) if (f1-f0) > 1: yspeed = gravity - ((f1-f0)/3) # slow down the yspeed based on the rate of change in force grips.append(measurements[0]) else: yspeed = gravity # reset it back to normal gravity # set the new speeds lander.speed = [xspeed, yspeed] print("new X speed is:", xspeed) print("new Y speed is:", yspeed) # Checks for collisions with moon sprite, to end the game if pygame.sprite.spritecollide(lander, collision_group, False): game_over = True # get all Sensors that have been collected sensors_collected = pygame.sprite.spritecollide(lander, collection_group, False) for obj in sensors_collected: obj.collected = True # move the objects on the screen only if game is not over yet if not game_over: lander.move() move_sensors(collection_group) # update display screen.blit(background,[0,0]) # Blit the screen every time through the loop screen.blit(lander.image,lander.rect) # And the lander screen.blit(moon.image,moon.rect) # And the moon # blit the sensors that have not been collected yet, and add to the score for those that have been collected score = 0 for obj in collection_group: if obj.collected: score = score + 10 else: screen.blit(obj.image,obj.rect) # Blit the Sensor # blit the score label score_label = font.render("Score: " + str(score), 1, (255,255,255)) # Make a surface out of the base font screen.blit(score_label,[480,600]) # Blit the label # Flip to the new screen pygame.display.flip() pygame.time.delay(30) # end of the game loop # game is over... finalize the rest # stop and close the gdx sensor my_gdx.stop() my_gdx.close() # display message label = font.render("Game over! Click anywhere to continue...", 1, (255,255,255)) # Make a surface out of the base font screen.blit(label,[50,50]) # Blit the label pygame.display.flip() # Flip to the new screen pygame.time.delay(30) # # wait for the mouse click to continue to the graph while True: for event in pygame.event.get(): # Get all event if event.type == pygame.QUIT: # if x clicked... sys.exit() # then quit the program elif event.type == pygame.MOUSEBUTTONDOWN: pygame.quit() save_user_data() graph_grip()
import gdx import matplotlib.pyplot as plt import numpy as np sensor = gdx.gdx() sensor.open_usb() alist = [] clist = [] time = [] sec_num = int(input('\n How many seconds of data would you like to record?: ')) time = np.arange(0, sec_num, step=0.5) sensor.select_sensors([2, 3]) sensor.start(500) for i in range(sec_num * 2): measurements = sensor.read() if measurements == None: break alist.append(measurements[0]) clist.append(measurements[1]) print( F"A Weighted Data: {measurements[0]}\n C Weighted Data: {measurements[1]}" ) sensor.stop() sensor.close() plt.plot(time, alist, color='red') plt.plot(time, clist, color='blue')
# LunarLander - main.py # This program is just for reference, # you cannot run it in Trinket import gdx my_gdx = gdx.gdx() # First establish a connection via USB my_gdx.open_usb() # Then you access the sensor information. sensor_info = my_gdx.sensor_info() for info in sensor_info: sensor_number = info[0] sensor_description = info[1] sensor_units = info[2] print("sensor number = ", sensor_number) print("sensor description = ", sensor_description) print("sensor units = ", sensor_units) # Close the connection with the sensor my_gdx.close()