
{"id":371,"date":"2018-10-02T07:54:09","date_gmt":"2018-10-02T07:54:09","guid":{"rendered":"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/?page_id=371"},"modified":"2019-09-18T15:30:55","modified_gmt":"2019-09-18T15:30:55","slug":"topic-4-analogue-input","status":"publish","type":"page","link":"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/microcontrollers\/mbed-os-2\/courses\/embedded-systems-in-context-level-4\/topic-4-analogue-input\/","title":{"rendered":"Topic 4 \u2013 Analogue Input"},"content":{"rendered":"<p><a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/embedded-systems-in-context-level-4\/\">Back to ToC<\/a><\/p>\n<p>In this section we look at interfacing with the analogue world. You will use a simple <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/potentiometer-glossary-entry\/\" target=\"_blank\" rel=\"noopener\"><b>potentiometer<\/b><\/a> to generate analogue voltages, and measure that voltage using an <strong><a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/analogue-to-digital-converter-adc-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">Analogue to Digital Converter (ADC)<\/a><\/strong>.\u00a0We also look at different ways to represent an analogue voltage as a digital value.\u00a0<a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/hysteresis-and-the-schmitt-trigger-glossary-entry\/\" target=\"_blank\" rel=\"noopener\"><b>Hysteresis<\/b><\/a> is used to manage signal noise and avoid output jitter.\u00a0You will also discover problems with noise, and use \u2018hysteresis\u2019 to avoid instability due to noise.<\/p>\n<h1><b>Intended Learning Outcomes<\/b><\/h1>\n<ol>\n<li>Use a <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/potentiometer-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">potentiometer<\/a> to generate and control an <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/glossary\/\" target=\"_blank\" rel=\"noopener\">analogue signal<\/a><\/li>\n<li>Convert an analogue signal to an integer digital representation using an <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/analogue-to-digital-converter-adc-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">analogue to digital converter<\/a><\/li>\n<li>Scale an integer value to a fractional value<\/li>\n<li>Use <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/hysteresis-and-the-schmitt-trigger-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">hysteresis<\/a> thresholds to avoid problems with noise<\/li>\n<li>Use <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/if-else-if-else-statement-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">conditional statements<\/a> and operators to make decisions in software<\/li>\n<li>Break a program into logical and reusable functions<\/li>\n<li>Use looping commands to perform iteration to average a measurement<\/li>\n<li>Use a hardware interrupt timer for accurate sampling.<\/li>\n<\/ol>\n<p>&nbsp;<\/p>\n<hr \/>\n<h1>Activity 4.1 Potentiometer<\/h1>\n<p>In this section, we are going to use a &#8220;<a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/potentiometer-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">potentiometer<\/a>&#8221; to create an <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/glossary\/\" target=\"_blank\" rel=\"noopener\">analogue signal<\/a>.\u00a0Your <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/potentiometer-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">potentiometer<\/a> should look something like the figure below.<\/p>\n<figure id=\"attachment_376\" aria-describedby=\"caption-attachment-376\" style=\"width: 200px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-376\" src=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/PotentiometerPhoto.png\" alt=\"\" width=\"200\" height=\"249\" srcset=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/PotentiometerPhoto.png 375w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/PotentiometerPhoto-241x300.png 241w\" sizes=\"auto, (max-width: 200px) 100vw, 200px\" \/><figcaption id=\"caption-attachment-376\" class=\"wp-caption-text\">Photo of the Potentiometer used in this course<\/figcaption><\/figure>\n<p>Below is a diagram for the prototype board. We have simply added a potentiometer to the circuit, with the middle terminal connected to pin A0.<\/p>\n<figure id=\"attachment_380\" aria-describedby=\"caption-attachment-380\" style=\"width: 800px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-380\" src=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/SchematicWithAnalogueIn.png\" alt=\"\" width=\"800\" height=\"809\" srcset=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/SchematicWithAnalogueIn.png 1810w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/SchematicWithAnalogueIn-297x300.png 297w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/SchematicWithAnalogueIn-768x777.png 768w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/SchematicWithAnalogueIn-1012x1024.png 1012w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/SchematicWithAnalogueIn-988x999.png 988w\" sizes=\"auto, (max-width: 800px) 100vw, 800px\" \/><figcaption id=\"caption-attachment-380\" class=\"wp-caption-text\">The prototyping board layout is shown above. Note the power supply rails have been linked to extended the power rails.<\/figcaption><\/figure>\n<p>The schematic for the potentiometer is shown below.<\/p>\n<figure id=\"attachment_377\" aria-describedby=\"caption-attachment-377\" style=\"width: 350px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-377\" src=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/PotentiometerCircuitSchematic.png\" alt=\"\" width=\"350\" height=\"264\" srcset=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/PotentiometerCircuitSchematic.png 531w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/PotentiometerCircuitSchematic-300x226.png 300w\" sizes=\"auto, (max-width: 350px) 100vw, 350px\" \/><figcaption id=\"caption-attachment-377\" class=\"wp-caption-text\">Potentiometer Circuit schematic, providing a variable voltage input to the analogue input A0<\/figcaption><\/figure>\n<p>&nbsp;<\/p>\n<figure id=\"attachment_378\" aria-describedby=\"caption-attachment-378\" style=\"width: 150px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-378\" src=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/PotentiometerImage.png\" alt=\"\" width=\"150\" height=\"149\" srcset=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/PotentiometerImage.png 541w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/PotentiometerImage-150x150.png 150w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/PotentiometerImage-300x298.png 300w\" sizes=\"auto, (max-width: 150px) 100vw, 150px\" \/><figcaption id=\"caption-attachment-378\" class=\"wp-caption-text\">(unofficial) Symbol for the potentiometer for prototyping diagrams<\/figcaption><\/figure>\n<div class=\"mceTemp\"><\/div>\n<h2>Task 4.1.1<\/h2>\n<p>Perform the following steps:<\/p>\n<table style=\"border-collapse: collapse;border: 1px solid black\" cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"middle\">Wire the circuit shown. Instead of connecting the wire to A0, connect it to a DVM on the voltage range.<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">By rotating the potentiometer (POT), what range of voltages do you observe?<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<table style=\"border-collapse: collapse;border: 1px solid black\" cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"middle\">Now connect the center terminal wire to A0 (as shown in the figure above)<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Create new project, paste in the code below, compile and and run.<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Run the terminal (PuTTY) to see the output. If nothing appears, you may need to change the COM port setting (use Windows Device Manager to check)<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Set the POT to the two extremes and observe the values<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Set the POT such that you get close to 0.5.<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Are you able to get precisely 0.5, and if not, <b>why<\/b>?<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Using an <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/if-else-if-else-statement-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">if-else<\/a> statement, write some additional code to switch the<span class=\"Apple-converted-space\">\u00a0<\/span>Green <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/led-light-emitting-diode-glossary-entry-tbd\/\" target=\"_blank\" rel=\"noopener\">LED<\/a> ON when the analogue input is between 0.0 and 0.5, the Red LED ON when greater than 0.5 and 1.0. <a href=\"https:\/\/os.mbed.com\/teams\/Students-Plymouth-University-UK-SoCEM\/code\/Task411Solution\/file\/248dad7a0a29\/main.cpp\" target=\"_blank\" rel=\"noopener\">A solution is available here<\/a>. See the <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/if-else-if-else-statement-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">glossary entry about if-else if-else<\/a> if you are unsure.<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Set the POT to halfway, and try and make the LED\u2019s switch on and off erratically.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Sometimes we might write the specification as follows:<\/p>\n<p class=\"ql-center-displayed-equation\" style=\"line-height: 43px;\"><span class=\"ql-right-eqno\"> &nbsp; <\/span><span class=\"ql-left-eqno\"> &nbsp; <\/span><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-6ffd882338ba834160ae9d2cdc8ffaa2_l3.png\" height=\"43\" width=\"259\" class=\"ql-img-displayed-equation quicklatex-auto-format\" alt=\"&#92;&#091; &#99;&#111;&#108;&#111;&#117;&#114;&#32;&#61;&#32;&#92;&#108;&#101;&#102;&#116;&#92;&#123; &#92;&#98;&#101;&#103;&#105;&#110;&#123;&#97;&#114;&#114;&#97;&#121;&#125;&#123;&#108;&#108;&#125; &#71;&#82;&#69;&#69;&#78;&#32;&#38;&#32;&#86;&#95;&#123;&#105;&#110;&#125;&#60;&#48;&#46;&#53;&#32;&#92;&#92; &#82;&#69;&#68;&#32;&#38;&#32;&#111;&#116;&#104;&#101;&#114;&#119;&#105;&#115;&#101; &#92;&#093;\" title=\"Rendered by QuickLaTeX.com\"\/><\/p>\n<pre class=\"theme:xcode lang:c++ mark:9,20 decode:true\">#include \"mbed.h\"\r\n\r\n\/\/Global objects\r\nBusOut binaryOutput(D5, D6, D7);    \r\nDigitalIn SW1(D3);\r\nDigitalIn SW2(D4);\r\n\r\n\/\/Analog input\r\nAnalogIn AIN(A0);\r\n\r\n\/\/Global variable\r\nfloat fVin = 0.0;\r\n\r\n\/\/Main function\r\nint main() {\r\n    \r\n    while(1) {\r\n        \r\n        \/\/Read ADC\r\n        fVin = AIN;\r\n        \r\n        \/\/Write to terminal\r\n        printf(\"Analog input = %5.3f\\n\", fVin); \r\n        \r\n        \/\/Wait\r\n        wait(0.5);\r\n        \r\n    } \/\/end while(1)\r\n} \/\/end main<\/pre>\n<h3><strong>AnalogIn<\/strong><\/h3>\n<p>In this example we introduce the Mbed-os type <span class=\"theme:classic lang:c++ decode:true crayon-inline\">AnalogIn<\/span>. This enables use to access an on-chip <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/glossary-2\/analogue-to-digital-converter-adc-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">analogue to digital converter<\/a> that converts an <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/glossary-2\/glossary\/\" target=\"_blank\" rel=\"noopener\">analogue signal<\/a> to a digital representation. We create a variable of type\u00a0<span class=\"theme:classic lang:c++ decode:true crayon-inline\">AnalogIn<\/span> much like we did with <span class=\"theme:classic lang:c++ decode:true crayon-inline \">DigitalIn<\/span>\u00a0:<\/p>\n<pre class=\"lang:c++ decode:true\">AnalogIn AIN(A0);<\/pre>\n<p>Like <span class=\"theme:classic lang:c++ decode:true crayon-inline \">DigitalIn<\/span>\u00a0, the single parameter is the pin name <span class=\"theme:classic lang:c++ decode:true crayon-inline\">A0<\/span>. We read the analogue input value as follows:<\/p>\n<pre class=\"lang:c++ decode:true\">fVin = AIN;<\/pre>\n<p>Note the data type of <span class=\"theme:classic lang:c++ decode:true crayon-inline \">fVin<\/span>\u00a0 is <span class=\"theme:classic lang:c++ decode:true crayon-inline\">float<\/span>. This type of data can hold fractional numbers, as opposed the <span class=\"theme:classic lang:c++ decode:true crayon-inline \">int<\/span>\u00a0 and <span class=\"theme:classic lang:c++ decode:true crayon-inline \">unsigned int<\/span>\u00a0 data types that only hold whole numbers. Using this method, the value we read is conveniently scaled between 0.0 (0V) and 1.0 (3.3V).<\/p>\n<h3>Observations<\/h3>\n<p>No signals are ever perfectly constant. The observed value we see changes due to electrical noise.<span class=\"Apple-converted-space\">\u00a0<\/span>Noise is <i>always<\/i> present, so as the value gets close to 0.5, there will always be some point where the output \u201cjitters\u201d between RED to GREEN. The output is unstable at this point.<\/p>\n<p>Consider the case where the output is not an LED, but something more critical:<\/p>\n<ul>\n<li><b>lift motor<\/b> &#8211; In such states, it will stop and start erratically, possibly causing damage, passenger discomfort and undue mechanical wear.<\/li>\n<li><b>automatic defibrillator<\/b> &#8211; a device to inject a unit of energy across a human chest to reset the electrical characteristics of the heart and hopefully restore its rhythm. You would certainly not want erratic outputs for such a device!<\/li>\n<\/ul>\n<p>Noise is not the only problem, as over longer periods of time, other factors such as temperature changes and component ageing can cause component values to drift.\u00a0We will address these problems using <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/hysteresis-and-the-schmitt-trigger-glossary-entry\/\" target=\"_blank\" rel=\"noopener\"><b>hysteresis <\/b><\/a>in a later task.<\/p>\n<h2>Task 4.1.2<\/h2>\n<p>Complete the following:<\/p>\n<table style=\"border-collapse: collapse;border: 1px solid black\" cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"middle\">The flow chart below is for Task 4.1.1 (previous task).\u00a0Sketch a new flow chart to use three LEDs, as specified by the equation<\/p>\n<p class=\"ql-center-displayed-equation\" style=\"line-height: 65px;\"><span class=\"ql-right-eqno\"> &nbsp; <\/span><span class=\"ql-left-eqno\"> &nbsp; <\/span><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-b6720f45f0098cf1b33cb63c09133635_l3.png\" height=\"65\" width=\"316\" class=\"ql-img-displayed-equation quicklatex-auto-format\" alt=\"&#92;&#091; &#99;&#111;&#108;&#111;&#117;&#114;&#32;&#61;&#32;&#92;&#108;&#101;&#102;&#116;&#92;&#123; &#92;&#98;&#101;&#103;&#105;&#110;&#123;&#97;&#114;&#114;&#97;&#121;&#125;&#123;&#108;&#108;&#125; &#71;&#82;&#69;&#69;&#78;&#32;&#38;&#32;&#48;&#46;&#48;&#32;&#92;&#108;&#101;&#113;&#32;&#86;&#95;&#123;&#105;&#110;&#125;&#32;&#60;&#32;&#48;&#46;&#52;&#32;&#92;&#92; &#89;&#69;&#76;&#76;&#79;&#87;&#32;&#38;&#32;&#48;&#46;&#52;&#32;&#92;&#108;&#101;&#113;&#32;&#86;&#95;&#123;&#105;&#110;&#125;&#32;&#60;&#32;&#48;&#46;&#54;&#32;&#92;&#92; &#71;&#82;&#69;&#69;&#78;&#32;&#38;&#32;&#111;&#116;&#104;&#101;&#114;&#119;&#105;&#115;&#101; &#92;&#093;\" title=\"Rendered by QuickLaTeX.com\"\/><\/p>\n<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Again, using <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/if-else-if-else-statement-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">if, else if and else<\/a> statements, code your solution and test.<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Does it still have regions when outputs are unstable?<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/embedded-systems-in-context-level-4\/topic-4-analogue-input\/task-4-1-2-solution\/\" target=\"_blank\" rel=\"noopener\">A solution is given here.<\/a><\/p>\n<p>&nbsp;<\/p>\n<figure id=\"attachment_391\" aria-describedby=\"caption-attachment-391\" style=\"width: 450px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-391\" src=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Task412FlowChart.png\" alt=\"\" width=\"450\" height=\"614\" srcset=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Task412FlowChart.png 681w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Task412FlowChart-220x300.png 220w\" sizes=\"auto, (max-width: 450px) 100vw, 450px\" \/><figcaption id=\"caption-attachment-391\" class=\"wp-caption-text\">Flow-chart for the simple threshold detector. Note this design suffers from output jitter in the region around Vin=0.5<\/figcaption><\/figure>\n<p>&nbsp;<\/p>\n<h2>Task 4.1.3<\/h2>\n<p>Perform the following tasks:<\/p>\n<table style=\"border-collapse: collapse;border: 1px solid black\" cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"middle\">The code below uses hysteresis to avoid the problem of noise for a single threshold.<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Read the glossary entry on Hysteresis<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Question: what is the noise margin?<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Sketch a flow chart for this code<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<pre class=\"theme:xcode lang:c++ decode:true\">#include \"mbed.h\"\r\n\r\n\r\n#define kRED    (1 &lt;&lt; 2)    \/\/4\r\n#define kYELLOW (1 &lt;&lt; 1)    \/\/2\r\n#define kGREEN  (1 &lt;&lt; 0)    \/\/1\r\n\r\n\/\/Global objects\r\n\/\/Outputs as an integer\r\nBusOut binaryOutput(D5, D6, D7);    \r\n\r\n\/\/Analogue Input\r\nAnalogIn AIN(A0);\r\nfloat fVin = 0.0;\r\n\r\n\/\/Main function\r\nint main() {\r\n   \r\n   \/\/This represents which state we are in\r\n   \/\/RED or GREEN\r\n   int state = 0;\r\n   \r\n   while(1) {\r\n      \r\n      \/\/Read ADC\r\n      fVin = AIN;\r\n      \r\n      \/\/Write to terminal\r\n      printf(\"Analog input = %6.4f\\n\", fVin);\r\n      \r\n      \/\/Now the \"state machine\" - next state logic\r\n      switch (state) {\r\n            \/\/The RED state\r\n         case 0:\r\n            \/\/Condition to switch state\r\n            if (fVin &gt; 0.6f) {\r\n               state = 1;\r\n            }\r\n            break;\r\n            \r\n            \/\/The GREEN state\r\n         case 1:\r\n            \r\n            \/\/Condition to switch state\r\n            if (fVin &lt; 0.4f) {\r\n               state = 0;\r\n            }\r\n            break;\r\n            \r\n         default:\r\n            state = 0;\r\n      }\r\n      \r\n      \/\/Output logic\r\n      switch (state) {\r\n         case 0:\r\n            binaryOutput = kGREEN;\r\n            break;\r\n         case 1:\r\n            binaryOutput = kRED;\r\n            break;\r\n         default:\r\n            binaryOutput = 0;\r\n      }\r\n      \r\n      \/\/Wait\r\n      wait(0.1);\r\n      \r\n   } \/\/end while(1)\r\n} \/\/end main<\/pre>\n<p>Note how this code uses a <strong><a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/switch-case-statement-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">switch-case<\/a><\/strong> to select the action for a given state. Using <strong><a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/switch-case-statement-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">switch-case<\/a><\/strong>, the code remains easy to read and debug. You could have equally used <strong><a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/if-else-if-else-statement-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">if-else if-else<\/a><\/strong> statements.<\/p>\n<h3>State Diagram<\/h3>\n<p>Sometimes we <em>model<\/em> this behaviour using a state diagram:<\/p>\n<figure id=\"attachment_399\" aria-describedby=\"caption-attachment-399\" style=\"width: 600px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-399\" src=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/HysteresisStateDiagram.png\" alt=\"\" width=\"600\" height=\"247\" srcset=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/HysteresisStateDiagram.png 1587w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/HysteresisStateDiagram-300x124.png 300w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/HysteresisStateDiagram-768x316.png 768w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/HysteresisStateDiagram-1024x422.png 1024w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><figcaption id=\"caption-attachment-399\" class=\"wp-caption-text\">Finite state digram to model the hysteresis technique for reducing the effects of noise<\/figcaption><\/figure>\n<h2>Additional Task 4.1.4<\/h2>\n<p>(if you have time)<\/p>\n<table style=\"border-collapse: collapse;border: 1px solid black\" cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"middle\">Starting with the code below, can you apply hysteresis to the three state system in task 4.1.2?<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">hint: add an upper and lower thresholds each decision in the original solution (given opposite). <a href=\"https:\/\/os.mbed.com\/teams\/Students-Plymouth-University-UK-SoCEM\/code\/Task414Solution\/file\/7912f2086c2b\/main.cpp\" target=\"_blank\" rel=\"noopener\">A solution is given here<\/a>.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<pre class=\"theme:xcode lang:c++ decode:true\">#include \"mbed.h\"\r\n#define kRED    4\r\n#define kYELLOW 2\r\n#define kGREEN  1\r\n\r\n\r\n\/\/Global objects\r\nBusOut binaryOutput(D5, D6, D7);\r\n\r\nDigitalIn SW1(D3);\r\nDigitalIn SW2(D4);\r\n\r\nAnalogIn AIN(A0);\r\nfloat fVin = 0.0;\r\n\r\n\/\/Main function\r\nint main() {\r\n   \r\n   \r\n   while(1) {\r\n      \r\n      \/\/Read ADC\r\n      fVin = AIN;\r\n      \r\n      \/\/Write to terminal\r\n      \/\/3 decimal places, fieldwidth=5\r\n      printf(\"Analog input = %6.4f\\n\", fVin);\r\n      \r\n      if (fVin &lt; 0.4f)  {\r\n         binaryOutput = kGREEN;\r\n      } else if (fVin &lt; 0.6f) {\r\n         binaryOutput = kYELLOW;\r\n      } else {\r\n         binaryOutput = kRED;\r\n      }\r\n      \r\n      \/\/Wait\r\n      wait(0.1);\r\n      \r\n   } \/\/end while(1)\r\n} \/\/end main<\/pre>\n<h1><\/h1>\n<hr \/>\n<h1>Activity 4.2 Light Dependent Resistor<\/h1>\n<p>In this task we are going to use a new passive component, the <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/light-dependent-resistor-ldr-glossary-entry\/\" target=\"_blank\" rel=\"noopener\"><b>light dependent resistor (LDR<\/b>)<\/a>.<\/p>\n<h2>Task 4.2.1<\/h2>\n<p>Perform the following tasks:<\/p>\n<table style=\"border-collapse: collapse;border: 1px solid black\" cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"middle\">Add the additional circuit below to your existing design (see further down the page for a full prototyping layout)<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Create a new project, build and run the sample code below<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Run PuTTY, and observe the outputs of this code in the terminal screen. Try rotating the potentiometer and blocking light from the LDR.<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Set the potentiometer such that when you move your hand over the LDR, so the LED\u2019s switch ON (See video below)<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div>\n<p><a href=\"https:\/\/www.youtube.com\/watch?v=lCB5O5XBR-k\">https:\/\/www.youtube.com\/watch?v=lCB5O5XBR-k<\/a><\/p>\n<\/div>\n<div><\/div>\n<div><\/div>\n<figure id=\"attachment_436\" aria-describedby=\"caption-attachment-436\" style=\"width: 450px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-436\" src=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/LDR-Circuit.png\" alt=\"\" width=\"450\" height=\"407\" srcset=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/LDR-Circuit.png 1225w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/LDR-Circuit-300x271.png 300w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/LDR-Circuit-768x695.png 768w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/LDR-Circuit-1024x926.png 1024w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/LDR-Circuit-1104x999.png 1104w\" sizes=\"auto, (max-width: 450px) 100vw, 450px\" \/><figcaption id=\"caption-attachment-436\" class=\"wp-caption-text\">Using an LDR within a potential divider circuit to generate a light dependent voltage.<\/figcaption><\/figure>\n<pre class=\"theme:xcode lang:c++ decode:true\">#include \"mbed.h\"\r\n\r\n#define kRED    (1 &lt;&lt; 2)    \/\/4\r\n#define kYELLOW (1 &lt;&lt; 1)    \/\/2\r\n#define kGREEN  (1 &lt;&lt; 0)    \/\/1\r\n#define kALL (kRED | kYELLOW | kGREEN)\r\n\r\n\/\/Global objects\r\nBusOut binaryOutput(D5, D6, D7);\r\nDigitalIn SW1(D3);\r\nDigitalIn SW2(D4);\r\n\r\nAnalogIn POT_ADC_In(A0);\r\nAnalogIn LDD_ADC_In(A1);\r\nfloat fPOT, fLDR = 0.0;\r\n\r\n\/\/Main function\r\nint main() {\r\n   \r\n   while(1) {\r\n      \r\n      \/\/Read ADC\r\n      fPOT = POT_ADC_In;\r\n      fLDR = LDD_ADC_In;\r\n      \r\n      \/\/Write to terminal\r\n      printf(\"POT = %6.4f\\tLDR = %6.4f\\n\", fPOT, fLDR);\r\n      \r\n      if (fLDR &gt; fPOT) {\r\n         binaryOutput = 0;      \/\/Binary 000\r\n      } else {\r\n         binaryOutput = kALL;   \/\/Binary 111\r\n      }\r\n      \r\n      \/\/Wait\r\n      wait(0.1);\r\n      \r\n   } \/\/end while(1)\r\n} \/\/end main<\/pre>\n<figure id=\"attachment_442\" aria-describedby=\"caption-attachment-442\" style=\"width: 600px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-442\" src=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Circuit-with-LDR.png\" alt=\"\" width=\"600\" height=\"608\" srcset=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Circuit-with-LDR.png 1814w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Circuit-with-LDR-296x300.png 296w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Circuit-with-LDR-768x778.png 768w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Circuit-with-LDR-1011x1024.png 1011w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Circuit-with-LDR-986x999.png 986w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><figcaption id=\"caption-attachment-442\" class=\"wp-caption-text\">Wiring instructions for the Light Dependent Resistor (LDR)<\/figcaption><\/figure>\n<h2>Task 4.2.2<\/h2>\n<p>Perform the following tasks:<\/p>\n<table style=\"border-collapse: collapse;border: 1px solid black\" cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"middle\">Now watch the video below<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Using <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/if-else-if-else-statement-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">if and else-if<\/a> statements, modify your code to achieve this. <a href=\"https:\/\/os.mbed.com\/teams\/Students-Plymouth-University-UK-SoCEM\/code\/Task422Solution\/file\/6d9e82b27127\/main.cpp\" target=\"_blank\" rel=\"noopener\">You can see a solution here.<\/a><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>https:\/\/youtube.com\/watch?v=aum8M_211uE<\/p>\n<h1><\/h1>\n<hr \/>\n<h1>Activity 4.3 Noise and Averaging<\/h1>\n<p>Watch the following video to observe the analogue signal generated by the LDR.<\/p>\n<p>https:\/\/youtube.com\/watch?v=ze2TYUZUKlQ<\/p>\n<p>As you can clearly see, the signal is not a smooth line, but has noise superimposed upon it.<\/p>\n<p>In this next activity, we are going to calculate an average of the input signal. We assume the noise is a \u201crandom signal\u201d which over time, will average to a value close to zero.<\/p>\n<p>Let us assume the measured signal can be described by as follows:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-e86da1a9fae393952f80bacd096c18ab_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#121;&#40;&#116;&#41;&#32;&#61;&#32;&#115;&#40;&#116;&#41;&#32;&#43;&#32;&#110;&#40;&#116;&#41;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"133\" style=\"vertical-align: -5px;\"\/><\/p>\n<p>where <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-a2f33825c8ec052e86696209360348d4_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#121;&#40;&#116;&#41;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"28\" style=\"vertical-align: -5px;\"\/>\u00a0is the measured signal we observe (measured in Volts), <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-deaf6182833d014ee4261790e0bca730_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#115;&#40;&#116;&#41;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"27\" style=\"vertical-align: -5px;\"\/>\u00a0is the perfect noise-free signal we want to observe, <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-0cf459fc110e8dc2e415eedd67ae885c_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#110;&#40;&#116;&#41;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"30\" style=\"vertical-align: -5px;\"\/>\u00a0is the noise and <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-6b97bb0f65c75b6cc0fba1868749478d_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#116;\" title=\"Rendered by QuickLaTeX.com\" height=\"12\" width=\"6\" style=\"vertical-align: 0px;\"\/>\u00a0is time (in seconds).<\/p>\n<ul>\n<li>We assume the noise <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-0cf459fc110e8dc2e415eedd67ae885c_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#110;&#40;&#116;&#41;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"30\" style=\"vertical-align: -5px;\"\/>\u00a0is a random signal with a mean of zero.<\/li>\n<li>As <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-deaf6182833d014ee4261790e0bca730_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#115;&#40;&#116;&#41;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"27\" style=\"vertical-align: -5px;\"\/>\u00a0is a function of light intensity, we can assume this changes very slowly. Over short periods, we can approximate it to be a constant. It is not random.<\/li>\n<\/ul>\n<p>We can therefore do the following:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-6b54f85ece812cae93495a7b011be6aa_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#97;&#118;&#101;&#114;&#97;&#103;&#101;&#32;&#92;&#123;&#32;&#121;&#40;&#116;&#41;&#32;&#92;&#125;&#32;&#61;&#32;&#97;&#118;&#101;&#114;&#97;&#103;&#101;&#32;&#92;&#123;&#32;&#115;&#40;&#116;&#41;&#32;&#43;&#32;&#110;&#40;&#116;&#41;&#32;&#92;&#125;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"293\" style=\"vertical-align: -5px;\"\/><\/p>\n<p>Written formally:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-cb5a2acc13ac3664a1d6ef445e12a8b0_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#69;&#32;&#92;&#123;&#32;&#121;&#40;&#116;&#41;&#32;&#92;&#125;&#32;&#61;&#32;&#69;&#32;&#92;&#123;&#32;&#115;&#40;&#116;&#41;&#32;&#43;&#32;&#110;&#40;&#116;&#41;&#32;&#92;&#125;&#125;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"197\" style=\"vertical-align: -5px;\"\/><\/p>\n<p>where <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-7b0bbcac0c75b13a795fc1a9431fada4_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#69;&#123;&#92;&#99;&#100;&#111;&#116;&#125;\" title=\"Rendered by QuickLaTeX.com\" height=\"12\" width=\"18\" style=\"vertical-align: 0px;\"\/>\u00a0represents the \u201cexpected value\u201d, or \u201caverage value\u201d in our case.<\/p>\n<p>Without going into too much mathematics, because the function <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-7b0bbcac0c75b13a795fc1a9431fada4_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#69;&#123;&#92;&#99;&#100;&#111;&#116;&#125;\" title=\"Rendered by QuickLaTeX.com\" height=\"12\" width=\"18\" style=\"vertical-align: 0px;\"\/>is linear, so we can also say:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-b1b76d0aa4a202e1575e2ac7ae9c5cad_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#69;&#32;&#92;&#123;&#32;&#121;&#40;&#116;&#41;&#32;&#92;&#125;&#32;&#61;&#32;&#69;&#32;&#92;&#123;&#32;&#115;&#40;&#116;&#41;&#32;&#43;&#32;&#110;&#40;&#116;&#41;&#32;&#92;&#125;&#32;&#61;&#32;&#69;&#32;&#92;&#123;&#32;&#115;&#40;&#116;&#41;&#32;&#92;&#125;&#32;&#43;&#32;&#69;&#32;&#92;&#123;&#32;&#110;&#40;&#116;&#41;&#32;&#92;&#125;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"366\" style=\"vertical-align: -5px;\"\/><\/p>\n<p>We can use our first assumption:<\/p>\n<p>We say that \u201cin the limit\u201d, as <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-332f9e157209b5a6e657ca68f199360d_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#116;&#32;&#92;&#114;&#105;&#103;&#104;&#116;&#97;&#114;&#114;&#111;&#119;&#32;&#92;&#105;&#110;&#102;&#116;&#121;\" title=\"Rendered by QuickLaTeX.com\" height=\"13\" width=\"51\" style=\"vertical-align: -1px;\"\/> then <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-147aa4221a37f597213240616855f7df_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#69;&#32;&#92;&#123;&#32;&#110;&#40;&#116;&#41;&#32;&#92;&#125;&#32;&#92;&#114;&#105;&#103;&#104;&#116;&#97;&#114;&#114;&#111;&#119;&#32;&#48;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"99\" style=\"vertical-align: -5px;\"\/><\/p>\n<p style=\"padding-left: 30px\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-30597e6c0b69d50d1579a1c232563500_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#92;&#116;&#104;&#101;&#114;&#101;&#102;&#111;&#114;&#101;&#32;&#69;&#32;&#92;&#123;&#32;&#121;&#40;&#116;&#41;&#32;&#92;&#125;&#32;&#92;&#97;&#112;&#112;&#114;&#111;&#120;&#32;&#69;&#32;&#92;&#123;&#32;&#115;&#40;&#116;&#41;&#32;&#92;&#125;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"161\" style=\"vertical-align: -5px;\"\/><\/p>\n<p>In other words, if we measure the average of the noisy signal, then we should begin to estimate the average of the signal itself.\u00a0We now apply our second assumption:<\/p>\n<p style=\"padding-left: 30px\">Over a short time period, we can approximate our signal <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-deaf6182833d014ee4261790e0bca730_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#115;&#40;&#116;&#41;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"27\" style=\"vertical-align: -5px;\"\/>\u00a0to be constant such that <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-8a880b713986be18e70acc873b5ea738_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#115;&#40;&#116;&#41;&#32;&#92;&#97;&#112;&#112;&#114;&#111;&#120;&#32;&#69;&#32;&#92;&#123;&#32;&#115;&#40;&#116;&#41;&#32;&#92;&#125;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"111\" style=\"vertical-align: -5px;\"\/><\/p>\n<p>In other words, if we calculate the average input signal, we can estimate its true value. The longer time used for the average, the more noise will be removed, however this assumes the signal does not change.\u00a0Let\u2019s now do this in code.<\/p>\n<p style=\"padding-left: 30px\">The average of a signal is estimated by measuring and summing N input samples, then dividing the total by N.<\/p>\n<p>Mathematically we write this as:<\/p>\n<p style=\"padding-left: 30px\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-7f60c7286d47825c2ccf5971868e0cc5_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#69;&#32;&#92;&#123;&#32;&#121;&#40;&#110;&#41;&#32;&#92;&#125;&#32;&#61;&#32;&#92;&#102;&#114;&#97;&#99;&#123;&#49;&#125;&#123;&#78;&#125;&#32;&#92;&#99;&#100;&#111;&#116;&#32;&#92;&#115;&#117;&#109;&#95;&#123;&#110;&#61;&#48;&#125;&#94;&#123;&#78;&#45;&#49;&#125;&#32;&#120;&#40;&#110;&#41;\" title=\"Rendered by QuickLaTeX.com\" height=\"23\" width=\"205\" style=\"vertical-align: -6px;\"\/><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-75c4a5f5914a4d041c8acacef67ceb4f_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#120;&#40;&#110;&#41;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"34\" style=\"vertical-align: -5px;\"\/>\u00a0is the <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-2abf0b71b2242df3a72e948f3e5c9ea0_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#110;&#94;&#123;&#116;&#104;&#125;\" title=\"Rendered by QuickLaTeX.com\" height=\"15\" width=\"24\" style=\"vertical-align: 0px;\"\/> input signal and <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-a63eb5ff0272d3119fa684be6e7acce8_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#110;\" title=\"Rendered by QuickLaTeX.com\" height=\"8\" width=\"11\" style=\"vertical-align: 0px;\"\/>is the sample number. This mathematical expression translates as:<\/p>\n<p style=\"padding-left: 30px\"><i>Sum N samples <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-1703ff17206362b9444b3ddf1b2f5383_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#110;&#40;&#110;&#41;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"35\" style=\"vertical-align: -5px;\"\/><\/i><i>, where <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-db358afc82b9bb2a8e9051fd5a352c14_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#110;&#61;&#48;&#32;&#46;&#46;&#46;&#32;&#40;&#78;&#45;&#49;&#41;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"118\" style=\"vertical-align: -5px;\"\/><\/i><i>, then divide by <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-b57494e2a3f4838b8025f0fe6e89db99_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#78;\" title=\"Rendered by QuickLaTeX.com\" height=\"12\" width=\"16\" style=\"vertical-align: 0px;\"\/><\/i><i>.<\/i><\/p>\n<p>If we sample the signal 100 times a second, we say the sampling rate <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-57f1e3727e4c2ecdb385980b685c445a_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#70;&#95;&#115;&#61;&#49;&#48;&#48;&#72;&#122;\" title=\"Rendered by QuickLaTeX.com\" height=\"15\" width=\"94\" style=\"vertical-align: -3px;\"\/>\u00a0and the time period <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-a03fd6da08bd50f1e692a0b71ceba46b_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#84;&#61;&#92;&#102;&#114;&#97;&#99;&#123;&#49;&#125;&#123;&#70;&#95;&#115;&#125;&#61;&#48;&#46;&#48;&#49;&#115;\" title=\"Rendered by QuickLaTeX.com\" height=\"24\" width=\"119\" style=\"vertical-align: -8px;\"\/>.<\/p>\n<p>Don&#8217;t worry if you struggle to follow the mathematics above. Much of the problem often stems fro understanding the notation which becomes more familiar with time and practise.<\/p>\n<h2>Task 4.3.1<\/h2>\n<p>Perform the following tasks:<\/p>\n<table style=\"border-collapse: collapse;border: 1px solid black\" cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"middle\">For both analogue inputs, modify the code below to calculate the average of N=10 samples. Samples should be recorded 100 times a second<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Use the <span class=\"theme:classic lang:default decode:true crayon-inline\">printf<\/span>\u00a0 function to output the average of both <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/potentiometer-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">potentiometer<\/a> and <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/light-dependent-resistor-ldr-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">LDR<\/a> signals<span class=\"Apple-converted-space\">\u00a0<\/span><\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Use the provided flowchart to guide you.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<pre class=\"theme:xcode lang:c++ decode:true\">#include \"mbed.h\"\r\n\r\n\/\/Global objects\r\nBusOut binaryOutput(D5, D6, D7);\r\nAnalogIn POT_ADC_In(A0);\r\nAnalogIn LDD_ADC_In(A1);\r\n\r\nfloat fPOT, fLDR = 0.0;\r\n\r\n\/\/Main function\r\nint main() {\r\n   \r\n   while(1) {\r\n      \r\n      \/\/Read ADC\r\n      fPOT = POT_ADC_In;\r\n      fLDR = LDD_ADC_In;\r\n      \r\n      \/\/TODO:\r\n      \/\/Calculate the average of both fPOT and fLDR,\r\n      \/\/then write to the terminal\r\n      \r\n      \/\/Write to terminal\r\n      printf(\"POT = %6.4f\\tLDR = %6.4f\\n\", fPOT, fLDR);\r\n      \r\n      if (fLDR &gt; fPOT) {\r\n         binaryOutput = 0;      \/\/Binary 000\r\n      } else {\r\n         binaryOutput = 7;   \/\/Binary 111\r\n      }\r\n      \r\n      \/\/Wait 0.01s\r\n      wait(0.01);\r\n      \r\n   } \/\/end while(1)\r\n} \/\/end main<\/pre>\n<figure id=\"attachment_445\" aria-describedby=\"caption-attachment-445\" style=\"width: 400px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-445\" src=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/FlowChartAveraging.png\" alt=\"\" width=\"400\" height=\"710\" srcset=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/FlowChartAveraging.png 810w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/FlowChartAveraging-169x300.png 169w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/FlowChartAveraging-768x1362.png 768w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/FlowChartAveraging-577x1024.png 577w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/FlowChartAveraging-563x999.png 563w\" sizes=\"auto, (max-width: 400px) 100vw, 400px\" \/><figcaption id=\"caption-attachment-445\" class=\"wp-caption-text\">Flowchart for the signal averaging task.<\/figcaption><\/figure>\n<blockquote><p>TIP &#8211;\u00a0The input samples are integers. An average is a fractional value. To convert an integer (type <span class=\"theme:classic lang:c++ decode:true crayon-inline \">int<\/span>\u00a0) to a fractional value (type <span class=\"theme:classic lang:c++ decode:true crayon-inline \">float<\/span>\u00a0), you can use a type cast.<\/p>\n<pre class=\"\">int x = 10; \/\/Integer variable\r\n\r\nfloat y = (float)x; \/\/Convert x to a float<\/pre>\n<\/blockquote>\n<p><a href=\"https:\/\/os.mbed.com\/teams\/Students-Plymouth-University-UK-SoCEM\/code\/Task431Solution\/file\/8f4002068b49\/main.cpp\" target=\"_blank\" rel=\"noopener\">A solution can be viewed here<\/a>.<\/p>\n<h3><b>Important Terminology<\/b><\/h3>\n<p>In task 4.3.1, we measured samples 100 times a second. We say the <i>sampling rate<\/i> is 100 samples per second. This is also commonly known as 100 Hertz (100Hz), named after the physicist <a href=\"https:\/\/en.wikipedia.org\/wiki\/Heinrich_Hertz\" target=\"_blank\" rel=\"noopener\">Heinrich Rudolf Hertz<\/a>.\u00a0We can also say the <i>sampling interval<\/i> T = 0.01s (10ms).<\/p>\n<h2>Task 4.3.2<\/h2>\n<p>Perform the following:<\/p>\n<table style=\"border-collapse: collapse;border: 1px solid black\" cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"middle\">How precise and consistent is the sampling rate in 4.3.1? (hint &#8211; remember that lines of code take time to execute).<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Using your solution in 4.3.1 (or the solution provided), look at the output in the terminal. Ideally, the averaged value would be constant, however due to noise, there will still be some variation. To how many decimal places is the signal constant?<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">By increasing N from 10 to 100, estimate to how many decimal places the average signal is constant. How does increasing N impact on the effect of noise?<span class=\"Apple-converted-space\">\u00a0 <\/span>How does it impact on \u2018responsiveness\u2019?<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Discussion<\/h3>\n<p>In terms of <i>precision<\/i>, the delay of the wait(0.01) statement results in a very precise delay, but the time for the remaining code also needs to be added.<\/p>\n<p>The sampling interval <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-8ae67bed17eb9334a46a3a6aa9835e7f_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#84;&#32;&#61;&#32;&#48;&#46;&#48;&#49;&#32;&#43;&#32;&#84;&#95;&#123;&#99;&#111;&#100;&#101;&#125;\" title=\"Rendered by QuickLaTeX.com\" height=\"15\" width=\"126\" style=\"vertical-align: -3px;\"\/><\/p>\n<p>where <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-7bc5fdeb22d4a4eb1d5e0ab26d84e51d_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#84;&#95;&#123;&#99;&#111;&#100;&#101;&#125;\" title=\"Rendered by QuickLaTeX.com\" height=\"15\" width=\"36\" style=\"vertical-align: -3px;\"\/>\u00a0is the time for remaining code to execute.<\/p>\n<p>In terms of <i>consistency<\/i>, there is a conditional ( <span class=\"theme:classic lang:default decode:true crayon-inline\">if<\/span>\u00a0 ) statement in this code. Therefore <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-7bc5fdeb22d4a4eb1d5e0ab26d84e51d_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#84;&#95;&#123;&#99;&#111;&#100;&#101;&#125;\" title=\"Rendered by QuickLaTeX.com\" height=\"15\" width=\"36\" style=\"vertical-align: -3px;\"\/>\u00a0is variable (every N samples, the code branches).<\/p>\n<p>Increasing N will reduce the impact of noise. Note also that increasing N will also reduce responsiveness. You could increase the sampling rate to correct for this, but there are better solutions.<\/p>\n<p>A further problem with our current design is that the output is only updated every N samples. As N becomes large, so the time between measurements also becomes large.<\/p>\n<p style=\"padding-left: 30px\">A more elegant solution is to store the past data in an <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/array-glossary-entry\/\" target=\"_blank\" rel=\"noopener\"><b>array<\/b><\/a>. Each time a new sample is added, we throw away the oldest sample and recalculate.<\/p>\n<p>There are a number of ways to achieve this, some more efficient than others. Let\u2019s start with the simplest to understand, but most inefficient.<\/p>\n<p>In C or C++, we can create an array of N samples as follows:<\/p>\n<p style=\"padding-left: 30px\"><span class=\"theme:classic lang:c++ decode:true crayon-inline\">float x[8];<\/span><\/p>\n<p>In this case, I have created an array of 8 samples to keep the diagrams small. In practice we will use larger arrays. We can visualise an array of samples as a sequence of numbered storage elements as shown below.<\/p>\n<figure id=\"attachment_455\" aria-describedby=\"caption-attachment-455\" style=\"width: 450px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-455\" src=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Array_1.png\" alt=\"\" width=\"450\" height=\"138\" srcset=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Array_1.png 962w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Array_1-300x92.png 300w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Array_1-768x236.png 768w\" sizes=\"auto, (max-width: 450px) 100vw, 450px\" \/><figcaption id=\"caption-attachment-455\" class=\"wp-caption-text\">Depicting an array of samples.<\/figcaption><\/figure>\n<p>The first element of the array is <span class=\"theme:classic lang:c++ decode:true crayon-inline \">x[0]<\/span>\u00a0 and the last is <span class=\"theme:classic lang:c++ decode:true crayon-inline \">x[7]<\/span>\u00a0. We can write some code to calculate the average of all elements in the array. For this we will use a<span class=\"Apple-converted-space\">\u00a0<a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/for-loop-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">for-loop<\/a>.<\/span><\/p>\n<pre class=\"theme:xcode lang:c++ decode:true \">int N=8;\r\nfloat sum = 0;\r\n\r\nfor (int n=0; n&lt;N; n++) {\r\n   sum += x[n];\r\n}\r\n\r\nfloat average = sum \/ (float)N;<\/pre>\n<p>We can now output the average as required.\u00a0When we measure the next sample, we can update our array and recalculate as follows.<\/p>\n<figure id=\"attachment_456\" aria-describedby=\"caption-attachment-456\" style=\"width: 450px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-456\" src=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Array_BucketBrigade.png\" alt=\"\" width=\"450\" height=\"238\" srcset=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Array_BucketBrigade.png 989w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Array_BucketBrigade-300x158.png 300w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Array_BucketBrigade-768x405.png 768w\" sizes=\"auto, (max-width: 450px) 100vw, 450px\" \/><figcaption id=\"caption-attachment-456\" class=\"wp-caption-text\">Depicting the logical shifting of elements in an array to create a &#8220;First In First Out&#8221; (FIFO) buffer.<\/figcaption><\/figure>\n<p>Note the order of the operations are numbered. First <span class=\"theme:classic lang:c++ decode:true crayon-inline \">x[6]<\/span>\u00a0 is copied over the oldest sample <span class=\"theme:classic lang:c++ decode:true crayon-inline \">x[7]<\/span>\u00a0. Then <span class=\"theme:classic lang:c++ decode:true crayon-inline \">x[5]<\/span>\u00a0 is copied over <span class=\"theme:classic lang:c++ decode:true crayon-inline \">x[6]<\/span>\u00a0 etc..\u00a0The last operation is to overwrite x[0] with the newly measured sample. We can now re-calculate the average as before.<\/p>\n<p>It should be noted at this point that the literal copying of samples (as depicted) is not the most efficient technique and that there are faster methods that are logically equivalent.<\/p>\n<h2>Task 4.3.3<\/h2>\n<p>Perform the following:<\/p>\n<table style=\"border-collapse: collapse;border: 1px solid black\" cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"middle\">Sketch a flow-chart for the method just described<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Create a new project and implement this method in code.<span class=\"Apple-converted-space\">\u00a0<\/span><\/p>\n<p>Make the array N samples in size, where N is defined as a constant. e.g.<\/p>\n<p><span class=\"theme:classic lang:default decode:true crayon-inline\">#define N 10<\/span><\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">If you get stuck, take a peek at the <a href=\"https:\/\/os.mbed.com\/teams\/Students-Plymouth-University-UK-SoCEM\/code\/Task433Solution\/file\/fa5ec79b26fb\/main.cpp\" target=\"_blank\" rel=\"noopener\">solution<\/a><\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">In what ways do you think this method is inefficient?<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Now watch the video (below) on how to log the data for off-line analysis on your PC.<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">If you wish, repeat this procedure for yourself. It\u2019s a useful technique.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>https:\/\/youtube.com\/watch?v=ojgWI-v5LUw%3Flist%3DPLhsioMrc4CkpVxHnrXO8wjSVWlMTnT6N_<\/p>\n<p><a href=\"https:\/\/os.mbed.com\/teams\/Students-Plymouth-University-UK-SoCEM\/code\/Task433Solution\/file\/fa5ec79b26fb\/main.cpp\" target=\"_blank\" rel=\"noopener\">One solution is provided<\/a>. Note also the following:<\/p>\n<p>The copying of data in the array is both repetitive and inefficient in computation.<span class=\"Apple-converted-space\">\u00a0<\/span>Instead of moving all the samples in the array, all we really need to do is overwrite the oldest sample and recalculate (this is known as a circular buffer).\u00a0Furthermore, the average is based on the sum of all elements in the array, we can simply \u201cupdate\u201d our sum as follows:<\/p>\n<p><span class=\"Apple-converted-space\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-044d61982ac0c7f809a87b623bdee9c0_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#97;&#118;&#101;&#114;&#97;&#103;&#101;&#40;&#110;&#43;&#49;&#41;&#61;&#97;&#118;&#101;&#114;&#97;&#103;&#101;&#40;&#110;&#41;&#43;&#110;&#101;&#119;&#83;&#97;&#109;&#112;&#108;&#101;&#45;&#111;&#108;&#100;&#101;&#115;&#116;&#83;&#97;&#109;&#112;&#108;&#101;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"468\" style=\"vertical-align: -5px;\"\/>\u00a0<\/span><\/p>\n<p>Note that I have also created an instance of \u201c<span class=\"theme:classic lang:default decode:true crayon-inline\">Serial<\/span>\u00a0\u201d. This allows data to be written back to the terminal at higher speeds (115200 bits\/second), equivalent to 14500 Bytes per second.<\/p>\n<p>You may also have found there was a lot of repetition in your solution (and mine!). Using functions can help reduce repetition and bugs.\u00a0Consider the following function prototype:<\/p>\n<pre class=\"theme:xcode lang:c++ decode:true\" style=\"padding-left: 90px\">float updateAverage(float newSample, float buffer[]);\r\n<\/pre>\n<p>This function accepts two parameters. The new sample (a single float) and the buffer (an array of float) used to store past samples.The function returns the average (single float).<\/p>\n<h2>Task 4.3.4<\/h2>\n<p>Perform the following:<\/p>\n<table style=\"border-collapse: collapse;border: 1px solid black\" cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"middle\">Starting with the code below, complete the function and use it to shorten the code. <a href=\"https:\/\/os.mbed.com\/teams\/Students-Plymouth-University-UK-SoCEM\/code\/Task434Solution\/file\/6a8980b23272\/main.cpp\" target=\"_blank\" rel=\"noopener\">A solution is provided<\/a> in case you want to check your answer.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<pre class=\"theme:xcode lang:c++ decode:true\">#include \"mbed.h\"\r\n\r\n\/\/Constants\r\n#define N 10\r\n\r\n\/\/Function Prototype\r\nfloat updateAverage(float newSample, float buffer[]);\r\n\r\n\/\/Global objects\r\nSerial pc(USBTX, USBRX);\r\n\r\nBusOut binaryOutput(D5, D6, D7);\r\nAnalogIn POT_ADC_In(A0);\r\nAnalogIn LDR_ADC_In(A1);\r\n\r\nfloat xPOT[N]; \/\/Aray of potentiometer samples\r\nfloat xLDR[N]; \/\/Aray of LDR samples\r\n\r\n\/\/Main function\r\nint main()\r\n{\r\n   \r\n   \/\/Set baud rate to 115200\r\n   pc.baud(115200);\r\n   \r\n   \/\/Print header\r\n   pc.printf(\"POT,LDR,avPOT, acLDR\\n\\n\");\r\n   \r\n   while(1) {\r\n      \r\n      \/\/Move the samples in both arrays to the right\r\n      for (unsigned int n=(N-1); n&gt;0; n--) {\r\n         xPOT[n] = xPOT[n-1];\r\n         xLDR[n] = xLDR[n-1];\r\n      }\r\n      \r\n      \/\/Insert the new sample at position 0\r\n      xPOT[0] = POT_ADC_In;\r\n      xLDR[0] = LDR_ADC_In;\r\n      \r\n      \/\/Calculate average for POT\r\n      float fSum = 0.0;\r\n      for (unsigned int n=0; n&lt;N; n++) {\r\n         fSum += xPOT[n];\r\n      }\r\n      float fPOTAverage = fSum \/ (float)N;\r\n      \r\n      \/\/Calculate average for LDR\r\n      fSum = 0.0;\r\n      for (unsigned int n=0; n&lt;N; n++) {\r\n         fSum += xLDR[n];\r\n      }\r\n      float fLDRAverage = fSum \/ (float)N;\r\n      \r\n      \/\/Write to terminal via Serial interface\r\n      pc.printf(\"%6.4f,%6.4f,%6.4f,%6.4f\\n\", xPOT[N\/2], xLDR[N\/2], fPOTAverage, fLDRAverage);\r\n      \r\n      \/\/Check the threshold\r\n      if (fLDRAverage &gt; fPOTAverage) {\r\n         binaryOutput = 0;   \/\/Binary 000\r\n      } else {\r\n         binaryOutput = 7;   \/\/Binary 111\r\n      }\r\n      \r\n      \/\/Wait 1\/100th second\r\n      wait(0.01);\r\n      \r\n      \r\n   } \/\/end while(1)\r\n} \/\/end main\r\n\r\n\r\n\/*\r\n First version of the updateAverage function\r\n TODO\r\n *\/\r\nfloat updateAverage(float newSample, float buffer[])\r\n{\r\n   \/\/Local variable - remember to initialise!\r\n   float average = 0.0;\r\n   \r\n   \/\/TODO: Move all samples to the right\r\n   \r\n   \r\n   \/\/TODO: Insert new sample\r\n   \r\n   \r\n   \/\/TODO: Calculate average\r\n   \r\n   \/\/Return the result\r\n   return average;\r\n}<\/pre>\n<p>The sampling rate is still not constant. The time between each sample read depends on the execution time of the code each time around the loop. Not only will this change as the code is maintained, but different \u201coptimisation settings\u201d or even a change in \u201c<a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/compiler-glossary-entry\/\" target=\"_blank\" rel=\"noopener\"><b>compiler<\/b><\/a> version\u201d will impact on code execution time.<\/p>\n<p>To address this, we can use a timer <b>interrupt<\/b> (<a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/interrupt-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">read the glossary entry<\/a> to learn more about interrupts).<\/p>\n<p>In Mbed-os, there is a component called a \u201c<span class=\"theme:classic lang:c++ decode:true crayon-inline\">Ticker<\/span>\u00a0\u201d. This object maintains a hardware timer. When that timer reaches a specified value, it calls the function you specify.\u00a0This function takes no arguments and returns no data. For example:<\/p>\n<pre class=\"lang:c++ decode:true \">void func();<\/pre>\n<p>It is probably best to give an example to explain this.<\/p>\n<pre class=\"lang:c++ mark:19,47 decode:true\">#include \"mbed.h\"\r\n\r\n\/\/Global objects\r\nDigitalOut myled(LED1);\r\nSerial pc(USBTX, USBRX);\r\nTicker t;\r\n\r\n\/\/Integer state of the LED\r\n\/\/static makes it visible only within main.cpp\r\nstatic int state = 0;\r\n\r\n\/\/Function prototype\r\nvoid doISR();\r\n\r\nint main() {\r\n   \r\n   \/\/Initialise\r\n   pc.baud(115200);\r\n   t.attach(doISR, 2);\r\n   myled = 0;\r\n   \r\n   \/\/Main loop\r\n   while(1) {\r\n      \r\n      \/\/Go to sleep and wait for an ISR to wake\r\n      sleep();    \/\/At is says\r\n      \r\n      \/\/At this point, the ISR has run\r\n      \r\n      \/\/Update LED\r\n      myled = state;\r\n      \r\n      \/\/Echo to terminal\r\n      if (state == 0) {\r\n         pc.printf(\"LED OFF\\n\");\r\n      } else {\r\n         pc.printf(\"LED ON\\n\");\r\n      }\r\n      wait(0.001); \/\/Plenty of time for the serial port to transmit\r\n   }\r\n}\r\n\r\n\/\/Note - the ISR is short, and does NOT \r\n\/\/call functions such as printf \r\n\/\/(it's actually unsafe to do so)\r\n\/\/Always check a function is \"reentrant\"\r\n\/\/before calling it\r\nvoid doISR() {\r\n   \/\/Toggle 0 to 1, or 1 to 0\r\n   state ^= 1;\r\n}<\/pre>\n<p>First we create an instance of the <span class=\"theme:classic lang:c++ decode:true crayon-inline\">Ticker<\/span>\u00a0 object<\/p>\n<p style=\"padding-left: 30px\"><span class=\"lang:c++ decode:true crayon-inline\">Ticker t;<\/span><\/p>\n<p>Now we specify what function it shall call, and how often.<\/p>\n<p style=\"padding-left: 30px\"><span class=\"lang:c++ decode:true crayon-inline\">t.attach(doISR, 2);<\/span><\/p>\n<p>The first parameter is the name of the function. In fact, this is actually the <i>address<\/i> of the function in program memory, but that is a detail right now. Sometimes you see it written like this:<\/p>\n<p style=\"padding-left: 30px\"><span class=\"lang:c++ decode:true crayon-inline \">t.attach(&amp;doISR, 2);<\/span><\/p>\n<p>where the prefix <span class=\"theme:classic lang:c++ decode:true crayon-inline\">&amp;<\/span>\u00a0means \u201caddress of\u201d. The ticker is actually a timer, which will call the function <span class=\"theme:classic lang:c++ decode:true crayon-inline\">doISR<\/span>\u00a0 every 2 seconds. This time is specified as the second parameter specifies (in seconds).<\/p>\n<p>What might surprise you is the first statement in the while loop, which is:<\/p>\n<p style=\"padding-left: 30px\"><span class=\"lang:c++ decode:true crayon-inline \">sleep();<\/span><\/p>\n<p>This does what it says: puts the CPU into a sleeping mode.<span class=\"Apple-converted-space\">\u00a0<\/span>Every 2 seconds, the CPU is woken up and the <span class=\"theme:classic lang:c++ decode:true crayon-inline\">doISR<\/span>\u00a0 function is called. On inspection, note that all this function does is toggle a variable between<br \/>\n0 and 1.<\/p>\n<p>The code in the while loop can then resume beyond the sleep() function, which is to update the LED output and write to the terminal.<\/p>\n<pre class=\"lang:c++ decode:true\">void doISR() { \r\n  \/\/Toggle 0 to 1, or 1 to 0\r\n  state ^= 1; \r\n}<\/pre>\n<p>The code in the while loop can then resume beyond the <span class=\"theme:classic lang:c++ decode:true crayon-inline\">sleep()<\/span>\u00a0 function, which is to update the LED output and write to the terminal.\u00a0The CPU then returns to the sleep mode until the ticker wakes it again.<\/p>\n<p><b>Notes:\u00a0<\/b><\/p>\n<ul>\n<li>The interrupt service routine runs once every 2 seconds. The frequency is fixed, and is independent of the code in the main function, compiler settings etc..\u00a0We can say that the ISR is \u201cdeterministic\u201d (fully predictable in time).<\/li>\n<li>Any data sent to the serial port (e.g. via <code>printf<\/code>\u00a0 or <code>puts<\/code>) <em>will generate a sequence of interrupts during communication<\/em>. A small delay is added to allow all bytes to be transmitted and for all the interrupts to be processed, otherwise the CPU will be brought out of sleep mode prematurely.<\/li>\n<\/ul>\n<h2>Additional Task 4.3.5<\/h2>\n<p>If you have time, try the following:<\/p>\n<table style=\"border-collapse: collapse;border: 1px solid black\" cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"middle\">Can you modify the solution in 4.3.4 to use a <span class=\"theme:classic lang:c++ decode:true crayon-inline\">Ticker<\/span><\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">The sampling rate should be precisely 100Hz (T=0.01s)<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Keep the ISR as short as possible.<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Add a DigitalOut for pin D8.<br \/>\n<span class=\"lang:c++ decode:true crayon-inline \">DigitalOut strobe(D8);<\/span><\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Inside the ISR, you should measure the POT and LDR samples and toggle the D8 pin<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">If you have access to an Oscilloscope, verify the sampling rate by monitoring pin D8<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Even if you cannot do Task 4.3.5, do take a look at <a href=\"https:\/\/os.mbed.com\/teams\/Students-Plymouth-University-UK-SoCEM\/code\/Task435Solution\/file\/e6cfe26c00ef\/main.cpp\/\" target=\"_blank\" rel=\"noopener\">the solution<\/a> and read the comments.<\/p>\n<p>The scope output on D8 is as follows:<\/p>\n<figure id=\"attachment_467\" aria-describedby=\"caption-attachment-467\" style=\"width: 1491px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-467 size-full\" src=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/ScopeD8.png\" alt=\"\" width=\"1491\" height=\"839\" srcset=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/ScopeD8.png 1491w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/ScopeD8-300x169.png 300w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/ScopeD8-768x432.png 768w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/ScopeD8-1024x576.png 1024w\" sizes=\"auto, (max-width: 1491px) 100vw, 1491px\" \/><figcaption id=\"caption-attachment-467\" class=\"wp-caption-text\">Using an oscilloscope to monitor the output signal on a micro controller pin. Note that signal noise is visible. We can see that the output toggles every 10ms.<\/figcaption><\/figure>\n<p>The oscilloscope output is shown above. Note the following:<\/p>\n<ul>\n<li>The interval between the signal switching state is measured as 10.0ms which is what was required<\/li>\n<li>The logic ON level is approx. 3.3V and the OFF level is approx. 0V<\/li>\n<li>You can see noise on the signal.<\/li>\n<\/ul>\n<p>(Digital noise is a reality of life. It can often originate from current spikes and a power supply that is not perfect).<\/p>\n<p>The key point from this exercise is that we can use Timer interrupts to obtain a precise sampling rate.\u00a0For many applications, this is absolutely critical. Systems that need deterministic timing are often known as <b>real-time<\/b> systems. <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/digital-signal-processing-dsp-glossary-entry\/\" target=\"_blank\" rel=\"noopener\"><b>Digital Signal Processing<\/b><\/a> (DSP) applications require precise sampling for the mathematics to be valid.<\/p>\n<p>Using interrupts is also more power efficient.<\/p>\n<blockquote><p><strong>Word of caution<\/strong>. Writing robust (and safe) interrupt code is not trivial, especially as the number of inputs increases. This can lead to problems such as <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/race-conditions-glossary-entry\/\" target=\"_blank\" rel=\"noopener\"><b>race conditions<\/b><\/a> (data corruption), priority inversion and deadlocks. These topics are beyond the scope of this level 4 course and will be covered in detail elsewhere.<\/p><\/blockquote>\n<p>Safer alternatives exist. To manage higher complexity, you might consider using a real-time \u201coperating system\u201d or \u201creal-time micro kernel\u201d to help write complex real-time software. Mbed-os actually offers such a facility, but again, this is beyond the scope of this course (and is covered elsewhere).<\/p>\n<h2>Additional Task 4.3.6<\/h2>\n<p>Only attempt this if you have time and are confident<\/p>\n<p>If you are feeling ambitious, you can further optimise these solutions (as discussed in the solution of Task 4.3.3).\u00a0The moving of data in the array is both repetitive and inefficient in computation.<span class=\"Apple-converted-space\">\u00a0<\/span>Instead of moving all the samples in the array, all we really need to do is overwrite the oldest sample and recalculate. This is known as circular buffering.\u00a0For this we simply need to keep track of where the oldest and newest sample are stored.<\/p>\n<p>Furthermore, the average is based on the sum of all elements in the array. Instead of calculating the complete sum every time, we can simply \u201cupdate\u201d our sum as follows:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-044d61982ac0c7f809a87b623bdee9c0_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#97;&#118;&#101;&#114;&#97;&#103;&#101;&#40;&#110;&#43;&#49;&#41;&#61;&#97;&#118;&#101;&#114;&#97;&#103;&#101;&#40;&#110;&#41;&#43;&#110;&#101;&#119;&#83;&#97;&#109;&#112;&#108;&#101;&#45;&#111;&#108;&#100;&#101;&#115;&#116;&#83;&#97;&#109;&#112;&#108;&#101;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"468\" style=\"vertical-align: -5px;\"\/><\/p>\n<table cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"middle\">Improve the solution in 4.3.5 to reduce the computation load using both the methods described<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><a href=\"https:\/\/os.mbed.com\/teams\/Students-Plymouth-University-UK-SoCEM\/code\/Task436Solution\/file\/315c40dcb63f\/main.cpp\" target=\"_blank\" rel=\"noopener\">A solution is given here.<\/a><\/p>\n<h1><\/h1>\n<hr \/>\n<h1>Activity 4.4 &#8211; Closer look at Analogue to Digital Conversion<\/h1>\n<p>We are using the Mbed-os framework (set of objects) to perform rapid development of embedded software. Until now, you have used a <span class=\"theme:classic lang:c++ decode:true crayon-inline\">DigitalIn<\/span>\u00a0 object to read the input from an on-chip <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/analogue-to-digital-converter-adc-glossary-entry\/\" target=\"_blank\" rel=\"noopener\"><b>Analogue to Digital Converter<\/b><\/a> (ADC).<\/p>\n<p>The default behavior is to return a value a fractional value of type float, scaled between 0.0 and 1.0.\u00a0This is ideal for further processing, but for education, does somewhat mask the true nature of an ADC and the issues around signal conversion.<\/p>\n<p>In this section we delve a little deeper to look at the ADC using some of the other functions in <span class=\"theme:classic lang:c++ decode:true crayon-inline \">DigitalIn<\/span>.<\/p>\n<h2>Task 4.1.1<\/h2>\n<table style=\"border-collapse: collapse;border: 1px solid black\" cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"middle\">Read the glossary entries on <strong><a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/glossary\/\" target=\"_blank\" rel=\"noopener\">Analogue Signals<\/a><\/strong>, <strong><a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/digital-signal-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">Digital Signals<\/a><\/strong> and the <b>Analogue to Digital Converter\u00a0<\/b><\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Form a group of 3 from people near you.<\/p>\n<p>Person A will form and ask one or more short questions on a chosen topic<\/p>\n<p>Person B will answer the question verbally for a maximum of 2 minutes<\/p>\n<p>Person C will keep time, observe and give constructive feedback at the end<\/p>\n<p>After each round, rotate roles and topics.<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">The topics are as follows<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Round 1: Analogue Signals<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Round 2: Digital Signals<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Round 3: Analogue to Digital Conversion<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>At this point, you probably have a circuit as is shown here. For the next task, ensure you have at least the POT wired.<\/p>\n<figure id=\"attachment_442\" aria-describedby=\"caption-attachment-442\" style=\"width: 1814px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-442\" src=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Circuit-with-LDR.png\" alt=\"\" width=\"1814\" height=\"1837\" srcset=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Circuit-with-LDR.png 1814w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Circuit-with-LDR-296x300.png 296w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Circuit-with-LDR-768x778.png 768w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Circuit-with-LDR-1011x1024.png 1011w, https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/uploads\/sites\/94\/2018\/10\/Circuit-with-LDR-986x999.png 986w\" sizes=\"auto, (max-width: 1814px) 100vw, 1814px\" \/><figcaption id=\"caption-attachment-442\" class=\"wp-caption-text\">Wiring instructions for the Light Dependent Resistor (LDR)<\/figcaption><\/figure>\n<h2>Task 4.4.2<\/h2>\n<p>Perform the following:<\/p>\n<table style=\"border-collapse: collapse;border: 1px solid black\" cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"middle\">Build and run the code below<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Monitor the output with PuTTY (Set the rate to 115200)<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Turn the POT to discover the minimum and maximum values<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Convert the HEX values to decimal<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">How many bits resolution do you think the ADC has? (8,10, 12t or 16 bit?)<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">What is the smallest input voltage required to get a value of 1?<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<pre class=\"lang:c++ decode:true\">#include \"mbed.h\"\r\n\r\n\/\/Function prototype\r\nvoid doSample1Hz();\r\n\r\n\/\/Global objects\r\nSerial pc(USBTX, USBRX);\r\nAnalogIn POT_ADC_In(A0);\r\nDigitalOut led(LED1);\r\n\r\n\/\/Shared variables\r\nvolatile static unsigned short sample16 = 0;\r\n\r\n\/\/The ticker, used to sample data at a fixed rate\r\nTicker t;\r\n\r\n\/\/Main function\r\nint main()\r\n{\r\n   \/\/Set baud rate to 115200\r\n   pc.baud(115200);\r\n   \r\n   \/\/Set up the ticker - 100Hz\r\n   t.attach(doSample1Hz, 1.0);\r\n   \r\n   while(1) {\r\n      \r\n      \/\/Sleep\r\n      sleep();\r\n      \r\n      \/\/Displauy the sample in HEX\r\n      pc.printf(\"ADC Value: %X\\n\", sample16);\r\n      \r\n   } \/\/end while(1)\r\n} \/\/end main\r\n\r\n\/\/ISR for the ticker - simply there to perform sampling\r\nvoid doSample1Hz()\r\n{\r\n   \/\/Toggle on board led\r\n   led = !led;\r\n   \r\n   \/\/READ ADC as an unsigned integer.\r\n   \/\/Shift right 4 bits &amp; store in static global variable\r\n   sample16 = POT_ADC_In.read_u16() &gt;&gt; 4;\r\n}<\/pre>\n<blockquote><p><b>Calculating Logs<\/b><\/p>\n<p>To perform a log in a base <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-501c081517b1f5e359fed99657131700_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#66;\" title=\"Rendered by QuickLaTeX.com\" height=\"12\" width=\"14\" style=\"vertical-align: 0px;\"\/>, you can use any log function on your calculator:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-294f81a07c3dbfde1b46771b786206cc_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#108;&#111;&#103;&#95;&#66;&#40;&#97;&#41;&#61;&#92;&#102;&#114;&#97;&#99;&#123;&#108;&#111;&#103;&#40;&#97;&#41;&#125;&#123;&#108;&#111;&#103;&#40;&#66;&#41;&#125;\" title=\"Rendered by QuickLaTeX.com\" height=\"29\" width=\"123\" style=\"vertical-align: -10px;\"\/><\/p>\n<p>For example, for <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-e5db0d5e9ba5d3a18a2e2d2e1ad0ddbb_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#108;&#111;&#103;&#95;&#50;&#123;&#49;&#54;&#125;&#61;&#92;&#102;&#114;&#97;&#99;&#123;&#108;&#111;&#103;&#95;&#123;&#49;&#48;&#125;&#40;&#49;&#54;&#41;&#125;&#123;&#108;&#111;&#103;&#95;&#123;&#49;&#48;&#125;&#40;&#50;&#41;&#125;&#61;&#52;\" title=\"Rendered by QuickLaTeX.com\" height=\"29\" width=\"163\" style=\"vertical-align: -10px;\"\/><\/p>\n<p>Similarly, <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-d5531f8f7aef0e80092efe1d500404e0_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#108;&#111;&#103;&#95;&#50;&#123;&#49;&#54;&#125;&#61;&#92;&#102;&#114;&#97;&#99;&#123;&#108;&#110;&#40;&#49;&#54;&#41;&#125;&#123;&#108;&#110;&#40;&#50;&#41;&#125;&#61;&#52;\" title=\"Rendered by QuickLaTeX.com\" height=\"29\" width=\"145\" style=\"vertical-align: -10px;\"\/><\/p><\/blockquote>\n<h3>Solution<\/h3>\n<p>The range is 000.. FFF (hex), which in decimal is 0..4095.\u00a0Therefore, there are 4096 possible values.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-4d848b2bfb3a5230a745539751e78756_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#108;&#111;&#103;&#95;&#123;&#50;&#125;&#40;&#52;&#48;&#57;&#54;&#41;&#61;&#32;&#49;&#50;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"120\" style=\"vertical-align: -5px;\"\/> bits<\/p>\n<p>Given the input range is 0&#8230;3.3V, the quantization level <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-5dacb7436512c107d65e2988fad6a1be_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#92;&#68;&#101;&#108;&#116;&#97;&#32;&#61;&#32;&#92;&#102;&#114;&#97;&#99;&#123;&#51;&#46;&#51;&#125;&#123;&#52;&#48;&#57;&#54;&#45;&#49;&#125;&#61;&#48;&#46;&#56;&#48;&#54;&#109;&#86;\" title=\"Rendered by QuickLaTeX.com\" height=\"22\" width=\"182\" style=\"vertical-align: -6px;\"\/><\/p>\n<p>The ADC will output a 1 when the input exceeds <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-content\/ql-cache\/quicklatex.com-937247cd017b889e5ca84fe8617059d9_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#92;&#68;&#101;&#108;&#116;&#97;&#32;&#47;&#32;&#50;\" title=\"Rendered by QuickLaTeX.com\" height=\"19\" width=\"32\" style=\"vertical-align: -5px;\"\/><\/p>\n<h2>Advanced Task 4.4.3<\/h2>\n<p>If you have time, try the following:<\/p>\n<table style=\"border-collapse: collapse;border: 1px solid black\" cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"middle\">Modify the code in task 4.4.2 to write the terminal output in binary format<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\">Hint : use the &amp; operator to test each of the 12 bits. Try and use a <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/for-loop-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">for-loop<\/a> to keep your solution compact and short<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><a href=\"https:\/\/os.mbed.com\/teams\/Students-Plymouth-University-UK-SoCEM\/code\/Task443Solution\/file\/5c5a623dc9e0\/main.cpp\" target=\"_blank\" rel=\"noopener\">A solution is given here<\/a>.<\/p>\n<h2>Advanced Task 4.4.4<\/h2>\n<p>Again, if you have time, try the following:<\/p>\n<table style=\"border-collapse: collapse;border: 1px solid black\" cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"middle\">Using only unsigned short and integer arithmetic, calculate the average value of the POT.<\/p>\n<p>Use a sampling rate of 100Hz<\/td>\n<\/tr>\n<tr>\n<td valign=\"middle\"><i>Hint:<\/i> let N be a power of 2, and use a right-shift &gt;&gt; to perform the division.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><a href=\"https:\/\/os.mbed.com\/teams\/Students-Plymouth-University-UK-SoCEM\/code\/Task444Solution\/file\/83a9911ab6ec\/main.cpp\" target=\"_blank\" rel=\"noopener\">A solution is given here<\/a>.<\/p>\n<h1>Some words of caution<\/h1>\n<p>In this section, we&#8217;ve had a first look at interfacing a micro controller to the analogue world. This has hopefully been a useful introduction to the practical mechanisms of sampling analogue signals such that real-world signals can be represented digitally inside a computer. We also had a first look at <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/interrupt-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">interrupts<\/a>.<\/p>\n<p>It is important to note that this is only an introduction.<\/p>\n<ul>\n<li>There is much more to learn when it comes to sampling real-world signals correctly such that they can be properly mathematically analysed and\/or processed. This is a topic that will be covered in another course (level 5 onwards).<\/li>\n<li>As mentioned in the text above, interrupts can be hazardous &#8211; their asynchronous nature means running code may be interrupted at unpredictable times, and in the absence of protection, can results in data inconsistency or even corruption (known as a <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/race-conditions-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">race condition<\/a>). Again, this is a topic that is covered in later stages. For now, the intention is that you are aware of interrupts and understand the very basic concept. <em>It is not recommended that you use interrupts outside of personal experimentation until you know more<\/em>.<\/li>\n<\/ul>\n<p>There is a saying, which goes something like this:<\/p>\n<blockquote><p>A little knowledge is a dangerous thing<\/p><\/blockquote>\n<p>or sometimes:<\/p>\n<blockquote><p>A little learning is a dangerous thing<\/p><\/blockquote>\n<p>This is particularly true for topics such as <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/interrupt-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">interrupts<\/a> and <a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/glossary-2\/analogue-to-digital-converter-adc-glossary-entry\/\" target=\"_blank\" rel=\"noopener\">analogue to digital conversion<\/a>.<\/p>\n<p><a href=\"http:\/\/blogs.plymouth.ac.uk\/embedded-systems\/mbed-os-2\/courses\/embedded-systems-in-context-level-4\/\">Back to ToC<\/a><\/p>\n<hr \/>\n<h1>Feedback<\/h1>\n<p>If you wish to leave feedback or have a question, please use the form below.<\/p>\n<p>[contact-form][contact-field label=&#8221;Name&#8221; type=&#8221;name&#8221; required=&#8221;true&#8221; \/][contact-field label=&#8221;Email&#8221; type=&#8221;email&#8221; required=&#8221;true&#8221; \/][contact-field label=&#8221;Website&#8221; type=&#8221;url&#8221; \/][contact-field label=&#8221;Message&#8221; type=&#8221;textarea&#8221; \/][\/contact-form]<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Back to ToC In this section we look at interfacing with the analogue world. You will use a simple potentiometer to generate analogue voltages, and measure that voltage using an Analogue to Digital Converter (ADC).\u00a0We also look at different ways to represent an analogue voltage as a digital value.\u00a0Hysteresis is used to manage signal noise&hellip; <a class=\"more-link\" href=\"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/microcontrollers\/mbed-os-2\/courses\/embedded-systems-in-context-level-4\/topic-4-analogue-input\/\">Continue reading <span class=\"screen-reader-text\">Topic 4 \u2013 Analogue Input<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":130,"menu_order":4,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-371","page","type-page","status-publish","hentry","entry"],"_links":{"self":[{"href":"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-json\/wp\/v2\/pages\/371","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-json\/wp\/v2\/comments?post=371"}],"version-history":[{"count":59,"href":"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-json\/wp\/v2\/pages\/371\/revisions"}],"predecessor-version":[{"id":709,"href":"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-json\/wp\/v2\/pages\/371\/revisions\/709"}],"up":[{"embeddable":true,"href":"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-json\/wp\/v2\/pages\/130"}],"wp:attachment":[{"href":"https:\/\/blogs.plymouth.ac.uk\/embedded-systems\/wp-json\/wp\/v2\/media?parent=371"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}