Ultimaker Cura Add new 3D Printer

TRONXY XY-2 Pro Printer Settings

To add TRONXY XY-2 Pro or any other 3D Printer into Ultimaker Cura, go to add printer. Then, under Add non-networked printer, go to a custom FFF printer, and then name your printer, then click Add.

TRONXY XY-2 Pro Build Plate Shape and Heated Bed

  • In the machine settings set the correct x, y, and z sizes for your build area. For the TRONXY XY-2 Pro, it’s 255, by 255, by 260 millimeters.
  • Set the build plate shape is rectangular
  • Leave “Origin at center” as it is.

TRONXY XY-2 Pro Nozzle Size and Filament Diameter

  • Click on a heated bed selection to heat up the bed automatically.
  • Under Extruder 1, set the nozzle size for your 3d printer (e.g. 0.4mm)
  • Then set the filament diameter (e.g. 1.75)

Read More

DHT11 Humidity and Temperature Sensor

In this tutorial you will learn how to use a DHT11 Temperature and Humidity Sensor with the Arduino, what is DHT11, difference between DHT11 and DHT22, DHT11 circuit diagram with the Arduino, and how to write Arduino code to read DHT11 Temperature and Humidity. Finally, we will introduce the Elegoo DHT11 module.

What is DHT11 ?

The DHT11 sensor is low-cost Temperature and Humidity sensor that is ideal for hobbyists and prototyping applications. The DHT11 temperature sensor range: 0 – 50°C (±2°C) and DHT11 humidity sensor range: 20-80% (±5%). Its Supply voltage: 3 to 5.5V. DHT11 sensor uses a OneWire protocol.  It integrates a thermistor and a capacitive humidity sensor. An integrated ADC converter converts the measured values into a digital signal, which is then output via the OneWire interface.

Range0°C to 50°C (Temperature) 20% to 80% (Humidity)
Accuracy±2°C (Temperature) ±5% (Humidity)
Supply voltage3 to 5.5V
Current consumptionMax. 2.5 mA
Sampling time1 measurement per second
DHT11 Specifications

DHT11 vs DHT22 Specifications

Both DHT11 and DHT22 have the same pin configuration but have different characteristics. The comparison is shown below. In summary, the DHT22 a little more accurate have a slightly larger temperature and humidity range.

 DHT11DHT22 (AM2302)
Voltage (supply and I/O)3 to 5.5V3 to 5.5V
Max current2.5mA2.5mA
Temperature range0-50°C-40 to 80°C
Temperature accuracy±2°C±0.5°C
Humidity range20-80%0-100%
Humidity accuracy5%2-5%
Sampling rate1 Hz0.5 Hz
Physical dimensions15.5mm x 12mm x 5.5mm15.1mm x 25mm x 7.7mm
Pins4 pins with 0.1 inch spacing4 pins with 0.1 inch spacing
DHT11 and DHT22 Specifications

DHT11 Sensor Application

DHT11 is usually used in Weather Stations, HVAC, Dehumidifier, data loggers, humidity regulators, Home Appliances, and Consumer Electronics.

DHT11 sensor circuit diagram

The circuit diagram below shows DHT sensor Arduino circuit. Connect Pin 1 directly to Supply (3.3V or 5V), pin 4 to GND, and Pin 2 to the microcontroller pin with pull-up resistor to the supply voltage.

DHT11 sensor Arduino circuit. Source: Elegoo Inc.

DHT11 and DHT22 Pin Configuration

DHT11 and DHT22 have only three connections: Vcc, GND, and Data. Pin 3 is not connected.

DHT11 Pin configuration
  • Pin 1: Vcc
  • Pin 2: Data
  • Pin 3: NC
  • Pin 4: GND

Parts list (DHT11 Arduino)

The parts required for this tutorial are:

  • 1 Arduino board
  • 1 Breadboard
  • 1 Sensor DHT11 or DHT22
  • 1 Resistor 10k ohm
  • Connecting wires

DHT11 Fritzing Circuit

The figure below shows the DHT11 sensor interfacing with arduino. The DHT11 data pin is connected to the arduino digital pin 2.

DHT11 fritzing circuit

DHT11 Arduino Code

First install DHT sensor library:

In the Arduino IDE, go to Sketch->Include Library->Manage Libraries…

Type DHT11 in the search tab then go to DHT sensor library and click Install

DHT sensor library

After installing DHT sensor library, you should include the header file DHT.h in your program. Then define the Arduino pin for DHT sensor (here it’s pin 2), then select the DHT type (here DHT11) and define dht object. See the DHT11 temperature and humidity sensor Arduino code below.

#include "DHT.h"

// Define DHT pin
#define DHTPIN 2
// DHT11 selected
#define DHTTYPE DHT11 // Other possibilities DHT21, DHT22 

// Define DHT object

void setup()
  // Start Serial at baudrate 9600
  // Start DHT sensor

void loop()
  // Read temperature sensor
  float temp = dht.readTemperature();
  // Read humidity sensor
  float humidity = dht.readHumidity();
  /* Are temp and humidity values valid numbers? */
  if (isnan(temp) || isnan(humidity))
    Serial.println("Failed to read from DHT11");
    // Print out  temp and humidity values
    Serial.print("Temperature: ");
    Serial.print(" °C, ");
    Serial.print("Humidity: ");
    Serial.println(" %");

In the setup routine, the serial interface is configured to print out the measurement on the serial monitor and the DHT sensor is started.

In the main program, the measured values for humidity and temperature are now read in and assigned to the variables humidity and temp. The program then checks whether a valid numerical value has been measured for humidity and temperature. If both measured values are valid, they are printed out on the serial monitor, otherwise an error message is printed out.

DHT11 Serial Monitor

The code shown above remains the same. After wiring the Elegoo DHT11 Sensor with the Arduino. Click UPLOAD to upload the program shown above then open the serial monitor, you can see the data as below: (The temperature is around 23°C the humidity is 59.00 %)

DHT11 serial monitor

Elegoo DHT11 Sensor Module

The Elegoo DHT11 Module integrates the built-in 10 Kohm pull-up resistor. See figure below.

Elegoo DHT11 sensor module

Elegoo DHT11 Pin configuration

The mark S denotes the signal (pin 3).

  • Pin 1: GND
  • Pin 2: Vcc (3.3V or 5V)
  • Pin 3: Output

Elegoo DHT11 Arduino Circuit Diagram

The circuit diagram below shows the DHT sensor Arduino circuit. Since the pull-up resistor is already integrated into the module, connct the data pin directly to the arduino pin 2.

DHT sensor Arduino circuit. Source: Elegoo Inc.
Read More

Arduino Photoresistor

Photoresistor or Light Dependent Resistor (LDR) is used wherever there is a need to sense the absence or presence of light. In this tutorial, you will learn what is photoresistor or Light Dependent Resistor (LDR), LDR interfacing with Arduino, and how to write Arduino code for LDR sensor and LED. We will also introduce the Elegoo 37 sensor kit and its photoresistor module. Finally, intensity control of an LED using LDR and Arduino board code is presented.

What is photoresistor ?

The photoresistor or LDR (Light Dependent Resistor) is a light-sensitive semiconductor element that changes its resistance value according to the intensity of the light: the higher the light intensity on the sensitive surface of the LDR, the smaller its resistance value becomes.

A photoresistor has two connecting wires and can be treated like a variable resistor. The resistance value can be measured with an ohmmeter. The resistor has a very high resistance value in darkness and a very low resistance value in brightness.

LDR circuit

As we already mentioned, the resistance value indicates how much light falls on the photocell. However, the microcontroller cannot measure resistance directly, but it can measure the voltage applied to a resistor. Since the voltage is proportional to the resistor value according to ohm’s law, the easiest photoresistor circuit is to build a voltage divider between a fixed resistor and the LDR. The result is a voltage that changes according to the light intensity. The voltage drop across the resistor is connected to the analog input of the Arduino as shown below.

If the photoresistor is subjected to high light intensity, its resistance becomes small in relation to the fixed resistor. There is less voltage at the smaller resistor than at the larger one. In the following circuit, this means that we will measure a voltage value close to 5V at Arduino pin A0 at sun light for instance. In complete darkness, almost the entire voltage is applied to the photoresistor, and we measure voltage close to 0V.

LDR connection with Arduino

Photoresistor Arduino code

Below is an LDR Arduino code that measures the analog value of the LDR and prints it on the serial monitor. The purpose is to determine the analog value on which the room is dark or bright. Simply cover and uncover the LDR with your finger and monitor the value on the serial monitor.

Try to find out at which value the room is considered dark! The reason to do it this way because you might not be able to find the datasheet of your specific LDR. And to choose an appropriate value for your application without having to determine the illumination in lux.

#define LDR_PIN  A0 // LDR pin
unsigned int photoresistor = 0; // LDR_PIN value

void setup() { 

void loop() {
  // Read analog value of the LDR
  photoresistor = analogRead(LDR_PIN);
  Serial.println(photoresistor); // Print on serial monitor 
  delay(1000); //Delay 1 second

Arduino LDR LED code

The Figure below shows the LDR connection with Arduino. The LDR circuit is connected to the Arduino analog pin A0. And an LED is connected to digital pin 13. The LED here is a representation of a lamp. You can replace the LED with a relay with transistor circuit, and the code remains the same.

Photoresistor circuit Arduino

Below is an Arduino code for LDR sensor and LED. This Arduino LDR LED code measures the analog value of the LDR and compares it with a threshold value (that you have already determined). If the LDR value is below the threshold, the LED turns on.

#define LED_PWM_PIN  13 // LED pin
#define LDR_PIN  A0 // LDR pin
unsigned int photoresistor = 0; // LDR_PIN value
const unsigned int thrLDR = 300; // Threshold for LDR

void setup() { 

void loop() {
  // Read analog value of the LDR_PIN 
  photoresistor = analogRead(LDR_PIN);
  // is LDR analog value greater than Threshold ?
  if (photoresistor < thrLDR) {
    digitalWrite(LED_PWM_PIN, HIGH); //Turn LED on
    digitalWrite(LED_PWM_PIN, LOW); //Turn LED off

  delay(1000); //Delay 1 second

Elegoo 37 sensor kit

The Elegoo 37 sensor kit contains 37 sensors and other electronic components that are combined together in a high-quality and nice plastic box. The benefit of buying such a kit is that the sensor circuits are already built for you so that you can concentrate on the code and your application.

Elegoo photoresistor

The Elegoo photoresistor module is a breakout board for the LDR circuit as shown below. Its LDR Resistance in darkness can go higher than 20 Megohms and as low as 80 Ohms in sunlight. The fixed resistor is 10 kOhm.

Elegoo photoresistor

The pin marked with – should be connected to GND, the middle pin should be connected to VCC, and the pin marked with S should be connected to Arduino analog pin.

Intensity control of LED using LDR and Arduino

Arduino LDR LED

In the previous code, the Arduino make a digital decision to turn the LED on or off if the room is dark or not. In this Arduino LDR example, we will use Arduino analog read and PWM output to change the intensity of the LED with respect to changes of the LDR brightness using Arduino map. Finally, it print out the LDR and LED PWM values. If the result is not satisfying, tune the values: 1023 and 255 for your application.

#define LED_PWM_PIN  9 // LED PWM pin
#define LDR_PIN  A0    // LDR analog pin
unsigned int ValLDR = 0, ledPWM = 0; // LDR and LED values

void setup() { 

void loop() {
  // Read analog value of the LDR_PIN 
  ValLDR = analogRead(LDR_PIN);

  // Map LDR to PWM range
  ledPWM = map(ValLDR, 0, 1023, 0, 255);
  // Set PWM to the LED pin
  analogWrite(LED_PWM_PIN, ledPWM);
  Serial.print("LDR value: ");
  Serial.print("       "); 
  Serial.print("LED PWM vlaue: ");

  delay(1000); //Delay 1 second
Read More

Arduino Analog

After reading this tutorial, you will understand the basic of Arduino analog pins: What they are, how to use them as input or output, how to analogRead, and how to analogWrite. Also, we present the concept of Pulse-width modulation (PWM).

What is Analog ?

Analog signals are the signals in our “analog” world. The temperature, for instance, can be expressed in
an infinite set of values: e.g. 25°C, 25.1°C, 25.12°C, 25.123°C, 0°C, -4°C, -4.7°C, etc.

Analog temperature sensors provide analog voltage as an output signal, which corresponds to the measured temperature. Let’s consider the temperature sensor LM35. It measures the surrounding temperature with a linear scale of 10 mV/°C.

The 5V Arduino Boards reads and processes analog signals in a voltage range from 0 to 5 volts. The microcontroller of the Arduino board has an internal Analog-to-digital converter (ADC) for processing the analog input signals. The Arduino Uno, for instance, has six analog channels, in which six analog voltages (i.e. sensors) can be processed in parallel. The ports available for this purpose are labeled A0 to A5 on the Arduino Uno.

The resolution of its ADC is 10 bits. The 10-bit resolution corresponds to 210 = 1024 values. With a reference voltage of 5 volts, input signals from 0 to 5 volts can be read in, which are digitized by the ADC into values from 0 to 1023. This results in an accuracy of 5 V / 1024 = 4.9 mV

This 5V reference voltage is generated from the supply voltage and can be changed with the analogReference command. However, this command is not covered in this article.

Arduino analogRead

The Arduino analog read is done using analogRead() function by passing the analog pin as the function parameter. In the following instructions, the analog port A0 is read in and the resulting raw ADC value is then stored in the variable rawADC.

unsigned int rawADC = 0;
rawADC = analogRead(A0);

Now, let’s write the first analog sketch. The following circuit diagram depicts a potentiometer (variable resistor) connected to the Arduino analog pin A0.

Potentiometer circuit diagram

In the following sketch, the analog port A0 is read in and the resulting raw ADC value is then stored in the variable rawADC. Consequently, the program prints out the rawADC value on the serial monitor. Now, by rotating the potentiometer from fully clockwise to fully counter-clockwise, you will see that the ADC value alters between 0 and 1023, which corresponds to 0 V to 5V, respectively.

unsigned int rawADC = 0;    // variable for analog value

void setup() {
    Serial.begin(9600); //Init serial @ 9600 baudrate

void loop() {
  // read the analog raw value:
  rawADC = analogRead(A0);

  // print to the Serial Monitor
  Serial.print("Potentiometer value = ");

  delay(1000);        // Wait 1000 ms

LM35 Arduino

The LM35 temperature sensor measures the temperature with a linear scale of 10 mV/°C. This means that each one degree Celsius is 10 mV. Thus, the equation to convert between raw ADC to degree Celsius is

Temperature [°C] = (rawADC/1024) * 5 * 100

The figure below shows the LM35 pinout for the TO-92 package from the LM35 datasheet. Simply connect pin 1 to 5V, pin 3 to GND, and pin 2 to an analog port.

LM35 pin diagram. Source: Texas Instruments

The following circuit diagram depicts an LM35 sensor connected to the Arduino analog pin A0.

LM35 interfacing with Arduino

In the following sketch, the temperature sensor LM35 is connected to the Arduino analog pin A0. The resulting raw ADC value is then stored in the variable rawADC. The temperature is then calculated according to the equation mentioned above and finally printed on the serial monitor.

// Define senor pin and variable for temperature
#define TEMP_SENSR_PIN  A0
double temp, rawADC;

void setup()
    Serial.begin(9600); //Init serial @ 9600 baudrate

void loop()
    // Read analog raw value
    rawADC = analogRead(TEMP_SENSR_PIN);
    // convert to degree celsius
    temp = (rawADC/1024.0) * 5.0 * 100.0;
    // Print temperature in °C
    Serial.println("°C ");

    delay(1000);        // Wait 1000 ms

Arduino analogWrite

The Arduino outputs analog signals by means of pulse width modulation (PWM). With this technique, an analog signal can be generated by generating a digital signal, alternating between HIGH and LOW, with variable pulse time.

Due to the variable times of the HIGH phase (pulse time), an analog voltage between 0 to 100% (0V to 5V) can be generated. Think of it as the resulting average voltage. The PWM register is 8 bits, i.e. values from 0 to 255 (28 -1), which corresponds to an analog voltage between 0 to 5V.  The Arduino Uno default PWM frequency is 490 Hz, which corresponds to a period T = 1/frequency, which equals around 2 ms. So within this period, we control the percentage of output high to the complete period. This percentage is called the duty cycle.

PWM signal. Source: wikipedia.org

The PWM is usually used to control motors, servos, or the brightness of an LED, etc. The Arduino Uno PWM pins are 3, 5, 6, 9, 10, and 11. They are the same for Arduino Nano and Mini.

The output of an analog voltage by means of PWM is done with the function:

 analogWrite(Pin, Value)

The parameter Pin defines the PWM pin and Value defines duty cycle in an integer value between 0 and 255 (corresponds to 0% to 100%) as function parameters. For instance, Value = 128 represents a 50% duty cycle and 2.5 V.

Arduino map

Consider the following circuit diagram, a potentiometer (poti) is connected to the Arduino analog pin A0 and an LED connected to port 9.

Arduino LED and Poti circuit diagram

The sketch below is written to read the analog voltage from the poti, map the analog range (0 to 1023) to the PWM range (0 to 255) using the Arduino map() function and finally output PWM to dim the LED. As a result, the LED changes its brightness as you rotate the poti.

// Port for PWM and variable for the PWM value
#define PWM_PIN 9
#define TEMP_SENSR_PIN  A0

unsigned int valuePWM, rawADC = 0;

void setup()
    // Set port 9 as PWM output
    pinMode(PWM_PIN, OUTPUT);

void loop()
    // Read analog raw value
    rawADC = analogRead(TEMP_SENSR_PIN);
    // Map analog raw range to PWM range
    valuePWM = map(rawADC, 0, 1023, 0, 255);
    // Set PWM to the pin
    analogWrite(PWM_PIN, valuePWM);

Arduino PWM to analog

As mentioned already, the PWM is not an actual analog signal. Rather, the resulting average voltage seems to be analog. Fortunately, combining the output PWM signal with a low-pass filter creates an analog signal as shown in the following circuit diagram. This circuit consists of an RC circuit and a buffer.

PWM to analog converter
Read More

Arduino Digital

After reading this tutorial, you will understand the basic of Arduino digital pins: What they are, how to configure them as input or output, how to digitalRead, and how to digitalWrite. Also we present, briefly, the concepts of debouncing, and pull-up & pull-down resistors.

Digital Inputs

Arduino digital pins know only two states: HIGH voltage (1’s) and LOW voltage (0’s), where 1 corresponds to a voltage of 5 volts and 0 to a voltage of 0 volts. The signals to be read in at the digital inputs come from other digital circuits such as push-button or limit switch, or sensors with digital outputs.

pinMode input

The digital pins of the Arduino microcontroller are programmed as inputs by default and have a high input impedance. No configuration needs to be done for an input. In most programs, however, inputs are defined with the pinMode().

As already explained in Arduino Sketch, the configuration is done in the setup() function.

void setup()
  pinMode(12, INPUT); // Set pin 12 as input

Pull-up and Pull-down Resistors

A pullup or pulldown resistor is used to provide a clearly defined signal (LOW or HIGH) at the input pin. Without a pullup or pulldown resistor, noise on an open input pin can cause Distortion so that false signals are detected by the microcontroller.

If you want to read the status of a switch, for example, a limit switch from a robot, the pullup or pulldown resistor should be connected. This is necessary so that the input has a fixed potential if the switch is not activated, to avoid the so-called floating state, where the actual voltage is not recognized as high nor low.

Pull-up Resistor

The figure below shows the connection of an Arduino input pullup resistor. If the 10kΩ resistor were replaced with wire, there would be a short circuit between 5V and GND pins when pressing the switch. In addition, the signal could no longer be determined correctly due to interference. The pullup resistor ensures that the signal is “pulled up” to VCC.

Pull-up Resistor

Internal Pull-up Resistor

Instead of connecting a pullup resistor, an internal pull-up can be enabled. This configuration is then done in the setup() using the pinMode function by passing the parameter INPUT_PULLUP. The next figure represents the Arduino internal pullup resistor.

void setup()
  // Set Port 2 as input and enable pullup resistor 
  pinMode(2, INPUT_PULLUP); 
Internal Pull-up Resistor

Pull-down Resistor

The figure below shows the connection of the Arduino input pulldown. It has the same concept as the pull up resistor, except that the read value is 0 V when the switch is not pressed. The pulldown resistor ensures that the signal is “pulled down” to GND.

Pull-down Resistor


Reading the value for a digital input is done using digitalRead(PinNumber). The read result is always a value HIGH or LOW. The Arduino Uno digital pins are in the range from 0 to 13.

int switchVal;           // variable for switch

void setup()
  pinMode(12, INPUT); // Set pin 12 as input

void loop()
  switchVal = digitalRead(12);     // Read pin 12

The PinNumber can be passed directly as a number in the pinMode function or passed as a Define or variable initialized at the beginning of the Arduino Sketch.

#define SWITCH_PIN   2   // Define input pin
int switchVal;           // variable for switch

void setup()
  pinMode(SWITCH_PIN, INPUT); // Set SWITCH_PIN as input

void loop()
  switchVal = digitalRead(SWITCH_PIN); // Read switch state


When reading digital signals from switches or push-buttons, it often happens that several signals with HIGH and LOW are read when the button is pressed. This behavior is called “bouncing”. As a result, the Arduino thinks that the switch is pressed several times.

The bouncing behavior can be suppressed by means of debouncing. The debouncing can be done on

  • hardware level (debouncing circuit)
  • software level (debouncing code)
Debouncing circuit

One of the debouncing circuits is the RC circuit, which consists of resistor (R) and capacitor (C). Here R2 and C1 act as a so-called low pass filter. The resistor R1 is the pull-up resistor.

RC Circuit
Debouncing code

Instead of using extra components for the debouncing circuit, the bouncing issue can be solved using the software. The simplest way is to use a small delay after the digitalRead as below. Choose a value between 10 and 50 ms.

  // read button state
  buttonSt = digitalRead(BUTTON_PIN);
  // Delay 50 ms for debouncing

A more robust way is to use Arduino debounce code, available in the Arduino IDE under File/Examples/02.Digital/Debounce.

This example implements the hysteresis by using the millis() function to update the button state after milliseconds since the last time the push-button pressed. It reverts the LED state each time the button is pressed.

Digital Outputs

The digital outputs of the Arduino are the signal transmitters to the outside world, which control LEDs, relays, etc. The outputs provide digital signals, i.e. 1 and 0 or HIGH and LOW. The voltage levels are 5 volts for HIGH and 0 volts for LOW. Of course, for 3.3 V Arduino, the output signals at signal HIGH are 3.3 volts.

The Arduino Uno maximum current for digital I/O is 40 mA. This current allows the direct control of an LED with a series resistor. The control of components such as relays, lamps, or motors requires an additional driver circuit that uses transistors or driver IC.

Arduino digitalWrite

Any of the Arduino Uno digital pins (0 to 13) can be initialized as output or input. An output pin must be initialized as output in the setup(). The output voltage is set to HIGH or LOW in the loop() for the application use, as shown in the blinking LED sketch.

Arduino read digital output

In some applications, we would like to read the current state of a specific digital output pin. One solution is to connect another input port to the output port we want to check. However, this solution requires reserving additional digital ports for this simple check!

A better solution to read the output pin with digitalRead(), although it is defined as an output. We wrote the sketch below to present this concept. The LED 1 follows the state of the push button. Next, the program waits 1 second. Subsequently, we read the actual state of LED 1 using ledSt = digitalRead(LED_PIN1) and pass it to LED 2 using digitalWrite(LED_PIN2, ledSt).

#define BUTTON_PIN  2    // Push-button pin
#define LED_PIN1   12    // LED 1 pin
#define LED_PIN2   13    // LED 2 pin

int ledSt = LOW;          // Current LED state
int buttonSt;             // Current button state

void setup()
  // Set LED 1 and 2 as outputs
  pinMode(LED_PIN1, OUTPUT);
  pinMode(LED_PIN2, OUTPUT);
  // Initialize pin 12 and 13 as low
  digitalWrite(LED_PIN1, LOW);
  digitalWrite(LED_PIN2, LOW);

void loop()
  // read button state
  buttonSt = digitalRead(BUTTON_PIN);
  // Delay 10 ms for debouncing

  // Set LED 1 as button state
  digitalWrite(LED_PIN1, buttonSt);
  // Dealy 1000 ms
  // Read LED 1 state
  ledSt = digitalRead(LED_PIN1); 
  // Set LED 2 as LED 1
  digitalWrite(LED_PIN2, ledSt); 

Read More

Arduino Testing

Test Arduino code

The testing of the software and hardware is carried out in several steps. During code programming, the programmer can check the syntax errors using the compiler directly in the Arduino IDE (using Verify button). However, this syntax error check does not give any indication of incorrect structuring or sequence of the program.

Testing the correct sequence of the code should be done directly on the board with external components connected. However, it’s a good idea to perform a hardware test for each component by writing small test programs for each external component individually.

By connecting all hardware parts and running the whole program for the first time, the first important test is done. Often the built solution does not run or runs partially faulty during the first tests. Now the debugging of the individual actions and functions of the program begins.

The display of individual variable values or signal states within the program sequence can be realized using the serial monitor by outputting the desired values to the serial interface. In the console the data are displayed during the program run and support the programmer in troubleshooting.

Arduino serial monitor

The serial monitor is a useful tool within the Arduino IDE and allows the display of the transmitted data via the serial port. When you open the Serial monitor, via the toolbar or Tools->Serial Monitor, a new window opens a new window without any content.

Serial Monitor

The serial monitor can now be used to receive data from the Arduino or to send data. To show data from the Arduino on the serial monitor, the Arduino Board must execute serial print instruction as shown in the example below.

void setup()
  // Initialize serial at baudrate of 9600

void loop()
  Serial.println("Hallo world");

Serial.begin(9600); instruction initialize the serial transmission with a transmission rate (called baud rate) of 9600 bits per second. This should match the baud rate on the serial monitor window in order to see sent data.

char letter = '0';

void setup()
  // Initialize serial at baudrate of 9600
void loop() {
  if (Serial.available() > 0){
    letter = Serial.read();
    if(letter == 'A'){
      Serial.println("Letter is A");
    else if(letter == 'B'){
      Serial.println("Letter is B");

Serial.begin(9600); instruction initialize the serial transmission with a transmission rate (called baud rate) of 9600 bits per second. This should match the baud rate on the serial monitor window in order to see sent data.

To receive the data from the Arduino board, the instruction Serial.println( ); is used to print out what’s inside the brackets on the serial monitor. For sending data from the serial monitor, write a text in the input field and press the button Send or press Enter.

Debug Arduino code

Where programming is done, errors occur. You will notice this quickly when you first lines of code for your Arduino board. A missing semicolon or a forgotten declaration and the IDE complains when compiling the program code. With smaller projects, you usually found the error quickly and fixed it then recompile again. Such errors are called compile errors.

But an error does not necessarily mean a missing semicolon or a typo in the code. Another type of error is called runtime error, where your program compiled successfully but your project does not work as expected.

Possible causes can vary: In the program structure a function is not called, a wrong formula used in the calculations, or even a variable declared with a wrong data type.

The approach to look deeper into the code to find the error is called debugging. The first important step is to make sure that the external components like a sensor or limit switch are wired properly. Second, check that they deliver correct values or signals. This can be tested using small sketches to check that they are functioning correctly.

Another way is to inject debugging instruction inside the code. One example is to use Serial print to print out sensor values or Computation output on the serial monitor. This way you can see what and where is things going wrong.

#define DEBUG

#define SENSOR_PIN  A0  // Sensor analog input pin 
#define PWM_PIN       9      // PWM output pin

int valSensor= 0;        // variable for sensor value
int valPwm= 0;        // variable for PWM output value

void setup()
  // Initialize serial at baudrate of 9600
  #ifdef DEBUG
    Serial.println("Debugging aktiviert");


void loop()

   // read the sensor value
  valSensor= analogRead(SENSOR_PIN);
  // map to PWM range
  valPwm= map(valSensor, 0, 1023, 0, 255);
  // Update the PWM value:
  analogWrite(PWM_PIN, valPwm);

  #ifdef DEBUG
    // Print on the Serial Monitor:
    Serial.print("sensor value = ");
    Serial.print("t PWM output value = ");

  // wait 500 milliseconds

By defining DEBUG, the values can be checked on the serial monitor. Once done with debugging, undefine DEBGU (replace #define with #undef) and no output is sent to the serial port.

Digital states can be visualized not only by the output on the serial monitor but also using LEDs. For this purpose, connect an LED and series resistors on the required port of the Arduino board. Then the LED will turn-on or off according to the actual voltage on the ouput pin.

Read More

Arduino Functions

Functions in Arduino

A function is a closed unit within a program and is called by its name. Usually with the function call still values are passed, which are processed then within the function. These values are called “parameters”. After execution of the function, which can be a calculation, a conversion or a signal output to an output port, this “small program” is executed and the main program, which called the function, is continued.

Often, however, the called function returns a response (called function return). This can be the result of a calculation or a status of a state.

Function Structure

The structure of the function is as follows:

Type FunctionName (type parameter){
//Function body
rerun val;

An example looks like this:

Function Structure

The type of a function indicates what kind of value is returned from the function. This can be int, char, etc. Accordingly, the data type of this return value is specified in the call of the function before the function name. The call of a function is usually made from the main program.

Arduino Function Example

Program 1

Program 1 shows the call of the function sensorRead from the main program (loop). The return value is the analog value with the int data type. For a function that does not have a return value, the keyword void is used for the type designation.

Program 2

In Program 2, the loop calls the function sensorReadPrintSerial which has no return value and no input parameter. Consequently, this it calls another function printVal, which has an input parameter an no return.  

Read More

Arduino – Variables and Datatypes

Arduino Variables

In programming, values that are stored for further processing are named with a single word called a variable. The value of a variable can change continuously or be changed by the program. The variable name should be chosen in such a way that it is easily readable and understandable within the program. In addition, a variable also has a data type that defines the value range.

The Variable must be declared before being used. So the data type, the variable name and the value of the variable are set. If no value is specified, the variable value is set to 0.

datatype Variable_Name = Value;


int motorSpeed = 255;

Comprehensible variable names such as motorSpeed or temperatureSensor improve the readability of the program

Arduino Datatypes

A data type describes the value range and the possible operations of a variable. Since the data types of the variables require different amounts of memory, you must be aware of exactly which possible values a variable defined can have when creating the program: Is it only a digital state with the values yes and no or can the variable hold an entire text? The data type must be selected accordingly. The most important data types and their value ranges for creating Arduino programs are listed below:

Data typeValue range    Memory requirement  Explanations/Notes    Examples
booleantrue/false1 byteValue for Yes/No or On/Off,  boolean machineStatus = true;  
int-32,768 to 32,7672 bytes  Integer values for values without decimal places  int potiValue = 1023;  
unsigned int  0 to 4,294,967,295    2 bytesInteger for positive values without decimal places  int tempValue = -5;  
byte0 to 2551 byteLow values (and correspondingly small memory requirements)    byte brightnessLED = 126;  
wordUnsigned 16-bit or 32-bit16-bit on Atmega boards.
32-bit on Due and Zero
Be aware of processor usedword value = 1500;
long-2,147,483,648 to 2,147,483,6474 bytesInteger numbers with big values        long offset = -15362;  
unsigned long0 to 4,294,967,2954 bytesUnsigned Integer numbers with big values  unsigned long secondsPassed = 45379;
float-3.4028235E+38 to 3.4028235E+384 bytesValues with decimal places  float voltageValue = 3.3;  
double-3.4028235E+38 to 3.4028235E+384 bytes-3.4028235E+38 to 3.4028235E+38double distanceGPS= 722.54;  
char  -128 to 127  1 byteValue for storing one character  char charR = ‘R’;  
unsigned char  0 to 2551 byteUsually used with numbers having range 0 to 255unsigned char charNumber = 255;
stringlength depends on definitiondepends on needStrings like texts or several charactersstring brand[ ] = “ROBOSANS”;
arraysize depends to definitionDepends on array sizestore values in variables with table form like e.g. lists of ports or configuration valuesint portsPWM[ ] = {3,5,6,9,10,11};
Arduino Datatypes

Read More

Arduino Sketch

What is Arduino Sketch ?

The code that runs on Arduino is usually called “Sketch”. Getting started with Arduino programming is quite easy because the structure of the Sketches is clear. The Arduino programming language is derived from C++ programming. You only need a few lines of code for your first simple projects.

Arduino Sketch Structure

The structure of an Arduino program is divided into two parts: setup() and loop().

Arduino Sketch Structure

The setup function is executed only once when the Arduino board is started or after a reset. In this function basic settings like variable declarations, the configuration of ports, or initialization routines. Additionally, the inputs and outputs are set, as shown in the Blink example below, the led pin 13 is set as output.

Arduino blinking LED Sketch

The setup function is mandatory and must always be present, even if no declarations have to be made. In this case, the function remains empty.

The loop function is the second area of the basic structure of an Arduino program and has the task of the main program. After the setup function has been executed once, the loop function is run through – as its name implies, as an endless loop. In the loop, all further instructions and function calls are accommodated, which are needed in the normal operation for the desired application. As in the blinking example, it turns on the LED, waits one second, turns it off, waits one second, and repeats forever.

Arduino Examples

The easiest way to get started is to work through example programs and then modify and extend them for your own applications. Also, you can find a lot of Arduino sketches and even complete projects for your application on the internet. One Arduino code example is called AnalogInOutSerial shown above.

AnalogInOutSerial Arduino example

It sets the pulse width modulation (PWM) of an output pin (9) based on the analog input readings on pin (A0), after mapping from the ADC scale (0 to 1023) to the output PWM scale (0 to 255). It also prints out the results on the Serial Monitor. The circuit diagram for this code is shown below

Read More

Arduino IDE

The Arduino IDE is a complete development environment containing code editor, documentation and a number of examples as well as standard libraries.

Arduino Software Setup

For the development of the Arduino programs, the Arduino integrated development environment (IDE) should be installed on the local computer. It can be downloaded free of charge from the Arduino website.

In addition, a USB driver must be installed and configured. This driver enables the USB port to communicate as a serial port with the FTDI chip on the Arduino board. The software is available in the archive file of the development environment and must be installed after the installation of the development environment.

Arduino Serial Port

Communication between the IDE takes place via the virtual COM port that has been set up, using the USB interface as the physical transmission medium.

  1. Connect the Arduino to the computer via a standard USB. After connection, power supply is applied to the board from the USB interface.
  1. Open the Arduino IDE. Select the Arduino board via the menu item Tools->Board.
Selecting the Arduino Board on the IDE
  1. Select the serial port (COM port) via the menu item Tools->Port. Note that the serial port to be used only appears in the listing if the Arduino board is connected to the computer via USB cable.
Selecting the com port on the IDE

Arduino blinking LED

For the first function test and the first executable Arduino program, various example programs are already stored in the IDE.

  1. Open the Blink program via Files->Examples->Basics. This test program controls the digital output port 13 of the Arduino (an LED is already connected on the board), blinks every second.
  2. Compile the program via the menu item Sketch->Verify/Compile.
  3. Upload the code to the Arduino’s microcontroller via Sketch->Upload into the microcontroller on the Arduino board.

Another way to compile (Verify) and upload the code is to use the symbols: to verify and to upload.

Read More
error: Content is protected !!