0% found this document useful (0 votes)
35 views52 pages

Iot Unit 2 Book

This document provides an overview of sensor interfacing with microcontrollers, focusing on various types of sensors such as gas, obstacle, heartbeat, and ultrasonic sensors. It includes procedures for interfacing these sensors with microcontrollers like NodeMCU and Arduino, along with code snippets for reading data and uploading it to cloud services like Adafruit. The document emphasizes the importance of understanding sensor types and their applications in building IoT systems.

Uploaded by

joelroys637
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
35 views52 pages

Iot Unit 2 Book

This document provides an overview of sensor interfacing with microcontrollers, focusing on various types of sensors such as gas, obstacle, heartbeat, and ultrasonic sensors. It includes procedures for interfacing these sensors with microcontrollers like NodeMCU and Arduino, along with code snippets for reading data and uploading it to cloud services like Adafruit. The document emphasizes the importance of understanding sensor types and their applications in building IoT systems.

Uploaded by

joelroys637
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 52
COPTER TONS TN Microcontrollers, and Their Interfacing LEARNING OBJECTIVES The chapter will help readers acquire an in-depth understanding of Different types of sensors and their use. Procedure to interface sensors to the microcontroller (computing boards). Procedure to control the sensors through webpages. Techniques to load the data Fundamentals of the most frequently used microcontrollers (8051 and ARM 7) -nsed to the cloud. Introduction to Sensor Interfacing There are numerous sensors available in the market and it is essential to know about these sensors to build a complete/comprehensive IoT system. In this chapter, the reader shalll be introduced to sensors that are frequently used towards building IoT applications. Also, the procedure for interfacing with the sensors is presented along with the software code for reference. It is recommended that readers have a hands-on experience with the code pre- sented. Also, for some interfacing exercises, the codes for uploading the data to the cloud are also presented. Readers need not worry much about the cloud part right now. It is covered in depth as part of the subsequent chapters. Readers are expected to install the Arduino IDE and follow the procedure as mentioned in Annexure Al, Arduino IDE supports most of the available embedded boards in the market. Selection of board from the available menu is an important step. Types of Sensors 2.2.1 MQ-02/05 - Gas Sensor Interfacing with NodeMCU/Arduino. Before getting gas sensor. -depth about how to interface, it is essential to also learn about MQ-02 FREE SAIS AT SRG In many malls we find smoke sensors on the ceilings which are designed in order to detect smoke (fire) and sprinkle water during outbreak of fire accidents. MQ-02 is capable of detecting H,, LPG, CH,, alcohol, and smoke. It is used vastly because of its quick and rapid response, When any flammable gas flows through this sensor, the coil inside this sensor burns and so the resistance of the coil decreases. Hence, the output voltage starts increasing, which can be detected using a microcontroller. There is another sensor by name MQ-05 also available in the market but it is not sensitive to smoke and hence is not preferred for smoke/ fire detection applications. Figure 2.1 shows how MQ-02 looks like. Figure 2.1 MQ-02 sensor. Figure 2.2 illustrates how this sensor functions, Also do note the following points: 1. Greater the gas concentratioi , greater is the output voltage. 2. Lower the gas concentration, lower is the output voltage. _ ¢g- Presence of smoke 1MQ-02 sensor ‘Voltage variation (output) Figure 2.2 Schematic representing functioning of MQ-02. Now, let us design a circuit using MQ-02 gas sensor to monitor the smoke percentage and upload those values to the cloud. (Readers need not worry about the cloud part; Chapter 5 covers cloud in detail.) MQ-02 generally has 4 pins. Figure 2.3 shows the pin layout of MQ-02. 22 Typesotsensos EEE ras ee PUR-LED Ug cd VCC (+5) % ~ - Ground (ume) , lg ait od ad “ ‘Analog output on Figure 2.3 Pin layout of MO-02 sensor. As it can be seen from Fig. 2.3 that MQ-02 has VCC (power), Ground followed by Analog and Digital pins. One can read the data as analog or digital based on the requirement and necessity. The connection diagram with the NodeMCU is presented in Fig. 2.4. One can see that AO pin is connected to Data (Analog pin) of MO-02. Also, Ground and VCC are con- nected appropriately at both the ends. The code to read the analog data is also provided. MQ-02 gas sensor Figure 2.4 Connection diagram — NodeMCU to MQ-02 sensor. HEE rociction to sensors, Microcontars, and Ther nteracing Code to interface AO of NodeMCU with MQ-02: finclude include int val; #define USE_SERIAL Serial #define GAS SENSOR AO // AO of NodeMCU is connected to Analog pin of MQ-02 void setup () { Serial begin (115200); // Baud rate. This has to be usiform in the IDB and Serial Monitor. delay (10); 1 void loop() { val=analogRead (GAS_SENSOR) ; 7 Analog read for reading any analog input. Serial.print (val); // Here, we print the value read through the serial monitor. Serial.printin(* "); delay(100) + 1 ‘The above code will read the sensory data and display the same through the serial monitor. ‘The compilation procedure is also summarized in Annexure A through which the reader can understand the flow. ‘The next section of the code is presented to get the sensed data stored in the cloud. Readers can choose any cloud service provider. Authors have chosen Adafruit as it is simple, easy to use, and most importantly free to use (with constraints). The procedure for setting up ‘Adafruit account is presented elaborately in Chapter 5. Readers are expected to have a look 22 WesotSensos ETE at the same to derive better clarity. Also, the term MOTT is used in the code frequently. We will explain this in depth with appropriate demo in later sections. The following code snippets shall help in getting the data to the cloud. Code snippet 2.1 shows the connection procedure to the Wi-Fi and the initialization steps. #includecAdafruit MOTT Client.h> #includecESPé266WiFi.h> fdefine wifi_name “Your SSID” define pswd “Your Wifi Password” fdefine server “io.adafruit.com” fdefine port 1883 define username “Your Adafruit User 1D” fdefine aiokey “Your AIO Key” Code Snippet 2.1 Initialization steps for connecting to the Intemet. Code snippet 2.2 is for setting up Wi-Fi connection and Adafruit client initialization steps. WiFiclient me; Adafruit MQTT Client matt (sme, server, port username, aickey) + Adafruit MOTT Publishgas_data~Adafruit MOTT Publish(smgtt, username” /feeds/ Gas_sensor”) ; void setup() { Serial begin (9600); delay(10); Serial.printin ("Connecting to “); Serial.print (wifi_name); WiFi -begin(wifi_name, pswa); while (WiPi.status() != WL CONNECTED) ‘ delay (500); Serial.print ("."); ) Code Snippet 2.2 Connecting to the Internet and initializing Adafruit cloud client. Now, the final step is to upload the obtained data from the sensor to the feed inside the Ada- fruit cloud. The following code does the above mentioned job. As seen in the simple analog read code, here also, the AO port is read for the data through code snippet 2.3. void loop() { if (matt connected ()) { int Gas_value= analogRead(A0); Serial. print1n(Gas_value); Code Snippet 2.3 Uploading the data into the cloud. HIRE itn sors esac ui Serial print ("Trying"); ) delay (200) Code Snippet 2.3 Continued. The screenshot in Fig. 2.5 shows the data which is uploaded to cloud with the time of upload and the corresponding sensor value (for this, the user should have already logged in with corresponding Adafruit account; the procedure is presented in Chapter 5). With the same code, one can interface any MQ sensors to the microcontroller with ease. There are many MO sensors available in the market and the purpose of the sensors is the same: to detect the smoke/gas, ete, Selection of sensors is difficult yet crucial and attention should be paid at this, stage. Following are points one should consider before selecting any sensor: 1. Cost. 2. Precision and accuracy. Understanding the environment. 4, Signal conditioning (removal of noise and other factors should be fea: ADC/DAC support availability 6. Size of the sensor (form factor) PRLS z Perey Ea Ee eT Ae 2018-06-24 3:01:03 pm ee Perr) 3:00:59 pm oda ee eal ta eto eee Figure 2.5 Uploaded cloud data. J predominantly used NodeMCU and Ardui is remain the sare. ards in this chapter. ¥ can use whichever y 22 Types of Sensors 2.2.2 Interfacing the Obstacle Sensor In real-time applications we use IR sensors for detecting the obstacles. A practical example could be easier to understand. Assume that a robot is deployed to detect the obstacles in the path, The robot has to detect and alert the presence of any obstacle on the way. So, here we use IR sensors which give either zero or one as its digital output based on the presence of the obstacle, The entire process through which the obstacle is sensed and the data is moved to cloud is presented in the code written below. Code snippet 2.4 is meant for establishing the connection to Adafruit client. An obstacle sensor is captured as a snap and is presented as Fig. 2.6. Also, one can clearly understand the interfacing details by referring to Fig. 2.7, Figure 2.7 Connection diagram for the IR sensor. Introduction to Sensors, Microcontrollers, and Their interfacing WiFiclient mer Adafruit_MOTT Client matt (Ame, server,port username, aiokey) + Adafruit MOTT Publish gas_data = Adafruit_MorT_Publish(eatt, usernane"/feeds/ 1R_data"); Code Snippet 2.4 Connection to Adafruit client. In code snippet 2.5, the following line is used to obtain digital output data from the IR sensor which is then processed to know whether an obstacle is present or not. int TR_stat= digitalRead(IR sensor); If the IR_stat value is equal to 1 then it depicts that the obstacle is pres- ent else it is not present. void loop () { 4£ (mgt .connected() } ( //Read data from 7th digital pin int TR_stat= analogRead (D3) Serial.printin(IR-stat) : Serial.print("..."); 4£(IR_data.publish(IR_stat) ) { Serial.printin ("success") ; else Serial print ("trying"); b ) delay (2000); , Code Snippet 2.5 Read the data and uploading to the cloud. Code snippet 2.6 is the code for acknowledging the presence of an obstacle in front of the sensor. if(IR_stat = t vy Serial.printin ("Something is present infront of me”); } else { Serial.printin ("The way is clear"); ) Code Snippet 2.6 Detecting the presence of the obstacle. 22 Typesof Sensors Now, et us understand how the IR sensor talks to us when it detects an obstacle present in front of it. The sensor gives out an output voltage which is of an order of few millivolts. One has to note that this generated voltage is digital, that is, either 1 or 0. So, we can just know whether an obstacle is present or not, One can refer to Fig, 28 to understand the working of IR sensor. —> IR sensor in the Generates a digital > robot voltage output Figure 2.8 Working on an IR sensor. One can also read the data as analog. However, we choose digital in this exercise as the target isto just detect the presence of an obstacle and not the size of the obstacle or other parameters. By now readers must be wondering: Why always Adafruit? Is there no other cloud service provider available? The answer is that you can choose any cloud service provider and code. Only some minimal ‘modifications are to be carried out in the code based an which the cloud service provider is chosen. 2.2.3 Interfacing the Heartbeat Sensor This is one of the very interesting interfacing exercises. Nowadays there are many applica- tions that use this sensor like the wearable applications which monitor the heartbeat accu- rately. The applications are mostly in the healthcare domain and the sensor is inexpensive. Here, in this exercise, heartbeat sensor is interfaced with Arduino UNO board and data is loaded onto the cloud. A heartbeat sensor is shown in Fig. 2.9 for the reader to have a look at how it looks. It is really small in size and affordable as well. 35 WEG iticton sear, icon nd Taran Figure 2.9 Heartbeat sensor. The interfacing diagrams presented in Fig. 2.10. Again,one could use NodeMCU or Arduino versions based on the availability and comfort. Figure 2.10 Connection diagram for heartbeat sensor. Code snippets 2.7, 2.8, and 2.9 reveal the pin initializations and data uploading part to the cloud WiFiclient me; Adafruit MOT? Client mgt (éme, server, port, username, aickey) : Adafruit MOTT Publish gas_data = Adafruit MOTT Publish (smgtt,username”/feeds/heartbeat_data”); Code Snippet 2.7 First part - Initialization. 22) est Si By performing an analog Read on the pin AO of Arduino, one can obtain data from the heartbeat sensor. Code snippet 2.8 shows the code snippet for implementing the above task. (GB) readers shovid understand tht the reed has to be analog read (oot dial ead) as one has to measure = the xact count of heat nstead of measung whether he parson sale ore void 1loop() { if (mgt connected () ) 1 int heartheat= analogRead (Ad); Serial.printin (heartbeat); Serial.print (*..."); Af (heartbeat_data.publish (heartbeat) ) { Serial.printin (“success”); ’ else { Serial.print ("frying"): 1 ) delay (2000); } Code Snippet 2.8 Data acquisition and data upload Code snippet 2.8 is meant for the data acquisition and the data upload. Code snippet 2.9 is meant to understand if the heartbeat is normal or not. This is done by comparing the thresh- old value with the read data. Lf (BPM >= 80) ( Serial.printin ("Rapid Heart beat”); ' else if(BPM <= 32) i Serial.printin ("tow heatbeat"); ' else 4 Serial.println ("You are PINE..1!"); ' Code Snippet 2.9 Thresholding the heartbeat values. [ERED todiction to Sensors, Micocontrolrs, and Ther interfacing Figure 2.11 represents how the heartbeat sensor functions. This sensor outputs a signal which must be analysed using a special method called Pulse Width Modulation (PWM). Fortunately, all this PWM will be done by the Arduino using the analog read command and the programmer need not do anything in addition, — —- Heartbeat sensor Generates adigtl Calcuates the BPM ‘on he finger square wave es output (Goats per minute) Figure 2.11 Usage and measurement of BPM using sensor. % (GB one can atvays ask: Do | have to know about al the sensors to learn oT? The answer is yes. Only then [L_ can one choose the right sensor for an application, 2.2.4 Interfacing the Ultrasonic Sound Sensor ‘These sensors are generally used to measure the distance of the objects surrounding us. The principle of these sensors is that they emanate ultrasonic sound which travels and hits the object surrounding us. The received ultrasonic pulse is captured by the sensor. By perform- ing some math on the obtained value, we can get the distance of the object from the sensor. This sensor can only measure the distance from the object and cannot determine which type of object is present around it. Now, let us dive into the coding part for ultrasonic sensor (code snippets 2.10-2.12). A simple application which one can connect to the ultrasonic sound sensor is automated parking. Figure 2.12 depicts how an ultrasonic sensor looks like. ‘The interfacing diagram is presented as Fig. 2.13. Figure 2.12 Ultrasonic sensor. 22 Types of Sensors SIoc\toe tered Figure 2.13 Connection diagram for ultrasonic sensor (HC-SR04). fdefine Trigger Pin 11 //D11 fdefine Echo pin 12 //D12 void setup() i Serial. becin (9500); pinMode (Trigger Pin, OUTPUT); pinMode(Echo_pin, INPUT); ' Code Snippet 2.10 Pin initialization for transmitter and receiver pins. Code snippet 2.10 deals with the initialization whereas code snippet 2.11 reveals the process of generating and receiving the ultrasonic pulses. Code snippet 2.12 shows how the data is uploaded to the cloud. double duration , distance; digitalWrite (Trigger_pin, Low); //Get Start delayMicroseconds (5); //stable the line //sending 10 micro seconds pulse digitalwrite (Trigger_pin, HIGH); delayMicroseconds (10); //delay //waiting to recieve signals digitalWrite(Trigger_pin, Low); duration = pulsetn (Echo pin,HIGH); //calculating time distance =(duration/2)/29.1 //Distance measurement step Code Snippet 2.11 Code for measuring the distance of the obstacle. inizoduction to Sensors, Microcorivallrs, and Their interfacing if (mgtt connected ()) { if (ultrasonic data.publish (distance) } fl Serial.printin(*Success”); ' else { Serial.printin(*Trying”); } Code Snippet 2.12 Uploading the data to Adafruit cloud, 5 x=) Receiver Calculate the time taken Measures the distance Sonic waves trom by rellected waves of the object the sensor Figure 2.14 Working of an ultrasonic sensor in real time. Asimple diagrammatic representation of how ultrasonic sensor works is presented in Fig, 2.14, | iteosoric sensor and ut ‘ound sensor are both the same. 2.2.5 Interfacing the Gyro Sensor Gyro sensor is one of the most prominent sensors of present wearable technologies. It is mostly used to find the posture or angle of rotation of a body. These sensors can sense 1. Rotational motion 2. Changes in orientation These are the motions that humans have difficulty in sensing, This sensor is fabricated with PC bus which is the most sophisticated two-wire communication protocol. It is used to com- municate with more number of devices (say 1000 devices) at a time. Rather than having 1000 microcontrollers at a time to control all the devices, instead we can do it with just one micro- controller. This example demonstrates a simple implementation of 12C bus with cloud com- puting, A gyro sensor is presented in Fig. 2.15. The interfacing diagram is presented in Fig. 22 eset seni Figure 2.16 Connections diagram for MPU-6050 sensor. Codes provided in code snippets 2.13 and 2.14 are used to begin the communication with the gyro sensor and set the sensor in order to write the data to the microcontroller. Now, all the data we get from the sensor comprises the x-, y-, z-axis values altogether. So, we have a need to parse them and process the values individually, Code shown in the code snippet 2.14 does this job. Introduction to Sensors, Microcontrollers, and Their interfacing void setupMPu() i Wire-beginTransmission(0b1101000); //This is the 12C address of the MPU (b1101000/b1101001 fer ACO low/high datasheet sec. 9.2) Wire.write(0x6s); //Accessing the register 63 - Power Management (Sec. 4.28) Wire.write(0b00000000); //Setting SLEEP register to 0. (Required; see Note on p. 9) Wire.end?ransmission(); Wire-beginfransmission(0b1101000); //12C address of the MPU Wire.write(0x1B); //Accessing the register 18 - Gyroscope Configuration (sec. 4.4) Wire.write(0x00000000); //Setting the gyro to full scale +/- 250deg./s Wire.end?ransmission(); } Code Snippet 2.13 Code for communicating with the gyro sensor. void recordgyroegisters() { Wire.begin?ransnission{0b1101000); //12¢ address of the MPU Wire.write (0x43); //Starting register for Gyro Readings Wire.end?rananission(); Wire.requestFrom(0b1101000, 6); //Request Gyro Registers (43 - 48) while (Wize.available() < 6); gyroX = Wire.read() << 8 | Wire.read(); //Store first two bytes into accelX gyroY = Wire.read() << 8 | Wire.read(); //Store middle two bytes into accelY gyroz = Wire.read{) << 8 | Wire.read(); //Store last two bytes into accelZ processGyroData(); , void processGyrodata () ( rotX = gyrok / 131.0; rotY = gyroY / 131.03 rot = gyroz / 131.07 Code Snippet 2.14 Parsing and processing the gyro data. Now, the data has to be uploaded to the cloud and this task is accomplished through code snippets 2.15 and 2.16. WiFiclient me; Adafruit MOTT Client mgt (éme,server,port, username, aickey) + Adafruit MOTT Publishgas data~Adafruit MOTT Publish(amgtt, username”/feeds/ Gas_sensor”); Code Snippet 2.15 Initializing Wi-Fi and Adafruit client. 22 TypesofSensors AEE) i (matt .connected()) 4 Serial. print ("Uploading. ."); {Upload all the three axis values gyro_data.publish (rotX); gyro_data-publish (rotY); gyro_data.publish (rotz); Code Snippet 2.16 Uploading the rotation angle data from the gyro sensor. Now an interesting question is: Can someone detect the fall of an elderly person? The answer may be simple that it can be recognized through visionary inputs, But when we want to detect a fall with sensors and implement IoT, the task becomes complex. So the answer to our question is that by monitoring the posture of the person’s body one can obtain better insights into when will the elder fall. This is where the gyro sensors come into the play. Figure 2.17 illustrates how the gyro sensor works. : ¥ wes Cpe ayers Gamma or 3. S07 S046 ric — % y, Z 506 503616 —> Beta x,y, 2504 503.617 x.y, 2506 508 618 Placed sensor for Obtained values of Determine the elevation Inclination measurement X,Y, Zaxes Using the axes alignment Figure 2.17 Working of a gyro sensor. TE SS Ra TS ‘Typical applications of gyro sensors include: 1; Angular Velocity Sensing: Sense the amount of angular velocity produced. Used in measuring the amount of motion itself. For example, checking athletic movement. Angle Sensing: Senses angular velocity produced by the sensor’s own movement. Angles are detected via integration operations by a CPU. The angle moved is fed to and reflected in an application. Examples include car navigation systems, game controllers, cellular. Control Mechanisms: Senses vibration produced by external factors, and trans- mits vibration data as electrical signals to a CPU, Used in correcting the orienta tion or balance of an object. Examples include camera-shake correction, vehicle control 2.2.6 Interfacing the LDR Sensor Light dependent resistor (LDR) is a component that has a (variable) resistance which changes with the light intensity that falls upon it. This allows them to be used in light sens- ing circuits, Hence LDRs are the sensors which are employed in the fields where we have a necessity of monitoring the intensity of light. Since the resistance of the sensor changes with the intensity of the light, hence the output voltage value changes. By putting a simple analog read statement in the code one could observe the output voltage values It is shown in the code snippets 2.18 and 2.18. An LDR is presented in Fig. 2.18 along with its symbol. ‘The interfacing diagram is presented in Fig. 2.19. Figure 2.18 LDR and its symbol Code snippets 2.17 and 2.18 enable the data read. Also, the code enables one to upload the data on to the cloud. Code snippet 2.18 showcases how to set the threshold limit which enables the user to understand if the light intensity is dark or bright. Figure 2.19 Connections for the LDR sensor. void loop () { if (mgt -connected() ) 4 //sead data from 7th digital pin int Light_intensity= analogRead(AQ); Serial. printin(Light_intensity); Serdal.print(™...)7_ if (LDR_sensor.publish(Light_intensity)) ( Serial.printin(*Success”); else i Serial.print (“Trying”); t } delay (2000) ; Code Snippet 2.17 Obtaining and uploading the data Introduction to Sensors, Microcontrollers, and Their interfacing if (Light_intensity < 300) feerintiertey (spatter tise £8 idgne lntensiay > 900) t gadtaz\peliein 730 Beghe”) : Code Snippet 2.18 Thresholding the sensor values ‘Figure 2.20 shows the working of the LDR. % @ FR Light whose intensity has Light focused onto LOR, Calculate the INTENSITY of to be measured the light Figure 2.20 Working of LDR. ‘Typical applications of LDRs include: 1. Power Saving/Smart Lighting: A common application of LDR is smart lighting that turns on when a person enters a cabin and turns off when he/she leaves it. This is also a feature in most escalators in malls. Also, automatic urinal flushing systems use LDR as the major component. 2. Lighting Switch: The most obvious application for an LDR js to automatically turn on a light at a certain light level. An example of this could be a street light or a garden light. 2.2 Types of Sensors 3. Camera Shutter Control: LDRs can be used to control the shutter speed on a camera. The LDR would be used to measure the light intensity which then adjusts the camera shutter speed to the appropriate level. 2.2.7 Interfacing the GPS GPS sensors are widely used for acquiring the location data about the place where the sensor is present (think OLA or UBER app for tracking cars). The data from the sensor is acquired in NMEA (National Marine Electronics Association) format, which is used by the marine department for communication. One can use this module (Fig. 2.21) in the places where location tag is to be added. This is a very economical method for getting the GPS data. In this section we will explain the interfacing process and also how to upload the data to the cloud. Multiple variants of the GPS sensors are avail- able in the market with various packaging options. One can select the appropriate one based on the cost and other technical requirements. Interfacing diagram is presented as Fig, 2.21. Code snippet 2.19 is meant to acquire the location data and code snippet 2.20 for uploading the data to cloud Figure 2.21 Connections diagram for the GPS module. Introduction to Sensors, Microcontrollers, and Their Interfacing Finclude a TinyGPSt++ (TinyGPSPlus) object. Tt requires the use of SoftwareSerial, assumes that you have a 9600-haud serial GPs device hooked up on pins 8(rx) and 9(tx).*/ static const int RXPin = 8, TXPin = 3; static const uint32_t GPsBaud = 9600; // Toe TinyGPst+ object ‘TinyGPsPlus gps; // Te serial connection to the GPS device SoftwareSerial ss(RXPin, TXPin); void setup() 4 Serial begin (115200); ss-begin(GPSBaud) ¢ ) void Loop() ‘ encoded, while (ss.available() > 0) if (gps-encode(ss.read())) displayinfo(); Lf (millis() > $000 && gps.charsProcessed() < 10) i Serial.printIn(*No GPS detected: check wiring.” while (true) ; ) void displaytnto() { Serial.print (“Location: “); if (gps.location. isvalid()) ( Serial.print (gps. location.lat(), 67 Serial.print (*,"); Serial.print (gps. location.1ng(), 67 rial.printin (); Finclude /*This sample sketch denonstrates the normal use of and /f This sketch displays information every time a new sentence is correctly Code Snippet 2.19 Parsed NMEA data to get location values. 22 Wwoesof Sensors ZEN void Loop () ( if (nqtt connected ()) ( GPS_sensor.publish(gps.location.latitude() , 6): GPS_sensor.publish (gps.location.longitude() , 6); delay(2000); //Upload for every 2 seconds ) , Code Snippet 2.20 Uploading data to the GPS sensor. GPS sensors are used majorly for purposes like person or vehicle tracking around the globe. Refer Fig, 2.22 to understand the scheme, latitude longitude GPS device with antenna Roturns itd and “Tracked cation tor eommunicaton Tonatude as outout Figure 2.22 Scheme for live tracking of a vehicle. 2.2.8 Interfacing the Colour Sensor Colour sensors are generally used to detect the RGB coordinates of a particular colour. ‘The colour sensor works by shining a white light on an object and then recording the reflected colour. Through red, green, and blue colour filters the photodiode converts the amount of light to current. These RGB values are further processed to find the exact colour combination. The interfacing diagram is presented in Fig. 2.23. Introduction to Sensors, Microcontrollers, and Their interfacing 8 (Ola) Figure 2.23 Connections diagram for colour sensor. In code snippet 2.21,S2, and $3 pins are set to LOW, where LOW indicates red colour. Sim- ilarly, for getting the blue and green values, these pins has to be set to HIGH, HIGH and LOW, HIGH, respectively. Code snippet 2.22 helps the data read to be done on the cloud. digitalWrite(s2, HIGH); digitalWrite(s3, HIGH); // Reading the output frequency frequency = pulseIn(sensorOut, LOW) //Remapping the value of the frequency to the RGB Model of 0 to 255 frequency = map(frequency, 30,90,255,0); // Printing the value on the serial monitor Serial.print("G= ");//printing name Serial.print (frequency);//printing RED colour frequency Serial.print(* ”); delay (100); // Setting Blue filtered photo diodes to be read Code Snippet 2.21 Sample code for calculating the red colour. 22 TypesofSonsors ERA digitalnrite(S2,Low); digitalWrite(s3,ATGH) + // Reading the output frequency frequency = pulseIn(sensorOut, LOW); //Remapping the value of the frequency to the RGB Model of 0 to 255 frequency = map(frequency, 25, 70,255, 0) Code Snippet 2.21 Continued. if (matt.connected ()) ‘ Colour_value.publish(Red_value) ; Colour_value.publish(Green_value) ; Colour_value-publish(Blue value); Code Snippet 2.22 Uploading to the Adafruit cloud. Colour sensors are mostly employed to detect the colour of the objects. These sensors give the ability to a robotic eye to detect the colour and perform actions according to it. The functioning of the RGB sensor is presented in Fig. 2.24. asap | SS ~ Sy — SEs | Colour sensor with ‘Output AGB colour Determine the photodiodes atthe centre ‘coordinates ‘complexion of surface Figure 2.24 Functioning of an RGB sensor. MRR sis sors irri ara art 2.2.9 Interfacing the pH Sensor A pH sensoris used to detect hydrogen ion (H+) concentration of a liquid indicating its acidity or alkalinity. When this sensor is immersed in a solution, the smaller ions are able to penetrate the boundary area of the glass membrane and the larger ions remain in the solution which creates a potential difference. The pH meter measures the difference in electrical potential between the pH electrodes. It returns different analog values for different liquids. By knowing the analog value of a known pH value liquid (like water, KC! solution), pH value for other fluids can be determined. The interfacing diagram is presented in Fig. 2.25. Code snippets 2.23 and 2.24 reveal code for connections and uploading the same to the cloud. Figure 2.25 Connections diagram for the pH sensor. id Loop (void) { static unsigned long samplingTime = millis(); unsigned long printTime = millis(); float plValue, voltage; (millis()-samplingTime > si pilArzay [pHArrayIndex++]=analogRead ( Lf (pHArrayIndex=-ArrayLenth) pHArrayIndex=0; avergearray(pHArray, ArrayLenth)* nsorPin) ; /1024; Code Snippet 2.23 Code for using pH sensor. 23 Controlng Sensors trough Webpages pValue = 3.5*voltage+offset; samplingTimesmillis(); ) if(millis() - printTime > printinterval) //Every 800 milliseconds, print a numerical, convert the state of the LED indicator { Serial.print (*Voltage:”); Serial.print (voltage, 2); Serial.print(* pi value: Serial.printin (pivalue, 2); digitalwrite(LEp, digitalnead (LED) ~1); printTime=millis(); Code Snippet 2.23 Continued. void loop) { if (mgtt.connected()) { //Uploading the pH value ph_sensor.publish (pHvalue) ; if (pvalue > 7.0) { Serial.print1n(*Alkaline"); ) else { Serial.printin ("Acidic"); ) Code Snippet 2.24 Thresholding the acidity of the fluid pH sensors are mostly used in chemistry laboratories where acidity test is necessary to be performed in order to determine the nature of any liquid. Acidity test consumes a lot of time in done without the pH sensors. Figure 2.26 explains how pH value can be determined with pH sensor. Having learnt about sensors and their interfacing, itis also essential to know how to control elements like the sensor, LED through a webpage. Controlling Sensors through Webpages Starting with the gas sensor (MQ series), Section 2.2 explained the interfacing procedure with code and guidelines to upload data onto the cloud. Sensors like Obstacle sensor, introduction to Sensors, Microcontrolers, and Their Interfacing acidic 5 6 7 8 9 —_ Py — neutral 10 11-12 13 14 SEBuB alkaline Outputs voltage Determine the alkalinity pH sensor with electrodes corresponding to He ins nena Figure 2.26 Determining the pH value using pH sensor. heartbeat sensor, ultrasonic sound sensor, gyro sensor, GPS, LDR, colour sensor, and pH sensor have been interfaced with computing boards. The next section talks about controlling the LED through a webpage. This can be seen as an automation exercise. One can take this forward to control the functioning of motor/fan through a webpage. 2.3.1 Controlling LED with a Webpage In this section, we will discuss how to create a webpage which is used to remotely control an LED with the help of NodeMCU. Follow the below steps for connections and creating a webpage. Instead of LED, it can be any other sensor or actuator. Since LED is easy to understand and simple to test, it has been chosen. Before running the code, it is important to know the following that guide the reader to con- nect the LED to NodeMCU and to set up the necessary steps: 1. Connect an LED on any Digital pin you prefer and change the number in the code (D0, D1, etc. has to be properly updated). 2. Feed the SSID, password of the available and accessible Wi-Fi network. 3. Inthe Arduino IDE, Go to Tools > Boards Select NodeMCU 1.0 (ESP-12E Module). ‘Then upload the code with the regular procedure. 4. One should open the serial monitor in the Arduino IDE after which RST button in the NodeMCU should be pressed and one could see an IP assigned and displayed. It is the IP assigned for NodeMCU. Also, one shall get the following messages out in the serial monitor: Connecting to *#** Wi-Fi connected Server started 2.2 Controling Sensors through Webpage Use this URL to connect: http://192.168.43.121/ (This could vary) new client GET /HTTP/LL Client disconnected 5. One can open any browser from the phone or PC and type http://192.168.43.121/ (this could certainly vary from time to time.) 6 One would see ON/OFF buttons on the screen. On pressing them, one can see the LEDs glowing/closing. ‘The complete code is presented below for easier understanding, #include const char* ssid = “#*#**«"; // Type your WiFi username const char* password = “*#*#*"; // Type your WiFi Password int ledPin = D0; // Change the digital pin to which LED is connected. (Heze, NodeMCU DO Pin is // used) wiFiserver server (80); void setup() { Serial begin (115200); // Bs usual, this is just to set up the baud rate. Make sure you have the same // baudrate in your serial monitor. delay(50)7 pinMode(ledPin, OVTPUT); // Contiqure LED as output digitalWrite(ledPin, LOW); // Initially, OFF. // Connect to WiFi network. All these will appear in the screen. Serial.println(); Serial.println()s Serial.print (“Connecting to “)7 Serial.print1n (ssid); WiFi begin (ssid, password); // Connect! You shall have the TETHERING REPORT as 1 device connected. while (WiFi.status() delay (500); Serial.print(*."); } CONNECTED) { Introduction to Sensors, Microcontrollers, and Their Interfacing Serial.printin(™); Serial.println("Wifi connected”); J) Stazt the server server.begin(); Serial.printin ("Server started”); // exint the IP address Serial.print("Use this URL to connect: “); Serial.print (“http://") 7 Serial.print(WiFi.localIP()); // Watchout, this is an important step! serial.printin("/”); } void loop () { // Check if a client has connected WiFiclient client = server.available(); if (Iclient) [ return; ' // Wait until the client sends some data Serial.printin(*new client”); while (!client .available()) ( delay (1); ' // Read the first line of the request string request - client.readStringuntil(*\r'); Serial.printin(request) ; elient.flush(}; J/ Match the request int value = Low; if (request. indexof (*/LE! digitalWrite(ledPin, HIGH); value = HIGH; i £ (request. indexof ("/LED=OFF”) digitalWrite(ledPin, LOW); value = LOW; : IN") t= -1) { -1) // Set ledPin according to the request // digitalWrite(ledPin, value); // Return the response elient.println("HTTP/1.1 200 0K"); 24 Wie A Rag client.printin(*Content~Type: text/ntml”); client.printin(™"); client.printin("”) ; client.printin(*chtml>"); client.print("Led is now: if(value == RIGH) { client.print (“on”); } else { client.print ("Off"); client.printin(*

"); client.printin(*
”); client.printin (“”); delay (1); Serial.print1n(*Client disonnected”) + Serial.printin(""); ‘The complete demo showing how to control LED ON/OFF with NodeMCU through HTML is presented at the link: !ups//mww.youtube-com/ watch? v=84PdsQqsISUfeature=youtu bedelist= PL3uLubnel 2TmsPAWS8NjROMLTIpuPENX © >] ———— @ fi 7:34/13.45 Having learnt about the sensors, interfacing them, understanding the control of a sensor from a webpage, it is important also to know the fundamentals of certain microcontroller architectures to make the learning complete in all aspects. As in-depth analysis of the archi- tectures is not in the scope of the book, in the next section we will cover the must-know fundamentals. Microcontrollers: A Quick Walkthrough ‘The field of microprocessor and microcontroller has grown enormously. The number of pro- cessors and controllers have increased and their capacity features are stunning, There are many versions of microprocessors from many manufacturers, It all started with Intel 8085 FIER itociuction to sensors, Microcortroles, and Ther interfacing and expanded to Intel 8086, 8088, 80186, 80188, 80286, Intel Pentium, Intel Celeron, Intel Core processors and many more. For microcontrollers, it started with simple 8051 and now there are so many including 80151,80251, MCS96, LPC2148, PIC microcontrollers and many more. This section shall detail 8051 microcontroller and ARM 7 architecture. In this section, a fundamental microcontroller 8051 from Intel is explained followed by ARM 7 which is the latest in the market. 2.4.1 8051: An Architectural View 8051 has got everything inbuilt; in fact, this is the feature which distinguishes 8051 from a microprocessor, say 8085. Figure 2.27 shows an architectural representation of 8051 micro- controller. Intel is the organisation that built 8051 and it is a big hit. Even though Intel was the starting point of 8051, other manufacturers are also permitted to make 8051 with same set of features and the instruction set being compatible. Figure 2.27 summarizes the architectural details for Intel 8051. External Counter Interrupt Input interrupts aK 128 Timer 1 control | | FLASH RAM Timer 0 cru Bus Bus ‘control SHO Fon control Ose, PO P2 Pi P3 Address! Data Figure 2.27 Architectural layout of 8051. ‘The following are the features supported by 8051: 1. 8-bit microcontroller supporting 8-bit operations. 2, Many general-purpose and few special function registers. a, Two major 8-bit registers for arithmetical and other operations, A and B. A is accumulator and is bit addressable. b. 21 special function registers (SFRs). They perform a lot of dedicated functions which makes life of programmers very easy. ¢. Few registers are bit addressable and few are not. 4, Control registers for timer, serial communication and interrupts will fall under SFR category. 24 Microconivollers:A Quick Walkthrough EEA 3. Four register banks having 8 registers in each bank. a, 4 * 8 =32 registers can be used by the programmers (stack finds b. Stack pointer register: Points to the stack; itis an 8-bit register. 4, Data pointer which is called a 16-bit register, but is a combination of two 8-bit regis- ters, DPH and DPL. 5. 16-bit program counter; no address for the same is allotted. A program counter is a helper for the controller. It holds the address of the next instruction to be executed. 6, Eight bit program status word (PSW). It is the flag register and it helps in selection of register banks as well. Internal ROM or EPROM. It normally comes out with 4k ROM. . Internal user accessible RAM area of 128 byt . 40 pins package. There are four ports (PO, P1, P2, and P3) which can be configured as input or output ports. 10. ‘Two 16-bit timer/counters: TO and TL. 1. Full duplex serial data receiver/transmitter: SBUF. 12. Support for interrupt programming, 13, Oscillator and clock circuits. 14, Easier and simpler instruction set. slot there). pea 8051 has evolved from its carlier version 8031 and it has grown as 8052 as well. The next section presents the information about the family and its features. 2.4.2 8051: Family Details ‘There are a few more microcontrollers that fall into the family of 8051. These are 8052 and 8031 of which 8052 is regarded as a developed version of 8051. 8031 is not as good as the other two as there is no in-built ROM available. Table 2.1 indicates the key differences between the family members. As already conveyed, though Intel manufactured 8051 first, it has permitted other companies also to manufacture 8051 with having the instruction set compatible. Many organisations such as Atmel, Dallas Semiconductors, Analog Devices, Texas Instruments are also into 8051 production and distribution. Habitually all of them support the same instruction set and features. Table 2.1 8051 family and specifications wi 31 rd coe ROM (Program Memory~On Chip) 0K 4K 8K RAM (bytes) 128 128 256 ‘Timers 2 2 3 VO pins 32 32 32 Serial port 1 1 1 Interrupt sources 8 6 8 BME tic sear, wicca Tha ra Understanding of any controller or processor is complete only when one understands the memory structure and register organisation. Readers are strongly motivated to understand the memory organisation of the processor they wish to work on before building the application. There are two broad categories of memory: Program memory and data memory. 1. Program memory is normally referred to be ROM which is non-volatile memory and read-only in nature. It is used to store a, Boot up programs. b. ISR (Interrupt service routines . Macro functions. In 8051, 4k byte of internal program memory is available. 2, Data memory is useful when the data has to be stored temporarily, say during con- text switching. 8051 is organized neatly with 256 bytes of memory; these bytes are split as follows: a, First 128 bytes: 00h to IFh Register Banks b, 20h to 2Fh Bit Addressable RAM ¢. 30 to 7Fh General Purpose RAM (Data can be stored here, general purpose data) d, Next 128 bytes: 80h to FFh Special Function Registers Figure 2.28 gives the basic split. FFA ‘Special function Registers (80H —FFH) Internal RAM (00+ -7FH) ‘00h Figure 2.28 Memory organization. Again, further analysis on both the halves of the organization is required. Taking the inter- nal RAM ranging from 00H to 7FH (128 bytes) first, Fig. 2.28 is drafted and explanation will be given with reference to Fig, 2.29. As seen in Fig, 2.29, 32 bytes from 00H to 1FH are allocated for register banks and stack area. There are four register banks as follows: Register bank 0, Register bank 1, Register bank 2, Register bank 3, and Register bank 4, Each bank has 8 registers; the default bank is 0. If the programmer wants to navigate to a different 24 Microcontvolers:A Quick Walkthrough [ESI bank other than default it is possible by having PSW set accordingly. Figure 2.30 shows the available banks and corresponding addresses. However, a programmer should be very care~ ful with one thing: Register bank 1 is not meant for general-purpose usage. It is dedicated space for stack. Stack uses it for storage of temporary data; in short, stack is used for context switching. If the programmer is too keen on using bank 1, there is a key idea to be followed. ‘The skill of using bank 1 is explained in stack programming. Byte Bit address address _b7 6 65 b4b3b2 bi bo 7Fh General purpose RAM area. 20 tytes, oh arn [FF 78 zen [77 70 zon [oF oy zach [er 60 aan | SF 58 2ah oy, £0. ‘Special function ee 48 registers zen [ar 40 oe 27h | BE 38 addressable (80H —FFH) aon [sr 20 28h af a Internal RAM aan [az 20 zon [F 18 corre zon [a7 10 ain [or 08 20h [or 00 1Fh_— | Register Bank 3 18h (RO,R1,R2,R3,R4,R5,R6,R7) ym | Register Bank 2 jon | (RO.RT.R2,F3,A4,95,R6,87) OFh Register Bank 1 (STACK) osh —_| (RO,R1,R2,R3,94,R5,R6,R7) 07h | Register Bank 0 ‘oon | (RO.RT, 2,3, 4,5 ,R6,R7) Figure 2.29 Memory organization ~ Internal RAM, Introduction to Sensors, Microcontrollers, and Their interfacing oor 08.0FH 10-17H 10-1FH a7 R7 ar a7 Re Re Re Re RS Rs RS AS ra Re pa ae Ra RS iy cy Re Re Re Re Rt Ri Ri at Ro Ro Ro Ro Register Bank 0 Register Bank 1 Register Bark2 Register Bank 3 Figure 2.30 Memory organization — Register banks. 2.4.3 Registers in 8051 Microcontroller “What is a register?” It is the first question to be answered before one proceeds further. A register is used to store information. To make the understanding simpler, consider an example where two numbers are to be added; the numbers to be added are stored in the mind of the person performing addition. The area where the numbers are stored can be called as register and the result of the addition is also stored in a register. All the micropro- cessors or microcontrollers will have some number of registers. The count may vary from architecture to architecture. In 8051, almost all the registers are 8-bit wide. 2.4.4 Special Function Registers (SFRs) Special Function Register (SFR) is the term used to denote the most important set of registers being used in 8051. There are 21 SFRs available with 8051 microcontroller and they are all presented in Fig. 2.31 with their corresponding address. For an instance, address of ACC is E0h and that of SBUF is 99h as seen from the figure. Likewise, addres of other SFRs that are present can be known. Some of these registers are bit-wise acces- sible while some are byte addressable only. From here onwards the attention will be completely on SFRs. 24 Microcontrolers:A Quick Walkthrough Fen Fh ron] 8 Fm Een Fn eon | Aco E7h Deh DFh pon | Psw om can oFh con cm zen | Fh Bon | Pe B7h aon |e Ah aon | Pe Ah sen | scon | sBuF oFh gon [pt 97h 88h | TCON TMOD TLO TL THO | THI 8Fh aon | po | sp | OP | on PcON | 87h Figure 2.31 SFRs in 8051 with address The following section discusses the registers and their functions in a brief. Each register has a specific function that has been detailed here. Figure 1. ..31 shows the different registers in a cell. Accumulator A: This is one of the most important registers without which one can say that 8051 is almost non-usable. It is an 8-bit register and is used in all mathemat- ical and arithmetical operations. By default it would have 0 in all its bits, and it is bit addressable. The reasons why accumulator A is crucial are as follows: a. All the results obtained because mathematical or arithmetical operations will be stored only in this register. b. In operations like addition, subtraction, division and multiplication, one of the operands will have to sit in the accumulator A. ¢. Many of the instructions that are being used will involve A. In short, without A register, 8051 is almost dead. FEEL strotuction to sensors, Microconrolers, and Their Interfacing 2 Register B: This is yet another register which cannot be ignored when multiplication or division is done. Register B must be one of the operands in the multiplication and division operations. It is also an 8-bit register and can be accessed bit wise. Program Status Word (PSW) Register: It is good to keep an indicator for knowing if something is going wrong. Microcontrollers have a provision for this called FLAGS. ‘There are few flags which will help the user to know if the operations are happening as expected, All these flags are accommodated in a special function register called program status word. It is bit accessible. Figure 2.32 shows the PSW format. Details of each component of the PSW are as follows: MsB LsB , uN Psw7 PSwWe PSWS PSW4 PSW3 PSW2 PSWw1 PSWO me l«l=lelelel-|r v7 |” [*= 4 03 [° [2 | = a {ej Figure 2.32 PSW Register. 2.4.4.1 Flags in PSW P — Parity Flag (PSW.0): It will be set or reset based on the value (numeric) present in the accumulator. If it has odd number of 1s then it is set and otherwise it is set to 0. So it serves just as an indicator. PSW.L: This field is not used and reserved for future usage. OV — Overflow Flag (PSW.2): When result of a signed operation is very large, OV fiag is used. It will be set in that case, else it will remain unset. RSO and RSI — Register Bank Select (PSW.3 and PSW.4): There are four register banks supported in 8051 and each of them has 8 registers from RO to R2.The user has a flexibility of selecting one of those banks by using the register bank select options, Table 2.2 helps the programmer in getting desired bank selected. Table 2.2 Register Bank Select ii ise) Pe cra) 0 ) Register Bank 0 1 Register Bank 1 Register Bank 2 1___ Register Bank 3 ABS 2.4 Microcontrollers:A Quick Walkthrough One important thing the programmer should remember is the clash between Stack Memory and Register Bank 1. This clash will be discussed in detail in the area of stack memory. As an example, the instruction to get the register bank selected is SETB PSW.X where X can be used for selecting the bank, that is, SETB_ PSW. 4; will get register bank 2 selected. By default register bank 0 will be selected. ‘What are the instructions needed to select register bank 3? Answer: SETB PSW.3 and SETB PSW.4 SEU ey ° FO (PSW.5): It is a general-purpose bit which can be used by a programmer as per his/her wish. Auxiliary Carry (PSW.6): It is used in the case of BCD related operations alone. When there is a carry from D3 to D4, this will be set. g. Carry (PSW.7): Like all other processors, 8051 has also got a carry flag. This is fre- quently by the processor for arithmetic and shift operations. 4, TCON, TMOD, TL1,TL0, TH1, and THO Special Function Registers: These special function registers are all related to timer / counter related operations. PO, PI, P2 and P3 Special Function Registers: All these are meant for accessing the available ports of 8051 and are useful in interfacing with the peripherals. 6. IP and IE Special Function Registers: These two play a vital role in interrupt pro- gramming. Can you differentiate interrupt and polling? Answer: Microprocessor or controller asking the peripherals for service is polling. Peripherals requesting microprocessor or controller for service is interrupt. Bl Uae) a PCON Special Function Register: This very important register is used for controlling power consumption. 8. SCON and SBUF Special Funct communications. on Register: SCON and SBUF help in serial FEO itociction to Sensors, tticrocontrolers, and Their neracing 9. Data Pointer (DPH and DPL): Data pointer register is an imaginary register. It is actually non-existent. It is a combo of data pointer high-byte (DPH) and data pointer low-byte (DPL) registers. DPH and DPL are 8 bits each and can be com- bined together or can be used alone as well. When a 16-bit data needs to be stored, DPTR can be used as one register and the instructions are provided for the same. Few instructions are provided here for the reference of the reader. © MOV DPTR, #DATA; will move the 16-bit data to DPTR. © INC DPR; increments the DPTR by 1. ‘The following instruction depicts how DPH and DPL will be used by the controller. © MOV DPTR, #2312; After execution, DPH will have 23H and DPL will have 12H. Since it is a combination of DPH and DPL, it is not represented by single address, DPH and DPL have their own addresses. From Fig. 2.33, one can see that DPH is represented by address 83H and DPL by 82H. Figure 2.33 diagrammatically represents the DPTR register. 1 { 1 ' DPTR (data pointer) > DPH + DPL ' Figure 2.33 Data pointer register. 10. Stack Pointer (SP): Every microcontroller or microprocessor will have a stack area for temporary storage purpose. One can access the stack through the stack pointer which is an 8-bit register and referred usually as stack pointer register. There are instructions related to stack and they are POP. PUSH and MOV SP. #XX, where XX. in the MOV SP, #XX is the address where stack pointer should point to. 11. Program Counter (PC): It is a born special register. It has got no address (actually, address not known). The purpose of PC is to keep a paper mark. In simple words, the address of next instruction to be executed will be kept in PC. It is one of the two 16-bit registers available in 8051. It makes job of the processor easier to navigate. ARM An ARM processor is one of a family of CPUs based on the RISC (reduced instruction set computer) architecture developed by Advanced RISC Machines (ARM). ARM processor is basically a 32-bit processor meant particularly for high-end applications which involve more complex computations and calculations. 2.5.1 ARM7: A Quick Overview ARM processor was first developed at ACORN Computer Limited of Cambridge, England between 1983 and 1985 just after the concept of RISC was introduced at Stanford a 67 | and Berkley (in 1980). ARM Limited was founded in 1980, ARM specializes in the concept of ARM core, which they have licensed to a number of other manufacturers to make a vari- ety of chips around the same processor core. So, now the focus is not on the family of processors, but conceptually a CPU architecture which may figure in a number of different chips intended for embedded applications. The ARM is based on RISC architecture, but it is not a purely RISC architecture because it has been enhanced to meet the requirement of embedded applications. ‘The requirements for embedded applications are basically high code density, low power consumption as well as low and smaller silicon footprint. Architecturally ARM satisfies var- ious conditions and properties of RISC processors as well. 2.5.2 ARM Evolution There are various versions of ARM architecture. This architecture has undergone a number of changes and these variations are implemented into a number of processors, having dis- tinct identity and number. There are four such versions. 1. The first version (1983-1985) supported 26 bit addressing scheme with no support being offered for multiply operation 2. The second and third versions include 32-bit addressing with multiply operation and co-processor. This distinguishes the ARM from the PIC and other low-end RISC microcontrollers which support only ADD or SUBTRACT operation. 3. The fourth version was enhanced with the availability of signed instructions and version 4T-Thumb, 16-bit compressed form of instruction, was introduced. 2.5.3 Features of ARM ARM has got lot of interesting features. Some of them are as follows: 1. ARM processor has a large uniform register file, It is basically a LOAD-STORE architecture, where data processing operations are only between registers and do not involve any memory operations. 2. Itisa32-bit processor and also has variants of 16-bit and 8-bit architectures. So, there are 16-bit and 8-bit variants embedded into a 32-bit processor. This offers flexibility for the users to choose based on the requirement. 3. ARM has got a very good speed versus power consumption ratio and high code den- sity as required by embedded applications. 4. Ithas got barrel shifter in the data path which can maximize the hardware usage avail- able on the chip. It has also got auto-increment and auto-decrement addressing modes to optimize program loops: this is not very common with RISC processor. Also ARM supports LOAD and STORE of multiple data elements through a single instruction. 5. ARM has also got a feature named “conditional execution” where an instruction gets executed only when a condition is being met, which maximizes the execution throughput. BIRR a ae ce arora These enhanced features make the ARM more suitable for embedded applications and all these distinguish the ARM from other typical RISC processors. 2.5.4 Basic ARM Architecture The previous section elucidates the various versions of ARM architecture and concludes that ARM architecture is not synonymous with any single organization. But, there is certain communality among the different variants. This section explains the basic features before going in detail about the variants. Any architecture is not only characterised by its data path, but also by its control path. Now, we shift our focus to the data path and the instruction set of the ARM with respect to the core data path. This data path is organized in such a way that the operands are not directly fetched from memory. A basic feature of RISC is that operands get fetched from registers and not from memory. Instructions typically use two source registers and single result/destination register. The more interesting fact is the presence of the “barrel shifter” and the “increment/decremen logic. The barrel shifter on the data path can preprocess the data before it enters the ALU, It is basically a combinational circuit that can shift a data bit to the left or to the right by an arbitrary number of positions in the same cycle itself. The classical shift register involves fiip-flops and the barrel shifter is available in the shift reg- ister where the number of shifts requires an equivalent number of clocks because the shifting takes place based on clocks, Whereas, the barrel shifter is made up of a combinational circuit where the shifting takes place in asingle attempt itself, With the barrel shifter in place the shift- ing becomes easier and can be done in an attempt. < In fact, the shift takes place in the same instruction itself. This is a very basic enhancement present in the ARM data path. The other interesting feature is the increment and decrement logic which can operate on the registers that are independent of ALU. This facilitates the implementation of auto-increment and auto-decrement features in the ARM, where it is used for movement of blocks of data between the memory and registers. 2.5.5 ARM Organisation Core Data Flow Model Figure 2.34 shows the ARM core flow diagram where the functional units are connected by data buses. The arrows represent the direction of data flow, the lines represent the buses, and the boxes represent either a storage unit or an operation unit. The following section shall indicate the core b purpose of each of these blocks is briefed. ig blocks in the data flow model. Also, the 1. Instruction Decoder: It decodes the instruction before execution. There are three Kinds of instruction sets supported in ARM core: ARM Instruction Set; Jazelle Instruction Set and THUMB Instruction Set. With the CPSR, one can set the opera- tion state and accordingly instruction set can be selected. 25 a 2. Load and Store Architecture: ARM falls in the reduced instruction set computer (RISC) category which follows the load and store architecture. This means that with load and store architecture in place, registers will be mandatory for process- ing to be carried out. Without registers one cannot do any sort of operation with ARM core. a, ARM has two source registers Rm and Rn and one destination register which carries the result. The destination register is named as Rd. A and B are the two buses that will help in reading the source operands. Rm and Re values will be fetched from the buses A and B and computation will be carried out in the ALU or MAC (Multiplication and Accumulate unit). Address registers are used to hold the address and address bus will facilitate the storage action, b, Barrel shifter is a kind of support which is very useful in association with ALU for expression evaluation and address caleulati ¢. After going through the steps and sequences the result will be moved to the register Rd. Register file (0-15) _—_—_—_ Control Result Rd t Rm Rn 8 ‘Acc a Barrel shifter Mac Instruction decoder ‘and ‘control ! Figure 2.34 Data flow model of ARM core. Introduction to Sensors, Microcontrollers, and Their interfacing 2.5.6 ARM Register Organisation Every microcontroller must have lots of registers as it plays a vital role in data transfer operations and storage functions. A register is used to store information, For the reader to understand in a simpler way, when two numbers are to be added, the numbers to be added are stored in the mind of the person performing addition. With respect to processors, the area where the numbers are stored can be called as registers. The result of the addition will also be stored, that again should be in register. All the microprocessors or micro- controllers will have some number of registers. The count may vary from architecture to architecture. This same information has been given when the 8051 registers were dealt. So, one thing is clear that the register’s purpose remains the same across the microcontrollers or microprocessors. Figure 2.35 illustrates the way the registers are organised in ARM. Program coun) (Stack pointer) (Pre y ofale[e[als][«[7] «ele | nol ane] ns] mas [crs] (Link register) Figure 2.35 ARM registers. ‘This figure reveals that there are 13 general-purpose registers (r0 to- r12) available for the programmers to use. They are all referred with a prefix r, which means the RAM location and also the register. All the registers are 32 bits in their size. Like 8051 architecture, there are some special function registers available here as well. They are r13, r14 and r15. Each of these three registers has a specific function as summarized below: 1. Stack Pointer (SP, r13): Every microcontroller or a processor will have a stack area for temporary storage purpose. One can access the stack through the stack pointer. It is similar to the one discussed for 8051. It will hold the address of the top of the stack. 2. Link Register (LR, r14): The name itself reveals the story behind the register. When a subroutine is called, the return address will be put here and when the subroutine execution is over, this register will be used for fetching the address back from where the control of execution has been initiated. 3. Program Counter (PC, r15): Well, reader is already aware of what a PC does. It is a born special register. It has got no address. The purpose of PC is to keep a paper mark. In simple words, the address of next instruction to be executed will be kept in PC. 25 aw [EZ Programmers are advised that they should not try using r13,r14 and r15 as general-purpose registers. Though they have all rights to use it as a general-purpose register, they should not use as it may cause side effects if not used properly. It may overwrite the contents of the PC which would disturb the flow of execution and is dangerous as well. There are many modes of operation available in ARM. Seven such modes are identified and they are all discussed in Section 2.5.8. 2.5.7 Current Program Status Register (CPSR) CPSR is one of the most important registers available with ARM architecture. Figure 2.36 illustrates how CPSR looks like as well as its components. This is a status register or a flag register. It can be compared to PSW (program status word) of 8051. One major difference is that CPSR is a 32-bit register whereas PSW is an 8-bit register. In Fig. 2.36 there are four flags: Negative flag, Zero flag, Carry flag and Overflow flag. Since there is a lot of room for extension, few bits are reserved and kept for future usage or for the moment they can be referred to be as unused. There are two fields which are meant for interrupt masking pur- pose, where with I, one can mask or unmask the IRQ interrupts. Then comes the THUMB field which helps in enabling or disabling the THUMB mode. Mode switching can be done only with CPSR. Carry Flag: Will be set it result of an ALU operation is getting carry generated Overflow Flag: When result of a signed operation results in an overflow, this flag is set Flag fields Interrupt mask bis NZCV Unused TF TT] Mode ai] \ 2827 Reserved for a7] 6a)4 0 : future use Negative Flag: Will tied io met FG |___Mode select bit. One of the be set if result of an ALU operation Zero Flag: Will be set if interrupts, Seven modes can be selected is Negative result of an ALU To select THUMB state. If sot to 1, THUMB is ‘operation is Zero mode is set. else normal ARM mode is set Figure 2.36 ARM-CPSR register. 2.5.8 ARM Family: A Comparison ‘There are many processors that have been released with ARM core such as ARM7Z,ARM9, ARMI0, ARMI1 and so on. As the number increases followed by ARM (such as ARM 7, ARM 9), the features also increase with more special attributes. For example, ARM9’s speed will be better than that of ARM7 and pipelining would be of a different architecture. In ‘Table 2.3, a comparison has been made between the different versions of the processor fall- ing under the ARM roof. RS SR SS ETH RSTO Table 2.3 Feature comparison of various ARM processors ARM7 i Er ARM11 Pipeline ‘Three stage Five stage Sixstage Fight stage MHz 80 150 260 335 MIPSMHZ 097 1 13 12 Architecture (Harvard/Von Neumann) VN Harvard = Harvard © Harvard Multiplier 8*32 8832 16*32 16932 1, Sensors are the most important components in the IoT applications. 2. Many sensors are available in the market and the most important task is to identify the right sensor for the right task. 3. MQ series sensors are most commonly used for gas detection applications. 4, NodeMCU or Arduino can be used as per the requirement. 5. Obstacle sensor (IR sensor) is used to understand if obstacles are present in the path and if present, it can be alerted through the output. 6. Heartbeat sensors are most used in the healthcare industry and analog Read is the pre- ferred option to read the data 7. Ultrasonic sound sensors have widespread applications such as parking automation process. 8. Gyro sensor is mostly used to find the posture or angle of rotation of a body. 9. Light dependent resistor (LDR) is a component that has a (variable) resistance which changes with the light intensity that falls upon it. It is used in energy saving, smart light- ing applications. 10, GPS sensor is used to track the location. It is used in maps and cab tracking. U1. pH sensor is a chemical sensor which will let us read the pH value of any liquid, say, water or milk 12, 8051 is one of the finest 8-bit microcontrollers available in the market. It has many general-purpose registers and special function registers. 13, 8051 has 4 register banks with 8 registers in each bank. 14, 8051 has internal ROM or EPROM. 15, 8051 normally comes in a 40 Pins package. 16, Programmer can select desired register bank with PSW. 17. Stack pointer is used to point to the stack 18. PUSH and POP operations can be used to add data on to the stack and remove data as well. 19, Bank 1 is the default stack area in 8051 20, There are two timers in 8051 and can be used as timers or counters. 21. Timers can be programmed in any of the 4 modes (Mode 0, Model, Mode 2 and 3). Ravn Oui 22, TCON and TMOD are the special function registers associated with timer operations. 23, IEis the register used to set/reset any interrupts, 24, SCON is the register useful in serial communication, 25. The baud rate is the rate used for the communication purpose and it is used to identify how much of the data had been transferred and with what speed. 26. ARM is abbreviation of ACRON RISC MACHINE. 27. ARM is based on RISC architecture. 28. ARM follows the load and store architecture. 29. ARM follows the Von-Neumann architecture. 30. There are total of 16 registers available for the user to access freely, Out of these r13, r14 and r1S are meant for stack pointer, link register and program counter. 31. There are three states supported by ARM core: ARM, THUMB and JAZELLE. 32. CPSR (Current Program Status Register) is used as a status register, similar to PSW of the 8051 microcontroller. It is a 32-bit register. 33. CPSR supports Negative, Carry, Overflow and Zero flags. 34, THUMB state can be set with accessing the CPSR and setting the THUMB bit T. 35. Jazelle is a special state of operation which supports JAVA-based operations. 36. SPSR is meant to store the status of the CPSR and is used to restore the context (com- plete CPSR information) after returning from the exception call. 37, Pipelining is used to increase speed of execution. 38. ARM supports multiple stages of pipelining, Three-, five- and six-stage pipelines are followed in different architectures. 39. ARM7 supports a three-stage pipeline which has Fetch, Decode and Execute stages. 40. ARM9 supports five-stage pipelining which has memory and write stages in addition. 41. RESET is the exception with highest priority. ESOL 1. Mention the importance of sensors in [oT applications with appropriate examples 2. Take any reference and explain how pH sensor can be used in an IoT application. 3. Mention clearly the procedure to interface the heartbeat sensor with any microcontroller of your choice, 4, Assume you have a fan at home. You wish to control the ON/OFF through Internet. Design a system for the same. Draw the system architecture, How is a microprocessor different from a microcontroller? Explain in detail. 5. Draw the architecture of 8051 while mentioning all the features. 6. Explain the importance of program counter in any application where microprocessor or microcontroller is used. 7. Explain the architectural details of ARM7 while clearly mentioning the usage of CPSR. 8. Explain clearly the register structure of ARM7, 9. Can ARM be called a microprocessor or a microcontroller? Justify. HIRE sect sesrs sant, Tt nracg Tamer} 1. Ayala, K.J.,2004. The 8051 Microcontroller. Publisher: Delmar Cengage Learning 2. Benziane, BA., 2017. Design and Implementation of a Sman Home System, Doctoral Dissertation. 3. Gondchawar, N. and Kawitkar, RS. 2016. loT based smart agriculture. Internation- al Journal of Advanced Research in Computer and Communication Engineering (JARCCE), 5(6), 177-181 4. Imteaj, A., Rahman, T., Hossain, M.K., Alam, M.S. and Rahat, S.A.,2017 February. An IoT based fire alarming and authentication system for workhouse using Raspberry Pi 3. (ECCE), International Conference on Electrical, Computer and Communication Engineering, 899-904, IEEE. 5. Jaggar, D., 1997 ARM architecture and systems [EEE Micro, 17(4),9-11. 6. Kumar, NS., Saravanan, M. and Jeevananthan, S., 2011. Microprocessors and Micro- controllers, Oxford University Press, Inc. 7. Predko,M. and Predko, M., 1998, Handbook of Microcontrollers. McGraw-Hill, Ine. 8. Vijayakumar, N, and Ramya, R.,2015, March. The real time monitoring of water quali ty in ToT environment. In (ICHECS), 2015 International Conference on Innovations in Information, Embedded and Communication Systems, 1-5, IEEE. 9. Yang, G., Xie, L., Mantysalo, M., Zhou, X., Pang, Z., Da Xu, L., Kao-Walter, S., Chen, Q. and Zheng, L.R., 2014, A health-loT platform based on the integration of intelligent packaging, unobtrusive bio-sensor, and intelligent medicine box. IEEE Transactions on Industrial Informatics, 10(4), 2180-2191. Quick Reference Sheet (A cheat sheet of available sensors and its applications) Given below are available rs in the market, along with their probable applications, CaN ma Cac) ae rv 1 Barometer (BMP 180) Atmospheric pressure measurement. Used in weather prediction tions. (Continued) DE Wetec) cea 2. Moisture Sensor (FC28) Measurement of soil moisture is its simplest application. 3. Obstacle Sensor (FCS1) Zp, Obsiacle detection L applicators: 4, Passive Infrared Motion detection Sensor (PIR Sensor) — applications. HC SRSO1 | a a Gas Sensor — MQ series Gas leakage detection, LPG detection, smoke detection applications 6 Accelerometer Sensor ~ ADXL series Fall detection, accelera- tion change monitoring. Used widely in smart phones. (Continued) inirodcton to Sensors, Microcontolers, and The Inertacing Application 1 BME 280 — Temperature, Humidity and Pressure Perishable qua monitoring, humidity and temperature data. 8. Proximity Sensor Parking and related applications. 9. Sound Sensor ~ LM 393 Sound detection (many variants available) applications 10. Ultrasonic Sound Sensor Level monitoring, trash ~HCSRO04 monitoring ete. IL LDR Sensor Energy management (smart lighting inside the office, among others) (Continued) Quick Reference Sheet IZ aN Cy Wie ec Application 12. Piezo Electric Plate Energy harvesting a wy applications 13, PH Sensor Water quality monitoring. - 14. REED Switch — Secured door access/ burglar alarms. 15. RFID/NFC (radio Access control frequency identification/ applications. Near Field Communication) 16. Slot Sensor Textile stitching applications. (Continued) Introduction to Sensors Microcontrollers, and Their Interfacing aed aM a 17 Heart Rate Sensor Monitor the rate of heartbeat of a person. 18 ‘Thermal Sensor High accuracy thermal imaging module. Level and direction calibration in UAV's. 19. GY-80 (consists accelerometer, gyro, magnetometer) Tae Cr ecm Ey ecu cecal eet) oo

You might also like