Advance I/O With Serial Monitor

Introduction: Advance I/O With Serial Monitor

About: Dr.Ing. Ievgen Shalaginov. My huge passion are renewable energies and the sustainable way of life. To follow my life goals a few other people and Istarted a “Shalaginov Eco-Energy” company with one main...

Serial monitor is a very useful tool for communication with other devices over the USB port, displaying the state of the digital I/O and analog values from sensors.

In my project I am using the serial monitor to control my programs workflow – state of the I/O, sensors measurements and calibration, sketch debugging.

Serial monitor together with potentiometer and analog sensor can be valuable part of your projects.

In this tutorial we will learn how to display and manipulate an analog and digital values in the serial monitor, and how to handle a different analog values with a help of the map() function.

Additionally, we will make some projects with potentiometer and joystick – which will be our building blocks for the future robotic projects.

Teacher Notes

Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.

Step 1: Serial Monitor Basics

All Arduino boards have at least one serial port (also known as a UART or USART), and some have several.

NOTE: On Uno, Nano, Mini, and Mega, pins 0 and 1 are used for communication with the computer. Connecting anything to these pins can interfere with that communication, including causing failed uploads to the board.

Before we can use the Serial Monitor, we need to activate it by adding Serial.begin(baud) function to our sketch in

void setup():

Serial.begin (9600);

The value 9600 is the speed at which the data will travel between the computer and the Arduino, also known as baud (bits per second). You’ll generally use 9600 baud with the Arduino IDE serial monitor, but other speeds are also available up to 115,200 bps. The specific baud rate doesn’t matter, as long as Arduino board and PC use the same rate.

Baud refers to a bits per second. So, if we select 9600 baud, one bit will have a length of 1 / 9600 baud, which will be 0.000104 sec (104 μsec).

In our first Example we will use the sketch with basic serial functions (you can use a table as reference).

Sending Text to the Serial Monitor

To send text to the Serial Monitor use Serial.print(data) function

Serial.print("Arduino for maker!");

This sends the text between the quotation marks to the Serial Monitor’s output window.

Serial.println () is the same as Serial.print(), except that it adds a carriage return and linefeed (\r\n) as if you had typed the data and then pressed Return or Enter

You can also use Serial.println(data, encoding) to display text and then force any following text to start on the next line. The encoding is optional; if not supplied, the data is treated as much like plain text

Serial.println("Arduino for maker!");

Serial.println(33); // Prints "75\r\n"

Serial.println(33, DEC); // The same as above.

Serial.println(33, HEX); // 21

Serial.println(33, OCT); // 41

Serial.println(33, BIN); // 100001

Displaying the Contents of Variables

You can also display the contents of variables on the Serial Monitor.

Serial.println (pi); // 3.14

If the variable is a float, by default it will be displayed with two decimal places. You can specify the number of decimal places by entering a second parameter after the variable name. For example, to display the float variable to four decimal places, we should enter the following:

Serial.println (pi, 4); // 3.1415

int Serial.read() - Fetches 1 byte of incoming serial data.

int data = Serial.read();

Serial.write() - writes the data in binary form from the serial buffer. The data is sent as bytes.

Serial.write(val);

Serial.write(str);

Serial.write(buf, len);

Its enough of theory - now we can start wit some practical examples.

Step 2: Using Digital Pins

Digital Read Serial

This example shows you how to monitor the state of a switch by establishing serial communication between your Arduino and your computer over USB.

Hardware Required:

  • Arduino Board
  • A momentary switch,
  • button, or toggle switch
  • 10k ohm resistor
  • hook-up wires
  • breadboard

Connect components according to the wiring diagram.

Pushbuttons or switches connect two points in a circuit when you press them. When the pushbutton is open (unpressed) there is no connection between the two legs of the pushbutton, so the pin is connected to ground (through the pull-down resistor) and reads as LOW, or 0. When the button is closed (pressed), it makes a connection between its two legs, connecting the pin to 5 volts, so that the pin reads as HIGH, or 1.

If you disconnect the digital i/o pin from everything, the LED may blink erratically. This is because the input is "floating" - that is, it doesn't have a solid connection to voltage or ground, and it will randomly return either HIGH or LOW. That's why you need a pull-down resistor in the circuit.

You will find Sketch in Arduino IDE under File – Examples - 01.Basics - DigitalReadSerial

Code explained

In the program below, the very first thing that you do will in the setup function is to begin serial communications, at 9600 bits of data per second, between your board and your computer with the line:

Serial.begin (9600);

Next, initialize digital pin 2, the pin that will read the output from your button, as an input:

pinMode(2,INPUT);

Now that your setup has been completed, move into the main loop of your code. When your button is pressed, 5 volts will freely flow through your circuit, and when it is not pressed, the input pin will be connected to ground through the 10k ohm resistor. This is a digital input, meaning that the switch can only be in either an on state (seen by your Arduino as a "1", or HIGH) or an off state (seen by your Arduino as a "0", or LOW), with nothing in between.

The first thing you need to do in the main loop of your program is to establish a variable to hold the information coming in from your switch. Since the information coming in from the switch will be either a "1" or a "0", you can use an int datatype. Call this variable sensorValue, and set it to equal whatever is being read on digital pin 2. You can accomplish all this with just one line of code:

int sensorValue = digitalRead(2);

Once the bord has read the input, make it print this information back to the computer as a decimal value. You can do this with the command Serial.println() in our last line of code:

Serial.println(sensorValue);

Now, when you open your Serial Monitor in the Arduino Software (IDE), you will see a stream of "0"s if your switch is open, or "1"s if your switch is closed.

In the next example we will use digital.Read() and digital.Write() functions, to display status in the serial monitor and switch Led ON/OFF from Serial monitor.

Step 3: Digital Read / Write Serial

In this example, we will monitor the state of the switch and Led, and additionally we will control Led from serial monitor. You can type "1" in serial monitor and press Send to switch Led ON or "0" to switch Led OFF (in your sketch you can define any other number or character to switch Led on/off)..

Hardware Required:

  • Arduino Board
  • A momentary switch,
  • button, or toggle switch
  • Led
  • 10k Ohm resistor
  • 330 Ohm resistor
  • hook-up wires
  • breadboard

Connect components according to the wiring diagram.

Code explained

To read the status of a button, we first define a digital I/O pin as an input in void setup() using the following:

pinMode(Button, INPUT); // input for button

Next, to discover whether the button is pressed, we use digitalRead(Button).

The function returns either HIGH (voltage is close to 5 V at the pin) or LOW (voltage is close to 0 V at the pin).

Serial.Read () - First, it checks whether there is any data (here: from the keyboard). This is done with the command: if (Serial.available ()> 0) If data is available, it is read out with Serial.read ().

In the main loop, you turn the LED on with the line:

digitalWrite(Led, HIGH);

This supplies 5 volts to the LED anode. That creates a voltage difference across the pins of the LED, and lights it up. Then you turn it off with the line:

digitalWrite(Led, LOW);

Note: The following commands would turn the LED on:

digitalWrite(Led,HIGH);

digitalWrite(Led,true);

digitalWrite(Led,1);

Similarly, the following commands would turn the LED off:

digitalWrite(Led,LOW);

digitalWrite(Led,false);

digitalWrite(Led,0);

To determine whether the button is pressed (digitalRead(Button) is set to HIGH), we use a comparison operator, a double equal sign (==). If we were to replace == with != (not equal to) in the sketch, then the LED would turn off when the button is pressed instead.

NOTE: A common mistake is to use a single equal sign (=), which means “make equal to, instead of a double equal sign (==), which says “equal to.” It will not cause an error message, but sketch will not work properly

# define

Before void setup(), we use #define statements to create fixed variables. #define is a useful C++ component that allows the programmer to give a name to a constant value before the program is compiled. Defined constants in Arduino don’t take up any program memory space on the chip. The compiler will replace references to these constants with the defined value at compile time

For example, when the IDE sees Led in the line at the beginning, it replaces it with the number 7.

We’re basically using the #define command to label the digital and analog pins for the LED and button in the sketch.

NOTE: do not use a semicolon after a #define value. #define constantName value

#define ledPin 7 // The compiler will replace any mention of ledPin with the value 7.

#define ledPin 7; // this is an error

#define ledPin = 7 // this is also an error

In this way you can easy change Pin connection number, if an LED is connected to another pin, only one line has to be changed.

Through using a clear variable names in the sketch you will create a program which is easier to read and understand, especially when multiple components are used.

Reference:

https://www.arduino.cc/en/Tutorial/DigitalPins

https://www.arduino.cc/reference/en/language/funct...

https://www.arduino.cc/reference/en/language/funct...

https://www.arduino.cc/reference/en/language/funct...

Step 4: Read Analog Value

Basics

Analog Inputs - the Arduino board's analog inputs can also be fed by sensors that are both analog and digital in character. A temperature sensor is an example of how it changes its resistance as a function of the ambient temperature and supplies a more or less high voltage level to the input; and this voltage value is transmitted to a corresponding temperature value and displayed or it controls an actuator (motor, fan, etc.).

Reading or outputting an analog voltage value is more difficult and requires some special functions in the microcontroller. For this reason, analogRead () works only for A0 to A5.

Analog input »ADC«

To measure analog voltages (magnitudes), the Arduino microcontroller board has an internal analog-to-digital converter (ADC). The ADC used in the ATmega has a resolution of 10 bits which means that analog voltage has a step of 0.0048V with a reference voltage of 5V. The microcontroller board has six analog inputs, but internally only a single ADC converter. The channels are periodically switched, this is also called multiplexed. The resolution can easily be calculated with this simple equation:

Ustep = Uref / Resolution

Ustep = 5 V / 1.024 = 0,0048 V

Thus, for a 5V reference voltage, the accuracy is +/- 0.0097V (measures accuracy is to two decimal places). The prerequisite is, of course, a stable reference voltage.

analogRead (pin) reads the value of a specified analog pin with a 10-bit resolution. This function is only available for pins (A0 - A5). The resulting integer values are in the range of 0 to 1023.

INFO: Unlike digital pins the analog pins do not have to be declared as input or output first.

Analog Outputs - on the Arduino board, some digital ports take over the analog functions by simulating an analog signal generated by pulse width modulation.

To output an analog signal, use analogWrite (), but you can only use special digital pins. These are marked on your Arduino board with the symbol (~) - digital PWM pins. On the Arduino Uno these are pins 3, 5, 6, 9, 10 and 11.

The analogWrite () function uses two arguments just like digitalWrite () - the first argument specifies which pin to use and the second specifies value to output. This second argument is a little different it use neither HIGH nor LOW, instead, use a number between 0 and 255, using 0 for 0V and 255 for 5V. The following sample code outputs a signal at pin 9 that is approximately half of 5V. So set the second argument to 125:

analogWrite (9, 125);

If you want to spend almost the maximum (5V), use a number below 255:

analogWrite (9, 249);

Example: Analog Read and Write Serial

This example shows you how to read analog input from the physical world using a potentiometer, and write analog value to dim LED. A potentiometer is a simple mechanical device that provides a varying amount of resistance when its shaft is turned. By passing voltage through a potentiometer and into an analog input on your board, it is possible to measure the amount of resistance produced by a potentiometer as an analog value. In this example you will monitor the state of your potentiometer after establishing serial communication between your Arduino and your computer running the Arduino Software (IDE).

Hardware Required

  • Arduino Board
  • 10k ohm Potentiometer
  • LED220
  • ohm resistor
  • hook-up wires
  • breadboard

Connect components according to the wiring diagram.

Arduino IDE code example : File - Examples - 03.Analog - AnalogInOutSerial
Code explained

In the sketch, after declaring two pin assignments (A 0 for our potentiometer and digital 9 for your LED) and two variables, sensorValue and outputValue, the only things that you do in the setup() function is to begin serial communication.

In the main loop, sensorValue is assigned to store the raw analog value read from the potentiometer. Arduino has an analogRead range from 0 to 1023, and an analogWrite range only from 0 to 255, therefore the data from the potentiometer needs to be converted to fit into the PWM range to use it to dim the LED.

In order to convert this value, use a function called map():

outputValue = map(sensorValue, 0, 1023, 0, 255);

outputValue is assigned to equal the scaled value from the potentiometer. map() accepts five arguments: The value to be mapped, the low range and high values of the input data, and the low and high values for that data to be remapped to. In this case, the sensor data is mapped down from its original range of 0 to 1023 to 0 to 255.

The newly mapped sensor data is then output to the analogOutPin dimming or brightening the LED as the potentiometer is turned. Finally, both the raw and scaled sensor values are sent to the Arduino Software (IDE) serial monitor window, in a steady stream of data.

Step 5: Map() Function

The map () function accepts five arguments. The first is the variable to be mapped, the second and third are the input area, and the fourth and fifth are the target area.

map(value, fromLow, fromHigh, toLow, toHigh)

The map() function parameters' meanings are as follows:

value: This is the value we already have and want to map into a new range

fromLow: This is the lower limit of the possible input range

fromHigh: This is the upper limit of the possible input range

toLow: This is the lower limit of the possible output range

toHigh: This is the upper limit of the possible output range

Finally, the function simply returns to us the mapped value corresponding to the output range.

Lets have a look at some examples:

The value provided by analogRead (0 to 1023) is mapped to a percentage (0 to 100).

percent = map(val,0,1023,0,100); // we will receive value from 0 to 100 percent

For example, a typical pot only rotates 270 degrees from end to end, and if you wanted to display the angle of the knob on your pot, then:

angle = map(val,0,1023,0,270); // angle of pot derived from analogRead val

Range values can also be negative (temperature sensors). If you want to display 0 when the pot is centered and negative values when the pot is rotated left and positive values when it is rotated right, you can do this

angle = map(val,0,1023,-135,135); // show angle of 270 degree pot with center as 0

In the next example we will use map() function to show voltage value in serial monitor.

Step 6: Advance Read Analog Values

The previous sketch disadvantage is that values will be printed all the time in serial monitor with 2 ms delay - it is quite irritating.To prevent this, you can use a hysteresis function. The value is only updated if the last digit to be measured exceeds or falls below a specified value. In addition, the example only outputs the measured value at the terminal if it differs from the previous one - when the potentiometer is rotated, the measured value will be outputted at the terminal.

In this way you can display your values professionally.In code we just ad small loop with min. max. Values and hysteresis.

If you receive values from some cheap and inaccurate sensor then you can increase hysteresis value.

Code explained

First we will start the serial communication between Arduino and computer at 9600 bits per second

Serial.begin(9600);

Next, you need to set a variable in the main loop of your code to store the resistance value (which is between 0 and 1023, ideal for an int data type) coming from potentiometers:

int sensorValue = analogRead(A0);

To change the values from 0-1023 in a range that corresponds to the voltage that the pin reads, you must create another variable (a float data type). To scale the numbers between 0.0 and 5.0 V, divide 5 by 1023.0 and multiply the values with sensorValue:

float voltageValue = sensorValue * (5.0 / 1023.0);

Finally we will display this information on the serial monitor.

Floating-point numbers consume lots of memory, and it is more efficient to use integer values. We can upgrade our sketch by using millivolts instead of volts. You can add the following command to your sketch.

Serial.println( (sensorVal * (500000/1023))/100); // print the sensor value in mV

Step 7: Summary

In this tutorial we had learned how to use a serial monitor with digital and analog I/O, and how print different values and parameters in serial monitor.

Additionally you can use constrain function to ensure that a value is always within some lower and upper limit.

constrain(x, min, max) - returns a value that is within the bounds of min and max.

Or you can improve Analog Measurement Precision with a Reference Voltage applied to the AREF pin. To increase precision while reading even lower voltages, we can use a lower reference voltage. For example, when the reference voltage is 5 V, analogRead() represents this with a value from 0 to 1,023. However, if we need to measure only a voltage with a maximum of 1.5 or 2 V, then we can alter the Arduino output to represent 2 V using the 0–1,023 value range to allow for more precise measurement.

As you can see the serial monitor is a great tool to experiment with your project.
Have fun with your experiments!

Be the First to Share

    Recommendations

    • Magnets Challenge

      Magnets Challenge
    • Raspberry Pi Contest 2020

      Raspberry Pi Contest 2020
    • Wearables Contest

      Wearables Contest

    Discussions