Arduino Serial Write

Posted on by admin

Serial.write It sends the binary data to the serial port in Arduino. The data through Serial.write is sent as a series of bytes or a single byte. The data type is sizet. When I just use Serial.write (integer) and display the value on a line graph in 'processing' the line will max out at 256 and loop back around to 0 as i vary the potentiometer. I understand that this is because the serial.write can only write in bytes (8 bits) so I would need to package the 16 bit integer into 2 bytes. From the Arduino site for Serial.write and Serial.print: Serial.write Writes binary data to the serial port. This data is sent as a byte or series of bytes; to send the characters representing the digits of a number use the print function instead. Serial.print Prints data to the serial port as human-readable ASCII text. Referring to the arduino referense page, the process for sending serial data is different in the output process. Serial print vs Serial write, Serial.print will send data to the serial port in human-readable ASCII text and Serial.write will send data in binary. Example of Serial Print: Serial.print (98) It will gives '98' Serial.print (1.2345).

Foreward

Hello everyone. Today I want to write a short tutorial in response to a request that we received yesterday on the Meccanismo Complesso site by pensodisi.

I hope that will be useful both to him and to all others who have similar needs.

Any request or suggestion will always be an incentive for us to improve.

Introduction

For those who delight in carrying out projects with Arduino, sooner or later they will have to deal with the exchange of values between the Arduino and the PC to which it is connected.

If you use Arduino connected to a sensor (see Fig.1), Arduino produce a series of data that may be sent to a computer to be stored in a file, displayed or processed in some way. If you use the Arduino connected to an actuator (see Fig.2), such as a stepper motor, most likely, the computer will send a series of data to the Arduino. The latter will process the received data by converting suitably into commands to send to the motor to make it move in the amount of necessary steps.

I’ll discuss this topic in two different articles.

In this tutorial we will see an example of the use of Arduino as a control for an actuator. To make this tutorial as simple as possible, we will use a servo motor as an actuator.

Instead, in an upcoming article, I will collect data from a sensor connected to the Arduino and sending these values to a PC.

Regarding the various commands to drive the servo motor or other motor types (DC or stepper motors) I suggest you refer to the article Motor Control with Arduino and the Adafruit Motorshield v2 board.

Drive a servo motor with a sequence of angles in a file

I chose a servo motor due to its simplicity, especially with regard to the controls. In this tutorial, the servo motor will assume the angles in a list within a TXT or CSV, moving sequentially in time, reading line by line.

I chose this example, because despite its simplicity, it contains all the essential elements remaining simple and easy intuitibile. It will then be easy to extend this example to more complex projects.

Let’s take a look at the general outline of what we will achieve in this tutorial:

As you can see, you will activate a serial connection between the Arduino board and the PC. On the Arduino board you will implement a sketch that will take care of “to listen” for any value (angle) sent from the PC. From the PC side, instead, you will activate a serial session in a Python shell (but it can be replaced by any program in Python) that will read the contents of the file (CSV or TXT) by sending appropriate signals via serial to the Arduino.

I chose the servo motor as an actuator also because it can be connected directly to the Arduino without the use of appropriate control boards. Refer to Figure 6 for the connections.

If you had the Motorshield v2 Arduino, you can refer to the following figure (Fig. 7).

The Arduino sketch

First, let us develop the sketch with the Arduino IDE. (Click here to go to the official page and download the latest release of the Arduino IDE).

First, you have to include the Servo library already included within dell’Arduino IDE

This library provides us with a whole series of commands to manage Servo Motors in an easy and intuitive way. This library is specialized for controlling this type of motors when they are directly connected to the Arduino. (If you are interested, you can consult the official page here).

First you define a myservo object, which corresponds to the servo motor. Define also the angle and newAngle variables that will hold the values of the angles. Then you will define a strValues array of characters that will hold up to 4 characters (for example, ‘123,’). This array is used to store the values of the angles sent to the PC via serial port. Finally, an index that will help you later to scan the array of characters.

Define now the two standard functions setup() and loop().

The setup function practically takes care of initializing the board, and then, first of all activate a serial communication at 9600 baud. Then you have to define the servo motor to be connected to pin 10 through the function attach() of the Servo library. Finally, define a starting angle for the motor (HOME position) which in my case I defined as 90°.

Write

The function instead must contain all of the commands that will be executed from the board in a continuous cycle. I left empty this function, but here you can implement everything you need to fulfill your specific needs.

Finally, define a new function called serialEvent(). This feature, although it is not included within the loop(), is always listening, and when a serial event is captured by the Arduino board, as in our case, the sending from the PC to a numeric value, the serialEvent function is activated, and the code inside is executed.

Each value sent from the PC is read character by character and inserted into the strValue array. If the character read will be a number (0 to 9) then it is stored in the array, if it will be a non-numeric character (in this case the comma ‘,’) the reading will be stopped and the value inside the array is converted to a numeric value through the atoi() function.

The numerical value so obtained is stored in the newAngle variable, and represents a new angle at which it must set the servo motor. This value to be acceptable must be between 0 and 180 degrees. This will then be compared with the current angle angle, and depending on whether major or minor, we will increase or decrease gradually (degree by degree) the angle of the servo motor. This is to avoid sudden jumps by the servo motor. The angle at which the engine must be set is defined by the write() function of the Servo library.

If you now execute the code, you will see the servo motor rotating to the corresponding position angle of 90°. Then it will wait motionless listening to the values sent from the PC.Before moving to Python, you can do some tests. Activate the Serial Monitor within the Arduino IDE, clicking on the menu item Tools> Serial Monitor.

A new window will appear to us, the Monitor Serial precisely and with it you will be able to experiment by writing directly the angles you want the servo motor to be moved. Write, for example, ‘123; ‘and press ENTER.

If you have correctly written the sketch and making all the connections, you’ll rotate the servo motor from the HOME position (90°) to 123°.

Commands from Python

Now you will look the Python part regarding the PC side.

First, start a Python Shell. If you have not already installed on your PC go here.

Once you open the shell import the serial library, and create a serial connection with ser listening to the Arduino board at 9600 bauds.

Beware the USB port in listening may vary, so check from the Arduino IDE the active port (eg. COM on Windows can be a 1,2,3 or 4). Then replace the serial port within the function Serial().

Now if you write:

you will get a result identical to that obtained previously with the Serial Monitor. The servo motor will rotate until it assumed the position corresponding angle of 110 °.

Serial

But the purpose of this tutorial is to read a sequence of values listed in a CSV file. Create a CSV file with a sequence of angles and save it as samples.csv.

Copy the file you just created in the working directory of the Python Shell. If you do not remember or do not know what it is, enter the following commands:

Vi apparirà la directory dove la shell di Python va a leggere direttamente. Copiato il file, scriviamo

Every 3 seconds (defined by time.sleep()) the Python Shell will read a line from the CSV file by sending the value, ie the angle, to the listening Arduino board, which in turn will trigger the servo motor.

Once the file is completed, close the reading of the file with the command.

Conclusions

As you can see the tutorial is basic, simple and easy to produce. it is a good starting point for any project that has among its functions the exchange of data.

Command lines of Python can be implemented in a program, and for serial communication you use a specific library, such as the pySerial library.

As regards the values I used angles, but you could use any type of value, for example steps of a stepper motor, a distance, etc..

Furthermore, in the case of several motors, for example in automation CNC with 2 motors (XY) or three motors (XYZ) it is possible to pass a line with multiple values, for example the first value as the number of steps and the second value as the motor to move (X, Y, or Z). In short this tutorial should open the way to many projects. And if you will be inspired, we would be proud of publishing your projects in this site.

[:]


Arduino boards such as the Uno, MEGA2560 and Due all have a serial port that connects to the USB device port on the board. This port allows sketches to be loaded to the board using a USB cable. Code in a sketch can use the same USB / serial port to communicate with the PC by using the Arduino IDE Serial Monitor window, or a Processing application for example. The USB port appears as a virtual COM port on the PC.


This article shows how to use Arduino serial ports when additional serial ports are needed for a project.

Arduino Serial Ports Available

The serial port for programming the Arduino mentioned above is a hardware serial port. The microcontroller on the Arduino board has a hardware serial port built-in, so that after the port has been initialized by software, a byte sent to the port will be sent out serially by the hardware.

The Arduino Uno has only one hardware serial port because the microcontroller used on the Uno has only one built-in serial port. The Arduino MEGA 2560 and Arduino Due both have 3 extra hardware serial ports.

Serial Port Technical Details

The hardware serial ports referred to here are UART (Universal Asynchronous Receiver Transmitter) ports. They may be referred to as USART (Universal Synchronous Asynchronous Receiver Transmitter) ports in the microcontroller documentation if they are configurable in both synchronous and asynchronous modes.

Arduino Serial Write Byte

Arduino Uno Serial Port

This image shows the only serial port available on the Arduino Uno highlighted in red. The port connects through a USB chip to the USB device port.

Arduino MEGA 2560 and Due

Both the MEGA 2560 and Due have 4 serial ports in total. One that connects through a USB port chip to the USB device port on the board and three extra serial ports that connect to pins on one of the pin headers of the board.

Arduino Due Serial Ports

Pins 0 and 1 of the Due and MEGA connect serial port 0 through to the USB device port so that these Arduino boards are compatible with the pin numbering of the Uno and therefore with Arduino shields.

The extra serial ports are ports 1 to 3 with each port having a transmit and receive pin.

It is important to be aware that the MEGA 2560 serial port pins use 5V voltage levels, but the Due uses 3.3V voltage levels.

How to Use Additional Arduino Serial Ports

An extra serial port can be used on an Arduino Uno, but must be simulated in software by using the SoftwareSerial library.

Arduino Uno

The following code is taken from the article on serial communications with the GT-511C3 fingerprint scanner which connects the fingerprint scanner to a software serial port on an Arduino Uno.

To use the software serial port, first the header file for the software serial library must be included.

Next create the software serial port, selecting the Arduino pins to use for receive (RX) and transmit (TX). Here pin 8 has been set as the receive pin and pin 7 as the transmit pin.

The software serial port had been given the name gtSerial which will be used in the sketch to refer to this serial port.

The port can now be checked for incoming data.

Arduino Serial Write

If data is available, it can be read from the port.

Data bytes can also be sent on the port.

How to Use Additional Serial Ports on the Arduino MEGA 2560 and Due

The additional hardware ports on the Arduino MEGA 2560 and Due can be used in the same way as the main USB serial port is used in sketches, only changing the name of the port. The USB serial port, or serial port 0 is referred to as Serial in sketches. To use serial port 1, the name changes to Serial1. Serial ports 2 and 3 are referred to as Serial2 and Serial3.

This sketch shows serial port 3 being used which transmits on pin 14 of the MEGA or Due and receives on pin 15.

The additional serial ports are immediately available in the sketch without having to include any libraries.

Serial port 3 must first be initialized to the desired baud rate.

The port can be checked for incoming data.

Arduino Write To Serial Monitor

If a byte has arrived on the serial port, it can be read.

A byte can be written to the serial port.

Arduino Serial Port Resources

Arduino Website References for Software and Hardware

  • Software serial library Arduino reference.
  • Serial port library Arduino reference for hardware ports.
  • Arduino Uno — hardware reference.
  • Arduino Mega 2560 — hardware reference.
  • Arduino Due — hardware reference.

Arduino Serial Write Code Youtube

Projects, Articles and Tutorials

Arduino Serial Write New Line

  • Using the Arduino serial port and serial monitor window.
  • Getting serial input from the serial monitor window.
  • Arduino serial thermometer breadboard project.
  • Measuring voltage with Arduino — displays voltage in the serial monitor window.
  • Reading an analog value with Arduino.
  • Finding the Arduino serial USB port number on a PC using Processing.
  • Serial communications with a fingerprint scanner using Arduino and Processing.