├── .gitignore
├── config.h
├── README.md
├── avgbuffer.h
├── filtering.h
├── ringbuffer.h
├── log.h
├── software_debounce.h
├── can_common.h
├── command_accumulator.h
├── util.h
├── mcp_can.h
├── mcp_can_dfs.h
├── LICENSE
├── mcp_can.cpp
└── prius3charger_buck.ino
/.gitignore:
--------------------------------------------------------------------------------
1 | .*
2 | !.gitignore
3 | *~
4 | *.bak*
5 | *.o
6 | *.d
7 | *.elf
8 | *.hex
9 | *.ll
10 | *.dump
11 | *.lst
12 | *.lss
13 | *.bin
14 | *.old
15 | old.*
16 |
17 | session.vim
18 |
19 | dump
20 | tmp
21 | old
22 | Log
23 | build
24 | local
25 |
26 |
--------------------------------------------------------------------------------
/config.h:
--------------------------------------------------------------------------------
1 | /*
2 | Part of prius3charger_buck
3 | Copyright (c) 2020 Perttu "celeron55" Ahola
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | #pragma once
20 |
21 | #define CONSOLE Serial
22 |
23 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # prius3charger_buck
2 |
3 | Prius Gen 3 buck/boost converter charger controller - buck mode charging
4 |
5 | For atmega328 on damienmaguire/Prius-Gen3-Inverter version V1c
6 |
7 | See comments in [prius3charger_buck.ino](prius3charger_buck.ino) for documentation.
8 |
9 | You can show appreciation of this work with money here: https://www.paypal.me/celeron55
10 |
11 | This program is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | This program is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 |
21 | You should have received a copy of the GNU General Public License
22 | along with this program. If not, see .
23 |
24 |
--------------------------------------------------------------------------------
/avgbuffer.h:
--------------------------------------------------------------------------------
1 | /*
2 | Part of prius3charger_buck
3 | Copyright (c) 2020 Perttu "celeron55" Ahola
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | #pragma once
20 | #include "ringbuffer.h"
21 |
22 | template
23 | struct AvgBuffer
24 | {
25 | RingBuffer2 buf;
26 | sumT sum = 0;
27 |
28 | void push(const T &v)
29 | {
30 | if(buf.full()){
31 | sum -= buf.pop();
32 | }
33 | buf.push(v);
34 | sum += v;
35 | }
36 |
37 | T avg()
38 | {
39 | return sum / buf.size();
40 | }
41 |
42 | sumT avg(sumT multiplier)
43 | {
44 | return (sum * multiplier) / buf.size();
45 | }
46 |
47 | void reset()
48 | {
49 | buf.reset();
50 | sum = 0;
51 | }
52 | };
53 |
54 |
--------------------------------------------------------------------------------
/filtering.h:
--------------------------------------------------------------------------------
1 | /*
2 | Part of prius3charger_buck
3 | Copyright (c) 2020 Perttu "celeron55" Ahola
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | #pragma once
20 |
21 | template
22 | struct DigitalNoiseFilter
23 | {
24 | int c = 0;
25 | bool filtered_v = false;
26 |
27 | bool feed(bool v)
28 | {
29 | if(v){
30 | if(c < 0)
31 | c = 0;
32 | if(c < LIM_RISE)
33 | c++;
34 | if(c == LIM_RISE)
35 | filtered_v = true;
36 | } else {
37 | if(c > 0)
38 | c = 0;
39 | if(c > -LIM_FALL)
40 | c--;
41 | if(c == -LIM_FALL)
42 | filtered_v = false;
43 | }
44 | return filtered_v;
45 | }
46 |
47 | bool get()
48 | {
49 | return filtered_v;
50 | }
51 |
52 | void reset(bool value)
53 | {
54 | c = 0;
55 | filtered_v = value;
56 | }
57 | };
58 |
--------------------------------------------------------------------------------
/ringbuffer.h:
--------------------------------------------------------------------------------
1 | /*
2 | Part of prius3charger_buck
3 | Copyright (c) 2020 Perttu "celeron55" Ahola
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | #pragma once
20 |
21 | template
22 | struct RingBuffer2
23 | {
24 | T data[S];
25 | size_t start = 0;
26 | size_t end = 0;
27 | size_t size_ = 0;
28 |
29 | void push(const T &v) {
30 | if(end == S)
31 | end = 0;
32 | data[end++] = v;
33 | if(size_ == S){
34 | start++;
35 | if(start == S)
36 | start = 0;
37 | } else {
38 | size_++;
39 | }
40 | }
41 |
42 | T pop(){
43 | if(size_ == 0)
44 | return 0;
45 | T v = data[start++];
46 | if(start == S)
47 | start = 0;
48 | size_--;
49 | return v;
50 | }
51 |
52 | T& operator[] (size_t i){
53 | i += start;
54 | if(i >= S)
55 | i -= S;
56 | return data[i];
57 | }
58 |
59 | bool full() const {
60 | return size_ == S;
61 | }
62 |
63 | size_t size() const {
64 | return size_;
65 | }
66 |
67 | void reset(){
68 | start = 0;
69 | end = 0;
70 | size_ = 0;
71 | }
72 | };
73 |
--------------------------------------------------------------------------------
/log.h:
--------------------------------------------------------------------------------
1 | /*
2 | Part of prius3charger_buck
3 | Copyright (c) 2020 Perttu "celeron55" Ahola
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | #pragma once
20 |
21 | static char log_format_buf[17];
22 |
23 | static void log_print_timestamp()
24 | {
25 | uint32_t t = millis();
26 | int ms = t % 1000;
27 | t /= 1000;
28 | int s = t % 60;
29 | t /= 60;
30 | int m = t % 60;
31 | t /= 60;
32 | int h = t;
33 | if(h == 0 && m == 0)
34 | snprintf(log_format_buf, sizeof log_format_buf, "%02i.%03is: ", s, ms);
35 | else if(h == 0)
36 | snprintf(log_format_buf, sizeof log_format_buf, "%02im%02i.%03is: ", m, s, ms);
37 | else
38 | snprintf(log_format_buf, sizeof log_format_buf, "%02ih%02im%02i.%03is: ", h, m, s, ms);
39 | CONSOLE.print(log_format_buf);
40 | }
41 |
42 | static void log_println(const char *line)
43 | {
44 | log_print_timestamp();
45 | CONSOLE.println(line);
46 | }
47 |
48 | static void log_println_P(const char *line)
49 | {
50 | log_print_timestamp();
51 | CONSOLE.println((__FlashStringHelper*)line);
52 | }
53 |
54 | #define log_println_f(x) log_println_P(PSTR(x))
55 |
56 |
--------------------------------------------------------------------------------
/software_debounce.h:
--------------------------------------------------------------------------------
1 | /*
2 | Part of prius3charger_buck
3 | Copyright (c) 2020 Perttu "celeron55" Ahola
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | #pragma once
20 | #include "filtering.h"
21 |
22 | template
23 | struct SoftwareDebouncePin
24 | {
25 | DigitalNoiseFilter filter;
26 |
27 | SoftwareDebouncePin()
28 | {
29 | (void)read();
30 | }
31 |
32 | // Reads value from hardware and returns it filtered
33 | bool read()
34 | {
35 | for(uint8_t i=0; i
49 | struct SoftwareDebounceAnalogPin
50 | {
51 | DigitalNoiseFilter filter;
52 |
53 | SoftwareDebounceAnalogPin()
54 | {
55 | (void)read();
56 | }
57 |
58 | // Reads value from hardware and returns it filtered
59 | bool read()
60 | {
61 | for(uint8_t i=0; i= 300);
63 | }
64 | return filter.get();
65 | }
66 |
67 | // Gets last value without reading it from hardware
68 | bool get()
69 | {
70 | return filter.get();
71 | }
72 | };
73 |
--------------------------------------------------------------------------------
/can_common.h:
--------------------------------------------------------------------------------
1 | /*
2 | MIT License
3 |
4 | Copyright (c) 2017 Collin Kidder
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in all
14 | copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 | SOFTWARE.
23 | */
24 |
25 | #pragma once
26 | #include
27 |
28 | //This structure presupposes little endian mode. If you use it on a big endian processor you're going to have a bad time.
29 | typedef union {
30 | uint64_t value;
31 | struct {
32 | uint32_t low;
33 | uint32_t high;
34 | };
35 | struct {
36 | uint16_t s0;
37 | uint16_t s1;
38 | uint16_t s2;
39 | uint16_t s3;
40 | };
41 | uint8_t bytes[8];
42 | uint8_t byte[8]; //alternate name so you can omit the s if you feel it makes more sense
43 | } BytesUnion;
44 |
45 | typedef struct
46 | {
47 | uint32_t id = 0; // EID if ide set, SID otherwise
48 | uint32_t fid = 0; // family ID
49 | uint8_t rtr = 0; // Remote Transmission Request
50 | uint8_t priority = 0; // Priority but only important for TX frames and then only for special uses.
51 | uint8_t extended = 0; // Extended ID flag
52 | uint16_t time = 0; // CAN timer value when mailbox message was received.
53 | uint8_t length = 0; // Number of data bytes
54 | BytesUnion data; // 64 bits - lots of ways to access it.
55 | } CAN_FRAME;
56 |
--------------------------------------------------------------------------------
/command_accumulator.h:
--------------------------------------------------------------------------------
1 | /*
2 | Part of prius3charger_buck
3 | Copyright (c) 2020 Perttu "celeron55" Ahola
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | #pragma once
20 |
21 | template
22 | struct CommandAccumulator
23 | {
24 | char buffer[T_buf_size];
25 | size_t next_i;
26 | bool overflow;
27 | bool ready;
28 |
29 | CommandAccumulator()
30 | {
31 | reset();
32 | }
33 |
34 | void reset()
35 | {
36 | memset(buffer, 0, T_buf_size);
37 | next_i = 0;
38 | overflow = false;
39 | ready = false;
40 | }
41 |
42 | bool put_char(char c)
43 | {
44 | if(ready){
45 | reset();
46 | }
47 | // Support backspace for convenience when testing
48 | if(c == 127){
49 | if(next_i != 0){
50 | next_i--;
51 | buffer[next_i] = 0;
52 | overflow = false;
53 | }
54 | return false;
55 | }
56 | // Check this first to resolve overflows at newline
57 | // NOTE: \r should be accepted as end-of-command because serial
58 | // terminals that's the enter key.
59 | if(c == '\n' || c == '\r'){
60 | if(overflow){
61 | reset();
62 | return false;
63 | } else if(next_i == 0){
64 | // Ignore initial newlines
65 | return false;
66 | } else {
67 | ready = true;
68 | return true;
69 | }
70 | }
71 | if(next_i == T_buf_size){
72 | overflow = true;
73 | return false; // Can't do much
74 | }
75 | buffer[next_i++] = c;
76 | return false;
77 | }
78 |
79 | template
80 | bool read(T_serial &serial)
81 | {
82 | while(serial.available()){
83 | char c = serial.read();
84 | if(put_char(c))
85 | return true;
86 | }
87 | return false;
88 | }
89 |
90 | const char* command()
91 | {
92 | return buffer;
93 | }
94 | };
95 |
--------------------------------------------------------------------------------
/util.h:
--------------------------------------------------------------------------------
1 | /*
2 | Part of prius3charger_buck
3 | Copyright (c) 2020 Perttu "celeron55" Ahola
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | #include
20 |
21 | #define NUM_ELEMS(x) (sizeof (x) / sizeof (x)[0])
22 |
23 | static unsigned long timestamp_age(unsigned long timestamp_ms)
24 | {
25 | return millis() - timestamp_ms;
26 | }
27 |
28 | static bool timestamp_younger_than(unsigned long timestamp_ms, unsigned long max_age)
29 | {
30 | // Timestamp is assumed to be initialized to 0. This means that a timestamp
31 | // of 0 is infinitely old.
32 | if(timestamp_ms == 0)
33 | return false;
34 | return timestamp_age(timestamp_ms) < max_age;
35 | }
36 |
37 | static int8_t fahrenheit_to_celsius(uint16_t fahrenheit)
38 | {
39 | int16_t result = ((int16_t)fahrenheit - 32) * 5 / 9;
40 | if(result < -128)
41 | return -128;
42 | if(result > 127)
43 | return 127;
44 | return result;
45 | }
46 |
47 | static bool ENM_compare_and_update(unsigned long &t0, const unsigned long &interval)
48 | {
49 | bool trigger_now = timestamp_age(t0) >= interval;
50 | if(trigger_now)
51 | t0 = millis();
52 | return trigger_now;
53 | }
54 |
55 | #define EVERY_N_MILLISECONDS(ms) for(static unsigned long t0 = 0; ENM_compare_and_update(t0, ms); )
56 |
57 | #define REPORT_BOOL(var) \
58 | {\
59 | static bool reported_value = false;\
60 | if(var != reported_value || console_report_all_values){\
61 | log_print_timestamp();\
62 | CONSOLE.print(F(">> "#var" = "));\
63 | if(var)\
64 | CONSOLE.println(F("TRUE"));\
65 | else\
66 | CONSOLE.println(F("FALSE"));\
67 | reported_value = var;\
68 | }\
69 | }
70 |
71 | #define REPORT_UINT8(var) \
72 | {\
73 | static uint8_t reported_value = 0;\
74 | if(var != reported_value){\
75 | log_print_timestamp();\
76 | CONSOLE.print(F(">> "#var" = "));\
77 | CONSOLE.println(var);\
78 | reported_value = var;\
79 | }\
80 | }
81 |
82 | #define REPORT_UINT16(var) \
83 | {\
84 | static uint16_t reported_value = 0;\
85 | if(var != reported_value || console_report_all_values){\
86 | log_print_timestamp();\
87 | CONSOLE.print(F(">> "#var" = "));\
88 | CONSOLE.println(var);\
89 | reported_value = var;\
90 | }\
91 | }
92 |
93 | #define REPORT_INT16(var) \
94 | {\
95 | static int16_t reported_value = 0;\
96 | if(var != reported_value || console_report_all_values){\
97 | log_print_timestamp();\
98 | CONSOLE.print(F(">> "#var" = "));\
99 | CONSOLE.println(var);\
100 | reported_value = var;\
101 | }\
102 | }
103 |
104 | #define REPORT_UINT8_HYS(var, hys) \
105 | {\
106 | static uint8_t reported_value = 0;\
107 | if(abs(((int16_t)var - (int16_t)reported_value)) > (hys) || console_report_all_values){\
108 | log_print_timestamp();\
109 | CONSOLE.print(F(">> "#var" = "));\
110 | CONSOLE.println(var);\
111 | reported_value = var;\
112 | }\
113 | }
114 |
115 | #define REPORT_UINT16_HYS(var, hys) \
116 | {\
117 | static uint16_t reported_value = 0;\
118 | if(abs(((int32_t)var - (int32_t)reported_value)) > (hys) || console_report_all_values){\
119 | log_print_timestamp();\
120 | CONSOLE.print(F(">> "#var" = "));\
121 | CONSOLE.println(var);\
122 | reported_value = var;\
123 | }\
124 | }
125 |
126 | #define REPORT_INT16_HYS(var, hys) \
127 | {\
128 | static int16_t reported_value = 0;\
129 | if(abs((int16_t)((int32_t)var - (int32_t)reported_value)) > (hys) || console_report_all_values){\
130 | log_print_timestamp();\
131 | CONSOLE.print(F(">> "#var" = "));\
132 | CONSOLE.println(var);\
133 | reported_value = var;\
134 | }\
135 | }
136 |
137 | #define REPORT_UINT16_FORMAT(var, hys, mul, unit) \
138 | {\
139 | static uint16_t reported_value = 0;\
140 | if(abs((int16_t)((int32_t)var - (int32_t)reported_value)) > (hys) || console_report_all_values){\
141 | log_print_timestamp();\
142 | CONSOLE.print(F(">> "#var" = "));\
143 | CONSOLE.print((float)var * mul);\
144 | CONSOLE.println(F(unit));\
145 | reported_value = var;\
146 | }\
147 | }
148 |
149 | #define REPORT_INT16_FORMAT(var, hys, mul, unit) \
150 | {\
151 | static int16_t reported_value = 0;\
152 | if(abs(var - reported_value) > (hys) || console_report_all_values){\
153 | log_print_timestamp();\
154 | CONSOLE.print(F(">> "#var" = "));\
155 | CONSOLE.print((float)var * mul);\
156 | CONSOLE.println(F(unit));\
157 | reported_value = var;\
158 | }\
159 | }
160 |
161 | #define REPORT_ENUM(var, names) \
162 | {\
163 | static uint8_t reported_value = 0;\
164 | if(var != reported_value || console_report_all_values){\
165 | log_print_timestamp();\
166 | CONSOLE.print(F(">> "#var" = "));\
167 | CONSOLE.println(names[var]);\
168 | reported_value = var;\
169 | }\
170 | }
171 |
172 | #define REPORT_ENUM_PROGMEM(var, names) \
173 | {\
174 | static uint8_t reported_value = 0;\
175 | if(var != reported_value || console_report_all_values){\
176 | log_print_timestamp();\
177 | CONSOLE.print(F(">> "#var" = "));\
178 | CONSOLE.println((__FlashStringHelper*)pgm_read_word(&names[var]));\
179 | reported_value = var;\
180 | }\
181 | }
182 |
183 | #define REPORT_UINT16_BITMAP(var, num_bits, names) \
184 | {\
185 | static uint16_t reported_value = 0;\
186 | if(var != reported_value){\
187 | log_print_timestamp();\
188 | CONSOLE.print(F(">> "#var" = "));\
189 | for(uint16_t i=0; i max)
206 | return max;
207 | return v;
208 | }
209 |
210 | static int16_t limit_int16(int16_t v, int16_t min, int16_t max)
211 | {
212 | if(v < min)
213 | return min;
214 | if(v > max)
215 | return max;
216 | return v;
217 | }
218 |
219 | static int32_t limit_int32(int32_t v, int32_t min, int32_t max)
220 | {
221 | if(v < min)
222 | return min;
223 | if(v > max)
224 | return max;
225 | return v;
226 | }
227 |
--------------------------------------------------------------------------------
/mcp_can.h:
--------------------------------------------------------------------------------
1 | /*
2 | mcp_can.h
3 | 2012 Copyright (c) Seeed Technology Inc. All right reserved.
4 | 2017 Copyright (c) Cory J. Fowler All Rights Reserved.
5 |
6 | Author:Loovee
7 | Contributor: Cory J. Fowler
8 | 2017-09-25
9 | This library is free software; you can redistribute it and/or
10 | modify it under the terms of the GNU Lesser General Public
11 | License as published by the Free Software Foundation; either
12 | version 2.1 of the License, or (at your option) any later version.
13 |
14 | This library is distributed in the hope that it will be useful,
15 | but WITHOUT ANY WARRANTY; without even the implied warranty of
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 | Lesser General Public License for more details.
18 |
19 | You should have received a copy of the GNU Lesser General Public
20 | License along with this library; if not, write to the Free Software
21 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-
22 | 1301 USA
23 | */
24 | #ifndef _MCP2515_H_
25 | #define _MCP2515_H_
26 |
27 | #include "mcp_can_dfs.h"
28 | #define MAX_CHAR_IN_MESSAGE 8
29 |
30 | class MCP_CAN
31 | {
32 | private:
33 |
34 | INT8U m_nExtFlg; // Identifier Type
35 | // Extended (29 bit) or Standard (11 bit)
36 | INT32U m_nID; // CAN ID
37 | INT8U m_nDlc; // Data Length Code
38 | INT8U m_nDta[MAX_CHAR_IN_MESSAGE]; // Data array
39 | INT8U m_nRtr; // Remote request flag
40 | INT8U m_nfilhit; // The number of the filter that matched the message
41 | INT8U MCPCS; // Chip Select pin number
42 | INT8U mcpMode; // Mode to return to after configurations are performed.
43 |
44 |
45 | /*********************************************************************************************************
46 | * mcp2515 driver function
47 | *********************************************************************************************************/
48 | // private:
49 | private:
50 |
51 | void mcp2515_reset(void); // Soft Reset MCP2515
52 |
53 | INT8U mcp2515_readRegister(const INT8U address); // Read MCP2515 register
54 |
55 | void mcp2515_readRegisterS(const INT8U address, // Read MCP2515 successive registers
56 | INT8U values[],
57 | const INT8U n);
58 |
59 | void mcp2515_setRegister(const INT8U address, // Set MCP2515 register
60 | const INT8U value);
61 |
62 | void mcp2515_setRegisterS(const INT8U address, // Set MCP2515 successive registers
63 | const INT8U values[],
64 | const INT8U n);
65 |
66 | void mcp2515_initCANBuffers(void);
67 |
68 | void mcp2515_modifyRegister(const INT8U address, // Set specific bit(s) of a register
69 | const INT8U mask,
70 | const INT8U data);
71 |
72 | INT8U mcp2515_readStatus(void); // Read MCP2515 Status
73 | INT8U mcp2515_setCANCTRL_Mode(const INT8U newmode); // Set mode
74 | INT8U mcp2515_configRate(const INT8U canSpeed, // Set baud rate
75 | const INT8U canClock);
76 |
77 | INT8U mcp2515_init(const INT8U canIDMode, // Initialize Controller
78 | const INT8U canSpeed,
79 | const INT8U canClock);
80 |
81 | void mcp2515_write_mf( const INT8U mcp_addr, // Write CAN Mask or Filter
82 | const INT8U ext,
83 | const INT32U id );
84 |
85 | void mcp2515_write_id( const INT8U mcp_addr, // Write CAN ID
86 | const INT8U ext,
87 | const INT32U id );
88 |
89 | void mcp2515_read_id( const INT8U mcp_addr, // Read CAN ID
90 | INT8U* ext,
91 | INT32U* id );
92 |
93 | void mcp2515_write_canMsg( const INT8U buffer_sidh_addr ); // Write CAN message
94 | void mcp2515_read_canMsg( const INT8U buffer_sidh_addr); // Read CAN message
95 | INT8U mcp2515_getNextFreeTXBuf(INT8U *txbuf_n); // Find empty transmit buffer
96 |
97 | /*********************************************************************************************************
98 | * CAN operator function
99 | *********************************************************************************************************/
100 |
101 | INT8U setMsg(INT32U id, INT8U rtr, INT8U ext, INT8U len, const INT8U *pData); // Set message
102 | INT8U clearMsg(); // Clear all message to zero
103 | INT8U readMsg(); // Read message
104 | INT8U sendMsg(); // Send message
105 |
106 | public:
107 | MCP_CAN(INT8U _CS);
108 | INT8U begin(INT8U idmodeset, INT8U speedset, INT8U clockset); // Initialize controller parameters
109 | INT8U init_Mask(INT8U num, INT8U ext, INT32U ulData); // Initialize Mask(s)
110 | INT8U init_Mask(INT8U num, INT32U ulData); // Initialize Mask(s)
111 | INT8U init_Filt(INT8U num, INT8U ext, INT32U ulData); // Initialize Filter(s)
112 | INT8U init_Filt(INT8U num, INT32U ulData); // Initialize Filter(s)
113 | INT8U setMode(INT8U opMode); // Set operational mode
114 | INT8U sendMsgBuf(INT32U id, INT8U ext, INT8U len, const INT8U *buf); // Send message to transmit buffer
115 | INT8U sendMsgBuf(INT32U id, INT8U len, const INT8U *buf); // Send message to transmit buffer
116 | INT8U readMsgBuf(INT32U *id, INT8U *ext, INT8U *len, INT8U *buf); // Read message from receive buffer
117 | INT8U readMsgBuf(INT32U *id, INT8U *len, INT8U *buf); // Read message from receive buffer
118 | INT8U checkReceive(void); // Check for received data
119 | INT8U checkError(void); // Check for errors
120 | INT8U getError(void); // Check for errors
121 | INT8U errorCountRX(void); // Get error count
122 | INT8U errorCountTX(void); // Get error count
123 | INT8U enOneShotTX(void); // Enable one-shot transmission
124 | INT8U disOneShotTX(void); // Disable one-shot transmission
125 | INT8U abortTX(void); // Abort queued transmission(s)
126 | INT8U setGPO(INT8U data); // Sets GPO
127 | INT8U getGPI(void); // Reads GPI
128 | };
129 |
130 | #endif
131 | /*********************************************************************************************************
132 | * END FILE
133 | *********************************************************************************************************/
134 |
--------------------------------------------------------------------------------
/mcp_can_dfs.h:
--------------------------------------------------------------------------------
1 | /*
2 | mcp_can_dfs.h
3 | 2012 Copyright (c) Seeed Technology Inc. All right reserved.
4 | 2017 Copyright (c) Cory J. Fowler All Rights Reserved.
5 |
6 | Author:Loovee
7 | Contributor: Cory J. Fowler
8 | 2017-09-25
9 | This library is free software; you can redistribute it and/or
10 | modify it under the terms of the GNU Lesser General Public
11 | License as published by the Free Software Foundation; either
12 | version 2.1 of the License, or (at your option) any later version.
13 |
14 | This library is distributed in the hope that it will be useful,
15 | but WITHOUT ANY WARRANTY; without even the implied warranty of
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 | Lesser General Public License for more details.
18 |
19 | You should have received a copy of the GNU Lesser General Public
20 | License along with this library; if not, write to the Free Software
21 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-
22 | 1301 USA
23 | */
24 | #ifndef _MCP2515DFS_H_
25 | #define _MCP2515DFS_H_
26 |
27 | #include
28 | #include
29 | #include
30 |
31 | #ifndef INT32U
32 | #define INT32U unsigned long
33 | #endif
34 |
35 | #ifndef INT8U
36 | #define INT8U byte
37 | #endif
38 |
39 | // if print debug information
40 | #define DEBUG_MODE 0
41 |
42 | /*
43 | * Begin mt
44 | */
45 | #define TIMEOUTVALUE 50
46 | #define MCP_SIDH 0
47 | #define MCP_SIDL 1
48 | #define MCP_EID8 2
49 | #define MCP_EID0 3
50 |
51 | #define MCP_TXB_EXIDE_M 0x08 /* In TXBnSIDL */
52 | #define MCP_DLC_MASK 0x0F /* 4 LSBits */
53 | #define MCP_RTR_MASK 0x40 /* (1<<6) Bit 6 */
54 |
55 | #define MCP_RXB_RX_ANY 0x60
56 | #define MCP_RXB_RX_EXT 0x40
57 | #define MCP_RXB_RX_STD 0x20
58 | #define MCP_RXB_RX_STDEXT 0x00
59 | #define MCP_RXB_RX_MASK 0x60
60 | #define MCP_RXB_BUKT_MASK (1<<2)
61 |
62 | /*
63 | ** Bits in the TXBnCTRL registers.
64 | */
65 | #define MCP_TXB_TXBUFE_M 0x80
66 | #define MCP_TXB_ABTF_M 0x40
67 | #define MCP_TXB_MLOA_M 0x20
68 | #define MCP_TXB_TXERR_M 0x10
69 | #define MCP_TXB_TXREQ_M 0x08
70 | #define MCP_TXB_TXIE_M 0x04
71 | #define MCP_TXB_TXP10_M 0x03
72 |
73 | #define MCP_TXB_RTR_M 0x40 /* In TXBnDLC */
74 | #define MCP_RXB_IDE_M 0x08 /* In RXBnSIDL */
75 | #define MCP_RXB_RTR_M 0x40 /* In RXBnDLC */
76 |
77 | #define MCP_STAT_RXIF_MASK (0x03)
78 | #define MCP_STAT_RX0IF (1<<0)
79 | #define MCP_STAT_RX1IF (1<<1)
80 |
81 | #define MCP_EFLG_RX1OVR (1<<7)
82 | #define MCP_EFLG_RX0OVR (1<<6)
83 | #define MCP_EFLG_TXBO (1<<5)
84 | #define MCP_EFLG_TXEP (1<<4)
85 | #define MCP_EFLG_RXEP (1<<3)
86 | #define MCP_EFLG_TXWAR (1<<2)
87 | #define MCP_EFLG_RXWAR (1<<1)
88 | #define MCP_EFLG_EWARN (1<<0)
89 | #define MCP_EFLG_ERRORMASK (0xF8) /* 5 MS-Bits */
90 |
91 | #define MCP_BxBFS_MASK 0x30
92 | #define MCP_BxBFE_MASK 0x0C
93 | #define MCP_BxBFM_MASK 0x03
94 |
95 | #define MCP_BxRTS_MASK 0x38
96 | #define MCP_BxRTSM_MASK 0x07
97 |
98 | /*
99 | * Define MCP2515 register addresses
100 | */
101 | #define MCP_RXF0SIDH 0x00
102 | #define MCP_RXF0SIDL 0x01
103 | #define MCP_RXF0EID8 0x02
104 | #define MCP_RXF0EID0 0x03
105 | #define MCP_RXF1SIDH 0x04
106 | #define MCP_RXF1SIDL 0x05
107 | #define MCP_RXF1EID8 0x06
108 | #define MCP_RXF1EID0 0x07
109 | #define MCP_RXF2SIDH 0x08
110 | #define MCP_RXF2SIDL 0x09
111 | #define MCP_RXF2EID8 0x0A
112 | #define MCP_RXF2EID0 0x0B
113 | #define MCP_BFPCTRL 0x0C
114 | #define MCP_TXRTSCTRL 0x0D
115 | #define MCP_CANSTAT 0x0E
116 | #define MCP_CANCTRL 0x0F
117 | #define MCP_RXF3SIDH 0x10
118 | #define MCP_RXF3SIDL 0x11
119 | #define MCP_RXF3EID8 0x12
120 | #define MCP_RXF3EID0 0x13
121 | #define MCP_RXF4SIDH 0x14
122 | #define MCP_RXF4SIDL 0x15
123 | #define MCP_RXF4EID8 0x16
124 | #define MCP_RXF4EID0 0x17
125 | #define MCP_RXF5SIDH 0x18
126 | #define MCP_RXF5SIDL 0x19
127 | #define MCP_RXF5EID8 0x1A
128 | #define MCP_RXF5EID0 0x1B
129 | #define MCP_TEC 0x1C
130 | #define MCP_REC 0x1D
131 | #define MCP_RXM0SIDH 0x20
132 | #define MCP_RXM0SIDL 0x21
133 | #define MCP_RXM0EID8 0x22
134 | #define MCP_RXM0EID0 0x23
135 | #define MCP_RXM1SIDH 0x24
136 | #define MCP_RXM1SIDL 0x25
137 | #define MCP_RXM1EID8 0x26
138 | #define MCP_RXM1EID0 0x27
139 | #define MCP_CNF3 0x28
140 | #define MCP_CNF2 0x29
141 | #define MCP_CNF1 0x2A
142 | #define MCP_CANINTE 0x2B
143 | #define MCP_CANINTF 0x2C
144 | #define MCP_EFLG 0x2D
145 | #define MCP_TXB0CTRL 0x30
146 | #define MCP_TXB1CTRL 0x40
147 | #define MCP_TXB2CTRL 0x50
148 | #define MCP_RXB0CTRL 0x60
149 | #define MCP_RXB0SIDH 0x61
150 | #define MCP_RXB1CTRL 0x70
151 | #define MCP_RXB1SIDH 0x71
152 |
153 |
154 | #define MCP_TX_INT 0x1C /* Enable all transmit interrup ts */
155 | #define MCP_TX01_INT 0x0C /* Enable TXB0 and TXB1 interru pts */
156 | #define MCP_RX_INT 0x03 /* Enable receive interrupts */
157 | #define MCP_NO_INT 0x00 /* Disable all interrupts */
158 |
159 | #define MCP_TX01_MASK 0x14
160 | #define MCP_TX_MASK 0x54
161 |
162 | /*
163 | * Define SPI Instruction Set
164 | */
165 | #define MCP_WRITE 0x02
166 |
167 | #define MCP_READ 0x03
168 |
169 | #define MCP_BITMOD 0x05
170 |
171 | #define MCP_LOAD_TX0 0x40
172 | #define MCP_LOAD_TX1 0x42
173 | #define MCP_LOAD_TX2 0x44
174 |
175 | #define MCP_RTS_TX0 0x81
176 | #define MCP_RTS_TX1 0x82
177 | #define MCP_RTS_TX2 0x84
178 | #define MCP_RTS_ALL 0x87
179 |
180 | #define MCP_READ_RX0 0x90
181 | #define MCP_READ_RX1 0x94
182 |
183 | #define MCP_READ_STATUS 0xA0
184 |
185 | #define MCP_RX_STATUS 0xB0
186 |
187 | #define MCP_RESET 0xC0
188 |
189 |
190 | /*
191 | * CANCTRL Register Values
192 | */
193 | #define MCP_NORMAL 0x00
194 | #define MCP_SLEEP 0x20
195 | #define MCP_LOOPBACK 0x40
196 | #define MCP_LISTENONLY 0x60
197 | #define MODE_CONFIG 0x80
198 | #define MODE_POWERUP 0xE0
199 | #define MODE_MASK 0xE0
200 | #define ABORT_TX 0x10
201 | #define MODE_ONESHOT 0x08
202 | #define CLKOUT_ENABLE 0x04
203 | #define CLKOUT_DISABLE 0x00
204 | #define CLKOUT_PS1 0x00
205 | #define CLKOUT_PS2 0x01
206 | #define CLKOUT_PS4 0x02
207 | #define CLKOUT_PS8 0x03
208 |
209 |
210 | /*
211 | * CNF1 Register Values
212 | */
213 | #define SJW1 0x00
214 | #define SJW2 0x40
215 | #define SJW3 0x80
216 | #define SJW4 0xC0
217 |
218 |
219 | /*
220 | * CNF2 Register Values
221 | */
222 | #define BTLMODE 0x80
223 | #define SAMPLE_1X 0x00
224 | #define SAMPLE_3X 0x40
225 |
226 |
227 | /*
228 | * CNF3 Register Values
229 | */
230 | #define SOF_ENABLE 0x80
231 | #define SOF_DISABLE 0x00
232 | #define WAKFIL_ENABLE 0x40
233 | #define WAKFIL_DISABLE 0x00
234 |
235 |
236 | /*
237 | * CANINTF Register Bits
238 | */
239 | #define MCP_RX0IF 0x01
240 | #define MCP_RX1IF 0x02
241 | #define MCP_TX0IF 0x04
242 | #define MCP_TX1IF 0x08
243 | #define MCP_TX2IF 0x10
244 | #define MCP_ERRIF 0x20
245 | #define MCP_WAKIF 0x40
246 | #define MCP_MERRF 0x80
247 |
248 |
249 | /*
250 | * Speed 8M
251 | */
252 | #define MCP_8MHz_1000kBPS_CFG1 (0x00)
253 | #define MCP_8MHz_1000kBPS_CFG2 (0xC0) /* Enabled SAM bit */
254 | #define MCP_8MHz_1000kBPS_CFG3 (0x80) /* Sample point at 75% */
255 |
256 | #define MCP_8MHz_500kBPS_CFG1 (0x00)
257 | #define MCP_8MHz_500kBPS_CFG2 (0xD1) /* Enabled SAM bit */
258 | #define MCP_8MHz_500kBPS_CFG3 (0x81) /* Sample point at 75% */
259 |
260 | #define MCP_8MHz_250kBPS_CFG1 (0x80) /* Increased SJW */
261 | #define MCP_8MHz_250kBPS_CFG2 (0xE5) /* Enabled SAM bit */
262 | #define MCP_8MHz_250kBPS_CFG3 (0x83) /* Sample point at 75% */
263 |
264 | #define MCP_8MHz_200kBPS_CFG1 (0x80) /* Increased SJW */
265 | #define MCP_8MHz_200kBPS_CFG2 (0xF6) /* Enabled SAM bit */
266 | #define MCP_8MHz_200kBPS_CFG3 (0x84) /* Sample point at 75% */
267 |
268 | #define MCP_8MHz_125kBPS_CFG1 (0x81) /* Increased SJW */
269 | #define MCP_8MHz_125kBPS_CFG2 (0xE5) /* Enabled SAM bit */
270 | #define MCP_8MHz_125kBPS_CFG3 (0x83) /* Sample point at 75% */
271 |
272 | #define MCP_8MHz_100kBPS_CFG1 (0x81) /* Increased SJW */
273 | #define MCP_8MHz_100kBPS_CFG2 (0xF6) /* Enabled SAM bit */
274 | #define MCP_8MHz_100kBPS_CFG3 (0x84) /* Sample point at 75% */
275 |
276 | #define MCP_8MHz_80kBPS_CFG1 (0x84) /* Increased SJW */
277 | #define MCP_8MHz_80kBPS_CFG2 (0xD3) /* Enabled SAM bit */
278 | #define MCP_8MHz_80kBPS_CFG3 (0x81) /* Sample point at 75% */
279 |
280 | #define MCP_8MHz_50kBPS_CFG1 (0x84) /* Increased SJW */
281 | #define MCP_8MHz_50kBPS_CFG2 (0xE5) /* Enabled SAM bit */
282 | #define MCP_8MHz_50kBPS_CFG3 (0x83) /* Sample point at 75% */
283 |
284 | #define MCP_8MHz_40kBPS_CFG1 (0x84) /* Increased SJW */
285 | #define MCP_8MHz_40kBPS_CFG2 (0xF6) /* Enabled SAM bit */
286 | #define MCP_8MHz_40kBPS_CFG3 (0x84) /* Sample point at 75% */
287 |
288 | #define MCP_8MHz_33k3BPS_CFG1 (0x85) /* Increased SJW */
289 | #define MCP_8MHz_33k3BPS_CFG2 (0xF6) /* Enabled SAM bit */
290 | #define MCP_8MHz_33k3BPS_CFG3 (0x84) /* Sample point at 75% */
291 |
292 | #define MCP_8MHz_31k25BPS_CFG1 (0x87) /* Increased SJW */
293 | #define MCP_8MHz_31k25BPS_CFG2 (0xE5) /* Enabled SAM bit */
294 | #define MCP_8MHz_31k25BPS_CFG3 (0x83) /* Sample point at 75% */
295 |
296 | #define MCP_8MHz_20kBPS_CFG1 (0x89) /* Increased SJW */
297 | #define MCP_8MHz_20kBPS_CFG2 (0xF6) /* Enabled SAM bit */
298 | #define MCP_8MHz_20kBPS_CFG3 (0x84) /* Sample point at 75% */
299 |
300 | #define MCP_8MHz_10kBPS_CFG1 (0x93) /* Increased SJW */
301 | #define MCP_8MHz_10kBPS_CFG2 (0xF6) /* Enabled SAM bit */
302 | #define MCP_8MHz_10kBPS_CFG3 (0x84) /* Sample point at 75% */
303 |
304 | #define MCP_8MHz_5kBPS_CFG1 (0xA7) /* Increased SJW */
305 | #define MCP_8MHz_5kBPS_CFG2 (0xF6) /* Enabled SAM bit */
306 | #define MCP_8MHz_5kBPS_CFG3 (0x84) /* Sample point at 75% */
307 |
308 | /*
309 | * speed 16M
310 | */
311 | #define MCP_16MHz_1000kBPS_CFG1 (0x00)
312 | #define MCP_16MHz_1000kBPS_CFG2 (0xCA)
313 | #define MCP_16MHz_1000kBPS_CFG3 (0x81) /* Sample point at 75% */
314 |
315 | #define MCP_16MHz_500kBPS_CFG1 (0x40) /* Increased SJW */
316 | #define MCP_16MHz_500kBPS_CFG2 (0xE5)
317 | #define MCP_16MHz_500kBPS_CFG3 (0x83) /* Sample point at 75% */
318 |
319 | #define MCP_16MHz_250kBPS_CFG1 (0x41)
320 | #define MCP_16MHz_250kBPS_CFG2 (0xE5)
321 | #define MCP_16MHz_250kBPS_CFG3 (0x83) /* Sample point at 75% */
322 |
323 | #define MCP_16MHz_200kBPS_CFG1 (0x41) /* Increased SJW */
324 | #define MCP_16MHz_200kBPS_CFG2 (0xF6)
325 | #define MCP_16MHz_200kBPS_CFG3 (0x84) /* Sample point at 75% */
326 |
327 | #define MCP_16MHz_125kBPS_CFG1 (0x43) /* Increased SJW */
328 | #define MCP_16MHz_125kBPS_CFG2 (0xE5)
329 | #define MCP_16MHz_125kBPS_CFG3 (0x83) /* Sample point at 75% */
330 |
331 | #define MCP_16MHz_100kBPS_CFG1 (0x44) /* Increased SJW */
332 | #define MCP_16MHz_100kBPS_CFG2 (0xE5)
333 | #define MCP_16MHz_100kBPS_CFG3 (0x83) /* Sample point at 75% */
334 |
335 | #define MCP_16MHz_80kBPS_CFG1 (0x44) /* Increased SJW */
336 | #define MCP_16MHz_80kBPS_CFG2 (0xF6)
337 | #define MCP_16MHz_80kBPS_CFG3 (0x84) /* Sample point at 75% */
338 |
339 | #define MCP_16MHz_50kBPS_CFG1 (0x47) /* Increased SJW */
340 | #define MCP_16MHz_50kBPS_CFG2 (0xF6)
341 | #define MCP_16MHz_50kBPS_CFG3 (0x84) /* Sample point at 75% */
342 |
343 | #define MCP_16MHz_40kBPS_CFG1 (0x49) /* Increased SJW */
344 | #define MCP_16MHz_40kBPS_CFG2 (0xF6)
345 | #define MCP_16MHz_40kBPS_CFG3 (0x84) /* Sample point at 75% */
346 |
347 | #define MCP_16MHz_33k3BPS_CFG1 (0x4E)
348 | #define MCP_16MHz_33k3BPS_CFG2 (0xE5)
349 | #define MCP_16MHz_33k3BPS_CFG3 (0x83) /* Sample point at 75% */
350 |
351 | #define MCP_16MHz_20kBPS_CFG1 (0x53) /* Increased SJW */
352 | #define MCP_16MHz_20kBPS_CFG2 (0xF6)
353 | #define MCP_16MHz_20kBPS_CFG3 (0x84) /* Sample point at 75% */
354 |
355 | #define MCP_16MHz_10kBPS_CFG1 (0x67) /* Increased SJW */
356 | #define MCP_16MHz_10kBPS_CFG2 (0xF6)
357 | #define MCP_16MHz_10kBPS_CFG3 (0x84) /* Sample point at 75% */
358 |
359 | #define MCP_16MHz_5kBPS_CFG1 (0x3F)
360 | #define MCP_16MHz_5kBPS_CFG2 (0xFF)
361 | #define MCP_16MHz_5kBPS_CFG3 (0x87) /* Sample point at 68% */
362 |
363 | /*
364 | * speed 20M
365 | */
366 | #define MCP_20MHz_1000kBPS_CFG1 (0x00)
367 | #define MCP_20MHz_1000kBPS_CFG2 (0xD9)
368 | #define MCP_20MHz_1000kBPS_CFG3 (0x82) /* Sample point at 80% */
369 |
370 | #define MCP_20MHz_500kBPS_CFG1 (0x40) /* Increased SJW */
371 | #define MCP_20MHz_500kBPS_CFG2 (0xF6)
372 | #define MCP_20MHz_500kBPS_CFG3 (0x84) /* Sample point at 75% */
373 |
374 | #define MCP_20MHz_250kBPS_CFG1 (0x41) /* Increased SJW */
375 | #define MCP_20MHz_250kBPS_CFG2 (0xF6)
376 | #define MCP_20MHz_250kBPS_CFG3 (0x84) /* Sample point at 75% */
377 |
378 | #define MCP_20MHz_200kBPS_CFG1 (0x44) /* Increased SJW */
379 | #define MCP_20MHz_200kBPS_CFG2 (0xD3)
380 | #define MCP_20MHz_200kBPS_CFG3 (0x81) /* Sample point at 80% */
381 |
382 | #define MCP_20MHz_125kBPS_CFG1 (0x44) /* Increased SJW */
383 | #define MCP_20MHz_125kBPS_CFG2 (0xE5)
384 | #define MCP_20MHz_125kBPS_CFG3 (0x83) /* Sample point at 75% */
385 |
386 | #define MCP_20MHz_100kBPS_CFG1 (0x44) /* Increased SJW */
387 | #define MCP_20MHz_100kBPS_CFG2 (0xF6)
388 | #define MCP_20MHz_100kBPS_CFG3 (0x84) /* Sample point at 75% */
389 |
390 | #define MCP_20MHz_80kBPS_CFG1 (0xC4) /* Increased SJW */
391 | #define MCP_20MHz_80kBPS_CFG2 (0xFF)
392 | #define MCP_20MHz_80kBPS_CFG3 (0x87) /* Sample point at 68% */
393 |
394 | #define MCP_20MHz_50kBPS_CFG1 (0x49) /* Increased SJW */
395 | #define MCP_20MHz_50kBPS_CFG2 (0xF6)
396 | #define MCP_20MHz_50kBPS_CFG3 (0x84) /* Sample point at 75% */
397 |
398 | #define MCP_20MHz_40kBPS_CFG1 (0x18)
399 | #define MCP_20MHz_40kBPS_CFG2 (0xD3)
400 | #define MCP_20MHz_40kBPS_CFG3 (0x81) /* Sample point at 80% */
401 |
402 |
403 | #define MCPDEBUG (0)
404 | #define MCPDEBUG_TXBUF (0)
405 | #define MCP_N_TXBUFFERS (3)
406 |
407 | #define MCP_RXBUF_0 (MCP_RXB0SIDH)
408 | #define MCP_RXBUF_1 (MCP_RXB1SIDH)
409 |
410 | #define MCP2515_SELECT() digitalWrite(MCPCS, LOW)
411 | #define MCP2515_UNSELECT() digitalWrite(MCPCS, HIGH)
412 |
413 | #define MCP2515_OK (0)
414 | #define MCP2515_FAIL (1)
415 | #define MCP_ALLTXBUSY (2)
416 |
417 | #define CANDEBUG 1
418 |
419 | #define CANUSELOOP 0
420 |
421 | #define CANSENDTIMEOUT (200) /* milliseconds */
422 |
423 | /*
424 | * initial value of gCANAutoProcess
425 | */
426 | #define CANAUTOPROCESS (1)
427 | #define CANAUTOON (1)
428 | #define CANAUTOOFF (0)
429 |
430 | #define CAN_STDID (0)
431 | #define CAN_EXTID (1)
432 |
433 | #define CANDEFAULTIDENT (0x55CC)
434 | #define CANDEFAULTIDENTEXT (CAN_EXTID)
435 |
436 | #define MCP_STDEXT 0 /* Standard and Extended */
437 | #define MCP_STD 1 /* Standard IDs ONLY */
438 | #define MCP_EXT 2 /* Extended IDs ONLY */
439 | #define MCP_ANY 3 /* Disables Masks and Filters */
440 |
441 | #define MCP_20MHZ 0
442 | #define MCP_16MHZ 1
443 | #define MCP_8MHZ 2
444 |
445 | #define CAN_4K096BPS 0
446 | #define CAN_5KBPS 1
447 | #define CAN_10KBPS 2
448 | #define CAN_20KBPS 3
449 | #define CAN_31K25BPS 4
450 | #define CAN_33K3BPS 5
451 | #define CAN_40KBPS 6
452 | #define CAN_50KBPS 7
453 | #define CAN_80KBPS 8
454 | #define CAN_100KBPS 9
455 | #define CAN_125KBPS 10
456 | #define CAN_200KBPS 11
457 | #define CAN_250KBPS 12
458 | #define CAN_500KBPS 13
459 | #define CAN_1000KBPS 14
460 |
461 | #define CAN_OK (0)
462 | #define CAN_FAILINIT (1)
463 | #define CAN_FAILTX (2)
464 | #define CAN_MSGAVAIL (3)
465 | #define CAN_NOMSG (4)
466 | #define CAN_CTRLERROR (5)
467 | #define CAN_GETTXBFTIMEOUT (6)
468 | #define CAN_SENDMSGTIMEOUT (7)
469 | #define CAN_FAIL (0xff)
470 |
471 | #define CAN_MAX_CHAR_IN_MESSAGE (8)
472 |
473 | #endif
474 | /*********************************************************************************************************
475 | END FILE
476 | *********************************************************************************************************/
477 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/mcp_can.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | mcp_can.cpp
3 | 2012 Copyright (c) Seeed Technology Inc. All right reserved.
4 | 2017 Copyright (c) Cory J. Fowler All Rights Reserved.
5 |
6 | Author: Loovee
7 | Contributor: Cory J. Fowler
8 | 2017-09-25
9 | This library is free software; you can redistribute it and/or
10 | modify it under the terms of the GNU Lesser General Public
11 | License as published by the Free Software Foundation; either
12 | version 2.1 of the License, or (at your option) any later version.
13 |
14 | This library is distributed in the hope that it will be useful,
15 | but WITHOUT ANY WARRANTY; without even the implied warranty of
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 | Lesser General Public License for more details.
18 |
19 | You should have received a copy of the GNU Lesser General Public
20 | License along with this library; if not, write to the Free Software
21 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-
22 | 1301 USA
23 | */
24 | #include "mcp_can.h"
25 |
26 | #define spi_readwrite SPI.transfer
27 | #define spi_read() spi_readwrite(0x00)
28 |
29 | /*********************************************************************************************************
30 | ** Function name: mcp2515_reset
31 | ** Descriptions: Performs a software reset
32 | *********************************************************************************************************/
33 | void MCP_CAN::mcp2515_reset(void)
34 | {
35 | SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
36 | MCP2515_SELECT();
37 | spi_readwrite(MCP_RESET);
38 | MCP2515_UNSELECT();
39 | SPI.endTransaction();
40 | delayMicroseconds(10);
41 | }
42 |
43 | /*********************************************************************************************************
44 | ** Function name: mcp2515_readRegister
45 | ** Descriptions: Read data register
46 | *********************************************************************************************************/
47 | INT8U MCP_CAN::mcp2515_readRegister(const INT8U address)
48 | {
49 | INT8U ret;
50 |
51 | SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
52 | MCP2515_SELECT();
53 | spi_readwrite(MCP_READ);
54 | spi_readwrite(address);
55 | ret = spi_read();
56 | MCP2515_UNSELECT();
57 | SPI.endTransaction();
58 |
59 | return ret;
60 | }
61 |
62 | /*********************************************************************************************************
63 | ** Function name: mcp2515_readRegisterS
64 | ** Descriptions: Reads sucessive data registers
65 | *********************************************************************************************************/
66 | void MCP_CAN::mcp2515_readRegisterS(const INT8U address, INT8U values[], const INT8U n)
67 | {
68 | INT8U i;
69 | SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
70 | MCP2515_SELECT();
71 | spi_readwrite(MCP_READ);
72 | spi_readwrite(address);
73 | // mcp2515 has auto-increment of address-pointer
74 | for (i=0; i TXBnD7 */
474 | a1 = MCP_TXB0CTRL;
475 | a2 = MCP_TXB1CTRL;
476 | a3 = MCP_TXB2CTRL;
477 | for (i = 0; i < 14; i++) { /* in-buffer loop */
478 | mcp2515_setRegister(a1, 0);
479 | mcp2515_setRegister(a2, 0);
480 | mcp2515_setRegister(a3, 0);
481 | a1++;
482 | a2++;
483 | a3++;
484 | }
485 | mcp2515_setRegister(MCP_RXB0CTRL, 0);
486 | mcp2515_setRegister(MCP_RXB1CTRL, 0);
487 | }
488 |
489 | /*********************************************************************************************************
490 | ** Function name: mcp2515_init
491 | ** Descriptions: Initialize the controller
492 | *********************************************************************************************************/
493 | INT8U MCP_CAN::mcp2515_init(const INT8U canIDMode, const INT8U canSpeed, const INT8U canClock)
494 | {
495 |
496 | INT8U res;
497 |
498 | mcp2515_reset();
499 |
500 | mcpMode = MCP_LOOPBACK;
501 |
502 | res = mcp2515_setCANCTRL_Mode(MODE_CONFIG);
503 | if(res > 0)
504 | {
505 | #if DEBUG_MODE
506 | Serial.print("Entering Configuration Mode Failure...\r\n");
507 | #endif
508 | return res;
509 | }
510 | #if DEBUG_MODE
511 | Serial.print("Entering Configuration Mode Successful!\r\n");
512 | #endif
513 |
514 | // Set Baudrate
515 | if(mcp2515_configRate(canSpeed, canClock))
516 | {
517 | #if DEBUG_MODE
518 | Serial.print("Setting Baudrate Failure...\r\n");
519 | #endif
520 | return res;
521 | }
522 | #if DEBUG_MODE
523 | Serial.print("Setting Baudrate Successful!\r\n");
524 | #endif
525 |
526 | if ( res == MCP2515_OK ) {
527 |
528 | /* init canbuffers */
529 | mcp2515_initCANBuffers();
530 |
531 | /* interrupt mode */
532 | mcp2515_setRegister(MCP_CANINTE, MCP_RX0IF | MCP_RX1IF);
533 |
534 | //Sets BF pins as GPO
535 | mcp2515_setRegister(MCP_BFPCTRL,MCP_BxBFS_MASK | MCP_BxBFE_MASK);
536 | //Sets RTS pins as GPI
537 | mcp2515_setRegister(MCP_TXRTSCTRL,0x00);
538 |
539 | switch(canIDMode)
540 | {
541 | case (MCP_ANY):
542 | mcp2515_modifyRegister(MCP_RXB0CTRL,
543 | MCP_RXB_RX_MASK | MCP_RXB_BUKT_MASK,
544 | MCP_RXB_RX_ANY | MCP_RXB_BUKT_MASK);
545 | mcp2515_modifyRegister(MCP_RXB1CTRL, MCP_RXB_RX_MASK,
546 | MCP_RXB_RX_ANY);
547 | break;
548 | /* The followingn two functions of the MCP2515 do not work, there is a bug in the silicon.
549 | case (MCP_STD):
550 | mcp2515_modifyRegister(MCP_RXB0CTRL,
551 | MCP_RXB_RX_MASK | MCP_RXB_BUKT_MASK,
552 | MCP_RXB_RX_STD | MCP_RXB_BUKT_MASK );
553 | mcp2515_modifyRegister(MCP_RXB1CTRL, MCP_RXB_RX_MASK,
554 | MCP_RXB_RX_STD);
555 | break;
556 |
557 | case (MCP_EXT):
558 | mcp2515_modifyRegister(MCP_RXB0CTRL,
559 | MCP_RXB_RX_MASK | MCP_RXB_BUKT_MASK,
560 | MCP_RXB_RX_EXT | MCP_RXB_BUKT_MASK );
561 | mcp2515_modifyRegister(MCP_RXB1CTRL, MCP_RXB_RX_MASK,
562 | MCP_RXB_RX_EXT);
563 | break;
564 | */
565 | case (MCP_STDEXT):
566 | mcp2515_modifyRegister(MCP_RXB0CTRL,
567 | MCP_RXB_RX_MASK | MCP_RXB_BUKT_MASK,
568 | MCP_RXB_RX_STDEXT | MCP_RXB_BUKT_MASK );
569 | mcp2515_modifyRegister(MCP_RXB1CTRL, MCP_RXB_RX_MASK,
570 | MCP_RXB_RX_STDEXT);
571 | break;
572 |
573 | default:
574 | #if DEBUG_MODE
575 | Serial.print("`Setting ID Mode Failure...\r\n");
576 | #endif
577 | return MCP2515_FAIL;
578 | break;
579 | }
580 |
581 |
582 | res = mcp2515_setCANCTRL_Mode(mcpMode);
583 | if(res)
584 | {
585 | #if DEBUG_MODE
586 | Serial.print("Returning to Previous Mode Failure...\r\n");
587 | #endif
588 | return res;
589 | }
590 |
591 | }
592 | return res;
593 |
594 | }
595 |
596 | /*********************************************************************************************************
597 | ** Function name: mcp2515_write_id
598 | ** Descriptions: Write CAN ID
599 | *********************************************************************************************************/
600 | void MCP_CAN::mcp2515_write_id( const INT8U mcp_addr, const INT8U ext, const INT32U id )
601 | {
602 | uint16_t canid;
603 | INT8U tbufdata[4];
604 |
605 | canid = (uint16_t)(id & 0x0FFFF);
606 |
607 | if ( ext == 1)
608 | {
609 | tbufdata[MCP_EID0] = (INT8U) (canid & 0xFF);
610 | tbufdata[MCP_EID8] = (INT8U) (canid >> 8);
611 | canid = (uint16_t)(id >> 16);
612 | tbufdata[MCP_SIDL] = (INT8U) (canid & 0x03);
613 | tbufdata[MCP_SIDL] += (INT8U) ((canid & 0x1C) << 3);
614 | tbufdata[MCP_SIDL] |= MCP_TXB_EXIDE_M;
615 | tbufdata[MCP_SIDH] = (INT8U) (canid >> 5 );
616 | }
617 | else
618 | {
619 | tbufdata[MCP_SIDH] = (INT8U) (canid >> 3 );
620 | tbufdata[MCP_SIDL] = (INT8U) ((canid & 0x07 ) << 5);
621 | tbufdata[MCP_EID0] = 0;
622 | tbufdata[MCP_EID8] = 0;
623 | }
624 |
625 | mcp2515_setRegisterS( mcp_addr, tbufdata, 4 );
626 | }
627 |
628 | /*********************************************************************************************************
629 | ** Function name: mcp2515_write_mf
630 | ** Descriptions: Write Masks and Filters
631 | *********************************************************************************************************/
632 | void MCP_CAN::mcp2515_write_mf( const INT8U mcp_addr, const INT8U ext, const INT32U id )
633 | {
634 | uint16_t canid;
635 | INT8U tbufdata[4];
636 |
637 | canid = (uint16_t)(id & 0x0FFFF);
638 |
639 | if ( ext == 1)
640 | {
641 | tbufdata[MCP_EID0] = (INT8U) (canid & 0xFF);
642 | tbufdata[MCP_EID8] = (INT8U) (canid >> 8);
643 | canid = (uint16_t)(id >> 16);
644 | tbufdata[MCP_SIDL] = (INT8U) (canid & 0x03);
645 | tbufdata[MCP_SIDL] += (INT8U) ((canid & 0x1C) << 3);
646 | tbufdata[MCP_SIDL] |= MCP_TXB_EXIDE_M;
647 | tbufdata[MCP_SIDH] = (INT8U) (canid >> 5 );
648 | }
649 | else
650 | {
651 | tbufdata[MCP_EID0] = (INT8U) (canid & 0xFF);
652 | tbufdata[MCP_EID8] = (INT8U) (canid >> 8);
653 | canid = (uint16_t)(id >> 16);
654 | tbufdata[MCP_SIDL] = (INT8U) ((canid & 0x07) << 5);
655 | tbufdata[MCP_SIDH] = (INT8U) (canid >> 3 );
656 | }
657 |
658 | mcp2515_setRegisterS( mcp_addr, tbufdata, 4 );
659 | }
660 |
661 | /*********************************************************************************************************
662 | ** Function name: mcp2515_read_id
663 | ** Descriptions: Read CAN ID
664 | *********************************************************************************************************/
665 | void MCP_CAN::mcp2515_read_id( const INT8U mcp_addr, INT8U* ext, INT32U* id )
666 | {
667 | INT8U tbufdata[4];
668 |
669 | *ext = 0;
670 | *id = 0;
671 |
672 | mcp2515_readRegisterS( mcp_addr, tbufdata, 4 );
673 |
674 | *id = (tbufdata[MCP_SIDH]<<3) + (tbufdata[MCP_SIDL]>>5);
675 |
676 | if ( (tbufdata[MCP_SIDL] & MCP_TXB_EXIDE_M) == MCP_TXB_EXIDE_M )
677 | {
678 | /* extended id */
679 | *id = (*id<<2) + (tbufdata[MCP_SIDL] & 0x03);
680 | *id = (*id<<8) + tbufdata[MCP_EID8];
681 | *id = (*id<<8) + tbufdata[MCP_EID0];
682 | *ext = 1;
683 | }
684 | }
685 |
686 | /*********************************************************************************************************
687 | ** Function name: mcp2515_write_canMsg
688 | ** Descriptions: Write message
689 | *********************************************************************************************************/
690 | void MCP_CAN::mcp2515_write_canMsg( const INT8U buffer_sidh_addr)
691 | {
692 | INT8U mcp_addr;
693 | mcp_addr = buffer_sidh_addr;
694 | mcp2515_setRegisterS(mcp_addr+5, m_nDta, m_nDlc ); /* write data bytes */
695 |
696 | if ( m_nRtr == 1) /* if RTR set bit in byte */
697 | m_nDlc |= MCP_RTR_MASK;
698 |
699 | mcp2515_setRegister((mcp_addr+4), m_nDlc ); /* write the RTR and DLC */
700 | mcp2515_write_id(mcp_addr, m_nExtFlg, m_nID ); /* write CAN id */
701 |
702 | }
703 |
704 | /*********************************************************************************************************
705 | ** Function name: mcp2515_read_canMsg
706 | ** Descriptions: Read message
707 | *********************************************************************************************************/
708 | void MCP_CAN::mcp2515_read_canMsg( const INT8U buffer_sidh_addr) /* read can msg */
709 | {
710 | INT8U mcp_addr, ctrl;
711 |
712 | mcp_addr = buffer_sidh_addr;
713 |
714 | mcp2515_read_id( mcp_addr, &m_nExtFlg,&m_nID );
715 |
716 | ctrl = mcp2515_readRegister( mcp_addr-1 );
717 | m_nDlc = mcp2515_readRegister( mcp_addr+4 );
718 |
719 | if (ctrl & 0x08)
720 | m_nRtr = 1;
721 | else
722 | m_nRtr = 0;
723 |
724 | m_nDlc &= MCP_DLC_MASK;
725 | mcp2515_readRegisterS( mcp_addr+5, &(m_nDta[0]), m_nDlc );
726 | }
727 |
728 | /*********************************************************************************************************
729 | ** Function name: mcp2515_getNextFreeTXBuf
730 | ** Descriptions: Send message
731 | *********************************************************************************************************/
732 | INT8U MCP_CAN::mcp2515_getNextFreeTXBuf(INT8U *txbuf_n) /* get Next free txbuf */
733 | {
734 | INT8U res, i, ctrlval;
735 | INT8U ctrlregs[MCP_N_TXBUFFERS] = { MCP_TXB0CTRL, MCP_TXB1CTRL, MCP_TXB2CTRL };
736 |
737 | res = MCP_ALLTXBUSY;
738 | *txbuf_n = 0x00;
739 |
740 | /* check all 3 TX-Buffers */
741 | for (i=0; i 0){
792 | #if DEBUG_MODE
793 | Serial.print("Entering Configuration Mode Failure...\r\n");
794 | #endif
795 | return res;
796 | }
797 |
798 | if (num == 0){
799 | mcp2515_write_mf(MCP_RXM0SIDH, ext, ulData);
800 |
801 | }
802 | else if(num == 1){
803 | mcp2515_write_mf(MCP_RXM1SIDH, ext, ulData);
804 | }
805 | else res = MCP2515_FAIL;
806 |
807 | res = mcp2515_setCANCTRL_Mode(mcpMode);
808 | if(res > 0){
809 | #if DEBUG_MODE
810 | Serial.print("Entering Previous Mode Failure...\r\nSetting Mask Failure...\r\n");
811 | #endif
812 | return res;
813 | }
814 | #if DEBUG_MODE
815 | Serial.print("Setting Mask Successful!\r\n");
816 | #endif
817 | return res;
818 | }
819 |
820 | /*********************************************************************************************************
821 | ** Function name: init_Mask
822 | ** Descriptions: Public function to set mask(s).
823 | *********************************************************************************************************/
824 | INT8U MCP_CAN::init_Mask(INT8U num, INT32U ulData)
825 | {
826 | INT8U res = MCP2515_OK;
827 | INT8U ext = 0;
828 | #if DEBUG_MODE
829 | Serial.print("Starting to Set Mask!\r\n");
830 | #endif
831 | res = mcp2515_setCANCTRL_Mode(MODE_CONFIG);
832 | if(res > 0){
833 | #if DEBUG_MODE
834 | Serial.print("Entering Configuration Mode Failure...\r\n");
835 | #endif
836 | return res;
837 | }
838 |
839 | if((num & 0x80000000) == 0x80000000)
840 | ext = 1;
841 |
842 | if (num == 0){
843 | mcp2515_write_mf(MCP_RXM0SIDH, ext, ulData);
844 |
845 | }
846 | else if(num == 1){
847 | mcp2515_write_mf(MCP_RXM1SIDH, ext, ulData);
848 | }
849 | else res = MCP2515_FAIL;
850 |
851 | res = mcp2515_setCANCTRL_Mode(mcpMode);
852 | if(res > 0){
853 | #if DEBUG_MODE
854 | Serial.print("Entering Previous Mode Failure...\r\nSetting Mask Failure...\r\n");
855 | #endif
856 | return res;
857 | }
858 | #if DEBUG_MODE
859 | Serial.print("Setting Mask Successful!\r\n");
860 | #endif
861 | return res;
862 | }
863 |
864 | /*********************************************************************************************************
865 | ** Function name: init_Filt
866 | ** Descriptions: Public function to set filter(s).
867 | *********************************************************************************************************/
868 | INT8U MCP_CAN::init_Filt(INT8U num, INT8U ext, INT32U ulData)
869 | {
870 | INT8U res = MCP2515_OK;
871 | #if DEBUG_MODE
872 | Serial.print("Starting to Set Filter!\r\n");
873 | #endif
874 | res = mcp2515_setCANCTRL_Mode(MODE_CONFIG);
875 | if(res > 0)
876 | {
877 | #if DEBUG_MODE
878 | Serial.print("Enter Configuration Mode Failure...\r\n");
879 | #endif
880 | return res;
881 | }
882 |
883 | switch( num )
884 | {
885 | case 0:
886 | mcp2515_write_mf(MCP_RXF0SIDH, ext, ulData);
887 | break;
888 |
889 | case 1:
890 | mcp2515_write_mf(MCP_RXF1SIDH, ext, ulData);
891 | break;
892 |
893 | case 2:
894 | mcp2515_write_mf(MCP_RXF2SIDH, ext, ulData);
895 | break;
896 |
897 | case 3:
898 | mcp2515_write_mf(MCP_RXF3SIDH, ext, ulData);
899 | break;
900 |
901 | case 4:
902 | mcp2515_write_mf(MCP_RXF4SIDH, ext, ulData);
903 | break;
904 |
905 | case 5:
906 | mcp2515_write_mf(MCP_RXF5SIDH, ext, ulData);
907 | break;
908 |
909 | default:
910 | res = MCP2515_FAIL;
911 | }
912 |
913 | res = mcp2515_setCANCTRL_Mode(mcpMode);
914 | if(res > 0)
915 | {
916 | #if DEBUG_MODE
917 | Serial.print("Entering Previous Mode Failure...\r\nSetting Filter Failure...\r\n");
918 | #endif
919 | return res;
920 | }
921 | #if DEBUG_MODE
922 | Serial.print("Setting Filter Successfull!\r\n");
923 | #endif
924 |
925 | return res;
926 | }
927 |
928 | /*********************************************************************************************************
929 | ** Function name: init_Filt
930 | ** Descriptions: Public function to set filter(s).
931 | *********************************************************************************************************/
932 | INT8U MCP_CAN::init_Filt(INT8U num, INT32U ulData)
933 | {
934 | INT8U res = MCP2515_OK;
935 | INT8U ext = 0;
936 |
937 | #if DEBUG_MODE
938 | Serial.print("Starting to Set Filter!\r\n");
939 | #endif
940 | res = mcp2515_setCANCTRL_Mode(MODE_CONFIG);
941 | if(res > 0)
942 | {
943 | #if DEBUG_MODE
944 | Serial.print("Enter Configuration Mode Failure...\r\n");
945 | #endif
946 | return res;
947 | }
948 |
949 | if((num & 0x80000000) == 0x80000000)
950 | ext = 1;
951 |
952 | switch( num )
953 | {
954 | case 0:
955 | mcp2515_write_mf(MCP_RXF0SIDH, ext, ulData);
956 | break;
957 |
958 | case 1:
959 | mcp2515_write_mf(MCP_RXF1SIDH, ext, ulData);
960 | break;
961 |
962 | case 2:
963 | mcp2515_write_mf(MCP_RXF2SIDH, ext, ulData);
964 | break;
965 |
966 | case 3:
967 | mcp2515_write_mf(MCP_RXF3SIDH, ext, ulData);
968 | break;
969 |
970 | case 4:
971 | mcp2515_write_mf(MCP_RXF4SIDH, ext, ulData);
972 | break;
973 |
974 | case 5:
975 | mcp2515_write_mf(MCP_RXF5SIDH, ext, ulData);
976 | break;
977 |
978 | default:
979 | res = MCP2515_FAIL;
980 | }
981 |
982 | res = mcp2515_setCANCTRL_Mode(mcpMode);
983 | if(res > 0)
984 | {
985 | #if DEBUG_MODE
986 | Serial.print("Entering Previous Mode Failure...\r\nSetting Filter Failure...\r\n");
987 | #endif
988 | return res;
989 | }
990 | #if DEBUG_MODE
991 | Serial.print("Setting Filter Successfull!\r\n");
992 | #endif
993 |
994 | return res;
995 | }
996 |
997 | /*********************************************************************************************************
998 | ** Function name: setMsg
999 | ** Descriptions: Set can message, such as dlc, id, dta[] and so on
1000 | *********************************************************************************************************/
1001 | INT8U MCP_CAN::setMsg(INT32U id, INT8U rtr, INT8U ext, INT8U len, const INT8U *pData)
1002 | {
1003 | int i = 0;
1004 | m_nID = id;
1005 | m_nRtr = rtr;
1006 | m_nExtFlg = ext;
1007 | m_nDlc = len;
1008 | for(i = 0; i> 3);
1287 | }
1288 |
1289 | /*********************************************************************************************************
1290 | END FILE
1291 | *********************************************************************************************************/
1292 |
--------------------------------------------------------------------------------
/prius3charger_buck.ino:
--------------------------------------------------------------------------------
1 | /*
2 | prius3charger_buck
3 | Copyright (c) 2020 Perttu "celeron55" Ahola
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 |
18 | Usage:
19 |
20 | Prius Gen 3 buck/boost converter charger controller - buck mode charging
21 | - For atmega328 on PriusG3_V1c
22 | - In Arduino IDE:
23 | 1) Board selection: Arduino Nano
24 | 2) Program bootloader using an ISP programmer like USBasp
25 | 3) Connect USB-serial adapter to "FTDI 5V" connector (GND -- 5V RX TX RST)
26 | 4) Upload and monitor using the serial connection at 57600 baud.
27 | - Alternatively you can use MiniCore for atmega328 with the "no bootloader"
28 | option and program using any in-circuit programmer supported by avrdude
29 |
30 | This program is designed to give excellent information on the serial console
31 | about what it is doing and why it is doing it.
32 |
33 | Notes about connections:
34 | - AC_CON_CTRL / AC_CONTACTOR_SWITCH:
35 | - This activates a contactor to connect AC into MG1 terminals after
36 | precharging. This is always required.
37 | - This can activate the battery side main contactor.
38 | ALTERNATIVELY the battery side main contactor can be controlled by an
39 | external controller based on CANbus messages or other signals.
40 | - This can activate a relay to feed 12V to the charger in parallel to the
41 | ignition key separated by diodes. This way once charging has started the
42 | ignition key can be turned off and the charger will shut down by itself
43 | when charging is complete.
44 | - This can activate an indicator LED to show that the charger is active
45 | - AC_PRECH_CTRL / AC_PRECHARGE_SWITCH:
46 | - This can activate a contactor to connect AC into MG1 terminals via
47 | precharge resistors.
48 | ALTERNATIVELY this software can precharge the MG/input side by boosting
49 | from the battery side.
50 | - This can activate the battery side precharge contactor.
51 | ALTERNATIVELY the battery side precharge can be initiated by an external
52 | controller based on CANbus messages or other signals.
53 | - This can activate an indicator LED to show that the charger is precharging
54 | - HV_CON_CTRL / CONVERTER_SHORT_SWITCH:
55 | - This can activate a contactor to short out the buck/boost converter to
56 | enable feeding more current to the motors than the converter inductor and
57 | IGBT can carry. This is switched on when the AC contactor and AC precharge
58 | switch outputs are inactive.
59 |
60 | TODO: Calibrate temperature sensors
61 |
62 | TODO: Maybe make output current and voltage values configurable in EEPROM. It's
63 | mostly a waste of program space though and a risky if you accidentally
64 | change them while monitoring.
65 |
66 | Connections:
67 | - A0: DCBUS1 (output side, lower voltage, toyota's battery voltage)
68 | - A1: DCBUS2 (input side, higher voltage, MG1/2 voltage)
69 | - A2: BOOST T1
70 | - A3: BOOST T2
71 | - A4: MG1 L1 current (10k/10k resistor divider)
72 | - A5: MG1 L2 current (10k/10k resistor divider)
73 | - A6: ACS758LCB-100U current sensor (not used in this version)
74 | - A7: EVSE_PP
75 | - 2/PD2: EVSE CP
76 | - 3/PD3: MCP2515 INT
77 | - 4/PD4: EVSE SW
78 | - 5/PD5: AC_CON_CTRL / AC_CONTACTOR_SWITCH
79 | - 6/PD6: HV_CON_CTRL / CONVERTER_SHORT_SWITCH
80 | - 7/PD7: AC_PRECH_CTRL / AC_PRECHARGE_SWITCH
81 | - 8/PB0: MCP2515 CS
82 | - 9/PB1/OC1A: Boost low side switch (active high)
83 | - 10/PB2/OC1B: Boost high side switch (active high)
84 |
85 | */
86 | #include "config.h"
87 | #include "log.h"
88 | #include "util.h"
89 | #include "command_accumulator.h"
90 | #include "avgbuffer.h"
91 | #include "software_debounce.h"
92 | // NOTE: These library portions are included with the project for ease of use.
93 | // NOTE: They are licensed separately under different open source licenses.
94 | // NOTE: See the files for details.
95 | #include "mcp_can.h"
96 | #include "can_common.h"
97 |
98 | // Charging parameters
99 | #define OUTPUT_CURRENT_MAX_A 80
100 | #define BATTERY_CHARGE_VOLTAGE 300
101 |
102 | // Other behavior
103 | #define EVSE_FORCE_INPUT_AMPS 0 // If 0, EVSE CP PWM is followed
104 | #define EVSE_PWM_TIMEOUT_MS 50
105 | #define MAX_PRECHARGE_MS 30000
106 | #define AC_PRECHARGE_MINIMUM_VOLTAGE 550 // European 3-phase rectifies to 600V
107 | #define PRECHARGE_BOOST_ENABLED true
108 | #define PRECHARGE_BOOST_START_MS 0
109 | #define PRECHARGE_BOOST_VOLTAGE 550 // European 3-phase rectifies to 600V
110 | //#define PWM_FREQ 3900 // Works for sure, but is very loud
111 | #define PWM_FREQ 10000 // Not much tested, but is much quieter
112 |
113 | // CANbus
114 | // Edit send_canbus_frames(), handle_canbus_frame() and init_system_can_filters() to do what you need
115 | #define CANBUS_ENABLE true
116 | #define CANBUS_SEND_INTERVAL_MS 200
117 | #define CANBUS_TIMEOUT_MS 2000
118 |
119 | // Advanced
120 | // Prints diagnostics about whether PWM output is limited by voltage or current
121 | #define REPORT_PWM_LIMITING_VALUE false
122 | // European 3-phase rectifies to 600V.
123 | // Our measured voltage likes to oscillate a lot under load.
124 | #define RECTIFIED_AC_MINIMUM_VOLTAGE 350
125 |
126 | // Absolute maximums
127 | #define INPUT_CURRENT_MAX_A 32
128 | #define INPUT_VOLTAGE_MAX_V 650 // Maximum of all Toyota inverters
129 | #define OUTPUT_VOLTAGE_MAX_V 305 // Yaris inverter has 300V and 350V capacitors
130 | #define BMS_MIN_CELL_MV_FOR_FAIL 2500
131 | #define BMS_MAX_CELL_MV_FOR_FAIL 4220
132 | #define BMS_MAX_TEMPREATURE_C_FOR_FAIL 45
133 | #define BOOST_MAX_TEMPERATURE_C 70
134 | #define CHARGE_FINISH_AT_A 4
135 |
136 | // Some secondary values that can be automatically set
137 | #define BATTERY_MINIMUM_VOLTAGE (BATTERY_CHARGE_VOLTAGE / 2)
138 |
139 | // Hardcoded tests
140 | #define TEST_CONTACTORS false
141 | #define TEST_BOOST false
142 | #define TEST_BUCK false
143 |
144 | // Scaling of analog inputs
145 | // NOTE: DCBUS2 is buck high side = MG side = 3-phase AC input side
146 | // NOTE: DCBUS1 is buck low side = battery side
147 | #define DCBUS2_OFFSET_BITS 0
148 | #define DCBUS2_V_PER_BIT 1.234
149 | /*#define DCBUS1_OFFSET_BITS 0
150 | #define DCBUS1_V_PER_BIT 0.438*/
151 | // Not sure what's up with this, maybe my Prius gen3 inverter is a bit wonky
152 | #define DCBUS1_OFFSET_BITS 74
153 | #define DCBUS1_V_PER_BIT 0.551
154 |
155 | // This is what it should be
156 | #define MG1_CURRENT_A_PER_BIT 1.0
157 | // This is what you need with wrong resistors on Yaris inverter
158 | //#define MG1_CURRENT_A_PER_BIT 0.735
159 |
160 | #define PWM_HANDLER_INTERVAL (uint8_t)(PWM_FREQ / 3400 + 1)
161 |
162 | #define DCBUS1_PIN A0
163 | #define DCBUS2_PIN A1
164 | #define BOOST_T1_PIN A2
165 | #define BOOST_T2_PIN A3
166 | #define MG1_L1_CURRENT_PIN A4
167 | #define MG1_L2_CURRENT_PIN A5
168 | #define EXTRA_CURRENT_SENSOR_PIN A6
169 | #define EVSE_PP_PIN A7
170 | #define EVSE_CP_PIN 2
171 | #define MCP2515_INT_PIN 3
172 | #define EVSE_SW_PIN 4
173 | #define AC_CONTACTOR_SWITCH_PIN 5
174 | #define CONVERTER_SHORT_SWITCH_PIN 6
175 | #define AC_PRECHARGE_SWITCH_PIN 7
176 | #define MCP2515_CS_PIN 8
177 | #define BOOST_LOW_SWITCH_PIN 9
178 | #define BOOST_HIGH_SWITCH_PIN 10
179 |
180 | // If non-zero, overrides everything except INPUT_CURRENT_MAX_A.
181 | // If zero, EVSE limit is followed.
182 | uint8_t force_ac_input_amps = EVSE_FORCE_INPUT_AMPS;
183 |
184 | // TODO: when reading these in the main thread, disable interrupts, maybe?
185 | volatile int16_t dcbus1_raw = 0;
186 | volatile int16_t dcbus2_raw = 0;
187 | volatile int16_t mg2l1_current_raw_calibrated_zero = 530;
188 | volatile int16_t mg2l2_current_raw_calibrated_zero = 530;
189 | volatile int16_t mg2l1_current_raw = 0;
190 | volatile int16_t mg2l2_current_raw = 0;
191 | volatile int16_t boost_t1_raw = 0;
192 | volatile int16_t boost_t2_raw = 0;
193 | volatile int16_t evse_pp_raw = 0;
194 | volatile int16_t input_voltage_V = 0;
195 | volatile int16_t output_voltage_V = 0;
196 | volatile int16_t input_dc_current_Ax10 = 0;
197 | volatile int16_t output_dc_current_Ax10 = 0;
198 |
199 | volatile enum DisablePwmReason {
200 | DPR_PWM_ENABLED,
201 | DPR_DCBUS1_OVERVOLTAGE,
202 | DPR_DCBUS2_OVERVOLTAGE,
203 | DPR_WANTED_PWM_IS_ZERO,
204 | DPR_BOOST_OVER_TEMPERATURE,
205 | DPR_LOST_EVSE_PROXIMITY_PILOT,
206 | DPR_PULSE_DONE,
207 |
208 | DPR_COUNT
209 | } disable_pwm = DPR_PWM_ENABLED;
210 | const char *DisablePwmReason_STRINGS[DPR_COUNT] = {
211 | "PWM_ENABLED",
212 | "DCBUS1_OVERVOLTAGE",
213 | "DCBUS2_OVERVOLTAGE",
214 | "WANTED_PWM_IS_ZERO",
215 | "DPR_BOOST_OVER_TEMPERATURE",
216 | "DPR_LOST_EVSE_PROXIMITY_PILOT",
217 | "DPR_PULSE_DONE",
218 | };
219 |
220 | // Once succesfully calibrated, PWM interrupt will be enabled
221 | bool current_sensor_zero_offsets_calibrated = false;
222 |
223 | // Current is measured at the MG current sensors where AC is coming in. This is
224 | // used to get a somewhat usable DC value from that.
225 | // 10 extra samples
226 | //AvgBuffer input_current_avgbuf;
227 | // 2 full waves
228 | AvgBuffer input_current_avgbuf;
229 |
230 | int8_t boost_t1_c = 0;
231 | int8_t boost_t2_c = 0;
232 |
233 | volatile uint8_t interrupt_counter_for_mainloop = 0;
234 | volatile bool mainloop_running = false;
235 | volatile bool console_report_all_values = false;
236 | CommandAccumulator<24> command_accumulator;
237 |
238 | enum SwitchingMode {
239 | SM_NONE,
240 | SM_BUCK,
241 | SM_BOOST,
242 | SM_BOOST_SINGLE_PULSE,
243 | };
244 |
245 | // Switching control is based on these, each is a maximum.
246 | volatile int16_t wanted_output_voltage = 0;
247 | volatile int16_t wanted_output_current = 0;
248 | volatile int16_t wanted_pwm = 0;
249 | SwitchingMode wanted_switching_mode = SM_BUCK;
250 |
251 | // Switching control state (don't touch from main program)
252 | volatile int16_t current_pwm = 0;
253 | volatile enum {BSPS_INIT, BSPS_PULSING, BSPS_PULSED} boost_single_pulse_state = BSPS_INIT;
254 | SwitchingMode current_switching_mode = SM_BUCK;
255 |
256 | // CANbus
257 |
258 | MCP_CAN system_can(MCP2515_CS_PIN);
259 |
260 | unsigned long canbus_last_receive_timestamp = 0;
261 |
262 | struct CanbusStatus {
263 | bool permit_charge = false;
264 | bool main_contactor_closed = false;
265 | uint16_t pack_voltage_V = 0;
266 | uint16_t cell_voltage_min_mV = 0;
267 | uint16_t cell_voltage_max_mV = 5000;
268 | int8_t cell_temperature_min = -128;
269 | int8_t cell_temperature_max = 127;
270 | bool charge_completed = false;
271 | uint16_t max_charge_current_A = 0;
272 | } canbus_status;
273 |
274 | // Charger state machine and related stuff
275 |
276 | enum ChargerState {
277 | CS_WAITING_START_TRIGGER,
278 | CS_WAITING_CANBUS,
279 | CS_WAITING_CHARGE_PERMISSION,
280 | CS_PRECHARGING,
281 | CS_CHARGING=8,
282 | CS_STOPPING_CHARGE,
283 | CS_DONE_CHARGING,
284 | CS_FAILED, // Keep output shut down and wait state reset by user action
285 | CS_ALLOW_MEASUREMENT_THEN_FAIL, // Wait 15s, then fail (DEBUG UTILITY)
286 | CS_COUNT
287 | } charger_state = CS_WAITING_START_TRIGGER;
288 |
289 | const char* const ChargerState_STRINGS[CS_COUNT] = {
290 | "CS_WAITING_START_TRIGGER",
291 | "CS_WAITING_CANBUS",
292 | "CS_WAITING_CHARGE_PERMISSION",
293 | "CS_PRECHARGING",
294 | "4", // Some room for future development
295 | "5",
296 | "6",
297 | "7",
298 | "CS_CHARGING",
299 | "CS_STOPPING_CHARGE",
300 | "CS_DONE_CHARGING",
301 | "CS_FAILED",
302 | "CS_ALLOW_MEASUREMENT_THEN_FAIL",
303 | };
304 |
305 | enum ChargerFailReason {
306 | CFR_NOT_FAILED,
307 | CFR_CANBUS_DEAD,
308 | CFR_BMS_NO_CHARGE_PERMIT,
309 | CFR_BMS_OVER_TEMPERATURE,
310 | CFR_BMS_OVER_VOLTAGE,
311 | CFR_BMS_UNDER_VOLTAGE,
312 | CFR_AC_PRECHARGE_FAILED,
313 | CFR_CUSTOM_MEASUREMENT_DELAY_ENDED,
314 | CFR_UNHANDLED_STATE,
315 | CFR_PRECHARGE_MINIMUM_VOLTAGE_NOT_SET,
316 | CFR_INPUT_VOLTAGE_TOO_LOW,
317 | CFR_INPUT_VOLTAGE_TOO_HIGH,
318 | CFR_LOST_EVSE_PROXIMITY_PILOT,
319 | CFR_PRECHARGE_VOLTAGE_THROUGH_THE_ROOF,
320 |
321 | CFR_COUNT
322 | };
323 |
324 | const char* const ChargerFailReason_STRINGS[CFR_COUNT] = {
325 | "CFR_NOT_FAILED",
326 | "CFR_CANBUS_DEAD",
327 | "CFR_BMS_NO_CHARGE_PERMIT",
328 | "CFR_BMS_OVER_TEMPERATURE",
329 | "CFR_BMS_OVER_VOLTAGE",
330 | "CFR_BMS_UNDER_VOLTAGE",
331 | "CFR_AC_PRECHARGE_FAILED",
332 | "CFR_CUSTOM_MEASUREMENT_DELAY_ENDED",
333 | "CFR_UNHANDLED_STATE",
334 | "CFR_PRECHARGE_MINIMUM_VOLTAGE_NOT_SET",
335 | "CFR_INPUT_VOLTAGE_TOO_LOW",
336 | "CFR_INPUT_VOLTAGE_TOO_HIGH",
337 | "CFR_LOST_EVSE_PROXIMITY_PILOT",
338 | "CFR_PRECHARGE_VOLTAGE_THROUGH_THE_ROOF",
339 | };
340 |
341 | struct ChargerStatus
342 | {
343 | ChargerFailReason fail_reason = CFR_NOT_FAILED;
344 | unsigned long no_start_condition_timestamp = 0;
345 | unsigned long start_timestamp = 0;
346 | unsigned long precharge_start_timestamp = 0;
347 | unsigned long charge_not_looking_complete_timestamp = 0;
348 | unsigned long stopping_charge_start_timestamp = 0;
349 | unsigned long fail_timestamp = 0;
350 | unsigned long allow_measurement_start_timestamp = 0;
351 | int16_t precharge_last_input_voltage = 0;
352 | int16_t precharge_last_battery_voltage = 0;
353 | bool battery_side_looks_precharged = false;
354 | } charger;
355 |
356 |
357 | // EVSE CP PWM measurement
358 | bool evse_pwm_enough_pulses_received = false;
359 | volatile unsigned long evse_pwm_last_rise_timestamp_us = 0;
360 | volatile unsigned long evse_pwm_last_valid_value_timestamp = 0;
361 | AvgBuffer evse_allowed_amps_avgbuf;
362 | volatile uint16_t evse_pwm_pulse_counter = 0;
363 |
364 | // EVSE final converted value from CP PWM
365 | uint8_t evse_allowed_amps = 0;
366 |
367 | // EVSE final converted value from PP resistance (0 = no cable)
368 | uint8_t evse_pp_cable_rating_a = 0;
369 |
370 | unsigned long inductor_short_switch_closed_timestamp = 0;
371 | unsigned long ac_contactor_closed_timestamp = 0;
372 |
373 | volatile enum LimitingValue {
374 | LV_NOTHING,
375 | LV_SOMETHING,
376 | LV_OUTPUT_CURRENT_SLOW,
377 | LV_INPUT_CURRENT_SLOW,
378 | LV_OUTPUT_VOLTAGE_SLOW,
379 | LV_OUTPUT_CURRENT,
380 | LV_INPUT_CURRENT,
381 | LV_OUTPUT_VOLTAGE,
382 | LV_OUTPUT_CURRENT_FAST,
383 | LV_INPUT_CURRENT_FAST,
384 | LV_OUTPUT_VOLTAGE_FAST,
385 |
386 | LV_COUNT,
387 | } limiting_value = LV_NOTHING;
388 |
389 | const char* const LimitingValue_STRINGS[LV_COUNT] = {
390 | "LV_NOTHING",
391 | "LV_SOMETHING",
392 | "LV_OUTPUT_CURRENT_SLOW",
393 | "LV_INPUT_CURRENT_SLOW",
394 | "LV_OUTPUT_VOLTAGE_SLOW",
395 | "LV_OUTPUT_CURRENT",
396 | "LV_INPUT_CURRENT",
397 | "LV_OUTPUT_VOLTAGE",
398 | "LV_OUTPUT_CURRENT_FAST",
399 | "LV_INPUT_CURRENT_FAST",
400 | "LV_OUTPUT_VOLTAGE_FAST",
401 | };
402 |
403 |
404 | void setup()
405 | {
406 | pinMode(DCBUS1_PIN, INPUT);
407 | pinMode(DCBUS2_PIN, INPUT);
408 | pinMode(BOOST_T1_PIN, INPUT);
409 | pinMode(BOOST_T2_PIN, INPUT);
410 | pinMode(MG1_L1_CURRENT_PIN, INPUT);
411 | pinMode(MG1_L2_CURRENT_PIN, INPUT);
412 | pinMode(EXTRA_CURRENT_SENSOR_PIN, INPUT);
413 | pinMode(EVSE_PP_PIN, INPUT);
414 | pinMode(EVSE_CP_PIN, INPUT);
415 | pinMode(MCP2515_INT_PIN, INPUT);
416 | pinMode(EVSE_SW_PIN, OUTPUT);
417 | pinMode(AC_CONTACTOR_SWITCH_PIN, OUTPUT);
418 | pinMode(CONVERTER_SHORT_SWITCH_PIN, OUTPUT);
419 | pinMode(AC_PRECHARGE_SWITCH_PIN, OUTPUT);
420 | pinMode(MCP2515_CS_PIN, OUTPUT);
421 | pinMode(BOOST_LOW_SWITCH_PIN, OUTPUT);
422 | pinMode(BOOST_HIGH_SWITCH_PIN, OUTPUT);
423 |
424 | // Wait for programming
425 | delay(2000);
426 |
427 | // We're using 57600 baud instead of 115200 because we can't process serial
428 | // data that fast with our monster interrupt routine running in sync with
429 | // PWM generation.
430 | Serial.begin(57600);
431 |
432 | log_println_f("-!- prius3charger_buck");
433 |
434 | #if TEST_CONTACTORS == true
435 | for(;;){
436 | log_println_f("DEBUG: AC_PRECHARGE_SWITCH_PIN on");
437 | digitalWrite(AC_PRECHARGE_SWITCH_PIN, HIGH);
438 | delay(1900);
439 | log_println_f("DEBUG: AC_CONTACTOR_SWITCH_PIN on");
440 | digitalWrite(AC_CONTACTOR_SWITCH_PIN, HIGH);
441 | delay(100);
442 | log_println_f("DEBUG: AC_PRECHARGE_SWITCH_PIN off");
443 | digitalWrite(AC_PRECHARGE_SWITCH_PIN, LOW);
444 | delay(2000);
445 | log_println_f("DEBUG: AC_CONTACTOR_SWITCH_PIN off");
446 | digitalWrite(AC_CONTACTOR_SWITCH_PIN, LOW);
447 | delay(2000);
448 | }
449 | #endif
450 |
451 | for(uint8_t i=0; i<10 && !current_sensor_zero_offsets_calibrated; i++){
452 | delay(100);
453 | calibrate_current_sensor_zero_offsets_if_needed();
454 | }
455 |
456 | SPI.begin();
457 |
458 | init_system_can();
459 |
460 | // EVSE PWM interrupt
461 | attachInterrupt(digitalPinToInterrupt(EVSE_CP_PIN), evse_cp_pwm_handler, CHANGE);
462 |
463 | mainloop_running = true;
464 | }
465 |
466 | void calibrate_current_sensor_zero_offsets_if_needed()
467 | {
468 | if(current_sensor_zero_offsets_calibrated)
469 | return;
470 |
471 | // Calibrate current sensor zero offsets before PWM output is initialized
472 | Serial.println(F("Calibrating current sensor zero offsets..."));
473 | set_pwm_inactive();
474 |
475 | int16_t il1_0 = analogRead(MG1_L1_CURRENT_PIN);
476 | int16_t il2_0 = analogRead(MG1_L2_CURRENT_PIN);
477 | int16_t il1_1 = 0;
478 | int16_t il2_1 = 0;
479 | const uint8_t require_stable_count = 20;
480 | uint8_t stable_count = 0;
481 | while(stable_count < require_stable_count){
482 | delay(20);
483 | il1_1 = analogRead(MG1_L1_CURRENT_PIN);
484 | il2_1 = analogRead(MG1_L2_CURRENT_PIN);
485 | if(abs(il1_1 - il1_0) >= 3 || abs(il2_1 - il2_0) >= 3){
486 | break;
487 | }
488 | stable_count++;
489 | }
490 | if(il1_1 < 460 || il1_1 > 570 || il2_1 < 460 || il2_1 > 570){
491 | Serial.print(F("Not accepting current calibration values: "));
492 | Serial.print(il1_1);
493 | Serial.print(F(", "));
494 | Serial.print(il2_1);
495 | Serial.print(" (out of range)");
496 | Serial.println();
497 | return;
498 | }
499 | if(stable_count < require_stable_count){
500 | Serial.print(F("Not accepting current calibration values: "));
501 | Serial.print(il1_1);
502 | Serial.print(F(", "));
503 | Serial.print(il2_1);
504 | Serial.print(" (unstable)");
505 | Serial.println();
506 | return;
507 | }
508 | mg2l1_current_raw_calibrated_zero = il1_1;
509 | mg2l2_current_raw_calibrated_zero = il2_1;
510 | log_print_timestamp();
511 | Serial.print(F("Calibrated zero offsets: IL1,2: "));
512 | Serial.print(mg2l1_current_raw_calibrated_zero);
513 | Serial.print(F(", "));
514 | Serial.print(mg2l2_current_raw_calibrated_zero);
515 | Serial.println();
516 |
517 | // PWM output
518 | // A: Set on compare match, phase and frequency correct, clk/1
519 | // B: Clear on compare match, phase and frequency correct, clk/1
520 | TCCR1A = _BV(COM1A1) | _BV(COM1A0) | _BV(COM1B1);
521 | TCCR1B = _BV(WGM13) | _BV(CS10);
522 | #define PWM_MAX (uint16_t)((F_CPU / 2.0) / (float)PWM_FREQ)
523 | ICR1 = PWM_MAX;
524 | // Interrupt at TOP
525 | TIMSK1 |= _BV(ICIE1);
526 |
527 | // Set initial PWM to zero
528 | set_pwm_inactive();
529 |
530 | current_sensor_zero_offsets_calibrated = true;
531 | }
532 |
533 | void loop()
534 | {
535 | #if TEST_BOOST == true
536 | dcbus2_raw = analogRead(DCBUS2_PIN) - DCBUS2_OFFSET_BITS;
537 | input_voltage_V = ((int32_t)dcbus2_raw * (int32_t)(DCBUS2_V_PER_BIT*1000)) / 1000;
538 | dcbus1_raw = analogRead(DCBUS1_PIN) - DCBUS1_OFFSET_BITS;
539 | output_voltage_V = ((int32_t)dcbus1_raw * (int32_t)(DCBUS1_V_PER_BIT*1000)) / 1000;
540 | EVERY_N_MILLISECONDS(200){
541 | Serial.print(output_voltage_V);
542 | Serial.print(" ");
543 | Serial.println(input_voltage_V);
544 | }
545 | if(input_voltage_V < 400 && ((millis()/1000)&1)==0){
546 | set_pwm_boost_active(ICR1 * 0.01);
547 | } else {
548 | set_pwm_inactive();
549 | }
550 | return;
551 | #endif
552 | #if TEST_BUCK == true
553 | dcbus2_raw = analogRead(DCBUS2_PIN) - DCBUS2_OFFSET_BITS;
554 | input_voltage_V = ((int32_t)dcbus2_raw * (int32_t)(DCBUS2_V_PER_BIT*1000)) / 1000;
555 | dcbus1_raw = analogRead(DCBUS1_PIN) - DCBUS1_OFFSET_BITS;
556 | output_voltage_V = ((int32_t)dcbus1_raw * (int32_t)(DCBUS1_V_PER_BIT*1000)) / 1000;
557 | EVERY_N_MILLISECONDS(200){
558 | Serial.print(output_voltage_V);
559 | Serial.print(" ");
560 | Serial.println(input_voltage_V);
561 | }
562 | if(output_voltage_V < 20 && ((millis()/1000)&1)==0){
563 | set_pwm_buck_active(ICR1 * 0.01);
564 | } else {
565 | set_pwm_inactive();
566 | }
567 | return;
568 | #endif
569 |
570 | EVERY_N_MILLISECONDS(1000){
571 | calibrate_current_sensor_zero_offsets_if_needed();
572 | }
573 |
574 | read_console_serial();
575 |
576 | read_canbus_frames();
577 |
578 | EVERY_N_MILLISECONDS(100){
579 | apply_canbus_timeouts();
580 | }
581 |
582 | convert_evse();
583 |
584 | handle_evse_pwm_timeout();
585 |
586 | handle_charger_state();
587 |
588 | control_inductor_short_switch();
589 |
590 | avoid_explosions();
591 |
592 | EVERY_N_MILLISECONDS(CANBUS_SEND_INTERVAL_MS){
593 | send_canbus_frames();
594 | }
595 |
596 | EVERY_N_MILLISECONDS(1000){
597 | convert_temperatures();
598 | }
599 | EVERY_N_MILLISECONDS(200){
600 | report_status_on_console();
601 | }
602 | EVERY_N_MILLISECONDS(5){
603 | interrupt_counter_for_mainloop = 0;
604 | }
605 | }
606 |
607 | void charger_fail(ChargerFailReason fail_reason)
608 | {
609 | charger_state = CS_FAILED;
610 |
611 | if(charger.fail_reason == CFR_NOT_FAILED){
612 | charger.fail_reason = fail_reason;
613 | charger.fail_timestamp = millis();
614 | }
615 |
616 | set_wanted_output_V_A_pwm(0, 0, 0, SM_NONE);
617 | digitalWrite(AC_CONTACTOR_SWITCH_PIN, LOW);
618 | digitalWrite(AC_PRECHARGE_SWITCH_PIN, LOW);
619 | digitalWrite(EVSE_SW_PIN, LOW);
620 |
621 | log_print_timestamp();
622 | CONSOLE.print("Charger failed: \"");
623 | CONSOLE.print(ChargerFailReason_STRINGS[charger.fail_reason]);
624 | CONSOLE.println("\"");
625 | }
626 |
627 | // Returns true if failed
628 | bool fail_if_charging_unsafe()
629 | {
630 | if(CANBUS_ENABLE){
631 | if(!canbus_alive()){
632 | charger_fail(CFR_CANBUS_DEAD);
633 | return true;
634 | }
635 | if(!canbus_status.permit_charge){
636 | charger_fail(CFR_BMS_NO_CHARGE_PERMIT);
637 | return true;
638 | }
639 | if(canbus_status.cell_temperature_max > BMS_MAX_TEMPREATURE_C_FOR_FAIL){
640 | charger_fail(CFR_BMS_OVER_TEMPERATURE);
641 | return true;
642 | }
643 | if(canbus_status.cell_voltage_min_mV < BMS_MIN_CELL_MV_FOR_FAIL){
644 | charger_fail(CFR_BMS_UNDER_VOLTAGE);
645 | return true;
646 | }
647 | if(canbus_status.cell_voltage_max_mV > BMS_MAX_CELL_MV_FOR_FAIL){
648 | charger_fail(CFR_BMS_OVER_VOLTAGE);
649 | return true;
650 | }
651 | }
652 | return false;
653 | }
654 |
655 | void restore_initial_state()
656 | {
657 | log_println_f("restore_initial_state()");
658 | if(charger_state != CS_FAILED && charger_state != CS_DONE_CHARGING){
659 | log_println_f("restore_initial_state(): Can't restore: Not failed or ended");
660 | return;
661 | }
662 | charger_state = CS_WAITING_START_TRIGGER;
663 | charger = ChargerStatus(); // Reset
664 | }
665 |
666 | void start_charging()
667 | {
668 | log_println_f("start_charging()");
669 |
670 | if(charger_state != CS_WAITING_START_TRIGGER &&
671 | charger_state != CS_DONE_CHARGING){
672 | log_println_f("Can't start charge: Not at charge cycle start or done charging");
673 | return;
674 | }
675 |
676 | charger = ChargerStatus(); // Reset
677 |
678 | charger.start_timestamp = millis();
679 |
680 | set_wanted_output_V_A_pwm(0, 0, 0, SM_NONE);
681 |
682 | // Request power from charger
683 | digitalWrite(EVSE_SW_PIN, HIGH);
684 |
685 | // Open converter short switch to let us have different voltages between the
686 | // MG and battery rails
687 | digitalWrite(CONVERTER_SHORT_SWITCH_PIN, LOW);
688 | // Wait for a little bit to make sure AC contactor doesn't switch before
689 | // converter short switch releases
690 | delay(100);
691 |
692 | charger_state = CS_WAITING_CANBUS;
693 | }
694 |
695 | void stop_charging()
696 | {
697 | if(charger_state == CS_FAILED){
698 | // Don't change failed state to anything else here as that can be unsafe.
699 | // Failed state can only be restored by power cycling or by
700 | // restore_initial_state().
701 | log_println_f("stop_charging(): Charger is in failed state.");
702 | return;
703 | }
704 | if(charger_state == CS_STOPPING_CHARGE){
705 | log_println_f("stop_charging(): Already stopped");
706 | return;
707 | }
708 |
709 | log_println_f("Stopping charger");
710 |
711 | charger_state = CS_STOPPING_CHARGE;
712 | charger.stopping_charge_start_timestamp = millis();
713 | }
714 |
715 | #define HANDLE_CHARGER_STATE(state, handler) \
716 | if(charger_state == (CS_##state)){ handler(); return; }
717 |
718 | void handle_charger_state()
719 | {
720 | // State modifiers
721 | if(charger_state != CS_FAILED){
722 | if(charger_state > CS_CHARGING && charger_state < CS_STOPPING_CHARGE){
723 | fail_if_charging_unsafe();
724 | }
725 | }
726 |
727 | // State handlers
728 | HANDLE_CHARGER_STATE(WAITING_START_TRIGGER, [&](){
729 | if(evse_pp_cable_rating_a > 0 && get_max_input_a() > 0 && current_sensor_zero_offsets_calibrated){
730 | // Wait until 2 seconds of continuous start conditions
731 | if(timestamp_age(charger.no_start_condition_timestamp) >= 2000){
732 | log_println_f("Charger start triggered");
733 | start_charging();
734 | } else {
735 | EVERY_N_MILLISECONDS(500){
736 | log_println_f("... Waiting stable starting condition for 2000ms");
737 | }
738 | }
739 | return;
740 | } else {
741 | charger.no_start_condition_timestamp = millis();
742 | }
743 | EVERY_N_MILLISECONDS(5000){
744 | if(evse_pp_cable_rating_a == 0){
745 | log_println_f("... Waiting for EVSE PP connection"
746 | " (pull it to ground if you don't have EVSE)");
747 | }
748 | if(get_max_input_a() == 0 && force_ac_input_amps == 0){
749 | log_println_f("... Waiting for EVSE CP PWM"
750 | " (set force_ac_input_amps if you don't have EVSE)");
751 | }
752 | }
753 | });
754 | HANDLE_CHARGER_STATE(WAITING_CANBUS, [&](){
755 | if(CANBUS_ENABLE){
756 | if(canbus_alive()){
757 | log_println_f("CANbus detected");
758 | charger_state = CS_WAITING_CHARGE_PERMISSION;
759 | }
760 | EVERY_N_MILLISECONDS(5000){
761 | log_println_f("... Waiting for CANbus");
762 | }
763 | } else {
764 | // Skip ahead, we don't need no CANbus!
765 | charger_state = CS_WAITING_CHARGE_PERMISSION;
766 | }
767 | });
768 | HANDLE_CHARGER_STATE(WAITING_CHARGE_PERMISSION, [&](){
769 | if((canbus_status.permit_charge || !CANBUS_ENABLE) && evse_pp_cable_rating_a > 0){
770 | if(CANBUS_ENABLE){
771 | log_println_f("BMS gives charge permission and cable proximity pilot is connected. Starting AC side precharge");
772 | } else {
773 | log_println_f("Cable proximity pilot is connected. Starting AC side precharge");
774 | }
775 | charger_state = CS_PRECHARGING;
776 |
777 |
778 | charger.precharge_start_timestamp = millis();
779 | charger.precharge_last_input_voltage = dcbus2_raw * DCBUS2_V_PER_BIT;
780 |
781 | report_status_on_console();
782 |
783 | log_print_timestamp();
784 | CONSOLE.print(F("Precharge starting at "));
785 | CONSOLE.print(charger.precharge_last_input_voltage);
786 | CONSOLE.println(" V");
787 | return;
788 | }
789 | EVERY_N_MILLISECONDS(5000){
790 | if(CANBUS_ENABLE){
791 | if(!canbus_status.permit_charge){
792 | log_println_f("... Waiting for BMS charge permission");
793 | }
794 | }
795 | if(evse_pp_cable_rating_a == 0){
796 | log_println_f("... Waiting for EVSE proximity pilot connection");
797 | }
798 | }
799 | });
800 | HANDLE_CHARGER_STATE(PRECHARGING, [&](){
801 | if(evse_pp_cable_rating_a == 0){
802 | charger_fail(CFR_LOST_EVSE_PROXIMITY_PILOT);
803 | return;
804 | }
805 |
806 | // Stop and cancel charging if any voltage goes through the roof
807 | if(input_voltage_V > INPUT_VOLTAGE_MAX_V ||
808 | output_voltage_V > OUTPUT_VOLTAGE_MAX_V){
809 | charger_fail(CFR_PRECHARGE_VOLTAGE_THROUGH_THE_ROOF);
810 | return;
811 | }
812 |
813 | // Delay closing the AC side precharge switch a bit.
814 | // This delay is useful if your precharge contactor doesn't quite work
815 | // at 12V but works at 14V, and your DC-DC converter is enabled at the
816 | // start of CS_PRECHARGING.
817 | // Ok yeah that's a bit silly for sure, but it happened to me!
818 | if(timestamp_age(charger.precharge_start_timestamp) >= 500){
819 | if(!digitalRead(AC_CONTACTOR_SWITCH_PIN)){
820 | digitalWrite(AC_PRECHARGE_SWITCH_PIN, HIGH);
821 | }
822 | }
823 |
824 | // Follow battery side precharge
825 | EVERY_N_MILLISECONDS(1000){
826 | if(!charger.battery_side_looks_precharged){
827 | if(
828 | abs(output_voltage_V - charger.precharge_last_battery_voltage) <= 2 &&
829 | output_voltage_V >= BATTERY_MINIMUM_VOLTAGE
830 | ){
831 | log_print_timestamp();
832 | CONSOLE.print(F("-> Battery side precharge looks FINISHED at "));
833 | CONSOLE.print(output_voltage_V);
834 | CONSOLE.println("V");
835 |
836 | charger.battery_side_looks_precharged = true;
837 | } else {
838 | log_print_timestamp();
839 | CONSOLE.print(F("... Battery side precharging at "));
840 | CONSOLE.print(output_voltage_V);
841 | CONSOLE.println("V");
842 |
843 | charger.precharge_last_battery_voltage = output_voltage_V;
844 | }
845 | }
846 |
847 | if(CANBUS_ENABLE){
848 | if(!canbus_status.main_contactor_closed){
849 | charger.battery_side_looks_precharged = false;
850 | }
851 | }
852 | }
853 |
854 | // Follow AC side precharge
855 | EVERY_N_MILLISECONDS(1000){
856 | if(!digitalRead(AC_CONTACTOR_SWITCH_PIN)){
857 | if(
858 | (abs(input_voltage_V - charger.precharge_last_input_voltage) <= 2
859 | || PRECHARGE_BOOST_ENABLED) &&
860 | input_voltage_V >= AC_PRECHARGE_MINIMUM_VOLTAGE
861 | ){
862 | uint16_t finish_voltage = input_voltage_V;
863 |
864 | digitalWrite(AC_CONTACTOR_SWITCH_PIN, HIGH);
865 | // This delay allows an NO AUX contact on the precharge
866 | // contactor to be paralleled with a resistor to form an
867 | // economizer for the main contactor.
868 | delay(100);
869 | digitalWrite(AC_PRECHARGE_SWITCH_PIN, LOW);
870 |
871 | log_print_timestamp();
872 | CONSOLE.print(F("-> AC side precharge FINISHED at "));
873 | CONSOLE.print(finish_voltage);
874 | CONSOLE.println("V, AC contactor CLOSED");
875 | } else {
876 | log_print_timestamp();
877 | CONSOLE.print(F("... AC side precharging at "));
878 | CONSOLE.print(input_voltage_V);
879 | CONSOLE.println("V");
880 |
881 | charger.precharge_last_input_voltage = input_voltage_V;
882 | }
883 | }
884 | }
885 |
886 | // Precharge finish condition
887 | if(digitalRead(AC_CONTACTOR_SWITCH_PIN) && charger.battery_side_looks_precharged){
888 | log_println_f("Input and battery side precharge done, now charging.");
889 | charger_state = CS_CHARGING;
890 | return;
891 | }
892 |
893 | // Precharge timeout
894 | if(timestamp_age(charger.precharge_start_timestamp) > MAX_PRECHARGE_MS){
895 | // Open precharge contactor
896 | digitalWrite(AC_PRECHARGE_SWITCH_PIN, LOW);
897 | // Stop boosting
898 | set_wanted_output_V_A_pwm(0, 0, 0, SM_NONE);
899 | set_pwm_inactive();
900 | // Report
901 | log_print_timestamp();
902 | CONSOLE.print(F("-> Precharge FAILED at "));
903 | CONSOLE.print(input_voltage_V);
904 | CONSOLE.print(F("V: Voltage not reaching target "));
905 | CONSOLE.print(AC_PRECHARGE_MINIMUM_VOLTAGE);
906 | CONSOLE.println("V");
907 | // Fail
908 | charger_fail(CFR_AC_PRECHARGE_FAILED);
909 | return;
910 | }
911 |
912 | // Use boosting to precharge in case there are no precharge resistors
913 | // configured.
914 | // This can be done only after the battery side has been precharged
915 | // first.
916 | if(PRECHARGE_BOOST_ENABLED &&
917 | timestamp_age(charger.precharge_start_timestamp) > PRECHARGE_BOOST_START_MS){
918 | if(!charger.battery_side_looks_precharged){
919 | EVERY_N_MILLISECONDS(5000){
920 | log_println_f("... Waiting battery side to be precharged before boosting");
921 | }
922 | }
923 | if(charger.battery_side_looks_precharged &&
924 | input_voltage_V < PRECHARGE_BOOST_VOLTAGE &&
925 | input_voltage_V < INPUT_VOLTAGE_MAX_V - 20){
926 | EVERY_N_MILLISECONDS(500){
927 | log_println_f("... Doing AC side precharge boost pulses");
928 | }
929 | EVERY_N_MILLISECONDS(1){
930 | // Make one boost pulse at a time so that we get updated
931 | // voltage measurements in between
932 | set_wanted_output_V_A_pwm(PRECHARGE_BOOST_VOLTAGE, 1, ICR1*0.05,
933 | SM_BOOST_SINGLE_PULSE);
934 | }
935 | } else {
936 | set_wanted_output_V_A_pwm(0, 0, 0, SM_NONE);
937 | set_pwm_inactive();
938 | }
939 | }
940 |
941 | // Report what we're waiting for
942 | if(!digitalRead(AC_CONTACTOR_SWITCH_PIN)){
943 | EVERY_N_MILLISECONDS(5000){
944 | log_println_f("... Doing AC side precharge");
945 | }
946 | }
947 | if(!charger.battery_side_looks_precharged){
948 | EVERY_N_MILLISECONDS(5000){
949 | log_println_f("... Doing battery side precharge");
950 | }
951 | }
952 | });
953 | HANDLE_CHARGER_STATE(CHARGING, [&](){
954 | if(evse_pp_cable_rating_a == 0){
955 | charger_fail(CFR_LOST_EVSE_PROXIMITY_PILOT);
956 | return;
957 | }
958 |
959 | check_and_react_if_high_power_input_failed();
960 |
961 | if(CANBUS_ENABLE){
962 | if(!canbus_status.permit_charge || !canbus_status.main_contactor_closed){
963 | report_status_on_console();
964 | log_println_f("BMS does not permit charging");
965 | charger_state = CS_STOPPING_CHARGE;
966 | charger.stopping_charge_start_timestamp = millis();
967 | return;
968 | }
969 | }
970 |
971 | // Stop charging if finished
972 |
973 | if(CANBUS_ENABLE){
974 | if(canbus_status.charge_completed){
975 | report_status_on_console();
976 | log_println_f("BMS reports charge completion, stopping");
977 | charger_state = CS_STOPPING_CHARGE;
978 | charger.stopping_charge_start_timestamp = millis();
979 | return;
980 | }
981 | }
982 |
983 | bool charge_looks_momentarily_complete =
984 | output_voltage_V >= BATTERY_CHARGE_VOLTAGE - 2 &&
985 | output_dc_current_Ax10 <= (CHARGE_FINISH_AT_A * 10);
986 |
987 | if(charge_looks_momentarily_complete){
988 | if(charger.charge_not_looking_complete_timestamp != 0 &&
989 | timestamp_age(charger.charge_not_looking_complete_timestamp) >= 30000){
990 | report_status_on_console();
991 | log_println_f("Charge looks complete, stopping");
992 | charger_state = CS_STOPPING_CHARGE;
993 | charger.stopping_charge_start_timestamp = millis();
994 | return;
995 | } else {
996 | EVERY_N_MILLISECONDS(5000){
997 | log_println_f("... Charge looks momentarily complete, waiting");
998 | }
999 | }
1000 | } else {
1001 | charger.charge_not_looking_complete_timestamp = millis();
1002 | }
1003 |
1004 | // Update output according to vehicle requirements
1005 |
1006 | if(CANBUS_ENABLE){
1007 | set_wanted_output_V_A_pwm(
1008 | BATTERY_CHARGE_VOLTAGE,
1009 | canbus_status.max_charge_current_A,
1010 | PWM_MAX,
1011 | SM_BUCK);
1012 | } else {
1013 | set_wanted_output_V_A_pwm(
1014 | BATTERY_CHARGE_VOLTAGE,
1015 | OUTPUT_CURRENT_MAX_A,
1016 | PWM_MAX,
1017 | SM_BUCK);
1018 | }
1019 |
1020 | if(fail_if_charging_unsafe())
1021 | return;
1022 | });
1023 | HANDLE_CHARGER_STATE(STOPPING_CHARGE, [&](){
1024 | set_wanted_output_V_A_pwm(0, 0, 0, SM_NONE);
1025 |
1026 | if(timestamp_age(charger.stopping_charge_start_timestamp) >= 1000){
1027 | charger_state = CS_DONE_CHARGING;
1028 | return;
1029 | }
1030 |
1031 | EVERY_N_MILLISECONDS(5000){
1032 | log_println_f("... Stopping charge");
1033 | }
1034 | });
1035 | HANDLE_CHARGER_STATE(DONE_CHARGING, [&](){
1036 | set_wanted_output_V_A_pwm(0, 0, 0, SM_NONE);
1037 |
1038 | digitalWrite(AC_PRECHARGE_SWITCH_PIN, LOW);
1039 | digitalWrite(AC_CONTACTOR_SWITCH_PIN, LOW);
1040 | digitalWrite(EVSE_SW_PIN, LOW);
1041 |
1042 | EVERY_N_MILLISECONDS(5000){
1043 | log_println_f("... Done charging");
1044 | }
1045 | });
1046 | HANDLE_CHARGER_STATE(FAILED, [&](){
1047 | set_wanted_output_V_A_pwm(0, 0, 0, SM_NONE);
1048 |
1049 | digitalWrite(AC_PRECHARGE_SWITCH_PIN, LOW);
1050 | digitalWrite(AC_CONTACTOR_SWITCH_PIN, LOW);
1051 | digitalWrite(EVSE_SW_PIN, LOW);
1052 |
1053 | EVERY_N_MILLISECONDS(5000){
1054 | log_print_timestamp();
1055 | CONSOLE.print("... In fault state: \"");
1056 | CONSOLE.print(ChargerFailReason_STRINGS[charger.fail_reason]);
1057 | CONSOLE.println("\"");
1058 | }
1059 |
1060 | // Reset automatically from some states that don't seem too dangerous
1061 | if(charger.fail_reason == CFR_LOST_EVSE_PROXIMITY_PILOT){
1062 | if(timestamp_age(charger.fail_timestamp) >= 5000){
1063 | log_println_f("Automatically resetting EVSE PP lost failure");
1064 | restore_initial_state();
1065 | }
1066 | }
1067 | });
1068 | HANDLE_CHARGER_STATE(ALLOW_MEASUREMENT_THEN_FAIL, [&](){
1069 | if(timestamp_age(charger.allow_measurement_start_timestamp) > 15000){
1070 | charger_fail(CFR_CUSTOM_MEASUREMENT_DELAY_ENDED);
1071 | }
1072 | EVERY_N_MILLISECONDS(2000){
1073 | log_println_f("... Allowing measurement for 15s");
1074 | }
1075 | });
1076 |
1077 | log_println_f("Unhandled charger state; falling back to stopping charge");
1078 | charger_fail(CFR_UNHANDLED_STATE);
1079 | }
1080 |
1081 | void control_inductor_short_switch()
1082 | {
1083 | // Maintain some timestamps
1084 | if(digitalRead(CONVERTER_SHORT_SWITCH_PIN)){
1085 | inductor_short_switch_closed_timestamp = millis();
1086 | }
1087 | if(digitalRead(AC_CONTACTOR_SWITCH_PIN)){
1088 | ac_contactor_closed_timestamp = millis();
1089 | }
1090 |
1091 | // Close converter short switch if charging isn't happening, AC contactor has
1092 | // been open for some time and the voltage difference is reasonable
1093 | if((charger_state == CS_WAITING_START_TRIGGER || charger_state == CS_DONE_CHARGING ||
1094 | charger_state == CS_FAILED) &&
1095 | timestamp_age(ac_contactor_closed_timestamp) >= 500){
1096 | if(!digitalRead(CONVERTER_SHORT_SWITCH_PIN)){
1097 | if(abs(input_voltage_V - output_voltage_V) < 20){
1098 | log_println_f("Closing converter short switch");
1099 | digitalWrite(CONVERTER_SHORT_SWITCH_PIN, HIGH);
1100 | } else {
1101 | EVERY_N_MILLISECONDS(5000){
1102 | log_println_f("Can't close converter short switch due to voltage "
1103 | "difference. If you're using the feature, make sure to "
1104 | "have a bleed down resistor in parallel with the "
1105 | "converter short switch.");
1106 | }
1107 | }
1108 | }
1109 | } else {
1110 | // Always if the AC main contactor is active, deactive the inductor
1111 | // short switch, and tell the programmer they messed up. You can look up
1112 | // if you find this in logs if your 3 phase breaker opened.
1113 | if(digitalRead(CONVERTER_SHORT_SWITCH_PIN)){
1114 | log_println_f("WARNING: CONVERTER_SHORT_SWITCH was active while AC "
1115 | "was active. The short switch has now been deactivated.");
1116 | digitalWrite(CONVERTER_SHORT_SWITCH_PIN, LOW);
1117 | }
1118 | }
1119 | }
1120 |
1121 | void avoid_explosions()
1122 | {
1123 | // Nah
1124 | }
1125 |
1126 | void set_wanted_output_V_A_pwm(int16_t voltage_V, int16_t current_A, int16_t pwm,
1127 | SwitchingMode switching_mode)
1128 | {
1129 | cli();
1130 | wanted_switching_mode = switching_mode;
1131 | wanted_output_voltage = voltage_V;
1132 | wanted_output_current = current_A;
1133 | wanted_pwm = pwm;
1134 | boost_single_pulse_state = BSPS_INIT;
1135 | sei();
1136 | }
1137 |
1138 | void check_and_react_if_high_power_input_failed()
1139 | {
1140 | cli();
1141 | int16_t voltage_now = dcbus2_raw * DCBUS2_V_PER_BIT;
1142 | sei();
1143 |
1144 | EVERY_N_MILLISECONDS(1000){
1145 | if(voltage_now < RECTIFIED_AC_MINIMUM_VOLTAGE){
1146 | log_print_timestamp();
1147 | CONSOLE.print(F("Input voltage dropped below the minimum voltage "));
1148 | CONSOLE.print(RECTIFIED_AC_MINIMUM_VOLTAGE);
1149 | CONSOLE.println(F(" V"));
1150 |
1151 | charger_fail(CFR_INPUT_VOLTAGE_TOO_LOW);
1152 | return;
1153 | }
1154 |
1155 | if(voltage_now > INPUT_VOLTAGE_MAX_V){
1156 | log_print_timestamp();
1157 | CONSOLE.print(F("Input voltage rose above the maximum voltage "));
1158 | CONSOLE.print(INPUT_VOLTAGE_MAX_V);
1159 | CONSOLE.println(F(" V"));
1160 |
1161 | charger_fail(CFR_INPUT_VOLTAGE_TOO_HIGH);
1162 | return;
1163 | }
1164 | }
1165 | }
1166 |
1167 | // Times are referenced to ICR1 value (ICR1 = 100%, 0 = 0%)
1168 | static void set_ontimes(uint16_t lowswitch_offtime, uint16_t highswitch_ontime)
1169 | {
1170 | // OC1A: Low side
1171 | OCR1A = lowswitch_offtime;
1172 | // OC1B: High side
1173 | OCR1B = highswitch_ontime;
1174 |
1175 | // We need to rewind TCNT1 to OCR1A so that the lowside gets turned off.
1176 | // Otherwise it will stay on for a full PWM cycle until it reaches the
1177 | // lowered OC1A on the next cycle and by that point we've had quite the
1178 | // boost pulse. At 10kHz such a pulse will create about 50V of extra voltage
1179 | // on the MG side.
1180 | if(TCNT1 >= OCR1A)
1181 | TCNT1 = OCR1A-1;
1182 | }
1183 |
1184 | // Sets high side switch PWM, and low side switch PWM based on it
1185 | static void set_pwm_buck_active(uint16_t highswitch_ontime)
1186 | {
1187 | if(!current_sensor_zero_offsets_calibrated)
1188 | return;
1189 | #if 0
1190 | const float deadtime_ns = 2500;
1191 | const uint16_t deadtime = (uint16_t)((float)deadtime_ns/(1.0/16e6*1e9));
1192 | set_ontimes(highswitch_ontime + deadtime, highswitch_ontime);
1193 | #else
1194 | set_ontimes(ICR1+1, highswitch_ontime);
1195 | #endif
1196 | }
1197 |
1198 | // Sets low side switch PWM, and high side switch PWM based on it
1199 | static void set_pwm_boost_active(uint16_t lowswitch_ontime)
1200 | {
1201 | if(!current_sensor_zero_offsets_calibrated)
1202 | return;
1203 | if(lowswitch_ontime > ICR1)
1204 | lowswitch_ontime = ICR1;
1205 | uint16_t lowswitch_offtime = ICR1 - lowswitch_ontime;
1206 | #if 0
1207 | const float deadtime_ns = 10000;
1208 | const uint16_t deadtime = (uint16_t)((float)deadtime_ns/(1.0/16e6*1e9));
1209 | set_ontimes(lowswitch_offtime, lowswitch_offtime - deadtime);
1210 | #else
1211 | set_ontimes(lowswitch_offtime, 0);
1212 | #endif
1213 | }
1214 |
1215 | static void set_pwm_inactive()
1216 | {
1217 | set_ontimes(ICR1, 0);
1218 | }
1219 |
1220 | static int16_t get_max_input_a()
1221 | {
1222 | int16_t max_input_a = [&]() -> int16_t {
1223 | // If force_ac_input_amps is set, it overrides everything except
1224 | // INPUT_CURRENT_MAX_A.
1225 | if(force_ac_input_amps != 0)
1226 | return force_ac_input_amps;
1227 | // Otherwise use EVSE CP PWM limit
1228 | return evse_allowed_amps;
1229 | }();
1230 |
1231 | // Cable limit (EVSE PP resistor)
1232 | // This is fairly reliable and fairly important so there is no need to
1233 | // support overriding it.
1234 | if(max_input_a >= evse_pp_cable_rating_a){
1235 | max_input_a = evse_pp_cable_rating_a;
1236 | }
1237 |
1238 | // Final limit
1239 | if(max_input_a >= INPUT_CURRENT_MAX_A){
1240 | max_input_a = INPUT_CURRENT_MAX_A;
1241 | }
1242 |
1243 | return max_input_a;
1244 | }
1245 |
1246 | static void control_buck()
1247 | {
1248 | int16_t max_input_a = get_max_input_a();
1249 |
1250 | // Calibrated input peak A = 2.0 * input RMS A (at around 10kW)
1251 | // Well, except that 2.0 will slowly blow a C32 fuse when input current is
1252 | // set at 32A.
1253 | // Let's randomly use 1.5, maybe it's good.
1254 | int16_t max_input_dc_current_Ax10 = max_input_a * 15;
1255 |
1256 | if(
1257 | output_dc_current_Ax10 >= wanted_output_current * 20
1258 | ){
1259 | // More than 200% current or more than 120% output voltage
1260 | if(current_pwm > 10)
1261 | current_pwm -= current_pwm / 8;
1262 | else
1263 | current_pwm = 0;
1264 | limiting_value = LV_OUTPUT_CURRENT_FAST;
1265 | } else if(
1266 | input_dc_current_Ax10 > max_input_dc_current_Ax10 * 2
1267 | ){
1268 | // More than 200% current or more than 120% output voltage
1269 | if(current_pwm > 10)
1270 | current_pwm -= current_pwm / 8;
1271 | else
1272 | current_pwm = 0;
1273 | limiting_value = LV_INPUT_CURRENT_FAST;
1274 | } else if(
1275 | output_voltage_V >= wanted_output_voltage * 6 / 5
1276 | ){
1277 | // More than 200% current or more than 120% output voltage
1278 | if(current_pwm > 10)
1279 | current_pwm -= current_pwm / 8;
1280 | else
1281 | current_pwm = 0;
1282 | limiting_value = LV_OUTPUT_VOLTAGE_FAST;
1283 | } else if(
1284 | output_dc_current_Ax10 > wanted_output_current * 12
1285 | ){
1286 | // More than 120% current or more than 100% output voltage
1287 | current_pwm--;
1288 | limiting_value = LV_OUTPUT_CURRENT;
1289 | } else if(
1290 | input_dc_current_Ax10 > max_input_dc_current_Ax10 * 6 / 5
1291 | ){
1292 | // More than 120% current or more than 100% output voltage
1293 | current_pwm--;
1294 | limiting_value = LV_INPUT_CURRENT;
1295 | } else if(
1296 | output_voltage_V > wanted_output_voltage
1297 | ){
1298 | // More than 120% current or more than 100% output voltage
1299 | current_pwm--;
1300 | limiting_value = LV_OUTPUT_VOLTAGE;
1301 | } else if(
1302 | output_dc_current_Ax10 < wanted_output_current * 5 &&
1303 | input_dc_current_Ax10 < max_input_dc_current_Ax10 / 2 &&
1304 | output_voltage_V < wanted_output_voltage
1305 | ){
1306 | // Less than 50% current and less than 100% output voltage
1307 | current_pwm++;
1308 | //limiting_value = LV_NOTHING; // Reset by report_status_on_console()
1309 | } else {
1310 | // Close to wanted values; adjust slower
1311 | static uint8_t counter = 0;
1312 | counter++;
1313 | if(counter >= 4){
1314 | counter = 0;
1315 |
1316 | // More than 100% current or more than 100% output voltage
1317 | if(output_dc_current_Ax10 > wanted_output_current * 10){
1318 | current_pwm--;
1319 | limiting_value = LV_OUTPUT_CURRENT_SLOW;
1320 | } else if(output_voltage_V > wanted_output_voltage){
1321 | current_pwm--;
1322 | limiting_value = LV_OUTPUT_VOLTAGE_SLOW;
1323 | } else if(input_dc_current_Ax10 > max_input_dc_current_Ax10){
1324 | current_pwm--;
1325 | limiting_value = LV_INPUT_CURRENT_SLOW;
1326 | } else {
1327 | // Less than 100% current and less than 100% output voltage
1328 | current_pwm++;
1329 | //limiting_value = LV_NOTHING; // Reset by report_status_on_console()
1330 | }
1331 | }
1332 | }
1333 |
1334 | if(current_pwm > wanted_pwm){
1335 | current_pwm = wanted_pwm;
1336 | }
1337 |
1338 | // Limit PWM
1339 | if(current_pwm < 0)
1340 | current_pwm = 0;
1341 | else if(current_pwm > ICR1)
1342 | current_pwm = ICR1;
1343 |
1344 | disable_pwm = [&](){
1345 | if(dcbus1_raw >= (int16_t)(OUTPUT_VOLTAGE_MAX_V / DCBUS1_V_PER_BIT)){
1346 | return DPR_DCBUS1_OVERVOLTAGE;
1347 | }
1348 | if(dcbus2_raw >= (int16_t)(INPUT_VOLTAGE_MAX_V / DCBUS2_V_PER_BIT)){
1349 | return DPR_DCBUS2_OVERVOLTAGE;
1350 | }
1351 | if(wanted_pwm == 0){
1352 | return DPR_WANTED_PWM_IS_ZERO;
1353 | }
1354 | if(boost_t1_c > BOOST_MAX_TEMPERATURE_C ||
1355 | boost_t2_c > BOOST_MAX_TEMPERATURE_C){
1356 | return DPR_BOOST_OVER_TEMPERATURE;
1357 | }
1358 | if(evse_pp_cable_rating_a == 0){
1359 | return DPR_LOST_EVSE_PROXIMITY_PILOT;
1360 | }
1361 | return DPR_PWM_ENABLED;
1362 | }();
1363 |
1364 | if(disable_pwm != DPR_PWM_ENABLED){
1365 | set_pwm_inactive();
1366 | current_pwm = 0;
1367 | } else {
1368 | set_pwm_buck_active(current_pwm);
1369 | }
1370 | }
1371 |
1372 | static void control_boost()
1373 | {
1374 | if(wanted_switching_mode == SM_BOOST_SINGLE_PULSE){
1375 | disable_pwm = DPR_PWM_ENABLED;
1376 | if(boost_single_pulse_state == BSPS_INIT){
1377 | // Start a pulse if it's needed
1378 | if(input_voltage_V >= INPUT_VOLTAGE_MAX_V ||
1379 | input_voltage_V >= wanted_output_voltage){
1380 | // Enough voltage, not creating pulse
1381 | current_pwm = 0;
1382 | set_pwm_inactive();
1383 | boost_single_pulse_state = BSPS_PULSED;
1384 | } else {
1385 | current_pwm = wanted_pwm;
1386 | set_pwm_boost_active(current_pwm);
1387 | boost_single_pulse_state = BSPS_PULSING;
1388 | }
1389 | } else if(boost_single_pulse_state == BSPS_PULSING){
1390 | // Pulse was started, now we end it
1391 | current_pwm = 0;
1392 | set_pwm_inactive();
1393 | boost_single_pulse_state = BSPS_PULSED;
1394 | } else {
1395 | // Pulse started and ended, nothing to do
1396 | disable_pwm = DPR_PULSE_DONE;
1397 | }
1398 | } else if(wanted_switching_mode == SM_BOOST){
1399 | disable_pwm = DPR_PWM_ENABLED;
1400 | if(input_voltage_V >= INPUT_VOLTAGE_MAX_V ||
1401 | input_voltage_V >= wanted_output_voltage){
1402 | // Enough voltage
1403 | current_pwm = 0;
1404 | set_pwm_inactive();
1405 | } else {
1406 | current_pwm = wanted_pwm;
1407 | set_pwm_boost_active(current_pwm);
1408 | }
1409 | }
1410 | }
1411 |
1412 | SIGNAL(TIMER1_CAPT_vect)
1413 | {
1414 | #if TEST_BOOST == true || TEST_BUCK == true
1415 | return;
1416 | #endif
1417 |
1418 | static uint8_t pwm_handler_interval_counter = 0;
1419 | pwm_handler_interval_counter++;
1420 | if(pwm_handler_interval_counter < PWM_HANDLER_INTERVAL)
1421 | return;
1422 | pwm_handler_interval_counter = 0;
1423 |
1424 | static uint8_t interrupt_counter = 0;
1425 |
1426 | // NOTE: We have time for one analogRead and some calculation per PWM cycle
1427 |
1428 | static uint8_t ch_i = 255;
1429 | ch_i++;
1430 | switch(ch_i){
1431 | case 0:
1432 | dcbus1_raw = analogRead(DCBUS1_PIN) - DCBUS1_OFFSET_BITS;
1433 | output_voltage_V = ((int32_t)dcbus1_raw * (int32_t)(DCBUS1_V_PER_BIT*1000)) / 1000;
1434 | break;
1435 | case 1:
1436 | dcbus2_raw = analogRead(DCBUS2_PIN) - DCBUS2_OFFSET_BITS;
1437 | input_voltage_V = ((int32_t)dcbus2_raw * (int32_t)(DCBUS2_V_PER_BIT*1000)) / 1000;
1438 | break;
1439 | case 2:
1440 | mg2l1_current_raw = analogRead(MG1_L1_CURRENT_PIN) -
1441 | mg2l1_current_raw_calibrated_zero;
1442 | break;
1443 | case 3:
1444 | mg2l2_current_raw = analogRead(MG1_L2_CURRENT_PIN) -
1445 | mg2l2_current_raw_calibrated_zero;
1446 | break;
1447 | case 4:
1448 | boost_t1_raw = analogRead(BOOST_T1_PIN);
1449 | break;
1450 | case 5:
1451 | boost_t2_raw = analogRead(BOOST_T2_PIN);
1452 | break;
1453 | case 6:
1454 | evse_pp_raw = analogRead(EVSE_PP_PIN);
1455 | break;
1456 | default:
1457 | ch_i = 255;
1458 | break;
1459 | }
1460 |
1461 | if(ch_i == 3){
1462 | // Control PWM
1463 |
1464 | int16_t l1_current_A =
1465 | abs(((int32_t)mg2l1_current_raw * (int32_t)(MG1_CURRENT_A_PER_BIT * 1000)) / 1000);
1466 | int16_t l2_current_A =
1467 | abs(((int32_t)mg2l2_current_raw * (int32_t)(MG1_CURRENT_A_PER_BIT * 1000)) / 1000);
1468 | int16_t input_now_A = l1_current_A > l2_current_A ? l1_current_A : l2_current_A;
1469 | input_current_avgbuf.push(input_now_A);
1470 | input_dc_current_Ax10 = limit_int32(input_current_avgbuf.avg(10), 0, 32767);
1471 | int32_t input_power_Wx10 = (int32_t)input_dc_current_Ax10 * input_voltage_V;
1472 | int16_t input_to_output_V_factor_x10 = input_voltage_V * 10 / output_voltage_V;
1473 | // Limit so that value is not too inaccurate
1474 | if(input_to_output_V_factor_x10 > 50) // 50 = 5x
1475 | input_to_output_V_factor_x10 = 50;
1476 | // With correction according to measurements in practice (0.74x)
1477 | output_dc_current_Ax10 = limit_int32((int32_t)input_dc_current_Ax10 *
1478 | input_to_output_V_factor_x10 * 74 / 1000, 0, 32767);
1479 | // Actually this is more accurate at around 10-15kW
1480 | // NOTE: Accurate as input power, but output after efficiency is
1481 | // probably more like above?
1482 | /*output_dc_current_Ax10 = limit_int32((int32_t)input_dc_current_Ax10 *
1483 | input_to_output_V_factor_x10 * 93 / 1000, 0, 32767);*/
1484 |
1485 | if(current_switching_mode != wanted_switching_mode){
1486 | current_pwm = 0;
1487 | current_switching_mode = wanted_switching_mode;
1488 | }
1489 |
1490 | if(current_switching_mode == SM_BUCK){
1491 | control_buck();
1492 | } else if(current_switching_mode == SM_BOOST_SINGLE_PULSE ||
1493 | current_switching_mode == SM_BOOST){
1494 | control_boost();
1495 | } else {
1496 | set_pwm_inactive();
1497 | current_pwm = 0;
1498 | }
1499 | }
1500 |
1501 | if(mainloop_running){
1502 | if(interrupt_counter == 0){ // 29Hz, 34ms
1503 | // If main loop doesn't reset counter before 340ms, issue warning
1504 | if(interrupt_counter_for_mainloop > 10){
1505 | Serial.println(F("WARNING: Too little time for main loop detected"));
1506 | interrupt_counter_for_mainloop = 0;
1507 | }
1508 | interrupt_counter_for_mainloop++;
1509 | }
1510 | }
1511 |
1512 | interrupt_counter++;
1513 | }
1514 |
1515 | void report_status_on_console()
1516 | {
1517 | static unsigned long last_accurate_report_timestamp = 0;
1518 | bool accurate = false;
1519 | if(timestamp_age(last_accurate_report_timestamp) >= 2000){
1520 | last_accurate_report_timestamp = millis();
1521 | accurate = true;
1522 | }
1523 |
1524 | // Configuration
1525 | REPORT_INT16(BATTERY_CHARGE_VOLTAGE);
1526 | REPORT_INT16(OUTPUT_CURRENT_MAX_A);
1527 |
1528 | // PWM control
1529 | REPORT_ENUM(disable_pwm, DisablePwmReason_STRINGS);
1530 | REPORT_INT16_FORMAT(wanted_output_voltage, 1, 1, " V")
1531 | REPORT_INT16_FORMAT(wanted_output_current, 1, 1, " A")
1532 | REPORT_UINT16_FORMAT(wanted_pwm, accurate ? 1 : 5, 100.0/PWM_MAX, " %")
1533 | //REPORT_INT16_FORMAT(dcbus1_raw, accurate ? 2 : 4, DCBUS1_V_PER_BIT, " V")
1534 | //REPORT_INT16_FORMAT(dcbus2_raw, accurate ? 2 : 4, DCBUS2_V_PER_BIT, " V")
1535 | //REPORT_INT16_FORMAT(mg2l1_current_raw, accurate ? 1 : 2, MG1_CURRENT_A_PER_BIT, " A")
1536 | //REPORT_INT16_FORMAT(mg2l2_current_raw, accurate ? 1 : 2, MG1_CURRENT_A_PER_BIT, " A")
1537 | #if REPORT_PWM_LIMITING_VALUE == true
1538 | REPORT_ENUM(limiting_value, LimitingValue_STRINGS);
1539 | limiting_value = LV_NOTHING;
1540 | #endif
1541 |
1542 | // Digital outputs
1543 | REPORT_BOOL(digitalRead(AC_CONTACTOR_SWITCH_PIN))
1544 | REPORT_BOOL(digitalRead(AC_PRECHARGE_SWITCH_PIN))
1545 | REPORT_BOOL(digitalRead(CONVERTER_SHORT_SWITCH_PIN))
1546 |
1547 | // Temperatures
1548 | //REPORT_INT16_FORMAT(boost_t1_raw, accurate ? 2 : 50, 1, " raw");
1549 | REPORT_INT16_FORMAT(boost_t1_c, accurate ? 2 : 5, 1, " C");
1550 | //REPORT_INT16_FORMAT(boost_t2_raw, accurate ? 2 : 50, 1, " raw");
1551 | REPORT_INT16_FORMAT(boost_t2_c, accurate ? 2 : 5, 1, " C");
1552 |
1553 | // EVSE
1554 | REPORT_INT16_FORMAT(evse_pp_raw, accurate ? 2 : 50, 1, " raw");
1555 | REPORT_UINT8(evse_allowed_amps);
1556 | REPORT_UINT8(evse_pp_cable_rating_a);
1557 | REPORT_INT16(get_max_input_a());
1558 |
1559 | // Charger status
1560 | REPORT_ENUM(charger_state, ChargerState_STRINGS);
1561 | REPORT_ENUM(charger.fail_reason, ChargerFailReason_STRINGS);
1562 |
1563 | // BMS
1564 | if(CANBUS_ENABLE){
1565 | REPORT_BOOL(canbus_alive())
1566 | REPORT_INT16_FORMAT(canbus_status.max_charge_current_A, accurate ? 1 : 2, 1, "A")
1567 | REPORT_INT16_FORMAT(canbus_status.cell_voltage_max_mV, accurate ? 10 : 100, 0.001, "V")
1568 | REPORT_BOOL(canbus_status.permit_charge)
1569 | REPORT_BOOL(canbus_status.main_contactor_closed)
1570 | }
1571 |
1572 | // Input and output voltage, current and PWM %
1573 | /*REPORT_INT16_FORMAT(input_voltage_V, accurate ? 2 : 4, 1, " V")
1574 | REPORT_INT16_FORMAT(output_voltage_V, accurate ? 2 : 4, 1, " V")
1575 | REPORT_INT16_FORMAT(input_dc_current_Ax10, accurate ? 1 : 2, 0.1, " A")
1576 | REPORT_INT16_FORMAT(output_dc_current_Ax10, accurate ? 1 : 2, 0.1, " A")
1577 | REPORT_UINT16_FORMAT(current_pwm, accurate ? 1 : 5, PWM_MAX/100.0/1024, " %")*/
1578 | {
1579 | static int16_t reported_input_voltage_V = 0;
1580 | static int16_t reported_output_voltage_V = 0;
1581 | static int16_t reported_input_dc_current_Ax10 = 0;
1582 | static int16_t reported_output_dc_current_Ax10 = 0;
1583 | static int16_t reported_current_pwm = 0;
1584 | if(
1585 | abs(input_voltage_V - reported_input_voltage_V) > (accurate ? 2 : 10) ||
1586 | abs(output_voltage_V - reported_output_voltage_V) > (accurate ? 2 : 4) ||
1587 | abs(input_dc_current_Ax10 - reported_input_dc_current_Ax10) > (accurate ? 1 : 5) ||
1588 | ((abs(output_dc_current_Ax10 - reported_output_dc_current_Ax10) > (accurate ? 1 : 8)) && current_pwm > 0) ||
1589 | abs(current_pwm - reported_current_pwm) > (accurate ? 1 : (PWM_MAX/100+1)) ||
1590 | console_report_all_values
1591 | ){
1592 | log_print_timestamp();
1593 | CONSOLE.print(F(">> PWM "));
1594 | CONSOLE.print((float)current_pwm / (float)(PWM_MAX / 100.0));
1595 | CONSOLE.print(F("%, in "));
1596 | CONSOLE.print(input_dc_current_Ax10 * 0.1);
1597 | CONSOLE.print(F("A @ "));
1598 | CONSOLE.print(input_voltage_V);
1599 | CONSOLE.print(F("V, out "));
1600 | CONSOLE.print(output_dc_current_Ax10 * 0.1);
1601 | CONSOLE.print(F("A @ "));
1602 | CONSOLE.print(output_voltage_V);
1603 | CONSOLE.print(F("V, "));
1604 | CONSOLE.print((int32_t)output_dc_current_Ax10 * output_voltage_V / 10);
1605 | CONSOLE.println(F("W"));
1606 |
1607 | reported_input_voltage_V = input_voltage_V;
1608 | reported_output_voltage_V = output_voltage_V;
1609 | reported_input_dc_current_Ax10 = input_dc_current_Ax10;
1610 | reported_output_dc_current_Ax10 = output_dc_current_Ax10;
1611 | reported_current_pwm = current_pwm;
1612 | }
1613 | }
1614 | }
1615 |
1616 | void console_help()
1617 | {
1618 | CONSOLE.println(F("Useful commands:"));
1619 | CONSOLE.println(F(" r (report)"));
1620 | CONSOLE.println(F(" chp (charger stop)"));
1621 | CONSOLE.println(F(" chr (charger restore)"));
1622 | CONSOLE.println(F(" aca (force_ac_input_amps)"));
1623 | }
1624 |
1625 | void handle_command(const char *command, size_t command_len)
1626 | {
1627 | if(command[0] == 'h' || command[0] == '?'){
1628 | console_help();
1629 | return;
1630 | }
1631 | if(strcmp(command, "report") == 0 || strcmp(command, "r") == 0){
1632 | console_report_all_values = true;
1633 | report_status_on_console();
1634 | console_report_all_values = false;
1635 | return;
1636 | }
1637 | if(strcmp(command, "charger stop") == 0 || strcmp(command, "chp") == 0){
1638 | stop_charging();
1639 | return;
1640 | }
1641 | if(strcmp(command, "charger restore") == 0 || strcmp(command, "chr") == 0){
1642 | restore_initial_state();
1643 | return;
1644 | }
1645 | if(strncmp(command, "aca ", 4) == 0){
1646 | force_ac_input_amps = strtol(&command[4], NULL, 10);
1647 | log_print_timestamp();
1648 | CONSOLE.print(F("force_ac_input_amps set: "));
1649 | CONSOLE.print(force_ac_input_amps);
1650 | CONSOLE.println(F(" A"));
1651 | return;
1652 | }
1653 |
1654 | CONSOLE.print(F("Unknown command: "));
1655 | CONSOLE.println(command);
1656 | console_help();
1657 | }
1658 |
1659 | void read_console_serial()
1660 | {
1661 | while(CONSOLE.available()){
1662 | if(command_accumulator.put_char(CONSOLE.read())){
1663 | const char *command = command_accumulator.command();
1664 | size_t len = command_accumulator.next_i;
1665 | log_print_timestamp();
1666 | CONSOLE.print(F("Command: "));
1667 | CONSOLE.println(command);
1668 | handle_command(command, len);
1669 | }
1670 | }
1671 | }
1672 |
1673 | void evse_cp_pwm_handler()
1674 | {
1675 | static bool state_before = false;
1676 |
1677 | int8_t state_sum = 0;
1678 | for(uint8_t i=0; i<10; i++){
1679 | state_sum += digitalRead(EVSE_CP_PIN) ? 1 : -1;
1680 | }
1681 | bool state_now = state_sum >= 0;
1682 |
1683 | if(state_now == state_before)
1684 | return;
1685 |
1686 | if(state_now){
1687 | evse_pwm_last_rise_timestamp_us = micros();
1688 | } else {
1689 | unsigned long t1 = micros();
1690 | if(t1 >= evse_pwm_last_rise_timestamp_us){
1691 | unsigned long t = t1 - evse_pwm_last_rise_timestamp_us;
1692 | uint32_t amps = t / 16;
1693 | if(amps >= 3 || amps <= 80){
1694 | evse_pwm_pulse_counter++;
1695 | evse_pwm_last_valid_value_timestamp = millis();
1696 | evse_allowed_amps_avgbuf.push(amps);
1697 | evse_allowed_amps = evse_allowed_amps_avgbuf.avg();
1698 | }
1699 | }
1700 | }
1701 | state_before = state_now;
1702 | }
1703 |
1704 | void handle_evse_pwm_timeout()
1705 | {
1706 | cli();
1707 | unsigned long t = evse_pwm_last_valid_value_timestamp;
1708 | sei();
1709 |
1710 | EVERY_N_MILLISECONDS(EVSE_PWM_TIMEOUT_MS){
1711 | cli();
1712 | uint16_t v = evse_pwm_pulse_counter;
1713 | evse_pwm_pulse_counter = 0;
1714 | sei();
1715 | if(v >= EVSE_PWM_TIMEOUT_MS / 2){ // 50% of pulses at 1ms/pulse
1716 | evse_pwm_enough_pulses_received = true;
1717 | } else {
1718 | evse_pwm_enough_pulses_received = false;
1719 | evse_allowed_amps = 0;
1720 | cli();
1721 | evse_allowed_amps_avgbuf.reset();
1722 | sei();
1723 | }
1724 | }
1725 | }
1726 |
1727 | void convert_evse()
1728 | {
1729 | evse_pp_cable_rating_a = [&](){
1730 | const uint16_t a = evse_pp_raw;
1731 | if(a < (uint16_t)(1024/5 * 0.94))
1732 | return 63;
1733 | if(a < (uint16_t)(1024/5 * 2.29))
1734 | return 32;
1735 | if(a < (uint16_t)(1024/5 * 2.70))
1736 | return 13;
1737 | if(a < (uint16_t)(1024/5 * 3.03))
1738 | return 6;
1739 | return 0;
1740 | }();
1741 | }
1742 |
1743 | void convert_temperatures()
1744 | {
1745 | {
1746 | int16_t t = boost_t1_raw;
1747 | // Not really calibrated
1748 | const int16_t bits_per_c = (867 - 792) / (20 - 35);
1749 | boost_t1_c = 20 + (boost_t1_raw - 867) / bits_per_c;
1750 | }
1751 | {
1752 | int16_t t = boost_t2_raw;
1753 | // Not really calibrated
1754 | const int16_t bits_per_c = (867 - 792) / (20 - 35);
1755 | boost_t2_c = 20 + (boost_t2_raw - 867) / bits_per_c;
1756 | }
1757 | }
1758 |
1759 | static void canbus_detected() {
1760 | canbus_last_receive_timestamp = millis();
1761 | }
1762 |
1763 | void init_system_can()
1764 | {
1765 | // Init MCP2515
1766 | for(uint8_t i=0; i<10; i++){
1767 | if(system_can.begin(MCP_STDEXT, CAN_500KBPS, MCP_16MHZ) == CAN_OK){
1768 | log_println_f("can_init: MCP2515 init ok");
1769 | // Allow messages to be transmitted
1770 | system_can.setMode(MCP_NORMAL);
1771 | // One-shot TX
1772 | //system_can.enOneShotTX();
1773 | break;
1774 | } else {
1775 | log_println_f("can_init: MCP2515 init failed");
1776 | }
1777 | delay(500);
1778 | }
1779 |
1780 | init_system_can_filters();
1781 | }
1782 |
1783 | void init_system_can_filters()
1784 | {
1785 | // Any 0x6** (input message) or 0x1** (BMS)
1786 | if(system_can.init_Mask(0, false, 0x0f00L << 16) == MCP2515_FAIL) goto filter_fail;
1787 | if(system_can.init_Filt(0, false, 0x0600L << 16) == MCP2515_FAIL) goto filter_fail;
1788 | if(system_can.init_Filt(1, false, 0x0100L << 16) == MCP2515_FAIL) goto filter_fail;
1789 |
1790 | // Any 0x1** (BMS)
1791 | if(system_can.init_Mask(1, false, 0x0f00L << 16) == MCP2515_FAIL) goto filter_fail;
1792 | if(system_can.init_Filt(2, false, 0x0100L << 16) == MCP2515_FAIL) goto filter_fail;
1793 | if(system_can.init_Filt(3, false, 0x0100L << 16) == MCP2515_FAIL) goto filter_fail;
1794 | if(system_can.init_Filt(4, false, 0x0100L << 16) == MCP2515_FAIL) goto filter_fail;
1795 | if(system_can.init_Filt(5, false, 0x0100L << 16) == MCP2515_FAIL) goto filter_fail;
1796 | return;
1797 |
1798 | filter_fail:
1799 | log_println_f("FAILED to set MCP2515 filters");
1800 | log_println_f("WARNING: CANbus communication will not work correctly.");
1801 | //for(;;);
1802 | }
1803 |
1804 | uint8_t pack_32A_into_4bits(uint8_t v)
1805 | {
1806 | uint8_t r = v / 2;
1807 | if(r > 0x0f)
1808 | r = 0x0f;
1809 | return r;
1810 | }
1811 |
1812 | void send_canbus_frames()
1813 | {
1814 | // Put our status info on the bus
1815 | {
1816 | CAN_FRAME frame;
1817 | frame.id = 0x600;
1818 | frame.length = 8;
1819 | bool request_inverter_disable = (evse_pp_cable_rating_a > 0 ||
1820 | evse_allowed_amps > 0 || (charger_state >= CS_WAITING_CANBUS &&
1821 | charger_state <= CS_STOPPING_CHARGE));
1822 | // Request main contactor, in addition to when it's actually needed,
1823 | // also when the inverter is requested to be disabled, so that the DC-DC
1824 | // can maintain charge in the 12V system.
1825 | bool request_main_contactor =
1826 | digitalRead(AC_PRECHARGE_SWITCH_PIN) || digitalRead(AC_CONTACTOR_SWITCH_PIN) ||
1827 | charger_state == CS_PRECHARGING || charger_state == CS_CHARGING ||
1828 | charger_state == CS_STOPPING_CHARGE || request_inverter_disable;
1829 | uint16_t pack_voltage_Vx10 = output_voltage_V * 10;
1830 | uint16_t charge_current_Ax10 = current_pwm == 0 ? 0 : output_dc_current_Ax10;
1831 | int8_t charger_temperature_c = boost_t1_c;
1832 | if(charger_temperature_c < boost_t2_c)
1833 | charger_temperature_c = boost_t2_c;
1834 | bool request_cooling = (charger_temperature_c > 40);
1835 |
1836 | frame.data.bytes[0] =
1837 | (request_main_contactor ? (1<<0) : 0) |
1838 | (false ? (1<<1) : 0) |
1839 | (false ? (1<<2) : 0) |
1840 | (request_inverter_disable ? (1<<3) : 0) |
1841 | (request_cooling ? (1<<4) : 0);
1842 | frame.data.bytes[1] = pack_voltage_Vx10 >> 8;
1843 | frame.data.bytes[2] = pack_voltage_Vx10 & 0xff;
1844 | frame.data.bytes[3] = output_dc_current_Ax10 / 10;
1845 | frame.data.bytes[4] = (pack_32A_into_4bits(evse_allowed_amps) << 4) |
1846 | pack_32A_into_4bits(evse_pp_cable_rating_a);
1847 | frame.data.bytes[5] = charger_temperature_c;
1848 | frame.data.bytes[6] = ((charger.fail_reason & 0x0f) << 4) | (charger_state & 0x0f);
1849 | frame.data.bytes[7] = force_ac_input_amps;
1850 |
1851 | if(!canc_send(system_can, frame)){
1852 | EVERY_N_MILLISECONDS(10000){
1853 | log_println_f("Failed to send CAN frame 0x600");
1854 | }
1855 | }
1856 | }
1857 |
1858 | // Put a separate message on the bus to disable the inverter when a cable is
1859 | // connected or we are charging
1860 | if(evse_pp_cable_rating_a > 0 || evse_allowed_amps > 0 ||
1861 | (charger_state >= CS_WAITING_CANBUS &&
1862 | charger_state <= CS_STOPPING_CHARGE)){
1863 | CAN_FRAME frame;
1864 | frame.id = 0x320;
1865 | frame.length = 8;
1866 |
1867 | frame.data.bytes[0] = 1;
1868 | frame.data.bytes[1] = 0;
1869 | frame.data.bytes[2] = 0;
1870 | frame.data.bytes[3] = 0;
1871 | frame.data.bytes[4] = 0;
1872 | frame.data.bytes[5] = 0;
1873 | frame.data.bytes[6] = 0;
1874 | frame.data.bytes[7] = 0;
1875 |
1876 | if(!canc_send(system_can, frame)){
1877 | EVERY_N_MILLISECONDS(10000){
1878 | log_println_f("Failed to send CAN frame 0x320");
1879 | }
1880 | }
1881 | }
1882 | }
1883 |
1884 | static void handle_canbus_frame(const CAN_FRAME &frame)
1885 | {
1886 | // BMS
1887 | if(frame.id == 0x100){
1888 | canbus_detected();
1889 |
1890 | canbus_status.permit_charge = frame.data.bytes[0] & (1<<0);
1891 | canbus_status.main_contactor_closed = frame.data.bytes[0] & (1<<2);
1892 | canbus_status.pack_voltage_V =
1893 | ((frame.data.bytes[1] << 8) | frame.data.bytes[2]) / 10;
1894 | return;
1895 | }
1896 | if(frame.id == 0x101){
1897 | canbus_detected();
1898 |
1899 | canbus_status.cell_voltage_min_mV = (uint16_t)((frame.data.bytes[0] << 4) |
1900 | (frame.data.bytes[1] >> 4)) * 10;
1901 | canbus_status.cell_voltage_max_mV = (uint16_t)(((frame.data.bytes[1] & 0x0f) << 8) |
1902 | frame.data.bytes[2]) * 10;
1903 | canbus_status.cell_temperature_min = frame.data.bytes[3];
1904 | canbus_status.cell_temperature_max = frame.data.bytes[4];
1905 | canbus_status.charge_completed = frame.data.bytes[5] & (1<<1);
1906 | return;
1907 | }
1908 | if(frame.id == 0x102){
1909 | canbus_detected();
1910 |
1911 | canbus_status.max_charge_current_A =
1912 | ((frame.data.bytes[2] << 8) | frame.data.bytes[3]) / 10;
1913 | return;
1914 | }
1915 |
1916 | // Configuration messages for ourselves
1917 | if(frame.id == 0x620){
1918 | // Set setting
1919 | uint8_t setting_id = frame.data.bytes[0];
1920 | uint16_t old_value = (frame.data.bytes[1] << 8) | frame.data.bytes[2];
1921 | uint16_t new_value = (frame.data.bytes[3] << 8) | frame.data.bytes[4];
1922 | if(setting_id == 0){ // AC input A limit setting
1923 | if(force_ac_input_amps == old_value){
1924 | force_ac_input_amps = new_value;
1925 | send_canbus_frames();
1926 |
1927 | log_print_timestamp();
1928 | CONSOLE.print(F("CANbus setting force_ac_input_amps = "));
1929 | CONSOLE.println(force_ac_input_amps);
1930 | }
1931 | }
1932 | if(setting_id == 1){
1933 | log_println_f("CANbus start charge");
1934 | start_charging();
1935 | }
1936 | if(setting_id == 2){
1937 | log_println_f("CANbus stop charge");
1938 | stop_charging();
1939 | }
1940 | if(setting_id == 3){
1941 | log_println_f("CANbus restore initial state");
1942 | restore_initial_state();
1943 | }
1944 | return;
1945 | }
1946 | }
1947 |
1948 | static void apply_canbus_timeouts()
1949 | {
1950 | if(CANBUS_ENABLE){
1951 | static bool canbus_reported_alive = false;
1952 | if(canbus_alive()){
1953 | if(!canbus_reported_alive &&
1954 | canbus_last_receive_timestamp != 0){
1955 | canbus_reported_alive = true;
1956 | log_println_f("CANbus up");
1957 | canbus_status = CanbusStatus(); // Reset status
1958 | }
1959 | } else {
1960 | if(canbus_reported_alive){
1961 | canbus_reported_alive = false;
1962 | log_println_f("CANbus lost");
1963 | canbus_status = CanbusStatus(); // Reset status
1964 | }
1965 | }
1966 | }
1967 | }
1968 |
1969 | static void read_canbus_frames()
1970 | {
1971 | if(CANBUS_ENABLE){
1972 | for(uint8_t i=0; i<10 && !digitalRead(MCP2515_INT_PIN); i++){
1973 | CAN_FRAME frame;
1974 | canc_read(system_can, frame);
1975 |
1976 | uint32_t &id = frame.id;
1977 | uint8_t &len = frame.length;
1978 | uint8_t *data = frame.data.bytes;
1979 |
1980 | handle_canbus_frame(frame);
1981 | }
1982 | }
1983 | }
1984 |
1985 | static bool canc_send(MCP_CAN &mcp_can, const CAN_FRAME &frame)
1986 | {
1987 | return (mcp_can.sendMsgBuf(frame.id, 0, frame.length,
1988 | frame.data.bytes) == CAN_OK);
1989 | }
1990 |
1991 | static bool canc_read(MCP_CAN &mcp_can, CAN_FRAME &frame)
1992 | {
1993 | memset(&frame, 0, sizeof frame);
1994 | uint8_t r = mcp_can.readMsgBuf(&frame.id, &frame.length, frame.data.bytes);
1995 | return (r == CAN_OK);
1996 | }
1997 |
1998 | static bool canbus_alive()
1999 | {
2000 | return timestamp_younger_than(canbus_last_receive_timestamp, CANBUS_TIMEOUT_MS);
2001 | }
2002 |
--------------------------------------------------------------------------------