First of all, I would encourage tp read a great article there. The great simplified approach and insights were provided by that link.

Let’s go through some key point and gain better understanding and develop some useful skills.

Correlation is a first key concept there, it can be described as the sum of the product of two signals:

\sum_{i=0}^{N}x(i)y(i)

We are talking there about the simplest correlation form, without any cross correlation equations involved.

The correlation can be positive, or negative if the signal is the same but simply out of the phase, or if signals are completely different correlation will have extremely small values.

So the key point in whole discrete transformation just a simple sweep – you take the point a the certain frequency (which you know can be represented by Euler equation) multiply by your signal, check the correlation, then continue up to the end.

The easiest way to learn is to look at some simple examples, let’s say we have sine and cosine at frequency equal to 7Hz:

And next there is a simple Octave piece of the code:

```
clf
clear
#input data variables
step = 1/256;
tstop = 2;
f1 = 7;
t = 0:step:tstop-step;
for i = 1:length(t)
rand_coeff1(i) = (rand()-0.5:0.5)/3;
rand_coeff2(i) = (rand()-0.5:0.5)/3;
end
y = sin(2*pi*f1*t);
ytry=e.^(j*2*pi*7*t);
y_product1 = y.*ytry;
plot(t,y)
hold on
grid on
correlation1 = sum(imag(y_product1));
correlation2 = sum(real(y_product1));
y = sin(2*pi*f1*t+pi/2);
plot(t,y)
ytry=e.^(j*2*pi*7*t);
y_product1 = y.*ytry;
correlation3 = sum(imag(y_product1));
correlation4 = sum(real(y_product1));
```

Here, in that code, one important thing should pop up – we should not forget to pull the phase information from these products.

correlaton1 | 256 |

correlation2 | ~10^(-14) |

correlation3 | ~10^(-13) |

correlation4 | 256 |

It could be clearly seen that correlation1 is indicating that signal which has been probed is the sine, while correlation4 indicates the cosine.

OK, so we can now distinguish sine from cosine, let’s make our example a little more complex – now we have two signals – at 7 and at 8Hz:

```
clf
clear
#input data variables
step = 1/256;
tstop = 2;
f1 = 7;
t = 0:step:tstop-step;
N = 16;
y = sin(2*pi*f1*t)+sin(2*pi*(f1+1)*t);
#ytry=e.^(j*2*pi*1*t);
#y_product1 = y.*ytry;
#plot(t,y)
##hold on
#grid on
for i=1:1:N
ytry=e.^(j*2*pi*i*t);
y_product = y.*ytry;
correlation_real(i) = sum(real(y_product));
correlation_imag(i) = sum(imag(y_product));
correlation_abs(i) = correlation_real(i) + correlation_imag(i);
plot(i,correlation_abs(i),'marker','o');
hold on;
grid on;
endfor
```

Checking the result:

Two peaks clearly seen at 7 and 8, looking into that picture I had couple questions – Why are these numbers so big? How to define proper N? What is the limits? How to make plot with bars instead of markers

Here some more realistic function, this time lets do it with numbers, so we will have some kind of an anсhor for us:

y = 2 + 5cos(2 \pi2 t)+3sin(2\pi3t)+2cos(2\pi4t)

And the sampled one curve is a set of values sampled with Fs = 8Hz, here I took 8 samples, which means that resolution will be equal to 1Hz.

To answer question why numbers are that big, it could be seen that it just corresponds to the amount of point which we took, so, the first attempt would be just do divide that correlation sum to N, let’s see what will happen:

```
clf
clear
#input data variables
step = 1/1024;
tstop = 1;
t = 0:step:tstop;
y = 2 + 5*cos(2*pi*t*2) + 3*sin(2*pi*t*3) + 2*cos(2*pi*t*4);
#plot(t,y,'b', 'linewidth',4);
grid on;
hold on;
N = 8;
Fs = 8;
ts = 1/Fs;
f_spectrum = 0:Fs/N:(Fs*(N-1))/N;
tsample = 0:ts:(N-1)*ts;
y_sampled = 2 + 5*cos(2*pi*tsample*2)+3*sin(2*pi*tsample*3) + 2*cos(2*pi*tsample*4);
#plot(tsample,y_sampled,'r','marker','o','linewidth',1,'markersize',20);
h=legend('original ','sampled ');
set(h,'fontsize',14,'fontname','FreeSans','fontweight','normal');
set(gca, 'linewidth', 3, 'fontsize', 18,'fontname', 'FreeSans') #modify line and fontsize of x and y axes
#xlabel('t, s');
#ylabel('Amplitude, V');
for i=0:1:(N-1)
ytry=e.^(-j*2*pi*i*Fs/N*tsample);
y_product = (y_sampled.*ytry)/N;
correlation_real(i+1) = sum(real(y_product));
correlation_imag(i+1) = sum(imag(y_product));
correlation_abs(i+1) = sqrt(correlation_real(i+1)^2 + correlation_imag(i+1)^2);
#plot(i,correlation_abs(i+1),'marker','o');
#hold on;
#grid on;
endfor
xlabel('F, Hz');
ylabel('Amplitude, V');
bar(f_spectrum,correlation_abs,0.1)
```

OK, a couple of things from my questions were addressed there, but if you draw enough of attention, it could be seen that we have proper values for DC and for F = 4Hz, while 2 and 3 Hz are half from what they should be. Also, we see another two harmonics after 4Hz – this is because we entered in the second Nyquist zone (>Fs/2) and we got the spectrum folding there (and all entries there are just complex conjugates for entries from the other side). So, for instance, what we see at 6 Hz is just 8-2 Hz and so on. This is also the reason why we see /2 degradation inside of the first Nyquist zone, but DC and Fs/2 actually matched in folding points. The conclusion is the next – we need to multiply by 2 points inside of (DC, Fs/2) but not touch edges. Also, we are not interested in the second half of points for the spectrum crafting.

```
clf
clear
#input data variables
step = 1/1024;
tstop = 1;
t = 0:step:tstop;
y = 2 + 5*cos(2*pi*t*2) + 3*sin(2*pi*t*3) + 2*cos(2*pi*t*4);
#plot(t,y,'b', 'linewidth',4);
grid on;
hold on;
N = 8;
Fs = 8;
ts = 1/Fs;
f_spectrum = 0:Fs/N:(Fs*(N-1))/N;
tsample = 0:ts:(N-1)*ts;
y_sampled = 2 + 5*cos(2*pi*tsample*2)+3*sin(2*pi*tsample*3) + 2*cos(2*pi*tsample*4);
#plot(tsample,y_sampled,'r','marker','o','linewidth',1,'markersize',20);
h=legend('original ','sampled ');
set(h,'fontsize',14,'fontname','FreeSans','fontweight','normal');
set(gca, 'linewidth', 3, 'fontsize', 18,'fontname', 'FreeSans') #modify line and fontsize of x and y axes
#xlabel('t, s');
#ylabel('Amplitude, V');
for i=0:1:(N-1)
ytry=e.^(-j*2*pi*i*Fs/N*tsample);
if ((i==0)||(i==N/2))
y_product = (y_sampled.*ytry)/N;
else
y_product = (y_sampled.*ytry)/(0.5*N);
endif
correlation_real(i+1) = sum(real(y_product));
correlation_imag(i+1) = sum(imag(y_product));
correlation_abs(i+1) = sqrt(correlation_real(i+1)^2 + correlation_imag(i+1)^2);
#plot(i,correlation_abs(i+1),'marker','o');
#hold on;
#grid on;
endfor
subplot(3,1,1);
title("mag");
bar(f_spectrum,correlation_abs,0.1)
subplot(3,1,2);
title("real")
bar(f_spectrum,correlation_real,0.1)
subplot(3,1,3)
title("imag")
bar(f_spectrum,correlation_imag,0.1)
```

With that code magnitude values matched truly across dc – Fs/2, also I have plotted real and imag values to show that the phase information available as well. Also, it is clearly seen that after Fs/2 we have the complex conjugate (take a look on imag plot).

This is great, but there is the one thing still which not quite aligned, if we look on the basic DFT equation:

F[n] = \sum_{k=0}^{N-1}f[k]e^{-j2\pi kn/N} (n=0:N-1)

Octave or matlab allows us to calculate correlation sum just by multiplying waveforms (or matrix) while not all other programming languages can allow that I guess. So, instead, we could “probe” each harmonic (n) by calculation of the correlation sum of the original signal with kn/N

Lets modify the code a little bit, to be compatible with the original DFT equation:

```
clf;
clear;
grid on;
hold on;
N = 8;
Fs = 8;
ts = 1/Fs;
f_spectrum = 0:Fs/N:(Fs*(N-1))/N;
tsample = 0:ts:(N-1)*ts;
y_sampled = 2 + 5*cos(2*pi*tsample*2)+3*sin(2*pi*tsample*3) + 2*cos(2*pi*tsample*4);
#plot(tsample,y_sampled,'r','marker','o','linewidth',1,'markersize',20);
h=legend('original ','sampled ');
set(h,'fontsize',14,'fontname','FreeSans','fontweight','normal');
set(gca, 'linewidth', 3, 'fontsize', 18,'fontname', 'FreeSans') #modify line and fontsize of x and y axes
#xlabel('t, s');
#ylabel('Amplitude, V');
for i=0:1:(N-1)
sum_harm = 0;
for k=0:1:(N-1)
sum_harm = sum_harm + y_sampled(k+1)*e^(-j*2*pi*i*k/N);
endfor
f(i+1) = sqrt(real(sum_harm)^2+imag(sum_harm)^2);
endfor
#normalization procedure
for i=1:1:N
if ((i==1)||(i==(N/2 + 1)))
f_norm(i) = f(i)/N;
else
f_norm(i) = f(i)*2/N;
endif
endfor
bar(f_spectrum,f_norm,0.1)
xlabel('f, Hz');
ylabel('Amplitude, V');
```

And the result is the same:

OK, so DFT is more or less clear I think, there are few notes should be taken into account still:

- Aliasing – that one we have seen already – we have “spectral folding” after Fs/2. To solve that one we can just not use half of the data
- Spectral leakage – in an example I used all harmonics were lying right in the spectral resolution (which is 1Hz for the example), but what if there will be some frequency which has some fractional part

So, lets assume we have 3.3Hz frequency with an amplitude 3 and Fs is equal to 8Hz, also I did N equal to 64, so the resolution is 0.125Hz and our harmonic doesn’t fall in that resolution.

It could be seen that amplitude spreads around somewhat of 3.3Hz and across different fft seeds.

To make this problem less hurting for the resulting spectrum, there is thing called window, which has direct impact on the spectrum by, basically, applying some extra transfer function to the sampled signal being processed.

Let say we have 64 samples, one of the most often used windows is the Hanning one, it has the next function:

w(n) = 0.5(1-cos(2\pi \frac{n}{N}))

It looks like this:

Little bit of a practice:

```
N = 64;
Fs = 8;
ts = 1/Fs;
#f_spectrum = 0:Fs/N:(Fs*(N-1))/N;
f_spectrum = 0:Fs/N:Fs/2;
tsample = 0:ts:(N-1)*ts;
nsample = 0:1:N;
y_sampled = 2 + 3*cos(2*pi*tsample*3.3);
for i=1:1:(N)
ywindowed(i) = 2+ 0.5*(1-cos(2*pi*i/N))*(y_sampled(i)-2);
endfor
plot(tsample,y_sampled,'b','linewidth',2,'markersize',10);
hold on;
plot(tsample,ywindowed,'r','marker','o','linewidth',2,'markersize',10);
```

Here, I just added some post processing to remove dc and then add dc, just to have a nicer plot (which impacts only dc component).

Now, if we apply that Hann window and plot the spectrum we would get:

It is still far from an ideal spectrum, but it is obvious that all extra spectral components which were spreaded across whole spectrum, now concentrated somewhere around 3.3Hz, so the leakage of spectral content away from the correct location is much reduced.

Octave has build in window functions, so instead of code I used, we can use that built-in possibility:

` ywindowed = y_sampled.*hanning(N)';`

OK, that one also looks clean more or less I think now. What is left there is the computing power which is used on the calculation of DFT, there are a lot of multiplications made (N*N), more resolution you want more multiplication you have. For instance, if some would want to have a nice spectrum with 65536 points it will result in 4294967296 – quite a significant amount of computations. That’s why FFT was invented which allows reusing already calculated coefficients using decimation in time or decimation in frequency algorithm, but that is out of the scope of this topic and, it is by itself quite a big thing to dig in.

But, I still want to show how to use built-in fft function in Octave, rather than invent own DFT or FFT code:

```
clf
clear
#input data variables
tstop = 1;
hold on;
N = 8;
Fs = 8;
ts = 1/Fs;
f_spectrum = 0:Fs/N:(Fs*(N-1))/N;
#define window there
#window = blackman(N);
window = 1;
tsample = 0:ts:(N-1)*ts;
y_sampled = 2 + 5*cos(2*pi*tsample*2)+3*sin(2*pi*tsample*3) + 2*cos(2*pi*tsample*4);
yFFT = y_sampled.*window';
set(gca, 'linewidth', 3, 'fontsize', 18,'fontname', 'FreeSans') #modify line and fontsize of x and y axes
#plot(tsample,y_sampled,'b','linewidth',2,'markersize',20);
grid on;
spectrum_complex = fft(yFFT, N)/(0.5*N);
spectrum_complex(1) = spectrum_complex(1) /2;
spectrum_complex(N/2+1) = spectrum_complex(N/2+1) /2;
spectrum_mag = abs(spectrum_complex);
bar(f_spectrum(1:(N/2+1)), spectrum_mag(1:(N/2+1)),0.2);
```

I am not quite sure if I did it right for edge points, but in that example it worked out.

]]>As it known from Fourier series, any signal can be represented as a sum of different simple signals, which basically allow as to simplify a computation and makes possible FFT transformation.

To begin to dig into basics let me refresh mind with couple fundamentals equations, which help to work with Fourier.

Math |
---|

Euler equations:e^{jx} = cos(x)+jsin(x) cos(x)=\frac{e^{jx}+e^{-jx}}{2} sin(x)=\frac{e^{jx}-e^{-jx}}{2j} Trigonometry:cos(x)cos(y)=0.5(cos(x-y)+cos(x+y)) sin(x)sin(y)=0.5(cos(x-y)-cos(x+y)) cos^2(x)=0.5(1+cos(2x)) \int_{-\pi}^{\pi} cos^2(x) \,dx=\int_{-\pi}^{\pi} {(1+cos(2x))} \,dx=0.5(x+sin(x)cos(x))\Biggr|_{-\pi}^{\pi}=\pi cos(-x)=cos(x) - even\ function, sin(-x)=-sin(x) - odd\ function |

OK, the theoretical basis is built, we can write down some basics of Fourier series.

FOURier series |
---|

Any signal can be represented as: f(x)=\sum_{n=0}^{\infty} a_ncos(nx) + \sum_{n=1}^{\infty} b_nsin(nx) How to calculate these coefficients? Use an ortogonal funciton! As known, if we integrate sin(x)cos(x) from -pi to pi, the result will be equal to 0, so that can be used for the calculation of coefficients. If we want to calculate the a coefficient, let’s multiply the function to cos(kx), in that case the integral will be non-zero only if k=n, so: \int_{-\pi}^{\pi} f(x)cos(kx) \,dx=\int_{-\pi}^{\pi} a_kcos^2(kx) \,dx=a_k\pi So, the coefficient is equal to: a_k=\frac{1}{\pi}\int_{-\pi}^{\pi} f(x)cos(kx) \,dx b_k=\frac{1}{\pi}\int_{-\pi}^{\pi} f(x)sin(kx) \,dx Now need to check what do we have when k equal to 0 – b_k will be equal to 0, while a_k is not: a_0=\frac{1}{2\pi}\int_{-\pi}^{\pi} f(x) \,dx |

**Example 1**: The delta (Dirac) function

Integral of Dirac function is equal to 1. This is important. Let’s look closer – that function is the even function, so it doesn’t contain the sine portion, only the cosine is presented.

a_0=\frac{1}{2\pi}\int_{-\pi}^{\pi} \delta(x) \,dx=\frac{1}{2\pi}For other coefficient it is also should be noticed that if we multiply the delta function by any other function in the area different from 0, the result will be 0, and in 0 area cosine is equal to 1, so:

a_k=\frac{1}{\pi}\int_{-\pi}^{\pi} \delta(x)cos(kx) \,dx=\frac{1}{\pi}Which basically means that all coefficients are equal to 1/pi, and a resulting representation is:

\delta(x)=\frac{1}{2\pi}+\frac{1}{\pi}(cosx + cos(2x) + cos(3x) + cos(4x) + ... )More harmonic we include, closer to ideal curve we move:

What I, personally still don’t understand why we have that 1/2pi term, it changes value for non-zero x moving it away from ideal form.

**Example 2**: The sign function

Sign function is equal to +1 from 0 to pi, and equal to -1 from -pi to 0:

Looking at that plot we already can say that this is an ODD function. So we don’t have cosine components, and, one more useful property of the odd function – we can integrate only half of the period and multiply result by two to get the full value.

b_k=\frac{2}{\pi}\int_{0}^{\pi} f(x)sin(kx) \,dx=\frac{2}{\pi}\int_{0}^{\pi} sin(kx) \,dx=\frac{2}{\pi}(\frac{-cos(kx)}{k})\Biggr|_{0}^{\pi}=\frac{2}{\pi}(\frac{2}{1};\frac{0}{2};\frac{2}{3};\frac{0}{4};\frac{2}{5};...)Now, lets instantiate it into Fourier series basic representation:

\frac{4}{\pi}(sin(x)+sin(3x)+sin(5x)+...)=\frac{4}{\pi}\sum_{k=1}^{\infty} \frac{sin((2k-1)x)}{2k-1}Only odd components are survived, like for usual square wave signal frequency content.

But what if our function will be phase shifted and turned from odd into the even function?

So now the function is even and will be represented by cosine terms. Lets start from a0:

a_0=\frac{1}{2\pi}\int_{-\pi}^{\pi} f(x) \,dx=\frac{1}{2\pi}\int_{-\pi}^{\pi} (-1) \,dx=(-x)\Biggr|_{-\pi}^{\pi}=0I actually think that a_0 calculation is wrong there, we actually need to take integrals from all 3 areas: -pi to -pi/2, -pi/2 to pi/2, pi/2 to pi. This will lead to the same result, still 0, so we can skip that. But we also can not do integral from -pi to pi for ak coefficients, because function is changed within that period, so we also can do that division by 3 areas.

a_{k*}=\frac{1}{\pi}\int_{-\pi}^{\frac{-\pi}{2}} f(x)cos(kx) \,dx=\frac{1}{\pi}(-\frac{sin(kx)}{k}\Biggr|_{-\pi}^{\frac{-\pi}{2}})=\frac{1}{\pi}(1;\frac{-1}{3};\frac{1}{5};...) a_{k**}=\frac{1}{\pi}\int_{\frac{\pi}{2}}^{\pi} f(x)cos(kx) \,dx=\frac{1}{\pi}(-\frac{sin(kx)}{k}\Biggr|_{\frac{\pi}{2}}^{\pi})=\frac{1}{\pi}(1;\frac{-1}{3};\frac{1}{5};...) a_{k***}=\frac{1}{\pi}\int_{\frac{-\pi}{2}}^{\frac{\pi}{2}} f(x)cos(kx) \,dx=\frac{1}{\pi}(\frac{sin(kx)}{k}\Biggr|_{\frac{-\pi}{2}}^{\frac{\pi}{2}})=\frac{2}{\pi}(1;\frac{-1}{3};\frac{1}{5};...)Now, all we need to do just to sum all 3 parts:

a_{k*}+a_{k**}+a_{k***}=\frac{4}{\pi} \sum_{k=1}^{\infty}\frac{cos((2k-1)x)}{(2k-1)(-1)^(k+1)}Let’s plot that function:

Looks similar to our initial function, so seems I did my calculation right.

**Complex form of Fourier series.**

Looking at coefficient derived in the first part it can be seen that a_0 is divided by two in comparison to usual (why?)

f(x)=\frac{a_0}{2} + \sum_{n=1}^{\infty} (a_ncos(nx) + b_nsin(nx))=\frac{a_0}{2} + \sum_{n=1}^{\infty}\frac{a_n-jb_n}{2}e^{jnx} + \sum_{n=1}^{\infty}\frac{a_n+jb_n}{2}e^{-jnx} = \sum_{-\infty}^{\infty}c_ne^{jnx} c_0=\frac{a_0}{2}, c_n=\frac{a_n-jb_n}{2}, c_{-n}=\frac{a_n+jb_n}{2}So we have three coefficient, the zero one and two complex conjugates.

c_0=\frac{1}{2\pi}\int_{-\pi}^{\pi} f(x) \,dxCoefficients would be:

c_n=\frac{1}{2\pi}\int_{-\pi}^{\pi} f(x)e^{-jnx} \,dx, n=0,\pm1,\pm2,\pm3...Let’s try to calculate Fourier series in complex form for sign function. C_0 component will still be 0, it is easy to check by integration from -pi to 0 plus integral from 0 to pi.

The same sum of integrals should be taken for c_n as well:

[katex]c_n=\frac{1}{2\pi}\int_{-\pi}^{\pi} f(x)e^{-jnx} \,dx=\frac{1}{2\pi}(\int_{-\pi}^{0} (-1)e^{-jnx} \,dx+\int_{0}^{\pi} e^{-jnx} \,dx)=\frac{1}{n\pi}(\frac{e^{jn\pi}+e^{-jn\pi}}{2}-1)=\frac{1}{n\pi}(cos(n\pi)-1)=\frac{1}{n\pi}((-1)^n-1)If n is even, the coefficient is equal to 0, only when it is odd (equal to 2k-1):

c_{2k-1}=-\frac{2j}{(2k-1)\pi}And the function can be represented as:

f(x)=sign(x)=-\frac{2j}{\pi}\sum_{k=-\infty}^{\infty}\frac{e^{j(2k-1)x}}{2k-1}Lets try to check in Octave, if the function we derived still equal to sign shape:

Looks similar, let's make something else I think.

f(x)=sin(8x)+sin(9x)+cos(x)Now the tough part - that function requires solving of the complex integral, which appeared not quite straightforward for Octave. Python looks like using the same quad algorithm came from Fortran. Matlab has that ability, but I dont have an ability to buy Matlab license

So the story is that I ended up with using of a webservice wolfram alpha, and hand calculated coefficients up to 9, still easier than hand calculate on the paper huh?

The code for octave looks like:

```
clf;
clear;
st = pi/256;
step = -pi:st:pi;
y = (sin(8*step)+sin(9*step)+cos(step));
plot(step,y)
hold on;
n = 9;
c_p(1) = 0.5;
c_p(2) = 0;
c_p(3) = 0;
c_p(4) = 0;
c_p(5) = 0;
c_p(6) = 0;
c_p(7) = 0;
c_p(8) = -0.5*j;
c_p(9) = -0.5*j;
c_n(1) = 0.5;
c_n(2) = 0;
c_n(3) = 0;
c_n(4) = 0;
c_n(5) = 0;
c_n(6) = 0;
c_n(7) = 0;
c_n(8) = 0.5*j;
c_n(9) = 0.5*j;
y_aprox = 0;
for i = 1:n
y_aprox = y_aprox + c_p(i)*exp(j*i*step) + c_n(i)*exp(-j*i*step);
endfor
plot(step, y_aprox)
legend("original", "approximated")
hold on
grid on
```

It is enough to fully represent the curve:

Looks right, but it is a pity that octave doesn't allow to make a complex integration. Or maybe not, if it will not impact the FFT by itself, will see.

]]>**Compiler**: Hi-TECH PICC

**Goal**: To make pulses with frequency 5Hz

Timer TMR0 module frequently used in many applications, it has next useful options:

- 8 bits counter/timer
- Internal/external oscillator for pulses counting
- An interrupt is generated after overflow

In that experiment we will make it without using interruptions.

The main diagram can be observed in the official datasheet from the microchip site (that’s where I got the one from beginning). All main setup/whistles can be found in OPTION register.

Looks like we have got everything we need. So from the goal we need to achieve 5 Hz pulses, or a duration 200ms. We have XTAL oscillator 4MHz, so the timer is getting 4/4 = 1 MHz or the 1 us pulse. So whole timer is 8 bit or can make 256 “ticks”, which are equal to 256us, while we need to get 200ms. We have two choices – one is to use a prescaler connected to timer TMR0 module, or the second one – to use extra variable in a similar role. When I wrote the original of that post in Russian language, I did that with the use of the variable. At the current moment of time – I don’t like that decision, but, in order to make everything aligned, I will just translate that code here:

```
#include <htc.h>
#define _XTAL_FREQ 4000000
__CONFIG(WDTDIS & UNPROTECT & MCLREN);
unsigned char cnt = 0;
unsigned char i = 0;
unsigned char srb = 0;
void main() {
TRISB = 0b01111111;
RB7 = 0;
for (;;) {
OPTION = 0b11010111; // counting 256 us
for (i=1;i<4;i++) { // 192 мus
TMR0 = 0;
while (TMR0 < 250) { cnt++; }
}
OPTION = 0b11010100; // now counting 32 us
TMR0 = 0; cnt = 0;
while (TMR0 < 250) {cnt++;} // 8 ms
srb = !srb;
RB7 = srb;
}
}
```

Let’s see now what we got in proteus!

1 square is 25ms, we have 8 of them or 25*8 = 200 ms. Looks like everything works fine.

The source code for that experiment can be found here.

]]>**Compiler**: Hi-TECH PICC

**Goal**: To connect button and learn how to enable IO

One from simplest things you can try with microcontroller – to connect button and make uC to do what you want.

Just a simple code there:

```
#include <htc.h>
#define _XTAL_FREQ 4000000 //Clock 4MHz
__CONFIG(MCLREN & WDTDIS & UNPROTECT);
unsigned char sRB1=0; //led is off initially
void main() {
TRISB = 0b11111101; // B2 output
RB1 = 0; // make В1 0
for (;;) {
if (RB0 == 0) {
__delay_ms(30); //debounce
if (RB0 == 0) { sRB1 = !sRB1;}
}
RB1 = sRB1;
}
}
```

Debounce is realized with delay macro, easy not optimal, but easy…

]]>**Compiler**: Hi-TECH PICC

**Goal**: To make led blink with certain frequency

The most simple thing you can do probably and see a result immediately – to make microcontroller drive your led with certain frequency. Theoretically LED can be connected directly to uC pin, it depends from certain microcontroller, some of them can drive as much as 50mA of output power, but the most safe thing – to connect it through “driver amplifier”. Here, I used npn BC847B transistor as a common emitter amplifier, R1 serves as base current limiter, R2 as the LED current limiter. The current thru LED can be simply calculated as:

(VDD - V_d)/R_2

There can be used pnp and nMOS or pMOS transistor as well, doesn’t matter. It is just a buffer. Please notice, that Vd voltage actually depends from LED type you use, so you need to refer to the datasheet of an available part.

First of all, to make it blink with certain frequency we need to let uC know the osc frequency:

`#define _XTAL_FREQ 4000000`

So we have 4MHz XTAL frequency and now uC knows that.

*Short notice:* *we have the osc freq 4 MHz, then following divider by 4, so our uC resulting frequency is 1MHz. Next, a macros _delay(n) can do only 197120 cycles, so the maximum delay we can get within that macros is 197.12 ms.*

As the next step, we need to configure the uC properly, it can be done with configuration setup in Hi-TECH PICC:

`__CONFIG(MCLREN & UNPROTECT & WDTDIS);`

- MCLREN – enable reset by MCLR pin (make sure that this pin is tied properly in your circuit, otherwise the program will be a whole time in the reset
- UNPROTECT – do not protect the code, so it can be decompiled
- WDTDIS – disable watchdog, that is an extremely useful feature which usually used by everyone to check if our microcontroller is not frozen, but for that super simple piece of the code we don’t need that definitely

All right, very simple, let’s just take a look on the whole code we have:

```
#include <htc.h>
#define _XTAL_FREQ 4000000 // Frequency 4 MHz
// Config: ext reset, no code protect, no watchdog
__CONFIG(MCLREN & UNPROTECT & WDTDIS);
unsigned char i; // just a variable
void main() {
TRISB = 0x00; // Whole B port configured as an output
PORTB = 0x00; // Set all B pins to 0
for (;;) { // run endless for loop
RB0 = 0;
__delay_ms(100); // pause 200 ms
__delay_ms(100);
RB0 = 1;
// the loop to make 800ms delay
for ( i = 0; i < 8; i++) {
__delay_ms(100);
}
}
}
```

I would like to note that using of _delay(n) macrosses is not quite good way to program uC, rather you should use hardware timers, which are way more reliable.

]]>