Friday, March 29, 2013

Talking with Matlab

One of the most important skills an experimentalist can have is the ability to collect data efficiently   What better way is there to do this than to have a computer collect and store the data?  The great thing about computer-instrument interactions is that you can tell the machine precisely what you want it to do and when.  So I am learning (or rather re-learning) Matlab, in order to be able to communicate with laboratory machines.

First off, a couple of cute exercises to reorient myself into the world of Matlab, I have been using Python for my senior thesis, and it may take a bit of adjusting :)

Exercise 1: Write a MATLAB program that evaluates the following:
Pretty easy, Here is the answer for x=-5, mu=2, and sigma=4 :  0.0216

Exercise 2: Write a function that will compute the Nth Fibonacci number.
Here's what my program found for numbers 1-10:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55

Exercise 3: Imagine that you are the owner of a car rental company with two locations, Albany and Boston. Some of your customers do “one-way rentals,” picking up a car in Albany and returning it in Boston, or the other way around. Over time, you have observed that each week 5% of the cars rented in Albany are dropped off in Boston, and 3% of the cars rented in Boston get dropped off in Albany. At the beginning of the year, there are 150 cars at each location.  Write a Program that takes in a & b and returns the updated values for the week.  What do you think the trend will be?
- I think that it will trend towards some equilibrium.  It did, after 23 Week, the number of cars were 116 and 184.

Exercise 4: write a for loop that will run the program for 52 weeks.  Yup, 116 & 184

Exercise 5: make the program plot the #of Cars at each.  a is red b is blue:


On to the heavy lifting!
______________________________________________________________________________

Serial Communications!
______________________________________________________________________________

First we need to understand how electronics talk to eachother, in bits (0 or 1) strung together in bytes (8bits)
Here is a little diagram for counting with bytes:
The Baud Rate is the number of bits per second.  Using the LogoChip from way back when, I calculated a bit time of ~52sec, or a baud rate of 19,200 bits/second.  If you go into the picoblock source code, you can change the bit time directly, which is pretty neat, but in order to talk to anything, you need to have a standard baud rate.

There is a slight predicament with using bytes, you can only count to 255! If you want to count anything higher, you need more bytes!  A 10 bit number can go up to 1023.  In this case there is a high byte and a low byte, the high byte only uses the first 2 bits, and represents the most significant digits.  To talk back and forth with something, you need to standardize which byte is first, I am using high-low.
If you want to look at negative numbers, the fist bit denotes the sign, 0 is +, 1 is - , and you can only count to 127.

I attached a light sensor to the logo chip, and programmed the chip to read out (in bytes) the value of the light sensor, which was fed to Matlab.  Matlab can read or write bytes, once you set up the port, <s= serial('COM4');> for example, and you set the baud rate <set(s,'BaudRate',19200);>.  To write a byte you can use <fwrite(s,5)> to write the number 5.  To read, use <value = fread(s,2);> The number you specify is the number of bytes you will read, since I am using 10bit numbers, I need to read 2 bytes to get each number.  This plot shows the light sensor data read into Matlab:  at t=30 I put my hand over the sensor

I also made a program, in which the logo chip would make a LED turn on when Matlab fed it 1, and turn off when fed 0.
______________________________________________________________________________

Matlab and the General Purpose Instrumentation Bus (GPIB)!
______________________________________________________________________________

So a bus is a way for multiple instruments to share the same line (like a public transportation bus lets multiple people go different places)

We are going to use it to control a Function Generator, which will be attached to a speaker.
Connecting to MATLAB is pretty simple.  If you don't know the address of the instrument, use the command "instrhwinfo(‘gpib’, ‘ni’)" and use the ObjectConstructorName: (‘gpib(‘ni’, 0, 10);’)
Then assign it to a variable using : gpib('NI', 0, 10);

The function generator was very simple to talk to,
fwrite(GPIB1, 'output on’);
fwrite(GPIB1, 'apply:square 440, 2.0, 0.0');  %(shape, Frequency, Voltage, DC-offset);

There was a pretty simple script provided, that played octaves on the speaker (Video Below)
But I decided to write a much more exciting program, see if you can guess the song!

Next I created a "Theremin" an instrument that is controlled by the proximity of your hands to the instrument. I'm pretty sure real Theremins use radio wave signals, but my make shift one works by shadows.
Here is a video.  There is a lag between the shadowing and the speaker playing, most likely due to the function generator taking a while to turn on.


The final activity of the my portion of the class was to write a program to read voltages from a Keithley multimeter.  This was done using the command "tmtool" which opens a GUI that makes it very easy to set up and connect with an instrument.  tmtool also generates the code needed to connect to the machine.
Here is a pic of it sampling a sine wave... doesn't look like it because it samples over a discrete interval.



Audio Amplifier

Now for what most people think of when they hear the word Amp! It only took a few weeks ;)

Here is a little video of me whistling into the mic and the oscilloscope recording the response from the amp.

Op Amp Integrator

In addition to basic Math, the op amps can also do calculus!
Here we construct an integrator :
 In this case we need to add a 10MegaOhm resistor in parallel to the capacitor, other wise any small DC offset in the signal will build up in the capacitor and our Vout signal will start to go crazy, (think integral of a horizontal line).




If I were to drive this with a 2V, 500Hz square wave, 
what would I get?

Well, it takes 0.002 s to complete a cycle, if we look at how much V is integrated over the positive half of the cycle, that would be 2V * 0.001s = 0.002V times 1 / RC = 2V.  Which is close to the peak to peak voltage you see in the picture (2.1V).  There is a DC offset though, -0.5V, since the DC gain of the contraption is 100, that means the function generator is off by only 5mV.





Op Amp Limitations

Unfortunately Op Amps are not as perfect as we thought....
There is a slight modification to the "Golden Rules"
1) The op amp will "try" to keep the voltage difference between the terminals equal to a small offset voltage.
2) The op amp will only sink a very small input bias current. (~3pA)

Let's test out some limitations!
Lab 9-1:  Slew Rate -
With a 1kHz square wave, I measured a rising slew rate of  11.5 V/microsecond,
and a falling slew rate of 13.6 V/mircosecond.
The rates were the same for waves from 100kHz - 10Hz

With a 2V sine wave, I surfed frequencies until I found where the output amplitude begins to drop (see pic below), this was 1.5MHz.   At 1.5MHz, a cycle will last 0.667 microseconds, which means the amp has 0.333 microseconds to rise from -2V to +2V.  With the slew rate I found above (11.5), the amp could only rise ~ 3.83 Volts in time. It makes sense that this frequency is were the amplitude begin to be limited.
Horizontal Lines show what V should be

Math with Op Amps

Op (operational, like mathematical operations) Amps can be used to do math with voltages.  For example:
Lab 8-7 Summing Amplifier:
Which will basically add the two signals together, a great way to add a DC offset to an oscillating signal.
Another way to do this?  I will think about that some more and get back to you

Question: What is a circuit that will subtract?

Photodiodes and op amps

The photodiode is basically the opposite of the LED (in fact you can just use the LED! though it will be a little week), instead of emitting a photon for every electron that bases with the current, it will create current for every photon absorbed.  The current is produced going the opposite direction from the diode wired normally.  Here's a schematic from the lab write up:
Unfortunately the current produced will be quite small... good thing we know how to use the Op Amp!!






Lab 8-6: Current to Voltage Converter
a) The Photodiode

Here is the diagram for wiring up the photo-diode, there were some high frequency oscillations (fuzz) which I was able to remove by adding a capacitor (see smaller pic).  After that, you could see the signal from the fluorescent lights much better.  The oscillations are pretty extreme... The output voltage was -10mV with a 100% modulation from the lights (dipped to 0V).  If you covered up the photodiode, the signal dropped to 0.  Looking at the summing junction (x on the diagram), the voltage was always 0, (makes sense right? remember Golden Rule #1?)

b) The PhotoTransistor
The idea is essentially the same, same parts and everything, but this time we wire up the photodiode as a transistor by attaching it to a current source.  This time the output voltage was 2V!  A much stronger signal. With 50% modulation.  Summing junction is still 0V.





Tuesday, March 5, 2013

Amplifiers

Ever wonder how an amplifier works?
If you were to attach a mic directly to a speaker, you wouldn't want any voltage drop along the way.  My little stickman's mic can be thought of as a Thevinin Circuit, with corresponding voltage and a resistance, and the speaker can be thought of the same way, though without a V since it is a passive device.
If you attach the two devices together, it will behave like a voltage divider.  As you know from previous blogs, if you want Vout to be close to Vin, the Zsource has to be MUCH smaller than Zload.  In reality, a speaker's resistance will be extremely low, like 8Ohms, since all it is is a coil of wire next to a magnet, so it will be next to impossible to output a useful sound.  Plus, if you go to a rock concert, you want it to be Loud!!  So how do we make our signal bigger?  With an Amp!
A neat tangent, if you have a long wire running through your house, the wire will pick up an additional signal, that oscillates at 60Hz, from the electric cables in the walls!  This can be a problem, interfering with the signals you want, so the differential amplifier was created:
If you take 2 wires, following the same path so the extra signal picked up is the same, put your desired signal on one of them (aka attach it to you mic), and leave the other without a signal (aka attach to ground), a op amp (a type of differential amplifier) will subtract one from the other then increase the voltage of the signal.
Unfortunately, it will not increase your signal for free, you need to give the op amp a power source and the amp output cannot surpass that source voltage (in fact it will max out a few volts below the power source 12V --> 10.8V)

Here are two "Golden Rules" about Op Amps:
1. With negative feedback in place (attach output to negative input) the output will try to make V- = V+ 
2. Op Amps have HUGE input impedance. Therefore they draw no current.

With these rules, you can figure out how amps will behave in almost any circuit!

Here's a picture of a LM 411 Op Amp, I have labeled the pin numbers and functions:



We did tons of labs on amps, read to see what you can do with them!

Lab 8-1 Open-Loop Test Circuit:
This lab is basically just to get your op amp wired correctly...
I couldn't find a "potentiometer” to play with the voltage, so I just used a triangle wave :) same difference. It changes from +11V to -11V virtually instantaneously:








Lab 8-2: Inverting Amplifier
We used this circuit:
to make an Inverting Amplifier, and drove it with a sine wave.  I calculated a gain of 7.6, and a maximum swing of 9.84V.  I also tried to measure the impedance of the circuit, for an input impedance I got ~1K, and output impedance too small to figure out, I actually tried to use a 1ohm resistor, then read further into the lab manual and realized they actually warn you not to do that, whoops!

Here's the signal I got: 
 (blue is IN yellow OUT)
As you can  see, there is 
a phase switch between in and out
 That's why it's an "inverting" amplifier!
V out = - R2 / R1  * V in




Lab 8-3: Non-inverting Amplifier
You can probably guess what this one will look like.  Here's the wiring:



It looks pretty similar, but notice the voltage is applied to the positive instead of the negative pin. I found a gain of 11 this time, but the resistance was a little wonky.  The Rin was huge, my 1MegaOhm resistor didn't even put a dent in the output! (no surprise, because of golden rule #2)  so I measured Cin.  I did this by finding the f3dB frequency, 20kHz.  RC was 8x10^-6.  As you can see in the graph, the IN and OUT are in phase with one another
Vout  = (1 + R2 / R1)  *  V in 


Lab 8-4: The Op Amp Follower
This one is a very simple idea, If you remember golden rule #1, the amp will try and make the - input the same as the +, so if you think about it, Vout will be exactly the same as Vin.  I also attempted to measure Zin, by adding a 1M resistor, which approximately cut the output signal by half, so Zin ~1M.


Lab 8-5:  Op Amp Current Source
In this experiment, we used a cute little blue box that was a variable resistor, if you twist the dial in the back, you can change the resistance across the box. The op amp (black box) is trying to keep the Voltage at pin 2 equal to the voltage at pin 3 (which is at .75V currently), but if we up the resistance of the blue box, then the op amp can't out put enough power to keep the pin at 0.75 V.  You can see it waiver with an oscilloscope or an ammeter. The current should be ~4mA, but after the output voltage peaks if you still increase R, you can see I drop.

Note:  The pretty looking diagrams are from "The Art of Electronics Student Manual" by Thomas Hayes