Skip to content

Instantly share code, notes, and snippets.

@Foadsf

Foadsf/.gitignore

Last active Sep 26, 2020
Embed
What would you like to do?
Scilab Serial Communication Toolbox (SSCT)
docinfo.html
Documentation.md
pics/

This text is documented in AsciiDoc format

Scilab Serial Communication Toolbox (SSCT)

Abstract:

Scilab Serial Communication Toolbox (SSCT) is inspired by a toolbox with a same name originally developed by Aditya Sengupta and Enrico Segre. However, this new development line is an attempt to comply / resemble MATLAB serial communication functionalities and syntax, as much as possible. The toolbox adds serial port (e.g. RS-232) protocol communication to Scilab / Scicoslab platforms, which are Free and Open Source Software (FOSS) alternatives of MATLAB. The toolbox can be used for sending commands to control robots, motors, or reading sensors such as GPS, laser scanners, compasses, etc [Esposito2009]. For the moment the toolbox only works on Wondows OS, but development for Linux and macOS are under progress and will be added soon. This toolbox is still in early stage prototyping stage and functions are not compiled. To use it just download this Gist and run the ssctmain.sci in Scilab. For ScicosLab, due to the fact that multiline commenting /* …​ */ is yet to be implemented, the AsciiDoc documentations in those tags need to be removed in advance.

A serial object structure with similar properties / attributes and functions of the one in MATLAB has been developed. There are of course some syntax differences due to Scilab intrinsic limitations, not-implemented features, as well as extra features considered to improve upon what MathWorks has already done. Considering that Scilab doesn’t have built-in Serial Port communication, external languages including Tcl, PowerShell, CMD / batch, bash, C, C++ have been used. Moreover, due to the lack of object oriented programing (OOP) capability in Scilab there are major differences between this toolbox and MATLAB. Mainly the serial object has no routine / subroutine / procedure accessible through dot . operator, as seen in the OOP languages. Furthermore, all the MATLAB functions starting with an f are changed to s to avoid confusion and conflicts with other Scilab functions, as well as possible copyright issues. For example MATLAB’s fopen is sopen in this toolbox. The syntax has been changed in a way to be more consistent and concise.

Although there are other FOSS options like Python, Octave, Julia, Sage, Maxima, R and FreeMat …​, Scilab stands out among these options for having the great xcos / scicos environment, which is a replica of SIMULINK visual programing. xcos / scicos can also include code blocks from other languages such as C/C++, Fortran, Scilab, and Modelica language. In addition, Scilab / ScicosLab also have a nice GUI building functionality which resembles MATLAB syntax. In general for users coming from a MATLAB background it is one of the best alternatives.

Introduction:

A typical serial port communication session has five steps:

  1. Find the valid, available, open, defined serial ports using the slist function

  2. Create a serial port object using the sdefine function, specifying the required properties.

  3. Opening the port using the sopen function and adjusting the properties using sconfig and sinfo function

  4. Sending or receiving data using

    1. sput for putting data to the serial port buffer and sflush for sending them out

    2. sget function for taking data out of the serial port buffer

  5. Closing the port using the sclose function and cleaning up the DefinedPorts list using the sdelete function.

Alternatively one can use the sprint and sread functions to send and read data in one step.

Example:

s1 = sdefine(Port = "COM1", BaudRate = 4800);
sopen(s1);
sput(s1, "*IDN?");
out = sget(s1);
sclose(s1);
sdelete(s1);
clear s1;

or alternatively using the simpler syntax:

sprint(Port = "COM1", Message = "*IDN?", BaudRate = 4800);
sread("COM1"); // to be implemented

Functions:

sprint()

writes text to the serial devoice (similar to the MATLAB fprintf)

Syntax:

<Result> = sprint(<SerialPort => SerialPort, <Message => Message, <Mode = "syn"/"async">)

Description:

The SerialPort is a serial port object defined by the serial function or a string of a valid serial port such as COM1. The Message is a Scilab string which can be a formatted text created by Scilab’s msprintf function or a SCPI / SCI command known to the serial device.

Example:

sprint(s1, 'RS232?');
sprint(s1,'*IDN?');
sprint(s1, msprintf('%s','RS232?'));
sprint(s1, msprintf('ch:%d scale:%d', 1, 20e-3), 'sync');

sinfo()

Check the input and output buffer for available bytes and the status of the port

Syntax:

[InutBytesAvailable, <OutputBytesAvailable>, <Status>, <Result>] = sinfo(SerialPort)

Tutorials:

Example 01:

In this example (inspired by this tutorial) you will learn how to communicate with an Arduino microcontroller (MCU) expansion board and a Windows PC, through serial port. By the end of this example you will be able to read the value of a potentiometer, while this can be also expanded to reading any other sensors as well. To follow along the example you require the hardware including an Arduino Uno MCU development board, a potentiometer, wiring and breadboard.

ex01 pic01
Figure 1. An Ardunio Uno board with Potentiometer connected to port A0. (Image courtesy of arduino.cc)

Alternatively you can use SimulIDE to simulate the hardware and the Null-modem emulator (com0com) one Windows, to stablish a pair of virtual serial ports.

The Arduino code is:

int potPin = A0;

long val = 0;
long val_ = 0;

void setup() {
  Serial.begin(9600);
}

void loop() {

    val = ((long) analogRead(potPin));

    if (val != val_) {
      val_ = val;
      Serial.println(val);
    }

}

find the port connected to the Arduino board by running the command:

slist(Verbose = %t, PortList = "all")

This will show you are the serial ports recognized by the operating system, including the "available" and "open"`s. Under `Description you should be able to find the Arduino serial port.

Scilab code

SimulIDE model

Click to see the source code

link:ex01.simu[]

Result:

ex01 pic02
Figure 2. Live plotting of a potentiometer from Arduino

Nomenclature / Glossary:

For those who are not familiar with serial communication, some terms used in the practice can be difficult to grasp. In this section we will try to explain those terms.

  • message: a serial message is 1 byte or 8 bits, which is able to represent between 0-255.

  • terminator: indicates how a message should end. The common terminator is a carriage return indicated as "cr" in this toolbox.

  • buffer: is like a container on the on both sides of the communication ports. The sender stores the data there before flushing them through the port and the receiver stores them there before dumping them over to the users space. The buffers have limited size which if exceeds the oldest data will be discarded. The size of buffer can be set through InputBufferSize and OutputBufferSize serial object property, which can not exceed the maximum provided by the hardware MaxInputBufferSize and MaxOutputBufferSize. If you do not flush/read the data on the sender/receiver side in time it can lead to irreversible data loss.

  • checksum: in simple terms is basically a signature attached to each message, known by the receiver, which can be used to verify that the data is not garbled.

  • polling and streaming: when requesting one single measurements from a sensor, it is called polling. If we read data from the sensor given a certain frequency it is called streaming.

  • Serial Command Interface (SCI): firstly used by Motorola in the 1970s, is basically a language known by the serial device (e.g. MCU) to do certain things upon receiving certain messages.

  • serial peripheral interface ( SPI )

  • universal asynchronous receiver/transmitter (UART)

  • USART

  • Standard Commands for Programmable Instruments (SCPI)

  • Transistor–transistor logic (TTL)

  • TTY: teletypewriter, teletype, terminal

  • Serial Port Profile (SPP)

Abbreviations:

  • EIA Electronic Industries Alliance

  • ANSI American National Standards Institute

  • TIA Telecommunications Industry Association

  • DIN Deutsches Institut für Normung

  • RS Recommended Standard

    • 232

      • DTE Data Terminal Equipment eg. IBM computer, printer, plotter etc

      • DCE Data Communication/circuit-terminating Equipment eg. modem, multiplexors, etc

    • 422, 449, 485, 530

  • ASCII: American Standard Code for Information Interchange

Pinout and Signals

Connectors used to be in the form of D-sub series or Mini-DIN

Serial and Parallel ports were found in two different forms, DB-25 and DE-9 (which is mistakenly also referred to as DB-9).

port (e.g. , DB-25, DE-9 …​),voltage (TTL 5V, True RS-232 12V), communication standards (RS-232, USB), data transmission method (parallel or serial)

DE-9 DB-25 acronym / abbreviation Name typical purpose DTE DCE

1

8

DCD

Data Carrier Detect

DCE is receiving a carrier from a remote DCE

in

out

2

3

RxD

Received Data

Carries data from DCE to DTE

in

out

3

2

TxD

Transmit Data

Carries data from DTE to DCE

out

in

4

20

DTR

Data Terminal Ready

DTE is ready to receive, initiate, or continue a call

out

in

5

7

GND

Common Ground

Zero voltage reference (signal ground)

-

-

6

6

DSR

Data Set Ready

DCE is ready to receive and send data

in

out

7

4

RTR

Ready To Receive

DTE is ready to receive data from DCE

out

in

7

4

RTS

Request To Send

flow control, DTE requests the DCE prepare to transmit data

out

in

8

5

CTS

Clear To Send

DCE is ready to accept data from the DTE

in

out

9

22

RI

Ring Indicator

DCE has detected an incoming ring signal on the telephone line

in

out

1

PG

Protective Ground

Frame / Chassis Ground

-

-

9

10

11

12

SDCD

Secondary Carrier Detect

Tone from a modem

in

out

13

SCTS

Secondary Clear To Send

in

out

14

STD

Secondary Transmitted Data

out

in

15

ST

Send Timing

16

SRD

Secondary Received Data

in

out

17

RT

receive timing

18

Loopback

19

SRTS

Secondary Request To Send

out

in

21

Loopback

23

Signal rate selection

24

TT

Transmitter Timing

25

References

  • [Esposito2009] Joel M. Esposito, Tutorial: Serial Communication in Matlab, 2009, URL

////
/*
////
+++ <details><summary> +++
Click to see the source code
+++ </summary><div> +++
[source,scilab]
....
*/
s7 = sdefine(Port = "COM7", BaudRate = 9600, Parity = 'none', DataBits = 8, StopBits = 1, OverWrite = %t); // Assuming COM7 is the port you got from above command
sopen(SerialPort = s7, Access = 'r');
pData = [];
pTime = [];
nData = csvTextScan(part(sget(s7), 1:$-1), ',');
pData = [pData, nData(2)];
pTime = [pTime, nData(1)];
plot(pTime, pData);
while %t
drawlater();
nData = csvTextScan(part(sget(s7), 1:$-1), ',');
pData = [pData, nData(2)];
pTime = [pTime, nData(1)];
clf();
plot(pTime, pData);
drawnow();
sleep(1000);
end
sclose(s7);
sdelete(s7);
/*
....
+++ </div></details> +++
////
*/
////
////
//fignr = 1002;
//f = figure(fignr);
//f.menubar_visible = "off";
//f.toolbar_visible = "off";
//f.infobar_visible = "off";
////delmenu(fignr, 'File');
////delmenu(fignr, 'Edit');
////delmenu(fignr, 'Tools');
////delmenu(fignr, '?');
////toolbar(fignr, 'off');
////f.background = 1;
//f.figure_name="GUI";
//f.tag="mainWindow";
////
<circuit type="simulide_0.1">
Arduino Uno-17:
<item itemtype="Arduino" hflip="1" rotation="0" x="-252" valLabRot="0" Mhz="16" valLabely="0" id="Arduino Uno" valLabelx="0" labelrot="0" vflip="1" labely="-21" Ser_Port="true" labelx="54" objectName="Arduino Uno-17" Program="sketch_noDelay_20190228_1/sketch_noDelay_20190228_1.ino.standard.hex" Ser_Monitor="true" Show_id="true" y="-244"/>
Potentiometer-15:
<item itemtype="Potentiometer" hflip="1" rotation="0" x="4" valLabRot="0" Show_res="true" valLabely="-42" id="Potentiometer-15" valLabelx="-17" labelrot="0" vflip="1" labely="-24" Resistance="10" labelx="0" objectName="Potentiometer-15" Value_Ohm="8380" Show_id="false" y="-252" Unit=" kO"/>
Connector-24:
<item pointList="4,-236,4,-188,-100,-188" itemtype="Connector" hflip="1" rotation="0" endpinid="Arduino Uno-17-PC0" x="4" valLabRot="0" valLabely="0" id="Connector-24" valLabelx="0" labelrot="0" vflip="1" labely="-24" labelx="0" objectName="Connector-24" startpinid="Potentiometer-15-PinM" Show_id="false" y="-236" enodeid="Circ_eNode-25"/>
Connector-26:
<item pointList="-12,-252,-12,-164,-100,-164" itemtype="Connector" hflip="1" rotation="0" endpinid="Arduino Uno-17-GND1" x="-12" valLabRot="0" valLabely="0" id="Connector-26" valLabelx="0" labelrot="0" vflip="1" labely="-24" labelx="-16" objectName="Connector-26" startpinid="Potentiometer-15-PinA" Show_id="false" y="-252" enodeid="enode-26"/>
Connector-28:
<item pointList="20,-252,20,-148,-100,-148" itemtype="Connector" hflip="1" rotation="0" endpinid="Arduino Uno-17-V5V" x="20" valLabRot="0" valLabely="0" id="Connector-28" valLabelx="0" labelrot="0" vflip="1" labely="-24" labelx="-16" objectName="Connector-28" startpinid="Potentiometer-15-PinB" Show_id="false" y="-252" enodeid="enode-28"/>
PlotterWidget-56:
<item focus="false" frameGeometry="" maximumHeight="200" childrenRegion="" windowFilePath="" autoFillBackground="false" sizePolicy="" palette="" toolTip="" accessibleName="" styleSheet="" layoutDirection="0" minimumSize="" windowIconText="" windowModified="false" rect="" statusTip="" windowOpacity="1" toolTipDuration="-1" acceptDrops="false" updatesEnabled="true" visible="false" isActiveWindow="true" objectName="PlotterWidget-56" itemtype="Plotter" maximumSize="" contextMenuPolicy="1" pos="" cursor="" font="MS Shell Dlg 2,7.8,-1,5,50,0,0,0,0,0" height="200" locale="" geometry="" minimumSizeHint="" whatsThis="" y="791" accessibleDescription="" MaxVolt="500" minimumWidth="200" inputMethodHints="0" x="0" baseSize="" maximized="false" windowIcon="" width="265" childrenRect="" normalGeometry="" MinVolt="0" enabled="true" mouseTracking="false" minimized="false" frameSize="" sizeHint="" fullScreen="false" sizeIncrement="" size="" windowTitle="" maximumWidth="1000" modal="false" focusPolicy="0" windowModality="0" minimumHeight="200"/>
SerialPortWidget-57:
<item focus="false" frameGeometry="" maximumHeight="170" childrenRegion="" windowFilePath="" autoFillBackground="false" sizePolicy="" palette="" toolTip="" accessibleName="" SettingsProp="COM6,0,3,0,0,0" styleSheet="" layoutDirection="0" minimumSize="" windowIconText="" windowModified="false" rect="" statusTip="" windowOpacity="1" toolTipDuration="-1" acceptDrops="false" updatesEnabled="true" visible="true" isActiveWindow="true" objectName="SerialPortWidget-57" itemtype="SerialPort" maximumSize="" contextMenuPolicy="1" pos="" cursor="" font="MS Shell Dlg 2,7.8,-1,5,50,0,0,0,0,0" height="170" locale="" geometry="" minimumSizeHint="" whatsThis="" y="806" accessibleDescription="" minimumWidth="0" inputMethodHints="0" x="528" baseSize="" maximized="false" windowIcon="" width="450" childrenRect="" normalGeometry="" enabled="true" mouseTracking="false" minimized="false" frameSize="" sizeHint="" fullScreen="false" sizeIncrement="" size="" windowTitle="Settings" maximumWidth="450" modal="false" focusPolicy="0" windowModality="0" minimumHeight="0"/>
</circuit>
View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

@mentablack

This comment has been minimized.

Copy link

@mentablack mentablack commented Apr 15, 2019

I'm having trouble with launching the .sci files with errors like in the ssctmain.sci
/*
!--error 2
Invalid factor.
at line 2 of exec file called by :

@Foadsf

This comment has been minimized.

Copy link
Owner Author

@Foadsf Foadsf commented May 28, 2019

Dear all, Feel free to contact me here on Twitter if I did not respond to your comments immediately.

@Foadsf

This comment has been minimized.

Copy link
Owner Author

@Foadsf Foadsf commented Oct 18, 2019

for some reason, the Firefox and Atoms AsciiDoc's plugins don't work properly. The Visual Studio Code plugin renders correctly. though the dark theme is annoying.

P.S. For the firefox addon to work please use this workaround.

@tanchinluh

This comment has been minimized.

Copy link

@tanchinluh tanchinluh commented Oct 19, 2019

hi, do you consider to work on UDP?

@Foadsf

This comment has been minimized.

Copy link
Owner Author

@Foadsf Foadsf commented Oct 20, 2019

@tanchinluh I'm afraid I don't have any knowledge about internet protocols (IP), TCP and UDP. But given the fact that the library is using Tcl, cmd/batch and PowerShell at the moment, if they support those protocols we should be able to integrate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.