owned this note
owned this note
Published
Linked with GitHub
---
tags: mdef, electronics, coding
---
# Inputs & Outputs
[TOC]
## Core ideas
* Why we need sensors.
* Physical, chemical or bio reactions.
* Sensing the environment.
* Close loop systems.
* Inferring metrics.
* Bike speed from counting wheel turns
* Water tank distance from distance from above
* Composed sensors
* Radar: emitter (output) and receiver (input) working in sync
* Complex post processing: Computer vision
* From a list of colors (pixel matrix) to meaningful data (i.e. object location based in color tracking)
Open the **discussion** with [**Sensor fusion**](https://en.wikipedia.org/wiki/Sensor_fusion) good and bad potential.
{%youtube aqbKrrru2co%}
## Digital signals
An advanced **Mouse detector** based on simple digital signal
![](https://i.imgur.com/A9HCGGh.jpg =500x)
In the Arduino world to read a digital signal we use the function [digitalRead](https://www.arduino.cc/reference/en/language/functions/digital-io/digitalread/) this signal only has two possible values:
|0 volts| 5 volts|
|---|---|
HIGH|LOW|
true|false
Depending on the type (and age) of the electronics we use the _HIGH_ value corresponds to different voltages, for exmple: 5v, 3.3v, 1.8v.
### Pullups y pulldowns
>Arduino (Atmega) **pins default to inputs**, so they don't need to be explicitly declared as inputs with pinMode() when you're using them as inputs. Pins configured this way are said to be in a **high-impedance state.** Input pins make extremely small demands on the circuit that they are sampling, equivalent to a series resistor of 100 megohm in front of the pin. This means that it takes very little current to move the input pin from one state to another.
>This also means however, that pins configured as pinMode(pin, INPUT) with nothing connected to them, or with wires connected to them that are not connected to other circuits, will report seemingly random changes in pin state, picking up electrical noise from the environment, or capacitively coupling the state of a nearby pin.
[Arduino reference](https://www.arduino.cc/en/Tutorial/DigitalPins)
![](http://cdn.sparkfun.com/assets/0/5/9/0/8/513901dfce395f671a000000.jpg =400x)
Arduino pins can also be configured as **INPUT_PULLUPS**, this will activate an internal pullup resistor of 20k. Or you can install external pullups/pulldowns depending if your circuit is active LOW or active HIGH.
### Counting pulses
Sometimes we want to count the number of times something happens in a period of time, like for example how many turns does an anemometer every minute. Counting pulses we can measure things like the speed of a bike, the position of a CNC router, the amount of people that enters a building, etc.
[pulseIn](https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/)
The example prints the time duration of a pulse on pin 7.
~~~c
int pin = 7;
unsigned long duration;
void setup() {
Serial.begin(9600);
pinMode(pin, INPUT);
}
void loop() {
duration = pulseIn(pin, HIGH);
Serial.println(duration);
}
~~~
### [Debouncing](https://www.arduino.cc/en/Tutorial/Debounce) buttons.
![](https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fhackaday.com%2Fwp-content%2Fuploads%2F2015%2F11%2Fdebounce_bouncing.png&f=1&nofb=1 =500x)
![](https://www.arduino.cc/en/uploads/Tutorial/button.png)
:::spoiler Example code
~~~c
/*
Debounce
Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
press), the output pin is toggled from LOW to HIGH or HIGH to LOW. There's a
minimum delay between toggles to debounce the circuit (i.e. to ignore noise).
The circuit:
- LED attached from pin 13 to ground
- pushbutton attached from pin 2 to +5V
- 10 kilohm resistor attached from pin 2 to ground
- Note: On most Arduino boards, there is already an LED on the board connected
to pin 13, so you don't need any extra components for this example.
created 21 Nov 2006
by David A. Mellis
modified 30 Aug 2011
by Limor Fried
modified 28 Dec 2012
by Mike Walters
modified 30 Aug 2016
by Arturo Guadalupi
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Debounce
*/
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = HIGH; // the current state of the output pin
int buttonState; // the current reading from the input pin
int lastButtonState = LOW; // the previous reading from the input pin
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
// set initial LED state
digitalWrite(ledPin, ledState);
}
void loop() {
// read the state of the switch into a local variable:
int reading = digitalRead(buttonPin);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited long enough
// since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer than the debounce
// delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
// only toggle the LED if the new button state is HIGH
if (buttonState == HIGH) {
ledState = !ledState;
}
}
}
// set the LED:
digitalWrite(ledPin, ledState);
// save the reading. Next time through the loop, it'll be the lastButtonState:
lastButtonState = reading;
}
~~~
:::
## Analog values
### ADC **Analog** to **Digital** converter.
In an ADC circuit there are several steps to go from an analog signal to a digital value. The first stage is called **Sampling and Holding**:
>An analog signal continuously changes with time, in order to measure the signal we have to keep it steady for a short duration so that it can be sampled.
The next stage is **Quantizing and Encoding:**
>On the output of (S/H), a certain voltage level is present. We assign a numerical value to it. The nearest value, in correspondence with the amplitude of sampling and holding signal, is searched.
![](https://nutaq.com/sites/default/files/images/blog-images/Two-stage%20process%20conversion%20of%20the%20voltage%20generated%20by%20the%20sensor%20to%20its%20digital%20equivalent%20performed%20by%20the%20ADC.png =600x)
The **resolution** of an ADC is measured in bits, a one bit resolution ADC is capable of delivering 2¹ different values (0 and 1). The Arduino UNO has a **10 bit** integrated ADC that means it can deliver 2¹⁰ values **from 0 to 1023**.
The [ESP32 Feather](https://hackmd.io/OcD2aBtRTG2pRfJKVV8CBg#AnalogRead) ADC has a **12 bit** resolution, and will generate a number between **0 - 4096.** To adjust the resolution you can just divide that value or use the [analogReadResolution()](https://www.arduino.cc/reference/en/language/functions/zero-due-mkr-family/analogreadresolution/) arduino function.
### Voltage divider
How to measure the resistance of a variable resistor
![](https://i.imgur.com/6W61AZH.png)
**R1** is variable but **R2** is static and defined by us (we try to find a resistor that is similar to the expected middle point value of the sensor readings).
>![](https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Resistive_divider2.svg/220px-Resistive_divider2.svg.png)
>
>![](https://wikimedia.org/api/rest_v1/media/math/render/svg/5d55415f24b63635bc017c3287b406c480a54472)
>
>To solve for **R1:**
>
>![](https://wikimedia.org/api/rest_v1/media/math/render/svg/bd9f9ac116b6ce45ed90f375b4c5b0e7bac1df87)
>
>To solve for **R2:**
>
>![](https://wikimedia.org/api/rest_v1/media/math/render/svg/80b9b6c4ed9db743097f939c93c4d239c6ecfaeb)
From [Wikipedia](https://en.wikipedia.org/wiki/Voltage_divider)
:::spoiler Code example
~~~c
int R2 = 10000;
float VIN = 5.0;
void setup() {
Serial.begin(9600);
}
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// Get the value of R1
int ldr = ((R2 * VIN) / voltage) - R2;
// print out the value you read:
Serial.print("voltage: ");
Serial.println(voltage);
Serial.print("LDR value: ");
Serial.println(ldr);
}
~~~
:::
## How to choose and use a sensor
_The section is aimed at **INPUTS** (sensors) but many concepts work also for **OUTPUTS** (motors, LEDs)_
* How to choose sensor?
* Integrated circuits, breakout boards, and off-the-shelf devices
* [IC Component](https://eu.mouser.com/ProductDetail/Bosch-Sensortec/BNO055)
* [Adafruit IMU Breakout](https://www.adafruit.com/product/2472)
* [Wii Nunchuck](https://en.wikipedia.org/wiki/Wii_Remote#Nunchuk) (check in Wallapop, Cash converters, Ebay...)
* How to wire a sensor?
* We will always look for well documented sensors [learn.sparkfun.com](https://learn.sparkfun.com/), [learn.adafruit.com](https://learn.adafruit.com/)
* Download the EAGLES from the Breakout boards to help you, [example](https://github.com/adafruit/Adafruit-GUVA-Analog-UV-Sensor-Breakout-PCB)
* How to code for a sensor?
* [Fab Academy sensors](http://academy.cba.mit.edu/classes/input_devices/index.html)
* Sensor interfaces:
* Tell me so[Digital Communication](https://learn.sparkfun.com/tutorials/serial-communication/all): [Serial / UART](https://www.arduino.cc/en/reference/serial), [SPI](https://www.arduino.cc/en/Reference/SPI), [I2C](https://www.arduino.cc/en/reference/wire) :warning: *We will always use an specific sensor library implementing the comunication*
:::info
We have a (really long) [**Sensor & Actuator list**](https://hackmd.io/xAjS5n_ASTOmX9EhacRRhw?both#Sensor-list) that need some work and updates, but still works as reference.
:::
## Actuators
## Hands on
![](https://upload.wikimedia.org/wikipedia/commons/thumb/4/4e/Morsetaste.jpg/1920px-Morsetaste.jpg)
As an excercise let's try to use a sensor and and actuator to comunicate, this will also start the discussion on networking and communication.
As explained above, we can use a simple [Light Dependant Resistor](https://en.wikipedia.org/wiki/Photoresistor) (LDR) to know the light level of the enviroment, or the area we point our LDR. If we pair our LDR with a LED it's easy to know if the led is ON or OFF, that's an optical [Telegraph](https://en.wikipedia.org/wiki/Telegraphy). As a first test we can use [morse code](https://en.wikipedia.org/wiki/Morse_code) to transmith data from the LED side to the LDR side.
![](https://i.imgur.com/pQ7GAxG.png)
### Reading light
The first step is to be able to read light levels, you can find a lot of information about LDR's on this [Adafruit guide](https://learn.adafruit.com/photocells/overview).
![](https://www.circuitgeeks.com/wp-content/uploads/2022/01/Arduino-LDR-Circuit.png?x29164 =300x) ![](https://i.imgur.com/gq2jbiN.png =300x)
Once you have everything connected you should be able to **read light levels in realtime**, now it's time to setup the transmitter with a light actuator (fancy naming for a LED).
### Actuating light
To build a **manual morse code transmitter** you can connect a button and a led and via code turn on/off the led based on button input, doing it this way you can also control the led in an automated way and transmit faster and more complex data packages.
![](https://i.imgur.com/XCjmglP.png)
### Going further...
Now the real challenge:
1. Write some code to **detect short and long pulses**
2. Think of a way to **separate groups of pulses** (maybe a long pause?) to be able to **detect letters** based on morse code table.
3. **Storing every group of pulses** on an arduino [String](https://www.arduino.cc/reference/en/language/variables/data-types/string/) variable, in the form of dots and dashes '.--.' could be an option...
4. **Translate the pulses into real letters comparing** the captured data with the ones on the morse code table (tip: the [switch case...](https://www.arduino.cc/reference/en/language/structure/control-structure/switchcase/) statement can help).
5. Now just Serial.print() the letter you have detected!!
After this, if there is still time, you can try to automatize the led side and have a complete automatic morse code transmitter/receiver.