/
rio.c
1234 lines (1030 loc) · 41.3 KB
/
rio.c
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
/********************************************************************
* Description: rio.c
* This file, 'rio.c', is a HAL component that
* provides an SPI connection to a external FPGA-Board running RIO gateware.
*
* Initially developed for RaspberryPi -> Arduino Due.
* Further developed for RaspberryPi -> Smoothieboard and clones (LPC1768).
*
* Author: Scott Alford
* Modified by: Oliver Dippel and Jesse Schoch
* License: GPL Version 2
*
* Credit to GP Orcullo and PICnc V2 which originally inspired this
* and portions of this code is based on stepgen.c by John Kasunich
* and hm2_rpspi.c by Matsche
*
* Copyright (c) 2021 All rights reserved.
*
* Last change:
********************************************************************/
#include "rtapi.h" /* RTAPI realtime OS API */
#include "rtapi_app.h" /* RTAPI realtime module decls */
#include "hal.h" /* HAL public API decls */
#include <math.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "rio.h"
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#ifdef TRANSPORT_UDP
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#endif
#ifdef TRANSPORT_SERIAL
#include <fcntl.h>
#include <termios.h>
#endif
#ifdef TRANSPORT_SPI
#include "bcm2835.h"
#include "bcm2835.c"
#endif
#ifdef TRANSPORT_FTDI
#include <ftdi.h>
#include <usb.h>
#include <stdio.h>
#include <string.h>
#define VENDOR 0x0403
#define PRODUCT 0x6010
#define CK 0x01 // AD0 SPI clock
#define DO 0x02 // AD1 SPI data out
#define DI 0x04 // AD2 SPI data in
#define CS 0x08 // AD3 SPI chip select
#define L0 0x10 // AD4 GPIOL0
#define L1 0x20 // AD5 GPIOL1
#define L2 0x40 // AD6 GPIOL2
#define L3 0x80 // AD7 GPIOL3
static uint8_t outpins = CS | DO | CK;
struct ftdi_context* ftdi;
int spi_init(void);
int spi_exit(void);
int spi_rw_buffer(uint8_t* pBuffer, uint8_t* rxBuffer, int numBytes);
#endif
#define MODNAME "rio"
#define PREFIX "rio"
MODULE_AUTHOR("Oliver Dippel (based on code from Scott Alford AKA scotta)");
MODULE_DESCRIPTION("Driver for RIO FPGA boards");
MODULE_LICENSE("GPL v2");
char *ctrl_type[JOINTS] = { "p" };
RTAPI_MP_ARRAY_STRING(ctrl_type, JOINTS, "control type (pos or vel)");
/***********************************************************************
* STRUCTURES AND GLOBAL VARIABLES *
************************************************************************/
typedef struct {
hal_bit_t *SPIenable;
hal_bit_t *SPIreset;
hal_bit_t *PRUreset;
bool SPIresetOld;
hal_bit_t *SPIstatus;
hal_bit_t *stepperEnable[JOINTS];
int pos_mode[JOINTS];
hal_float_t *pos_cmd[JOINTS]; // pin: position command (position units)
hal_float_t *vel_cmd[JOINTS]; // pin: velocity command (position units/sec)
hal_float_t *pos_fb[JOINTS]; // pin: position feedback (position units)
hal_s32_t *count[JOINTS]; // pin: psition feedback (raw counts)
hal_float_t pos_scale[JOINTS]; // param: steps per position unit
hal_float_t fb_scale[JOINTS]; // param: steps per position unit
float freq[JOINTS]; // param: frequency command sent to PRU
hal_float_t *freq_cmd[JOINTS]; // pin: frequency command monitoring, available in LinuxCNC
hal_float_t maxvel[JOINTS]; // param: max velocity, (pos units/sec)
hal_float_t maxaccel[JOINTS]; // param: max accel (pos units/sec^2)
hal_float_t *pgain[JOINTS];
hal_float_t *ff1gain[JOINTS];
hal_float_t *deadband[JOINTS];
float old_pos_cmd[JOINTS]; // previous position command (counts)
float old_pos_cmd_raw[JOINTS]; // previous position command (counts)
float old_scale[JOINTS]; // stored scale value
float scale_recip[JOINTS]; // reciprocal value used for scaling
float prev_cmd[JOINTS];
float cmd_d[JOINTS]; // command derivative
hal_float_t *setPoint[VARIABLE_OUTPUTS];
hal_float_t *setPointOffset[VARIABLE_OUTPUTS];
hal_float_t *setPointScale[VARIABLE_OUTPUTS];
hal_float_t *processVariable[VARIABLE_INPUTS];
hal_s32_t *processVariableS32[VARIABLE_INPUTS];
hal_bit_t *outputs[DIGITAL_OUTPUT_BYTES * 8];
hal_bit_t *inputs[DIGITAL_INPUT_BYTES * 8 * 2]; // for not pins * 2
hal_float_t *processVariableScale[VARIABLE_INPUTS];
hal_float_t *processVariableOffset[VARIABLE_INPUTS];
hal_float_t *processVariableExtra[VARIABLE_INPUTS][2];
#ifdef INDEX_MAX
hal_bit_t *index_enable[INDEX_MAX];
#endif
} data_t;
static data_t *data;
static txData_t txData;
static rxData_t rxData;
long stamp = 0;
/* other globals */
#ifdef INDEX_MAX
float index_enable_in[INDEX_MAX] = {0.0};
#endif
static int comp_id; // component ID
static const char *modname = MODNAME;
static const char *prefix = PREFIX;
static int num_chan = 0; // number of step generators configured
static long old_dtns; // update_freq function period in nsec - (THIS IS RUNNING IN THE PI)
static double dt; // update_freq period in seconds - (THIS IS RUNNING IN THE PI)
static double recip_dt; // recprocal of period, avoids divides
static int64_t accum[JOINTS] = { 0 };
static int32_t old_count[JOINTS] = { 0 };
static int32_t accum_diff = 0;
typedef enum CONTROL { POSITION, VELOCITY, INVALID } CONTROL;
static int reset_gpio_pin = 25; // RPI GPIO pin number used to force watchdog reset of the PRU
#ifdef TRANSPORT_UDP
#define DST_PORT 2390
#define SRC_PORT 2390
#define SEND_TIMEOUT_US 10
#define RECV_TIMEOUT_US 10
#define READ_PCK_DELAY_NS 10000
static int udpSocket;
static int errCount;
struct sockaddr_in dstAddr, srcAddr;
struct hostent *server;
static const char *dstAddress = UDP_IP;
static int UDP_init(void);
#endif
#ifdef TRANSPORT_SERIAL
int serial_fd = -1;
#endif
/***********************************************************************
* LOCAL FUNCTION DECLARATIONS *
************************************************************************/
static int rt_bcm2835_init(void);
static void update_freq(void *arg, long period);
static void rio_readwrite();
static void rio_transfer();
static CONTROL parse_ctrl_type(const char *ctrl);
/***********************************************************************
* INIT AND EXIT CODE *
************************************************************************/
#ifdef TRANSPORT_SERIAL
int set_interface_attribs (int fd, int speed, int parity) {
struct termios tty;
if (tcgetattr (fd, &tty) != 0) {
rtapi_print("ERROR: can't setup usb: %s\n", strerror(errno));
return errno;
}
cfsetospeed (&tty, speed);
cfsetispeed (&tty, speed);
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars
tty.c_iflag &= ~IGNBRK; // disable break processing
tty.c_lflag = 0; // no signaling chars, no echo,
tty.c_oflag = 0; // no remapping, no delays
tty.c_cc[VMIN] = 0; // read doesn't block
tty.c_cc[VTIME] = 0; // 0.5 seconds read timeout
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl
tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls, enable reading
tty.c_cflag &= ~(PARENB | PARODD); // shut off parity
tty.c_cflag |= parity;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CRTSCTS;
if (tcsetattr (fd, TCSANOW, &tty) != 0) {
rtapi_print("ERROR: can't setup usb: %s\n", strerror(errno));
return errno;
}
return 0;
}
#endif
int rtapi_app_main(void)
{
char name[HAL_NAME_LEN + 1];
int n = 0;
int bn = 0;
int retval = 0;
for (n = 0; n < JOINTS; n++) {
if(parse_ctrl_type(ctrl_type[n]) == INVALID) {
rtapi_print_msg(RTAPI_MSG_ERR,
"STEPGEN: ERROR: bad control type '%s' for axis %i (must be 'p' or 'v')\n",
ctrl_type[n], n);
return -1;
}
}
// connect to the HAL, initialise the driver
comp_id = hal_init(modname);
if (comp_id < 0) {
rtapi_print_msg(RTAPI_MSG_ERR, "%s ERROR: hal_init() failed \n", modname);
return -1;
}
// allocate shared memory
data = hal_malloc(sizeof(data_t));
if (data == 0) {
rtapi_print_msg(RTAPI_MSG_ERR,
"%s: ERROR: hal_malloc() failed\n", modname);
hal_exit(comp_id);
return -1;
}
#ifdef TRANSPORT_UDP
// Initialize the UDP socket
rtapi_print("Info: Initialize the UDP socket: %s\n", UDP_IP);
if (UDP_init() < 0) {
rtapi_print_msg(RTAPI_MSG_ERR, "Error: The board is unreachable\n");
return -1;
}
#endif
#ifdef TRANSPORT_SERIAL
rtapi_print("Info: Initialize serial connection: %s\n", SERIAL_PORT);
serial_fd = open (SERIAL_PORT, O_RDWR | O_NOCTTY | O_SYNC);
if (serial_fd < 0) {
rtapi_print_msg(RTAPI_MSG_ERR,"usb setup error\n");
return errno;
}
set_interface_attribs (serial_fd, SERIAL_SPEED, 0);
uint8_t rxBufferTmp[SPIBUFSIZE];
int cnt = 0;
int rec = 0;
while((rec = read(serial_fd, rxBufferTmp, SPIBUFSIZE)) <= SPIBUFSIZE && cnt++ < 190) {
usleep(100);
}
#endif
#ifdef TRANSPORT_SPI
rtapi_print("Info: Initialize SPI connection\n");
// Map the RPi BCM2835 peripherals - uses "rtapi_open_as_root" in place of "open"
if (!rt_bcm2835_init()) {
rtapi_print_msg(RTAPI_MSG_ERR,"rt_bcm2835_init failed. Are you running with root privlages??\n");
return -1;
}
// Set the SPI0 pins to the Alt 0 function to enable SPI0 access, setup CS register
// and clear TX and RX fifos
if (!bcm2835_spi_begin()) {
rtapi_print_msg(RTAPI_MSG_ERR,"bcm2835_spi_begin failed. Are you running with root privlages??\n");
return -1;
}
// Configure SPI0
// The defines are set in rio.h
bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST);
bcm2835_spi_setDataMode(BCM2835_SPI_MODE0);
bcm2835_spi_setClockDivider(SPI_SPEED);
bcm2835_spi_chipSelect(BCM2835_SPI_CS_NONE);
#endif
#ifdef TRANSPORT_FTDI
rtapi_print("Info: Initialize FTDI-SPI connection\n");
spi_init();
#endif
retval = hal_pin_bit_newf(HAL_IN, &(data->SPIenable),
comp_id, "%s.SPI-enable", prefix);
if (retval != 0) goto error;
retval = hal_pin_bit_newf(HAL_IN, &(data->SPIreset),
comp_id, "%s.SPI-reset", prefix);
if (retval != 0) goto error;
retval = hal_pin_bit_newf(HAL_OUT, &(data->SPIstatus),
comp_id, "%s.SPI-status", prefix);
if (retval != 0) goto error;
//bcm2835_gpio_fsel(reset_gpio_pin, BCM2835_GPIO_FSEL_OUTP);
retval = hal_pin_bit_newf(HAL_IN, &(data->PRUreset),
comp_id, "%s.PRU-reset", prefix);
if (retval != 0) goto error;
// export all the variables for each joint
for (n = 0; n < JOINTS; n++) {
// export pins
data->pos_mode[n] = (parse_ctrl_type(ctrl_type[n]) == POSITION);
retval = hal_pin_bit_newf(HAL_IN, &(data->stepperEnable[n]),
comp_id, "%s.joint.%01d.enable", prefix, n);
if (retval != 0) goto error;
retval = hal_pin_float_newf(HAL_IN, &(data->pos_cmd[n]),
comp_id, "%s.joint.%01d.pos-cmd", prefix, n);
if (retval < 0) goto error;
*(data->pos_cmd[n]) = 0.0;
if (data->pos_mode[n] == 0) {
retval = hal_pin_float_newf(HAL_IN, &(data->vel_cmd[n]),
comp_id, "%s.joint.%01d.vel-cmd", prefix, n);
if (retval < 0) goto error;
*(data->vel_cmd[n]) = 0.0;
}
retval = hal_pin_float_newf(HAL_OUT, &(data->freq_cmd[n]),
comp_id, "%s.joint.%01d.freq-cmd", prefix, n);
if (retval < 0) goto error;
*(data->freq_cmd[n]) = 0.0;
retval = hal_pin_float_newf(HAL_OUT, &(data->pos_fb[n]),
comp_id, "%s.joint.%01d.pos-fb", prefix, n);
if (retval < 0) goto error;
*(data->pos_fb[n]) = 0.0;
retval = hal_param_float_newf(HAL_RW, &(data->pos_scale[n]),
comp_id, "%s.joint.%01d.scale", prefix, n);
if (retval < 0) goto error;
data->pos_scale[n] = 1.0;
retval = hal_param_float_newf(HAL_RW, &(data->fb_scale[n]),
comp_id, "%s.joint.%01d.fb-scale", prefix, n);
if (retval < 0) goto error;
data->fb_scale[n] = 0.0;
retval = hal_pin_s32_newf(HAL_OUT, &(data->count[n]),
comp_id, "%s.joint.%01d.counts", prefix, n);
if (retval < 0) goto error;
*(data->count[n]) = 0;
retval = hal_pin_float_newf(HAL_IN, &(data->pgain[n]),
comp_id, "%s.joint.%01d.pgain", prefix, n);
if (retval < 0) goto error;
*(data->pgain[n]) = 0.0;
retval = hal_pin_float_newf(HAL_IN, &(data->ff1gain[n]),
comp_id, "%s.joint.%01d.ff1gain", prefix, n);
if (retval < 0) goto error;
*(data->ff1gain[n]) = 0.0;
retval = hal_pin_float_newf(HAL_IN, &(data->deadband[n]),
comp_id, "%s.joint.%01d.deadband", prefix, n);
if (retval < 0) goto error;
*(data->deadband[n]) = 0.0;
retval = hal_param_float_newf(HAL_RW, &(data->maxaccel[n]),
comp_id, "%s.joint.%01d.maxaccel", prefix, n);
if (retval < 0) goto error;
data->maxaccel[n] = 1.0;
}
for (n = 0; n < VARIABLE_OUTPUTS; n++) {
retval = hal_pin_float_newf(HAL_IN, &(data->setPoint[n]),
comp_id, "%s.%s", prefix, vout_names[n]);
if (retval < 0) goto error;
*(data->setPoint[n]) = 0.0;
retval = hal_pin_float_newf(HAL_IN, &(data->setPointScale[n]),
comp_id, "%s.%s-scale", prefix, vout_names[n]);
if (retval < 0) goto error;
*(data->setPointScale[n]) = 1.0;
retval = hal_pin_float_newf(HAL_IN, &(data->setPointOffset[n]),
comp_id, "%s.%s-offset", prefix, vout_names[n]);
if (retval < 0) goto error;
*(data->setPointOffset[n]) = 0.0;
}
for (n = 0; n < VARIABLE_INPUTS; n++) {
retval = hal_pin_float_newf(HAL_OUT, &(data->processVariable[n]), comp_id, "%s.%s", prefix, vin_names[n]);
if (retval < 0) goto error;
*(data->processVariable[n]) = 0.0;
retval = hal_pin_s32_newf(HAL_OUT, &(data->processVariableS32[n]), comp_id, "%s.%s-s32", prefix, vin_names[n]);
if (retval < 0) goto error;
*(data->processVariableS32[n]) = 0;
retval = hal_pin_float_newf(HAL_IN, &(data->processVariableScale[n]), comp_id, "%s.%s-scale", prefix, vin_names[n]);
if (retval < 0) goto error;
*(data->processVariableScale[n]) = 1.0;
retval = hal_pin_float_newf(HAL_IN, &(data->processVariableOffset[n]), comp_id, "%s.%s-offset", prefix, vin_names[n]);
if (retval < 0) goto error;
*(data->processVariableOffset[n]) = 0.0;
}
int index_num = 0;
for (bn = 0; bn < DIGITAL_OUTPUT_BYTES; bn++) {
for (n = 0; n < 8; n++) {
if (bn * 8 + n < DIGITAL_OUTPUTS) {
if (dout_types[bn * 8 + n] != DTYPE_INDEX) {
retval = hal_pin_bit_newf(HAL_IN, &(data->outputs[bn * 8 + n]), comp_id, "%s.%s", prefix, dout_names[bn * 8 + n]);
if (retval != 0) goto error;
*(data->outputs[bn * 8 + n]) = 0;
} else {
#ifdef INDEX_MAX
retval = hal_pin_bit_newf(HAL_IO, &(data->index_enable[index_num]), comp_id, "%s.%s", prefix, dout_names[bn * 8 + n]);
if (retval != 0) goto error;
index_num++;
#endif
}
}
}
}
for (bn = 0; bn < DIGITAL_INPUT_BYTES; bn++) {
for (n = 0; n < 8; n++) {
if (bn * 8 + n < DIGITAL_INPUTS) {
if (din_types[bn * 8 + n] != DTYPE_INDEX) {
retval = hal_pin_bit_newf(HAL_OUT, &(data->inputs[(bn * 8 + n) * 2]), comp_id, "%s.%s", prefix, din_names[bn * 8 + n]);
if (retval != 0) goto error;
*(data->inputs[(bn * 8 + n) * 2]) = 0;
retval = hal_pin_bit_newf(HAL_OUT, &(data->inputs[(bn * 8 + n) * 2 + 1]), comp_id, "%s.%s-not", prefix, din_names[bn * 8 + n]);
if (retval != 0) goto error;
*(data->inputs[(bn * 8 + n) * 2 + 1]) = 1;
}
}
}
}
error:
if (retval < 0) {
rtapi_print_msg(RTAPI_MSG_ERR,
"%s: ERROR: pin export failed with err=%i\n",
modname, retval);
hal_exit(comp_id);
return -1;
}
// Export functions
rtapi_snprintf(name, sizeof(name), "%s.update-freq", prefix);
retval = hal_export_funct(name, update_freq, data, 1, 0, comp_id);
if (retval < 0) {
rtapi_print_msg(RTAPI_MSG_ERR,
"%s: ERROR: update function export failed\n", modname);
hal_exit(comp_id);
return -1;
}
rtapi_snprintf(name, sizeof(name), "%s.readwrite", prefix);
retval = hal_export_funct(name, rio_readwrite, data, 1, 0, comp_id);
if (retval < 0) {
rtapi_print_msg(RTAPI_MSG_ERR,
"%s: ERROR: read function export failed\n", modname);
hal_exit(comp_id);
return -1;
}
rtapi_print_msg(RTAPI_MSG_INFO, "%s: installed driver\n", modname);
hal_ready(comp_id);
return 0;
}
void rtapi_app_exit(void)
{
hal_exit(comp_id);
}
/***********************************************************************
* LOCAL FUNCTION DEFINITIONS *
************************************************************************/
// This is the same as the standard bcm2835 library except for the use of
// "rtapi_open_as_root" in place of "open"
#ifdef TRANSPORT_UDP
int UDP_init(void)
{
int ret;
// Create a UDP socket
udpSocket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (udpSocket < 0) {
rtapi_print("ERROR: can't open socket: %s\n", strerror(errno));
return -errno;
}
bzero((char*) &dstAddr, sizeof(dstAddr));
dstAddr.sin_family = AF_INET;
dstAddr.sin_addr.s_addr = inet_addr(dstAddress);
dstAddr.sin_port = htons(DST_PORT);
bzero((char*) &srcAddr, sizeof(srcAddr));
srcAddr.sin_family = AF_INET;
srcAddr.sin_addr.s_addr = htonl(INADDR_ANY);
srcAddr.sin_port = htons(SRC_PORT);
// bind the local socket to SCR_PORT
ret = bind(udpSocket, (struct sockaddr *) &srcAddr, sizeof(srcAddr));
if (ret < 0) {
rtapi_print("ERROR: can't bind: %s\n", strerror(errno));
return -errno;
}
// Connect to send and receive only to the server_addr
ret = connect(udpSocket, (struct sockaddr*) &dstAddr, sizeof(struct sockaddr_in));
if (ret < 0) {
rtapi_print("ERROR: can't connect: %s\n", strerror(errno));
return -errno;
}
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = RECV_TIMEOUT_US;
ret = setsockopt(udpSocket, SOL_SOCKET, SO_RCVTIMEO, (char*) &timeout, sizeof(timeout));
if (ret < 0) {
rtapi_print("ERROR: can't set receive timeout socket option: %s\n", strerror(errno));
return -errno;
}
timeout.tv_usec = SEND_TIMEOUT_US;
ret = setsockopt(udpSocket, SOL_SOCKET, SO_SNDTIMEO, (char*) &timeout,
sizeof(timeout));
if (ret < 0) {
rtapi_print("ERROR: can't set send timeout socket option: %s\n", strerror(errno));
return -errno;
}
return 0;
}
#endif
#ifdef TRANSPORT_SPI
int rt_bcm2835_init(void)
{
int memfd;
int ok;
FILE *fp;
if (debug) {
bcm2835_peripherals = (uint32_t*)BCM2835_PERI_BASE;
bcm2835_pads = bcm2835_peripherals + BCM2835_GPIO_PADS/4;
bcm2835_clk = bcm2835_peripherals + BCM2835_CLOCK_BASE/4;
bcm2835_gpio = bcm2835_peripherals + BCM2835_GPIO_BASE/4;
bcm2835_pwm = bcm2835_peripherals + BCM2835_GPIO_PWM/4;
bcm2835_spi0 = bcm2835_peripherals + BCM2835_SPI0_BASE/4;
bcm2835_bsc0 = bcm2835_peripherals + BCM2835_BSC0_BASE/4;
bcm2835_bsc1 = bcm2835_peripherals + BCM2835_BSC1_BASE/4;
bcm2835_st = bcm2835_peripherals + BCM2835_ST_BASE/4;
bcm2835_aux = bcm2835_peripherals + BCM2835_AUX_BASE/4;
bcm2835_spi1 = bcm2835_peripherals + BCM2835_SPI1_BASE/4;
return 1; /* Success */
}
/* Figure out the base and size of the peripheral address block
// using the device-tree. Required for RPi2/3/4, optional for RPi 1
*/
if ((fp = fopen(BMC2835_RPI2_DT_FILENAME, "rb"))) {
unsigned char buf[16];
uint32_t base_address;
uint32_t peri_size;
if (fread(buf, 1, sizeof(buf), fp) >= 8) {
base_address = (buf[4] << 24) |
(buf[5] << 16) |
(buf[6] << 8) |
(buf[7] << 0);
peri_size = (buf[8] << 24) |
(buf[9] << 16) |
(buf[10] << 8) |
(buf[11] << 0);
if (!base_address) {
/* looks like RPI 4 */
base_address = (buf[8] << 24) |
(buf[9] << 16) |
(buf[10] << 8) |
(buf[11] << 0);
peri_size = (buf[12] << 24) |
(buf[13] << 16) |
(buf[14] << 8) |
(buf[15] << 0);
}
/* check for valid known range formats */
if ((buf[0] == 0x7e) &&
(buf[1] == 0x00) &&
(buf[2] == 0x00) &&
(buf[3] == 0x00) &&
((base_address == BCM2835_PERI_BASE) || (base_address == BCM2835_RPI2_PERI_BASE) || (base_address == BCM2835_RPI4_PERI_BASE))) {
bcm2835_peripherals_base = (off_t)base_address;
bcm2835_peripherals_size = (size_t)peri_size;
if( base_address == BCM2835_RPI4_PERI_BASE ) {
pud_type_rpi4 = 1;
}
}
}
fclose(fp);
}
/* else we are prob on RPi 1 with BCM2835, and use the hardwired defaults */
/* Now get ready to map the peripherals block
* If we are not root, try for the new /dev/gpiomem interface and accept
* the fact that we can only access GPIO
* else try for the /dev/mem interface and get access to everything
*/
memfd = -1;
ok = 0;
if (geteuid() == 0) {
/* Open the master /dev/mem device */
if ((memfd = rtapi_open_as_root("/dev/mem", O_RDWR | O_SYNC) ) < 0) {
fprintf(stderr, "bcm2835_init: Unable to open /dev/mem: %s\n",
strerror(errno)) ;
goto exit;
}
/* Base of the peripherals block is mapped to VM */
bcm2835_peripherals = mapmem("gpio", bcm2835_peripherals_size, memfd, bcm2835_peripherals_base);
if (bcm2835_peripherals == MAP_FAILED) goto exit;
/* Now compute the base addresses of various peripherals,
// which are at fixed offsets within the mapped peripherals block
// Caution: bcm2835_peripherals is uint32_t*, so divide offsets by 4
*/
bcm2835_gpio = bcm2835_peripherals + BCM2835_GPIO_BASE/4;
bcm2835_pwm = bcm2835_peripherals + BCM2835_GPIO_PWM/4;
bcm2835_clk = bcm2835_peripherals + BCM2835_CLOCK_BASE/4;
bcm2835_pads = bcm2835_peripherals + BCM2835_GPIO_PADS/4;
bcm2835_spi0 = bcm2835_peripherals + BCM2835_SPI0_BASE/4;
bcm2835_bsc0 = bcm2835_peripherals + BCM2835_BSC0_BASE/4; /* I2C */
bcm2835_bsc1 = bcm2835_peripherals + BCM2835_BSC1_BASE/4; /* I2C */
bcm2835_st = bcm2835_peripherals + BCM2835_ST_BASE/4;
bcm2835_aux = bcm2835_peripherals + BCM2835_AUX_BASE/4;
bcm2835_spi1 = bcm2835_peripherals + BCM2835_SPI1_BASE/4;
ok = 1;
} else {
/* Not root, try /dev/gpiomem */
/* Open the master /dev/mem device */
if ((memfd = open("/dev/gpiomem", O_RDWR | O_SYNC) ) < 0) {
fprintf(stderr, "bcm2835_init: Unable to open /dev/gpiomem: %s\n",
strerror(errno)) ;
goto exit;
}
/* Base of the peripherals block is mapped to VM */
bcm2835_peripherals_base = 0;
bcm2835_peripherals = mapmem("gpio", bcm2835_peripherals_size, memfd, bcm2835_peripherals_base);
if (bcm2835_peripherals == MAP_FAILED) goto exit;
bcm2835_gpio = bcm2835_peripherals;
ok = 1;
}
exit:
if (memfd >= 0)
close(memfd);
if (!ok)
bcm2835_close();
return ok;
}
#endif
#ifdef TRANSPORT_FTDI
int spi_init(void) {
int ftdi_status = 0;
ftdi = ftdi_new();
if ( ftdi == NULL ) {
fprintf(stderr, "Failed to initialize device\r\n");
return 1;
}
ftdi_status = ftdi_usb_open(ftdi, VENDOR, PRODUCT);
if ( ftdi_status != 0 ) {
fprintf(stderr, "Can't open device. Got error %s\r\n", ftdi_get_error_string(ftdi));
return 1;
}
ftdi_usb_reset(ftdi);
ftdi_set_interface(ftdi, INTERFACE_B);
ftdi_set_bitmode(ftdi, 0, 0); // reset
ftdi_set_bitmode(ftdi, 0, BITMODE_MPSSE); // enable mpsse on all bits
ftdi_usb_purge_buffers(ftdi);
usleep(50000); // sleep 50 ms for setup to complete
return 0;
}
int spi_exit(void) {
ftdi_usb_reset(ftdi);
ftdi_usb_close(ftdi);
return 0;
}
int spi_rw_buffer(uint8_t* pBuffer, uint8_t* rxBuffer, int numBytes) {
int inx = 0;
uint8_t buf[1024] = {0};
// assert CS (active low)
buf[inx++] = SET_BITS_LOW;
buf[inx++] = 0;
buf[inx++] = outpins;
// commands to write and read n bytes in SPI0 (polarity = phase = 0) mode
buf[inx++] = MPSSE_DO_WRITE | MPSSE_WRITE_NEG | MPSSE_DO_READ;
buf[inx++] = (numBytes - 1) & 0xff; // length-1 low byte
buf[inx++] = ((numBytes - 1)>>8) & 0xff; // length-1 high byte
memcpy(buf+inx, pBuffer, numBytes);
inx += numBytes;
// de-assert CS
buf[inx++] = SET_BITS_LOW;
buf[inx++] = CS;
buf[inx++] = outpins;
ftdi_usb_purge_tx_buffer(ftdi);
if ( ftdi_write_data(ftdi, buf, inx) != inx ) {
fprintf(stderr, "spi write failed\r\n");
return -1;
}
uint8_t readBuf[1024] = {0};
if ( ftdi_read_data(ftdi, readBuf, numBytes) != numBytes ) {
fprintf(stderr, "spi read failed\r\n");
return -1;
} else {
memcpy(rxBuffer, readBuf, numBytes);
}
/*
int n = 0;
printf("%d - ", numBytes);
for (n = 0; n < numBytes; n++) {
printf("%d ", rxBuffer[n]);
}
printf("\n");
*/
return 0;
}
#endif
void update_freq(void *arg, long period)
{
int i;
data_t *data = (data_t *)arg;
double max_ac, vel_cmd, dv, new_vel, max_freq, desired_freq;
double error, command, feedback;
double periodfp, periodrecip;
float pgain, ff1gain, deadband;
// precalculate timing constants
periodfp = period * 0.000000001;
periodrecip = 1.0 / periodfp;
// calc constants related to the period of this function (LinuxCNC SERVO_THREAD)
// only recalc constants if period changes
if (period != old_dtns) { // Note!! period = LinuxCNC SERVO_PERIOD
old_dtns = period; // get ready to detect future period changes
dt = period * 0.000000001; // dt is the period of this thread, used for the position loop
recip_dt = 1.0 / dt; // calc the reciprocal once here, to avoid multiple divides later
}
// loop through generators
for (i = 0; i < JOINTS; i++) {
// check for scale change
if (data->pos_scale[i] != data->old_scale[i]) {
data->old_scale[i] = data->pos_scale[i]; // get ready to detect future scale changes
// scale must not be 0
if ((data->pos_scale[i] < 1e-20) && (data->pos_scale[i] > -1e-20)) // validate the new scale value
data->pos_scale[i] = 1.0; // value too small, divide by zero is a bad thing
// we will need the reciprocal, and the accum is fixed point with
//fractional bits, so we precalc some stuff
data->scale_recip[i] = (1.0 / STEP_MASK) / data->pos_scale[i];
}
// calculate frequency limit
//max_freq = PRU_BASEFREQ/(4.0); //limit of DDS running at 80kHz
max_freq = PRU_BASEFREQ/(2.0);
// check for user specified frequency limit parameter
if (data->maxvel[i] <= 0.0) {
// set to zero if negative
data->maxvel[i] = 0.0;
} else {
// parameter is non-zero, compare to max_freq
desired_freq = data->maxvel[i] * fabs(data->pos_scale[i]);
if (desired_freq > max_freq) {
// parameter is too high, limit it
data->maxvel[i] = max_freq / fabs(data->pos_scale[i]);
} else {
// lower max_freq to match parameter
max_freq = data->maxvel[i] * fabs(data->pos_scale[i]);
}
}
/* set internal accel limit to its absolute max, which is
zero to full speed in one thread period */
max_ac = max_freq * recip_dt;
// check for user specified accel limit parameter
if (data->maxaccel[i] <= 0.0) {
// set to zero if negative
data->maxaccel[i] = 0.0;
} else {
// parameter is non-zero, compare to max_ac
if ((data->maxaccel[i] * fabs(data->pos_scale[i])) > max_ac) {
// parameter is too high, lower it
data->maxaccel[i] = max_ac / fabs(data->pos_scale[i]);
} else {
// lower limit to match parameter
max_ac = data->maxaccel[i] * fabs(data->pos_scale[i]);
}
}
/* at this point, all scaling, limits, and other parameter
changes have been handled - time for the main control */
if (data->pos_mode[i]) {
/* POSITION CONTROL MODE */
// use Proportional control with feed forward (pgain, ff1gain and deadband)
if (*(data->pgain[i]) != 0) {
pgain = *(data->pgain[i]);
} else {
pgain = 1.0;
}
if (*(data->ff1gain[i]) != 0) {
ff1gain = *(data->ff1gain[i]);
} else {
ff1gain = 1.0;
}
if (*(data->deadband[i]) != 0) {
deadband = *(data->deadband[i]);
} else {
deadband = 1 / data->pos_scale[i];
}
// read the command and feedback
command = *(data->pos_cmd[i]);
feedback = *(data->pos_fb[i]);
// calcuate the error
error = command - feedback;
// apply the deadband
if (error > deadband) {
error -= deadband;
} else if (error < -deadband) {
error += deadband;
} else {
error = 0;
}
// calcuate command and derivatives
data->cmd_d[i] = (command - data->prev_cmd[i]) * periodrecip;
// save old values
data->prev_cmd[i] = command;
// calculate the output value
vel_cmd = pgain * error + data->cmd_d[i] * ff1gain;
} else {
/* VELOCITY CONTROL MODE */
// calculate velocity command in counts/sec
vel_cmd = *(data->vel_cmd[i]);
}
vel_cmd = vel_cmd * data->pos_scale[i];
// apply frequency limit
if (vel_cmd > max_freq) {
vel_cmd = max_freq;
} else if (vel_cmd < -max_freq) {
vel_cmd = -max_freq;
}
// calc max change in frequency in one period
dv = max_ac * dt;
// apply accel limit
if ( vel_cmd > (data->freq[i] + dv) ) {
new_vel = data->freq[i] + dv;
} else if ( vel_cmd < (data->freq[i] - dv) ) {
new_vel = data->freq[i] - dv;
} else {
new_vel = vel_cmd;
}
// test for disabled stepgen
if (*data->stepperEnable == 0) {
// set velocity to zero
new_vel = 0;
}
data->freq[i] = new_vel; // to be sent to the PRU
*(data->freq_cmd[i]) = data->freq[i]; // feedback to LinuxCNC
}
}
void rio_readwrite()
{
int i = 0;
int bi = 0;
double curr_pos;
long new_stamp;
long duration;
new_stamp = rtapi_get_time();
duration = new_stamp - stamp;
stamp = new_stamp;
// Data header
txData.header = PRU_READ;
if (*(data->SPIenable)) {
if( (*(data->SPIreset) && !(data->SPIresetOld)) || *(data->SPIstatus) ) {
// reset rising edge detected, try SPI transfer and reset OR PRU running
int i = 0;
// Data header
txData.header = PRU_WRITE;
// Joint frequency commands
for (i = 0; i < JOINTS; i++) {
if (joints_type[i] == JOINT_PWMDIR) {
txData.jointFreqCmd[i] = data->freq[i];
} else if (joints_type[i] == JOINT_STEPPER) {
txData.jointFreqCmd[i] = PRU_OSC / data->freq[i] / 2;
} else {
txData.jointFreqCmd[i] = PRU_OSC / data->freq[i];
}
}
for (bi = 0; bi < JOINT_ENABLE_BYTES; bi++) {
txData.jointEnable[bi] = 0;
for (i = 0; i < JOINTS; i++) {