Arduino Driver guide
(Redirected from Arduino Device Class guide)
Using existing Drivers
Already existing Arduino Drivers, e.g. implemented as Logger or Switch, can be used after configuring the Arduino.
- Install the ArduinoIDE
- For every Driver, there exists one ".ino" file which can be found in the corresponding Driver folder. In the Version manager, right-click the version of the driver and select "Open .ino file in Arduino IDE".
- Configure your ArduinoIDE by setting the Arduino type (e.g. nano, uno, or mega) and the COM port
- Upload the ".ino" file to the Arduino
- Now your Arduino knows how to handle the commands send by the SweepMe! Driver
Creating an own Driver for Arduino
Arduino can easily be combined with SweepMe! However, there are some guidelines which make the implementation much easier:
- Try to sends a text during the setup() routine of the Arduino, so that SweepMe! knows that sending commands can be done from now on.
- The Arduino can send text via its function println() which uses a LineFeed character as terminator ("\n"). Thus, the Arduino should also expect to receive messages ending with a LineFeed ("\n") so that the write and read terminators are identical. The standard terminator of SweepMe! is a LineFeed ("\n") so that you do not have to set it.
- If the Arduino sends a message back after receiving a command, do not send more than one line. Otherwise, one has to read out the COM port multiple times in the SweepMe! Driver
- Try to have a constant length or format of the return message, so that reading out the string is less errorneous
- Try to make every parameter adjustable by a single command, e.g. "Pixel = 03", "Voltage = 0.05", or "Frequency = 400". That way, multiple items of the sequencer can communicate with the Arduino and multiple parameters can be swept.
- Use the standard baudrate of 9600 so that other Arduino Drivers can easily be copied and modified.
- After finishing your Driver, put your ino file as uploaded to the Arduino into the folder of the Driver. Give the ino file exactly the same name as used for the folder to allow for easy manipulation using the Arduino IDE.
Example Driver
Arduinos are typically implemented as Switch if you rather set some values or as Logger if you rather read some values. The following code shows a Switch Driver which can set and read a value.
from __future__ import annotations
from typing import Any
from pysweepme.EmptyDeviceClass import EmptyDevice
class Device(EmptyDevice):
"""Driver for an Arduino that sets a voltage and returns a reading."""
def __init__(self) -> None:
super().__init__()
self.shortname = "Arduino"
self.variables = ["Voltage"]
self.units = ["V"]
self.plottype = [True] # set to False if the variable is a string and cannot be plotted
self.savetype = [True] # set to False if there is no need to save the variable to the data file
self.port_manager = True # using the port manager works seamlessly
self.port_types = ["COM"] # Arduinos are always listed as COM ports
self.port_properties = {
"baudrate": 9600,
"timeout": 3, # in s, the Arduino needs some time after the port was opened
}
self.port_string: str = ""
self.reading: float = float("nan")
def update_gui_parameters(self, parameters: dict[str, Any]) -> dict[str, Any]:
"""Return the GUI fields of the driver."""
return {"SweepMode": ["Voltage in V"]}
def apply_gui_parameters(self, parameters: dict[str, Any]) -> None:
"""Store the selections of the user."""
self.port_string = parameters.get("Port", "")
def initialize(self) -> None:
"""Wait for the Arduino to finish its setup() routine."""
identifier = "Arduino_" + self.port_string
# we only wait once, e.g. if the driver is used in multiple modules with the same Arduino
if identifier not in self.device_communication:
self.port.read() # reads "Arduino initialized" that is sent by the .ino file below
self.device_communication[identifier] = True
def apply(self) -> None:
"""Send the new set value and wait for the confirmation of the Arduino."""
self.port.query(f"Voltage={float(self.value)}")
def measure(self) -> None:
"""Request a reading and read the answer in the same step."""
self.reading = float(self.port.query("Read?"))
def call(self) -> list[float]:
"""Return the measured value to SweepMe!."""
return [self.reading]
Example Arduino .ino file
The following code shows you an example how to implement the above guidelines into an Arduino ino file. It has to be adapted to your needs.
// define some variables
unsigned int variable1;
String command; // the variable command
// define functions which you need later
void myFunction()
{
variable1++;
}
//
void setup()
{
// configure your pins here
Serial.begin(9600); // set Arduino to baudrate 9600
// Serial.setTimeout(1000); // change timeout if necessary, default is 1000 ms
Serial.println("Arduino initialized"); // send some text to let SweepMe! know that the Arduino has finished the setup() function
}
void loop ()
{
// check whether some command has been received at the COM port
if (Serial.available()) {
command = Serial.readStringUntil('\n'); // make sure you have '\n', "\n" does not work
if (command == "Read?") {
// sending back the answer as a single line, here a number that the driver converts with float()
Serial.println(some_function_to_read_a_value()); // you can send several parts using print, but finish with exactly one println per command
}
// if the command starts with some special text you can
else if (command == "Voltage?") {
// use some functions to get the parameter 'voltage' and return it
voltage = some_function_to_retrieve_the_voltage_value();
Serial.println(voltage); // here we send the value, the command 'println' adds a Line Feed character ('\n') to each message automatically
}
// if the command starts with some special text you can
else if (command.startsWith("Voltage=")) {
// split the value from the command here and change the parameter accordingly
float set_voltage = command.substring(command.indexOf('=')+1).toFloat();
my_voltage_function(set_voltage); // here you need to run any function that changes the voltage
Serial.println("Voltage=..."); // reply to let SweepMe! know that the parameter is changed.
}
else if (command == "Frequency?") {
// split the value from the command here and change the parameter accordingly
frequency = some_function_to_retrieve_the_frequency_value();
Serial.println(frequency); // reply to let SweepMe! know that the parameter is changed
}
else if (command.startsWith("Frequency=")) {
// split the value from the command here and change the parameter accordingly
int set_frequency = command.substring(command.indexOf('=')+1).toInt();
my_frequency_function(set_frequency); // here you need to run any function that changes the voltage
Serial.println("Frequency=..."); // reply to let SweepMe! know that the parameter is changed
}
}
}