Arduino – Quick Guide

Arduino – Quick Guide ”; Previous Next Arduino – Overview Arduino is a prototype platform (open-source) based on an easy-to-use hardware and software. It consists of a circuit board, which can be programed (referred to as a microcontroller) and a ready-made software called Arduino IDE (Integrated Development Environment), which is used to write and upload the computer code to the physical board. The key features are − Arduino boards are able to read analog or digital input signals from different sensors and turn it into an output such as activating a motor, turning LED on/off, connect to the cloud and many other actions. You can control your board functions by sending a set of instructions to the microcontroller on the board via Arduino IDE (referred to as uploading software). Unlike most previous programmable circuit boards, Arduino does not need an extra piece of hardware (called a programmer) in order to load a new code onto the board. You can simply use a USB cable. Additionally, the Arduino IDE uses a simplified version of C++, making it easier to learn to program. Finally, Arduino provides a standard form factor that breaks the functions of the micro-controller into a more accessible package. Board Types Various kinds of Arduino boards are available depending on different microcontrollers used. However, all Arduino boards have one thing in common: they are programed through the Arduino IDE. The differences are based on the number of inputs and outputs (the number of sensors, LEDs, and buttons you can use on a single board), speed, operating voltage, form factor etc. Some boards are designed to be embedded and have no programming interface (hardware), which you would need to buy separately. Some can run directly from a 3.7V battery, others need at least 5V. Here is a list of different Arduino boards available. Arduino boards based on ATMEGA328 microcontroller Board Name Operating Volt Clock Speed Digital i/o Analog Inputs PWM UART Programming Interface Arduino Uno R3 5V 16MHz 14 6 6 1 USB via ATMega16U2 Arduino Uno R3 SMD 5V 16MHz 14 6 6 1 USB via ATMega16U2 Red Board 5V 16MHz 14 6 6 1 USB via FTDI Arduino Pro 3.3v/8 MHz 3.3V 8MHz 14 6 6 1 FTDI-Compatible Header Arduino Pro 5V/16MHz 5V 16MHz 14 6 6 1 FTDI-Compatible Header Arduino mini 05 5V 16MHz 14 8 6 1 FTDI-Compatible Header Arduino Pro mini 3.3v/8mhz 3.3V 8MHz 14 8 6 1 FTDI-Compatible Header Arduino Pro mini 5v/16mhz 5V 16MHz 14 8 6 1 FTDI-Compatible Header Arduino Ethernet 5V 16MHz 14 6 6 1 FTDI-Compatible Header Arduino Fio 3.3V 8MHz 14 8 6 1 FTDI-Compatible Header LilyPad Arduino 328 main board 3.3V 8MHz 14 6 6 1 FTDI-Compatible Header LilyPad Arduino simple board 3.3V 8MHz 9 4 5 0 FTDI-Compatible Header Arduino boards based on ATMEGA32u4 microcontroller Board Name Operating Volt Clock Speed Digital i/o Analog Inputs PWM UART Programming Interface Arduino Leonardo 5V 16MHz 20 12 7 1 Native USB Pro micro 5V/16MHz 5V 16MHz 14 6 6 1 Native USB Pro micro 3.3V/8MHz 5V 16MHz 14 6 6 1 Native USB LilyPad Arduino USB 3.3V 8MHz 14 6 6 1 Native USB Arduino boards based on ATMEGA2560 microcontroller Board Name Operating Volt Clock Speed Digital i/o Analog Inputs PWM UART Programming Interface Arduino Mega 2560 R3 5V 16MHz 54 16 14 4 USB via ATMega16U2B Mega Pro 3.3V 3.3V 8MHz 54 16 14 4 FTDI-Compatible Header Mega Pro 5V 5V 16MHz 54 16 14 4 FTDI-Compatible Header Mega Pro Mini 3.3V 3.3V 8MHz 54 16 14 4 FTDI-Compatible Header Arduino boards based on AT91SAM3X8E microcontroller Board Name Operating Volt Clock Speed Digital i/o Analog Inputs PWM UART Programming Interface Arduino Mega 2560 R3 3.3V 84MHz 54 12 12 4 USB native Arduino – Board Description In this chapter, we will learn about the different components on the Arduino board. We will study the Arduino UNO board because it is the most popular board in the Arduino board family. In addition, it is the best board to get started with electronics and coding. Some boards look a bit different from the one given below, but most Arduinos have majority of these components in common. Power USB Arduino board can be powered by using the USB cable from your computer. All you need to do is connect the USB cable to the USB connection (1). Power (Barrel Jack) Arduino boards can be powered directly from the AC mains power supply by connecting it to the Barrel Jack (2). Voltage Regulator The function of the voltage regulator is to control the voltage given to the Arduino board and stabilize the DC voltages used by the processor and other elements. Crystal Oscillator The crystal oscillator helps Arduino in dealing with time issues. How does Arduino calculate time? The answer is, by using the crystal oscillator. The number printed on top of the Arduino crystal is 16.000H9H. It tells us that the frequency is 16,000,000 Hertz or 16 MHz. Arduino Reset You can reset your Arduino board, i.e., start your program from the beginning. You can reset the UNO board in two ways. First, by using the reset button (17) on the board. Second, you can connect an external reset button to the Arduino pin labelled RESET (5). Pins (3.3, 5, GND, Vin) 3.3V (6) − Supply 3.3 output volt 5V (7) − Supply 5 output volt Most of the components used with Arduino board works fine with 3.3 volt and 5 volt. GND (8)(Ground) − There are several GND pins on the Arduino, any of which can be used to ground your circuit. Vin (9) − This pin also can be used to power the Arduino board from an external power source, like AC mains power supply. Analog pins The Arduino UNO board has six analog input pins A0 through A5. These pins can read the signal from an analog sensor like the humidity sensor or temperature sensor and convert it into a digital value that can

Arduino – Useful Resources

Arduino – Useful Resources ”; Previous Next The following resources contain additional information on Arduino. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Arduino based Text to Speech (TTS) Converter 12 Lectures 1 hours Ashraf Said More Detail Arduino meets Python: Step by Step 13 Lectures 42 mins Ashraf Said More Detail Arduino Communication with SPI Protocol 13 Lectures 1.5 hours Ashraf Said More Detail Arduino Interrupt: Step by Step Guide with Practical Example 17 Lectures 1 hours Ashraf Said More Detail Arduino Email Sending Motion Detector 12 Lectures 53 mins Ashraf Said More Detail Arduino SMS Sending Motion Detector using Python 17 Lectures 1 hours Ashraf Said More Detail Print Page Previous Next Advertisements ”;

Arduino – Advanced I/O Function

Arduino – Advanced I/O Function ”; Previous Next In this chapter, we will learn some advanced Input and Output Functions. analogReference() Function Configures the reference voltage used for analog input (i.e. the value used as the top of the input range). The options are − DEFAULT − The default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards) INTERNAL − An built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on the Arduino Mega) INTERNAL1V1 − A built-in 1.1V reference (Arduino Mega only) INTERNAL2V56 − A built-in 2.56V reference (Arduino Mega only) EXTERNAL − The voltage applied to the AREF pin (0 to 5V only) is used as the reference analogReference() Function Syntax analogReference (type); type − can use any type of the follow (DEFAULT, INTERNAL, INTERNAL1V1, INTERNAL2V56, EXTERNAL) Do not use anything less than 0V or more than 5V for external reference voltage on the AREF pin. If you are using an external reference on the AREF pin, you must set the analog reference to EXTERNAL before calling the analogRead() function. Otherwise, you will short the active reference voltage (internally generated) and the AREF pin, possibly damaging the microcontroller on your Arduino board. Alternatively, you can connect the external reference voltage to the AREF pin through a 5K resistor, allowing you to switch between external and internal reference voltages. Note that the resistor will alter the voltage that is used as the reference because there is an internal 32K resistor on the AREF pin. The two act as a voltage divider. For example, 2.5V applied through the resistor will yield 2.5 * 32 / (32 + 5) = ~2.2V at the AREF pin. Example int analogPin = 3;// potentiometer wiper (middle terminal) connected to analog pin 3 int val = 0; // variable to store the read value void setup() { Serial.begin(9600); // setup serial analogReference(EXTERNAL); // the voltage applied to the AREF pin (0 to 5V only) // is used as the reference. } void loop() { val = analogRead(analogPin); // read the input pin Serial.println(val); // debug value } Print Page Previous Next Advertisements ”;

Arduino – Random Numbers

Arduino – Random Numbers ”; Previous Next To generate random numbers, you can use Arduino random number functions. We have two functions − randomSeed(seed) random() randomSeed (seed) The function randomSeed(seed) resets Arduino’s pseudorandom number generator. Although the distribution of the numbers returned by random() is essentially random, the sequence is predictable. You should reset the generator to some random value. If you have an unconnected analog pin, it might pick up random noise from the surrounding environment. These may be radio waves, cosmic rays, electromagnetic interference from cell phones, fluorescent lights and so on. Example randomSeed(analogRead(5)); // randomize using noise from analog pin 5 random( ) The random function generates pseudo-random numbers. Following is the syntax. random( ) Statements Syntax long random(max) // it generate random numbers from 0 to max long random(min, max) // it generate random numbers from min to max Example long randNumber; void setup() { Serial.begin(9600); // if analog input pin 0 is unconnected, random analog // noise will cause the call to randomSeed() to generate // different seed numbers each time the sketch runs. // randomSeed() will then shuffle the random function. randomSeed(analogRead(0)); } void loop() { // print a random number from 0 to 299 Serial.print(“random1=”); randNumber = random(300); Serial.println(randNumber); // print a random number from 0to 299 Serial.print(“random2=”); randNumber = random(10, 20);// print a random number from 10 to 19 Serial.println (randNumber); delay(50); } Let us now refresh our knowledge on some of the basic concepts such as bits and bytes. Bits A bit is just a binary digit. The binary system uses two digits, 0 and 1. Similar to the decimal number system, in which digits of a number do not have the same value, the ‘significance’ of a bit depends on its position in the binary number. For example, digits in the decimal number 666 are the same, but have different values. Bytes A byte consists of eight bits. If a bit is a digit, it is logical that bytes represent numbers. All mathematical operations can be performed upon them. The digits in a byte do not have the same significance either. The leftmost bit has the greatest value called the Most Significant Bit (MSB). The rightmost bit has the least value and is therefore, called the Least Significant Bit (LSB). Since eight zeros and ones of one byte can be combined in 256 different ways, the largest decimal number that can be represented by one byte is 255 (one combination represents a zero). Print Page Previous Next Advertisements ”;

Arduino – Communication

Arduino – Communication ”; Previous Next Hundreds of communication protocols have been defined to achieve this data exchange. Each protocol can be categorized into one of the two categories: parallel or serial. Parallel Communication Parallel connection between the Arduino and peripherals via input/output ports is the ideal solution for shorter distances up to several meters. However, in other cases when it is necessary to establish communication between two devices for longer distances it is not possible to use parallel connection. Parallel interfaces transfer multiple bits at the same time. They usually require buses of data – transmitting across eight, sixteen, or more wires. Data is transferred in huge, crashing waves of 1’s and 0’s. Advantages and Drawbacks of Parallel Communication Parallel communication certainly has its advantages. It is faster than serial, straightforward, and relatively easy to implement. However, it requires many input/output (I/O) ports and lines. If you have ever had to move a project from a basic Arduino Uno to a Mega, you know that the I/O lines on a microprocessor can be precious and few. Therefore, we prefer serial communication, sacrificing potential speed for pin real estate. Serial Communication Modules Today, most Arduino boards are built with several different systems for serial communication as standard equipment. Which of these systems are used depends on the following factors − How many devices the microcontroller has to exchange data with? How fast the data exchange has to be? What is the distance between these devices? Is it necessary to send and receive data simultaneously? One of the most important things concerning serial communication is the Protocol, which should be strictly observed. It is a set of rules, which must be applied such that the devices can correctly interpret data they mutually exchange. Fortunately, Arduino automatically takes care of this, so that the work of the programmer/user is reduced to simple write (data to be sent) and read (received data). Types of Serial Communications Serial communication can be further classified as − Synchronous − Devices that are synchronized use the same clock and their timing is in synchronization with each other. Asynchronous − Devices that are asynchronous have their own clocks and are triggered by the output of the previous state. It is easy to find out if a device is synchronous or not. If the same clock is given to all the connected devices, then they are synchronous. If there is no clock line, it is asynchronous. For example, UART (Universal Asynchronous Receiver Transmitter) module is asynchronous. The asynchronous serial protocol has a number of built-in rules. These rules are nothing but mechanisms that help ensure robust and error-free data transfers. These mechanisms, which we get for eschewing the external clock signal, are − Synchronization bits Data bits Parity bits Baud rate Synchronization Bits The synchronization bits are two or three special bits transferred with each packet of data. They are the start bit and the stop bit(s). True to their name, these bits mark the beginning and the end of a packet respectively. There is always only one start bit, but the number of stop bits is configurable to either one or two (though it is normally left at one). The start bit is always indicated by an idle data line going from 1 to 0, while the stop bit(s) will transition back to the idle state by holding the line at 1. Data Bits The amount of data in each packet can be set to any size from 5 to 9 bits. Certainly, the standard data size is your basic 8-bit byte, but other sizes have their uses. A 7-bit data packet can be more efficient than 8, especially if you are just transferring 7-bit ASCII characters. Parity Bits The user can select whether there should be a parity bit or not, and if yes, whether the parity should be odd or even. The parity bit is 0 if the number of 1’s among the data bits is even. Odd parity is just the opposite. Baud Rate The term baud rate is used to denote the number of bits transferred per second [bps]. Note that it refers to bits, not bytes. It is usually required by the protocol that each byte is transferred along with several control bits. It means that one byte in serial data stream may consist of 11 bits. For example, if the baud rate is 300 bps then maximum 37 and minimum 27 bytes may be transferred per second. Arduino UART The following code will make Arduino send hello world when it starts up. void setup() { Serial.begin(9600); //set up serial library baud rate to 9600 Serial.println(“hello world”); //print hello world } void loop() { } After the Arduino sketch has been uploaded to Arduino, open the Serial monitor at the top right section of Arduino IDE. Type anything into the top box of the Serial Monitor and press send or enter on your keyboard. This will send a series of bytes to the Arduino. The following code returns whatever it receives as an input. The following code will make Arduino deliver output depending on the input provided. void setup() { Serial.begin(9600); //set up serial library baud rate to 9600 } void loop() { if(Serial.available()) //if number of bytes (characters) available for reading from { serial port Serial.print(“I received:”); //print I received Serial.write(Serial.read()); //send what you read } } Notice that Serial.print and Serial.println will send back the actual ASCII code, whereas Serial.write will send back the actual text. See ASCII codes for more information. Print Page Previous Next Advertisements ”;

Arduino – Servo Motor

Arduino – Servo Motor ”; Previous Next A Servo Motor is a small device that has an output shaft. This shaft can be positioned to specific angular positions by sending the servo a coded signal. As long as the coded signal exists on the input line, the servo will maintain the angular position of the shaft. If the coded signal changes, the angular position of the shaft changes. In practice, servos are used in radio-controlled airplanes to position control surfaces like the elevators and rudders. They are also used in radio-controlled cars, puppets, and of course, robots. Servos are extremely useful in robotics. The motors are small, have built-in control circuitry, and are extremely powerful for their size. A standard servo such as the Futaba S-148 has 42 oz/inches of torque, which is strong for its size. It also draws power proportional to the mechanical load. A lightly loaded servo, therefore, does not consume much energy. The guts of a servo motor is shown in the following picture. You can see the control circuitry, the motor, a set of gears, and the case. You can also see the 3 wires that connect to the outside world. One is for power (+5volts), ground, and the white wire is the control wire. Working of a Servo Motor The servo motor has some control circuits and a potentiometer (a variable resistor, aka pot) connected to the output shaft. In the picture above, the pot can be seen on the right side of the circuit board. This pot allows the control circuitry to monitor the current angle of the servo motor. If the shaft is at the correct angle, then the motor shuts off. If the circuit finds that the angle is not correct, it will turn the motor until it is at a desired angle. The output shaft of the servo is capable of traveling somewhere around 180 degrees. Usually, it is somewhere in the 210-degree range, however, it varies depending on the manufacturer. A normal servo is used to control an angular motion of 0 to 180 degrees. It is mechanically not capable of turning any farther due to a mechanical stop built on to the main output gear. The power applied to the motor is proportional to the distance it needs to travel. So, if the shaft needs to turn a large distance, the motor will run at full speed. If it needs to turn only a small amount, the motor will run at a slower speed. This is called proportional control. How Do You Communicate the Angle at Which the Servo Should Turn? The control wire is used to communicate the angle. The angle is determined by the duration of a pulse that is applied to the control wire. This is called Pulse Coded Modulation. The servo expects to see a pulse every 20 milliseconds (.02 seconds). The length of the pulse will determine how far the motor turns. A 1.5 millisecond pulse, for example, will make the motor turn to the 90-degree position (often called as the neutral position). If the pulse is shorter than 1.5 milliseconds, then the motor will turn the shaft closer to 0 degrees. If the pulse is longer than 1.5 milliseconds, the shaft turns closer to 180 degrees. Components Required You will need the following components − 1 × Arduino UNO board 1 × Servo Motor 1 × ULN2003 driving IC 1 × 10 KΩ Resistor Procedure Follow the circuit diagram and make the connections as shown in the image given below. Sketch Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking on New. Arduino Code /* Controlling a servo position using a potentiometer (variable resistor) */ #include <Servo.h> Servo myservo; // create servo object to control a servo int potpin = 0; // analog pin used to connect the potentiometer int val; // variable to read the value from the analog pin void setup() { myservo.attach(9); // attaches the servo on pin 9 to the servo object } void loop() { val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023) val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180) myservo.write(val); // sets the servo position according to the scaled value delay(15); } Code to Note Servo motors have three terminals – power, ground, and signal. The power wire is typically red, and should be connected to the 5V pin on the Arduino. The ground wire is typically black or brown and should be connected to one terminal of ULN2003 IC (10 -16). To protect your Arduino board from damage, you will need some driver IC to do that. Here we have used ULN2003 IC to drive the servo motor. The signal pin is typically yellow or orange and should be connected to Arduino pin number 9. Connecting the Potentiometer A voltage divider/potential divider are resistors in a series circuit that scale the output voltage to a particular ratio of the input voltage applied. Following is the circuit diagram − $$V_{out} = (V_{in} times R_{2})/ (R_{1} + R_{2})$$ Vout is the output potential, which depends on the applied input voltage (Vin) and resistors (R1 and R2) in the series. It means that the current flowing through R1 will also flow through R2 without being divided. In the above equation, as the value of R2 changes, the Vout scales accordingly with respect to the input voltage, Vin. Typically, a potentiometer is a potential divider, which can scale the output voltage of the circuit based on the value of the variable resistor, which is scaled using the knob. It has three pins: GND, Signal, and +5V as shown in the diagram below − Result By changing the pot’s NOP position, servo motor will change its angle. Print Page Previous

Arduino – Program Structure

Arduino – Program Structure ”; Previous Next In this chapter, we will study in depth, the Arduino program structure and we will learn more new terminologies used in the Arduino world. The Arduino software is open-source. The source code for the Java environment is released under the GPL and the C/C++ microcontroller libraries are under the LGPL. Sketch − The first new terminology is the Arduino program called “sketch”. Structure Arduino programs can be divided in three main parts: Structure, Values (variables and constants), and Functions. In this tutorial, we will learn about the Arduino software program, step by step, and how we can write the program without any syntax or compilation error. Let us start with the Structure. Software structure consist of two main functions − Setup( ) function Loop( ) function Void setup ( ) { } PURPOSE − The setup() function is called when a sketch starts. Use it to initialize the variables, pin modes, start using libraries, etc. The setup function will only run once, after each power up or reset of the Arduino board. INPUT − – OUTPUT − – RETURN − – Void Loop ( ) { } PURPOSE − After creating a setup() function, which initializes and sets the initial values, the loop() function does precisely what its name suggests, and loops consecutively, allowing your program to change and respond. Use it to actively control the Arduino board. INPUT − – OUTPUT − – RETURN − – Print Page Previous Next Advertisements ”;

Arduino – Control Statements

Arduino – Control Statements ”; Previous Next Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program. It should be along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general form of a typical decision making structure found in most of the programming languages − Control Statements are elements in Source Code that control the flow of program execution. They are − S.NO. Control Statement & Description 1 If statement It takes an expression in parenthesis and a statement or block of statements. If the expression is true then the statement or block of statements gets executed otherwise these statements are skipped. 2 If …else statement An if statement can be followed by an optional else statement, which executes when the expression is false. 3 If…else if …else statement The if statement can be followed by an optional else if…else statement, which is very useful to test various conditions using single if…else if statement. 4 switch case statement Similar to the if statements, switch…case controls the flow of programs by allowing the programmers to specify different codes that should be executed in various conditions. 5 Conditional Operator ? : The conditional operator ? : is the only ternary operator in C. Print Page Previous Next Advertisements ”;

Arduino – I/O Functions

Arduino – I/O Functions ”; Previous Next The pins on the Arduino board can be configured as either inputs or outputs. We will explain the functioning of the pins in those modes. It is important to note that a majority of Arduino analog pins, may be configured, and used, in exactly the same manner as digital pins. Pins Configured as INPUT Arduino pins are by default configured as inputs, so they do not need to be explicitly declared as inputs with pinMode() when you are using them as inputs. Pins configured this way are said to be in a high-impedance state. Input pins make extremely small demands on the circuit that they are sampling, equivalent to a series resistor of 100 megaohm in front of the pin. This means that it takes very little current to switch the input pin from one state to another. This makes the pins useful for such tasks as implementing a capacitive touch sensor or reading an LED as a photodiode. Pins configured as pinMode(pin, INPUT) with nothing connected to them, or with wires connected to them that are not connected to other circuits, report seemingly random changes in pin state, picking up electrical noise from the environment, or capacitively coupling the state of a nearby pin. Pull-up Resistors Pull-up resistors are often useful to steer an input pin to a known state if no input is present. This can be done by adding a pull-up resistor (to &plus;5V), or a pull-down resistor (resistor to ground) on the input. A 10K resistor is a good value for a pull-up or pull-down resistor. Using Built-in Pull-up Resistor with Pins Configured as Input There are 20,000 pull-up resistors built into the Atmega chip that can be accessed from software. These built-in pull-up resistors are accessed by setting the pinMode() as INPUT_PULLUP. This effectively inverts the behavior of the INPUT mode, where HIGH means the sensor is OFF and LOW means the sensor is ON. The value of this pull-up depends on the microcontroller used. On most AVR-based boards, the value is guaranteed to be between 20kΩ and 50kΩ. On the Arduino Due, it is between 50kΩ and 150kΩ. For the exact value, consult the datasheet of the microcontroller on your board. When connecting a sensor to a pin configured with INPUT_PULLUP, the other end should be connected to the ground. In case of a simple switch, this causes the pin to read HIGH when the switch is open and LOW when the switch is pressed. The pull-up resistors provide enough current to light an LED dimly connected to a pin configured as an input. If LEDs in a project seem to be working, but very dimly, this is likely what is going on. Same registers (internal chip memory locations) that control whether a pin is HIGH or LOW control the pull-up resistors. Consequently, a pin that is configured to have pull-up resistors turned on when the pin is in INPUTmode, will have the pin configured as HIGH if the pin is then switched to an OUTPUT mode with pinMode(). This works in the other direction as well, and an output pin that is left in a HIGH state will have the pull-up resistor set if switched to an input with pinMode(). Example pinMode(3,INPUT) ; // set pin to input without using built in pull up resistor pinMode(5,INPUT_PULLUP) ; // set pin to input using built in pull up resistor Pins Configured as OUTPUT Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state. This means that they can provide a substantial amount of current to other circuits. Atmega pins can source (provide positive current) or sink (provide negative current) up to 40 mA (milliamps) of current to other devices/circuits. This is enough current to brightly light up an LED (do not forget the series resistor), or run many sensors but not enough current to run relays, solenoids, or motors. Attempting to run high current devices from the output pins, can damage or destroy the output transistors in the pin, or damage the entire Atmega chip. Often, this results in a “dead” pin in the microcontroller but the remaining chips still function adequately. For this reason, it is a good idea to connect the OUTPUT pins to other devices through 470Ω or 1k resistors, unless maximum current drawn from the pins is required for a particular application. pinMode() Function The pinMode() function is used to configure a specific pin to behave either as an input or an output. It is possible to enable the internal pull-up resistors with the mode INPUT_PULLUP. Additionally, the INPUT mode explicitly disables the internal pull-ups. pinMode() Function Syntax Void setup () { pinMode (pin , mode); } pin − the number of the pin whose mode you wish to set mode − INPUT, OUTPUT, or INPUT_PULLUP. Example int button = 5 ; // button connected to pin 5 int LED = 6; // LED connected to pin 6 void setup () { pinMode(button , INPUT_PULLUP); // set the digital pin as input with pull-up resistor pinMode(button , OUTPUT); // set the digital pin as output } void setup () { If (digitalRead(button ) == LOW) // if button pressed { digitalWrite(LED,HIGH); // turn on led delay(500); // delay for 500 ms digitalWrite(LED,LOW); // turn off led delay(500); // delay for 500 ms } } digitalWrite() Function The digitalWrite() function is used to write a HIGH or a LOW value to a digital pin. If the pin has been configured as an OUTPUT with pinMode(), its voltage will be set to the corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW. If the pin is configured as an INPUT, digitalWrite() will enable (HIGH) or disable (LOW) the internal pullup on the input pin. It is recommended to set the pinMode() to INPUT_PULLUP to enable the internal pull-up resistor. If you do not set the pinMode() to OUTPUT, and connect an LED

Arduino – Character Functions

Arduino – Character Functions ”; Previous Next All data is entered into computers as characters, which includes letters, digits and various special symbols. In this section, we discuss the capabilities of C++ for examining and manipulating individual characters. The character-handling library includes several functions that perform useful tests and manipulations of character data. Each function receives a character, represented as an int, or EOF as an argument. Characters are often manipulated as integers. Remember that EOF normally has the value –1 and that some hardware architectures do not allow negative values to be stored in char variables. Therefore, the character-handling functions manipulate characters as integers. The following table summarizes the functions of the character-handling library. When using functions from the character-handling library, include the <cctype> header. S.No. Prototype & Description 1 int isdigit( int c ) Returns 1 if c is a digit and 0 otherwise. 2 int isalpha( int c ) Returns 1 if c is a letter and 0 otherwise. 3 int isalnum( int c ) Returns 1 if c is a digit or a letter and 0 otherwise. 4 int isxdigit( int c ) Returns 1 if c is a hexadecimal digit character and 0 otherwise. (See Appendix D, Number Systems, for a detailed explanation of binary, octal, decimal and hexadecimal numbers.) 5 int islower( int c ) Returns 1 if c is a lowercase letter and 0 otherwise. 6 int isupper( int c ) Returns 1 if c is an uppercase letter; 0 otherwise. 7 int isspace( int c ) Returns 1 if c is a white-space character—newline (”n”), space (” ”), form feed (”f”), carriage return (”r”), horizontal tab (”t”), or vertical tab (”v”)—and 0 otherwise. 8 int iscntrl( int c ) Returns 1 if c is a control character, such as newline (”n”), form feed (”f”), carriage return (”r”), horizontal tab (”t”), vertical tab (”v”), alert (”a”), or backspace (”b”)—and 0 otherwise. 9 int ispunct( int c ) Returns 1 if c is a printing character other than a space, a digit, or a letter and 0 otherwise. 10 int isprint( int c ) Returns 1 if c is a printing character including space (” ”) and 0 otherwise. 11 int isgraph( int c ) Returns 1 if c is a printing character other than space (” ”) and 0 otherwise. Examples The following example demonstrates the use of the functions isdigit, isalpha, isalnum and isxdigit. Function isdigit determines whether its argument is a digit (0–9). The function isalpha determines whether its argument is an uppercase letter (A-Z) or a lowercase letter (a–z). The function isalnum determines whether its argument is an uppercase, lowercase letter or a digit. Function isxdigit determines whether its argument is a hexadecimal digit (A–F, a–f, 0–9). Example 1 void setup () { Serial.begin (9600); Serial.print (“According to isdigit:r”); Serial.print (isdigit( ”8” ) ? “8 is a”: “8 is not a”); Serial.print (” digitr” ); Serial.print (isdigit( ”8” ) ?”# is a”: “# is not a”) ; Serial.print (” digitr”); Serial.print (“rAccording to isalpha:r” ); Serial.print (isalpha(”A” ) ?”A is a”: “A is not a”); Serial.print (” letterr”); Serial.print (isalpha(”A” ) ?”b is a”: “b is not a”); Serial.print (” letterr”); Serial.print (isalpha(”A”) ?”& is a”: “& is not a”); Serial.print (” letterr”); Serial.print (isalpha( ”A” ) ?”4 is a”:”4 is not a”); Serial.print (” letterr”); Serial.print (“rAccording to isalnum:r”); Serial.print (isalnum( ”A” ) ?”A is a” : “A is not a” ); Serial.print (” digit or a letterr” ); Serial.print (isalnum( ”8” ) ?”8 is a” : “8 is not a” ) ; Serial.print (” digit or a letterr”); Serial.print (isalnum( ”#” ) ?”# is a” : “# is not a” ); Serial.print (” digit or a letterr”); Serial.print (“rAccording to isxdigit:r”); Serial.print (isxdigit( ”F” ) ?”F is a” : “F is not a” ); Serial.print (” hexadecimal digitr” ); Serial.print (isxdigit( ”J” ) ?”J is a” : “J is not a” ) ; Serial.print (” hexadecimal digitr” ); Serial.print (isxdigit( ”7” ) ?”7 is a” : “7 is not a” ) ; Serial.print (” hexadecimal digitr” ); Serial.print (isxdigit( ”$” ) ? “$ is a” : “$ is not a” ); Serial.print (” hexadecimal digitr” ); Serial.print (isxdigit( ”f” ) ? “f is a” : “f is not a”); } void loop () { } Result According to isdigit: 8 is a digit # is not a digit According to isalpha: A is a letter b is a letter & is not a letter 4 is not a letter According to isalnum: A is a digit or a letter 8 is a digit or a letter # is not a digit or a letter According to isxdigit: F is a hexadecimal digit J is not a hexadecimal digit 7 is a hexadecimal digit $ is not a hexadecimal digit f is a hexadecimal digit We use the conditional operator (?:) with each function to determine whether the string ” is a ” or the string ” is not a ” should be printed in the output for each character tested. For example, line a indicates that if ”8” is a digit—i.e., if isdigit returns a true (nonzero) value—the string “8 is a ” is printed. If ”8” is not a digit (i.e., if isdigit returns 0), the string ” 8 is not a ” is printed. Example 2 The following example demonstrates the use of the functions islower and isupper. The function islower determines whether its argument is a lowercase letter (a–z). Function isupper determines whether its argument is an uppercase letter (A–Z). int thisChar = 0xA0; void setup () { Serial.begin (9600); Serial.print (“According to islower:r”) ; Serial.print (islower( ”p” ) ? “p is a” : “p is not a” ); Serial.print ( ” lowercase letterr” ); Serial.print ( islower( ”P”) ? “P is a” : “P is not a”) ; Serial.print (“lowercase letterr”); Serial.print (islower( ”5” ) ? “5 is a” : “5 is not a” ); Serial.print ( ” lowercase letterr”