# Photoresistors

![breadboard](breadboard.png)

This project uses a photoresistor feeding into the ADC and an LED fed with PWM to create a nightlight that gets brighter as the ambient light gets darker.

# Lessons Learned

The code in this lesson is unremarkable; the lessons here were primarily in correcting some fundamental misunderstandings in my basic electronics knowledge.

- Resistors in a circuit don't work the way I thought they did
- How a voltage divider actually works and why we might use one
- How a photoresistor actually works under the hood

# Resistors

Resistors, if you don't know, are a device that goes inside of a circuit to (surprise) provide a resistance to the electrical current in the circuit. The common practical application is to reduce the voltage in the circuit.

I always thought resistors worked much like a hose reducer. Say you have a 2" hose with a 1 gallon per minute of water flowing through it. Now you reduce that hose to 1" with a 2" to 1" adapter. The orifice is physically 50% smaller so now you can only fit 50% as much matter through it in a given period of time. Electronics tutorials often use streams of water as an analogy for electrical current, and this makes easy sense.

![voltage divider](voltagedivider.png)

So when I looked at the circuit diagram, I wondered, "why are we measuring the voltage on the circuit UPSTREAM from the photoresistor?" Wouldn't it stand to reason that you would witness the impact of the resistor *downstream* of the resistor? For example it doesn't make sense to measure the impact of a `2" -> 1"` hose reducer on the `2"` side, right?

The answer is because, as it turns out, if you take the measurement downstream of the photoresistor in this particular example, you will always read 0v. You will never see a change in the output voltage from the photoresistor. In order to see the impact of the photoresistor in the circuit, you need to measure upstream of the photoresistor.

<center><img alt="wot" width="320" src="wot.jpeg"/></center>

## "Downstream" doesn't work how you think

For an actual electrical engineer, or someone with a better grasp of electronics fundamentals, this may be a real "DUH-HUH" moment. So forgive me as I shake the blinders from my eyes. 

The water analogy from many simpler electronics tutorials lead me to use words like "upstream" and "downstream", but those terms are a bit misleading. Yes current flows, and it flows like water, but an electrical circuit is not actually like a river or a water hose. When a river flows around a sharp bend in topography, the bend reduces the flow of the river because the floor of the riverbed and the earth on the riverbank introduce friction against the water and reduce its velocity. Once the water flows past this bend, it may be completely straight and fully unimpeded until it reaches its eventual destination in the ocean. There are two interesting questions here.

1. At what point downstream from that bend does the river become the ocean? Or, for our circuits, at what point does the circuit cease to be supply voltage and become ground reference voltage?

At some point after the bend in the river, the river will eventually reach the ocean. The ocean and the river are made up of different types of water. The river is fresh water; the ocean is salt water. There is an interface between the two at which point the water is neither river nor ocean, it is some mix of both. You go just a little upstream from that interface, it is the freshwater river. You go a little more downstream, it is the saltwater ocean. Electrical circuits do not behave this way. For an electrical circuit, it would be more like, as soon as the topography of the bend is complete, the freshwater river immediately ceases to be detectable and it is instantly the ocean. Even if the real body of the ocean is hundreds of miles away, at the instant where the pathway leaves the topographical bend connected to the upstream freshwater source, it becomes the river. This is because, in an electrical circuit, the concept of the hundreds of miles of riverbed between the bend and the ocean are irrelevant; the only thing that matters is the potential difference between point connection points. As soon as the downstream leg of our resistor R1 becomes attached to the rest of the circuit that eventally leads (unimpeded by another components) to ground, that downstream leg of R1 **becomes ground itself**.

The water analogy further breaks down here when we begin thinking about current. In the river analogy, even when the river meets the ocean, there is still current. The ocean is constantly moving. So the individual water molecules never stop moving. Rivers flow because of gravity; you call the difference in altitude between a river's origin and its exit to the sea as the *potential difference*. Because of the external force of gravity, the river flows down the terrain towards lower elevations, until it eventually reaches sea level. At that point, there is no longer a *potential difference* in the river's trajectory, if there were no more external forces acting on the water, it would have no more reason to flow. There would be no current. (Let us exclude for a moment the idea of all the various forces that can act upon a still body of water to induce currents in an otherwise level body of water at sea level). 

Circuits behave similarly to the river in the analogy, but not exactly, because they don't have the same external forces working on them in the same way. Current only flows in an electrical circuit because there is a potential difference between one end of the circuit and the other. There is a positive and a negative; a source and a return; a supply and a ground. The difference in charge between these two points is expressed as a *potential difference*, otherwise known as a *voltage*. This difference in charge between two points is what causes current to flow, like the elevation difference in the river analogy. Whenever a circuit has no potential difference - meaning that the voltage between point A and point B is essentially 0 volts - there is no current flow. The water is perfectly still. And this brings us to the second interesting question.

2. At what point downstream from that bend can you no longer detect the impact of the bend on the velocity of the water? Or, for our circuits, at what point does the voltage change from the resistance of the bend become undetectable?

At a certain point downstream from the bend in the river, assuming that all other forces acting on the water in the river (such as gravity and the rate of change in elevation over distance) remain constant, the impact of the bend will no longer be detectable on the velocity of the water in the river. The water will behave like any other falling object and will, given enough time, reach a point where the force of gravity and the friction drag of the riverbed equalizes, and the water reaches a terminal velocity. It may take a few feet or a few miles past the riverbend for this to occur but, all things being equal, it will occur. Circuits don't behave this way. In the circuit, where a resistor takes the place of the river bend, instead of applying a momentary friction to a moving object, applies a constant resistance to the current through its body. As soon as the current exits the other side of the river bend (the resistor), the resistance is no longer being applied. The only thing that can be measured on the downstream side of the river bend (the resistor) is the difference between the river bend and the sea. In order to detect the effect of the resistor, you actually have to examine the change in the water *as it is entering the riverbend from upstream*.

## Far out, man

<center><img alt="okay, so..." src="stirring-what.gif"/></center>

Okay, hear me out. Let's abandon our current breadboard project for a moment, and imagine a theoretical circuit powered by 5 volts (instead of the 3.3v being used in our ESP32 here) because the math with 5v is simpler. Consider this circuit, wired up on a breadboard:

```
+5V --> 10k Resistor --> Wire --> GND
```

Our intuition here might say that, on a 5v current, a 10k resistor should give us an output of about 2.5v, right? Right, it's not a perfect assumption, but let's go with that. 

* Put your voltmeter red probe on the +5V rail side of the resistor, and the black probe on GND. You will see 5v.
* Put your voltmeter red probe on the downstream side of the resistor, away from the +5V rail. Put your black probe on GND. What do you think you will see? 2.5v? No. You will see 0v.

The downstream side of the resistor is physically attached to ground. Even though there are wires and breadboard ports between that leg of the resistor and "ground", it is physically attached to ground, and it is therefore ground. The river has met with the ocean at that point. There is no longer a potential difference between the river and the ocean, regardless of the space in between, so there is no current. The current does not have to flow from the downstream leg of the resistor to the ground port of the breadboard to reach ground. It is already at ground as soon as it reaches the downstream leg.

The 2.5v measurement we are looking for, if we could find it, is being released through the resistor material as heat.. The resistor, being the bend in the river that applies friction to the current, does theoretically progressively limit the voltage, but only to the portion that has current moving through it. And like physical mechanical friction, the resistance produces heat, which is where the voltage goes as it drops. There is some point inside the physical body of the resistor at which point the voltage is 2.5v if you could measure it, but it is somewhere in that process of converting current to heat. Since the downstream side is connected directly to ground, current only flows until it reaches the point of connection to ground at which point the potential difference drops to zero, and current no longer flows. So if you want to find the 2.5v, you need to put something else between that resistor and ground, and it can't just be a wire. It needs to be something else that presents a potential difference above ground.

## A voltage divider is the answer

If you remember back to [tutorial 4 with Analog Digital Conversion](../04-adc/README.md#measuring-potentiometers), I talked about potentiometers, and how they are a `voltage divider`.

> Potentiometers are adjustable resistors (just like a rheostat), but with 3 pins, they're acting as two resistors in series like a voltage divider.

I used the term voltage divider there not because I actually understood what it was doing, but because that was part of the terminology used in the material I used to better understand potentiometers. And while I understand the moving the wiper changed the resistance on the output tap, and I understood that this could be described as a voltage divider, I didn't really understand what a voltage divider was, what it does, and why it does it.

A voltage divider does exactly what it says: it creates a point in the circuit at which the available voltage is equal to some portion of the input voltage, produced by dividing the input voltage across a couple of points of resistance. Note that it needs *a couple* of points of resistance, not *a single point*. We have already covered what hapens if you only have a single point of resistance in a circuit. Let's revisit the simple circuit from above, and revise it a bit:

```
+5V --> 10k Resistor --> Bare Wire --> 10k Resistor --> GND
           (R1)            (Tap)          (R2)
```

Now take your voltmeter and put the black probe on ground. Put the red probe on the wire between the two 10k resistors. What do you read? 2.5 volts!

Because the 2 10k resistors are wired in series, there is a potential difference between the upstream (supply) leg of R1 to the upstream (supply) of R2. The total potential difference measured across the entire circuit remains constant - tapping the supply side of R1 and the ground side of R2 would show a total 5v difference. Since R1 is no longer physically connected directly to ground and instead leads to another component, current continues to flow past R1 towards R2 downstream. This allows us to place a tap (the bare wire) in between R1 and R2, where we can detect voltage (being the potential difference between this point and ground). And by placing another 10k resistor in as R2, we can detect the potential difference between the tap (at the junction between R1 and R2) and the GND. And because R2 is a 10k resistor, we get a reading of 2.5v.

$$ Vout = Vin * \frac{R2}{R1 + R2} $$

The voltage reading of any given voltage divider is going to be equal to the input voltage times (the value of the bottom resistor divided by the sum of both resistors). So in our case:

$$ Vout = 5 * \frac{10k}{10k + 10k} $$

... Or `Vout = 2.5v`. For fun, stick different value resistors in the R1 and R2 place. Probe it, and see how the value at the tap changes. And THAT is why potentiometers act like a voltage divider - because by turning the dial, you can change the sweep of the wiper, which changes the size of the resistive material on both sides of the wiper, which changes the resistance value of the material on both sides of the wiper, changing the resistance values of the two sides of the potentiometer!

This is also why the tutorial circuit is wired up the way it is. Because it's using a 10k resistor as the first half, and the photoresistor, as the second half, of a voltage divider. As the photoresistor reacts to light, the resistance value of the photoresistor changes, which changes the R2 value in the voltage divider, which varies the value being shown on the tap at the GPIO pin which is processed by the ADC on the ESP32.

# Photoresistors

Normal resistors are fixed devices. They are made of a given material that provides a fixed resistance based on the properties of the material.

Photoresistors (or **LDR**s, **Light Dependent Resistors**) are different. They provide different resistance values depending on the amount of light being applied to them. Unlike potentiometers, they don't have mechanical action and don't act like voltage dividers. Instead, photoresistors are made of a semicoductor material (such as cadmium sulfide) that is sandwiched between a conductor and an insulator.

Semiconductors, unlike solid conductors like a copper wire, don't always have free electrons available to carry current. They are usually bound up. When a LDR semiconductor is struck by a photon from a beam of light (or the ambient photons bouncing around my lab area), those electrons absorb energy from the photons, becoming a free electron, which contributes to the material's ability to conduct current. The more photons strike an LDR, the more free electrons it has, therefore the more current it can handle, therefore the less resistance it offers. Conversely, when it is in darkness, there are less photons, therefore the electrons become dormant again, leading to poor conductivity, and higher resistance.

So when we hook the photoresistor to pin 1 on our ESP32 to measure it through the ADC, what we're trying to do is get a measure of how much resistance is currentl being offered by the photoresistor. We want to know how much light is exposed to it, and that can only be measured by measuring the resistance it provides. But the ESP32 can't measure resistance, it can only measure voltage. Hence why we rig the photoresistor up into a voltage divider, and hook it to the ADC pin. With the photoresistor as the bottom leg of the voltage divider, and a constant value on the other half, we can tap the center of the voltage divider and know that any change in the voltage value there is due to a change in the amount of light hitting the photoresistor. 
