Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 38

Final Portfolio

Ben Barukh
Instructor: Brian Rasnow, Ph.D.
December 9, 2022

Contents
1|Page
Lab 1 - LED Nightlight....................................................................................................................4
Objective......................................................................................................................................4
Methods.......................................................................................................................................4
Finding the LED’s I-V curve and characteristics: Vf and I......................................................4
Finding the Wall Wart’s characteristics: Vth and Rth...............................................................4
Designing a circuit that operates at the desired I.....................................................................4
Construction techniques...............................................................................................................4
Results..........................................................................................................................................5
LED I-V curve and Vf..............................................................................................................5
Wall Wart’s Thevenin equivalent............................................................................................5
Final schematic and explanation..............................................................................................5
Validation – measurements of all the V’s and I’s in the circuit..............................................6
Pictures of a nicely soldered operating LED nightlight...........................................................7
Discussion....................................................................................................................................7
What worked, what didn’t, why? Any surprises?....................................................................7
How did theory and measurements agree and/or disagree?.....................................................7
How much power will your night light use, and what is its monthly cost to use? How can
you further reduce that cost and should you?..........................................................................7
Lab 3 - Auto IV curve......................................................................................................................8
Objective:.....................................................................................................................................8
Methods:......................................................................................................................................8
Results:......................................................................................................................................10
Discussion:.................................................................................................................................12
Appendix....................................................................................................................................13
Lab 4 - Transistor HFE..................................................................................................................13
Objective........................................................................................................................................13
Methods.........................................................................................................................................14
Hardware Interface....................................................................................................................14
Software Interface......................................................................................................................15
Data Interface.............................................................................................................................16
Results............................................................................................................................................16
Discussion......................................................................................................................................21
Appendix........................................................................................................................................21
Lab 5 - Arduino Controlled DC Power Supply.............................................................................22
Objective:.......................................................................................................................................22
Methods:........................................................................................................................................22
A. Hardware interface................................................................................................................22
B. Software interface.................................................................................................................23
C. Data interface........................................................................................................................24
D. Calibration............................................................................................................................25
E. Testing...................................................................................................................................26
Results:..........................................................................................................................................27
A. Pictures of the prototype and wired hardware interface.......................................................27

2|Page
B. Calibration data (showing voltage vs. PWM value), and polyfit..........................................28
C. Testing -- data showing the error in voltage output vs. v command ....................................30
Discussion:.....................................................................................................................................31
Appendex:......................................................................................................................................31
Lab 7 - RC Bode plot.....................................................................................................................32
Objective:.......................................................................................................................................32
Methods:........................................................................................................................................32
Hardware....................................................................................................................................32
Software.....................................................................................................................................34
Results:..........................................................................................................................................35
Validation of the system............................................................................................................35
Bode Plot data............................................................................................................................36
Discussion:.....................................................................................................................................38
Conclusions:..................................................................................................................................38
Possible Future Modifications.......................................................................................................38
Appendix........................................................................................................................................38
Arduino Code.............................................................................................................................38
oscope5.m..................................................................................................................................39

Lab 1 - LED Nightlight


Objective
The objective of this lab it to turn a wall wart into an LED nightlight. Using a wall wart, and
LED, and resisters, to create a night light that can be plugged into a wall socket. And calculating
characteristics of the different components, such as the I-V curve of the LED and the Thevenin
resistance and voltage of the wall wart.

Methods
Finding the LED’s I-V curve and characteristics: Vf and I
Using the simple circuit to the right to find Vf, by measuring the
voltage across the LED using a multimeter and finding I by adjusting the
potentiometer and using Ohm’s law R=IV and finding the new R also
using the multimeter. To create the curve, we find corresponding I-V’s and
place them along the graph.

Finding the Wall Wart’s characteristics: Vth and Rth


The wall wart’s approximate characteristics are printed on the label. To get the actual
output voltage, the Vth, I used a multimeter to read the voltage actually being outputted. To get
RL
the Rth I used the formula V L=V th , with RL having a resistance of ~100 ohm and VL is
R L + R th
the voltage measured across RL.

3|Page
Designing a circuit that operates at the desired I
When designing for a nightlight, I kept in mind that while the
light had to be active, it also could not be too bright, so using the graph
that was provided, and from the internet to the right, I was able to get a
general idea and calculation of minimum safe resistances for each type
of LED. I thought it would be best to aim for the Vf that would
intersect with a I just above the knee, and not go below it so that the
light would light up, but not be too bright of a nightlight.
V V
For the current have to keep in the I = and R= forms of
R I
ohm’s law to find an amount of resistance they will fulfill the needs of
the nightlight safely.

Construction techniques
The pre-construction/testing phase I used a solder less bread board to test different
resistances to see what would be best for the night light within my range. After that, having
chosen the proper resistance I clipped the old connectors off the wall wart, I soldered the resistor
and LED in series on to it and finally wrapped the exposed wires.

Results
LED I-V curve and Vf >> %% RED LED I-V curve
% 6 SEP 22 BEN BARUKH
data = [ ... % Vr Vd
00
.965 1.84
1.39 1.86
I VF W 2.051 1.89
0 0 X 4.177 1.95
0.96 1.84 % 0 -12.21
5
10.81k
];
1.39 1.86 7.49k [foo, indx] = sort(data(:,1));
2.05 1.89 data = data(indx,:);
1
5.064k Vr = data(:,1);
4.17 1.95 Vd = data(:,2);
7
2.473k Rmin = 1015; % ohms
Id = Vr / Rmin * 1000; % mA
plot(Vd, Id, 'o-');
xlabel('V/volts');
ylabel('I/mA');

Wall Wart’s Thevenin equivalent

RL 99.6
V L=V th  12.20=12.28  Rth =0.653
R L + R th 99.6+ R th

4|Page
Final schematic and explanation

The final schematic of the circuit shown to the left.


I chose 1000 W because it provided the desired brightness for
the nightlight, and in comparison at that same resistance the
blue LED is much brighter, and the green much dimmer.
When designing this nightlight, I did not design I child’s fear
of darkness in mind, more rather needing to walk around in a
dark room and not fall because I can’t see the floor. Also, I
chose the red because I have read the blue light can disrupt a person’s quality of sleep. In the
preparation phase I found the lower in resistance I went the brighter the LED, but also the hotter
the resistors got. I found that if the LED is to be brighter Resistors would have to be put in
parallel, because just using smaller resistances would result in a single resister heating up which
can be dangerous.

Validation – measurements of all the V’s and I’s in the circuit

5|Page
Pictures of a nicely soldered operating LED nightlight

Discussion

What worked, what didn’t, why? Any surprises?


When testing out LED colors I was surprised to find when using all same components
aside from swapping the led the brightness from mot to least was blue, red, green, but accord to
some calculations I did it should have been blue, green, Red.

How did theory and measurements agree and/or disagree?


I originally thought less resistance would bean less heat but I was wrong in this
assumption, because as resistance went up the current went down. Other than that, my theory and
measurements otherwise agreed.

6|Page
How much power will your night light use, and what is its monthly cost to use? How can you
further reduce that cost and should you?
In California power costs 28.98 cents per kWh, and power (P) is P=V2/R so

P=0.15Watts

While this is a great price hypothetically if you wanted to further reduce the cost you can either
reduce the voltage or increase the resistance, when looking at the power formula I used.

Lab 3 - Auto IV curve


Objective:
The objective is to build a circuit using an Arduino microcontroller to measure the I-V
characteristic curves of LEDs and resistors, through automation. Then, to use MATLAB to
create plots and graphs to assist in analyzing the data.

Methods:

Below is shown the circuit for automating the input of the IV-curves and the code used for the
Arduino. The scemstic of the power supoply can be found in the appendex at the dewnd of this
document.
void setup() {
Serial.begin(9600);
pinMode(5, INPUT_PULLUP);
}

void loop() {
if(analogRead(A0)) //turnes on
when pwer is activated
{
Serial.print(analogRead(A0));
Serial.print('\t');
Serial.println(analogRead(A1));
}
delay(200); //milli sec
} //loop

R1 is meant to be a buffer between the higher voltages and the LED, and during the
nightlight lab I learned that having a resistance of about 1k ohms is a safe and reliable resistance

7|Page
for the LEDs I have. R4 and R5 act as protective buffers for the Arduino, as the Arduino nano
that is being used can only handle voltages approaching 5V. R2 and R3, both act as a voltage
divider that connects to R5 and in turn the Arduino.

Image 1 shows the board running at maximum voltage, where as image 2 shows it running at
minimum voltage, both with the red LED. Image 3 contains a close up for the circuit shown in
the schematic above.

img.1 img.2 img.3

Matlab code for generating plots


Input voltages
vref = 4.56; % volts
R1 = 1015; % ohms
R2 = 20.11e3; % ohms
R3 = 9.94e3; % ohms
data = [... % A0 A1
XXX XXX
XXX XXX
] * vref / 1023;
% first peek at raw data
plot(data, '.-'); grid;
xlabel('sample #'); ylabel('voltage');
legend('A0','A1');
IV curve
%[attach to end of previous code chunk]
vd = data(:,1); % diode voltage
vin = data(:,2) * (R2+R3)/R3;
i = (vin - vd) / R1 * 1000; % mA
plot(vd, i,'.-'); grid;
xlabel('volts'); ylabel('mA'); title('i-v curve');

%save results for later use


if ~exist('varname','var'),varnames = {}; end
dev = input('name this device: ', 's');
cmd = ['v' dev '=vd; i' dev '=i;']; % or sprintf
disp(cmd); eval(cmd);
varnames{length(varnames)+1} = dev;

1; % set breakpoint here.


Combining all the plots

8|Page
cmd = 'plot('; % the first part
for i=1:length(varnames) % add each v,i pair
cmd = [cmd sprintf('v%s,i%s,', varnames{i},varnames{i})];
end
cmd = [cmd(1:end-1) ');']; % delete last comma
disp(cmd);
disp(cmd);
eval(cmd);
legend(varnames); % that was easy!!
xlabel('volts'); ylabel('mA'); title('measured i-v curves')
grid;

The full process I went through was first to collect the data points of each IV curve. I stored each
set on an Excel sheet. Next, was to use the MATLAB code above to generate the input voltages,
IV curves, then a combined plot containing all IV curves.

Results:
I am also including an Excel sheet with all the data point I’ve collected during tested, it includes
all five LEDs and 100 ohm, 220 ohm, 560 ohm resistors.
Blue
LED

Green
LED

9|Page
Yello
w
LED

White
LED

Red
LED

10 | P a g e
100
Ohm

220
Ohm

560
Ohm

11 | P a g e
Discussion:
A characteristic curve is defined as a graph showing the relationship between two variable but
interdependent quantities, which in this case are the current and voltage. With LEDs of the same
color like blue/white the graphs hold closely the same with differences most likely being due to
noise, human error, or other such factors. LEDs of other colors appear on other points of the
graph, and the resistors appear on different points as well. The LEDs appear to have an
exponential shape to them, where as the resistors are more linear. The slopes I got for the
100ohm, 220ohm, and 560 ohm resisters, are 34.29R, 15.62R, and 6.34R respectively.

Appendix
This is the adjustable LM317 driven power supply used during the course of this lab.

12 | P a g e
Lab 4 - Transistor HFE

Objective
Measure the current gain of an NPN transistor, using ic/ib=hfe. Also to automat the process as much a
possible.

Methods
Hardware Interface

Figure 1: various angles of the HFE circuit on the test board.

Figure 2: the design schematic of the circuit the transistor used is a NPN S8050. The schematic of the power
supply can be Found in Figure A, in the appendix.

13 | P a g e
The specific board type being used is the ProMini328_5V.

Software Interface

Figure 3: the code used for collecting the data through the Arduino.

The circuit is built so when the button is pushed pin D5 is connected to ground and the Arduino starts taking in
data.

Data Interface
Connecting the Arduino to Matlab, and taking in data:

To detect and get the properties of the board use:

ard = arduino('COM5','ProMini328_5V');

For taking in the data use:

data = {readVoltage(ard,'A0'), readVoltage(ard,'A1'), readVoltage(ard,'A2')};


while(readDigitalPin(ard,'D5')==0)
tmp = {readVoltage(ard,'A0'), readVoltage(ard,'A1'), readVoltage(ard,'A2')};
data = cat(1,data,tmp);
end
data = cell2mat(data);

14 | P a g e
Results
data = {readVoltage(ard,'A0'), readVoltage(ard,'A1'), readVoltage(ard,'A2')};
while(readDigitalPin(ard,'D5')==0)
tmp = {readVoltage(ard,'A0'), readVoltage(ard,'A1'), readVoltage(ard,'A2')};
data = cat(1,data,tmp);
end
data = cell2mat(data);
plot(data);
xlabel('sample #'); ylabel('Volts');
legend('A0','A1','A2');
title('quick look at "raw" data')

Figure 3. First look at raw data from the Arduino.

vref = 4.59; % volts


Rb = 1e6; % base resistor, R4, ohms
Rc = 1105; % collector resistor, R1, ohms
vce = data(:,1); % collector-emitter voltage
vbe = data(:,2); % base-emitter voltage
vin = data(:,3);
ib = (vin-vbe)/Rb * 1e6; % base current in uA
ic = (vref-vce)/Rc * 1000; % collector current in mA
plot(ib, ic,'d-')
grid; xlabel('base current/\muA');
ylabel('collector current/mA')

15 | P a g e
Figure 4. Relation between base and collector currents (with Rc = 1k) is very linear above the lowest currents
(bottom left).

p = polyfit(ib(ib>.1), ic(ib>.1), 1); % help polyfit for more info


fprintf('beta = %.1f\n', p(1)*1e3)
beta = 283.4

ib1k = ib; ic1k = ic; beta(1) = p(1)*1e3;


Rc = 666; % ohms
data2 = {readVoltage(ard,'A0'), readVoltage(ard,'A1'), readVoltage(ard,'A2')};
while(readDigitalPin(ard,'D5')==0)
tmp = {readVoltage(ard,'A0'), readVoltage(ard,'A1'), readVoltage(ard,'A2')};
data2 = cat(1,data2,tmp);
end
data2 = cell2mat(data2);
vce = data2(:,1); % collector-emitter voltage
vbe = data2(:,2); % base-emitter voltage
vin = data2(:,3);
ib = (vin-vbe)/Rb * 1e6; % base current in uA
ic = (vref-vce)/Rc * 1000; % collector current in mA
plot(ib, ic,'d-')
grid; xlabel('base current/\muA');
ylabel('collector current/mA')

16 | P a g e
Figure 5: replacing Rc with 10k

p = polyfit(ib(ib>.1), ic(ib>.1), 1); % help polyfit for more info


fprintf('beta = %.1f\n', p(1)*1e3)
beta = 290.5

ib681 = ib; ic681 = tic; beta(2) = p(1)*1e3; % save the former results
Rc = 10.03e3; % collector resistor
data3 = {readVoltage(ard,'A0'), readVoltage(ard,'A1'), readVoltage(ard,'A2')};
while(readDigitalPin(ard,'D5')==0)
tmp = {readVoltage(ard,'A0'), readVoltage(ard,'A1'), readVoltage(ard,'A2')};
data3 = cat(1,data3,tmp);
end
data3 = cell2mat(data3);
vce = data3(:,1); % collector-emitter voltage
vbe = data3(:,2); % base-emitter voltage
vin = data3(:,3);
ib = (vin-vbe)/Rb * 1e6; % base current in uA
ic = (vref-vce)/Rc * 1000; % collector current in mA
plot(ib, ic,'d-')
grid; xlabel('base current/\muA');
ylabel('collector current/mA')

17 | P a g e
Figure 6. Collector vs. base currents with Rc = 10k which causes the BJT to saturate around ic = .45mA.

ib10k = ib; ic10k = ic; % for consistency


plot(ib681,ic681, ib1k,ic1k, ib10k, ic10k);
grid;
xlabel('base current/\muA');
ylabel('collector current/mA')
legend('681\Omega','1k','10k','location','best');
title('varying R_C')

18 | P a g e
Figure 7. Superposition of Figs. 3-5, all values of Rc show similar slope before saturation.

indx = ic > .1 & ic < .8*max(ic); % a different filter


p = polyfit(ib(indx), ic(indx), 1);
beta(3) = p(1)*1e3;
fprintf('beta = %.1f\n', beta(3))
beta = 253.0

vref / Rc * 1000 % mA
ans = 0.4576

max(ic)
ans = 0.4479

Discussion

fprintf('beta = %.0f±%.0f\n',mean(beta), std(beta))


beta = 273±18

19 | P a g e
Appendix

Figure A: design schematic of the power supply.

Lab 5 - Arduino Controlled DC Power Supply


Objective:
the objective is to create an Arduino controlled DC Power Supply, using our previously made Power supply

Methods:
A. Hardware interface.

The figures above show the schematics. The purpose of the power supply is to provide the main source of
power in the circuit. The PWM filter helps to increases the settling time of the voltage coming from the

20 | P a g e
Arduino and the rate at which we can change the voltage, allowing for consistent voltages of different levels to
be produced from the Arduino port. The emitter follower takes the voltage produced from the PWM(and filter)
into its base, and the amount going into the base of the emitter follower helps to determine how much from the
12VDC makes it through the transistor. The resister and potentiometer of the emitter follower restrict the
maximum amount of current going in toot the current mirror.
B. Software interface.
the code within the Arduino:
void measureWaveformsBinary(void);

const int analogOutPin = 5;


int settleTime = 200; // msec
#define NUMSAMP 400
#define MAX_SETTLING_TIME 5000
int data[NUMSAMP + 1][2], i;

void setup()
{
Serial.begin(115200);
pinMode(analogOutPin, OUTPUT);
} // setup

void loop()
{
if (Serial.available())
{
switch (Serial.read())
{
case 'p': // set pwm value
{
int pwmVal = Serial.parseInt();
analogWrite(analogOutPin, constrain(pwmVal, 0, 255));
delay(settleTime);
break;
}
case 'b': // readAndWriteWaveformsBinary
{
measureWaveformsBinary();
break;
}
case 's': // settling time (in msec)
{
int t = Serial.parseInt();
settleTime = constrain(t, 0, MAX_SETTLING_TIME);
break;
}
} // switch
}
delay(1);
} // loop

void measureWaveformsBinary()

21 | P a g e
{
unsigned long t0, t1;
t0 = micros(); // time it to compute sample rate
for (i = 0; i < NUMSAMP; i++)
{
data[i][0] = analogRead(A0);
data[i][1] = analogRead(A1);
}
t1 = micros();
data[i][0] = t1 - t0; // put dt at end of data
data[i][1] = (t1 - t0) >> 16; // most significant 2 bytes
Serial.write((uint8_t*)data, (NUMSAMP + 1) * 2 * sizeof(int));
}

C. Data interface.
This command will have MATLAB find what port the Arduino is connected to, and the one after will allow us
to access it as a variable
ports = serialportlist
ard = serialport(ports(end),115200)

Using the following line of code in the console in Matlab, where volts is equal to the amount of volts you want
the power supply to produce, you can control the voltage produced by the power supply
volts2pwm(volts, ard)

with in this function lies this code


function [pwmVal] = volts2pwm(volts, ard)
% function [pwmVal] = volts2pmw(volts, ard)
% return pwm value corresponding to volts for LM317 arduino ...
% if a serial port is passes as 2nd arg then sends p command
pv = [-0.0526 0.9434 -24.7402 281.5264];
pwmVal = round(polyval(pv, volts));
pwmVal(pwmVal < 0) = 0;
pwmVal(pwmVal > 255) = 255;
if nargin == 2
writeline(ard,['p' num2str(pwmVal)]);
end
end

this calls to the code in the Arduino and modifies the delay
case 'p': // set pwm value
{
int pwmVal = Serial.parseInt();
analogWrite(analogOutPin, constrain(pwmVal, 0, 255));
delay(settleTime);
break;
}

22 | P a g e
D. Calibration.
The following Matlab code was used to collect the calibration data, and compile it into graphs:

to get the experimental data:


vref = 4.62; % volts on vref pin
Vmin = 1.20;
Vmax = 10.2;
R7 = 9.92e3;
R6 = 20.08e3;
flush(ard);
pwm = (50:5:255)'; % 42 different values
v317 = zeros(size(pwm));
tic;
for i=1:length(pwm)
writeline(ard,['p' num2str(pwm(i))]);
pause(.2); % extra time for the voltage to stabilize
runOnce = true;
oscopeV1; % --> new data = [A0 A1]
v317(i) = vref * mean(data(:,2)) / 1023 * (R6+R7)/R7;
end
toc
plot(pwm, v317, '.-'); xlabel('pwm value'); ylabel('DCVout'); grid;

the theoretical data:


%% model 1
R1 = 1400; % ohms measured between LM317 pins 1 and 2 (with power off)
R2 = 10.8e3; % max ohms measured between ground and *unconnected* terminal
R5 = 3.4e3 ; % R5+R11, calling it R5
T1baseVoltage = pwm * vref / 255; % the PWM filter's gain = 1 at DC
T1emitterVoltage = T1baseVoltage -.6; % Vbe in saturation
T2collectorVoltage = 0.6;
iMirror = (T1emitterVoltage-T2collectorVoltage) / R5;
% if T1 isn't conducting then iMirror = 0:
iMirror(T1baseVoltage < 0.6 + T2collectorVoltage) = 0;
iR1 = 1.25/ R1; % A, from LM317 datasheet. 50uA from iADJ
iR2 = iR1 - iMirror ; % KCL says iR1 = iR2 + iMirror
VR2 = iR2 * R2;
DCVout = VR2 + 1.2;
% the output is always less than input voltage - dropout voltage
DCVout(DCVout < 1.2) = 1.2; % Vmin
plot(pwm, [v317 DCVout],'.-');
xlabel('PWM value'); ylabel('DCVout');
grid; axis tight;
legend('experiment','theory')

%% model 2, with hfe


hfe = 240; % estimated
T1baseVoltage = pwm * vref / 255 * (R5*hfe)/(R5*hfe+22e3); % see below

23 | P a g e
T1emitterVoltage = T1baseVoltage -.6; % Vbe in saturation
iMirror = (T1emitterVoltage-T2collectorVoltage) / R5; % A
% if T1 isn't conducting then iMirror = 0:
iMirror(T1baseVoltage < 0.6 + T2collectorVoltage) = 0;
iR1 = 1.25 / R1;
iR2 = iR1 - iMirror; % KCL says iR1 = iR2 + iMirror
VR2 = iR2 * R2;
DCVout2 = VR2 + 1.25;
DCVout2(DCVout2 > Vmax) = Vmax;
DCVout2(DCVout2 < 1.2) = 1.2; % Vmin
plot(pwm, [v317 DCVout DCVout2]);
xlabel('PWM value'); ylabel('DCVout');
dots; grid; axis tight;
legend('experiment','theory1','theory2')

%% model 3, with IAdj added


hfe = 240; % estimated
iAdj = 20e-6; % amps estimated
T1baseVoltage = pwm * vref / 255 * (R5*hfe)/(R5*hfe+22.2e3); % see below
T1emitterVoltage = T1baseVoltage -.6; % Vbe in saturation
iMirror = (T1emitterVoltage-T2collectorVoltage) / R5; % A
% if T1 isn't conducting then iMirror = 0:
iMirror(T1baseVoltage < 0.6 + T2collectorVoltage) = 0;
iR1 = 1.25 / R1;
iR2 = iR1 + iAdj - iMirror; % KCL
VR2 = iR2 * R2;
DCVout3 = VR2 + 1.2;
DCVout3(DCVout3 > Vmax) = Vmax;
DCVout3(DCVout3 < 1.2) = 1.2; % Vmin
plot(pwm, [v317 DCVout DCVout2 DCVout3]);
xlabel('PWM value'); ylabel('DCVout');
dots; grid; axis tight;
legend('experiment','theory1','theory2','theory3')
E. Testing
By connecting a volt meter to my red and black jumpers I can see what the meter says v. what I input.

24 | P a g e
Results:
A. Pictures of the prototype and wired hardware interface.

25 | P a g e
B. Calibration data (showing voltage vs. PWM value), and polyfit.
With PR being the potentiometer resistance of the emitter follower, being changed experimentally:

PR=2.38k

26 | P a g e
PR=3.93k

PR=1.50K

27 | P a g e
By seeing how adjusting the potentiometer effects the slope, I can adjust it to be in a good range of the poly fit
data.

In the volts2pwm code, changing

pv = [-0.0526 0.9434 -24.7402 281.5264];

to

pv = [-0.0933 0.95 -24.75 285];

does not make too much of a difference, but in the case of my board it brings the output closer to the desired
values, in this case it lined up the input of 5 volts to be the output. What can be gained from this is that after
tinkering with the variables, i can come closer to something that will be near one to one when inputting the
function.
C. Testing -- data showing the error in voltage output vs. v command .
The following is some tasting data showing the error in the command, with the emitter follower turn pot at
2.3k

volts2pwm(volts, ard); meter; board

volts2pwm(11, ard); 10.22v; 10.2v

volts2pwm(7, ard); 6.8v; 6.8v

volts2pwm(5, ard); 4.96v; 4.964

28 | P a g e
volts2pwm(3, ard); 3.2v; 3.2v

volts2pwm(1, ard); 1.58v; 1.56v

Discussion:
Something that I learned, is that similar to the potentiometers function in the power supply, my manipulating
the one in the emitter follower I can change the lower limits of the slope, as seen in the calibration data. All of
this dose come up to the end conclusion that through the Arduino, and receiving commands through MATLAB
the power supply voltage can be manipulated digitally.

Appendix:
oscopeV1 code:
%% script oscopeV1.m -- first version of an Arduino oscilloscope display
% 16oct22 BR, Arduino running oscope1, command set = b, p, s
if ~exist('runBtn','var') % add the button once
runBtn = uicontrol('style','radiobutton','string','run','units', ...
'normalized','position',[.13 .93 .1 .04]);
runBtn.Callback = 'oscopeV1';
end
if ~exist('ard','var') % initalize arduino
disp('initializing arduino ...')
ports = serialportlist;
ard = serialport(ports{end},115200);
ard.Timeout = 2;
clear ports;
pause(1); % time to boot
end
if ~exist('runOnce','var')
runOnce = false;
end

while runBtn.Value || runOnce


write(ard,'b','char');
bin = read(ard,802,'int16');
dt = bitshift(bin(802),16)+bin(801); % microseconds
data = reshape(bin(1:800),2,400)';
t = linspace(0,dt/1000,400)'; % calibrate the time axis
if ~exist('plotHandle','var') % first time plot and label
plotHandle = plot(t, data, '.-');
xlabel('msec'); ylabel('ADU')
legend('A0','A1');
else % change data inside the plot is faster
set(plotHandle(1),'XData',t,'YData',data(:,1));
set(plotHandle(2),'XData',t,'YData',data(:,2));
end
displayfps;
drawnow;
runOnce = false;
end

29 | P a g e
Lab 7 - RC Bode plot
Objective:
The objective is to measure the frequency response (aka the Bode Plot) of an R-C Series Circuit, with the
assistance of the XR2206 function generator and Arduino in tandem. And also, to make sad function generator
automated.

Methods:
Hardware

Fig.1 the schematic of the automated frequency generator. (the order of stages from D5 to R6 should be read
left to right.)

30 | P a g e
Fig.2(a,b) the board after soldering a connector pin to R6 so it can connect to the current mirror/Arduino.

Both because I difficulty installing the connector through the top of the f-gen board and to keep it looking
clean, I removed the generator to add a wire out the bottom using save excess from other components to
connect to the orange jumper seen in the middle of the board, keeping most, with the exception of the white
jumpers, at the center range. having the wire available through the bottom opens up the possibility for
hardwiring components more cleanly.

31 | P a g e
Fig.3 shows the prototype of the functioning automated function generator.

To find the corner frequency or the mid usable range of the current junction:
R1 = 4.645e3; % ohms measured with DMM
C1 = 97.5e-9; % farads with DMM
fc = 1/(2*pi*R1*C1);
fprintf('corner frequency expected at %.1fHz\n',fc);
Software
The following function is used to control the PWM (pulse with modulation) produced by the Arduino that in
turn drives the function generator.
function [pwmVal] = freq2pwm(freq, ard)
% function [pwmVal] = volts2pmw(freq, ard)
% return pwm value corresponding to freq (Hz) for XR2206 arduino control
% using the identical current mirror circuit built for the LM317 and
% volts2pwm function
% if a serial port is passes as 2nd arg then sends p command
pf = [-4.7600 21.0615 -37.4208 145.0802 -100.4311];
pwmVal = round(polyval(pf, freq / 1e3)) + 150;
pwmVal(pwmVal < 0) = 0;
pwmVal(pwmVal > 255) = 255;
if nargin == 2
writeline(ard,['p' num2str(pwmVal)]);
end
end

Controlling the frequency though the console can be done by using

freq2pwm (f, ard)

where f is equal to what ever frequency you want the generator to produce.

32 | P a g e
further code used such as oscope5 and the Arduino code can be found in the appendix.

The MATLAB code used to fin the bode plots are as follows,
%% measure Bode plot data for an RC series circuit
writeline(ard, 'p 5');
pause(1); % time to stabilize
tic;
setFreqs = linspace(30,1650,50)'; % low and high frequency and npts
amplitudes = zeros(length(setFreqs), 2); % allocate storage for results
freqs = zeros(size(setFreqs));
for i = 1:length(setFreqs)
freq2pwm(setFreqs(i),ard);
pause(.5);
runBtn.UserData = true; % runOnce
oscope5;
freqs(i) = dat.freq;
amplitudes(i,:) = dat.ampl;
fprintf('|'); % simple progress indicator
end
toc
clear i
freq2pwm(setFreqs(1),ard); % let it rest at lowest f
figure; % take a quick peek at raw data
plot(freqs,abs(amplitudes),'-o'); grid;
xlabel('Hz'); ylabel('amplitude/ADU')
legend('|A0|','|A1|')
print -djpeg bodeRAW.jpg % save figure as jpg file
%% analysis (remember, the amplitudes are complex numbers)
vr = amplitudes(:,1)-amplitudes(:,2); % voltage across R1
vc = amplitudes(:,2); % voltage across C1
vr = vr ./amplitudes(:,1); % divide by Vo normalizes vr to a gain
vc = vc ./amplitudes(:,1); % divide by Vo normalizes vc to a gain
figure;
bodePlot(freqs,[vr vc],fc)
legend('Vr','Vc','location','best')
print -djpeg bodePLOT.jpg % save figure as jpg file

Results:
Validation of the system
The circuit was validated by using freq2pwm in the console, and trying out various frequencies, and observing
changes in oscope5.

33 | P a g e
Bode Plot data

Fig.4 this is the raw data received by running the test.

Fig.5 this shows the Bode plots, amplitude and degrees, calculated from the raw data

34 | P a g e
Fig.6 this chows the data received compared to the theoretical. as can be seen, the two are very near identical,
nearly indistinguishable.

Fig.7 this is the percent error between the measured and the theoretical, and shows that the error is around
0.03%.

35 | P a g e
Discussion:
Looking at the data I would say the that the creation of the bode plot was a success. The data and theory run a
very close match with an error between -0.035% and +0.025%.

Conclusions:
What I took away from this is how to create Bode Plots, and a better understanding of using PWM to drive can
control circuits.

Possible Future Modifications


If I could find a three way switch, where it has connection 1, off, and connection 2, I would add that to the
board and ard wire the automation components in order to switch between automated F-Gen and automated
power supply.

Appendix
Arduino Code
/* file: oscope1.ino COMMAND SET
b -- measure a buffer of A0 and A1 appended with read time in microseconds, return in binary
p <pwmValue> write pwmValue to D5
*/
void measureWaveformsBinary(void);

const int analogOutPin = 5;


int settleTime = 200; // msec
#define NUMSAMP 400
int data[NUMSAMP + 2][2], i;
unsigned long t0, t1;

void setup()
{
Serial.begin(115200);
pinMode(analogOutPin, OUTPUT);
} // setup

void loop()
{
if (Serial.available())
{
switch (Serial.read())
{
case 'p': // set pwm value
{
int pwmVal = Serial.parseInt();
analogWrite(analogOutPin, constrain(pwmVal, 0, 255));
delay(settleTime);
break;
}
case 'b': // readAndWriteWaveformsBinary

36 | P a g e
{
measureWaveformsBinary();
break;
}
}
} // switch
delay(1);
} // loop

void measureWaveformsBinary()
{ // Measure as fast as possible NUMSAMP on A0 and A1
// return data and time in binary format
// 31oct22 BR: adding 1 to all data values, so we can use a 0 as terminator.
// Otherwise, data that equals default terminator (LF=10) stops the read.
t0 = micros(); // time it to compute sample rate
for (i = 0; i < NUMSAMP; i++)
{
data[i][0] = analogRead(A0) + 1;
data[i][1] = analogRead(A1) + 1;
}
t1 = micros();
data[i][0] = t1 - t0; // put dt at end of data
data[i][1] = (t1 - t0) >> 16; // most significant 2 bytes
data[++i][0] = 0; // terminator
data[i][1] = 0; // terminator
Serial.write((uint8_t*)data, (NUMSAMP + 2) * 2 * sizeof(int));
} // measureWaveformsBinary

oscope5.m
if ~exist('runBtn','var') || ~isvalid(runBtn) % add the button once
runBtn = uicontrol('style','radiobutton','string','run','units', ...
'normalized','position',[.13 .93 .1 .04]);
runBtn.Callback = 'oscope5';
runBtn.UserData = true; % using this field for runOnce
end
if ~exist('ard','var') % initalize arduino
disp('initializing arduino ...')
ports = serialportlist;
ard = serialport(ports{end},115200);
ard.Timeout = 2;
configureTerminator(ard, 0);
clear ports;
pause(2); % time to boot
end

while runBtn.Value || runBtn.UserData


writeline(ard,'b');
try
dat.bin = read(ard,804,'int16');
dat.dt = bitshift(dat.bin(802),16)+dat.bin(801); % microseconds
dat.raw = reshape(dat.bin(1:800),2,400)' - 1;

37 | P a g e
[dat.data, dat.npds] = trim(dat.raw, 440, -1, 1); % adjust 2nd arg = ADU with steepest slope
dat.t = linspace(0,dat.dt/1000,400)';
dat.t = dat.t(1:length(dat.data));
dat.sr = length(dat.raw)/dat.dt*1e6; % sample rate (#/sec)
dat.freq = dat.sr/(length(dat.data)/dat.npds); % Hz, 1/sec
dat.data = arddeskew(dat.data, 'fourier');
dat.fd = fft(dat.data); % data was trimmed to npds
dat.ampl = dat.fd(dat.npds+1,:) / length(dat.data) * 2;
dat.theta = rad2deg(angle(dat.fd(dat.npds+1,:)));
catch
flush(ard);
break;
end
try % change data inside the plot is faster
set(dat.plotHandle(1),'XData',dat.t,'YData',dat.data(:,1));
set(dat.plotHandle(2),'XData',dat.t,'YData',dat.data(:,2));
dat.plotHandle(3).String = sprintf('%.2fHz V1=%.2f V2 = %.2f deg=%.2f', ...
dat.freq, abs(dat.ampl), diff(dat.theta));
catch
dat.plotHandle = plot(dat.t, dat.data, '.-');
xlabel('msec'); ylabel('ADU')
legend('A0','A1'); grid on;
dat.plotHandle(3) = title(sprintf('%.2fHz V1=%.2f V2 = %.2f deg=%.2f', ...
dat.freq, dat.ampl, diff(dat.theta)),'FontSize',12);
end
displayfps;
drawnow;
runBtn.UserData = false; % runOnce
end

38 | P a g e

You might also like