-
Notifications
You must be signed in to change notification settings - Fork 1
/
phm.py
executable file
·2089 lines (1892 loc) · 68.6 KB
/
phm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import array, time, sys, os, struct
from math import *
from Tkinter import *
"""
Python library for communicating to the "C program" on ATmega16 using RS232
interface. The commands are grouped according to the number of bytes should
follow as input data.
Each call to ATmega16 sends a status reply and variable length Data.
The Python function is responsible for receiving the correct amount of
data. No handshaking protocol is used at the moment.
There are some commands that initiate some periodic activity on ATmega16 and
collects the data later.
This library also has some Tkinter based graphics routins. The plot routines
Y-axis scale is assumed to be from -5000 to +5000. Can be improved
The UPhm class handles the communications through the ATmega8 based
USB version
Last Edited 30-Jun-09 : function usb_reconnect() added
serial and usb modules are loaded only when required.
"""
#-----------------Commands to the kernel running on Atmaga16 ------------
# Commands with No arguments. ATmega16 starts action after getting a single byte (1 to 40)
LCD_INIT = 1 # Clear LCD Display
DIGIN = 2 # Digital Input (4 bits)
READBLOCK = 3 # ADC read block
MULTIREADBLOCK =4 # ADC read block
ADCREAD = 5 # Digitises selected channel
GETCHANMASK = 6 # Channel mask info for MRB
COUNT = 7 # measure the frequency of counter input
READACOMP = 8 # Analog comparator status, 1 when IN- < 1.23V
GETTIME = 9 # get the time is seconds since Epoch
STARTHIST = 10 # Start histogramming
READHIST = 11 # Send the histogram to PC, 2 x 256 bytes data
CLEARHIST = 12 # Clear the histogram memory
STOPHIST = 13 # Stop histogramming
STOPWAVE = 14 # Disable interrupt based waveform generation
SMRB_START = 15 # Initiate an interrupt driven multi read block
SMRB_STATUS = 16 # Returns the TC0 ISR status + nbytes collected
SMRB_GETDATA= 17 # Sends the data collected by SMRB to PC
SMRB_STOP = 18 # Force Stop SMRB
PMRB_STATUS = 19 # Returns the TC0 ISR status
PMRB_GETDATA= 20 # Data collected in PROM by PMRB to PC
SPI_PULL = 21 # Pull one byte from SPI
SPI_PULL_BAR= 22 # Pull for AD7718 like device
CHIP_DISABLE= 23 # CS disable for SPI
HR_ADCINIT = 24 # SPI ADC
HRADCREAD = 25 # Digitizes the addon ADC , current channel
GETMCUSTAT = 26 # Get several microcontroller registers
GETVERSION = 27 # Get the version information phx.y
HR_GET_CAL = 28 # Read the AD7718 gain & offsetregisters
# Commands with One byte argument ( AT waits for one more byte before processing)(41 to 80)
DIGOUT = 41 # Digital output (4 bits)
SETADCSIZE = 42 # ADC data size (1 or 2)
SETCURCHAN = 43 # Select Current ADC channel
R2FTIME = 44 # Rise to Fall of signal on input pins
R2RTIME = 45 # Rise to Fall of signal on input pins
F2RTIME = 46 # Fall to Rise of signal on input pins
F2FTIME = 47 # Fall to Rise of signal on input pins
SET2RTIME = 48 # Setting of bit to rising edge
SET2FTIME = 49 # to falling time
CLR2RTIME = 50 # Setting of bit to rising edge
CLR2FTIME = 51 # to falling time
PULSE2RTIME = 52 # Pulse to rising edge
PULSE2FTIME = 53 # Pulse to falling edge
SETPULSEWIDTH =54 # width for PULSE2 functions (0 to 250)
SETPULSEPOL = 55 # PULSE polarity (0 for HIGH true)
ADDCHAN = 56 # Add to MRB list
DELCHAN = 57 # Del from "
SETDAC = 58 # Set the PWM ADC (0 to 255) 0 to 5V
TPEND = 59 # Period og pendulum from light barrier
PULSEOUT = 60 # Send 100 pulses on D3, specify gap between them
AINPERIOD = 61 # measure ADC input signal periods
LCD_PUTCHAR = 62 # display to LCD
CHIP_ENABLE = 63 # Enable SPI device
CHIP_ENABLE_BAR=64 # Enable SPI device
SPI_PUSH = 65 # Push one byte to SPI
SPI_PUSH_BAR = 66 # Push one byte to SPI
HR_SETCHAN = 67 # SPI ADC select channel
HR_CALINT = 68 # internal calibration of selected channel
HR_CALEXT = 69 # External Zero /FS calibration
GETPORT = 70 # Read the uC port
# Commands with Two bytes argument (81 to 120)
SETNUMSAMPLES =81 # Number of samples per channel
SETCOUNTER2 = 82 # Oscillator output on counter2
SETADCDELAY = 83 # Interval between digitizations ( 0 to 1000 usec)
SETACTION = 84 # Block Read Actions of SET/CLR type
WAITACTION = 85 # Block Read Actions of wait type
MULTIR2R = 86 # Rising edge to rising edge after N cycles
ADCTRIGLEVELS =87 # First and second ADC trigger level values
HRSETDAC = 88 # 16 bit DAC
SETWAVEFORM = 89 # We need to calculate OCR0, clock tick is 32 usec
PULSE_D0D1 = 90 # Interrupt driven square wave on D0 and D1
MULTI_EDGES = 91 # Rising and Falling Edge pair timings
COPY_E2S = 92 # copy eeprom to seeprom plugin, at specified address
SETDDR = 93 # Set the direction of uC port
SETPORT = 94 # Set Data/or pullup on uC port
# Commands with Three bytes argument (121 to 150)
READSEEPROM = 121 # Read data from Seeprom plug-in
TABLEDATA = 122 # Write one byte of WAVETABLE to AVR EPROM
# Commands with Four bytes argument (151 to 180)
SETTIME = 161 # Set time. elaped seconds since 1970
PMRB_START = 162 # PMRB arg: number of 128 byte blocks, delay in seconds
# Reply from Atmega16
DONE = 'D' # success
SUCCESS = ord('D') # Byte representation of 'D'.
INVCMD = 'C' # Invalid command
INVARG = 'A' # Input data out of bounds
INVBUFSIZE = 'B' # READBLOCK request exceeds buffer size
TIMEOUT = 'T' # Time interval measurement failed
NOCLOCK = 'N' # Clock not set error, for PMRB
USBERROR = 'U' # ATmega8 based USB interface reported error
ADCRNGERR = 'R' # SPI ADC Range ERROR
TABLESIZE = 100 # number of points in the User defined waveform
USERWAVE = 2 # Wave form table from EEPROM, loaded by user
HRUSERWAVE = 3 # Wave Table from AVR EEPROM, to plug-in HRDAC
WIDTH = 300.0 # used by plot()
HALF_HEIGHT=100.0
YMAX = 5000.0 #5000 mV
import glob
device_list = []
for g in ('/dev/ttyS*', '/dev/tts/USB*', '/dev/ttyUSB*', '/dev/tty.usb*'):
device_list.extend(glob.glob(g))
device_list.extend(range(4))
logfile = None # To keep track of Hardware connection failures
def phm(dev = None):
"""
Create an instance of the Class named 'Phm'. If the file descriptor to
access the phoenix hardware in set, the instance is returned. Otherwise
None is returned.
"""
global logfile
logfile = open('phm.log','w')
object = Phm()
logfile.close()
if object.handle != None:
object.stop_wave()
object.set_adc_size(object.adc_size)
return object
print 'Could not find Phoenix-M on RS232 or USB ports'
print 'Check hardware connections.'
#----------------------- USB Version ----------------------------
VENDOR_ID = 0x03eb # Vendor ID of Atmel
PRODUCT_ID = 0x21ff # Atmega based usb interface
VDR = 0xC0 # USB Vendor device request
RS_WRITE = 10
RS_READ = 14
RS_SETBAUD = 12
USBMAXTRY = 500
BUFSIZE = 1802 # status + adcinfo + 800 data
class Phm:
buf = array.array('B',BUFSIZE * [0]) # unsigned character array, Global
seeprom_active = 0
num_samples = 100 # 1 to 800
num_chans = 1 # 1 to 4
current_chan = 1 # 0 to 3
adc_size = 1 # 1 or 2 bytes
adc_delay = 10 # 10 to 1000 usecs, Atmega16
adc_format_bip = 0; # 1 if through level shifter amplifier
maxwaitds = 40 # timeout = 40 * 50 msec
pulse_width = 13 # 1 to 1000 usecs
pulse_pol = 0 # HIGH TRUE (0) or LOW TRUE (1)
handle = None
usb_dev = False
last_message = ''
colors = ['black', 'red', 'green', 'blue']
plotwin = None # used by plot_data()
plot_trace = []
border = 5 # used by window() etc.
root = None
line_data = []
line_trace = []
box_trace = []
box_data = []
grid_trace = []
bordcol = '#555555'
gridcol = '#f0f0f0'
gridcol2 ='#d0d0d0'
def find_usb_phoenix(self):
import usb
global logfile
logfile.write('Searching for USB version of Phoenix.\n')
busses = usb.busses()
for bus in busses:
devices = bus.devices
for dev in devices: # Search for AVRUSB
if dev.idVendor == VENDOR_ID and dev.idProduct==PRODUCT_ID:
interface = dev.configurations[0].interfaces[0][0]
logfile.write('AVR309 found. Trying to Claim it..\n')
try:
self.handle = dev.open()
self.handle.setConfiguration(dev.configurations[0])
self.handle.claimInterface(interface)
except:
logfile.write('AVR309: Open/Claim Interface failed.\n')
logfile.write('Another program using it already ?.\n')
self.handle = None
return
self.usb_dev = True
logfile.write('Found USB Phoenix. Setting Baudrate..')
self.setbaud(38)
logfile.write('Clearing buffer\n')
self.clearbuf()
v = self.get_version()
if v == None:
logfile.write('No Phoenix on AVR309.\n')
self.handle = None
def usb_reconnect(self):
global logfile
if self.usb_dev == False:
print 'No active USB connection'
return
try:
self.handle.releaseInterface()
except:
pass
logfile = open('phm.log','w')
logfile.write('Trying to Re-connect USB Link.\n')
self.find_usb_phoenix()
logfile.close()
def __init__(self, dev = None):
"""
First searches for the USB version of Phoenix. If not found searches
on the RS232 ports and the USB-to-Serial adapters.
Currently the software can support one USB device + one Serial device.
Supporting multiple USB versions are not yet done.
"""
global logfile
logfile.write('Entering Phm..\n')
try:
self.find_usb_phoenix()
self.last_message = 'Phoenix Hardware on USB'
self.set_adc_size(self.adc_size)
except:
logfile.write('USB software support not working.\n')
self.handle = None
if self.handle != None: # Found a USB Phoenix
return
logfile.write('Searching for RS232 version of Phoenix.')
# We did not find a USB phoenix. Now try serial one
self.handle = None
for dev in device_list:
logfile.write('Searching on %s\n'%dev)
try:
import serial
self.handle = serial.Serial(dev, 38400, stopbits=1,\
timeout = 0.3, parity=serial.PARITY_EVEN)
self.handle.flush()
self.usb_dev = False
v = self.get_version()
if v[0] == 'p' and v[1] == 'h': # we got it
logfile.write('Found version %s\n'%v)
self.handle.timeout = 3 # larger timeout needed
self.last_message = 'Phoenix Hardware on' + str(dev)
return
else:
logfile.write('No Phoenix on %s\n'%dev)
except:
logfile.write('Error Opening %s\n'%dev)
self.handle = None
#-------------------------Communication to Phoenix via ATmega8-USB-----------------
def write(self, val):
if self.usb_dev == False: # This is a RS232 device
self.handle.write(chr(val))
else:
self.handle.controlMsg(VDR, RS_WRITE, 1, value = val)
def setbaud(self, val):
self.handle.controlMsg(VDR, RS_SETBAUD, 1, value = val, index = 0)
def clearbuf(self):
if self.usb_dev == False: # Serial device
self.handle.flush()
return
while 1:
part = self.handle.controlMsg(VDR, RS_READ, 800)
if len(part) < 3:
break
def unpackPacket(self,bytesPerDataPacket, packet):
# Needed to convert from signed longs to string.
self.__unpack_format__ = 'B'*bytesPerDataPacket
# Needed to convert from string to unsigned bytes.
self.__pack_format__ = 'b'*bytesPerDataPacket
# Convert data from signed to unsigned.
data = struct.unpack(self.__unpack_format__, struct.pack(self.__pack_format__, *packet))
return data
def read(self, nb): # loop until getting 'nb' bytes
if self.usb_dev == False: # Read from RS232 device
for index in range(nb):
ch = self.handle.read()
self.buf[index] = ord(ch)
return index + 1
# Read from USB device
index = 0
remaining = nb
timer = 0
while remaining:
if remaining <= 200:
bsize = remaining
else:
bsize = 200
part = self.handle.controlMsg(VDR, RS_READ, bsize + 2)
if os.name != 'posix': # Workaround a PyUSB version problem.
part = self.unpackPacket(len(part), part)
if len(part) < 3:
timer = timer + 1
if timer > USBMAXTRY:
self.buf[0] = ord(USBERROR)
return 0
continue;
pl = len(part) - 2
for k in range(2,len(part)):
self.buf[index] = part[k]
index = index + 1
remaining = remaining - pl
return index
def last_msg(self):
return self.last_message
# -------------------------- uC PORT I/O ---------------------------
def set_ddr(self, port, direc):
self.write(SETDDR)
self.write(port) # 0 to 3 for A,B,C and D
self.write(direc)
self.read(1)
return
def set_port(self, port, val):
self.write(SETPORT)
self.write(port) # 0 to 3 for A,B,C and D
self.write(val)
self.read(1)
return
def get_port(self, port):
self.write(SETPORT)
self.write(port) # 0 to 3 for A,B,C and D
self.read(1)
self.read(1) # get the status byte only
return self.buf[0]
return
# -------------------------- Digital I/O ---------------------------
def read_inputs(self):
"""
Return a 4 bit number representing the voltage levels on the
four digital input sockets.
Usage:
p = phm()
print p.read_inputs()
"""
self.write(DIGIN)
self.read(1) # get the status byte only
if self.buf[0] != SUCCESS:
self.clearbuf()
return None
self.read(1) # get the status byte only
return self.buf[0] & 15
def read_acomp(self):
"""
Returns the status of Analog comparator
1 if AN- is < 1.23V
p = phm()
print p.read_acomp()
"""
self.write(READACOMP) # Error check ???
self.read(1)
if self.buf[0] != SUCCESS:
return None
self.read(1)
return self.buf[0]
def write_outputs(self, val):
"""
Writes a 4 bit number to the Digital Output Sockets
Usage:
p = phm()
p.write_outputs(val)
"""
self.write(DIGOUT) # Error check ???
self.write(val)
self.read(1)
return
def pulse_out(self, data):
"""
Send a Robosapien pulse on D3.
"""
self.write(PULSEOUT)
self.write(data)
self.read(1)
#-------------------- Analog Outputs / Inputs ---------------------------
def set_voltage(self, val):
"""
Sets the PWM DAC between zero to 5000 mV
Usage:
s = phm()
s.set_dac(val)
"""
val = (val * 255.0) / 5000.0
iv = int(val)
self.write(SETDAC)
self.write(iv)
self.read(1)
return
def set_dac(self, val):
"""
Sets the PWM DAC input raw value from 0 to 255
Usage:
s = phm()
s.set_dac(val)
"""
self.write(SETDAC)
self.write(val)
self.read(1)
return
def select_adc(self, val):
"""
Selects the ADC channel to be digitized by the get_voltage()
and read_block() functions. Does not affect multi_read_block()
Usage:
s = phm()
s.select_adc(val)
"""
self.write(SETCURCHAN)
self.write(val)
self.read(1)
self.current_chan = val
self.set_adc_size(self.adc_size) # set size also ???
return
def set_adc_size(self, val):
"""
Sets the ADC datasize to 1 or 2 bytes. ATmega16 ADC is can
be set to 10 bits or 8 bits resolution. For 10 bit resolution,
the delay between digitizations should be set more than 100
microseconds.
Usage:
s = phm()
s.set_adc_size(val)
"""
self.write(SETADCSIZE)
self.write(val)
self.read(1)
self.adc_size = val
return
def zero_to_5000(self):
"""
Use get_voltage() instead of this function.
"""
return self.get_voltage()
def get_voltage(self):
"""
Reads the voltage present at the Analog Input, selected using
select_adc(0) function. Returns the system time stamp and the
voltage in millivolts, 0 to +5000 mV
The return value is a tuple containing he PC timestamp and the
voltage.
"""
res = self.read_adc()
if res == None:
return None
if self.adc_size == 1:
volt = res[1] * 5000.0 / 255.0
else: # 10 bit data
volt = res[1] * 5000.0 / 1023.0
return (res[0],volt)
def minus5000_to_5000(self):
"""
Use get_voltage_bip() instead of this function.
"""
return self.get_voltage_bip()
def get_voltage_bip(self):
"""
Analog Inputs take only 0 to 5V range signals. Bipolar signals
are fed though the level shifting amplifiers. This function
returns the voltage given at the input of the level shifter.
Otherwise same as get_voltage().
"""
res = self.read_adc()
if res == None:
return None
if self.adc_size == 1:
volt = res[1] * 10000.0 / 255.0 - 5000.0
else: # 10 bit data
volt = res[1] * 10000.0 / 1023.0 - 5000.0
return (res[0],volt)
def read_adc(self):
"""
Digitizes the ADC input and returns the binary value.
result is from 0 to 255 for adc_size = 1
and 0 to 1023 if adc_size = 2.
System time stamp also is returned to the caller
The time stamp is used to find the time interval between
two calls.
"""
self.write(ADCREAD)
self.read(1)
if self.buf[0] != SUCCESS:
return None
t = time.time() #add system time stamp
if self.adc_size == 1:
self.read(1)
return (t, self.buf[0])
else:
self.read(2)
val = (self.buf[1] << 8) | self.buf[0]
return (t,val)
def adc_input_period(self, ch):
"""
Time between two rising edges on ADC Input. The signal must be a
squarewave with more than 2 volts amplitude.
"""
self.write(AINPERIOD)
self.write(ch)
self.read(1)
if self.buf[0] != SUCCESS:
return -1.0
self.read(3)
low = self.buf[1] << 8 | self.buf[0]
return low + 50000 * self.buf[2]
def read_block(self, np, delay, bip=0):
"""
Returns a block of data from the ADC. The channel to be digitized
is set by calling select_adc().
The call returns a status byte, then another byte for adc_size
followed by (np * adc_size) bytes of data.
For two byte ADC data, the lower byte of Dataword comes first
Arguments:
np : Number of points to digitize
delay : Interval between samples in microseconds
bip : 1 when using (x+5)/2 gain block, else 0
"""
self.set_adc_delay(delay)
self.set_num_samples(np)
self.write(READBLOCK)
self.read(1) # get Status
if self.buf[0] != SUCCESS:
self.clearbuf()
return ['READBLOCK returned error %c'%self.buf[0]]
self.read(1) # get adcsize
self.adc_size = self.buf[0] >> 4
nb = self.read(self.num_samples * self.adc_size)
index = 0
dat = []
if self.adc_size == 1:
for i in range(np):
t = i * self.adc_delay
if bip == 0:
volt = self.buf[index] * 5000.0 / 255
else:
volt = self.buf[index] * 10000.0 / 255.0 - 5000.0
volt = -volt
dat.append([t,volt])
index = index + 1
else: # 10 bit data
for i in range(np):
t = i * self.adc_delay
val = self.buf[index+1]
val = (val << 8) | self.buf[index]
if bip == 0:
volt = val * 5000.0 / 1023.0
else:
volt = val * 10000.0 / 1023.0 - 5000.0
volt = -volt
dat.append([t,volt])
index = index + 2
return dat
def multi_read_block(self, np, delay, bip=0):
"""
Returns a block of data from the ADC.
The channels to be digitized are set by add_channel() calls.
The call returns a status byte, then another byte reporting
a channel mask and adc_size.
followed by (np * num_chans * adc_size) bytes of data.
For two byte ADC data, the lower byte of Dataword comes first
Arguments:
np : Number of points to digitize
nchan : number of channels
delay : Interval between samples in microseconds
bip : 1 when using (x+5)/2 gain block, else 0
"""
self.set_num_samples(np)
self.set_adc_delay(delay)
self.write(MULTIREADBLOCK)
self.read(1) # get status
if self.buf[0] != SUCCESS:
self.clearbuf()
return ['MULTIREADBLOCK returned error %c'%self.buf[0]]
self.read(1) # get chmask
chmask = self.buf[0] #channel mask and ADC data size
nc = 0
for x in range(4):
if (1 << x) & chmask:
nc = nc + 1
self.num_chans = nc # Update nchan & size
self.adc_size = chmask >> 4
nb = self.num_samples * self.adc_size * nc
if self.read(nb) != nb:
return ['MULTIREADBLOCK returned error %c'%self.buf[0]]
dat = []
index = 0
if self.adc_size == 1:
for i in range(np):
item = []
item.append(i * self.adc_delay*nc) # *nc added 8-Sep-07
for chan in range(self.num_chans):
if bip == 0:
item.append(self.buf[index] * 5000.0 / 255)
else:
y = self.buf[index] * 10000.0 / 255.0 - 5000.0
item.append(-y)
index = index + 1
dat.append(item)
else: # 10 bit data
for i in range(np):
item = []
item.append(i * self.adc_delay*nc) # *nc added 8-Sep-07
for chan in range(self.num_chans):
val = (self.buf[index+1] << 8) | self.buf[index]
if bip == 0:
item.append(val * 5000.0 / 1023.0)
else:
y = (val * 10000.0 / 1023.0 - 5000.0)
item.append(-y)
index = index + 2
dat.append(item)
return dat
def add_channel(self, val):
"""Adds the channel to the MULTIREADBLOCK list (0 to 3)
Usage:
s = phm()
s.add_channel(val)
"""
self.write(ADDCHAN)
self.write(val)
self.read(1)
return
def del_channel(self, val):
"""Deletes the channel from the MULTIREADBLOCK list (0 to 3)
Usage:
s = phm()
s.del_channel(chan)
"""
self.write(DELCHAN)
self.write(val)
self.read(1)
return
def get_chanmask(self):
"""Returns the numbr of active channels used by MULTIREADBLOCK.
and the adc_size. res = (adc_size << 4) | chanmask
This is needed for programs calling MRB to interpret the data.
Usage:
s = phm()
print s.get_numchans()
"""
self.write(GETCHANMASK)
self.read(1)
if self.buf[0] != SUCCESS:
return None
self.read(1)
return self.buf[0]
def set_adc_trig(self, tr1, tr2, shifted = 0):
"""
Sets the ADC trigger Levels , Inital and final
If tr1 < tr2 then +ive trigger
"""
if shifted == 0:
low = int (255.0 * tr1 / 5000.0)
hi = int (255.0 * tr2 / 5000.0)
else:
low = int (255.0 * (tr1 + 5000.0) / 10000.0)
hi = int (255.0 * (tr2 + 5000.0) / 10000.0)
self.fd.write(chr(ADCTRIGLEVELS))
self.fd.write(chr(low))
self.fd.write(chr(hi))
res = self.fd.read()
def enable_rising_wait(self, pin):
"""
Same as enable_wait_high()
"""
return self.enable_wait_high(pin)
def enable_wait_high(self, pin):
"""
Defines the WAIT action for BLOCKREAD calls. Digitization
starts after detecting a HIGH level on the specified Digital
Input (0 to 3) or 4 (ACMP input)
"""
if pin == 4:
mask = 0
else:
mask = 1 << pin
self.write(WAITACTION)
self.write(1)
self.write(mask)
self.read(1)
def enable_falling_wait(self, pin):
"""
Same as enable_wait_low()
"""
return self.enable_wait_low(pin)
def enable_wait_low(self, pin):
"""
Defines the WAIT action for Block Read calls. Digitization
starts after detecting a Falling Edge on the specified Digital
Input (0 to 3) or 4 (ACMP input)
"""
if pin == 4:
mask = 0
else:
mask = 1 << pin
self.write(WAITACTION)
self.write(2)
self.write(mask)
self.read(1)
def disable_wait(self):
"""
Clear all the WAIT type actions on Digital input sockets.
"""
self.write(WAITACTION)
self.write(0)
self.write(0)
self.read(1)
def enable_set_high(self, pin):
"""
Defines the SET action for Block Read calls. The specified
Digital Output pin ia made HIGH before starting digitization.
"""
mask = 1 << pin
self.write(SETACTION)
self.write(1) # 1 means SET BIT action
self.write(mask)
self.read(1)
def enable_set_low(self, pin):
"""
Defines the CLEAR action for BLOCKREAD calls. The specified
Digital Output pin ia made LOW before starting digitization.
"""
mask = 1 << pin
self.write(SETACTION)
self.write(2) # 2 means CLR BIT action
self.write(mask) # The bit to be cleared
self.read(1)
def enable_pulse_high(self, pin):
"""
Defines the SET action for BLOCKREAD calls. A HIGH TRUE pulse
is given to the Selected Digital Output before starting digitization.
It is the responsibility of the caller to keep it HIGH
before calling read_block()
"""
mask = 1 << pin
self.write(SETACTION)
self.write(3) # 3 means HIGH TRUE Pulse
self.write(mask)
self.read(1)
def enable_pulse_low(self, pin):
"""
Defines the SET action for BLOCKREAD calls. A LOW TRUE pulse
is send on the Selected Digital Output before starting digitization.
It is the responsibility of the caller to keep it HIGH
before calling read_block()
"""
mask = 1 << pin
self.write(SETACTION)
self.write(4) # 4 means LOW TRUE Pulse
self.write(mask)
self.read(1)
def disable_set(self):
"""
Clear all the SET/CLR type actions on Digital outputs
just before block_read() functions
"""
self.write(SETACTION)
self.write(0) # 0 => No more SET/CLR actions
self.write(0)
self.read(1)
def set_num_samples(self, val):
"""Selects the number of samples per channel to be
digitized during the READBLOCK type calls
num_samples * num_chans * adc_size <= BUFSIZE in bytes
returns the new value on success or old value on failure.
Usage:
s = phm()
ns = s.set_num_samples(val)
"""
low = val & 255;
hi = val >> 8;
self.write(SETNUMSAMPLES)
self.write(low)
self.write(hi)
self.read(1)
if self.buf[0] == SUCCESS:
self.num_samples = val # failure keeps the old value
return self.num_samples
def set_adc_delay(self, val):
"""Sets the delay between conversions. 6 to 100 usecs
for 8 MHz clock. Delay below 100 usecs are not good for
10 bit accuracy.
This function is internally used by Block read functions.
"""
low = val & 255;
hi = val >> 8;
self.write(SETADCDELAY)
self.write(low)
self.write(hi)
self.read(1)
if self.buf[0] == SUCCESS:
self.adc_delay = val
return
#---------------- Wave Generation & counting -----------------------
def set_frequency(self, freq): # Freq in Hertz
"""
Sets the output frequency of the square wave
output on the Programmable Wave Generator pin of ATmega8.
From 15Hz to 40000000 Hz (4 MHz)
It is not possible to set all values. The function
sets the nearest possible value and returns it.
Usage:
p = phm()
print s.frequency(1000)
"""
if freq < 1: # Disable PWG
self.write(SETCOUNTER2)
self.write(0)
self.write(0)
self.read(1)
return 0
div = [4000000.0, 500000.0, 125000.0, 62500.0, 31250.0,15625.0,3906.25]
for i in range(7):
clock_sel = i+1
freq0 = div[i]
if ( freq0/ freq) <= 256:
break
setpoint = freq0/freq
if setpoint > 255:
setpoint = 255
OCR2 = int(setpoint)-1
# print clock_sel, OCR2
self.write(SETCOUNTER2)
self.write(clock_sel)
self.write(OCR2)
self.read(1)
if self.buf[0] != SUCCESS:
return None
if setpoint == 0:
return freq0
else:
return freq0/(OCR2+1)
def load_wavetable(self, v):
"""
Sends the 250 bytes wavetable to the AVR internal EEPROM
Returns number of bytes loaded, maximum is 250.
"""
if len(v) > TABLESIZE:
return 0;
self.stop_wave()
# print 'len = ', len(v)
addr = 0
for x in v:
self.eeprom_write_byte(addr,x)
addr = addr + 1
return addr-1
def start_wave(self, freq, plugin = 0):
"""
The wave form is generated on the DAC output by periodic output
of data from a table. Table has to be stored in eeprom first.
"""
for OCR0 in range(200):
possible = 100.0/(OCR0+1)
if freq >= possible:
break;
OCR0 = OCR0 +1
self.write(SETWAVEFORM)
self.write(OCR0)
if plugin == 0:
self.write(USERWAVE)
else:
self.write(HRUSERWAVE)
self.read(1)
fr = 1000000.0 / (100 * (OCR0+1)* 32)
return fr
def pulse_d0d1(self, freq):
"""
The squae wave is generated on the D0 and D1
by using TC0 ISR.
"""
if freq < 0.1:
self.stop_wave()
return 0
val = int(1000000.0/(64.0 * freq))
if val > 65535:
return 0
low = val & 255;
hi = val >> 8;
self.write(PULSE_D0D1)
self.write(low)
self.write(hi)
self.read(1)
return 1.0/(64.0*val)
def stop_wave(self):
self.write(STOPWAVE)
self.read(1)
def measure_frequency(self): # Returns freqency in Hertz
"""
Measures the frequency of the 0 to 5V square wave
at the counter input. Returns the value in Hertz.
External input is given to the 16 bit counter TCNT1.
The 8 bit counter runs in parallel with a 1 MHz clock.
When TCNT0 reaches 100, it is cleared a another variable
is incremented.
Usage:
s = phm()
print s.get_frequency()
"""
self.write(COUNT)
self.read(1)
if self.buf[0] != SUCCESS:
return None
self.read(3)
tcnt0 = self.buf[0]
low = self.buf[1]
hi = self.buf[2]
novflow = (hi << 8) | low
count = novflow * 256.0 + tcnt0 # count in one second