diff options
Diffstat (limited to 'rpi/max7219/max7219.c')
-rw-r--r-- | rpi/max7219/max7219.c | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/rpi/max7219/max7219.c b/rpi/max7219/max7219.c new file mode 100644 index 0000000..33a7fed --- /dev/null +++ b/rpi/max7219/max7219.c @@ -0,0 +1,84 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <signal.h> +#include <time.h> +#include <wiringPi.h> +#include <sys/wait.h> +#include <fcntl.h> +#include <unistd.h> +#include "max7219.h" + +#define wait nanosleep(&cl,NULL) +const struct timespec cl={0,10}; +/* + * _sendpacket(d) + * sends a 16 bit packet to the data line. + * for internal usage only. + */ +void _sendpacket(unsigned short d) +{ + unsigned char i; + for(i=16;i>0;--i) + { + unsigned short mask=1<<(i-1); + digitalWrite(P_CLK,0);wait; + digitalWrite(P_DATA,(d&mask)?1:0); + wait;digitalWrite(P_CLK,1);wait; + } +} +/* + * max7219_send(r,d,chip) + * sets the value of register #d in chip #chip to d. + * chips are 0-indexed. chip=-1 means send to all chips. + */ +void max7219_send(unsigned char r,unsigned char d,int chip) +{ + digitalWrite(P_CS,0);wait; + for(int i=0;i<NCHIPS;++i) + _sendpacket(chip==-1||i+chip==NCHIPS-1?(r<<8)|d:0); + digitalWrite(P_CS,1);wait; +} +/* + * max7219_batch(d) + * sends a batch of data to the chips. each element in d + * is a register-data pair. length of d should equal to + * the number of chips. + * the first chip receives the first data pair, + * the second chip receives the second one etc. + */ +void max7219_batch(unsigned short *d) +{ + digitalWrite(P_CS,0);wait; + for(int i=0;i<NCHIPS;++i) + _sendpacket(d[NCHIPS-1-i]); + digitalWrite(P_CS,1);wait; +} +/* + * max7219_init() + * initialize all chips, putting them into matrix mode. + */ +void max7219_init() +{ + wiringPiSetup(); + pinMode(P_DATA,OUTPUT); + pinMode(P_CS,OUTPUT); + pinMode(P_CLK,OUTPUT); + max7219_send(SCAN_LIMIT,7,-1); + max7219_send(DECODE_MODE,0,-1); + max7219_send(DISPLAY_TEST,0,-1); + max7219_send(INTENSITY,1,-1); + max7219_send(SHUTDOWN,1,-1); +} +/* + * max7219_deinit(clear) + * putting all chips into sleep, optionally clearing + * all the registers when `clear` is set + */ +void max7219_deinit(int clear) +{ + max7219_send(SHUTDOWN,0,-1); + if(clear) + for(int i=0;i<8;++i) + max7219_send(i+1,0,-1); +} |