Wolfram Language & System 10.3 (2015)|Legacy Documentation

This is documentation for an earlier version of the Wolfram Language.View current documentation (Version 11.2)
WOLFRAM LANGUAGE DEVICE CONNECTION

Arduino
This feature is not supported on the Wolfram Cloud.

provides low-level, general-purpose input and output through digital and analog pins on the open source Arduino Uno microcontroller board connected over serial to Mathematica.
It can be used for a large variety of tasks, focusing on interacting with the actual world with motors, sensors, etc.
It can be used for general purpose input and output (GPIO), as well as execution of C/C++ code on the device.
Additionally, the board has 13 digital inputs and outputs, with six Pulse Width Modulationcapable pins and six pins capable of reading analog voltages as well as digital input and output.
On an Arduino Uno, the following pins are available for reading and writing: 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, (14), (15), (16), (17), (18), (19).
The Arduino Uno runs a custom program called a sketch that communicates with Mathematica. This sketch must be uploaded to the Arduino with DeviceConfigure prior to using DeviceRead, DeviceWrite, or DeviceExecute.
Note: By default, allows any pin to be used interchangeably in read and write mode. DeviceConfigure can be used to configure specific pins as read or write.
Arduino Uno

Device DiscoveryDevice Discovery

  • Discovering an Arduino is basically the same as discovering a serial port, as that is the method of communication with the Arduino. Thus, automatic discovery of an Arduino is challenging and currently unimplemented.
  • On Unix-based systems, names of serial connections can sometimes be identified by comparing the list of /dev/tty* devices before and after a particular connection is plugged in.
  • On Windows-based systems, names of serial connections can sometimes be identified by opening up the Device Manager and examining the list of "Virtual COM Ports" or just "Ports (COM & LPT)", depending on your version of Windows.

Opening the DeviceOpening the Device

    DeviceOpen["Arduino",name]
    opens the Arduino on the serial port with the specified name. Typical names on Unix-based systems are or " and under Windows are , , etc.

  • If the correct version of the Arduino software is not installed on the host computer, you will be prompted to have it automatically installed. If you opt to have it automatically installed, Version 1.6.3 will be installed. Currently, only Versions 1.6.0, 1.6.1, 1.6.3, and 1.6.4 are supported. Additionally, on Windows you may be prompted to install drivers if they are not already installed on your machine.
  • Note: After opening a connection to the Arduino, if the custom Mathematica sketch has not yet been uploaded to this particular Arduino, it must first be uploaded with DeviceConfigure before usage.

Configuring the DeviceConfiguring the Device

  • Note: Any modifications to the sketch require redeployment to the Arduino. This may take anywhere from 5 to 30 seconds and is automatically done when needed.
  • DeviceConfigure[dev,"PinConfigure"<|n1dir1,n2dir2,|>]
    sets the direction of pin to be .

    DeviceConfigure[dev,<|n1dir1,n2dir2,|>]
    sets the direction of pin to be .

  • DeviceConfigure also works with lists of rules.
  • does not modify the sketch the Arduino runs, so it does not require redeployment to the Arduino.
  • Configuring a pin as one direction will disable using that pin in another direction without reconfiguration. It is recommended to set the direction of each pin before usage with sensitive hardware.
  • Valid directions are:
  • "Input"sets the pin to be a digital input, or an analog input if the pin supports it
    "Output"sets the pin to be a digital output pin, capable of outputting 5 volts (1 or high), 0 volts (0 or low), or an analog value (PWM) if the pin supports it
    "AnalogOutput"sets the pin to an analog (PWM) output, which accepts any real number between 0 and 1, or any rational number of the form , where is an Integer between 0 and 255
    "AnalogInput"sets the pin to be an analog input, reading an analog voltage of 0 to 5 volts automatically
  • Analog output (PWM) is only supported on pins 3, 5, 6, 9, 10, and 11.
  • Analog input is only supported on pins (14), (15), (16), (17), (18), and (19).
  • DeviceConfigure[dev,"Upload"opts]
    configures the sketch for the DeviceObject dev as specified by opts and uploads it to the Arduino.

  • DeviceConfigure configures the Arduino's sketch that it runs. It can add functionality like new functions, C++ classes, and variables, as well as control the direction of pins.
  • DeviceConfigure[dev,"Upload""Functions"<|funcnameArduinoCode[<|"ArgumentTypes"{type1,type2,},"ReturnType"return,"Code"codestr|>]|>]
    adds the function with argument types and return type return with C/C++ definition codestr to the sketch, so that the function can be called with DeviceExecute["Arduino",funcname].

  • will add the given C/C++ code to the sketch and allow for execution of this set of code with DeviceExecute. is to be specified as an association, with funcname going to . The argument to is an association, with going to a list of the argument types, going to the return type, and going to the actual String of C/C++ code.
  • The following is a summary of the conversion of types between the Wolfram Language and C. Note that a double and a float are the same on the Arduino, just as a short is the same as an int. More information on the Arduino architecture can be found online at http://arduino.cc/en/Reference/HomePage:
  • byte, char, short, int, longInteger
    float, doubleReal
    float [], double []{Real}
    byte [], short [], int [], long []{Integer}
    char []String
  • Integer lists on the Arduino must be specified as long pointers () when they appear as arguments to the function, as integers in Mathematica are implemented as long data types on the Arduino. Additionally, a single integer list as the argument must be specified as , and a single real list as . Real lists on the Arduino may be specified as either double pointers () or as float pointers ().
  • data types on the Arduino are unsupported.
  • Supported return types for functions on the Arduino are Integer, Real, and String. Note that for String returning functions, the string that the function returns must be a null-terminated C string, or else undefined behavior may occur.
  • Omitting the of a function whose definition has a non-void return type will simply cause the returned value to be ignored and not returned to Mathematica over the serial port.
  • DeviceConfigure[dev,"Upload""Functions"<|funcnameCFunction[type,name,args,body]|>]
    adds the function with name funcname to the Arduino's sketch, as defined with SymbolicC CFunction.

  • To use a SymbolicC function, you must first load the package:
  • Needs["SymbolicC`"]
  • DeviceConfigure[dev,"Upload""Libraries"lib]
    includes the library lib in the Arduino's sketch for usage in user-defined functions.

    DeviceConfigure[dev,"Upload""Libraries"{lib1,lib2,}]
    includes the libraries in the Arduino's sketch for usage in user-defined functions.

  • Libraries are intended for usage within any custom code in codestr specified with the or Initialization options.
  • The following values are valid for lib:
  • "dir"directory containing the relevant library
    "file"archive file containing the relevant library
    "LibraryName"literal name of a built-in library
    TI{lib1,lib2,}list of any combination of the above
  • Due to size limitations, some libraries may not be able to be uploaded to the Arduino.
  • Some libraries, such as the , , and libraries, have dependencies on other libraries. These are not resolved automatically and must be manually specified by the user. For the , , and libraries, the library is necessary and so must also be included in the list of libraries.
  • The following is a list of support built-in libraries from the Arduino software:
  • "Firmata"library for interfacing computer programs using a standard serial protocol.
    "GSM"library for interfacing with the Arduino GSM shield
    "LiquidCrystal"library for interfacing with LCD displays
    "SD"library for interfacing with SD cards
    "Servo"library for controlling servo motors
    "Stepper"library for controlling stepper motors
    "Temboo"library for interfacing with the Temboo platform
    "TFT"library for interfacing with TFT displays
    "Ethernet"library for interfacing with the Arduino Ethernet shield
    "Wire"library for interfacing with I2C devices
    "SPI"library that enables communication using the SPI standard
    "EEPROM"library that enables reading and writing to the Arduino's EEPROM
    "SoftwareSerial"library that enables serial communication on any digital pins
  • DeviceConfigure[dev,"Upload"Initializationcodestr]
    configures the Arduino's sketch to have the C/C++ code in codestr prepended to the file.

  • Typical usage of Initialization code would be declaration of objects, variables, or classes that are to be used across different functions. Note that some initialization code can in fact just be placed inside the codestr option. Large amounts of Initialization code could be placed inside a library instead.
  • Other options include:
  • "FlashVerify"True
    "Debug"False
    "CleanIntermediate"True
  • sets whether or not the program is verified after upload to the Arduino. Setting this to False will decrease the time necessary to upload but introduces the possibility that the program could fail to be uploaded properly, and there is no way to know this except that the Arduino does not function correctly. It is recommended that this be left as the default unless you absolutely need the speed. Possible values are True or False.
  • sets whether or not debugging information is to be output to the screen. Information includes the location of the temporary folder used for compilation of the sketch and various libraries, as well as the raw commands used to configure, compile, and upload the sketch to the Arduino. Possible values are True or False.
  • sets whether or not to delete intermediate files in the $TemporaryDirectory directory used to configure the Arduino's custom sketch. Possible values are True or False.

Device PropertiesDevice Properties

  • The only properties supported currently are , which returns a Dataset of the most recent value of pins as well as the state of various pins, , which returns the name of the serial port the Arduino is attached to, and , which is used for the location of the Arduino software on the host machine.
  • is read only, while can be used to specify another location to use for compiling and uploading functions.
  • Here is an example:
  • and are read only, while can be written to and used to specify the location of the Arduino software to use for compiling and uploading functions.
  • The property specified is verified, so the one specified by the user must be a valid location of the Arduino software. This is determined from the presence of the Arduino libraries and certain AVR utilities necessary for the driver. Versions 1.6.0, 1.6.1, 1.6.3, and 1.6.4 of the software is the currently supported version. The Arduino software can be downloaded from http://arduino.cc/en/main/software.

Reading DataReading Data

    DeviceRead[dev,n]
    reads the value of pin n.

    DeviceRead[dev,{{n1,n2,}}]
    reads the value of each pin , returning an association of to the pin's value.

    DeviceRead[dev,n,{"ReturnFunction"(func)}]
    reads the value of pin n, applying func to the value before returning it.

    DeviceRead[dev,n,{"ReadMode"mode}]
    reads the mode value of pin n.

  • Possible values for are and .
  • Reading from an analog pin defaults to performing an analog read of that pin. Reading a digital value can be obtained by using .
  • Only pins (14), (15), (16), (17), (18), and (19) support analog reading. Any pin supports digital reading.
  • DeviceReadTimeSeries is also supported.
  • "ReturnFunction" f will return . For analog input pins, val will be a number between 0 and 1023 that corresponds to the analog voltage on that pin. 1023 corresponds to 5 volts, and 0 corresponds to 0 volts. Applying voltages higher than 5 volts to any pin on the Arduino may damage the device. For all other pins, val will be 1 or 0, depending on if the voltage on that pin is above or below 3 volts, respectively.
  • Note: By default, allows any pin to be used interchangeably in read and write mode. DeviceConfigure can be used to configure specific pins as read or write.

Writing DataWriting Data

    DeviceWrite[dev,nval]
    writes the value val to pin n.

    DeviceWrite[dev,<|n1val1,n2val2,|>]
    writes each value to pin .

  • The value val must be either 0 or 1, unless pin n supports Pulse Width Modulation (PWM).
  • DeviceWrite also supports lists of rules.
  • PWM is supported on pins 3, 5, 6, 9, 10, and 11. On these pins, val can be any real number between 0 and 1, or any rational number of the form , where is an Integer between 0 and 255. This corresponds to the duty cycle of the PWM timer on that pin.
  • PWM pins also support writing a Quantity of volts between 0 and 5 that is scaled to a duty cycle.
  • Note: By default, allows any pin to be used interchangeably in read and write mode. DeviceConfigure can be used to configure specific pins as read or write.

Executing CommandsExecuting Commands

    DeviceExecute[dev,funcname]
    executes the function funcname on the Arduino.

    DeviceExecute[dev,funcname,args]
    executes the function funcname with arguments args on the Arduino.

    DeviceExecute[dev,funcname,{args,"Scheduling"timespec}]
    executes the function funcname with arguments args on a schedule specified by timespec.

  • will schedule the function to be run on the Arduino. This means that the function will continue to be run after Mathematica is closed, as long as the Arduino has uninterrupted power. If the Arduino is reset or loses power, the function will need to be rescheduled.
  • The Arduino can schedule things to millisecond precision, so the time specified by timespec is rounded to the nearest thousandths place.
  • The timing of the schedule specified by timespec supports the following formats:
  • dtruns the function every dt seconds
    {wait}runs the function once, after waiting wait seconds
    {dt,count}runs the function count times, every dt seconds
  • After scheduling a task on the Arduino, it may be stopped prematurely with DeviceExecute[dev,"DeleteTask",funcname]
  • Only one function may run or be scheduled at any given time on the Arduino.

Closing and Releasing ResourcesClosing and Releasing Resources

    DeviceClose[dev]
    closes the connection to the Arduino device dev and frees the serial port.

  • Note that simply physically removing the Arduino from the machine's USB or serial port does not close the connection. DeviceClose is recommended to be called before removal of the device for properly ending usage.
  • Any functions scheduled on the Arduino will continue to run even after the connection to the device is closed, so long as the Arduino has uninterrupted power.

ExamplesExamplesopen allclose all

Basic Examples  (1)Basic Examples  (1)

Open a connection to the Arduino and upload the required sketch to the device:

In[1]:=
Click for copyable input

Set the Pulse Width Modulation of the duty cycle of pin 3 to be 50%:

In[2]:=
Click for copyable input
Out[2]=

Write a value of 0 to digital pin 10:

In[3]:=
Click for copyable input
Out[3]=

Write a Pulse Width Modulation duty cycle to pin 5 that corresponds roughly to 2.5 volts for some devices:

In[4]:=
Click for copyable input
Out[4]=

Read from multiple analog input pins:

In[5]:=
Click for copyable input
Out[5]=

Read from pin 4, using to compare the value to 1:

In[6]:=
Click for copyable input
Out[6]=

Read the value from analog pin A3, applying a conversion function to turn the value into inches:

In[7]:=
Click for copyable input
Out[7]=

Get the most recently read value for a particular pin:

In[8]:=
Click for copyable input
Out[8]=

Upload a SymbolicC function to the Arduino that adds two numbers and the number 1000 together:

In[9]:=
Click for copyable input
In[10]:=
Click for copyable input

Now run the function with the arguments 1 and 20:

In[11]:=
Click for copyable input
Out[11]=

Upload a function to control a servo motor attached to the Arduino on pin 9, taking as its argument the position to rotate the servo to, using the Arduino built-in Servo library:

In[12]:=
Click for copyable input

Now rotate the servo to the 90 degrees position:

In[13]:=
Click for copyable input

The following example requires an LCD to be attached to the Arduino on pins 12, 11, 5, 4, 3, and 2. First upload a simple function that writes a string to the LCD screen:

In[14]:=
Click for copyable input

Now, write a string to the LCD screen:

In[15]:=
Click for copyable input
In[16]:=
Click for copyable input