SERIAL_SINGLE_MEASUREMENT
Python Code
from typing import Optional
from numpy import array
from flojoy import Vector, SerialDevice, flojoy, DataContainer
@flojoy(inject_connection=True)
def SERIAL_SINGLE_MEASUREMENT(
connection: SerialDevice,
default: Optional[DataContainer] = None,
) -> Vector:
"""Takes a single reading of data from a serial device (e.g. Arduino).
If the data is comma seperated (e.g. 25,26,27) with multiple measurements,
a Vector is returned. You should use the VECTOR_INDEXING node to choose
the specific measurement you want.
Parameters
----------
device : SerialDevice
Defines the communication port on which the serial device is connected.
Returns
-------
Vector
The output from the serial device.
"""
ser = connection.get_handle()
s = ""
while s == "":
s = ser.readline().decode()
reading = s[:-2].split(",")
reading = array(reading) # Create an array
reading = reading.astype("float64") # Convert the array to float
ser.flush()
return Vector(v=reading)
Videos
Arduino Temperature Sensor
Example
In this example, we use the SERIAL_SINGLE_MEASUREMENT
node to extract some measurements
received from an Arduino microcontroller and visualize the output.
First, you need to connect the Arduino to your computer. Then, you’ll need to upload an Arduino script to your board to define its behavior (with the Arduino IDE software). When your Arduino sends data to the serial monitor of the Arduino IDE, you can start using the SERIAL_SINGLE_MEASUREMENT
node. After placing the node on Flojoy, you must specify the communication port to which the Arduino is connected. This port is found in the Arduino IDE software under Tools/Port.
The SERIAL_SINGLE_MEASUREMENT
node receives data through serial communication with the Arduino, and stores the measured values in a table called reading
. The Arduino then prints new values on the serial console for each loop. The SERIAL_SINGLE_MEASUREMENT
node extracts a measurement (which can contain single or multiple values, as seen in the output).
The TABLE
node displays all values stored in the single measurement.
Remarks about the Arduino code:
This example works with the arduino_example.ino
Arduino code (see Appendix).
The last line that the Arduino should return, is the data with a new line at the end (i.e. println()
).
For example:
The SERIAL_SINGLE_MEASUREMENT
node receives data from the Arduino serial console as a string and splits it using ”,” as a separator. It then returns the values measured in a list called reading
.
Update the Single Measurement with a Loop:
To update the values received from the Arduino, use the LOOP
node to create a loop around the SERIAL_SINGLE_MEASUREMENT
and TABLE
nodes.
The loop allows the user to update measurements, but only the last measurement will be saved and displayed.
To record all the measurements for a given period, use the SERIAL_TIMESERIES
node.