j 160 Assignment: DAQ 1: the LED Labs banner

Data Acquisition: The LED Labs
(Code and Writeup weights are on Universal Hand-in Page).

How To Succeed

Each team member MUST submit something to Blackboard for this lab. See "What to Hand In" below. Before you show up at the lab,

  1. write all the code you plan to use. The code is completely separate from the hardware and can and should all be written in advance. You can comment out commands (all DAQ toolbox commands) and pretend they worked (e.g. make up a vector of outputs), test your program logic and printing on this fake data.
  2. Make sure you know the functionality of the breadboard (what connects to what and what doesn't). Make a wiring diagram or picture for the laboratory setups and connections to the 6009 so that you know just what you want to do before you arrive. You may have bugs, but that's better than being clueless when the gun goes off.
  3. Use the same kit every time! Use the sign-out sheet, and remember Your Hardware Kit Number. If you want to continue working past one lab, you need to find your previous kit and the original sign-up sheet can disappear (it seems). Do NOT mess with any kit that is not your original one.

More Readings on DAQ: Digital I/O

Make sure you've read the relevant part of the UR DAQ Reading.

Here's a short guide to official on-line resources.. I also recommend the related readings from the GrandDaddy of this course: you want PDF links: DAQ1, 2, and 3, under Description on the EGR53L Assignments Page 2009.. Note there are plenty of differences in hardware details but much of the prose and even the code is directly applicable.

Acknowledgement

Having pointed to the documents at Duke, I gratefully acknowledge the shocking similarity between this and them. I ruthlessly ripped off all the LED project ideas from Prof. Gustafson (who has been most helpful to me in emails as well) and his Duke Colleagues. Sincere thanks!

Safety and Lab Practices

You'll work in pairs, so buddy up. Each team gets a kit of materials, instruments and tools.

We take SAFETY seriously and so should you. Intentionally risky behavior rates a visit with the judicial council.

  1. No food or drink in the lab. Don't want to gum up the equipment.
  2. Remove jewelry on or near your hands. Don't want electrical shorts.
  3. Keep your work area clean: nothing but your kit, whatever hardcopy reading and writing media you'll use (e.g. printouts and a pen).
  4. Take care when wiring. Make sure you understand what connects to what, where positive and ground voltages are, which polarity diodes are in. We don't want surprises, even though we should not see more than 6 volts in our labs.
  5. If you get surprised, see or smell smoke, or anything weird happens, back off and call for help.

Equipment

The kit for this lab should include:

  1. The 6009 unit. Here are pictures of 6009 Connection Labels in one style (maybe even the same as ours).
  2. A screwdriver
  3. 4 LEDs
  4. 4 Resistors (470, 560, 680 ohm all work), 1/4 watt (tiny) or 1/2 watt (small) are fine. Resistor Color Codes .
  5. Various colored wires for you to make connections with.

Trouble Shooting

As stated in the tutorial, the 'Dev3' argument in commands like DIO = digitalio('nidaq', 'Dev3'); could be correct or might be wrong for you. We don't know what it depends on, but it always should look like 'DevN' for some small integer N. If the DAQ toolkit doesn't like your guess you'll get an error message, with a suggestion to call daqhwinfo('nidaq'), which will tell you what you should call the device in device-constructor calls as above.

If Matlab can't find the 6009 (e.g. you get errors on ai = analoginput('nidaq', 'Dev3')), and daqhwinfo('nidaq') doesn't show a device with a real name (e.g. could be Dev4), then make sure 6009 is plugged into the chassis, not the screen, of computer. Probably best to kill and restart Matlab if this happens. At least delete('daqfind'); clear.

The 6009 has internal state that sometimes gets mysteriously set and can render the device "crazed".
IF you get strange errors involving timeouts, lack of timeouts, operations not finished, or samples missed, if get(ai) (for instance) shows the object in the 'Running' state when it shouldn't be, if you're told to kill off other jobs or set SampleRate lower, or you get other mysterious whining, AND your code seems OK, then do the following:

  1. delete(daqfind);
  2. clear;
  3. Turn off connections into the 6009 that may have voltages on them.
  4. Disconnect the 6009 from its USB cable and reconnect.
That should fix things. If MatLab is in a loop and you can't stop it with CTRL-C, then you may have to CTRL-ALT-DEL (hold down all at once). Select Task Manager, find and select the Matlab process, and click 'End Process' or whatever to kill it. If necessary, call for help.

Basic Wiring for the LED Labs

breadboard

The breadboard is used to connect components together. The idea is quite simple: Each horizontal line of 5 holes (A-E, and F-J) is tied together electrically, and can be used as a connection point for up to 5 wires or leads. The red and blue columns are generally used as power source and ground repectively (often only one on each side).

We can set up the board for all the LED experiments in a way that we can add and remove wires, but don't have to shuffle components. There is considerable regularity we can exploit. For instance, LEDs need to be oriented so that current (plus to minus) runs from into the positive leas, and out the negative lead. Also we always want a resistor in series with the LED. This can be pre-wired in a regular way. For any given circuit, there are a zillion ways to wire it. A basic strategy is to lay things out so you can get at them, and the connection patterns are clear.

Important LED Fact Diodes only conduct one way. LEDs do that and emit light. If too much current tries too hard (higher voltage) to go the Wrong Way through a diode it can be killed. Likewise it can be burned out by too much going the right way. The diode must be wired in the right direction in order to emit light. Unlike a resistor, it has a 'positive' end (connected to the voltage source) and a 'negative' end, connected to ground. Two clues: 1) the positive end has a longer wire. 2) The bulb of the has a rim that is flattened on the 'negative' side. Be careful. Resistors on the other hand are symmetric.

You should start wiring at this point, based on the above requirements and your knowledge of the principles. There ar many equivalent ways to wire your circuit correctly with the breadboard. Do one that makes sense for you. What made sense to CB is:

  1. Note that ultimately we need 4 LED-resistor pairs. WE can the following (or something equivalent), repeat it four times, and then leave this setup for the duration of the LED labs.
  2. Run each pair as horizontally as possible (shortways across the board, with input coming from the left.)
  3. Use three rows (to leave some room for fingers) across the board for each LED-resistor combination.
  4. Leave room to take off 6009 inputs from every 'interesting' junction in the circuit.
  5. Plug one end of a long wire (it's going to a 6009 output terminal) to breadboard location row 1, column A (1,A). It will be the source of positive voltage: it is an input wire for the cicuit.
  6. Plug the "positive" (longer) LED lead into (1, B) and its short lead into (3,A).
  7. Connect the resistor between (3,E) and (1,F).
  8. Connect (1,J) to the blue vertical column.
  9. Note: It doesn't matter if the resistor and LED change places as long as you make sure the current will still flow the same way in the LED.
  10. Finally plug a long wire, headed for a 6009 GND terminal, into the blue vertical column on the right side. this will be the system ground wire.

What we now have is a resistor and LED in series: if the input wire from (1,A) is connected to a 5 volt source and the ground wire from the blue vertical column is connected to ground, we expect the LED to light up. That's Lab 1. If we connect the input wire (1,A) to a varying voltage source (say between -1 and 5 volts) we expect the LED to be lit, dimmer or brighter, depending on the voltage (that's Lab 2). All that remains is to get the input and ground wires into the right spots on the 6009, which will provide the input voltages and ground. Also a small matter of programming.

If you duplicate the above circuit this four times spread down the board, (once for each LED/resistor circuit), you are set for all the experiments we will be performing. The system ground (long blue) wire is common, and does not have to be duplicated. Now you can connect the four long red wires from column A to the outputs (initially digital, next analog) of the 6009, and use the long blue wire to connect the vertical blue column to the ground on the 6009.

Lab 1: Digital Output

Wiring

Wire the LED -resistor pairs according to the Basic wiring instructions above. Using the little screwdriver, connect three input wires from the breadboard to connections P00, P01, P02 of the 6009 and the ground wwire to GND on the same side.

How to Connect: Unscrewing (counter-clockwise, leftie-loosey) the screws opens up little jaws that drop open. Insert the wire above the lower jaw and tighten the screw (rightie-tightie) to raise the jaw and clamp the wire.

Plug the 6009 into a USB connection ON THE CHASSIS (NOT THE SCREEN) of your computer.

Use some of the code provided (see below) to test your circuit, and don't be hesitant about modifying the logic of the code to do something slightly different... for instance, how about turning the LEDS on and off at random?

Sample Matlab Code

The code directory has some working examples (landing.txt, broadway.txt, count.txt) of what it takes to send digital signals to the LEDs. There are two repetitive ones (inspired by landing lights at airports and broadway signs), and one that relates the lights to binary numbers. You can also work from the command window, issuing one command a time to get started.

Lab2.txt, Lab3a.txt, Lab3b.txt are for analog input and output (later).

Work: Digital Output for Binary to Hex Translation

You know about number bases from the last section of the tutorial. If you want more, read the Radix entry in wikipedia: it's short. The hexa- (or sexa-) decimal number system has 16 digits, 0-9 and A-F, denoting integers 0 - 15. We like it because it's a short way to write binary numbers, as in raw computer addresses, or 8-bit bytes using two hex digits per byte. hex 0 is short for '0000', hex A is short for '1010' (decimal 10).

1. Add a fourth LED-resistor pair to your board.

2. Write a program that displays a random number between 0 and 15, pause and repeat (some number of times or until CTRL-C).

3. Last, write a program that issues adequate instructions to the user and then does the following.

Display a random binary digit from 0 to 15 in the four lights, and start a timer (In Matlab, help tic ). Wait for user input of a "hex digit" User should enter an integer from 0 to 9 or a letter {a,b,c,d,e,f}, or a negative value to terminate the process. Give feedback (e.g. "CORRECT" or "NO" ). If response is correct, stop the timer, record the response time, and display a new binary code. If the response is incorrect (and non-negative) re-request answer and leave timer running. If user types a negative number the trial and process is aborted and statistics are computed and plotted. Keep track of the number of trials, the number of wrong answers for each trial (0 if the first answer is correct), and the time spent until the correct answer is given.

When the user (you, probably) gets bored and bails out, plot the total number of answers (1 plus number of incorrect answers) and time-to-correct-answer for each trial (in order). Also plot the current ratio of total incorrect answers to trials, and the current average response time (over the test so far) versus trial number. You should, it says here, be able to observe a 'learning curve' like you hear about in Psychology 101.

Lab 2: Analog Output for LED Modulation

Take the input wires for the first two LED circuits and move them from the digital ports of the 6009 to the analog output connections (other side of the 6009). You can now drive the first two LED and resistor pairs using analog (continuously variable) output channels.

Write a script that deletes all existing DAQ objects, creates an AnalogOutput object, and using a for-loop, produces on channel 0, an analog signal representing a sine wave that varies from 0 to 5 volts with a period of 2 seconds. On Channel 1 send a cosine signal with the same range and frequency. This should send different analog voltages to the first two LEDs in your array make a nice, aesthetic, subtle, continuous variation instead of the harsh, simple-minded, on-off effect of digital output.

In more detail, Over 100 iterations, you should create sine and cosine signals that go through a full wavelength. So you want something like for each k between 1 and 100,
Voltage1 = 2.5 + 2.5*(sin( k* 2*pi/100), and then pause for .02 seconds. Use the cosine equivalent for Voltage2. Make sure you understand and believe this is the right formula. If you want to watch 4 oscillations, just run k from 0 to 400. You could make the number of oscillations a user input. You can also vary the frequency by changing the pause time.

Try writing all this, running and debugging BEFORE you look at a (slightly different) template version in code directory at Lab2.txt.

Lab 3: Analog Output and Input for Voltage Drop Analysis

3A: Putsample and Getsample

For this exercise we'll use the 6009 ouput setup of Lab2, but we only care about one LED-resistor pair, so pick one. We'll generate an output for it, so you can leave the AO wiring as it was. We want to measure the voltage at three locations on the circuit using three input ports on the 6009. We will use ports AI 0, AI 1, and AI 2 on the 6009, as differential inputs. This means that two wires will come out of the circuit for each AI input, and go into the two adjacent connectors for analog input. For channel AI 0, they may be labelled AI0 + and -, or AI0 and AI4, depending on label style on your 6009. Similarly for AI 1 and AI 2.

Where do the inputs come FROM on the circuit? For definiteness let's say the LED is closest to the positive input, then comes the resistor, then comes ground. If your circuit goes resistor-led, just swap the apropriate list items below

  1. for AI 0, we connect the + side (AI0) to the positive pin of the LED (same place the input is connected to). We connect the - side (AI4) plugs in after the LED-resistor pair and before the ground. This measures voltage drop across the whole circuit and should mirror what AO sends in.
  2. For AI 1, the + side plugs in the same place (electrically) as AI0's, and the - side goes in between the LED and resistor. This measures voltage drop across the LED.
  3. For AI 2, the + side plugs in the same place (electrically) as AI 1's - wire, between the led and resistor, and the - side goes in between the resistor and ground, like AI 0's. This measures voltage drop across the resistor.

Your code should create one analogoutput and one analoginput device, and add one output channel and three input channels, in accordance with the numbering on the connectors you are using on the 6009. Use zeros(300,3) to create and initialize a Results array.

Over k = 1:300 iterations:

  1. Compute a voltage voltsout that goes (linearly) from -1 to 5 volts.
  2. Call putsample(ao, voltsout); to set the output voltage to voltsout
  3. Pause for .01 second (seems a good idea to avoid race between put and get).
  4. Set Results(k,:) = getsample(ai); to save the three voltages of interest.

Now plot three curves: one for each measured voltage. If you plot the entire array it should generate 3 curves in 3 colors automagically, (one per column), and you can use legend() to identify which line is which.

Some demo code is in the directory at Lab3a.txt, but only takes data from the LED. When I did this just for the LED I saw this:

ledvolts

Note that this curve suggests that the demo program is not doing quite what we might have expected, since we wanted voltages to start changing immediately. What is the issue (hint: USB-6009 documentation). Don't spend a lot of time on this, but can you figure out a fix?

Your other plots will show you more, including the resistor soaking up voltage not being used by the LED (the total voltage drop across the circuit must equal the sum of the voltage drops across the components). Recall that the LED conducts nothing for negative voltages (it is a diode, after all), and thus the entire input voltage should appear across the LED while it is negative. This continues for a while even after the volatage goes positive, with the diode conducting negligable current. Eventually, the diode "turns on" and lights up, and the voltage across it becomes approximately fixed, with the remainder of the input appearing across the resistor. The actual current-voltage relationship across a forward-biased diode is fairly well modeled as an exponential. Because this exponential increases so fast, we have the sudden "turn-on" and voltage limiting effect seen in this circuit. Series of diodes are sometimes used to protect circuits from voltage transients by exploiting this effect.

You could check that adding two of data columns you've collected produces the third. Might be good for the writeup!

For some extra credit, extract the non-linear tailing-off part of the LED's voltage curve and fit it with the best model you can. Can you find details of the underlying theory somehow (like asking your favorite ECE student or prof, or reading a book?).

3B: Putsample and GetData

In this exercise we want to use the 6009's ability to acquire a set of samples at precisely specified intervals. The sinusoid generation exercise used Matlab's pause function to generate samples at a desired rate, but the Matlab timer is not very precise. If we are interested in accurately measuring the time behavior of some process, using the pause function to control the sampling would be likely to yield poor quality data.

Same wiring setup exactly. This time we will use the GetData 6009 control function to acquire a set of samples automatically at a specified rate. The signal we will measure will be generated as before using the Matlab pause function. Note that this allows us to look at the reliability of the pause command.

A sparse code template, again only for one analoginput channel, is in the code directory at Lab3b.txt You have to extend it to take 3 channels of input, supply a few commands as indicated, and write the guts of the iteration to supply the voltages to the board. You may want to change things: you may not want to use a trigger, which eliminates several statements and means your input acquisition will start with the start(ai) statement.

We can generate a signal by modifying the code from the previous exercise. Let's change the voltage input iteration to go over the same range of [-1, 5] but in 25 steps with a .04 pause beteeen each. If we do that, and run the program twice we get two different plots of LED voltage drop: The following images show the results of doing this with the (slightly buggy) demo code from the previous exercise at 100Hz. You get to pick the sample rate, and you might want to try several, including at least one above 1000Hz just to see if anything interesting shows up.

jaggyled jaggyled2

Note that this is more or less what we expected to see: a quantized version of the LAB3A LED plot. The 6009 can take up to 48000 samples/sec, but and can only generate 160 analog outputs in the same time. Clearly it's not designed as a signal generator (!!) However we can use it to observe experimental data at a fairly high rate as in this lab, where we are essentially putting a high-resolution microscope on a (MatLab) component's behavior. By doing this, and making use of our previous voltage in - LED voltage out relationship (whose accuracy is not dependent on accurate timing) we obtain results that suggest that Matlab's pauses are really pretty approximate (why?). Not good for real-time or precision control applications.

What to Hand In

See the Universal Hand-in Page.

Each team member MUST hand in two submissions to Blackboard for this lab.

One member should submit both the zipped code archive for the LED Lab Code grade column and the .pdf writeup for the LED writeup grade column. Make sure both names are on the README and writeup, and it would be good to mention both names in the submission comments.

The other member should submit two 1-liner .txt files saying "I worked with so-and-so". That makes it impossible for us to forget the partner who doesn't submit code and writeup.

Submit to Blackboard before the drop-dead date for any credit and before the due date for partial-to-full (or extra!) credit.

Check immediately to see that BB correctly received what you sent!


Last Change: 04/28/2011: CB