最近、小型ソーラーパネルをポチッたのでソーラーパネルの発電の実験をしてみた。パネルの向きを決定するのが以外に面倒で簡単に太陽の方向に合わせる方法はないのかと調べてみたところ自作してる人がそれなりにいるようだ。その多くは光センサーによりパネルを太陽の方向に合わせる仕組みのようだが曇りや雨など暗いときに太陽の方法に向けることが難しそうに思える。暗いときにどっち向いてようが問題ないとは思うけどバグッてるようでカッコ悪いから計算で求めた太陽位置に向けるものを考えてみた。
太陽位置の計算(sun.h)は、株式会社気象データシステム様が公開されている拡張アメダス気象データ 内の技術解説一般【年差を考慮した太陽位置の簡易計算】のプログラムの一部をC言語に置き換えたものを利用しているがご厚意により正式に公開許可を頂けた。感謝。m(_ _)m
開発用にとアリエクスプレスで購入した製品と同じものがアマゾンでも売られているようだ。
製品に含まれているボードはお手軽で便利だ。USB給電のみでも無負荷ならサーボを動作させられるしUSBシリアル接続で書き込みもできてしまう。汎用の開発ボードとしても利用できるかも。
ファームウェアも公開されている。HWタイマーで信号作って動作してるのかなと思ってコードを確認してみたらな~~んと割り込みを使ったソフトウェア制御だったりしてちょっと衝撃を受けてしまった。しかもOLED表示させるとコントローラー操作のレスポンスが劇的に悪化してしまう。このプログラムは見なかったことにしよう...(-_-;)
開発はSTMicroelectronicsが公開してるArduino用の”STM32 MCU based boards by STMicroelectronics”
を利用したがライブラリにサーボが含まれていたのでコードを確認したらこちらも割り込みを使ったソフトウェア制御だった。
サーボってソフトウェア制御するのが今時なのか?と一瞬思ってしまったがソフトウェア制御だとCPU負荷は高いし正確な信号が出せないからサーボがプルプル震えたりするんじゃね?とか余計なことを考えてしまった結果、ハードウェア制御するサーボライブラリも作ってみた。
ボードのサーボ信号出力ピンはTIM1/2/3/4/5/8の各HWタイマーの出力ピンに合わせてあるのでハードウェア制御するつもりだったけれど作れなくて諦めてしまったのだろうか...それはともかく24CH同時にHWタイマーでPWM駆動できるライブラリを作ることはできた。50Hzの標準的なサーボのパルス範囲である2000usを6400分割した分解能でパルスを作ることが可能だ。
それと時刻と設定値の保存用にEEPROM付きRTCモジュールを使ってみた。設定値をEEPROMに保存すればRTCモジュールを入れ替えるだけで時刻も設定も引き継がれるのでとても便利だ。
WINGONEER 小型DS3231 AT24C32 I2Cモジュール用の高精度リアルタイムクロックモジュール,ボタン電池付き(A145)
※充電回路付きであるためモジュールに電源供給する場合は付属のボタン電池(CR2032)を使ってはいけない。充電電圧に適合するのはLIR2032のみ。他のML2032などでは過充電となるため絶対に使ってはいけない。
※DS3231/AT24CXX用のライブラリも新たに作成。
日付の設定は一度だけ必要。Arduino-IDEのシリアルモニターや端末などから”calendar 2024-08-06 12:00:00″の形式で現在時刻を送信すればOKだ。その他、各種パラメタも設定することができる。
【コマンド一覧】
calendar yy-mm-dd HH:MM:SS
latitude n
longitude n
longitude_std n
servo1.ch n
servo1.range n
servo1.min n
servo1.max n
servo2.ch n
servo2.range n
servo2.min n
servo2.max n
load
save
reset
config
debug [0 | 1]
turn [auto | min | center | max]
rtc +-n
※設定値を変更した後保存するにはsaveコマンドを実行し変更内容を適用するにはresetコマンドを実行する。
【動作実験中の様子】
【修正履歴】
2024-08-26
初めてDS3231を使ってみて一日数十ミリ秒程度の誤差には収まってはいるので特に不満はないのだが、GPSモジュールも入手しやすくなってるようなので調整する必要のないGPSクロックにしたほうがいいのかもと思う今日この頃...
あと、AT24C1024に対応してみた。試験してないけど。
2024-08-24
sun.hのSun::timeZoneOffset()をより汎用的な実装に変更。それと年の経過日(dayOfYear)が1からになっていたので0からに修正。
2024-08-23
株式会社気象データシステム様より太陽位置計算プログラムの公開許可を頂いた。
DS3231の誤差の件はようやく確認がとれた。PCの時刻と比較していたがPCの時刻にもかなりの誤差があったりして確認に手間取っていたがDS3231のAgingOffsetにより0.1-0.2ppm程度まで誤差を調整することができるようだ。
2024-08-22
DS3231ライブラリの仕様変更。
2024-08-21
DS3231ライブラリの仕様変更。
2024-08-20
DS3231ライブラリの機能追加とエラー処理の強化。起動時のサーボの動き方を変更。
2024-08-18
DS3231ライブラリをアラーム割り込みに対応。SQW(1Hz)を利用したDS3231のアラーム機能のエミュレーションなので下記のどちらかの方法でSQW(1Hz)設定とそのGPIOピン指定が必要。
DECLARE_DS3231(Wire) rtc;
rtc.begin(SQWピン番号)
or
rtc.begin();
rtc.outputSQW(rtc.SQWRATE_1);
rtc.emuratin(SQWピン番号);
2024-08-17
もう少し様子見する必要はあるがDS3231の誤差が大きい件は解決したかもしれない。
一秒に一回リードするだけでも時刻に影響を与えるようなのでDS3231ライブラリを修正し起動時に一回だけリードした後はDS3231のSQW(1Hz)信号によるGPIO割り込み処理にて日付更新していく方法に変更してみた。これで暫く様子をみてみよう。
2024-08-16
本当のことかどうかは確かめてないけどDS3231の頻繁なリードにより時刻が狂うという記事を見つけたので念の為その対策を行った。
DS3231のSQW(1Hz)出力により一秒に一回だけDS3231をリードするようにDS3231ライブラリを改良してみた。
しかし、想定外にDS3231の誤差が大きすぎるようだ。データシート通りの2ppmの誤差なら最大でも5-6日で一秒狂う計算になるはずが一日で一秒以上狂うし、エージングオフセットでも調整しきれないくらいの誤差だし、秒のタイミングが安定してないような気もするし...不良チップ或いはfakeチップなのだろうか?それとも何らかの外部的要因によるものなのか?とりあえずめいっぱい補正かけて一日0.5秒程度の誤差にはなったのだが根本的な原因が知りたいところだ。
2024-08-15
サーボ位置の微調整用のコマンドとRTC誤差補正コマンドを追加。AT24CXXのwriteメソッドがページ境界をまたがる書き込みをしたときの不具合を修正。
2024-08-14
軽微な最適化を行った。
2024-08-12
DS3231/AT24CXXに対応。その他バグ修正。
2024-08-09
高さの角度を0-90度に制限していたが赤道付近の地域など90度を前後する地域がありそうなので0-180度に設定変更。その他、メソッド名の変更など若干の修正を行った。
【スケッチ】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 |
/* SolarTracker.ino - Solar Tracking Control Program STM32 MCU based boards by STMicroelectronics [2.8.1] url : https://github.com/stm32duino/BoardManagerFiles/raw/main/package_stmicroelectronics_index.json Board: Generic STM32F1 series Board part number: "Generic F103RCTx" Upload method : "STM32QubeProgrammer (Serial)" U(S)ART support : "Enabled (no generic 'Serial')" Copyright (c) 2024 Sasapea's Lab. All right reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <string> #include <stdio.h> #include <string.h> #include <math.h> #include <Wire.h> #include "solartracker.h" #include "servo24.h" #include "at24cxx.h" #include "ds3231.h" #if !defined(DECLARE_DS3231) #include "rtc.h" #endif #define DEFAULT_LATITUDE 35.69 /* 規定の設置場所の緯度 */ #define DEFAULT_LONGITUDE 139.75 /* 規定の設置場所の経度 */ #define DEFAULT_LONGITUDE_STD 135 /* 規定の標準時の経度 */ #define PIN_LED PC13 #define PIN_DS3231_SQW PB8 HardwareSerial Serial(USART1); class SolarTracker : public SolarTrackerBase { public: SolarTracker(void) : SolarTrackerBase() { _debug = false; _turnmode = 0; _initmode = 3; } void begin(void) { /* Setup Wire Clock */ Wire.setClock(_rtc.WIRE_CLOCK); /* Setup EEPROM */ _eeprom.begin(); /* Load Config Data from EEPROM */ loadConfig(); /* Setup RTC */ #if defined(DECLARE_DS3231) && defined(PIN_DS3231_SQW) _rtc.begin(PIN_DS3231_SQW); #else _rtc.begin(); #endif #if defined(DECLARE_DS3231) _rtc.setAgingOffset(_config.rtcoff); #endif /* Init LED */ initLED(); /* Setup Servo */ for (size_t i = 0; i < lengthof(specs); ++i) { _servo[i].begin((Servo24::SERVO)_config.servo[i].ch, _config.servo[i].range, _config.servo[i].min, _config.servo[i].max); _servo[i].turn(_servo[i].anglerange() >> 1); } /* Setup SolarTracker */ SolarTrackerBase::begin(_config.latitude, _config.longitude, _config.longitude_std); SolarTrackerBase::delay(SERVO_DELAY); } uint16_t turn(const struct tm &tmbuf, float h, float a, uint16_t delay) override { /* debug print */ if (_debug) { Serial.printf("%02d-%02d-%02d %02d:%02d:%02d, h = %d.%02d, a = %d.%02d\n", tmbuf.tm_year + 1900, tmbuf.tm_mon + 1, tmbuf.tm_mday, tmbuf.tm_hour, tmbuf.tm_min, tmbuf.tm_sec, to_string(h, 2).c_str(), to_string(a, 2).c_str()); } /* 太陽位置が追尾範囲内なら回転させる (南は180度) */ a -= 180 - (_servo[0].anglerange() >> 1); if ((h >= 0) && (h <= _servo[1].anglerange()) && (a >= 0) && (a <= _servo[0].anglerange())) { _servo[0].turn(a, delay); _servo[1].turn(h, delay); return 0; } /* 故障や保守のため太陽位置が追尾範囲外になったら中立位置に戻しておく */ else if (delay == 0) { _servo[0].turn(_servo[0].anglerange() >> 1, SERVO_DELAY); _servo[1].turn(_servo[1].anglerange() >> 1, SERVO_DELAY); } /* 翌日の日の出時にゆっくり回転させるための回転時間(ミリ秒)を指定 */ /* 次回の呼び出し以降、引数delayにこの値が設定される */ return SERVO_DELAY; } void tracking(void) { struct tm &tmbuf = getCalendar(); if (_initmode) { if (!_servo[0].busy() && !_servo[1].busy()) { if (_initmode) turn(--_initmode + 1); } } else if (_turnmode == 0) SolarTrackerBase::tracking(tmbuf); config(); } private: void config(void) { static char cmd[128]; static size_t cnt; while (Serial.available()) { char c = Serial.read(); if ((c == '\r') || (c == '\n')) { if (cnt) { char *arg; cmd[cnt] = 0; if ((arg = strchr(cmd, ' '))) { *arg++ = 0; while (*arg == ' ') arg++; } else arg = &cmd[cnt]; cnt = 0; if (strcasecmp(cmd, "calendar") == 0) { _tmbuf.tm_sec = 0; if (sscanf(arg, "%d%c%d%c%d %d%c%d%c%d", &_tmbuf.tm_year, &c, &_tmbuf.tm_mon, &c, &_tmbuf.tm_mday, &_tmbuf.tm_hour, &c, &_tmbuf.tm_min, &c, &_tmbuf.tm_sec) >= 8) { _tmbuf.tm_year -= 1900; _tmbuf.tm_mon -= 1; setCalendar(_tmbuf); } getCalendar(); Serial.printf("%02d-%02d-%02d %02d:%02d:%02d\n", _tmbuf.tm_year + 1900, _tmbuf.tm_mon + 1, _tmbuf.tm_mday, _tmbuf.tm_hour, _tmbuf.tm_min, _tmbuf.tm_sec); } else if (strcasecmp(cmd, "latitude") == 0) _config.latitude = atof(arg); else if (strcasecmp(cmd, "longitude") == 0) _config.longitude = atof(arg); else if (strcasecmp(cmd, "longitude_std") == 0) _config.longitude_std = atof(arg); else if (strncasecmp(cmd, "servo", 5) == 0) { char *part; size_t ch = strtol(cmd + 5, &part, 10); if ((ch > 0) && (ch <= lengthof(specs))) { --ch; if (strcasecmp(part, ".ch") == 0) _config.servo[ch].range = (Servo24::SERVO)atoi(arg); else if (strcasecmp(part, ".range") == 0) _config.servo[ch].range = atoi(arg); else if (strcasecmp(part, ".min") == 0) { _config.servo[ch].min = atoi(arg); _servo[ch].pulse(_config.servo[ch].min, _config.servo[ch].max, true); } else if (strcasecmp(part, ".max") == 0) { _config.servo[ch].max = atoi(arg); _servo[ch].pulse(_config.servo[ch].min, _config.servo[ch].max, true); } else Serial.printf("-- invalid command --\n"); } else Serial.printf("-- invalid command --\n"); } #if defined(DECLARE_DS3231) else if (strcasecmp(cmd, "rtc") == 0) _rtc.setAgingOffset(_config.rtcoff = atoi(arg)); #endif else if (strcasecmp(cmd, "load") == 0) loadConfig(); else if (strcasecmp(cmd, "save") == 0) saveConfig(); else if (strcasecmp(cmd, "reset") == 0) __NVIC_SystemReset(); else if (strcasecmp(cmd, "config") == 0) { Serial.printf("[configurations]\n"); Serial.printf(" latitude = %d.%02d\n", (int)_config.latitude , (int)(abs(_config.latitude) * 100) % 100); Serial.printf(" longitude = %d.%02d\n", (int)_config.longitude , (int)(abs(_config.longitude) * 100) % 100); Serial.printf(" longitude_std = %d.%02d\n", (int)_config.longitude_std, (int)(abs(_config.longitude_std) * 100) % 100); for (size_t i = 0; i < lengthof(specs); ++i) Serial.printf(" servo%d { .ch = %d, .range = %d, .min = %d, .max = %d }\n", i + 1, _config.servo[i].ch, _config.servo[i].range, _config.servo[i].min, _config.servo[i].max); #if defined(DECLARE_DS3231) Serial.printf(" RTC.AgingOffset = %d\n", _config.rtcoff); #endif } else if (strcasecmp(cmd, "debug") == 0) _debug = atoi(arg); else if (strcasecmp(cmd, "turn") == 0) { if (strcasecmp(arg, "auto") == 0) { if (_turnmode) { SolarTrackerBase::delay(SERVO_DELAY); SolarTrackerBase::tracking(getCalendar(), true); } _turnmode = 0; } else if (strcasecmp(arg, "center") == 0) turn(_turnmode = 1); else if (strcasecmp(arg, "max") == 0) turn(_turnmode = 2); else if (strcasecmp(arg, "min") == 0) turn(_turnmode = 3); else Serial.printf("-- invalid command --\n"); } else if (cmd[0]) Serial.printf("-- invalid command --\n"); } } else if (cnt < sizeof(cmd) - 1) cmd[cnt++] = c; } } void turn(uint8_t mode) { switch (mode) { case 1: _servo[1].turn(_servo[1].anglerange() >> 1, SERVO_DELAY); _servo[0].turn(_servo[0].anglerange() >> 1, SERVO_DELAY); break; case 2: _servo[1].turn(_servo[1].anglerange(), SERVO_DELAY); _servo[0].turn(_servo[0].anglerange(), SERVO_DELAY); break; case 3: _servo[1].turn(0, SERVO_DELAY); _servo[0].turn(0, SERVO_DELAY); break; } } struct tm &getCalendar(void) { _rtc.getCalendar(_tmbuf); turnLED(_tmbuf.tm_sec & 1); return _tmbuf; } void setCalendar(struct tm &tmbuf) { _rtc.setCalendar(tmbuf); } void loadConfig(void) { const uint16_t MARKER = 0xDEFA; _config.marker = 0; #if defined(DECLARE_AT24C32) _eeprom.read(0, &_config, sizeof(_config)); #endif if (_config.marker != MARKER) { _config.marker = MARKER; _config.latitude = DEFAULT_LATITUDE; _config.longitude = DEFAULT_LONGITUDE; _config.longitude_std = DEFAULT_LONGITUDE_STD; for (size_t i = 0; i < lengthof(specs); ++i) { _config.servo[i].ch = specs[i].ch; _config.servo[i].range = specs[i].range; _config.servo[i].min = specs[i].min; _config.servo[i].max = specs[i].max; } #if defined(DECLARE_DS3231) _config.rtcoff = 0; #endif saveConfig(); } } void saveConfig(void) { #if defined(DECLARE_AT24C32) _eeprom.write(0, &_config, sizeof(_config)); #endif } static std::string to_string(float value, uint8_t precision = 6) { char buf[32]; if (precision > 6) precision = 6; bool sign = value < 0; value = abs(value); unsigned long decimal = pow(10, precision); snprintf(buf, sizeof(buf), "%s%lu.%0*lu", sign ? "-" : "", (unsigned long)value, precision, (unsigned long)(value * decimal) % decimal); return std::string(buf); } static void initLED(void) { #if defined(PIN_LED) pinMode(PIN_LED, OUTPUT); #endif } static void turnLED([[maybe_unused]] bool on) { #if defined(PIN_LED) digitalWrite(PIN_LED, on ? HIGH : LOW); #endif } static constexpr uint16_t SERVO_DELAY = 3000; static constexpr struct { uint16_t ch; uint16_t range; uint16_t min; uint16_t max; } specs[] = { { Servo24::SERVO_1, 270, 2500, 500 }, { Servo24::SERVO_2, 180, 500, 2500 }, }; typedef struct { uint32_t marker; float latitude; float longitude; float longitude_std; struct { uint16_t ch; uint16_t range; uint16_t min; uint16_t max; } servo[lengthof(specs)]; #if defined(DECLARE_DS3231) int8_t rtcoff; #endif } config_t; config_t _config; Servo24 _servo[lengthof(specs)]; struct tm _tmbuf; #if defined(DECLARE_DS3231) DECLARE_DS3231(Wire) _rtc; #else Rtc _rtc; #endif #if defined(DECLARE_AT24C32) DECLARE_AT24C32(Wire) _eeprom; #endif bool _debug; uint8_t _turnmode; uint8_t _initmode; }; SolarTracker solar; HardwareTimer timx(TIM4); void setup() { /* Setup Serial */ Serial.begin(115200); /* Setup Wire I2C-1 PB7(sda) PB6(scl) I2C-2 PB9(sda) PB8(scl), *** Remap the I2C before call begin() *** I2C-3 PB11(sda) PB10(scl) */ Wire.setSCL(PB_6); Wire.setSDA(PB_7); Wire.begin(); /* Setup SolarTracker */ solar.begin(); } void loop() { solar.tracking(); #if !defined(PIN_DS3231_SQW) delay(100); #endif } |
【ライブラリ】
サーボ・ライブラリはbegin()の最小パルス幅(pulsemin)/最大パルス幅(pulsemax)引数を逆に指定することで回転方向が逆になる。
回転範囲の制限は角度値(angle)を調整するのではなくbegin()の最小パルス幅(pulsemin)/最大パルス幅(pulsemax)引数で調整すべき。
分解能を上げたいときは回転範囲(anglerange)を大きくする。6400を指定すると最大分解能となる。それ以上を指定することもできるが分解能的には意味がない。
サーボの制御信号タイミングはHWタイマー毎に同じなので制御タイミングが重要ならHWタイマー毎に4個ずつサーボをペアにすること。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 |
/* servo24.h - 24 Channel Servo Motor Library for STM32 Family 2024-08-02: First Version for STM32F103RCT6 Copyright (c) 2024 Sasapea's Lab. All right reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include <stdint.h> #include <stdbool.h> #include "ticktimer.h" #include "HardwareTimer.h" #define lengthof(a) (sizeof(a) / sizeof(a[0])) class Servo24 { public: typedef enum { SERVO_1 , SERVO_2 , SERVO_3 , SERVO_4 , SERVO_5 , SERVO_6 , SERVO_7 , SERVO_8 , SERVO_9 , SERVO_10, SERVO_11, SERVO_12, SERVO_13, SERVO_14, SERVO_15, SERVO_16, SERVO_17, SERVO_18, SERVO_19, SERVO_20, SERVO_21, SERVO_22, SERVO_23, SERVO_24, } SERVO; Servo24(void) : _instance(nullptr) { _anglerange = 0; _angle = 0; } virtual ~Servo24(void) { end(); } /* The argument period can only be changed on a per timer. */ bool begin(SERVO channel, uint16_t anglerange = 180, uint16_t pulsemin = 500, uint16_t pulsemax = 2500, uint16_t period = 20000) { if (_instance) return false; _index = channel / lengthof(TIMMAP[0].pinname); _channel = channel % lengthof(TIMMAP[0].pinname); _anglerange = anglerange; _pulsemin = pulsemin; _pulsemax = pulsemax; _delay = 0; _count = 0; _angle = (uint16_t)-1; _angleto = 0; _anglefrom = 0; const timmap_t &map = TIMMAP[_index]; timobj_t &obj = timobj[_index]; if (obj.servo[_channel]) return false; obj.servo[_channel] = this; if (obj.instance == nullptr) { obj.period = period; obj.instance = new HardwareTimer(map.instance); obj.instance->setOverflow(period, MICROSEC_FORMAT); obj.instance->resume(); /* start TIMx clock */ } _period = obj.period; _instance = obj.instance; _overflow = _instance->getOverflow(TICK_FORMAT); _instance->setMode(_channel + 1, TIMER_OUTPUT_COMPARE_PWM1, map.pinname[_channel]); _instance->setCaptureCompare(_channel + 1, 0, TICK_COMPARE_FORMAT); /* no signal */ _instance->resumeChannel(_channel + 1); /* start TIMx channel */ _ticktimer.begin(_period > 2000 ? _period / 2000 : 1, tick0, this); return true; } void end(void) { if (_instance) { unregister(); _instance = nullptr; } } bool turn(uint16_t angle, uint16_t delay = 0, bool wait = false) { if (angle > _anglerange) return false; if (angle == _angle) return true; _ticktimer.stop(); _delay = delay; _count = 0; _anglefrom = (_angle != (uint16_t)-1 ? _angle : angle); _angleto = angle; if (delay) { if (_anglefrom != _angleto) { _ticktimer.start(); if (wait) ::delay(delay); } } else turn0(angle); return true; } void pulse(uint16_t min, uint16_t max, bool turn = false) { _pulsemin = min; _pulsemax = max; if (turn && (_angle != (uint16_t)-1)) turn0(_angle, true); } uint16_t anglerange(void) { return _anglerange; } bool busy(void) { return _ticktimer.running(); } private: void unregister(void) { _ticktimer.stop(); timobj_t &obj = timobj[_index]; obj.servo[_channel] = nullptr; for (uint32_t i = 0; i < lengthof(obj.servo); ++i) { if (obj.servo[i]) return; } delete obj.instance; obj.instance = nullptr; } void turn0(uint16_t angle, bool force = false) { if (force || (_angle != angle)) { _angle = angle; _instance->setCaptureCompare(_channel + 1, _overflow * (_pulsemin + (int32_t)(int16_t)(_pulsemax - _pulsemin) * angle / _anglerange) / _period, TICK_COMPARE_FORMAT); } } void tick(void) { if ((_count += _ticktimer.millis()) < _delay) turn0(_anglefrom + (int32_t)(int16_t)(_angleto - _anglefrom) * _count / _delay); else { _ticktimer.stop(); turn0(_angleto); } } static void tick0(void *argument) { ((Servo24 *)argument)->tick(); } HardwareTimer *_instance; uint16_t _index; uint16_t _channel; uint16_t _anglerange; uint16_t _pulsemin; uint16_t _pulsemax; uint16_t _period; uint32_t _overflow; uint16_t _delay; uint16_t _count; uint16_t _angle; uint16_t _angleto; uint16_t _anglefrom; TickTimer _ticktimer; typedef struct { TIM_TypeDef *instance; PinName pinname[4]; } timmap_t; /* STM32F103RCT6: Yahboom YB_ESV01 24Ch Servo Board */ static constexpr timmap_t TIMMAP[] = { { TIM5, { PA_0_ALT2 , PA_1_ALT2, PA_2_ALT2 , PA_3_ALT2 } }, { TIM3, { PB_4 , PB_5 , PB_0_ALT2 , PB_1_ALT2 } }, { TIM2, { PA_15_ALT1, PB_3_ALT1, PB_10_ALT1, PB_11_ALT1 } }, { TIM4, { PB_6 , PB_7 , PB_8 , PB_9 } }, { TIM8, { PC_6_ALT1 , PC_7_ALT1, PC_8_ALT1 , PC_9_ALT1 } }, { TIM1, { PA_8 , PB_14 , PB_15 , PA_11 } } }; typedef struct { HardwareTimer *instance; Servo24 *servo[lengthof(TIMMAP[0].pinname)]; uint16_t period; } timobj_t; static timobj_t timobj[lengthof(TIMMAP)]; }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/* servo24.cpp - 24 Channel Servo Motor Library for STM32 Family Copyright (c) 2024 Sasapea's Lab. All right reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "servo24.h" Servo24::timobj_t Servo24::timobj[]; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
/* ticktimer.h - SysTick Timer Library for ARDUINO (AVR/STM32) Copyright (c) 2024 Sasapea's Lab. All right reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include <stdint.h> #include <stdbool.h> #include <vector> #include "cpu.h" #if !defined(ARDUINO_ARCH_AVR) #include <functional> #endif class TickTimer { public: #if defined(ARDUINO_ARCH_AVR) typedef void (*callback_t)(void); #else typedef std::function<void(void)> callback_t; #endif void begin(uint32_t millis, callback_t callback) { if (!initialized) { initialized = true; instances.clear(); initOnce(); } _millis = millis; _callback = callback; _running = false; } void start(void) { if (!_running && _millis && _callback) { Cpu::state_t save = Cpu::disableInterrupts(); instances.push_back(this); Cpu::restoreInterrupts(save); _count = 0; _running = true; } } void stop(void) { if (_running) { _running = false; auto it = std::find(instances.begin(), instances.end(), this); if (it != instances.end()) { Cpu::state_t save = Cpu::disableInterrupts(); instances.erase(it); Cpu::restoreInterrupts(save); } } } bool running(void) { return _running; } uint32_t millis(void) { return _millis; } private: void tick(void) { if (_running && (++_count >= _millis)) { _count = 0; if (_callback) _callback(); } } static void tick0(void) { for (TickTimer *inst: instances) inst->tick(); } static void initOnce(void); /* timer initialize */ friend void TickTimer_Tick(void); static bool initialized; static std::vector<TickTimer *> instances; uint32_t _millis; callback_t _callback; bool _running; uint32_t _count; }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
/* ticktimer.cpp - SysTick Timer Library for ARDUINO (AVR/STM32) Copyright (c) 2024 Sasapea's Lab. All right reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ticktimer.h" bool TickTimer::initialized = false; std::vector<TickTimer *> TickTimer::instances; inline void TickTimer_Tick(void) { TickTimer::tick0(); } #if defined(ARDUINO_ARCH_AVR) #if defined(TIFR) #define TIFR0 TIFR #endif #if defind(TIMSK) #define TIMSK0 TIMSK #endif #if (F_CPU == 16000000) || (F_CPU == 16500000) #define PERIOD_US 4 #elif (F_CPU == 8000000) #define PERIOD_US 8 #else #error "System Clock Not Supported. (8MHz or 16MHz)" #endif ISR(TIMER0_COMPA_vect) { OCR0A += (1000 / PERIOD_US); TickTimer_Tick(); } void TickTimer::initOnce(void) { TCCR0A = 0; // standard mode OCR0A = TCNT0 + (1000 / PERIOD_US); TIFR0 = _BV(OCF0A); TIMSK0 |= _BV(OCIE0A); } #elif defined(ARDUINO_ARCH_ESP8266) #error "ESP8266 Not Supported" #elif defined(ARDUINO_ARCH_ESP32) #error "ESP32 Not Supported" #elif defined(ARDUINO_ARCH_SAMD) #error "SAMD Not Supported" #elif defined(ARDUINO_ARCH_NRF5) #error "NRF52 Not Supported" #elif defined(ARDUINO_ARCH_RP2040) #error "RP2040 Not Supported" #elif defined(ARDUINO_ARCH_STM32) // && defined(ARDUINO_GENERIC_F103RCTX) /* for STM32 based boards by STMicroelectronics */ extern "C" void HAL_SYSTICK_Callback(void) { TickTimer_Tick(); } void TickTimer::initOnce(void) { } #else #error "CPU Not Supported" #endif |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 |
/* cpu.h - CPU Library for ARDUINO (AVR/ESP8266/ESP32/ARM) Copyright (c) 2024 Sasapea's Lab. All right reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include "Arduino.h" #if defined(ARDUINO_ARCH_AVR) #include <avr/interrupt.h> class Cpu { public: typedef uint8_t state_t; static inline state_t disableInterrupts(void) { state_t save = SREG; cli(); return save; } static inline void restoreInterrupts(state_t save) { SREG = save; } }; #elif defined(ARDUINO_ARCH_ESP8266) class Cpu { public: typedef size_t state_t; static inline state_t disableInterrupts(void) { return noInterrupts(); } static inline void restoreInterrupts(state_t save) { xt_wsr_ps(save); } }; #elif defined(ARDUINO_ARCH_ESP32) class Cpu { public: typedef size_t state_t; static inline state_t disableInterrupts(void) { return portSET_INTERRUPT_MASK_FROM_ISR(); } static inline void restoreInterrupts(state_t save) { portCLEAR_INTERRUPT_MASK_FROM_ISR(save); } }; #elif defined(ARDUINO_ARCH_STM32) \ || defined(ARDUINO_ARCH_SAMD) \ || defined(ARDUINO_ARCH_NRF5) \ || defined(ARDUINO_ARCH_RP2040) class Cpu { public: typedef size_t state_t; static inline state_t disableInterrupts(void) { state_t save = __get_PRIMASK(); __disable_irq(); return save; } static inline void restoreInterrupts(state_t save) { __set_PRIMASK(save); } }; #else class Cpu { public: typedef size_t state_t; static inline state_t disableInterrupts(void) { noInterrupts(); return 0; } static inline void restoreInterrupts(state_t save) { (void)save; interrupts(); } }; #endif |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 |
/* sun.h - Sun Time and Position Library Copyright (c) 2024 Sasapea's Lab. All right reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #ifndef _POSIX_THREAD_SAFE_FUNCTIONS #define _POSIX_THREAD_SAFE_FUNCTIONS #endif #include <math.h> #include <time.h> #pragma push_macro("DEG") #pragma push_macro("RAD") #undef DEG #define DEG (180 / M_PI) #undef RAD #define RAD (M_PI / 180) class Sun { public: void begin(void) { _rise = -1; _set = -1; _degh = -1; _dega = -1; _in0 = -1; } /************************************* 現在日の出/日の入り時刻を計算する *************************************/ void time(float lat, float lon) { time(lat, lon, timeZoneOffset()); } void time(float lat, float lon, int tzoff) { struct tm tm; time_t now = ::time(nullptr); ::localtime_r(&now, &tm); time(tm, lat, lon, tzoff); } /************************************* 指定日の日の出/日の入り時刻を計算する *************************************/ void time(const struct tm &date, float lat, float lon) { time(date, lat, lon, timeZoneOffset()); } void time(const struct tm &date, float lat, float lon, int tzoff) { int n = dayOfYear(date); int m = isLeapYear(date.tm_year + 1900) ? 366 : 365; suntime(lat, lon, n, m, tzoff, _rise, _set); } /************************************* 日の出時刻を取得 *************************************/ int rise(void) { return _rise; } /************************************* 日の入り時刻を取得 *************************************/ int set(void) { return _set; } /************************************* 時間値の抽出 *************************************/ static void timepart(int value, int &hour, int &minute, int &second) { hour = value / 3600 % 24; minute = value / 60 % 60; second = value % 60; } /************************************* 現在時刻の太陽の位置を計算する *************************************/ void pos(float lat, float lon, float lons) { struct tm tm; time_t now = ::time(nullptr); ::localtime_r(&now, &tm); pos(tm, lat, lon, lons); } /************************************* 指定時刻の太陽の位置を計算する *************************************/ void pos(const struct tm &date, float lat, float lon, float lons) { float t, dlt; sunpos(date, lon, lons, t, dlt, _in0); horisys(lat, t, dlt, _degh, _dega); } /************************************* 太陽高度(度)を取得 *************************************/ float degh(void) { return _degh; } /************************************* 太陽方位角(北:0度、東:90度、南:180度、西:270度)を取得 *************************************/ float dega(void) { return _dega; } /************************************* 大気外法線面日射量を取得 *************************************/ float in0(void) { return _in0; } protected: static int timeZoneOffset(void) { static int tzoff = 1; if (tzoff == 1) { struct tm l, g; time_t t = ::time(nullptr); tzoff = mktime(localtime_r(&t, &l)) - mktime(gmtime_r(&t, &g)); } return tzoff; } static bool isLeapYear(int year) { return ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))); } static int dayOfYear(const struct tm &date) { const int YDAYS[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; return YDAYS[date.tm_mon] + date.tm_mday + ((date.tm_mon >= 2) && isLeapYear(date.tm_year + 1900)) - 1; } /************************************************************************* Original Source: http://radiopench.blog96.fc2.com/blog-entry-735.html Arduinoで日の出・日の入り時刻を計算 近似式を使って日の出・日の入り時刻を求める。 by ラジオペンチ, 2017/5/10, http://radiopench.blog96.fc2.com/ 参考サイト http://k-ichikawa.blog.enjoy.jp/etc/HP/js/sunRise/srs.html http://www.iot-kyoto.com/satoh/2016/01/22/post-99/ *************************************************************************/ static void suntime(float lat, float lon, int nday, int mday, int tzsec, int &rise, int &set) { lat *= RAD; rise = sunrise(lon, lat, nday, mday) * 3600 + tzsec; if (rise < 0) rise += 86400; set = sunset(lon, lat, nday, mday) * 3600 + tzsec; if (set < 0) set += 86400; } static float sunrise(float x, float y, int n, int m) // 日の出時刻を求める関数 { float d = dcalc(n, m); // 太陽赤緯を求める float e = ecalc(n, m); // 均時差を求める // 太陽の時角幅を求める (視半径、大気差などを補正 (-0.899度)) float t = acos((sin(-0.899 * RAD) - sin(d) * sin(y)) / (cos(d) * cos(y))) * DEG; return (-t + 180 - x) / (360 / 24) - e; // 日の出時刻を返す } static float sunset(float x, float y, int n, int m) // 日の入り時刻を求める関数 { float d = dcalc(n, m); // 太陽赤緯を求める float e = ecalc(n, m); // 均時差を求める // 太陽の時角幅を求める (視半径、大気差などを補正 (-0.899度)) float t = acos((sin(-0.899 * RAD) - sin(d) * sin(y)) / (cos(d) * cos(y))) * DEG; return (t + 180 - x) / (360 / 24) - e; // 日の入り時刻を返す } static float dcalc(int n, int m) // 近似式で太陽赤緯を求める { float w = (n + 0.5) * 2 * M_PI / m; // 日付をラジアンに変換 float d = + 0.33281 - 22.984 * cos(w) - 0.34990 * cos(2 * w) - 0.13980 * cos(3 * w) + 3.7872 * sin(w) + 0.03250 * sin(2 * w) + 0.07187 * sin(3 * w); return d * RAD; // 赤緯を返す(単位はラジアン) } static float ecalc(int n, int m) // 近似式で均時差を求める { float w = (n + 0.5) * 2 * M_PI / m; // 日付をラジアンに換算 float e = + 0.0072 * cos(w) - 0.0528 * cos(2 * w) - 0.0012 * cos(3 * w) - 0.1229 * sin(w) - 0.1565 * sin(2 * w) - 0.0041 * sin(3 * w); return e; // 均一時差を返す(単位は時) } int _rise; int _set; /************************************************************************* Original Source: 年差を考慮した太陽位置の簡易計算 (TE_Simplified_SP_230724.pdf) 202306 AKASAKA Hiroshi 太陽位置を計算するプログラム 地点緯度lat, 経度lon, 標準時経度lons, 計算対象日付dateを指定する。 株式会社気象データシステム(https://metds.co.jp/) 資料一覧: https://metds.co.jp/documents/ea/ *************************************************************************/ static void sunpos(const struct tm &date, float lon, float lons, float &t, float &dlt, float &in0) { const float J0 = 1.37; int year = date.tm_year + 1900; // // 黄道傾斜角の計算 // float dlt0 = -23.4393 + 0.013 * (year - 2000.0) / 100; // // 地方標準時(日本ならJST)1月1日基準の通算計算対象時刻nday(日)の計算 // float nday = dayOfYear(date) + date.tm_hour / 24.0 + date.tm_min / (24.0 * 60.0) + date.tm_sec / (24.0 * 60.0 * 60.0) - lons / (24.0 * 15.0); // // 平均近点角mの計算 // float n = year - 1968.0; float m = 0.9856 * (nday - (3.71 + 0.2596 * n - (int)((n + 3.0) / 4.0))); // // 冬至点と近日点がなす角度eps、真近点角vの計算 // float eps = 12.3901 + 0.0172 * (n+m / 360.0); float v = m + 1.918 * sin(m * RAD) + 0.02 * sin(2.0 * m * RAD); // // 均時差et(°)の計算 // float veps = (v + eps) * RAD; float et = (m - v) - atan(0.043 * sin(2.0 * veps) / (1.0 - 0.043 * cos(2.0 * veps))) / RAD; // // 大気外法線面日射量IN0の計算 // in0 = J0 * (1.0 + 0.033 * cos(RAD * v)); // // 視赤緯dlt(°)の計算 // float sindlt = cos(veps) * sin(RAD * dlt0); dlt = asin(sindlt) / RAD; // // 時角t(°)の計算 // t = 15.0 * (date.tm_hour + date.tm_min / 60.0 + date.tm_sec / 3600.0 - 12.0) + (lon - lons) + et; } /*************************************************************************************** 緯度lat(°)、時角t(°)、視赤緯dlt(°)、均時差et(°)を受け、 太陽高度degh(°)、太陽方位角dega(°)を返すサブプログラム ****************************************************************************************/ static void horisys(float lat, float t, float dlt, float °h, float °a) { float sinh = sin(RAD * lat) * sin(RAD * dlt) + cos(RAD * lat) * cos(RAD * dlt) * cos(RAD * t); float cosh = sqrt(1.0 - sinh * sinh); float sina = cos(RAD * dlt) * sin(RAD * t) / cosh; float cosa = (sinh * sin(RAD * lat) - sin(RAD * dlt)) / (cosh * cos(RAD * lat)); // degh = asin(sinh) / RAD; if (sina > 0) dega = 180 + 90.0 - atan(cosa / sina) / RAD; else if (sina == 0) dega = 0.0; else dega = 180 - 90.0 - atan(cosa / sina) / RAD; } float _degh; float _dega; float _in0; }; #pragma pop_macro("RAD") #pragma pop_macro("DEG") |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
/* solartracker.h - Sun Tracking Control with Servo Motor Copyright (c) 2024 Sasapea's Lab. All right reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include <stdint.h> #include <stdbool.h> #include "sun.h" class SolarTrackerBase { public: void begin(float lat, float lon, float lons) { _sun.begin(); _lat = lat; _lon = lon; _lons = lons; _minutes = -1; _start = 0; _delay = 0; } void tracking(struct tm &tmbuf, bool force = false) { if (_start) { if (millis() - _start < _delay) return; _start = 0; _delay = 0; } if (force || (_minutes != tmbuf.tm_min)) { _minutes = tmbuf.tm_min; _sun.pos(tmbuf, _lat, _lon, _lons); uint16_t rv = turn(tmbuf, _sun.degh(), _sun.dega(), _delay); if (rv) _delay = rv; else _start = millis(); } } void delay(uint32_t millis) { _delay = millis; } virtual uint16_t turn(const struct tm &tmbuf, float h, float a, uint16_t delay) = 0; private: float _lat; float _lon; float _lons; int _minutes; uint32_t _start; uint32_t _delay; Sun _sun; }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
/* at24cxx.h - AT24CXX EEPROM Library for ARDUINO Copyright (c) 2024 Sasapea's Lab. All right reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #define DECLARE_AT24C32(instance) AT24CXX<typeof(instance), instance, 32, 4096> #define DECLARE_AT24C64(instance) AT24CXX<typeof(instance), instance, 32, 8192> #define DECLARE_AT24C128(instance) AT24CXX<typeof(instance), instance, 64, 16384> #define DECLARE_AT24C256(instance) AT24CXX<typeof(instance), instance, 64, 32768> #define DECLARE_AT24C512(instance) AT24CXX<typeof(instance), instance, 128, 65536> #define DECLARE_AT24C1024(instance) AT24CXX<typeof(instance), instance, 256, 131072> template<typename WIRE_T, WIRE_T& WIRE, size_t PAGE_SIZE, size_t ROM_SIZE> class AT24CXX { public: static constexpr uint32_t WIRE_CLOCK = 400000; enum { ERR_NONE = 0, ERR_IO = 4, ERR_ARG = 8, }; void begin(uint8_t addr = 0x57) { /* Initialize Wire with setup() */ _address = addr; _errcode = 0; } bool read(size_t addr, void *buf, size_t len) { if ((addr + len > ROM_SIZE) || (!buf && len)) { _errcode = ERR_ARG; return false; } uint8_t *ptr = (uint8_t *)buf; while (len) { size_t n = PAGE_SIZE - (addr % PAGE_SIZE); if (len < n) n = len; if (!read0(addr, ptr, n)) return false; ptr += n; addr += n; len -= n; } _errcode = ERR_NONE; return true; } bool write(size_t addr, const void *buf, size_t len) { if ((addr + len > ROM_SIZE) || (!buf && len)) { _errcode = ERR_ARG; return false; } const uint8_t *ptr = (const uint8_t *)buf; while (len) { size_t n = PAGE_SIZE - (addr % PAGE_SIZE); if (len < n) n = len; if (!write0(addr, ptr, n)) return false; ptr += n; addr += n; len -= n; delay(20); } _errcode = ERR_NONE; return true; } int errcode(void) { return _errcode; } private: uint8_t devaddr(size_t addr) { return ROM_SIZE <= 0xFFFF ? _address : (addr <= 0xFFFF ? _address & ~1 : _address | 1); } bool read0(size_t addr, void *buf, size_t len) { if (!write0(addr, nullptr, 0, false)) return false; WIRE.requestFrom(devaddr(addr), len); return (_errcode = WIRE.readBytes((uint8_t *)buf, len) == len ? ERR_NONE : ERR_IO) == ERR_NONE; } bool write0(size_t addr, const void *buf, size_t len, uint8_t sendStop = true) { WIRE.beginTransmission(devaddr(addr)); if ((_errcode = WIRE.endTransmission(sendStop)) != ERR_NONE) return false; uint8_t wordaddr[] = { (uint8_t)(addr >> 8), (uint8_t)addr }; WIRE.beginTransmission(devaddr(addr)); WIRE.write(wordaddr, sizeof(wordaddr)); if (buf && len) WIRE.write((const uint8_t *)buf, len); return (_errcode = WIRE.endTransmission(sendStop)) == ERR_NONE; } uint8_t _address; int _errcode; }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 |
/* ds3231.h - DS3231/DS3232 RTC Library for ARDUINO Copyright (c) 2024 Sasapea's Lab. All right reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include <stdint.h> #include <stdbool.h> #include <time.h> #include "Arduino.h" #if defined(JENNIC_CHIP_FAMILY_JN516x) #undef _BIT_FIELDS_HTOL #define _BIT_FIELDS_HTOL #endif #define DECLARE_DS3231(instance) DS3231<typeof(instance), instance> template<typename WIRE_T, WIRE_T& WIRE> class DS3231 { public: static constexpr uint32_t WIRE_CLOCK = 400000; enum { ERR_NONE = 0, ERR_IO = 4, ERR_ARG = 8, }; typedef enum : uint8_t { SQWRATE_1, SQWRATE_1024, SQWRATE_4096, SQWRATE_8192, } SQWRATE; typedef enum : uint8_t { CNVRATE_64, CNVRATE_128, CNVRATE_256, CNVRATE_512, } CNVRATE; typedef struct __attribute((packed)) { #if defined(_BIT_FIELDS_HTOL) uint8_t EOSC : 1; /* RW[0]: Enable Oscillator */ uint8_t BBSQW : 1; /* RW[0]: Battery-Backed Square-Wave Enable */ uint8_t CONV : 1; /* RW[0]: Convert Temperature */ SQWRATE RS : 2; /* RW[SQWFREQ_8192]: Rate Select */ uint8_t INTCN : 1; /* RW[1]: Interrupt Control */ uint8_t A2IE : 1; /* RW[0]: Alarm 2 Interrupt Enable */ uint8_t A1IE : 1; /* RW[0]: Alarm 1 Interrupt Enable */ #else uint8_t A1IE : 1; /* RW[0]: Alarm 1 Interrupt Enable */ uint8_t A2IE : 1; /* RW[0]: Alarm 2 Interrupt Enable */ uint8_t INTCN : 1; /* RW[1]: Interrupt Control */ SQWRATE RS : 2; /* RW[SQWFREQ_8192]: Rate Select */ uint8_t CONV : 1; /* RW[0]: Convert Temperature */ uint8_t BBSQW : 1; /* RW[0]: Battery-Backed Square-Wave Enable */ uint8_t EOSC : 1; /* RW[0]: Enable Oscillator */ #endif } control_t; typedef struct __attribute((packed)) { #if defined(_BIT_FIELDS_HTOL) uint8_t OSF : 1; /* RW[1]: Oscillator Stop Flag */ uint8_t BB32KHz : 1; /* RW[1]: Battery-Backed 32KHz Output [DS3232] */ CNVRATE CRATE : 2; /* RW[CNVRATE_64]: Conversion Rate [DS3232] */ uint8_t EN32KHz : 1; /* RW[1]: Enable 32KHz Output */ uint8_t BSY : 1; /* RO[x]: Busy */ uint8_t A2F : 1; /* RW[x]: Alarm 2 Flag */ uint8_t A1F : 1; /* RW[x]: Alarm 1 Flag */ #else uint8_t A1F : 1; /* RW[x]: Alarm 1 Flag */ uint8_t A2F : 1; /* RW[x]: Alarm 2 Flag */ uint8_t BSY : 1; /* RO[x]: Busy */ uint8_t EN32KHz : 1; /* RW[1]: Enable 32KHz Output */ CNVRATE CRATE : 2; /* RW[CNVRATE_64]: Conversion Rate [DS3232] */ uint8_t BB32KHz : 1; /* RW[1]: Battery-Backed 32KHz Output [DS3232] */ uint8_t OSF : 1; /* RW[1]: Oscillator Stop Flag */ #endif } status_t; typedef void (*callback_t)(status_t status, void *argument); static bool begin(uint16_t pin = PIN_NC) { /* Initialize Wire with setup() */ _errcode = 0; _callback = nullptr; _argument = nullptr; _pinsqw = PIN_NC; bool rv = read(offsetof(regmap_t, Alarm1), &_regmap.Alarm1, offsetof(regmap_t, Temperature) - offsetof(regmap_t, Alarm1)); if (rv && (pin != PIN_NC)) { rv = outputSQW(SQWRATE_1); if (rv) rv = emuration(pin); } return rv; } static void setCallback(callback_t callback, void *argument = nullptr) { /* Only valid in emulation mode */ _callback = callback; _argument = argument; } static bool getCalendar(struct tm &tmbuf) { bool rv = true; if (_pinsqw == PIN_NC) { rv = read(offsetof(regmap_t, Calendar), &_regmap.Calendar, sizeof(_regmap.Calendar)); if (rv) toBinary(_regmap.Calendar); } if (rv) { do { tmbuf = { .tm_sec = _regmap.Calendar.Seconds, .tm_min = _regmap.Calendar.Minutes, .tm_hour = _regmap.Calendar.Hour, .tm_mday = _regmap.Calendar.Date, .tm_mon = _regmap.Calendar.Month - 1, .tm_year = _regmap.Calendar.Year + 100, .tm_wday = _regmap.Calendar.Day - 1, .tm_yday = dayOfYear(_regmap.Calendar), .tm_isdst = 0 }; } while (tmbuf.tm_sec != _regmap.Calendar.Seconds); } return rv; } static bool setCalendar(const struct tm &tmbuf) { bool rv = (tmbuf.tm_year >= 100) && (tmbuf.tm_year < 200); if (!rv) _errcode = ERR_ARG; else { calendar_t cal = { .Seconds = bin2bcd(tmbuf.tm_sec), .Minutes = bin2bcd(tmbuf.tm_min), .Hour = bin2bcd(tmbuf.tm_hour), .Day = bin2bcd(dayOfWeek(tmbuf.tm_year + 1900, tmbuf.tm_mon + 1, tmbuf.tm_mday) + 1), .Date = bin2bcd(tmbuf.tm_mday), .Month = bin2bcd(tmbuf.tm_mon + 1), .Year = bin2bcd(tmbuf.tm_year - 100) }; rv = write(offsetof(regmap_t, Calendar), &cal, sizeof(cal)); if (rv && (_pinsqw != PIN_NC)) toBinary(cal); } return rv; } static bool getAlarm1(struct tm &tmbuf) { bool rv = true || read(offsetof(regmap_t, Alarm1), &_regmap.Alarm1, sizeof(_regmap.Alarm1)); if (rv) { tmbuf = { .tm_sec = _regmap.Alarm1.Seconds & ALMMSK ? -1 : bcd2bin(_regmap.Alarm1.Seconds), .tm_min = _regmap.Alarm1.Minutes & ALMMSK ? -1 : bcd2bin(_regmap.Alarm1.Minutes), .tm_hour = _regmap.Alarm1.Hour & ALMMSK ? -1 : bcd2bin(_regmap.Alarm1.Hour), .tm_mday = _regmap.Alarm1.DayOrDate & (ALMMSK | ALMDAY) ? -1 : bcd2bin(_regmap.Alarm1.DayOrDate), .tm_mon = -1, .tm_year = -1, .tm_wday = _regmap.Alarm1.DayOrDate & ALMMSK ? -1 : bcd2bin(_regmap.Alarm1.DayOrDate & ~ALMDAY) - 1, .tm_yday = -1, .tm_isdst = -1 }; }; return rv; } static bool setAlarm1(const struct tm &tmbuf, bool week, bool enable = true) { alarm1_t alarm = { .Seconds = tmbuf.tm_sec < 0 ? ALMMSK : bin2bcd(tmbuf.tm_sec), .Minutes = tmbuf.tm_min < 0 ? ALMMSK : bin2bcd(tmbuf.tm_min), .Hour = tmbuf.tm_hour < 0 ? ALMMSK : bin2bcd(tmbuf.tm_hour), .DayOrDate = week ? (tmbuf.tm_wday < 0 ? ALMMSK : bin2bcd(tmbuf.tm_wday + 1) | ALMDAY) : (tmbuf.tm_mday <= 0 ? ALMMSK : bin2bcd(tmbuf.tm_mday)) }; bool rv = write(offsetof(regmap_t, Alarm1), &alarm, sizeof(alarm)); if (rv) { _regmap.Alarm1 = alarm; rv = alarm1(enable); } return rv; } static bool alarm1(bool enable) { control_t control; bool rv = getControl(control); if (rv) { control.A1IE = enable; control.INTCN = _pinsqw == PIN_NC; rv = setControl(control); } return rv; } static bool getAlarm2(struct tm &tmbuf) { bool rv = true || read(offsetof(regmap_t, Alarm2), &_regmap.Alarm2, sizeof(_regmap.Alarm2)); if (rv) { tmbuf = { .tm_sec = -1, .tm_min = _regmap.Alarm2.Minutes & ALMMSK ? -1 : bcd2bin(_regmap.Alarm2.Minutes), .tm_hour = _regmap.Alarm2.Hour & ALMMSK ? -1 : bcd2bin(_regmap.Alarm2.Hour), .tm_mday = _regmap.Alarm2.DayOrDate & (ALMMSK | ALMDAY) ? -1 : bcd2bin(_regmap.Alarm2.DayOrDate), .tm_mon = -1, .tm_year = -1, .tm_wday = _regmap.Alarm2.DayOrDate & ALMMSK ? -1 : bcd2bin(_regmap.Alarm2.DayOrDate & ~ALMDAY) - 1, .tm_yday = -1, .tm_isdst = -1 }; }; return rv; } static bool setAlarm2(const struct tm &tmbuf, bool week, bool enable = true) { alarm2_t alarm = { .Minutes = tmbuf.tm_min < 0 ? ALMMSK : bin2bcd(tmbuf.tm_min), .Hour = tmbuf.tm_hour < 0 ? ALMMSK : bin2bcd(tmbuf.tm_hour), .DayOrDate = week ? (tmbuf.tm_wday < 0 ? ALMMSK : bin2bcd(tmbuf.tm_wday + 1) | ALMDAY) : (tmbuf.tm_mday <= 0 ? ALMMSK : bin2bcd(tmbuf.tm_mday)) }; bool rv = write(offsetof(regmap_t, Alarm2), &alarm, sizeof(alarm)); if (rv) { _regmap.Alarm2 = alarm; rv = alarm2(enable); } return rv; } static bool alarm2(bool enable) { control_t control; bool rv = getControl(control); if (rv) { control.A2IE = enable; control.INTCN = _pinsqw == PIN_NC; rv = setControl(control); } return rv; } static bool getControl(control_t &value) { bool rv = true || read(offsetof(regmap_t, Control), &_regmap.Control, sizeof(_regmap.Control)); if (rv) value = _regmap.Control; return rv; } static bool setControl(control_t value) { bool rv = write(offsetof(regmap_t, Control), &value, sizeof(value)); if (rv) { _regmap.Control = value; if ((value.RS != SQWRATE_1) || value.INTCN) cancel(); } return rv; } static bool getStatus(status_t &value) { bool rv = read(offsetof(regmap_t, Status), &_regmap.Status, sizeof(_regmap.Status)); if (rv) value = _regmap.Status; return rv; } static bool setStatus(status_t value) { bool rv = write(offsetof(regmap_t, Status), &value, sizeof(value)); if (rv) _regmap.Status = value; return rv; } static bool getAgingOffset(int8_t &value) { bool rv = true || read(offsetof(regmap_t, AgingOffset), &_regmap.AgingOffset, sizeof(_regmap.AgingOffset)); if (rv) value = _regmap.AgingOffset; return rv; } static bool setAgingOffset(int8_t value, bool conv = true) { bool rv = write(offsetof(regmap_t, AgingOffset), &value, sizeof(value)); if (rv) { _regmap.AgingOffset = value; if (conv) rv = conversion(); } return rv; } static bool getTemperature(int16_t &value) { bool rv = read(offsetof(regmap_t, Temperature), &_regmap.Temperature, sizeof(_regmap.Temperature)); if (rv) value = (((int16_t)_regmap.Temperature.MSB << 8) | _regmap.Temperature.LSB) >> 6; return rv; } static bool oscillator(bool enable = true) { control_t control; bool rv = getControl(control); if (rv) { control.EOSC = |