aboutsummaryrefslogtreecommitdiff
path: root/rpi/max7219/max7219.c
blob: 33a7fed8216e59694f55165bc0595fd40ed5d39b (plain) (blame)
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
#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);
}