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 +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”

Arduino – Installation

Arduino – Installation ”; Previous Next After learning about the main parts of the Arduino UNO board, we are ready to learn how to set up the Arduino IDE. Once we learn this, we will be ready to upload our program on the Arduino board. In this section, we will learn in easy steps, how to set up the Arduino IDE on our computer and prepare the board to receive the program via USB cable. Step 1 − First you must have your Arduino board (you can choose your favorite board) and a USB cable. In case you use Arduino UNO, Arduino Duemilanove, Nano, Arduino Mega 2560, or Diecimila, you will need a standard USB cable (A plug to B plug), the kind you would connect to a USB printer as shown in the following image. In case you use Arduino Nano, you will need an A to Mini-B cable instead as shown in the following image. Step 2 − Download Arduino IDE Software. You can get different versions of Arduino IDE from the Download page on the Arduino Official website. You must select your software, which is compatible with your operating system (Windows, IOS, or Linux). After your file download is complete, unzip the file. Step 3 − Power up your board. The Arduino Uno, Mega, Duemilanove and Arduino Nano automatically draw power from either, the USB connection to the computer or an external power supply. If you are using an Arduino Diecimila, you have to make sure that the board is configured to draw power from the USB connection. The power source is selected with a jumper, a small piece of plastic that fits onto two of the three pins between the USB and power jacks. Check that it is on the two pins closest to the USB port. Connect the Arduino board to your computer using the USB cable. The green power LED (labeled PWR) should glow. Step 4 − Launch Arduino IDE. After your Arduino IDE software is downloaded, you need to unzip the folder. Inside the folder, you can find the application icon with an infinity label (application.exe). Double-click the icon to start the IDE. Step 5 − Open your first project. Once the software starts, you have two options − Create a new project. Open an existing project example. To create a new project, select File → New. To open an existing project example, select File → Example → Basics → Blink. Here, we are selecting just one of the examples with the name Blink. It turns the LED on and off with some time delay. You can select any other example from the list. Step 6 − Select your Arduino board. To avoid any error while uploading your program to the board, you must select the correct Arduino board name, which matches with the board connected to your computer. Go to Tools → Board and select your board. Here, we have selected Arduino Uno board according to our tutorial, but you must select the name matching the board that you are using. Step 7 − Select your serial port. Select the serial device of the Arduino board. Go to Tools → Serial Port menu. This is likely to be COM3 or higher (COM1 and COM2 are usually reserved for hardware serial ports). To find out, you can disconnect your Arduino board and re-open the menu, the entry that disappears should be of the Arduino board. Reconnect the board and select that serial port. Step 8 − Upload the program to your board. Before explaining how we can upload our program to the board, we must demonstrate the function of each symbol appearing in the Arduino IDE toolbar. A − Used to check if there is any compilation error. B − Used to upload a program to the Arduino board. C − Shortcut used to create a new sketch. D − Used to directly open one of the example sketch. E − Used to save your sketch. F − Serial monitor used to receive serial data from the board and send the serial data to the board. Now, simply click the “Upload” button in the environment. Wait a few seconds; you will see the RX and TX LEDs on the board, flashing. If the upload is successful, the message “Done uploading” will appear in the status bar. Note − If you have an Arduino Mini, NG, or other board, you need to press the reset button physically on the board, immediately before clicking the upload button on the Arduino Software. Print Page Previous Next Advertisements ”;

Arduino – Data Types

Arduino – Data Types ”; Previous Next Data types in C refers to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in the storage and how the bit pattern stored is interpreted. The following table provides all the data types that you will use during Arduino programming. void Boolean char Unsigned char byte int Unsigned int word long Unsigned long short float double array String-char array String-object void The void keyword is used only in function declarations. It indicates that the function is expected to return no information to the function from which it was called. Example Void Loop ( ) { // rest of the code } Boolean A Boolean holds one of two values, true or false. Each Boolean variable occupies one byte of memory. Example boolean val = false ; // declaration of variable with type boolean and initialize it with false boolean state = true ; // declaration of variable with type boolean and initialize it with true Char A data type that takes up one byte of memory that stores a character value. Character literals are written in single quotes like this: ”A” and for multiple characters, strings use double quotes: “ABC”. However, characters are stored as numbers. You can see the specific encoding in the ASCII chart. This means that it is possible to do arithmetic operations on characters, in which the ASCII value of the character is used. For example, ”A” + 1 has the value 66, since the ASCII value of the capital letter A is 65. Example Char chr_a = ‘a’ ;//declaration of variable with type char and initialize it with character a Char chr_c = 97 ;//declaration of variable with type char and initialize it with character 97 unsigned char Unsigned char is an unsigned data type that occupies one byte of memory. The unsigned char data type encodes numbers from 0 to 255. Example Unsigned Char chr_y = 121 ; // declaration of variable with type Unsigned char and initialize it with character y byte A byte stores an 8-bit unsigned number, from 0 to 255. Example byte m = 25 ;//declaration of variable with type byte and initialize it with 25 int Integers are the primary data-type for number storage. int stores a 16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) – 1). The int size varies from board to board. On the Arduino Due, for example, an int stores a 32-bit (4-byte) value. This yields a range of -2,147,483,648 to 2,147,483,647 (minimum value of -2^31 and a maximum value of (2^31) – 1). Example int counter = 32 ;// declaration of variable with type int and initialize it with 32 Unsigned int Unsigned ints (unsigned integers) are the same as int in the way that they store a 2 byte value. Instead of storing negative numbers, however, they only store positive values, yielding a useful range of 0 to 65,535 (2^16) – 1). The Due stores a 4 byte (32-bit) value, ranging from 0 to 4,294,967,295 (2^32 – 1). Example Unsigned int counter = 60 ; // declaration of variable with type unsigned int and initialize it with 60 Word On the Uno and other ATMEGA based boards, a word stores a 16-bit unsigned number. On the Due and Zero, it stores a 32-bit unsigned number. Example word w = 1000 ;//declaration of variable with type word and initialize it with 1000 Long Long variables are extended size variables for number storage, and store 32 bits (4 bytes), from -2,147,483,648 to 2,147,483,647. Example Long velocity = 102346 ;//declaration of variable with type Long and initialize it with 102346 unsigned long Unsigned long variables are extended size variables for number storage and store 32 bits (4 bytes). Unlike standard longs, unsigned longs will not store negative numbers, making their range from 0 to 4,294,967,295 (2^32 – 1). Example Unsigned Long velocity = 101006 ;// declaration of variable with type Unsigned Long and initialize it with 101006 short A short is a 16-bit data-type. On all Arduinos (ATMega and ARM based), a short stores a 16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) – 1). Example short val = 13 ;//declaration of variable with type short and initialize it with 13 float Data type for floating-point number is a number that has a decimal point. Floating-point numbers are often used to approximate the analog and continuous values because they have greater resolution than integers. Floating-point numbers can be as large as 3.4028235E+38 and as low as -3.4028235E+38. They are stored as 32 bits (4 bytes) of information. Example float num = 1.352;//declaration of variable with type float and initialize it with 1.352 double On the Uno and other ATMEGA based boards, Double precision floating-point number occupies four bytes. That is, the double implementation is exactly the same as the float, with no gain in precision. On the Arduino Due, doubles have 8-byte (64 bit) precision. Example double num = 45.352 ;// declaration of variable with type double and initialize it with 45.352 Print Page Previous Next Advertisements ”;

Arduino – Overview

Arduino – Overview ”; Previous Next 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 Print Page Previous Next Advertisements ”;

Arduino – Home

Arduino Tutorial PDF Version Quick Guide Resources Job Search Discussion 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. Arduino provides a standard form factor that breaks the functions of the micro-controller into a more accessible package. Audience This tutorial is intended for enthusiastic students or hobbyists. With Arduino, one can get to know the basics of micro-controllers and sensors very quickly and can start building prototype with very little investment. This tutorial is intended to make you comfortable in getting started with Arduino and its various functions. Prerequisites Before you start proceeding with this tutorial, we assume that you are already familiar with the basics of C and C++. If you are not well aware of these concepts, then we will suggest you go through our short tutorials on C and C++. A basic understanding of microcontrollers and electronics is also expected. Print Page Previous Next Advertisements ”;

Arduino – Board Description

Arduino – Board Description ”; Previous Next 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 be read by the microprocessor. Main microcontroller Each Arduino board has its own microcontroller (11). You can assume it as the brain of your board. The main IC (integrated circuit) on the Arduino is slightly different from board to board. The microcontrollers are usually of the ATMEL Company. You must know what IC your board has before loading up a new program from the Arduino IDE. This information is available on the top of the IC. For more details about the IC construction and functions, you can refer to the data sheet. ICSP pin Mostly, ICSP (12) is an AVR, a tiny programming header for the Arduino consisting of MOSI, MISO, SCK, RESET, VCC, and GND. It is often referred to as an SPI (Serial Peripheral Interface), which could be considered as an “expansion” of the output. Actually, you are slaving the output device to the master of the SPI bus. Power LED indicator This LED should light up when you plug your Arduino into a power source to indicate that your board is powered up correctly. If this light does not turn on, then there is something wrong with the connection. TX and RX LEDs On your board, you will find two labels: TX (transmit) and RX (receive). They appear in two places on the Arduino UNO board. First, at the digital pins 0 and 1, to indicate the pins responsible for serial communication. Second, the TX and RX led (13). The TX led flashes with different speed while sending the serial data. The speed of flashing depends on the baud rate used by the board. RX flashes during the receiving process. Digital I/O The Arduino UNO board has 14 digital I/O pins (15) (of which 6 provide PWM (Pulse Width Modulation) output. These pins can be configured to work as input digital pins to read logic values (0 or 1) or as digital output pins to drive different modules like LEDs, relays, etc. The pins labeled “~” can be used to generate PWM. AREF AREF stands for Analog Reference. It is sometimes, used to set an external reference voltage (between 0 and 5 Volts) as the upper limit for the analog input pins. Print Page Previous Next Advertisements ”;

Apex – Batch Processing

Apex – Batch Processing ”; Previous Next In this chapter, we will understand Batch Processing in Apex. Consider a scenario wherein, we will process large number of records on daily basis, probably the cleaning of data or maybe deleting some unused data. What is Batch Apex? Batch Apex is asynchronous execution of Apex code, specially designed for processing the large number of records and has greater flexibility in governor limits than the synchronous code. When to use Batch Apex? When you want to process large number of records on daily basis or even on specific time of interval then you can go for Batch Apex. Also, when you want an operation to be asynchronous then you can implement the Batch Apex. Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex. Batch Apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks of data. Using Batch Apex When we are using the Batch Apex, we must implement the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically. You can monitor the class by following these steps − To monitor or stop the execution of the batch Apex Batch job, go to Setup → Monitoring → Apex Jobs or Jobs → Apex Jobs. Database.Batchable interface has the following three methods that need to be implemented − Start Execute Finish Let us now understand each method in detail. Start The Start method is one of the three methods of the Database.Batchable interface. Syntax global void execute(Database.BatchableContext BC, list<sobject<) {} This method will be called at the starting of the Batch Job and collects the data on which the Batch job will be operating. Consider the following points to understand the method − Use the Database.QueryLocator object when you are using a simple query to generate the scope of objects used in the batch job. In this case, the SOQL data row limit will be bypassed. Use the iterable object when you have complex criteria to process the records. Database.QueryLocator determines the scope of records which should be processed. Execute Let us now understand the Execute method of the Database.Batchable interface. Syntax global void execute(Database.BatchableContext BC, list<sobject<) {} where, list<sObject< is returned by the Database.QueryLocator method. This method gets called after the Start method and does all the processing required for Batch Job. Finish We will now discuss the Finish method of the Database.Batchable interface. Syntax global void finish(Database.BatchableContext BC) {} This method gets called at the end and you can do some finishing activities like sending an email with information about the batch job records processed and status. Batch Apex Example Let us consider an example of our existing Chemical Company and assume that we have requirement to update the Customer Status and Customer Description field of Customer Records which have been marked as Active and which have created Date as today. This should be done on daily basis and an email should be sent to a User about the status of the Batch Processing. Update the Customer Status as ”Processed” and Customer Description as ”Updated Via Batch Job”. // Batch Job for Processing the Records global class CustomerProessingBatch implements Database.Batchable<sobject> { global String [] email = new String[] {”[email protected]”}; // Add here your email address here // Start Method global Database.Querylocator start (Database.BatchableContext BC) { return Database.getQueryLocator(”Select id, Name, APEX_Customer_Status__c, APEX_Customer_Decscription__c From APEX_Customer__c WHERE createdDate = today AND APEX_Active__c = true”); // Query which will be determine the scope of Records fetching the same } // Execute method global void execute (Database.BatchableContext BC, List<sobject> scope) { List<apex_customer__c> customerList = new List<apex_customer__c>(); List<apex_customer__c> updtaedCustomerList = new List<apex_customer__c>(); // List to hold updated customer for (sObject objScope: scope) { APEX_Customer__c newObjScope = (APEX_Customer__c)objScope ; // type casting from generic sOject to APEX_Customer__c newObjScope.APEX_Customer_Decscription__c = ”Updated Via Batch Job”; newObjScope.APEX_Customer_Status__c = ”Processed”; updtaedCustomerList.add(newObjScope); // Add records to the List System.debug(”Value of UpdatedCustomerList ”+updtaedCustomerList); } if (updtaedCustomerList != null && updtaedCustomerList.size()>0) { // Check if List is empty or not Database.update(updtaedCustomerList); System.debug(”List Size ” + updtaedCustomerList.size()); // Update the Records } } // Finish Method global void finish(Database.BatchableContext BC) { Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // Below code will fetch the job Id AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors, a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById, a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()]; // get the job Id System.debug(”$$$ Jobid is”+BC.getJobId()); // below code will send an email to User about the status mail.setToAddresses(email); mail.setReplyTo(”[email protected]”); // Add here your email address mail.setSenderDisplayName(”Apex Batch Processing Module”); mail.setSubject(”Batch Processing ”+a.Status); mail.setPlainTextBody(”The Batch Apex job processed” + a.TotalJobItems+”batches with ”+a.NumberOfErrors+”failures”+”Job Item processed are”+a.JobItemsProcessed); Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail}); } } To execute this code, first save it and then paste the following code in Execute anonymous. This will create the object of class and Database.execute method will execute the Batch job. Once the job is completed then an email will be sent to the specified email address. Make sure that you have a customer record which has Active as checked. // Paste in Developer Console CustomerProessingBatch objClass = new CustomerProessingBatch(); Database.executeBatch (objClass); Once this class is executed, then check the email address you have provided where you will receive the email with information. Also, you can check the status of the batch job via the Monitoring page and steps as provided above. If you check the debug logs, then you can find the List size which indicates how many records have been processed. Limitations We can only have 5 batch job processing at a time. This is one of the limitations of Batch Apex. Scheduling the Apex Batch Job using Apex Detail Page You can schedule the Apex class via Apex detail page as given below − Step 1 − Go to Setup ⇒ Apex Classes, Click on Apex Classes. Step 2 − Click on the Schedule Apex button. Step 3 − Provide details. Scheduling the Apex Batch Job using Schedulable Interface

Apex – Quick Guide

Apex – Quick Guide ”; Previous Next Apex – Overview What is Apex? Apex is a proprietary language developed by the Salesforce.com. As per the official definition, Apex is a strongly typed, object-oriented programming language that allows developers to execute the flow and transaction control statements on the Force.com platform server in conjunction with calls to the Force.com API. It has a Java-like syntax and acts like database stored procedures. It enables the developers to add business logic to most system events, including button clicks, related record updates, and Visualforce pages.Apex code can be initiated by Web service requests and from triggers on objects. Apex is included in Performance Edition, Unlimited Edition, Enterprise Edition, and Developer Edition. Features of Apex as a Language Let us now discuss the features of Apex as a Language − Integrated Apex has built in support for DML operations like INSERT, UPDATE, DELETE and also DML Exception handling. It has support for inline SOQL and SOSL query handling which returns the set of sObject records. We will study the sObject, SOQL, SOSL in detail in future chapters. Java like syntax and easy to use Apex is easy to use as it uses the syntax like Java. For example, variable declaration, loop syntax and conditional statements. Strongly Integrated With Data Apex is data focused and designed to execute multiple queries and DML statements together. It issues multiple transaction statements on Database. Strongly Typed Apex is a strongly typed language. It uses direct reference to schema objects like sObject and any invalid reference quickly fails if it is deleted or if is of wrong data type. Multitenant Environment Apex runs in a multitenant environment. Consequently, the Apex runtime engine is designed to guard closely against runaway code, preventing it from monopolizing shared resources. Any code that violates limits fails with easy-to-understand error messages. Upgrades Automatically Apex is upgraded as part of Salesforce releases. We don”t have to upgrade it manually. Easy Testing Apex provides built-in support for unit test creation and execution, including test results that indicate how much code is covered, and which parts of your code can be more efficient. When Should Developer Choose Apex? Apex should be used when we are not able to implement the complex business functionality using the pre-built and existing out of the box functionalities. Below are the cases where we need to use apex over Salesforce configuration. Apex Applications We can use Apex when we want to − Create Web services with integrating other systems. Create email services for email blast or email setup. Perform complex validation over multiple objects at the same time and also custom validation implementation. Create complex business processes that are not supported by existing workflow functionality or flows. Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object) like using the Database methods for updating the records. Perform some logic when a record is modified or modify the related object”s record when there is some event which has caused the trigger to fire. Working Structure of Apex As shown in the diagram below (Reference: Salesforce Developer Documentation), Apex runs entirely on demand Force.com Platform Flow of Actions There are two sequence of actions when the developer saves the code and when an end user performs some action which invokes the Apex code as shown below − Developer Action When a developer writes and saves Apex code to the platform, the platform application server first compiles the code into a set of instructions that can be understood by the Apex runtime interpreter, and then saves those instructions as metadata. End User Action When an end-user triggers the execution of Apex, by clicking a button or accessing a Visualforce page, the platform application server retrieves the compiled instructions from the metadata and sends them through the runtime interpreter before returning the result. The end-user observes no differences in execution time as compared to the standard application platform request. Since Apex is the proprietary language of Salesforce.com, it does not support some features which a general programming language does. Following are a few features which Apex does not support − It cannot show the elements in User Interface. You cannot change the standard SFDC provided functionality and also it is not possible to prevent the standard functionality execution. Creating multiple threads is also not possible as we can do it in other languages. Understanding the Apex Syntax Apex code typically contains many things that we might be familiar with from other programming languages. Variable Declaration As strongly typed language, you must declare every variable with data type in Apex. As seen in the code below (screenshot below), lstAcc is declared with data type as List of Accounts. SOQL Query This will be used to fetch the data from Salesforce database. The query shown in screenshot below is fetching data from Account object. Loop Statement This loop statement is used for iterating over a list or iterating over a piece of code for a specified number of times. In the code shown in the screenshot below, iteration will be same as the number of records we have. Flow Control Statement The If statement is used for flow control in this code. Based on certain condition, it is decided whether to go for execution or to stop the execution of the particular piece of code. For example, in the code shown below, it is checking whether the list is empty or it contains records. DML Statement Performs the records insert, update, upsert, delete operation on the records in database. For example, the code given below helps in updating Accounts with new field value. Following is an example of how an Apex code snippet will look like. We are going to study all these Apex programming concepts further in this tutorial. Apex – Environment In this chapter, we will understand the environment for our Salesforce Apex development. It is assumed that you already have a Salesforce edition

Apex – Trigger Design Patterns

Apex – Trigger Design Patterns ”; Previous Next Design patterns are used to make our code more efficient and to avoid hitting the governor limits. Often developers can write inefficient code that can cause repeated instantiation of objects. This can result in inefficient, poorly performing code, and potentially the breaching of governor limits. This most commonly occurs in triggers, as they can operate against a set of records. We will see some important design pattern strategies in this chapter. Bulk Triggers Design Patterns In real business case, it will be possible that you may need to process thousands of records in one go. If your trigger is not designed to handle such situations, then it may fail while processing the records. There are some best practices which you need to follow while implementing the triggers. All triggers are bulk triggers by default, and can process multiple records at a time. You should always plan to process more than one record at a time. Consider a business case, wherein, you need to process large number of records and you have written the trigger as given below. This is the same example which we had taken for inserting the invoice record when the Customer Status changes from Inactive to Active. // Bad Trigger Example trigger Customer_After_Insert on APEX_Customer__c (after update) { for (APEX_Customer__c objCustomer: Trigger.new) { if (objCustomer.APEX_Customer_Status__c == ”Active” && trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == ”Inactive”) { // condition to check the old value and new value APEX_Invoice__c objInvoice = new APEX_Invoice__c(); objInvoice.APEX_Status__c = ”Pending”; insert objInvoice; //DML to insert the Invoice List in SFDC } } } You can now see that the DML Statement has been written in for the loop block which will work when processing only few records but when you are processing some hundreds of records, it will reach the DML Statement limit per transaction which is the governor limit. We will have a detailed look on Governor Limits in a subsequent chapter. To avoid this, we have to make the trigger efficient for processing multiple records at a time. The following example will help you understand the same − // Modified Trigger Code-Bulk Trigger trigger Customer_After_Insert on APEX_Customer__c (after update) { List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>(); for (APEX_Customer__c objCustomer: Trigger.new) { if (objCustomer.APEX_Customer_Status__c == ”Active” && trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == ”Inactive”) { //condition to check the old value and new value APEX_Invoice__c objInvoice = new APEX_Invoice__c(); objInvoice.APEX_Status__c = ”Pending”; InvoiceList.add(objInvoice);//Adding records to List } } insert InvoiceList; // DML to insert the Invoice List in SFDC, this list contains the all records // which need to be modified and will fire only one DML } This trigger will only fire 1 DML statement as it will be operating over a List and the List has all the records which need to be modified. By this way, you can avoid the DML statement governor limits. Trigger Helper Class Writing the whole code in trigger is also not a good practice. Hence you should call the Apex class and delegate the processing from Trigger to Apex class as shown below. Trigger Helper class is the class which does all the processing for trigger. Let us consider our invoice record creation example again. // Below is the Trigger without Helper class trigger Customer_After_Insert on APEX_Customer__c (after update) { List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>(); for (APEX_Customer__c objCustomer: Trigger.new) { if (objCustomer.APEX_Customer_Status__c == ”Active” && trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == ”Inactive”) { // condition to check the old value and new value APEX_Invoice__c objInvoice = new APEX_Invoice__c(); objInvoice.APEX_Status__c = ”Pending”; InvoiceList.add(objInvoice); } } insert InvoiceList; // DML to insert the Invoice List in SFDC } // Below is the trigger with helper class // Trigger with Helper Class trigger Customer_After_Insert on APEX_Customer__c (after update) { CustomerTriggerHelper.createInvoiceRecords(Trigger.new, trigger.oldMap); // Trigger calls the helper class and does not have any code in Trigger } Helper Class public class CustomerTriggerHelper { public static void createInvoiceRecords (List<apex_customer__c> customerList, Map<id, apex_customer__c> oldMapCustomer) { List<apex_invoice__c> InvoiceList = new Listvapex_invoice__c>(); for (APEX_Customer__c objCustomer: customerList) { if (objCustomer.APEX_Customer_Status__c == ”Active” && oldMapCustomer.get(objCustomer.id).APEX_Customer_Status__c == ”Inactive”) { // condition to check the old value and new value APEX_Invoice__c objInvoice = new APEX_Invoice__c(); // objInvoice.APEX_Status__c = ”Pending”; InvoiceList.add(objInvoice); } } insert InvoiceList; // DML to insert the Invoice List in SFDC } } In this, all the processing has been delegated to the helper class and when we need a new functionality we can simply add the code to the helper class without modifying the trigger. Single Trigger on Each sObject Always create a single trigger on each object. Multiple triggers on the same object can cause the conflict and errors if it reaches the governor limits. You can use the context variable to call the different methods from helper class as per the requirement. Consider our previous example. Suppose that our createInvoice method should be called only when the record is updated and on multiple events. Then we can control the execution as below − // Trigger with Context variable for controlling the calling flow trigger Customer_After_Insert on APEX_Customer__c (after update, after insert) { if (trigger.isAfter && trigger.isUpdate) { // This condition will check for trigger events using isAfter and isUpdate // context variable CustomerTriggerHelper.createInvoiceRecords(Trigger.new); // Trigger calls the helper class and does not have any code in Trigger // and this will be called only when trigger ids after update } } // Helper Class public class CustomerTriggerHelper { //Method To Create Invoice Records public static void createInvoiceRecords (List<apex_customer__c> customerList) { for (APEX_Customer__c objCustomer: customerList) { if (objCustomer.APEX_Customer_Status__c == ”Active” && trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == ”Inactive”) { // condition to check the old value and new value APEX_Invoice__c objInvoice = new APEX_Invoice__c(); objInvoice.APEX_Status__c = ”Pending”; InvoiceList.add(objInvoice); } } insert InvoiceList; // DML to insert the Invoice List in SFDC } } Print Page Previous Next Advertisements ”;