Serial Communications with Processing

Serial Communications with Processing

Serial Communications with Processing

The Serial class

The operations to use serial communications in Processing are defined in the class Serial.The first operation to perform to use them in a program (sketch) will be to incorporate it into the code with import processing.serial.*;.

Table of Contents

    Class Serial It has five different constructors depending on the parameters indicated. The only required parameter is the parent object (parent) which usually corresponds to the main program (say, the program window) of the class PApplet. As normally the parent will be the program being written (the sketch current), the value of this first mandatory parameter will be this.

    The other five parameters that can be passed to the constructor are ① the speed, ② the name of the serial port ③ the parity used in the protocol, ④ the data bits and ⑤ the stop bits. The most frequently passed parameters, in addition to the required parent object, are the port name and speed.

    La serial communications speed is an integer (int) what defaults to the value 9600 if this parameter is not passed to the constructor.

    Serial ports available. The list method

    El port name has the form determined by the system, in this way, for example in Linux distributions it will be something like /dev/ttyS4 /dev/ttyACM3 o / dev / ttyUSB1 (depending on the port type), while on Windows it will be something like COM12. Unless a port is physically associated with a device, the program will normally not know which port to use. A common way to select the port is to obtain a list of the available ones, show it to the user and allow them to choose the one they want to use. The method Serial.list() returns a vector of text strings (String) with the names of the ports available on the system.

    The port used by default by the library Serial is the first of those returned by the method list (surely COM1 on Windows or /dev/ttyS0 en GNU / Linux). Except in very limited contexts in which the hardware being worked with is strictly known (such as a system in kiosk mode), it is not usually omitted and the destination port is expressly indicated.

    Processing serial Linux Serial list port ttyACM ttyS ttyUSB

    The screenshot above shows the output of a system GNU / Linux which has four serial ports RS-232 (ttyS0 a ttyS3) and five adapters of two types (ttyACM0 a ttyACM1 y ttyUSB0 a ttyUSB2).

    Linux serial devices permissions ttyACM ttyS ttyUSB

    In order to access the serial ports, the user must belong to the group to which the system assigns them, normally tty o dial out. In the screenshot of the image above you can see that the serial ports listed with ls /dev/tty[ASU]* -la belong to the group dial out which has read and write access permissions on them.

    Serial protocol parameters

    La parity of serial communications is expressed in Processing as a character (char) which can take the values: ① N (none) to not detect the parity, ② E (Even) to indicate that the parity bit is even, ③ O (odds) to indicate that the parity bit is odd, ④ M (mark) to always make the parity bit and ⑤ S (space) to always make one the parity bit. The default value, if not passed to the constructor as a parameter, is N (without parity).

    Number data bits, which is eight by default, indicates the number of bits that make up the net data payload (called a character or sometimes a word) that is transmitted in each basic unit of the frame. The parameter indicating the number of data bits is expressed as an integer (int).

    Finally, the fifth possible parameter indicates the duration of the final mark, expressed as stop bits (stop bits), which is indicated as a number represented in floating point (float) that can take the values 1.0 (the default value if the parameter is not passed to the constructor), 1.5: 2.0.

    Constructors of the Serial class

    The following list shows the different combinations of parameters that can be passed to the class constructor Serial:

    • Serial(padre)
    • Serial(padre,puerto)
    • Serial(padre,velocidad)
    • Serial(padre,puerto,velocidad)
    • Serial(padre,puerto,velocidad,paridad,bits_datos,bits_parada)
    End serial communications. The stop method.

    To release the serial port, assigned when instantiating Serial, and that other system applications can use it, communications are terminated with the method stop, which does not receive parameters.

    Send data through the serial port. The write.method

    To send data, the class Serial de Processing incorporates the method write with which you can transmit ① text strings (String), ② bytes or ③ byte vectors (byte[]). It is interesting to remember that byte en Processing (At Java) represents an integer between -128 and 127 and, by default, strings use the encoding UTF-16.

    Read data from serial port

    So that the program can perform other tasks while data is received through the serial port, it is usual to store in a buffer the data that arrives and read it when appropriate. Although usually not very efficient, you can stop the application to load all available data; However, the most common thing will be to read the information as it arrives, either in each iteration of draw, when a certain quantity is available or a special code has been received.

    Amount of data available in the buffer. The available method

    To know if data has arrived at buffer series, the method available returns the number of bytes that have already been stored in this buffer. In either case, read operations can return a special value (such as -1 o null) when trying to load data from buffer series when empty.

    Load one byte at a time. The read method

    The main methods of the class Serial that serve to read the information received by a serial port are those of "type read» that differ between them, mainly, by the type of data in which they deliver the information received.

    read is used to deliver the bytes received by the serial port as a value between 0 and 255. As the data type byte de Processing represents the range between -128 and 127 and not between 0 and 255, it is necessary to use a int in order to represent the range returned by read. If you try to read with read and buffer string is empty, returns value -1

    Read characters from the serial port. The readChar method

    The method readChar is similar to read but it returns a value in format char instead of a int. As internally, the char en Processing (At Java) are stored with two bytes, the value chosen to return when reading with readChar a buffer empty series is 0xFFFF o -1.

    Load a text string. The readString and readStringUntil methods.

    The method readString returns an object String formed from all the data available in the buffer series at the time of consultation.

    The method readString creates the text string assuming that the bytes received by the serial port are in the format ASCII so this reading method cannot be used for other encodings.

    If it is about reading the buffer series with readString when empty, the return value is null.

    The method readStringUntil add to readString the ability to return information loaded into the buffer series splitting it by a special character (code) that is passed as a parameter. This way of reading the information received allows us to distinguish both separators and terminators that help interpret the information received.

    The method readStringUntil bring back null when in the buffer series does not find the code specified in the argument passed to it (one byte).

    In the following code for Arduino sends three messages through the serial port. The first two end in a tab, so they will appear in the console. Processing, while the third, although it will be sent through the serial port, will not be read with readStringUntil(9) since it does not end in a tab (with code ASCII 9).

    Processing Serial.readStringUntil read serial string

    Read data blocks. The readBytes and readBytesUntil methods.

    The methods seen above are used to read data with specific formats, to read blocks of raw data or with a format that is not provided for in Processing methods are used readBytes y readBytesUntil

    The method readBytes try to read the data available in the buffer series. If no parameter is passed to the method readBytes all available data is read and returned in a vector (byte[]). If an integer is passed as a parameter, a maximum of the number of bytes indicated by this number is read and they are also returned as a vector.

    There is a third way to use readBytes, more efficient, which takes as an argument a byte vector into which the contents of the buffer series. This way of using readBytes returns an integer (int) which represents the number of bytes that have been read.

    The method readBytesUntil works in a similar way but includes a first parameter that represents the value of the byte that, if found in the buffer, will indicate the end of the reading. In this method, the parameter that determines the maximum number of bytes that will be read does not make sense since the amount will be determined by the special code.

    To test the operation of the method readBytes Let's assume the following code for Arduino which sends a text through the serial port.

    The following example program for Processing reads text from the serial port in 32-byte blocks (TOTAL_BYTES). To verify that it works, it shows it through the console as characters, forcing the type of the bytes received to char.

    In the following screenshot you can see how they are displayed in the console Processing the data that has been loaded in blocks of (maximum) 32 bytes (TOTAL_BYTES) every time. But there is a problem that has already been talked about: Arduino has been sending the verses of Federico Garcia Lorca of the example encoded as text in format UTF-8, which is not the one used Processing (Java), what do you prefer UTF-16 so those who do not correspond to the rank of the ASCII printable are interpreted incorrectly.

    Processing Serial.readBytes UTF-16

    To solve this problem, the character sets can be loaded (charset) and define a new object String forcing it to be represented with encoding UTF-8 as shown in the following example code.

    Processing Serial.readBytes UTF-8

    Read the latest data received. The last and lastChar methods.

    While the rest of the reading methods (the "type read») they load the information of the buffer series in the same order that it has arrived (FIFO), with these two methods the last byte that has reached the buffer series. The method last returns the value of the last byte as a int y lastChar returns the value as a char.

    Serial buffer management

    Although the methods seen so far are perfectly functional, they do not always represent the best way to exploit access to the serial port. To load the data, they need to periodically check the status of the buffer series and read the data available in a repeating part of the code. A generally more efficient way is to read the data only when you know it is available.

    Read the serial port when data is received. The Serial event.

    To access the buffer serial when the data is received, the Serial event can be exploited by managing it through the method definition serialEvent. This method uses the serial port that launches it as an argument.

    Size the serial buffer. The buffer method.

    If you know the number of bytes that make up a block of useful data, you can further optimize this style of reading the data. buffer series through serialEvent. The method buffer allows you to set the number of bytes that will be stored in the buffer before launching a Serial event. The method expects as a parameter an integer that represents the number of bytes.

    Fill the buffer until a value is received. The bufferUntil method.

    Instead of setting the method call serialEvent for a quantity of data in the buffer, with the method bufferUntil you can configure to store data until a special value arrives and then raise the Serial event. The parameter passed to this method is a int which represents the value produced by the call to serialEvent.

    Delete the data stored in the buffer. The clear method.

    With the method clear You can delete the data that is currently in the buffer. This method can be used, for example, to start a new data reception session ignoring the data remaining from the previous one.

    Typical Processing application for reading data through the serial port

    Finally, it is convenient to recapitulate the operations of the object Serial de Processing that are more commonly used, going through a typical example of receiving data through the serial port to draw a graph with them, in this case of stacked areas.

    Import the Serial library

    Determine data protocol (separators)

    Determine the object of the Serial class

    Instantiate the Serial class object by setting the serial port used

    Configure the serial port buffer

    Implement a handler for the Serial event

    Read serial buffer

    Condition the data received

    End serial communications

    The example code below illustrates this summary with a functional (although very simple) application that generates an area graph with the values ​​that are received through the serial port, something similar to what the following animation shows.

    graphic with Processing with data received through the serial port

    In order not to get lost in the rest of the program and focus attention on serial communications with Processing, the lines of code that correspond to the previous operations are highlighted.

    Post Comment

    You May Have Missed