Arduino Tutorial (page 3)

  

 

Page 1 Page 2 At this 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    

 

 

Input/Output Port Management Functions (Pins)

As mentioned, the main function of the microcontroller is to control its ports and either to power or to take power from them. In the initialization of each program (within the setup function) we will need to characterize the Pins we use as input or output.

The pinMode (Pin, Mode) function uses its name and arguments a) the pin number and b) the mode of operation marked by the word INPUT or OUTPUT.

As is already mentioned we have 14 digital Pins, 6 of which are PWM, with names 0..13 and six analogs with the names Α0..Α5.

For example:

PinMode(12, OUTPUT);
PinMode(ledPin, OUTPUT);
PinMode(A2, INPUT);

 

 

Input - Output Functions

To be able to power out through a pin, it must first be set as output as we saw in the previous paragraph. Then, using the appropriate command, we can always give the desired output voltage.

Correspondingly, in order to "read" from an input, we should initially define it as input and using the appropriate function of each function to read the corresponding value.

 

 

Digital Outputs

All 14 Arduino pins can work as digital outputs, ie output 0V or 5V. This is done by using the digitalWrite (Pin, Value) function, where the pin argument refers to the port number for which we will output an output voltage, while the output voltage can be 0V or 5V, represented by default values ​​in Parameter value:

  •  
  • • LOW: will give 0 V to the output (pin)
  •  
  • • HIGH: will give 5 V at pin (pin)

 

For example:

 

DigitalWrite(ledPin, HIGH);

 

Note: The corresponding port should be set as an output to the setup () procedure, using the pinMode function.

 

For example:


PinMode(10, OUTPUT);

 

 

Digital Inputs

All 14 Arduino digital pins can work as digital inputs, that is, they can read as input voltage with either 0 or 5V. This is done by using the digitalRead (Pin) function, where the Pin argument refers to the port number for which we will enter and the function returns its input value by its name. The input voltage can be 0V or 5V, which are represented by predefined values ​​at the reading we read:

 

  • • LOW: when it receives 0V at pin (pin)
  •  
  • • HIGH: when receiving 5V at pin (pin)
  •  

For example:

 

Val = digitalRead(ledPin);

 

Note: The corresponding port should be set as an input to the setup () procedure, using the pinMode function.

For example:

 

PinMode(10, INPUT);

 

 

Analog Outputs (PWM pins)

Some of the 14 Pins of Arduino have the PWM indication, ie they can simulate the analog output via pulse code modulation.

Thus, with values ​​from 0 to 255 we simulate (in proportion) the interval from 0 to 5V. This is done by using the analogWrite (Pin, Value) function, where the pin argument refers to the port number for which output current will be given, and the output voltage ranges from 0 V to 5 V, which voltage values ​​are analogously represented with values ​​in the variable value. Value 0 gives 0V to the pin output, value 255 gives a 5V voltage to the pin output. By analogy, we can give intermediate voltages (eg 122 for 2.5V voltage) by programming the Arduino microcontroller.

For example:

 

AnalogWrite (ledPin, 122);

 

Reminder: This function can only support PWM pins and not all digital ones. PWM pins are 3, 5, 6, 9, 10, 11.

 

Caution: The corresponding port should be set as an output to the setup () procedure, using the pinMode function.

 

For example:

 

PinMode (10, OUTPUT);

 

 

Analog Inputs

Arduino has 6 analogue inputs, marked with the symbols A0, A1, A2, A3, A4, A5. We can connect an analog component (eg. a potentiometer) and read it as an input. This is done by using the analogRead(Pin) function, where the Pin argument refers to the port number for which we will enter, while the function returns its input value by its name. Entry value ranges from 0 to 1023. We usually use a variable to enter the value.

 

For example:

 

Int r = analogRead(A1);

 

Note: The corresponding port should be set as an input to the setup () procedure, using the pinMode function.

 

For example:

 

PinMode (A1, INPUT);

 

Time functions

In most of our programs we will need to manage or record time. For this purpose there are corresponding functions that help us.

 

 

Time Function - delay ()

In most of our programs we will need to manage or record time. For this purpose there are corresponding functions that help us. In our program we can set a delay to last for the time that we define an event. This is achieved by using the delay (time) function where in the time position we give the time in ms (1/1000 sec). The delay (time) command means that our time-lapse program stops at this point.

For example:

 

Delay (1000); // stops running the program for 1000 ms = 1 sec
 

Delay (500); // stops execution at this point for 500 ms = 0.5 sec

 

 

Time Function - delayMicroseconds ()

Exactly as with the above delay function, we can use delayMicroseconds (), where the delay time is now given in microseconds (1/106 sec).

 
For example:

 

DelayMicroseconds (10); // stop execution for 10μsec = 1/100000 sec

 

 

Time Logging Function - millis ()

Arduino has a built-in clock that counts the time since it is turned on (or reset). This information is available to us at any point by calling the millis() function, which returns our time in milliseconds (1/1000 sec) that has passed since the activation of our unit. This helps us to measure time in our programs, especially in cases where we want to "remember" things.

For example, if we want to check if a certain time has elapsed since something happened (eg, a last key was pressed), we can record the event in a time variable and this time take it away from the next one.

For example:

 

LastPress = millis ();
 

If (lastPress - millis ()> 1000) {...}

 

 

Value Mapping Function - map ()

Many times we will need to assign a value belonging to a value field to another value belonging to another value range. This mathematical act is relatively simple, but Arduino provides us with a function to do this, the

Map (, , , , )

where

is the value we want to convert
is the lower limit of the original value interval
is the upper limit of the original value interval
is the lower limit of the range of the final value (I want to convert)
is the upper limit of the final value (I want to be converted)

For example:

 

Val = map (wave, 0, 1023, 0, 179); / * I convert an analog value I read from a potentiometer (0 to 1023) to a value for a servo (0 to 179) * /

 

 

The Serial Communication Port (Serial)

Arduino provides a serial communication port between the board and the computer or any device we want. For this purpose, using a USB cable (when it comes to the computer) or pins 0 and 1 is used when we want a more specialized connection (eg with another device). For this reason, it is suggested that if it is not necessary in our applications, do not use these pins. In order to activate the serial communication port, it is enough to give the setup () the Serial.begin command (BaudRate), where BaudRate expresses the rate at which the bits will be transmitted (a value of 9600 is usually enough).

 

For example:

 

Serial.begin (9600);

 

We can use the serial port in applications for two-way communication, ie to send and receive data. A simple case of using this communication is to debugging our programs, so we can see what prices give us the counters and what values ​​our variables have through the serial communication screen. A command that helps us with this is print(), which prints a message or values, or println() that works exactly the same but printing with a line break at a time.

 

For example:

 

Serial.print ("Connection Closed"); / * Will display this message on the screen without changing the line after * /

 

Serial.println (distance); / * Will display the value of the variable distance on a line * /

 

When you have connected your Arduino to the USB port on your computer, the serial screen is activated by the top icon "Serial Screen" (Figure 2), and in the window that opens you can see all the messages sent from the loaded code Already running on the board.

 

Serial Screen

 

 

Selection Structure

In programming many times we will need to review a condition to decide whether to run a piece of code or run another piece of code. We do this by using the selection structure, which is compiled as: If {} and Else {}

We have the kind of control we want to make, usually by using comparison operators (>, <, =, <>,> =, <=), e.g. (potVal > 300). The condition may be even more complex, using the logical operators (|| for H ', && for KA), e.g. (potVal > 300) && (timePass > = 2000).

The {commands} block executes the commands we want in each case respectively. If is true, the first commands will be executed, if not true then the second commands will be executed, but In any case, the last piece else {} does not have to exist.

Finally, there are more complex forms of structure that we' ll discuss them later.

 

 

Repeat Structure (for)

Many times we will need to repeat a process several times. In this case, we have commands that repeat a set of commands as many times as we want, either by counting the iterations or by checking a condition each time. The most common format we encounter in a repeat is the one with the predetermined number of steps. This is as follows:

 

for (; <finish_condition>;)

{commands}

 

Where a control variable is used as follows:

 we give the initial value, e.g. i = 0

 we give the change of each iteration, e.g. i + 5

<finish_conditionthe condition to finish repeating, e.g. i < 10 (as long as it is true it will run)

 

Example:

For (i=1;i<10;i=i+1) { Brightness = brightness + 5;
AnalogWrite (ledPin, brightness);
};

 

There are repeat commands that do not have a predetermined number of steps but continue indefinitely by checking a condition. In the following worksheets you will not need to use such a command, but for reference purposes we have the following commands:

  • • while  {} // as long as the condition holds the commands are running
  • • repeat {} until // run as long as the condition does not apply any more

 

 

Support Libraries

All libraries of the Arduino computing platform are on the internet and can be downloaded freely by anyone, and their purpose is the ease of use of various accessories (lcd, rc_servo, etc.) with them. The Arduino environment (IDE) can be expanded using libraries, just like most programming platforms, since libraries provide additional functionality for their use, greatly simplifying the programming process. A number of libraries are pre-installed, and it's very easy to download and edit them or even create yours.

The use of libraries offers more functionality in collaboration with the material and the handling of the data. To use a library in a sketch, it can be selected from the Sketch → Import Library menu. This will import one or more libraries #include statements at the top of the sketch. Because the libraries are loaded on the board with the sketch, they increase the size of the space occupied. If a sketch no longer needs a library, we can just delete it from the top of the code.

To install libraries that are not already in the software, a library called other-libraries can be created in the sketchbook directory. Then we unpack the library there. Below are some of the contributed libraries supported by Arduino.

 

Communication (networking and protocols):

  • Messenger - for processing text-based messages from computer
  • NewSoftSerial - an improved version of the SoftwareSerial library
  • OneWire - control devices that use the One Wire protocol
  • PS2Keyboard - read characters from a PS2 keyboard
  • Simple Message System - send messages between Arduino and computer
  • SSerial2Mobile - send text messages or emails using a cell phone
  • Webduino - extensible web server library
  • X10 - Sending X10 signals over AC power lines
  • XBee - for communicating with XBees in API mode
  • SerialControl - Remote control other Arduinos over the serial connection


Sensing:


Displays and LEDs:

  • GFX - base class with standard graphics routines
  • GLCD - graphics routines for LCD based on the KS0108
  • Improved LCD library fixes LCD initialization bugs in official Arduino LCD library
  • LedControl - for controlling LED matrices or seven-segment displays with a MAX7221 or MAX7219
  • LedControl - an alternative to the Matrix library for driving multiple LEDs with Maxim chips
  • LedDisplay - control of a HCMS-29xx scrolling LED display
  • Matrix - Basic LED Matrix display manipulation library
  • PCD8544 - for the LCD controller on Nokia 55100-like displays
  • Sprite - for use in animations with LED matrix
  • ST7735 - for the LCD controller on a 1.8", 128x160 TFT screen


Audio and Waveforms:

  • FFT - for frequency analysis of analog signals
  • Tone - for generation of audio frequency square waves


Motors and PWM:

  • TLC5940 - 16 channel 12 bit PWM controller


Timing:

  • DateTime - for keeping track of the current date and time
  • Metro - time actions at regular intervals
  • MsTimer2 - uses the timer 2 interrupt to trigger an action every N ms


Utilities:

 

 

Continue to Examples page