This repository was archived by the owner on Jun 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGUIDesign.c
More file actions
1929 lines (1772 loc) · 65.1 KB
/
GUIDesign.c
File metadata and controls
1929 lines (1772 loc) · 65.1 KB
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
/**
@file GUIDesign.c
@brief Contains functions and callbacks for primary GUI. Handles data processing
and communication with the ADwin.
*/
// Modified by Seth Aubin on August 2, 2010
// change to the "ADbasic binary file: "TransferData_August02_2010.TB1"
// purpose: activate DIO 1 and DIO 2 outputs.
// 2006
// March 9: Reorder the routines to more closely match the order in which they
// are executed.
// Applies to the 'engine' but not the cosmetic/table handling routnes
#include "GUIDesign.h"
#include <ansi_c.h>
#include <toolbox.h>
#include <userint.h>
#include <utility.h>
#include "Adwin.h"
#include "AnalogControl2.h"
#include "AnalogSettings2.h"
#include "DigitalSettings2.h"
#include "GUIDesign2.h"
#include "Scan.h"
#include "ScanTableLoader.h"
#include "main.h"
#include "scan2.h"
#include "vars.h"
// Forward declarations of functions
void BuildUpdateList(double[500],
struct AnalogTableValues[NUMBERANALOGCHANNELS + 1][500],
int[NUMBERDIGITALCHANNELS + 1][500], int);
int OptimizeTimeLoop(int*, int);
void ShiftColumn(int, int, int);
void RunOnce(void);
double CalcFcnValue(int, double, double, double, double, double);
double CheckIfWithinLimits(double, int);
void UpdateScanValue(int);
void ExportScanBuffer(void);
// Clipboard to hold data from copy/paste cells
/**
@brief Set to FALSE on first column copy. Prevents pasting from an uninitialized
clipboard.
*/
BOOL ClipboardEmpty = TRUE;
/**
@brief Clipboard for time.
*/
double TimeClip;
/**
@brief Clipboard for analog column.
*/
struct AnalogTableValues AnalogClip[NUMBERANALOGCHANNELS + 1];
/**
@brief Clipboard for digital column.
*/
int DigClip[NUMBERDIGITALCHANNELS + 1];
/**
@brief Clipboard for analog cell.
*/
struct AnalogTableValues AnalogCellClip = {.fcn = 1};
/**
@brief Clipboard for digital cell.
*/
int DigCellClip = 0;
/**
@brief Returns if the page is checked.
@param page The page number
@return 0 if not checked
@return 1 if checked
@author Kerry Wang
*/
BOOL IsPageChecked(int page) {
BOOL bool;
GetCtrlVal(panelHandle, CheckboxArray[page], &bool);
return bool;
}
/**
@brief Callback for the Run button. Disables scanning and activates the timer if
Repeat is enabled. Calls RunOnce() to run the ADwin.
*/
int CVICALLBACK CMD_RUN_CALLBACK(int panel, int control, int event,
void* callbackData, int eventData1,
int eventData2) {
int repeat = 0;
switch (event) {
case EVENT_COMMIT:
PScan.Scan_Active = FALSE;
// Forces the BuildUpdateList() routine to generate
// new data for the ADwin
ChangedVals = TRUE;
GetCtrlVal(panelHandle, PANEL_TOGGLEREPEAT,
&repeat); // reads the state of the "repeat" switch
if (repeat == TRUE) {
SetCtrlAttribute(panelHandle, PANEL_TIMER, ATTR_ENABLED, 1);
// activate timer: calls TIMER_CALLBACK to restart the RunOnce commands
// after a set time.
} else {
SetCtrlAttribute(panelHandle, PANEL_TIMER, ATTR_ENABLED, 0);
// deactivate timer
}
RunOnce(); // starts the routine to build the ADwin data.
break;
}
return 0;
}
/**
@brief Callback for the Scan button. Pretty much a copy of CMD_RUN_CALLBACK(),
but activates the Scan flag and resets the scan counter.
@todo could be integrated into the CMD_RUN routine.... but this works
*/
int CVICALLBACK CMD_SCAN_CALLBACK(int panel, int control, int event,
void* callbackData, int eventData1,
int eventData2) {
int repeat = 0;
switch (event) {
case EVENT_COMMIT:
UpdateScanValue(TRUE); // sending value of 1 resets the scan counter.
PScan.Scan_Active = TRUE;
ChangedVals = TRUE;
repeat = TRUE;
SetCtrlVal(panelHandle, PANEL_TOGGLEREPEAT,
repeat); // sets "repeat" button to active
SetCtrlAttribute(panelHandle, PANEL_TIMER, ATTR_ENABLED,
1); // Turn on the timer
RunOnce(); // starts the routine to build the ADwin data.
break;
}
return 0;
}
/**
@brief Callback for the timer object. When the timer's countdown reaches 0,
disable itself and call RunOnce() again.
The timer is activated in CMD_RUN_CALLBACK(), CMD_SCAN_CALLBACK(), and
BuildUpdateList(). It gets deactivated here and when we hit CMDSTOP_CALLBACK().
*/
int CVICALLBACK TIMER_CALLBACK(int panel, int control, int event,
void* callbackData, int eventData1,
int eventData2) {
switch (event) {
case EVENT_TIMER_TICK:
SetCtrlAttribute(panelHandle, PANEL_TIMER, ATTR_ENABLED, FALSE);
// disable timer and re-enable in the runonce (or update list) loop, if
// the repeat butn is pressed. reset the timer too and set a timer time of
// 50ms?
if (PScan.Scan_Active == TRUE) {
UpdateScanValue(FALSE);
}
RunOnce();
break;
}
return 0;
}
/**
@brief Callback for the Stop button. Turns off the timer object and the repeat
button.
Lets the ADwin finish its current program. Interrupting the program partway can
be bad for the equipment as the variables are not cleared in memory and updates
can get out of sync.
@author Stefan Myrskog
*/
int CVICALLBACK CMDSTOP_CALLBACK(int panel, int control, int event,
void* callbackData, int eventData1,
int eventData2) {
SetCtrlAttribute(panelHandle_sub2, SUBPANEL2, ATTR_VISIBLE,
0); // hide the SCAN display panel
switch (event) {
case EVENT_COMMIT:
SetCtrlAttribute(panelHandle, PANEL_TIMER, ATTR_ENABLED, 0);
SetCtrlVal(panelHandle, PANEL_TOGGLEREPEAT, 0);
// check to see if we need to export a Scan history
if (PScan.Scan_Active == TRUE) {
ExportScanBuffer();
}
break;
}
return 0;
}
/**
@brief Flattens the time, analog, and digital tables from multiple "pages" to a
single long page. Passes the tables to BuildUpdateList() to send to the ADwin.
@todo Change meta arrays to be malloc'd at runtime, or use dynamic lists.
@todo Change name to be more descriptive.
*/
void RunOnce(void) {
// could/should change these following defs and use malloc instead, but they
// should never exceed.. 170 or so.
// initialize the 0th element even though we're not using it,
// otherwise will raise uninitialized exception
double MetaTimeArray[500] = {0};
int MetaDigitalArray[NUMBERDIGITALCHANNELS + 1][500] = {0};
struct AnalogTableValues MetaAnalogArray[NUMBERANALOGCHANNELS + 1][500] = {0};
int mindex = 0; // Index in the meta arrays
// go through for each page
for (int page = 1; page <= NUMBEROFPAGES; page++) {
// if the page is selected (checkbox is checked)
if (IsPageChecked(page)) {
// go through for each column
for (int col = 1; col <= NUMBEROFCOLUMNS; col++) {
// Ignore columns with negative times
if (TimeArray[col][page] > 0) {
mindex++; // increase the number of columns counter
MetaTimeArray[mindex] = TimeArray[col][page];
// go through for each analog channel
for (int channel = 1; channel <= NUMBERANALOGCHANNELS; channel++) {
// Sets MetaArray with appropriate fcn val when "same" selected
if (AnalogTable[col][channel][page].fcn == 6) {
// on the right for repeat function, currently set to hold val
MetaAnalogArray[channel][mindex].fcn = 1;
MetaAnalogArray[channel][mindex].fval =
MetaAnalogArray[channel][mindex - 1].fval;
MetaAnalogArray[channel][mindex].tscale =
MetaAnalogArray[channel][mindex - 1].tscale;
} else {
MetaAnalogArray[channel][mindex] =
AnalogTable[col][channel][page];
}
}
for (int channel = 1; channel <= NUMBERDIGITALCHANNELS; channel++) {
MetaDigitalArray[channel][mindex] =
DigTableValues[col][channel][page];
}
}
// Skip to next page on time 0
else if (TimeArray[col][page] == 0) {
break;
}
}
}
}
DrawNewTable(1);
// Send the new arrays to BuildUpdateList()
BuildUpdateList(MetaTimeArray, MetaAnalogArray, MetaDigitalArray, mindex);
}
/**
@brief Builds the data from the arrays into ADwin-friendly format.
@param TMatrix[] Stores the interval time of each column
@param AMat[] Stores info located in the analog table
@param DMat[] Stores info located in the digital table
Each array can have up to 499 elements. Note that elements are 1-indexed, the
0-th index is undefined and should not be accessed.
@param numtimes The actual number of valid update period elements.
We generate the following 3 arrays:
- UpdateNum
- Each entry is the number of channel updates (i.e. ChNum/ChVal pairs) to be
performed on the next ADwin trigger, which comes once every 10 microseconds.
- ChNum
- Each entry is the channel number to be updated. Synchronous with ChVal.
Channel number definitions as follows:
- 1-32: Analog lines. ChVal is the voltage, from -10V to 10V.
- 101, 102: Digital cards, with 32 lines each. ChVal is a 32-bit integer, one
bit for each line, starting from LSB.
- ChVal
- Each entry is the value to be written to a channel. Synchronous with ChNum.
*/
void BuildUpdateList(
double TMatrix[500],
struct AnalogTableValues AMat[NUMBERANALOGCHANNELS + 1][500],
int DMat[NUMBERDIGITALCHANNELS + 1][500], int numtimes) {
BOOL UseCompression;
int NewTimeMat[500] = {0};
int UsingFcns[NUMBERANALOGCHANNELS + 1] = {0};
double cycletime = 0;
int repeat = 0, timesum = 0;
// Change run button appearance while operating
SetCtrlAttribute(panelHandle, PANEL_CMD_RUN, ATTR_CMD_BUTTON_COLOR,
VAL_GREEN);
int timemult = RoundRealToNearestInteger(
1 / EVENTPERIOD); // number of adwin upates per ms
// make a new time list...converting the TimeTable from milliseconds to number
// of events (numtimes=total #of columns)
for (int i = 1; i <= numtimes; i++) {
NewTimeMat[i] = RoundRealToNearestInteger(
TMatrix[i] * timemult); // number of Adwin events in column i
timesum = timesum + NewTimeMat[i]; // total number of Adwin events
}
cycletime =
timesum * EVENTPERIOD / 1000; // Total duration of the cycle, in seconds
// reupdate the ADWIN array if the user values have changed
if (ChangedVals == TRUE) {
// dynamically allocate the memory for the time array (instead of using a
// static array:UpdateNum) We are making an assumption about how many
// programmable points we may need to use. For now assume that number of
// channel updates <= 4* #of events, serious overestimate
int* UpdateNum = calloc(timesum + 1, sizeof *UpdateNum);
if (!UpdateNum) {
exit(1);
}
int* ChNum = calloc(timesum * 4, sizeof *ChNum);
if (!ChNum) {
exit(1);
}
float* ChVal = calloc(timesum * 4, sizeof *ChVal);
if (!ChVal) {
exit(1);
}
int nuptotal = 0;
int count = 0;
double NewAval, TempChVal, TempChVal2;
double LastAval[NUMBERANALOGCHANNELS + 1] = {0};
long ResetToZeroAtEnd[NUMBERANALOGCHANNELS + 6];
static int didboot = 0;
static int didprocess = 0;
// Go through for each column that needs to be updated
// Important Variables:
// count: Number of Adwin events until the current position
// nupcurrent: number of updates for the current Adwin event
// nuptotal: current position in the channel/value column
int LastDVal = 0;
int LastDVal2 = 0;
// make sure to always update on first column to
// prevent lingering from past loops in repeat mode
BOOL firstCol = TRUE;
for (int i = 1; i <= numtimes; i++) {
// find out how many channels need updating this round...
// if it's a non-step fcn, then keep a list of UsingFcns, and change it
// now
int nupcurrent = 0;
int usefcn = 0;
// scan over the analog channel..find updated values by comparing to old
// values.
for (int j = 1; j <= NUMBERANALOGCHANNELS; j++) {
LastAval[j] = -99;
if (AMat[j][i].fval != AMat[j][i - 1].fval) {
nupcurrent++;
nuptotal++;
ChNum[nuptotal] = AChName[j].chnum;
NewAval =
CalcFcnValue(AMat[j][i].fcn, AMat[j][i - 1].fval, AMat[j][i].fval,
AMat[j][i].tscale, 0.0, TMatrix[i]);
TempChVal = AChName[j].tbias + NewAval * AChName[j].tfcn;
ChVal[nuptotal] = CheckIfWithinLimits(TempChVal, j);
if (AMat[j][i].fcn != 1) {
usefcn++;
// mark these lines for special attention..more complex
UsingFcns[usefcn] = j;
}
}
} // done scanning the analog values.
// now the digital value
int digval = 0;
int digval2 = 0;
for (int row = 1; row <= NUMBERDIGITALCHANNELS; row++) {
int digchannel = DChName[row].chnum;
if (digchannel <= 32) {
// Set bits using logical OR. Technically left-shifting a 32 bit
// signed int by 31 bits is undefined behavior, but it works as
// expected on modern machines
digval |= (DMat[row][i] << (digchannel - 1));
} else if ((digchannel >= 101) && (digchannel <= 132)) {
digval2 |= DMat[row][i] << (digchannel - 101);
}
} // finished computing current digital data
if (firstCol || digval != LastDVal) {
nupcurrent++;
nuptotal++;
ChNum[nuptotal] = 101;
ChVal[nuptotal] = digval;
}
LastDVal = digval;
if (firstCol || digval2 != LastDVal2) {
nupcurrent++;
nuptotal++;
ChNum[nuptotal] = 102;
ChVal[nuptotal] = digval2;
}
LastDVal2 = digval2;
firstCol = FALSE;
count++;
UpdateNum[count] = nupcurrent;
// end of first scan
// now do the remainder of the loop...but just the complicated fcns, i.e.
// ramps, sine wave
int t = 0;
while (t < NewTimeMat[i] - 1) {
t++;
int k = 0;
nupcurrent = 0;
while (k < usefcn) {
k++;
int c = UsingFcns[k];
NewAval =
CalcFcnValue(AMat[c][i].fcn, AMat[c][i - 1].fval, AMat[c][i].fval,
AMat[c][i].tscale, t, TMatrix[i]);
TempChVal = AChName[c].tbias + NewAval * AChName[c].tfcn;
TempChVal2 = CheckIfWithinLimits(TempChVal, c);
// only update if the ADwin will output a new value.
// ADwin is 16 bit, +/-10 V, to 1 bit resolution implies dV=20V/2^16
// ~= 0.3mV
if (fabs(TempChVal2 - LastAval[k]) > 0.0003) {
nupcurrent++;
nuptotal++;
ChNum[nuptotal] = AChName[c].chnum;
ChVal[nuptotal] = AChName[c].tbias + NewAval * AChName[c].tfcn;
LastAval[k] = TempChVal2;
}
}
count++;
UpdateNum[count] = nupcurrent;
} // Done this element of the TMatrix
} // done scanning over times array
// read some menu options
GetMenuBarAttribute(menuHandle, MENU_PREFS_COMPRESSION, ATTR_CHECKED,
&UseCompression);
int newcount = 0;
if (UseCompression) {
newcount = OptimizeTimeLoop(UpdateNum, count);
}
// tstop = clock();
if (didboot == FALSE) // is the ADwin booted? if not, then boot
{
Boot("ADbasic\\ADwin11.btl", 0);
didboot = 1;
}
if (didprocess == FALSE) // is the ADwin process already loaded?
{
Load_Process("ADbasic\\TransferDataExternalClock.TB1");
didprocess = 1;
}
if (UseCompression) {
// Let ADwin know how many counts (read as Events)
// we will be using.
SetPar(1, newcount);
SetData_Long(1, UpdateNum, 1, newcount + 1);
} else {
// Let ADwin know how many counts (read as Events) we
// will be using.
SetPar(1, count);
SetData_Long(1, UpdateNum, 1, count + 1);
}
// Send the Array to the AdWin Sequencer
int GlobalDelay = 3000; // 3000 * 3.33...ns = 0.01 ms ticks. No longer
// necessary with external trigger, but still here
// in case we ever need to use the internal clock
SetPar(2, GlobalDelay);
SetData_Long(2, ChNum, 1, nuptotal + 1);
SetData_Float(3, ChVal, 1, nuptotal + 1);
for (int i = 1; i <= NUMBERANALOGCHANNELS; i++) {
ResetToZeroAtEnd[i - 1] = AChName[i].resettozero;
}
SetData_Long(4, ResetToZeroAtEnd, 1, NUMBERANALOGCHANNELS);
// done evaluating channels that are reset to zero (low)
ChangedVals = 0;
free(UpdateNum);
free(ChNum);
free(ChVal);
}
Start_Process(1); // start the process on ADwin
SetCtrlAttribute(panelHandle, PANEL_CMD_RUN, ATTR_CMD_BUTTON_COLOR,
0x00B0B0B0);
// re-enable the timer if necessary
GetCtrlVal(panelHandle, PANEL_TOGGLEREPEAT, &repeat);
if ((PScan.Scan_Active == TRUE) && (PScan.ScanDone == TRUE)) {
repeat = FALSE; // remember to reset the front panel repeat button
SetCtrlVal(panelHandle, PANEL_TOGGLEREPEAT, repeat);
}
if (repeat == TRUE) {
SetCtrlAttribute(panelHandle, PANEL_TIMER, ATTR_ENABLED, 1);
SetCtrlAttribute(panelHandle, PANEL_TIMER, ATTR_INTERVAL, cycletime);
ResetTimer(panelHandle, PANEL_TIMER);
}
}
/**
@brief Given an analog function setting and a time, calculate the analog value.
@param fcn Function type, see AnalogTableValues.fcn.
@param Vinit For ramps and S curve, voltage at telapsed = 0. Not used for step
and sine wave.
@param Vfinal For step, voltage to step to. For ramps and S curve, voltage at
telapsed >= timescale. For sine wave, the amplitude.
@param timescale For ramps and S curve, time to reach Vfinal. For sine wave, the
frequency. Not used for step.
@param telapsed The time elapsed since the start of the cell.
@param celltime Total time duration of this cell
@return The resulting analog value.
@todo What is SimpleTiming? Seems turned on by default.
*/
double CalcFcnValue(int fcn, double Vinit, double Vfinal, double timescale,
double telapsed, double celltime) {
BOOL UseSimpleTiming;
GetMenuBarAttribute(menuHandle, MENU_PREFS_SIMPLETIMING, ATTR_CHECKED,
&UseSimpleTiming);
double value = -99;
double amplitude;
if (UseSimpleTiming == TRUE) {
timescale = celltime - EVENTPERIOD;
}
if (timescale <= 0) {
timescale = 1;
}
double tms = telapsed * EVENTPERIOD;
// add commands here to select 'simple timing'
switch (fcn) {
case 1: // step function
value = Vfinal;
break;
case 2: // linear ramp
amplitude = Vfinal - Vinit;
double slope = amplitude / timescale;
if (tms > timescale) {
value = Vfinal;
} else {
value = Vinit + slope * tms;
}
break;
case 3: // exponential
amplitude = Vfinal - Vinit;
double newtime = timescale;
if (UseSimpleTiming == TRUE) {
newtime = timescale / fabs(log(fabs(amplitude)) - log(0.001));
}
value = Vfinal - amplitude * exp(-tms / newtime);
break;
case 4: // S curve
amplitude = Vfinal - Vinit;
double aconst = 3 * amplitude / pow(timescale, 2);
double bconst = -2 * amplitude / pow(timescale, 3);
if (tms > timescale) {
value = Vfinal;
} else {
value = Vinit + (aconst * pow(tms, 2) + bconst * pow(tms, 3));
}
break;
case 5:
// generate a sinewave. Use Vfinal as the amplitude and timescale
// as the frequency
// ignore the 'Simple Timing' option...use the user entered value.
amplitude = Vfinal;
// consider it to be Hertz (tms is time in milliseconds)
value = amplitude * sin(2 * Pi() * timescale * tms / 1000);
}
// Check if the value exceeds the allowed voltage limits.
return value;
}
/**
@brief Compresses the UpdateNum list by replacing long strings of 0's with a
single negative number representing the amount replaced. i.e. if we see 2000 0's
in a row, replace with -2000 instead.
@param UpdateNum Array to be optimized (1-indexed)
@param count Length of UpdateNum
@return Length of UpdateNum after optimization, including index 0
*/
int OptimizeTimeLoop(int* UpdateNum, int count) {
int i = 1; // i is the counter through the original UpdateNum list
int t = 1; // t is the counter through the NewUpdateNum list
int LowZeroThreshold =
0; // minimum number of consecutive zero's to encounter before optimizing
int HighZeroThreshold =
100000; // maximum number of consecutive zero's to optimize
// Loop through UpdateNum[]
while (i <= count) {
if (UpdateNum[i] != 0) {
UpdateNum[t] = UpdateNum[i];
i++;
t++;
} else // found a 0
{ // now we need to scan to find the # of zeros
int j = 1;
while (((i + j) < (count + 1)) && (UpdateNum[i + j] == 0)) {
j++;
} // if this fails, then AA[i+j]!=0
if ((i + j) < (count + 1)) {
int numberofzeros = j;
if (numberofzeros <= LowZeroThreshold) {
for (int k = 1; k <= numberofzeros; k++) {
UpdateNum[t] = 0;
t++;
i++;
}
} else {
while (numberofzeros > HighZeroThreshold) {
numberofzeros = numberofzeros - HighZeroThreshold;
UpdateNum[t] = -HighZeroThreshold;
t++;
}
UpdateNum[t] = -numberofzeros;
t++;
UpdateNum[t] = UpdateNum[i + j];
t++;
i = i + j + 1;
}
} else {
UpdateNum[t] = -(count + 1 - i - j);
i = i + j + 1;
}
}
}
return t;
}
// June 7, 2005 : Completed Scan capability, added on-screen display of scan
// progress.
// May 11, 2005: added capability to change time and DDS settings too.
// Redesigned Scan structure May 03, 2005 existing problem: if the final value
// isn't exactly reached by the steps, then the last stage is skipped and the
// cycle doesn't end
// has to do with numsteps. Should be programmed with ceiling(), not abs
/**
@brief Black magic
@todo Write documentation
*/
void UpdateScanValue(int Reset) {
int cx, cy, cz;
double cellval, nextcell;
BOOL UseList;
int hour, minute, second;
static BOOL ScanUp;
static int timesdid, counter;
cx = PScan.Column;
cy = PScan.Row;
cz = PScan.Page;
SetCtrlAttribute(panelHandle_sub2, SUBPANEL2, ATTR_VISIBLE, 1);
// if Use_List is checked, then read values off of the SCAN_TABLE on the main
// panel.
GetCtrlVal(panelHandle7, SCANPANEL_CHECK_USE_LIST, &UseList);
// Initialization on first iteration
if (Reset == TRUE) {
counter = 0;
for (int i = 0; i < 1000; i++) {
ScanBuffer[i].Step = 0;
ScanBuffer[i].Iteration = 0;
ScanBuffer[i].Value = 0;
}
// Copy information from the appropriate scan mode to the variables.
switch (PScan.ScanMode) {
case 0: // set to analog
ScanVal.End = PScan.Analog.End_Of_Scan;
ScanVal.Start = PScan.Analog.Start_Of_Scan;
ScanVal.Step = PScan.Analog.Scan_Step_Size;
ScanVal.Iterations = PScan.Analog.Iterations_Per_Step;
break;
case 1: // time scan
ScanVal.End = PScan.Time.End_Of_Scan;
ScanVal.Start = PScan.Time.Start_Of_Scan;
ScanVal.Step = PScan.Time.Scan_Step_Size;
ScanVal.Iterations = PScan.Time.Iterations_Per_Step;
break;
}
// if we are set to use the scan list instead of a linear
// scan, then read first value
if (UseList) {
GetTableCellVal(panelHandle, PANEL_SCAN_TABLE, MakePoint(1, 1), &cellval);
ScanVal.Start = cellval;
}
timesdid = 0;
ScanVal.Current_Step = 0;
ScanVal.Current_Iteration = -1;
ScanVal.Current_Value = ScanVal.Start;
// determine the sign of the step and correct if necessary
if (ScanVal.End >= ScanVal.Start) {
ScanUp = TRUE;
if (ScanVal.Step < 0) {
ScanVal.Step = -ScanVal.Step;
}
} else {
ScanUp = FALSE; // ie. we scan downwards
if (ScanVal.Step > 0) {
ScanVal.Step = -ScanVal.Step;
}
}
} // Done setting/resetting values
// numsteps to depend on mode
if (UseList) {
// UseList=TRUE .... therefore using table of Scan Values
ScanVal.Current_Iteration++;
if (ScanVal.Current_Iteration >= ScanVal.Iterations) {
ScanVal.Current_Iteration = 0;
ScanVal.Current_Step++;
// read next element of scan list
GetTableCellVal(panelHandle, PANEL_SCAN_TABLE,
MakePoint(1, ScanVal.Current_Step + 1), &cellval);
// indicate which element of the list we are currently using
SetTableCellAttribute(panelHandle, PANEL_SCAN_TABLE,
MakePoint(1, ScanVal.Current_Step + 1),
ATTR_TEXT_BGCOLOR, VAL_LT_GRAY);
SetTableCellAttribute(panelHandle, PANEL_SCAN_TABLE,
MakePoint(1, ScanVal.Current_Step),
ATTR_TEXT_BGCOLOR, VAL_WHITE);
ScanVal.Current_Value = cellval;
ChangedVals = TRUE;
}
}
else {
// UseList=FALSE.... therefor assume linear scanning
// calculate number of steps in the ramp
int numsteps = ceil(fabs((ScanVal.Start - ScanVal.End) / ScanVal.Step));
PScan.ScanDone = FALSE;
timesdid++;
ScanVal.Current_Iteration++;
if ((ScanVal.Current_Iteration >= ScanVal.Iterations) &&
(ScanVal.Current_Step < numsteps)) // update the step at correct time
{
ScanVal.Current_Iteration = 0;
ScanVal.Current_Step++;
ScanVal.Current_Value = ScanVal.Current_Value + ScanVal.Step;
ChangedVals = TRUE;
}
// if we are at the last step, then set the scan value to the last value (in
// case the step size causes the scan to go too far
if ((ScanVal.Current_Value >= ScanVal.End) && (ScanUp == TRUE)) {
ScanVal.Current_Value = ScanVal.End;
}
if ((ScanVal.Current_Value <= ScanVal.End) && (ScanUp == FALSE)) {
ScanVal.Current_Value = ScanVal.End;
}
}
// insert current scan values into the tables , so they are included in the
// next BuildUpdateList
switch (PScan.ScanMode) {
case 0: // Analog value
AnalogTable[cx][cy][cz].fval = ScanVal.Current_Value;
AnalogTable[cx][cy][cz].fcn = PScan.Analog.Analog_Mode;
break;
case 1: // Time duration
TimeArray[cx][cz] = ScanVal.Current_Value;
break;
}
// Record current scan information into a string buffer, so we can write it to
// disk later.
GetSystemTime(&hour, &minute, &second);
ScanBuffer[counter].Step = ScanVal.Current_Step;
ScanBuffer[counter].Iteration = ScanVal.Current_Iteration;
ScanBuffer[counter].Value = ScanVal.Current_Value;
ScanBuffer[0].BufferSize = counter;
sprintf(ScanBuffer[counter].Time, "%d:%d:%d", hour, minute, second);
counter++;
// display current scan parameters on screen
SetCtrlVal(panelHandle_sub2, SUBPANEL2_NUM_SCANVAL, ScanVal.Current_Value);
SetCtrlVal(panelHandle_sub2, SUBPANEL2_NUM_SCANSTEP, ScanVal.Current_Step);
SetCtrlVal(panelHandle_sub2, SUBPANEL2_NUM_SCANITER,
ScanVal.Current_Iteration);
// check for end condition
if (UseList) // Scanning ends if we program -999 into a cell of the Scan List
{
GetTableCellVal(panelHandle, PANEL_SCAN_TABLE,
MakePoint(1, ScanVal.Current_Step + 2), &nextcell);
if ((nextcell <= -999) &&
(ScanVal.Current_Iteration >= ScanVal.Iterations - 1)) {
PScan.ScanDone = TRUE;
}
}
else // not using the ScanTable
{
if (ScanUp) {
if ((ScanVal.Current_Value >= ScanVal.End) &&
(ScanVal.Current_Iteration >= ScanVal.Iterations - 1)) { // Done Scan
PScan.ScanDone = TRUE; // Flag used in RunOnce() to initiate a stop
}
} else {
if ((ScanVal.Current_Value <= ScanVal.End) &&
(ScanVal.Current_Iteration >= ScanVal.Iterations - 1)) { // Done Scan
PScan.ScanDone = TRUE; // Flag used in RunOnce() to initiate a stop
}
}
} // done checking the scan is done
// if the scan is done, then cleanup and write the starting values back into
// the tables
if (PScan.ScanDone == TRUE) { // reset initial values in the tables
AnalogTable[cx][cy][cz].fval = PScan.Analog.Start_Of_Scan;
TimeArray[cx][cz] = PScan.Time.Start_Of_Scan;
// hide the information panel
SetCtrlAttribute(panelHandle_sub2, SUBPANEL2, ATTR_VISIBLE, 0);
ExportScanBuffer(); // prompt to write out information
}
}
/**
@brief Loads internal arrays from the .arr file.
@param savedname[] Path to the associated .pan file
Note that if the lengths of any of the data arrays are changed, previous saves
will no longer be compatible. See the save-converter branch.
*/
void LoadArrays(char savedname[500]) {
char buff[500] = "";
strncat(buff, savedname, strlen(savedname) - 4);
strncat(buff, ".arr", 4);
FILE* fdata = fopen(buff, "rb");
if (fdata == NULL) {
MessagePopup("Load error", "Failed to open file");
return;
}
// now for the times.
fread(&TimeArray, sizeof TimeArray, 1, fdata);
// and the analog data
fread(&AnalogTable, sizeof AnalogTable, 1, fdata);
fread(&DigTableValues, sizeof DigTableValues, 1, fdata);
fread(&AChName, sizeof AChName, 1, fdata);
fread(&DChName, sizeof DChName, 1, fdata);
char buttonName[80];
for (int page = 1; page <= NUMBEROFPAGES; page++) {
fread(&buttonName, sizeof buttonName, 1, fdata);
SetCtrlAttribute(panelHandle, ButtonArray[page], ATTR_ON_TEXT, buttonName);
SetCtrlAttribute(panelHandle, ButtonArray[page], ATTR_OFF_TEXT, buttonName);
}
fclose(fdata);
SetAnalogChannels();
SetDigitalChannels();
}
/**
@brief Saves internal arrays to a .arr file.
@param savedname[] Path to the associated .pan file
Note that if the lengths of any of the data arrays are changed, previous saves
will no longer be compatible. See the save-converter branch.
*/
void SaveArrays(char savedname[500]) {
char buff[500] = "";
strncpy(buff, savedname, strlen(savedname) - 4);
strncat(buff, ".arr", 4);
FILE* fdata = fopen(buff, "wb");
if (fdata == NULL) {
MessagePopup("Save error", "Failed to open file for writing");
return;
}
// now for the times.
fwrite(&TimeArray, sizeof TimeArray, 1, fdata);
// and the analog data
fwrite(&AnalogTable, sizeof AnalogTable, 1, fdata);
fwrite(&DigTableValues, sizeof DigTableValues, 1, fdata);
fwrite(&AChName, sizeof AChName, 1, fdata);
fwrite(&DChName, sizeof DChName, 1, fdata);
char buttonName[80];
for (int page = 1; page <= NUMBEROFPAGES; page++) {
GetCtrlAttribute(panelHandle, ButtonArray[page], ATTR_ON_TEXT, buttonName);
fwrite(&buttonName, sizeof buttonName, 1, fdata);
}
fclose(fdata);
}
/**
@brief Loads panel values from .pan and .arr files.
*/
void LoadSettings(void) {
int status = ConfirmPopup(
"Load",
"Are you sure you want to load a new panel?\nUnsaved data will be lost!");
if (status == 0) {
return; // Don't load
}
char fsavename[500];
// prompt for a file, if selected then load the Panel and Arrays
status = FileSelectPopupEx("C:\\UserDate\\Data", "*.pan", "", "Load Settings",
VAL_LOAD_BUTTON, 0, 0, fsavename);
if (status != VAL_EXISTING_FILE_SELECTED) {
return;
}
if (RecallPanelState(panelHandle, fsavename, 1) < 0) {
MessagePopup("Load error", "Failed to load from file");
return;
}
RecallPanelState(commentsHandle, fsavename, 2);
LoadArrays(fsavename);
SetPanelAttribute(panelHandle, ATTR_TITLE, fsavename);
// Reset button state and redraw table by simulating click on first page
// button
TOGGLE_CALLBACK(panelHandle, ButtonArray[1], EVENT_COMMIT, NULL, 0, 0);
}
/**
@brief Saves panel values to .pan and .arr files.
*/
void SaveSettings(void) {
char fsavename[500];
int status =
FileSelectPopupEx("C:\\UserDate\\Data", "*.pan", "", "Save Settings",
VAL_SAVE_BUTTON, 0, 0, fsavename);
if (status != VAL_NO_FILE_SELECTED) {
SavePanelState(panelHandle, fsavename, 1);
SavePanelState(commentsHandle, fsavename, 2);
SaveArrays(fsavename);
SetPanelAttribute(panelHandle, ATTR_TITLE, fsavename);
} else {
MessagePopup("File Error", "No file was selected");
}
}
/**
@brief Helper function to alternate color every three rows
@param index 1-based index to get color for
@return Hex code for gray or light gray, depending on index
@author Kerry Wang
*/
int ColorPicker(int index) {
index--; // correct for 1-based indices
if ((index / 3) % 2)
return VAL_GRAY;
else
return 0x00B0B0B0;
}
/**
@brief Redraws analog and digital tables.
@param isdimmed Whether or not to dim disabled columns
*/
void DrawNewTable(int isdimmed) {
if (IsPageChecked(currentpage) == FALSE) { // dim the tables
SetCtrlAttribute(panelHandle, PANEL_ANALOGTABLE, ATTR_DIMMED, 1);
SetCtrlAttribute(panelHandle, PANEL_DIGTABLE, ATTR_DIMMED, 1);
SetCtrlAttribute(panelHandle, PANEL_TIMETABLE, ATTR_DIMMED, 1);
} else { // undim the tables
SetCtrlAttribute(panelHandle, PANEL_ANALOGTABLE, ATTR_DIMMED, 0);
SetCtrlAttribute(panelHandle, PANEL_DIGTABLE, ATTR_DIMMED, 0);
SetCtrlAttribute(panelHandle, PANEL_TIMETABLE, ATTR_DIMMED, 0);
}
for (int i = 1; i <= NUMBEROFCOLUMNS; i++) // scan over the columns
{
SetTableCellAttribute(panelHandle, PANEL_TIMETABLE, MakePoint(i, 1),
ATTR_CELL_DIMMED, 0);
// scan over analog channels
for (int j = 1; j <= NUMBERANALOGCHANNELS; j++) {
int cmode = AnalogTable[i][j][currentpage].fcn;
double vnow = AnalogTable[i][j][currentpage].fval;
if (cmode != 6) {
// write the ending value into the cell
SetTableCellAttribute(panelHandle, PANEL_ANALOGTABLE, MakePoint(i, j),
ATTR_CTRL_VAL, vnow);
} else if (i == 1 && currentpage == 1) {
ConfirmPopup("User Error",