Arduino Tutorial (page 2)

  

 

Page 1 At this page (2) Page 3 Page 4 (Examples) Page 5 (Examples)
⚛ Introduction to Arduino ⚛ Ultrasonic Sensors ⚛ Input/Output Port Management Functions (Pins) ⚛ The Flashing LED ⚛ Led Chase Effect
⚛ Supply of necessary components ⚛ Arduino Shields ⚛ Input - Output Functions ⚛ Fade in-Fade out ⚛ Led Chase Effect with potentiometer
⚛ LEDs ⚛ Input/Output Ports (Pins) ⚛ Digital Outputs ⚛ Fade in-Fade out, Blink at peaks ⚛ Effects by detecting light (Led effect + light sensor)
⚛ Buttons ⚛ Power Supply ⚛ Digital Inputs ⚛ Gradual increase and decrease of brightness with a potentiometer ⚛ Using sound (Buzzer)
⚛ Potentiometers ⚛ Arduino (IDE) Installation ⚛ Analog Outputs (PWM pins) ⚛ Using the serial screen ⚛ Sound & Light Sensor
⚛ Piezo Buzzers ⚛ Programming Arduino - Basic Functions ⚛ Analog Inputs ⚛ Playing with colors (RGB Led) ⚛ Moving shafts (Servos)
⚛ Photoresistors (LDR) ⚛ Basic structures and programming functions ⚛ Time Function - delay () ⚛ Making an RGB Led ⚛ Moving Servos with a potentiometer
⚛ Servo Motors ⚛ Type of variables ⚛ Time Function - delayMicroseconds () ⚛ Traffic lights ⚛ Motor Control (DC Motor)
⚛ DC Motors ⚛ Programming Comments ⚛ Time Logging Function - millis () ⚛ Pedestrian traffic lights ⚛ Controlling 2 or more motors
    ⚛ Value Mapping Function - map () ⚛ Pedestrian traffic lights and stop button ⚛ Using ultrasound to measure a distance
    ⚛ The Serial Communication Port (Serial)    
    ⚛ Selection Structure    
    ⚛ Repeat Structure (for)    
    ⚛ Support Libraries    

 

 

Ultrasonic Sensors

The ultrasonic sensor module uses two devices, one to send an ultrasonic signal and one to receive it. So, from the time that elapses from sending until we get the signal back we can calculate the distance to which an object is in front of the sensor. Figure shows a classic such sensor, the HC-SR04 Ultrasonic Distance Sensor.

ultrasonic distance sensor

We use a cable for the source (VCC - 5V), one for GND, one pin to send a trigger and one pin to receive the Echo signal. The Pin for the trigger will be set as output, while the Pin for the echo as an input to the setup () function. Sending a signal is done by sending a voltage to the trigger.

 

DigitalWrite(trigPin, HIGH); // give a voltage, begin to send a signal

DelayMicroseconds(10); // leave some time

DigitalWrite(trigPin, LOW); // relieves the voltage, stops sending the signal

 

While we take time until the signal return to echo with the command

 

Duration = pulseIn(echoPin, HIGH);

 

The calculation of the distance (in cm) is based on the speed of the sound, that is

 

Distance = Duration / 58.138  or Distance = Duration / 58.2

 

The value of 58,138 comes from the manufacturer and results from the speed of the sound. Because the measurements are empirical, detailed observation may give us more detailed values ​​- for example another application with the same sensor suggests division by 58.2 (in the first case we have a trigger for 2μs and the second for 10μs.), and the formula is:

 

Distance = ((HIGH pulse duration) * (sound speed: 340m/s)) / 2

 

We divide with 2 because our signal went and it came back, that is, it has doubled. The pulse duration is given by pulses in microseconds (10-6 sec). As mentioned in http://arduino.cc/en/Reference/pulseIn all these measurements are empirical, so we have deviations.

A classic arrangement is to place the ultrasound sensor on a servo so that we can move it right (servos at 0 degrees), left (servos at 180 degrees) and straight (servos at 90 degrees) with appropriate commands.

 

 

Arduino Shields

Arduino can be expanded with boards called shields and which have built-in circuits to expand with its existing pins. For example, there is WiFi Shield, BlueTooth Shield etc, giving Arduino the functionality that says its name. These shields can be used in a later stage, having understood the basic functions and having reached a satisfactory handling and programming stage, so we will not analyze them here yet.

arduino shields

The only shield we will deal with here is the ArduinoSensor Shield which extends the pins of Ground, Voltage and Pin so that for each pin (either analogue or digital) we have both the source (5V) and the ground (GND) close together.

sensor shield

 

Generally, we recommend finding a starter kit that usually includes a usb cable, breadboard, cables (females and males) as well as enough leds, resistors, capacitors, potentiometer, photosensitive resistors, buttons etc , Such as the Arduino Starter Kite.g.

It is generally acceptable to support the Arduino manufacturers and creators, but at this point it should be noted that similar Arduino implementations, materials and kits, especially those coming from China, are purchased at a much lower cost, including their transport, Can reach even 1/3 of the corresponding value.

 

 

Input/Output Ports (Pins)

The Arduino Uno R3 has 14 digital input / output pins and six analog input pins. The 14 digital ports are numbered from 0 to 13, while six are proportional to the letter A followed by a number from 0 to 5 (eg A3). At the output the pins can give 0 to 5V. Of the 14 digital ports, six, and in particular 3, 5, 6, 9, 10, 11, are also PWM (Pulse Width Modulation), ie they can simulate analogue outputs.

ArduinoUNO pinout

So, briefly on input and output we have:

• For digital input, we use 14 digital 0..13. When they work digitally, the input can be either 0 or 5V, designated LOW or HIGH.

• For digital output, we use 14 digital 0..13. When they work digitally, the output can be 0 or 5V, designated LOW or HIGH.

• For analog input, ie read values ​​between 0 and 5V, we use the six analogue ports A0..A5.

• For analogue output, we can use the six PWM digital ports (3, 5, 6, 9, 10, 11), which will give us an output voltage of any value we want in the range of 0 to 5V.

By writing code we need to initialize the ports we use with the pinMode () function, ie to give the information for which we use if it is for input or output.

When the serial communication monitor is used, the pins 0 and 1 are used for this, so is better that you do not use them in your applications unless necessary (eg, not having the remaining 12 pins for the application).

Also, at Port 13 there is usually a LED already connected to the Arduino Uno board, so we can use it for related functions.

 

 

Power Supply

Arduino can work with power from your computer's USB port or from a stand-alone battery power supply. The unit provides a constant voltage of 5V at its outputs.

To supply power to the unit from an external source, it is done with an external power supply - the recommended operating voltage is 7V to 12V, so it can operate and give 5V at the output constant (see the specifications here). You can connect the power supply directly to the pins for this purpose: (+) in the Pin VCC IN and (-) in the GND next to it.

power-supply and battery

The board can work with an external source of 6 to 20 volts. However, if powered with less than 7 volts, the 5Volt output pin will not be able to output a voltage of 5 volts. Conversely, if we give more than 12 volts, the voltage stabilizer on the board will overheat and may be destroyed. Therefore, an ideal voltage is 9 volts.

If your unit is permanently connected to a USB port, it works seamlessly with the 5V provided by the USB port.

 

 

Arduino Software (IDE) Installation

Now its time to start the installation of the Arduino IDE to your PC. The following instructions shows an installation on Windows 10 PC.

So lets start by downloading the software from the official site. There are two types of downloads for the IDE software, the Installer (.exe) and the Zip packages. If you want to install everything at once, you should download the Installer (.exe) because it contains everything needed and the drivers will be automatically installed. If you choose to download the Zip file, which is the best solution for creating a portable installation, then you have to install the drivers manually. The next pictures shows the installation form the Installer (.exe). 

Now run the Installation. While at the procedure you will get operating system messages. Don't worry, just accept them and proceed.

The first window shows you a list of options, check the options you need and proceed.

Arduino IDE installation window 1

The second window lets you choose the installation directory. Choose another installation directory If you want to, if not just click install button and proceed (recommended).

Arduino IDE installation window 2

Just wait few seconds and the process will install all the required files to run the Arduino Software (IDE).

Arduino IDE installation window 3

Now you can open the Arduino IDE application.

 

Arduino IDE

 

Under Tools --> Board select the Arduino Uno option.

 

Arduino IDE select board

 

Now, Open Device Manager and find the board. Get the number of the COM port.

 

arduinoc om port number

 

Now go to IDE application again, under Tools --> Serial Port select the same COM port that the Device Manager showed.

 

arduino ide select com port

 

Before you start your project, to make sure that everything is working fine, you should load the simplest demo code, the "Blink". This demo doesn't need any extra components to connect to the board. You just load it and run it at File --> Examples --> 01.Basics --> Blink. Click on the Upload icon button and imediately the code will start the complilation of the code and then it will upload it to the IDE board. via the USB cable.

 

arduino ide sketch

 

Once the upload is completed the board start running immediately the code, then you should see the LED marked as "L" on the board to start blinking. That means everything is ok and so you can start constructing your project.

Example

 

 

Programming Arduino - Basic Functions

After installing the Arduino IDE we can write our first code sections.

The Arduino logic is very simple - basically there are two basic functions, setup () and loop (), which work as follows:

• setup () - here we put all the commands that must run once when the unit is turned on (ie, when we turn on the power or when the reset key is pressed). Variable value initializations are usually entered and, in any case, the identification of the inputs/outputs that we will use (ie if a particular pin will be input or output).

• loop () - here we write our program. The commands that exist will run and when it reaches the end, the loop () will resume, continuing from the start, and again. This will happen continuously, as long as Arduino is running or until the reset key is pressed.

Thus, the basic function of Arduino is that run the setup () function at the beginning and then the loop () again and again until it is closed (not supplied with power) or press the reset button.

In the case of Reset, the setup () function is reapplied once and then the loop () again and again, such as when the microcontroller is initially energized. If we have made changes to our program and loaded it into the microcontroller (we will see this procedure below), it is enough to press the Reset key to load our program from the beginning as described.

A typical program has the following structure:

Void setup () {
 / * The commands here will run only on activation or after Reset * /
}
Void loop () {
/ * The commands here will run again and again until the Reset * /
}

 

 

Basic structures and programming functions

Below, are some of the most basic structures and functions that can be used as tools when writing an Arduino program:

Flow Control Structures

  • • if (one-state control structure)
  • • if ... else (multi-condition control structure)
  • • for (repeat condition control structure)
  • • while (conditional repeat control structure)
  • • do ... while (conditional repeat control structure)
  • • switch ... case (case control structure)
  • • break (break command of a repetitive structure)
  • • continue (command to skip the current repeat)
  • • return (return function from a function)
  • • goto (transition to some point of the code)


Numerical Operators

  • • = (assignment operator)
  • • + (addition function)
  • • - (Removal Operator)
  • • * (multiplication operator)
  • • / (splitting operator)
  • • % (remainder of integer division remainder)


Logical Operators

  • • && (logical coupling)
  • • || (Logical disjunction)
  • • ! (Logical refusal)
     

Binary Operators

  • • & (binary coupling)
  • • | (Binary tuning)
  • • ^ (binary exclusive tuning)
  • • ~ (binary denial)
  • • << (binary left shift)
  • • >> (binary right sliding)
     

Enhancers and Reduction Operators

  • • ++ (increase by one integer unit)
  • • - (decrease by one integer unit)
     

Complex Operators

  • • + =, - =, * =, / =,% = (composite numerical operators)
  • • & =, | =, ^ =, ~ =, << =, >> = (complex binary operators)
     

Comparison Operators

  • • == (equality)
  • • ! = (Inequality)
  • • <(smaller)
  • • > (larger)
  • • <= (less than or equal to)
  • • > = (greater or equal)
     

Indicators Operators

  • • * (content acquisition operator)
  • • & (address acquisition operator)
     

Logic Signal Voltage Levels

  • • HIGH (high level value for an input or output contact)
  • • LOW (low-level value for an input or output contact)
  • • false (logical level of falsehood in one condition)
  • • true (logic level of truth in one condition)
  • • INPUT (used to define a contact as an input)
  • • OUTPUT (used to define a contact as an output)
  • • A0, ..., A5 (interfaces for analogue input contacts)


Data Types

  • • boolean (logic binary value)
  • • char (8 digits highlighted)
  • • unsigned char (8 digit non-signed character)
  • • byte (8 digit non-signed character)
  • • int (marked integer 16 digits)
  • • unsigned int (16-digit non-signed integer)
  • • word (16-digit non-signed integer)
  • • long (32-digit integer tagged)
  • • unsigned long (32-digit non-signed integer)
  • • float, double (single precision floating point number)
  • • String (alphanumeric object with useful methods)
  • • The character table can also be considered as an alphanumeric
     

Type Conversion Functions

  • • char (), byte ()
  • • int (), word (), long ()
  • • float (), double ()
     

Input and Output Functions

  • • pinMode () (defines a contact as input or output)
     

Digital Input and Output Functions

  • • digitalWrite () (writes to a digital output contact)
  • • digitalRead () (reads from a digital input contact)


Analog Input and Output Functions

  • • analogReference () defines the analogue reference voltage)
  • • analogWrite () (writes PWM signals to an output contact)
  • • analogRead () (reads by an analog input contact)


Advanced Input and Output Functions

  • • tone () (produces a square frequency signal)
  • • noTone () (stops producing square signals)
  • • shiftOut () (slides the digits of a value into an output contact)
  • • pulseIn () (returns the duration to μs of a HIGH or LOW pulse)


Time Functions

  • • millis () (run time in ms)
  • • micros () (duration of the program in ms)
  • • delay () pause - duration is given in ms)
  • • delayMicroseconds () (program pause - duration is given in μs)


Mathematical and Trigonometric Functions

  • • max () (finds the largest of two numbers)
  • • min () (finds the smallest of two numbers)
  • • abs () (returns the absolute value of a number)
  • • constrain () (checks for overflow or margin overflow)
  • • map () (performs linear boundary transformation)
  • • pow () (returns the result of a force)
  • • sqrt () (returns the root of a number)
  • • sin () (calculates the sine of a number)
  • • cos () (calculates the cosine of a number)
  • • tan () (calculates the tangent of a number)


Pseudo Random Number Generator Functions

  • • random () (a new number is given by the generator)
  • • randomSeed () (sets the seed of the production generator)


Binary Number Processing Functions

  • • lowByte () (returns the right one byte of a variable)
  • • highByte () returns the leftmost byte of a variable)
  • • bitRead () (reads a specific digit of a variable)
  • • bitWrite () (writes to a specific digit of a variable)
  • • bitSet () (writes the value 1 to a digit of a variable)
  • • bitClear () (writes the value 0 to a digit of a variable)
  • • bit () (calculates a specific force based on 2)


Shutdown Service Routines

  • • attachInterrupt () (activates a shutdown service routine)
  • • detachInterrupt () (disables a shutdown service routine)


Stop Activation and Deactivation Functions

  • • interrupts () activates the stop signals
  • • noInterrupts () (disables interrupt signals)


Serial Communication Support

  • • Serial (object of serial communication with useful methods)

 

 

Type of variables

As in all programming languages, you can declare variables names. The types of variables supported in Arduino are many. But for a beginner, the following types will be enough:

  • • boolean, with values ​​0 and 1 (or True/False)
  • • byte, with values ​​from 0 to 255
  • • int, integer with values ​​from -32768 to 32767
  • • long, integer with values ​​from -2147483648 to 2147483647
  • • float, decimal numbers
  • • char, one character (one Byte size)
  • • string, table of characters 


An example of a variable is given below:


Int ledPin = 13; // set intact variable ledPin and initialize its value to 13
Float SinVal; // define real SinVal variable

 

 

Programming Comments

As in all programming languages, you can have comments to make it easier to understand and maintain the code you writing. you can use the two vertices // for a comment on a line (the comment follows and is ignored), or you can use the / * ..  * / for comments written on multiple lines (that is between / * and * / is ignored) .

For example:

 

Int ledPin = 13; // set pin number for LED

/ * In the code below we will program one
LED blinks every 1 sec * /

 

 

Continue to page 3