Home

Innovative Experiments using Phoenix

image

Contents

1. 29 3 7 2 Inverting Op Amps with externally controllable gain 30 3 7 3 Non Inverting variable gain Amplifier 31 3 7 4 The Constant Current Source Module 31 3 9 Plug in M d uleg 4 of om an GD ek WR el 2 eS 32 3 8 1 16 character LCD display 32 3 8 2 High resolution AD DA card 32 3 8 3 Radiation detection system 32 3 9 Other Accessories e Us ie 8 GI E Ta 32 3 9 1 Light barrier oaoa a 33 3 9 2 Rod Ponca are A ae Game wt Gao a i aan a 33 3 9 3 Pendulum motion digitizer using DC motor 33 3 9 4 Temperature Sensors ooo a a 33 Experiments 34 4 1 A sine wave for free Power line pickup 34 4 1 1 Mathematical analysis of the data oaa aa 36 4 2 Capacitor charging and discharging 38 4 2 1 Linear Charging of a Capacitor 42 4 3 IV Characteristics of Diodes ooa a 42 4 4 Mathematical operations using RC circuits aa 44 4 5 Digitizing audio signals using a condenser microphone 47 Alt SEMCTCISC Ter ica Pas eo EN Hed Fe ee es 48 4 6 Synchronizing Digitization with External Events 48 4 7 Temperature Measurements 00 0004 49 4 7 1 Temperature of cooling water using PT100 50 4 8 Measuring Velocity of sound 005 53 4 8 1 Piezo transceiver ee 3 wae eta bh oe Ra Se oe a eR 53 4 8 2 Condenser microphone 55 4 9 Study of Pendulum
2. 26o 4 224 oe 464 Re ee we eae 56 4 9 1 A Rod Pendulum measuring acceleration due to gravity 57 4 9 2 Nature of oscillations of the pendulum 57 4 9 3 Acceleration due to gravity by time of flight method 61 3 4 10 Study of Timer and Delay circuits using 555 IC 4 10 1 Timer using 555 ae ae ee a en Be 4 10 2 Mono stable multi vibrator 5 Micro controller development system 5 1 Hardware Basics wm ee ae a he OA ee we hed eee 5 1 1 Programming tools 008 5 1 2 Setting Clock Speed by Programming Fuses 5 1 3 Uploading the HEX file 2 2 ne ae go ee ke 5 2 Example Programs 4 ee aw Boks ee ee ee ek 5 2 1 Blinking Lights ah te eee Uk Be ak eS 5 2 2 Writing to the LCD Display 5 2 3 Analog to Digital Converters 5 2 4 Pulse width modulation using Timer Counters 6 Building Standalone Systems 6 1 Frequency Counter for 5V square wave signal 6 2 Room Temperature Monitor 8 O21 ARIKCLCISC ei dn oa tk der ak De eb a wh ee 7 Appendix A Number systems 8 Appendix B Introduction to Python Language 8 0 1 1 Exercises 2 ike ake le its a 4 9 Appendix C Signal Processing with Python Numeric 9 1 Constructing a sampled sine wave Oo baking the EET ispa oe ae Ht haat aps eae ee ees Ges Bn ce 10 Appendix D Python API Library for Phoenix M 65 67 68 68 70 71 71 72 7
3. 4 8 Measuring Velocity of sound The simplest way to measure the velocity of anything is to divide the distance s by time taken Since phoenix can measure time intervals with microsecond accuracy we can apply the same method to measure the velocity of sound We will first try to do this with a pair of piezo electric crystals and later by using a microphone 4 8 1 Piezo transceiver A piezo electric crystal has mechanical and electrical axes It deforms along the mechanical axis if a voltage is applied along the electrical axis If a force is applied along the mechanical axis a voltage is generated along the electrical axis We are using a commercially available piezo transmitter and receiver pair that has a resonant frequency of 40 KHz The experimental setup is shown in figure 4 19 The transmitter piezo is excited by sending a 13 micro seconds wide pulse 53 Digout D3 100 Ohm 100x Q GND Figure 4 19 Piezo Transceiver setup measuring velocity of sound Distance cm Timeusec Dist difference Time diff Vel m s 4 224 5 253 1 29 344 8 6 282 2 58 344 8 T 310 3 86 348 8 Table 4 1 Velocity of sound on Digital Output Socket D3 to generate a sound wave The sound wave reaches the receiver piezo kept several centimeters away and induces a small voltage across it This signal is amplified by two variable gain amplifiers in series each with a gain of 100 The output is fed to Dig
4. the first index starts at 0 It is possible to do negative indexing which helps you extract elements from right to left The addition and multiplication operations behave logically The str functions converts an integer to string We will find this useful when we wish to concatenate an integer or floating point number and a string Let s find out the ASCII value of a character And let s convert an ASCII value into its equivalent character form 88 gt gt gt chr 65 7A gt gt gt chr 97 a ees Complex Numbers Python has built in complex numbers Here are a few statements which demonstrates this capability Soa 1 2j gt gt gt b 3 4 gt gt gt a b 4 6j gt gt gt a b 5 10j SS Arrays Lists Here is how you go about manipulating a set of numbers or any other ob jects in Python gt gt gt a 1 2 3 9 hello gt gt gt alo 1 gt gt gt print al3 hello gt gt gt al4 Traceback most recent call last File lt stdin gt line 1 in IndexError list index out of range 89 The expression al0 is said to index the array with 0 the first index Note that it is not possible to index the array with 4 as the last element is at index 3 the Python interpreter generates what is called an exception if you try doing it This is standard behaviour You can concatenate arrays and do more interesting stuff SS a
5. ADC channel s in bulk say 200 samples at precisely timed intervals There are functions available in the Phoenix library to do exactly this There are two important block read functions read_ block and multi_ read_ block We will examine read_ block first Connect 5V to ADC channel 0 and exe cute the following code fragment gt gt gt p select_adc 0 25 gt gt gt p set_adc_size 1 gt gt gt m p read_block 100 50 0 gt gt gt print m We are basically asking the Phoenix box to take 100 readings from the ADC from the currently selected channel with an inter read delay of 50 microsec onds The last argument to read_ block will be 1 only when we are analyzing bipolar signals connected through the X 5 2 gain block Here are the first few readings which you might expect 0 4941 1764705882351 50 4980 3921568627447 100 4941 1764705882351 150 4980 3921568627447 200 4960 7843137254904 Each item of the list is a two element tuple The first element of the tuple is the time in microseconds at which the reading was taken by the Micro controller s ADC and the second element is the voltage in mV read The very first reading has a time stamp of 0 and subsequent readings have a difference of 50 microseconds between them this value has been specified by us as the second argument to read_ block Now you can try another experiment Connect the PWG to channel 0 of the ADC and exe
6. bit3 is 1 and the output on pin D3 will be high If you are new to binary arithmetic make sure that you understand this clearly Exercises 1 With a multimeter or LED s verify which all pins are high low when you execute p write_outputs 10 Is DO different 2 How would you call p write_outputs if you want DO and D3 to be high and all other pins low 3 1 1 Blinking LED It s time to make the LED blink Type the following code at the Python prompt gt gt gt import time gt gt gt while 1 p write_outputs 1 time sleep 1 p write_outputs 0 time sleep 1 gt gt gt The logic is easy to understand writing a 1 results in digital output pin DO going high we then delay execution for one second by calling the sleep The socket marked DO is buffered using a transistor and can be used for driving 5V relay coils This output works well only with some load connected to ground The HIGH level voltage of DO is slightly less than 5V due to the transistor 3This is absolutely important unless you understand this idea properly you will not be able to do anything with the Phoenix box 19 routine the LED stays high during this period We then make it go low by writing a 0 and again sleeps for 1 second The whole process gets repeated infinitely Press Ctrl C to come out of the loop 3 1 1 1 Exercise Connect an LED each in series with a 1KOhm resistor between digital outp
7. l 2 3 gt gt gt b 4 5 6 gt gt gt a b 1 2 3 4 5 6 SS aS 1 2 3 1 2 3 1 2 3 gt gt gt a append 10 gt gt gt print a 1 2 3 10 gt gt gt print al0 3 from index 0 to index 2 1 2 3 gt gt gt print al 1 negative indexing 10 gt gt gt a range 10 gt gt gt print a 0 1 2 3 4 5 6 7 8 9 ig The sign is the comment symbol in Python comment lines are ignored by the language interpreter and are written for readability s sake Tuples Tuples are like lists but with a major difference You can t modify the contents of a tuple in any way gt gt gt a 1 2 3 a sequence of objects within ordinary paren thesis forms a tuple gt gt gt al0 9 error 90 Functions Here is how you define a function in Python gt gt gt def sqr x note the colon return x x ee erties The character sequence which appears automatically only if you are in the interactive mode denotes the fact that you are now within a function definition Python syntax says that body of a function should be indented 2 I have used a tab for this purpose We have defined a simple function sqr which accepts a number and returns it s square Here is how we call it gt gt gt sqr 3 9 SSS Here is another example def add a b return a b a b A Python function can return anything in t
8. 2 Power line pickup and its sine wave fit by the python program as the argument xmgrace pickup dat Select Data gt Transformation gt NonLinearCurveFitting from the main menu and enter the equation V t Vo sin 27 ft 1000000 0 6 C Xmerace accepts the adjustable parameters as AO Al etc e V t is the value of voltage at time t Vois the amplitude The value will be close to 5000 milli volts repre sented by parameter AO f is the frequency of the wave parameter A1 e is the value of time divided by 1000000 to convert micro seconds to seconds fis the phase offset since we are not starting the digitization at zero crossing parameter A2 37 e C is the amplitude offset that may be present parameter A4 Reasonable starting values should be given by the user for Vo and f to guide the fitting algorithm Try different values until you get a good fit The figure 4 2 shows the data plotted along with the fitted curve The Curve fitting window 4 3 shows the parameter values The extracted value of frequency is 48 73 Hz Did not believe it and cross checked it by feeding a 50 Hz sine wave from a precision function generator to the ADC input The result of a similar analysis gave 49 98 Hz Checked with the power distribution people and confirmed that the line frequency was really below 49 Hz Exercise Repeat the experiment by changing the length of the wire touching one end by your hand and rising the oth
9. 350 344 8 20 0 645 341 8 30 0 925 346 8 40 1 218 345 4 50 1517 343 1 60 1810 342 8 4 9 Study of Pendulum Studying the oscillations of a pendulum is part of any elementary physics course Since the time period of a pendulum is a function of acceleration due to gravity one can calculate g by doing a pendulum experiment The accuracy of the result depends mainly on how accurate we can measure the period T of the pendulum Let us explore the pendulum using phoenix 56 4 9 1 A Rod Pendulum measuring acceleration due to gravity A rod pendulum is very easy to fabricate We took a cylindrical rod and fixed a knife edge at one end of it to make a T shaped structure The pendulum is suspended on the knife edges and its lower end intercepts a light barrier while oscillating The light barrier is made of an LED and photo transistor The output of the light barrier is connected to Digital Input D3 The program rodpend py is used for measuring T and calculating the value of g The code is listed below import phm math p phm phm length 14 65 length of the rod pendulum pisgr math pi math pi for i in range 50 T p pendulum_period 3 1000000 0 g 4 0 pisqr 2 0 length 3 0 T T print i T g The output of the program is redirected to a file and a histogram is made using xmgrace program as shown in figure 4 21 The mean value and per centage error in the measurement can be
10. 8 bit wide and each bit can be configured as input or output The behavior of the ports are controlled by programming the corresponding internal registers In addition to the normal digital In put Output operation most of the pins have alternate functions as shown in 67 figure 5 1 Once the alternate functions are enabled internally correspond ing PIN will get connected to those units For example enabling the on chip ADC will make Port A pins as ADC inputs We will try to introduce the different features of ATmegal6 by small example programs For more details refer to the ATmegal6 manual provided on the CD Refer to the schematic diagram5 2 to find out the wiring between the front panel sockets and AT megas 5 1 1 Programming tools The AVR GCC compiler and associated tools are on the CD It is desirable to start with the Live CD first where all the programs are installed and ready to use On GNU Linux systems install the rpm files using the script install sh in the RPM directory The directory opt cdk4avr bin should be added to the path for the tools to work properly Under MS Windows run the file Win AV R install exe to install the compiler and tools To save typing the necessary commands are put in a file named compile bat t This script can be used for compiling the code and generate the executable format file echo compiling 1 c avr gcc Wall 02 mmcu atmega16 W1 Map 1 map o 1 1 c avr objcopy
11. AQ 1805 61 I Bounds Al 46 7305 Bounds care fi Aa fi 65826 J Bounds zaza Th aa Laan ast caninas fi lt An lt TF SO 7 Figure 4 3 Curve fitting window of xmgrace 39 D3 a Ara W 1uF ADC CHO Figure 4 4 Circuit to study Capacitor p phm phm p select_adc 0 p write_outputs 8 time sleep 1 p enable_set_low 3 data p read_block 200 50 0 p plot_data data time sleep 5 We make the digital output pins go high and sleep for 1 second allowing the capacitor to charge to full 5V The call to function p enable_set_low 3 is similar to select_ adc or add_channel whose effect is seen only later when a read_ block or multi_read_ block is called The idea is this in certain situations an ADC read should begin immediately after a few digital outputs are set to 1 or 0 so we can combine the two together and ask the ADC read functions themselves to do the set to LOW or HIGH and then start reading In this case it brings to logic LOW pin D3 thereby starting the capacitor discharge process The function then starts reading the voltage across the capacitor applied on ADC channel 0 at 250 microsecond intervals The voltage across the capacitor as a function of time is shown 2You may wonder as to why such a seemingly complicated function like enable _set_low is required We can as well make the digital output pin go high by calling write_ outputs and then call read_block The problem
12. Integration circuit we will apply a square wave produced by the PWG to CHO of the Phoenix ADC We will apply the same signal to an RC circuit R 1K C 1uF and observe the waveform across the capacitor The circuit is shown in figure 4 10 We will repeat the experiment for 3 different cases by varying the Period of the square wave to show the different results 1 RC amp T Results in a Triangular wave form4 11 2 RC gt gt T The result is a DC level with some ripple4 12 3 RC lt lt T The sharp edges becomes exponential 4 13 The code sqintegrate py which generated these three plots is as follows data was taken with 1K resistor 1uF capacitor Three sets are taken a freq 1000 Hz and sampling delay 10micro seconds samples 400 b freq 5000 Hz and sampling delay 10micro seconds samples 300 c freq 100 Hz sampling delay 20micro seconds samples 300 win import phm p phm phm 45 5V PWG W 1K Z 1uF 20x 20x X 5 2 Piezo C MIC ADC CHO Buzzer Figure 4 14 Microphone digitizing buzzer sound freq 1000 samples 300 delay 10 p add_channel 0 p add_channel 1 print p set_frequency freq while p read_inputs 15 p plot_data p multi_read_block samples delay 0 Run the code by changing the frequency to study the relation between RC and T 4 5 Digitizing audio signals using a condenser microphone A condenser microphone is wired as shown in figure 4 14to
13. Phoenix M 3 1 The Digital Outputs You should see four sockets labeled DO to D3 in a section marked Digi tal Outputs It s possible to make these pins go high and low under program control Invoke the Python interpreter and enter the following lines gt gt gt p write_outputs 0 Connect an LED and a 1K Ohm resistor in series between digital output pin D3 and ground any one of the Black sockets make sure that the longer leg the anode of the LED is connected to D3 You will see that the LED is OFF Now type the following line gt gt gt p write_outputs 8 You will see that the LED has lighted up Want to put it off Type gt gt gt p write_outputs 0 again What is happening here gt gt gt p write_outputs 8 we are asking the Phoenix box to write the number 8 to the digital output lines Now what does that really mean The number 15 can be expressed as 1000 in binary let s call the rightmost bit bit0 or the least significant bit and the leftmost bit bit3 or the most 1A single strand wire with a bit of insulation stripped off its end and bent into a thin hook can be conveniently inserted into the Phoenix connectors The LED and resistor can be placed on a breadboard 18 significant bit The value of these bits have a relation to the voltages on digital output pins DO to D3 If bit0 is 1 the voltage on DO will be 5V and if it is 0 the voltage would be OV Thus when we write 8
14. a frequency spectrum from 0 to 500 Each slot of the array should be thought of as a bin which holds the strength of signals of frequency 0 4Hz 5 9Hz 10 14Hz etc in the original signal We have two peaks at slots 5 and 10 because the two frequency components of our signal are 25Hz and 50Hz We have been able to recover frequency information from a sequence of sampled data points This is a very powerful idea so powerful that much of modern multimedia audio and video processing would not exist without it 99 Figure 9 1 100 Chapter 10 Appendix D Python API Library for Phoenix M The Python Application Programming Interface API used for manipulating the Phoenix box has a collection of around 30 functions A list of these functions together with their parameters and typical invocation is presented in this Appendix Conventions A statement of the form void write_ outputs integer n Describes a function whose name is write outputs which does not return anything and which has just one argument whose type is integer Note that this is just an elaborate description of the function called a PROTOTYPE in C terminology and does not represent the way in which the function is to be invoked in a Python program that is described in detailed in the tutorial presented in the Chapter Interacting with Phoeniz M 101 Simple Digital I O write outputs PROTOTYPE void write_ outputs integer n DESCRIPTION The fu
15. accuracy using them 3 3 Waveform Generation and Frequency Count ing Identify the socket marked PWG Programmable Waveform Generator on the Phoenix box Now execute the following command at the Python prompt gt gt gt p set_frequency 1000 1000 gt gt gt This results in a 1000Hz 0 to 5V square waveform being generated on PWG If you have a CRO you can observe the waveform on it An easier way is to simply connect the PWG socket to a socket marked CNTR the Phoenix box has a built in frequency counter which can measure frequencies upto 1 MHz Measuring frequency is simple once the signal is connected to the CNTR socket execute the following Python function gt gt gt p measure_frequency 1000 gt gt gt Tt is possible to set frequencies from 15Hz to 4MHz but it need not always set the exact frequency which you have specified only something close to it The actual frequency set is returned by the function 21 In this case we are getting 1000 which is the frequency of the waveform on the PWG socket If you have a 0 to 5V range Square wave you can measure its frequency using this call You can measure the frequency of an external oscillator signal by connecting it to the CNTR input provided it is a 0 to 5V signal Measuring frequency using the Digital input sockets and Analog Comparator Socket will be discussed later 3 4 Digital to Analog converter DAC An analog output voltage ra
16. and plots it on to the screen this process is repeated If every time we start digitizing from a different part of the signal say a periodic sine wave the display will not remain static and will tend to run around The solution is to sample the waveform at a fixed point every time If we call the function set_adc_ trig with arguments say 10 and 20 each MULTIREADBLOCK will digitize the signal when it is on a rising path between 10 and 20 EXAMPLE p set_adc_ trig 10 20 enable set high enable set low PROTOTYPE void enable_set_high integer pin void enable_set_low integer pin DESCRIPTION In some applications it would be necessary to make a digital output pin go high low before digitization starts It is ofcourse possible to do this by first calling write outputs and then start ing digitization but the in between delay may not be acceptable 114 in some applications This function when called with a digital output pin number as argument makes a subsequent ADC block digitization function set clear the pin before it begins the digiti zation process EXAMPLE p enable_set_high integer pin p enable_set_low integer pin disable set PROTOTYPE void disable_ set void DESCRIPTION If this function is called the ADC block read functions will no longer set a digital output pin high or low before starting digitization In short this function cancels the effect of calling enable set high or enable_ se
17. any time and get the results This is not the case for transient signals We have to synchronize the digitization process with the process that generates the signal For example the signal induced in a coil if you drop a magnet into it Phoenix M does this by making the read_block and multi_read_block calls to wait on a transition on the Digital Inputs or Analog Comparator Input 48 Connect the condenser microphone as shown in figure Configure the two inverting amplifiers to give a gain of 20 and 10 first plug in resistor is 500 Ohm and second one is 1 KOhm The output of the second inverting amplifier is given to Digital Input D3 through a 1K resistor The same is given to ADC through the level shifting amplifier Make some sound to the microphone The p enable_ rising wait 3 will make the read_block function to wait until D3 goes HIGH With no input signal the input to DO will be near OV that is taken as LOW The program wcro py used is listed below import phm p phm phm p select_adc 0 p enable_rising_wait 3 while 1 v p read_block 200 20 1 if v None p plot_data v Exercise Use a similar setup to study the voltage induced on a coil when a magnet is suddenly dropped into it 4 7 Temperature Measurements In certain experiments it is necessary to measure temperature at regular time intervals This can be done by connecting the output of a temperature sensor to one of t
18. capture the audio signals One end of the microphone goes to Vcc through a resistor the other end is grounded The output is taken via a capacitor to block the DC used for biasing the microphone The signal is amplified by two variable gain inverting amplifiers in series with a total gain of 400 The amplified output is level shifted and connected to ADC channel 0 The program cro py is AT 3000 2000 1000 Volatge mV 1000 2000 1 i 1 l l 1 1 0 1000 2000 3000 4000 5000 Time usecs Figure 4 15 Buzzer output digitized used to capture the waveform and a screen shot is shown in figure 4 15 4 5 1 Exercise The data collected by the program cro py is in the file buzzer dat on the CD Open it in xmgrace and do a curve fitting to extract the frequency as described in section 4 1 The frequency can be roughly estimated by looking through the data file for time interval between two zero crossings Hint The value is close to 3 7KHz The technique of taking Fourier Transforms using Python is discussed in an Appendix Go through it and see whether you can calculate the frequency using that 4 6 Synchronizing Digitization with External Events In the previous examples we have seen how to digitize a continuous waveform We can start the digitization process at
19. draw more than 100mA current from the 5V regulated supply Take necessary protections against back emf when connecting inductive loads like motors or relay coils 8 Forcibly Inserting Multi Meter probes with diameter more than 2 mm to the front panel sockets will damage them 9 And don t pour coffee into the sockets 14 2 3 Installing Software for PC interfacing There is no need to install any software if you plan to use Phoenix M by booting from the Live CD Otherwise on a GNU Linux distribution you need to install the pyserial module and the phm py module To install pyserial unzip the file pyserial 2 2 zip located inside the directory Phoenix M Linux on the CD into a directory and run the following commands from that directory python setup py build python setup py install To install the phoenix M library just copy the file phm py to directory named site packages inside the python directory On MSWindows install the files inside the directory M Swin on the CD by clicking on them and copy phm py to the directory named lib inside the python directory python24 inside the root directory of C drive 2 3 1 Software for programming ATmegal6 Again there is no need to install any software if you are working from the live CD Otherwise you need to install the AVR GCC compiler and other development tools On GNU Linux systems that supports installing rpm files goto the Linux RPM directory on the
20. inside infinite loops where plot function may not work properly EXAMPLE v p read_block 200 10 1 p plot_ data v 117 Bibliography 1 ATMegal6 Documentation Atmel corporation www atmel com dyn resources prod_documents doc2466 pdf 2 Plotting package xmgrace http plasma gate weizmann ac il Grace 118
21. is that all these functions communicate with the Phoenix box using a slow speed serial cable For example the read_ block function simply sends a request which is encoded as a number over the serial line asking the micro controller in the Phoenix box to digitize some input and send it back By the time this request reaches the micro controller over the serial line the capacitor would have discharged to a certain extend So we have to instruct the Phoenix micro controller in just ONE command to set a pin LOW and then start the digitization process 40 Figure 4 5 RC Discharge Plot in Figure 4 5 which looks like an exponential function When the rate of change of something is proportional to its instantaneous value the change is exponential Let us examine why it is exponential and what is an exponential function with the help of some elementary relationships The discharge of the capacitor results in a current I through the resistor and according to Ohm s law V IR Voltage across the capacitor at any instant is proportional to the stored charge at that instant V Q C These two relations imply a and we current is nothing but the rate of flow of charge I 2 Solving the differential equation a te results in Q t Qoe Re which also implies V t Voe Re Exercise Modify the python program to watch the charging process Change the code to make D3 LOW by calling p write_outputs 0 and set it to HIGH just before digiti
22. j text j data 0 ihex 1 1 hex avr objdump S 1 gt 1 1st More information on the AVR GCC compiler and the library functions are on the CD in html format 5 1 2 Setting Clock Speed by Programming Fuses Several parameters like processor clock source clock speed etc can be pro grammed through the same cable that is used for uploading the executable The bat extension may look odd but there is a reason With that extension it can be used under MSWindows also 68 1CS Phoenix M Hardware schemat 69 Figure 5 2 T z z 7 i T P 3 wg 9002 20 Sunt Apsua E u sey Y zey f l roog E L lL L l AB Jequinn wewnoog ea ML ced Suouuexs sqLOWETe 8 SORKYY PeserNd oo 104 eORLOW FIANIS
23. mV across it We have chosen a gain of roughly 30 to amplify this voltage The gain is provided by the non inverting amplifier with a 330Qresistor from the Yellow socket to ground How do we calculate the temperature from the measured voltage The resistance is easily obtained by dividing the measured voltage by the gain of the amplifier To get the temperature from the resistance one need the calibration chart of P100 or use the equation to calculate it Rr Roll AT BT 100CT CT4 Rr Resistance at temperature T Rois the resistance at 0 Celsius A 3 9083 x 10 e B 5 775 x 107 The first three terms are enough for temperatures above zero degree Cel sius and the resulting quadratic equation can be solved for T The program pt100 py listed below prints the temperature at regular intervals The out put of the program is redirected to a file named cooling pt100 dat and plotted used xmgrace as shown in figure4 18 import phm math time p phm phm gain 30 7 amplifier gain offset 0 0 Amplifier offset measured with input grounded ccs_current 1 0 CCS output 1 mA def r2t r Convert resistance to temperature for PT100 rO 100 0 A 3 9083e 3 l Temp Celcius 1 1 1 500 1000 1500 2000 Time seconds Figure 4 18 PT100 Cooling water temperature B 5 7750e 7 c 1 r r0 b4ac math sqrt A A 4 B c t A b4ac 2 0 B return t def v
24. multi_read_ block is invoked this channel list is consulted and analog values on all the channels in the list are digitized As an experiment try deleting one channel from the list and re issuing the multi_read_ block call 27 AL Figure 3 2 Rising to falling edge delay The multi_read_block function examines only the channel list it does not care which channel has been set by calling select_ adc The channel list is maintained internal to the memory of the micro controller which controls the Phoenix box if an application adds a channel to the list a call to multi_ read_block later from another application will result in that channel also getting digitized Programs like CROs must remove all channels from the list while starting and then add the required ones 3 6 Time Measurement Functions The Phoenix library includes several functions which can be invoked to mea sure time periods Most of these functions basically measure time delays between rising falling edges on the various Digital Input pins or Analog Com parator Input Say you wish to compute the on time of a square wave applied to digital input pin DO see figure 3 2 you can simply connect the PWG socket to DO and execute gt gt gt p set_frequency 1000 gt gt gt p r2ftime 0 0 500 The function accepts two digital input pin numbers which can be the same or different and returns the time in microseconds between two consecutive rising and f
25. one of the features of Phoenix M This is achieved by loading the required software into the micro controller At the same time the tools to change this resident code also is being provided along with the system This enables the students to use it as a general purpose micro controller development kit and designing stand alone projects 1 2 Features for Developing Experiments Phoenix M offers the following features through the front panel sockets for developing computerized science experiments 1 Four channels of Analog Inputs 2 Programmable voltage source 3 Four Digital Inputs 4 Analog Comparator Input 5 Four Digital outputs One with 100 mA drive capability 6 Square Wave Generator 10 Hz to 4 MHz 7 Frequency Counter 1 Hz to 1 MHz 8 Constant Current Source 1 mA 9 Two Variable Gain Inverting Amplifiers T 10 One Variable Gain Non Inverting Amplifier 11 Two Bipolar to Unipolar Converting Amplifiers 12 5V Regulated DC Output from the external 9V DC input 13 Serial Interface to PC 14 Easy to use Python language library To develop science and electronics experiments suitable sensor elements are wired to the front panel sockets and accessed from the PC using the Python library The program running on the micro controller accepts the commands from the PC performs the tasks and sends the reply Phoenix M can run on any computer with a Serial Port and a Python Interpreter with a library to access the ser
26. set to 10 microseconds EXAMPLE p set__adc_delay 20 112 set adc_ size PROTOTYPE void set_adc_size int size DESCRIPTION The Phoenix M ADC can take 8 bit or 10 bit samples Calling this function with argument 1 will choose 8 bits an argument of 2 chooses 10 bits Default size is 8 bits EXAMPLE p set_adc_ size 1 get chanmask add_ channel del_ channel PROTOTYPE integer get__chanmask void void add_channel integer channel void del_ channel integer channel DESCRIPTION get_chanmask returns the current ADC channel mask The channel mask decides which all channels will be read by a multi_ read_ block call Let s say the channel mask s value is 5 Expressed in binary 5 is 0101 Bits DO rightmost bit as well as D2 are set this means that channels 0 and 2 will be read by a multi_ read_ block call add_ channel adds a channel to the mask Say the current mask is 5 channels 0 and 2 present calling add_channel 1 will result in the mask becoming 7 binar 0111 bits DO D1 and D2 set and D3 clear Calling del_ channel results in the specified channel being removed from the mask 113 set adc_ trig PROTOTYPE void set_adc_trig integer trl integer tr2 DESCRIPTION This function is useful when writing a CRO application The effect of the function is evident only when a MULTIREADBLOCK function is called to read data in bulk A CRO application typi cally reads a number of samples from the ADC in bulk
27. which you can perform complex list manipulations in a compact way The inter ested reader should look up these functions once he gets a firm foundation in Python basics Plotting with Python The Phoenix LiveCD comes with the Grace plotting package which can be accessed from Python Here is how you do a simple plot gt gt gt import pygrace gt gt gt pg pygrace grace gt gt gt x 123 gt gt gt y 4 5 6 gt gt gt pg plot x y Using the idea presented in section 8 0 1 1 it should now be possible for you to visualize the RC discharge curve using Pygrace Running programs in batch mode If your program is more than a few lines long its better to save it in a file to make future modifications easier The convention is that Python program files have an extension of py a typical name would be hello py Once the file has been created you can run it by typing python hello py at the Operating System command prompt 4 An earlier version of this document had explained these functions but participants of a workshop on Phoenix found it difficult to understand so we thought og eliminating them from this introductory document 95 Chapter 9 Appendix C Signal Processing with Python Numeric One of the disadvantages of Python is that it is slow a Python program runs considerably slower than an equivalent C program This becomes an issue when we start doing compute intensive applicat
28. 200 microseconds If we wish to measure static or slowly changing parameters like temperature accurately we better use 10 bit resolution and a conversion delay of over 200 micro seconds If the objective is to visualize plot a graph of a fast varying signal it is better to use 8 bit resolution and a conversion delay of 10 micro seconds We will do one or two experiments to have a better idea of how things work First connect digital output D3 to ADC channel 0 and execute 24 gt gt gt p write_outputs 15 p gt gt gt p set_adc_size 2 gt gt gt p set_adc_delay 200 gt gt gt p select_adc 0 gt gt gt p read_adc 1023 gt gt gt p zero_to_5000 1148537333 2460589 5000 0 The ADC is now working in 10 bit mode the function call p set__adc_ size 2 does this digital output pin is high close to 5V ADC range is 0 to 5000mV so the ADC will output a value close to 1023 maximum possible 10 bit number The zero_to_5000 function converts the output of the ADC into voltage from 0 to 5000 mV irrespective of the adc data size 8 ro 10 bits gt gt gt p set_adc_size 1 gt gt gt m p read_adc gt gt gt print m 1 255 The ADC is now working in 8 bit mode maximum output is 255 the range is 0 5000mV and the input is close to 5V so the output should be close to 255 3 5 2 Waveform Digitization In certain applications you will be required to capture data from one or more
29. 2r v v v offset gain return v ccs_current p select_adc 0 p set_adc_size 2 p set_adc_delay 200 strt p zero_to_5000 0 for x in range 1000 res p zero_to_5000 r v2r res 1 temp r2t r print 45 2f 5 2f res 0 strt temp time sleep 1 0 Even though the experiment looks simple there are several errors that need to be eliminated The CCS is marked as 1 mA but the resistors in the circuit implemented that can have upto 1 error To find out the actual 52 current do the following Take a 100 Ohm resistor and measure its resistance R with a good multimeter Connect it from CCS to ground and measure the voltage V across it Now V R gives you the actual current output from CCS For measurements around room temperature the voltage output is under a couple of hundred millivolts For better precision this need to be amplified to 5V to utilize the full range of the ADC A gain of 20 to 30 depends on the upper limit of measurement can be implemented using the variable gain amplifiers The offset voltage of the amplifier should be measured by grounding the input and subtracted from the actual readings The actual gain should also should be calculated by measuring the input and output at a a couple of voltages Another method of calibrating the setup is to measure the ADC output at 0 and100 and assume a linear relation which may not be very accurate between the ADC output and the temperature
30. 4 79 76 76 79 81 82 85 91 96 97 98 101 Chapter 1 Introduction Phoenix M is an equipment that can be used for developing computer inter faced science experiments without getting into the details of electronics or computer programming For developing experiments this is a middle path between the push buttonsystems and the developfromscratch approach Emphasis is on leveraging the power of personal computers for experiment control data acquisition and processing Phoenix M can also function as a micro controller development system helping embedded system designs Phoenix M is developed by Inter University Accelerator Centre t IUAC is an autonomous research institute of University Grants Commission India providing particle accelerator based research facilities to the Universities This document provides and overview of the equipment its operation at various levels of sophistication and several experiments that can be done using it 1 1 Objectives of PHOENIX One may question the relevance of using a computer for experimental data collection and advocate taking readings manually to improve the experimen tal skill of the students The objective of Phoenix is to approach the process Being a product meant for the education sector IUAC has granted permission for commercial production of it without any royalty For more details visitwww iuac res in elab phoenix vendors of laboratory experiments from a diffe
31. 8 using the scripts as shown below compile bat blink load bat blink Now the LED should start blinking What is happening How our ADC input became an output The program blink c has configured the PORT A as an output port and we have not enabled the ADC All the four ports can be configured as input or output in a similar fashion 5 2 2 Writing to the LCD Display Phoenix M has a provision to attach a 16 character LCD display to the board We have used the Hitachi 44780 based LCD display that is available easily The connections between the LCD module and ATmegal6 are shown in the table5 2 There are total seven connections between LCD and ATmega16 four of them are data lines and three are control lines Programming details of the LCD module and the example programs are available on given on the CD We will use the file led16 c from the cprog directory A program named ledtest c also is given in the same directory Here is a small program hello c that writes to the LCD display LCD Display was the main debugging tool during Phoenix M program development include lt stdio h gt include lt stdlib h gt 72 Pin Function Description ATmega8 Pin 1 Vss Ground pin 2 Vdd 5V supply 3 Vo Intensity OV for maximum 4 RS HIGH for Data LOW for Commands PD4 5 R W H for read L for write PD3 6 EN Enable signal PD2 7 DBO 8 DBI 9 DB2 10 DB3 11 DB4 PA4 12 DB5 P
32. 94 1 SSA door ero d amp a Ved NNA WO ON zn T z z 7 z 6pin con pin Signal AT pin P Port pin 1 RESET 9 16 2 SCK 8 1 3 MISO 7 11 4 MOSI 6 2 5 6 GROUND Il 19 Table 5 1 Parallel port programming cable code To set 8MHz clock speed with external crystal and disable the JTAG interface set the fuse LOW to EF and HIGH to D9 uisp dprog dapa dpart atmegai6 dlpt 0x378 wr_fuse_1 OxEF uisp dprog dapa dpart atmegai6 dlpt 0x378 wr_fuse_h 0xD9 The Phoenix M programs are written for 8MHz clock speed The RS232 baud rates are derived from the processor clock and it is 38400 baud for 8MHz clock The Python library uses this speed and the processor MUST be set to 8MHz for things to work Refer to the ATmegal6 documentation for more details 5 1 3 Uploading the HEX file The executable file is generated in the HEX format It is uploaded to AT megal6 through the PC parallel port using the cable provided The pin connections of the cable are shown in table5 1 One end of the cable is a 6 pin connector and other end is 25 pin D connector for the PC parallel port A program named wisp is used for uploading the HEX file The same program is used for setting the fuses of ATmegal6 The script load bat listed below contains the commands to upload a file The usage of this is explained in the examples section echo Uploading 1 c uisp dprog dapa dpart atmegai6 dlpt 0
33. A5 13 DB6 PA6 14 DB7 PA7 15 x Back light LED control not used 16 x Table 5 2 LCD connections include lt inttypes h gt include lt avr io h gt include lcd16 c int main void DDRA DDRD initDis 255 PORT A as output 255 PORT D as output play 0 writeLCD H writeLCD e writeLCD 1 writeLCD 1 writeLCD o 73 5 2 3 Analog to Digital Converters The on chip 10 bit ADC has 8 multiplexed inputs ATmegal6 has analog supply volatge pin AVCC and an external ADC reference voltage pin In ternal reference voltage source also has been provided T Phoenix M circuit gives same 5V DC to both AVCC and AREF Operation of the ADC is con trolled through the special registers provided for that purpose ADCSRA ADMUX ADCL ADCH etc are the important registers to control the ADC Let us explore the ADC functioning using the program adc c listed below which reads the input of channel 0 and writes the digital output to the LCD display include lt stdio h gt include lt inttypes h gt tinclude lt avr sfr_defs h gt include lt avr io h gt include 1lcd16 c uint8_t lo hi uint16_t dat 16 bit unsigned datatype int main DDRA Oxf0 4 bits ADC Input 4 bits LCD data output DDRD 255 PORTD as output for initDisplay ADMUX 0 External reference 10 bit data channel 0 ADCSRA BV ADEN BV ADSC 7 Enabl
34. CD and run the install script by typing sh install sh This will install all the necessary tools for software development on AVR micro controllers including ATmegal6 On MS Windows run the self ex tracting archive Win AV RGCC eze to install the development suite Exam ple programs are available inside directory cprogs on the CD On most systems this will be usr lib python2 x where x is the version number 15 2 4 Powering Up Connect the the provided serial cable between the 9 pin D connector on the Phoenix box and COM1 first serial port of the PC Connect the 9V DC adapter to the socket on the Phoenix box and apply power The power LED near the 5V socket should light up The easiest way to use Phoenix M is to boot the PC with the supplied GNU Linux live CD you will get a text prompt along with instructions on how to proceed further Enter graphics mode by running the commands xconf followed by startx You can read various documents concerning Phoenix M and other other ed ucational tools by simply running the browser Start a command shell and you are ready to get into the fascinating world of Phoenix M 2If COM1 is not available you can use COM2 but you will have to make a very small change during library initialization 3If you using it under MS Windows install Python Interpreter Pywin32 Pyserial and Phoenix library modules provided on the CD Phoenix Library phm py should be copied to the di
35. Counters with Separate Prescalar Compare One 16 bit TImer Counter with Separate Prescaler Compare and Cap ture mode Real TIme Counter with Separate Oscillator Four PWM Channels 8 channel 10 bit ADC Byte oriented Two wire Serial Interface Programmable Serial USART Special Micro controller Features Power on Reset and Programmable Brown out Detection Internal Calibrated RC Oscillator External and Internal Interrupt Sources Six Sleep Modes Idle ADC Noise Reduction Power save Power down Standby and Extended Standby I O and Packages 32 Programmable I O Lines 40 pin PDIP 44 lead TQFP and 44 pad MLF Operating Voltages 66 MCK TO PEO PAO ADCO Tl PRI PA ADC1 INT2ZAINO PBZ C amp PAZ ADC2 OCOAINT PBSC 4 PAS ADC 55 Pet os Pad ADCA MOSI PES Cs PAS ADCS MISO PES CF PAG ADCS SCK PBT C PA ADCT RESET O p AREF VOC GND GND BNET XTAL2 PCT TOSC2 XTALI POE TOSC1 RED POO PCs TOI THD POI Ped TOO INTO Poe PCS TMS INT1 POS PCZ TCK OC1B PD PC1 50A OC1A PDS PCO SCL CPI PDS PO 002 Figure 5 1 ATmegal6 Pin diagram and DIP package 4 5 5 5V for ATmegal6 Speed Grades 0 16 MHz for ATmegal6 Power Consumption at 4 Mhz 3V 35 C Active 1 1mA Idle Mode 0 35mA Power down Mode lt 1 uA 5 1 Hardware Basics ATmegal6 interacts with the external world through four I O ports named as A B C and D The ports are
36. Innovative Experiments using PHOENIX Ajith Kumar B P Inter University Accelerator Centre New Delhi 110 067 amp Pramode C E I C Software Trissur Kerala Version 1 2006 Contents 1 Introduction Il 4 bieetives of PHOENIX aranea a be ee ee a E 1 2 Features for Developing Experiments 1 3 Microcontroller development system 1 4 Stand alone Systems 2 6 2 6 40 2 8245 2 pe Ss 2 Hardware and Software De Th front panel spaci a ose abe Bigs GSS Oy ered ee Bld ae ee E Y 2 2 Things to be careful about when using Phoenix 2 3 Installing Software for PC interfacing 2 3 1 Software for programming ATmegal6 Dice HOWELL ose cr ick deat aua week Aah wee Gee BE ae 3 Interacting with Phoenix M 3 1 The Digital Outputs 224 24 8 4 ee eee a Y 3 1 1 Blinking LED tp 8 6a ane he GO aaa Oe Rani et SELL Exercise t46 cA in ae Shin ae eh eee sd a J27 Digital Inputs ar BEE ee GS Si cle oe BS Aan dO a te ee oh a a 3 3 Waveform Generation and Frequency Counting 3 4 Digital to Analog converter DAC 3 5 Analog to Digital converter 20 20004 gl Introductions r sasa honk din eheats 3 ee hae gue tog 3 5 2 Waveform Digitization is ep ed es ek ES 3 6 Time Measurement Functions 3 7 lt Non programmable units wc 4 goes eee ee eae ee GS 10 11 14 15 15 16 3 7 1 Converting bipolar signals to unipolar
37. PE ou vd cba HE E 9LXEGOT teed OWI LLELLL FERE ahs HLEH 906ENZ 2 PPPPPP a0za0 1 40000 2 Nr vo 3 Ano evo b L Vo by O wa poe yOND ZON N9 N ai a ag MOk eza uppg a k or cha W zezenz 0L oza 10 oe x ME Sd Lj JF H L Ol GLY H vou Me x novo Sit NIYO 5 b 5 K f BBBRBEEB RE BRNRBRRRRR za tL eav zay Lav oady O oT gt anh OL ah SZEREPRE BOE 6 SBRSRESSS i m S Pos k BERBERS s S8aRBRESY L_ _o 0L exe F gretewLy n A lt 9 als sed E a 919 x db wines A a ypy PIP lt 933 yoyDDDD AF or Net cos 2 SIREL 8NA FERE BYRBRES Moo L BE 2o OL viH 260 L C blo LEERE EGLLEE n veon vun BERB FPBRBBB eN 9 E 8 OL 664 rr S0 i lala ai zr PEP A A Sal al NL NIH tdl Tr T Ho ans H inom no FEE TERRE T i S lt n lt ads 1noTN 5 NTN iB IS mns vm 1 n en anoor_ f__ noo t en sem b oN It S10 ads TOS a PRE 7 esen p Lanes i ma 9 ca S Bee Hor guaqvaH a E ca LIS wn a 210 an ma sE Ste NIY IN me 01 Se E a 5 zA na Bern Noo yo a Ho 60 HOLOANNOS 001 629 o lowd fi L TA Pr ee aes mn 1001 1 0 ane go noes ova FF RR 22 S a ZO0PNE oF oe eT HMO ree HNO 234 H H oon gagasaue son Se T INOA NA ST 4 t 22229999 ZAs ogzoszieni suo sa EN00 on zig 080 M aon OOF GIO ae E u00 u00 n go zo eis 40 2 1 sa a b T nog NH a OF OvosoaZn7 ON 2 ns 6 N Eye L ved L veo P wn Ano HYOA n diy vid NI FWOA L L L k o
38. alling edges Similarly we can measure the falling edge to rising edge time also using the p f2rtime 0 0 call From which we can calculate the period of the wave and the duty cycle The arguments can be different For example you can measure the time between a rising edge on one Input to a rising edge on another Input 28 Digital Inputs are specified by argument values from 0 to 3 If the Input is connected to the Analog Comparator use the argument value 4 as shown below gt gt gt p r2ftime 4 4 500 Time measurement capability is important for many experiments Direct measurement of the velocity of sound period of a pendulum etc will be done using this feature For measuring the time period of a signal applied to an Input we can use the function p multi_r2rtime pin skipcycles The skip cycles mentions the number of cycles to be skipped in between If it is zero you get the period of the wave Higher number can be used to get the effect of averaging The result of measuring a 1 KHz signal connected to Input 0 the result is the time taken for 10 cycles gt gt gt p multi_r2rtime 0 9 10000 You will find more information regarding these functions in the API reference 3 7 Non programmable units We have had a brief tour of all the programmable features which the Phoenix box provides There are a few functional units within the Phoenix box which can t be manipulated by code understanding how the
39. cal parameters into electrical signals The number of science experiments one can do with Phoenix M is limited mainly by the availability of sensor elements Here we describe several experiments that can be done using some sensor elements that are easily available During the tutorial introduction we interacted with Phoenix M by typing commands at Python prompt Typing them in a file using a text editor and executing under python makes cor recting errors much easier Here we will follow that approach and all the programs listed below are available on the Phoenix CD 4 1 A sine wave for free Power line pickup There are two types of electric power available generally known as AC and DC power The Direct Current or DC flows in the same direction and is generally made available from battery cells The electricity coming to our houses is Alternating Current or AC which changes the direction of flow continuously What is the nature of this direction change The frequency of AC power available in India is 50 Hz Let us explore this using Phoenix M and a piece of wire A frequency of 50 Hz means the period of the wave 34 is 20 milliseconds If we capture the signal for 100 milliseconds there will be 5 cycles during that time interval Let us digitize 200 samples at 500 microsecond intervals and analyze it Connect one and of a 25 cm wire to the Ch0 input of the ADC and let the other end float The 50 Hz signals picked up by the ADC can be displa
40. cute the following code segment gt gt gt p set_frequency 1000 gt gt gt m p read_block 100 50 0 gt gt gt p plot m Figure 3 1 is the plot you would get Let s now play with the multi_ read_ block function The function reads analog data from multiple channels remember the Phoenix ADC has 4 channels and returns them as a list of the form ts1 adval0 advaln ts2 adval0 advaln where adval0 is value read from channel 0 advall is data read from channel 1 and so on Let s try an experiment Connect channel 0 of the ADC to GND and Channel 1 to 5V Now execute the following code segment 26 Figure 3 1 Square wave digitized by ADC gt gt gt p add_channel 1 gt gt gt m p multi_read_block 100 50 0 gt gt gt print m Here are the first few readings 0 19 607843137254903 4960 7843137254904 50 0 0 4980 3921568627447 100 0 0 4980 3921568627447 150 0 0 4980 3921568627447 200 0 0 4960 7843137254904 Note the time stamp values increasing in steps of 50 micro seconds while channel 0 and channel 1 values stay close to OV and 5V How does the multi_read_ block function know what all channels have to be digitized Code running on the Phoenix box maintains a channel list which will by default have only channel 0 You can add channels to the list by calling add_ channel and remove channels from the list by calling del_ channel Whenever a
41. d the print over statement executes The loop prints numbers from 0 to 9 and then terminates The for loop in Python is used mostly for the purpose of examining elements of an array one by one Here is an example a 10 hello 20 for i in a print i The loop will repeat as many times as there are elements in the array a The first time value of i will be a 0 next time a l and so on Here is a nested for loop written under the assumption that all the elements of the list being processed are themselves lists a 1 2 3 4 5 hello 10 for m in a for i in m print i The value of m in the first iteration of the outer loop will be 1 2 3 The inner loop simply extracts all the elements of this list and prints them out The process is repeated for the two other sub lists 92 If statement Here is a Python code segment which makes use of an if statement a input if a gt 5 print hello elif a lt 2 print world else print nothing Importing libraries You might sometimes have to make use of functions which are not part of the core Python interpreter but defined in some external library good examples are the math functions sin cos etc Here is how you go about doing it gt gt gt import math gt gt gt math sin 0 0 0 gt gt gt math cos 0 1 0 2S The import statement lets you use the functions defin
42. e Start Low clock speed while ADCSRA amp 1 lt lt ADIF wait for ADC conversion lo ADCL hi ADCH sbi ADCSRA ADIF get ready for next conversion dat hi lt lt 8 lo write16 dat 74 delay 10000 5 2 4 Pulse width modulation using Timer Counters ATmega16 has three Timer Counter units two of them are 8 bit and one is 16 bit For a quick demo let us generate a 31 25 KHz pulse on OC2 pin 21 For this we program the control register and set point registers of TC2 as shown in the code pwm c below include lt avr sfr_defs h gt include lt avr io hb gt int main DDRD 255 OCR2 127 Change this from 0 to 255 for changing duty cycle TCCR2 BV WGM21 BV WGM20 BV COM21 1 Fast PWM mode TCNT2 0 Timer Counters are very versatile and programming them could become re ally complex depending on the application Read the documentation for more details 79 Chapter 6 Building Standalone Systems The Phoenix M hardware can be converted into standalone systems that can be used independent of the PC The LCD panel provides a minimalistic display device The front panel sockets can be configured for Input Output of various kinds The concept is demonstrated with the following examples 6 1 Frequency Counter for 5V square wave sig nal The CNTR socket is connected to PBO T0 We will configure Timer Counter 0 to count the external pulses applied to t
43. e setup and the AVR GCC compiler The program is compiled on the PC and the executable output is uploaded to the micro controller through a cable connected to the Parallel port of PC The AVR GCC compiler for both GNU Linux and MS Windows is provided on the Phoenix CD Most of the ATmegal6 micro controller Input Output pins are available through the front panel sockets A 16 Character LCD Display is provided along with C routines to access it An introduction to ATmegal6 micro controller is given below For more details refer to the PDF document on the CD Features High performance Low power AVR 8 bit Micro controller Advanced RISC Architecture 131 Powerful Instructions Most Single Clock Cycle Execution 32 x 8 General Purpose Working Registers Up to 6 MIPS Throughput at 16MHz Fully Static Operation On chip 2 cycle Multiplier 65 Nonvolatile Program and Data Memories 16k Bytes of In System Self Programmable Flash Optional Boot Code Section with Independent Lock Bits 512K Bytes EEPROM Programming Lock for Software Security JTAG IEEE std 1149 1 Compliant Interface Boundary scan Capabilities According to the JTAG Standard Extensive On chip Debug Support Programming of Flash EEPROM Fuses and Lock Bits through the JAGS Interface Peripheral Features On chip Analog Comparator Programmable Watchdog Timer with Separate On chip Oscillator Master Slave SPI Serial Interface Two 8 bit Timer
44. e symbol A represents 10 in decimal symbol B represents 11 and so on Conversion to decimal It s very easy to convert a hexadecimal number to decimal let s take the hex number 12 as an example The procedure is 2 16 1 16 The result is 18 which is the equivalent decimal number One more example would make things clear Let s convert the number 2ab3 to decimal The procedure is 3 16 11 164 10 167 2 16 We are simply taking each digit of the number from the least significant rightmost to the most significant converting it to decimal and multiplying it by increasing powers of 16 83 Conversion to binary Lets convert the hex number 2A to binary the idea is to take each hex digit and convert it into a 4 bit binary number and append all the 4 bit sequences obtained The number A in hex is 10 in decimal the equivalent binary is 1010 The number 2 in binary is 0010 So 2A is 00101010 The reverse conversion binary to hex too is simple group the binary num ber into 4 bit sequences convert each 4 bit sequence to hex and append all the hex digits together 84 Chapter 8 Appendix B Introduction to Python Language After booting your machine with the Live CD and logging in as root as per the instructions provided on the boot up screen you should familiarize yourself with the Python programming language as it will be your primary vehicle for interacting with the Phoenix b
45. ed in the math library note that the function names have to be prefixed with the library name An alternate notation is gt gt gt from math import gt gt gt sin 0 0 0 gt gt gt cos 0 1 0 Sy 93 Note that now we don t have to prefix the function name with the library name With this much of a background in Python we are ready to conduct experiments with our Phoenix box Later as the need arises we shall explore a bit more of Python syntax looping plotting higher order functions etc to make our experiments more sophisticated Data manipulation in Python The Phoenix M library makes very heavy use of the elegant list manipulation abilities of Python As you start writing more advanced programs on your own you will feel the need for doing non trivial list manipulations Let us look at two examples Let s say we have a list of the form 1 20 2 15 3 36 Now we want to generate a new list of the form 1 2 3 20 15 36 Here is a program which does just this a 1 20 2 15 3 36 b I l for v in a b 0 append v 0 b 1 append v 1 print b Now lets do the reverse process ie take a list of the form 1 2 3 20 15 36 and convert it into a list of the form 1 20 2 15 3 36 a 1 2 3 20 15 36 b n len a 0 for i in range n b append a i bli 94 There are 3 functions in Python map filter and reduce using
46. er hand moving it near any electrical equipment etc do not touch any power line You can also analyze other wave forms if you have a signal generator 4 2 Capacitor charging and discharging Every student learning about electricity knows that a capacitor charges and discharges exponentially but not very many has seen it doing so Such ex periments require fast data acquisition since the entire process is over within milli seconds Let us explore this phenomena using Phoenix M All you need is a capacitor and a resistor Refer Figure 4 4 on page 40 for the experimental setup The RC circuit under study is connected between the Digital output socket D3 and Ground The voltage across the capacitor is monitored by the ADC channel 0 The voltage on D3 can be set to OV or 5V under software control Taking D3 to 5V will make the capacitor charge to 5V through the resistor R and then taking D3 to OV will cause it to discharge All we need to do is digitize the voltage across C just after changing the output of D3 Let us study the discharge process first The python program cap py listed below does the job import phm time 38 File Edit View Help Source _ Destination Graph GO fshown 2 sets GO shown 2 sets GO SO 2 200 GO S1 2 200 GO S1 2 200 Se A fit Main Advanced Formula ly A0 sin 2 PI Al xZ 1000000 A2 AS Parameters 4 4 Tolerance jo Iterations 15 7 a
47. er resolution can set by the user default is 8 bit The speed of the ADC the time it takes to convert an analog input to digital also can be set within certain limits To explore the ADCs connect the DAC 23 output to channel zero of the ADC and issue the following commands gt gt gt p set_dac 200 gt gt gt p select_adc 0 gt gt gt print p read_adc 1148439372 3935859 199 The select _adc function is used for selecting the channel to which we have connected the input The read_adc call returned two values instead of one The first is the system time stamp from the PC we are not concerned with it at present and the second is the output of the ADC received from Phoenix M The value is not 200 but 199 this is mainly due to the limitations of the DAC The above exercise can be done more conveniently by the following functions gt gt gt p set_voltage 4000 gt gt gt m p zero_to_5000 gt gt gt print m 1148440112 655 4019 6078431372548 gt gt gt print m 1 4019 6078431372548 The zero_to_5000 function converts the ADC output into milli volts the first number in the output is again the time stamp from PC The maximum resolution of the ADC output is 10 bits but it can be reduced to 8 bits for faster data transfer The conversion time of the ADC also can be set by the user by calling p set__adc_ delay When set to 10 bit resolution the conversion time should be set to larger than
48. g using the simple pendulum equation w L 972 cm sec The errors are due to the simple pendulum approaximation and the error in measurement of length 58 DC Motor 200x X 5 2 CHO GND Pendulum Figure 4 22 Pendulum block diagram 4000 4 2000 Voltage mV o 2000 4000 E 4 Time sec Figure 4 23 Decaying oscillations 59 File Edit View Help SOLUCE Destination Graph Graph 0 shown 2 sets 0 shown 2 sets GO SO0 2 1 OO f 0 87 2 100 AD 528 6 E Bounds AT 787082 _J Bounds AZ j3 3905 _J Bounds Figure 4 24 Pendulum Data fitted with equation GNDC C DO output DO Input gene Contact sensor Figure 4 25 Gravity by free fall 4 9 3 Acceleration due to gravity by time of flight method There are many ways to time the free fall of an object under gravity here is one interesting idea Take a small relay and remove its cover so that you can access the coil directly Connect one end of the coil to the Digital Output DO the only output with transistor buffering We have used the coil from 12V relay with a coil resistance of 150 Ohms The coil resistance should not be less than 100 Ohms and it should be able to magnetically hold a metal ball of radius around 1 cm The experimental setup is shown in figure 4 25 Digital Output DO is made high to ene
49. h ends of the 1 KOhm resistor is known We have tried to study different diodes including Light Emitting Diodes with different wavelengths The code iv py is ran for each diode and the output redirected to different files For example python iv py gt red dat after connecting the RED LED The code iv py is listed below import phm time p phm phm 43 4148 DR150 RED GREEN YELLOW w T WHITE Current mA N T i 0 E 0 500 1000 150 a 1 1 0 2000 2500 3000 Voltage mV Figure 4 9 Diode Characteristics p set_adc_size 2 p set_adc_delay 200 va 0 0 while va lt 5000 0 p set_voltage va time sleep 0 001 vb p zero_to_5000 1 va va 19 6 print vb va vb 1000 0 The program output is redirected to a file and plotted using the program xmerace by specifying all the data files as command line arguments The output is shown in the figure 4 9 Note the difference between different diodes If the frequency of the LEDs are known it is possible to estimate the value of Plank s constant from these results 4 4 Mathematical operations using RC circuits RC circuits can be used for integration and differentiation of waveforms with respect to time For example a square wave of a particular frequency can be integrated to a triangular wave using proper RC values In this experiment 44 PWG ADC CHO 1K ADC CH1 1uF i Figure 4 10
50. h may bewilder a newbie 86 gt gt gt 0x10 16 gt gt gt 010 8 gt gt gt hex 255 Oxf gt gt gt oct 8 010 Se The Ox prefix stands for hexadecimal and a simple 0 prefix makes the constant an octal constant The dynamic nature of Python Let s look at a few lines of Python code gt gt gt al gt gt gt type a lt type int gt gt gt gt a hello gt gt gt type a lt type str gt Python does not have any kind of variable declaration unlike C C A Python variable is created when an assignment statement is executed So the variable a is created only when the statement a 1 executes the interpreter assigns the type int to a at that point of time Later a can be assigned to an object of an entirely different type as in the example above Strings A Python string is a sequence of characters written within single or double quotations 87 gt gt gt a hello gt gt gt b world gt gt gt print al0 h gt gt gt print a 1 o gt gt gt print a b helloworld gt gt gt printa 3 hellohellohello Let s try another experiment gt gt gt str 123 123 gt gt gt str 1 23 1 23 SS gt gt gt ord A 65 gt gt gt ord a 97 ese The manipulations done above are very simple You can extract individual characters of a string by indexing it
51. he range of 10 20 mV You should take this effect in consideration when you are doing precise measurements 3 7 3 Non Inverting variable gain Amplifier There is one Non Inverting amplifier whose gain can be controlled by a plug gin resistor Rg connected between the Yellow socket and ground The Inter nal feed back resistor is 10 KOhm and the gain will be 1 10000 Rg This unit is useful for amplifying the RTD type temperature sensor outputs 3 7 4 The Constant Current Source Module Phoenix box has a socket labeled CCS it s a ImA constant current source Connect a 1K resistor between the CCS and ground and measure the voltage across the resistor it will be 1V The current through a circuit should vary 31 as you change the value of the resistance but a CCS will maintain a constant flow in this case 1 milli ampere Try to verify this behavior The CCS module is useful when measuring temperature using thermis tors 3 8 Plug in Modules There is a 16 pin connector on the front side of Phoenix M It is meant for plugging in the LCD display and other additional circuitry as explained below 3 8 1 16 character LCD display 3 8 2 High resolution AD DA card 3 8 3 Radiation detection system 3 9 Other Accessories For doing experiments using Phoenix we require different kinds of sensors Sensors for measuring temperature pressure etc are commercially available Most of them provide a low level voltage out
52. he ADC inputs of Phoenix and record the value at regular intervals There are several sensors available for measuring temperature like thermocouples platinum resistance elements and solid state devices like AD590 and LM35 They work on different principles and require different kind of signal processing circuits to convert their output into the 0 to 5V range required by the ADC We will examine some of the sensors in the following sections 49 Figure 4 16 Collision sound microphone CCS gain 1 10K 330 Figure 4 17 PT100 Circuit 4 7 1 Temperature of cooling water using PT100 PT100 is an easily available Resistance Temperature Detector RTD that can be used from 200 C to 800 C It has a resistance of 100 Ohms at zero degree Celsius the temperature vs resistance charts are available The circuit for connecting PT100 with Phoenix M is shown in figure 4 17 The PT100 sensor is connected between the 1mA Constant Current Source and ground The voltage across PT100 is given by Ohm s law for example if the resistance is 100Q the voltage will be 100 1 mA 100 mV This must be amplified before giving to the ADC The gain is chosen in such a 50 way that that amplifier output is close to 5V at the maximum temperature we are planning to measure In the present experiment we just observe the cooling curve of hot water in a beaker The maximum temperature is 100 C and the resistance of PT100 is 138Qat that point that gives 138
53. hich has to be measured by grounding the input and accounted for when making precise measurements 11 One variable gain non inverting amplifier This is located on the bot tom right corner of the front panel The gain can be programmed by connecting appropriate resistors from the Yellow socket to ground 12 Two offset amplifiers to convert 5V to 5V signals to 0 to 5V signals This is required since our ADC can only take 0 to 5V input range For digitizing signals swinging between 5V to 5V we need to convert them first to 0 to 5V range Input is GREEN and output is BLUE To reduce the chances of feeding signals to output sockets by mistake the following Color Convention is used e GREEN Inputs digital or analog 13 e RED Digital Outputs and the 5V regulated DC output e BLUE Analog Outputs e YELLOW Gain selection resistors e BLACK Ground connections 2 Things to be careful about when using Phoenix 1 The digital output pins can drive only 5mA Don t connect any load less than 1K Ohm to them 2 Digital output DO is transistor buffered and can provide 100 mA Don t use it for timing controls 3 Digital and ADC inputs should not be negative or above 5V ie should be from 0 to 5V 4 Variable gain amplifier outputs should be connected to Digital Inputs only through a One KOhm series resistor 5 Amplifier inputs should be within 5 to 5V range 6 Output pins should not be tied together 7 Do not
54. his case we are building a tuple containing a b and a b and returning it 8 0 1 1 Exercises 1 Write a function which accepts time in seconds and returns the distance travelled by an object falling under gravity Test it out 2 Write a function which accepts four co ordinates x1 yl x2 y2 and returns the distance between x1 y1 and x2 y2 Be careful with the way you do the indentation if your function has multiple lines each line should be indented at the same level use a single tab before each statement and do not mix space and tab The Python interpreter uses indentation to judge which all statements are within a function or a loop if you don t get it right you might end up with subtle syntax errors 3Called a parameter or argument to the function 91 While and For loops Here is an example of the Python while loop a 0 while a lt 10 print a a a 1 print over The indented statements are within the body of the loop Note the use of colon after while This is the way the loop works the Python interpreter first evaluates the expression a lt 10 as it is true the body is executed The interpreter again evaluates the expression a lt 10 which is found to be true so the body is executed once again The sequence repeats until the expression evaluates to false which happens when a is 10 at this point control comes out of the loop an
55. his pin and count the number of pulses for one second The 16 bit Timer Counter TC1 will be programmed to run on a 1 MHz clock generated internally to generate a signal when we reach one second The result is displayed on the LCD panel The program frcount c is listed below include lt stdio h gt include lt stdlib h gt include lt inttypes h gt Hinclude lt avr sfr_defs h gt include lt avr io h gt include 1lcd16 c 76 uint32_t x uinti6_t tmp16 uint8_t tmp8 char ss 20 int main DDRA Oxf0 4 bits ADC Input 4 bits LCD data output DDRB 0x00 Configure as input PORTB 255 DDRC Oxf0 Low nibble Input amp High nibble output PORTC 15 Enable pullup resistors low 4 DDRD 255 PORTD as output Three lines of code below generates a 31 25 KHz pulse on PWG Connect PWG to CNTR for testing the standalone frequency meter OCR2 127 Change this from 0 to 255 for changing duty cycle TCCR2 BV WGM21 BVCWGM20 BV COM21 1 Fast PWM mode TCNT2 0 Frequency counter code starts here while 1 TCCR1B BV WGM12 BV CS11 Wavegen mode Clock 8 to TCC1 TCCRO 7 normal External clock TIFR 255 clear all flags OCR1A 49999 tmp16 0 tmp8 0 TCNTO 0 counts external input TCNT1 0 to keep time with clk 8 while 1 if TIFR amp BV OCF1A 50000 usecs elapsed if tmp8 20 TT TCCRO 0 1 second Stop c
56. ial port Free Software platforms like GNU Linux is highly recommended Required software for both GNU Linux and MS Windows are provided on the CD The system can also be used by booting from the Live CD without in stalling anything to the computer hard disk 1 3 Microcontroller development system This is another level of application of Phoenix M and those who are only interested in developing PC interfaced experiments may ignore it The ATmeag16 1 microcontroller inside Phoenix M can be programmed in C or assembler The program is compiled on the PC and the output hex format file is uploaded to the micro controller through a cable connected to the Par allel port of PC The C compiler and development tools for this purpose are provided on the CD for both GNU Linux and MS Windows operating sys tems Most of the ATmega8 micro controller Input Output pins are available through the front panel sockets A 16 Character LCD Display is provided along with C functions to access it Details of using Phoenix M as a micro controller development system will be discussed in chapter 5 1 4 Stand alone Systems The unit can be converted into standalone equipment like frequency counter function generator temperature controller etc by loading appropriate pro grams and using the sockets and the LCD display for Input Output Example applications will be discussed in chapter 6 Chapter 2 Hardware and Software Phoenix M kit comes with some accesso
57. ified by pin2 to go high or low EXAMPLE p set2rtime 0 1 DAC Functions set dac PROTOTYPE void set_ dac integer n DESCRIPTION Write a one byte value to the 8 bit DAC The DAC output varies from 0 to 5000 mV Writing a 0 to the DAC results in an output voltage of 0 and writing a 255 results in an output voltage of 5V Intermediate values give appropriately scaled outputs Al most always you will not have to use this function in your code the set_ voltage function is much more convenient Note that using the PWG by calling set_ frequency will re sult in the DAC output changing these units should not be used at the same time EXAMPLE p set_ dac 127 107 set voltage PROTOTYPE void set_ voltage integer n DESCRIPTION Set the output voltage of the DAC The value of n should be an integer between 0 and 5000 It represents voltage in mV EXAMPLE p set_ voltage 1250 ADC functions read_ adc PROTOTYPE tuple read_adc void DESCRIPTION Digitizes the analog voltage on the current ADC channel set by the select_adc call and returns a number in the range 0 255 or 0 1023 depending on the ADC sample size set by the set_adc_size function and the system time stamp as a tuple EXAMPLE p read_adc 108 select adc PROTOTYPE void select__adc integer channel DESCRIPTION Selects the current ADC channel The functions read_ adc minus5000_ to 5000 zero_ to _ 5000 and read_ block
58. ing falling edge on the digital input or analog comparator input pin specified by rx rx 0 3 means digital inputs DO to D3 rx 4 means analog comparator input If pol is 0 the pulse is logic HIGH and if it is 1 the pulse is logic LOW This call is useful for doing experiments like measuring veloc ity of sound using ultrasound transducers the idea is to send out a pulse on the transmitter and wait for reception at the receiver EXAMPLE p pulse2rtime 0 1 20 0 r2ftime r2rtime f2rtime f2ftime PROTOTYPE integer r2ftime integer pinl integer pin2 remaining functions have similar prototypes DESCRIPTION r2ftime returns delay in microseconds between a rising edge on pinl and falling edge on pin2 the pins can be the same Pin numbers 0 to 3 indicate digital input pins DO to D3 and pin number 4 stands for the analog comparator input The remaining functions behave similarly computing the time difference between two consecutive rising edges falling and rising edges and two consecutive falling edges However there is one restriction In the case of r2rtime and f2ftime the pins CAN NOT be the same EXAMPLE p r2ftime 0 1 106 set2rtime set2ftime clr2rtime clr2ftime PROTOTYPE integer set2rtime pin1 pin2 remaining functions have similar prototypes DESCRIPTION These functions set clear a digital output pin specified by pinl and wait for the digital input or analog comparator pin spec
59. ions like say finding out the Fourier Transform or doing matrix math But there is a way out it s possible to call high speed C code directly from Python The designers of the Numeric extension to Python have taken this approach and the result is a powerful library using which we can do complex numerical computation efficiently Let s start with a simple program gt gt gt from Numeric import gt gt gt x array 1 2 3 4 gt gt gt y sin x gt gt gt print y y 0 The function array takes an ordinary Python list as argument and returns a special Numeric array The Numeric array is very different from a Python list even though it can be indexed like a list it can be used to store only integers real numbers or complex numbers There are specialized functions to manipulate the elements of a Numeric array at a very high speed The 96 sin function used in the program above is one example it is not the usual Python sin function you note that this function accepts a Numeric array and finds out the sin of each and every element of the array a new array holding the computed values is returned This is the behaviour of almost all Numeric function they act on arrays as a whole 9 1 Constructing a sampled sine wave Let s imitate what the Phoenix ADC does in software we will sample a 50Hz sine wave at a frequency of 1KHz we will take 200 samples The samples will be
60. ital Input D3 through a 1K resistor The interval between the output pulse and the rising edge of D3 is measured by the following program piezo py The output is redirected to a file import phm p phm phm p write_outputs 0 for x in range 10 print p pulse2rtime 3 3 13 0 To avoid gross errors in this experiment one should be aware of the follow ing Applying one pulse to the transmitter piezo is like banging a metal plate 3It is very important to use this resistor The amplifier output is bipolar and goes negative values Feeding negative voltage to D3 may damage the micro controller The 1KOhm resistor acts as a current limiter for the diode that protects the micro controller from negative inputs 54 to make sound it generates a train of waves whose frequency is around 40 KHz The receiver output is a wave envelope whose amplitude rises quickly and then goes down rather slowly When we amplify this signal one of the crests during the building up of the envelope makes the Digital Input HIGH When we increase the distance between the crystals the amplitude of the signal also goes down At some point this will result in sudden jump of 25 microseconds in the time measurement which is caused by D3 going HIGH by the next pulse This can be avoided by taking groups of reading at different distances varying it by 3 to 4 centi meters 4 8 2 Condenser microphone Velocity of sound can be measured by banging two metal plates
61. ld be 270mV An ADC helps us convert this voltage into a numerical quantity Let s see how Say the minimum voltage we would like to measure is 0V and maximum is 5000mV ie 5V Let s divide this 0 5000 range into 256 discrete steps each step of size 19 53 ie 5000 0 256 The zeroth step is from 0 to 19 53 the first step from 19 53 to 39 06 and so on If we have a device which accepts as input a voltage in the range 0 to 5000mV and returns the number of the step to which the input belongs to our objective of converting the analog input to digital is achieved An 8 bit 8 bits give you 256 different numbers from 0 to 255 ADC does exactly this We call the number 8 the resolution of the ADC We note that there is a certain amount of inaccuracy in the conversion process an 8 bit ADC will resolve all voltages in a certain step to one particular step number thus you will not be able to differentiate whether your input was exactly OmV or lmV or 2mV or 19 53mV all these inputs simply map to step zero A 10 bit ADC can do a better job as 10 bits can hold numbers from 0 to 1023 1024 combinations a 0 to 5000mV range can be broken down into steps of size 5mV each Analog inputs are one of the important features of Phoenix M There are four channels of Analog inputs that can digitize a voltage between 0 to 5V Feeding a voltage outside these limits may damage the micro controller The Analog to Digital Convert
62. nction writes the number n to the digital outputs DO to D3 EXAMPLE p write_ outputs 1 read_ inputs PROTOTYPE integer read_inputs void DESCRIPTION The function reads data from the digital inputs and returns it as an integer EXAMPLE m p read_inputs print m 102 read_acomp PROTOTYPE integer read_acomp void DESCRIPTION Returns 1 or 0 depending on whether the voltage on the Ana log Comparator input is respectively less than or greater than 1 23V EXAMPLE p read_acomp Waveform generation frequency counting and time measurement set frequency PROTOTYPE integer set_ frequency integer n DESCRIPTION The function generates a square waveform on the PWG socket of the Phoenix box whose frequency is n Hz The frequency can vary from 15Hz to 4MHz We may not get the exact frequency which we have specified only something close to it The function returns the actual frequency in Hz Note that waveform genera tion is done purely in hardware the Phoenix box can perform some other action while the waveform is being generated The DAC unit should not be used while PWG is running doing so will result in a waveform of a different frequency EXAMPLE m p set_ frequency 1000 103 measure frequency PROTOTYPE integer measure_ frequency void DESCRIPTION Measure the frequency of the square waveform at the CNTR input Returns the frequency in Hz The function is very accurate for val
63. nging from 0 to 5V can be programmed to the socket marked PVS Programmable Voltage Source Execute the following lines of code and measure the output with a multimeter after each step gt gt gt p set_dac 0 gt gt gt p set_dac 128 gt gt gt p set_dac 255 The output can be varied from 0 to 5V in 256 steps When using this function you need to calculate the number to be used for a given voltage This can be avoided by using gt gt gt p set_voltage 2000 The output should now measure near 2000 millivolts Remember that you can set the voltage in steps of nearly 20 mV only since 5000 mV range is covered in 256 steps The DAC on the Phoenix box is made by filtering the Pulse Width Modu lated signal from the Programmable Waveform Generator PWG Due to this one can t use both PWG and DAC at the same time If you call set_ dac while a waveform is being generated on the PWG it s frequency will change Similarly if you call set_ frequency after fixing a specific voltage level on the DAC the voltage will change 22 3 5 Analog to Digital converter 3 5 1 Introduction Analog to Digital converters are a critical part of computerized measurement and control systems Let s say we wish to measure temperature a sensor like the LM35 converts temperature in degree Celsius to voltage in milli volts at a rate of 10mV per degree Celsius Thus if room temperature is 27 degree Celsius the sensor output wou
64. o h gt include lt stdlib h gt include lt inttypes h gt include lt avr sfr_defs h gt include lt avr io h gt include lcd16 c int gain 11 amplifier gain is 11 for 1K resistor uinti6_t tmp16 uint8_t tmp8 79 uint32_t x y char ss 20 int main DDRA Oxf0 DDRB 0x00 PORTB 255 DDRC Oxf0 PORTC 15 DDRD 255 ADMUX 0 while 1 ADMUX 0 ADCSRA BV ADEN while ADCSRA amp 1 lt lt ADIF tmp8 ADCL tmpi6 ADCH lt lt 8 sbi ADCSRA ADIF BVCADSC tmp8 4 bits ADC Input 4 bits LCD data Configure as input Low nibble Input amp High nibble output Enable pullup resistors low 4 PORTD as output 10 bit data channel 0 10 bit data channel 0 7 Low clock speed wait for ADC conversic sprintf ss 41d 41d x y x 10 while ss tmp8 writeLCD ss tmp8 x tmp16 x x 5000 x x 1023 gain y X x x 10 initDisplay Q tmp8 0 delay 32000 80 Floating point calculations are avoided Loading the floating point library will make the size of the executable beyond 16 kilo bytes 6 2 1 Exercise Modify the above system to make a temperature controller Pin 26 PC4 of ATmega8 is transistor buffered on the phoenix board This can be used for driving a 5V relay that in turn will switch the heater power On or OFF The state of PC4 can be controlled by software depending on
65. obtained from the width of the histogram peak 4 9 2 Nature of oscillations of the pendulum A simple pendulum can be studied in several different ways depending on the sensor you have got If you have an angle encoder the angular displacement of the pendulum can be measured as a function of time What we used is a DC motor with the pendulum attached to its shaft When the pendulum oscillates it rotates the axis of the motor and a small time varying voltage is induced across the terminal of the motor This voltage is amplified and 57 frequency S T 1 1 1 1 979 979 5 980 980 5 981 gravity g Figure 4 21 Measured g Histogram plotted as a function of time The experimental setup and output are shown in figure 4 22 on the facing page The program pend _digitize py is listed below The output of the program is send to a file and plotted using x mgrace The period of oscillation can be extracted by fitting the data with the equa tion of an exponentially decaying sinusoidal wave The equation used for fitting the data is the following A t Aosin wt 0Jet C e A t Displacement at time t e Ap Maximum displacement w Angular velocity 0 displacement at t 0 e d Damping factor e C Constant to take care of DC offset from amplifiers The angular velocity wis found to be 7 87 and the length of the pendulum is 15 7 cm The calculated value of
66. ounting break TIFR BV OCF1A if TIFR amp BV TOVO overflow after 255 counts tmp16 TIFR BVCTOVO Clear OVF flag x tmp16 x x lt lt 8 TCNTO sprintf ss 4ld x initDisplay tmp8 0 while ss tmp8 writeLCD ss tmp8 delay 20000 The above program also generates a 31 25 KHz square wave on PWG pin 21 of ATmega8 that can be used for quick testing of the system The following table gives the values measured by this program for different frequency inputs from a HP33120A function generator 78 Frequency from HP33120A displayed by ATmega8 program 50 50 100 100 1000 1000 5000 4999 10000 9999 50000 49992 100000 99983 500000 4999913 1000000 999828 For counting small amplitude signals amplify them using the gain blocks provided on Phoenix and feed to the CNTR input through a 1KOhm resistor in series 6 2 Room Temperature Monitor We use the LM35 temperature sensor along with phoenix M to display the room temperature on the LCD display LM35 is a three pin IC with 5V supply Ground and the output leads The output voltage is zero at 0 degree Celsius and increases 10mV per degree The output of LM35 is amplified by the non inverting amplifier A 1K resistor is used to get a gain of 11 The amplifier output is fed to ADC Ch0 The program 1m35 c listed below is uploaded to the system include lt stdi
67. own below along with the results obtained at each step print p measure_frequency signal connected to CNTR 904 print p r2ftime 0 0 signal to DO input 733 print p f2rtime 0 0 371 Exercise Cross check the above results with that predicted by the equa tion for frequency and duty cycle The resistor values used are of 1 tolerance and capacitor of 5 tolerance 62 4K7 O DO input 4K7 Figure 4 26 555 oscillator circuit 4 10 2 Mono stable multi vibrator The monostable circuit is wired up as shown in figure4 27 The 555 IC require a LOW TRUE signal at pin 2 to trigger it The output goes HIGH for a duration decided by the R and C values and comes back to LOW The following lines of code is used for triggering 555 and measuring the time interval from trigger to the falling edge of the signal from pin 3 p write_outputs 8 keep D3 high p pulse2ftime 3 0 1 1 1 usec wide LOW TRUE pulse on D3 to a falling edge 123 Again it is left as an exercise to the reader to verify whether 123 microseconds is acceptable based on the RC values used 63 10K D3 output 0 1UF Figure 4 27 Monostable multi vibrator using 555 64 Chapter 5 Micro controller development system The heart of Phoenix M hardware is an ATmegal6 micro controller The system comes with a pre loaded program that listens for commands from the PC through the Serial Port This program is developed using the same hardwar
68. ox Arithmetic Python http www python org is a very high level language with clear syntax and predictable behavior unlike C which never works the way you imagine it to work You can start interacting with it by invoking the com mand python at the interpreter prompt You would see something similar to this root don user manual python Python 2 3 4 1 Sep 11 2004 22 35 14 GCC 3 3 2 20031022 Red Hat Linux 3 3 2 1 on linux2 Type help copyright credits or license for more in formation ee 85 The gt gt gt sequence represents the Python prompt where you can interac tively enter short Python programs Let s try out our first program gt gt gt print 1 2 3 gt gt gt 1 2 3 gt gt gt print hello world hello world gt gt gt That s about as simple as you can get You can do all standard math operations Seeds 6 Sas DAE 8 SS 2 501 1125899906842624L SAL 2 0 gt gt gt 1 20 0 5 SSS Note that adding a suffix L converts the number to a long integer which can have as many digits as can be computed within the constraints of time and space It s possible to represent integer constants in three separate bases deci mal default octal and hexadecimal Be careful not to insert any additional space before the first character of each line you type at the prompt Python has some unusual interpretations for whitespace whic
69. polar ie between 5V and 5V it should be 0 otherwise The function reads from multiple ADC channels specified by a channel list on powerup the list will contain only channel 0 The functions get _chanmask add_ channel and del_ channel can be used to manipulate the channel list The list returned by the function will look like this assuming channel 0 and channel 1 are there in the channel list ts0 chanO_ val0 chan1_ val0 ts1 chanO_ vall chan1_ vall tsn chan0_ valn chan1_ valn The first element of each list is the time stamp and the subse quent elements are the readings in mV taken from the respective channels Care should be taken to see to it that np num_channels sample_ size is less than 800 which is the maximum buffer size allowed for storing ADC data EXAMPLE p add_channel 1 add channel 1 also to the list channel 0 is present by default v p multi_read_block 100 10 0 111 read _ block PROTOTYPE list read_ block integer np integer delay integer bipolar DESCRIPTION Similar to multi_read_ block only difference is that data is read from a single channel selected by the select adc call ExAMPLE p read_ block 100 10 0 set adc_ delay PROTOTYPE void set_adc_delay int delay_us DESCRIPTION Sets the delay between ADC conversions A delay of 6 to 100 microseconds is good for 8 bit conversions while 10 bit conversions will require more than 100 microseconds delay Default is
70. put proportional to the measured parameter This can be fed to one of the ADC inputs after amplification The gain decided in such a way that the maximum output from the sensor is amplified to the upper limit of the ADC input For example if we plan to measure temperature up to 100 celcius and the sensor output is 100 mV at that temperature the gain is selected is 50 to get a maximum 5V at the ADC input This is required to utilize the ADC to its maximum resolution There are several other sensors and accessories that we can make using available components 32 2N2222 Figure 3 5 Light barrier circuit 3 9 1 Light barrier The light barrier is a U shaped structure with a photo transistor and a Light Emitting Diode facing each other with a gap of 2 cm in between as shown in figure 3 5 There are three connections to the module Ground 5V supply and the signal output The output of the module is generally LOW and goes high when the light emitted by the LED is prevented from reaching the photo transistor By connecting this to Phoenix Digital Input sockets one can measure time intervals 3 9 2 Rod Pendulum 3 9 3 Pendulum motion digitizer using DC motor 3 9 4 Temperature Sensors 33 Chapter 4 Experiments Phoenix M is a computer interface with some added features Several ex periments on electricity and electronics can be done without much extra accessories Science experiments require sensor elements that converts phys i
71. read from the channel selected by invoking select adc EXAMPLE select_adc 2 select channel 2 minus5000_to_ 5000 PROTOTYPE tuple minus5000_ to_5000 void DESCRIPTION Reads the analog voltage on the current ADC channel and returns a voltage reading in mV between 5000 and 5000 This call is used only when we wish to read bipolar signals level shifted to 0 5V range by the X 5 2 amplifier System time stamp is also returned EXAMPLE p minus5000_ to_5000 109 zero _to_ 5000 PROTOTYPE tuple zero_ to_5000 void DESCRIPTION Reads the analog voltage on the current ADC channel and returns a voltage reading in mV between 0 and 5000 This call is used when we wish to read unipolar signals connected directly to the ADC channels System time stamp is also returned EXAMPLE p zero_ to_5000 cro_ read PROTOTYPE list cro_read integer np DESCRIPTION Special function to support the CRO program Assumes that ADC data size is 1 byte The parameter is the number of samples to take Returns a list of tuples with raw 8 bit ADC data EXAMPLE p cro_read 100 110 multi_read_ block PROTOTYPE list multi_read_block integer np integer delay integer bipo lar DESCRIPTION Returns a block of data from the ADC The first argument specifies the number of samples to read The second argument is the delay between two samples in microseconds The third argument should be 1 if the ADC reading is to be interpreted as bi
72. rectory Python24 lib Start python from the command prompt by typing python24 python at the C gt prompt 16 Chapter 3 Interacting with Phoenix M This chapter is a tutorial introduction on accessing Phoenix M from the PC using the Python Library The emphasis is on getting familiar with hardware and software features rather than doing actual experiments Phoenix M li brary functions are explained in Appendix D and a brief introduction to the Python programming language is given in Appendix B It is assumed that Python Interpreter and Phoenix M library are installed and the equipment is connected to the serial port of the PC Start the Python Interpreter from the command prompt You should see something like the following Python 2 3 4 1 Oct 26 2004 16 42 40 GCC 3 4 2 20041017 Red Hat 3 4 2 6 fc3 on linux2 Type help copyright credits or license for more information gt gt gt The first step is to import the phoenix library and create and object of type class phm This is done by the the following lines of code gt gt gt import phm gt gt gt p phm phm The variable p is an object of class phm and represents the Phoenix box in software These two lines must be present in the beginning of all Python 17 programs accessing Phoenix M Let us start by accessing the features of Phoenix M one by one Again we remind you NOT to connect any signals greater than 5 VOLTS to
73. rent plane Performing experiments should be the fun part of learning science subjects but students at the col lege level do the traditional lab experiments by just following a given set of inflexible steps to take some measurements Limitations of the apparatus does not allow taking sufficient data points involving fast changing parame ters like position of a moving body or a fluctuating temperature This to a major extent affects the accuracy of results especially where the time mea surements are concerned Generally the students take three readings and calculate the average value The statistical error analysis techniques are never done and are not possible owing to the lack of sufficient data One is forced to make assumptions whose validity cannot be checked The process of experiments is more or less done like performing a ritual and the students have no confidence in the results they obtain A more important point is that the ability to perform experiments with some confidence in the results opens up an entirely new way of learning science From the experimental data students can construct a mathemati cal model and examine the fundamental laws governing various phenomena Research laboratories around the world performing physics experiments use various types of sensors interfaced to computers for data acquisition They formulate hypotheses design and perform experiments analyze the data to check whether they agree with the theory Unfor
74. rgize the coil Now attach the metal ball to the relay and and release it under software control The ball falls on the contact sensor and takes the Input DO to LOW The code gdirect py is listed below import phm time p phm phm p write_outputs 1 energize the coil time sleep 2 time to attach the ball to the coil print p clr2ftime 0 0 time of flight The value of gravity g can be calculated using the expression S 5 gt where S is the distance and t is the time of flight There are certain sources of error in this experiment We assume that the ball is released at the moment the 61 current is withdrawn but due the inductance of the coil the balls falls after a delay This delay error can be estimated by taking the readings at different heights Using two light barriers at different hieghts is another solution 4 10 Study of Timer and Delay circuits using 555 IC Constructing astable and monostable multi vibrators using C 555 is done in elementary electronics practicals Using phoenix one can measure the frequency and duty cycle of the output with micro second accuracy In the case of mono stable Phoenix can apply the trigger pulse and measure the width of the output 4 10 1 Timer using 555 An astable multi vibrator is wired using IC 555 as shown in figure 4 26 The output of the circuit is fed to CNTR input for frequency measurement and then to Digital Input DO for duty cycle measurement The code used is sh
75. ries to try some simple experiments quickly Verify that you get the following components with your Phoenix kit 1 2 10 11 12 The Phoenix box Figure 2 1 9V DC adapter Serial port cable for communicating with the PC Bootable CD containing Phoenix driver software and assorted tools LED with resistor and three pins one RC measurement cable with 4 pins one 15 cm long wire with 2mm banana pins three 25 cm long wire with 2mm banana pins two Condenser microphone with biasing and signal cables one 1 KQ and 100 Q resistors with pins for variable gain amplifier two one 5V DC powered Piezo buzzer without pin Metal film Resistors 10 KQ 500Q 2009 10 The following accessories are available separately 10 1 16x1 LCD display 2 Parallel port cable for micro controller programming 3 Diode Char Set Setup to Study several PN junctions 4 Light barrier Time measurements by intercepting a beam of light 5 Pendulum waveform digitizer using DC motor as transducer 6 Rod pendulum 7 PT100 temperature sensor 8 LM35 temperature sensor 9 40KHz piezo transceiver pair for sound wave experiments 10 10 cm cable with pins pack of 10 11 20 cm cable with pins pack of 10 2 1 The front panel On the front panel you will find several 2mm banana sockets with different colors Their functions are briefly explained below 1 5V OUT This is a regulated 5V power supply that can be u
76. se units work is essen tial for doing practical experiments with Phoenix In the next part of this document we shall look at these non programmable units 3 7 1 Converting bipolar signals to unipolar The ADC channels accept only unipolar signals 0 5V the Phoenix box comes with two amplifiers which take a bipolar 5V to 5V signal and raises it to 0 5V Search around the front panel for a section which looks like what is shown in Figure 3 3 29 OHO OUT X 5 2 IN TE e Figure 3 3 Offset amplifier If the input voltage is X output is X 5 2 Test this out by ap plying OV and 5V at one of the inputs and measuring the voltage at the corresponding output using a multimeter Exercise Test the offset amplifier with an input of 5V You can use the inverting Op Amps described in the next section to generate 5V 3 7 2 Inverting Op Amps with externally controllable gain In many practical applications it would be necessary for us to take a very weak signal say a few millivolts and convert it into a stronger one which can be processed by the ADC Analog comparator or digital inputs We will have to amplify the signal hundreds of times The Phoenix box provides two inverting amplifiers Figure whose gain ie amplification factor can be set by connecting an external resistor of appropriate value The value of the resistor is found using the formula Gain 10KQ Ri The operational amplifiers
77. sed for powering external circuits It can deliver only upto 100mA current which is derived from the 9V unregulated DC supply from the adapter 2 Digital outputs four RED sockets at the lower left corner The socket marked DO is buffered with a transistor it can be used to drive 5V relay coils The logic HIGH output on DO will be about 4 57V whereas on D1 D2 D3 it will be about 5 0V DO should not be used in applications involving precise timing of less than a few milli seconds 11 Figure 2 1 The Phoenix M box 12 3 Digital inputs four GREEN sockets at the lower left corner It might sometimes be necessary to connect analog outputs swinging between 5V to 5V to the digital inputs In this case you MUST use a 1K resistor in series between your analog output and the digital input pin 4 ADC inputs four GREEN sockets marked CH0 to CH3 5 PWG Programmable Waveform Generator 6 DAC 8 bit Digital to Analog Converter output 7 CMP Analog Comparator negative input the positive input is tied to the internal 1 23 V reference 8 CNTR Digital frequency counter only for 0 to 5V pulses 9 1 mA CCS Constant Current Source BLUE Socket mainly for Re sistance Temperature Detectors RTD 10 Two variable gain inverting amplifiers GREEN sockets marked IN and BLUE sockets marked OUT with YELLOW sockets in between to insert resistors The amplifiers are built using TL084 Op Amps and have a certain offset w
78. t__ low EXAMPLE p disable_ set enable rising wait enable falling wait PROTOTYPE void enable_ rising wait integer pin vooid enable_ falling wait integer pin DESCRIPTION 115 If an ADC block read function is called after invoking one of these functions the block read will wait for one of the digital 0 to 3 or analog comparator 4 inputs to go high low before starting the digitization process EXAMPLE p enable_ rising wait 2 p enable_ falling wait 1 disable wait PROTOTYPE void disable_ wait void DESCRIPTION Similar to disable set This function will cancel the effect of calling enable_ rising wait or enable_ falling wait save data PROTOTYPE void save_ data data fn plot dat DESCRIPTION Save the data returned by the ADC block read functions into a file in multi column format Default filename is plot dat this can be overriden EXAMPLE v p read_block 200 10 1 p save_data v sine dat 116 Plotting Functions PROTOTYPE void plot data width 400 height 300 parent None DESCRIPTION Plots the data returned by read_ block and multi_read_ block Provides grid window resizing and coordinate measurement fa cilities Any previous plot existing on the window will be deleted EXAMPLE v p read_block 200 10 1 p plot v PROTOTYPE void plot_ data data width 400 height 300 DESCRIPTION Plots the data returned by read_ block and multi_read_ block Use this
79. taken at points of time 0 001 0 002 003 Let s create a Numeric array to represent these points in time gt gt gt t arange 0 200 0 001 gt gt gt print m The arange function creates a Numeric array of 200 numbers from 0 to 199 the multiplication operator acts on each and every element of this array and the result is stored in m Now let us create our sampled sine wave gt gt gt signall sin 50 2 pi t To verify that we are indeed getting a sine wave we can think of writing a simple Python script to store the elements of the array signal 1 to a file and then do a plot using xmgrace We will be getting 10 full cycles of a sine wave signal frequency is 50Hz and sampling frequency is 1KHz so if we take 1000 samples there will be 50 cycles in it if we take 200 samples we will get 10 cycles Let s now create another signal with a frequency of 25Hz gt gt gt signal2 sin 25 2 pi t We will combine these signals gt gt gt signal signall signal2 97 Note that the addition operator is adding up the corresponding elements of both the arrays the addition operator works in a very different way when applied to ordinary Python lists it simply returns a concatenated list A fundamental problem in signal processing is given a digitized wave form identify what all frequencies are present in it In the above example the question is whether it is possible to find out given
80. the Live CD Notepad under MSWindows 39 Figure 4 1 Power line Pickup 4 1 1 Mathematical analysis of the data By counting the number of waves within a given time interval one can roughly figure out the frequency of the line pickup but it won t be accurate and don t tell us much about the nature of the wave Let us approach the problem in a more systematic manner We have measured the value of the voltage at 200 different instances of time and want to find out the function that governs the time dependency of the voltage Problems of this class are solved by fitting the experimental data with some mathematical formula provided by the the ory governing the physical phenomena under investigation Curve fitting is a method of comparing experimental results with a theoretical model Here the theoretical value of voltage as a function of time is given by a sinusoidal wave represented by the equation V Vo sin2af where Vo is the amplitude and f is the frequency The experimental data can be fitted using this equation to extract these parameters We use the two dimensional plotting package xmgrace 2 for plotting a fitting the data Xmgrace is free software and included on the CD along with user manual and a tutorial Xmerace is started from the command prompt with file pickup dat saved 36 4000 2000 Voltage mV 2000 4000 f 20000 40000 60000 80000 le 05 Time usecs Figure 4
81. the array signal and the sampling frequency 1KHz that signal is composed to two sine waves of frequency 25Hz and 50Hz The magic of Fourier transforms lets us do it 9 2 Taking the FFT Let s execute the following program from Numeric import from FFT import t arange 0 200 0 001 signall sin 50 2 pi t signal2 sin 25 2 pi t signal signall signal2 f abs real_ fft signal for i in f print i The real_ fft function returns a 100 element array of complex numbers the input array was 200 elements long the reason for this reduction in half is that the remaining elements are simply complex conjugates We are interested in the absolute value of these complex numbers so we take the abs Now we have a hundred element array of numbers which if analyzed properly will give us a clear picture as to what all frequencies are present in our signal Running the above program results in a lot of numbers getting printed on the screen Assuming you are working on GNU Linux you can use redi rection at the shell prompt to store these numbers in a file you simply type 98 python analyze py gt data Now the data can be plotted using xmgrace Figure 9 1 is the resulting graph You see two peaks one at 5 and the other at 10 How do you interpret this We have a 100 element array of numbers Our sampling frequency was 1000Hz and we had 200 samples The 100 numbers in the array represent
82. the difference between the measured temperature and the reference point 81 Chapter 7 Appendix A Number systems A basic understanding of binary and hexadecimal number systems is required to work with Phoenix M The Binary Number System Only two digits 1 and 0 are available for counting in binary here is how you do it 00 01 10 11 100 101 110 111 1000 and so on Converting a binary number to decimal is simple Let s convert 1011 to decimal 1x20 TO 042 71 x2 Take each digit of the binary number from the rightmost one and keep multiplying it with increasing powers of 2 Converting small decimal numbers to binary becomes quite easy with practice simply visualize this sequence ise 128 64 32 16 8 4 2 1 Say you want to convert 37 to binary 37 is 32 4 1 so you visualize a bit pattern Os 0 1 0 0 1 01 82 with 1 s at positions occupied by 32 4 and 1 and zero s at all other places The rightmost bit the so called least significant bit of an eight bit pattern will be labeled DO and the leftmost bit the most significant bit will be labeled D7 The Hexadecimal Number System Counting You count in decimal like this 0 1 2 8 9 10 11 12 There are only ten distinct symbols from 0 to 9 available In hexadecimal you have 16 distinct symbols you count in hex like this 0 1 2 8 9 A B C D E F 10 11 18 19 1A 1B 1C 1D 1E 1F 20 Th
83. together and recording the time of arrival of sound at a microphone kept at a distance One metallic plate is connected to ground another one is connected to a digital input say DO The generated sound travels through air and reaches the microphone and induces an electrical signal The electrical signal is amplified 200 times by two amplifiers in series and connected to D3 The experimental setup is shown figure 4 20 We have used 1 mm thick aluminium plates to generate the sound When we strike one by the other the digital input DO gets grounded resulting in a falling edge at DO The amplified sound signal causes a rising edge on D1 4 The software measures the time interval between two falling edges using the following lines of code To get better results repeat the measurement several times and take average import pm p phm phm print p f2ftime 0 1 Here is a table of measurements obtained experimentally Rising or falling edge depends on the amplifier offset etc If the amplifier output will start oscillating when the sound signal arrives If is already HIGH it will go LOW when the sound signal arrives and we should look for a falling edge 59 Grounded Plate Digital input DO 5V Digital Input D1 1K distance 7 __ 1UF 20x 10x Mic GND Figure 4 20 Velocity of sound by microphone Distance cm Time milli seconds Speed distance time 0 0 060 To be treated as offset 10 0
84. tunately the data acqui sition hardware used by scientists is too expensive for college laboratories where teaching is the main goal and not research With the advent of in expensive personal computers the only missing link is the data acquisition hardware that is fast and sensitive enough to do physics experiments If such a data acquisition hardware is cheap enough then college level or even school laboratories could afford to do experiments using computers and per form numerical analysis of the data Physics with Home made Equipment and Innovative Experiments PHOENIX is a step in that direction Phoenix provides microsecond level accuracy for timing measurements but the present version gives only 0 1 resolution for analog parameters limited by the 10 bit ADC used The basic unit only provides an interface to the PC and the kind of ex periments you can do depends on the sensor elements available The layered software design does not demand much programming skills from the user At the same time we do not encourage the use of black boxes where you get the results at the click of a mouse button The approach is to get the data by typing one or two lines of Python code Phoenix M is the micro controller based version of this interface which also doubles as a training kit for electronics engineering and computer sci ence students Collecting data from the sensor elements and controlling the different parameters of the experiment from the PC is
85. ues up to 100KHz EXAMPLE f p measure_ frequency adc_ freq PROTOTYPE integer adc_ freq integer chan DESCRIPTION Measure the time period of a signal applied on one of the ADC channels Returns period in microseconds pulse out PROTOTYPE integer pulse_out integer delay us DESCRIPTION Send one pulse out on digital output pin D3 with high time equal to delay_us EXAMPLE p pulse_out 1000 generate 1ms pulse 104 pendulum _ period PROTOTYPE integer pendulum _ period integer pin DESCRIPTION range 0 to 4 0 1 2 or 3 if the light barrier output is con nected to digital input pins DO to D3 4 if connected to analog comparator input multi _r2rtime PROTOTYPE integer multi_r2rtime integer pin integer skipcycles DESCRIPTION Measure time in microseconds between two rising edges of a waveform applied to a digital input pin DO to D3 or analog comparator input If skipcycles is zero period of the waveform is returned In general skipcycles number of consecutive rising and falling edges are skipped between the two rising edges EXAMPLE p multi_r2rtime 0 3 pulse2rtime pulse2ftime PROTOTYPE integer pulse2rtime integer tx integer rx integer width inte ger pol integer pulse2ftime integer tx integer rx integer width inte ger pol 105 DESCRIPTION This function sends out a single pulse of width width on the digital output pin specified by tx and waits for a ris
86. used for implemeting them require both positive and neg ative supply voltages Phoenix M generates them by using a charge pump IC that gives output from 6V to 7V range Due to this reason amplifiers in some units may saturate at around 4 5 V You can test this by giving the 5V supply to the inverting amplifier and check the output using a multimeter insert a 10K gain resistor for unity gain The amplifiers can also be used for implementing summing junctions and other in verting op amp circuits 30 Ri IN OUT Figure 3 4 Inverting Amplifier So if you want a gain of 10 you will choose a resistor of value Ri 1K note that resistor values are never exact a 1K resistor will be never exactly 1K so don t expect to get a gain of precisely 10 Connect the resistor between the two YELLOW sockets apply input to the GREEN socket marked IN and take output from the BLUE socket marked OUT Make sure that you don t choose a gain greater than 40 You can take the output of one amplifier and feed it into the input of another one if you want larger amplification The units are implemented by TL084 op amps and will have some offset that is there will be some voltage at the output even when the input is zero To measure this ground the input supply a gain resistor of 10K Ohm and measure the output You should see a value in the range of 1 2 mV Try with a gain resistance value of 1KOhm and you will note that it is in t
87. ut pins D0 D1 D2 D3 and ground Write a Python program to make these LED s light up and go off sequentially 3 2 Digital Inputs The Phoenix box is equipped with four digital input pins labeled DO D1 D2 D3 look at the section of the panel marked DIGITAL INPUTS Execute the following Python code segment and repeat it after connecting a wire from D3 GREEN socket to Ground gt gt gt p read_inputs 15 gt gt gt p read_inputs 7 How do we interpret the results If we express 15 and 7 in binary forms we get the bit patterns 1111 and 0111 According to our convention we call the rightmost bit bit0 and the leftmost bit bit3 If bit3 is 1 it means that the voltage on digital input pin D3 is HIGH ie 5V and if it is 0 it means that the voltage on D3 is LOW ie OV Similar is the case with all the other bits All bits are internally pulled up to 5V and we got the 15 when D3 is grounded we got 7 Another experiment Connect digital output pins D3 to the digital input pins D3 Execute the following code fragment 4We will follow this HIGH means 5V and LOW means 0V convention throughout this document 20 gt gt gt p write_outputs 0 gt gt gt p read_inputs gt gt gt p write_outputs 8 gt gt gt p read_inputs 15 It s easy to justify the results which we are getting The digital inputs are versatile We will come to the time measurements with microsecond
88. x378 erase uisp verify dprog dapa dpart atmegal6 dlpt 0x378 upload if 1 hex 70 For example executing the following command from the directory where load bat and hex are located will upload avrk hex to the micro controller load bat avrk Uploading this program is necessary for the python library to communicate to Atmega8 After trying any of the following examples load avrk if you want to restore the functioning of Phoenix M as a PC interface 5 2 Example Programs The example programs will use Phoenix M hardware for demonstrating var ious features of ATmegal6 Extra hardware will be plugged into the front panel sockets as required It is desirable to have a multimeter to test the results 5 2 1 Blinking Lights If you have booted from the live CD open a command prompt and set the default directory as root phm Create a file named blink c with the following lines in it Connect an LED from the socket marked ADC Ch0 to ground through a 1KOhm resistor include lt stdio h gt include lt stdlib h gt include lt inttypes h gt tinclude lt avr io h gt void delay uint16_t k roughly 2 usec per loop at 8 MHz system clock volatile uint16_t x K while x x int main void 71 DDRA Oxff Configure all bits of PORT A as output for 33 PORTA 255 delay 20000 PORTA 0 delay 20000 Compile the code and upload it to ATmega
89. yed as a function of time by the read_block and plot_ data functions With few lines of code you are making a simple CRO Type in the following program in a text editor and save it as a file named say pickup py import phm p phm phm p select_adc 0 while p read_inputs 15 v p read_block 200 500 1 p plot_data v p save_data v pickup dat Run the program by typing python pickup py at the Operating System command prompt after plugging one end of 25 cm wire to ChO of the ADC Make sure that none of the digital input pins are grounded You should see a waveform similar to that of figure 4 1 Adjust the position of the wire or touch the floating end with your hand to see the changes in the waveform How do you terminate the program The while loop is continuously reading from the digital inputs and checking whether the value is 15 if none of the sockets DO to D3 are grounded the value returned by read_inputs will definitely be 15 and the loop body will execute If you ground one of the digital inputs the value returned by read_ inputs will be something other than 15 this will result in the loop terminating Terminate the program when a good trace is on the screen last sample collected is saved to the disk file pickup dat just before exiting if you are not familiar with standard GNU Linux editors like vi or emacs you can use Nedit which is available from the start menu of
90. zation with p enable_set_high 3 Extract the RC value by fitting the data using the equation using xmgrace package 41 CCS ADC CHO T D3 Figure 4 6 Linear Charging of Capacitor 4 2 1 Linear Charging of a Capacitor Exponential charging and discharging of capacitors are explained in the pre vious section If we can keep the current flowing through the resistor con stant the capacitor will charge linearly Let s wire up the circuit shown in Figure 4 6 When D3 is HIGH no charging occurs When D0 goes LOW the capacitor starts charging through the 1mA constant current source and run the following Python script import phm time p phm phm p enable_set_low 3 p write_outputs 8 time sleep 1 v p multi_read_block 400 20 0 p plot_data v time sleep 5 You will obtain a graph like the one shown in Figure 4 3 IV Characteristics of Diodes Diode IV characteristic can be obtained easily using the DAC and ADC features The circuit for this is shown in figure 4 8 Connect one end of a 1 42 Figure 4 7 Linear charging R 1 KOhm C 1 uF DAC ChO GND Figure 4 8 Circuit for Diode IV Characteristic KOhm resistor to the DAC output The other end is connected to the ADC ChO Input Positive terminal of the diode also is connected to the ADC ChO and negative to ground The Voltage across the diode is directly measured by the ADC and the current is calculated using Ohm s law since the voltage at bot

Download Pdf Manuals

image

Related Search

Related Contents

Grandway FHP2/FHS2 - Optical Power Meter - Coral  A Value-Priced DSO with High Performance & Reliability  Operating Instructions - Cab Produkttechnik GmbH & Co KG    (Code article : 5133002183) Coupe-bordures  Black & Decker TROS1500C Use & Care Manual  報告書 - 東京都  SE77 DeviceNet Advanced User Guide  マイクロハイファイ コンポーネントシステム 取扱説明書  Toma de carga USB 230 V Instrucciones de servicio y de montaje 1  

Copyright © All rights reserved.
Failed to retrieve file