MODULE III Arduino Programming
Write a Arduino program to read the analog joystick value and display the direction of joystick action on serial monitor. Use baud-rate of 9600.
Interfacing a Joystick
The Joystick
Schematic
Internet of Things (IoT) EC4045 Open Elective-II
Prepared by Asst.Prof. Ayaskanta Mishra, School of Electronics Engineering, KIIT How this works
The joystick in the picture is nothing but two potentiometers that allow us to messure the movement of the stick in 2-D. Potentiometers are variable resistors and, in a way, they act as sensors providing us with a variable voltage depending on the rotation of the device around its shaft.
The kind of program that we need to monitor the joystick has to make a polling to two of the analog pins. We can send these values back to the computer, but then we face the classic problem that the transmission over the communication port has to be made with 8bit values, while our DAC (Digital to Analog Converter - that is messuring the values from the
potentiometers in the joystick) has a resolution of 10bits. In other words this means that our sensors are characterized with a value between 0 and 1024.
The following code includes a method called treatValue() that is transforming the sensor's messurement into a value between 0 and 9 and sends it in ASCII back to the computer. This allows to easily send the information into e.g. Flash and parse it inside your own code.
Finally we make the LED blink with the values read from the sensors as a direct visual feedback of how we control the joystick.
/* Read Jostick * --- *
* Reads two analog pins that are supposed to be * connected to a jostick made of two potentiometers *
* We send three bytes back to the comp: one header and two * with data as signed bytes, this will take the form:
* Jxy\r\n *
* x and y are integers and sent in ASCII *
* http://www.0j0.org | http://arduino.berlios.de * copyleft 2005 DojoDave for DojoCorp
*/
int ledPin = 13;
int joyPin1 = 0; // slider variable connecetd to analog pin 0 int joyPin2 = 1; // slider variable connecetd to analog pin 1
int value1 = 0; // variable to read the value from the analog pin 0 int value2 = 0; // variable to read the value from the analog pin 1
void setup() {
pinMode(ledPin, OUTPUT); // initializes digital pins 0 to 7 as outputs Serial.begin(9600);
}
int treatValue(int data) { return (data * 9 / 1024) + 48;
}
void loop() {
// reads the value of the variable resistor value1 = analogRead(joyPin1);
// this small pause is needed between reading
// analog pins, otherwise we get the same value twice delay(100);
// reads the value of the variable resistor value2 = analogRead(joyPin2);
digitalWrite(ledPin, HIGH);
delay(value1);
digitalWrite(ledPin, LOW);
delay(value2);
Serial.print('J');
Serial.print(treatValue(value1));
Serial.println(treatValue(value2));
}
Write a Arduino program to read data from a GSM modem and write it on the serial monitor. Draw the pin connection diagram for UART communication with suitable components.
Connecting GSM Module to Arduino
There are two ways of connecting GSM module to arduino. In any case, the communication between Arduino and GSM module is serial. So we are supposed to use serial pins of Arduino (Rx and Tx). So if you are going with this method, you may connect the Tx pin of GSM module to Rx pin of Arduino and Rx pin of GSM module to Tx pin of Arduino. You read it right ? GSM Tx –> Arduino Rx and GSM Rx –> Arduino Tx. Now connect the ground pin of arduino to ground pin of gsm module! So that’s all! You made 3 connections and the wiring is over! Now you can load different programs to communicate with gsm module and make it work.
Note:- The problem with this connection is that, while programming Arduino uses serial ports to load program from the Arduino IDE. If these pins are used in wiring, the program will not be loaded successfully to Arduino. So you have to disconnect wiring in Rx and Tx each time you burn the program to arduino. Once the program is loaded successfully, you can reconnect these pins and have the system working!
To avoid this difficulty, I am using an alternate method in which two digital pins of arduino are used for serial communication. We need to select two PWM enabled pins of arduinofor this method. So I choose pins 9 and 10 (which are PWM enabled pins). This method is made possible with the SoftwareSerial Library of Ardunio. SoftwareSerial is a library of Arduino which enables serial data communication through other digital pins of Arduino. The library replicates hardware functions and handles the task of serial communication.
I hope you understood so far! Lets get to the circuit diagram! So given below is the circuit diagram to connect gsm module to arduino – and hence use the circuit to send sms and receive sms using arduino and gsm modem.
Internet of Things (IoT) EC4045
Make the connections as shown! Now lets get to the coding part. The program has two objectives as described below:-
1) Send SMS using Arduino and GSM Module program
2) Receive SMS using Arduino and GSM Module Module.
The Program
#include <SoftwareSerial.h>
SoftwareSerial mySerial(9, 10);
void setup() {
mySerial.begin(9600); // Setting the baud rate of GSM Module Serial.begin(9600); // Setting the baud rate of Serial Monitor (Arduino) delay(100);
}
void loop() {
if (Serial.available()>0) switch(Serial.read()) {
case 's':
SendMessage();
break;
case 'r':
RecieveMessage();
break;
}
if (mySerial.available()>0) Serial.write(mySerial.read());
}
Internet of Things (IoT) EC4045 Open Elective
Make the connections as shown! Now lets get to the coding part. The program has two Arduino and GSM Module – to a specified mobile number inside the Receive SMS using Arduino and GSM Module – to the SIM card loaded in the GSM
// Setting the baud rate of GSM Module // Setting the baud rate of Serial Monitor (Arduino)
Open Elective-II
Make the connections as shown! Now lets get to the coding part. The program has two to a specified mobile number inside the to the SIM card loaded in the GSM
void SendMessage() {
mySerial.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode delay(1000); // Delay of 1000 milli seconds or 1 second
mySerial.println("AT+CMGS=\"+91xxxxxxxxxx\"\r"); // Replace x with mobile number delay(1000);
mySerial.println("I am SMS from GSM Module");// The SMS text you want to send delay(100);
mySerial.println((char)26);// ASCII code of CTRL+Z delay(1000);
}
void RecieveMessage() {
mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS delay(1000);
}
so that’s the program/code to make arduino send sms and receive sms using gsm module!
Let’s get to explanation of program!
The Program Explanation
We begin by including SoftwareSerial library into the program. In the next line, we create a constructor of SoftwareSerial with name mySerial and we pass the digital pin numbers as parameters. The actual format is like SoftwareSerial mySerial (Rx, Tx);
So in our code, pin number 9 will act as Rx of Arduino and 10 will act as Tx of Arduino. Lets get to the configuration part of program inside setup. The first task is to set baud rates of SoftwareSerial library to communicate with GSM module. We achieve this by invoking mySerial.begin function. Our second task is to set the baud rate of Arduino IDE’s Serial Monitor. We do this by invoking Serial.begin function. Both should be set at the same baud rate and we use 9600 bits/second here in our tutorial. Configuration part is over with setting baud rates and its good to give a small delay of 100 milli seconds.
Now lets get to the actual program inside loop(). To make things simpler, I have developed a user input based program. The program seeks user input via serial monitor of Arduino. If the input is ‘s’ the program will invoke function to send an sms from GSM module. If the user input is ‘r’, the program will invoke the function to receive a live SMS from GSM module and display it on serial monitor of Arduino. The whole program is as simple as that!
Serial.available() – checks for any data coming through serial port of arduino. The function returns the number of bytes available to read from serial buffer. If there is no data available, it returns a -1 (value less than zero).
Serial.read() – Reads all the data available on serial buffer (or incoming serial data if put otherwise). Returns the first byte of incoming serial data.
mySerial.available() – checks for any data coming from GSM module through the SoftwareSerial pins 9 and 10. Returns the number of bytes available to read from software serial port. Returns a -1 if no data is available to read.
mySerial.read() – Reads the incoming data through software serial port.
Serial.write() – Prints data to serial monitor of arduino. So the function Serial.write(mySerial.read()) – prints the data collected from software serial port to serial monitor of arduino.
Lets get the functions SendMessage() and RecieveMessage()
Internet of Things (IoT) EC4045 Open Elective-II
Prepared by Asst.Prof. Ayaskanta Mishra, School of Electronics Engineering, KIIT
These are the functions in which we actually send commands to GSM module from Arduino.
These commands to communicate with GSM module are called AT Commands. There are different commands to perform different tasks using the GSM module. You can read complete AT Commands Library to understand all that is possible with GSM module.
SendMessage() – is the function we created in our arduino sketch to send an SMS. To send an SMS, we should set our GSM module to Text mode first. This is achieved by sending an AT Command “AT+CMGF=1” We send this command by writing this to SoftwareSerial port. To achieve this we use the mySerial.println() function. mySerial.println writes data to software serial port (the Tx pin of our Software Serial – that is pin 10) and this will be captured by GSM module (through its Rx pin). After setting the GSM module to Text mode, we should the the mobile number to which we shall send the SMS. This is achieved with AT command “AT+CMGS=\”+91xxxxxxxxxx\”\r” – where you may replace all x with the mobile number.
In next step, we should send the actual content of SMS. The end of SMS content is identified with CTRL+Z symbol. The ASCII value of this CTRL+Z is 26. So we send a char(26) to GSM module using the line mySerial.println((char)26); Each and every AT command may be followed by 1 second delay. We must give some time for GSM module to respond properly.
Once these commands are send to GSM module, you shall receive an SMS in the set mobile number.
RecieveMessage() – is the function to receive an SMS (a live SMS). The AT command to receive a live SMS is “AT+CNMI=2,2,0,0,0” – we just need to send this command to GSM module and apply a 1 second delay. Once you send this command, try sending an SMS to the SIM card number put inside GSM module. You will see the SMS you had sent displayed on your Arduino serial monitor.
There are different AT commands for different tasks. If you want to read all SMS’s stored in your SIM card, send the following AT Command to gsm module – “AT+CMGL=\”ALL\”\r”
Okay! That’s all and you are done. And you have learnt how to use arduino to send sms and receive sms message with example code.
I shall summarize this tutorial on how to send/receive a text message using arduino and gsm module with the following notes:-
AT Commands to Send SMS using Arduino and GSM Module
AT+CMGF=1 // Set the GSM module in text mode
AT+CMGS=\"+YYxxxxxxxxxx\"\r // Input the mobile number| YY is country code
“the message” with stopping character (char)26 // ASCII of ctrl+z AT Commands to Receive SMS using Arduino and GSM Module
AT+CMGF=1 // Set the GSM Module in text mode AT+CNMI=2,2,0,0,0 // AT Command to receive live sms
Read the AT commands library and start playing with your GSM module and Arduino! If you have any doubts please ask in comments.
Write a program for Arduino UNO to read analog temperature and humidity data using analog read and there is a R-G-B LED as output device. When the temperature value is less that 50º C and humidity is less than 50% the Green LED should glow.
When the temperature is in between 50 º C to 100º C and humidity is above 75% blue
LED should glow. When the temperature is above 100º C and humidity is above 90%
red LED should glow. If none of these three condition satisfies no LED should glow.
[Student Task]
Write a simple Arduino program to blink a LED with 500 msec. delay in between On and off.
The value of the resistor in series with the LED may be of a different value than 220 ohm; the LED will lit up also with values up to 1K ohm.
Code
After you build the circuit plug your Arduino or Genuino board into your computer, start the Arduino Software (IDE) and enter the code below. You may also load it from the menu File/Examples/01.Basics/Blink . The first thing you do is to initialize LED_BUILTIN pin as an output pin with the line
pinMode(LED_BUILTIN, OUTPUT);
In the main loop, you turn the LED on with the line:
digitalWrite(LED_BUILTIN, HIGH);
This supplies 5 volts to the LED anode. That creates a voltage difference across the pins of the LED, and lights it up. Then you turn it off with the line:
digitalWrite(LED_BUILTIN, LOW);
That takes the LED_BUILTIN pin back to 0 volts, and turns the LED off. In between the on and the off, you want enough time for a person to see the change, so the delay() commands
Internet of Things (IoT) EC4045 Open Elective-II
Prepared by Asst.Prof. Ayaskanta Mishra, School of Electronics Engineering, KIIT tell the board to do nothing for 1000 milliseconds, or one second. When you use
the delay() command, nothing else happens for that amount of time. Once you've understood the basic examples, check out the BlinkWithoutDelay example to learn how to create a delay while doing other things.
Once you've understood this example, check out the DigitalReadSerial example to learn how read a switch connected to the board.
/*
Blink
Turns an LED on for one second, then off for one second, repeatedly.
Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to the correct LED pin independent of which board is used.
If you want to know what pin the on-board LED is connected to on your Arduino model, check the Technical Specs of your board at:
https://www.arduino.cc/en/Main/Products
modified 8 May 2014 by Scott Fitzgerald modified 2 Sep 2016 by Arturo Guadalupi modified 8 Sep 2016 by Colby Newman
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Blink
*/
// the setup function runs once when you press reset or power the board void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs over and over again forever void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(500); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(500); // wait for a second
}
The ADC inside Arduino UNO is how many bits? If the analog voltage input in 0- 5 V, calculate the resolution.
If you supply PIC with 5 V and your reference voltage is Vsupply then in case of 10 bit ADC you have 2^10 -1 = 1024 - 1 = 1023 steps for 5 V . 5 V / 1023 = 4.88 mV -> each step of ADC represents 4.88 mV . The resolution of ADC is 4.88 mV .
Draw a simple 230 V AC bulb ON/OFF circuit using LDR and required other components. Write very briefly for each component working for ON / OFF cases.
A simple project using an Arduino: automatically turn lights on when an LDR sensor detects darkness.
This system works by sensing the intensity of light in its environment. The sensor that can be used to detect light is an LDR. It's inexpensive, and you can buy it from any local electronics store or online.
The LDR gives out an analog voltage when connected to VCC (5V), which varies in magnitude in direct proportion to the input light intensity on it. That is, the greater the intensity of light, the greater the corresponding voltage from the LDR will be. Since the LDR gives out an analog voltage, it is connected to the analog input pin on the Arduino. The Arduino, with its built-in ADC (analog-to-digital converter), then converts the analog voltage (from 0-5V) into a digital value in the range of (0-1023). When there is sufficient light in its environment or on its surface, the converted digital values read from the LDR through the Arduino will be in the range of 800-1023.
Circuit
Code
const int lamp = 2;
boolean x = true;
.
void setup() {
Serial.begin(9600);
pinMode(lamp , OUTPUT);
}
void loop() {
int c = analogRead(A0);
delay(500);
if ( c<300 && x == true){
digitalWrite(lamp,HIGH);
x = false;
delay(1000);
}
Internet of Things (IoT) EC4045 Open Elective-II
Prepared by Asst.Prof. Ayaskanta Mishra, School of Electronics Engineering, KIIT
else if ( c <300 && x == false){
x = true;
digitalWrite(lamp,LOW);
delay(1000);
} }
Write an Arduino Program from breathing LED.
Circuit
Connect the anode (the longer, positive leg) of your LED to digital output pin 9 on your board through a 220 ohm resistor.
Connect the cathode (the shorter, negative leg) directly to ground.
click the image to enlarge
image developed using Fritzing. For more circuit examples, see the Fritzing project page
Code
After declaring pin 9 to be your ledPin, there is nothing to do in the setup() function of your code.
The analogWrite() function that you will be using in the main loop of your code requires two arguments: One telling the function which pin to write to, and one indicating what PWM value to write.
In order to fade your LED off and on, gradually increase your PWM value from 0 (all the way off) to 255 (all the way on), and then back to 0 once again to complete the cycle. In the sketch below, the PWM value is set using a variable called brightness. Each time through the loop, it increases by the value of the
variable fadeAmount.
If brightness is at either extreme of its value (either 0 or 255), then fadeAmount is changed to its negative. In other words, if fadeAmount is 5, then it is set to -5. If it's -5, then it's set to 5. The next time through the loop, this change causes brightness to change direction as well.
analogWrite() can change the PWM value very fast, so the delay at the end of the sketch controls the speed of the fade. Try changing the value of the delay and see how it changes the fading effect.
/*
Fade
This example shows how to fade an LED on pin 9 using the analogWrite() function.
The analogWrite() function uses PWM, so if you want to change the pin you're using, be sure to use another PWM capable pin. On most Arduino, the PWM pins are identified with a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Fade
*/
int led = 9; // the PWM pin the LED is attached to int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness <= 0 || brightness >= 255) { fadeAmount = -fadeAmount;
}
// wait for 30 milliseconds to see the dimming effect delay(30);
}