### Install VPython using pip Source: https://github.com/vernierst/godirect-examples/blob/main/python/vpython_examples/readme.md This command installs the VPython library using pip, which is necessary for using VPython functionalities in your Python projects. ```bash pip install vpython ``` -------------------------------- ### Basic VPython starter program Source: https://github.com/vernierst/godirect-examples/blob/main/python/vpython_examples/readme.md A simple VPython program that creates a sphere, useful for testing VPython installation and basic functionality without Go Direct sensors. ```python from vpython import * sphere() ``` -------------------------------- ### Check VPython installation version Source: https://github.com/vernierst/godirect-examples/blob/main/python/vpython_examples/readme.md This command displays the installed version of the VPython library in your terminal. ```bash pip show vpython ``` -------------------------------- ### Show godirect Module Installation Information Source: https://github.com/vernierst/godirect-examples/blob/main/python/readme.md Displays detailed information about the installed godirect Python module, including its version number. This command is used to confirm a successful installation. ```shell pip3 show godirect ``` -------------------------------- ### Start Data Collection Source: https://github.com/vernierst/godirect-examples/blob/main/python/example_without_gdx/readme.md Initiates data collection from the enabled sensors at the default rate. An optional `period` parameter can specify the sampling interval in milliseconds. ```python # start measurements at the typical data rate mydevice.start() # returns True on success # start measurements at 1000ms per sample mydevice.start(period=1000) ``` -------------------------------- ### Check Python 3 Installation (Command Line) Source: https://github.com/vernierst/godirect-examples/blob/main/python/readme.md This command checks if Python 3 is installed on your system. If not, it suggests trying 'python3 --version'. Installation instructions from python.org are also mentioned. ```bash python --version ``` ```bash python3 --version ``` -------------------------------- ### Basic Data Collection with gdx Module Source: https://github.com/vernierst/godirect-examples/blob/main/python/readme.md A fundamental example demonstrating data collection from a Go Direct sensor using the gdx module. It covers opening a connection (USB), selecting sensors, starting data collection, reading measurements in a loop, and finally stopping and closing the connection. Assumes the gdx module is accessible. ```python from gdx import gdx gdx = gdx.gdx() gdx.open(connection='usb') gdx.select_sensors() gdx.start() for i in range(0,5): measurements = gdx.read() if measurements == None: break print(measurements) gdx.stop() gdx.close() ``` -------------------------------- ### Get Enabled Sensors Source: https://github.com/vernierst/godirect-examples/blob/main/python/example_without_gdx/readme.md Retrieves a list of `GoDirectSensor` objects that have been enabled for data collection after `start()` has been called. ```python # get a list of the GoDirectSensor objects that are enabled mysensors = mydevice.get_enabled_sensors() ``` -------------------------------- ### GoDirect Initialization API Source: https://github.com/vernierst/godirect-examples/blob/main/python/example_without_gdx/readme.md Demonstrates how to initialize the GoDirect library, specifying whether to use BLE, USB, or both. ```APIDOC ## GoDirect Initialization API ### Description Initialize the GoDirect library, optionally specifying connection methods (BLE, USB). ### Method Instantiation ### Endpoint N/A ### Parameters #### Query Parameters - **use_ble** (boolean) - Optional - Set to True to enable Bluetooth Low Energy connections. - **use_usb** (boolean) - Optional - Set to True to enable USB connections. ### Request Example ```python # Use both BLE and USB (default) godirect = GoDirect() # Use only BLE godirect = GoDirect(use_ble=True, use_usb=False) # Use only USB godirect = GoDirect(use_ble=False, use_usb=True) ``` ### Response N/A ``` -------------------------------- ### Install Linux Dependencies for godirect Source: https://github.com/vernierst/godirect-examples/blob/main/python/readme.md Installs necessary Linux packages, libusb1.0.0 and libudev-dev, required by the godirect module and its dependencies for USB communication. This is a prerequisite for the pip3 installation on some Linux distributions. ```shell sudo apt install libusb1.0.0 sudo apt install libudev-dev ``` -------------------------------- ### Install Bleak Module Source: https://github.com/vernierst/godirect-examples/blob/main/python/readme.md Installs or updates the 'bleak' module, a necessary component for Bluetooth Low Energy (BLE) communication on various platforms. Ensure you are using 'pip3' for Python 3 installations. ```shell pip3 install bleak ``` -------------------------------- ### Open Device Connection Source: https://github.com/vernierst/godirect-examples/blob/main/python/example_without_gdx/readme.md Opens a connection to a selected GoDirectDevice. Setting `auto_start=True` will automatically enable default sensors and begin measurements upon opening. If `auto_start=False`, manual calls to `enable_sensors()` and `start()` are required. ```python # returns True on success or False on failure mydevice.open(auto_start=False) ``` -------------------------------- ### Device Connection and Data Collection API Source: https://github.com/vernierst/godirect-examples/blob/main/python/example_without_gdx/readme.md Details on opening a device, enabling sensors, starting/stopping measurements, and reading data. ```APIDOC ## Device Connection and Data Collection API ### Description Manage the connection to a Go Direct device, configure sensor readings, and collect data. ### Method Function Call ### Endpoint N/A ### Parameters #### Path Parameters - **device** (GoDirectDevice object) - The device object obtained from discovery. #### Query Parameters - **auto_start** (boolean) - Optional - If True, automatically enables default sensors and starts measurements upon opening the device. - **period** (integer) - Optional - The measurement interval in milliseconds when starting data collection. #### Request Body - **sensor_ids** (list of integers) - Optional - A list of sensor numbers to enable for data collection. ### Request Example ```python # Open device and automatically start measurements if mydevice.open(auto_start=True): # Device is connected and sensors are active spass # Open device without auto-starting if mydevice.open(auto_start=False): # Get available sensors sensors = mydevice.list_sensors() # Enable specific sensors mydevice.enable_sensors([2, 3, 4]) # Start measurements at default rate mydevice.start() # Start measurements at 1000ms interval mydevice.start(period=1000) # Get enabled sensors mysensors = mydevice.get_enabled_sensors() # Read data in a loop for i in range(0, 10): if mydevice.read(): for sensor in mysensors: print(sensor.values) sensor.clear() # Stop data collection mydevice.stop() # Close the device connection mydevice.close() # Quit the GoDirect library gracefully godirect.quit() ``` ### Response - **open()** (boolean) - Returns True on successful connection, False otherwise. - **start()** (boolean) - Returns True on successful start, False otherwise. - **read()** (boolean) - Returns True if new data was received, False otherwise. - **list_sensors()** - Returns a list of Sensor objects. - **get_enabled_sensors()** - Returns a list of enabled Sensor objects. - **Sensor.values** (list) - A list of collected measurements for a sensor. ``` -------------------------------- ### Debugging API Source: https://github.com/vernierst/godirect-examples/blob/main/python/example_without_gdx/readme.md Instructions on how to enable verbose logging for debugging purposes. ```APIDOC ## Debugging API ### Description Configure the logging module to output detailed debugging information from the godirect library and its dependencies. ### Method Function Call ### Endpoint N/A ### Parameters N/A ### Request Example ```python import logging logging.basicConfig() logging.getLogger('godirect').setLevel(logging.DEBUG) logging.getLogger('bleak').setLevel(logging.DEBUG) logging.getLogger('pygatt').setLevel(logging.DEBUG) ``` ### Response N/A ``` -------------------------------- ### Install godirect Module using pip3 Source: https://github.com/vernierst/godirect-examples/blob/main/python/readme.md Installs the Vernier godirect Python module for USB and BLE communication using pip3. This command is applicable across Windows, macOS, and Linux systems. Ensure Python 3 and pip are installed. ```shell pip3 install godirect ``` -------------------------------- ### Device Discovery API Source: https://github.com/vernierst/godirect-examples/blob/main/python/example_without_gdx/readme.md Covers methods for listing available devices or automatically finding the nearest one. ```APIDOC ## Device Discovery API ### Description Methods for discovering available Go Direct devices via BLE or USB. ### Method Function Call ### Endpoint N/A ### Parameters #### Query Parameters - **threshold** (integer) - Optional - For BLE discovery, specifies the minimum dB value to consider a device 'near'. ### Request Example ```python # Get a list of all available devices devices = godirect.list_devices() # Automatically find the nearest device (BLE or USB) mydevice = godirect.get_device() # Automatically find the nearest device with a specific BLE threshold mydevice = godirect.get_device(threshold=-200) ``` ### Response - **devices** (list of GoDirectDevice objects) - A list of discovered devices. - **mydevice** (GoDirectDevice object or None) - The discovered device or None if no device is found. ``` -------------------------------- ### Start Measurements on Connected Go Direct Devices Source: https://github.com/vernierst/godirect-examples/blob/main/javascript/advanced_examples/gdx_using_two_devices.html Initiates data collection from all connected Go Direct devices. ```javascript function startMeasurements() { if (deviceObject1.device && deviceObject2.device) { deviceObject1.device.start(); deviceObject2.device.start(); } } ``` -------------------------------- ### Install Vernierpygatt Module for Bluegiga Dongle Source: https://github.com/vernierst/godirect-examples/blob/main/python/readme.md Installs the 'vernierpygatt' module, which is required when using a Bluegiga BLED112 Bluetooth Low Energy Dongle to connect to GoDirect devices. This module facilitates communication via the dongle. ```shell pip3 install vernierpygatt ``` -------------------------------- ### Initialize Go Direct Module and Chart Source: https://github.com/vernierst/godirect-examples/blob/main/javascript/advanced_examples/gdx_making_a_chart.html Sets up event listeners for device selection (Bluetooth/USB) and initializes a Chart.js line chart to display sensor data. It also checks for browser compatibility with Web Bluetooth and WebHID. ```javascript window.chartColors = { // create colors for chart to use green: 'rgb(255, 99, 132)', }; const usbBtn = document.querySelector('#usb'); const usbLabel = document.querySelector('#usb_label'); const bleBtn = document.querySelector('#ble'); const bleLabel = document.querySelector('#ble_label'); const selectDeviceBtn = document.querySelector('#select_device'); const output = document.querySelector('#output'); // create global array for sensor readings to be stored let sensorReadings = []; if (navigator.bluetooth) { bleLabel.innerHTML = `Bluetooth`; } else { if (navigator.hid) usbBtn.checked = true; bleLabel.innerHTML = `Bluetooth Not Supported More information`; bleBtn.disabled = true; } if (navigator.hid) { usbLabel.innerHTML = `USB`; } else { if (navigator.bluetooth) bleBtn.checked = true; usbLabel.innerHTML = `USB Not Supported More information`; usbBtn.disabled = true; } if (!navigator.bluetooth && !navigator.hid) { selectDeviceBtn.style.visibility='hidden'; } // chart setup let config = { // type of chart, could be 'line' or 'bar' type: 'line', data: { // x axis labels labels: [1,2,3,4,5,6,7,8,9,10], datasets: [{ label: '', backgroundColor: window.chartColors.green, borderColor: window.chartColors.green, // initial data, sensor data to be added with addData function data: [], fill: false, }] }, options: { responsive: true, title: { display: true, text: 'Chart.js Line Chart' }, tooltips: { mode: 'index', intersect: false, }, hover: { mode: 'nearest', intersect: true }, scales: { xAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Time' } }], yAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Value' } }] } } }; window.onload = function() { let ctx = document.getElementById('canvas').getContext('2d'); window.myLine = new Chart(ctx, config); }; let colorNames = Object.keys(window.chartColors); config.data.datasets.forEach(function(dataset) { // send the data to the dataset to be added to the line dataset.data.pop(); }); // start the selectDevice function when the button is pressed selectDeviceBtn.addEventListener('click', selectDevice); ``` -------------------------------- ### List Available Devices Source: https://github.com/vernierst/godirect-examples/blob/main/python/example_without_gdx/readme.md Retrieves a list of all available GoDirectDevice objects from both BLE and USB backends that the library can detect. ```python # returns a list of GoDirectDevice objects devices = godirect.list_devices() ``` -------------------------------- ### Python Environment Variable Configuration (Windows) Source: https://github.com/vernierst/godirect-examples/blob/main/python/readme.md Instructions for modifying a Python installation on Windows to ensure Python is added to the system's environment variables. This is crucial for running Python commands from any directory. ```shell Add Python to environment variables ``` -------------------------------- ### Initialize UI Elements and Handle Bluetooth/USB Availability (JavaScript) Source: https://github.com/vernierst/godirect-examples/blob/main/javascript/gdx_getting_started_2.html This snippet initializes various HTML elements for device selection and updates their content based on the availability of Bluetooth and USB (HID) APIs. It also conditionally hides the device selection button if neither technology is supported. ```javascript const usbBtn = document.querySelector('#usb'); const usbLabel = document.querySelector('#usb_label'); const bleBtn = document.querySelector('#ble'); const bleLabel = document.querySelector('#ble_label'); const selectDeviceBtn = document.querySelector('#select_device'); const output = document.querySelector('#output'); const error = document.querySelector('#error'); if (navigator.bluetooth) { bleLabel.innerHTML = `Bluetooth`; } else { if (navigator.hid) usbBtn.checked = true; bleLabel.innerHTML = `Bluetooth Not Supported More information`; bleBtn.disabled = true; } if (navigator.hid) { usbLabel.innerHTML = `USB`; } else { if (navigator.bluetooth) bleBtn.checked = true; usbLabel.innerHTML = `USB Not Supported More information`; usbBtn.disabled = true; } if (!navigator.bluetooth && !navigator.hid) { selectDeviceBtn.style.visibility='hidden'; } ``` -------------------------------- ### Configure Connection Type (BLE/USB) Source: https://github.com/vernierst/godirect-examples/blob/main/python/example_without_gdx/readme.md Initializes the GoDirect library, allowing specification of whether to use Bluetooth Low Energy (BLE), USB, or both for device connections. The default is to enable both. ```python godirect = GoDirect(use_ble=True, use_usb=True) ``` -------------------------------- ### Workaround for Bleak Module Incompatibility (Python 3.8) Source: https://github.com/vernierst/godirect-examples/blob/main/python/readme.md Provides a workaround for a known incompatibility error ('option --single-version-externally-managed not recognized') when installing the 'bleak' module with Python v3.8. Refer to the linked GitHub issue for detailed solutions. ```text error: option --single-version-externally-managed not recognized ``` -------------------------------- ### List Available Sensors on Device Source: https://github.com/vernierst/godirect-examples/blob/main/python/example_without_gdx/readme.md Retrieves a list of all sensor objects available on an already opened GoDirect device. ```python # returns a list of Sensor objects sensors = mydevice.list_sensors() ``` -------------------------------- ### Enable Specific Sensors Source: https://github.com/vernierst/godirect-examples/blob/main/python/example_without_gdx/readme.md Selects which sensors on the device should be enabled for data collection by passing a list of their corresponding numbers. If not called, default sensors are enabled when `start()` is invoked. ```python # pass a list of sensor numbers to enable mydevice.enable_sensors([2,3,4]) ``` -------------------------------- ### Copy udev Rule File on Linux Source: https://github.com/vernierst/godirect-examples/blob/main/python/readme.md Copies the vstlibusb.rules file to the /etc/udev/rules.d/ directory on Linux systems using super-user privileges. This rule is essential for enabling communication with Go Direct devices over USB. ```shell sudo cp vstlibusb.rules /etc/udev/rules.d/. ``` -------------------------------- ### Start and Stop Data Collection Source: https://github.com/vernierst/godirect-examples/blob/main/python/readme.md Starts data collection at a specified interval (in milliseconds) or prompts the user if no interval is provided. Stops data collection without disconnecting the device, allowing for new collection rounds. ```python gdx.start(1000) # Sample every 1000 milliseconds gdx.start(100) # Sample every 100 milliseconds gdx.stop() ``` -------------------------------- ### Select and Connect to Go Direct Device (Bluetooth/USB) Source: https://github.com/vernierst/godirect-examples/blob/main/javascript/advanced_examples/gdx_using_two_devices.html Handles the selection of a Go Direct device, either via Bluetooth or USB. It opens the device and sets up event listeners for connection and data. ```javascript const selectCorrectDevice = async () => { if (!deviceObject1.device) { await selectDevice(deviceObject1); if (deviceObject1.device) { selectDeviceBtn.textContent = `Connect to 2nd Go Direct Device`; } } else { await selectDevice(deviceObject2); if (deviceObject2.device) { selectDeviceBtn.style.visibility='hidden'; connectionType.style.visibility='hidden'; } } }; async function selectDevice(deviceObject) { const bluetooth = document.querySelector('input[name="type"]:checked').value === "1"; try { let deviceSelected; if (bluetooth) { if (!navigator.bluetooth) { return Promise.reject(new Error('No Web Bluetooth support.')); } deviceSelected = await navigator.bluetooth.requestDevice({ filters: [{ namePrefix: 'GDX' }], optionalServices: ['d91714ef-28b9-4f91-ba16-f0d9a604f112'] }); } else { if (!navigator.hid) { return Promise.reject(new Error('No Web HID support.')); } const devices = await navigator.hid.requestDevice({ filters: [ { vendorId: 0x08f7, productId: 0x0010, }, ] }); deviceSelected = devices[0]; } if (!deviceSelected) throw new DOMException(`No device selected.`); deviceObject.device = await godirect.createDevice(deviceSelected, {open: false, startMeasurements: false}); deviceObject.device.on('device-closed', () => ((deviceObject) => { if (deviceObject.device) { output.textContent += `\n\nDisconnected from `+deviceObject.device.name; deviceObject.device = null; } })(deviceObject)); deviceObject.device.on('device-opened', () => ((deviceObject) => { output.textContent += `\nConnected to `+deviceObject.device.name+`\n`; const enabledSensor = deviceObject.device.sensors[0]; const line = addLine(deviceObject.device, enabledSensor); enabledSensor.on('value-changed', (sensor) => { console.log(`Sensor: ${sensor.name} value: ${sensor.value} units: ${sensor.unit}`); line.data.push(sensor.value); window.myLine.update(); output.textContent += `\n Sensor: ${sensor.name} value: ${sensor.value} units: ${sensor.unit}`; if (sensor.values.length >= 10){ deviceObject.device.close(); } }); startMeasurements(); })(deviceObject)); await deviceObject.device.open(false); } catch (err) { console.error(err); deviceObject.device = null; } }; ``` -------------------------------- ### Initialize Chart and UI Elements with JavaScript Source: https://github.com/vernierst/godirect-examples/blob/main/javascript/advanced_examples/gdx_using_two_devices.html Initializes chart colors and selects UI elements for interaction. It also checks for Web Bluetooth and Web HID support to enable or disable connection options. ```javascript window.chartColors = { red: 'rgb(255, 99, 132)', orange: 'rgb(255, 159, 64)' }; const usbBtn = document.querySelector('#usb'); const usbLabel = document.querySelector('#usb_label'); const bleBtn = document.querySelector('#ble'); const bleLabel = document.querySelector('#ble_label'); const connectionType = document.querySelector('#connection_type'); const selectDeviceBtn = document.querySelector('#select_device'); const output = document.querySelector('#output'); if (navigator.bluetooth) { bleLabel.innerHTML = `Bluetooth`; } else { if (navigator.hid) usbBtn.checked = true; bleLabel.innerHTML = `Bluetooth Not Supported More information`; bleBtn.disabled = true; } if (navigator.hid) { usbLabel.innerHTML = `USB`; } else { if (navigator.bluetooth) bleBtn.checked = true; usbLabel.innerHTML = `USB Not Supported More information`; usbBtn.disabled = true; } if (!navigator.bluetooth && !navigator.hid) { selectDeviceBtn.style.visibility='hidden'; } selectDeviceBtn.textContent = `Connect to 1st Go Direct Device`; const sensorUnit = ""; let deviceObject1 = {device: null}; let deviceObject2 = {device: null}; ``` -------------------------------- ### Connect and Read Sensor Data Source: https://github.com/vernierst/godirect-examples/blob/main/python/example_without_gdx/readme.md Connects to the first available USB or closest BLE device, reads 10 samples from enabled sensors, and prints the sensor descriptions and values. It handles device opening, sensor retrieval, data reading, and connection closing. ```python from godirect import GoDirect godirect = GoDirect() device = godirect.get_device() if device != None and device.open(auto_start=True): sensors = device.get_enabled_sensors() print("Connected to "+device.name) print("Reading 10 measurements") for i in range(0,10): if device.read(): for sensor in sensors: print(sensor.sensor_description+": "+str(sensor.values)) sensor.clear() device.stop() device.close() godirect.quit() ``` -------------------------------- ### Configure Line Chart Settings Source: https://github.com/vernierst/godirect-examples/blob/main/javascript/advanced_examples/gdx_using_two_devices.html Defines the initial configuration for the line chart, including its type and data structure. ```javascript const config = { type: 'line', data: { labels: [0,1,2,3, ``` -------------------------------- ### Upgrade godirect Module Source: https://github.com/vernierst/godirect-examples/blob/main/python/readme.md Upgrades the Vernier godirect Python module to the latest available version using pip3. This command should be run when a newer version of the module is released. ```shell pip3 install godirect --upgrade ``` -------------------------------- ### Monitor the COLLECT/STOP button state with gdx.vp_collect_is_pressed() Source: https://github.com/vernierst/godirect-examples/blob/main/python/vpython_examples/readme.md This function monitors the state of the VPython canvas COLLECT/STOP button. When COLLECT is clicked, it starts data collection by calling gdx.start(). When STOP is clicked, it calls gdx.stop(). ```python while gdx.vp_collect_is_pressed() == True ``` -------------------------------- ### Get slider period for sampling rate with gdx.vp_get_slider_period() Source: https://github.com/vernierst/godirect-examples/blob/main/python/vpython_examples/readme.md This function retrieves the value from the slider used to adjust the data collection sampling rate. It returns the value as the period (dt) in milliseconds. ```python gdx.vp_get_slider_period() ``` -------------------------------- ### Configure and Render Chart.js Line Chart Source: https://github.com/vernierst/godirect-examples/blob/main/javascript/advanced_examples/gdx_using_two_devices.html This JavaScript code configures a Chart.js line chart with specified data, options, and scales. It initializes the chart on window load using the provided canvas context. Dependencies include the Chart.js library and potentially window.chartColors for color management. ```javascript const config = { type: 'line', data: { labels: [4,5,6,7,8,9,10], datasets: [], }, options: { responsive: true, title: { display: true, text: 'Chart.js Line Chart' }, tooltips: { mode: 'index', intersect: false, }, hover: { mode: 'nearest', intersect: true }, scales: { xAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Time' } }], yAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Value' } }] } } }; window.onload = function() { const ctx = document.getElementById('canvas').getContext('2d'); window.myLine = new Chart(ctx, config); }; ``` -------------------------------- ### Export Sensor Data as CSV with Vernier Go Direct JavaScript Source: https://github.com/vernierst/godirect-examples/blob/main/javascript/gdx_getting_started_5.html This example demonstrates exporting sensor data collected from a Vernier Go Direct device into a CSV file using the godirect-js module. It covers selecting a device via Bluetooth or USB, enabling a sensor, collecting 10 measurements, and disconnecting. The collected data can then be downloaded as a CSV file. ```javascript const usbBtn = document.querySelector('#usb'); const usbLabel = document.querySelector('#usb_label'); const bleBtn = document.querySelector('#ble'); const bleLabel = document.querySelector('#ble_label'); const selectDeviceBtn = document.querySelector('#select_device'); const csvBtn = document.querySelector('#csv'); const output = document.querySelector('#output'); const error = document.querySelector('#error'); if (navigator.bluetooth) { bleLabel.innerHTML = `Bluetooth`; } else { if (navigator.hid) usbBtn.checked = true; bleLabel.innerHTML = `Bluetooth Not Supported More information`; bleBtn.disabled = true; } if (navigator.hid) { usbLabel.innerHTML = `USB`; } else { if (navigator.bluetooth) bleBtn.checked = true; usbLabel.innerHTML = `USB Not Supported More information`; usbBtn.disabled = true; } if (!navigator.bluetooth && !navigator.hid) { selectDeviceBtn.style.visibility='hidden'; } csvBtn.style.visibility='hidden'; // create array to store data to be saved in the csv file let data = []; let sensor = null; const selectDevice = async () => { const bluetooth = document.querySelector('input[name="type"]:checked').value === "1"; error.textContent = ""; try { const gdxDevice = await godirect.selectDevice(bluetooth); gdxDevice.start(1000); output.textContent += `\n Connected to `+gdxDevice.name; output.textContent += `\n Reading 10 measurements `; gdxDevice.on('device-closed', () => { output.textContent += `\n\n Disconnected from `+gdxDevice.name+`\n`; csvBtn.style.visibility='visible'; }); sensor = gdxDevice.getSensor(1); sensor.setEnabled(true); sensor.on('value-changed', (sensor) => { // only collect 10 samples and disconnect. if (sensor.values.length > 10){ gdxDevice.close(); } // log the sensor name, new value and units. console.log(`Sensor: ${sensor.name} value: ${sensor.value} units: ${sensor.unit}`); // add data points to the data array data.push(sensor.value); // output the change to the pre tag output.textContent += `\n Sensor: ${sensor.name} value: ${sensor.value} units: ${sensor.unit}`; }); } catch (err) { console.error(err); error.innerText += "\n "+err; if (err.toString().includes('cross-origin')) { error.innerHTML+= '\n
Are you running in an embedded iframe? Try running this example in its own window.
' } } }; // download csv function to be used when button is pressed function download_csv() { let csv = sensor.name; // add each row of the the sensor data array to the csv file data.forEach( row => { csv += " \n" + row; }); // create and download new csv file console.log(csv); let hiddenElement = document.createElement('a'); hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv); hiddenElement.target = '_blank'; hiddenElement.download = 'sensor.csv'; hiddenElement.click(); } selectDeviceBtn.addEventListener('click', selectDevice); ``` -------------------------------- ### Set Logging Verbosity for Debugging Source: https://github.com/vernierst/godirect-examples/blob/main/python/example_without_gdx/readme.md Configures the logging levels for the `godirect`, `bleak`, and `pygatt` modules to `DEBUG` or `INFO` to capture detailed communication information during operation. ```python import logging logging.basicConfig() logging.getLogger('godirect').setLevel(logging.DEBUG) logging.getLogger('bleak').setLevel(logging.DEBUG) logging.getLogger('pygatt').setLevel(logging.DEBUG) ``` -------------------------------- ### Get Automatically Detected Device Source: https://github.com/vernierst/godirect-examples/blob/main/python/example_without_gdx/readme.md Attempts to automatically find and return the nearest or most suitable GoDirect device. An optional threshold can be provided to filter BLE devices based on signal strength (dB). ```python # returns a GoDirectDevice on success or None on failure mydevice = godirect.get_device() # to adjust the BLE threshold pass in a minimum dB value mydevice = godirect.get_device(threshold=-200) ``` -------------------------------- ### Vernier Go Direct JavaScript Example for Desmos Integration Source: https://github.com/vernierst/godirect-examples/blob/main/javascript/advanced_examples/gdx_start_stop_desmos.html This JavaScript code sets up a Desmos graphing calculator and connects to a Vernier Go Direct sensor via Bluetooth. It handles device selection, real-time data collection, and updates a Desmos table with sensor readings. Dependencies include the Desmos API and the Vernier Go Direct Module. ```javascript // setup the calculator let elt = document.getElementById('calculator'); let calc = Desmos.GraphingCalculator(elt); // store the x & y values to be graphed let xvalues = ['']; let yvalues = ['']; let collecting = false; let delta = 1.0; function updateTable () { calc.setExpressions([ { id: 'table1', type: 'table', columns: [ {latex: 'x_1', values: xvalues}, {latex: 'y_1', values: yvalues} ] } ]); } updateTable(); const selectDeviceBtn = document.querySelector('#select_device'); const collectBtn = document.querySelector('#start_stop_collection'); const output = document.querySelector('#output'); let count = 0; // create global object gdxDevice to be used in other let gdxDevice; const selectDevice = async () => { try { if (gdxDevice){ gdxDevice.close(); } else { // connect to the gdx device const bleDevice = await navigator.bluetooth.requestDevice({ filters: [{ namePrefix: 'GDX' }], optionalServices: ['d91714ef-28b9-4f91-ba16-f0d9a604f112'] }); // Create the device but don't open or start measurements. gdxDevice = await godirect.createDevice(bleDevice, {open: false, startMeasurements: false}); // print that the device is disconnected gdxDevice.on('device-closed', () => { output.textContent += `\n\n Disconnected from `+gdxDevice.name+`\n`; gdxDevice = undefined; selectDeviceBtn.textContent = `Select Go Direct Device`; }); gdxDevice.on('device-opened', () => { output.textContent += `\n Connected to `+gdxDevice.name; output.textContent += `\n Press start to start collection \n`; output.textContent += `\n If you can't see your sensor values on the graph right away, \n Zoom out of the graph in the Desmos Window \n`; selectDeviceBtn.textContent = `Disconnect from ${gdxDevice.name}`; // Only enable one sensor since that is all this example can handle. const sensor = gdxDevice.sensors[0]; sensor.setEnabled(true); sensor.on('value-changed', (sensor) => { // log the sensor name, new value and units. console.log(`Sensor: ${sensor.name} value: ${sensor.value} units: ${sensor.unit}`); // output the change to the pre tag output.textContent += `\n Sensor: ${sensor.name} value: ${sensor.value} units: ${sensor.unit}`; let y = sensor.value; let x = count; // add the x & y values to their respective arrays, round the number 4 places xvalues.push(x.toPrecision(4)); yvalues.push(y.toPrecision(4)); // add a sensor value every delta on the x, change according to sampleRate count += delta; // update the table with the new sensor values updateTable(); }); }); gdxDevice.open(false); } } catch (err) { console.error(err); } }; // start collection function const startStopCollection = async () => { if (!collecting) { collecting = true; collectBtn.textContent = `Stop Collection`; gdxDevice.start(delta*1000); xvalues = ['']; yvalues = ['']; count = 0.0; // update the table with the new sensor values updateTable(); } else { collecting = false; collectBtn.textContent = `Start Collection`; gdxDevice.stop(); } }; ``` -------------------------------- ### Disconnect GoDirect Device Source: https://github.com/vernierst/godirect-examples/blob/main/python/readme.md Disconnects the GoDirect device from the USB or Bluetooth connection and quits the GoDirect session. After calling this function, no other gdx functions can be called. ```python gdx.close() ``` -------------------------------- ### Connect to Go Direct Device and Collect Data Source: https://github.com/vernierst/godirect-examples/blob/main/javascript/advanced_examples/gdx_making_a_chart.html Handles the connection to a selected Go Direct device (Bluetooth or USB). Once connected, it enables the default sensor, listens for value changes, and collects up to 10 measurements before disconnecting. Sensor readings are logged and added to a chart. ```javascript // select device function, awaits connection to the device const selectDevice = async () => { const bluetooth = document.querySelector('input[name="type"]:checked').value === "1"; try { const gdxDevice = await godirect.selectDevice(bluetooth); output.textContent += `\n Connected to `+gdxDevice.name; output.textContent += `\n Reading 10 measurements \n`; gdxDevice.on('device-closed', () => { output.textContent += `\n\n Disconnected from `+gdxDevice.name+`\n`; }); // enable the default sensor to use for measurements gdxDevice.enableDefaultSensors(); const enabledSensors = gdxDevice.sensors.filter(s => s.enabled); enabledSensors.forEach(sensor => { sensor.on('value-changed', (sensor) => { // Only collect 10 samples and disconnect. if (sensor.values.length > 10){ gdxDevice.close(); } // log the sensor name, new value and units. console.log(`Sensor: ${sensor.name} value: ${sensor.value} units: ${sensor.unit}`); // output the change to the pre tag // add the sensor value to the sensorReading array sensorReadings.push(sensor.value); let unit = sensor.unit; // use the addData function to add the sensor data to the chart addData(config, sensor.unit); // print the sensor name, value and units output.textContent += `\n Sensor: ${sensor.name} value: ${sensor.value} units: ${sensor.unit}`; }); }); } catch (err) { console.error(err); } }; ``` -------------------------------- ### Select Go Direct Device, Collect Data, and Disconnect (JavaScript) Source: https://github.com/vernierst/godirect-examples/blob/main/javascript/gdx_getting_started_2.html This asynchronous function handles the process of selecting a Go Direct device (via Bluetooth or USB), enabling default sensors, collecting up to 10 measurements, logging sensor data, and disconnecting from the device. It includes error handling and specific logging for disconnected devices and data changes. ```javascript const selectDevice = async () => { const bluetooth = document.querySelector('input[name="type"]:checked').value === "1"; error.textContent = ""; try { const gdxDevice = await godirect.selectDevice(bluetooth); output.textContent += `\n Connected to `+gdxDevice.name; output.textContent += `\n Reading 10 measurements \n`; gdxDevice.on('device-closed', () => { output.textContent += `\n\n Disconnected from `+gdxDevice.name+`\n`; }); gdxDevice.enableDefaultSensors(); const enabledSensors = gdxDevice.sensors.filter(s => s.enabled); enabledSensors.forEach(sensor => { sensor.on('value-changed', (sensor) => { // Only collect 10 samples and disconnect. if (sensor.values.length > 10){ gdxDevice.close(); } // log the sensor name, new value and units. console.log(`Sensor: ${sensor.name} value: ${sensor.value} units: ${sensor.unit}`); // output the change to the pre tag output.textContent += `\n Sensor: ${sensor.name} value: ${sensor.value} units: ${sensor.unit}`; }); }); } catch (err) { console.error(err); error.innerText += "\n "+err; if (err.toString().includes('cross-origin')) { error.innerHTML+= '\nAre you running in an embedded iframe? Try running this example in its own window.
' } } }; selectDeviceBtn.addEventListener('click', selectDevice); ``` -------------------------------- ### Select Sensors for Data Collection Source: https://github.com/vernierst/godirect-examples/blob/main/python/readme.md Selects which sensors to enable for data collection on connected GoDirect devices. Can select sensors for a single device using a 1D list or for multiple devices using a 2D list. If no sensors are specified, it lists available sensors and prompts the user. ```python gdx.select_sensors([1]) gdx.select_sensors([1, 2]) gdx.select_sensors([[1, 2, 3], [1]]) ``` -------------------------------- ### Control VPython Box Size with Go Direct Sensor Data Source: https://github.com/vernierst/godirect-examples/blob/main/python/vpython_examples/readme.md This Python code uses the 'gdx' module to read data from a Vernier Go Direct sensor and dynamically control the size of a VPython box object. It initializes the connection, selects sensors, sets up the VPython environment, and continuously updates the box's length based on incoming sensor measurements. ```python from gdx import gdx from vpython import * gdx = gdx.gdx() gdx.open(connection='usb') gdx.select_sensors() gdx.vp_vernier_canvas() b = box(size=0.1*vec(1,1,1), color=color.red) gdx.start(period=250) while gdx.vp_close_is_pressed() == False: while gdx.vp_collect_is_pressed() == True: measurements = gdx.read() sensor0_data = measurements[0] b.length = 0.1 * sensor0_data ``` -------------------------------- ### Connect to GoDirect Devices via USB or Bluetooth Source: https://github.com/vernierst/godirect-examples/blob/main/python/readme.md Connects to GoDirect devices using either USB or Bluetooth. Can automatically connect to specified devices by name or serial number, or use proximity pairing for the strongest BLE signal. If no device is specified, it lists available devices and prompts the user. ```python gdx.open(connection='usb') gdx.open(connection='ble') gdx.open(connection='usb', device_to_open="GDX-FOR 071000U9, GDX-HD 151000C1") gdx.open(connection='ble', device_to_open="GDX-FOR 071000U9, GDX-HD 151000C1") gdx.open(connection='ble', device_to_open="proximity_pairing") ``` -------------------------------- ### Monitor the CLOSE button state with gdx.vp_close_is_pressed() Source: https://github.com/vernierst/godirect-examples/blob/main/python/vpython_examples/readme.md This function monitors the state of the VPython canvas CLOSE button. When the button is pressed (returns True), it initiates the stopping of data collection and disconnection of the Go Direct device. ```python while gdx.vp_close_is_pressed() == False ``` -------------------------------- ### Connect Go Direct Sensor and Stream Data to Desmos Graph (JavaScript) Source: https://github.com/vernierst/godirect-examples/blob/main/javascript/advanced_examples/gdx_using_desmos.html This JavaScript code snippet connects to a Vernier Go Direct sensor via Bluetooth, reads sensor data, and streams it to a Desmos graphing calculator. It updates the graph in real-time with new sensor values and adds a linear regression line. The example limits data collection to 10 measurements per session and disconnects automatically. ```javascript let elt = document.getElementById('calculator'); let calc = Desmos.GraphingCalculator(elt); // x &y arrays to store values to graph let xvalues = []; let yvalues = []; // update table function to add values to the graph function updateTable () { calc.setExpressions([ { id: 'table1', type: 'table', columns: [ {latex: 'x_1', values: xvalues}, {latex: 'y_1', values: yvalues} ] }, // linear regression equation to find line of best fit, can be changed depending on data { id: 'regression', latex: 'y_1~mx_1+b'} ]); } updateTable(); const selectDeviceBtn = document.querySelector('#select_device'); const output = document.querySelector('#output'); let count = 0; const selectDevice = async () => { try { const gdxDevice = await godirect.selectDevice(); output.textContent += `\n Connected to `+gdxDevice.name; output.textContent += `\n Reading 10 measurements \n`; output.textContent += `\n If you can't see your sensor values on the graph right away, \n Zoom out of the graph in the Desmos Window \n`; gdxDevice.on('device-closed', () => { output.textContent += `\n\n Disconnected from `+gdxDevice.name+`\n`; }); gdxDevice.enableDefaultSensors(); const enabledSensors = gdxDevice.sensors.filter(s => s.enabled); enabledSensors.forEach(sensor => { sensor.on('value-changed', (sensor) => { // Only collect 10 samples and disconnect. if (sensor.values.length > 10) { gdxDevice.close(); } // log the sensor name, new value and units. console.log(`Sensor: ${sensor.name} value: ${sensor.value} units: ${sensor.unit}`); // output the change to the pre tag output.textContent += `\n Sensor: ${sensor.name} value: ${sensor.value} units: ${sensor.unit}`; let y = sensor.value; let x = count++; // add the x & y values to the x & y arrays xvalues.push(x.toPrecision(4)); yvalues.push(y.toPrecision(4)); // update the graph with the current values updateTable(); }); }); } catch (err) { console.error(err); } }; // start the selectDevice function after the button is clicked selectDeviceBtn.addEventListener('click', selectDevice); ``` -------------------------------- ### Select Vernier Go Direct Device with JavaScript Source: https://github.com/vernierst/godirect-examples/blob/main/javascript/gdx_getting_started_4.html This JavaScript snippet allows users to select a Vernier Go Direct device via Bluetooth or USB. It checks for browser support for Web Bluetooth and WebHID APIs, updates UI elements to reflect support, and initiates the device selection process. It handles potential errors during connection, including cross-origin issues. ```javascript const usbBtn = document.querySelector('#usb'); const usbLabel = document.querySelector('#usb_label'); const bleBtn = document.querySelector('#ble'); const bleLabel = document.querySelector('#ble_label'); const selectDeviceBtn = document.querySelector('#select_device'); const output = document.querySelector('#output'); const error = document.querySelector('#error'); if (navigator.bluetooth) { bleLabel.innerHTML = `Bluetooth`; } else { if (navigator.hid) usbBtn.checked = true; bleLabel.innerHTML = `Bluetooth Not Supported More information`; bleBtn.disabled = true; } if (navigator.hid) { usbLabel.innerHTML = `USB`; } else { if (navigator.bluetooth) bleBtn.checked = true; usbLabel.innerHTML = `USB Not Supported More information`; usbBtn.disabled = true; } if (!navigator.bluetooth && !navigator.hid) { selectDeviceBtn.style.visibility='hidden'; } const selectDevice = async () => { const bluetooth = document.querySelector('input[name="type"]:checked').value === "1"; error.textContent = ""; try { const gdxDevice = await godirect.selectDevice(bluetooth); output.textContent += `\n Connected to `+gdxDevice.name; output.textContent += `\n Reading 10 measurements `; gdxDevice.on('device-closed', () => { output.textContent += `\n\n Disconnected from `+gdxDevice.name+`\n`; }); // set the sample rate to 1 second gdxDevice.start(1000); // enable sensor channel 1 const sensor = gdxDevice.getSensor(1); sensor.setEnabled(true); // using the enabled sensor, collect 10 values sensor.on('value-changed', (sensor) => { // Only collect 10 samples and disconnect. if (sensor.values.length > 10){ gdxDevice.close(); } // log the sensor name, new value and units. console.log(`Sensor: ${sensor.name} value: ${sensor.value} units: ${sensor.unit}`); // output the change to the pre tag output.textContent += `\n Sensor: ${sensor.name} value: ${sensor.value} units: ${sensor.unit}`; }); } catch (err) { console.error(err); error.innerText += "\n "+err; if (err.toString().includes('cross-origin')) { error.innerHTML+= '\nAre you running in an embedded iframe? Try running this example in its own window.
' } } }; selectDeviceBtn.addEventListener('click', selectDevice); ``` -------------------------------- ### Read Sensor Measurements Source: https://github.com/vernierst/godirect-examples/blob/main/python/readme.md Reads single-point measurements from the selected sensors at the desired sampling period. Returns readings as a 1D list. This function should be used within a loop that iterates quickly enough to keep up with the sampling period. ```python measurements = gdx.read() ```