Compare commits
5
Commits
972e97ae89
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a5851470b1 | ||
|
|
04c21e04d5 | ||
|
|
c4f3516c7c | ||
|
|
5d4b62c40b | ||
|
|
009066d182 |
+25
-1
@@ -1,2 +1,26 @@
|
||||
# Local WiFi credentials (see Fetch_rain/secrets.h.example)
|
||||
# Local WiFi credentials and ThingHTTP API keys (see Fetch_rain/secrets.h.example)
|
||||
secrets.h
|
||||
|
||||
# PlatformIO build output and installed dependencies
|
||||
.pio/
|
||||
.pioenvs/
|
||||
.piolibdeps/
|
||||
|
||||
# Compiler and linker artefacts
|
||||
*.bin
|
||||
*.elf
|
||||
*.hex
|
||||
*.map
|
||||
*.lst
|
||||
*.o
|
||||
*.d
|
||||
*.a
|
||||
*.ino.cpp
|
||||
|
||||
# Editors / OS
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
desktop.ini
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# Dependências externas
|
||||
|
||||
## DS3231 — biblioteca de relógio em tempo real
|
||||
|
||||
- **Usada por:** `Projeto.ino` — `#include <DS3231.h>` e `DS3231 rtc(SDA, SCL)`.
|
||||
- **Versão:** 1.01 (25 de Agosto de 2014); a 1.0 é de 17 de Agosto de 2014.
|
||||
- **Origem:** Rinky-Dink Electronics, Henning Karlsen — http://www.RinkyDinkElectronics.com/
|
||||
- **Licença:** CC BY-NC-SA 3.0 (Atribuição – NãoComercial – CompartilhaIgual).
|
||||
|
||||
Porque não está neste repositório: a CC BY-NC-SA 3.0 proíbe uso comercial e
|
||||
obriga a licenciar obras derivadas sob a mesma licença, o que é incompatível
|
||||
com a licença MIT deste repositório (que autoriza uso comercial). A biblioteca
|
||||
foi retirada do repositório e tem de ser instalada à parte:
|
||||
|
||||
1. Descarregar a versão 1.01 em http://www.RinkyDinkElectronics.com/ (DS3231).
|
||||
2. Instalar na pasta `libraries/` do Arduino IDE, ou declarar como dependência
|
||||
se construíres com PlatformIO ou `arduino-cli` (o IDE do Arduino não procura
|
||||
uma pasta `libs/` dentro do sketch).
|
||||
3. Uso comercial da biblioteca exige uma licença paga ao autor dela.
|
||||
|
||||
A remoção foi feita **no repositório** (índice e histórico a partir daqui); não
|
||||
apaga nenhuma cópia da biblioteca que exista fora do Git, no disco do autor.
|
||||
|
||||
## Como a dependência é declarada agora
|
||||
|
||||
`lib_deps` em `platformio.ini` (projecto do `Projeto.ino`):
|
||||
|
||||
```ini
|
||||
lib_deps =
|
||||
https://github.com/whonore/DS3231.git#v1.01
|
||||
```
|
||||
|
||||
A biblioteca **não está no registry oficial do PlatformIO**: foram verificados
|
||||
os 87 resultados da pesquisa por `DS3231` e nenhum expõe a API que `Projeto.ino`
|
||||
usa (`class Time` com o campo `hour`, `char *getTimeStr()`, e o construtor
|
||||
`DS3231(data_pin, sclk_pin)`). Por isso fica fixa à tag `v1.01` de um espelho,
|
||||
cujos ficheiros foram comparados byte a byte com o `libs/DS3231` que saiu deste
|
||||
repositório: `DS3231.h`, `DS3231.cpp`, `hardware/avr/HW_AVR.h`,
|
||||
`hardware/avr/HW_AVR_defines.h`, `keywords.txt` e `Documentation/version.txt`
|
||||
têm o mesmo SHA-256, e `version.txt` diz 1.01 (25 de Agosto de 2014).
|
||||
|
||||
O espelho é uma cópia da biblioteca original, redistribuída sob a mesma licença
|
||||
CC BY-NC-SA 3.0; continua a não ser este repositório a redistribuí-la.
|
||||
@@ -0,0 +1,22 @@
|
||||
; PlatformIO project for Fetch_rain.ino (ESP8266).
|
||||
; Build it from the repository root with: pio run -d Fetch_rain
|
||||
;
|
||||
; The board is named on the course poster kept in this repository,
|
||||
; Sumbrella.pdf: "ESP8226 ESP-01" (sic) — an ESP-01, whose flash size the poster
|
||||
; does not give. esp01 targets the 512 KB module, which is the variant the
|
||||
; firmware fits either way; use board = esp01_1m for a 1 MB ESP-01.
|
||||
;
|
||||
; Fetch_rain.ino does not compile without secrets.h, which is not versioned:
|
||||
; cp Fetch_rain/secrets.h.example Fetch_rain/secrets.h
|
||||
|
||||
[platformio]
|
||||
src_dir = .
|
||||
|
||||
[env:esp8266]
|
||||
platform = espressif8266
|
||||
board = esp01
|
||||
framework = arduino
|
||||
monitor_speed = 115200
|
||||
upload_speed = 115200
|
||||
lib_deps =
|
||||
marcoschwartz/LiquidCrystal_I2C@1.1.4
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 André Guilherme dos Santos Neto and João Miguel Alves Moitas
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,21 +1,200 @@
|
||||
https://youtu.be/7n7HcTeeHdM
|
||||
# sumbrella
|
||||
|
||||
## Configuration
|
||||
Two Arduino sketches for a smart umbrella: an ESP8266 ESP-01 sketch that fetches the rain probability for today, tomorrow and the day after from ThingSpeak over WiFi, and an Arduino Nano sketch that drives a red/green LED from a DS3231 real-time clock.
|
||||
|
||||
The WiFi credentials are **not** stored in the repository. The sketch
|
||||
`Fetch_rain/Fetch_rain.ino` includes a non-versioned header `secrets.h`
|
||||
that defines `WIFI_SSID` and `WIFI_PASSWORD`:
|
||||
## What it is
|
||||
|
||||
Two independent sketches, in two PlatformIO projects. Neither sketch names its own board in its source; the board is named on the course poster kept in this repository, `Sumbrella.pdf` ("Listagem de material"): *Arduino Nano* and *ESP8226 ESP-01*.
|
||||
|
||||
`Fetch_rain/Fetch_rain.ino` (176 lines, ESP8266 ESP-01)
|
||||
|
||||
| Lines | What |
|
||||
|---|---|
|
||||
| 1-3 | `ESP8266WiFi.h`, `Wire.h`, `LiquidCrystal_I2C.h` |
|
||||
| 5 | `#include "secrets.h"` — not versioned, see *Requirements* |
|
||||
| 7 | `LiquidCrystal_I2C lcd(0x27, 16, 2);` |
|
||||
| 10-11 | `ssid` and `password`, taken from `secrets.h` |
|
||||
| 13 | `host = "api.thingspeak.com"` |
|
||||
| 15-37 | `setup()`: serial at 115200 baud, joins the WiFi network and blocks until connected |
|
||||
| 40-73 | `loop()`: calls `today()`, `tmrw()`, `aftmrw()` in turn and prints each result |
|
||||
| 91-119, 121-148, 150-176 | one helper per day, identical apart from the ThingHTTP key |
|
||||
|
||||
Each helper opens a TCP connection to `api.thingspeak.com:80`, sends `GET /apps/thinghttp/send_request?api_key=<key>` (lines 103, 132, 160), skips 18 lines of response headers, reads the body up to the first `%` and returns it as an `int` (lines 116-118). On a failed connection it returns `-1`, and `loop()` then prints `Something went wrong, resetting...` and calls `setup()` again from inside `loop()` (lines 49, 59, 69). The rain percentages go to the serial port; that is the whole user interface.
|
||||
|
||||
`Projeto.ino` (31 lines, Arduino Nano)
|
||||
|
||||
- Lines 1-3: `#include <DS3231.h>` and `DS3231 rtc(SDA, SCL)` — SDA/SCL are A4/A5, i.e. pins 18 and 19.
|
||||
- Lines 6-12 `setup()`: serial at 9600 baud, `rtc.begin()`, pins 5 and 6 as `OUTPUT`.
|
||||
- Lines 14-26 `loop()`: prints `rtc.getTimeStr()`, takes `hour` out of the `Time` struct returned by `rtc.getTime()`, and calls `rgLed(150, 150)` while `7 < hour < 14` (08:00-13:59), otherwise `rgLed(0, 0)`; one second per iteration.
|
||||
- Lines 28-31 `rgLed()`: `analogWrite` on pins 5 and 6. Which of the two is the red LED and which is the green one is not stated anywhere in the code or the poster.
|
||||
|
||||
Things that are dead or missing — recorded here, deliberately not changed:
|
||||
|
||||
- The LCD is never used. `lcd` is constructed on line 7 of `Fetch_rain.ino` and there is not a single `lcd.` call in either sketch. It costs one library dependency and nothing else.
|
||||
- There is no rain sensor. Every rain value comes from the ThingSpeak HTTP responses; neither sketch reads an analogue or digital sensor.
|
||||
- Lines 75-90 of `Fetch_rain.ino` are blank.
|
||||
- The values returned by `today()`, `tmrw()` and `aftmrw()` are printed and discarded; nothing drives the LED from the rain probability, and `Projeto.ino` never reads the network.
|
||||
|
||||
## Requirements
|
||||
|
||||
- [PlatformIO Core](https://docs.platformio.org/) 6.2.0, on Python 3.13 (tested in a virtualenv; nothing was installed system-wide).
|
||||
- Internet access on the first build: PlatformIO downloads the `espressif8266` and `atmelavr` platforms, their toolchains, and the two libraries below (about 200 MB).
|
||||
- No board is needed to build or to run the tests. Flashing needs the Nano on a USB port and the ESP-01 on a 3.3 V serial adapter; nothing here was run on hardware.
|
||||
- Two external libraries, both declared in `lib_deps`:
|
||||
- `marcoschwartz/LiquidCrystal_I2C@1.1.4` — for the unused LCD, from the PlatformIO registry.
|
||||
- DS3231 1.01 (Rinky-Dink Electronics, Henning Karlsen) — for `Projeto.ino`. **It is not in the PlatformIO registry**: all 87 registry search hits for "DS3231" were checked and none exposes the `class Time` / `getTimeStr()` / `DS3231(data_pin, sclk_pin)` API this sketch uses. It is therefore pinned in `lib_deps` to the tag `v1.01` of a mirror whose files were verified byte-for-byte identical to the `libs/DS3231` that was removed from this repository. It is CC BY-NC-SA 3.0 and is not redistributed here — see [DEPENDENCIAS.md](DEPENDENCIAS.md).
|
||||
|
||||
`Fetch_rain.ino` does not compile without `Fetch_rain/secrets.h`, which is not versioned. Copy the example and fill in your own values:
|
||||
|
||||
```bash
|
||||
cp Fetch_rain/secrets.h.example Fetch_rain/secrets.h
|
||||
# edit Fetch_rain/secrets.h with your own network name and password
|
||||
# then edit Fetch_rain/secrets.h: WIFI_SSID, WIFI_PASSWORD and the three
|
||||
# THINGHTTP_KEY_* values
|
||||
```
|
||||
|
||||
`secrets.h` is listed in `.gitignore`, so it is never committed. The
|
||||
sketch does not compile without it. If the old password was ever
|
||||
pushed, change it on the router as well as in `secrets.h`.
|
||||
## Install / Build
|
||||
|
||||
`secrets.h` also defines the three ThingHTTP API keys used by the daily
|
||||
scheduled channels (`THINGHTTP_KEY_TODAY`, `THINGHTTP_KEY_TMRW`,
|
||||
`THINGHTTP_KEY_AFTMRW`). They used to be hard-coded in the sketch; the old
|
||||
values were committed, so they must be regenerated in ThingHTTP.
|
||||
There is one PlatformIO project per sketch, because PlatformIO only converts a `*.ino` file that sits at the top of its own `src_dir`.
|
||||
|
||||
```bash
|
||||
# canonical copy on the self-hosted Gitea (aneto/sumbrella), mirrored to GitHub:
|
||||
git clone ssh://git@127.0.0.1:2222/aneto/sumbrella.git
|
||||
cd sumbrella
|
||||
|
||||
python3 -m venv ~/.venvs/platformio
|
||||
~/.venvs/platformio/bin/pip install platformio
|
||||
export PATH="$HOME/.venvs/platformio/bin:$PATH"
|
||||
|
||||
cp Fetch_rain/secrets.h.example Fetch_rain/secrets.h # or ./run.sh does it
|
||||
|
||||
pio run # Projeto.ino -> Arduino Nano
|
||||
pio run -d Fetch_rain # Fetch_rain.ino -> ESP8266 ESP-01
|
||||
./run.sh # both, then the offline test suite
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Upload with `pio run -t upload` (`pio run -d Fetch_rain -t upload` for the ESP-01; it needs `board = esp01_1m` if the module has 1 MB of flash instead of 512 KB). Then read the serial port at the baud rate in `platformio.ini`: 115200 for the ESP-01, 9600 for the Nano (`pio device monitor`).
|
||||
|
||||
No board was attached to the machine this was built on, so this is not a captured session — it is the exact shape of the output, taken from the `Serial.print` calls:
|
||||
|
||||
```text
|
||||
Connecting to <ssid>
|
||||
.....
|
||||
WiFi connected
|
||||
IP address:
|
||||
192.168.1.23
|
||||
|
||||
Today: 20
|
||||
Tomorrow: 45
|
||||
After tomorrow: 10
|
||||
```
|
||||
|
||||
with `Something went wrong, resetting...` replacing a value when the connection to `api.thingspeak.com` fails, after which `setup()` runs again. `Projeto.ino` prints one line per second, `HH:MM:SS`, and lights the two LEDs on pins 5 and 6 while the hour is 8 to 13.
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
./run.sh # equivalent to: pio run && pio run -d Fetch_rain && bash tests/run_tests.sh
|
||||
```
|
||||
|
||||
Everything below runs without hardware and fails the shell (`exit != 0`) on the first real problem. Output of a run on the machine this was written on:
|
||||
|
||||
```text
|
||||
== pio check, ESP8266 ESP-01
|
||||
Component HIGH MEDIUM LOW
|
||||
Fetch_rain.ino 0 0 7
|
||||
Total 0 4 33
|
||||
esp8266 cppcheck PASSED 00:00:00.112
|
||||
|
||||
== pio check, Arduino Nano
|
||||
Component HIGH MEDIUM LOW
|
||||
Fetch_rain 0 0 7
|
||||
Fetch_rain/.pio/libdeps/esp8266/LiquidCrystal_I2C 0 4 26
|
||||
Projeto.ino 0 0 2
|
||||
Total 0 5 61
|
||||
nano cppcheck PASSED 00:00:00.467
|
||||
|
||||
== compile ESP8266 ESP-01 (Fetch_rain.ino)
|
||||
RAM: [==== ] 35.4% (used 28972 bytes from 81920 bytes)
|
||||
Flash: [====== ] 64.5% (used 280119 bytes from 434160 bytes)
|
||||
artefact: Fetch_rain/.pio/build/esp8266/firmware.bin (284272 bytes)
|
||||
-> PASS
|
||||
|
||||
== compile Arduino Nano (Projeto.ino)
|
||||
RAM: [= ] 10.1% (used 206 bytes from 2048 bytes)
|
||||
Flash: [= ] 11.4% (used 3508 bytes from 30720 bytes)
|
||||
artefact: .pio/build/nano/firmware.hex (9889 bytes)
|
||||
-> PASS
|
||||
|
||||
== secrets hygiene
|
||||
PASS secrets.h untracked and ignored; secrets.h.example defines every symbol the sketch uses and holds no real value; no tracked file holds a literal credential
|
||||
-> PASS
|
||||
|
||||
== secrets negative tests
|
||||
PASS negative case detected: secrets.h.example loses one symbol
|
||||
PASS negative case detected: .gitignore loses the secrets.h rule
|
||||
PASS negative case detected: a tracked file gains a literal api_key
|
||||
PASS negative case detected: secrets.h.example is deleted
|
||||
PASS control copy is clean
|
||||
SELFTEST OK
|
||||
-> PASS
|
||||
|
||||
== pin validity
|
||||
PASS all pins used are valid and PWM-capable where required
|
||||
-> PASS
|
||||
|
||||
== pin negative tests
|
||||
PASS negative case detected: pin outside the board range
|
||||
PASS negative case detected: analogWrite on a non-PWM pin
|
||||
PASS negative case detected: ESP8266 Dn pin name in an AVR sketch
|
||||
PASS control copy is clean
|
||||
SELFTEST OK
|
||||
-> PASS
|
||||
|
||||
== overall
|
||||
ALL TESTS PASSED
|
||||
```
|
||||
|
||||
Each run ends with a full compile of both targets and checks that the linked `firmware.bin` and `firmware.hex` really came out, with their size. The static analysis is placed first on purpose: `pio check` empties the build directory and deletes those binaries.
|
||||
|
||||
The zero-warning figure is for the two sketches: a clean build prints no warning for `Projeto.ino` or `Fetch_rain.ino`. The DS3231 library itself prints 41 warnings (40 `-Wwrite-strings`, 1 `-Wparentheses`) and `LiquidCrystal_I2C` raises 4 cppcheck `medium` findings; both are third-party and were left alone.
|
||||
|
||||
What the suite covers:
|
||||
|
||||
- **Compile.** Both targets are built for real, for the board named in `platformio.ini`. A compile error fails the run.
|
||||
- **Static analysis.** `pio check` on both projects; it fails on any `high` defect.
|
||||
- **Secrets.** `tests/check_secrets.py` fails if `Fetch_rain/secrets.h` is tracked or is missing from `.gitignore`, if `Fetch_rain/secrets.h.example` is missing or does not define every `WIFI_*`/`THINGHTTP_KEY_*` symbol `Fetch_rain.ino` uses, if the example holds anything that is not a placeholder, or if any tracked file holds a literal value for `api_key`/`password`/`passwd`/`pwd`/`ssid`/`secret`/`token` (quoted or not; a value that is a SCREAMING_SNAKE_CASE identifier counts as a symbol reference, not a literal).
|
||||
- **Negative cases.** `--selftest` re-runs the same checkers against throwaway copies in which a symbol was deleted from `secrets.h.example`, the `secrets.h` rule was removed from `.gitignore`, a literal key was appended to `README.md`, the example was deleted, a pin was pushed out of range, `analogWrite` was moved to a non-PWM pin, and an ESP8266 `Dn` name was put in an AVR sketch. Each mutation must be detected, and an untouched copy must be clean; if a mutation goes undetected the selftest fails.
|
||||
- **Pins.** `tests/check_pins.py` resolves every `pinMode`/`digitalWrite`/`digitalRead`/`analogWrite`/`analogRead` argument and the `SDA`/`SCL` macros against the Nano pin map, and checks that `analogWrite` is only used on PWM-capable pins.
|
||||
|
||||
Not covered, because it needs hardware: uploading, the WiFi association, the ThingSpeak responses, the I2C conversation with the DS3231, the LCD (which the code never writes to) and the LED behaviour. Nothing here was flashed.
|
||||
|
||||
## Structure
|
||||
|
||||
```text
|
||||
Projeto.ino Nano + DS3231: 08:00-13:59 window, two LEDs on pins 5 and 6 (31 lines)
|
||||
Fetch_rain/Fetch_rain.ino ESP-01: three ThingHTTP GETs, percentages on the serial port (176 lines)
|
||||
Fetch_rain/secrets.h.example the five symbols the sketch needs, with placeholder values (11 lines)
|
||||
Fetch_rain/platformio.ini PlatformIO project for the ESP-01 (src_dir = .) (22 lines)
|
||||
platformio.ini PlatformIO project for Projeto.ino (src_dir = .) (32 lines)
|
||||
run.sh build both targets, then run the tests (6 lines)
|
||||
tests/run_tests.sh the suite: pio check, the two compiles, and the two checkers (74 lines)
|
||||
tests/check_secrets.py secrets hygiene, with --selftest for the negative cases (196 lines)
|
||||
tests/check_pins.py pins against the board pin maps, with --selftest (170 lines)
|
||||
DEPENDENCIAS.md the DS3231 library: origin, version, licence, why it is not here
|
||||
LICENSE MIT
|
||||
Sumbrella.pdf the course poster; the only place the boards are named
|
||||
Screenshot_6.jpg photo of the assembly; no code reads it
|
||||
README.md this file
|
||||
```
|
||||
|
||||
Every path above is in the repository. `Fetch_rain/secrets.h` is created from the example, is listed in `.gitignore` and is never committed.
|
||||
|
||||
## License
|
||||
|
||||
MIT — see [LICENSE](LICENSE). Copyright (c) 2020 André Guilherme dos Santos Neto and João Miguel Alves Moitas. `Sumbrella.pdf`, the course poster kept in this repository, names two students as authors of the work (André Guilherme dos Santos Neto and João Miguel Alves Moitas); the `LICENSE` file names only the first of them.
|
||||
|
||||
The DS3231 library used by `Projeto.ino` is third-party. It is CC BY-NC-SA 3.0, incompatible with MIT, and for that reason it is not redistributed here: it was removed from `libs/DS3231` and is now declared as an external dependency in [DEPENDENCIAS.md](DEPENDENCIAS.md) and pinned in `lib_deps`. It keeps its own licence, and commercial use of it requires a paid licence from its author (Rinky-Dink Electronics).
|
||||
|
||||
The WiFi password and the three ThingHTTP keys are not in the repository and never were: every revision reachable from `main` (six commits, including the `ESP8266_Fetching_Data.ino` sketch that was deleted in `b804d9a`) was scanned for a credential-looking literal and none was found — the old sketch carried the literal string `<REDACTED>` in its place.
|
||||
|
||||
@@ -1,447 +0,0 @@
|
||||
/*
|
||||
DS3231.cpp - Arduino/chipKit library support for the DS3231 I2C Real-Time Clock
|
||||
Copyright (C)2015 Rinky-Dink Electronics, Henning Karlsen. All right reserved
|
||||
|
||||
This library has been made to easily interface and use the DS3231 RTC with
|
||||
an Arduino or chipKit.
|
||||
|
||||
You can find the latest version of the library at
|
||||
http://www.RinkyDinkElectronics.com/
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the CC BY-NC-SA 3.0 license.
|
||||
Please see the included documents for further information.
|
||||
|
||||
Commercial use of this library requires you to buy a license that
|
||||
will allow commercial use. This includes using the library,
|
||||
modified or not, as a tool to sell products.
|
||||
|
||||
The license applies to all part of the library including the
|
||||
examples and tools supplied with the library.
|
||||
*/
|
||||
#include "DS3231.h"
|
||||
|
||||
// Include hardware-specific functions for the correct MCU
|
||||
#if defined(__AVR__)
|
||||
#include "hardware/avr/HW_AVR.h"
|
||||
#elif defined(__PIC32MX__)
|
||||
#include "hardware/pic32/HW_PIC32.h"
|
||||
#elif defined(__arm__)
|
||||
#include "hardware/arm/HW_ARM.h"
|
||||
#endif
|
||||
|
||||
#define REG_SEC 0x00
|
||||
#define REG_MIN 0x01
|
||||
#define REG_HOUR 0x02
|
||||
#define REG_DOW 0x03
|
||||
#define REG_DATE 0x04
|
||||
#define REG_MON 0x05
|
||||
#define REG_YEAR 0x06
|
||||
#define REG_CON 0x0e
|
||||
#define REG_STATUS 0x0f
|
||||
#define REG_AGING 0x10
|
||||
#define REG_TEMPM 0x11
|
||||
#define REG_TEMPL 0x12
|
||||
|
||||
#define SEC_1970_TO_2000 946684800
|
||||
|
||||
static const uint8_t dim[] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
|
||||
|
||||
/* Public */
|
||||
|
||||
Time::Time()
|
||||
{
|
||||
this->year = 2014;
|
||||
this->mon = 1;
|
||||
this->date = 1;
|
||||
this->hour = 0;
|
||||
this->min = 0;
|
||||
this->sec = 0;
|
||||
this->dow = 3;
|
||||
}
|
||||
|
||||
DS3231::DS3231(uint8_t data_pin, uint8_t sclk_pin)
|
||||
{
|
||||
_sda_pin = data_pin;
|
||||
_scl_pin = sclk_pin;
|
||||
}
|
||||
|
||||
Time DS3231::getTime()
|
||||
{
|
||||
Time t;
|
||||
_burstRead();
|
||||
t.sec = _decode(_burstArray[0]);
|
||||
t.min = _decode(_burstArray[1]);
|
||||
t.hour = _decodeH(_burstArray[2]);
|
||||
t.dow = _burstArray[3];
|
||||
t.date = _decode(_burstArray[4]);
|
||||
t.mon = _decode(_burstArray[5]);
|
||||
t.year = _decodeY(_burstArray[6])+2000;
|
||||
return t;
|
||||
}
|
||||
|
||||
void DS3231::setTime(uint8_t hour, uint8_t min, uint8_t sec)
|
||||
{
|
||||
if (((hour>=0) && (hour<24)) && ((min>=0) && (min<60)) && ((sec>=0) && (sec<60)))
|
||||
{
|
||||
_writeRegister(REG_HOUR, _encode(hour));
|
||||
_writeRegister(REG_MIN, _encode(min));
|
||||
_writeRegister(REG_SEC, _encode(sec));
|
||||
}
|
||||
}
|
||||
|
||||
void DS3231::setDate(uint8_t date, uint8_t mon, uint16_t year)
|
||||
{
|
||||
if (((date>0) && (date<=31)) && ((mon>0) && (mon<=12)) && ((year>=2000) && (year<3000)))
|
||||
{
|
||||
year -= 2000;
|
||||
_writeRegister(REG_YEAR, _encode(year));
|
||||
_writeRegister(REG_MON, _encode(mon));
|
||||
_writeRegister(REG_DATE, _encode(date));
|
||||
}
|
||||
}
|
||||
|
||||
void DS3231::setDOW()
|
||||
{
|
||||
int dow;
|
||||
byte mArr[12] = {6,2,2,5,0,3,5,1,4,6,2,4};
|
||||
Time _t = getTime();
|
||||
|
||||
dow = (_t.year % 100);
|
||||
dow = dow*1.25;
|
||||
dow += _t.date;
|
||||
dow += mArr[_t.mon-1];
|
||||
if (((_t.year % 4)==0) && (_t.mon<3))
|
||||
dow -= 1;
|
||||
while (dow>7)
|
||||
dow -= 7;
|
||||
_writeRegister(REG_DOW, dow);
|
||||
}
|
||||
|
||||
void DS3231::setDOW(uint8_t dow)
|
||||
{
|
||||
if ((dow>0) && (dow<8))
|
||||
_writeRegister(REG_DOW, dow);
|
||||
}
|
||||
|
||||
char *DS3231::getTimeStr(uint8_t format)
|
||||
{
|
||||
static char output[] = "xxxxxxxx";
|
||||
Time t;
|
||||
t=getTime();
|
||||
if (t.hour<10)
|
||||
output[0]=48;
|
||||
else
|
||||
output[0]=char((t.hour / 10)+48);
|
||||
output[1]=char((t.hour % 10)+48);
|
||||
output[2]=58;
|
||||
if (t.min<10)
|
||||
output[3]=48;
|
||||
else
|
||||
output[3]=char((t.min / 10)+48);
|
||||
output[4]=char((t.min % 10)+48);
|
||||
output[5]=58;
|
||||
if (format==FORMAT_SHORT)
|
||||
output[5]=0;
|
||||
else
|
||||
{
|
||||
if (t.sec<10)
|
||||
output[6]=48;
|
||||
else
|
||||
output[6]=char((t.sec / 10)+48);
|
||||
output[7]=char((t.sec % 10)+48);
|
||||
output[8]=0;
|
||||
}
|
||||
return (char*)&output;
|
||||
}
|
||||
|
||||
char *DS3231::getDateStr(uint8_t slformat, uint8_t eformat, char divider)
|
||||
{
|
||||
static char output[] = "xxxxxxxxxx";
|
||||
int yr, offset;
|
||||
Time t;
|
||||
t=getTime();
|
||||
switch (eformat)
|
||||
{
|
||||
case FORMAT_LITTLEENDIAN:
|
||||
if (t.date<10)
|
||||
output[0]=48;
|
||||
else
|
||||
output[0]=char((t.date / 10)+48);
|
||||
output[1]=char((t.date % 10)+48);
|
||||
output[2]=divider;
|
||||
if (t.mon<10)
|
||||
output[3]=48;
|
||||
else
|
||||
output[3]=char((t.mon / 10)+48);
|
||||
output[4]=char((t.mon % 10)+48);
|
||||
output[5]=divider;
|
||||
if (slformat==FORMAT_SHORT)
|
||||
{
|
||||
yr=t.year-2000;
|
||||
if (yr<10)
|
||||
output[6]=48;
|
||||
else
|
||||
output[6]=char((yr / 10)+48);
|
||||
output[7]=char((yr % 10)+48);
|
||||
output[8]=0;
|
||||
}
|
||||
else
|
||||
{
|
||||
yr=t.year;
|
||||
output[6]=char((yr / 1000)+48);
|
||||
output[7]=char(((yr % 1000) / 100)+48);
|
||||
output[8]=char(((yr % 100) / 10)+48);
|
||||
output[9]=char((yr % 10)+48);
|
||||
output[10]=0;
|
||||
}
|
||||
break;
|
||||
case FORMAT_BIGENDIAN:
|
||||
if (slformat==FORMAT_SHORT)
|
||||
offset=0;
|
||||
else
|
||||
offset=2;
|
||||
if (slformat==FORMAT_SHORT)
|
||||
{
|
||||
yr=t.year-2000;
|
||||
if (yr<10)
|
||||
output[0]=48;
|
||||
else
|
||||
output[0]=char((yr / 10)+48);
|
||||
output[1]=char((yr % 10)+48);
|
||||
output[2]=divider;
|
||||
}
|
||||
else
|
||||
{
|
||||
yr=t.year;
|
||||
output[0]=char((yr / 1000)+48);
|
||||
output[1]=char(((yr % 1000) / 100)+48);
|
||||
output[2]=char(((yr % 100) / 10)+48);
|
||||
output[3]=char((yr % 10)+48);
|
||||
output[4]=divider;
|
||||
}
|
||||
if (t.mon<10)
|
||||
output[3+offset]=48;
|
||||
else
|
||||
output[3+offset]=char((t.mon / 10)+48);
|
||||
output[4+offset]=char((t.mon % 10)+48);
|
||||
output[5+offset]=divider;
|
||||
if (t.date<10)
|
||||
output[6+offset]=48;
|
||||
else
|
||||
output[6+offset]=char((t.date / 10)+48);
|
||||
output[7+offset]=char((t.date % 10)+48);
|
||||
output[8+offset]=0;
|
||||
break;
|
||||
case FORMAT_MIDDLEENDIAN:
|
||||
if (t.mon<10)
|
||||
output[0]=48;
|
||||
else
|
||||
output[0]=char((t.mon / 10)+48);
|
||||
output[1]=char((t.mon % 10)+48);
|
||||
output[2]=divider;
|
||||
if (t.date<10)
|
||||
output[3]=48;
|
||||
else
|
||||
output[3]=char((t.date / 10)+48);
|
||||
output[4]=char((t.date % 10)+48);
|
||||
output[5]=divider;
|
||||
if (slformat==FORMAT_SHORT)
|
||||
{
|
||||
yr=t.year-2000;
|
||||
if (yr<10)
|
||||
output[6]=48;
|
||||
else
|
||||
output[6]=char((yr / 10)+48);
|
||||
output[7]=char((yr % 10)+48);
|
||||
output[8]=0;
|
||||
}
|
||||
else
|
||||
{
|
||||
yr=t.year;
|
||||
output[6]=char((yr / 1000)+48);
|
||||
output[7]=char(((yr % 1000) / 100)+48);
|
||||
output[8]=char(((yr % 100) / 10)+48);
|
||||
output[9]=char((yr % 10)+48);
|
||||
output[10]=0;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return (char*)&output;
|
||||
}
|
||||
|
||||
char *DS3231::getDOWStr(uint8_t format)
|
||||
{
|
||||
char *output = "xxxxxxxxxx";
|
||||
char *daysLong[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
|
||||
char *daysShort[] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
|
||||
Time t;
|
||||
t=getTime();
|
||||
if (format == FORMAT_SHORT)
|
||||
output = daysShort[t.dow-1];
|
||||
else
|
||||
output = daysLong[t.dow-1];
|
||||
return output;
|
||||
}
|
||||
|
||||
char *DS3231::getMonthStr(uint8_t format)
|
||||
{
|
||||
char *output= "xxxxxxxxx";
|
||||
char *monthLong[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
|
||||
char *monthShort[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
|
||||
Time t;
|
||||
t=getTime();
|
||||
if (format == FORMAT_SHORT)
|
||||
output = monthShort[t.mon-1];
|
||||
else
|
||||
output = monthLong[t.mon-1];
|
||||
return output;
|
||||
}
|
||||
|
||||
long DS3231::getUnixTime(Time t)
|
||||
{
|
||||
uint16_t dc;
|
||||
|
||||
dc = t.date;
|
||||
for (uint8_t i = 0; i<(t.mon-1); i++)
|
||||
dc += dim[i];
|
||||
if ((t.mon > 2) && (((t.year-2000) % 4) == 0))
|
||||
++dc;
|
||||
dc = dc + (365 * (t.year-2000)) + (((t.year-2000) + 3) / 4) - 1;
|
||||
|
||||
return ((((((dc * 24L) + t.hour) * 60) + t.min) * 60) + t.sec) + SEC_1970_TO_2000;
|
||||
|
||||
}
|
||||
|
||||
void DS3231::enable32KHz(bool enable)
|
||||
{
|
||||
uint8_t _reg = _readRegister(REG_STATUS);
|
||||
_reg &= ~(1 << 3);
|
||||
_reg |= (enable << 3);
|
||||
_writeRegister(REG_STATUS, _reg);
|
||||
}
|
||||
|
||||
void DS3231::setOutput(byte enable)
|
||||
{
|
||||
uint8_t _reg = _readRegister(REG_CON);
|
||||
_reg &= ~(1 << 2);
|
||||
_reg |= (enable << 2);
|
||||
_writeRegister(REG_CON, _reg);
|
||||
}
|
||||
|
||||
void DS3231::setSQWRate(int rate)
|
||||
{
|
||||
uint8_t _reg = _readRegister(REG_CON);
|
||||
_reg &= ~(3 << 3);
|
||||
_reg |= (rate << 3);
|
||||
_writeRegister(REG_CON, _reg);
|
||||
}
|
||||
|
||||
float DS3231::getTemp()
|
||||
{
|
||||
uint8_t _msb = _readRegister(REG_TEMPM);
|
||||
uint8_t _lsb = _readRegister(REG_TEMPL);
|
||||
return (float)_msb + ((_lsb >> 6) * 0.25f);
|
||||
}
|
||||
|
||||
/* Private */
|
||||
|
||||
void DS3231::_sendStart(byte addr)
|
||||
{
|
||||
pinMode(_sda_pin, OUTPUT);
|
||||
digitalWrite(_sda_pin, HIGH);
|
||||
digitalWrite(_scl_pin, HIGH);
|
||||
digitalWrite(_sda_pin, LOW);
|
||||
digitalWrite(_scl_pin, LOW);
|
||||
shiftOut(_sda_pin, _scl_pin, MSBFIRST, addr);
|
||||
}
|
||||
|
||||
void DS3231::_sendStop()
|
||||
{
|
||||
pinMode(_sda_pin, OUTPUT);
|
||||
digitalWrite(_sda_pin, LOW);
|
||||
digitalWrite(_scl_pin, HIGH);
|
||||
digitalWrite(_sda_pin, HIGH);
|
||||
pinMode(_sda_pin, INPUT);
|
||||
}
|
||||
|
||||
void DS3231::_sendNack()
|
||||
{
|
||||
pinMode(_sda_pin, OUTPUT);
|
||||
digitalWrite(_scl_pin, LOW);
|
||||
digitalWrite(_sda_pin, HIGH);
|
||||
digitalWrite(_scl_pin, HIGH);
|
||||
digitalWrite(_scl_pin, LOW);
|
||||
pinMode(_sda_pin, INPUT);
|
||||
}
|
||||
|
||||
void DS3231::_sendAck()
|
||||
{
|
||||
pinMode(_sda_pin, OUTPUT);
|
||||
digitalWrite(_scl_pin, LOW);
|
||||
digitalWrite(_sda_pin, LOW);
|
||||
digitalWrite(_scl_pin, HIGH);
|
||||
digitalWrite(_scl_pin, LOW);
|
||||
pinMode(_sda_pin, INPUT);
|
||||
}
|
||||
|
||||
void DS3231::_waitForAck()
|
||||
{
|
||||
pinMode(_sda_pin, INPUT);
|
||||
digitalWrite(_scl_pin, HIGH);
|
||||
while (digitalRead(_sda_pin)==HIGH) {}
|
||||
digitalWrite(_scl_pin, LOW);
|
||||
}
|
||||
|
||||
uint8_t DS3231::_readByte()
|
||||
{
|
||||
pinMode(_sda_pin, INPUT);
|
||||
|
||||
uint8_t value = 0;
|
||||
uint8_t currentBit = 0;
|
||||
|
||||
for (int i = 0; i < 8; ++i)
|
||||
{
|
||||
digitalWrite(_scl_pin, HIGH);
|
||||
currentBit = digitalRead(_sda_pin);
|
||||
value |= (currentBit << 7-i);
|
||||
delayMicroseconds(1);
|
||||
digitalWrite(_scl_pin, LOW);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
void DS3231::_writeByte(uint8_t value)
|
||||
{
|
||||
pinMode(_sda_pin, OUTPUT);
|
||||
shiftOut(_sda_pin, _scl_pin, MSBFIRST, value);
|
||||
}
|
||||
|
||||
uint8_t DS3231::_decode(uint8_t value)
|
||||
{
|
||||
uint8_t decoded = value & 127;
|
||||
decoded = (decoded & 15) + 10 * ((decoded & (15 << 4)) >> 4);
|
||||
return decoded;
|
||||
}
|
||||
|
||||
uint8_t DS3231::_decodeH(uint8_t value)
|
||||
{
|
||||
if (value & 128)
|
||||
value = (value & 15) + (12 * ((value & 32) >> 5));
|
||||
else
|
||||
value = (value & 15) + (10 * ((value & 48) >> 4));
|
||||
return value;
|
||||
}
|
||||
|
||||
uint8_t DS3231::_decodeY(uint8_t value)
|
||||
{
|
||||
uint8_t decoded = (value & 15) + 10 * ((value & (15 << 4)) >> 4);
|
||||
return decoded;
|
||||
}
|
||||
|
||||
uint8_t DS3231::_encode(uint8_t value)
|
||||
{
|
||||
uint8_t encoded = ((value / 10) << 4) + (value % 10);
|
||||
return encoded;
|
||||
}
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
/*
|
||||
DS3231.cpp - Arduino/chipKit library support for the DS3231 I2C Real-Time Clock
|
||||
Copyright (C)2015 Rinky-Dink Electronics, Henning Karlsen. All right reserved
|
||||
|
||||
This library has been made to easily interface and use the DS3231 RTC with
|
||||
an Arduino or chipKit.
|
||||
|
||||
You can find the latest version of the library at
|
||||
http://www.RinkyDinkElectronics.com/
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the CC BY-NC-SA 3.0 license.
|
||||
Please see the included documents for further information.
|
||||
|
||||
Commercial use of this library requires you to buy a license that
|
||||
will allow commercial use. This includes using the library,
|
||||
modified or not, as a tool to sell products.
|
||||
|
||||
The license applies to all part of the library including the
|
||||
examples and tools supplied with the library.
|
||||
*/
|
||||
#ifndef DS3231_h
|
||||
#define DS3231_h
|
||||
|
||||
#if defined(__AVR__)
|
||||
#include "Arduino.h"
|
||||
#include "hardware/avr/HW_AVR_defines.h"
|
||||
#elif defined(__PIC32MX__)
|
||||
#include "WProgram.h"
|
||||
#include "hardware/pic32/HW_PIC32_defines.h"
|
||||
#elif defined(__arm__)
|
||||
#include "Arduino.h"
|
||||
#include "hardware/arm/HW_ARM_defines.h"
|
||||
#endif
|
||||
|
||||
#define DS3231_ADDR_R 0xD1
|
||||
#define DS3231_ADDR_W 0xD0
|
||||
#define DS3231_ADDR 0x68
|
||||
|
||||
#define FORMAT_SHORT 1
|
||||
#define FORMAT_LONG 2
|
||||
|
||||
#define FORMAT_LITTLEENDIAN 1
|
||||
#define FORMAT_BIGENDIAN 2
|
||||
#define FORMAT_MIDDLEENDIAN 3
|
||||
|
||||
#define MONDAY 1
|
||||
#define TUESDAY 2
|
||||
#define WEDNESDAY 3
|
||||
#define THURSDAY 4
|
||||
#define FRIDAY 5
|
||||
#define SATURDAY 6
|
||||
#define SUNDAY 7
|
||||
|
||||
#define SQW_RATE_1 0
|
||||
#define SQW_RATE_1K 1
|
||||
#define SQW_RATE_4K 2
|
||||
#define SQW_RATE_8K 3
|
||||
|
||||
#define OUTPUT_SQW 0
|
||||
#define OUTPUT_INT 1
|
||||
|
||||
class Time
|
||||
{
|
||||
public:
|
||||
uint8_t hour;
|
||||
uint8_t min;
|
||||
uint8_t sec;
|
||||
uint8_t date;
|
||||
uint8_t mon;
|
||||
uint16_t year;
|
||||
uint8_t dow;
|
||||
|
||||
Time();
|
||||
};
|
||||
|
||||
class DS3231
|
||||
{
|
||||
public:
|
||||
DS3231(uint8_t data_pin, uint8_t sclk_pin);
|
||||
void begin();
|
||||
Time getTime();
|
||||
void setTime(uint8_t hour, uint8_t min, uint8_t sec);
|
||||
void setDate(uint8_t date, uint8_t mon, uint16_t year);
|
||||
void setDOW();
|
||||
void setDOW(uint8_t dow);
|
||||
|
||||
char *getTimeStr(uint8_t format=FORMAT_LONG);
|
||||
char *getDateStr(uint8_t slformat=FORMAT_LONG, uint8_t eformat=FORMAT_LITTLEENDIAN, char divider='.');
|
||||
char *getDOWStr(uint8_t format=FORMAT_LONG);
|
||||
char *getMonthStr(uint8_t format=FORMAT_LONG);
|
||||
long getUnixTime(Time t);
|
||||
|
||||
void enable32KHz(bool enable);
|
||||
void setOutput(byte enable);
|
||||
void setSQWRate(int rate);
|
||||
float getTemp();
|
||||
|
||||
private:
|
||||
uint8_t _scl_pin;
|
||||
uint8_t _sda_pin;
|
||||
uint8_t _burstArray[7];
|
||||
boolean _use_hw;
|
||||
|
||||
void _sendStart(byte addr);
|
||||
void _sendStop();
|
||||
void _sendAck();
|
||||
void _sendNack();
|
||||
void _waitForAck();
|
||||
uint8_t _readByte();
|
||||
void _writeByte(uint8_t value);
|
||||
void _burstRead();
|
||||
uint8_t _readRegister(uint8_t reg);
|
||||
void _writeRegister(uint8_t reg, uint8_t value);
|
||||
uint8_t _decode(uint8_t value);
|
||||
uint8_t _decodeH(uint8_t value);
|
||||
uint8_t _decodeY(uint8_t value);
|
||||
uint8_t _encode(uint8_t vaule);
|
||||
#if defined(__arm__)
|
||||
Twi *twi;
|
||||
#endif
|
||||
};
|
||||
#endif
|
||||
Binary file not shown.
@@ -1,3 +0,0 @@
|
||||
Version:
|
||||
1.0 17 Aug 2014 - initial release
|
||||
1.01 25 Aug 2014 - small bugfix
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,77 +0,0 @@
|
||||
// DS3231_Serial_Easy
|
||||
// Copyright (C)2015 Rinky-Dink Electronics, Henning Karlsen. All right reserved
|
||||
// web: http://www.RinkyDinkElectronics.com/
|
||||
//
|
||||
// A quick demo of how to use my DS3231-library to
|
||||
// quickly send time and date information over a serial link
|
||||
//
|
||||
// To use the hardware I2C (TWI) interface of the Arduino you must connect
|
||||
// the pins as follows:
|
||||
//
|
||||
// Arduino Uno/2009:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Arduino Analog 4 or the dedicated SDA pin
|
||||
// SCL pin -> Arduino Analog 5 or the dedicated SCL pin
|
||||
//
|
||||
// Arduino Leonardo:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Arduino Digital 2 or the dedicated SDA pin
|
||||
// SCL pin -> Arduino Digital 3 or the dedicated SCL pin
|
||||
//
|
||||
// Arduino Mega:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Arduino Digital 20 (SDA) or the dedicated SDA pin
|
||||
// SCL pin -> Arduino Digital 21 (SCL) or the dedicated SCL pin
|
||||
//
|
||||
// Arduino Due:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Arduino Digital 20 (SDA) or the dedicated SDA1 (Digital 70) pin
|
||||
// SCL pin -> Arduino Digital 21 (SCL) or the dedicated SCL1 (Digital 71) pin
|
||||
//
|
||||
// The internal pull-up resistors will be activated when using the
|
||||
// hardware I2C interfaces.
|
||||
//
|
||||
// You can connect the DS3231 to any available pin but if you use any
|
||||
// other than what is described above the library will fall back to
|
||||
// a software-based, TWI-like protocol which will require exclusive access
|
||||
// to the pins used, and you will also have to use appropriate, external
|
||||
// pull-up resistors on the data and clock signals.
|
||||
//
|
||||
|
||||
#include <DS3231.h>
|
||||
|
||||
// Init the DS3231 using the hardware interface
|
||||
DS3231 rtc(SDA, SCL);
|
||||
|
||||
void setup()
|
||||
{
|
||||
// Setup Serial connection
|
||||
Serial.begin(115200);
|
||||
// Uncomment the next line if you are using an Arduino Leonardo
|
||||
//while (!Serial) {}
|
||||
|
||||
// Initialize the rtc object
|
||||
rtc.begin();
|
||||
|
||||
// The following lines can be uncommented to set the date and time
|
||||
//rtc.setDOW(WEDNESDAY); // Set Day-of-Week to SUNDAY
|
||||
//rtc.setTime(12, 0, 0); // Set the time to 12:00:00 (24hr format)
|
||||
//rtc.setDate(1, 1, 2014); // Set the date to January 1st, 2014
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
// Send Day-of-Week
|
||||
Serial.print(rtc.getDOWStr());
|
||||
Serial.print(" ");
|
||||
|
||||
// Send date
|
||||
Serial.print(rtc.getDateStr());
|
||||
Serial.print(" -- ");
|
||||
|
||||
// Send time
|
||||
Serial.println(rtc.getTimeStr());
|
||||
|
||||
// Wait one second before repeating :)
|
||||
delay (1000);
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
// DS3231_Serial_Hard
|
||||
// Copyright (C)2015 Rinky-Dink Electronics, Henning Karlsen. All right reserved
|
||||
// web: http://www.RinkyDinkElectronics.com/
|
||||
//
|
||||
// A quick demo of how to use my DS3231-library to
|
||||
// retrieve time- and date-data for you to manipulate.
|
||||
//
|
||||
// To use the hardware I2C (TWI) interface of the Arduino you must connect
|
||||
// the pins as follows:
|
||||
//
|
||||
// Arduino Uno/2009:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Arduino Analog 4 or the dedicated SDA pin
|
||||
// SCL pin -> Arduino Analog 5 or the dedicated SCL pin
|
||||
//
|
||||
// Arduino Leonardo:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Arduino Digital 2 or the dedicated SDA pin
|
||||
// SCL pin -> Arduino Digital 3 or the dedicated SCL pin
|
||||
//
|
||||
// Arduino Mega:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Arduino Digital 20 (SDA) or the dedicated SDA pin
|
||||
// SCL pin -> Arduino Digital 21 (SCL) or the dedicated SCL pin
|
||||
//
|
||||
// Arduino Due:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Arduino Digital 20 (SDA) or the dedicated SDA1 (Digital 70) pin
|
||||
// SCL pin -> Arduino Digital 21 (SCL) or the dedicated SCL1 (Digital 71) pin
|
||||
//
|
||||
// The internal pull-up resistors will be activated when using the
|
||||
// hardware I2C interfaces.
|
||||
//
|
||||
// You can connect the DS3231 to any available pin but if you use any
|
||||
// other than what is described above the library will fall back to
|
||||
// a software-based, TWI-like protocol which will require exclusive access
|
||||
// to the pins used, and you will also have to use appropriate, external
|
||||
// pull-up resistors on the data and clock signals.
|
||||
//
|
||||
|
||||
#include <DS3231.h>
|
||||
|
||||
// Init the DS3231 using the hardware interface
|
||||
DS3231 rtc(SDA, SCL);
|
||||
|
||||
// Init a Time-data structure
|
||||
Time t;
|
||||
|
||||
void setup()
|
||||
{
|
||||
// Setup Serial connection
|
||||
Serial.begin(115200);
|
||||
// Uncomment the next line if you are using an Arduino Leonardo
|
||||
//while (!Serial) {}
|
||||
|
||||
// Initialize the rtc object
|
||||
rtc.begin();
|
||||
|
||||
// The following lines can be uncommented to set the date and time
|
||||
//rtc.setDOW(WEDNESDAY); // Set Day-of-Week to SUNDAY
|
||||
//rtc.setTime(12, 0, 0); // Set the time to 12:00:00 (24hr format)
|
||||
//rtc.setDate(1, 1, 2014); // Set the date to January 1st, 2014
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
// Get data from the DS3231
|
||||
t = rtc.getTime();
|
||||
|
||||
// Send date over serial connection
|
||||
Serial.print("Today is the ");
|
||||
Serial.print(t.date, DEC);
|
||||
Serial.print(". day of ");
|
||||
Serial.print(rtc.getMonthStr());
|
||||
Serial.print(" in the year ");
|
||||
Serial.print(t.year, DEC);
|
||||
Serial.println(".");
|
||||
|
||||
// Send Day-of-Week and time
|
||||
Serial.print("It is the ");
|
||||
Serial.print(t.dow, DEC);
|
||||
Serial.print(". day of the week (counting monday as the 1th), and it has passed ");
|
||||
Serial.print(t.hour, DEC);
|
||||
Serial.print(" hour(s), ");
|
||||
Serial.print(t.min, DEC);
|
||||
Serial.print(" minute(s) and ");
|
||||
Serial.print(t.sec, DEC);
|
||||
Serial.println(" second(s) since midnight.");
|
||||
|
||||
// Send a divider for readability
|
||||
Serial.println(" - - - - - - - - - - - - - - - - - - - - -");
|
||||
|
||||
// Wait one second before repeating :)
|
||||
delay (1000);
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
// DS3231_Temperature
|
||||
// Copyright (C)2015 Rinky-Dink Electronics, Henning Karlsen. All right reserved
|
||||
// web: http://www.RinkyDinkElectronics.com/
|
||||
//
|
||||
// A quick demo of how to use my DS3231-library to
|
||||
// quickly send the current temperature over a serial link
|
||||
//
|
||||
// To use the hardware I2C (TWI) interface of the Arduino you must connect
|
||||
// the pins as follows:
|
||||
//
|
||||
// Arduino Uno/2009:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Arduino Analog 4 or the dedicated SDA pin
|
||||
// SCL pin -> Arduino Analog 5 or the dedicated SCL pin
|
||||
//
|
||||
// Arduino Leonardo:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Arduino Digital 2 or the dedicated SDA pin
|
||||
// SCL pin -> Arduino Digital 3 or the dedicated SCL pin
|
||||
//
|
||||
// Arduino Mega:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Arduino Digital 20 (SDA) or the dedicated SDA pin
|
||||
// SCL pin -> Arduino Digital 21 (SCL) or the dedicated SCL pin
|
||||
//
|
||||
// Arduino Due:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Arduino Digital 20 (SDA) or the dedicated SDA1 (Digital 70) pin
|
||||
// SCL pin -> Arduino Digital 21 (SCL) or the dedicated SCL1 (Digital 71) pin
|
||||
//
|
||||
// The internal pull-up resistors will be activated when using the
|
||||
// hardware I2C interfaces.
|
||||
//
|
||||
// You can connect the DS3231 to any available pin but if you use any
|
||||
// other than what is described above the library will fall back to
|
||||
// a software-based, TWI-like protocol which will require exclusive access
|
||||
// to the pins used, and you will also have to use appropriate, external
|
||||
// pull-up resistors on the data and clock signals.
|
||||
//
|
||||
|
||||
#include <DS3231.h>
|
||||
|
||||
// Init the DS3231 using the hardware interface
|
||||
DS3231 rtc(SDA, SCL);
|
||||
|
||||
void setup()
|
||||
{
|
||||
// Setup Serial connection
|
||||
Serial.begin(115200);
|
||||
// Uncomment the next line if you are using an Arduino Leonardo
|
||||
//while (!Serial) {}
|
||||
|
||||
// Initialize the rtc object
|
||||
rtc.begin();
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
// Send current temperature
|
||||
Serial.print("Temperature: ");
|
||||
Serial.print(rtc.getTemp());
|
||||
Serial.println(" C");
|
||||
delay (1000);
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
// DS3231_UnixTime
|
||||
// Copyright (C)2015 Rinky-Dink Electronics, Henning Karlsen. All right reserved
|
||||
// web: http://www.RinkyDinkElectronics.com/
|
||||
//
|
||||
// A quick demo of how to use my DS3231-library to
|
||||
// convert date and time to UnixTime
|
||||
//
|
||||
// To use the hardware I2C (TWI) interface of the Arduino you must connect
|
||||
// the pins as follows:
|
||||
//
|
||||
// Arduino Uno/2009:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Arduino Analog 4 or the dedicated SDA pin
|
||||
// SCL pin -> Arduino Analog 5 or the dedicated SCL pin
|
||||
//
|
||||
// Arduino Leonardo:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Arduino Digital 2 or the dedicated SDA pin
|
||||
// SCL pin -> Arduino Digital 3 or the dedicated SCL pin
|
||||
//
|
||||
// Arduino Mega:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Arduino Digital 20 (SDA) or the dedicated SDA pin
|
||||
// SCL pin -> Arduino Digital 21 (SCL) or the dedicated SCL pin
|
||||
//
|
||||
// Arduino Due:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Arduino Digital 20 (SDA) or the dedicated SDA1 (Digital 70) pin
|
||||
// SCL pin -> Arduino Digital 21 (SCL) or the dedicated SCL1 (Digital 71) pin
|
||||
//
|
||||
// The internal pull-up resistors will be activated when using the
|
||||
// hardware I2C interfaces.
|
||||
//
|
||||
// You can connect the DS3231 to any available pin but if you use any
|
||||
// other than what is described above the library will fall back to
|
||||
// a software-based, TWI-like protocol which will require exclusive access
|
||||
// to the pins used, and you will also have to use appropriate, external
|
||||
// pull-up resistors on the data and clock signals.
|
||||
//
|
||||
|
||||
#include <DS3231.h>
|
||||
|
||||
// Init the DS3231 using the hardware interface
|
||||
DS3231 rtc(SDA, SCL);
|
||||
|
||||
Time t;
|
||||
|
||||
void setup()
|
||||
{
|
||||
// Setup Serial connection
|
||||
Serial.begin(115200);
|
||||
// Uncomment the next line if you are using an Arduino Leonardo
|
||||
//while (!Serial) {}
|
||||
|
||||
// Initialize the rtc object
|
||||
rtc.begin();
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
// Send Current time
|
||||
Serial.print("Current Time.............................: ");
|
||||
Serial.print(rtc.getDOWStr());
|
||||
Serial.print(" ");
|
||||
Serial.print(rtc.getDateStr());
|
||||
Serial.print(" -- ");
|
||||
Serial.println(rtc.getTimeStr());
|
||||
|
||||
// Send Unixtime
|
||||
// ** Note that there may be a one second difference between the current time **
|
||||
// ** and current unixtime show if the second changes between the two calls **
|
||||
Serial.print("Current Unixtime.........................: ");
|
||||
Serial.println(rtc.getUnixTime(rtc.getTime()));
|
||||
|
||||
// Send Unixtime for 00:00:00 on January 1th 2014
|
||||
Serial.print("Unixtime for 00:00:00 on January 1th 2014: ");
|
||||
t.hour = 0;
|
||||
t.min = 0;
|
||||
t.sec = 0;
|
||||
t.year = 2014;
|
||||
t.mon = 1;
|
||||
t.date = 1;
|
||||
Serial.println(rtc.getUnixTime(t));
|
||||
|
||||
// Wait indefinitely
|
||||
while (1) {};
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
// DS3231_Serial_Easy
|
||||
// Copyright (C)2015 Rinky-Dink Electronics, Henning Karlsen. All right reserved
|
||||
// web: http://www.RinkyDinkElectronics.com/
|
||||
//
|
||||
// A quick demo of how to use my DS3231-library to
|
||||
// quickly send time and date information over a serial link
|
||||
//
|
||||
// To use the hardware I2C (TWI) interface of the chipKit you must connect
|
||||
// the pins as follows:
|
||||
//
|
||||
// chipKit Uno32/uC32:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Analog 4
|
||||
// SCL pin -> Analog 5
|
||||
// *** Please note that JP6 and JP8 must be in the I2C position (closest to the analog pins)
|
||||
//
|
||||
// chipKit Max32:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Digital 20 (the pin labeled SDA)
|
||||
// SCL pin -> Digital 21 (the pin labeled SCL)
|
||||
//
|
||||
// The chipKit boards does not have pull-up resistors on the hardware I2C interface
|
||||
// so external pull-up resistors on the data and clock signals are required.
|
||||
//
|
||||
// You can connect the DS3231 to any available pin but if you use any
|
||||
// other than what is described above the library will fall back to
|
||||
// a software-based, TWI-like protocol which will require exclusive access
|
||||
// to the pins used.
|
||||
//
|
||||
|
||||
#include <DS3231.h>
|
||||
|
||||
// Init the DS3231 using the hardware interface
|
||||
DS3231 rtc(SDA, SCL);
|
||||
|
||||
void setup()
|
||||
{
|
||||
// Setup Serial connection
|
||||
Serial.begin(115200);
|
||||
|
||||
// Initialize the rtc object
|
||||
rtc.begin();
|
||||
|
||||
// The following lines can be uncommented to set the date and time
|
||||
//rtc.setDOW(WEDNESDAY); // Set Day-of-Week to SUNDAY
|
||||
//rtc.setTime(12, 0, 0); // Set the time to 12:00:00 (24hr format)
|
||||
//rtc.setDate(1, 1, 2014); // Set the date to January 1st, 2014
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
// Send Day-of-Week
|
||||
Serial.print(rtc.getDOWStr());
|
||||
Serial.print(" ");
|
||||
|
||||
// Send date
|
||||
Serial.print(rtc.getDateStr());
|
||||
Serial.print(" -- ");
|
||||
|
||||
// Send time
|
||||
Serial.println(rtc.getTimeStr());
|
||||
|
||||
// Wait one second before repeating :)
|
||||
delay (1000);
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
// DS3231_Serial_Hard
|
||||
// Copyright (C)2015 Rinky-Dink Electronics, Henning Karlsen. All right reserved
|
||||
// web: http://www.RinkyDinkElectronics.com/
|
||||
//
|
||||
// A quick demo of how to use my DS3231-library to
|
||||
// retrieve time- and date-data for you to manipulate.
|
||||
//
|
||||
// To use the hardware I2C (TWI) interface of the chipKit you must connect
|
||||
// the pins as follows:
|
||||
//
|
||||
// chipKit Uno32/uC32:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Analog 4
|
||||
// SCL pin -> Analog 5
|
||||
// *** Please note that JP6 and JP8 must be in the I2C position (closest to the analog pins)
|
||||
//
|
||||
// chipKit Max32:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Digital 20 (the pin labeled SDA)
|
||||
// SCL pin -> Digital 21 (the pin labeled SCL)
|
||||
//
|
||||
// The chipKit boards does not have pull-up resistors on the hardware I2C interface
|
||||
// so external pull-up resistors on the data and clock signals are required.
|
||||
//
|
||||
// You can connect the DS3231 to any available pin but if you use any
|
||||
// other than what is described above the library will fall back to
|
||||
// a software-based, TWI-like protocol which will require exclusive access
|
||||
// to the pins used.
|
||||
//
|
||||
|
||||
#include <DS3231.h>
|
||||
|
||||
// Init the DS3231 using the hardware interface
|
||||
DS3231 rtc(SDA, SCL);
|
||||
|
||||
// Init a Time-data structure
|
||||
Time t;
|
||||
|
||||
void setup()
|
||||
{
|
||||
// Setup Serial connection
|
||||
Serial.begin(115200);
|
||||
|
||||
// Initialize the rtc object
|
||||
rtc.begin();
|
||||
|
||||
// The following lines can be uncommented to set the date and time
|
||||
//rtc.setDOW(WEDNESDAY); // Set Day-of-Week to SUNDAY
|
||||
//rtc.setTime(12, 0, 0); // Set the time to 12:00:00 (24hr format)
|
||||
//rtc.setDate(1, 1, 2014); // Set the date to January 1st, 2014
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
// Get data from the DS3231
|
||||
t = rtc.getTime();
|
||||
|
||||
// Send date over serial connection
|
||||
Serial.print("Today is the ");
|
||||
Serial.print(t.date, DEC);
|
||||
Serial.print(". day of ");
|
||||
Serial.print(rtc.getMonthStr());
|
||||
Serial.print(" in the year ");
|
||||
Serial.print(t.year, DEC);
|
||||
Serial.println(".");
|
||||
|
||||
// Send Day-of-Week and time
|
||||
Serial.print("It is the ");
|
||||
Serial.print(t.dow, DEC);
|
||||
Serial.print(". day of the week (counting monday as the 1th), and it has passed ");
|
||||
Serial.print(t.hour, DEC);
|
||||
Serial.print(" hour(s), ");
|
||||
Serial.print(t.min, DEC);
|
||||
Serial.print(" minute(s) and ");
|
||||
Serial.print(t.sec, DEC);
|
||||
Serial.println(" second(s) since midnight.");
|
||||
|
||||
// Send a divider for readability
|
||||
Serial.println(" - - - - - - - - - - - - - - - - - - - - -");
|
||||
|
||||
// Wait one second before repeating :)
|
||||
delay (1000);
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
// DS3231_Temperature
|
||||
// Copyright (C)2015 Rinky-Dink Electronics, Henning Karlsen. All right reserved
|
||||
// web: http://www.RinkyDinkElectronics.com/
|
||||
//
|
||||
// A quick demo of how to use my DS3231-library to
|
||||
// quickly send the current temperature over a serial link
|
||||
//
|
||||
// To use the hardware I2C (TWI) interface of the chipKit you must connect
|
||||
// the pins as follows:
|
||||
//
|
||||
// chipKit Uno32/uC32:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Analog 4
|
||||
// SCL pin -> Analog 5
|
||||
// *** Please note that JP6 and JP8 must be in the I2C position (closest to the analog pins)
|
||||
//
|
||||
// chipKit Max32:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Digital 20 (the pin labeled SDA)
|
||||
// SCL pin -> Digital 21 (the pin labeled SCL)
|
||||
//
|
||||
// The chipKit boards does not have pull-up resistors on the hardware I2C interface
|
||||
// so external pull-up resistors on the data and clock signals are required.
|
||||
//
|
||||
// You can connect the DS3231 to any available pin but if you use any
|
||||
// other than what is described above the library will fall back to
|
||||
// a software-based, TWI-like protocol which will require exclusive access
|
||||
// to the pins used.
|
||||
//
|
||||
|
||||
#include <DS3231.h>
|
||||
|
||||
// Init the DS3231 using the hardware interface
|
||||
DS3231 rtc(SDA, SCL);
|
||||
|
||||
void setup()
|
||||
{
|
||||
// Setup Serial connection
|
||||
Serial.begin(115200);
|
||||
|
||||
// Initialize the rtc object
|
||||
rtc.begin();
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
// Send current temperature
|
||||
Serial.print("Temperature: ");
|
||||
Serial.print(rtc.getTemp());
|
||||
Serial.println(" C");
|
||||
delay (1000);
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
// DS3231_UnixTime
|
||||
// Copyright (C)2015 Rinky-Dink Electronics, Henning Karlsen. All right reserved
|
||||
// web: http://www.RinkyDinkElectronics.com/
|
||||
//
|
||||
// A quick demo of how to use my DS3231-library to
|
||||
// convert date and time to UnixTime
|
||||
//
|
||||
// To use the hardware I2C (TWI) interface of the chipKit you must connect
|
||||
// the pins as follows:
|
||||
//
|
||||
// chipKit Uno32/uC32:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Analog 4
|
||||
// SCL pin -> Analog 5
|
||||
// *** Please note that JP6 and JP8 must be in the I2C position (closest to the analog pins)
|
||||
//
|
||||
// chipKit Max32:
|
||||
// ----------------------
|
||||
// DS3231: SDA pin -> Digital 20 (the pin labeled SDA)
|
||||
// SCL pin -> Digital 21 (the pin labeled SCL)
|
||||
//
|
||||
// The chipKit boards does not have pull-up resistors on the hardware I2C interface
|
||||
// so external pull-up resistors on the data and clock signals are required.
|
||||
//
|
||||
// You can connect the DS3231 to any available pin but if you use any
|
||||
// other than what is described above the library will fall back to
|
||||
// a software-based, TWI-like protocol which will require exclusive access
|
||||
// to the pins used.
|
||||
//
|
||||
|
||||
#include <DS3231.h>
|
||||
|
||||
// Init the DS3231 using the hardware interface
|
||||
DS3231 rtc(SDA, SCL);
|
||||
|
||||
Time t;
|
||||
|
||||
void setup()
|
||||
{
|
||||
// Setup Serial connection
|
||||
Serial.begin(115200);
|
||||
|
||||
// Initialize the rtc object
|
||||
rtc.begin();
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
// Send Current time
|
||||
Serial.print("Current Time.............................: ");
|
||||
Serial.print(rtc.getDOWStr());
|
||||
Serial.print(" ");
|
||||
Serial.print(rtc.getDateStr());
|
||||
Serial.print(" -- ");
|
||||
Serial.println(rtc.getTimeStr());
|
||||
|
||||
// Send Unixtime
|
||||
// ** Note that there may be a one second difference between the current time **
|
||||
// ** and current unixtime show if the second changes between the two calls **
|
||||
Serial.print("Current Unixtime.........................: ");
|
||||
Serial.println(rtc.getUnixTime(rtc.getTime()));
|
||||
|
||||
// Send Unixtime for 00:00:00 on January 1th 2014
|
||||
Serial.print("Unixtime for 00:00:00 on January 1th 2014: ");
|
||||
t.hour = 0;
|
||||
t.min = 0;
|
||||
t.sec = 0;
|
||||
t.year = 2014;
|
||||
t.mon = 1;
|
||||
t.date = 1;
|
||||
Serial.println(rtc.getUnixTime(t));
|
||||
|
||||
// Wait indefinitely
|
||||
while (1) {};
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
void DS3231::begin()
|
||||
{
|
||||
_use_hw = false;
|
||||
if ((_sda_pin == SDA) and (_scl_pin == SCL))
|
||||
{
|
||||
_use_hw = true;
|
||||
twi = TWI1;
|
||||
pmc_enable_periph_clk(WIRE_INTERFACE_ID);
|
||||
PIO_Configure(g_APinDescription[PIN_WIRE_SDA].pPort, g_APinDescription[PIN_WIRE_SDA].ulPinType, g_APinDescription[PIN_WIRE_SDA].ulPin, g_APinDescription[PIN_WIRE_SDA].ulPinConfiguration);
|
||||
PIO_Configure(g_APinDescription[PIN_WIRE_SCL].pPort, g_APinDescription[PIN_WIRE_SCL].ulPinType, g_APinDescription[PIN_WIRE_SCL].ulPin, g_APinDescription[PIN_WIRE_SCL].ulPinConfiguration);
|
||||
NVIC_DisableIRQ(TWI1_IRQn);
|
||||
NVIC_ClearPendingIRQ(TWI1_IRQn);
|
||||
NVIC_SetPriority(TWI1_IRQn, 0);
|
||||
NVIC_EnableIRQ(TWI1_IRQn);
|
||||
|
||||
}
|
||||
else if ((_sda_pin == SDA1) and (_scl_pin == SCL1))
|
||||
{
|
||||
_use_hw = true;
|
||||
twi = TWI0;
|
||||
pmc_enable_periph_clk(WIRE1_INTERFACE_ID);
|
||||
PIO_Configure(g_APinDescription[PIN_WIRE1_SDA].pPort, g_APinDescription[PIN_WIRE1_SDA].ulPinType, g_APinDescription[PIN_WIRE1_SDA].ulPin, g_APinDescription[PIN_WIRE1_SDA].ulPinConfiguration);
|
||||
PIO_Configure(g_APinDescription[PIN_WIRE1_SCL].pPort, g_APinDescription[PIN_WIRE1_SCL].ulPinType, g_APinDescription[PIN_WIRE1_SCL].ulPin, g_APinDescription[PIN_WIRE1_SCL].ulPinConfiguration);
|
||||
NVIC_DisableIRQ(TWI0_IRQn);
|
||||
NVIC_ClearPendingIRQ(TWI0_IRQn);
|
||||
NVIC_SetPriority(TWI0_IRQn, 0);
|
||||
NVIC_EnableIRQ(TWI0_IRQn);
|
||||
}
|
||||
|
||||
if (_use_hw)
|
||||
{
|
||||
// activate internal pullups for twi.
|
||||
digitalWrite(SDA, 1);
|
||||
digitalWrite(SCL, 1);
|
||||
|
||||
// Reset the TWI
|
||||
twi->TWI_CR = TWI_CR_SWRST;
|
||||
// TWI Slave Mode Disabled, TWI Master Mode Disabled.
|
||||
twi->TWI_CR = TWI_CR_SVDIS;
|
||||
twi->TWI_CR = TWI_CR_MSDIS;
|
||||
// Set TWI Speed
|
||||
twi->TWI_CWGR = (TWI_DIV << 16) | (TWI_SPEED << 8) | TWI_SPEED;
|
||||
// Set master mode
|
||||
twi->TWI_CR = TWI_CR_MSEN;
|
||||
}
|
||||
else
|
||||
{
|
||||
pinMode(_scl_pin, OUTPUT);
|
||||
}
|
||||
}
|
||||
|
||||
void DS3231::_burstRead()
|
||||
{
|
||||
if (_use_hw)
|
||||
{
|
||||
// Set slave address and number of internal address bytes.
|
||||
twi->TWI_MMR = (1 << 8) | TWI_MMR_MREAD | (DS3231_ADDR << 16);
|
||||
// Set internal address bytes
|
||||
twi->TWI_IADR = 0;
|
||||
// Send START condition
|
||||
twi->TWI_CR = TWI_CR_START;
|
||||
|
||||
for (int i=0; i<6; i++)
|
||||
{
|
||||
while ((twi->TWI_SR & TWI_SR_RXRDY) != TWI_SR_RXRDY)
|
||||
{
|
||||
};
|
||||
_burstArray[i] = twi->TWI_RHR;
|
||||
}
|
||||
|
||||
twi->TWI_CR = TWI_CR_STOP;
|
||||
while ((twi->TWI_SR & TWI_SR_RXRDY) != TWI_SR_RXRDY) {};
|
||||
_burstArray[6] = twi->TWI_RHR;
|
||||
while ((twi->TWI_SR & TWI_SR_TXCOMP) != TWI_SR_TXCOMP) {};
|
||||
}
|
||||
else
|
||||
{
|
||||
_sendStart(DS3231_ADDR_W);
|
||||
_waitForAck();
|
||||
_writeByte(0);
|
||||
_waitForAck();
|
||||
_sendStart(DS3231_ADDR_R);
|
||||
_waitForAck();
|
||||
|
||||
for (int i=0; i<7; i++)
|
||||
{
|
||||
_burstArray[i] = _readByte();
|
||||
if (i<6)
|
||||
_sendAck();
|
||||
else
|
||||
_sendNack();
|
||||
}
|
||||
_sendStop();
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t DS3231::_readRegister(uint8_t reg)
|
||||
{
|
||||
uint8_t readValue=0;
|
||||
|
||||
if (_use_hw)
|
||||
{
|
||||
// Set slave address and number of internal address bytes.
|
||||
twi->TWI_MMR = (1 << 8) | TWI_MMR_MREAD | (DS3231_ADDR << 16);
|
||||
// Set internal address bytes
|
||||
twi->TWI_IADR = reg;
|
||||
// Send START and STOP condition to read a single byte
|
||||
twi->TWI_CR = TWI_CR_START | TWI_CR_STOP;
|
||||
while ((twi->TWI_SR & TWI_SR_RXRDY) != TWI_SR_RXRDY) {};
|
||||
readValue = twi->TWI_RHR;
|
||||
while ((twi->TWI_SR & TWI_SR_TXCOMP) != TWI_SR_TXCOMP) {};
|
||||
}
|
||||
else
|
||||
{
|
||||
_sendStart(DS3231_ADDR_W);
|
||||
_waitForAck();
|
||||
_writeByte(reg);
|
||||
_waitForAck();
|
||||
_sendStart(DS3231_ADDR_R);
|
||||
_waitForAck();
|
||||
readValue = _readByte();
|
||||
_sendNack();
|
||||
_sendStop();
|
||||
}
|
||||
return readValue;
|
||||
}
|
||||
|
||||
void DS3231::_writeRegister(uint8_t reg, uint8_t value)
|
||||
{
|
||||
if (_use_hw)
|
||||
{
|
||||
// Set slave address and number of internal address bytes.
|
||||
twi->TWI_MMR = (1 << 8) | (DS3231_ADDR << 16);
|
||||
// Set internal address bytes
|
||||
twi->TWI_IADR = reg;
|
||||
// Send a single byte to start transfer
|
||||
twi->TWI_THR = value;
|
||||
while ((twi->TWI_SR & TWI_SR_TXRDY) != TWI_SR_TXRDY) {};
|
||||
// Send STOP condition
|
||||
twi->TWI_CR = TWI_CR_STOP;
|
||||
while ((twi->TWI_SR & TWI_SR_TXCOMP) != TWI_SR_TXCOMP) {};
|
||||
}
|
||||
else
|
||||
{
|
||||
_sendStart(DS3231_ADDR_W);
|
||||
_waitForAck();
|
||||
_writeByte(reg);
|
||||
_waitForAck();
|
||||
_writeByte(value);
|
||||
_waitForAck();
|
||||
_sendStop();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
// *** Hardwarespecific defines ***
|
||||
#define SDA 20
|
||||
#define SCL 21
|
||||
#define SDA1 70
|
||||
#define SCL1 71
|
||||
|
||||
#define TWI_SPEED TWI_SPEED_400k // Set default TWI Speed
|
||||
#define TWI_SPEED_100k 208
|
||||
#define TWI_SPEED_400k 101
|
||||
|
||||
#define TWI_DIV TWI_DIV_400k // Set divider for TWI Speed (must match TWI_SPEED setting)
|
||||
#define TWI_DIV_100k 1
|
||||
#define TWI_DIV_400k 0
|
||||
@@ -1,153 +0,0 @@
|
||||
void DS3231::begin()
|
||||
{
|
||||
if ((_sda_pin == SDA) and (_scl_pin == SCL))
|
||||
{
|
||||
_use_hw = true;
|
||||
// activate internal pullups for twi.
|
||||
digitalWrite(SDA, HIGH);
|
||||
digitalWrite(SCL, HIGH);
|
||||
//delay(1); // Workaround for a linker bug
|
||||
|
||||
// initialize twi prescaler and bit rate
|
||||
cbi(TWSR, TWPS0);
|
||||
cbi(TWSR, TWPS1);
|
||||
TWBR = ((F_CPU / TWI_FREQ) - 16) / 2;
|
||||
|
||||
// enable twi module, acks, and twi interrupt
|
||||
TWCR = _BV(TWEN) | _BV(TWIE)/* | _BV(TWEA)*/;
|
||||
}
|
||||
else
|
||||
{
|
||||
_use_hw = false;
|
||||
pinMode(_scl_pin, OUTPUT);
|
||||
}
|
||||
}
|
||||
|
||||
void DS3231::_burstRead()
|
||||
{
|
||||
if (_use_hw)
|
||||
{
|
||||
// Send start address
|
||||
TWCR = _BV(TWEN) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA); // Send START
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
TWDR = DS3231_ADDR_W;
|
||||
TWCR = _BV(TWEN) | _BV(TWINT) | _BV(TWEA); // Clear TWINT to proceed
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
TWDR = 0;
|
||||
TWCR = _BV(TWEN) | _BV(TWINT) | _BV(TWEA); // Clear TWINT to proceed
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
|
||||
// Read data starting from start address
|
||||
TWCR = _BV(TWEN) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA); // Send rep. START
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
TWDR = DS3231_ADDR_R;
|
||||
TWCR = _BV(TWEN) | _BV(TWINT) | _BV(TWEA); // Clear TWINT to proceed
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
for (int i=0; i<7; i++)
|
||||
{
|
||||
TWCR = _BV(TWEN) | _BV(TWINT) | _BV(TWEA); // Send ACK and clear TWINT to proceed
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
_burstArray[i] = TWDR;
|
||||
}
|
||||
TWCR = _BV(TWEN) | _BV(TWINT); // Send NACK and clear TWINT to proceed
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
|
||||
TWCR = _BV(TWEN)| _BV(TWINT) | _BV(TWSTO); // Send STOP
|
||||
}
|
||||
else
|
||||
{
|
||||
_sendStart(DS3231_ADDR_W);
|
||||
_waitForAck();
|
||||
_writeByte(0);
|
||||
_waitForAck();
|
||||
_sendStart(DS3231_ADDR_R);
|
||||
_waitForAck();
|
||||
|
||||
for (int i=0; i<7; i++)
|
||||
{
|
||||
_burstArray[i] = _readByte();
|
||||
if (i<6)
|
||||
_sendAck();
|
||||
else
|
||||
_sendNack();
|
||||
}
|
||||
_sendStop();
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t DS3231::_readRegister(uint8_t reg)
|
||||
{
|
||||
uint8_t readValue=0;
|
||||
|
||||
if (_use_hw)
|
||||
{
|
||||
// Send start address
|
||||
TWCR = _BV(TWEN) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA); // Send START
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
TWDR = DS3231_ADDR_W;
|
||||
TWCR = _BV(TWEN) | _BV(TWINT) | _BV(TWEA); // Clear TWINT to proceed
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
TWDR = reg;
|
||||
TWCR = _BV(TWEN) | _BV(TWINT) | _BV(TWEA); // Clear TWINT to proceed
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
|
||||
// Read data starting from start address
|
||||
TWCR = _BV(TWEN) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA); // Send rep. START
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
TWDR = DS3231_ADDR_R;
|
||||
TWCR = _BV(TWEN) | _BV(TWINT) | _BV(TWEA); // Clear TWINT to proceed
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
TWCR = _BV(TWEN) | _BV(TWINT) | _BV(TWEA); // Send ACK and clear TWINT to proceed
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
readValue = TWDR;
|
||||
TWCR = _BV(TWEN) | _BV(TWINT); // Send NACK and clear TWINT to proceed
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
|
||||
TWCR = _BV(TWEN)| _BV(TWINT) | _BV(TWSTO); // Send STOP
|
||||
}
|
||||
else
|
||||
{
|
||||
_sendStart(DS3231_ADDR_W);
|
||||
_waitForAck();
|
||||
_writeByte(reg);
|
||||
_waitForAck();
|
||||
_sendStart(DS3231_ADDR_R);
|
||||
_waitForAck();
|
||||
readValue = _readByte();
|
||||
_sendNack();
|
||||
_sendStop();
|
||||
}
|
||||
return readValue;
|
||||
}
|
||||
|
||||
void DS3231::_writeRegister(uint8_t reg, uint8_t value)
|
||||
{
|
||||
if (_use_hw)
|
||||
{
|
||||
// Send start address
|
||||
TWCR = _BV(TWEN) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA); // Send START
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
TWDR = DS3231_ADDR_W;
|
||||
TWCR = _BV(TWEN) | _BV(TWINT) | _BV(TWEA); // Clear TWINT to proceed
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
TWDR = reg;
|
||||
TWCR = _BV(TWEN) | _BV(TWINT) | _BV(TWEA); // Clear TWINT to proceed
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
TWDR = value;
|
||||
TWCR = _BV(TWEN) | _BV(TWINT) | _BV(TWEA); // Clear TWINT to proceed
|
||||
while ((TWCR & _BV(TWINT)) == 0) {}; // Wait for TWI to be ready
|
||||
|
||||
TWCR = _BV(TWEN)| _BV(TWINT) | _BV(TWSTO); // Send STOP
|
||||
}
|
||||
else
|
||||
{
|
||||
_sendStart(DS3231_ADDR_W);
|
||||
_waitForAck();
|
||||
_writeByte(reg);
|
||||
_waitForAck();
|
||||
_writeByte(value);
|
||||
_waitForAck();
|
||||
_sendStop();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
// *** Hardwarespecific defines ***
|
||||
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
|
||||
|
||||
#ifndef TWI_FREQ
|
||||
#define TWI_FREQ 400000L
|
||||
#endif
|
||||
@@ -1,192 +0,0 @@
|
||||
inline void _waitForIdleBus() { while (I2C1CON & 0x1f) {} }
|
||||
|
||||
void DS3231::begin()
|
||||
{
|
||||
if ((_sda_pin == SDA) and (_scl_pin == SCL))
|
||||
{
|
||||
uint32_t tpgd;
|
||||
|
||||
_use_hw = true;
|
||||
pinMode(SDA, OUTPUT);
|
||||
digitalWrite(SDA, HIGH);
|
||||
IFS0CLR = 0xE0000000; // Clear Interrupt Flag
|
||||
IEC0CLR = 0xE0000000; // Disable Interrupt
|
||||
I2C1CONCLR = (1 << _I2CCON_ON); // Disable I2C interface
|
||||
tpgd = ((F_CPU / 8) * 104) / 125000000;
|
||||
I2C1BRG = (F_CPU / (2 * TWI_FREQ) - tpgd) - 2; // Set I2C Speed
|
||||
I2C1ADD = DS3231_ADDR; // Set I2C device address
|
||||
I2C1CONSET = (1 << _I2CCON_ON) | (1 << _I2CCON_STREN); // Enable I2C Interface
|
||||
}
|
||||
else
|
||||
{
|
||||
_use_hw = false;
|
||||
pinMode(_scl_pin, OUTPUT);
|
||||
}
|
||||
}
|
||||
|
||||
void DS3231::_burstRead()
|
||||
{
|
||||
if (_use_hw)
|
||||
{
|
||||
_waitForIdleBus(); // Wait for I2C bus to be Idle before starting
|
||||
I2C1CONSET = (1 << _I2CCON_SEN); // Send start condition
|
||||
if (I2C1STAT & (1 << _I2CSTAT_BCL)) { return; } // Check if there is a bus collision
|
||||
while (I2C1CON & (1 << _I2CCON_SEN)) {} // Wait for start condition to finish
|
||||
I2C1TRN = (DS3231_ADDR<<1); // Send device Write address
|
||||
while (I2C1STAT & (1 << _I2CSTAT_IWCOL)) // Check if there is a Write collision
|
||||
{
|
||||
I2C1STATCLR = (1 << _I2CSTAT_IWCOL); // Clear Write collision flag
|
||||
I2C1TRN = (DS3231_ADDR<<1); // Retry send device Write address
|
||||
}
|
||||
while (I2C1STAT & (1 << _I2CSTAT_TRSTAT)) {} // Wait for transmit to finish
|
||||
while (I2C1STAT & (1 << _I2CSTAT_ACKSTAT)) {} // Wait for ACK
|
||||
I2C1TRN = 0; // Send the register address
|
||||
while (I2C1STAT & (1 << _I2CSTAT_TRSTAT)) {} // Wait for transmit to finish
|
||||
while (I2C1STAT & (1 << _I2CSTAT_ACKSTAT)) {} // Wait for ACK
|
||||
_waitForIdleBus(); // Wait for I2C bus to be Idle before starting
|
||||
I2C1CONSET = (1 << _I2CCON_RSEN); // Send start condition
|
||||
if (I2C1STAT & (1 << _I2CSTAT_BCL)) { return; } // Check if there is a bus collision
|
||||
while (I2C1CON & (1 << _I2CCON_RSEN)) {} // Wait for start condition to finish
|
||||
I2C1TRN = (DS3231_ADDR<<1) | 1; // Send device Read address
|
||||
while (I2C1STAT & (1 << _I2CSTAT_IWCOL)) // Check if there is a Write collision
|
||||
{
|
||||
I2C1STATCLR = (1 << _I2CSTAT_IWCOL); // Clear Write collision flag
|
||||
I2C1TRN = (DS3231_ADDR<<1) | 1; // Retry send device Read address
|
||||
}
|
||||
while (I2C1STAT & (1 << _I2CSTAT_TRSTAT)) {} // Wait for transmit to finish
|
||||
while (I2C1STAT & (1 << _I2CSTAT_ACKSTAT)) {} // Wait for ACK
|
||||
byte dummy = I2C1RCV; // Clear _I2CSTAT_RBF (Receive Buffer Full)
|
||||
for (int i=0; i<7; i++)
|
||||
{
|
||||
_waitForIdleBus(); // Wait for I2C bus to be Idle before continuing
|
||||
I2C1CONSET = (1 << _I2CCON_RCEN); // Set RCEN to start receive
|
||||
while (I2C1CON & (1 << _I2CCON_RCEN)) {} // Wait for Receive operation to finish
|
||||
while (!(I2C1STAT & (1 << _I2CSTAT_RBF))) {} // Wait for Receive Buffer Full
|
||||
_burstArray[i] = I2C1RCV; // Read data
|
||||
if (i == 6)
|
||||
I2C1CONSET = (1 << _I2CCON_ACKDT); // Prepare to send NACK
|
||||
else
|
||||
I2C1CONCLR = (1 << _I2CCON_ACKDT); // Prepare to send ACK
|
||||
I2C1CONSET = (1 << _I2CCON_ACKEN); // Send ACK/NACK
|
||||
while (I2C1CON & (1 << _I2CCON_ACKEN)) {} // Wait for ACK/NACK send to finish
|
||||
}
|
||||
I2C1CONSET = (1 << _I2CCON_PEN); // Send stop condition
|
||||
while (I2C1CON & (1 << _I2CCON_PEN)) {} // Wait for stop condition to finish
|
||||
}
|
||||
else
|
||||
{
|
||||
_sendStart(DS3231_ADDR_W);
|
||||
_waitForAck();
|
||||
_writeByte(0);
|
||||
_waitForAck();
|
||||
_sendStart(DS3231_ADDR_R);
|
||||
_waitForAck();
|
||||
|
||||
for (int i=0; i<7; i++)
|
||||
{
|
||||
_burstArray[i] = _readByte();
|
||||
if (i<6)
|
||||
_sendAck();
|
||||
else
|
||||
_sendNack();
|
||||
}
|
||||
_sendStop();
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t DS3231::_readRegister(uint8_t reg)
|
||||
{
|
||||
uint8_t readValue=0;
|
||||
|
||||
if (_use_hw)
|
||||
{
|
||||
_waitForIdleBus(); // Wait for I2C bus to be Idle before starting
|
||||
I2C1CONSET = (1 << _I2CCON_SEN); // Send start condition
|
||||
if (I2C1STAT & (1 << _I2CSTAT_BCL)) { return 0xff; }// Check if there is a bus collision
|
||||
while (I2C1CON & (1 << _I2CCON_SEN)) {} // Wait for start condition to finish
|
||||
I2C1TRN = (DS3231_ADDR<<1); // Send device Write address
|
||||
while (I2C1STAT & (1 << _I2CSTAT_IWCOL)) // Check if there is a Write collision
|
||||
{
|
||||
I2C1STATCLR = (1 << _I2CSTAT_IWCOL); // Clear Write collision flag
|
||||
I2C1TRN = (DS3231_ADDR<<1); // Retry send device Write address
|
||||
}
|
||||
while (I2C1STAT & (1 << _I2CSTAT_TRSTAT)) {} // Wait for transmit to finish
|
||||
while (I2C1STAT & (1 << _I2CSTAT_ACKSTAT)) {} // Wait for ACK
|
||||
I2C1TRN = reg; // Send the register address
|
||||
while (I2C1STAT & (1 << _I2CSTAT_TRSTAT)) {} // Wait for transmit to finish
|
||||
while (I2C1STAT & (1 << _I2CSTAT_ACKSTAT)) {} // Wait for ACK
|
||||
_waitForIdleBus(); // Wait for I2C bus to be Idle before starting
|
||||
I2C1CONSET = (1 << _I2CCON_RSEN); // Send start condition
|
||||
if (I2C1STAT & (1 << _I2CSTAT_BCL)) { return 0xff; }// Check if there is a bus collision
|
||||
while (I2C1CON & (1 << _I2CCON_RSEN)) {} // Wait for start condition to finish
|
||||
I2C1TRN = (DS3231_ADDR<<1) | 1; // Send device Read address
|
||||
while (I2C1STAT & (1 << _I2CSTAT_IWCOL)) // Check if there is a Write collision
|
||||
{
|
||||
I2C1STATCLR = (1 << _I2CSTAT_IWCOL); // Clear Write collision flag
|
||||
I2C1TRN = (DS3231_ADDR<<1) | 1; // Retry send device Read address
|
||||
}
|
||||
while (I2C1STAT & (1 << _I2CSTAT_TRSTAT)) {} // Wait for transmit to finish
|
||||
while (I2C1STAT & (1 << _I2CSTAT_ACKSTAT)) {} // Wait for ACK
|
||||
byte dummy = I2C1RCV; // Clear _I2CSTAT_RBF (Receive Buffer Full)
|
||||
_waitForIdleBus(); // Wait for I2C bus to be Idle before continuing
|
||||
I2C1CONSET = (1 << _I2CCON_RCEN); // Set RCEN to start receive
|
||||
while (I2C1CON & (1 << _I2CCON_RCEN)) {} // Wait for Receive operation to finish
|
||||
while (!(I2C1STAT & (1 << _I2CSTAT_RBF))) {} // Wait for Receive Buffer Full
|
||||
readValue = I2C1RCV; // Read data
|
||||
I2C1CONSET = (1 << _I2CCON_ACKDT); // Prepare to send NACK
|
||||
I2C1CONSET = (1 << _I2CCON_ACKEN); // Send NACK
|
||||
while (I2C1CON & (1 << _I2CCON_ACKEN)) {} // Wait for NACK send to finish
|
||||
I2C1CONSET = (1 << _I2CCON_PEN); // Send stop condition
|
||||
while (I2C1CON & (1 << _I2CCON_PEN)) {} // Wait for stop condition to finish
|
||||
}
|
||||
else
|
||||
{
|
||||
_sendStart(DS3231_ADDR_W);
|
||||
_waitForAck();
|
||||
_writeByte(reg);
|
||||
_waitForAck();
|
||||
_sendStart(DS3231_ADDR_R);
|
||||
_waitForAck();
|
||||
readValue = _readByte();
|
||||
_sendNack();
|
||||
_sendStop();
|
||||
}
|
||||
return readValue;
|
||||
}
|
||||
|
||||
void DS3231::_writeRegister(uint8_t reg, uint8_t value)
|
||||
{
|
||||
if (_use_hw)
|
||||
{
|
||||
_waitForIdleBus(); // Wait for I2C bus to be Idle before starting
|
||||
I2C1CONSET = (1 << _I2CCON_SEN); // Send start condition
|
||||
if (I2C1STAT & (1 << _I2CSTAT_BCL)) { return; } // Check if there is a bus collision
|
||||
while (I2C1CON & (1 << _I2CCON_SEN)) {} // Wait for start condition to finish
|
||||
I2C1TRN = (DS3231_ADDR<<1); // Send device Write address
|
||||
while (I2C1STAT & (1 << _I2CSTAT_IWCOL)) // Check if there is a Write collision
|
||||
{
|
||||
I2C1STATCLR = (1 << _I2CSTAT_IWCOL); // Clear Write collision flag
|
||||
I2C1TRN = (DS3231_ADDR<<1); // Retry send device Write address
|
||||
}
|
||||
while (I2C1STAT & (1 << _I2CSTAT_TRSTAT)) {} // Wait for transmit to finish
|
||||
while (I2C1STAT & (1 << _I2CSTAT_ACKSTAT)) {} // Wait for ACK
|
||||
I2C1TRN = reg; // Send the 1st data byte
|
||||
while (I2C1STAT & (1 << _I2CSTAT_TRSTAT)) {} // Wait for transmit to finish
|
||||
while (I2C1STAT & (1 << _I2CSTAT_ACKSTAT)) {} // Wait for ACK
|
||||
I2C1TRN = value; // Send the 2nd data byte
|
||||
while (I2C1STAT & (1 << _I2CSTAT_TRSTAT)) {} // Wait for transmit to finish
|
||||
while (I2C1STAT & (1 << _I2CSTAT_ACKSTAT)) {} // Wait for ACK
|
||||
I2C1CONSET = (1 << _I2CCON_PEN); // Send stop condition
|
||||
while (I2C1CON & (1 << _I2CCON_PEN)) {} // Wait for stop condition to finish
|
||||
}
|
||||
else
|
||||
{
|
||||
_sendStart(DS3231_ADDR_W);
|
||||
_waitForAck();
|
||||
_writeByte(reg);
|
||||
_waitForAck();
|
||||
_writeByte(value);
|
||||
_waitForAck();
|
||||
_sendStop();
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
// *** Hardwarespecific defines ***
|
||||
|
||||
#if !defined(_UP_MCU_)
|
||||
#if defined(__32MX320F128H__)
|
||||
#define SDA 18 // A4 (Remeber to set the jumper correctly)
|
||||
#define SCL 19 // A5 (Remeber to set the jumper correctly)
|
||||
#elif defined(__32MX340F512H__)
|
||||
#define SDA 18 // A4 (Remeber to set the jumper correctly)
|
||||
#define SCL 19 // A5 (Remeber to set the jumper correctly)
|
||||
#elif defined(__32MX795F512L__)
|
||||
#define SDA 20 // Digital 20
|
||||
#define SCL 21 // Digital 21
|
||||
#else
|
||||
#error "Unsupported PIC32 MCU!"
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef TWI_FREQ
|
||||
#define TWI_FREQ 400000L
|
||||
#endif
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
DS3231 KEYWORD1
|
||||
Time KEYWORD1
|
||||
|
||||
begin KEYWORD2
|
||||
getTime KEYWORD2
|
||||
setTime KEYWORD2
|
||||
setDate KEYWORD2
|
||||
setDOW KEYWORD2
|
||||
getTimeStr KEYWORD2
|
||||
getDateStr KEYWORD2
|
||||
getDOWStr KEYWORD2
|
||||
getMonthStr KEYWORD2
|
||||
getUnixTime KEYWORD2
|
||||
enable32KHz KEYWORD2
|
||||
setOutput KEYWORD2
|
||||
setSQWRate KEYWORD2
|
||||
getTemp KEYWORD2
|
||||
|
||||
hour KEYWORD2
|
||||
min KEYWORD2
|
||||
sec KEYWORD2
|
||||
date KEYWORD2
|
||||
mon KEYWORD2
|
||||
year KEYWORD2
|
||||
dow KEYWORD2
|
||||
|
||||
FORMAT_SHORT LITERAL1
|
||||
FORMAT_LONG LITERAL1
|
||||
|
||||
FORMAT_LITTLEENDIAN LITERAL1
|
||||
FORMAT_BIGENDIAN LITERAL1
|
||||
FORMAT_MIDDLEENDIAN LITERAL1
|
||||
|
||||
MONDAY LITERAL1
|
||||
TUESDAY LITERAL1
|
||||
WEDNESDAY LITERAL1
|
||||
THURSDAY LITERAL1
|
||||
FRIDAY LITERAL1
|
||||
SATURDAY LITERAL1
|
||||
SUNDAY LITERAL1
|
||||
|
||||
SQW_RATE_1 LITERAL1
|
||||
SQW_RATE_1K LITERAL1
|
||||
SQW_RATE_4K LITERAL1
|
||||
SQW_RATE_8K LITERAL1
|
||||
|
||||
OUTPUT_SQW LITERAL1
|
||||
OUTPUT_INT LITERAL1
|
||||
|
||||
SDA LITERAL1
|
||||
SCL LITERAL1
|
||||
SDA1 LITERAL1
|
||||
SCL1 LITERAL1
|
||||
@@ -0,0 +1,32 @@
|
||||
; PlatformIO project for Projeto.ino, the DS3231 sketch that sits in the
|
||||
; repository root. The ESP8266 sketch has its own project, because PlatformIO
|
||||
; only converts a *.ino file that is at the top of its src_dir:
|
||||
;
|
||||
; pio run -> Projeto.ino (Arduino Nano)
|
||||
; pio run -d Fetch_rain -> Fetch_rain.ino (ESP8266 ESP-01)
|
||||
; ./run.sh -> both, then the offline tests
|
||||
;
|
||||
; Neither sketch names its board in its own source. The board is named on the
|
||||
; course poster kept in this repository, Sumbrella.pdf, under "Listagem de
|
||||
; material": "Arduino Nano" and "ESP8226 ESP-01" (sic). Projeto.ino agrees with
|
||||
; the Nano: analogWrite() on pins 5 and 6, both PWM-capable, plus the SDA/SCL
|
||||
; macros, which are A4/A5 = 18/19 on the Nano exactly as on the Uno.
|
||||
|
||||
[platformio]
|
||||
src_dir = .
|
||||
|
||||
[env:nano]
|
||||
platform = atmelavr
|
||||
board = nanoatmega328new
|
||||
framework = arduino
|
||||
monitor_speed = 9600
|
||||
; src_dir is the repository root, so keep the ESP8266 sketch's own project
|
||||
; directory (and the .pio tree PlatformIO creates inside it) out of this build.
|
||||
build_src_filter = +<*> -<Fetch_rain/>
|
||||
lib_deps =
|
||||
; DS3231 1.01 — Rinky-Dink Electronics / Henning Karlsen. It is NOT in the
|
||||
; PlatformIO registry (all 87 registry search hits were checked for the
|
||||
; class Time / getTimeStr() / DS3231(data, sclk) API it needs), so it is
|
||||
; pinned to a byte-identical mirror of the removed libs/DS3231 at tag v1.01.
|
||||
; See DEPENDENCIAS.md.
|
||||
https://github.com/whonore/DS3231.git#v1.01
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build both targets and run the offline test suite. Exit status != 0 on any
|
||||
# build error or test failure. No board is needed.
|
||||
set -uo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
exec bash tests/run_tests.sh
|
||||
@@ -0,0 +1,170 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline check: every MCU pin used by the sketches exists on the target board.
|
||||
|
||||
Board data is the published pin map of each board:
|
||||
|
||||
- Arduino Nano (ATmega328P, DIP-30): digital pins 0-19, where A0-A5 are 14-19,
|
||||
PWM on 3, 5, 6, 9, 10 and 11, and SDA/SCL are A4/A5 = 18/19.
|
||||
- ESP-01 (ESP8266EX, 8-pin module): GPIO0-GPIO3 are the pins broken out; PWM is
|
||||
available on every ESP8266 GPIO except GPIO16.
|
||||
|
||||
The board of each sketch is the one named on the course poster kept in this
|
||||
repository (Sumbrella.pdf, "Listagem de material": Arduino Nano and ESP8266
|
||||
ESP-01) and declared in platformio.ini.
|
||||
|
||||
Run with --selftest to prove the check bites: copies with an out-of-range pin
|
||||
and with analogWrite() on a non-PWM pin must both be rejected.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
BOARDS = {
|
||||
"nano": {
|
||||
"env": "nano",
|
||||
"sketch": "Projeto.ino",
|
||||
"pins": set(range(0, 20)),
|
||||
"pwm": {3, 5, 6, 9, 10, 11},
|
||||
"macros": {"SDA": 18, "SCL": 19},
|
||||
"dn_pins": False,
|
||||
},
|
||||
"esp01": {
|
||||
"env": "esp8266",
|
||||
"sketch": os.path.join("Fetch_rain", "Fetch_rain.ino"),
|
||||
"pins": {0, 1, 2, 3},
|
||||
"pwm": {0, 1, 2, 3},
|
||||
"macros": {},
|
||||
"dn_pins": True,
|
||||
},
|
||||
}
|
||||
|
||||
CALL_RE = re.compile(
|
||||
r"\b(pinMode|digitalWrite|digitalRead|analogWrite|analogRead)\s*\(\s*"
|
||||
r"([A-Za-z_][A-Za-z0-9_]*|\d+)"
|
||||
)
|
||||
ESPNUM_RE = re.compile(r"\bD(\d{1,2})\b")
|
||||
|
||||
|
||||
def read(path):
|
||||
with open(path, encoding="utf-8") as fh:
|
||||
return fh.read()
|
||||
|
||||
|
||||
def used_pins(text, macros):
|
||||
"""Return [(function, raw_pin_text, resolved_int)] for a sketch."""
|
||||
found = []
|
||||
for func, raw in CALL_RE.findall(text):
|
||||
if raw.isdigit():
|
||||
found.append((func, raw, int(raw)))
|
||||
elif raw in macros:
|
||||
found.append((func, raw, macros[raw]))
|
||||
return found
|
||||
|
||||
|
||||
def check(root):
|
||||
errors = []
|
||||
for board, cfg in BOARDS.items():
|
||||
path = os.path.join(root, cfg["sketch"])
|
||||
if not os.path.isfile(path):
|
||||
errors.append("%s: sketch %s is missing" % (board, cfg["sketch"]))
|
||||
continue
|
||||
text = read(path)
|
||||
|
||||
for func, raw, pin in used_pins(text, cfg["macros"]):
|
||||
if pin not in cfg["pins"]:
|
||||
errors.append("%s: %s(%s) -> pin %s does not exist on %s "
|
||||
"(valid: 0-%d)"
|
||||
% (board, func, raw, pin, board,
|
||||
max(cfg["pins"])))
|
||||
elif func == "analogWrite" and pin not in cfg["pwm"]:
|
||||
errors.append("%s: analogWrite(%s) -> pin %s is not PWM-capable"
|
||||
% (board, raw, pin))
|
||||
|
||||
# A stray D0..D16 style pin on the AVR target would not compile.
|
||||
if not cfg["dn_pins"] and ESPNUM_RE.search(text):
|
||||
errors.append("%s: %s uses an ESP8266 Dn pin name"
|
||||
% (board, cfg["sketch"]))
|
||||
return errors
|
||||
|
||||
|
||||
def run_selftest():
|
||||
failures = []
|
||||
|
||||
def copy():
|
||||
tmp = tempfile.mkdtemp(prefix="sumbrella-pin-selftest-")
|
||||
dst = os.path.join(tmp, "repo")
|
||||
shutil.copytree(REPO, dst, symlinks=True)
|
||||
return tmp, dst
|
||||
|
||||
cases = [
|
||||
("pin outside the board range",
|
||||
"Projeto.ino",
|
||||
lambda t: t.replace("pinMode(5, OUTPUT)", "pinMode(23, OUTPUT)")),
|
||||
("analogWrite on a non-PWM pin",
|
||||
"Projeto.ino",
|
||||
lambda t: t.replace("analogWrite(5, redValue)",
|
||||
"analogWrite(4, redValue)")),
|
||||
("ESP8266 Dn pin name in an AVR sketch",
|
||||
"Projeto.ino",
|
||||
lambda t: t.replace("pinMode(6, OUTPUT)", "pinMode(D6, OUTPUT)")),
|
||||
]
|
||||
|
||||
for name, rel, mutate in cases:
|
||||
tmp, dst = copy()
|
||||
try:
|
||||
p = os.path.join(dst, rel)
|
||||
text = read(p)
|
||||
new = mutate(text)
|
||||
if new == text:
|
||||
print(" FAIL selftest could not mutate %s (%s)" % (rel, name))
|
||||
failures.append(name)
|
||||
continue
|
||||
with open(p, "w", encoding="utf-8") as fh:
|
||||
fh.write(new)
|
||||
if check(dst):
|
||||
print(" PASS negative case detected: %s" % name)
|
||||
else:
|
||||
print(" FAIL negative case NOT detected: %s" % name)
|
||||
failures.append(name)
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
tmp, dst = copy()
|
||||
try:
|
||||
if check(dst):
|
||||
print(" FAIL control copy is not clean: %s" % "; ".join(check(dst)))
|
||||
failures.append("control")
|
||||
else:
|
||||
print(" PASS control copy is clean")
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
return failures
|
||||
|
||||
|
||||
def main():
|
||||
if "--selftest" in sys.argv:
|
||||
print("check_pins.py --selftest")
|
||||
failures = run_selftest()
|
||||
if failures:
|
||||
print("SELFTEST FAILED: %s" % ", ".join(failures))
|
||||
return 1
|
||||
print("SELFTEST OK")
|
||||
return 0
|
||||
|
||||
errors = check(REPO)
|
||||
for err in errors:
|
||||
print(" FAIL %s" % err)
|
||||
if errors:
|
||||
return 1
|
||||
print(" PASS all pins used are valid and PWM-capable where required")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,196 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline checks: no credential leaks and a complete secrets.h.example.
|
||||
|
||||
Failure conditions (each one makes this script exit non-zero):
|
||||
1. Fetch_rain/secrets.h is tracked by git.
|
||||
2. Fetch_rain/secrets.h is not covered by .gitignore.
|
||||
3. Fetch_rain/secrets.h.example is missing, or does not define every
|
||||
WIFI_*/THINGHTTP_KEY_* symbol that Fetch_rain.ino references.
|
||||
4. Fetch_rain/secrets.h.example holds anything that does not look like a
|
||||
placeholder.
|
||||
5. Any git-tracked file holds a literal value for a credential-looking key
|
||||
(api_key / password / passwd / pwd / ssid / secret / token), quoted or
|
||||
not. A value that is a SCREAMING_SNAKE_CASE identifier is treated as a
|
||||
reference to a symbol, not as a literal.
|
||||
|
||||
Run with --selftest to prove those checks actually bite: the checker is re-run
|
||||
against deliberately broken copies and MUST fail on each one.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
SKETCH = os.path.join("Fetch_rain", "Fetch_rain.ino")
|
||||
EXAMPLE = os.path.join("Fetch_rain", "secrets.h.example")
|
||||
SECRETS = os.path.join("Fetch_rain", "secrets.h")
|
||||
|
||||
SYMBOL_RE = re.compile(r"\b((?:WIFI|THINGHTTP_KEY)_[A-Z0-9_]+)\b")
|
||||
KEY = r"(api[_-]?key|password|passwd|pwd|ssid|secret|token)"
|
||||
QUOTED_RE = re.compile(KEY + r"""\s*[=:]\s*["']([^"'\n]{6,})["']""", re.I)
|
||||
BARE_RE = re.compile(KEY + r"\s*[=:]\s*([A-Za-z0-9_\-\.]{8,})", re.I)
|
||||
SYMBOL_VALUE_RE = re.compile(r"^[A-Z0-9_]+$")
|
||||
PLACEHOLDER_HINTS = ("your-", "your_", "example", "changeme", "change-me",
|
||||
"xxx", "todo", "placeholder", "<", "$", "{}")
|
||||
SKIP_SUFFIX = (".jpg", ".jpeg", ".png", ".pdf", ".gif", ".ico", ".zip")
|
||||
|
||||
|
||||
def read(root, rel):
|
||||
with open(os.path.join(root, rel), encoding="utf-8") as fh:
|
||||
return fh.read()
|
||||
|
||||
|
||||
def git(root, *args):
|
||||
return subprocess.run(["git", "-C", root, *args], capture_output=True,
|
||||
text=True)
|
||||
|
||||
|
||||
def is_real(value):
|
||||
"""True if `value` is a literal that must not be in a tracked file."""
|
||||
if "(" in value or ")" in value or "+" in value or " " in value:
|
||||
return False
|
||||
if SYMBOL_VALUE_RE.match(value):
|
||||
return False
|
||||
return not any(h in value.lower() for h in PLACEHOLDER_HINTS)
|
||||
|
||||
|
||||
def check(root):
|
||||
errors = []
|
||||
tracked = [p for p in git(root, "ls-files").stdout.splitlines() if p]
|
||||
if not tracked:
|
||||
return ["%s is not a git checkout with tracked files" % root]
|
||||
|
||||
if SECRETS in tracked:
|
||||
errors.append("SECURITY: %s is tracked by git" % SECRETS)
|
||||
if git(root, "check-ignore", "-q", SECRETS).returncode != 0:
|
||||
errors.append("SECURITY: %s is not matched by .gitignore" % SECRETS)
|
||||
|
||||
if not os.path.isfile(os.path.join(root, EXAMPLE)):
|
||||
errors.append("%s is missing" % EXAMPLE)
|
||||
example_text = ""
|
||||
else:
|
||||
example_text = read(root, EXAMPLE)
|
||||
|
||||
used = set(SYMBOL_RE.findall(read(root, SKETCH)))
|
||||
defined = set(re.findall(r"^\s*(?:const\s+char\s*\*\s*)?([A-Z0-9_]+)\s*=",
|
||||
example_text, re.MULTILINE))
|
||||
missing = sorted(used - defined)
|
||||
if missing:
|
||||
errors.append("%s does not define %s (used by %s)"
|
||||
% (EXAMPLE, ", ".join(missing), SKETCH))
|
||||
|
||||
for name, value in re.findall(r"\b([A-Z0-9_]+)\s*=\s*\"([^\"]*)\"",
|
||||
example_text):
|
||||
if not any(h in value.lower() for h in PLACEHOLDER_HINTS):
|
||||
errors.append("%s looks like a real value, not a placeholder: "
|
||||
"%s = \"%s\"" % (EXAMPLE, name, value))
|
||||
|
||||
for rel in tracked:
|
||||
if rel.endswith(SKIP_SUFFIX) or rel == EXAMPLE:
|
||||
continue
|
||||
try:
|
||||
text = read(root, rel)
|
||||
except (UnicodeDecodeError, IsADirectoryError):
|
||||
continue
|
||||
for lineno, line in enumerate(text.splitlines(), 1):
|
||||
for regex in (QUOTED_RE, BARE_RE):
|
||||
for key, value in regex.findall(line):
|
||||
if is_real(value):
|
||||
errors.append("SECURITY: literal %s in %s:%d (%s)"
|
||||
% (key.lower(), rel, lineno, value))
|
||||
return errors
|
||||
|
||||
|
||||
def run_selftest():
|
||||
failures = []
|
||||
# The literal is assembled at run time so that this file itself does not
|
||||
# contain the pattern the checker looks for.
|
||||
fake_key = "Th1ngsP34k" + "RealKey" + "0001"
|
||||
|
||||
def temp_copy():
|
||||
tmp = tempfile.mkdtemp(prefix="sumbrella-selftest-")
|
||||
dst = os.path.join(tmp, "repo")
|
||||
shutil.copytree(REPO, dst, symlinks=True)
|
||||
return tmp, dst
|
||||
|
||||
def drop_symbol(dst):
|
||||
p = os.path.join(dst, EXAMPLE)
|
||||
lines = [l for l in open(p, encoding="utf-8")
|
||||
if not l.startswith("const char* THINGHTTP_KEY_TMRW")]
|
||||
open(p, "w", encoding="utf-8").writelines(lines)
|
||||
shutil.copyfile(p, os.path.join(dst, SECRETS))
|
||||
|
||||
def drop_gitignore_rule(dst):
|
||||
p = os.path.join(dst, ".gitignore")
|
||||
lines = [l for l in open(p, encoding="utf-8")
|
||||
if l.strip() != "secrets.h"]
|
||||
open(p, "w", encoding="utf-8").writelines(lines)
|
||||
|
||||
def inject_literal(dst):
|
||||
with open(os.path.join(dst, "README.md"), "a", encoding="utf-8") as fh:
|
||||
fh.write("\n<!-- api_key=" + fake_key + " -->\n")
|
||||
|
||||
def remove_example(dst):
|
||||
os.remove(os.path.join(dst, EXAMPLE))
|
||||
|
||||
cases = [
|
||||
("secrets.h.example loses one symbol", drop_symbol),
|
||||
(".gitignore loses the secrets.h rule", drop_gitignore_rule),
|
||||
("a tracked file gains a literal api_key", inject_literal),
|
||||
("secrets.h.example is deleted", remove_example),
|
||||
]
|
||||
|
||||
for name, mutate in cases:
|
||||
tmp, dst = temp_copy()
|
||||
try:
|
||||
mutate(dst)
|
||||
if check(dst):
|
||||
print(" PASS negative case detected: %s" % name)
|
||||
else:
|
||||
print(" FAIL negative case NOT detected: %s" % name)
|
||||
failures.append(name)
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
# Control: the untouched copy must be clean, otherwise the negative cases
|
||||
# above prove nothing.
|
||||
tmp, dst = temp_copy()
|
||||
try:
|
||||
errs = check(dst)
|
||||
if errs:
|
||||
print(" FAIL control copy is not clean: %s" % "; ".join(errs))
|
||||
failures.append("control")
|
||||
else:
|
||||
print(" PASS control copy is clean")
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
return failures
|
||||
|
||||
|
||||
def main():
|
||||
if "--selftest" in sys.argv:
|
||||
print("check_secrets.py --selftest")
|
||||
failures = run_selftest()
|
||||
if failures:
|
||||
print("SELFTEST FAILED: %s" % ", ".join(failures))
|
||||
return 1
|
||||
print("SELFTEST OK")
|
||||
return 0
|
||||
|
||||
errors = check(REPO)
|
||||
for err in errors:
|
||||
print(" FAIL %s" % err)
|
||||
if errors:
|
||||
return 1
|
||||
print(" PASS secrets.h untracked and ignored; secrets.h.example defines "
|
||||
"every symbol the sketch uses and holds no real value; no tracked "
|
||||
"file holds a literal credential")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+74
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env bash
|
||||
# Offline test suite for sumbrella. Exit status != 0 if anything fails.
|
||||
# Nothing here needs a board: it is a real compile for both targets plus
|
||||
# static analysis of the sources. See README.md, section "Tests".
|
||||
#
|
||||
# The static analysis runs first on purpose: `pio check` triggers a clean build
|
||||
# and removes firmware.bin/firmware.elf/firmware.hex, so the real compiles come
|
||||
# last and leave the linked binaries in place.
|
||||
set -uo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
PIO="${PIO:-}"
|
||||
if [ -z "$PIO" ]; then
|
||||
for c in "$(command -v pio || true)" "$HOME/.venvs/platformio/bin/pio"; do
|
||||
[ -n "$c" ] && [ -x "$c" ] && PIO="$c" && break
|
||||
done
|
||||
fi
|
||||
|
||||
if [ ! -f Fetch_rain/secrets.h ]; then
|
||||
cp Fetch_rain/secrets.h.example Fetch_rain/secrets.h
|
||||
fi
|
||||
|
||||
rc=0
|
||||
run() {
|
||||
local name="$1"; shift
|
||||
echo "== $name"
|
||||
if "$@"; then
|
||||
echo " -> PASS"
|
||||
else
|
||||
echo " -> FAIL"
|
||||
rc=1
|
||||
fi
|
||||
echo
|
||||
}
|
||||
|
||||
build() {
|
||||
local name="$1" dir="$2" artefact="$3"
|
||||
echo "== $name"
|
||||
if "$PIO" run ${dir:+-d "$dir"}; then
|
||||
if [ -f "$artefact" ]; then
|
||||
echo " artefact: $artefact ($(stat -c%s "$artefact") bytes)"
|
||||
else
|
||||
echo " artefact missing: $artefact"
|
||||
rc=1
|
||||
fi
|
||||
echo " -> PASS"
|
||||
else
|
||||
echo " -> FAIL"
|
||||
rc=1
|
||||
fi
|
||||
echo
|
||||
}
|
||||
|
||||
if [ -n "$PIO" ]; then
|
||||
run "pio check, ESP8266 ESP-01" "$PIO" check -d Fetch_rain --skip-packages
|
||||
run "pio check, Arduino Nano" "$PIO" check --skip-packages
|
||||
build "compile ESP8266 ESP-01 (Fetch_rain.ino)" "Fetch_rain" \
|
||||
"Fetch_rain/.pio/build/esp8266/firmware.bin"
|
||||
build "compile Arduino Nano (Projeto.ino)" "" \
|
||||
".pio/build/nano/firmware.hex"
|
||||
else
|
||||
echo "== compile + static analysis: SKIPPED (no pio on PATH or in ~/.venvs/platformio)"
|
||||
echo
|
||||
rc=1
|
||||
fi
|
||||
|
||||
run "secrets hygiene" python3 tests/check_secrets.py
|
||||
run "secrets negative tests" python3 tests/check_secrets.py --selftest
|
||||
run "pin validity" python3 tests/check_pins.py
|
||||
run "pin negative tests" python3 tests/check_pins.py --selftest
|
||||
|
||||
echo "== overall"
|
||||
if [ "$rc" -eq 0 ]; then echo "ALL TESTS PASSED"; else echo "TESTS FAILED"; fi
|
||||
exit "$rc"
|
||||
Reference in New Issue
Block a user