-
Notifications
You must be signed in to change notification settings - Fork 0
/
code.c
133 lines (102 loc) · 1.9 KB
/
code.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
// [!] THIS CODE IS TO BE USED ONLY AS A REFERENCE [!]
void
initInputSPI(void)
{
DDRB |= 0b10110000;
PORTB = 0b01000000;
}
void
spiInit(void)
{
initInputSPI();
SPCR = 0b01010000;
SPSR |= 0b00000001;
}
uint8_t
spiSend(uint8_t data)
{
enterCriticalSection();
SPDR = data;
while((SPSR & 0b10000000) != 0b10000000){}
uint8_t receivedData = SPDR;
leaveCriticalSection();
return receivedData;
}
uint8_t
spiReceive(void)
{
enterCriticalSection();
uint8_t output = spiSend(0xFF);
leaveCriticalSection();
return output;
}
void
initSRAM(void)
{
enterCriticalSection();
spiInit();
PORTB &= 0b11101111;
spiSend(1);
spiSend(0);
PORTB |= 0b00010000;
leaveCriticalSection();
}
MemValue
readSRAM(uint16_t addr)
{
enterCriticalSection();
PORTB &= 0b11101111;
spiSend(0x03);
spiSend(0b00000000);
spiSend((uint8_t) (addr >> 8));
spiSend((uint8_t) addr);
MemValue output = spiReceive();
PORTB |= 0b00010000;
leaveCriticalSection();
return output;
}
void
writeSRAM(uint16_t addr, uint8_t value)
{
enterCriticalSection();
PORTB &= 0b11101111;
spiSend(0x02);
spiSend(0b00000000);
spiSend((uint8_t) (addr >> 8));
spiSend((uint8_t) addr);
spiSend(value);
PORTB |= 0b00010000;
leaveCriticalSection();
}
void
enterCriticalSection(void) {
uint8_t gIEB = ((SREG >> 7) << 7);
SREG &= 0b01111111; // Deactivate interrupts
if(criticalSectionCount < 255)
{
criticalSectionCount++;
}
else
{
os_error("Error: Too many critical sections");
}
TIMSK2 &= 0b11111101; // Deactivate scheduler
SREG |= gIEB;
}
void leaveCriticalSection(void) {
uint8_t gIEB = ((SREG >> 7) << 7);
SREG &= 0b01111111;
if(criticalSectionCount > 0)
{
criticalSectionCount--;
}
else
{
error("Error: too many critical sections left");
}
if (criticalSectionCount == 0)
{
TIMSK2 |= (1 << 1); // Activate scheduler
}
SREG |= gIEB;
}