Compare commits

...

72 Commits

Author SHA1 Message Date
Stefan b98f159811
New readme 2022-12-18 18:34:45 +01:00
Temm 02d5ad0d2a
Fix setChannel range check (#1495) 2022-04-18 12:24:46 +02:00
azzar 7d6f22c4e6
Update DisplayUI.cpp (#1540)
replace wrong comments
2022-04-18 12:23:52 +02:00
Stefan Kremser da75a4f954
Update FUNDING.yml 2022-04-09 22:25:32 +02:00
Stefan Kremser a1f467ed6e
Update stale.yml 2021-12-12 21:00:03 +01:00
Devin Norgarb bbe1b24e30
Update README.md (#1420)
small grammatical + spelling  typo Readme
2021-08-21 13:46:31 +02:00
Erdinc 8dd2a58ba2
version updated to 2.6.1 on web interface (#1468) 2021-08-21 13:46:01 +02:00
Spacehuhn 7f7d215305 Update compile script 2021-08-07 16:09:08 +02:00
Spacehuhn 684e47f7d5 Added Hackheld Vega bin 2021-08-07 16:08:56 +02:00
Spacehuhn f984e897a0 Upped version to 2.6.1 2021-08-07 15:24:55 +02:00
Spacehuhn 7a574188c7 Made Neopixel run on 800 Khz 2021-08-07 15:12:44 +02:00
Spacehuhn 1ed2f127fd Added Hackheld Vega config 2021-08-07 15:12:38 +02:00
Spacehuhn 397ec9fc70 Change beacon interval to 100ms 2021-08-07 15:12:27 +02:00
Spacehuhn f3432d20fb Change beacon interval to 100ms 2021-02-17 18:16:42 +01:00
Spacehuhn 27b921e44f Removed redundant DEFAULT_SSID 2021-02-03 19:52:44 +01:00
Spacehuhn bbafd9fdf2 Fixed msg not defined error 2021-02-01 21:50:24 +01:00
Spacehuhn 60be948cc0 Web interface "loading..." banner 2021-01-31 13:09:56 +01:00
Spacehuhn 8b99fcbb33 Compiled web files 2021-01-29 17:50:50 +01:00
Spacehuhn 84f2f83f13 Info on clicking WiFi Off
Informs the user that they can reconnect after restarting
2021-01-29 17:49:13 +01:00
Ignatius Tremor fe06b87dc1
Fix for setting web AP channel (#1388)
* Deleted wifi channel set without effect

* When initializing wifi, use actual channel from settings instead of always using channel 1
2021-01-24 23:36:33 +01:00
Spacehuhn 535d2d3f95 Fixed 404 errors when using littlefs 2021-01-23 12:46:59 +01:00
Spacehuhn 4bd56ff755 Fixed clock going out of sync 2021-01-23 12:37:01 +01:00
Spacehuhn 8c289baf33 Fixed issue with LittleFS (webSpiffs) setup 2021-01-23 12:36:46 +01:00
Spacehuhn 4e7264bc4f Clock submenu 2021-01-23 12:05:33 +01:00
Spacehuhn 0272e83c3d Fixed clock update
https://github.com/SpacehuhnTech/esp8266_deauther/issues/1385

https://github.com/SpacehuhnTech/esp8266_deauther/issues/1384
2021-01-23 11:52:44 +01:00
Spacehuhn 333e3ebd86 Removed remnants of forcePackets setting
The setting was already removed in 2019 with the rewrite of  the settings module. In my tests, it didn't make the performance better, but added complexity and made the web interface unstable.
2021-01-17 11:19:08 +01:00
Spacehuhn abf56ca866 Fixed compiler script 2021-01-17 11:03:05 +01:00
Spacehuhn d06e5d35c8 Added pl.lang 2021-01-16 10:24:38 +01:00
Spacehuhn 33c999c334 Compiled web files 2021-01-14 22:18:31 +01:00
Spacehuhn e01e95bc08 Added ko.lang 2021-01-14 22:17:47 +01:00
Spacehuhn 33e0cd2250 Increased name length to 17 2021-01-14 21:57:05 +01:00
Spacehuhn 85b37e7bb1 Merged .uk lang 2021-01-14 16:03:08 +01:00
Spacehuhn 2f43126301 Improved web responsiveness
By only forcing a channel change when required by the attack
2021-01-13 11:57:42 +01:00
Stefan Kremser d4ba63789b
Update README.md 2021-01-12 18:32:19 +01:00
Spacehuhn 247f9ce336 Reintroduced led command 2021-01-12 14:11:26 +01:00
Spacehuhn 3e4e699e78 Fix channel hopping issue 2021-01-12 13:24:30 +01:00
Spacehuhn 1e93e65355 Fixed nightly workflow 2021-01-11 20:59:59 +01:00
Stefan Kremser 0d9f4388fb
Update README.md 2021-01-11 20:52:23 +01:00
Spacehuhn 371982c03b Compiled web files 2021-01-11 20:42:58 +01:00
Spacehuhn 8715dc5478 Updated README.md 2021-01-11 19:12:58 +01:00
Spacehuhn 10e3c82f59 Missing semicolon 2021-01-11 18:19:27 +01:00
Spacehuhn 6ffc5506a0 Added display examples to compiler script 2021-01-11 18:17:08 +01:00
Spacehuhn d01bd2bfc4 Updated copyright in code 2021-01-11 18:14:55 +01:00
Spacehuhn d95d7c7aa7 Visual improvements for web interface 2021-01-11 18:04:59 +01:00
Spacehuhn 077eee674b Update version number 2021-01-11 16:14:26 +01:00
Spacehuhn e0ed92ec38 Made web interface URL and IP customisable 2021-01-11 16:10:15 +01:00
Spacehuhn df03cac35f Adjusted LED brightness for example configs 2021-01-11 14:23:28 +01:00
Spacehuhn 4f89248e71 Display example configs 2021-01-11 12:24:45 +01:00
Spacehuhn aa577ebe11 Draw "Resetting..." on OLED 2021-01-11 11:58:20 +01:00
Spacehuhn 0c908c577c Draw "> Scanning..." at startup on OLED 2021-01-11 11:58:01 +01:00
Spacehuhn 85a7c12b97 Fixed Dotstar support 2021-01-11 11:15:22 +01:00
Spacehuhn 57e50ea65f Reset settings via button
Hold button (config defaults to gpio 0) for 5 seconds to reset settings
2021-01-10 23:22:29 +01:00
Spacehuhn a559457dd9 Maltronics Deauther config 2021-01-10 22:45:40 +01:00
Spacehuhn e238ae11c6 Included necessary libraries locally 2021-01-10 22:30:14 +01:00
Spacehuhn 51429b8c37 Removed config duplicates 2021-01-10 22:26:48 +01:00
Spacehuhn 57bd66c249 Compiled web files 2021-01-10 18:49:21 +01:00
Spacehuhn 5d5b385d7e Merge remote-tracking branch 'Kry9toN/v2' into v2.5 2021-01-10 18:27:49 +01:00
Spacehuhn 2641985940 Updated welcome message 2021-01-10 18:20:46 +01:00
Spacehuhn 6b4db8ff4a Merge branch 'v2' into v2.5 2021-01-10 18:16:18 +01:00
Kry9toN 3e160481ed
add indonesia language
- add in.lang
- regen code and archive from script utils
2020-11-02 15:21:23 +07:00
Stefan Kremser e3c706e9a4
Update config.yml 2020-10-26 11:54:56 +01:00
Phil Eichinger 2be65e7274
Update german translation (#1331)
* web_interface: de: Fix grammar

See also: https://www.duden.de/rechtschreibung/Display

* web_interface: de: Fix typo

See also: https://www.duden.de/rechtschreibung/Intervall

* web_interface: de: Fix structure of sentence

This was not a proper german sentence.

* web_interface: de: Fix capitalization

Versenden is used a noun

* web_interface: de: Fix typo

See also: https://www.duden.de/rechtschreibung/Datei

* web_interface: de: Fix typo

* web_interface: de: Fix capitalizition

* web_interface: de: Add translation
2020-10-26 00:35:09 +01:00
Stefan Kremser 8e3443502f
Merge pull request #1278 from victor-kayan/update-pt-br-lang
Update web interface pt-br language
2020-10-26 00:34:04 +01:00
Stefan Kremser 8991ef7b8e
Merge pull request #1324 from saskadaniel/v2
This is a lang file for Hungarian (hu) translated from the English lang file.
2020-10-26 00:25:43 +01:00
saskadaniel ec833526c9
Hungarian translation 2020-10-08 14:04:42 +02:00
Stefan Kremser ca12730069
Merge pull request #1322 from kawaiipantsu/webui-add-lang-da
Added lang file DA
2020-10-04 20:06:41 +02:00
David Bjørnsten-Lindhard 99ee3299f8 Added lang file DA 2020-10-04 19:13:00 +02:00
Stefan Kremser 063baaeeb9
Merge pull request #1320 from 13r1ckz/Add_NL_lang_file
Add nl lang file
2020-10-03 09:59:10 +02:00
13r1ckzi7rtx2080S 65cc59b7d1 add nl lang file 2020-10-02 23:23:42 +02:00
13r1ckzi7rtx2080S 4f4cb099e9 Add lang nl file 2020-10-02 23:18:43 +02:00
Stefan Kremser 1157233aef
Create FUNDING.yml 2020-07-29 19:57:42 +02:00
Victor Kayan d63248b99f Update web interface pt-br language 2020-07-22 17:34:40 -03:00
167 changed files with 20432 additions and 1497 deletions

2
.github/FUNDING.yml vendored
View File

@ -3,7 +3,7 @@
github: spacehuhntech
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
ko_fi: spacehuhn
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username

14
.github/config.yml vendored
View File

@ -1,12 +1,14 @@
# Configuration for welcome - https://github.com/behaviorbot/welcome
newIssueWelcomeComment: >
Thanks for opening your first issue here! 🎉<br>
Congrats on opening your first issue on this repository! 🎉<br>
This is a automated message to help you avoid common pitfalls when asking for help online.<br>
👉 Be sure to:<br>
1. 📖 Have a look at the [Wiki](https://github.com/spacehuhntech/esp8266_deauther/wiki) and [README](https://github.com/SpacehuhnTech/esp8266_deauther/blob/v2/README.md) for information<br>
2. 🔍 Search for similar [issues (open and closed)](https://github.com/SpacehuhnTech/esp8266_deauther/issues?q=is%3Aissue+)<br>
3. ✍️ Provide enough information to understand, recreate and help out with your problem<br>
4. Let us know if you find a solution and please share it with us<br>
5. 📕 Close the issue when your problem has been solved
* 🇬🇧 Communicate in English so everybody can understand you<br>
* 📖 Have a look at the [Wiki](https://github.com/spacehuhntech/esp8266_deauther/wiki) and [README](https://github.com/SpacehuhnTech/esp8266_deauther/blob/v2/README.md) for information<br>
* 🔍 Search for similar [issues (open and closed)](https://github.com/SpacehuhnTech/esp8266_deauther/issues?q=is%3Aissue+)<br>
* ✍️ Provide enough information to understand, recreate and help out with your problem<br>
* Let us know if you find a solution and please share it with us<br>
* 📕 Close the issue when your problem has been solved
newPRWelcomeComment:

2
.github/stale.yml vendored
View File

@ -1,5 +1,5 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 90
daysUntilStale: 180
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7
# Issues with these labels will never be considered stale

View File

@ -10,11 +10,12 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Build message title
run: echo ::set-env name=TITLE::Deauther V2.5 $(echo ${{ github.sha }} | cut -c -7)
id: notif
run: echo ::set-output name=TITLE::Deauther V2 $(echo ${{ github.sha }} | cut -c -7)
- name: Send message
run: |
curl -X POST https://api.github.com/repos/spacehuhntech/nightly-deauther/dispatches \
-H 'Accept: application/vnd.github.everest-preview+json' \
-u ${{ secrets.ACCESS_TOKEN }} \
--data '{"event_type": "${{ env.TITLE }}", "client_payload": {}}'
--data '{"event_type": "${{ steps.notif.outputs.TITLE }}", "client_payload": {}}'

View File

@ -2,7 +2,7 @@ Do not redistribute, advertise or sell this software as a "jammer"!!!
MIT License
Copyright (c) 2018 Stefan Kremser
Copyright (c) 2020 Spacehuhn Technologies
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

118
README.md
View File

@ -1,110 +1,38 @@
# ESP8266 Deauther 2.0
# ESP8266 Deauther
<p align="center"><img alt="PICTURE logo" src="https://raw.githubusercontent.com/wiki/spacehuhn/esp8266_deauther/img/deauther_logo.png" width="200"></p>
<img src='https://deauther.com/img/logo.png' alt='Deauther Logo' width='200' />
<p align="center">
🐦 <a href="https://twitter.com/spacehuhn">Twitter</a>
| 📺 <a href="https://www.youtube.com/channel/UCFmjA6dnjv-phqrFACyI8tw">YouTube</a>
| 🌍 <a href="https://spacehuhn.de">spacehuhn.de</a><br>
<br>
<b>Scan for WiFi devices, block selected connections, create dozens of networks and confuse WiFi scanners!<br><br>
Click <a href="https://github.com/spacehuhn/esp8266_deauther/wiki/Installation">here</a> for the installation tutorial.<br>
Click <a href="https://github.com/spacehuhn/esp8266_deauther/releases">here</a> for the .bin files.<br><br>
Support the development of this project by purchasing one of the <a href="https://github.com/spacehuhn/esp8266_deauther/wiki/Supported-Devices">official deauther boards</a>.<br/>
Or become a patron on <a href="https://patreon.com/spacehuhn" target="_blank">patreon.com/spacehuhn</a>.<br>
Also available: <a href="https://www.tindie.com/products/Spacehuhn/spacehuhn-stickers/">Stickers</a></b>!
</p>
**Scan for WiFi devices, block selected connections, create dozens of networks and confuse WiFi scanners.**
# [👉 Wiki](https://github.com/SpacehuhnTech/esp8266_deauther/wiki)
# [👉 Binaries](https://github.com/SpacehuhnTech/esp8266_deauther/releases)
# [👉 Development Boards](https://github.com/SpacehuhnTech/esp8266_deauther/wiki/Supported-Devices)
## New Documentation
## What is New
[Here is a quick video about what is new](https://youtu.be/6oRmm3xfp6U)
Version 2.0:
- Completly rewritten code base for better performance and later enhancements
- Custom Deauther SDK for easy compiling using Arduino
- New serial command line interface to control and debug the program
- New display UI with a lot of new functions
- Improved web interface with multi-language support
- Improved scanning for access points and stations (+ continuous scanning mode)
- Save and select device names for both scanning and attacking
- Save up to 60 SSIDs and 25 devices in one list (you can create, load and save multiple lists)
- Added [PacketMonitor](https://github.com/spacehuhn/PacketMonitor) to display UI
- Deauth detection when scanning
- RGB LED support for a quick indication what the device is doing (attacking, scanning, ...)
- Better documentation on the new [wiki](https://github.com/spacehuhn/esp8266_deauther/wiki)
Hi 👋
Please visit [Deauther.com](https://deauther.com) for information about this project.
Here are some quick links:
## About this project
This software allows you to easily perform a variety of actions to test 802.11 wireless networks by using an inexpensive ESP8266 WiFi SoC (System On A Chip).
* [Buy](https://deauther.com/docs/buy)
* [Download](https://deauther.com/docs/download)
* [DIY Tutorial](https://deauther.com/docs/category/diy-tutorial)
* [Usage](https://deauther.com/docs/category/usage)
* [FAQ](https://deauther.com/docs/faq)
The main feature, the deauthentication attack, is used to disconnect devices from their WiFi network.
No one seems to care about this huge vulnerability in the official 802.11 WiFi standard, so I took action and enabled everyone who has less than 10 USD to spare to recreate this project.
I hope it raises more attention on the issue. In 2009 the WiFi Alliance actually fixed the problem (see [802.11w](https://en.wikipedia.org/wiki/IEEE_802.11w-2009)), but only a few companies implemented it into their devices and software.
To effectively prevent a deauthentication attack, both client and access point must support the 802.11w standard with protected management frames (PMF).
While most client devices seem to support it when the access point forces it, basically no WiFi access point has it enabled.
## Password
Feel free to test your hardware out, annoy these companies with the problem, share this project and push for a fix!
This project is also a great way to learn more about WiFi, micro controllers, Arduino, hacking and electronics/programming in general.
**But please use this tool responsibly and do not use it against others without their permission!**
The password for `pwned` is `deauther`
The difference between deauthing and jamming: [click me](https://github.com/spacehuhn/esp8266_deauther/wiki/FAQ#difference-between-jammer-and-deauther)
## About this Project
## Official Deauther Boards
This firmware allows you to easily perform a variety of actions to test 802.11 networks using an [ESP8266](https://www.espressif.com/en/products/socs/esp8266). It's also a great project for learning about WiFi, microcontrollers, Arduino, hacking and electronics/programming in general.
![PICTURE DSTIKE Deauther OLED Board](https://raw.githubusercontent.com/wiki/spacehuhn/esp8266_deauther/img/DSTIKE_Deauther_Board.jpg)
If you want to support the development of this project, you can buy one of the official boards by DSTIKE (Travis Lin) on following sites:
- [Tindie](https://tindie.com/stores/lspoplove)
- [AliExpress](https://dstike.aliexpress.com/store/2996024)
- [Taobao](https://shop135375846.taobao.com)
Those boards are optimized for this project, ready to use and come preflashed with the Deauther software!
For more details visit the [Wiki](https://github.com/spacehuhn/esp8266_deauther/wiki) under [Supported Devices](https://github.com/spacehuhn/esp8266_deauther/wiki/Supported-Devices).
The deauthentication attack is the main feature, which can be used to disconnect devices from their WiFi network.
Although this denial-of-service attack is nothing new, a lot of devices are still vulnerable to it. Luckily this is slowly changing with more WiFi 6 enabled devices being used. But a lot of outdated WiFi devices remain in place, for example in cheap IoT hardware.
With an ESP8266 Deauther, you can easily test this attack on your 2.4GHz WiFi network/devices and see whether it's successful or not. And if it is, you know you should upgrade your network.
## Disclaimer
This project is a proof of concept for testing and educational purposes.
Neither the ESP8266, nor its SDK was meant or built for such purposes. Bugs can occur!
Neither the ESP8266, nor its SDK was meant or built for such purposes. **Bugs can occur!**
Use it only against your own networks and devices!
**Use it only against your own networks and devices!**
Please check the legal regulations in your country before using it.
I don't take any responsibility for what you do with this program.
It is **not a frequency jammer** as claimed falsely by many people. Its attack, its method and how to protect against it is described above. It uses valid Wi-Fi frames described in the IEEE 802.11 standard and doesn't block or disrupt any frequencies.
This project is meant to draw more attention on this issue.
The [deauthentication](https://en.wikipedia.org/wiki/Wi-Fi_deauthentication_attack) attack shows how vulnerable the 802.11 Wi-Fi standard is and that it has to be fixed.
A solution is already there, why don't we use it?
**Please don't refer to this project as "jammer", that totally undermines the real purpose of this project!**
If you do, it only proves that you didn't understand anything of what this project stands for. Publishing content about this without a proper explanation shows that you only do it for the clicks, fame and/or money and have no respect for intellectual property, the community behind it and the fight for a better WiFi standard!
## Getting Started
Visit our new [Wiki](https://github.com/spacehuhn/esp8266_deauther/wiki) on how to recreate this project and use it.
Happy Hacking!
## Credits
A huge thanks to:
- [@deantonious](http://github.com/deantonious)
- [@jLynx](https://github.com/jLynx)
- [@lspoplove](https://github.com/lspoplove)
- [@schinfo](https://github.com/schinfo)
- [@tobozo](https://github.com/tobozo)
- [@xdavidhu](https://github.com/xdavidhu)
- [@PwnKitteh](https://github.com/PwnKitteh)
for helping out with various things regarding this project and keeping it alive!
I also want to thank Espressif and their community for this awesome chip and all the software and hardware projects around it and the countless tutorials you can find online!
Shoutout to everyone working on the libraries used for this project:
- [esp8266-oled-ssd1306](https://github.com/ThingPulse/esp8266-oled-ssd1306)
- [ArduinoJson](https://github.com/bblanchon/ArduinoJson)
- [LinkedList](https://github.com/ivanseidel/LinkedList)
Also thanks to everyone that supports this project by [donating](http://spacehuhn.de/donate), being my [patron](http://patreon.com/spacehuhn) or buying one of the [official Deauther boards](https://www.tindie.com/stores/lspoplove) from DSTIKE.
## License
This software is licensed under the MIT License. See the [license file](LICENSE) for details.
We don't take any responsibility for what you do with this program.

View File

@ -1,5 +1,6 @@
#ifndef config_h
#define config_h
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#pragma once
#define ENABLE_DEBUG
#define DEBUG_PORT Serial
@ -7,13 +8,13 @@
#define DEFAULT_ESP8266
/* ---------------------------------------------------------- */
/* ===>> !!! Uncomment the board that you're using: !!! <<=== */
/* ---------------------------------------------------------- */
// #define NODEMCU
// #define WEMOS_D1_MINI
// #define DSTIKE_DEAUTHER
// #define HACKHELD_VEGA
// #define DISPLAY_EXAMPLE_I2C
// #define DISPLAY_EXAMPLE_SPI
// #define MALTRONICS
// #define DSTIKE_DEAUTHER_V1
// #define DSTIKE_DEAUTHER_V2
// #define DSTIKE_DEAUTHER_V3
@ -39,11 +40,11 @@
// #define DSTIKE_DEAUTHER_MOSTER_V5
// #define DSTIKE_USB_DEAUTHER
// #define DSTIKE_USB_DEAUTHER_V2
// #define DSTIKE_DEAUTHER_WRISTBAND
// #define DSTIKE_DEAUTHER_WATCH
// #define DSTIKE_DEAUTHER_WATCH_V2
// #define DSTIKE_DEAUTHER_MINI
// #define DSTIKE_DEAUTHER_MINI_EVO
// #define LYASI_7W_E27_LAMP
// #define AVATAR_5W_E14_LAMP
@ -55,11 +56,110 @@
// #define RESET_SETTINGS
// ========== CONFIGS ========== //
#if defined(DSTIKE_D_DUINO_B_V5_LED_RING)
// https://github.com/spacehuhntech/hackheld
#if defined(HACKHELD_VEGA)
// ===== LED ===== //
#define USE_LED true
#define LED_NEOPIXEL
#define LED_NEOPIXEL_GRB
// #define LED_NEOPIXEL_RGB
#define LED_MODE_BRIGHTNESS 10
#define LED_NUM 1
#define LED_NEOPIXEL_PIN 15 // D8
// ===== DISPLAY ===== //
#define USE_DISPLAY true
#define FLIP_DIPLAY true
#define SH1106_I2C
#define I2C_ADDR 0x3C
#define I2C_SDA 4 // D2
#define I2C_SCL 5 // D1
// ===== BUTTONS ===== //
#define BUTTON_UP 14 // D5
#define BUTTON_DOWN 12 // D6
#define BUTTON_A 2 // D4
#define BUTTON_B 0 // D3
// https://github.com/SpacehuhnTech/esp8266_deauther/wiki/Setup-Display-&-Buttons#example-setup-with-i2c-oled
#elif defined(DISPLAY_EXAMPLE_I2C)
// ===== DISPLAY ===== //
#define SH1106_I2C
// #define SSD1306_I2C
#define I2C_ADDR 0x3C
#define I2C_SDA 5
#define I2C_SCL 4
// #define FLIP_DIPLAY true
// ===== BUTTONS ===== //
#define BUTTON_UP 14
#define BUTTON_DOWN 12
#define BUTTON_A 13
// ===== LED ===== //
#define LED_NEOPIXEL_GRB
#define LED_NEOPIXEL_NUM 12
// #define LED_NEOPIXEL_RGB
#define LED_NUM 1
#define LED_NEOPIXEL_PIN 9
#define LED_MODE_BRIGHTNESS 10
// https://github.com/SpacehuhnTech/esp8266_deauther/wiki/Setup-Display-&-Buttons#example-setup-with-spi-oled
#elif defined(DISPLAY_EXAMPLE_SPI)
#define SH1106_SPI
// #define SSD1306_SPI
#define SPI_RES 5
#define SPI_DC 4
#define SPI_CS 15
// #define FLIP_DIPLAY true
// ===== BUTTONS ===== //
#define BUTTON_UP 0
#define BUTTON_DOWN 12
#define BUTTON_A 2
// ===== LED ===== //
#define LED_NEOPIXEL_GRB
// #define LED_NEOPIXEL_RGB
#define LED_NUM 1
#define LED_NEOPIXEL_PIN 9
#define LED_MODE_BRIGHTNESS 10
#elif defined(MALTRONICS)
// ===== Reset ====== //
#define RESET_BUTTON 5
// ===== LED ===== //
#define LED_DOTSTAR
#define LED_NUM 1
#define LED_DOTSTAR_CLK 12
#define LED_DOTSTAR_DATA 13
#define LED_MODE_BRIGHTNESS 255
// ===== Web ===== //
#define WEB_IP_ADDR (192, 168, 4, 2)
#define WEB_URL "deauther.tools"
#elif defined(DSTIKE_D_DUINO_B_V5_LED_RING)
// ===== LED ===== //
#define LED_NEOPIXEL_GRB
#define LED_NUM 12
#define LED_NEOPIXEL_PIN 15
// ===== DISPLAY ===== //
@ -76,7 +176,7 @@
// ===== LED ===== //
#define LED_NEOPIXEL_GRB
#define LED_NEOPIXEL_NUM 1
#define LED_NUM 1
#define LED_NEOPIXEL_PIN 15
// ===== DISPLAY ===== //
@ -94,14 +194,14 @@
// ===== LED ===== //
#define LED_NEOPIXEL_GRB
#define LED_NEOPIXEL_NUM 1
#define LED_NUM 1
#define LED_NEOPIXEL_PIN 15
#elif defined(DSTIKE_DEAUTHER_OLED_V1_5_S)
// ===== LED ===== //
#define LED_NEOPIXEL_GRB
#define LED_NEOPIXEL_NUM 1
#define LED_NUM 1
#define LED_NEOPIXEL_PIN 15
// ===== DISPLAY ===== //
@ -154,7 +254,7 @@
// ===== LED ===== //
#define LED_NEOPIXEL_GRB
#define LED_NEOPIXEL_NUM 1
#define LED_NUM 1
#define LED_NEOPIXEL_PIN 15
// ===== DISPLAY ===== //
@ -171,7 +271,7 @@
// ===== LED ===== //
#define LED_NEOPIXEL_GRB
#define LED_NEOPIXEL_NUM 1
#define LED_NUM 1
#define LED_NEOPIXEL_PIN 15
#define HIGHLIGHT_LED 16
@ -192,14 +292,14 @@
// ===== LED ===== //
#define LED_NEOPIXEL_GRB
#define LED_NEOPIXEL_NUM 1
#define LED_NUM 1
#define LED_NEOPIXEL_PIN 4
#elif defined(DSTIKE_DEAUTHER_WRISTBAND) || defined(DSTIKE_DEAUTHER_WATCH) || defined(DSTIKE_DEAUTHER_MINI)
#elif defined(DSTIKE_DEAUTHER_WATCH) || defined(DSTIKE_DEAUTHER_MINI)
// ===== LED ===== //
#define LED_NEOPIXEL_GRB
#define LED_NEOPIXEL_NUM 1
#define LED_NUM 1
#define LED_NEOPIXEL_PIN 15
#define HIGHLIGHT_LED 16
@ -218,7 +318,7 @@
// ===== LED ===== //
#define LED_NEOPIXEL_GRB
#define LED_NEOPIXEL_NUM 1
#define LED_NUM 1
#define LED_NEOPIXEL_PIN 15
#define HIGHLIGHT_LED 16
@ -246,7 +346,7 @@
#define LED_MODE_IDLE 0, 255, 0
#define LED_MODE_BRIGHTNESS 10
#define LED_MY92_NUM 1
#define LED_NUM 1
#define LED_MY92_DATA 4
#define LED_MY92_CLK 5
#define LED_MY92_CH_R 0
@ -266,7 +366,7 @@
#define LED_MODE_IDLE 0, 255, 0
#define LED_MODE_BRIGHTNESS 10
#define LED_MY92_NUM 1
#define LED_NUM 1
#define LED_MY92_DATA 13
#define LED_MY92_CLK 15
#define LED_MY92_CH_R 0
@ -275,11 +375,11 @@
#define LED_MY92_CH_BRIGHTNESS 3
#define LED_MY92_MODEL MY92XX_MODEL_MY9291
#elif defined(DEFAULT_ESP8266) || defined(NODEMCU) || defined(WEMOS_D1_MINI) || defined(DSTIKE_USB_DEAUTHER) || defined(DSTIKE_NODEMCU_07) || defined(DSTIKE_DEAUTHER) || defined(DSTIKE_DEAUTHER_V1) || defined(DSTIKE_DEAUTHER_V2) || defined(DSTIKE_DEAUTHER_V3)
#elif defined(DEFAULT_ESP8266) || defined(NODEMCU) || defined(WEMOS_D1_MINI) || defined(DSTIKE_USB_DEAUTHER) || defined(DSTIKE_NODEMCU_07) || defined(DSTIKE_DEAUTHER_V1) || defined(DSTIKE_DEAUTHER_V2) || defined(DSTIKE_DEAUTHER_V3)
// ===== LED ===== //
#define LED_DIGITAL
#define LED_PIN_R 16 // NodeMCU on-board LED
#define LED_PIN_B 2 // ESP-12 LED
// #define LED_DIGITAL
// #define LED_PIN_R 16 // NodeMCU on-board LED
// #define LED_PIN_B 2 // ESP-12 LED
#endif /* if defined(DEFAULT_ESP8266) || defined(NODEMCU) || defined(WEMOS_D1_MINI) || defined(DSTIKE_USB_DEAUTHER) || defined(DSTIKE_NODEMCU_07) || defined(DSTIKE_DEAUTHER) || defined(DSTIKE_DEAUTHER_V1) || defined(DSTIKE_DEAUTHER_V2) || defined(DSTIKE_DEAUTHER_V3) */
// ============================== //
@ -334,10 +434,6 @@
#define MIN_DEAUTH_FRAMES 3
#endif /* ifndef MIN_DEAUTH_FRAMES */
#ifndef DEFAULT_SSID
#define DEFAULT_SSID "pwned"
#endif /* ifndef DEFAULT_SSID */
// ===== ACCESS POINT ===== //
#ifndef AP_SSID
#define AP_SSID "pwned"
@ -386,12 +482,12 @@
#define LED_NEOPIXEL
#endif /* if defined(LED_NEOPIXEL_RGB) || defined(LED_NEOPIXEL_GRB) */
#if !defined(LED_DIGITAL) && !defined(LED_RGB) && !defined(LED_NEOPIXEL) && !defined(MY92)
#if !defined(LED_DIGITAL) && !defined(LED_RGB) && !defined(LED_NEOPIXEL) && !defined(LED_MY92) && !defined(LED_DOTSTAR)
#define LED_DIGITAL
#define USE_LED false
#else /* if !defined(LED_DIGITAL) && !defined(LED_RGB) && !defined(LED_NEOPIXEL) && !defined(MY92) */
#else // if !defined(LED_DIGITAL) && !defined(LED_RGB) && !defined(LED_NEOPIXEL) && !defined(LED_MY92) && !defined(LED_DOTSTAR)
#define USE_LED true
#endif /* if !defined(LED_DIGITAL) && !defined(LED_RGB) && !defined(LED_NEOPIXEL) && !defined(MY92) */
#endif // if !defined(LED_DIGITAL) && !defined(LED_RGB) && !defined(LED_NEOPIXEL) && !defined(LED_MY92) && !defined(LED_DOTSTAR)
#ifndef LED_PIN_R
#define LED_PIN_R 255
@ -491,12 +587,30 @@
#define BUTTON_B 255
#endif // ifndef BUTTON_B
// ===== Reset ====== //
#ifndef RESET_BUTTON
#if BUTTON_UP != 0 && BUTTON_DOWN != 0 && BUTTON_A != 0 && BUTTON_B != 0
#define RESET_BUTTON 0
#else // if BUTTON_UP != 0 && BUTTON_DOWN != 0 && BUTTON_A != 0 && BUTTON_B != 0
#define RESET_BUTTON 255
#endif // if BUTTON_UP != 0 && BUTTON_DOWN != 0 && BUTTON_A != 0 && BUTTON_B != 0
#endif // ifndef RESET_BUTTON
// ===== Web ===== //
#ifndef WEB_IP_ADDR
#define WEB_IP_ADDR (192, 168, 4, 1)
#endif // ifndef WEB_IP_ADDR
#ifndef WEB_URL
#define WEB_URL "deauth.me"
#endif // ifndef WEB_URL
// ======== CONSTANTS ========== //
// Do not change these values unless you know what you're doing!
#define DEAUTHER_VERSION "2.5.0"
#define DEAUTHER_VERSION "2.6.1"
#define DEAUTHER_VERSION_MAJOR 2
#define DEAUTHER_VERSION_MINOR 5
#define DEAUTHER_VERSION_REVISION 0
#define DEAUTHER_VERSION_MINOR 6
#define DEAUTHER_VERSION_REVISION 1
#define EEPROM_SIZE 4095
#define BOOT_COUNTER_ADDR 1
@ -551,7 +665,7 @@
#define LED_NEOPIXEL_RGB
#define LED_NEOPIXEL_GRB
#define LED_NEOPIXEL_NUM 1
#define LED_NUM 1
#define LED_NEOPIXEL_PIN 255
#define LED_MODE_OFF 0,0,0
@ -560,7 +674,7 @@
#define LED_MODE_IDLE 0,255,0
#define LED_MODE_BRIGHTNESS 10
#define LED_MY92_NUM 1
#define LED_NUM 1
#define LED_MY92_DATA 4
#define LED_MY92_CLK 5
#define LED_MY92_CH_R 0
@ -570,6 +684,11 @@
#define LED_MY92_MODEL MY92XX_MODEL_MY9291
#define LED_MY92_MODEL MY92XX_MODEL_MY9231
#define LED_DOTSTAR
#define LED_NUM 1
#define LED_DOTSTAR_CLK 12
#define LED_DOTSTAR_DATA 13
// ===== DISPLAY ===== //
#define USE_DISPLAY false
#define DISPLAY_TIMEOUT 600
@ -594,11 +713,18 @@
#define BUTTON_A 255
#define BUTTON_B 255
// ===== Reset ====== //
#define RESET_BUTTON 5
// ===== Web ===== //
#define WEB_IP_ADDR (192, 168, 4, 1)
#define WEB_URL "deauth.me"
*/
// ========== ERROR CHECKS ========== //
#if LED_MODE_BRIGHTNESS == 0
#error LED_MODE_BRIGHTNESS must not be zero!
#endif /* if LED_MODE_BRIGHTNESS == 0 */
#endif /* ifndef config_h */
#endif /* if LED_MODE_BRIGHTNESS == 0 */

View File

@ -1,3 +1,5 @@
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#include "Accesspoints.h"
Accesspoints::Accesspoints() {
@ -170,6 +172,7 @@ String Accesspoints::getMacStr(int num) {
if (!check(num)) return String();
uint8_t* mac = getMac(num);
return bytesToStr(mac, 6);
}

View File

@ -1,5 +1,6 @@
#ifndef Accesspoints_h
#define Accesspoints_h
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#pragma once
#include "Arduino.h"
#include <ESP8266WiFi.h>
@ -76,6 +77,4 @@ class Accesspoints {
void internal_select(int num);
void internal_deselect(int num);
void internal_remove(int num);
};
#endif // ifndef Accesspoints_h
};

View File

@ -1,3 +1,5 @@
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#include "Attack.h"
#include "settings.h"
@ -67,6 +69,9 @@ void Attack::stop() {
deauth.tc = 0;
beacon.tc = 0;
probe.tc = 0;
deauth.active = false;
beacon.active = false;
probe.active = false;
prntln(A_STOP);
}
}
@ -242,7 +247,7 @@ void Attack::deauthAllUpdate() {
void Attack::probeUpdate() {
if (probe.active && (probe.maxPkts > 0) && (probe.packetCounter < probe.maxPkts)) {
if (probe.time <= currentTime - (1000 / probe.maxPkts)) {
if (settings::getAttackSettings().attack_all_ch) setWifiChannel(probe.tc % 11);
if (settings::getAttackSettings().attack_all_ch) setWifiChannel(probe.tc % 11, true);
probe.tc += sendProbe(probe.tc);
if (probe.tc >= ssids.count()) probe.tc = 0;
@ -285,11 +290,11 @@ bool Attack::deauthDevice(uint8_t* apMac, uint8_t* stMac, uint8_t reason, uint8_
// build deauth packet
packetSize = sizeof(deauthPacket);
uint8_t deauthpkt[packetSize];
memcpy(deauthpkt, deauthPacket, packetSize);
memcpy(&deauthpkt[4], stMac, 6);
memcpy(&deauthpkt[10], apMac, 6);
memcpy(&deauthpkt[16], apMac, 6);
@ -298,18 +303,19 @@ bool Attack::deauthDevice(uint8_t* apMac, uint8_t* stMac, uint8_t reason, uint8_
// send deauth frame
deauthpkt[0] = 0xc0;
if (sendPacket(deauthpkt, packetSize, ch, 1)) {
if (sendPacket(deauthpkt, packetSize, ch, true)) {
success = true;
deauth.packetCounter++;
}
// send disassociate frame
uint8_t disassocpkt[packetSize];
memcpy(disassocpkt, deauthpkt, packetSize);
disassocpkt[0] = 0xa0;
if (sendPacket(disassocpkt, packetSize, ch, 1)) {
if (sendPacket(disassocpkt, packetSize, ch, false)) {
success = true;
deauth.packetCounter++;
}
@ -324,7 +330,7 @@ bool Attack::deauthDevice(uint8_t* apMac, uint8_t* stMac, uint8_t reason, uint8_
// send deauth frame
disassocpkt[0] = 0xc0;
if (sendPacket(disassocpkt, packetSize, ch, 1)) {
if (sendPacket(disassocpkt, packetSize, ch, false)) {
success = true;
deauth.packetCounter++;
}
@ -332,7 +338,7 @@ bool Attack::deauthDevice(uint8_t* apMac, uint8_t* stMac, uint8_t reason, uint8_
// send disassociate frame
disassocpkt[0] = 0xa0;
if (sendPacket(disassocpkt, packetSize, ch, 1)) {
if (sendPacket(disassocpkt, packetSize, ch, false)) {
success = true;
deauth.packetCounter++;
}
@ -344,7 +350,7 @@ bool Attack::deauthDevice(uint8_t* apMac, uint8_t* stMac, uint8_t reason, uint8_
}
bool Attack::sendBeacon(uint8_t tc) {
if (settings::getAttackSettings().attack_all_ch) setWifiChannel(tc % 11);
if (settings::getAttackSettings().attack_all_ch) setWifiChannel(tc % 11, true);
mac[5] = tc;
return sendBeacon(mac, ssids.getName(tc).c_str(), wifi_channel, ssids.getWPA2(tc));
}
@ -372,11 +378,12 @@ bool Attack::sendBeacon(uint8_t* mac, const char* ssid, uint8_t ch, bool wpa2) {
// =====
uint16_t tmpPacketSize = (packetSize - 32) + ssidLen; // calc size
uint8_t* tmpPacket = new uint8_t[tmpPacketSize]; // create packet buffer
memcpy(&tmpPacket[0], &beaconPacket[0], 38 + ssidLen); // copy first half of packet into buffer
tmpPacket[37] = ssidLen; // update SSID length byte
memcpy(&tmpPacket[38 + ssidLen], &beaconPacket[70], wpa2 ? 39 : 13); // copy second half of packet into buffer
bool success = sendPacket(tmpPacket, tmpPacketSize, ch, 1);
bool success = sendPacket(tmpPacket, tmpPacketSize, ch, false);
if (success) {
beacon.time = currentTime;
@ -390,7 +397,7 @@ bool Attack::sendBeacon(uint8_t* mac, const char* ssid, uint8_t ch, bool wpa2) {
}
bool Attack::sendProbe(uint8_t tc) {
if (settings::getAttackSettings().attack_all_ch) setWifiChannel(tc % 11);
if (settings::getAttackSettings().attack_all_ch) setWifiChannel(tc % 11, true);
mac[5] = tc;
return sendProbe(mac, ssids.getName(tc).c_str(), wifi_channel);
}
@ -404,7 +411,7 @@ bool Attack::sendProbe(uint8_t* mac, const char* ssid, uint8_t ch) {
memcpy(&probePacket[10], mac, 6);
memcpy(&probePacket[26], ssid, ssidLen);
if (sendPacket(probePacket, packetSize, ch, 1)) {
if (sendPacket(probePacket, packetSize, ch, false)) {
probe.time = currentTime;
probe.packetCounter++;
return true;
@ -413,19 +420,16 @@ bool Attack::sendProbe(uint8_t* mac, const char* ssid, uint8_t ch) {
return false;
}
bool Attack::sendPacket(uint8_t* packet, uint16_t packetSize, uint8_t ch, uint16_t tries) {
bool Attack::sendPacket(uint8_t* packet, uint16_t packetSize, uint8_t ch, bool force_ch) {
// Serial.println(bytesToStr(packet, packetSize));
// set channel
setWifiChannel(ch);
setWifiChannel(ch, force_ch);
// sent out packet
bool sent = wifi_send_pkt_freedom(packet, packetSize, 0) == 0;
// try again until it's sent out
for (int i = 0; i < tries && !sent; i++) sent = wifi_send_pkt_freedom(packet, packetSize, 0) == 0;
if (sent) tmpPacketRate++;
if (sent) ++tmpPacketRate;
return sent;
}

View File

@ -1,5 +1,6 @@
#ifndef Attack_h
#define Attack_h
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#pragma once
#include "Arduino.h"
#include <ESP8266WiFi.h>
@ -12,7 +13,7 @@ extern "C" {
#include "SSIDs.h"
#include "Scan.h"
extern SSIDs ssids;
extern SSIDs ssids;
extern Accesspoints accesspoints;
extern Stations stations;
extern Scan scan;
@ -26,7 +27,7 @@ extern void getRandomMac(uint8_t* mac);
extern void setOutputPower(float dBm);
extern String macToStr(const uint8_t* mac);
extern String bytesToStr(const uint8_t* b, uint32_t size);
extern void setWifiChannel(uint8_t ch);
extern void setWifiChannel(uint8_t ch, bool force);
extern bool writeFile(String path, String& buf);
extern int8_t free80211_send(uint8_t* buffer, uint16_t len);
@ -55,7 +56,7 @@ class Attack {
bool sendProbe(uint8_t tc);
bool sendProbe(uint8_t* mac, const char* ssid, uint8_t ch);
bool sendPacket(uint8_t* packet, uint16_t packetSize, uint8_t ch, uint16_t tries);
bool sendPacket(uint8_t* packet, uint16_t packetSize, uint8_t ch, bool force_ch);
bool isRunning();
@ -151,16 +152,16 @@ class Attack {
};
uint8_t beaconPacket[109] = {
/* 0 - 3 */ 0x80, 0x00, 0x00, 0x00, // Type/Subtype: managment beacon frame
/* 4 - 9 */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // Destination: broadcast
/* 10 - 15 */ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // Source
/* 16 - 21 */ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // Source
/* 0 - 3 */ 0x80, 0x00, 0x00, 0x00, // Type/Subtype: managment beacon frame
/* 4 - 9 */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // Destination: broadcast
/* 10 - 15 */ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // Source
/* 16 - 21 */ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // Source
// Fixed parameters
/* 22 - 23 */ 0x00, 0x00, // Fragment & sequence number (will be done by the SDK)
/* 24 - 31 */ 0x83, 0x51, 0xf7, 0x8f, 0x0f, 0x00, 0x00, 0x00, // Timestamp
/* 32 - 33 */ 0xe8, 0x03, // Interval: 0x64, 0x00 => every 100ms - 0xe8, 0x03 => every 1s
/* 34 - 35 */ 0x31, 0x00, // capabilities Tnformation
/* 22 - 23 */ 0x00, 0x00, // Fragment & sequence number (will be done by the SDK)
/* 24 - 31 */ 0x83, 0x51, 0xf7, 0x8f, 0x0f, 0x00, 0x00, 0x00, // Timestamp
/* 32 - 33 */ 0x64, 0x00, // Interval: 0x64, 0x00 => every 100ms - 0xe8, 0x03 => every 1s
/* 34 - 35 */ 0x31, 0x00, // capabilities Tnformation
// Tagged parameters
@ -195,11 +196,9 @@ class Attack {
/* 85 - 86 */ 0x01, 0x00,
/* 87 - 90 */ 0x00, 0x0f, 0xac, 0x02,
/* 91 - 92 */ 0x02, 0x00,
/* 93 - 100 */ 0x00, 0x0f, 0xac, 0x04, 0x00, 0x0f, 0xac, 0x04, /*Fix: changed 0x02(TKIP) to 0x04(CCMP) is default. WPA2 with TKIP not supported by many devices*/
/* 93 - 100 */ 0x00, 0x0f, 0xac, 0x04, 0x00, 0x0f, 0xac, 0x04, /*Fix: changed 0x02(TKIP) to 0x04(CCMP) is default. WPA2 with TKIP not supported by many devices*/
/* 101 - 102 */ 0x01, 0x00,
/* 103 - 106 */ 0x00, 0x0f, 0xac, 0x02,
/* 107 - 108 */ 0x00, 0x00
};
};
#endif // ifndef Attack_h
};

View File

@ -1,3 +1,5 @@
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#include "CLI.h"
#include <LittleFS.h>
@ -283,7 +285,6 @@ void CLI::runCommand(String input) {
prntln(CLI_HELP_SEND_PROBE);
prntln(CLI_HELP_LED_A);
prntln(CLI_HELP_LED_B);
prntln(CLI_HELP_LED_ENABLE);
prntln(CLI_HELP_DRAW);
prntln(CLI_HELP_SCREEN_ON);
prntln(CLI_HELP_SCREEN_MODE);
@ -1078,7 +1079,7 @@ void CLI::runCommand(String input) {
for (int i = 0; i < packetSize; i++) packet[i] = strtoul((packetStr.substring(i * 2,
i * 2 + 2)).c_str(), NULL, 16);
if (attack.sendPacket(packet, packetSize, wifi_channel, 10)) {
if (attack.sendPacket(packet, packetSize, wifi_channel, true)) {
prntln(CLI_CUSTOM_SENT);
counter++;
} else {
@ -1086,6 +1087,21 @@ void CLI::runCommand(String input) {
}
}
// ===== LED ===== //
// led <r> <g> <b> [<brightness>]
else if ((list->size() == 4) && eqlsCMD(0, CLI_LED)) {
led::setColor(list->get(1).toInt(), list->get(2).toInt(), list->get(3).toInt());
}
// led <#rrggbb> [<brightness>]
else if ((list->size() == 2) &&
eqlsCMD(0, CLI_LED) && (list->get(1).charAt(0) == HASHSIGN)) {
uint8_t c[3];
strToColor(list->get(1), c);
led::setColor(c[0], c[1], c[2]);
}
// ===== DELAY ===== //
else if ((list->size() == 2) && eqlsCMD(0, CLI_DELAY)) {
uint32_t endTime = currentTime + getTime(list->get(1));
@ -1094,11 +1110,11 @@ void CLI::runCommand(String input) {
// ------- loop function ----- //
currentTime = millis();
wifi::update(); // manage access point
wifi::update(); // manage access point
scan.update(); // run scan
attack.update(); // run attacks
ssids.update(); // run random mode, if enabled
led::update(); // update LED color
led::update(); // update LED color
// auto-save
if (settings::getAutosaveSettings().enabled && (currentTime - autosaveTime > settings::getAutosaveSettings().time)) {
@ -1229,10 +1245,10 @@ void CLI::runCommand(String input) {
// ===== SCREEN ===== //
// screen mode <menu/packetmonitor/buttontest/loading>
else if (eqlsCMD(0, CLI_SCREEN) && eqlsCMD(1, CLI_MODE)) {
if (eqlsCMD(2, CLI_MODE_BUTTONTEST)) displayUI.mode = displayUI.DISPLAY_MODE::BUTTON_TEST;
else if (eqlsCMD(2, CLI_MODE_PACKETMONITOR)) displayUI.mode = displayUI.DISPLAY_MODE::PACKETMONITOR;
else if (eqlsCMD(2, CLI_MODE_LOADINGSCREEN)) displayUI.mode = displayUI.DISPLAY_MODE::LOADSCAN;
else if (eqlsCMD(2, CLI_MODE_MENU)) displayUI.mode = displayUI.DISPLAY_MODE::MENU;
if (eqlsCMD(2, CLI_MODE_BUTTONTEST)) displayUI.mode = DISPLAY_MODE::BUTTON_TEST;
else if (eqlsCMD(2, CLI_MODE_PACKETMONITOR)) displayUI.mode = DISPLAY_MODE::PACKETMONITOR;
else if (eqlsCMD(2, CLI_MODE_LOADINGSCREEN)) displayUI.mode = DISPLAY_MODE::LOADSCAN;
else if (eqlsCMD(2, CLI_MODE_MENU)) displayUI.mode = DISPLAY_MODE::MENU;
else parameterError(list->get(2));
prntln(CLI_CHANGED_SCREEN);
}

View File

@ -1,5 +1,6 @@
#ifndef CLI_h
#define CLI_h
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#pragma once
#include "Arduino.h"
#include <ESP8266WiFi.h>
@ -16,8 +17,8 @@ extern "C" {
#include "DisplayUI.h"
#include "led.h"
extern Names names;
extern SSIDs ssids;
extern Names names;
extern SSIDs ssids;
extern Accesspoints accesspoints;
extern Stations stations;
extern Scan scan;
@ -64,8 +65,8 @@ class CLI {
private:
bool enabled = false;
SimpleList<String>*list;
SimpleList<String>*queue;
SimpleList<String>* list;
SimpleList<String>* queue;
bool delayed = false;
uint32_t delayTime = 0;
@ -85,6 +86,4 @@ class CLI {
int toInt(String str);
uint32_t getTime(String time);
bool eqlsCMD(int i, const char* keyword);
};
#endif // ifndef CLI_h
};

View File

@ -1,3 +1,5 @@
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#include "DisplayUI.h"
#include "settings.h"
@ -69,10 +71,10 @@ void DisplayUI::setup() {
clock.setClockMode(false);
clockHour = clock.getHour(h12, PM_time);
clockMinute = clock.getMinute();
#else
#else // ifdef RTC_DS3231
clockHour = random(12);
clockMinute = random(60);
#endif
#endif // ifdef RTC_DS3231
// ===== MENUS ===== //
@ -85,15 +87,10 @@ void DisplayUI::setup() {
scan.start(SCAN_MODE_SNIFFER, 0, SCAN_MODE_OFF, 0, false, wifi_channel);
mode = DISPLAY_MODE::PACKETMONITOR;
});
addMenuNode(&mainMenu, D_CLOCK, [this]() { // PACKET MONITOR
mode = DISPLAY_MODE::CLOCK;
display.setFont(ArialMT_Plain_24);
display.setTextAlignment(TEXT_ALIGN_CENTER);
});
addMenuNode(&mainMenu, D_CLOCK, &clockMenu); // CLOCK
#ifdef HIGHLIGHT_LED
addMenuNode(&mainMenu, D_LED, [this]() { // LED
addMenuNode(&mainMenu, D_LED, [this]() { // LED
highlightLED = !highlightLED;
digitalWrite(HIGHLIGHT_LED, highlightLED);
});
@ -444,6 +441,20 @@ void DisplayUI::setup() {
});
});
// CLOCK MENU
createMenu(&clockMenu, &mainMenu, [this]() {
addMenuNode(&clockMenu, D_CLOCK_DISPLAY, [this]() { // CLOCK
mode = DISPLAY_MODE::CLOCK_DISPLAY;
display.setFont(ArialMT_Plain_24);
display.setTextAlignment(TEXT_ALIGN_CENTER);
});
addMenuNode(&clockMenu, D_CLOCK_SET, [this]() { // CLOCK SET TIME
mode = DISPLAY_MODE::CLOCK;
display.setFont(ArialMT_Plain_24);
display.setTextAlignment(TEXT_ALIGN_CENTER);
});
});
// ===================== //
// set current menu to main menu
@ -461,7 +472,7 @@ void DisplayUI::setupLED() {
#endif // ifdef HIGHLIGHT_LED
void DisplayUI::update() {
void DisplayUI::update(bool force) {
if (!enabled) return;
up->update();
@ -469,7 +480,7 @@ void DisplayUI::update() {
a->update();
b->update();
draw();
draw(force);
uint32_t timeout = settings::getDisplaySettings().timeout * 1000;
@ -521,7 +532,7 @@ void DisplayUI::setupButtons() {
else currentMenu->selected = currentMenu->list->size() - 1;
} else if (mode == DISPLAY_MODE::PACKETMONITOR) { // when in packet monitor, change channel
scan.setChannel(wifi_channel + 1);
} else if (mode == DISPLAY_MODE::CLOCK) { // when in packet monitor, change channel
} else if (mode == DISPLAY_MODE::CLOCK) { // when in clock, change time
setTime(clockHour, clockMinute + 1, clockSecond);
}
}
@ -537,7 +548,7 @@ void DisplayUI::setupButtons() {
else currentMenu->selected = currentMenu->list->size() - 1;
} else if (mode == DISPLAY_MODE::PACKETMONITOR) { // when in packet monitor, change channel
scan.setChannel(wifi_channel + 1);
} else if (mode == DISPLAY_MODE::CLOCK) { // when in packet monitor, change channel
} else if (mode == DISPLAY_MODE::CLOCK) { // when in clock, change time
setTime(clockHour, clockMinute + 10, clockSecond);
}
}
@ -554,7 +565,7 @@ void DisplayUI::setupButtons() {
else currentMenu->selected = 0;
} else if (mode == DISPLAY_MODE::PACKETMONITOR) { // when in packet monitor, change channel
scan.setChannel(wifi_channel - 1);
} else if (mode == DISPLAY_MODE::CLOCK) { // when in packet monitor, change channel
} else if (mode == DISPLAY_MODE::CLOCK) { // when in clock, change time
setTime(clockHour, clockMinute - 1, clockSecond);
}
}
@ -572,7 +583,7 @@ void DisplayUI::setupButtons() {
scan.setChannel(wifi_channel - 1);
}
else if (mode == DISPLAY_MODE::CLOCK) { // when in packet monitor, change channel
else if (mode == DISPLAY_MODE::CLOCK) { // when in clock, change time
setTime(clockHour, clockMinute - 10, clockSecond);
}
}
@ -599,6 +610,7 @@ void DisplayUI::setupButtons() {
break;
case DISPLAY_MODE::CLOCK:
case DISPLAY_MODE::CLOCK_DISPLAY:
mode = DISPLAY_MODE::MENU;
display.setFont(DejaVu_Sans_Mono_12);
display.setTextAlignment(TEXT_ALIGN_LEFT);
@ -654,18 +666,24 @@ String DisplayUI::getChannel() {
return ch;
}
void DisplayUI::draw() {
if ((currentTime - drawTime > drawInterval) && currentMenu) {
void DisplayUI::draw(bool force) {
if (force || ((currentTime - drawTime > drawInterval) && currentMenu)) {
drawTime = currentTime;
updatePrefix();
#ifndef RTC_DS3231
if (clockTime < currentTime - 1000) {
setTime(clockHour, clockMinute++, clockSecond + 1);
#ifdef RTC_DS3231
bool h12;
bool PM_time;
clockHour = clock.getHour(h12, PM_time);
clockMinute = clock.getMinute();
clockSecond = clock.getSecond();
#else // ifdef RTC_DS3231
if (currentTime - clockTime >= 1000) {
setTime(clockHour, clockMinute, ++clockSecond);
clockTime += 1000;
}
#endif
#endif // ifdef RTC_DS3231
switch (mode) {
case DISPLAY_MODE::BUTTON_TEST:
@ -685,14 +703,18 @@ void DisplayUI::draw() {
break;
case DISPLAY_MODE::INTRO:
if (currentTime - startTime >= screenIntroTime) {
if (!scan.isScanning() && (currentTime - startTime >= screenIntroTime)) {
mode = DISPLAY_MODE::MENU;
}
drawIntro();
break;
case DISPLAY_MODE::CLOCK:
case DISPLAY_MODE::CLOCK_DISPLAY:
drawClock();
break;
case DISPLAY_MODE::RESETTING:
drawResetting();
break;
}
updateSuffix();
@ -786,8 +808,13 @@ void DisplayUI::drawIntro() {
drawString(0, center(str(D_INTRO_0), maxLen));
drawString(1, center(str(D_INTRO_1), maxLen));
drawString(2, center(str(D_INTRO_2), maxLen));
drawString(3, center(str(D_INTRO_3), maxLen));
drawString(4, center(DEAUTHER_VERSION, maxLen));
drawString(3, center(DEAUTHER_VERSION, maxLen));
if (scan.isScanning()) {
if (currentTime - startTime >= screenIntroTime+4500) drawString(4, left(str(D_SCANNING_3), maxLen));
else if (currentTime - startTime >= screenIntroTime+3000) drawString(4, left(str(D_SCANNING_2), maxLen));
else if (currentTime - startTime >= screenIntroTime+1500) drawString(4, left(str(D_SCANNING_1), maxLen));
else if (currentTime - startTime >= screenIntroTime) drawString(4, left(str(D_SCANNING_0), maxLen));
}
}
void DisplayUI::drawClock() {
@ -800,6 +827,10 @@ void DisplayUI::drawClock() {
display.drawString(64, 20, clockTime);
}
void DisplayUI::drawResetting() {
drawString(2, center(str(D_RESETTING), maxLen));
}
void DisplayUI::clearMenu(Menu* menu) {
while (menu->list->size() > 0) {
menu->list->remove(0);
@ -906,5 +937,5 @@ void DisplayUI::setTime(int h, int m, int s) {
clock.setHour(clockHour);
clock.setMinute(clockMinute);
clock.setSecond(clockSecond);
#endif
#endif // ifdef RTC_DS3231
}

View File

@ -1,5 +1,6 @@
#ifndef DisplayUI_h
#define DisplayUI_h
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#pragma once
#include "language.h"
#include "A_config.h"
@ -11,29 +12,29 @@
// ===== adjustable ===== //
#if defined(SSD1306_I2C)
#include <Wire.h>
#include <SSD1306Wire.h>
#include "src/esp8266-oled-ssd1306-4.1.0/SSD1306Wire.h"
#elif defined(SSD1306_SPI)
#include <SPI.h>
#include <SSD1306Spi.h>
#include "src/esp8266-oled-ssd1306-4.1.0/SSD1306Spi.h"
#elif defined(SH1106_I2C)
#include <Wire.h>
#include <SH1106Wire.h>
#include "src/esp8266-oled-ssd1306-4.1.0/SH1106Wire.h"
#elif defined(SH1106_SPI)
#include <SPI.h>
#include <SH1106Spi.h>
#include "src/esp8266-oled-ssd1306-4.1.0/SH1106Spi.h"
#endif /* if defined(SSD1306_I2C) */
#ifdef RTC_DS3231
#include <DS3231.h>
#endif
#include "src/DS3231-1.0.3/DS3231.h"
#endif // ifdef RTC_DS3231
#include <SimpleButton.h>
#include "src/SimpleButton/SimpleButton.h"
using namespace simplebutton;
extern Names names;
extern SSIDs ssids;
extern Names names;
extern SSIDs ssids;
extern Accesspoints accesspoints;
extern Stations stations;
extern Scan scan;
@ -47,10 +48,14 @@ extern String right(String a, int len);
extern String leftRight(String a, String b, int len);
extern String replaceUtf8(String str, String r);
const char D_INTRO_0[] PROGMEM = "";
const char D_INTRO_1[] PROGMEM = "ESP8266 Deauther";
const char D_INTRO_2[] PROGMEM = "by @Spacehuhn";
const char D_INTRO_3[] PROGMEM = DISPLAY_TEXT;
const char D_INTRO_0[] PROGMEM = "ESP8266 Deauther";
const char D_INTRO_1[] PROGMEM = "by @Spacehuhn";
const char D_INTRO_2[] PROGMEM = DISPLAY_TEXT;
const char D_RESETTING[] PROGMEM = "Resetting...";
const char D_SCANNING_0[] PROGMEM = "> Scanning";
const char D_SCANNING_1[] PROGMEM = "> Scanning.";
const char D_SCANNING_2[] PROGMEM = "> Scanning..";
const char D_SCANNING_3[] PROGMEM = "> Scanning...";
struct MenuNode {
std::function<String()>getStr; // function used to create the displayed string
@ -59,18 +64,26 @@ struct MenuNode {
};
struct Menu {
SimpleList<MenuNode>*list;
Menu * parentMenu;
uint8_t selected;
SimpleList<MenuNode>* list;
Menu * parentMenu;
uint8_t selected;
std::function<void()> build; // function that is executed when button is clicked
};
enum class DISPLAY_MODE { OFF,
BUTTON_TEST,
MENU,
LOADSCAN,
PACKETMONITOR,
INTRO,
CLOCK,
CLOCK_DISPLAY,
RESETTING };
class DisplayUI {
public:
enum DISPLAY_MODE { OFF = 0, BUTTON_TEST = 1, MENU = 2, LOADSCAN = 3, PACKETMONITOR = 4, INTRO = 5, CLOCK = 6 };
uint8_t mode = DISPLAY_MODE::MENU;
bool highlightLED = false;
DISPLAY_MODE mode = DISPLAY_MODE::MENU;
bool highlightLED = false;
Button* up = NULL;
Button* down = NULL;
@ -88,10 +101,10 @@ class DisplayUI {
SH1106Spi display = SH1106Spi(SPI_RES, SPI_DC, SPI_CS);
#endif /* if defined(SSD1306_I2C) */
const uint8_t maxLen = 18;
const uint8_t lineHeight = 12;
const uint8_t buttonDelay = 250;
const uint8_t drawInterval = 100; // 100ms = 10 FPS
const uint8_t maxLen = 18;
const uint8_t lineHeight = 12;
const uint8_t buttonDelay = 250;
const uint8_t drawInterval = 100; // 100ms = 10 FPS
const uint16_t scrollSpeed = 500; // time interval in ms
const uint16_t screenIntroTime = 2500;
const uint16_t screenWidth = 128;
@ -115,7 +128,7 @@ class DisplayUI {
void setupLED();
#endif // ifdef HIGHLIGHT_LED
void update();
void update(bool force = false);
void on();
void off();
@ -144,6 +157,7 @@ class DisplayUI {
Menu scanMenu;
Menu showMenu;
Menu attackMenu;
Menu clockMenu;
Menu apListMenu;
Menu stationListMenu;
@ -160,12 +174,13 @@ class DisplayUI {
String getChannel();
// draw functions
void draw();
void draw(bool force = false);
void drawButtonTest();
void drawMenu();
void drawLoadingScan();
void drawPacketMonitor();
void drawIntro();
void drawResetting();
void clearMenu(Menu* menu);
// menu functions
@ -191,7 +206,7 @@ class DisplayUI {
#ifdef RTC_DS3231
DS3231 clock;
#endif
#endif // ifdef RTC_DS3231
};
// ===== FONT ===== //
@ -652,6 +667,4 @@ const uint8_t DejaVu_Sans_Mono_12[] PROGMEM = {
0x00, 0x00, 0x60, 0x40, 0x80, 0x67, 0x08, 0x1C, 0x84, 0x03, 0x60, // 253
0x00, 0x00, 0xFC, 0x7F, 0x20, 0x08, 0x20, 0x08, 0x20, 0x08, 0xC0, 0x07, // 254
0x00, 0x00, 0x60, 0x40, 0x88, 0x67, 0x00, 0x1C, 0x88, 0x03, 0x60 // 255
};
#endif // ifndef DisplayUI_h
};

View File

@ -1,5 +1,6 @@
#ifndef EEPROMHELPER_H
#define EEPROMHELPER_H
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#pragma once
// ========== Includes ========== //
#include <EEPROM.h>
@ -58,6 +59,4 @@ class EEPROMHelper {
for (unsigned long i = 0; i<size; i++) EEPROM.write(i, 0x00);
EEPROM.commit();
}
};
#endif /* ifndef EEPROMHELPER_H */
};

View File

@ -1,3 +1,5 @@
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#include "Names.h"
#include <LittleFS.h>
@ -258,6 +260,7 @@ void Names::setMac(int num, String macStr) {
if (!check(num)) return;
uint8_t mac[6];
strToMac(macStr, mac);
internal_add(mac, getName(num), getBssid(num), getCh(num), getSelected(num));
prntln(N_CHANGED_MAC);
@ -280,6 +283,7 @@ void Names::setBSSID(int num, String bssidStr) {
if (!check(num)) return;
uint8_t mac[6];
strToMac(bssidStr, mac);
internal_add(getMac(num), getName(num), mac, getCh(num), getSelected(num));
prntln(N_CHANGED_BSSID);
@ -362,6 +366,7 @@ String Names::getMacStr(int num) {
if (!check(num)) return String();
uint8_t* mac = getMac(num);
return bytesToStr(mac, 6);
}
@ -471,6 +476,7 @@ void Names::internal_add(uint8_t* mac, String name, uint8_t* bssid, uint8_t ch,
if ((ch < 1) || (ch > 14)) ch = 1;
Device newDevice;
newDevice.mac = deviceMac;
newDevice.name = deviceName;
newDevice.apBssid = deviceBssid;

View File

@ -1,16 +1,17 @@
#ifndef Names_h
#define Names_h
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#pragma once
#include <ESP8266WiFi.h>
extern "C" {
#include "user_interface.h"
}
#include "ArduinoJson.h"
#include "src/ArduinoJson-v5.13.5/ArduinoJson.h"
#include "language.h"
#include "SimpleList.h"
#define NAME_LIST_SIZE 25
#define NAME_MAX_LENGTH 16
#define NAME_MAX_LENGTH 17
extern void checkFile(String path, String data);
extern JsonVariant parseJSONFile(String path, DynamicJsonBuffer& jsonBuffer);
@ -97,6 +98,4 @@ class Names {
void internal_add(String macStr, String name, String bssidStr, uint8_t ch, bool selected);
void internal_remove(int num);
void internal_removeAll();
};
#endif // ifndef Names_h
};

View File

@ -1,3 +1,5 @@
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#include "SSIDs.h"
#include <LittleFS.h>
@ -42,6 +44,7 @@ void SSIDs::save(bool force) {
if (!force && !changed) return;
String buf = String(); // create buffer
buf += String(OPEN_CURLY_BRACKET) + String(DOUBLEQUOTES) + str(SS_JSON_RANDOM) + String(DOUBLEQUOTES) + String(
DOUBLEPOINT) + b2s(randomMode) + String(COMMA); // {"random":false,
buf += String(DOUBLEQUOTES) + str(SS_JSON_SSIDS) + String(DOUBLEQUOTES) + String(DOUBLEPOINT) +
@ -233,6 +236,7 @@ void SSIDs::replace(int num, String name, bool wpa2) {
if (len > 32) len = 32;
SSID newSSID;
newSSID.name = randomize(name);
newSSID.wpa2 = wpa2;
newSSID.len = (uint8_t)len;
@ -301,6 +305,7 @@ void SSIDs::internal_add(String name, bool wpa2, int len) {
name = fixUtf8(name);
SSID newSSID;
newSSID.name = name;
newSSID.wpa2 = wpa2;
newSSID.len = (uint8_t)len;
@ -314,4 +319,4 @@ void SSIDs::internal_remove(int num) {
void SSIDs::internal_removeAll() {
list->clear();
}
}

View File

@ -1,12 +1,13 @@
#ifndef SSIDs_h
#define SSIDs_h
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#pragma once
#include "Arduino.h"
#include <ESP8266WiFi.h>
extern "C" {
#include "user_interface.h"
}
#include "ArduinoJson.h"
#include "src/ArduinoJson-v5.13.5/ArduinoJson.h"
#include "language.h"
#include "SimpleList.h"
#include "Accesspoints.h"
@ -80,6 +81,4 @@ class SSIDs {
void internal_add(String name, bool wpa2, int add);
void internal_remove(int num);
void internal_removeAll();
};
#endif // ifndef SSIDs_h
};

View File

@ -1,3 +1,5 @@
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#include "Scan.h"
#include "settings.h"
@ -59,7 +61,7 @@ void Scan::start(uint8_t mode, uint32_t time, uint8_t nextmode, uint32_t continu
uint8_t channel) {
if (mode != SCAN_MODE_OFF) stop();
setWifiChannel(channel);
setWifiChannel(channel, true);
Scan::continueStartTime = currentTime;
Scan::snifferPacketTime = continueStartTime;
Scan::snifferOutputTime = continueStartTime;
@ -237,7 +239,7 @@ void Scan::setChannel(uint8_t ch) {
else if (ch < 1) ch = 14;
wifi_promiscuous_enable(0);
setWifiChannel(ch);
setWifiChannel(ch, true);
wifi_promiscuous_enable(1);
}

View File

@ -1,5 +1,6 @@
#ifndef Scan_h
#define Scan_h
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#pragma once
#include "Arduino.h"
#include "Accesspoints.h"
@ -23,9 +24,9 @@ extern Stations stations;
extern Names names;
extern SSIDs ssids;
extern uint8_t wifiMode;
extern uint8_t wifiMode;
extern void setWifiChannel(uint8_t ch);
extern void setWifiChannel(uint8_t ch, bool force);
extern bool appendFile(String path, String& buf);
extern bool writeFile(String path, String& buf);
extern void readFileToSerial(const String path);
@ -90,6 +91,4 @@ class Scan {
int findAccesspoint(uint8_t* mac);
String FILE_PATH = "/scan.json";
};
#endif // ifndef Scan_h
};

View File

@ -1,12 +1,6 @@
#ifndef SimpleList_h
#define SimpleList_h
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
/*
===========================================
Copyright (c) 2018 Stefan Kremser
github.com/spacehuhn
===========================================
*/
#pragma once
#include <type_traits>
#include <cstddef>
@ -166,6 +160,7 @@ void SimpleList<T>::add(int index, T obj) {
}
SimpleListNode<T>* newNode = new SimpleListNode<T>();
newNode->data = obj;
if (index == 0) {
@ -191,6 +186,7 @@ void SimpleList<T>::insert(T obj) {
// create new node
SimpleListNode<T>* newNode = new SimpleListNode<T>();
newNode->data = obj;
if (listSize == 0) {
@ -516,6 +512,4 @@ void SimpleList<T>::sort() {
}
this->sorted = true;
}
#endif // ifndef SimpleList_h
}

View File

@ -1,3 +1,5 @@
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#include "Stations.h"
Stations::Stations() {
@ -133,6 +135,7 @@ String Stations::getAPMacStr(int num) {
if (!check(num)) return String();
uint8_t* mac = getAPMac(num);
return bytesToStr(mac, 6);
}
@ -164,6 +167,7 @@ String Stations::getMacStr(int num) {
if (!check(num)) return String();
uint8_t* mac = getMac(num);
return bytesToStr(mac, 6);
}
@ -256,7 +260,7 @@ void Stations::remove(int num) {
prnt(ST_REMOVED_STATION);
prntln(num);
internal_remove(num);
changed = true;
}
@ -342,6 +346,7 @@ void Stations::internal_add(uint8_t* mac, int accesspointNum) {
if (count() >= STATION_LIST_SIZE) removeOldest();
Station newStation;
newStation.ap = accesspointNum;
newStation.ch = wifi_channel;
newStation.mac = (uint8_t*)malloc(6);
@ -365,4 +370,4 @@ void Stations::internal_removeAll() {
free(getTime(i));
}
list->clear();
}
}

View File

@ -1,5 +1,6 @@
#ifndef Stations_h
#define Stations_h
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#pragma once
#include "Arduino.h"
extern "C" {
@ -93,6 +94,4 @@ class Stations {
void internal_add(uint8_t* mac, int accesspointNum);
void internal_remove(int num);
void internal_removeAll();
};
#endif // ifndef Stations_h
};

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,8 +1,4 @@
/*
Copyright (c) 2020 Stefan Kremser (@Spacehuhn)
This software is licensed under the MIT License. See the license file for details.
Source: github.com/spacehuhn/esp8266_deauther
*/
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#pragma once

View File

@ -1,9 +1,7 @@
/*
===========================================
Copyright (c) 2018 Stefan Kremser
github.com/spacehuhn
===========================================
*/
/* =====================
This software is licensed under the MIT License:
https://github.com/spacehuhntech/esp8266_deauther
===================== */
extern "C" {
// Please follow this tutorial:
@ -14,7 +12,7 @@ extern "C" {
#include "EEPROMHelper.h"
#include <ArduinoJson.h>
#include "src/ArduinoJson-v5.13.5/ArduinoJson.h"
#if ARDUINOJSON_VERSION_MAJOR != 5
// The software was build using ArduinoJson v5.x
// version 6 is still in beta at the time of writing
@ -37,8 +35,8 @@ extern "C" {
#include "led.h"
// Run-Time Variables //
Names names;
SSIDs ssids;
Names names;
SSIDs ssids;
Accesspoints accesspoints;
Stations stations;
Scan scan;
@ -46,6 +44,8 @@ Attack attack;
CLI cli;
DisplayUI displayUI;
simplebutton::Button* resetButton;
#include "wifi.h"
uint32_t autosaveTime = 0;
@ -63,9 +63,9 @@ void setup() {
// start SPIFFS
prnt(SETUP_MOUNT_SPIFFS);
//bool spiffsError = !LittleFS.begin();
// bool spiffsError = !LittleFS.begin();
LittleFS.begin();
prntln(/*spiffsError ? SETUP_ERROR : */SETUP_OK);
prntln(/*spiffsError ? SETUP_ERROR : */ SETUP_OK);
// Start EEPROM
EEPROMHelper::begin(EEPROM_SIZE);
@ -83,7 +83,7 @@ void setup() {
#endif // ifdef FORMAT_EEPROM
// Format SPIFFS when in boot-loop
if (/*spiffsError || */!EEPROMHelper::checkBootNum(BOOT_COUNTER_ADDR)) {
if (/*spiffsError || */ !EEPROMHelper::checkBootNum(BOOT_COUNTER_ADDR)) {
prnt(SETUP_FORMAT_SPIFFS);
LittleFS.format();
prntln(SETUP_OK);
@ -114,12 +114,9 @@ void setup() {
// start display
if (settings::getDisplaySettings().enabled) {
displayUI.setup();
displayUI.mode = displayUI.DISPLAY_MODE::INTRO;
displayUI.mode = DISPLAY_MODE::INTRO;
}
// copy web files to SPIFFS
//copyWebFiles(false);
// load everything else
names.load();
ssids.load();
@ -128,9 +125,6 @@ void setup() {
// create scan.json
scan.setup();
// set channel
setWifiChannel(settings::getWifiSettings().channel);
// dis/enable serial command interface
if (settings::getCLISettings().enabled) {
cli.enable();
@ -151,13 +145,16 @@ void setup() {
// setup LED
led::setup();
// setup reset button
resetButton = new ButtonPullup(RESET_BUTTON);
}
void loop() {
currentTime = millis();
led::update(); // update LED color
wifi::update(); // manage access point
led::update(); // update LED color
wifi::update(); // manage access point
attack.update(); // run attacks
displayUI.update();
cli.update(); // read and run serial input
@ -180,4 +177,20 @@ void loop() {
displayUI.setupLED();
#endif // ifdef HIGHLIGHT_LED
}
}
resetButton->update();
if (resetButton->holding(5000)) {
led::setMode(LED_MODE::SCAN);
DISPLAY_MODE _mode = displayUI.mode;
displayUI.mode = DISPLAY_MODE::RESETTING;
displayUI.update(true);
settings::reset();
settings::save(true);
delay(2000);
led::setMode(LED_MODE::IDLE);
displayUI.mode = _mode;
}
}

View File

@ -1,12 +1,13 @@
#ifndef functions_h
#define functions_h
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#pragma once
#include "Arduino.h"
#include <LittleFS.h>
extern "C" {
#include "user_interface.h"
}
#include "ArduinoJson.h"
#include "src/ArduinoJson-v5.13.5/ArduinoJson.h"
/*
Here is a collection of useful functions and variables.
@ -196,6 +197,7 @@ bool eqls(const char* str, const char* keywordPtr) {
if (strlen(str) > 255) return false; // when string too long
char keyword[strlen_P(keywordPtr) + 1];
strcpy_P(keyword, keywordPtr);
uint8_t lenStr = strlen(str);
@ -309,8 +311,8 @@ void prntln(const uint32_t i) {
}
/* ===== WiFi ===== */
void setWifiChannel(uint8_t ch) {
if ((ch != wifi_channel) && (ch > 0) && (ch < 15)) {
void setWifiChannel(uint8_t ch, bool force) {
if (((ch != wifi_channel) || force) && (ch < 15)) {
wifi_channel = ch;
wifi_set_channel(wifi_channel);
}
@ -324,6 +326,7 @@ void setOutputPower(float dBm) {
}
uint8_t val = (dBm * 4.0f);
system_phy_set_max_tpw(val);
}
@ -825,6 +828,4 @@ String formatBytes(size_t bytes) {
else if (bytes < (1024 * 1024)) return String(bytes / 1024.0) + "KB";
else if (bytes < (1024 * 1024 * 1024)) return String(bytes / 1024.0 / 1024.0) + "MB";
else return String(bytes / 1024.0 / 1024.0 / 1024.0) + "GB";
}
#endif // ifndef functions_h
}

View File

@ -1,5 +1,6 @@
#ifndef language_h
#define language_h
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#pragma once
#include "Arduino.h"
@ -200,9 +201,8 @@ const char CLI_HELP_COMMENT[] PROGMEM = "// <comments>";
const char CLI_HELP_SEND_DEAUTH[] PROGMEM = "send deauth <apMac> <stMac> <rason> <channel>";
const char CLI_HELP_SEND_BEACON[] PROGMEM = "send beacon <mac> <ssid> <ch> [wpa2]";
const char CLI_HELP_SEND_PROBE[] PROGMEM = "send probe <mac> <ssid> <ch>";
const char CLI_HELP_LED_A[] PROGMEM = "led <r> <g> <b> [<brightness>]";
const char CLI_HELP_LED_B[] PROGMEM = "led <#rrggbb> [<brightness>]";
const char CLI_HELP_LED_ENABLE[] PROGMEM = "led <enable/disable>";
const char CLI_HELP_LED_A[] PROGMEM = "led <r> <g> <b>";
const char CLI_HELP_LED_B[] PROGMEM = "led <#rrggbb>";
const char CLI_HELP_DRAW[] PROGMEM = "draw";
const char CLI_HELP_SCREEN_ON[] PROGMEM = "screen <on/off>";
const char CLI_HELP_SCREEN_MODE[] PROGMEM = "screen mode <menu/packetmonitor/buttontest/loading>";
@ -365,6 +365,8 @@ const char D_SHOW[] PROGMEM = "SELECT";
const char D_ATTACK[] PROGMEM = "ATTACK";
const char D_PACKET_MONITOR[] PROGMEM = "PACKET MONITOR";
const char D_CLOCK[] PROGMEM = "CLOCK";
const char D_CLOCK_DISPLAY[] PROGMEM = "CLOCK DISPLAY";
const char D_CLOCK_SET[] PROGMEM = "SET CLOCK";
// SCAN MENU
const char D_SCAN_APST[] PROGMEM = "SCAN AP + ST";
@ -541,7 +543,7 @@ const char W_BAD_ARGS[] PROGMEM = "BAD ARGS";
const char W_BAD_PATH[] PROGMEM = "BAD PATH";
const char W_FILE_NOT_FOUND[] PROGMEM = "ERROR 404 File Not Found";
const char W_STARTED_AP[] PROGMEM = "Started AP";
const char W_WEBINTERFACE[] PROGMEM = "/web"; // default folder containing the web files
const char W_WEBINTERFACE[] PROGMEM = "/web"; // default folder containing the web files
const char W_DEFAULT_LANG[] PROGMEM = "/lang/default.lang";
const char W_HTML[] PROGMEM = "text/html";
@ -619,5 +621,4 @@ const char S_JSON_LEDENABLED[] PROGMEM = "led";
// Display
const char S_JSON_DISPLAYINTERFACE[] PROGMEM = "display";
const char S_JSON_DISPLAY_TIMEOUT[] PROGMEM = "displayTimeout";
#endif // ifndef language_h
const char S_JSON_DISPLAY_TIMEOUT[] PROGMEM = "displayTimeout";

View File

@ -1,43 +1,43 @@
/*
Copyright (c) 2020 Stefan Kremser (@Spacehuhn)
This software is licensed under the MIT License. See the license file for details.
Source: github.com/spacehuhn/esp8266_deauther
*/
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#include "led.h"
#include "A_config.h" // Config for LEDs
#include <Arduino.h> // digitalWrite, analogWrite, pinMode
#include <Arduino.h> // digitalWrite, analogWrite, pinMode
#include "language.h" // Strings used in printColor and tempDisable
#include "settings.h" // used in update()
#include "Attack.h" // used in update()
#include "Scan.h" // used in update()
#include "Attack.h" // used in update()
#include "Scan.h" // used in update()
// Inlcude libraries for Neopixel or LED_MY92xx if used
#if defined(LED_NEOPIXEL)
#include <Adafruit_NeoPixel.h>
#include "src/Adafruit_NeoPixel-1.7.0/Adafruit_NeoPixel.h"
#elif defined(LED_MY92)
#include <my92xx.h>
#include "src/my92xx-3.0.3/my92xx.h"
#elif defined(LED_DOTSTAR)
#include "src/Adafruit_DotStar-1.1.4/Adafruit_DotStar.h"
#endif // if defined(LED_NEOPIXEL)
extern Attack attack;
extern Scan scan;
extern Attack attack;
extern Scan scan;
namespace led {
// ===== PRIVATE ===== //
LED_MODE mode = OFF;
#if defined(LED_NEOPIXEL_RGB)
Adafruit_NeoPixel strip {LED_NEOPIXEL_NUM, LED_NEOPIXEL_PIN, NEO_RGB + NEO_KHZ400};
#elif defined(LED_NEOPIXEL_GRB)
Adafruit_NeoPixel strip {LED_NEOPIXEL_NUM, LED_NEOPIXEL_PIN, NEO_GRB + NEO_KHZ400};
#elif defined(LED_MY92)
my92xx myled {LED_MY92_MODEL, LED_MY92_NUM, LED_MY92_DATA, LED_MY92_CLK, MY92XX_COMMAND_DEFAULT};
#endif
#if defined(LED_NEOPIXEL_RGB)
Adafruit_NeoPixel strip { LED_NUM, LED_NEOPIXEL_PIN, NEO_RGB + NEO_KHZ800 };
#elif defined(LED_NEOPIXEL_GRB)
Adafruit_NeoPixel strip { LED_NUM, LED_NEOPIXEL_PIN, NEO_GRB + NEO_KHZ800 };
#elif defined(LED_MY92)
my92xx myled { LED_MY92_MODEL, LED_NUM, LED_MY92_DATA, LED_MY92_CLK, MY92XX_COMMAND_DEFAULT };
#elif defined(LED_DOTSTAR)
Adafruit_DotStar strip { LED_NUM, LED_DOTSTAR_DATA, LED_DOTSTAR_CLK, DOTSTAR_BGR };
#endif // if defined(LED_NEOPIXEL_RGB)
void setColor(uint8_t r, uint8_t g, uint8_t b) {
#if defined(LED_DIGITAL)
#if defined(LED_DIGITAL)
if (LED_ANODE) {
if (LED_PIN_R < 255) digitalWrite(LED_PIN_R, r > 0);
if (LED_PIN_G < 255) digitalWrite(LED_PIN_G, g > 0);
@ -47,7 +47,7 @@ namespace led {
if (LED_PIN_G < 255) digitalWrite(LED_PIN_G, g == 0);
if (LED_PIN_B < 255) digitalWrite(LED_PIN_B, b == 0);
}
#elif defined(LED_RGB)
#elif defined(LED_RGB)
if (r > 0) r = r * LED_MODE_BRIGHTNESS / 100;
if (g > 0) g = g * LED_MODE_BRIGHTNESS / 100;
if (b > 0) b = b * LED_MODE_BRIGHTNESS / 100;
@ -61,43 +61,43 @@ namespace led {
analogWrite(LED_PIN_R, r);
analogWrite(LED_PIN_G, g);
analogWrite(LED_PIN_B, b);
#elif defined(LED_NEOPIXEL)
#elif defined(LED_NEOPIXEL) || defined(LED_DOTSTAR)
for (size_t i = 0; i < LED_NEOPIXEL_NUM; i++) {
for (size_t i = 0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, r, g, b);
}
strip.show();
#elif defined(LED_MY9291)
#elif defined(LED_MY9291)
myled.setChannel(LED_MY92_CH_R, r);
myled.setChannel(LED_MY92_CH_G, g);
myled.setChannel(LED_MY92_CH_B, b);
myled.setChannel(LED_MY92_CH_BRIGHTNESS, LED_MODE_BRIGHTNESS);
myled.setState(true);
myled.update();
#endif // if defined(LED_DIGITAL)
#endif // if defined(LED_DIGITAL)
}
// ===== PUBLIC ===== //
void setup() {
analogWriteRange(0xff);
#if defined(LED_DIGITAL) || defined(LED_RGB)
if (LED_PIN_R < 255) pinMode(LED_PIN_R, OUTPUT);
if (LED_PIN_G < 255) pinMode(LED_PIN_G, OUTPUT);
if (LED_PIN_B < 255) pinMode(LED_PIN_B, OUTPUT);
#elif defined(LED_NEOPIXEL)
strip.begin();
strip.setBrightness(LED_MODE_BRIGHTNESS);
strip.show();
#elif defined(LED_MY9291)
myled.setChannel(LED_MY92_CH_R, 0);
myled.setChannel(LED_MY92_CH_G, 0);
myled.setChannel(LED_MY92_CH_B, 0);
myled.setChannel(LED_MY92_CH_BRIGHTNESS, LED_MODE_BRIGHTNESS);
myled.setState(true);
myled.update();
#endif // if defined(LED_DIGITAL) || defined(LED_RGB)
#if defined(LED_DIGITAL) || defined(LED_RGB)
if (LED_PIN_R < 255) pinMode(LED_PIN_R, OUTPUT);
if (LED_PIN_G < 255) pinMode(LED_PIN_G, OUTPUT);
if (LED_PIN_B < 255) pinMode(LED_PIN_B, OUTPUT);
#elif defined(LED_NEOPIXEL) || defined(LED_DOTSTAR)
strip.begin();
strip.setBrightness(LED_MODE_BRIGHTNESS);
strip.show();
#elif defined(LED_MY9291)
myled.setChannel(LED_MY92_CH_R, 0);
myled.setChannel(LED_MY92_CH_G, 0);
myled.setChannel(LED_MY92_CH_B, 0);
myled.setChannel(LED_MY92_CH_BRIGHTNESS, LED_MODE_BRIGHTNESS);
myled.setState(true);
myled.update();
#endif // if defined(LED_DIGITAL) || defined(LED_RGB)
}
void update() {
@ -132,4 +132,4 @@ namespace led {
}
}
}
}
}

View File

@ -1,11 +1,9 @@
/*
Copyright (c) 2020 Stefan Kremser (@Spacehuhn)
This software is licensed under the MIT License. See the license file for details.
Source: github.com/spacehuhn/esp8266_deauther
*/
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#pragma once
#include <cstdint>
enum LED_MODE {
OFF,
SCAN,
@ -14,7 +12,8 @@ enum LED_MODE {
};
namespace led {
void setup();
void update();
void setMode(LED_MODE new_mode, bool force = false);
void setup();
void update();
void setMode(LED_MODE new_mode, bool force = false);
void setColor(uint8_t r, uint8_t g, uint8_t b);
}

View File

@ -1,13 +1,9 @@
/*
Copyright (c) 2020 Stefan Kremser (@Spacehuhn)
This software is licensed under the MIT License. See the license file for details.
Source: github.com/spacehuhn/esp8266_deauther
*/
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#include "settings.h"
#include "A_config.h" // Default Settings
#include "language.h" // prnt and prntln
#include "A_config.h" // Default Settings
#include "language.h" // prnt and prntln
#include "EEPROMHelper.h" // To load and save settings_t
#include "debug.h"
@ -17,29 +13,29 @@ extern bool writeFile(String path, String& buf);
extern void getRandomMac(uint8_t* mac);
extern bool macValid(uint8_t* mac);
#define JSON_FLAG(_NAME,_VALUE)\
str += String('"') + String(FPSTR(_NAME)) + String(F("\":")) + String(_VALUE?"true":"false") + String(',');
#define JSON_FLAG(_NAME, _VALUE)\
str += String('"') + String(FPSTR(_NAME)) + String(F("\":")) + String(_VALUE ? "true" : "false") + String(',');
#define JSON_VALUE(_NAME,_VALUE)\
#define JSON_VALUE(_NAME, _VALUE)\
str += String('"') + String(FPSTR(_NAME)) + String(F("\":\"")) + String(_VALUE) + String(F("\","));
#define JSON_INT(_NAME,_VALUE)\
#define JSON_INT(_NAME, _VALUE)\
str += String('"') + String(FPSTR(_NAME)) + String(F("\":")) + String(_VALUE) + String(',');
#define JSON_HEX(_NAME,_BYTES,_LEN)\
#define JSON_HEX(_NAME, _BYTES, _LEN)\
str += String('"') + String(FPSTR(_NAME)) + String(F("\":\""));\
for (int i = 0; i<_LEN; i++) {\
if (i > 0) str += ':';\
if (i > 0) str += ':';\
if (_BYTES[i] < 0x10) str += '0';\
str += String(_BYTES[i], HEX);\
str += String(_BYTES[i], HEX);\
}\
str += String(F("\","));
#define JSON_DEC(_NAME,_BYTES,_LEN)\
#define JSON_DEC(_NAME, _BYTES, _LEN)\
str += String(F("\"")) + String(FPSTR(_NAME)) + String(F("\":\""));\
for (int i = 0; i<_LEN; i++) {\
if (i > 0) str += '.';\
str += String(_BYTES[i]);\
str += String(_BYTES[i]);\
}\
str += String(F("\","));
@ -47,7 +43,7 @@ extern bool macValid(uint8_t* mac);
namespace settings {
// ========== PRIVATE ========== //
const char* SETTINGS_PATH = "/settings.json";
settings_t data;
bool changed = false;
@ -56,7 +52,7 @@ namespace settings {
str.reserve(600);
str += '{';
// Version
JSON_VALUE(S_JSON_VERSION, DEAUTHER_VERSION);
@ -104,7 +100,7 @@ namespace settings {
// Display
JSON_FLAG(S_JSON_DISPLAYINTERFACE, data.display.enabled);
JSON_INT(S_JSON_DISPLAY_TIMEOUT, data.display.timeout);
str.setCharAt(str.length()-1, '}');
}
@ -114,21 +110,23 @@ namespace settings {
// read data from eeproms
settings_t newData;
EEPROMHelper::getObject(SETTINGS_ADDR, newData);
// calc and check hash
if (newData.magic_num == MAGIC_NUM) {
data = newData;
data.version.major = DEAUTHER_VERSION_MAJOR;
data.version.minor = DEAUTHER_VERSION_MINOR;
data = newData;
data.version.major = DEAUTHER_VERSION_MAJOR;
data.version.minor = DEAUTHER_VERSION_MINOR;
data.version.revision = DEAUTHER_VERSION_REVISION;
debuglnF("OK");
save();
} else {
debuglnF("Invalid Hash");
/*debug(data.magic_num);
debugF(" != ");
debugln(MAGIC_NUM);*/
debugF(" != ");
debugln(MAGIC_NUM);*/
reset();
save();
@ -143,47 +141,48 @@ namespace settings {
void reset() {
data.magic_num = MAGIC_NUM;
data.version.major = DEAUTHER_VERSION_MAJOR;
data.version.minor = DEAUTHER_VERSION_MINOR;
data.version.major = DEAUTHER_VERSION_MAJOR;
data.version.minor = DEAUTHER_VERSION_MINOR;
data.version.revision = DEAUTHER_VERSION_REVISION;
data.attack.attack_all_ch = ATTACK_ALL_CH;
data.attack.random_tx = RANDOM_TX;
data.attack.timeout = ATTACK_TIMEOUT;
data.attack.deauths_per_target = DEAUTHS_PER_TARGET;
data.attack.deauth_reason = DEAUTH_REASON;
data.attack.beacon_interval = beacon_interval_t::INTERVAL_100MS;
data.attack.attack_all_ch = ATTACK_ALL_CH;
data.attack.random_tx = RANDOM_TX;
data.attack.timeout = ATTACK_TIMEOUT;
data.attack.deauths_per_target = DEAUTHS_PER_TARGET;
data.attack.deauth_reason = DEAUTH_REASON;
data.attack.beacon_interval = beacon_interval_t::INTERVAL_100MS;
data.attack.probe_frames_per_ssid = PROBE_FRAMES_PER_SSID;
data.wifi.channel = 1;
getRandomMac(data.wifi.mac_st);
getRandomMac(data.wifi.mac_ap);
data.sniffer.channel_time = CH_TIME;
data.sniffer.channel_time = CH_TIME;
data.sniffer.min_deauth_frames = MIN_DEAUTH_FRAMES;
strncpy(data.ap.ssid, AP_SSID, 32);
strncpy(data.ap.password, AP_PASSWD, 64);
data.ap.hidden = AP_HIDDEN;
uint8_t ip[4] = AP_IP_ADDR;
memcpy(data.ap.ip, ip, 4);
data.web.enabled = WEB_ENABLED;
data.web.enabled = WEB_ENABLED;
data.web.captive_portal = WEB_CAPTIVE_PORTAL;
data.web.use_spiffs = WEB_USE_SPIFFS;
data.web.use_spiffs = WEB_USE_SPIFFS;
memcpy(data.web.lang, DEFAULT_LANG, 3);
data.cli.enabled = CLI_ENABLED;
data.cli.enabled = CLI_ENABLED;
data.cli.serial_echo = CLI_ECHO;
data.led.enabled = USE_LED;
data.display.enabled = USE_DISPLAY;
data.display.timeout = DISPLAY_TIMEOUT;
changed = true;
debuglnF("Settings reset to default");
}
@ -192,7 +191,7 @@ namespace settings {
EEPROMHelper::saveObject(SETTINGS_ADDR, data);
changed = false;
String json_buffer;
get_json(json_buffer);
@ -205,9 +204,10 @@ namespace settings {
debugln(SETTINGS_PATH);
}
}
void print() {
String json_buffer;
get_json(json_buffer);
json_buffer.replace("\":", ": ");
@ -267,7 +267,7 @@ namespace settings {
const display_settings_t& getDisplaySettings() {
return data.display;
}
// ===== SETTERS ===== //
void setAllSettings(settings_t& newSettings) {

View File

@ -1,12 +1,8 @@
/*
Copyright (c) 2020 Stefan Kremser (@Spacehuhn)
This software is licensed under the MIT License. See the license file for details.
Source: github.com/spacehuhn/esp8266_deauther
*/
/* This software is licensed under the MIT License: https://github.com/spacehuhntech/esp8266_deauther */
#pragma once
#include <Arduino.h> // Arduino String, Serial
#include <Arduino.h> // Arduino String, Serial
#include "A_config.h"
// ===== VERSION ===== //
@ -24,7 +20,7 @@ typedef struct autosave_settings_t {
// ===== ATTACK ===== //
typedef enum beacon_interval_t {
INTERVAL_1S = 0,
INTERVAL_1S = 0,
INTERVAL_100MS = 1
} beacon_interval_t;
@ -114,11 +110,11 @@ namespace settings {
void print();
const settings_t& getAllSettings();
const version_t & getVersion();
const version_t& getVersion();
const autosave_settings_t& getAutosaveSettings();
const attack_settings_t & getAttackSettings();
const wifi_settings_t & getWifiSettings();
const sniffer_settings_t & getSnifferSettings();
const attack_settings_t& getAttackSettings();
const wifi_settings_t& getWifiSettings();
const sniffer_settings_t& getSnifferSettings();
const access_point_settings_t& getAccessPointSettings();
const web_settings_t& getWebSettings();
const cli_settings_t& getCLISettings();

View File

@ -0,0 +1,638 @@
/*!
* @file Adafruit_DotStar.cpp
*
* @mainpage Arduino Library for driving Adafruit DotStar addressable LEDs
* and compatible devicess -- APA102, etc.
*
* @section intro_sec Introduction
*
* This is the documentation for Adafruit's DotStar library for the
* Arduino platform, allowing a broad range of microcontroller boards
* (most AVR boards, many ARM devices, ESP8266 and ESP32, among others)
* to control Adafruit DotStars and compatible devices -- APA102, etc.
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing products
* from Adafruit!
*
* @section author Author
*
* Written by Limor Fried and Phil Burgess for Adafruit Industries with
* contributions from members of the open source community.
*
* @section license License
*
* This file is part of the Adafruit_DotStar library.
*
* Adafruit_DotStar is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Adafruit_DotStar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with DotStar. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "Adafruit_DotStar.h"
#if !defined(__AVR_ATtiny85__)
#include <SPI.h>
#endif
#define USE_HW_SPI 255 ///< Assigned to dataPin to indicate 'hard' SPI
/*!
@brief DotStar constructor for hardware SPI. Must be connected to
MOSI, SCK pins.
@param n Number of DotStars in strand.
@param o Pixel type -- one of the DOTSTAR_* constants defined in
Adafruit_DotStar.h, for example DOTSTAR_BRG for DotStars
expecting color bytes expressed in blue, red, green order
per pixel. Default if unspecified is DOTSTAR_BRG.
@return Adafruit_DotStar object. Call the begin() function before use.
*/
Adafruit_DotStar::Adafruit_DotStar(uint16_t n, uint8_t o)
: numLEDs(n), dataPin(USE_HW_SPI), brightness(0), pixels(NULL),
rOffset(o & 3), gOffset((o >> 2) & 3), bOffset((o >> 4) & 3) {
updateLength(n);
}
/*!
@brief DotStar constructor for 'soft' (bitbang) SPI. Any two pins
can be used.
@param n Number of DotStars in strand.
@param data Arduino pin number for data out.
@param clock Arduino pin number for clock out.
@param o Pixel type -- one of the DOTSTAR_* constants defined in
Adafruit_DotStar.h, for example DOTSTAR_BRG for DotStars
expecting color bytes expressed in blue, red, green order
per pixel. Default if unspecified is DOTSTAR_BRG.
@return Adafruit_DotStar object. Call the begin() function before use.
*/
Adafruit_DotStar::Adafruit_DotStar(uint16_t n, uint8_t data, uint8_t clock,
uint8_t o)
: dataPin(data), clockPin(clock), brightness(0), pixels(NULL),
rOffset(o & 3), gOffset((o >> 2) & 3), bOffset((o >> 4) & 3) {
updateLength(n);
}
/*!
@brief Deallocate Adafruit_DotStar object, set data and clock pins
back to INPUT.
*/
Adafruit_DotStar::~Adafruit_DotStar(void) {
free(pixels);
if (dataPin == USE_HW_SPI)
hw_spi_end();
else
sw_spi_end();
}
/*!
@brief Initialize Adafruit_DotStar object -- sets data and clock pins
to outputs and initializes hardware SPI if necessary.
*/
void Adafruit_DotStar::begin(void) {
if (dataPin == USE_HW_SPI)
hw_spi_init();
else
sw_spi_init();
}
// Pins may be reassigned post-begin(), so a sketch can store hardware
// config in flash, SD card, etc. rather than hardcoded. Also permits
// "recycling" LED ram across multiple strips: set pins to first strip,
// render & write all data, reassign pins to next strip, render & write,
// etc. They won't update simultaneously, but usually unnoticeable.
/*!
@brief Switch over to hardware SPI. DotStars must be connected to
MOSI, SCK pins. Data in pixel buffer is unaffected and can
continue to be used.
*/
void Adafruit_DotStar::updatePins(void) {
sw_spi_end();
dataPin = USE_HW_SPI;
hw_spi_init();
}
/*!
@brief Switch over to 'soft' (bitbang) SPI. DotStars can be connected
to any two pins. Data in pixel buffer is unaffected and can
continue to be used.
@param data Arduino pin number for data out.
@param clock Arduino pin number for clock out.
*/
void Adafruit_DotStar::updatePins(uint8_t data, uint8_t clock) {
hw_spi_end();
dataPin = data;
clockPin = clock;
sw_spi_init();
}
/*!
@brief Change the length of a previously-declared Adafruit_DotStar
strip object. Old data is deallocated and new data is cleared.
Pin numbers and pixel format are unchanged.
@param n New length of strip, in pixels.
@note This function is deprecated, here only for old projects that
may still be calling it. New projects should instead use the
'new' keyword.
*/
void Adafruit_DotStar::updateLength(uint16_t n) {
free(pixels);
uint16_t bytes = (rOffset == gOffset)
? n + ((n + 3) / 4)
: // MONO: 10 bits/pixel, round up to next byte
n * 3; // COLOR: 3 bytes/pixel
if ((pixels = (uint8_t *)malloc(bytes))) {
numLEDs = n;
clear();
} else {
numLEDs = 0;
}
}
// SPI STUFF ---------------------------------------------------------------
/*!
@brief Initialize hardware SPI.
@note This library is written in pre-SPI-transactions style and needs
some rewriting to correctly share the SPI bus with other devices.
*/
void Adafruit_DotStar::hw_spi_init(void) { // Initialize hardware SPI
#ifdef __AVR_ATtiny85__
PORTB &= ~(_BV(PORTB1) | _BV(PORTB2)); // Outputs
DDRB |= _BV(PORTB1) | _BV(PORTB2); // DO (NOT MOSI) + SCK
#elif (SPI_INTERFACES_COUNT > 0) || !defined(SPI_INTERFACES_COUNT)
SPI.begin();
// Hardware SPI clock speeds are chosen to run at roughly 1-8 MHz for most
// boards, providing a slower but more reliable experience by default. If
// you want faster LED updates, experiment with the clock speeds to find
// what works best with your particular setup.
#if defined(__AVR__) || defined(CORE_TEENSY) || defined(__ARDUINO_ARC__) || \
defined(__ARDUINO_X86__)
SPI.setClockDivider(SPI_CLOCK_DIV2); // 8 MHz (6 MHz on Pro Trinket 3V)
#else
#ifdef ESP8266
SPI.setFrequency(8000000L);
#elif defined(PIC32)
// Use begin/end transaction to set SPI clock rate
SPI.beginTransaction(SPISettings(8000000, MSBFIRST, SPI_MODE0));
SPI.endTransaction();
#else
SPI.setClockDivider((F_CPU + 4000000L) / 8000000L); // 8-ish MHz on Due
#endif
#endif
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
#endif
}
/*!
@brief Stop hardware SPI.
*/
void Adafruit_DotStar::hw_spi_end(void) {
#ifdef __AVR_ATtiny85__
DDRB &= ~(_BV(PORTB1) | _BV(PORTB2)); // Inputs
#elif (SPI_INTERFACES_COUNT > 0) || !defined(SPI_INTERFACES_COUNT)
SPI.end();
#endif
}
/*!
@brief Initialize 'soft' (bitbang) SPI. Data and clock pins are set
to outputs.
*/
void Adafruit_DotStar::sw_spi_init(void) {
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
#ifdef __AVR__
dataPort = portOutputRegister(digitalPinToPort(dataPin));
clockPort = portOutputRegister(digitalPinToPort(clockPin));
dataPinMask = digitalPinToBitMask(dataPin);
clockPinMask = digitalPinToBitMask(clockPin);
*dataPort &= ~dataPinMask;
*clockPort &= ~clockPinMask;
#else
digitalWrite(dataPin, LOW);
digitalWrite(clockPin, LOW);
#endif
}
/*!
@brief Stop 'soft' (bitbang) SPI. Data and clock pins are set to inputs.
*/
void Adafruit_DotStar::sw_spi_end() {
pinMode(dataPin, INPUT);
pinMode(clockPin, INPUT);
}
#ifdef __AVR_ATtiny85__
// Teensy/Gemma-specific stuff for hardware-half-assisted SPI
#define SPIBIT \
USICR = ((1 << USIWM0) | (1 << USITC)); \
USICR = \
((1 << USIWM0) | (1 << USITC) | (1 << USICLK)); // Clock bit tick, tock
static void spi_out(uint8_t n) { // Clock out one byte
USIDR = n;
SPIBIT SPIBIT SPIBIT SPIBIT SPIBIT SPIBIT SPIBIT SPIBIT
}
#elif (SPI_INTERFACES_COUNT > 0) || !defined(SPI_INTERFACES_COUNT)
// All other boards have full-featured hardware support for SPI
#define spi_out(n) (void)SPI.transfer(n) ///< Call hardware SPI function
// Pipelining reads next byte while current byte is clocked out
#if (defined(__AVR__) && !defined(__AVR_ATtiny85__)) || defined(CORE_TEENSY)
#define SPI_PIPELINE
#endif
#else // no hardware spi
#define spi_out(n) sw_spi_out(n)
#endif
/*!
@brief Soft (bitbang) SPI write.
@param n 8-bit value to transfer.
*/
void Adafruit_DotStar::sw_spi_out(uint8_t n) {
for (uint8_t i = 8; i--; n <<= 1) {
#ifdef __AVR__
if (n & 0x80)
*dataPort |= dataPinMask;
else
*dataPort &= ~dataPinMask;
*clockPort |= clockPinMask;
*clockPort &= ~clockPinMask;
#else
if (n & 0x80)
digitalWrite(dataPin, HIGH);
else
digitalWrite(dataPin, LOW);
digitalWrite(clockPin, HIGH);
#if F_CPU >= 48000000
__asm__ volatile("nop \n nop");
#endif
digitalWrite(clockPin, LOW);
#if F_CPU >= 48000000
__asm__ volatile("nop \n nop");
#endif
#endif
}
}
/* ISSUE DATA TO LED STRIP -------------------------------------------------
Although the LED driver has an additional per-pixel 5-bit brightness
setting, it is NOT used or supported here. On APA102, the normally
very fast PWM is gated through a much slower PWM (about 400 Hz),
rendering it useless for POV or other high-speed things that are
probably why one is using DotStars instead of NeoPixels in the first
place. I'm told that some APA102 clones use current control rather than
PWM for this, which would be much more worthwhile. Still, no support
here, no plans for it. If you really can't live without it, you can fork
the library and add it for your own use, but any pull requests for this
are unlikely be merged for the foreseeable future.
*/
/*!
@brief Transmit pixel data in RAM to DotStars.
*/
void Adafruit_DotStar::show(void) {
if (!pixels)
return;
uint8_t *ptr = pixels, i; // -> LED data
uint16_t n = numLEDs; // Counter
uint16_t b16 = (uint16_t)brightness; // Type-convert for fixed-point math
if (dataPin == USE_HW_SPI) {
// TO DO: modernize this for SPI transactions
#ifdef SPI_PIPELINE
uint8_t next;
for (i = 0; i < 3; i++)
spi_out(0x00); // First 3 start-frame bytes
SPDR = 0x00; // 4th is pipelined
do { // For each pixel...
while (!(SPSR & _BV(SPIF)))
; // Wait for prior byte out
SPDR = 0xFF; // Pixel start
for (i = 0; i < 3; i++) { // For R,G,B...
next = brightness ? (*ptr++ * b16) >> 8 : *ptr++; // Read, scale
while (!(SPSR & _BV(SPIF)))
; // Wait for prior byte out
SPDR = next; // Write scaled color
}
} while (--n);
while (!(SPSR & _BV(SPIF)))
; // Wait for last byte out
#else
for (i = 0; i < 4; i++)
spi_out(0x00); // 4 byte start-frame marker
if (brightness) { // Scale pixel brightness on output
do { // For each pixel...
spi_out(0xFF); // Pixel start
for (i = 0; i < 3; i++)
spi_out((*ptr++ * b16) >> 8); // Scale, write RGB
} while (--n);
} else { // Full brightness (no scaling)
do { // For each pixel...
spi_out(0xFF); // Pixel start
for (i = 0; i < 3; i++)
spi_out(*ptr++); // Write R,G,B
} while (--n);
}
#endif
// Four end-frame bytes are seemingly indistinguishable from a white
// pixel, and empirical testing suggests it can be left out...but it's
// always a good idea to follow the datasheet, in case future hardware
// revisions are more strict (e.g. might mandate use of end-frame
// before start-frame marker). i.e. let's not remove this. But after
// testing a bit more the suggestion is to use at least (numLeds+1)/2
// high values (1) or (numLeds+15)/16 full bytes as EndFrame. For details
// see also:
// https://cpldcpu.wordpress.com/2014/11/30/understanding-the-apa102-superled/
for (i = 0; i < ((numLEDs + 15) / 16); i++)
spi_out(0xFF);
} else { // Soft (bitbang) SPI
for (i = 0; i < 4; i++)
sw_spi_out(0); // Start-frame marker
if (brightness) { // Scale pixel brightness on output
do { // For each pixel...
sw_spi_out(0xFF); // Pixel start
for (i = 0; i < 3; i++)
sw_spi_out((*ptr++ * b16) >> 8); // Scale, write
} while (--n);
} else { // Full brightness (no scaling)
do { // For each pixel...
sw_spi_out(0xFF); // Pixel start
for (i = 0; i < 3; i++)
sw_spi_out(*ptr++); // R,G,B
} while (--n);
}
for (i = 0; i < ((numLEDs + 15) / 16); i++)
sw_spi_out(0xFF); // End-frame marker (see note above)
}
}
/*!
@brief Fill the whole DotStar strip with 0 / black / off.
*/
void Adafruit_DotStar::clear() {
memset(pixels, 0,
(rOffset == gOffset) ? numLEDs + ((numLEDs + 3) / 4)
: // MONO: 10 bits/pixel
numLEDs * 3); // COLOR: 3 bytes/pixel
}
/*!
@brief Set a pixel's color using separate red, green and blue components.
@param n Pixel index, starting from 0.
@param r Red brightness, 0 = minimum (off), 255 = maximum.
@param g Green brightness, 0 = minimum (off), 255 = maximum.
@param b Blue brightness, 0 = minimum (off), 255 = maximum.
*/
void Adafruit_DotStar::setPixelColor(uint16_t n, uint8_t r, uint8_t g,
uint8_t b) {
if (n < numLEDs) {
uint8_t *p = &pixels[n * 3];
p[rOffset] = r;
p[gOffset] = g;
p[bOffset] = b;
}
}
/*!
@brief Set a pixel's color using a 32-bit 'packed' RGB value.
@param n Pixel index, starting from 0.
@param c 32-bit color value. Most significant byte is 0, second is
red, then green, and least significant byte is blue.
e.g. 0x00RRGGBB
*/
void Adafruit_DotStar::setPixelColor(uint16_t n, uint32_t c) {
if (n < numLEDs) {
uint8_t *p = &pixels[n * 3];
p[rOffset] = (uint8_t)(c >> 16);
p[gOffset] = (uint8_t)(c >> 8);
p[bOffset] = (uint8_t)c;
}
}
/*!
@brief Fill all or part of the DotStar strip with a color.
@param c 32-bit color value. Most significant byte is 0, second
is red, then green, and least significant byte is blue.
e.g. 0x00RRGGBB. If all arguments are unspecified, this
will be 0 (off).
@param first Index of first pixel to fill, starting from 0. Must be
in-bounds, no clipping is performed. 0 if unspecified.
@param count Number of pixels to fill, as a positive value. Passing
0 or leaving unspecified will fill to end of strip.
*/
void Adafruit_DotStar::fill(uint32_t c, uint16_t first, uint16_t count) {
uint16_t i, end;
if (first >= numLEDs) {
return; // If first LED is past end of strip, nothing to do
}
// Calculate the index ONE AFTER the last pixel to fill
if (count == 0) {
// Fill to end of strip
end = numLEDs;
} else {
// Ensure that the loop won't go past the last pixel
end = first + count;
if (end > numLEDs)
end = numLEDs;
}
for (i = first; i < end; i++) {
this->setPixelColor(i, c);
}
}
/*!
@brief Convert hue, saturation and value into a packed 32-bit RGB color
that can be passed to setPixelColor() or other RGB-compatible
functions.
@param hue An unsigned 16-bit value, 0 to 65535, representing one full
loop of the color wheel, which allows 16-bit hues to "roll
over" while still doing the expected thing (and allowing
more precision than the wheel() function that was common to
prior DotStar and NeoPixel examples).
@param sat Saturation, 8-bit value, 0 (min or pure grayscale) to 255
(max or pure hue). Default of 255 if unspecified.
@param val Value (brightness), 8-bit value, 0 (min / black / off) to
255 (max or full brightness). Default of 255 if unspecified.
@return Packed 32-bit RGB color. Result is linearly but not perceptually
correct, so you may want to pass the result through the gamma32()
function (or your own gamma-correction operation) else colors may
appear washed out. This is not done automatically by this
function because coders may desire a more refined gamma-
correction function than the simplified one-size-fits-all
operation of gamma32(). Diffusing the LEDs also really seems to
help when using low-saturation colors.
*/
uint32_t Adafruit_DotStar::ColorHSV(uint16_t hue, uint8_t sat, uint8_t val) {
uint8_t r, g, b;
// Remap 0-65535 to 0-1529. Pure red is CENTERED on the 64K rollover;
// 0 is not the start of pure red, but the midpoint...a few values above
// zero and a few below 65536 all yield pure red (similarly, 32768 is the
// midpoint, not start, of pure cyan). The 8-bit RGB hexcone (256 values
// each for red, green, blue) really only allows for 1530 distinct hues
// (not 1536, more on that below), but the full unsigned 16-bit type was
// chosen for hue so that one's code can easily handle a contiguous color
// wheel by allowing hue to roll over in either direction.
hue = (hue * 1530L + 32768) / 65536;
// Because red is centered on the rollover point (the +32768 above,
// essentially a fixed-point +0.5), the above actually yields 0 to 1530,
// where 0 and 1530 would yield the same thing. Rather than apply a
// costly modulo operator, 1530 is handled as a special case below.
// So you'd think that the color "hexcone" (the thing that ramps from
// pure red, to pure yellow, to pure green and so forth back to red,
// yielding six slices), and with each color component having 256
// possible values (0-255), might have 1536 possible items (6*256),
// but in reality there's 1530. This is because the last element in
// each 256-element slice is equal to the first element of the next
// slice, and keeping those in there this would create small
// discontinuities in the color wheel. So the last element of each
// slice is dropped...we regard only elements 0-254, with item 255
// being picked up as element 0 of the next slice. Like this:
// Red to not-quite-pure-yellow is: 255, 0, 0 to 255, 254, 0
// Pure yellow to not-quite-pure-green is: 255, 255, 0 to 1, 255, 0
// Pure green to not-quite-pure-cyan is: 0, 255, 0 to 0, 255, 254
// and so forth. Hence, 1530 distinct hues (0 to 1529), and hence why
// the constants below are not the multiples of 256 you might expect.
// Convert hue to R,G,B (nested ifs faster than divide+mod+switch):
if (hue < 510) { // Red to Green-1
b = 0;
if (hue < 255) { // Red to Yellow-1
r = 255;
g = hue; // g = 0 to 254
} else { // Yellow to Green-1
r = 510 - hue; // r = 255 to 1
g = 255;
}
} else if (hue < 1020) { // Green to Blue-1
r = 0;
if (hue < 765) { // Green to Cyan-1
g = 255;
b = hue - 510; // b = 0 to 254
} else { // Cyan to Blue-1
g = 1020 - hue; // g = 255 to 1
b = 255;
}
} else if (hue < 1530) { // Blue to Red-1
g = 0;
if (hue < 1275) { // Blue to Magenta-1
r = hue - 1020; // r = 0 to 254
b = 255;
} else { // Magenta to Red-1
r = 255;
b = 1530 - hue; // b = 255 to 1
}
} else { // Last 0.5 Red (quicker than % operator)
r = 255;
g = b = 0;
}
// Apply saturation and value to R,G,B, pack into 32-bit result:
uint32_t v1 = 1 + val; // 1 to 256; allows >>8 instead of /255
uint16_t s1 = 1 + sat; // 1 to 256; same reason
uint8_t s2 = 255 - sat; // 255 to 0
return ((((((r * s1) >> 8) + s2) * v1) & 0xff00) << 8) |
(((((g * s1) >> 8) + s2) * v1) & 0xff00) |
(((((b * s1) >> 8) + s2) * v1) >> 8);
}
/*!
@brief Query the color of a previously-set pixel.
@param n Index of pixel to read (0 = first).
@return 'Packed' 32-bit RGB value. Most significant byte is 0, second is
is red, then green, and least significant byte is blue.
*/
uint32_t Adafruit_DotStar::getPixelColor(uint16_t n) const {
if (n >= numLEDs)
return 0;
uint8_t *p = &pixels[n * 3];
return ((uint32_t)p[rOffset] << 16) | ((uint32_t)p[gOffset] << 8) |
(uint32_t)p[bOffset];
}
/*!
@brief Adjust output brightness. Does not immediately affect what's
currently displayed on the LEDs. The next call to show() will
refresh the LEDs at this level.
@param b Brightness setting, 0=minimum (off), 255=brightest.
@note For various reasons I think brightness is better handled in
one's sketch, but it's here for parity with the NeoPixel
library. Good news is that brightness setting in this library
is 'non destructive' -- it's applied as color data is being
issued to the strip, not during setPixelColor(), and also
means that getPixelColor() returns the exact value originally
stored.
*/
void Adafruit_DotStar::setBrightness(uint8_t b) {
// Stored brightness value is different than what's passed. This
// optimizes the actual scaling math later, allowing a fast 8x8-bit
// multiply and taking the MSB. 'brightness' is a uint8_t, adding 1
// here may (intentionally) roll over...so 0 = max brightness (color
// values are interpreted literally; no scaling), 1 = min brightness
// (off), 255 = just below max brightness.
brightness = b + 1;
}
/*!
@brief Retrieve the last-set brightness value for the strip.
@return Brightness value: 0 = minimum (off), 255 = maximum.
*/
uint8_t Adafruit_DotStar::getBrightness(void) const {
return brightness - 1; // Reverse above operation
}
/*!
@brief A gamma-correction function for 32-bit packed RGB colors.
Makes color transitions appear more perceptially correct.
@param x 32-bit packed RGB color.
@return Gamma-adjusted packed color, can then be passed in one of the
setPixelColor() functions. Like gamma8(), this uses a fixed
gamma correction exponent of 2.6, which seems reasonably okay
for average DotStars in average tasks. If you need finer
control you'll need to provide your own gamma-correction
function instead.
*/
uint32_t Adafruit_DotStar::gamma32(uint32_t x) {
uint8_t *y = (uint8_t *)&x;
// All four bytes of a 32-bit value are filtered to avoid a bunch of
// shifting and masking that would be necessary for properly handling
// different endianisms (and each byte is a fairly trivial operation,
// so it might not even be wasting cycles vs a check and branch.
// In theory this might cause trouble *if* someone's storing information
// in the unused most significant byte of an RGB value, but this seems
// exceedingly rare and if it's encountered in reality they can mask
// values going in or coming out.
for (uint8_t i = 0; i < 4; i++)
y[i] = gamma8(y[i]);
return x; // Packed 32-bit return
}

View File

@ -0,0 +1,211 @@
/*!
* @file Adafruit_DotStar.h
*
* This file is part of the Adafruit_DotStar library.
*
* Adafruit_DotStar is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Adafruit_DotStar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with DotStar. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef _ADAFRUIT_DOT_STAR_H_
#define _ADAFRUIT_DOT_STAR_H_
#if (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#include <pins_arduino.h>
#endif
// Color-order flag for LED pixels (optional extra parameter to constructor):
// Bits 0,1 = R index (0-2), bits 2,3 = G index, bits 4,5 = B index
#define DOTSTAR_RGB (0 | (1 << 2) | (2 << 4)) ///< Transmit as R,G,B
#define DOTSTAR_RBG (0 | (2 << 2) | (1 << 4)) ///< Transmit as R,B,G
#define DOTSTAR_GRB (1 | (0 << 2) | (2 << 4)) ///< Transmit as G,R,B
#define DOTSTAR_GBR (2 | (0 << 2) | (1 << 4)) ///< Transmit as G,B,R
#define DOTSTAR_BRG (1 | (2 << 2) | (0 << 4)) ///< Transmit as B,R,G
#define DOTSTAR_BGR (2 | (1 << 2) | (0 << 4)) ///< Transmit as B,G,R
#define DOTSTAR_MONO 0 ///< Single-color strip WIP DO NOT USE, use RGB for now
// These two tables are declared outside the Adafruit_DotStar class
// because some boards may require oldschool compilers that don't
// handle the C++11 constexpr keyword.
/* A PROGMEM (flash mem) table containing 8-bit unsigned sine wave (0-255).
Copy & paste this snippet into a Python REPL to regenerate:
import math
for x in range(256):
print("{:3},".format(int((math.sin(x/128.0*math.pi)+1.0)*127.5+0.5))),
if x&15 == 15: print
*/
static const uint8_t PROGMEM _DotStarSineTable[256] = {
128, 131, 134, 137, 140, 143, 146, 149, 152, 155, 158, 162, 165, 167, 170,
173, 176, 179, 182, 185, 188, 190, 193, 196, 198, 201, 203, 206, 208, 211,
213, 215, 218, 220, 222, 224, 226, 228, 230, 232, 234, 235, 237, 238, 240,
241, 243, 244, 245, 246, 248, 249, 250, 250, 251, 252, 253, 253, 254, 254,
254, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 253, 253, 252, 251,
250, 250, 249, 248, 246, 245, 244, 243, 241, 240, 238, 237, 235, 234, 232,
230, 228, 226, 224, 222, 220, 218, 215, 213, 211, 208, 206, 203, 201, 198,
196, 193, 190, 188, 185, 182, 179, 176, 173, 170, 167, 165, 162, 158, 155,
152, 149, 146, 143, 140, 137, 134, 131, 128, 124, 121, 118, 115, 112, 109,
106, 103, 100, 97, 93, 90, 88, 85, 82, 79, 76, 73, 70, 67, 65,
62, 59, 57, 54, 52, 49, 47, 44, 42, 40, 37, 35, 33, 31, 29,
27, 25, 23, 21, 20, 18, 17, 15, 14, 12, 11, 10, 9, 7, 6,
5, 5, 4, 3, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 2, 2, 3, 4, 5, 5, 6, 7, 9, 10, 11,
12, 14, 15, 17, 18, 20, 21, 23, 25, 27, 29, 31, 33, 35, 37,
40, 42, 44, 47, 49, 52, 54, 57, 59, 62, 65, 67, 70, 73, 76,
79, 82, 85, 88, 90, 93, 97, 100, 103, 106, 109, 112, 115, 118, 121,
124};
/* Similar to above, but for an 8-bit gamma-correction table.
Copy & paste this snippet into a Python REPL to regenerate:
import math
gamma=2.6
for x in range(256):
print("{:3},".format(int(math.pow((x)/255.0,gamma)*255.0+0.5))),
if x&15 == 15: print
*/
static const uint8_t PROGMEM _DotStarGammaTable[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3,
3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10,
11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 17,
17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25,
25, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33, 34, 34, 35,
36, 37, 38, 38, 39, 40, 41, 42, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 68, 69, 70, 71, 72, 73, 75, 76, 77, 78, 80, 81,
82, 84, 85, 86, 88, 89, 90, 92, 93, 94, 96, 97, 99, 100, 102,
103, 105, 106, 108, 109, 111, 112, 114, 115, 117, 119, 120, 122, 124, 125,
127, 129, 130, 132, 134, 136, 137, 139, 141, 143, 145, 146, 148, 150, 152,
154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182,
184, 186, 188, 191, 193, 195, 197, 199, 202, 204, 206, 209, 211, 213, 215,
218, 220, 223, 225, 227, 230, 232, 235, 237, 240, 242, 245, 247, 250, 252,
255};
/*!
@brief Class that stores state and functions for interacting with
Adafruit DotStars and compatible devices.
*/
class Adafruit_DotStar {
public:
Adafruit_DotStar(uint16_t n, uint8_t o = DOTSTAR_BRG);
Adafruit_DotStar(uint16_t n, uint8_t d, uint8_t c, uint8_t o = DOTSTAR_BRG);
~Adafruit_DotStar(void);
void begin(void);
void show(void);
void setPixelColor(uint16_t n, uint32_t c);
void setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b);
void fill(uint32_t c = 0, uint16_t first = 0, uint16_t count = 0);
void setBrightness(uint8_t);
void clear();
void updateLength(uint16_t n);
void updatePins(void);
void updatePins(uint8_t d, uint8_t c);
/*!
@brief Get a pointer directly to the DotStar data buffer in RAM.
Pixel data is stored in a device-native format (a la the
DOTSTAR_* constants) and is not translated here. Applications
that access this buffer will need to be aware of the specific
data format and handle colors appropriately.
@return Pointer to DotStar buffer (uint8_t* array).
@note This is for high-performance applications where calling
setPixelColor() on every single pixel would be too slow (e.g.
POV or light-painting projects). There is no bounds checking
on the array, creating tremendous potential for mayhem if one
writes past the ends of the buffer. Great power, great
responsibility and all that.
*/
uint8_t *getPixels(void) const { return pixels; };
uint8_t getBrightness(void) const;
/*!
@brief Return the number of pixels in an Adafruit_DotStar strip object.
@return Pixel count (0 if not set).
*/
uint16_t numPixels(void) const { return numLEDs; };
uint32_t getPixelColor(uint16_t n) const;
/*!
@brief An 8-bit integer sine wave function, not directly compatible
with standard trigonometric units like radians or degrees.
@param x Input angle, 0-255; 256 would loop back to zero, completing
the circle (equivalent to 360 degrees or 2 pi radians).
One can therefore use an unsigned 8-bit variable and simply
add or subtract, allowing it to overflow/underflow and it
still does the expected contiguous thing.
@return Sine result, 0 to 255, or -128 to +127 if type-converted to
a signed int8_t, but you'll most likely want unsigned as this
output is often used for pixel brightness in animation effects.
*/
static uint8_t sine8(uint8_t x) {
return pgm_read_byte(&_DotStarSineTable[x]); // 0-255 in, 0-255 out
}
/*!
@brief An 8-bit gamma-correction function for basic pixel brightness
adjustment. Makes color transitions appear more perceptially
correct.
@param x Input brightness, 0 (minimum or off/black) to 255 (maximum).
@return Gamma-adjusted brightness, can then be passed to one of the
setPixelColor() functions. This uses a fixed gamma correction
exponent of 2.6, which seems reasonably okay for average
DotStars in average tasks. If you need finer control you'll
need to provide your own gamma-correction function instead.
*/
static uint8_t gamma8(uint8_t x) {
return pgm_read_byte(&_DotStarGammaTable[x]); // 0-255 in, 0-255 out
}
/*!
@brief Convert separate red, green and blue values into a single
"packed" 32-bit RGB color.
@param r Red brightness, 0 to 255.
@param g Green brightness, 0 to 255.
@param b Blue brightness, 0 to 255.
@return 32-bit packed RGB value, which can then be assigned to a
variable for later use or passed to the setPixelColor()
function. Packed RGB format is predictable, regardless of
LED strand color order.
*/
static uint32_t Color(uint8_t r, uint8_t g, uint8_t b) {
return ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
}
static uint32_t ColorHSV(uint16_t hue, uint8_t sat = 255, uint8_t val = 255);
static uint32_t gamma32(uint32_t x);
private:
uint16_t numLEDs; ///< Number of pixels
uint8_t dataPin; ///< If soft SPI, data pin #
uint8_t clockPin; ///< If soft SPI, clock pin #
uint8_t brightness; ///< Global brightness setting
uint8_t *pixels; ///< LED RGB values (3 bytes ea.)
uint8_t rOffset; ///< Index of red in 3-byte pixel
uint8_t gOffset; ///< Index of green byte
uint8_t bOffset; ///< Index of blue byte
#ifdef __AVR__
uint8_t dataPinMask; ///< If soft SPI, data pin bitmask
uint8_t clockPinMask; ///< If soft SPI, clock pin bitmask
volatile uint8_t *dataPort; ///< If soft SPI, data PORT
volatile uint8_t *clockPort; ///< If soft SPI, clock PORT
#endif
void hw_spi_init(void); ///< Start hardware SPI
void hw_spi_end(void); ///< Stop hardware SPI
void sw_spi_init(void); ///< Start bitbang SPI
void sw_spi_out(uint8_t n); ///< Bitbang SPI write
void sw_spi_end(void); ///< Stop bitbang SPI
};
#endif // _ADAFRUIT_DOT_STAR_H_

View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,366 @@
/*!
* @file Adafruit_NeoPixel.h
*
* This is part of Adafruit's NeoPixel library for the Arduino platform,
* allowing a broad range of microcontroller boards (most AVR boards,
* many ARM devices, ESP8266 and ESP32, among others) to control Adafruit
* NeoPixels, FLORA RGB Smart Pixels and compatible devices -- WS2811,
* WS2812, WS2812B, SK6812, etc.
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing products
* from Adafruit!
*
* Written by Phil "Paint Your Dragon" Burgess for Adafruit Industries,
* with contributions by PJRC, Michael Miller and other members of the
* open source community.
*
* This file is part of the Adafruit_NeoPixel library.
*
* Adafruit_NeoPixel is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Adafruit_NeoPixel is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with NeoPixel. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#ifndef ADAFRUIT_NEOPIXEL_H
#define ADAFRUIT_NEOPIXEL_H
#ifdef ARDUINO
#if (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#include <pins_arduino.h>
#endif
#endif
#ifdef TARGET_LPC1768
#include <Arduino.h>
#endif
// The order of primary colors in the NeoPixel data stream can vary among
// device types, manufacturers and even different revisions of the same
// item. The third parameter to the Adafruit_NeoPixel constructor encodes
// the per-pixel byte offsets of the red, green and blue primaries (plus
// white, if present) in the data stream -- the following #defines provide
// an easier-to-use named version for each permutation. e.g. NEO_GRB
// indicates a NeoPixel-compatible device expecting three bytes per pixel,
// with the first byte transmitted containing the green value, second
// containing red and third containing blue. The in-memory representation
// of a chain of NeoPixels is the same as the data-stream order; no
// re-ordering of bytes is required when issuing data to the chain.
// Most of these values won't exist in real-world devices, but it's done
// this way so we're ready for it (also, if using the WS2811 driver IC,
// one might have their pixels set up in any weird permutation).
// Bits 5,4 of this value are the offset (0-3) from the first byte of a
// pixel to the location of the red color byte. Bits 3,2 are the green
// offset and 1,0 are the blue offset. If it is an RGBW-type device
// (supporting a white primary in addition to R,G,B), bits 7,6 are the
// offset to the white byte...otherwise, bits 7,6 are set to the same value
// as 5,4 (red) to indicate an RGB (not RGBW) device.
// i.e. binary representation:
// 0bWWRRGGBB for RGBW devices
// 0bRRRRGGBB for RGB
// RGB NeoPixel permutations; white and red offsets are always same
// Offset: W R G B
#define NEO_RGB ((0<<6) | (0<<4) | (1<<2) | (2)) ///< Transmit as R,G,B
#define NEO_RBG ((0<<6) | (0<<4) | (2<<2) | (1)) ///< Transmit as R,B,G
#define NEO_GRB ((1<<6) | (1<<4) | (0<<2) | (2)) ///< Transmit as G,R,B
#define NEO_GBR ((2<<6) | (2<<4) | (0<<2) | (1)) ///< Transmit as G,B,R
#define NEO_BRG ((1<<6) | (1<<4) | (2<<2) | (0)) ///< Transmit as B,R,G
#define NEO_BGR ((2<<6) | (2<<4) | (1<<2) | (0)) ///< Transmit as B,G,R
// RGBW NeoPixel permutations; all 4 offsets are distinct
// Offset: W R G B
#define NEO_WRGB ((0<<6) | (1<<4) | (2<<2) | (3)) ///< Transmit as W,R,G,B
#define NEO_WRBG ((0<<6) | (1<<4) | (3<<2) | (2)) ///< Transmit as W,R,B,G
#define NEO_WGRB ((0<<6) | (2<<4) | (1<<2) | (3)) ///< Transmit as W,G,R,B
#define NEO_WGBR ((0<<6) | (3<<4) | (1<<2) | (2)) ///< Transmit as W,G,B,R
#define NEO_WBRG ((0<<6) | (2<<4) | (3<<2) | (1)) ///< Transmit as W,B,R,G
#define NEO_WBGR ((0<<6) | (3<<4) | (2<<2) | (1)) ///< Transmit as W,B,G,R
#define NEO_RWGB ((1<<6) | (0<<4) | (2<<2) | (3)) ///< Transmit as R,W,G,B
#define NEO_RWBG ((1<<6) | (0<<4) | (3<<2) | (2)) ///< Transmit as R,W,B,G
#define NEO_RGWB ((2<<6) | (0<<4) | (1<<2) | (3)) ///< Transmit as R,G,W,B
#define NEO_RGBW ((3<<6) | (0<<4) | (1<<2) | (2)) ///< Transmit as R,G,B,W
#define NEO_RBWG ((2<<6) | (0<<4) | (3<<2) | (1)) ///< Transmit as R,B,W,G
#define NEO_RBGW ((3<<6) | (0<<4) | (2<<2) | (1)) ///< Transmit as R,B,G,W
#define NEO_GWRB ((1<<6) | (2<<4) | (0<<2) | (3)) ///< Transmit as G,W,R,B
#define NEO_GWBR ((1<<6) | (3<<4) | (0<<2) | (2)) ///< Transmit as G,W,B,R
#define NEO_GRWB ((2<<6) | (1<<4) | (0<<2) | (3)) ///< Transmit as G,R,W,B
#define NEO_GRBW ((3<<6) | (1<<4) | (0<<2) | (2)) ///< Transmit as G,R,B,W
#define NEO_GBWR ((2<<6) | (3<<4) | (0<<2) | (1)) ///< Transmit as G,B,W,R
#define NEO_GBRW ((3<<6) | (2<<4) | (0<<2) | (1)) ///< Transmit as G,B,R,W
#define NEO_BWRG ((1<<6) | (2<<4) | (3<<2) | (0)) ///< Transmit as B,W,R,G
#define NEO_BWGR ((1<<6) | (3<<4) | (2<<2) | (0)) ///< Transmit as B,W,G,R
#define NEO_BRWG ((2<<6) | (1<<4) | (3<<2) | (0)) ///< Transmit as B,R,W,G
#define NEO_BRGW ((3<<6) | (1<<4) | (2<<2) | (0)) ///< Transmit as B,R,G,W
#define NEO_BGWR ((2<<6) | (3<<4) | (1<<2) | (0)) ///< Transmit as B,G,W,R
#define NEO_BGRW ((3<<6) | (2<<4) | (1<<2) | (0)) ///< Transmit as B,G,R,W
// Add NEO_KHZ400 to the color order value to indicate a 400 KHz device.
// All but the earliest v1 NeoPixels expect an 800 KHz data stream, this is
// the default if unspecified. Because flash space is very limited on ATtiny
// devices (e.g. Trinket, Gemma), v1 NeoPixels aren't handled by default on
// those chips, though it can be enabled by removing the ifndef/endif below,
// but code will be bigger. Conversely, can disable the NEO_KHZ400 line on
// other MCUs to remove v1 support and save a little space.
#define NEO_KHZ800 0x0000 ///< 800 KHz data transmission
#ifndef __AVR_ATtiny85__
#define NEO_KHZ400 0x0100 ///< 400 KHz data transmission
#endif
// If 400 KHz support is enabled, the third parameter to the constructor
// requires a 16-bit value (in order to select 400 vs 800 KHz speed).
// If only 800 KHz is enabled (as is default on ATtiny), an 8-bit value
// is sufficient to encode pixel color order, saving some space.
#ifdef NEO_KHZ400
typedef uint16_t neoPixelType; ///< 3rd arg to Adafruit_NeoPixel constructor
#else
typedef uint8_t neoPixelType; ///< 3rd arg to Adafruit_NeoPixel constructor
#endif
// These two tables are declared outside the Adafruit_NeoPixel class
// because some boards may require oldschool compilers that don't
// handle the C++11 constexpr keyword.
/* A PROGMEM (flash mem) table containing 8-bit unsigned sine wave (0-255).
Copy & paste this snippet into a Python REPL to regenerate:
import math
for x in range(256):
print("{:3},".format(int((math.sin(x/128.0*math.pi)+1.0)*127.5+0.5))),
if x&15 == 15: print
*/
static const uint8_t PROGMEM _NeoPixelSineTable[256] = {
128,131,134,137,140,143,146,149,152,155,158,162,165,167,170,173,
176,179,182,185,188,190,193,196,198,201,203,206,208,211,213,215,
218,220,222,224,226,228,230,232,234,235,237,238,240,241,243,244,
245,246,248,249,250,250,251,252,253,253,254,254,254,255,255,255,
255,255,255,255,254,254,254,253,253,252,251,250,250,249,248,246,
245,244,243,241,240,238,237,235,234,232,230,228,226,224,222,220,
218,215,213,211,208,206,203,201,198,196,193,190,188,185,182,179,
176,173,170,167,165,162,158,155,152,149,146,143,140,137,134,131,
128,124,121,118,115,112,109,106,103,100, 97, 93, 90, 88, 85, 82,
79, 76, 73, 70, 67, 65, 62, 59, 57, 54, 52, 49, 47, 44, 42, 40,
37, 35, 33, 31, 29, 27, 25, 23, 21, 20, 18, 17, 15, 14, 12, 11,
10, 9, 7, 6, 5, 5, 4, 3, 2, 2, 1, 1, 1, 0, 0, 0,
0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 4, 5, 5, 6, 7, 9,
10, 11, 12, 14, 15, 17, 18, 20, 21, 23, 25, 27, 29, 31, 33, 35,
37, 40, 42, 44, 47, 49, 52, 54, 57, 59, 62, 65, 67, 70, 73, 76,
79, 82, 85, 88, 90, 93, 97,100,103,106,109,112,115,118,121,124};
/* Similar to above, but for an 8-bit gamma-correction table.
Copy & paste this snippet into a Python REPL to regenerate:
import math
gamma=2.6
for x in range(256):
print("{:3},".format(int(math.pow((x)/255.0,gamma)*255.0+0.5))),
if x&15 == 15: print
*/
static const uint8_t PROGMEM _NeoPixelGammaTable[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3,
3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7,
7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12,
13, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20,
20, 21, 21, 22, 22, 23, 24, 24, 25, 25, 26, 27, 27, 28, 29, 29,
30, 31, 31, 32, 33, 34, 34, 35, 36, 37, 38, 38, 39, 40, 41, 42,
42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
58, 59, 60, 61, 62, 63, 64, 65, 66, 68, 69, 70, 71, 72, 73, 75,
76, 77, 78, 80, 81, 82, 84, 85, 86, 88, 89, 90, 92, 93, 94, 96,
97, 99,100,102,103,105,106,108,109,111,112,114,115,117,119,120,
122,124,125,127,129,130,132,134,136,137,139,141,143,145,146,148,
150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,
182,184,186,188,191,193,195,197,199,202,204,206,209,211,213,215,
218,220,223,225,227,230,232,235,237,240,242,245,247,250,252,255};
/*!
@brief Class that stores state and functions for interacting with
Adafruit NeoPixels and compatible devices.
*/
class Adafruit_NeoPixel {
public:
// Constructor: number of LEDs, pin number, LED type
Adafruit_NeoPixel(uint16_t n, uint16_t pin=6,
neoPixelType type=NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel(void);
~Adafruit_NeoPixel();
void begin(void);
void show(void);
void setPin(uint16_t p);
void setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b);
void setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b,
uint8_t w);
void setPixelColor(uint16_t n, uint32_t c);
void fill(uint32_t c=0, uint16_t first=0, uint16_t count=0);
void setBrightness(uint8_t);
void clear(void);
void updateLength(uint16_t n);
void updateType(neoPixelType t);
/*!
@brief Check whether a call to show() will start sending data
immediately or will 'block' for a required interval. NeoPixels
require a short quiet time (about 300 microseconds) after the
last bit is received before the data 'latches' and new data can
start being received. Usually one's sketch is implicitly using
this time to generate a new frame of animation...but if it
finishes very quickly, this function could be used to see if
there's some idle time available for some low-priority
concurrent task.
@return 1 or true if show() will start sending immediately, 0 or false
if show() would block (meaning some idle time is available).
*/
bool canShow(void) {
if (endTime > micros()) {
endTime = micros();
}
return (micros() - endTime) >= 300L;
}
/*!
@brief Get a pointer directly to the NeoPixel data buffer in RAM.
Pixel data is stored in a device-native format (a la the NEO_*
constants) and is not translated here. Applications that access
this buffer will need to be aware of the specific data format
and handle colors appropriately.
@return Pointer to NeoPixel buffer (uint8_t* array).
@note This is for high-performance applications where calling
setPixelColor() on every single pixel would be too slow (e.g.
POV or light-painting projects). There is no bounds checking
on the array, creating tremendous potential for mayhem if one
writes past the ends of the buffer. Great power, great
responsibility and all that.
*/
uint8_t *getPixels(void) const { return pixels; };
uint8_t getBrightness(void) const;
/*!
@brief Retrieve the pin number used for NeoPixel data output.
@return Arduino pin number (-1 if not set).
*/
int16_t getPin(void) const { return pin; };
/*!
@brief Return the number of pixels in an Adafruit_NeoPixel strip object.
@return Pixel count (0 if not set).
*/
uint16_t numPixels(void) const { return numLEDs; }
uint32_t getPixelColor(uint16_t n) const;
/*!
@brief An 8-bit integer sine wave function, not directly compatible
with standard trigonometric units like radians or degrees.
@param x Input angle, 0-255; 256 would loop back to zero, completing
the circle (equivalent to 360 degrees or 2 pi radians).
One can therefore use an unsigned 8-bit variable and simply
add or subtract, allowing it to overflow/underflow and it
still does the expected contiguous thing.
@return Sine result, 0 to 255, or -128 to +127 if type-converted to
a signed int8_t, but you'll most likely want unsigned as this
output is often used for pixel brightness in animation effects.
*/
static uint8_t sine8(uint8_t x) {
return pgm_read_byte(&_NeoPixelSineTable[x]); // 0-255 in, 0-255 out
}
/*!
@brief An 8-bit gamma-correction function for basic pixel brightness
adjustment. Makes color transitions appear more perceptially
correct.
@param x Input brightness, 0 (minimum or off/black) to 255 (maximum).
@return Gamma-adjusted brightness, can then be passed to one of the
setPixelColor() functions. This uses a fixed gamma correction
exponent of 2.6, which seems reasonably okay for average
NeoPixels in average tasks. If you need finer control you'll
need to provide your own gamma-correction function instead.
*/
static uint8_t gamma8(uint8_t x) {
return pgm_read_byte(&_NeoPixelGammaTable[x]); // 0-255 in, 0-255 out
}
/*!
@brief Convert separate red, green and blue values into a single
"packed" 32-bit RGB color.
@param r Red brightness, 0 to 255.
@param g Green brightness, 0 to 255.
@param b Blue brightness, 0 to 255.
@return 32-bit packed RGB value, which can then be assigned to a
variable for later use or passed to the setPixelColor()
function. Packed RGB format is predictable, regardless of
LED strand color order.
*/
static uint32_t Color(uint8_t r, uint8_t g, uint8_t b) {
return ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
}
/*!
@brief Convert separate red, green, blue and white values into a
single "packed" 32-bit WRGB color.
@param r Red brightness, 0 to 255.
@param g Green brightness, 0 to 255.
@param b Blue brightness, 0 to 255.
@param w White brightness, 0 to 255.
@return 32-bit packed WRGB value, which can then be assigned to a
variable for later use or passed to the setPixelColor()
function. Packed WRGB format is predictable, regardless of
LED strand color order.
*/
static uint32_t Color(uint8_t r, uint8_t g, uint8_t b, uint8_t w) {
return ((uint32_t)w << 24) | ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
}
static uint32_t ColorHSV(uint16_t hue, uint8_t sat=255, uint8_t val=255);
/*!
@brief A gamma-correction function for 32-bit packed RGB or WRGB
colors. Makes color transitions appear more perceptially
correct.
@param x 32-bit packed RGB or WRGB color.
@return Gamma-adjusted packed color, can then be passed in one of the
setPixelColor() functions. Like gamma8(), this uses a fixed
gamma correction exponent of 2.6, which seems reasonably okay
for average NeoPixels in average tasks. If you need finer
control you'll need to provide your own gamma-correction
function instead.
*/
static uint32_t gamma32(uint32_t x);
protected:
#ifdef NEO_KHZ400 // If 400 KHz NeoPixel support enabled...
bool is800KHz; ///< true if 800 KHz pixels
#endif
bool begun; ///< true if begin() previously called
uint16_t numLEDs; ///< Number of RGB LEDs in strip
uint16_t numBytes; ///< Size of 'pixels' buffer below
int16_t pin; ///< Output pin number (-1 if not yet set)
uint8_t brightness; ///< Strip brightness 0-255 (stored as +1)
uint8_t *pixels; ///< Holds LED color values (3 or 4 bytes each)
uint8_t rOffset; ///< Red index within each 3- or 4-byte pixel
uint8_t gOffset; ///< Index of green byte
uint8_t bOffset; ///< Index of blue byte
uint8_t wOffset; ///< Index of white (==rOffset if no white)
uint32_t endTime; ///< Latch timing reference
#ifdef __AVR__
volatile uint8_t *port; ///< Output PORT register
uint8_t pinMask; ///< Output PORT bitmask
#endif
#if defined(ARDUINO_ARCH_STM32) || defined(ARDUINO_ARCH_ARDUINO_CORE_STM32)
GPIO_TypeDef *gpioPort; ///< Output GPIO PORT
uint32_t gpioPin; ///< Output GPIO PIN
#endif
};
#endif // ADAFRUIT_NEOPIXEL_H

View File

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

View File

@ -0,0 +1,86 @@
// This is a mash-up of the Due show() code + insights from Michael Miller's
// ESP8266 work for the NeoPixelBus library: github.com/Makuna/NeoPixelBus
// Needs to be a separate .c file to enforce ICACHE_RAM_ATTR execution.
#if defined(ESP8266)
#include <Arduino.h>
#ifdef ESP8266
#include <eagle_soc.h>
#endif
static uint32_t _getCycleCount(void) __attribute__((always_inline));
static inline uint32_t _getCycleCount(void) {
uint32_t ccount;
__asm__ __volatile__("rsr %0,ccount":"=a" (ccount));
return ccount;
}
#ifdef ESP8266
void ICACHE_RAM_ATTR espShow(
uint8_t pin, uint8_t *pixels, uint32_t numBytes, boolean is800KHz) {
#else
void espShow(
uint8_t pin, uint8_t *pixels, uint32_t numBytes, boolean is800KHz) {
#endif
#define CYCLES_800_T0H (F_CPU / 2500000) // 0.4us
#define CYCLES_800_T1H (F_CPU / 1250000) // 0.8us
#define CYCLES_800 (F_CPU / 800000) // 1.25us per bit
#define CYCLES_400_T0H (F_CPU / 2000000) // 0.5uS
#define CYCLES_400_T1H (F_CPU / 833333) // 1.2us
#define CYCLES_400 (F_CPU / 400000) // 2.5us per bit
uint8_t *p, *end, pix, mask;
uint32_t t, time0, time1, period, c, startTime;
#ifdef ESP8266
uint32_t pinMask;
pinMask = _BV(pin);
#endif
p = pixels;
end = p + numBytes;
pix = *p++;
mask = 0x80;
startTime = 0;
#ifdef NEO_KHZ400
if(is800KHz) {
#endif
time0 = CYCLES_800_T0H;
time1 = CYCLES_800_T1H;
period = CYCLES_800;
#ifdef NEO_KHZ400
} else { // 400 KHz bitstream
time0 = CYCLES_400_T0H;
time1 = CYCLES_400_T1H;
period = CYCLES_400;
}
#endif
for(t = time0;; t = time0) {
if(pix & mask) t = time1; // Bit high duration
while(((c = _getCycleCount()) - startTime) < period); // Wait for bit start
#ifdef ESP8266
GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, pinMask); // Set high
#else
gpio_set_level(pin, HIGH);
#endif
startTime = c; // Save start time
while(((c = _getCycleCount()) - startTime) < t); // Wait high duration
#ifdef ESP8266
GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, pinMask); // Set low
#else
gpio_set_level(pin, LOW);
#endif
if(!(mask >>= 1)) { // Next bit/byte
if(p >= end) break;
pix = *p++;
mask = 0x80;
}
}
while((_getCycleCount() - startTime) < period); // Wait for last bit
}
#endif // ESP8266

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,738 @@
/*
DS3231.cpp: DS3231 Real-Time Clock library
Eric Ayars
4/1/11
Spliced in DateTime all-at-once reading (to avoid rollover) and unix time
from Jean-Claude Wippler and Limor Fried
Andy Wickert
5/15/11
Fixed problem with SD processors(no function call) by replacing all occurences of the term PM, which
is defined as a macro on SAMD controllers by PM_time.
Simon Gassner
11/28/2017
Released into the public domain.
*/
#include "DS3231.h"
// These included for the DateTime class inclusion; will try to find a way to
// not need them in the future...
#if defined(__AVR__)
#include <avr/pgmspace.h>
#elif defined(ESP8266)
#include <pgmspace.h>
#endif // if defined(__AVR__)
// Changed the following to work on 1.0
// #include "WProgram.h"
#include <Arduino.h>
#define CLOCK_ADDRESS 0x68
#define SECONDS_FROM_1970_TO_2000 946684800
// Constructor
DS3231::DS3231() {
// nothing to do for this constructor.
}
// Utilities from JeeLabs/Ladyada
////////////////////////////////////////////////////////////////////////////////
// utility code, some of this could be exposed in the DateTime API if needed
// DS3231 is smart enough to know this, but keeping it for now so I don't have
// to rewrite their code. -ADW
static const uint8_t daysInMonth[] PROGMEM = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// number of days since 2000/01/01, valid for 2001..2099
static uint16_t date2days(uint16_t y, uint8_t m, uint8_t d) {
if (y >= 2000)
y -= 2000;
uint16_t days = d;
for (uint8_t i = 1; i < m; ++i) days += pgm_read_byte(daysInMonth + i - 1);
if ((m > 2) && (y % 4 == 0))
++days;
return days + 365 * y + (y + 3) / 4 - 1;
}
static long time2long(uint16_t days, uint8_t h, uint8_t m, uint8_t s) {
return ((days * 24L + h) * 60 + m) * 60 + s;
}
/*****************************************
Public Functions
*****************************************/
/*******************************************************************************
* TO GET ALL DATE/TIME INFORMATION AT ONCE AND AVOID THE CHANCE OF ROLLOVER
* DateTime implementation spliced in here from Jean-Claude Wippler's (JeeLabs)
* RTClib, as modified by Limor Fried (Ladyada); source code at:
* https://github.com/adafruit/RTClib
******************************************************************************/
////////////////////////////////////////////////////////////////////////////////
// DateTime implementation - ignores time zones and DST changes
// NOTE: also ignores leap seconds, see http://en.wikipedia.org/wiki/Leap_second
DateTime::DateTime(uint32_t t) {
t -= SECONDS_FROM_1970_TO_2000; // bring to 2000 timestamp from 1970
ss = t % 60;
t /= 60;
mm = t % 60;
t /= 60;
hh = t % 24;
uint16_t days = t / 24;
uint8_t leap;
for (yOff = 0;; ++yOff) {
leap = yOff % 4 == 0;
if (days < 365 + leap)
break;
days -= 365 + leap;
}
for (m = 1;; ++m) {
uint8_t daysPerMonth = pgm_read_byte(daysInMonth + m - 1);
if (leap && (m == 2))
++daysPerMonth;
if (days < daysPerMonth)
break;
days -= daysPerMonth;
}
d = days + 1;
}
DateTime::DateTime(uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t min, uint8_t sec) {
if (year >= 2000)
year -= 2000;
yOff = year;
m = month;
d = day;
hh = hour;
mm = min;
ss = sec;
}
static uint8_t conv2d(const char* p) {
uint8_t v = 0;
if (('0' <= *p) && (*p <= '9'))
v = *p - '0';
return 10 * v + *++p - '0';
}
// UNIX time: IS CORRECT ONLY WHEN SET TO UTC!!!
uint32_t DateTime::unixtime(void) const {
uint32_t t;
uint16_t days = date2days(yOff, m, d);
t = time2long(days, hh, mm, ss);
t += SECONDS_FROM_1970_TO_2000; // seconds from 1970 to 2000
return t;
}
// Slightly modified from JeeLabs / Ladyada
// Get all date/time at once to avoid rollover (e.g., minute/second don't match)
static uint8_t bcd2bin(uint8_t val) {
return val - 6 * (val >> 4);
}
static uint8_t bin2bcd(uint8_t val) {
return val + 6 * (val / 10);
}
DateTime RTClib::now() {
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0); // This is the first register address (Seconds)
// We'll read from here on for 7 bytes: secs reg, minutes reg, hours, days, months and years.
Wire.endTransmission();
Wire.requestFrom(CLOCK_ADDRESS, 7);
uint8_t ss = bcd2bin(Wire.read() & 0x7F);
uint8_t mm = bcd2bin(Wire.read());
uint8_t hh = bcd2bin(Wire.read());
Wire.read();
uint8_t d = bcd2bin(Wire.read());
uint8_t m = bcd2bin(Wire.read());
uint16_t y = bcd2bin(Wire.read()) + 2000;
return DateTime(y, m, d, hh, mm, ss);
}
///// ERIC'S ORIGINAL CODE FOLLOWS /////
byte DS3231::getSecond() {
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x00);
Wire.endTransmission();
Wire.requestFrom(CLOCK_ADDRESS, 1);
return bcdToDec(Wire.read());
}
byte DS3231::getMinute() {
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x01);
Wire.endTransmission();
Wire.requestFrom(CLOCK_ADDRESS, 1);
return bcdToDec(Wire.read());
}
byte DS3231::getHour(bool& h12, bool& PM_time) {
byte temp_buffer;
byte hour;
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x02);
Wire.endTransmission();
Wire.requestFrom(CLOCK_ADDRESS, 1);
temp_buffer = Wire.read();
h12 = temp_buffer & 0b01000000;
if (h12) {
PM_time = temp_buffer & 0b00100000;
hour = bcdToDec(temp_buffer & 0b00011111);
} else {
hour = bcdToDec(temp_buffer & 0b00111111);
}
return hour;
}
byte DS3231::getDoW() {
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x03);
Wire.endTransmission();
Wire.requestFrom(CLOCK_ADDRESS, 1);
return bcdToDec(Wire.read());
}
byte DS3231::getDate() {
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x04);
Wire.endTransmission();
Wire.requestFrom(CLOCK_ADDRESS, 1);
return bcdToDec(Wire.read());
}
byte DS3231::getMonth(bool& Century) {
byte temp_buffer;
byte hour;
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x05);
Wire.endTransmission();
Wire.requestFrom(CLOCK_ADDRESS, 1);
temp_buffer = Wire.read();
Century = temp_buffer & 0b10000000;
return bcdToDec(temp_buffer & 0b01111111);
}
byte DS3231::getYear() {
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x06);
Wire.endTransmission();
Wire.requestFrom(CLOCK_ADDRESS, 1);
return bcdToDec(Wire.read());
}
void DS3231::setSecond(byte Second) {
// Sets the seconds
// This function also resets the Oscillator Stop Flag, which is set
// whenever power is interrupted.
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x00);
Wire.write(decToBcd(Second));
Wire.endTransmission();
// Clear OSF flag
byte temp_buffer = readControlByte(1);
writeControlByte((temp_buffer & 0b01111111), 1);
}
void DS3231::setMinute(byte Minute) {
// Sets the minutes
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x01);
Wire.write(decToBcd(Minute));
Wire.endTransmission();
}
void DS3231::setHour(byte Hour) {
// Sets the hour, without changing 12/24h mode.
// The hour must be in 24h format.
bool h12;
// Start by figuring out what the 12/24 mode is
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x02);
Wire.endTransmission();
Wire.requestFrom(CLOCK_ADDRESS, 1);
h12 = (Wire.read() & 0b01000000);
// if h12 is true, it's 12h mode; false is 24h.
if (h12) {
// 12 hour
if (Hour > 12) {
Hour = decToBcd(Hour-12) | 0b01100000;
} else {
Hour = decToBcd(Hour) & 0b11011111;
}
} else {
// 24 hour
Hour = decToBcd(Hour) & 0b10111111;
}
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x02);
Wire.write(Hour);
Wire.endTransmission();
}
void DS3231::setDoW(byte DoW) {
// Sets the Day of Week
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x03);
Wire.write(decToBcd(DoW));
Wire.endTransmission();
}
void DS3231::setDate(byte Date) {
// Sets the Date
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x04);
Wire.write(decToBcd(Date));
Wire.endTransmission();
}
void DS3231::setMonth(byte Month) {
// Sets the month
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x05);
Wire.write(decToBcd(Month));
Wire.endTransmission();
}
void DS3231::setYear(byte Year) {
// Sets the year
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x06);
Wire.write(decToBcd(Year));
Wire.endTransmission();
}
void DS3231::setClockMode(bool h12) {
// sets the mode to 12-hour (true) or 24-hour (false).
// One thing that bothers me about how I've written this is that
// if the read and right happen at the right hourly millisecnd,
// the clock will be set back an hour. Not sure how to do it better,
// though, and as long as one doesn't set the mode frequently it's
// a very minimal risk.
// It's zero risk if you call this BEFORE setting the hour, since
// the setHour() function doesn't change this mode.
byte temp_buffer;
// Start by reading byte 0x02.
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x02);
Wire.endTransmission();
Wire.requestFrom(CLOCK_ADDRESS, 1);
temp_buffer = Wire.read();
// Set the flag to the requested value:
if (h12) {
temp_buffer = temp_buffer | 0b01000000;
} else {
temp_buffer = temp_buffer & 0b10111111;
}
// Write the byte
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x02);
Wire.write(temp_buffer);
Wire.endTransmission();
}
float DS3231::getTemperature() {
// Checks the internal thermometer on the DS3231 and returns the
// temperature as a floating-point value.
// Updated / modified a tiny bit from "Coding Badly" and "Tri-Again"
// http://forum.arduino.cc/index.php/topic,22301.0.html
byte tMSB, tLSB;
float temp3231;
// temp registers (11h-12h) get updated automatically every 64s
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x11);
Wire.endTransmission();
Wire.requestFrom(CLOCK_ADDRESS, 2);
// Should I do more "if available" checks here?
if (Wire.available()) {
tMSB = Wire.read(); // 2's complement int portion
tLSB = Wire.read(); // fraction portion
temp3231 = ((((short)tMSB << 8) | (short)tLSB) >> 6) / 4.0;
}
else {
temp3231 = -9999; // Some obvious error value
}
return temp3231;
}
void DS3231::getA1Time(byte& A1Day, byte& A1Hour, byte& A1Minute, byte& A1Second, byte& AlarmBits, bool& A1Dy, bool& A1h12, bool& A1PM) {
byte temp_buffer;
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x07);
Wire.endTransmission();
Wire.requestFrom(CLOCK_ADDRESS, 4);
temp_buffer = Wire.read(); // Get A1M1 and A1 Seconds
A1Second = bcdToDec(temp_buffer & 0b01111111);
// put A1M1 bit in position 0 of DS3231_AlarmBits.
AlarmBits = AlarmBits | (temp_buffer & 0b10000000)>>7;
temp_buffer = Wire.read(); // Get A1M2 and A1 minutes
A1Minute = bcdToDec(temp_buffer & 0b01111111);
// put A1M2 bit in position 1 of DS3231_AlarmBits.
AlarmBits = AlarmBits | (temp_buffer & 0b10000000)>>6;
temp_buffer = Wire.read(); // Get A1M3 and A1 Hour
// put A1M3 bit in position 2 of DS3231_AlarmBits.
AlarmBits = AlarmBits | (temp_buffer & 0b10000000)>>5;
// determine A1 12/24 mode
A1h12 = temp_buffer & 0b01000000;
if (A1h12) {
A1PM = temp_buffer & 0b00100000; // determine am/pm
A1Hour = bcdToDec(temp_buffer & 0b00011111); // 12-hour
} else {
A1Hour = bcdToDec(temp_buffer & 0b00111111); // 24-hour
}
temp_buffer = Wire.read(); // Get A1M4 and A1 Day/Date
// put A1M3 bit in position 3 of DS3231_AlarmBits.
AlarmBits = AlarmBits | (temp_buffer & 0b10000000)>>4;
// determine A1 day or date flag
A1Dy = (temp_buffer & 0b01000000)>>6;
if (A1Dy) {
// alarm is by day of week, not date.
A1Day = bcdToDec(temp_buffer & 0b00001111);
} else {
// alarm is by date, not day of week.
A1Day = bcdToDec(temp_buffer & 0b00111111);
}
}
void DS3231::getA2Time(byte& A2Day, byte& A2Hour, byte& A2Minute, byte& AlarmBits, bool& A2Dy, bool& A2h12, bool& A2PM) {
byte temp_buffer;
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x0b);
Wire.endTransmission();
Wire.requestFrom(CLOCK_ADDRESS, 3);
temp_buffer = Wire.read(); // Get A2M2 and A2 Minutes
A2Minute = bcdToDec(temp_buffer & 0b01111111);
// put A2M2 bit in position 4 of DS3231_AlarmBits.
AlarmBits = AlarmBits | (temp_buffer & 0b10000000)>>3;
temp_buffer = Wire.read(); // Get A2M3 and A2 Hour
// put A2M3 bit in position 5 of DS3231_AlarmBits.
AlarmBits = AlarmBits | (temp_buffer & 0b10000000)>>2;
// determine A2 12/24 mode
A2h12 = temp_buffer & 0b01000000;
if (A2h12) {
A2PM = temp_buffer & 0b00100000; // determine am/pm
A2Hour = bcdToDec(temp_buffer & 0b00011111); // 12-hour
} else {
A2Hour = bcdToDec(temp_buffer & 0b00111111); // 24-hour
}
temp_buffer = Wire.read(); // Get A2M4 and A1 Day/Date
// put A2M4 bit in position 6 of DS3231_AlarmBits.
AlarmBits = AlarmBits | (temp_buffer & 0b10000000)>>1;
// determine A2 day or date flag
A2Dy = (temp_buffer & 0b01000000)>>6;
if (A2Dy) {
// alarm is by day of week, not date.
A2Day = bcdToDec(temp_buffer & 0b00001111);
} else {
// alarm is by date, not day of week.
A2Day = bcdToDec(temp_buffer & 0b00111111);
}
}
void DS3231::setA1Time(byte A1Day, byte A1Hour, byte A1Minute, byte A1Second, byte AlarmBits, bool A1Dy, bool A1h12, bool A1PM) {
// Sets the alarm-1 date and time on the DS3231, using A1* information
byte temp_buffer;
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x07); // A1 starts at 07h
// Send A1 second and A1M1
Wire.write(decToBcd(A1Second) | ((AlarmBits & 0b00000001) << 7));
// Send A1 Minute and A1M2
Wire.write(decToBcd(A1Minute) | ((AlarmBits & 0b00000010) << 6));
// Figure out A1 hour
if (A1h12) {
// Start by converting existing time to h12 if it was given in 24h.
if (A1Hour > 12) {
// well, then, this obviously isn't a h12 time, is it?
A1Hour = A1Hour - 12;
A1PM = true;
}
if (A1PM) {
// Afternoon
// Convert the hour to BCD and add appropriate flags.
temp_buffer = decToBcd(A1Hour) | 0b01100000;
} else {
// Morning
// Convert the hour to BCD and add appropriate flags.
temp_buffer = decToBcd(A1Hour) | 0b01000000;
}
} else {
// Now for 24h
temp_buffer = decToBcd(A1Hour);
}
temp_buffer = temp_buffer | ((AlarmBits & 0b00000100)<<5);
// A1 hour is figured out, send it
Wire.write(temp_buffer);
// Figure out A1 day/date and A1M4
temp_buffer = ((AlarmBits & 0b00001000)<<4) | decToBcd(A1Day);
if (A1Dy) {
// Set A1 Day/Date flag (Otherwise it's zero)
temp_buffer = temp_buffer | 0b01000000;
}
Wire.write(temp_buffer);
// All done!
Wire.endTransmission();
}
void DS3231::setA2Time(byte A2Day, byte A2Hour, byte A2Minute, byte AlarmBits, bool A2Dy, bool A2h12, bool A2PM) {
// Sets the alarm-2 date and time on the DS3231, using A2* information
byte temp_buffer;
Wire.beginTransmission(CLOCK_ADDRESS);
Wire.write(0x0b); // A1 starts at 0bh
// Send A2 Minute and A2M2
Wire.write(decToBcd(A2Minute) | ((AlarmBits & 0b00010000) << 3));
// Figure out A2 hour
if (A2h12) {
// Start by converting existing time to h12 if it was given in 24h.
if (A2Hour > 12) {
// well, then, this obviously isn't a h12 time, is it?
A2Hour = A2Hour - 12;
A2PM = true;
}
if (A2PM) {
// Afternoon
// Convert the hour to BCD and add appropriate flags.
temp_buffer = decToBcd(A2Hour) | 0b01100000;
} else {
// Morning
// Convert the hour to BCD and add appropriate flags.
temp_buffer = decToBcd(A2Hour) | 0b01000000;
}
} else {
// Now for 24h
temp_buffer = decToBcd(A2Hour);
}
// add in A2M3 bit
temp_buffer = temp_buffer | ((AlarmBits & 0b00100000)<<2);
// A2 hour is figured out, send it
Wire.write(temp_buffer);
// Figure out A2 day/date and A2M4
temp_buffer = ((AlarmBits & 0b01000000)<<1) | decToBcd(A2Day);
if (A2Dy) {
// Set A2 Day/Date flag (Otherwise it's zero)
temp_buffer = temp_buffer | 0b01000000;
}
Wire.write(temp_buffer);
// All done!
Wire.endTransmission();
}
void DS3231::turnOnAlarm(byte Alarm) {
// turns on alarm number "Alarm". Defaults to 2 if Alarm is not 1.
byte temp_buffer = readControlByte(0);
// modify control byte
if (Alarm == 1) {
temp_buffer = temp_buffer | 0b00000101;
} else {
temp_buffer = temp_buffer | 0b00000110;
}
writeControlByte(temp_buffer, 0);
}
void DS3231::turnOffAlarm(byte Alarm) {
// turns off alarm number "Alarm". Defaults to 2 if Alarm is not 1.
// Leaves interrupt pin alone.
byte temp_buffer = readControlByte(0);
// modify control byte
if (Alarm == 1) {
temp_buffer = temp_buffer & 0b11111110;
} else {
temp_buffer = temp_buffer & 0b11111101;
}
writeControlByte(temp_buffer, 0);
}
bool DS3231::checkAlarmEnabled(byte Alarm) {
// Checks whether the given alarm is enabled.
byte result = 0x0;
byte temp_buffer = readControlByte(0);
if (Alarm == 1) {
result = temp_buffer & 0b00000001;
} else {
result = temp_buffer & 0b00000010;
}
return result;
}
bool DS3231::checkIfAlarm(byte Alarm) {
// Checks whether alarm 1 or alarm 2 flag is on, returns T/F accordingly.
// Turns flag off, also.
// defaults to checking alarm 2, unless Alarm == 1.
byte result;
byte temp_buffer = readControlByte(1);
if (Alarm == 1) {
// Did alarm 1 go off?
result = temp_buffer & 0b00000001;
// clear flag
temp_buffer = temp_buffer & 0b11111110;
} else {
// Did alarm 2 go off?
result = temp_buffer & 0b00000010;
// clear flag
temp_buffer = temp_buffer & 0b11111101;
}
writeControlByte(temp_buffer, 1);
return result;
}
void DS3231::enableOscillator(bool TF, bool battery, byte frequency) {
// turns oscillator on or off. True is on, false is off.
// if battery is true, turns on even for battery-only operation,
// otherwise turns off if Vcc is off.
// frequency must be 0, 1, 2, or 3.
// 0 = 1 Hz
// 1 = 1.024 kHz
// 2 = 4.096 kHz
// 3 = 8.192 kHz (Default if frequency byte is out of range)
if (frequency > 3) frequency = 3;
// read control byte in, but zero out current state of RS2 and RS1.
byte temp_buffer = readControlByte(0) & 0b11100111;
if (battery) {
// turn on BBSQW flag
temp_buffer = temp_buffer | 0b01000000;
} else {
// turn off BBSQW flag
temp_buffer = temp_buffer & 0b10111111;
}
if (TF) {
// set ~EOSC to 0 and INTCN to zero.
temp_buffer = temp_buffer & 0b01111011;
} else {
// set ~EOSC to 1, leave INTCN as is.
temp_buffer = temp_buffer | 0b10000000;
}
// shift frequency into bits 3 and 4 and set.
frequency = frequency << 3;
temp_buffer = temp_buffer | frequency;
// And write the control bits
writeControlByte(temp_buffer, 0);
}
void DS3231::enable32kHz(bool TF) {
// turn 32kHz pin on or off
byte temp_buffer = readControlByte(1);
if (TF) {
// turn on 32kHz pin
temp_buffer = temp_buffer | 0b00001000;
} else {
// turn off 32kHz pin
temp_buffer = temp_buffer & 0b11110111;
}
writeControlByte(temp_buffer, 1);
}
bool DS3231::oscillatorCheck() {
// Returns false if the oscillator has been off for some reason.
// If this is the case, the time is probably not correct.
byte temp_buffer = readControlByte(1);
bool result = true;
if (temp_buffer & 0b10000000) {
// Oscillator Stop Flag (OSF) is set, so return false.
result = false;
}
return result;
}
/*****************************************
Private Functions
*****************************************/
byte DS3231::decToBcd(byte val) {
// Convert normal decimal numbers to binary coded decimal
return (val/10*16) + (val%10);
}
byte DS3231::bcdToDec(byte val) {
// Convert binary coded decimal to normal decimal numbers
return (val/16*10) + (val%16);
}
byte DS3231::readControlByte(bool which) {
// Read selected control byte
// first byte (0) is 0x0e, second (1) is 0x0f
Wire.beginTransmission(CLOCK_ADDRESS);
if (which) {
// second control byte
Wire.write(0x0f);
} else {
// first control byte
Wire.write(0x0e);
}
Wire.endTransmission();
Wire.requestFrom(CLOCK_ADDRESS, 1);
return Wire.read();
}
void DS3231::writeControlByte(byte control, bool which) {
// Write the selected control byte.
// which=false -> 0x0e, true->0x0f.
Wire.beginTransmission(CLOCK_ADDRESS);
if (which) {
Wire.write(0x0f);
} else {
Wire.write(0x0e);
}
Wire.write(control);
Wire.endTransmission();
}

View File

@ -0,0 +1,183 @@
/*
* DS3231.h
*
* Arduino Library for the DS3231 Real-Time Clock chip
*
* (c) Eric Ayars
* 4/1/11
* released into the public domain. If you use this, please let me know
* (just out of pure curiosity!) by sending me an email:
* eric@ayars.org
*
*/
// Modified by Andy Wickert 5/15/11: Spliced in stuff from RTClib
// Modified by Simon Gassner 11/28/2017: Changed Term "PM" to "PM_time" for compability with SAMD Processors
#ifndef DS3231_h
#define DS3231_h
// Changed the following to work on 1.0
//#include "WProgram.h"
#include <Arduino.h>
#include <Wire.h>
// DateTime (get everything at once) from JeeLabs / Adafruit
// Simple general-purpose date/time class (no TZ / DST / leap second handling!)
class DateTime {
public:
DateTime (uint32_t t =0);
DateTime (uint16_t year, uint8_t month, uint8_t day,
uint8_t hour =0, uint8_t min =0, uint8_t sec =0);
DateTime (const char* date, const char* time);
uint16_t year() const { return 2000 + yOff; }
uint8_t month() const { return m; }
uint8_t day() const { return d; }
uint8_t hour() const { return hh; }
uint8_t minute() const { return mm; }
uint8_t second() const { return ss; }
uint8_t dayOfTheWeek() const;
// 32-bit times as seconds since 1/1/2000
long secondstime() const;
// 32-bit times as seconds since 1/1/1970
// THE ABOVE COMMENT IS CORRECT FOR LOCAL TIME; TO USE THIS COMMAND TO
// OBTAIN TRUE UNIX TIME SINCE EPOCH, YOU MUST CALL THIS COMMAND AFTER
// SETTING YOUR CLOCK TO UTC
uint32_t unixtime(void) const;
protected:
uint8_t yOff, m, d, hh, mm, ss;
};
class RTClib {
public:
// Get date and time snapshot
static DateTime now();
};
// Eric's original code is everything below this line
class DS3231 {
public:
//Constructor
DS3231();
// Time-retrieval functions
// the get*() functions retrieve current values of the registers.
byte getSecond();
byte getMinute();
byte getHour(bool& h12, bool& PM_time);
// In addition to returning the hour register, this function
// returns the values of the 12/24-hour flag and the AM/PM flag.
byte getDoW();
byte getDate();
byte getMonth(bool& Century);
// Also sets the flag indicating century roll-over.
byte getYear();
// Last 2 digits only
// Time-setting functions
// Note that none of these check for sensibility: You can set the
// date to July 42nd and strange things will probably result.
void setSecond(byte Second);
// In addition to setting the seconds, this clears the
// "Oscillator Stop Flag".
void setMinute(byte Minute);
// Sets the minute
void setHour(byte Hour);
// Sets the hour
void setDoW(byte DoW);
// Sets the Day of the Week (1-7);
void setDate(byte Date);
// Sets the Date of the Month
void setMonth(byte Month);
// Sets the Month of the year
void setYear(byte Year);
// Last two digits of the year
void setClockMode(bool h12);
// Set 12/24h mode. True is 12-h, false is 24-hour.
// Temperature function
float getTemperature();
// Alarm functions
void getA1Time(byte& A1Day, byte& A1Hour, byte& A1Minute, byte& A1Second, byte& AlarmBits, bool& A1Dy, bool& A1h12, bool& A1PM);
/* Retrieves everything you could want to know about alarm
* one.
* A1Dy true makes the alarm go on A1Day = Day of Week,
* A1Dy false makes the alarm go on A1Day = Date of month.
*
* byte AlarmBits sets the behavior of the alarms:
* Dy A1M4 A1M3 A1M2 A1M1 Rate
* X 1 1 1 1 Once per second
* X 1 1 1 0 Alarm when seconds match
* X 1 1 0 0 Alarm when min, sec match
* X 1 0 0 0 Alarm when hour, min, sec match
* 0 0 0 0 0 Alarm when date, h, m, s match
* 1 0 0 0 0 Alarm when DoW, h, m, s match
*
* Dy A2M4 A2M3 A2M2 Rate
* X 1 1 1 Once per minute (at seconds = 00)
* X 1 1 0 Alarm when minutes match
* X 1 0 0 Alarm when hours and minutes match
* 0 0 0 0 Alarm when date, hour, min match
* 1 0 0 0 Alarm when DoW, hour, min match
*/
void getA2Time(byte& A2Day, byte& A2Hour, byte& A2Minute, byte& AlarmBits, bool& A2Dy, bool& A2h12, bool& A2PM);
// Same as getA1Time();, but A2 only goes on seconds == 00.
void setA1Time(byte A1Day, byte A1Hour, byte A1Minute, byte A1Second, byte AlarmBits, bool A1Dy, bool A1h12, bool A1PM);
// Set the details for Alarm 1
void setA2Time(byte A2Day, byte A2Hour, byte A2Minute, byte AlarmBits, bool A2Dy, bool A2h12, bool A2PM);
// Set the details for Alarm 2
void turnOnAlarm(byte Alarm);
// Enables alarm 1 or 2 and the external interrupt pin.
// If Alarm != 1, it assumes Alarm == 2.
void turnOffAlarm(byte Alarm);
// Disables alarm 1 or 2 (default is 2 if Alarm != 1);
// and leaves the interrupt pin alone.
bool checkAlarmEnabled(byte Alarm);
// Returns T/F to indicate whether the requested alarm is
// enabled. Defaults to 2 if Alarm != 1.
bool checkIfAlarm(byte Alarm);
// Checks whether the indicated alarm (1 or 2, 2 default);
// has been activated.
// Oscillator functions
void enableOscillator(bool TF, bool battery, byte frequency);
// turns oscillator on or off. True is on, false is off.
// if battery is true, turns on even for battery-only operation,
// otherwise turns off if Vcc is off.
// frequency must be 0, 1, 2, or 3.
// 0 = 1 Hz
// 1 = 1.024 kHz
// 2 = 4.096 kHz
// 3 = 8.192 kHz (Default if frequency byte is out of range);
void enable32kHz(bool TF);
// Turns the 32kHz output pin on (true); or off (false).
bool oscillatorCheck();;
// Checks the status of the OSF (Oscillator Stop Flag);.
// If this returns false, then the clock is probably not
// giving you the correct time.
// The OSF is cleared by function setSecond();.
private:
byte decToBcd(byte val);
// Convert normal decimal numbers to binary coded decimal
byte bcdToDec(byte val);
// Convert binary coded decimal to normal decimal numbers
byte readControlByte(bool which);
// Read selected control byte: (0); reads 0x0e, (1) reads 0x0f
void writeControlByte(byte control, bool which);
// Write the selected control byte.
// which == false -> 0x0e, true->0x0f.
};
#endif

View File

@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <http://unlicense.org/>

View File

@ -0,0 +1,139 @@
#include "AnalogStick.h"
namespace simplebutton {
AnalogStick::AnalogStick() {
setup(255, 255, 255);
}
AnalogStick::AnalogStick(uint8_t xPin, uint8_t yPin, uint8_t buttonPin) {
setup(xPin, yPin, buttonPin);
}
AnalogStick::~AnalogStick() {
if (this->up) delete this->up;
if (this->down) delete this->down;
if (this->left) delete this->left;
if (this->right) delete this->right;
}
void AnalogStick::setup(uint8_t xPin, uint8_t yPin, uint8_t buttonPin) {
this->xPin = xPin;
this->yPin = yPin;
this->buttonPin = buttonPin;
if (xPin < 255) pinMode(xPin, INPUT);
if (yPin < 255) pinMode(yPin, INPUT);
if (buttonPin < 255) pinMode(buttonPin, INPUT);
this->button = new ButtonPullup(buttonPin);
this->up = new ButtonAnalog(yPin);
this->down = new ButtonAnalog(yPin);
this->left = new ButtonAnalog(xPin);
this->right = new ButtonAnalog(xPin);
setLogic(1024);
}
void AnalogStick::update() {
button->update();
up->update();
down->update();
left->update();
right->update();
this->xValue = left->getState();
this->yValue = up->getState();
}
void AnalogStick::update(uint8_t xValue, uint8_t yValue, bool buttonPress) {
this->xValue = xValue;
this->yValue = yValue;
button->update(buttonPress);
up->update(yValue);
down->update(yValue);
left->update(xValue);
right->update(xValue);
}
uint8_t AnalogStick::getX() {
return xValue;
}
uint8_t AnalogStick::getY() {
return yValue;
}
void AnalogStick::setButtons(ButtonAnalog* up, ButtonAnalog* down, ButtonAnalog* left, ButtonAnalog* right,
Button* button) {
if (this->up) delete this->up;
if (this->down) delete this->down;
if (this->left) delete this->left;
if (this->right) delete this->right;
this->up = up ? up : new ButtonAnalog();
this->down = down ? down : new ButtonAnalog();
this->left = left ? left : new ButtonAnalog();
this->right = right ? right : new ButtonAnalog();
this->button = button ? button : new Button();
setLogic(this->logic, this->tolerance);
}
void AnalogStick::setLogic(uint16_t logic) {
setLogic(logic, tolerance);
}
void AnalogStick::setLogic(uint16_t logic, uint8_t tolerance) {
this->logic = logic;
this->tolerance = tolerance;
uint16_t difference = (double)logic * ((double)tolerance / double(100));
up->setBounds(0, difference);
down->setBounds(logic - difference, logic);
left->setBounds(0, difference);
right->setBounds(logic - difference, logic);
}
void AnalogStick::setUpdateInterval(uint32_t updateInterval) {
button->setUpdateInterval(updateInterval);
up->setUpdateInterval(updateInterval);
down->setUpdateInterval(updateInterval);
left->setUpdateInterval(updateInterval);
right->setUpdateInterval(updateInterval);
}
void AnalogStick::setDefaultMinPushTime(uint32_t defaultMinPushTime) {
button->setDefaultMinPushTime(defaultMinPushTime);
up->setDefaultMinPushTime(defaultMinPushTime);
down->setDefaultMinPushTime(defaultMinPushTime);
left->setDefaultMinPushTime(defaultMinPushTime);
right->setDefaultMinPushTime(defaultMinPushTime);
}
void AnalogStick::setDefaultMinReleaseTime(uint32_t defaultMinReleaseTime) {
button->setDefaultMinReleaseTime(defaultMinReleaseTime);
up->setDefaultMinReleaseTime(defaultMinReleaseTime);
down->setDefaultMinReleaseTime(defaultMinReleaseTime);
left->setDefaultMinReleaseTime(defaultMinReleaseTime);
right->setDefaultMinReleaseTime(defaultMinReleaseTime);
}
void AnalogStick::setDefaultTimeSpan(uint32_t defaultTimeSpan) {
button->setDefaultTimeSpan(defaultTimeSpan);
up->setDefaultTimeSpan(defaultTimeSpan);
down->setDefaultTimeSpan(defaultTimeSpan);
left->setDefaultTimeSpan(defaultTimeSpan);
right->setDefaultTimeSpan(defaultTimeSpan);
}
void AnalogStick::setDefaultHoldTime(uint32_t defaultHoldInterval) {
button->setDefaultHoldTime(defaultHoldInterval);
up->setDefaultHoldTime(defaultHoldInterval);
down->setDefaultHoldTime(defaultHoldInterval);
left->setDefaultHoldTime(defaultHoldInterval);
right->setDefaultHoldTime(defaultHoldInterval);
}
}

View File

@ -0,0 +1,53 @@
#ifndef SimpleButton_AnalogStick_h
#define SimpleButton_AnalogStick_h
#include "ButtonPullup.h"
#include "ButtonAnalog.h"
namespace simplebutton {
class AnalogStick {
public:
Button* button = NULL;
ButtonAnalog* up = NULL;
ButtonAnalog* down = NULL;
ButtonAnalog* left = NULL;
ButtonAnalog* right = NULL;
AnalogStick();
AnalogStick(uint8_t xPin, uint8_t yPin, uint8_t buttonPin);
~AnalogStick();
void setup(uint8_t xPin, uint8_t yPin, uint8_t buttonPin);
void update();
void update(uint8_t xValue, uint8_t yValue, bool buttonPress);
uint8_t getX();
uint8_t getY();
void setButtons(ButtonAnalog* up, ButtonAnalog* down, ButtonAnalog* left, ButtonAnalog* right,
Button* button);
void setLogic(uint16_t logic);
void setLogic(uint16_t logic, uint8_t tolerance);
void setUpdateInterval(uint32_t updateInterval);
void setDefaultMinPushTime(uint32_t defaultMinPushTime);
void setDefaultMinReleaseTime(uint32_t defaultMinReleaseTime);
void setDefaultTimeSpan(uint32_t defaultTimeSpan);
void setDefaultHoldTime(uint32_t defaultHoldInterval);
private:
uint16_t logic = 1024;
uint8_t tolerance = 25; // percentage
uint8_t xValue = 0;
uint8_t yValue = 0;
uint8_t xPin = 0;
uint8_t yPin = 0;
uint8_t buttonPin = 0;
};
}
#endif // ifndef SimpleButton_AnalogStick_h

View File

@ -0,0 +1,319 @@
#include "../SimpleButton.h"
namespace simplebutton {
Button::Button() {
setup(255, false);
}
Button::Button(uint8_t pin) {
setup(pin, false);
}
Button::Button(uint8_t pin, bool inverted) {
setup(pin, inverted);
}
Button::~Button() {}
void Button::setup(uint8_t pin, bool inverted) {
this->button_pin = pin;
this->button_inverted = inverted;
enable();
}
void Button::enable() {
button_enabled = true;
if ((button_pin < 255) && !button_setup) {
pinMode(button_pin, INPUT);
button_setup = true;
}
}
void Button::disable() {
button_enabled = false;
}
void Button::reset() {
pushedFlag = false;
releasedFlag = false;
holdFlag = false;
}
void Button::push() {
if (!state) {
state = true;
prevPushTime = pushTime;
prevReleaseTime = releaseTime;
pushedFlag = true;
pushTime = millis();
holdTime = millis();
holdFlag = false;
}
}
void Button::release() {
if (state) {
state = false;
releasedFlag = true;
releaseTime = millis();
}
}
void Button::click() {
click(defaultMinPushTime);
}
void Button::click(uint32_t time) {
push();
pushTime = millis() - time - defaultMinReleaseTime;
release();
releaseTime = millis() - defaultMinReleaseTime;
updateEvents();
}
int Button::read() {
bool currentState = false;
if (button_enabled && button_setup) {
currentState = digitalRead(button_pin);
if (button_inverted) currentState = !currentState;
}
return (int)currentState;
}
void Button::update() {
if (millis() - updateTime >= updateInterval) {
updateEvents();
if (button_enabled && button_setup) update(read());
}
}
void Button::update(int state) {
// update time
updateTime = millis();
// check events
updateEvents();
// update state
if (state > 0) push();
else release();
}
void Button::updateEvents() {
Event* e = this->events;
while (e != NULL) {
switch (e->getMode()) {
case e->MODE::PUSHED:
if (this->pushed()) e->run();
break;
case e->MODE::RELEASED:
if (this->released()) e->run();
break;
case e->MODE::CLICKED:
if (this->clicked(e->getMinPushTime(), e->getMinReleaseTime())) e->run();
break;
case e->MODE::DOUBLECLICKED:
if (this->doubleClicked(e->getMinPushTime(), e->getMinReleaseTime(), e->getTimeSpan())) e->run();
break;
case e->MODE::HOLDING:
if (this->holding(e->getInterval())) e->run();
break;
}
e = e->next;
}
}
bool Button::isInverted() {
return button_inverted;
}
bool Button::isEnabled() {
return button_enabled;
}
bool Button::isSetup() {
return button_setup;
}
bool Button::getState() {
return state;
}
int Button::getClicks() {
return (int)clicks;
}
int Button::getPushTime() {
return (int)(millis() - pushTime);
}
bool Button::pushed() {
if (pushedFlag) {
pushedFlag = false;
return true;
}
return false;
}
bool Button::released() {
if (releasedFlag && (pushTime < releaseTime)) {
releasedFlag = false;
return true;
}
return false;
}
bool Button::clicked() {
return clicked(defaultMinPushTime);
}
bool Button::clicked(uint32_t minPushTime) {
return clicked(minPushTime, defaultMinReleaseTime);
}
bool Button::clicked(uint32_t minPushTime, uint32_t minReleaseTime) {
bool notHolding = !holdFlag;
bool minTime = millis() - pushTime >= minPushTime;
bool releaseTimeout = millis() - releaseTime >= minReleaseTime;
if (notHolding && minTime && releaseTimeout) {
if (released()) {
clicks++;
return true;
}
}
return false;
}
bool Button::doubleClicked() {
return doubleClicked(defaultMinPushTime);
}
bool Button::doubleClicked(uint32_t minPushTime) {
return doubleClicked(minPushTime, defaultTimeSpan);
}
bool Button::doubleClicked(uint32_t minPushTime, uint32_t timeSpan) {
return doubleClicked(minPushTime, defaultMinReleaseTime, timeSpan);
}
bool Button::doubleClicked(uint32_t minPushTime, uint32_t minReleaseTime, uint32_t timeSpan) {
bool wasPrevClicked = prevReleaseTime - prevPushTime >= minPushTime;
bool inTimeSpan = millis() - prevPushTime <= timeSpan;
bool releaseTimeout = millis() - prevReleaseTime >= minReleaseTime;
if (wasPrevClicked && inTimeSpan && releaseTimeout) {
if (clicked(minPushTime)) {
pushTime = 0;
return true;
}
}
return false;
}
bool Button::holding() {
return holding(defaultHoldInterval);
}
bool Button::holding(uint32_t interval) {
if (getState() && (millis() - holdTime >= interval)) {
holdTime = millis();
holdFlag = true;
return true;
}
return false;
}
void Button::setUpdateInterval(uint32_t updateInterval) {
this->updateInterval = updateInterval;
}
void Button::setDefaultMinPushTime(uint32_t defaultMinPushTime) {
this->defaultMinPushTime = defaultMinPushTime;
}
void Button::setDefaultMinReleaseTime(uint32_t defaultMinReleaseTime) {
this->defaultMinReleaseTime = defaultMinReleaseTime;
}
void Button::setDefaultTimeSpan(uint32_t defaultTimeSpan) {
this->defaultTimeSpan = defaultTimeSpan;
}
void Button::setDefaultHoldTime(uint32_t defaultHoldInterval) {
this->defaultHoldInterval = defaultHoldInterval;
}
void Button::setOnPushed(ButtonEventFunction) {
this->addEvent(new PushEvent(fnct));
}
void Button::setOnReleased(ButtonEventFunction) {
this->addEvent(new ReleaseEvent(fnct));
}
void Button::setOnClicked(ButtonEventFunction) {
setOnClicked(fnct, defaultMinPushTime, defaultMinReleaseTime);
}
void Button::setOnClicked(ButtonEventFunction, uint32_t minPushTime) {
setOnClicked(fnct, minPushTime, defaultMinReleaseTime);
}
void Button::setOnClicked(ButtonEventFunction, uint32_t minPushTime, uint32_t minReleaseTime) {
this->addEvent(new ClickEvent(fnct, minPushTime, minReleaseTime));
}
void Button::setOnDoubleClicked(ButtonEventFunction) {
setOnDoubleClicked(fnct, defaultMinPushTime, defaultMinReleaseTime, defaultTimeSpan);
}
void Button::setOnDoubleClicked(ButtonEventFunction, uint32_t minPushTime) {
setOnDoubleClicked(fnct, minPushTime, defaultMinReleaseTime, defaultTimeSpan);
}
void Button::setOnDoubleClicked(ButtonEventFunction, uint32_t minPushTime, uint32_t timeSpan) {
setOnDoubleClicked(fnct, minPushTime, defaultMinReleaseTime, timeSpan);
}
void Button::setOnDoubleClicked(ButtonEventFunction, uint32_t minPushTime, uint32_t minReleaseTime, uint32_t timeSpan) {
this->addEvent(new DoubleclickEvent(fnct, minPushTime, minReleaseTime, timeSpan));
}
void Button::setOnHolding(ButtonEventFunction) {
setOnHolding(fnct, defaultHoldInterval);
}
void Button::setOnHolding(ButtonEventFunction, uint32_t interval) {
this->addEvent(new HoldEvent(fnct, interval));
}
void Button::clearEvents() {
delete events;
events = NULL;
}
void Button::addEvent(Event* e) {
if (events == NULL) events = e;
else {
Event* tmp = events;
while (tmp->next != NULL) tmp = tmp->next;
tmp->next = e;
}
}
}

View File

@ -0,0 +1,111 @@
#ifndef SimpleButton_Button_h
#define SimpleButton_Button_h
#include "Arduino.h"
#include "../Events/Event.h"
#include "../Events/PushEvent.h"
#include "../Events/ReleaseEvent.h"
#include "../Events/ClickEvent.h"
#include "../Events/DoubleclickEvent.h"
#include "../Events/HoldEvent.h"
namespace simplebutton {
class Button {
public:
Button();
Button(uint8_t pin);
Button(uint8_t pin, bool inverted);
virtual ~Button();
void setup(uint8_t pin, bool inverted);
virtual void enable();
virtual void disable();
virtual void reset();
virtual void push();
virtual void release();
virtual void click();
virtual void click(uint32_t time);
virtual int read();
virtual void update();
virtual void update(int state);
virtual void updateEvents();
virtual bool isInverted();
virtual bool isEnabled();
virtual bool isSetup();
virtual bool getState();
virtual int getClicks();
virtual int getPushTime();
virtual bool pushed();
virtual bool released();
virtual bool clicked();
virtual bool clicked(uint32_t minPushTime);
virtual bool clicked(uint32_t minPushTime, uint32_t minReleaseTime);
virtual bool doubleClicked();
virtual bool doubleClicked(uint32_t minPushTime);
virtual bool doubleClicked(uint32_t minPushTime, uint32_t timeSpan);
virtual bool doubleClicked(uint32_t minPushTime, uint32_t minReleaseTime, uint32_t timeSpan);
virtual bool holding();
virtual bool holding(uint32_t interval);
virtual void setUpdateInterval(uint32_t updateInterval);
virtual void setDefaultMinPushTime(uint32_t defaultMinPushTime);
virtual void setDefaultMinReleaseTime(uint32_t defaultMinReleaseTime);
virtual void setDefaultTimeSpan(uint32_t defaultTimeSpan);
virtual void setDefaultHoldTime(uint32_t defaultHoldInterval);
virtual void setOnPushed(ButtonEventFunction);
virtual void setOnReleased(ButtonEventFunction);
virtual void setOnClicked(ButtonEventFunction);
virtual void setOnClicked(ButtonEventFunction, uint32_t minPushTime);
virtual void setOnClicked(ButtonEventFunction, uint32_t minPushTime, uint32_t minReleaseTime);
virtual void setOnDoubleClicked(ButtonEventFunction);
virtual void setOnDoubleClicked(ButtonEventFunction, uint32_t minPushTime);
virtual void setOnDoubleClicked(ButtonEventFunction, uint32_t minPushTime, uint32_t timeSpan);
virtual void setOnDoubleClicked(
ButtonEventFunction, uint32_t minPushTime, uint32_t minReleaseTime, uint32_t timeSpan);
virtual void setOnHolding(ButtonEventFunction);
virtual void setOnHolding(ButtonEventFunction, uint32_t interval);
virtual void clearEvents();
protected:
Event* events = NULL;
bool button_inverted = false;
bool button_setup = false;
bool button_enabled = false;
bool state = false;
bool pushedFlag = false;
bool releasedFlag = false;
bool holdFlag = false;
uint8_t button_pin = 255;
uint16_t clicks = 0;
uint32_t pushTime = 0;
uint32_t releaseTime = 0;
uint32_t prevPushTime = 0;
uint32_t prevReleaseTime = 0;
uint32_t holdTime = 0;
uint32_t updateTime = 0;
uint32_t updateInterval = 5;
uint32_t defaultMinPushTime = 40;
uint32_t defaultMinReleaseTime = 40;
uint32_t defaultTimeSpan = 500;
uint32_t defaultHoldInterval = 500;
void addEvent(Event* e);
};
}
#endif // ifndef SimpleButton_Button_h

View File

@ -0,0 +1,77 @@
#include "ButtonAnalog.h"
namespace simplebutton {
ButtonAnalog::ButtonAnalog() {
setup(255, 0, 1024);
}
ButtonAnalog::ButtonAnalog(uint8_t pin) {
setup(pin, 0, 1024);
}
ButtonAnalog::ButtonAnalog(uint16_t minValue, uint16_t maxValue) {
setup(255, minValue, maxValue);
}
ButtonAnalog::ButtonAnalog(uint8_t pin, uint16_t minValue, uint16_t maxValue) {
setup(pin, minValue, maxValue);
}
ButtonAnalog::~ButtonAnalog() {}
void ButtonAnalog::setup(uint8_t pin, uint16_t minValue, uint16_t maxValue) {
this->button_pin = pin;
this->minValue = minValue;
this->maxValue = maxValue;
enable();
}
int ButtonAnalog::read() {
int currentState = 0;
if (button_enabled && button_setup) {
currentState = analogRead(button_pin);
}
return currentState;
}
void ButtonAnalog::update() {
if (millis() - updateTime >= updateInterval) {
Button::updateEvents();
if (button_enabled && button_setup) update(read());
}
}
void ButtonAnalog::update(int state) {
uint16_t newState = state;
updateTime = millis();
value = newState;
if ((newState >= minValue) && (newState <= maxValue)) push();
else release();
}
void ButtonAnalog::setMin(uint16_t minValue) {
this->minValue = minValue;
}
void ButtonAnalog::setMax(uint16_t maxValue) {
this->maxValue = maxValue;
}
void ButtonAnalog::setBounds(uint16_t minValue, uint16_t maxValue) {
setMin(minValue);
setMax(maxValue);
}
void ButtonAnalog::setValue(int value) {
this->value = (uint16_t)value;
}
uint16_t ButtonAnalog::getValue() {
return value;
}
}

View File

@ -0,0 +1,37 @@
#ifndef SimpleButton_ButtonAnalog_h
#define SimpleButton_ButtonAnalog_h
#include "Button.h"
namespace simplebutton {
class ButtonAnalog : public Button {
public:
ButtonAnalog();
ButtonAnalog(uint8_t pin);
ButtonAnalog(uint16_t minValue, uint16_t maxValue);
ButtonAnalog(uint8_t pin, uint16_t minValue, uint16_t maxValue);
~ButtonAnalog();
void setup(uint8_t pin, uint16_t minValue, uint16_t maxValue);
int read();
void update();
void update(int state);
void setMin(uint16_t minValue);
void setMax(uint16_t maxValue);
void setBounds(uint16_t minValue, uint16_t maxValue);
uint16_t getValue();
void setValue(int value);
private:
uint16_t minValue = 0;
uint16_t maxValue = 1024;
uint16_t value = 0;
};
}
#endif // ifndef SimpleButton_ButtonAnalog_h

View File

@ -0,0 +1,55 @@
#include "ButtonGPIOExpander.h"
namespace simplebutton {
ButtonGPIOExpander::ButtonGPIOExpander() {
setup(NULL, 255, false);
}
ButtonGPIOExpander::ButtonGPIOExpander(GPIOExpander* pcf, uint8_t pin) {
setup(pcf, pin, false);
}
ButtonGPIOExpander::ButtonGPIOExpander(GPIOExpander* pcf, uint8_t pin, bool inverted) {
setup(pcf, pin, inverted);
}
ButtonGPIOExpander::~ButtonGPIOExpander() {}
void ButtonGPIOExpander::setup(GPIOExpander* pcf, uint8_t pin, bool inverted) {
this->pcf = pcf;
this->button_pin = pin;
this->button_inverted = inverted;
enable();
}
void ButtonGPIOExpander::enable() {
button_enabled = true;
if (pcf) {
pcf->write(button_pin, 0);
if (pcf->connected()) button_setup = true;
}
}
int ButtonGPIOExpander::read() {
bool currentState = false;
if (button_enabled && button_setup) {
currentState = pcf->read(button_pin) > 0;
if (button_inverted) currentState = !currentState;
}
return (int)currentState;
}
void ButtonGPIOExpander::update() {
if (button_enabled && button_setup) {
update(read());
}
}
void ButtonGPIOExpander::update(int state) {
Button::update(state);
}
}

View File

@ -0,0 +1,32 @@
#ifndef SimpleButton_ButtonGPIOExpander_h
#define SimpleButton_ButtonGPIOExpander_h
#include "Button.h"
#include "../libs/GPIOExpander.h"
#include "../libs/PCF8574.h"
#include "../libs/PCF8575.h"
#include "../libs/MCP23017.h"
namespace simplebutton {
class ButtonGPIOExpander : public Button {
public:
ButtonGPIOExpander();
ButtonGPIOExpander(GPIOExpander* pcf, uint8_t pin);
ButtonGPIOExpander(GPIOExpander* pcf, uint8_t pin, bool inverted);
virtual ~ButtonGPIOExpander();
void setup(GPIOExpander* pcf, uint8_t pin, bool inverted);
virtual void enable();
virtual int read();
virtual void update();
virtual void update(int state);
protected:
GPIOExpander* pcf = NULL;
};
}
#endif // ifndef SimpleButton_ButtonGPIOExpander_h

View File

@ -0,0 +1,28 @@
#include "ButtonPullup.h"
namespace simplebutton {
ButtonPullup::ButtonPullup() {
setup(255);
}
ButtonPullup::ButtonPullup(uint8_t pin) {
setup(pin);
}
ButtonPullup::~ButtonPullup() {}
void ButtonPullup::setup(uint8_t pin) {
this->button_pin = pin;
this->button_inverted = true;
enable();
}
void ButtonPullup::enable() {
button_enabled = true;
if ((button_pin < 255) && !button_setup) {
pinMode(button_pin, INPUT_PULLUP);
button_setup = true;
}
}
}

View File

@ -0,0 +1,20 @@
#ifndef SimpleButton_ButtonPullup_h
#define SimpleButton_ButtonPullup_h
#include "Button.h"
namespace simplebutton {
class ButtonPullup : public Button {
public:
ButtonPullup();
ButtonPullup(uint8_t pin);
~ButtonPullup();
void setup(uint8_t pin);
void enable();
};
}
#endif // ifndef SimpleButton_ButtonPullup_h

View File

@ -0,0 +1,29 @@
#include "ButtonPullupGPIOExpander.h"
namespace simplebutton {
ButtonPullupGPIOExpander::ButtonPullupGPIOExpander() {
setup(NULL, 255);
}
ButtonPullupGPIOExpander::ButtonPullupGPIOExpander(GPIOExpander* pcf, uint8_t pin) {
setup(pcf, pin);
}
ButtonPullupGPIOExpander::~ButtonPullupGPIOExpander() {}
void ButtonPullupGPIOExpander::setup(GPIOExpander* pcf, uint8_t pin) {
this->pcf = pcf;
this->button_pin = pin;
this->button_inverted = true;
enable();
}
void ButtonPullupGPIOExpander::enable() {
button_enabled = true;
if (pcf) {
pcf->write(button_pin, 1);
if (pcf->connected()) button_setup = true;
}
}
}

View File

@ -0,0 +1,20 @@
#ifndef SimpleButton_ButtonPullupGPIOExpander_h
#define SimpleButton_ButtonPullupGPIOExpander_h
#include "ButtonGPIOExpander.h"
namespace simplebutton {
class ButtonPullupGPIOExpander : public ButtonGPIOExpander {
public:
ButtonPullupGPIOExpander();
ButtonPullupGPIOExpander(GPIOExpander* pcf, uint8_t pin);
~ButtonPullupGPIOExpander();
void setup(GPIOExpander* pcf, uint8_t pin);
void enable();
};
}
#endif // ifndef SimpleButton_ButtonPullupGPIOExpander_h

View File

@ -0,0 +1,400 @@
#include "PS2Gamepad.h"
namespace simplebutton {
#include "PS2Gamepad.h"
PS2Gamepad::PS2Gamepad() {}
PS2Gamepad::PS2Gamepad(uint8_t clockPin, uint8_t cmdPin, uint8_t attPin, uint8_t dataPin, bool analog) {
setup(clockPin, cmdPin, attPin, dataPin, analog);
}
PS2Gamepad::~PS2Gamepad() {
if (up) delete up;
if (down) delete down;
if (left) delete left;
if (right) delete right;
if (l1) delete l1;
if (l2) delete l2;
if (r1) delete r1;
if (r2) delete r2;
if (square) delete square;
if (triangle) delete triangle;
if (cross) delete cross;
if (circle) delete circle;
if (select) delete select;
if (start) delete start;
if (analogLeft) delete analogLeft;
if (analogRight) delete analogRight;
}
void PS2Gamepad::setup(uint8_t clockPin, uint8_t cmdPin, uint8_t attPin, uint8_t dataPin, bool analog) {
// pin setup
this->clockPin = clockPin;
this->cmdPin = cmdPin;
this->attPin = attPin;
this->dataPin = dataPin;
this->rumbleEnabled = analog;
this->pressureEnabled = analog;
pinMode(clockPin, OUTPUT);
pinMode(attPin, OUTPUT);
pinMode(cmdPin, OUTPUT);
pinMode(dataPin, INPUT_PULLUP);
digitalWrite(cmdPin, HIGH);
digitalWrite(clockPin, HIGH);
// button setup
if (!up) up = new ButtonAnalog(1, 255);
if (!down) down = new ButtonAnalog(1, 255);
if (!left) left = new ButtonAnalog(1, 255);
if (!right) right = new ButtonAnalog(1, 255);
if (!l1) l1 = new ButtonAnalog(1, 255);
if (!l2) l2 = new ButtonAnalog(1, 255);
if (!r1) r1 = new ButtonAnalog(1, 255);
if (!r2) r2 = new ButtonAnalog(1, 255);
if (!square) square = new ButtonAnalog(1, 255);
if (!triangle) triangle = new ButtonAnalog(1, 255);
if (!cross) cross = new ButtonAnalog(1, 255);
if (!circle) circle = new ButtonAnalog(1, 255);
if (!select) select = new Button();
if (!start) start = new Button();
if (!analogLeft) {
analogLeft = new AnalogStick();
analogLeft->setLogic(256);
}
if (!analogRight) {
analogRight = new AnalogStick();
analogRight->setLogic(256);
}
// connection setup
poll();
delay(10);
poll();
delay(10);
poll();
/*
if ((gamepadData[1] != 0x41) && (gamepadData[1] != 0x73) && (gamepadData[1] != 0x79)) {
errorCode = 1;
return;
}
*/
int tries = 0;
bool success = false;
do {
sendEnter();
delayMicroseconds(5);
digitalWrite(cmdPin, HIGH);
digitalWrite(clockPin, HIGH);
digitalWrite(attPin, LOW); // enable joystick
delayMicroseconds(5);
sendRead();
digitalWrite(attPin, HIGH); // disable joystick
sendMode();
if (rumbleEnabled) sendRumble();
if (pressureEnabled) sendBytesLarge();
sendExit();
poll();
if ((gamepadData[1] == 0x79) || (gamepadData[1] == 0x73)) {
success = true;
} else {
tries++;
}
} while (tries < 10 && !success);
if (!success) {
errorCode = 2;
} else {
is_connected = true;
}
}
void PS2Gamepad::update() {
if (is_connected && (millis() - lastPoll > updateInterval)) {
poll();
up->update(getDigitalValue(4));
down->update(getDigitalValue(6));
left->update(getDigitalValue(7));
right->update(getDigitalValue(5));
l1->update(getDigitalValue(10));
l2->update(getDigitalValue(8));
r1->update(getDigitalValue(11));
r2->update(getDigitalValue(9));
square->update(getDigitalValue(15));
triangle->update(getDigitalValue(12));
cross->update(getDigitalValue(14));
circle->update(getDigitalValue(13));
select->update(getDigitalValue(0));
start->update(getDigitalValue(3));
analogLeft->update(getAnalogValue(7), getAnalogValue(8), getDigitalValue(1));
analogRight->update(getAnalogValue(5), getAnalogValue(6), getDigitalValue(2));
if (pressureEnabled) {
up->setValue(getDigitalValue(4) | getAnalogValue(11));
down->setValue(getDigitalValue(6) | getAnalogValue(12));
left->setValue(getDigitalValue(7) | getAnalogValue(10));
right->setValue(getDigitalValue(5) | getAnalogValue(9));
l1->setValue(getDigitalValue(10) | getAnalogValue(17));
l2->setValue(getDigitalValue(8) | getAnalogValue(19));
r1->setValue(getDigitalValue(11) | getAnalogValue(18));
r2->setValue(getDigitalValue(9) | getAnalogValue(20));
square->setValue(getDigitalValue(15) | getAnalogValue(16));
triangle->setValue(getDigitalValue(12) | getAnalogValue(13));
cross->setValue(getDigitalValue(14) | getAnalogValue(15));
circle->setValue(getDigitalValue(13) | getAnalogValue(14));
}
}
}
String PS2Gamepad::getError() {
String msg;
switch (errorCode) {
case 0:
msg += String("OK");
break;
case 1:
msg += String("Mode not matched or not found [");
msg += String(gamepadData[1], HEX);
msg += String("]");
break;
case 2:
msg += String("Not accepting commands [");
msg += String(gamepadData[1], HEX);
msg += String("]");
break;
}
errorCode = 0;
return msg;
}
bool PS2Gamepad::connected() {
return is_connected;
}
void PS2Gamepad::setUpdateInterval(uint32_t updateInterval) {
this->updateInterval = updateInterval;
}
void PS2Gamepad::setMotors(uint8_t motorA, uint8_t motorB) {
if (!rumbleEnabled) {
rumbleEnabled = true;
pressureEnabled = true;
reconfig();
}
poll(motorA, motorB);
}
void PS2Gamepad::reconfig() {
sendEnter();
sendMode();
if (rumbleEnabled) sendRumble();
if (pressureEnabled) sendBytesLarge();
sendExit();
}
void PS2Gamepad::poll() {
if (millis() - lastPoll > 1500) reconfig();
lastPoll = millis();
uint8_t dwordA[9] = { 0x01, 0x42, 0x00, motorA, motorB, 0x00, 0x00, 0x00, 0x00 };
uint8_t dwordB[12] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
int tries = 0;
bool success = false;
do {
digitalWrite(cmdPin, HIGH);
digitalWrite(clockPin, HIGH);
digitalWrite(attPin, LOW); // low enable joystick
delayMicroseconds(5);
// send command to ask for data
for (int i = 0; i < 9; i++) {
gamepadData[i] = shift(dwordA[i]);
}
// if controller is in full data return mode, get the rest of data
if (gamepadData[1] == 0x79) {
for (int i = 0; i < 12; i++) {
gamepadData[i + 9] = shift(dwordB[i]);
}
}
digitalWrite(attPin, HIGH); // disable joystick
// Check to see if we received valid data or not.
// We should be in analog mode for our data to be valid (analog == 0x7_)
if ((gamepadData[1] & 0xf0) == 0x70) {
success = true;
} else {
// If we got to here, we are not in analog mode, try to recover...
reconfig();
tries++;
}
} while (tries < 10 && !success);
prevButtonData = buttonData;
buttonData = ((uint16_t)gamepadData[4] << 8) | gamepadData[3];
}
void PS2Gamepad::poll(uint8_t motorA, uint8_t motorB) {
this->motorA = motorA;
this->motorB = motorB;
poll();
}
bool PS2Gamepad::getDigitalValue(uint8_t button) {
if (/*button >= 0 && */ button <= 15) return (~buttonData >> button) & 1;
else return 0;
}
uint8_t PS2Gamepad::getAnalogValue(uint8_t button) {
return gamepadData[button];
}
uint8_t PS2Gamepad::shift(uint8_t data) {
uint8_t tmp = 0;
for (int i = 0; i < 8; i++) {
if (data & (1 << i)) digitalWrite(cmdPin, HIGH);
else digitalWrite(cmdPin, LOW);
digitalWrite(clockPin, LOW);
delayMicroseconds(5);
if (digitalRead(dataPin)) bitSet(tmp, i);
digitalWrite(clockPin, HIGH);
delayMicroseconds(5);
}
digitalWrite(cmdPin, HIGH);
delayMicroseconds(5);
return tmp;
}
void PS2Gamepad::sendEnter() {
digitalWrite(attPin, LOW);
shift(0x01);
shift(0x43);
shift(0x00);
shift(0x01);
shift(0x00);
digitalWrite(attPin, HIGH);
}
void PS2Gamepad::sendMode() {
digitalWrite(attPin, LOW);
shift(0x01);
shift(0x44);
shift(0x00);
shift(0x01);
shift(0x03);
shift(0x00);
shift(0x00);
shift(0x00);
shift(0x00);
digitalWrite(attPin, HIGH);
}
void PS2Gamepad::sendRumble() {
digitalWrite(attPin, LOW);
shift(0x01);
shift(0x4D);
shift(0x00);
shift(0x00);
shift(0x01);
digitalWrite(attPin, HIGH);
}
void PS2Gamepad::sendBytesLarge() {
digitalWrite(attPin, LOW);
shift(0x01);
shift(0x4F);
shift(0x00);
shift(0xFF);
shift(0xFF);
shift(0x03);
shift(0x00);
shift(0x00);
shift(0x00);
digitalWrite(attPin, HIGH);
}
void PS2Gamepad::sendExit() {
digitalWrite(attPin, LOW);
shift(0x01);
shift(0x43);
shift(0x00);
shift(0x00);
shift(0x5A);
shift(0x5A);
shift(0x5A);
shift(0x5A);
shift(0x5A);
digitalWrite(attPin, HIGH);
}
void PS2Gamepad::sendRead() {
digitalWrite(attPin, LOW);
shift(0x01);
shift(0x45);
shift(0x00);
controllerType = shift(0x5A);
shift(0x5A);
shift(0x5A);
shift(0x5A);
shift(0x5A);
shift(0x5A);
digitalWrite(attPin, HIGH);
}
}

View File

@ -0,0 +1,93 @@
#ifndef SimpleButton_PS2Gamepad_h
#define SimpleButton_PS2Gamepad_h
#include "Button.h"
#include "AnalogStick.h"
namespace simplebutton {
class PS2Gamepad {
public:
ButtonAnalog* up = NULL;
ButtonAnalog* down = NULL;
ButtonAnalog* left = NULL;
ButtonAnalog* right = NULL;
ButtonAnalog* l1 = NULL;
ButtonAnalog* l2 = NULL;
ButtonAnalog* r1 = NULL;
ButtonAnalog* r2 = NULL;
ButtonAnalog* square = NULL;
ButtonAnalog* triangle = NULL;
ButtonAnalog* cross = NULL;
ButtonAnalog* circle = NULL;
Button* select = NULL;
Button* start = NULL;
AnalogStick* analogLeft = NULL;
AnalogStick* analogRight = NULL;
PS2Gamepad();
PS2Gamepad(uint8_t clockPin, uint8_t cmdPin, uint8_t attPin, uint8_t dataPin, bool analog = true);
~PS2Gamepad();
void setup(uint8_t clockPin, uint8_t cmdPin, uint8_t attPin, uint8_t dataPin, bool analog = true);
void reconfig();
void update();
String getError();
bool connected();
void setUpdateInterval(uint32_t updateInterval);
void setMotors(uint8_t motorA, uint8_t motorB);
private:
void poll();
void poll(uint8_t motorA, uint8_t motorB);
bool getDigitalValue(uint8_t button);
uint8_t getAnalogValue(uint8_t button);
// config
uint8_t motorA = 0x00; // 0 = OFF, 1 = ONN
uint8_t motorB = 0x00; // usually 0-39 = OFF, 40 - 255 = ON
bool rumbleEnabled = false;
bool pressureEnabled = false;
uint32_t updateInterval = 25;
// class variables
bool is_connected = false;
uint8_t errorCode = 0;
uint8_t controllerType = 0;
uint8_t gamepadData[21];
uint16_t buttonData = 0;
uint16_t prevButtonData = 0;
uint32_t lastPoll = 0;
uint8_t clockPin = 0;
uint8_t cmdPin = 0;
uint8_t attPin = 0;
uint8_t dataPin = 0;
// in/output
uint8_t shift(uint8_t data);
// commands
void sendEnter();
void sendMode();
void sendRumble();
void sendBytesLarge();
void sendExit();
void sendRead();
};
}
#endif // ifndef SimpleButton_PS2Gamepad_h

View File

@ -0,0 +1,172 @@
#include "RotaryEncoder.h"
namespace simplebutton {
RotaryEncoder::RotaryEncoder() {
setButtons(NULL, NULL, NULL);
}
RotaryEncoder::RotaryEncoder(uint8_t channelA, uint8_t channelB, uint8_t button) {
setup(channelA, channelB, button);
}
RotaryEncoder::RotaryEncoder(GPIOExpander* pcf, uint8_t channelA, uint8_t channelB, uint8_t button) {
setup(pcf, channelA, channelB, button);
}
RotaryEncoder::RotaryEncoder(Button* clockwise, Button* anticlockwise, Button* button) {
setup(clockwise, anticlockwise, button);
}
RotaryEncoder::~RotaryEncoder() {
if (this->clockwise) delete this->clockwise;
if (this->anticlockwise) delete this->anticlockwise;
if (this->button) delete this->button;
}
void RotaryEncoder::setup(uint8_t channelA, uint8_t channelB, uint8_t button) {
this->clockwise = new ButtonPullup(channelA);
this->anticlockwise = new ButtonPullup(channelB);
this->button = new ButtonPullup(button);
prevA = clockwise->read();
prevB = anticlockwise->read();
}
void RotaryEncoder::setup(GPIOExpander* pcf, uint8_t channelA, uint8_t channelB, uint8_t button) {
this->clockwise = new ButtonPullupGPIOExpander(pcf, channelA);
this->anticlockwise = new ButtonPullupGPIOExpander(pcf, channelB);
this->button = new ButtonPullupGPIOExpander(pcf, button);
prevA = clockwise->read();
prevB = anticlockwise->read();
}
void RotaryEncoder::setup(Button* clockwise, Button* anticlockwise, Button* button) {
setButtons(clockwise, anticlockwise, button);
prevA = clockwise->read();
prevB = anticlockwise->read();
}
void RotaryEncoder::update() {
update(clockwise->read(), anticlockwise->read(), button->read());
}
void RotaryEncoder::update(bool stateA, bool stateB, bool buttonState) {
button->update(buttonState);
if (curState == State::STILL) {
if ((stateA != prevA) && (stateB == prevB)) {
prevA = stateA;
curState = State::ANTICLOCKWISE;
} else if ((stateA == prevA) && (stateB != prevB)) {
prevB = stateB;
curState = State::CLOCKWISE;
}
} else if ((curState != State::STILL) && (stateA == stateB)) {
prevA = stateA;
prevB = stateB;
if (curState == prevState) steps++;
else steps = 1;
if (steps >= button_steps) {
if (curState == State::CLOCKWISE) {
if (!inverted) goClockwise();
else goAnticlockwise();
} else if (curState == State::ANTICLOCKWISE) {
if (!inverted) goAnticlockwise();
else goClockwise();
}
steps = 0;
}
prevState = curState;
curState = State::STILL;
}
}
void RotaryEncoder::reset() {
button->reset();
clockwise->reset();
anticlockwise->reset();
curState = State::STILL;
prevState = State::STILL;
steps = 0;
}
int32_t RotaryEncoder::getPos() {
return pos;
}
void RotaryEncoder::setButtons(Button* clockwise, Button* anticlockwise, Button* button) {
if (this->clockwise) delete this->clockwise;
if (this->anticlockwise) delete this->anticlockwise;
if (this->button) delete this->button;
this->clockwise = clockwise ? clockwise : new Button();
this->anticlockwise = anticlockwise ? anticlockwise : new Button();
this->button = button ? button : new Button();
}
void RotaryEncoder::setPos(int32_t pos) {
this->pos = pos;
}
void RotaryEncoder::setMin(int32_t value) {
this->min = value;
}
void RotaryEncoder::setMax(int32_t value) {
this->max = value;
}
void RotaryEncoder::setEncoding(uint8_t steps) {
if ((steps == 1) || (steps == 2) || (steps == 4)) this->button_steps = steps;
}
void RotaryEncoder::enableLoop(bool loop) {
this->loop = loop;
}
void RotaryEncoder::setInverted(bool inverted) {
this->inverted = inverted;
}
void RotaryEncoder::goClockwise() {
clockwise->click();
anticlockwise->reset();
if (pos < max) pos++;
else if (loop) pos = min;
}
void RotaryEncoder::goAnticlockwise() {
anticlockwise->click();
clockwise->reset();
if (pos > min) pos--;
else if (loop) pos = max;
}
bool RotaryEncoder::clicked() {
return button->clicked();
}
bool RotaryEncoder::incremented() {
return clockwise->clicked();
}
bool RotaryEncoder::decremented() {
return anticlockwise->clicked();
}
bool RotaryEncoder::minVal() {
return pos == min;
}
bool RotaryEncoder::maxVal() {
return pos == max;
}
}

View File

@ -0,0 +1,71 @@
#ifndef SimpleButton_RotaryEncoder_h
#define SimpleButton_RotaryEncoder_h
#include "Button.h"
#include "ButtonPullup.h"
#include "ButtonGPIOExpander.h"
#include "ButtonPullupGPIOExpander.h"
namespace simplebutton {
class RotaryEncoder {
public:
Button* button = NULL;
Button* clockwise = NULL;
Button* anticlockwise = NULL;
RotaryEncoder();
RotaryEncoder(uint8_t channelA, uint8_t channelB, uint8_t button);
RotaryEncoder(GPIOExpander* pcf, uint8_t channelA, uint8_t channelB, uint8_t button);
RotaryEncoder(Button* clockwise, Button* anticlockwise, Button* button);
~RotaryEncoder();
void setup(uint8_t channelA, uint8_t channelB, uint8_t button);
void setup(GPIOExpander* pcf, uint8_t channelA, uint8_t channelB, uint8_t button);
void setup(Button* clockwise, Button* anticlockwise, Button* button);
void update();
void update(bool stateA, bool stateB, bool buttonState);
void reset();
int32_t getPos();
void setButtons(Button* clockwise, Button* anticlockwise, Button* button);
void setPos(int32_t pos);
void enableLoop(bool loop);
void setEncoding(uint8_t steps);
void setMin(int32_t value);
void setMax(int32_t value);
void setInverted(bool inverted);
bool clicked();
bool incremented();
bool decremented();
bool minVal();
bool maxVal();
private:
int32_t pos = 0;
bool prevA = false;
bool prevB = false;
enum State { STILL = 0, CLOCKWISE = 1, ANTICLOCKWISE = 2 };
State curState = State::STILL;
State prevState = State::STILL;
uint8_t button_steps = 1; // how many steps per turn (encoding)
uint8_t steps = 0; // tmp counter
int32_t min = -128;
int32_t max = 127;
bool loop = false;
bool inverted = false;
void goClockwise();
void goAnticlockwise();
};
}
#endif // ifndef SimpleButton_RotaryEncoder_h

View File

@ -0,0 +1,276 @@
#include "RotaryEncoderI2C.h"
namespace simplebutton {
RotaryEncoderI2C::RotaryEncoderI2C() {
setup(0x30);
}
RotaryEncoderI2C::RotaryEncoderI2C(uint8_t i2cAddress) {
setup(i2cAddress);
}
RotaryEncoderI2C::RotaryEncoderI2C(uint8_t i2cAddress, TwoWire* wire) {
setup(i2cAddress, wire);
}
RotaryEncoderI2C::~RotaryEncoderI2C() {}
void RotaryEncoderI2C::setup(uint8_t i2cAddress) {
setup(i2cAddress, &Wire);
}
void RotaryEncoderI2C::setup(uint8_t i2cAddress, TwoWire* wire) {
this->i2cAddress = i2cAddress;
this->wire = wire;
this->clockwise = new Button();
this->anticlockwise = new Button();
this->button = new Button();
setMin(-128);
setMax(127);
begin();
}
bool RotaryEncoderI2C::interrupt() {
if (interruptEnable) return digitalRead(interruptPin) == LOW;
return true;
}
void RotaryEncoderI2C::enableInterrupt(uint8_t pin, bool pullup) {
interruptPin = pin;
interruptEnable = true;
interruptPullup = pullup;
pinMode(pin, INPUT);
}
bool RotaryEncoderI2C::update() {
if (interrupt()) {
readStatus();
if (clicked()) button->click();
if (incremented()) clockwise->click();
if (decremented()) anticlockwise->click();
return true;
}
return false;
}
void RotaryEncoderI2C::begin() {
uint8_t config = 0x00;
if (interruptEnable) config = config | 0x01;
if (ledEnabled) config = config | 0x02;
if (loop) config = config | 0x04;
if (inverted) config = config | 0x08;
if (!interruptPullup) config = config | 0x10;
if (encoding) config = config | 0x20;
setConfig(config);
}
void RotaryEncoderI2C::reset() {
button->reset();
clockwise->reset();
anticlockwise->reset();
setConfig(0x80);
update();
}
bool RotaryEncoderI2C::connected() {
return error == 0;
}
String RotaryEncoderI2C::getError() {
String msg;
switch (error) {
case 0:
msg += "OK";
break;
case 1:
msg += String(F("Data too long to fit in transmit buffer"));
break;
case 2:
msg += String(F("Received NACK on transmit of address"));
break;
case 3:
msg += String(F("Received NACK on transmit of data"));
case 4:
msg += String(F("Unknown transmission error"));
break;
case 5:
msg += String(F("I2C error"));
break;
}
return msg;
}
void RotaryEncoderI2C::setConfig(uint8_t config) {
write(0x00, config);
}
void RotaryEncoderI2C::enableLed(bool led) {
ledEnabled = led;
}
void RotaryEncoderI2C::enableLoop(bool loop) {
this->loop = loop;
}
void RotaryEncoderI2C::setEncoding(uint8_t encoding) {
if (encoding == 1) this->encoding = false;
else if (encoding == 2) this->encoding = true;
}
void RotaryEncoderI2C::setInverted(bool inverted) {
this->inverted = inverted;
}
void RotaryEncoderI2C::setPos(int32_t value) {
write(0x02, value);
}
void RotaryEncoderI2C::setMin(int32_t value) {
write(0x0A, value);
}
void RotaryEncoderI2C::setMax(int32_t value) {
write(0x06, value);
}
void RotaryEncoderI2C::setLed(uint8_t valueA, uint8_t valueB) {
setLedA(valueA);
setLedB(valueB);
}
void RotaryEncoderI2C::setLedA(uint8_t value) {
if (ledEnabled) write(0x0E, value);
}
void RotaryEncoderI2C::setLedB(uint8_t value) {
if (ledEnabled) write(0x0F, value);
}
int32_t RotaryEncoderI2C::getPos() {
return read32(0x02);
}
uint8_t RotaryEncoderI2C::readStatus() {
status = read(0x01);
return status;
}
uint8_t RotaryEncoderI2C::readLedA() {
return read(0x0E);
}
uint8_t RotaryEncoderI2C::readLedB() {
return read(0x0F);
}
int32_t RotaryEncoderI2C::readMax() {
return read32(0x06);
}
int32_t RotaryEncoderI2C::readMin() {
return read32(0x0A);
}
bool RotaryEncoderI2C::clicked() {
return status & 0x01;
}
bool RotaryEncoderI2C::incremented() {
return status & 0x02;
}
bool RotaryEncoderI2C::decremented() {
return status & 0x04;
}
bool RotaryEncoderI2C::minVal() {
return status & 0x10;
}
bool RotaryEncoderI2C::maxVal() {
return status & 0x08;
}
void RotaryEncoderI2C::write(uint8_t address, uint8_t value) {
wire->beginTransmission(i2cAddress);
wire->write(address);
wire->write(value);
error = wire->endTransmission();
}
void RotaryEncoderI2C::write(uint8_t address, int32_t value) {
wire->beginTransmission(i2cAddress);
wire->write(address);
wire->write(((uint32_t)value >> 24) & 0xFF);
wire->write(((uint32_t)value >> 16) & 0xFF);
wire->write(((uint32_t)value >> 8) & 0xFF);
wire->write((uint32_t)value & 0xFF);
error = wire->endTransmission();
}
uint8_t RotaryEncoderI2C::read(uint8_t address) {
uint8_t data = 0xFF;
// ask for some sweet data
wire->beginTransmission(i2cAddress);
wire->write(address);
error = wire->endTransmission();
// read out the sweet data
wire->requestFrom(i2cAddress, (uint8_t)1);
if (wire->available() == 1) {
data = wire->read();
} else {
error = ROTARY_ENCODER_I2C_ERROR;
}
return data;
}
int32_t RotaryEncoderI2C::read32(uint8_t address) {
uint32_t data = 0xFFFFFFFF;
// ask for some sweet data
wire->beginTransmission(i2cAddress);
wire->write(address);
error = wire->endTransmission();
// read out the sweet data
wire->requestFrom(i2cAddress, (uint8_t)4);
if (wire->available() == 4) {
data = wire->read();
data = (data << 8) | wire->read();
data = (data << 8) | wire->read();
data = (data << 8) | wire->read();
} else {
error = ROTARY_ENCODER_I2C_ERROR;
}
return (int32_t)data;
}
}

View File

@ -0,0 +1,92 @@
#ifndef SimpleButton_RotaryEncoderI2C_h
#define SimpleButton_RotaryEncoderI2C_h
#include "Arduino.h"
#include <Wire.h>
#define ROTARY_ENCODER_I2C_ERROR 5
#include "Button.h"
namespace simplebutton {
class RotaryEncoderI2C {
public:
Button* clockwise = NULL;
Button* anticlockwise = NULL;
Button* button = NULL;
RotaryEncoderI2C();
RotaryEncoderI2C(uint8_t i2cAddress);
RotaryEncoderI2C(uint8_t i2cAddressdress, TwoWire* wire);
~RotaryEncoderI2C();
void setup(uint8_t i2cAddress);
void setup(uint8_t i2cAddress, TwoWire* wire);
bool update();
void begin();
void reset();
bool connected();
String getError();
void setConfig(uint8_t config);
void enableInterrupt(uint8_t pin, bool pullup);
void enableLed(bool led);
void enableLoop(bool loop);
void setEncoding(uint8_t encoding);
void setInverted(bool inverted);
bool interrupt();
void setPos(int32_t value);
void setMin(int32_t value);
void setMax(int32_t value);
void setLed(uint8_t valueA, uint8_t valueB);
void setLedA(uint8_t value);
void setLedB(uint8_t value);
int32_t getPos();
uint8_t readStatus();
uint8_t readLedA();
uint8_t readLedB();
int32_t readMax();
int32_t readMin();
bool clicked();
bool incremented();
bool decremented();
bool minVal();
bool maxVal();
private:
// temp variables
uint8_t status = 0x00;
uint8_t error = 0;
// i2c stuff
uint8_t i2cAddress = 0x00;
TwoWire* wire = NULL;
// config
uint8_t interruptPin = 0;
bool interruptEnable = false; // INTE
bool interruptPullup = true;
bool ledEnabled = false; // LEDE
bool encoding = false; // x1 = false, x2 = true
bool loop = false; // WRAPE
bool inverted = false; // DIRE
// internal functions
void write(uint8_t address, uint8_t value);
void write(uint8_t address, int32_t value);
uint8_t read(uint8_t address);
int32_t read32(uint8_t address);
};
}
#endif // ifndef SimpleButton_RotaryEncoderI2C_h

View File

@ -0,0 +1,63 @@
#include "Switch.h"
namespace simplebutton {
Switch::Switch() {
button = new Button();
}
Switch::Switch(uint8_t pin) {
setup(pin);
}
Switch::Switch(GPIOExpander* pcf, uint8_t pin) {
setup(pcf, pin);
}
Switch::Switch(Button* button) {
setup(button);
}
Switch::~Switch() {
if (this->button) delete this->button;
}
void Switch::setup(uint8_t pin) {
button = new Button(pin);
tmpState = button->read();
}
void Switch::setup(GPIOExpander* pcf, uint8_t pin) {
button = new ButtonGPIOExpander(pcf, pin);
tmpState = button->read();
}
void Switch::setup(Button* button) {
setButton(button);
tmpState = button->read();
}
void Switch::update() {
update(button->read());
}
void Switch::update(bool state) {
bool prevState = tmpState;
tmpState = state > 0;
if (prevState != tmpState) button->click();
}
void Switch::setButton(Button* button) {
if (this->button) delete this->button;
this->button = button ? button : new Button();
}
bool Switch::getState() {
return tmpState;
}
bool Switch::clicked() {
return button->clicked();
}
}

View File

@ -0,0 +1,36 @@
#ifndef SimpleButton_Switch_h
#define SimpleButton_Switch_h
#include "Button.h"
#include "ButtonGPIOExpander.h"
namespace simplebutton {
class Switch {
public:
Button* button = NULL;
Switch();
Switch(uint8_t pin);
Switch(GPIOExpander* pcf, uint8_t pin);
Switch(Button* button);
~Switch();
void setup(uint8_t pin);
void setup(GPIOExpander* pcf, uint8_t pin);
void setup(Button* button);
void update();
void update(bool state);
void setButton(Button* button);
bool getState();
bool clicked();
private:
bool tmpState = false;
};
}
#endif // ifndef SimpleButton_Switch_h

View File

@ -0,0 +1,28 @@
#include "ClickEvent.h"
namespace simplebutton {
ClickEvent::ClickEvent(ButtonEventFunction, uint32_t minPushTime, uint32_t minReleaseTime) {
this->fnct = fnct;
this->minPushTime = minPushTime;
this->minReleaseTime = minReleaseTime;
}
ClickEvent::~ClickEvent() {
if (next) {
delete next;
next = NULL;
}
}
uint8_t ClickEvent::getMode() {
return MODE::CLICKED;
}
uint32_t ClickEvent::getMinPushTime() {
return minPushTime;
}
uint32_t ClickEvent::getMinReleaseTime() {
return minReleaseTime;
}
}

View File

@ -0,0 +1,22 @@
#ifndef SimpleButton_ClickEvent_h
#define SimpleButton_ClickEvent_h
#include "Event.h"
namespace simplebutton {
class ClickEvent : public Event {
public:
ClickEvent(ButtonEventFunction, uint32_t minPushTime, uint32_t minReleaseTime);
~ClickEvent();
uint8_t getMode();
uint32_t getMinPushTime();
uint32_t getMinReleaseTime();
private:
uint32_t minPushTime = 0;
uint32_t minReleaseTime = 0;
};
}
#endif // ifndef SimpleButton_ClickEvent_h

Some files were not shown because too many files have changed in this diff Show More