---
jupytext:
  text_representation:
    extension: .md
    format_name: myst
    format_version: 0.13
    jupytext_version: 1.17.1
kernelspec:
  display_name: Python 3
  language: python
  name: python3
---

```{code-cell} python3
:tags: [thebe-remove-input-init, auto-execute-page]

%pip install ipympl==0.9.3
```

```{code-cell} python3
:tags: [thebe-remove-input-init]

import matplotlib
if not hasattr(matplotlib.RcParams, "_get"):
    matplotlib.RcParams._get = dict.get

import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
from ipywidgets import interact, FloatSlider, FloatLogSlider

%matplotlib inline
%config InlineBackend.figure_formats = ['svg']
```

# Microcontrollers, logics and code
This chapter is about microcontrollers, like an Arduino or Raspberry Pi Pico. In a learning platform such as [ALPACA, an Advanced Learning Platform for Analog Circuits and Automation](https://research.tudelft.nl/en/publications/the-advanced-learning-platform-for-analog-circuits-and-automation) these microcontrollers are used for producing and acquiring signals, without the need for an oscilloscope, multimeter or function generator. We will also discuss the relation between analog and digital signals

## Sampling (Physics theory)
Sampling can happen both in the amplitude, and in the time domain. In this section we look at different data types, and sampling. 

### Digital Signal types
Analog electronics work with voltages, digital logic work with 0-1. But there are other signal types as well. 

#### False-True
Building on the logical signals, the digital 0 corresponds to False, and the digital 1 corresponds to True. 

#### Counting: Binary-hexadecimal
We count in a decimal, base-10, system. That means that as soon as a digit hits 10, the next digit is increased. 

```{prf:example} Decimal Counting
:label: Decimal_Counting
1234 = 1000+200+30+4  <br>
1234 = 1 $\cdot$ 1000 + 2$\cdot$ 100 + 3$\cdot$ 10 + 4$\cdot$ 1  <br>
1234 = 1 $\cdot$ 10^3 + 2$\cdot$ 10^2 + 3$\cdot$ 10^1 + 4$\cdot$ 10^0
```

In the Western world we are used to this decimal base-10 counting, since we have ten numbers: 0 to 9. 

For a computer that uses false-true or 0-1 values, base-2 would make more sense. In such a binary number with only 0&1 values (or bits), the left bit is most significant, so corresponds to the highest order. The right bit is the least significant, so 2^0 = 1.

An inside joke: "there are 10 types of people understanding binary codes, they either understand or do not". 

```{prf:example} Binary Counting
:label: Binary_Counting
decimal 1234 = 1000+200+30+4

In order to transfer it to binary counting you subtract powers of 2, starting with the highest one  <br>
1234 = 1024 + 128+64+16+2 <br>
1234 = 2^10 + 2^7 + 2^6 + 2^4 + 2^1 <br>
decimal (1234) = binary (0100 1101 0010)
```

To make the binary code more readable, there is a way to condense 4 binary digits into 1 hexadecimal digit. You have the regular 1-10, and then the decimal numbers 10 till 15 are related to hexadecimal A-F

```{prf:example} Binary to Hexadecimal Counting
:label: Hexadecimal_Counting
binary 0000 = decimal 0 = hexadecimal 0 <br>
binary 0001 = decimal 1 = hexadecimal 1 <br>
binary 0010 = decimal 2 = hexadecimal 2 <br>
binary 0011 = decimal 3 = hexadecimal 3 <br>
binary 0100 = decimal 4 = hexadecimal 4 <br>
binary 0101 = decimal 5 = hexadecimal 5 <br>
binary 0110 = decimal 6 = hexadecimal 6 <br>
binary 0111 = decimal 7 = hexadecimal 7 <br>
binary 1000 = decimal 8 = hexadecimal 8 <br>
binary 1001 = decimal 9 = hexadecimal 9 <br>
binary 1010 = decimal 10 = hexadecimal A <br>
binary 1011 = decimal 11 = hexadecimal B <br>
binary 1100 = decimal 12 = hexadecimal C <br>
binary 1101 = decimal 13 = hexadecimal D <br>
binary 1110 = decimal 14 = hexadecimal E <br>
binary 1111 = decimal 15 = hexadecimal F
```
#### Data types - Bit resolution
Numbers in computers have different data types, which are linked to their resolution. 

The data types to distinguish are int, uint, and float. Int means integer, which can be signed (int) or unsigned (uint). 
uint 8 means 8 bits are used, so values from 0 up to 2^8-1 = 255 are possible. As one can imagine uint64 reaches higher numbers than uint32. 

```{prf:example} Wrapping around
:label: Wrapping_around
If you have a number defined as uint8, then what is uint(255) + 1? 

Since the bit depth is limited, you cannot get a number > 255.  <br>
And binary 1111 1111 + 0000 0001 = 0000 0000 (since 1 0000 0000 is not possible)
```

For a signed integer, the minimal value is $- 2^{nbit-1}$ and the maximum value is $2 ^{nbit-1} -1$. For example int16 scales from -32768 to 32767. 

Not only integer values are required, also values smaller than 1 should be represented. Then the data type will be float, either single or double precision. 

for a single: 1 bit is used for the sign, 8 for the exponent, and 23 for the fraction. This results in values between 1.4E-45 to 3.4E+38. Note this notation: 1.4E-45 = 1.4 $\cdot 10^-{45}$.

for a double: 1 bit is used for the sign, 11 for the exponent, and 52 for the fraction.  This results in values between 4.9E-324 to 1.8E+308,

#### Words: ASCII
If computers work with binary code, then how are characters represented? 
Those are represented in ASCII code, which stands for American Standard Code for Information Interchange. This is true for regular characters, capitals or not, but also for the special characters. 

For example: 
ASCII 48 = character 0 <br>
ASCII 65 = character A <br>
ASCII 97 = character a <br>
ASCII 130 = character é

This allows one to program a [Caesar cipher and decipher](https://en.wikipedia.org/wiki/Caesar_cipher).

```{figure} images/images_12/in_book/Caesar_cipher_left_shift_of_3.svg
:name: fig:12_Ceasar_cipher
:width: 600px
In Caesar's ciphering all characters are shifted over a known number of characters. In this example there is a shift of 3, D becomes A. <br>
Created by Matt_crypto, in public domain, [original link](https://commons.wikimedia.org/wiki/File:Caesar_cipher_left_shift_of_3.svg)
```

### Analog versus digital signals (discretization in amplitude)
As soon as values are recorded, they are digitized. The display of an oscilloscope might seem analog, but it is actually 12 (or 8) bit. That means that the resolution, the smallest measurable step for 12 bit with 1V/div display is:

$$
\frac {8 div \cdot 1V/div }{2^{12}}= 2 mV
$$

The discretization error is given by the difference between the actual value and the discretizated value. 

```{prf:example} Discretization Error
:label: Discretization_Error
Discretization can be seen as rounding a number to a certain minimal stepsize. For example a minimal stepsize (resolution) of 0.1. 
Then the discretization error of 3.22 is: 3.22-3.2 = 0.02. 

The max discretization step is equal to half of the resolution. 
```

As a side effect of the resolution, one might not able to find an answer to a comparison. If the resolution is 2 mV, then are you ever going to find the measured signal equal to for example 2.413 V?

Also circuits like a differentiator will be influenced by discretization: differentiating a stepwise signal will result in only spikes at a step. This in contrast to a gradual increase resulting in a steady signal. 

The way how to go from analog to digital values and vice versa is explained in a later section on ADC/ DAC. 

```{figure} images/images_12/in_book/challenges_of_discretization.svg
:name: fig:challenges_of_discretization
:width: 600px
Challenges in discretization. A) the threshold value will never be reached due to discretization. B) Although analog and discrete signals are comparable, the differential signal will be different. 
```

### Aliasing (sampling in time)
The alternating voltage from you wall outlets is an analogue signal. We can think of it as a sine wave with a frequency of 50 Hz and a $V_{RMS}$ of 230 V. 

<!--
```{figure} images/images_12/in_book/PyDAQ6-fig1.png
Sine with frequency 50 Hz and $V_{RMS}$ of 230 V (amplitude 325 V). Note: never measure such high voltage directly, always use an attenuating probe. 
```
-->

:::{figure-start} images/nothing.svg
:name: fig:sine_frequency_fig1
:alt: Nothing
:align: center
Sine with frequency 50 Hz and $V_{RMS}$ of 230 V (amplitude 325 V). Note: never measure such high voltage directly, always use an attenuating probe. 
:::

```{code-cell} python3
:tags: [hide-input, thebe-init]

import numpy as np
import matplotlib.pyplot as plt

# Signal parameters
V_rms = 230          # RMS voltage [V]
f = 50               # frequency [Hz]

# Convert RMS voltage to peak voltage
V_peak = np.sqrt(2) * V_rms

# Time axis: 0 to 0.1 s
t = np.linspace(0, 0.1, 1000)

# AC voltage
v = V_peak * np.sin(2 * np.pi * f * t)

# Plot
fig, ax = plt.subplots(figsize=(9, 4.5))

ax.plot(t, v, linewidth=2)

ax.set_xlabel("Time (s)")
ax.set_ylabel("Amplitude (V)")

ax.set_xlim(0, 0.1)
ax.set_ylim(-350, 350)

ax.grid(True, alpha=0.5)

plt.tight_layout()
plt.show()
```

:::{figure-end}
:::

If we want to grasp this analogue signal in a digital environment, we will need to convert it. To do so, we measure the voltage at many timepoints with a fixed interval. Such a measurement is called a 'sample'. The sampling frequency (or sampling rate) is the frequency of these measurements. In the following image, we used a sampling frequency of 260 Hz. Since the analogue signal is 50 Hz, we have approximately five samples per period.

<!--
```{figure} images/images_12/in_book/PyDAQ6-fig2.png
Sine with frequency 50 Hz, sampled at 260 Hz
```
-->

:::{figure-start} images/nothing.svg
:name: fig:sine_frequency_fig2
:alt: Nothing
:align: center
Sine with frequency 50 Hz, sampled at 260 Hz.
:::

```{code-cell} python3
:tags: [hide-input, thebe-init]

import numpy as np
import matplotlib.pyplot as plt

# -----------------------------
# Signal parameters
# -----------------------------
V_rms = 230          # RMS voltage [V]
f_signal = 50        # analogue signal frequency [Hz]
f_sample = 260       # sampling frequency [Hz]

# Peak voltage
V_peak = np.sqrt(2) * V_rms

# -----------------------------
# Continuous analogue signal
# -----------------------------
t = np.linspace(0, 0.1, 2000)
v = V_peak * np.sin(2 * np.pi * f_signal * t)

# -----------------------------
# Sampling points
# -----------------------------
T_sample = 1 / f_sample

t_sample = np.arange(
    0,
    0.1 + T_sample,
    T_sample
)

# Keep only samples within 0.1 s
t_sample = t_sample[t_sample <= 0.1]

v_sample = V_peak * np.sin(
    2 * np.pi * f_signal * t_sample
)

# -----------------------------
# Plot
# -----------------------------
fig, ax = plt.subplots(figsize=(9, 4.8))

# Original analogue signal
ax.plot(
    t,
    v,
    linestyle=":",
    linewidth=2,
    alpha=0.35
)

# Sampled signal
markerline, stemlines, baseline = ax.stem(
    t_sample,
    v_sample
)

# Style the samples
plt.setp(
    stemlines,
    linestyle="--",
    linewidth=2,
    alpha=0.7
)

plt.setp(
    markerline,
    marker="x",
    markersize=7,
    markeredgewidth=2
)

# Hide stem baseline
baseline.set_visible(False)

# -----------------------------
# Axes
# -----------------------------
ax.set_xlabel("Time (s)")
ax.set_ylabel("Amplitude (V)")

ax.set_xlim(0, 0.1)
ax.set_ylim(-350, 350)

ax.set_xticks(np.arange(0, 0.101, 0.02))
ax.set_yticks(np.arange(-300, 301, 100))

ax.grid(True, alpha=0.5)

plt.tight_layout()
plt.show()
```

:::{figure-end}
:::

If we let the computer connect all these samples, we retrieve a signal that looks reasonably similar to the original signal. This is called reconstruction. Good reconstruction is only possible if the sampling frequency is high enough.

<!--
```{figure} images/images_12/in_book/PyDAQ6-fig3.png
Sine with frequency 50 Hz, sampled at 260 Hz, and reconstructed
```
-->

:::{figure-start} images/nothing.svg
:name: fig:sine_frequency_fig3
:alt: Nothing
:align: center
Sine with frequency 50 Hz, sampled at 260 Hz, and reconstructed
:::

```{code-cell} python3
:tags: [hide-input, thebe-init]

import numpy as np
import matplotlib.pyplot as plt

# -----------------------------
# Signal parameters
# -----------------------------
V_rms = 230          # RMS voltage [V]
f_signal = 50        # analogue signal frequency [Hz]
f_sample = 260       # sampling frequency [Hz]

# Peak voltage
V_peak = np.sqrt(2) * V_rms

# -----------------------------
# Original analogue signal
# -----------------------------
t = np.linspace(0, 0.1, 2000)

v = V_peak * np.sin(
    2 * np.pi * f_signal * t
)

# -----------------------------
# Sampling points
# -----------------------------
T_sample = 1 / f_sample

t_sample = np.arange(
    0,
    0.1 + T_sample,
    T_sample
)

# Keep samples within the plotting range
t_sample = t_sample[t_sample <= 0.1]

v_sample = V_peak * np.sin(
    2 * np.pi * f_signal * t_sample
)

# -----------------------------
# Plot
# -----------------------------
fig, ax = plt.subplots(figsize=(9, 4.8))

# Original continuous signal
ax.plot(
    t,
    v,
    linestyle=":",
    linewidth=2,
    alpha=0.30,
    label="Original signal"
)

# Sampling stems
markerline, stemlines, baseline = ax.stem(
    t_sample,
    v_sample
)

plt.setp(
    stemlines,
    linestyle="--",
    linewidth=2,
    color="tab:green",
    alpha=0.7
)

# We draw the markers with the reconstruction below,
# so hide the default stem markers
markerline.set_visible(False)
baseline.set_visible(False)

# -----------------------------
# Reconstructed signal
# Connect consecutive samples
# -----------------------------
ax.plot(
    t_sample,
    v_sample,
    color="tab:blue",
    marker="x",
    markersize=7,
    markeredgewidth=2,
    linewidth=2,
    label="Reconstructed signal"
)

# -----------------------------
# Axes
# -----------------------------
ax.set_xlabel("Time (s)")
ax.set_ylabel("Amplitude (V)")

ax.set_xlim(0, 0.1)
ax.set_ylim(-350, 350)

ax.set_xticks(np.arange(0, 0.101, 0.02))
ax.set_yticks(np.arange(-300, 301, 100))

ax.grid(True, alpha=0.5)

plt.tight_layout()
plt.show()
```

:::{figure-end}
:::

But what happens if there are not enough samples per period? And what is the minimal number of samples per period? 

If there are not enough samples per period, you encounter aliasing. This is very well visible in the wagon-wheel effect: in movies of a moving car, you see at some speed that the car still move forward but the wheels seem to spin backwards. This is because the motion of the wheel is too fast to be still captured correctly on film. 

Aliasing occurs at less than two samples per period. 
Or phrase it from the frequency perspective: aliasing occurs when signal frequencies are above Nyquist frequency $f_N$, which is half of the sample rate $f_{sample}$. 

$$
f_N = \frac{f_{sample}}{2}
$$ (Nyquist)

Then depending on the relation of the speed versus the sampling rate the amplitude of a sample can be anywhere between 0 and the amplitude of the input signal. Triggering, meaning when to start the measurement, can be of influence of the measured amplitude. But also the direction or phase can be positive or negative. One thing for sure, the measured frequency will not be equal to the input frequency. 

```{figure} images/images_12/in_book/WagonWheelEffect.gif
:name: fig:WagonWheelEffect
:width: 100px
The velocity of the camera, moving towards the right, constantly increases at the same rate (while to the camera, the objects appear sliding to the left). Halfway through the 24-second loop, the objects appear to suddenly shift and head in the reverse direction, towards the right. <br>
Created by Ulillillia, under CC BY-SA 3.0, [original link](https://en.wikipedia.org/wiki/File:WagonWheelEffect.gif)
```

#### Sampling from the mathematical viewpoint
Another way of looking at discretization is seeing it as the multiplication of the original continuous signal with a Dirac comb, which is given by the following pulse train with time $T$ between two samples:

$$
\sum_{k=-\infty}^{\infty} \delta(t - kT)
$$

Multiplication in the time domain means a convolution in the frequency domain. The Fourier transform of a Dirac comb is also a Dirac comb, with the periodicity of $ \frac{N}{T}  $. 

```{prf:example} Sampling a Sine
:label: sampling-sine
The Fourier transform of the single-frequency sine wave $sin(2 \pi f_{in}t)$ gives an amplitude at $\pm f$.
If this sine is sampled with period $T_{sample}$ with corresponding frequency $f_{sample}$, peaks in the Fourier transform of the sampled sine occur at $N f_{in} \pm f_{sample}$. 

But then it is no longer clear from the resulting frequency plot whether you measure a signal with $f = f_{in}$ or $f = 2 f_{sample} + f_{in}$. 
```
After sampling, each band with frequencies around $ N f_{sample}$ is identical, and therefore no longer distinguishable. Only for signal input frequencies between $\pm f_{sample}/2 $, the measured frequency is identical to the input frequency. For input frequencies outside the Nyquist frequency $\pm f_{sample}/2 $, the measured frequency is lower than the input frequency. 

```{figure} images/images_12/in_book/Bandpass_sampling_depiction.svg
:name: fig:band_sampling
:width: 600px
Two signals B (green, top line) and A (blue, 2nd line) are measured with a sampling rate $f_s = A/3$. The Fourier transforms of both sampled figures are identical. Sampling is the cause, aliasing is the result. <br>
Created by Bob K, under CC0, [original link](https://en.wikipedia.org/wiki/Sampling_(signal_processing)#/media/File:Bandpass_sampling_depiction.svg)
```

#### Calculating with Aliasing
In the previous paragraph you already saw that due to sampling frequencies are measured as $f = 2 f_{sample} + f_{in}$. 
Therefore, one way of calculating the measured frequency (often looking at frequencies between 0 and $f_{sample}/2$) is to subtract as many times $f_{sample}$ and when close to f=0, take the absolute value of the frequency. The last (absolute value) step is because often only the positive part of the spectrum is displayed. 

There is a more rule-of-thumb approach: mirroring input frequencies in $N f_{Nyquist}$, where $N f_{Nyquist} < f_{input}$.
- If you 'mirror' $+f_A$ in f=0, it becomes $-f_A$. 
- If you mirror $f_N + f_A$ in f=$f_N$, it becomes $f_N-f_A$. 
- If the frequencies are higher, it might be you need to mirror multiple times: alternating between mirroring around $f_N$ (for f>$f_N$) and 0 (for f<0) can be repeated indefinitely.



```{prf:example} Sampling for input frequency between $f_N$ and $f_s$
:label: aliasing_once
mathematical approach: 
if $f_{in}$ =2500 Hz and $f_{N}$= 2400 Hz, then $f_{meas}$ = |2500-2*2400 Hz| = |-2300 Hz|= 2300 Hz


mirroring approach:
if $f_{in}$ =2500 Hz and $f_{N}$= 2400 Hz, then $f_{meas}$= 2400 Hz - (2500-2400)Hz = 2300 Hz. 
```

```{prf:example} Sampling for input frequency above $f_s$
:label: aliasing_twice
Look at $f_{sample}$=4800 Hz and $f_{in}$=5300 Hz. 

mathematical approach: 
$f_{meas}$ = 5300-4800 Hz = 500 Hz

mirroring approach:
Firstly, the 5300 Hz 'mirrors' around $f_N$ (of 2400 Hz), and it will land on -500 kHz: 2400 - (5300-2400) = 2400 +2400 - 5300 = 4800-5300 =-500 Hz. 
The next step is to mirror it back around the origin, so make it absolute: 500 Hz. Since this is between 0 Hz and the Nyquist frequency, 500 Hz is the frequency that will be measured. 
```

Both approaches are correct, the mathematical approach being a bit more universal, effective and less error prone. 

<!--
```{figure} images/images_12/in_book/PyDAQ6-aliasing-explanation-1-b.png
:name: fig:mirrored_twice
If you use the mirroring approach, the sign flips at every mirroring. First in $f_N$, then in f=0. 

```
-->

:::{figure-start} images/nothing.svg
:name: fig:mirrored_twice
:alt: Nothing
:align: center
If you use the mirroring approach, the sign flips at every mirroring. First in $f_N$, then in f=0.
:::

```{code-cell} python3
:tags: [hide-input, thebe-init]

import numpy as np
import matplotlib.pyplot as plt

# --------------------------------------------------
# Frequencies
# --------------------------------------------------
f_nyquist = 2.4       # kHz
f_sample = 2 * f_nyquist
f_original = 5.3      # kHz

# First reflection around Nyquist
f_mirror = 2 * f_nyquist - f_original # this is derived from f_n + (f_ori-f_n) mirroring to f_n -(f_ori-f_n)

# Reflection around zero gives observed alias
f_alias = abs(f_mirror)

# --------------------------------------------------
# Create schematic FFT around alias frequency
# --------------------------------------------------
f = np.linspace(0, f_nyquist, 400)

# Narrow peak to visually represent the FFT
sigma = 0.035
fft_amp = np.exp(
    -0.5 * ((f - f_alias) / sigma) ** 2
)

# --------------------------------------------------
# Plot
# --------------------------------------------------
fig, ax = plt.subplots(figsize=(10, 5))

# FFT peak
ax.plot(
    f,
    fft_amp,
    color="tab:blue",
    linewidth=2,
    label="FFT"
)

ax.plot(
    f_alias,
    1,
    marker="X",
    color="tab:blue",
    markersize=8
)

# Nyquist frequency
ax.axvline(
    f_nyquist,
    color="tab:orange",
    linewidth=2,
    label="Nyquist frequency"
)

# --------------------------------------------------
# Important frequency locations
# --------------------------------------------------

# First mirrored position
ax.vlines(
    f_mirror,
    0,
    1,
    colors="gray",
    linestyles="--",
    linewidth=2
)

ax.plot(
    f_mirror,
    1,
    marker="X",
    color="gray",
    markersize=7
)

# Aliased frequency
ax.vlines(
    f_alias,
    0,
    1,
    colors="gray",
    linestyles="--",
    linewidth=1.5,
    alpha=0.7
)

# Original frequency
ax.vlines(
    f_original,
    0,
    1,
    colors="gray",
    linestyles="--",
    linewidth=2
)

ax.plot(
    f_original,
    1,
    marker="X",
    color="gray",
    markersize=7
)

# --------------------------------------------------
# Labels
# --------------------------------------------------
ax.text(
    f_original,
    1.10,
    "original\nfrequency",
    ha="center",
    va="bottom",
    color="red"
)

ax.text(
    f_alias,
    1.10,
    "",
    ha="center",
    va="bottom"
)

ax.text(
    f_nyquist + 0.08,
    0.55,
    r"$f_N$",
    rotation=90,
    va="center"
)

# --------------------------------------------------
# Reflection arrows
# --------------------------------------------------

# Original frequency -> reflection around Nyquist
ax.annotate(
    "",
    xy=(f_mirror, -0.20),
    xytext=(f_original, -0.20),
    arrowprops=dict(
        arrowstyle="->",
        linewidth=3,
        connectionstyle="arc3,rad=-0.35",
        color="red"
    ),
    annotation_clip=False
)

ax.text(
    (f_original + f_mirror) / 2,
    -0.28,
    "Flipping around the Nyquist frequency",
    ha="center",
    va="top"
)

# Negative frequency -> positive frequency
ax.annotate(
    "",
    xy=(f_alias, 1.02),
    xytext=(f_mirror, 1.02),
    arrowprops=dict(
        arrowstyle="->",
        linewidth=3,
        connectionstyle="arc3,rad=-0.6",
        color="red"
    )
)

ax.text(
    0,
    1.18,
    "Around the origin",
    ha="center"
)

# --------------------------------------------------
# Axes
# --------------------------------------------------
ax.set_xlabel("Frequency (kHz)")
ax.set_ylabel("Amplitude of Fourier coefficient")

ax.set_xlim(-5, 7)
ax.set_ylim(0, 1.1)

ax.grid(True, alpha=0.4)
ax.legend(loc="upper left")

plt.tight_layout()
plt.show()

```

:::{figure-end}
:::

**mind the sign, or mind the phase** <br>
We have not addressed the sign inversion of the measured signal, which flips sign with every 'mirror' action. Therefore the number of flips will tell you whether the aliased signal has a **positive or negative phase** (or phrased differently: whether the signal starts going up or going down at $t=0$, given that the original signal goes up). Every flip will lead to a sign inversion. Two flips, like in the above case, will cancel out, meaning that the aliased signal will have the same phase as the original.


````{prf:example} Aliasing
Study the image below, which concerns a signal frequency of 8.4 kHz sampled with a frequency of 4.8 kHz again. 
* Will the sign of the aliased signal be inverted with respect to the input signal? 

First to do: calculate $f_N$ = 2400 Hz

Mathematical approach: 
- Subtract as many times $f_{sample}$ to get within $\pm f_N$
- 8400 - 2*4800 = -1200 Hz.
- flip the sign, and get to +1200 Hz. 

Mirroring approach (fast): 
- Subtract as many times $f_{sample}$ without flipping the sign: 8400 - 4800 = 3600 Hz.
- Aliase once: 3600 Hz 'mirrored' in 2400 Hz = 2400 - 1200 = 1200 Hz. 
- One mirror action, so sign is flipped

Mirroring approach (slow):
- $f_N$ - $f_{in}$ = 2400 - 8400 = -6000 (mirror once)
- make absolute: 6000 Hz (mirrored twice)
- 2400 -6000 = -3600 (mirrored 3x)
- make absolute: 3600 Hz (mirrored 4x)
- 2400 - 3600 = -1200 Hz (mirrored 5x)
- make absolute: 1200 Hz (mirrored 6x)

Up to you which approach you prefer
````

:::{figure-start} images/nothing.svg
:name: fig:mirrored_more_often
:alt: Nothing
:align: center
If you use the mirroring approach, the sign flips at every mirroring. First in $f_N$, then in f=0, then in $f_N$ again.
:::

```{code-cell} python3
:tags: [hide-input, thebe-init]

import numpy as np
import matplotlib.pyplot as plt

# --------------------------------------------------
# Frequencies (kHz)
# --------------------------------------------------
f_nyquist = 2.4
f_original = 8.4

# Mirroring sequence
f1 = 2 * f_nyquist - f_original   # -3.6 kHz
f2 = -f1                           #  3.6 kHz
f_alias = 2 * f_nyquist - f2      #  1.2 kHz

# --------------------------------------------------
# Schematic FFT peak
# --------------------------------------------------
f = np.linspace(0, f_nyquist, 500)

sigma = 0.04
fft_amp = np.exp(
    -0.5 * ((f - f_alias) / sigma) ** 2
)

# --------------------------------------------------
# Plot
# --------------------------------------------------
fig, ax = plt.subplots(figsize=(11, 5.5))

# Blue FFT curve
ax.plot(
    f,
    fft_amp,
    color="tab:blue",
    linewidth=2.5,
    label="FFT"
)

# Blue dashed line at aliased frequency
ax.vlines(
    f_alias,
    0,
    1,
    colors="tab:blue",
    linestyles="--",
    linewidth=2
)

# Blue marker at FFT peak
ax.plot(
    f_alias,
    1,
    marker="X",
    color="tab:blue",
    markersize=10
)

# --------------------------------------------------
# Nyquist frequency
# --------------------------------------------------
ax.axvline(
    f_nyquist,
    color="tab:orange",
    linewidth=2.5,
    label="Nyquist frequency"
)

# --------------------------------------------------
# Grey dashed mirroring positions
# --------------------------------------------------
mirror_points = [f1, f2, f_original]

for fx in mirror_points:
    ax.vlines(
        fx,
        0,
        1,
        colors="gray",
        linestyles="--",
        linewidth=2
    )

    ax.plot(
        fx,
        1,
        marker="X",
        color="gray",
        markersize=9
    )

# --------------------------------------------------
# Red arrows showing mirroring
# --------------------------------------------------
arrow_kw = dict(
    arrowstyle="->",
    color="red",
    linewidth=5,
    mutation_scale=18
)

# Original frequency -> first mirror
ax.annotate(
    "",
    xy=(f1, -0.16),
    xytext=(f_original, -0.16),
    arrowprops=arrow_kw,
    annotation_clip=False
)

# First mirror -> second mirror
ax.annotate(
    "",
    xy=(f2, 1.03),
    xytext=(f1, 1.03),
    arrowprops=arrow_kw,
    annotation_clip=False
)

# Second mirror -> final aliased frequency
ax.annotate(
    "",
    xy=(f_alias, -0.02),
    xytext=(f2, -0.02),
    arrowprops=arrow_kw,
    annotation_clip=False
)

# --------------------------------------------------
# Axes
# --------------------------------------------------
ax.set_xlabel("Frequency (kHz)")
ax.set_ylabel("Amplitude of Fourier coefficient")

ax.set_xlim(-7, 12)
ax.set_ylim(0, 1.1)

ax.grid(True, alpha=0.4)
ax.legend(loc="upper left")

plt.tight_layout()
plt.show()
```

:::{figure-end}
:::

<!--
```{figure} images/images_12/in_book/PyDAQ6-aliasing-explanation-3-b.png
:name: fig:mirrored_more_often
If you use the mirroring approach, the sign flips at every mirroring. First in $f_N$, then in f=0, then in $f_N$ again.

```
-->

The overview of $f_{meas}$ depending on $f_{in}$ and $f_{N}$ is as follows:

:::{figure-start} images/nothing.svg
:name: fig:aliasing_freq_phase
:alt: Nothing
:align: center
*interactive plot*: This plot gives an overview of the relation between $f_{measured}$ and $f_{in}$. Also not that aliasing does not only give a difference between measured and input frquency, but also the sign can be opposite.
:::


```{code-cell} python3
:tags: [hide-input, thebe-init]

def calculate_f_aliased (fs, f_in, sample_every_N):
    ff= f_in % fs
    signf=1
    if ff> fs/2: 
        ff=fs-ff
        signf=-1
    degf=0.5*(1+signf)*180
    return ff, signf,  degf

def find_closest(array1, value1):
    diff_array=np.abs(array1-value1)
    return np.where(diff_array==min(diff_array)) [0]
    

def plot_aliasing_sines(fs_scaled=10): #slider for fs
    #plots for two sines, f2 aliased, f1 non aliased
    f1=1
    f2=6.5
    sample_every_N=10
    fs=fs_scaled*sample_every_N
    t_step= 1/fs
    tmax=1
    tt=np.arange(0,tmax, t_step)

    U1= np.sin(2*np.pi*f1*tt)
    U2= np.sin(2*np.pi*f2*tt)
    f_aliased, signf,_= calculate_f_aliased (fs_scaled, f2, sample_every_N)
    # print(f_aliased)
    U3= signf*np.sin(2*np.pi*f_aliased*tt)

    
    fig, axs = plt.subplots(2, 2, figsize=(8, 7), sharey=False)
    ax1, ax2, ax3, ax4 = axs.flatten()

    ax2.plot(tt, U1, 'r')
    ax2.plot(tt[::10], U1[:: sample_every_N], 'r*')
    ax2.set_ylabel('U1 [V]')
    ax2.set_xlabel('time [s]')
    
    ax4.plot(tt, U2, 'b')
    ax4.plot(tt[::10], U2[:: sample_every_N], 'bv')
    ax4.plot(tt, U3, 'g-.')
    ax4.set_ylabel('U2&U3 [V]')
    ax4.set_xlabel('time [s]')
 

    f_in=np.linspace(0,5*fs_scaled,1000)
    f_out=np.zeros(np.shape(f_in))
    f_phase=np.zeros(np.shape(f_in))
    for ii in range(len(f_in)):
        f_out[ii], _,f_phase[ii]= calculate_f_aliased (fs_scaled, f_in[ii], sample_every_N)
    
    f1_index=find_closest(f_in,f1)
    f2_index=find_closest(f_in, f2)
   
    ax1.plot(f_in, f_out,'k')
    ax1.plot(f_in[f1_index], f_out[f1_index],'r*')
    ax1.plot(f_in[f2_index], f_out[f2_index],'bv')
    ax1.set_xlabel('$f_{set}$ [Hz]')
    ax1.set_ylabel('$f_{measured}$ [Hz]')
    
    ax3.plot(f_in, f_phase,'k')
    ax3.plot(f_in[f1_index], f_phase[f1_index],'r*')
    ax3.plot(f_in[f2_index], f_phase[f2_index],'bv')
    ax3.set_xlabel('$f_{set}$ [Hz]')
    ax3.set_ylabel('$phase_{measured}$ [degrees]')

    plt.show()
    

# plot_aliasing_sines(fs_scaled=10, f1=1, f2=23.5)

interact(
    plot_aliasing_sines,
    fs_scaled=FloatSlider(value=10, min=4, max=23.5, step=0.5, description='fsample (Hz)')
)
```

:::{figure-end}
:::



#### Anti-Aliasing 

If you want to prevent aliasing from happening, then remove the higher to-be-aliased frequencies before the acquisition. For this you might know a nice filter to use. 

But think whether you really want to prevent aliasing or not. In speech recording, you do not want to have higher frequency signal parts aliased to lower frequencies. 
But in case of a limited acquisition bandwidth, and recording of a block wave for which higer frequency parts aliase to unoccupied lower frequencies, aliasing might be useful. 

```{figure} images/images_12/in_book/aliased_speech_block.svg
:name: fig:low_pass_rc_filter
:width: 600px
A low-pass RC filter will always help to prevent unwanted frequencies to be aliased upon acquisition. Whether anti-aliasing is required is influenced by the content of the original signal. a) aliased speed signals overlap with the original signal, b) aliased block wave peaks might not overlap with the input block wave.
```

## Electrical principles of microcontrollers
### TTL, 3.3-5 V
TTL stands for transistor-transistor logic. When going from an analog signal to TTL: The "low" voltage level is zero to 0.8 volts, and the "high" voltage level is 2 volts to 5 volts. When producing a TTL signal, than the low voltage generated is 0 V, and the high value is 3.3 or 5 V (depending also on its purpose, and se with which type of microcontroller).

### Pull-up, pull down resistors
Generally, these resistors are in place to define the voltage at an otherwise undefined state, for example when opening a switch. 

Imagine a measurement of an electronic circuit, which contains a switch. There are two options: one wants to measure the input voltage when the switch is open, or when the switch is closed. 

In a circuit, where one measures $U_{in}$ with a switch closed, there will be moments where the switch is open, and the input pin is floating. It would be better to have both states (switch open and closed) defined, instead of having one state floating (=undetermined). Then use a pull down resistor, as in &nbsp;{numref}`fig:pull-down_resistor` . When the switch is open, the input pin of the microcontroller unit (MCU) is connected to ground via the pull down resistor. When the switch is closed, the input pin will be connected to $U_{in}$. 

The opposite will happen with the pull-up resistor scheme &nbsp;{numref}`fig:pull-up_resistor`. The switch closed means one measures 0 V, and with the switch open, the MCU input is at $U_{in}$, assuming the internal resistance of the MCU is much higher than the pull-up resistor. 

<table align="center">
<tr>
<td>

```{figure} images/images_2/in_book/2_pull-down_resistor.svg
---
name: fig:pull-down_resistor
width: 250px
align: center
---
A pull-down resistor pulls the MCU input to ground when the switch is open
```

</td> 
<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
<td>

```{figure} images/images_2/in_book/2_pull-up_resistor.svg
---
name: fig:pull-up_resistor
width: 280px
align: center
---
A pull-up resistor elevates (or pulls up) the MCU input to a high voltage. 
```
</td>
</tr>
</table>


### Logical conunctions
Based on transistors, you can build logical ports. Transistors are then treated as switches, as is also explained in [this transistor as switch video](https://collegerama.tudelft.nl/mediasite/Showcase/public/Presentation/ffecac60ba9c4d3f88be9fbb20b074531d).

Let's first look at the NOT operation, which means that a 0 in gives 1 out, and 1 in gives 0 out. The schematic is given in figure {numref}`fig:transistor_NOT`

```{figure} images/images_12/in_book/transistor_NOT.svg
:name: fig:transistor_NOT
:width: 600px
NOT operator, based on a single transistor and pull-up resistor. <br>
In the IEC graphical notation, the graphic notation for a NOT gate is a box one input, one output, a small circle at the exit, marked with a '1'. The '1' denotes a non-inverting transfer from input to output, and the circle denotes the NOT operation. Together, they denote the output is the inverse of the input. 
```

When combining two transistors in series, one can make an AND gate, which gives an output of 1 only when both inputs are true. 

```{figure} images/images_12/in_book/transistor_AND.svg
:name: fig:transistor_AND
:width: 600px
AND operator, based on a two transistors in series and (pull-up) resistor. <br> The symbol for the AND gate is a squared box with an '&', two inputs and one output which is only true if both inputs are true. 
```
The AND and NOT gate can be combined into a NAND gate, which output is high except when both inputs (A&B) are high. 

The OR operator requires two transistors in parallel, or can be build from combining one AND and a few NOT operations. OR means that the output is 1 if one or both inputs are high. 

```{figure} images/images_12/in_book/transistor_OR.svg
:name: fig:transistor_OR
:width: 700px
OR operator, based on either two transistors in parallel, or an AND operation plus three NOTs. The symbol for the OR gate is a squared box with an '$\ge$1', two inputs and one output which is true if one or both inputs are true.  
```
The OR and NOT gate can be combined into a NOR gate, which output is high only when both (A&B) inputs are low. This is equal to {numref}`fig:transistor_OR` without the last NOT operator. 

Still a basic operation, but more complex in the schematic, is the XOR. The output is high is only one of the inputs is high. Or said differently if the inputs are non-identical.

```{figure} images/images_12/in_book/transistor_XOR.svg
:name: fig:transistor_XOR
:width: 600px
XOR operator, based on a combination of AND, OR and NOT operations. The symbol for the XOR gate is a squared box with an '=1', two inputs and one output which is true only if one of the inputs is true. 
```
More complicated operations include memory, like [latches](#latch-section).

### Conversion from analog to digital, or vice versa
In order to go from analog signals to digital ones and vice versa, one needs converters: ADC (analog-to-digital converter) of DAC (digital-to-analog converter)

#### Digital to Analog Conversion

When placing two resistors or 2R value in parallel, the overall replacement resistor is R. Each 2R resistor can be seen as two resistors R in series. 
If such operation of 2R in parallel, splitting 2R in 2 R in series, is repeated multiple times, the result would be a ladder network. In each branch of this ladder network the voltage is half of the previous branch

```{figure} images/images_12/in_book/animated_ladder_network.svg
:width: 90%
:name: fig:ladder_network
Ladder-network construction. First, two resistors of resistance $2R$ connected in parallel are equivalent to a single resistor of resistance $R$. Therefore, the rightmost white resistor $R$ can be replaced by the two blue resistors of resistance $2R$ in parallel. In the next step, the rightmost blue resistor $R$ is again replaced by two green resistors of resistance $2R$ in parallel. As the ladder extends away from $U_{in}$, the current through each successive vertical resistor diminishes.
```

If in each branch of the ladder a switch is placed, which is controlled by a digital signal, on digital demand the contribution of each branch can be added or removed. The adding is done with a summing current-to-voltage amplifier, as shown in the figure below.  

```{figure} images/images_12/in_book/DAC.svg
:name: fig:DAC_ladder
:width: 600px
With a DAC circuit, where the switches are controlled with digital 0 and 1, decreasing voltages are added together. 
```

### Analog to Digital Conversion
When converting analog to digital via the successive approximation method, in several iterations the input voltage is compared to a set value with increasing bit depth. Initially, it is checked whether a signal is above or below half of the maximum voltage, deciding whether the first digital is 0 ($U_{in}$ < $\frac{U_{max}}{2}$, or 1. This checking is done with a comparator. 
Since the comparator has two inputs, the signal which you want to compare, and the signal you want to compare it to, let's call that the threshold level. 

This threshold level can be set by an DAC, starting with the most significant bit (mst). In next iterations the threshold level needs to be adapted with the voltage level corresponding to the bit depth already found. So the first comparison is with $\frac{U_{ref}}{2}$ and the next comparison is with $\frac{U_{ref}}{2} + \frac{U_{ref}}{4} $ or $\frac{U_{ref}}{2} - \frac{U_{ref}}{4} $.

```{figure} images/images_12/in_book/ADC.svg
:name: fig:ADC
:width: 600px
With an ADC circuit, bits are found (set) to approach the $U_{in}$ as close as possible. 
```

```{figure} images/images_12/in_book/ADC_workflow.svg
:name: fig:ADC_workflow
:width: 600px
The first bit found corresponds to the most significant bit (contributing $\frac{U_{ref}}{2}$). In the next step the next bit, which is a factor 2 smaller, is checked. 
```

### Clock speeds & baud rates
In microcontrollers, or other acquisition devices, often a reference clock is used to do an acquisition. For example 20 MHz clock speed. Then you can calculate the minimum time step (here $t_{min.step}= \frac{1}{20 MHz}$), and the only sample rates which can be collected correspond to period with an integer times the minimum time step ($N t_{min.step}$).

For serial communication with computers the frequency by which information is send between a device and computer is called the baud rate. A standard baud rate is a doubling of 300/s, for example 19200/s. You might imagine that when the computer is listening at another speed (baud rate) than the speed a device is sending, data can get lost. 

Note that in general the baud rate is not the same as the bit rate. Baud rate is the number of symbols per second (or state changes per second). A symbol can represent a number of bits and for standard serial communication with a serial port. In case the symbol is just 0 or 1 (so 1 bit), the bit rate and the baud rate are equal. Otherwise bit rate = baud rate x bits per symbol.

## Practical electronics
### Microprocessor - microcontroller
A microprocessor is a CPU (central processing unit), which requires external components to be able to function. Microprocessors are optimised for high speed computing, especially when multiple CPU's run in parallel. <br>
A microcontroller is a self-contained system, which has a CPU but also other components such as in- and output ports, memory. Microcontrollers are optimised for simple tasks, which makes them more cost-effective for an intended task.  <br>
Development boards as Arduino or Raspberry Pi Pico contain such (single chip) microcontoller plus additional components, which make it easier to use in practical projects. 

### Memory
With simple gates one does not yet have memory. However, with simple gates memory can be build. In this section we discuss increasing levels of memory

(latch-section)=
#### Latch
A latch is used to store one bit, so either 0 or 1, asynchronously, direclty when the inputs change. It can be build of two NOR gates, from which the output of NOR 1 is the input of NOR gate 2 (and vice versa). A NOR gate is an OR gate in series with a NOT; the NOR operator only gives a 1 out if both inputs are 0. 
A latch has two inputs SET and RESET, and two outputs Q and notQ (or Qbar).

What happens for S=R=0?
- If S=R= 0, and Q=0 (notQ=1), then Q becomes NOR(S,notQ)=NOR(0,1)=0.
- If S=R=0, and Q=1 (notQ=0), then Q becomes NOR(S, notQ)= NOR(0,0)=1. 
So if S=R=0, then Q holds it value. 

What happens if S=1, R=0? 
- If S=1, R=0, Q=0, then Q becomes NOR(S,notQ)=NOR(1,1)=0. 
- If S=1, R=0, Q=1, then Q becomes NOR(S,notQ)=NOR(1,0)=0.
- So when S=1, R=0, the value of Q gets 0. 
- When S set back to 0 (R=0, Q=0), then Q stays NOR(0,1)=0

What happens when S=0, R=1? 
- If S=0, R=1, then notQ=NOR(R,Q)=NOR(1,Q)=0
- then Q becomes NOR(0,0)=1, which is a stable state. 

So recapping: 
* S=R=0, keeps Q in the previous state: the latch can be used as memory
* you can (re)set the memory by:
    * S=1, R=0, sets Q=0
    * S=0, R=1, sets Q=1



```{figure} images/images_12/in_book/latch.svg
:name: fig:latch
:width: 70%
Want to see this latch in action? Have a look at [this latch in action video](https://www.youtube.com/watch?v=Hi7rK0hZnfc)
```
While a latch changes outputs directly if the inputs change (level-triggered,asynchonously), a flipflop requires a clock input and changes state only on the clock signal (edge-triggered, synchronous).

A register is a group of flip-flops working together to store multiple bits (often 8, 16, 32 or 64 bits). Registers are used to store all kinds of information. 

#### Interrupts
An interrupt is an signal that triggers a CPU to temporarily pauses execution of its current and starts a separate piece of code called an interrupt handler. 

During such CPU interrupt registers are used to store data before, and on the interrupt: which interrupt occur, whether an interrupt may trigger the CPU, and how the CPU can continue after an interrupt. 

### Programming sequence
The timing and order of signals is important, if not well aligned or not well triggered, some signals might not even come through. Let's look for example at a DAC, like the MCP4822. 

As written by student Thijn Hoekstra, in his project report on the RaspBerry Pi Pico: <br> 
Transmitting a command to the MCP4822 using the SPI interface is done using four digital lines: 
- the Chip Select ($\overline{CS}$) line, 
- the Serial Clock Input (SCK) line,
- the Serial Data Input (SDI), 
- the Latch DAC Input ($\overline{LDAC}$). 

The line above $\overline{CS}$ and $\overline{LDAC}$ indicate they are active low, meaning their function is executed when the pin is low instead of high. 

Before sending a command to the DAC, $\overline{CS}$ and $\overline{LDAC}$ are set to HIGH. Setting $\overline{CS}$ to LOW selects the MCP4822 and initiates the transmission. The SCK line oscillates between HIGH and LOW and sets the tempo at which each bit of the WCR is transmitted to the DAC, the clock cycle. Each time SCK rises from LOW to HIGH, the MCP4822 checks whether SDI is HIGH (1) or LOW (0). By changing the SDI signal in between clock cycles, each bit of the WCR is sent to and read by the MCP4822. When the entire register has been transmitted, $\overline{CS}$ should be reset to HIGH and $\overline{LDAC}$ should be pulsed to LOW and back to HIGH. These signals cause VOUT to update. 

```{figure} images/images_12/in_book/MCP4822_DAC_signals.svg
:name: fig:MCP4822
:width: 600px
Schematic of a write command for the MCP4822.
Source: [datasheet MCP4802/4812/4822](https://ww1.microchip.com/downloads/en/DeviceDoc/20002249B.pdf) on (Document listing | Microchip Technology)[https://www.microchip.com/en-us/document-listing]
```

### Pulse Width Modulation
Pulse Width Modulation is a method to transcribe signals with varying amplitude as a signal with pulses with varying pulse widths. Or said differently: in a pulse width modulated signal, the duty cycle per pulse depends on the original amplitude signal. 

<!--
```{figure} images/images_12/in_book/What-is-PWM-585x400.svg
:width: 70%
:name: fig:PWM
Pulse Width Modulation
```-->

:::{figure-start} images/nothing.svg
:name: fig:PWM
:alt: Nothing
:align: center

*interactive plot*: Pulse Width Modulation — adjust the signal frequency and carrier frequency to see how the pulse pattern changes.

:::

```{code-cell} python3
:tags: [hide-input, thebe-init]

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
from ipywidgets import interact, FloatSlider

def plot_pwm(f_signal=1.0, f_carrier=10.0):
    t = np.linspace(0, 2, 2000)

    Uin = np.sin(2 * np.pi * f_signal * t)
    carrier = signal.sawtooth(2 * np.pi * f_carrier * t, width=0.5)
    pwm = np.where(Uin > carrier, 1.0, -1.0)

    fig, ax = plt.subplots(figsize=(10, 6))
    ax.plot(t, Uin, color='orange', linewidth=2.5, label=r'$U_{in}$ (signal)')
    ax.step(t, pwm, color='black', linewidth=1.2, where='post', label='PWM output')
    ax.set_xlabel('t')
    ax.set_ylabel('U')
    ax.set_ylim(-1.3, 1.3)
    ax.legend(loc='upper right')
    ax.set_title(f'Pulse Width Modulation (signal: {f_signal:.1f} Hz, carrier: {f_carrier:.0f} Hz)')
    plt.tight_layout()
    plt.show()

interact(
    plot_pwm,
    f_signal=FloatSlider(value=1.0, min=0.5, max=3.0, step=0.1, description='Signal (Hz)'),
    f_carrier=FloatSlider(value=10.0, min=4.0, max=40.0, step=1.0, description='Carrier (Hz)'),
)
```


:::{figure-end}
:::

Information in amplitude is transferred into information in time. This can be useful if the time resolution in your measurement is (much) better than your amplitude resolution. This could be the case if your signal is noisy. 

````{prf:example} Morse code
:label: morse code
You might think of Morse code as an extreme form of Pulse Width Modulation, but now only two lengths: a short and long pulse. However, PWM has information in the length of the pulses, and Morse code has information in the sequence of pulses (and pauses). The overlap between the two can be mainly found in the lack of influence in the pulse height. 

```{figure} images/images_12/in_book/Morse_Code.jpg
:name: fig:Morse_Code
:width: 600px
Morse encoding: only short and long pulses. Can you Morse code a message, like your own name?
```
````

### Counter
As the name already hints at, a counter counts pulses. 
A PWM signal can be generated by a counter: the pulses of a reference clock signal can be counted, and only when they are above certain threshold value, a high value is outputted.  
A PWM signal generated by for example an oscillator can be measured by a counter, which is then used to measure how often the pulses occur. If the oscillator's frequency is intensity-dependent, then the counted pulse rate directly relate to the intensity, and the system acts as an intensity meter.   

## Examples

### Digital or analog comparator
With an OPAMP with positive feedback you can make a comparator. But you can also make one by measuring the voltage, and digitally compare it to a reference voltage. 

Be careful what comparison to use, the following often will not give an outcome

```python
voltage == threshold 
```

First of all because the threshold is a number which never will be reached, when it does not match the resolution of the measurement device. But even if the measurement device can measure the threshold value, than often the exact threshold value is simply not captured. 
Therefore the next comparison makes more sense, since then the first data point larger or equal to the threshold is detected:

```python
voltage >= threshold 
```

Another drawback of the comparing with a single value is the sensitivity to noise. Like with a real comparator it is better to build in hysteresis, to make the output signal less dependent on noise on the input. But then you need to build in some memory on the previous state as well. Have a try whether the following code works:

```python
U_HIGH = 3.0
U_LOW = 2.0

def comparator(input_signal, previous_state):
    if input_signal > U_HIGH:
        return 1
    elif input_signal < U_LOW:
        return 0
    else:
        return previous_state

# Example usage
input_signals = [1.5, 2.5, 3.2, 2.8, 2.1, 1.9, 3.5]
output_state = 0  # Initial state

for signal in input_signals:
    output_state = comparator(signal, output_state)
    print(f"Input: {signal:.2f} U → Output: {output_state}")
```

### Accurate frequency measurement
When measuring a frequency of pulses, one can either measure the length of a single pulse, or count the number of pulses within a given time. The most extreme cases are: 1 pulse in the whole time window, or 1 pulse per 2 time points. 
For low frequencies the measurement of the period (or half period for known duty cycle) gives a better value than the number of pulses divided by the overall time. 
For high frequencies the number of pulses per time gives a better measurement than the inverse of the period. 

Challenge: Write python code to check the accuracy of both frequency measurements:
- generates a PWM signal with 50% duty cycle, lets say in 100 data points. 
- In a loop increase the frequency of the PWM signal, and measure the signal frequency from the period and from the number of pulses per time. 
- Plot the measured the input frequency and both measured frequencies. <br>

Then analyze which frequency measurement is most accurate. 

### ALEX: Alternating Laser Excitation
Often with Single Molecule Fluorescence the location of multiple, differently colored, fluorescent probes are followed. And often this requires excitation at multiple laser wavelengths. Then alternating laser excitation (ALEX), which uses counter, is used. The input to ALEX is a pulse train synced with each acquisition (often an output on the camera), plus some specs on start, high and low time of each color. 
A scheme for 10 green images and 1 red image can be (values in pulses):
* $N_{green delay}$ = 0, $N_{red delay}$ =10
* $N_{green high}$=10, $N_{red high}$=2
* $N_{green low}$=2, $N_{red low}$=10

```{figure} images/images_12/in_book/ALEX.svg
:name: fig:ALEX
:width: 600px
Overview how ALEX can be programmed to depend on the trigger out of an EMCCD camera. 
```

## Exercises
Most of the exercises involve writing Python code. Such code could eventually run on a microcontroller, and relates to topics in this chapter.

````{exercise} Conversion decimal - binary and back  (on paper)
a) Convert 5287 into binary, by a derivation on paper. <br>
b) Convert 0110000110101001 into decimal, by a derivation on paper.


```{tip} 
:name: decimal to binary
:class: dropdown
Start by subtracting the highest order of 2, in this case 4096 which is $2^{12}$. This would correspond to the left most digit (1 xxxx xxxx xxxx). <br>
Since the remainder (5287-4096) is smaller than $2^{11}$, the next digit is 0 (1 0xxx xxxx xxxx).
```

```{tip} 
:name: binary to deci
:class: dropdown
Start with the least significant bit (rightmost value), which corresponds to $2^0$ = 1. <br>
The next bit>0 corresponds to $2^3$=8. Find all corresponding values to each bit with value 1, and sum all these corresponding values. 
```

```{admonition} Numeric answer
:class: dropdown, seealso
You can use the computer calculator in programmer mode to verify your answers. 
```
````

````{exercise} Conversion decimal - binary (in Python)
a) write a Python function, which can be used to convert a binary number into a decimal number
b) write a Python function, which converts a decimal number into binary code
c) extra challenge: adapt the code from b) to include one more input which is the base (binary base =2, decimal base =10). Try a tertiary base of 3. 


```{tip} 
:class: dropdown
:name: tip for a&b Python decimal conversion
Verify your code for a & b with the computer's calculator in programming mode 
```

```{tip} 
:class: dropdown
:name: tip for c Tertiary base
Start with the least significant bit (rightmost value), which corresponds to $2^0$ = 1.
The next bit>0 corresponds to $2^3$=8. Find all corresponding values to each bit with value 1, and sum all these corresponding values. 
```

```{admonition} Numeric answer
:class: dropdown, seealso
If the following works than you've done the exercise correctly. If not, keep on troubleshooting. <br>
1111 in base-2 = 10001010111 <br>
4284 in base-3 = 12212200 <br>
11111111 in base-10 = 255
```
````

````{exercise} AD converter

In a bit-like manner, so one bit per iteration:
a) Write a Python function, which like an ADC converts a voltage to an 8bits value (full range corresponds to 5 V) <br>
b) Write a Python function, which like a DAC converts a bit value into a voltage (again full range is 5V)
 

```{tip} 
:name: tip for a&b ADC-DAC convert
:class: dropdown
Start with which value corresponds to the most significant bit (msb). Then think about what to do if the (input) voltage is below or above this msb-voltage. 
Do this again, and look at whether you see a similarity with the previous iteration. Try to eventually write the code in a loop. 
```

```{admonition} Code answer
:class: dropdown, seealso
Some initial checkds: 
$U_{in}$=0 correpsonds to 00000000 <br>
$U_{in}$=2.5 correpsonds to 10000000 <br>
$U_{in}$=5 corresponds to 11111111

Further you can verify your answers with the Python code bin, for example bin(2.5/5)
```
````

````{exercise} Differentiator (analysis in Python)


```python
import numpy as np
time= np.arange(1, 100.1, 0.1)
signal=np.sine(2*np.pi* 0.01*time) 
```

a) write code to differentiate a signal <br>
b) round the signal to multiples of 0.1. <br>
c) compare the differentiated signal with the differentiated rounded signal. What difference do you observe

```{tip} 
:name: differentiating a signal
:class: dropdown
You could subtract one array with all signal values except the first, from another array with all signal values except the last
```

```{tip} 
:name: rounding a signal
:class: dropdown
remember the special cases of division: 5/2, 5//2, 5%2
```

```{admonition} Code answer
:class: dropdown, seealso
Some initial checks: 
The differentiated rounded signal will have spikes (and a lot of zeros), while the differentiated signal will almost all the time have a non-zero value. 
```
````

````{exercise} Write code to generate a PWM signal 


Write code to generate a PWM signal, based on the following signal:

```python
import numpy as np
time= np.arange(0, 100, 0.1)
signal=np.sine(2*np.pi* 0.02*time) 
```
Follow the next steps: 
a) average the sine, per block of 50 time points <br>
b) generate a pulse which depends on this average. The value of the pulse can be +1,0,-1, and the length of the pulse depends on the average0sine-value-per-block.  

```{tip} 
:name: PWM_conversion
:class: dropdown
You might want to write code for the first block of 50 data points, and later on add a loop. 

An average-sine-value of 1 becomes a +1 for 50 time points <br>
An average-sine-value of 0.2 becomes a +1 for 10 time points <br>
An average-sine-value of -0.5 becomes a -1 for 25 time points
```

```{admonition} Code answer
:class: dropdown, seealso
Check that your PWM signal looks (quite) {numref}`fig:PWM`
```
````



````{exercise} Ceasar's deciphering (in Python)

This is one of the advanced exercises in [Programming Foundations](https://interactivetextbooks.tudelft.nl/programming-foundations/content/chapter8/exercises.html), exercise 8.20.

If you want to go one step further: Try to write code for [keyed Caesar's deciphering](https://www.boxentriq.com/code-breaking/keyed-caesar-cipher). Then the keyword, or at least the unique characters of the keyword come first in the ciphering. 

For example the Keyword 'COOLSTUFF' means the decipher string becomes COLSTUFABDEGHIJKMNPQRVWXYZ
````

````{exercise} Stepfinder (in Python)
In any biophysics experiment you get noisy data. And often you look for finding one or multiple steps in such noisy data. One approach could be to use the stepfinder, written by Kerssemakers, J., Laura Munteanu, E., Laan, L. *et al*. Assembly dynamics of microtubules at molecular resolution. [*Nature* **442**, 709–712 (2006)](https://doi.org/10.1038/nature04928).

The approach is as follows:
1. Assume a step position
2. Generate a new_data array, which holds two values: 
    a. initially the averaged amplitude left of the assumed step position, 
    b. after the step position use the averaged amplitude right of the assumed step position
3. Subtract the new_data from the actual data, square this difference and sum this squared difference over the whole data-array. 
4. Now repeat step 1-3 in an iterative manner for each possible step position, store the summed square difference in an Chi-squared array, and find the best position for the step. 

```{figure} images/images_12/in_book/stepfinder.svg
:name: fig:stepfinder
:width: 500px
Visualization of the stepfinder functions
```

Questions:
A. Explain why the above approach leads to {numref}`fig:stepfinder`, and how to find the best position for the step
B. Write Python code
C. extra advanced challenges: 
    - expand the code to find multiple steps
    - write code to find the optimal number of steps. Hint: checkout the best Chi-squared value per number of steps. See supplementary methods 3 of [this stepfinder paper](https://doi.org/10.1038/nature04928). 

Python code for noisy data with one step: 
```python
import numpy as np
from matplotlib import pyplot as plt
from time import time
import sys

def createdata_onestep(nmax=10,signaltonoise=50):
    data = np.empty((2,nmax))         # initialise data
    tmax = 20*(np.random.rand(1)+1)   # set time axis
    tmin = 0.5*tmax*np.random.rand(1)
    data[0,:] = np.transpose(np.linspace(tmin,tmax,nmax))
    stepsize = 10*np.random.rand(1)    # set first and last position and stepsize
    initialposition = np.random.rand(1)
    stepindex = np.random.randint(2,nmax-2)    # define the timepoint of the step
    noise = stepsize/signaltonoise*np.random.randn(nmax) # define some noisy data
    data[1,:] = initialposition + noise
    data[1,stepindex:] += stepsize     # add the step to the data
    return data,data[0,stepindex]

data_not_so_noisy,_ = createdata_onestep(600,50)
data_noisy,_ = createdata_onestep(400,10)
data_extremely_noisy,_ = createdata_onestep(500,3)
```

````

````{exercise} Center of Mass code (in Python)

Code is given to generate a Point Spread Function; due to the diffraction limit a point is imaged as a certain spread. This code is included because of its inclusion of noise and background, related to discretization in amplitude and sampling in space, and their effect on the data. 

```python
import matplotlib.pyplot as plt
import numpy as np

x, y = np.linspace(-10,10,400), np.linspace(-10,10,400)
X, Y = np.meshgrid(x, y)

f1 = np.sinc(np.hypot(X, Y))
plt.imshow(f1)
```

The following code can be used to determine the Center of Mass (COM):

```python
def Center_of_Mass(image):
    ss=np.shape(image) 
    xv=np.arange(0,ss[0])
    yv=np.arange(0,ss[1])
    Yv=np.tile(yv,(ss[0],1))
    Xv=np.tile(xv,(ss[1],1)).transpose()
    mx=np.sum(np.sum(np.multiply(Xv,image)))/np.sum(np.sum(image))
    my=np.sum(np.sum(np.multiply(Yv,image)))/np.sum(np.sum(image))
    return my,mx
```

Adapt your code to also work on noisy data, where the COM is not in the middle of the image:

```python
x2, y2 = np.linspace(-9,11,400), np.linspace(-13,7,400) 
X2, Y2 = np.meshgrid(x2, y2)
f2 = np.sinc(np.hypot(X2, Y2)) 

nnn=np.random.rand(np.size(X2,0),np.size(Y2,1)) # adding noise
bg=np.random.rand() # add background, preferably a constant between 0 and 1
im2=f2+nnn+bg
```
````

````{exercise} Aliasing theory

a) For a sample rate of 100kHz, what is the maximum signal freqency you can measure? <br>
b) Explain why this max detectable frequency is not equal to the sampling rate?


```{tip} 
:name: rewrite_sine_as_sum_exponents
:class: dropdown
Assume the simplest signal, a sine with one frequency, and rewrite it as sum of exponents. 
At which frequencies in the Fourier spectrum will you see peaks?
```



```{admonition} Numeric answer a
:class: dropdown, seealso

$$
f_{Nyquist} = \frac{ f_{sample rate}}{2}
$$ 
```

```{admonition} Numeric answer b
:class: dropdown, seealso
A sine is sum of 2 exponents, positive and negative frequency, which helps you to explain the factor of 2 
```
````

````{exercise} Aliasing a single sine

Two times a signal is measured. Derive which frequency and which sign (+ or -) this measured signal has? <br>
a) The frequency of the input signal is 450 Hz, and the sampling rate is 650 Hz <br>
b) The input signal's frequency is 7 kHz, and the Nyquist frequency is 3.2 kHz

```{tip} 
:name: max_measureable_frequency?
:class: dropdown
Always derive the maximal measurable frequency first.  
```

```{admonition} Numeric answer a
:class: dropdown, seealso

The measured frequency is 200 Hz
```

```{admonition} Numeric answer b
:class: dropdown, seealso
The measured frequency is 0.6 kHz
```
````

````{exercise} Deriving a possible input frequency (before aliasing)

You do a measurement with a sampling frequency of 960 Hz, and measure a single peak with a frequency of 320 Hz. <br>
a) Which frequency does the input signal minimally have? <br>
b) Assume the sign of the input and output signal are opposite (or phrased differently have a 180 degrees phase difference). Derive a possible frequency of the input signal <br>
c) Assume the sign of input and output signal are the same. Derive a possible input frequency above 500 Hz. <br>
d) How to know for sure whether the input signal was defined by a frequency as described in a, b, or c?

```{tip} 
:name: again_max_measurable_frequency
:class: dropdown
Always derive the maximal measurable frequency first.  
```

```{admonition} Numeric answer a
:class: dropdown, seealso

The minimal input frequency is 320 Hz
```

```{admonition} Numeric answer b
:class: dropdown, seealso
a possible input frequency is 640 Hz. 
```

```{admonition} Numeric answer c
:class: dropdown, seealso
a possible input frequency is 1280 Hz. 
```

```{admonition} Numeric answer d
:class: dropdown, seealso
With a single measurement you get many possible input frequencies. Do a second measurement with another sampling rate. 
```

````

````{exercise} Measuring two signals with two different sampling rates

You have an input signal which is the sum of two sines. <br>

When measuring with a sampling rate of 5 kHz, the measured frequencies are 0.5 kHz and 2 kHz. <br> 
When measuring with a sampling rate of 3.5 kHz, the measured frequencies are 1 and 1.5 kHz. 

a) Make a list of possible input frequencies, based on the 5 kHz sampling. <br>
b) Make a list of possible input frequencies, based on the 3.5 kHz sampling. <br>
c) Compare the two lists and derive what the input frequencies were. <br>

```{tip} 
:name: aliasing_no_summing
:class: dropdown
You measure two frequencies for each sampling rate. So there are no overlapping frequencies, which makes the derivation easier.   
```

```{admonition} Numeric answer a
:class: dropdown, seealso
Sampling rate of 5kHz, means $f_{Nyquist}$ = 2.5 kHz <br>
a1. possible frequencies: 0.5 kHz, 4.5 kHz, 5.5 kHz, 9.5 kHz, ....<br>
a2. possible frequencies: 2 kHz, 3 kHz, 7 kHz, 8 kHz, ....
```

```{admonition} Numeric answer b
:class: dropdown, seealso
Sampling rate of 3.5kHz, means $f_{Nyquist}$ = 1.75 kHz <br>
b1. possible frequencies: 1 kHz, 2.5 kHz, 4.5 kHz, 5 kHz, ....<br>
b2. possible frequencies: 1.5 kHz, 2 kHz, 5 kHz, 5.5 kHz, ....
```

```{admonition} Numeric answer c
:class: dropdown, seealso
either a1&b1 match, or a1&b2. 
a1&b1 both have 4.5 kHz, a2&b2 both have 2 kHz. 
```
````


````{exercise} Letting two sines disappear


You sum two input signals, both sines with frequencies 15 kHz and 33 kHz. When playing around with the frequency you manage to let both signals disappear. 

a) Derive which sampling rate you used? <br>
b) Explain whether there are more than 1 solution for a)


```{tip} 
:name: aliasing_inverted_sign
:class: dropdown
A good start could be to choose the Nyquist frequency between the two input frequencies.  
Finding a second possible sampling rate would be a good explanation. 
```

```{admonition} Numeric answer a
:class: dropdown, seealso
33 kHz aliases to 15 kHz with an inverted sign. 
Sampling rate = 48 kHz
```

```{admonition} Numeric answer b
:class: dropdown, seealso
Sampling rate = 24 kHz
```


````

````{exercise} (Anti)Aliasing of a block wave


You measure a block wave with fundamental frequency 4 kHz with a Nyquist frequency of 19 kHz. <br>
a) Write down the first 5 freqencies at which peaks occur in the non-aliased spectrum of the block wave <br>
b) Select the first and last of these 10 frequencies which will be aliased, and derive what their corresponding measured frequency will be. <br>
c) How to counteract aliasing?


```{tip} 
:name: aliasing_block
:class: dropdown
a block wave has higher odd harmonics
```

```{admonition} Numeric answer a
:class: dropdown, seealso
4 kHz = fundamental Higher odd harmonics are: 12 kHz, 20 kHz, 28 kHz, 36 kHz
```

```{admonition} Numeric answer b
:class: dropdown, seealso
All frequencies above the Nyquist frequency are aliased, starting with 20 kHz and ending with 40 kHz. 
20 kHz is measured as 18 kHz <br>
28 kHz is measured as 10 kHz <br>
36 kHz is measured as 2 kHz <br>
```

```{admonition} Numeric answer c
:class: dropdown, seealso
Use an analog filter, low pass with f-3dB at the Nyquist frequency (or a little bit below)
```

````
