-
Notifications
You must be signed in to change notification settings - Fork 0
/
arduino_version.ino
1711 lines (1498 loc) · 60.6 KB
/
arduino_version.ino
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
/*
* This Arduino sketch is the software for a pan/tilt/zoom controller. It uses wired motor control
* for panning and tilting, and uses LANC for sending zoom commands to compatible cameras. It
* supports both the Bescor MP-101 (with direct wiring) and the Vidpro MH-430 (with a Pololu
* Dual MC33926 Motor Driver Shield). The LANC circuit can be found on the web at:
*
* http://controlyourcamera.blogspot.com/2011/02/arduino-controlled-video-recording-over.html
*
* Note that the record button in that circuit is unused, and does not need to be included.
* The LANC portions of this code are verified to work with the Canon XH-A1, Panasonic AG-CX350,
* and Sony DCR-TRV9. It is likely that it will work with any LANC-compatible (a.k.a. Control-L)
* camera.
*/
/*
* PTZ Controller
* © 2020 David A. Gatwood.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Constants. Do not change
#define PTZ_MODE_LANC 0
#define PTZ_MODE_P2 1
#define PTZ_MODE_PANASONIC_PTZ 2
#pragma mark - Configuration settings
#undef TEMPORARY_NO_LANC
// For MP-101 hardware configuration, set to true (different outputs).
// For Vidpro MH-430 hardware configuration with a motor controller, set to false.
#define USE_MP_101_MODE 0
// Enables VISCA remote control support.
//
// This code can be used in conjunction with an Ethernet shield and a CAN bus shield
// to provide support for remote control.
//
// In this mode, this software listens for VISCA UDP messages on port 17479 (DG in ASCII)
// and sends back a response to the sending port/IP.
//
// It then uses LANC to control the pan, tilt, and zoom speed based on those
// commands unless the control switch pin (NETWORK_MODE_SWITCH_PIN) is grounded,
// in which case it provides local manual control. Thus, the same control box
// can be used either within a few feet of the device by a nearby operator or
// remotely over the network by an operator far away.
#define ENABLE_VISCA 1
// Enables absolute position storage and retrieval of pan and tilt.
#define ENABLE_ABSOLUTE_POSITIONING 1
// Enables absolute zoom positioning and tally light status (Panasonic cameras only).
#define ENABLE_ABSOLUTE_ZOOM 1
// Sets the PTZ mode
//
// PTZ_MODE_LANC: Normal LANC-only mode.
// PTZ_MODE_P2: P2 protocol mode (experimental).
// PTZ_MODE_PANASONIC_PTZ: PTZ protocol mode (experimental).
//
#define ACTIVE_PTZ_MODE PTZ_MODE_PANASONIC_PTZ
// Uses the current tally state (Panasonic cameras only) to determine the maximum
// pan, tilt, and zoom speed. Supported only if ACTIVE_PTZ_MODE == PTZ_MODE_P2.
#define USE_TALLY_FOR_SPEED_CONTROL 1
// Speed settings used for preset recall when speed is determined using tally lights.
#define LIVE_MAX_PAN_SPEED 8 // Max is 24
#define LIVE_MAX_TILT_SPEED 8 // Max is 24
#define LIVE_MAX_ZOOM_SPEED 3 // Max is 8
#define OFFLINE_MAX_PAN_SPEED 24 // Max is 24
#define OFFLINE_MAX_TILT_SPEED 24 // Max is 24
#define OFFLINE_MAX_ZOOM_SPEED 8 // Max is 8
// Set to 1 to make (manual) zooming faster when controlled over VISCA. The VISCA
// protocol supports zoom speeds from -7 to 7. The LANC protocol supports zoom
// speeds from 0 to 7 in each direction, plus a separate command for stopping,
// i.e. effectively the equivalent of -8 to 8. By default, this software maps the
// VISCA speeds 1:1, leaving the fastest LANC zoom speed unused. Setting this to
// 1 changes the mapping so that the slowest LANC zoom speed is unused instead.
#define ENABLE_FASTER_VISCA_ZOOM 0
#define USE_S_CURVE 1
// Enabling this causes it to send a CAN-bus command that tells a rotary encoder
// to change its device ID.
#undef reassignCANBusID
#define oldCANBusID 1
#define newCANBusID 2
#define panCANBusID 1
#define tiltCANBusID 2
int current_pan_position = 0;
int current_tilt_position = 0;
const double e_constant = 2.71828;
#if ENABLE_VISCA
#define NETWORK_MODE_SWITCH_PIN 22
#define SD_CS_PIN 6
#define ETHERNET_CS_PIN 10
#define CAN_BUS_CS_PIN 41
#include <SD.h>
// Configure the Ethernet shield here.
const byte arduino_mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEE };
const byte arduino_ip[] = { 192, 168, 100, 252 };
const byte arduino_dns[] = { 8, 8, 8, 8 }; // Unused.
const byte arduino_gateway[] = { 192, 168, 100, 1 };
const byte arduino_subnet[] = { 255, 255, 255, 0 };
EthernetUDP listen_udp;
const unsigned short listen_port = 17479;
bool pan_recall_in_progress = false; // True if a pan recall is in progress, else false.
int current_pan_recall_start = -1; // The starting position for the current pan recall.
int current_pan_recall_target = -1; // The target position for the current pan recall.
int current_pan_speed = 0; // The current pan speed provided by either
// a pan/tilt speed command or by an active
// preset recall.
int current_pan_recall_max_speed = 0; // The speed for the current motion, whether provided
// in a VISCA absolute move command or loaded from
// default_pan_recall_max_speed during a preset recall.
int default_pan_recall_max_speed = 10; // The speed used for tilting during a preset recall.
bool tilt_recall_in_progress = false; // True if a tilt recall is in progress, else false.
int current_tilt_recall_start = -1; // The starting position for the current tilt recall.
int current_tilt_recall_target = -1; // The target position for the current tilt recall.
int current_tilt_speed = 0; // The current tilt speed provided by either
// a pan/tilt speed command or by an active
// preset recall.
int current_tilt_recall_max_speed = 0; // The speed for the current motion, whether provided
// in a VISCA absolute move command or loaded from
// default_pan_recall_max_speed during a preset recall.
int default_tilt_recall_max_speed = 10; // The speed used for tilting during a preset recall.
int current_tally_state; // 0 if off, 5 if on program, 6 if on preview.
typedef struct {
uint8_t cmd[2];
uint16_t len;
uint32_t sequence_number;
uint8_t data[30]; // In theory, if IPv6, could be up to 65519, but not enough RAM for that.
} visca_cmd_t;
typedef struct {
uint8_t cmd[2];
uint16_t len; // Big endian!
uint32_t sequence_number;
uint8_t data[30]; // In theory, if IPv6, could be up to 65527, but not enough RAM for that.
} visca_response_t;
typedef struct {
int pan_position;
int tilt_position;
int zoom_position;
} position_data_blob_t;
#define bcopy(src, dest, len) memcpy(dest, src, len)
#define htons(a) ((a & 0x00ff) << 8) | ((a & 0xff00) >> 8)
int current_zoom_position = 0; // Absolute position provided by P2 data, or 0.
#if ENABLE_ABSOLUTE_POSITIONING
MCP2515 mcp2515(CAN_BUS_CS_PIN);
#endif
#if ENABLE_ABSOLUTE_ZOOM
// The IP address of the Panasonic camera, if applicable.
const byte camera_ip[] = { 192, 168, 100, 14 };
IPAddress panasonic_address = IPAddress(camera_ip);
EthernetUDP panasonic_udp;
const unsigned short panasonic_p2_port = 49153;
bool zoom_recall_in_progress = false; // True if a zoom recall is in progress, else false.
int current_zoom_recall_start = -1; // The starting position for the current zoom recall.
int current_zoom_recall_target = -1; // The target position for the current zoom recall.
int current_zoom_speed = 0; // The current zoom speed provided by either
// a zoom speed command or by an active
// preset recall.
int current_zoom_recall_max_speed = 0; // The speed for the current motion, whether provided
// in a VISCA absolute move command or loaded from
// default_pan_recall_max_speed during a preset recall.
int default_zoom_recall_max_speed = 10; // The speed used for tilting during a preset recall.
typedef struct p2_optical_data {
uint8_t type;
uint8_t size;
uint8_t reserved_1;
uint8_t reserved_2;
uint8_t reserved_3;
uint8_t focus_ft_high;
uint8_t focus_ft_low;
uint8_t focus_in;
uint8_t iris_high;
uint8_t iris_low;
uint8_t focus_exp : 4;
uint8_t focus_sig_high : 4;
uint8_t focus_sig_low;
uint8_t zoom_exp : 4;
uint8_t zoom_sig_high : 4;
uint8_t zoom_sig_low;
uint8_t lens_model_name[30];
uint8_t master_gain_high;
uint8_t master_gain_low;
uint8_t shutter_speed_high;
uint8_t shutter_speed_low;
uint8_t reserved_4 : 4;
uint8_t shutter_mode : 4;
uint8_t shutter_speed_decimal;
uint8_t gamma_mode;
uint8_t reserved_5;
uint8_t atw_wb : 2;
uint8_t under_over : 2;
uint8_t color_temp_high : 4;
uint8_t color_temp_low;
uint8_t nd_filter;
uint8_t cc_filter;
uint8_t iris_info : 2;
uint8_t focus_info : 2;
uint8_t zoom_info : 2;
uint8_t model_info : 2;
uint8_t agc_enabled : 1;
uint8_t gain_mode : 1;
uint8_t iA_zoom_info : 2;
uint8_t rb_gain_info : 1;
uint8_t iris_type : 1;
uint8_t iZoom_sm : 1;
uint8_t nd_disp_type : 1;
uint8_t vfr_mode : 4;
uint8_t vfr_frame_rate_high : 4;
uint8_t vfr_frame_rate_low;
uint8_t iA_zoom_exp : 4;
uint8_t iA_zoom_high : 4;
uint8_t iA_zoom_low;
uint8_t iso_select : 4;
uint8_t e1_gain_mode : 1;
uint8_t awb_color_temp : 1;
uint8_t color_temp_mag : 1;
uint8_t awb_channel : 1;
uint8_t color_temp_GMg_high;
uint8_t color_temp_GMg_low;
} p2_optical_data_t;
typedef struct p2_camera_data {
uint8_t type;
uint8_t size;
uint8_t junk1;
uint8_t junk2;
uint8_t tally_and_thumbnail;
uint8_t junk3[30];
} p2_camera_data_t;
#endif
#endif
bool useNetwork = false; // Updated each loop from NETWORK_MODE_SWITCH_PIN if networking is enabled, else false.
const int kMotorMax = 400;
const double kMotorSpeedPower = 2.0;
const int kMinimumMotorThreshold = 50; // Ensure that values close to the center are treated as stopped.
#if ACTIVE_PTZ_MODE == PTZ_MODE_PANASONIC_PTZ
const int kZoomMax = 49;
#else
const int kZoomMax = 9;
#endif
const double kZoomSpeedPower = 2.0;
const int kMinimumZoomThreshold = 50; // Ensure that values close to the center are treated as stopped.
bool networkMode = false;
#if !USE_MP_101_MODE
DualMC33926MotorShield md;
#endif
// The analog pins are the same in all configurations.
#define MP101AnalogPowerPin A0
#define MP101AnalogGroundPin A1
#define horizontalSensePin A3
#define verticalSensePin A2
#define zoomSensePin A4
#if ENABLE_VISCA && USE_MP_101_MODE
// VISCA requires a Mega 2560, because there aren't enough pins on a normal Arduino.
// By using the same pin order, you can just move the connector over.
// One connector is on the odd pins from one end. The other is on the even pins
// near the other end, leaving the last four pins clear because they are needed for SPI.
#if ACTIVE_PTZ_MODE == PTZ_MODE_LANC || ACTIVE_PTZ_MODE == PTZ_MODE_P2
#define LANC_ENABLED 1
#endif
#if LANC_ENABLED
#define lancOutputPin 33
#define lancInputPin 42
#endif
#define MP101UpPin 25
#define MP101DownPin 27
#define MP101LeftPin 29
#define MP101RightPin 31
#elif ENABLE_VISCA // && ! USE_MP_101_MODE
#if LANC_ENABLED
#define lancOutputPin 48
#define lancInputPin 42
#endif
#elif USE_MP_101_MODE
// The MP101 setup doesn't have the motor control on pin 8, so keep LANC on a single connector.
#if LANC_ENABLED
#define lancOutputPin 8
#define lancInputPin 11
#endif
#define MP101UpPin 2
#define MP101DownPin 3
#define MP101LeftPin 4
#define MP101RightPin 5
#else // !ENABLE_VISCA && ! USE_MP_101_MODE
// Use the only free pin we have on a non-Mega Arduino.
#if LANC_ENABLED
#define lancOutputPin 6
#define lancInputPin 11
#endif
#endif
typedef enum {
kDebugModePan = 0x1,
kDebugModeTilt = 0x2,
kDebugModeZoom = 0x4,
kDebugScaling = 0x8,
kDebugLANC = 0x16,
} debugMode;
int debugPanAndTilt = 0; // kDebugModePan;// kDebugModeZoom; // Bitmap from debugMode.
void setup() {
// Initialize the motor controller
Serial.begin(9600);
#if USE_MP_101_MODE
pinMode(MP101AnalogPowerPin, OUTPUT);
digitalWrite(MP101AnalogPowerPin, HIGH);
pinMode(MP101AnalogGroundPin, OUTPUT);
digitalWrite(MP101AnalogGroundPin, LOW);
pinMode(MP101UpPin, OUTPUT);
pinMode(MP101DownPin, OUTPUT);
pinMode(MP101LeftPin, OUTPUT);
pinMode(MP101RightPin, OUTPUT);
#else // !USE_MP_101_MODE
Serial.print(F("Initializing motor controller."));
md.init();
Serial.print(F("Done."));
#endif
#if ENABLE_VISCA
pinMode(NETWORK_MODE_SWITCH_PIN, INPUT_PULLUP);
pinMode(11,INPUT);
pinMode(12,INPUT);
pinMode(13,INPUT);
pinMode(53,OUTPUT);
digitalWrite(53,HIGH);
#if ENABLE_ABSOLUTE_POSITIONING
configureCANBus();
#endif
#endif
#ifndef TEMPORARY_NO_LANC
#if LANC_ENABLED
Serial.print(F("Initializing LANC."));
lancSetup();
Serial.print(F("Done."));
#endif
#endif // TEMPORARY_NO_LANC
#if ENABLE_VISCA
pinMode(SD_CS_PIN, OUTPUT);
pinMode(ETHERNET_CS_PIN, OUTPUT);
SD.begin(SD_CS_PIN);
Ethernet.begin(arduino_mac, arduino_ip, arduino_dns, arduino_gateway, arduino_subnet);
disableSDCardReader();
listen_udp.begin(listen_port);
#if ENABLE_ABSOLUTE_ZOOM
Serial.println("Enabling Panasonic Networking.");
panasonic_udp.begin(panasonic_p2_port);
Serial.println("Done.");
#endif // ENABLE_ABSOLUTE_ZOOM
#endif // ENABLE_VISCA
}
void stopIfFault()
{
#if !USE_MP_101_MODE
if (md.getFault()) {
md.setM1Speed(0);
md.setM2Speed(0);
Serial.println(F("fault"));
while(1);
}
#endif
}
void loop() {
#if LANC_ENABLED
#if defined(TEMPORARY_NO_LANC) || !ENABLE_VISCA
useNetwork = true;
#else // !TEMPORARY_NO_LANC
useNetwork = digitalRead(NETWORK_MODE_SWITCH_PIN);
#endif // TEMPORARY_NO_LANC
if (!useNetwork) {
handleZoom();
}
#endif
handleNonLANCOperations();
}
void handleNonLANCOperations() {
#if ENABLE_VISCA
#if ENABLE_ABSOLUTE_POSITIONING
updatePanAndTiltPosition();
#if ENABLE_ABSOLUTE_ZOOM
#if ACTIVE_PTZ_MODE == PTZ_MODE_P2
updateZoomPositionFromP2Data();
#elif ACTIVE_PTZ_MODE == PTZ_MODE_PANASONIC_PTZ
updateZoomPositionByHTTP();
#else
#error ENABLE_ABSOLUTE_ZOOM requires ACTIVE_PTZ_MODE == (PTZ_MODE_P2 | PTZ_MODE_PANASONIC_PTZ)
#endif
#endif // updatePanAndTiltPosition
#endif // ENABLE_ABSOLUTE_POSITIONING
handleNetworkControlRequests();
#endif // ENABLE_VISCA
if (useNetwork) {
#if (ENABLE_VISCA && ENABLE_ABSOLUTE_POSITIONING)
handleRecallUpdates();
#endif
} else {
handleMotorControl();
}
}
#pragma mark - Motor control
void handleMotorControl() {
int rawHorizontalValue = analogRead(horizontalSensePin);
setHorizontalSpeedWithScaling(rawHorizontalValue);
int rawVerticalValue = analogRead(verticalSensePin);
setVerticalSpeedWithScaling(rawVerticalValue);
}
void setHorizontalSpeedWithScaling(int rawHorizontalValue) {
int scaledHorizontalSpeed = scaleHorizontalSpeed(rawHorizontalValue);
setHorizontalSpeed(scaledHorizontalSpeed);
}
int maxPanTiltValue(void) {
#if USE_MP_101_MODE
return 255
#else // !USE_MP_101_MODE
return kMotorMax;
#endif // USE_MP_101_MODE
}
int scaleHorizontalSpeed(int rawHorizontalValue) {
int horizontalValue = computeScaledSpeedValue(1023 - rawHorizontalValue, kMotorSpeedPower, kMinimumMotorThreshold,
maxPanTiltValue()); // Reversed.
logValues("horizontal: ", rawHorizontalValue, horizontalValue, kDebugModePan);
return horizontalValue;
}
void setHorizontalSpeed(int horizontalValue) {
#if USE_MP_101_MODE
setMP101Horizontal(horizontalValue);
#else
md.setM2Speed(horizontalValue);
#endif
}
void setVerticalSpeedWithScaling(int rawHorizontalValue) {
int scaledVerticalSpeed = scaleHorizontalSpeed(rawHorizontalValue);
setVerticalSpeed(scaledVerticalSpeed);
}
int scaleVerticalSpeed(int rawVerticalValue) {
int verticalValue = computeScaledSpeedValue(rawVerticalValue, kMotorSpeedPower, kMinimumMotorThreshold,
maxPanTiltValue());
logValues("vertical: ", rawVerticalValue, verticalValue, kDebugModeTilt);
return verticalValue;
}
void setVerticalSpeed(int verticalValue) {
#if 0
setMP101Vertical(verticalValue);
#else
md.setM1Speed(verticalValue);
#endif
}
// By stripping the sign and scaling the value to the range 0..1, we can raise the input value to
// an arbitrary power to change the curve. We then multiply that by maxScale and provide the
// sign to get a value in the range [-maxScale .. maxScale]. (Positive and negative input values
// are not exactly balanced numerically, so we throw away the largest possible value on the positive
// side.)
int computeScaledSpeedValue(int bareValue, int power, int threshold, int maxScale) {
int rawSpeed = abs(bareValue - 512); // Range -512 .. 511
bool direction = (bareValue >= 512); // Equal number of positive and negative values.
if (debugPanAndTilt & kDebugScaling) {
Serial.print(F("bareValue: "));
Serial.print(rawSpeed);
Serial.print(F(" rawSpeed: "));
Serial.print(rawSpeed);
Serial.print(F(" direction: "));
Serial.println(direction ? F("true") : F("false"));
}
if (rawSpeed <= threshold) {
return 0;
}
int maxSpeed = 511 - threshold;
double speedPercentage = ((double)rawSpeed / (double)maxSpeed);
if (debugPanAndTilt & kDebugScaling) {
Serial.print(F("Percent: "));
Serial.println(speedPercentage);
}
speedPercentage = pow(speedPercentage, power);
float scaledSpeed = (speedPercentage * maxScale);
int scaledSpeedInt = (int)scaledSpeed;
if (scaledSpeed > maxScale) {
scaledSpeedInt = maxScale;
}
return direction ? scaledSpeedInt : (0 - scaledSpeedInt);
}
#pragma mark - MP101 motor control
#if USE_MP_101_MODE
void setMP101Horizontal(int horizontalValue) {
int leftPinValue = (horizontalValue < 0) ? -horizontalValue : 0;
int rightPinValue = (horizontalValue > 0) ? horizontalValue : 0;
analogWrite(MP101LeftPin, leftPinValue);
analogWrite(MP101RightPin, rightPinValue);
if (0) {
Serial.print(F("Left: "));
Serial.print(leftPinValue);
Serial.print(F(" Right: "));
Serial.println(rightPinValue);
}
}
void setMP101Vertical(int verticalValue) {
int upPinValue = (verticalValue > 0) ? verticalValue : 0;
int downPinValue = (verticalValue < 0) ? -verticalValue : 0;
analogWrite(MP101UpPin, upPinValue);
analogWrite(MP101DownPin, downPinValue);
if (0) {
Serial.print(F("Up: "));
Serial.print(upPinValue);
Serial.print(F(" Down: "));
Serial.println(downPinValue);
}
}
#endif
#pragma mark - Logging
void logValues(char *label, int rawValue, int scaledValue, debugMode mode) {
if (debugPanAndTilt & mode) {
Serial.write(label);
Serial.print(rawValue);
Serial.print(F(" -> "));
Serial.print(scaledValue);
Serial.println(F(""));
}
}
#pragma mark - Zoom control (generic)
int scaleZoomSpeed(int rawZoomValue) {
#if !USE_MP_101_MODE
rawZoomValue = 1023 - rawZoomValue;
#endif
int zoomSpeed = computeScaledSpeedValue(rawZoomValue, kZoomSpeedPower, kMinimumZoomThreshold, kZoomMax); // Reversed.
logValues("zoom: ", rawZoomValue, zoomSpeed, kDebugModeZoom);
return zoomSpeed;
}
#pragma mark - LANC
#if LANC_ENABLED
extern boolean ZOOM_IN_0[];
extern boolean ZOOM_IN_1[];
extern boolean ZOOM_IN_2[];
extern boolean ZOOM_IN_3[];
extern boolean ZOOM_IN_4[];
extern boolean ZOOM_IN_5[];
extern boolean ZOOM_IN_6[];
extern boolean ZOOM_IN_7[];
extern boolean ZOOM_OUT_0[];
extern boolean ZOOM_OUT_1[];
extern boolean ZOOM_OUT_2[];
extern boolean ZOOM_OUT_3[];
extern boolean ZOOM_OUT_4[];
extern boolean ZOOM_OUT_5[];
extern boolean ZOOM_OUT_6[];
extern boolean ZOOM_OUT_7[];
extern boolean IDLE_COMMAND[];
void handleZoom() {
int rawZoomValue = analogRead(zoomSensePin);
int scaledZoomSpeed = scaleZoomSpeed(rawZoomValue);
sendZoomSpeedViaLANC(scaledZoomSpeed);
}
void sendZoomSpeedViaLANC(int zoomSpeed) {
switch (zoomSpeed) {
case -9: // Extremely unlikely
case -8:
lancCommand(ZOOM_OUT_7);
break;
case -7:
lancCommand(ZOOM_OUT_6);
break;
case -6:
lancCommand(ZOOM_OUT_5);
break;
case -5:
lancCommand(ZOOM_OUT_4);
break;
case -4:
lancCommand(ZOOM_OUT_3);
break;
case -3:
lancCommand(ZOOM_OUT_2);
break;
case -2:
lancCommand(ZOOM_OUT_1);
break;
case -1:
lancCommand(ZOOM_OUT_0);
break;
case 0:
lancCommand(IDLE_COMMAND);
break;
case 1:
lancCommand(ZOOM_IN_0);
break;
case 2:
lancCommand(ZOOM_IN_1);
break;
case 3:
lancCommand(ZOOM_IN_2);
break;
case 4:
lancCommand(ZOOM_IN_3);
break;
case 5:
lancCommand(ZOOM_IN_4);
break;
case 6:
lancCommand(ZOOM_IN_5);
break;
case 7:
lancCommand(ZOOM_IN_6);
break;
case 8:
case 9: // Extremely unlikely
lancCommand(ZOOM_IN_7);
break;
default:
break;
}
}
#pragma mark - LANC Library
/*******************************************************************************************
* All code below this point is derived from an existing LANC example, with the loop() *
* method stripped out, the setup() method renamed to lancSetup(), and shorter timeouts *
* added so that a failed LANC connection won't prevent pan and tilt control from working. *
* The copyright notice and licensing terms are included below. *
*******************************************************************************************/
/*
SIMPLE LANC REMOTE
Version 1.0
Sends LANC commands to the LANC port of a video camera.
Tested with a Canon XF300 camcorder
For the interface circuit interface see
http://controlyourcamera.blogspot.com/2011/02/arduino-controlled-video-recording-over.html
Feel free to use this code in any way you want.
2011, Martin Koch
"LANC" is a registered trademark of SONY.
CANON calls their LANC compatible port "REMOTE".
*/
int cmdRepeatCount;
int bitDuration = 104; //Duration of one LANC bit in microseconds.
//LANC commands byte 0 + byte 1
//Tested with Canon XF300
//Start-stop video recording
boolean REC[] = {LOW,LOW,LOW,HIGH,HIGH,LOW,LOW,LOW, LOW,LOW,HIGH,HIGH,LOW,LOW,HIGH,HIGH}; // 18 33
boolean IDLE_COMMAND[] = {LOW,LOW,LOW,LOW,LOW,LOW,LOW,LOW, LOW,LOW,LOW,LOW,LOW,LOW,LOW,LOW}; // 00 00
//Zoom in from slowest to fastest speed
boolean ZOOM_IN_0[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,LOW,LOW,LOW,LOW,LOW,LOW,LOW}; // 28 00
boolean ZOOM_IN_1[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,LOW,LOW,LOW,LOW,LOW,HIGH,LOW}; // 28 02
boolean ZOOM_IN_2[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,LOW,LOW,LOW,LOW,HIGH,LOW,LOW}; // 28 04
boolean ZOOM_IN_3[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,LOW,LOW,LOW,LOW,HIGH,HIGH,LOW}; // 28 06
boolean ZOOM_IN_4[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,LOW,LOW,LOW,HIGH,LOW,LOW,LOW}; // 28 08
boolean ZOOM_IN_5[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,LOW,LOW,LOW,HIGH,LOW,HIGH,LOW}; // 28 0A
boolean ZOOM_IN_6[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,LOW,LOW,LOW,HIGH,HIGH,LOW,LOW}; // 28 0C
boolean ZOOM_IN_7[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,LOW,LOW,LOW,HIGH,HIGH,HIGH,LOW}; // 28 0E
//Zoom out from slowest to fastest speed
boolean ZOOM_OUT_0[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,LOW,LOW,HIGH,LOW,LOW,LOW,LOW}; // 28 10
boolean ZOOM_OUT_1[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,LOW,LOW,HIGH,LOW,LOW,HIGH,LOW}; // 28 12
boolean ZOOM_OUT_2[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,LOW,LOW,HIGH,LOW,HIGH,LOW,LOW}; // 28 14
boolean ZOOM_OUT_3[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,LOW,LOW,HIGH,LOW,HIGH,HIGH,LOW}; // 28 16
boolean ZOOM_OUT_4[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,LOW,LOW,HIGH,HIGH,LOW,LOW,LOW}; // 28 18
boolean ZOOM_OUT_5[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,LOW,LOW,HIGH,HIGH,LOW,HIGH,LOW}; // 28 1A
boolean ZOOM_OUT_6[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,LOW,LOW,HIGH,HIGH,HIGH,LOW,LOW}; // 28 1C
boolean ZOOM_OUT_7[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,LOW,LOW,HIGH,HIGH,HIGH,HIGH,LOW}; // 28 1E
//Focus control. Camera must be switched to manual focus
boolean FOCUS_NEAR[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,HIGH,LOW,LOW,LOW,HIGH,HIGH,HIGH}; // 28 47
boolean FOCUS_FAR[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,HIGH,LOW,LOW,LOW,HIGH,LOW,HIGH}; // 28 45
boolean FOCUS_AUTO[] = {LOW,LOW,HIGH,LOW,HIGH,LOW,LOW,LOW, LOW,HIGH,LOW,LOW,LOW,LOW,LOW,HIGH}; // 28 41
//boolean POWER_OFF[] = {LOW,LOW,LOW,HIGH,HIGH,LOW,LOW,LOW, LOW,HIGH,LOW,HIGH,HIGH,HIGH,HIGH,LOW}; // 18 5E
//boolean POWER_ON[] = {LOW,LOW,LOW,HIGH,HIGH,LOW,LOW,LOW, LOW,HIGH,LOW,HIGH,HIGH,HIGH,LOW,LOW}; // 18 5C
// Doesn't work because there's no power supply from the LANC port when the camera is off
//boolean POWER_OFF2[] = {LOW,LOW,LOW,HIGH,HIGH,LOW,LOW,LOW, LOW,LOW,HIGH,LOW,HIGH,LOW,HIGH,LOW}; // 18 2A
// Turns the XF300 off and then on again
//boolean POWER_SAVE[] = {LOW,LOW,LOW,HIGH,HIGH,LOW,LOW,LOW, LOW,HIGH,HIGH,LOW,HIGH,HIGH,LOW,LOW}; // 18 6C
// Didn't work
void lancSetup() {
pinMode(lancInputPin, INPUT); // listens to the LANC line
pinMode(lancOutputPin, OUTPUT); // writes to the LANC line
digitalWrite(lancOutputPin, LOW); // set LANC line to +5V
delay(5000); // Wait for camera to power up completly
bitDuration = bitDuration - 8; // Writing to the digital port takes about 8 microseconds,
// so only 96 microseconds are left for each bit
pinMode(zoomSensePin, INPUT); // listens to the LANC line
}
void lancCommand(boolean lancBit[]) {
#ifndef TEMPORARY_NO_LANC
cmdRepeatCount = 0;
while (cmdRepeatCount < 5) { // repeat 5 times to make sure the camera accepts the command
// If this breaks, change the timeout (which didn't exist before, and thus defaulted to one second).
// This gives us 40 adjustments per second, and is 5000 msec longer than a full LANC cycle, which
// means this should kick in only if the LANC hardware is not attached.
int missed = 0;
unsigned long duration = 0;
while (((duration = pulseIn(lancInputPin, HIGH, 25000))) < 5000) {
// "pulseIn, HIGH" catches any 0V TO +5V TRANSITION and waits until the LANC line goes back to 0V
// "pulseIn" also returns the pulse duration so we can check if the previous +5V duration was long enough (>5ms)
// to be the pause before a new 8 byte data packet. Loop till pulse duration is >5ms
// Run the motor at least 100 times per second anyway while we're waiting.
if (duration == 0) {
if (debugPanAndTilt & kDebugLANC) {
Serial.println(F("No pulse"));
}
handleNonLANCOperations();
}
}
// LOW after long pause means the START bit of Byte 0 is here
delayMicroseconds(bitDuration); // wait START bit duration
// Write the 8 bits of byte 0
// Note that the command bits have to be put out in reverse order with the least significant, right-most bit (bit 0) first
for (int i=7; i>-1; i--) {
digitalWrite(lancOutputPin, lancBit[i]); //Write bits.
delayMicroseconds(bitDuration);
}
// Byte 0 is written now put LANC line back to +5V
digitalWrite(lancOutputPin, LOW);
delayMicroseconds(10); //make sure to be in the stop bit before byte 1
while (digitalRead(lancInputPin)) {
// Loop as long as the LANC line is +5V during the stop bit
}
// 0V after the previous stop bit means the START bit of Byte 1 is here
delayMicroseconds(bitDuration); // wait START bit duration
// Write the 8 bits of Byte 1
// Note that the command bits have to be put out in reverse order with the least significant, right-most bit (bit 0) first
for (int i=15; i>7; i--) {
digitalWrite(lancOutputPin,lancBit[i]); // Write bits
delayMicroseconds(bitDuration);
}
// Byte 1 is written now put LANC line back to +5V
digitalWrite(lancOutputPin, LOW);
cmdRepeatCount++; // increase repeat count by 1
/* Control bytes 0 and 1 are written, now don’t care what happens in Bytes 2 to 7
and just wait for the next start bit after a long pause to send the first two command bytes again. */
} // While cmdRepeatCount < 5
#endif
}
#endif // LANC_ENABLED
#if ENABLE_VISCA
#if ENABLE_ABSOLUTE_POSITIONING
struct can_frame canBusFrameMake(uint32_t can_id, uint8_t can_dlc, uint8_t *data) {
struct can_frame message;
message.can_id = can_id;
message.can_dlc = can_dlc;
memcpy(message.data, data, sizeof(message.data));
return message;
}
void configureCANBus(void) {
// Reset the CAN bus bridge and configure it for 500 kbps operation.
mcp2515.reset();
mcp2515.setBitrate(CAN_500KBPS);
mcp2515.setNormalMode();
#ifdef reassignCANBusID
// When programming them:
//
// 0. Configure for 500 kbps.
// 1. To reassign device XX to be device YY
// Sent: 0x04 0xXX 0x02 0xYY
// Response: 0x04 0xYY 0x02 0x00
// Last byte is an error code. If you get back this:
// Response: 0x04 0xXX 0x02 0xZZ
// with some error code ZZ from the original device id (XX),
// report the error.
uint8_t data[8] = { 0x04, oldCANBusID, 0x02, newCANBusID, 0, 0, 0, 0 };
struct can_frame message = canBusFrameMake(oldCANBusID, 4, data);
if (mcp2515.sendMessage(&message) == MCP2515::ERROR_OK) {
struct can_frame response;
if (mcp2515.readMessage(&response) == MCP2515::ERROR_OK) {
if (response.data[0] == 0x4 && response.data[1] == oldCANBusID &&
response.data[2] == 0x2 && response.data[3] == 0 &&
response.can_id == newCANBusID) {
Serial.println("Reassignment successful.");
} else {
Serial.print("Reassignment failed with error ");
Serial.println(response.data[3]);
}
}
}
#endif // reassignCANBusID
}
// Stores data into current_pan_position and current_tilt_position.
void updatePanAndTiltPosition(void) {
// Information about the BR38-COM series of multi-turn CAN-bus encoders:
//
// 1. Send broadcast (destination ID 0).
// Command: 0x1
// For device XX:
// Sent: 0x04 0xXX 0x01 0x00
// For value 0xAABBCCDD from device XX:
// Response: 0x07 0xXX 0x01 0xDD 0xCC 0xBB 0xAA
uint8_t data[8] = { 0x04, 0x00, 0x01, 0, 0, 0, 0, 0 };
struct can_frame message = canBusFrameMake(0x00, 4, data);
if (mcp2515.sendMessage(&message) == MCP2515::ERROR_OK) {
struct can_frame response;
for (int i = 0; i < 2; i++) {
if (mcp2515.readMessage(&response) == MCP2515::ERROR_OK) {
if (response.data[0] == 0x7 && response.data[2] == 0x1) {
long value = response.data[3] | (response.data[4] << 8) |
(response.data[5] << 16) | (response.data[6] << 24);
if (response.data[1] == panCANBusID) {
current_pan_position = value;
} else if (response.data[1] == tiltCANBusID) {
current_tilt_position = value;
} else {
Serial.print("Received message from unknown CAN bus ID ");
Serial.println(response.data[1]);
}
} else {
char buf[120];
sprintf(buf, "Unknown response: %02x %02x %02x %02x %02x %02x %02x %02x from device %ld with length code %d",
response.data[0], response.data[1], response.data[2], response.data[3],
response.data[4], response.data[5], response.data[6], response.data[7],
response.can_id, response.can_dlc);
Serial.println(buf);
}
}
}
}
}
#if ENABLE_ABSOLUTE_ZOOM
#if ACTIVE_PTZ_MODE == PTZ_MODE_P2
// Helper function that computes the zoom position from a P2 data packet.
int zoomPositionFromData(p2_optical_data_t *optical_data) {
int bits = optical_data->zoom_sig_high << 8 | optical_data->zoom_sig_low;
int exponent = optical_data->zoom_exp;
int exp = optical_data->zoom_exp; // 1..15 repeating, but starts at 3.
int high = optical_data->zoom_sig_high - 11; // 0 or 1.
int rough_value = ((high * 15) + exp) - 3;
int low = optical_data->zoom_sig_low; // 0..255. Starts at 112.
return ((rough_value << 8) + low) - 112;
}
// Helper function that tells the Panasonic camera to start providing its zoom position.
// This should be called about once every 5 seconds. If you do not call it for 15
// seconds, the camera stops providing zoom position data.
bool enableZoomPositionupdates(void) {
char requestBuf[3] = { 0xff, 0x01, 0xff };
if (!panasonic_udp.beginPacket(panasonic_address, panasonic_p2_port)) {
return false;
}
panasonic_udp.write(requestBuf, 3);
return (panasonic_udp.endPacket() == 1);
}
bool timeToRequestZoomPosition(void) {
static long lastChecked = 0;
static bool hasChecked = false;
// Check once per 5 seconds.
if (!hasChecked || (millis() > lastChecked + 5000)) {
hasChecked = true;
return true;
}
return false;
}
void updateZoomPositionFromP2Data(void) {
uint8_t packetBuffer[UDP_TX_PACKET_MAX_SIZE]; // buffer to hold incoming packet,
int packetSize;
if (timeToRequestZoomPosition()) {
enableZoomPositionupdates();
}
while ((packetSize = panasonic_udp.parsePacket()) > 0) {
panasonic_udp.read((unsigned char *)packetBuffer, UDP_TX_PACKET_MAX_SIZE);
uint8_t message_type = packetBuffer[0];
if (message_type == 6) {
p2_optical_data_t *optical_data = (p2_optical_data_t *)packetBuffer;
current_zoom_position = zoomPositionFromData(optical_data);