-
Notifications
You must be signed in to change notification settings - Fork 1
/
arduPi_pi2.cpp
executable file
·1525 lines (1265 loc) · 42.3 KB
/
arduPi_pi2.cpp
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
/*
* Copyright (C) 2012 Libelium Comunicaciones Distribuidas S.L.
* http://www.libelium.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Version 2.0
* Author: Sergio Martinez
*/
#include "arduPi_pi2.h"
struct bcm2835_peripheral gpio = {GPIO_BASE2};
struct bcm2835_peripheral bsc_rev1 = {IOBASE + 0X205000};
struct bcm2835_peripheral bsc_rev2 = {IOBASE + 0X804000};
struct bcm2835_peripheral bsc0;
volatile uint32_t *bcm2835_bsc01;
void *spi0 = MAP_FAILED;
static uint8_t *spi0Mem = NULL;
pthread_t idThread2;
pthread_t idThread3;
pthread_t idThread4;
pthread_t idThread5;
pthread_t idThread6;
pthread_t idThread7;
pthread_t idThread8;
pthread_t idThread9;
pthread_t idThread10;
pthread_t idThread11;
pthread_t idThread12;
pthread_t idThread13;
timeval start_program, end_point;
/*********************************
* *
* SerialPi Class implementation *
* ----------------------------- *
*********************************/
/******************
* Public methods *
******************/
//Constructor
SerialPi::SerialPi(){
REV = getBoardRev();
serialPort="/dev/ttyAMA0";
timeOut = 1000;
}
//Sets the data rate in bits per second (baud) for serial data transmission
void SerialPi::begin(int serialSpeed){
switch(serialSpeed){
case 50: speed = B50 ; break ;
case 75: speed = B75 ; break ;
case 110: speed = B110 ; break ;
case 134: speed = B134 ; break ;
case 150: speed = B150 ; break ;
case 200: speed = B200 ; break ;
case 300: speed = B300 ; break ;
case 600: speed = B600 ; break ;
case 1200: speed = B1200 ; break ;
case 1800: speed = B1800 ; break ;
case 2400: speed = B2400 ; break ;
case 9600: speed = B9600 ; break ;
case 19200: speed = B19200 ; break ;
case 38400: speed = B38400 ; break ;
case 57600: speed = B57600 ; break ;
case 115200: speed = B115200 ; break ;
default: speed = B230400 ; break ;
}
if ((sd = open(serialPort, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK)) == -1){
fprintf(stderr,"Unable to open the serial port %s - \n", serialPort);
exit(-1);
}
fcntl (sd, F_SETFL, O_RDWR) ;
tcgetattr(sd, &options);
cfmakeraw(&options);
cfsetispeed (&options, speed);
cfsetospeed (&options, speed);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_oflag &= ~OPOST;
tcsetattr (sd, TCSANOW, &options);
ioctl (sd, TIOCMGET, &status);
status |= TIOCM_DTR;
status |= TIOCM_RTS;
ioctl (sd, TIOCMSET, &status);
unistd::usleep (10000);
}
//Prints data to the serial port as human-readable ASCII text.
void SerialPi::print(const char *message){
unistd::write(sd,message,strlen(message));
}
//Prints data to the serial port as human-readable ASCII text.
void SerialPi::print (char message){
unistd::write(sd,&message,1);
}
/*Prints data to the serial port as human-readable ASCII text.
* It can print the message in many format representations such as:
* Binary, Octal, Decimal, Hexadecimal and as a BYTE. */
void SerialPi::print(unsigned char i,Representation rep){
char * message;
switch(rep){
case BIN:
message = int2bin(i);
unistd::write(sd,message,strlen(message));
break;
case OCT:
message = int2oct(i);
unistd::write(sd,message,strlen(message));
break;
case DEC:
sprintf(message,"%d",i);
unistd::write(sd,message,strlen(message));
break;
case HEX:
message = int2hex(i);
unistd::write(sd,message,strlen(message));
break;
case BYTE:
unistd::write(sd,&i,1);
break;
}
}
/* Prints data to the serial port as human-readable ASCII text.
* precission is used to limit the number of decimals.
*/
void SerialPi::print(float f, int precission){
/*
const char *str1="%.";
char * str2;
char * str3;
char * message;
sprintf(str2,"%df",precission);
asprintf(&str3,"%s%s",str1,str2);
sprintf(message,str3,f);
*/
char message[10];
sprintf(message, "%.1f", f );
unistd::write(sd,message,strlen(message));
}
/* Prints data to the serial port as human-readable ASCII text followed
* by a carriage retrun character '\r' and a newline character '\n' */
void SerialPi::println(const char *message){
const char *newline="\r\n";
char * msg = NULL;
asprintf(&msg,"%s%s",message,newline);
unistd::write(sd,msg,strlen(msg));
}
/* Prints data to the serial port as human-readable ASCII text followed
* by a carriage retrun character '\r' and a newline character '\n' */
void SerialPi::println(char message){
const char *newline="\r\n";
char * msg = NULL;
asprintf(&msg,"%s%s",&message,newline);
unistd::write(sd,msg,strlen(msg));
}
/* Prints data to the serial port as human-readable ASCII text followed
* by a carriage retrun character '\r' and a newline character '\n' */
void SerialPi::println(int i, Representation rep){
char * message;
switch(rep){
case BIN:
message = int2bin(i);
break;
case OCT:
message = int2oct(i);
break;
case DEC:
sprintf(message,"%d",i);
break;
case HEX:
message = int2hex(i);
break;
}
const char *newline="\r\n";
char * msg = NULL;
asprintf(&msg,"%s%s",message,newline);
unistd::write(sd,msg,strlen(msg));
}
/* Prints data to the serial port as human-readable ASCII text followed
* by a carriage retrun character '\r' and a newline character '\n' */
void SerialPi::println(float f, int precission){
const char *str1="%.";
char * str2;
char * str3;
char * message;
sprintf(str2,"%df",precission);
asprintf(&str3,"%s%s",str1,str2);
sprintf(message,str3,f);
const char *newline="\r\n";
char * msg = NULL;
asprintf(&msg,"%s%s",message,newline);
unistd::write(sd,msg,strlen(msg));
}
/* Writes binary data to the serial port. This data is sent as a byte
* Returns: number of bytes written */
int SerialPi::write(unsigned char message){
unistd::write(sd,&message,1);
return 1;
}
/* Writes binary data to the serial port. This data is sent as a series
* of bytes
* Returns: number of bytes written */
int SerialPi::write(const char *message){
int len = strlen(message);
unistd::write(sd,&message,len);
return len;
}
/* Writes binary data to the serial port. This data is sent as a series
* of bytes placed in an buffer. It needs the length of the buffer
* Returns: number of bytes written */
int SerialPi::write(char *message, int size){
unistd::write(sd,message,size);
return size;
}
/* Get the numberof bytes (characters) available for reading from
* the serial port.
* Return: number of bytes avalable to read */
int SerialPi::available(){
int nbytes = 0;
if (ioctl(sd, FIONREAD, &nbytes) < 0) {
fprintf(stderr, "Failed to get byte count on serial.\n");
exit(-1);
}
return nbytes;
}
/* Reads 1 byte of incoming serial data
* Returns: first byte of incoming serial data available */
char SerialPi::read() {
unistd::read(sd,&c,1);
return c;
}
/* Reads characters from th serial port into a buffer. The function
* terminates if the determined length has been read, or it times out
* Returns: number of bytes readed */
int SerialPi::readBytes(char message[], int size){
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
int count;
for (count=0;count<size;count++){
if(available()) unistd::read(sd,&message[count],1);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
timespec t = timeDiff(time1,time2);
if((t.tv_nsec/1000)>timeOut) break;
}
return count;
}
/* Reads characters from the serial buffer into an array.
* The function terminates if the terminator character is detected,
* the determined length has been read, or it times out.
* Returns: number of characters read into the buffer. */
int SerialPi::readBytesUntil(char character,char buffer[],int length){
char lastReaded = character +1; //Just to make lastReaded != character
int count=0;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
while(count != length && lastReaded != character){
if(available()) unistd::read(sd,&buffer[count],1);
lastReaded = buffer[count];
count ++;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
timespec t = timeDiff(time1,time2);
if((t.tv_nsec/1000)>timeOut) break;
}
return count;
}
bool SerialPi::find(const char *target){
findUntil(target,NULL);
}
/* Reads data from the serial buffer until a target string of given length
* or terminator string is found.
* Returns: true if the target string is found, false if it times out */
bool SerialPi::findUntil(const char *target, const char *terminal){
int index = 0;
int termIndex = 0;
int targetLen = strlen(target);
int termLen = strlen(terminal);
char readed;
timespec t;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
if( *target == 0)
return true; // return true if target is a null string
do{
if(available()){
unistd::read(sd,&readed,1);
if(readed != target[index])
index = 0; // reset index if any char does not match
if( readed == target[index]){
if(++index >= targetLen){ // return true if all chars in the target match
return true;
}
}
if(termLen > 0 && c == terminal[termIndex]){
if(++termIndex >= termLen) return false; // return false if terminate string found before target string
}else{
termIndex = 0;
}
}
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
t = timeDiff(time1,time2);
}while((t.tv_nsec/1000)<=timeOut);
return false;
}
/* returns the first valid (long) integer value from the current position.
* initial characters that are not digits (or the minus sign) are skipped
* function is terminated by the first character that is not a digit. */
long SerialPi::parseInt(){
bool isNegative = false;
long value = 0;
char c;
//Skip characters until a number or - sign found
do{
c = peek();
if (c == '-') break;
if (c >= '0' && c <= '9') break;
unistd::read(sd,&c,1); // discard non-numeric
}while(1);
do{
if(c == '-')
isNegative = true;
else if(c >= '0' && c <= '9')// is c a digit?
value = value * 10 + c - '0';
unistd::read(sd,&c,1); // consume the character we got with peek
c = peek();
}while(c >= '0' && c <= '9');
if(isNegative)
value = -value;
return value;
}
float SerialPi::parseFloat(){
boolean isNegative = false;
boolean isFraction = false;
long value = 0;
char c;
float fraction = 1.0;
//Skip characters until a number or - sign found
do{
c = peek();
if (c == '-') break;
if (c >= '0' && c <= '9') break;
unistd::read(sd,&c,1); // discard non-numeric
}while(1);
do{
if(c == '-')
isNegative = true;
else if (c == '.')
isFraction = true;
else if(c >= '0' && c <= '9') { // is c a digit?
value = value * 10 + c - '0';
if(isFraction)
fraction *= 0.1;
}
unistd::read(sd,&c,1); // consume the character we got with peek
c = peek();
}while( (c >= '0' && c <= '9') || (c == '.' && isFraction==false));
if(isNegative)
value = -value;
if(isFraction)
return value * fraction;
else
return value;
}
// Returns the next byte (character) of incoming serial data without removing it from the internal serial buffer.
char SerialPi::peek(){
//We obtain a pointer to FILE structure from the file descriptor sd
FILE * f = fdopen(sd,"r+");
//With a pointer to FILE we can do getc and ungetc
c = getc(f);
ungetc(c, f);
return c;
}
// Remove any data remaining on the serial buffer
void SerialPi::flush(){
while(available()){
unistd::read(sd,&c,1);
}
}
/* Sets the maximum milliseconds to wait for serial data when using SerialPi::readBytes()
* The default value is set to 1000 */
void SerialPi::setTimeout(long millis){
timeOut = millis;
}
//Disables serial communication
void SerialPi::end(){
unistd::close(sd);
}
/*******************
* Private methods *
*******************/
//Returns a timespec struct with the time elapsed between start and end timespecs
timespec SerialPi::timeDiff(timespec start, timespec end){
timespec temp;
if ((end.tv_nsec-start.tv_nsec)<0) {
temp.tv_sec = end.tv_sec-start.tv_sec-1;
temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
} else {
temp.tv_sec = end.tv_sec-start.tv_sec;
temp.tv_nsec = end.tv_nsec-start.tv_nsec;
}
return temp;
}
//Returns a binary representation of the integer passed as argument
char * SerialPi::int2bin(int i){
size_t bits = sizeof(int) * CHAR_BIT;
char * str = (char *)malloc(bits + 1);
int firstCeros = 0;
int size = bits;
if(!str) return NULL;
str[bits] = 0;
// type punning because signed shift is implementation-defined
unsigned u = *(unsigned *)&i;
for(; bits--; u >>= 1)
str[bits] = u & 1 ? '1' : '0';
//Delete first 0's
for (int i=0; i<bits; i++){
if(str[i] == '0'){
firstCeros++;
}else{
break;
}
}
char * str_noceros = (char *)malloc(size-firstCeros+1);
for (int i=0; i<(size-firstCeros);i++){
str_noceros[i]=str[firstCeros+i];
}
return str_noceros;
}
//Returns an hexadecimal representation of the integer passed as argument
char * SerialPi::int2hex(int i){
char buffer[32];
sprintf(buffer,"%x",i);
char * hex = (char *)malloc(strlen(buffer)+1);
strcpy(hex,buffer);
return hex;
}
//Returns an octal representation of the integer passed as argument
char * SerialPi::int2oct(int i){
char buffer[32];
sprintf(buffer,"%o",i);
char * oct = (char *)malloc(strlen(buffer)+1);
strcpy(oct,buffer);
return oct;
}
/*******************************
* *
* WirePi Class implementation *
* --------------------------- *
*******************************/
/******************
* Public methods *
******************/
//Constructor
WirePi::WirePi(){
REV = getBoardRev();
if(map_peripheral(&gpio) == -1) {
printf("Failed to map the physical GPIO registers into the virtual memory space.\n");
}
memfd = -1;
i2c_byte_wait_us = 0;
// Open the master /dev/memory device
if ((memfd = open("/dev/mem", O_RDWR | O_SYNC) ) < 0)
{
fprintf(stderr, "bcm2835_init: Unable to open /dev/mem: %s\n",
strerror(errno)) ;
exit(1);
}
bcm2835_bsc01 = mapmem("bsc1", BLOCK_SIZE, memfd, BCM2835_BSC1_BASE2);
if (bcm2835_bsc01 == MAP_FAILED) exit(1);
// start timer
gettimeofday(&start_program, NULL);
}
//Initiate the Wire library and join the I2C bus.
void WirePi::begin(){
volatile uint32_t* paddr = bcm2835_bsc01 + BCM2835_BSC_DIV/4;
// Set the I2C/BSC1 pins to the Alt 0 function to enable I2C access on them
ch_gpio_fsel(RPI_V2_GPIO_P1_03, BCM2835_GPIO_FSEL_ALT0); // SDA
ch_gpio_fsel(RPI_V2_GPIO_P1_05, BCM2835_GPIO_FSEL_ALT0); // SCL
// Read the clock divider register
uint16_t cdiv = ch_peri_read(paddr);
// Calculate time for transmitting one byte
// 1000000 = micros seconds in a second
// 9 = Clocks per byte : 8 bits + ACK
i2c_byte_wait_us = ((float)cdiv / BCM2835_CORE_CLK_HZ) * 1000000 * 9;
}
//Begin a transmission to the I2C slave device with the given address
void WirePi::beginTransmission(unsigned char address){
// Set I2C Device Address
volatile uint32_t* paddr = bcm2835_bsc01 + BCM2835_BSC_A/4;
ch_peri_write(paddr, address);
}
//Writes data to the I2C.
void WirePi::write(char data){
char i2cdata[1];
i2cdata[0] = data;
write(i2cdata,1);
}
//Writes data to the I2C.
uint8_t WirePi::write(const char * buf, uint32_t len){
volatile uint32_t* dlen = bcm2835_bsc01 + BCM2835_BSC_DLEN/4;
volatile uint32_t* fifo = bcm2835_bsc01 + BCM2835_BSC_FIFO/4;
volatile uint32_t* status = bcm2835_bsc01 + BCM2835_BSC_S/4;
volatile uint32_t* control = bcm2835_bsc01 + BCM2835_BSC_C/4;
uint32_t remaining = len;
uint32_t i = 0;
uint8_t reason = BCM2835_I2C_REASON_OK;
// Clear FIFO
ch_peri_set_bits(control, BCM2835_BSC_C_CLEAR_1 , BCM2835_BSC_C_CLEAR_1 );
// Clear Status
ch_peri_write_nb(status, BCM2835_BSC_S_CLKT | BCM2835_BSC_S_ERR | BCM2835_BSC_S_DONE);
// Set Data Length
ch_peri_write_nb(dlen, len);
// pre populate FIFO with max buffer
while( remaining && ( i < BCM2835_BSC_FIFO_SIZE ) )
{
ch_peri_write_nb(fifo, buf[i]);
i++;
remaining--;
}
// Enable device and start transfer
ch_peri_write_nb(control, BCM2835_BSC_C_I2CEN | BCM2835_BSC_C_ST);
// Transfer is over when BCM2835_BSC_S_DONE
while(!(ch_peri_read_nb(status) & BCM2835_BSC_S_DONE ))
{
while ( remaining && (ch_peri_read_nb(status) & BCM2835_BSC_S_TXD ))
{
// Write to FIFO, no barrier
ch_peri_write_nb(fifo, buf[i]);
i++;
remaining--;
}
}
// Received a NACK
if (ch_peri_read(status) & BCM2835_BSC_S_ERR)
{
reason = BCM2835_I2C_REASON_ERROR_NACK;
}
// Received Clock Stretch Timeout
else if (ch_peri_read(status) & BCM2835_BSC_S_CLKT)
{
reason = BCM2835_I2C_REASON_ERROR_CLKT;
}
// Not all data is sent
else if (remaining)
{
reason = BCM2835_I2C_REASON_ERROR_DATA;
}
ch_peri_set_bits(control, BCM2835_BSC_S_DONE , BCM2835_BSC_S_DONE);
return reason;
}
void WirePi::endTransmission(){
// Set all the I2C/BSC1 pins back to input
ch_gpio_fsel(RPI_V2_GPIO_P1_03, BCM2835_GPIO_FSEL_INPT); // SDA
ch_gpio_fsel(RPI_V2_GPIO_P1_05, BCM2835_GPIO_FSEL_INPT); // SCL
}
//Used by the master to request bytes from a slave device
void WirePi::requestFrom(unsigned char address,int quantity){
// Set I2C Device Address
volatile uint32_t* paddr = bcm2835_bsc01 + BCM2835_BSC_A/4;
ch_peri_write(paddr, address);
i2c_bytes_to_read = quantity;
}
//Reads a byte that was transmitted from a slave device to a master after a call to WirePi::requestFrom()
unsigned char WirePi::read(){
char buf;
i2c_bytes_to_read=1;
read(&buf);
return (unsigned char)buf;
}
uint8_t WirePi::read(char* buf){
volatile uint32_t* dlen = bcm2835_bsc01 + BCM2835_BSC_DLEN/4;
volatile uint32_t* fifo = bcm2835_bsc01 + BCM2835_BSC_FIFO/4;
volatile uint32_t* status = bcm2835_bsc01 + BCM2835_BSC_S/4;
volatile uint32_t* control = bcm2835_bsc01 + BCM2835_BSC_C/4;
uint32_t remaining = i2c_bytes_to_read;
uint32_t i = 0;
uint8_t reason = BCM2835_I2C_REASON_OK;
// Clear FIFO
ch_peri_set_bits(control, BCM2835_BSC_C_CLEAR_1 , BCM2835_BSC_C_CLEAR_1 );
// Clear Status
ch_peri_write_nb(status, BCM2835_BSC_S_CLKT | BCM2835_BSC_S_ERR | BCM2835_BSC_S_DONE);
// Set Data Length
ch_peri_write_nb(dlen, i2c_bytes_to_read);
// Start read
ch_peri_write_nb(control, BCM2835_BSC_C_I2CEN | BCM2835_BSC_C_ST | BCM2835_BSC_C_READ);
// wait for transfer to complete
while (!(ch_peri_read_nb(status) & BCM2835_BSC_S_DONE))
{
// we must empty the FIFO as it is populated and not use any delay
while (ch_peri_read_nb(status) & BCM2835_BSC_S_RXD)
{
// Read from FIFO, no barrier
buf[i] = ch_peri_read_nb(fifo);
i++;
remaining--;
}
}
// transfer has finished - grab any remaining stuff in FIFO
while (remaining && (ch_peri_read_nb(status) & BCM2835_BSC_S_RXD))
{
// Read from FIFO, no barrier
buf[i] = ch_peri_read_nb(fifo);
i++;
remaining--;
}
// Received a NACK
if (ch_peri_read(status) & BCM2835_BSC_S_ERR)
{
reason = BCM2835_I2C_REASON_ERROR_NACK;
}
// Received Clock Stretch Timeout
else if (ch_peri_read(status) & BCM2835_BSC_S_CLKT)
{
reason = BCM2835_I2C_REASON_ERROR_CLKT;
}
// Not all data is received
else if (remaining)
{
reason = BCM2835_I2C_REASON_ERROR_DATA;
}
ch_peri_set_bits(control, BCM2835_BSC_S_DONE , BCM2835_BSC_S_DONE);
return reason;
}
// Read an number of bytes from I2C sending a repeated start after writing
// the required register. Only works if your device supports this mode
uint8_t WirePi::read_rs(char* regaddr, char* buf, uint32_t len){
volatile uint32_t* dlen = bcm2835_bsc01 + BCM2835_BSC_DLEN/4;
volatile uint32_t* fifo = bcm2835_bsc01 + BCM2835_BSC_FIFO/4;
volatile uint32_t* status = bcm2835_bsc01 + BCM2835_BSC_S/4;
volatile uint32_t* control = bcm2835_bsc01 + BCM2835_BSC_C/4;
uint32_t remaining = len;
uint32_t i = 0;
uint8_t reason = BCM2835_I2C_REASON_OK;
// Clear FIFO
ch_peri_set_bits(control, BCM2835_BSC_C_CLEAR_1 , BCM2835_BSC_C_CLEAR_1 );
// Clear Status
ch_peri_write_nb(status, BCM2835_BSC_S_CLKT | BCM2835_BSC_S_ERR | BCM2835_BSC_S_DONE);
// Set Data Length
ch_peri_write_nb(dlen, 1);
// Enable device and start transfer
ch_peri_write_nb(control, BCM2835_BSC_C_I2CEN);
ch_peri_write_nb(fifo, regaddr[0]);
ch_peri_write_nb(control, BCM2835_BSC_C_I2CEN | BCM2835_BSC_C_ST);
// poll for transfer has started
while ( !( ch_peri_read_nb(status) & BCM2835_BSC_S_TA ) )
{
// Linux may cause us to miss entire transfer stage
if(ch_peri_read(status) & BCM2835_BSC_S_DONE)
break;
}
// Send a repeated start with read bit set in address
ch_peri_write_nb(dlen, len);
ch_peri_write_nb(control, BCM2835_BSC_C_I2CEN | BCM2835_BSC_C_ST | BCM2835_BSC_C_READ );
// Wait for write to complete and first byte back.
delayMicroseconds(i2c_byte_wait_us * 3);
// wait for transfer to complete
while (!(ch_peri_read_nb(status) & BCM2835_BSC_S_DONE))
{
// we must empty the FIFO as it is populated and not use any delay
while (remaining && ch_peri_read_nb(status) & BCM2835_BSC_S_RXD)
{
// Read from FIFO, no barrier
buf[i] = ch_peri_read_nb(fifo);
i++;
remaining--;
}
}
// transfer has finished - grab any remaining stuff in FIFO
while (remaining && (ch_peri_read_nb(status) & BCM2835_BSC_S_RXD))
{
// Read from FIFO, no barrier
buf[i] = ch_peri_read_nb(fifo);
i++;
remaining--;
}
// Received a NACK
if (ch_peri_read(status) & BCM2835_BSC_S_ERR)
{
reason = BCM2835_I2C_REASON_ERROR_NACK;
}
// Received Clock Stretch Timeout
else if (ch_peri_read(status) & BCM2835_BSC_S_CLKT)
{
reason = BCM2835_I2C_REASON_ERROR_CLKT;
}
// Not all data is sent
else if (remaining)
{
reason = BCM2835_I2C_REASON_ERROR_DATA;
}
ch_peri_set_bits(control, BCM2835_BSC_S_DONE , BCM2835_BSC_S_DONE);
return reason;
}
/*******************
* Private methods *
*******************/
// Exposes the physical address defined in the passed structure using mmap on /dev/mem
int WirePi::map_peripheral(struct bcm2835_peripheral *p)
{
// Open /dev/mem
if ((p->mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0) {
printf("Failed to open /dev/mem, try checking permissions.\n");
return -1;
}
p->map = mmap(
NULL,
BLOCK_SIZE,
PROT_READ|PROT_WRITE,
MAP_SHARED,
p->mem_fd, // File descriptor to physical memory virtual file '/dev/mem'
p->addr_p // Address in physical map that we want this memory block to expose
);
if (p->map == MAP_FAILED) {
perror("mmap");
return -1;
}
p->addr = (volatile unsigned int *)p->map;
return 0;
}
void WirePi::unmap_peripheral(struct bcm2835_peripheral *p) {
munmap(p->map, BLOCK_SIZE);
unistd::close(p->mem_fd);
}
void WirePi::wait_i2c_done() {
//Wait till done, let's use a timeout just in case
int timeout = 50;
while((!((BSC0_S) & BSC_S_DONE)) && --timeout) {
unistd::usleep(1000);
}
if(timeout == 0)
printf("wait_i2c_done() timeout. Something went wrong.\n");
}
/*******************************
* *
* SPIPi Class implementation *
* --------------------------- *
*******************************/
/******************
* Public methods *
******************/
SPIPi::SPIPi(){
REV = getBoardRev();
uint8_t *mapaddr;
if ((spi0Mem = (uint8_t*)malloc(BLOCK_SIZE + (PAGESIZE - 1))) == NULL){
fprintf(stderr, "bcm2835_init: spi0Mem malloc failed: %s\n", strerror(errno));
exit(1);
}
mapaddr = spi0Mem;
if (((uint32_t)mapaddr % PAGESIZE) != 0)
mapaddr += PAGESIZE - ((uint32_t)mapaddr % PAGESIZE) ;
spi0 = (uint32_t *)mmap(mapaddr, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_FIXED, gpio.mem_fd, BCM2835_SPI0_BASE2) ;
if ((int32_t)spi0 < 0){
fprintf(stderr, "bcm2835_init: mmap failed (spi0): %s\n", strerror(errno)) ;
exit(1);
}
}
void SPIPi::begin(){
// Set the SPI0 pins to the Alt 0 function to enable SPI0 access on them
ch_gpio_fsel(7, BCM2835_GPIO_FSEL_ALT0); // CE1
ch_gpio_fsel(8, BCM2835_GPIO_FSEL_ALT0); // CE0
ch_gpio_fsel(9, BCM2835_GPIO_FSEL_ALT0); // MISO
ch_gpio_fsel(10, BCM2835_GPIO_FSEL_ALT0); // MOSI
ch_gpio_fsel(11, BCM2835_GPIO_FSEL_ALT0); // CLK
// Set the SPI CS register to the some sensible defaults
volatile uint32_t* paddr = (volatile uint32_t*)spi0 + BCM2835_SPI0_CS/4;
ch_peri_write(paddr, 0); // All 0s
// Clear TX and RX fifos
ch_peri_write_nb(paddr, BCM2835_SPI0_CS_CLEAR);
}
void SPIPi::end(){
// Set all the SPI0 pins back to input
ch_gpio_fsel(7, BCM2835_GPIO_FSEL_INPT); // CE1
ch_gpio_fsel(8, BCM2835_GPIO_FSEL_INPT); // CE0
ch_gpio_fsel(9, BCM2835_GPIO_FSEL_INPT); // MISO
ch_gpio_fsel(10, BCM2835_GPIO_FSEL_INPT); // MOSI
ch_gpio_fsel(11, BCM2835_GPIO_FSEL_INPT); // CLK
}
void SPIPi::setBitOrder(uint8_t order){
// BCM2835_SPI_BIT_ORDER_MSBFIRST is the only one suported by SPI0
}
// defaults to 0, which means a divider of 65536.
// The divisor must be a power of 2. Odd numbers
// rounded down. The maximum SPI clock rate is
// of the APB clock
void SPIPi::setClockDivider(uint16_t divider){
volatile uint32_t* paddr = (volatile uint32_t*)spi0 + BCM2835_SPI0_CLK/4;
ch_peri_write(paddr, divider);
}
void SPIPi::setDataMode(uint8_t mode){
volatile uint32_t* paddr = (volatile uint32_t*)spi0 + BCM2835_SPI0_CS/4;
// Mask in the CPO and CPHA bits of CS
ch_peri_set_bits(paddr, mode << 2, BCM2835_SPI0_CS_CPOL | BCM2835_SPI0_CS_CPHA);
}
// Writes (and reads) a single byte to SPI
uint8_t SPIPi::transfer(uint8_t value){
volatile uint32_t* paddr = (volatile uint32_t*)spi0 + BCM2835_SPI0_CS/4;
volatile uint32_t* fifo = (volatile uint32_t*)spi0 + BCM2835_SPI0_FIFO/4;
ch_peri_set_bits(paddr, BCM2835_SPI0_CS_CLEAR, BCM2835_SPI0_CS_CLEAR);
ch_peri_set_bits(paddr, BCM2835_SPI0_CS_TA, BCM2835_SPI0_CS_TA);
while (!(ch_peri_read(paddr) & BCM2835_SPI0_CS_TXD))
delayMicroseconds(10);
ch_peri_write_nb(fifo, value);
while (!(ch_peri_read_nb(paddr) & BCM2835_SPI0_CS_DONE))
delayMicroseconds(10);
uint32_t ret = ch_peri_read_nb(fifo);
ch_peri_set_bits(paddr, 0, BCM2835_SPI0_CS_TA);
return ret;
}
// Writes (and reads) a number of bytes to SPI
void SPIPi::transfernb(char* tbuf, char* rbuf, uint32_t len){