From b3f5e3e3181d6506fcaa9c823d8ad9cde84532ed Mon Sep 17 00:00:00 2001 From: Anson Chik Date: Fri, 20 Dec 2019 12:33:58 +0800 Subject: [PATCH] Just some refactoring --- Software/ATmega32U4/HackCube.cpp | 47 +- Software/ATmega32U4/HackCube.h | 17 +- Software/ATmega32U4/HackRadio.cpp | 17 +- Software/ATmega32U4/HackRadio.h | 6 +- Software/ATmega32U4/RCSwitch.cpp | 538 ++-- Software/ATmega32U4/RF24.cpp | 2172 ++++++++-------- Software/ATmega32U4/RF24_config.h | 209 +- Software/ATmega32U4/SerialCommunication.h | 168 +- Software/ATmega32U4/attack.h | 622 ++--- Software/ATmega32U4/cc1101.cpp | 609 +++-- Software/ATmega32U4/cc1101.h | 98 +- Software/ATmega32U4/cc1101_spi.cpp | 27 +- Software/ATmega32U4/cc1101_spi.h | 8 +- Software/ATmega32U4/ccpacket.h | 5 +- Software/ATmega32U4/em4095.cpp | 724 +++--- Software/ATmega32U4/em4095.h | 55 +- Software/ATmega32U4/hid.h | 54 +- Software/ATmega32U4/nfc.h | 143 +- Software/ATmega32U4/printf.h | 2 +- Software/ATmega32U4/rf.h | 12 +- Software/ATmega32U4/rf_rollcode.h | 145 +- Software/ESP8266/APScan.cpp | 429 ++-- Software/ESP8266/APScan.h | 21 +- Software/ESP8266/ClientScan.cpp | 387 +-- Software/ESP8266/ClientScan.h | 19 +- Software/ESP8266/ESP8266.ino | 74 +- Software/ESP8266/JSON.h | 215 +- Software/ESP8266/LED.h | 466 ++-- Software/ESP8266/Mac.cpp | 82 +- Software/ESP8266/Mac.h | 24 +- Software/ESP8266/MacList.cpp | 60 +- Software/ESP8266/MacList.h | 16 +- Software/ESP8266/NameList.cpp | 122 +- Software/ESP8266/NameList.h | 17 +- Software/ESP8266/SerialCommunication.h | 85 +- Software/ESP8266/WEB.h | 44 +- Software/ESP8266/WIFI.h | 187 +- Software/ESP8266/WebInterface.h | 575 ++--- Software/ESP8266/data/HID.html | 181 +- Software/ESP8266/data/NFC.html | 462 ++-- Software/ESP8266/data/RF.html | 1026 ++++---- Software/ESP8266/data/Setup.html | 536 ++-- Software/ESP8266/data/WIFI.html | 312 +-- Software/ESP8266/data/color/colorpicker.css | 315 ++- Software/ESP8266/data/color/colorpicker.js | 2555 +++++++++---------- Software/ESP8266/data/js/functions.js | 276 +- Software/ESP8266/data/js/prompt.js | 75 +- Software/ESP8266/scan_js.h | 417 +-- Software/ESP8266/webfiles.h | 127 +- Software/ESP8266_cn/APScan.cpp | 435 ++-- Software/ESP8266_cn/APScan.h | 21 +- Software/ESP8266_cn/ESP8266_cn.ino | 70 +- Software/ESP8266_cn/JSON.h | 215 +- Software/ESP8266_cn/LED.h | 466 ++-- Software/ESP8266_cn/Mac.cpp | 82 +- Software/ESP8266_cn/Mac.h | 24 +- Software/ESP8266_cn/MacList.cpp | 60 +- Software/ESP8266_cn/MacList.h | 15 +- Software/ESP8266_cn/NameList.cpp | 122 +- Software/ESP8266_cn/NameList.h | 17 +- Software/ESP8266_cn/SerialCommunication.h | 85 +- Software/ESP8266_cn/WEB.h | 44 +- Software/ESP8266_cn/WIFI.h | 176 +- Software/ESP8266_cn/WebInterface.h | 4 +- Software/ESP8266_cn/data/HID.html | 185 +- Software/ESP8266_cn/data/NFC.html | 465 ++-- Software/ESP8266_cn/data/RF.html | 1036 ++++---- Software/ESP8266_cn/data/Setup.html | 537 ++-- Software/ESP8266_cn/data/WIFI.html | 82 +- Software/ESP8266_cn/data/js/functions.js | 277 +- Software/ESP8266_cn/data/js/prompt.js | 75 +- Software/ESP8266_cn/scan_js.h | 444 ++-- 72 files changed, 10177 insertions(+), 9543 deletions(-) diff --git a/Software/ATmega32U4/HackCube.cpp b/Software/ATmega32U4/HackCube.cpp index 2926803..b8e819e 100644 --- a/Software/ATmega32U4/HackCube.cpp +++ b/Software/ATmega32U4/HackCube.cpp @@ -1,38 +1,37 @@ #include "HackCube.h" -HackCube::Cube(void){ +HackCube::Cube(void) { }; -void HackCube::Begin() -{ +void HackCube::Begin() { }; -void HackCube::pinSetup(){ - pinMode(nRF_CS_1, OUTPUT); - pinMode(nRF_CE,OUTPUT); +void HackCube::pinSetup() { + pinMode(nRF_CS_1, OUTPUT); + pinMode(nRF_CE, OUTPUT); - pinMode(RF433_CS, OUTPUT); - pinMode(RF433_GDO0,OUTPUT); - pinMode(RF433_GDO2, INPUT); - - digitalWrite(RF433_CS, HIGH); - digitalWrite(RF433_GDO0, LOW); - digitalWrite(RF315_CS, HIGH); - digitalWrite(RF315_GDO0, LOW); + pinMode(RF433_CS, OUTPUT); + pinMode(RF433_GDO0, OUTPUT); + pinMode(RF433_GDO2, INPUT); - pinMode(RF315_CS, OUTPUT); - pinMode(RF315_GDO0,OUTPUT); - pinMode(RF315_GDO2, INPUT); + digitalWrite(RF433_CS, HIGH); + digitalWrite(RF433_GDO0, LOW); + digitalWrite(RF315_CS, HIGH); + digitalWrite(RF315_GDO0, LOW); - pinMode(RF_EN, OUTPUT); - digitalWrite(RF_EN, HIGH); + pinMode(RF315_CS, OUTPUT); + pinMode(RF315_GDO0, OUTPUT); + pinMode(RF315_GDO2, INPUT); - pinMode(ID_OUT, INPUT); - pinMode(MOD, OUTPUT); - pinMode(SHD, OUTPUT); + pinMode(RF_EN, OUTPUT); + digitalWrite(RF_EN, HIGH); - digitalWrite(MOD,LOW); - digitalWrite(SHD,LOW); + pinMode(ID_OUT, INPUT); + pinMode(MOD, OUTPUT); + pinMode(SHD, OUTPUT); + + digitalWrite(MOD, LOW); + digitalWrite(SHD, LOW); }; diff --git a/Software/ATmega32U4/HackCube.h b/Software/ATmega32U4/HackCube.h index b3a7efb..eb666e6 100644 --- a/Software/ATmega32U4/HackCube.h +++ b/Software/ATmega32U4/HackCube.h @@ -6,18 +6,19 @@ #include "Pin.h" -class HackCube{ +class HackCube { public: - Cube(void); - // 初始化模块 - void Begin(); - // 将模块io设置为对应的输入输出模式 - void pinSetup(); + Cube(void); -private: - int pin; + // 初始化模块 + void Begin(); + + // 将模块io设置为对应的输入输出模式 + void pinSetup(); +private: + int pin; }; #endif diff --git a/Software/ATmega32U4/HackRadio.cpp b/Software/ATmega32U4/HackRadio.cpp index 8d90d75..122f842 100644 --- a/Software/ATmega32U4/HackRadio.cpp +++ b/Software/ATmega32U4/HackRadio.cpp @@ -4,7 +4,7 @@ //#if defined(__AVR_ATmega1280__) //#if defined (MCU_STM32F103R) -#if defined(__STM32F1__) +#if defined(__STM32F1__) #include "itoa.h" #endif // @@ -74,7 +74,6 @@ void HackRadio::transmit(int nHighPulses, int nLowPulses) { void HackRadio::Send0() { - this->transmit(721,390);//690 420 //Serial.print("0"); } @@ -184,13 +183,13 @@ void HackRadio::handleInterrupt() { static unsigned int changeCount; static unsigned long lastTime; static unsigned int repeatCount; - + long time = micros(); duration = time - lastTime; if ( changeCount > 155 - && duration > HackRadio::timings[0] - 4000 + && duration > HackRadio::timings[0] - 4000 && duration < HackRadio::timings[0] + 4000 && HackRadio::timings[24]<4500 && HackRadio::timings[24]>3500 @@ -204,13 +203,13 @@ void HackRadio::handleInterrupt() { } - + if (changeCount >= HackRadio_MAX_CHANGES) { changeCount = 0; repeatCount = 0; } HackRadio::timings[changeCount++] = duration; - lastTime = time; + lastTime = time; } bool HackRadio::receiveProtocol2(unsigned int changeCount){ @@ -218,15 +217,15 @@ bool HackRadio::receiveProtocol2(unsigned int changeCount){ String tiaoma; String action; unsigned long delay = HackRadio::timings[0] / 31; - unsigned long delayTolerance = delay * HackRadio::nReceiveTolerance * 0.01; + unsigned long delayTolerance = delay * HackRadio::nReceiveTolerance * 0.01; for (int i = 25 ; i< 89 ; i=i+2){ - if (HackRadio::timings[i] < HackRadio::timings[i+1]){ + if (HackRadio::timings[i] < HackRadio::timings[i+1]){ tiaoma +="0"; } else if (HackRadio::timings[i] > HackRadio::timings[i+1]) { tiaoma +="1"; } } - for (int i = 89 ; i< 145 ; i=i+2) { + for (int i = 89 ; i< 145 ; i=i+2) { if (HackRadio::timings[i] < HackRadio::timings[i+1]) { sn +="0"; } else if (HackRadio::timings[i] > HackRadio::timings[i+1]) { diff --git a/Software/ATmega32U4/HackRadio.h b/Software/ATmega32U4/HackRadio.h index b7bd3da..0938f41 100644 --- a/Software/ATmega32U4/HackRadio.h +++ b/Software/ATmega32U4/HackRadio.h @@ -45,9 +45,9 @@ class HackRadio{ static void handleInterrupt(); static bool receiveProtocol2(unsigned int changeCount); static String dec4bin(String data); - String getkey(); - String getsn(); - String getaction(); + String getKey(); + String getSN(); + String getAction(); bool available(); void resetAvailable(); diff --git a/Software/ATmega32U4/RCSwitch.cpp b/Software/ATmega32U4/RCSwitch.cpp index 1a6736e..4d9a01b 100644 --- a/Software/ATmega32U4/RCSwitch.cpp +++ b/Software/ATmega32U4/RCSwitch.cpp @@ -34,18 +34,18 @@ #include "RCSwitch.h" #ifdef RaspberryPi - // PROGMEM and _P functions are for AVR based microprocessors, - // so we must normalize these for the ARM processor: - #define PROGMEM - #define memcpy_P(dest, src, num) memcpy((dest), (src), (num)) +// PROGMEM and _P functions are for AVR based microprocessors, +// so we must normalize these for the ARM processor: +#define PROGMEM +#define memcpy_P(dest, src, num) memcpy((dest), (src), (num)) #endif #if defined(ESP8266) || defined(ESP32) - // interrupt handler and related code must be in RAM on ESP8266, - // according to issue #46. - #define RECEIVE_ATTR ICACHE_RAM_ATTR +// interrupt handler and related code must be in RAM on ESP8266, +// according to issue #46. +#define RECEIVE_ATTR ICACHE_RAM_ATTR #else - #define RECEIVE_ATTR +#define RECEIVE_ATTR #endif @@ -71,19 +71,48 @@ #if defined(ESP8266) || defined(ESP32) static const RCSwitch::Protocol proto[] = { #else -static const RCSwitch::Protocol PROGMEM proto[] = { +static const RCSwitch::Protocol PROGMEM +proto[] = { #endif - { 350, { 1, 31 }, { 1, 3 }, { 3, 1 }, false }, // protocol 1 - { 650, { 1, 10 }, { 1, 2 }, { 2, 1 }, false }, // protocol 2 - { 100, { 30, 71 }, { 4, 11 }, { 9, 6 }, false }, // protocol 3 - { 380, { 1, 6 }, { 1, 3 }, { 3, 1 }, false }, // protocol 4 - { 500, { 6, 14 }, { 1, 2 }, { 2, 1 }, false }, // protocol 5 - { 450, { 23, 1 }, { 1, 2 }, { 2, 1 }, true }, // protocol 6 (HT6P20B) - { 150, { 2, 62 }, { 1, 6 }, { 6, 1 }, false } // protocol 7 (HS2303-PT, i. e. used in AUKEY Remote) +{ +350, { +1, 31 }, { +1, 3 }, { +3, 1 }, false }, // protocol 1 +{ +650, { +1, 10 }, { +1, 2 }, { +2, 1 }, false }, // protocol 2 +{ +100, { +30, 71 }, { +4, 11 }, { +9, 6 }, false }, // protocol 3 +{ +380, { +1, 6 }, { +1, 3 }, { +3, 1 }, false }, // protocol 4 +{ +500, { +6, 14 }, { +1, 2 }, { +2, 1 }, false }, // protocol 5 +{ +450, { +23, 1 }, { +1, 2 }, { +2, 1 }, true }, // protocol 6 (HT6P20B) +{ +150, { +2, 62 }, { +1, 6 }, { +6, 1 }, false } // protocol 7 (HS2303-PT, i. e. used in AUKEY Remote) }; enum { - numProto = sizeof(proto) / sizeof(proto[0]) + numProto = sizeof(proto) / sizeof(proto[0]) }; #if not defined( RCSwitchDisableReceiving ) @@ -100,34 +129,34 @@ unsigned int RCSwitch::timings[RCSWITCH_MAX_CHANGES]; #endif RCSwitch::RCSwitch() { - this->nTransmitterPin = -1; - this->setRepeatTransmit(10); - this->setProtocol(1); - #if not defined( RCSwitchDisableReceiving ) - this->nReceiverInterrupt = -1; - this->setReceiveTolerance(60); - RCSwitch::nReceivedValue = 0; - #endif + this->nTransmitterPin = -1; + this->setRepeatTransmit(10); + this->setProtocol(1); +#if not defined( RCSwitchDisableReceiving ) + this->nReceiverInterrupt = -1; + this->setReceiveTolerance(60); + RCSwitch::nReceivedValue = 0; +#endif } /** * Sets the protocol to send. */ void RCSwitch::setProtocol(Protocol protocol) { - this->protocol = protocol; + this->protocol = protocol; } /** * Sets the protocol to send, from a list of predefined protocols */ void RCSwitch::setProtocol(int nProtocol) { - if (nProtocol < 1 || nProtocol > numProto) { - nProtocol = 1; // TODO: trigger an error, e.g. "bad protocol" ??? - } + if (nProtocol < 1 || nProtocol > numProto) { + nProtocol = 1; // TODO: trigger an error, e.g. "bad protocol" ??? + } #if defined(ESP8266) || defined(ESP32) - this->protocol = proto[nProtocol-1]; + this->protocol = proto[nProtocol-1]; #else - memcpy_P(&this->protocol, &proto[nProtocol-1], sizeof(Protocol)); + memcpy_P(&this->protocol, &proto[nProtocol - 1], sizeof(Protocol)); #endif } @@ -135,8 +164,8 @@ void RCSwitch::setProtocol(int nProtocol) { * Sets the protocol to send with pulse length in microseconds. */ void RCSwitch::setProtocol(int nProtocol, int nPulseLength) { - setProtocol(nProtocol); - this->setPulseLength(nPulseLength); + setProtocol(nProtocol); + this->setPulseLength(nPulseLength); } @@ -144,25 +173,27 @@ void RCSwitch::setProtocol(int nProtocol, int nPulseLength) { * Sets pulse length in microseconds */ void RCSwitch::setPulseLength(int nPulseLength) { - this->protocol.pulseLength = nPulseLength; + this->protocol.pulseLength = nPulseLength; } /** * Sets Repeat Transmits */ void RCSwitch::setRepeatTransmit(int nRepeatTransmit) { - this->nRepeatTransmit = nRepeatTransmit; + this->nRepeatTransmit = nRepeatTransmit; } /** * Set Receiving Tolerance */ #if not defined( RCSwitchDisableReceiving ) + void RCSwitch::setReceiveTolerance(int nPercent) { - RCSwitch::nReceiveTolerance = nPercent; + RCSwitch::nReceiveTolerance = nPercent; } + #endif - + /** * Enable transmissions @@ -170,15 +201,15 @@ void RCSwitch::setReceiveTolerance(int nPercent) { * @param nTransmitterPin Arduino Pin to which the sender is connected to */ void RCSwitch::enableTransmit(int nTransmitterPin) { - this->nTransmitterPin = nTransmitterPin; - pinMode(this->nTransmitterPin, OUTPUT); + this->nTransmitterPin = nTransmitterPin; + pinMode(this->nTransmitterPin, OUTPUT); } /** * Disable transmissions */ void RCSwitch::disableTransmit() { - this->nTransmitterPin = -1; + this->nTransmitterPin = -1; } /** @@ -188,7 +219,7 @@ void RCSwitch::disableTransmit() { * @param nDevice Number of the switch itself (1..3) */ void RCSwitch::switchOn(char sGroup, int nDevice) { - this->sendTriState( this->getCodeWordD(sGroup, nDevice, true) ); + this->sendTriState(this->getCodeWordD(sGroup, nDevice, true)); } /** @@ -198,7 +229,7 @@ void RCSwitch::switchOn(char sGroup, int nDevice) { * @param nDevice Number of the switch itself (1..3) */ void RCSwitch::switchOff(char sGroup, int nDevice) { - this->sendTriState( this->getCodeWordD(sGroup, nDevice, false) ); + this->sendTriState(this->getCodeWordD(sGroup, nDevice, false)); } /** @@ -209,7 +240,7 @@ void RCSwitch::switchOff(char sGroup, int nDevice) { * @param nDevice Number of device (1..4) */ void RCSwitch::switchOn(char sFamily, int nGroup, int nDevice) { - this->sendTriState( this->getCodeWordC(sFamily, nGroup, nDevice, true) ); + this->sendTriState(this->getCodeWordC(sFamily, nGroup, nDevice, true)); } /** @@ -220,7 +251,7 @@ void RCSwitch::switchOn(char sFamily, int nGroup, int nDevice) { * @param nDevice Number of device (1..4) */ void RCSwitch::switchOff(char sFamily, int nGroup, int nDevice) { - this->sendTriState( this->getCodeWordC(sFamily, nGroup, nDevice, false) ); + this->sendTriState(this->getCodeWordC(sFamily, nGroup, nDevice, false)); } /** @@ -230,7 +261,7 @@ void RCSwitch::switchOff(char sFamily, int nGroup, int nDevice) { * @param nChannelCode Number of the switch itself (1..4) */ void RCSwitch::switchOn(int nAddressCode, int nChannelCode) { - this->sendTriState( this->getCodeWordB(nAddressCode, nChannelCode, true) ); + this->sendTriState(this->getCodeWordB(nAddressCode, nChannelCode, true)); } /** @@ -240,7 +271,7 @@ void RCSwitch::switchOn(int nAddressCode, int nChannelCode) { * @param nChannelCode Number of the switch itself (1..4) */ void RCSwitch::switchOff(int nAddressCode, int nChannelCode) { - this->sendTriState( this->getCodeWordB(nAddressCode, nChannelCode, false) ); + this->sendTriState(this->getCodeWordB(nAddressCode, nChannelCode, false)); } /** @@ -250,9 +281,9 @@ void RCSwitch::switchOff(int nAddressCode, int nChannelCode) { * @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") * @param nChannelCode Number of the switch itself (1..5) */ -void RCSwitch::switchOn(const char* sGroup, int nChannel) { - const char* code[6] = { "00000", "10000", "01000", "00100", "00010", "00001" }; - this->switchOn(sGroup, code[nChannel]); +void RCSwitch::switchOn(const char *sGroup, int nChannel) { + const char *code[6] = {"00000", "10000", "01000", "00100", "00010", "00001"}; + this->switchOn(sGroup, code[nChannel]); } /** @@ -262,9 +293,9 @@ void RCSwitch::switchOn(const char* sGroup, int nChannel) { * @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") * @param nChannelCode Number of the switch itself (1..5) */ -void RCSwitch::switchOff(const char* sGroup, int nChannel) { - const char* code[6] = { "00000", "10000", "01000", "00100", "00010", "00001" }; - this->switchOff(sGroup, code[nChannel]); +void RCSwitch::switchOff(const char *sGroup, int nChannel) { + const char *code[6] = {"00000", "10000", "01000", "00100", "00010", "00001"}; + this->switchOff(sGroup, code[nChannel]); } /** @@ -273,8 +304,8 @@ void RCSwitch::switchOff(const char* sGroup, int nChannel) { * @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") * @param sDevice Code of the switch device (refers to DIP switches 6..10 (A..E) where "1" = on and "0" = off, if all DIP switches are on it's "11111") */ -void RCSwitch::switchOn(const char* sGroup, const char* sDevice) { - this->sendTriState( this->getCodeWordA(sGroup, sDevice, true) ); +void RCSwitch::switchOn(const char *sGroup, const char *sDevice) { + this->sendTriState(this->getCodeWordA(sGroup, sDevice, true)); } /** @@ -283,8 +314,8 @@ void RCSwitch::switchOn(const char* sGroup, const char* sDevice) { * @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") * @param sDevice Code of the switch device (refers to DIP switches 6..10 (A..E) where "1" = on and "0" = off, if all DIP switches are on it's "11111") */ -void RCSwitch::switchOff(const char* sGroup, const char* sDevice) { - this->sendTriState( this->getCodeWordA(sGroup, sDevice, false) ); +void RCSwitch::switchOff(const char *sGroup, const char *sDevice) { + this->sendTriState(this->getCodeWordA(sGroup, sDevice, false)); } @@ -292,23 +323,23 @@ void RCSwitch::switchOff(const char* sGroup, const char* sDevice) { * Returns a char[13], representing the code word to be send. * */ -char* RCSwitch::getCodeWordA(const char* sGroup, const char* sDevice, bool bStatus) { - static char sReturn[13]; - int nReturnPos = 0; +char *RCSwitch::getCodeWordA(const char *sGroup, const char *sDevice, bool bStatus) { + static char sReturn[13]; + int nReturnPos = 0; - for (int i = 0; i < 5; i++) { - sReturn[nReturnPos++] = (sGroup[i] == '0') ? 'F' : '0'; - } + for (int i = 0; i < 5; i++) { + sReturn[nReturnPos++] = (sGroup[i] == '0') ? 'F' : '0'; + } - for (int i = 0; i < 5; i++) { - sReturn[nReturnPos++] = (sDevice[i] == '0') ? 'F' : '0'; - } + for (int i = 0; i < 5; i++) { + sReturn[nReturnPos++] = (sDevice[i] == '0') ? 'F' : '0'; + } - sReturn[nReturnPos++] = bStatus ? '0' : 'F'; - sReturn[nReturnPos++] = bStatus ? 'F' : '0'; + sReturn[nReturnPos++] = bStatus ? '0' : 'F'; + sReturn[nReturnPos++] = bStatus ? 'F' : '0'; - sReturn[nReturnPos] = '\0'; - return sReturn; + sReturn[nReturnPos] = '\0'; + return sReturn; } /** @@ -328,64 +359,64 @@ char* RCSwitch::getCodeWordA(const char* sGroup, const char* sDevice, bool bStat * * @return char[13], representing a tristate code word of length 12 */ -char* RCSwitch::getCodeWordB(int nAddressCode, int nChannelCode, bool bStatus) { - static char sReturn[13]; - int nReturnPos = 0; +char *RCSwitch::getCodeWordB(int nAddressCode, int nChannelCode, bool bStatus) { + static char sReturn[13]; + int nReturnPos = 0; - if (nAddressCode < 1 || nAddressCode > 4 || nChannelCode < 1 || nChannelCode > 4) { - return 0; - } + if (nAddressCode < 1 || nAddressCode > 4 || nChannelCode < 1 || nChannelCode > 4) { + return 0; + } - for (int i = 1; i <= 4; i++) { - sReturn[nReturnPos++] = (nAddressCode == i) ? '0' : 'F'; - } + for (int i = 1; i <= 4; i++) { + sReturn[nReturnPos++] = (nAddressCode == i) ? '0' : 'F'; + } - for (int i = 1; i <= 4; i++) { - sReturn[nReturnPos++] = (nChannelCode == i) ? '0' : 'F'; - } + for (int i = 1; i <= 4; i++) { + sReturn[nReturnPos++] = (nChannelCode == i) ? '0' : 'F'; + } - sReturn[nReturnPos++] = 'F'; - sReturn[nReturnPos++] = 'F'; - sReturn[nReturnPos++] = 'F'; + sReturn[nReturnPos++] = 'F'; + sReturn[nReturnPos++] = 'F'; + sReturn[nReturnPos++] = 'F'; - sReturn[nReturnPos++] = bStatus ? 'F' : '0'; + sReturn[nReturnPos++] = bStatus ? 'F' : '0'; - sReturn[nReturnPos] = '\0'; - return sReturn; + sReturn[nReturnPos] = '\0'; + return sReturn; } /** * Like getCodeWord (Type C = Intertechno) */ -char* RCSwitch::getCodeWordC(char sFamily, int nGroup, int nDevice, bool bStatus) { - static char sReturn[13]; - int nReturnPos = 0; - - int nFamily = (int)sFamily - 'a'; - if ( nFamily < 0 || nFamily > 15 || nGroup < 1 || nGroup > 4 || nDevice < 1 || nDevice > 4) { - return 0; - } - - // encode the family into four bits - sReturn[nReturnPos++] = (nFamily & 1) ? 'F' : '0'; - sReturn[nReturnPos++] = (nFamily & 2) ? 'F' : '0'; - sReturn[nReturnPos++] = (nFamily & 4) ? 'F' : '0'; - sReturn[nReturnPos++] = (nFamily & 8) ? 'F' : '0'; +char *RCSwitch::getCodeWordC(char sFamily, int nGroup, int nDevice, bool bStatus) { + static char sReturn[13]; + int nReturnPos = 0; + + int nFamily = (int) sFamily - 'a'; + if (nFamily < 0 || nFamily > 15 || nGroup < 1 || nGroup > 4 || nDevice < 1 || nDevice > 4) { + return 0; + } + + // encode the family into four bits + sReturn[nReturnPos++] = (nFamily & 1) ? 'F' : '0'; + sReturn[nReturnPos++] = (nFamily & 2) ? 'F' : '0'; + sReturn[nReturnPos++] = (nFamily & 4) ? 'F' : '0'; + sReturn[nReturnPos++] = (nFamily & 8) ? 'F' : '0'; - // encode the device and group - sReturn[nReturnPos++] = ((nDevice-1) & 1) ? 'F' : '0'; - sReturn[nReturnPos++] = ((nDevice-1) & 2) ? 'F' : '0'; - sReturn[nReturnPos++] = ((nGroup-1) & 1) ? 'F' : '0'; - sReturn[nReturnPos++] = ((nGroup-1) & 2) ? 'F' : '0'; + // encode the device and group + sReturn[nReturnPos++] = ((nDevice - 1) & 1) ? 'F' : '0'; + sReturn[nReturnPos++] = ((nDevice - 1) & 2) ? 'F' : '0'; + sReturn[nReturnPos++] = ((nGroup - 1) & 1) ? 'F' : '0'; + sReturn[nReturnPos++] = ((nGroup - 1) & 2) ? 'F' : '0'; - // encode the status code - sReturn[nReturnPos++] = '0'; - sReturn[nReturnPos++] = 'F'; - sReturn[nReturnPos++] = 'F'; - sReturn[nReturnPos++] = bStatus ? 'F' : '0'; + // encode the status code + sReturn[nReturnPos++] = '0'; + sReturn[nReturnPos++] = 'F'; + sReturn[nReturnPos++] = 'F'; + sReturn[nReturnPos++] = bStatus ? 'F' : '0'; - sReturn[nReturnPos] = '\0'; - return sReturn; + sReturn[nReturnPos] = '\0'; + return sReturn; } /** @@ -407,76 +438,76 @@ char* RCSwitch::getCodeWordC(char sFamily, int nGroup, int nDevice, bool bStatus * * @return char[13], representing a tristate code word of length 12 */ -char* RCSwitch::getCodeWordD(char sGroup, int nDevice, bool bStatus) { - static char sReturn[13]; - int nReturnPos = 0; - - // sGroup must be one of the letters in "abcdABCD" - int nGroup = (sGroup >= 'a') ? (int)sGroup - 'a' : (int)sGroup - 'A'; - if ( nGroup < 0 || nGroup > 3 || nDevice < 1 || nDevice > 3) { - return 0; - } +char *RCSwitch::getCodeWordD(char sGroup, int nDevice, bool bStatus) { + static char sReturn[13]; + int nReturnPos = 0; + + // sGroup must be one of the letters in "abcdABCD" + int nGroup = (sGroup >= 'a') ? (int) sGroup - 'a' : (int) sGroup - 'A'; + if (nGroup < 0 || nGroup > 3 || nDevice < 1 || nDevice > 3) { + return 0; + } - for (int i = 0; i < 4; i++) { - sReturn[nReturnPos++] = (nGroup == i) ? '1' : 'F'; - } + for (int i = 0; i < 4; i++) { + sReturn[nReturnPos++] = (nGroup == i) ? '1' : 'F'; + } - for (int i = 1; i <= 3; i++) { - sReturn[nReturnPos++] = (nDevice == i) ? '1' : 'F'; - } + for (int i = 1; i <= 3; i++) { + sReturn[nReturnPos++] = (nDevice == i) ? '1' : 'F'; + } - sReturn[nReturnPos++] = '0'; - sReturn[nReturnPos++] = '0'; - sReturn[nReturnPos++] = '0'; + sReturn[nReturnPos++] = '0'; + sReturn[nReturnPos++] = '0'; + sReturn[nReturnPos++] = '0'; - sReturn[nReturnPos++] = bStatus ? '1' : '0'; - sReturn[nReturnPos++] = bStatus ? '0' : '1'; + sReturn[nReturnPos++] = bStatus ? '1' : '0'; + sReturn[nReturnPos++] = bStatus ? '0' : '1'; - sReturn[nReturnPos] = '\0'; - return sReturn; + sReturn[nReturnPos] = '\0'; + return sReturn; } /** * @param sCodeWord a tristate code word consisting of the letter 0, 1, F */ -void RCSwitch::sendTriState(const char* sCodeWord) { - // turn the tristate code word into the corresponding bit pattern, then send it - unsigned long code = 0; - unsigned int length = 0; - for (const char* p = sCodeWord; *p; p++) { - code <<= 2L; - switch (*p) { - case '0': - // bit pattern 00 - break; - case 'F': - // bit pattern 01 - code |= 1L; - break; - case '1': - // bit pattern 11 - code |= 3L; - break; +void RCSwitch::sendTriState(const char *sCodeWord) { + // turn the tristate code word into the corresponding bit pattern, then send it + unsigned long code = 0; + unsigned int length = 0; + for (const char *p = sCodeWord; *p; p++) { + code <<= 2L; + switch (*p) { + case '0': + // bit pattern 00 + break; + case 'F': + // bit pattern 01 + code |= 1L; + break; + case '1': + // bit pattern 11 + code |= 3L; + break; + } + length += 2; } - length += 2; - } - this->send(code, length); + this->send(code, length); } /** * @param sCodeWord a binary code word consisting of the letter 0, 1 */ -void RCSwitch::send(const char* sCodeWord) { - // turn the tristate code word into the corresponding bit pattern, then send it - unsigned long code = 0; - unsigned int length = 0; - for (const char* p = sCodeWord; *p; p++) { - code <<= 1L; - if (*p != '0') - code |= 1L; - length++; - } - this->send(code, length); +void RCSwitch::send(const char *sCodeWord) { + // turn the tristate code word into the corresponding bit pattern, then send it + unsigned long code = 0; + unsigned int length = 0; + for (const char *p = sCodeWord; *p; p++) { + code <<= 1L; + if (*p != '0') + code |= 1L; + length++; + } + this->send(code, length); } /** @@ -485,35 +516,35 @@ void RCSwitch::send(const char* sCodeWord) { * then the bit at position length-2, and so on, till finally the bit at position 0. */ void RCSwitch::send(unsigned long code, unsigned int length) { - if (this->nTransmitterPin == -1) - return; + if (this->nTransmitterPin == -1) + return; #if not defined( RCSwitchDisableReceiving ) - // make sure the receiver is disabled while we transmit - int nReceiverInterrupt_backup = nReceiverInterrupt; - if (nReceiverInterrupt_backup != -1) { - this->disableReceive(); - } + // make sure the receiver is disabled while we transmit + int nReceiverInterrupt_backup = nReceiverInterrupt; + if (nReceiverInterrupt_backup != -1) { + this->disableReceive(); + } #endif - for (int nRepeat = 0; nRepeat < nRepeatTransmit; nRepeat++) { - for (int i = length-1; i >= 0; i--) { - if (code & (1L << i)) - this->transmit(protocol.one); - else - this->transmit(protocol.zero); + for (int nRepeat = 0; nRepeat < nRepeatTransmit; nRepeat++) { + for (int i = length - 1; i >= 0; i--) { + if (code & (1L << i)) + this->transmit(protocol.one); + else + this->transmit(protocol.zero); + } + this->transmit(protocol.syncFactor); } - this->transmit(protocol.syncFactor); - } - // Disable transmit after sending (i.e., for inverted protocols) - digitalWrite(this->nTransmitterPin, LOW); + // Disable transmit after sending (i.e., for inverted protocols) + digitalWrite(this->nTransmitterPin, LOW); #if not defined( RCSwitchDisableReceiving ) - // enable receiver again if we just disabled it - if (nReceiverInterrupt_backup != -1) { - this->enableReceive(nReceiverInterrupt_backup); - } + // enable receiver again if we just disabled it + if (nReceiverInterrupt_backup != -1) { + this->enableReceive(nReceiverInterrupt_backup); + } #endif } @@ -521,35 +552,36 @@ void RCSwitch::send(unsigned long code, unsigned int length) { * Transmit a single high-low pulse. */ void RCSwitch::transmit(HighLow pulses) { - uint8_t firstLogicLevel = (this->protocol.invertedSignal) ? LOW : HIGH; - uint8_t secondLogicLevel = (this->protocol.invertedSignal) ? HIGH : LOW; - - digitalWrite(this->nTransmitterPin, firstLogicLevel); - delayMicroseconds( this->protocol.pulseLength * pulses.high); - digitalWrite(this->nTransmitterPin, secondLogicLevel); - delayMicroseconds( this->protocol.pulseLength * pulses.low); + uint8_t firstLogicLevel = (this->protocol.invertedSignal) ? LOW : HIGH; + uint8_t secondLogicLevel = (this->protocol.invertedSignal) ? HIGH : LOW; + + digitalWrite(this->nTransmitterPin, firstLogicLevel); + delayMicroseconds(this->protocol.pulseLength * pulses.high); + digitalWrite(this->nTransmitterPin, secondLogicLevel); + delayMicroseconds(this->protocol.pulseLength * pulses.low); } #if not defined( RCSwitchDisableReceiving ) + /** * Enable receiving data */ void RCSwitch::enableReceive(int interrupt) { - this->nReceiverInterrupt = interrupt; - this->enableReceive(); + this->nReceiverInterrupt = interrupt; + this->enableReceive(); } void RCSwitch::enableReceive() { - if (this->nReceiverInterrupt != -1) { - RCSwitch::nReceivedValue = 0; - RCSwitch::nReceivedBitlength = 0; + if (this->nReceiverInterrupt != -1) { + RCSwitch::nReceivedValue = 0; + RCSwitch::nReceivedBitlength = 0; #if defined(RaspberryPi) // Raspberry Pi - wiringPiISR(this->nReceiverInterrupt, INT_EDGE_BOTH, &handleInterrupt); + wiringPiISR(this->nReceiverInterrupt, INT_EDGE_BOTH, &handleInterrupt); #else // Arduino - attachInterrupt(this->nReceiverInterrupt, handleInterrupt, CHANGE); + attachInterrupt(this->nReceiverInterrupt, handleInterrupt, CHANGE); #endif - } + } } /** @@ -557,42 +589,42 @@ void RCSwitch::enableReceive() { */ void RCSwitch::disableReceive() { #if not defined(RaspberryPi) // Arduino - detachInterrupt(this->nReceiverInterrupt); + detachInterrupt(this->nReceiverInterrupt); #endif // For Raspberry Pi (wiringPi) you can't unregister the ISR - this->nReceiverInterrupt = -1; + this->nReceiverInterrupt = -1; } bool RCSwitch::available() { - return RCSwitch::nReceivedValue != 0; + return RCSwitch::nReceivedValue != 0; } void RCSwitch::resetAvailable() { - RCSwitch::nReceivedValue = 0; + RCSwitch::nReceivedValue = 0; } unsigned long RCSwitch::getReceivedValue() { - return RCSwitch::nReceivedValue; + return RCSwitch::nReceivedValue; } unsigned int RCSwitch::getReceivedBitlength() { - return RCSwitch::nReceivedBitlength; + return RCSwitch::nReceivedBitlength; } unsigned int RCSwitch::getReceivedDelay() { - return RCSwitch::nReceivedDelay; + return RCSwitch::nReceivedDelay; } unsigned int RCSwitch::getReceivedProtocol() { - return RCSwitch::nReceivedProtocol; + return RCSwitch::nReceivedProtocol; } -unsigned int* RCSwitch::getReceivedRawdata() { - return RCSwitch::timings; +unsigned int *RCSwitch::getReceivedRawdata() { + return RCSwitch::timings; } /* helper function for the receiveProtocol method */ static inline unsigned int diff(int A, int B) { - return abs(A - B); + return abs(A - B); } /** @@ -603,15 +635,16 @@ bool RECEIVE_ATTR RCSwitch::receiveProtocol(const int p, unsigned int changeCoun const Protocol &pro = proto[p-1]; #else Protocol pro; - memcpy_P(&pro, &proto[p-1], sizeof(Protocol)); + memcpy_P(&pro, &proto[p - 1], sizeof(Protocol)); #endif unsigned long code = 0; //Assuming the longer pulse length is the pulse captured in timings[0] - const unsigned int syncLengthInPulses = ((pro.syncFactor.low) > (pro.syncFactor.high)) ? (pro.syncFactor.low) : (pro.syncFactor.high); + const unsigned int syncLengthInPulses = ((pro.syncFactor.low) > (pro.syncFactor.high)) ? (pro.syncFactor.low) + : (pro.syncFactor.high); const unsigned int delay = RCSwitch::timings[0] / syncLengthInPulses; const unsigned int delayTolerance = delay * RCSwitch::nReceiveTolerance / 100; - + /* For protocols that start low, the sync period looks like * _________ * _____________| |XXXXXXXXXXXX| @@ -659,43 +692,44 @@ bool RECEIVE_ATTR RCSwitch::receiveProtocol(const int p, unsigned int changeCoun void RECEIVE_ATTR RCSwitch::handleInterrupt() { - static unsigned int changeCount = 0; - static unsigned long lastTime = 0; - static unsigned int repeatCount = 0; - - const long time = micros(); - const unsigned int duration = time - lastTime; - - if (duration > RCSwitch::nSeparationLimit) { - // A long stretch without signal level change occurred. This could - // be the gap between two transmission. - if (diff(duration, RCSwitch::timings[0]) < 200) { - // This long signal is close in length to the long signal which - // started the previously recorded timings; this suggests that - // it may indeed by a a gap between two transmissions (we assume - // here that a sender will send the signal multiple times, - // with roughly the same gap between them). - repeatCount++; - if (repeatCount == 2) { - for(unsigned int i = 1; i <= numProto; i++) { - if (receiveProtocol(i, changeCount)) { - // receive succeeded for protocol i - break; - } + static unsigned int changeCount = 0; + static unsigned long lastTime = 0; + static unsigned int repeatCount = 0; + + const long time = micros(); + const unsigned int duration = time - lastTime; + + if (duration > RCSwitch::nSeparationLimit) { + // A long stretch without signal level change occurred. This could + // be the gap between two transmission. + if (diff(duration, RCSwitch::timings[0]) < 200) { + // This long signal is close in length to the long signal which + // started the previously recorded timings; this suggests that + // it may indeed by a a gap between two transmissions (we assume + // here that a sender will send the signal multiple times, + // with roughly the same gap between them). + repeatCount++; + if (repeatCount == 2) { + for (unsigned int i = 1; i <= numProto; i++) { + if (receiveProtocol(i, changeCount)) { + // receive succeeded for protocol i + break; + } + } + repeatCount = 0; + } } + changeCount = 0; + } + + // detect overflow + if (changeCount >= RCSWITCH_MAX_CHANGES) { + changeCount = 0; repeatCount = 0; - } } - changeCount = 0; - } - - // detect overflow - if (changeCount >= RCSWITCH_MAX_CHANGES) { - changeCount = 0; - repeatCount = 0; - } - - RCSwitch::timings[changeCount++] = duration; - lastTime = time; + + RCSwitch::timings[changeCount++] = duration; + lastTime = time; } + #endif diff --git a/Software/ATmega32U4/RF24.cpp b/Software/ATmega32U4/RF24.cpp index d71402c..10ed6e4 100644 --- a/Software/ATmega32U4/RF24.cpp +++ b/Software/ATmega32U4/RF24.cpp @@ -12,311 +12,303 @@ /****************************************************************************/ -void RF24::csn(bool mode) -{ +void RF24::csn(bool mode) { #if defined (RF24_TINY) - if (ce_pin != csn_pin) { - digitalWrite(csn_pin,mode); - } - else { - if (mode == HIGH) { - PORTB |= (1<CSN HIGH - delayMicroseconds(100); // allow csn to settle. - } - else { - PORTB &= ~(1<CSN LOW - delayMicroseconds(11); // allow csn to settle - } - } - // Return, CSN toggle complete - return; - + if (ce_pin != csn_pin) { + digitalWrite(csn_pin,mode); + } + else { + if (mode == HIGH) { + PORTB |= (1<CSN HIGH + delayMicroseconds(100); // allow csn to settle. + } + else { + PORTB &= ~(1<CSN LOW + delayMicroseconds(11); // allow csn to settle + } + } + // Return, CSN toggle complete + return; + #elif defined(ARDUINO) && !defined (RF24_SPI_TRANSACTIONS) - // Minimum ideal SPI bus speed is 2x data rate - // If we assume 2Mbs data rate and 16Mhz clock, a - // divider of 4 is the minimum we want. - // CLK:BUS 8Mhz:2Mhz, 16Mhz:4Mhz, or 20Mhz:5Mhz - - #if !defined (SOFTSPI) - _SPI.setBitOrder(MSBFIRST); - _SPI.setDataMode(SPI_MODE0); - _SPI.setClockDivider(SPI_CLOCK_DIV2); - #endif + // Minimum ideal SPI bus speed is 2x data rate + // If we assume 2Mbs data rate and 16Mhz clock, a + // divider of 4 is the minimum we want. + // CLK:BUS 8Mhz:2Mhz, 16Mhz:4Mhz, or 20Mhz:5Mhz + +#if !defined (SOFTSPI) + _SPI.setBitOrder(MSBFIRST); + _SPI.setDataMode(SPI_MODE0); + _SPI.setClockDivider(SPI_CLOCK_DIV2); +#endif #elif defined (RF24_RPi) - if(!mode) - _SPI.chipSelect(csn_pin); + if(!mode) + _SPI.chipSelect(csn_pin); #endif #if !defined (RF24_LINUX) - digitalWrite(csn_pin,mode); - delayMicroseconds(csDelay); + digitalWrite(csn_pin, mode); + delayMicroseconds(csDelay); #endif } /****************************************************************************/ -void RF24::ce(bool level) -{ - //Allow for 3-pin use on ATTiny - if (ce_pin != csn_pin) digitalWrite(ce_pin,level); +void RF24::ce(bool level) { + //Allow for 3-pin use on ATTiny + if (ce_pin != csn_pin) digitalWrite(ce_pin, level); } /****************************************************************************/ - inline void RF24::beginTransaction() { - #if defined (RF24_SPI_TRANSACTIONS) +inline void RF24::beginTransaction() { +#if defined (RF24_SPI_TRANSACTIONS) _SPI.beginTransaction(SPISettings(RF24_SPI_SPEED, MSBFIRST, SPI_MODE0)); - #endif +#endif csn(LOW); - } +} /****************************************************************************/ - inline void RF24::endTransaction() { +inline void RF24::endTransaction() { csn(HIGH); - #if defined (RF24_SPI_TRANSACTIONS) +#if defined (RF24_SPI_TRANSACTIONS) _SPI.endTransaction(); - #endif - } +#endif +} /****************************************************************************/ -uint8_t RF24::read_register(uint8_t reg, uint8_t* buf, uint8_t len) -{ - uint8_t status; +uint8_t RF24::read_register(uint8_t reg, uint8_t *buf, uint8_t len) { + uint8_t status; + +#if defined (RF24_LINUX) + beginTransaction(); //configures the spi settings for RPi, locks mutex and setting csn low + uint8_t * prx = spi_rxbuff; + uint8_t * ptx = spi_txbuff; + uint8_t size = len + 1; // Add register value to transmit buffer + + *ptx++ = ( R_REGISTER | ( REGISTER_MASK & reg ) ); - #if defined (RF24_LINUX) - beginTransaction(); //configures the spi settings for RPi, locks mutex and setting csn low - uint8_t * prx = spi_rxbuff; - uint8_t * ptx = spi_txbuff; - uint8_t size = len + 1; // Add register value to transmit buffer + while (len--){ *ptx++ = RF24_NOP; } // Dummy operation, just for reading - *ptx++ = ( R_REGISTER | ( REGISTER_MASK & reg ) ); + _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size); - while (len--){ *ptx++ = RF24_NOP; } // Dummy operation, just for reading - - _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size); - - status = *prx++; // status is 1st byte of receive buffer + status = *prx++; // status is 1st byte of receive buffer - // decrement before to skip status byte - while ( --size ){ *buf++ = *prx++; } - endTransaction(); //unlocks mutex and setting csn high + // decrement before to skip status byte + while ( --size ){ *buf++ = *prx++; } + endTransaction(); //unlocks mutex and setting csn high #else - beginTransaction(); - status = _SPI.transfer( R_REGISTER | ( REGISTER_MASK & reg ) ); - while ( len-- ){ - *buf++ = _SPI.transfer(0xff); - } - endTransaction(); + beginTransaction(); + status = _SPI.transfer(R_REGISTER | (REGISTER_MASK & reg)); + while (len--) { + *buf++ = _SPI.transfer(0xff); + } + endTransaction(); #endif - return status; + return status; } /****************************************************************************/ -uint8_t RF24::read_register(uint8_t reg) -{ - uint8_t result; - - #if defined (RF24_LINUX) - - beginTransaction(); - - uint8_t * prx = spi_rxbuff; - uint8_t * ptx = spi_txbuff; - *ptx++ = ( R_REGISTER | ( REGISTER_MASK & reg ) ); - *ptx++ = RF24_NOP ; // Dummy operation, just for reading - - _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, 2); - result = *++prx; // result is 2nd byte of receive buffer - - endTransaction(); - #else +uint8_t RF24::read_register(uint8_t reg) { + uint8_t result; + +#if defined (RF24_LINUX) + + beginTransaction(); + + uint8_t * prx = spi_rxbuff; + uint8_t * ptx = spi_txbuff; + *ptx++ = ( R_REGISTER | ( REGISTER_MASK & reg ) ); + *ptx++ = RF24_NOP ; // Dummy operation, just for reading - beginTransaction(); - _SPI.transfer( R_REGISTER | ( REGISTER_MASK & reg ) ); - result = _SPI.transfer(0xff); - endTransaction(); + _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, 2); + result = *++prx; // result is 2nd byte of receive buffer - #endif + endTransaction(); +#else + + beginTransaction(); + _SPI.transfer(R_REGISTER | (REGISTER_MASK & reg)); + result = _SPI.transfer(0xff); + endTransaction(); + +#endif - return result; + return result; } /****************************************************************************/ -uint8_t RF24::write_register(uint8_t reg, const uint8_t* buf, uint8_t len) -{ - uint8_t status; +uint8_t RF24::write_register(uint8_t reg, const uint8_t *buf, uint8_t len) { + uint8_t status; - #if defined (RF24_LINUX) - beginTransaction(); - uint8_t * prx = spi_rxbuff; - uint8_t * ptx = spi_txbuff; - uint8_t size = len + 1; // Add register value to transmit buffer +#if defined (RF24_LINUX) + beginTransaction(); + uint8_t * prx = spi_rxbuff; + uint8_t * ptx = spi_txbuff; + uint8_t size = len + 1; // Add register value to transmit buffer - *ptx++ = ( W_REGISTER | ( REGISTER_MASK & reg ) ); - while ( len-- ) - *ptx++ = *buf++; - - _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size); - status = *prx; // status is 1st byte of receive buffer - endTransaction(); - #else + *ptx++ = ( W_REGISTER | ( REGISTER_MASK & reg ) ); + while ( len-- ) + *ptx++ = *buf++; - beginTransaction(); - status = _SPI.transfer( W_REGISTER | ( REGISTER_MASK & reg ) ); - while ( len-- ) - _SPI.transfer(*buf++); - endTransaction(); + _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size); + status = *prx; // status is 1st byte of receive buffer + endTransaction(); +#else - #endif + beginTransaction(); + status = _SPI.transfer(W_REGISTER | (REGISTER_MASK & reg)); + while (len--) + _SPI.transfer(*buf++); + endTransaction(); + +#endif - return status; + return status; } /****************************************************************************/ -uint8_t RF24::write_register(uint8_t reg, uint8_t value) -{ - uint8_t status; +uint8_t RF24::write_register(uint8_t reg, uint8_t value) { + uint8_t status; - IF_SERIAL_DEBUG(printf_P(PSTR("write_register(%02x,%02x)\r\n"),reg,value)); + IF_SERIAL_DEBUG(printf_P(PSTR("write_register(%02x,%02x)\r\n"), reg, value)); - #if defined (RF24_LINUX) +#if defined (RF24_LINUX) beginTransaction(); - uint8_t * prx = spi_rxbuff; - uint8_t * ptx = spi_txbuff; - *ptx++ = ( W_REGISTER | ( REGISTER_MASK & reg ) ); - *ptx = value ; - - _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, 2); - status = *prx++; // status is 1st byte of receive buffer - endTransaction(); - #else + uint8_t * prx = spi_rxbuff; + uint8_t * ptx = spi_txbuff; + *ptx++ = ( W_REGISTER | ( REGISTER_MASK & reg ) ); + *ptx = value ; - beginTransaction(); - status = _SPI.transfer( W_REGISTER | ( REGISTER_MASK & reg ) ); - _SPI.transfer(value); - endTransaction(); + _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, 2); + status = *prx++; // status is 1st byte of receive buffer + endTransaction(); +#else + + beginTransaction(); + status = _SPI.transfer(W_REGISTER | (REGISTER_MASK & reg)); + _SPI.transfer(value); + endTransaction(); - #endif +#endif - return status; + return status; } /****************************************************************************/ -uint8_t RF24::write_payload(const void* buf, uint8_t data_len, const uint8_t writeType) -{ - uint8_t status; - const uint8_t* current = reinterpret_cast(buf); - - data_len = rf24_min(data_len, payload_size); - uint8_t blank_len = dynamic_payloads_enabled ? 0 : payload_size - data_len; - - //printf("[Writing %u bytes %u blanks]",data_len,blank_len); - IF_SERIAL_DEBUG( printf("[Writing %u bytes %u blanks]\n",data_len,blank_len); ); - - #if defined (RF24_LINUX) - beginTransaction(); - uint8_t * prx = spi_rxbuff; - uint8_t * ptx = spi_txbuff; +uint8_t RF24::write_payload(const void *buf, uint8_t data_len, const uint8_t writeType) { + uint8_t status; + const uint8_t *current = reinterpret_cast(buf); + + data_len = rf24_min(data_len, payload_size); + uint8_t blank_len = dynamic_payloads_enabled ? 0 : payload_size - data_len; + + //printf("[Writing %u bytes %u blanks]",data_len,blank_len); + IF_SERIAL_DEBUG(printf("[Writing %u bytes %u blanks]\n", data_len, blank_len); ); + +#if defined (RF24_LINUX) + beginTransaction(); + uint8_t * prx = spi_rxbuff; + uint8_t * ptx = spi_txbuff; uint8_t size; - size = data_len + blank_len + 1 ; // Add register value to transmit buffer + size = data_len + blank_len + 1 ; // Add register value to transmit buffer - *ptx++ = writeType; + *ptx++ = writeType; while ( data_len-- ) *ptx++ = *current++; while ( blank_len-- ) - *ptx++ = 0; - - _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size); - status = *prx; // status is 1st byte of receive buffer - endTransaction(); + *ptx++ = 0; - #else + _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size); + status = *prx; // status is 1st byte of receive buffer + endTransaction(); - beginTransaction(); - status = _SPI.transfer( writeType ); - while ( data_len-- ) { - _SPI.transfer(*current++); - } - while ( blank_len-- ) { - _SPI.transfer(0); - } - endTransaction(); +#else - #endif + beginTransaction(); + status = _SPI.transfer(writeType); + while (data_len--) { + _SPI.transfer(*current++); + } + while (blank_len--) { + _SPI.transfer(0); + } + endTransaction(); + +#endif - return status; + return status; } /****************************************************************************/ -uint8_t RF24::read_payload(void* buf, uint8_t data_len) -{ - uint8_t status; - uint8_t* current = reinterpret_cast(buf); - - if(data_len > payload_size) data_len = payload_size; - uint8_t blank_len = dynamic_payloads_enabled ? 0 : payload_size - data_len; - - //printf("[Reading %u bytes %u blanks]",data_len,blank_len); - - IF_SERIAL_DEBUG( printf("[Reading %u bytes %u blanks]\n",data_len,blank_len); ); - - #if defined (RF24_LINUX) - beginTransaction(); - uint8_t * prx = spi_rxbuff; - uint8_t * ptx = spi_txbuff; +uint8_t RF24::read_payload(void *buf, uint8_t data_len) { + uint8_t status; + uint8_t *current = reinterpret_cast(buf); + + if (data_len > payload_size) data_len = payload_size; + uint8_t blank_len = dynamic_payloads_enabled ? 0 : payload_size - data_len; + + //printf("[Reading %u bytes %u blanks]",data_len,blank_len); + + IF_SERIAL_DEBUG(printf("[Reading %u bytes %u blanks]\n", data_len, blank_len); ); + +#if defined (RF24_LINUX) + beginTransaction(); + uint8_t * prx = spi_rxbuff; + uint8_t * ptx = spi_txbuff; uint8_t size; size = data_len + blank_len + 1; // Add register value to transmit buffer - *ptx++ = R_RX_PAYLOAD; - while(--size) - *ptx++ = RF24_NOP; - - size = data_len + blank_len + 1; // Size has been lost during while, re affect - - _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size); - - status = *prx++; // 1st byte is status - + *ptx++ = R_RX_PAYLOAD; + while(--size) + *ptx++ = RF24_NOP; + + size = data_len + blank_len + 1; // Size has been lost during while, re affect + + _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size); + + status = *prx++; // 1st byte is status + if (data_len > 0) { while ( --data_len ) // Decrement before to skip 1st status byte *current++ = *prx++; - + *current = *prx; } - endTransaction(); - #else + endTransaction(); +#else - beginTransaction(); - status = _SPI.transfer( R_RX_PAYLOAD ); - while ( data_len-- ) { - *current++ = _SPI.transfer(0xFF); - } - while ( blank_len-- ) { - _SPI.transfer(0xff); - } - endTransaction(); + beginTransaction(); + status = _SPI.transfer(R_RX_PAYLOAD); + while (data_len--) { + *current++ = _SPI.transfer(0xFF); + } + while (blank_len--) { + _SPI.transfer(0xff); + } + endTransaction(); - #endif +#endif - return status; + return status; } /****************************************************************************/ -uint8_t RF24::Reader(void* buf){ - uint8_t rx_len = read_register(R_RX_PAYLOAD); +uint8_t RF24::Reader(void *buf) { + uint8_t rx_len = read_register(R_RX_PAYLOAD); /* if(rx_len>0 && rx_len<33) { @@ -329,119 +321,116 @@ uint8_t RF24::Reader(void* buf){ // NRF_CE_L(); // read_register(R_RX_PAYLOAD,buf,5); // NRF_CE_H(); - read_payload( buf, 5 ); - write_register(NRF_STATUS,_BV(RX_DR) | _BV(MAX_RT) | _BV(TX_DS) ); - return rx_len; + read_payload(buf, 5); + write_register(NRF_STATUS, _BV(RX_DR) | _BV(MAX_RT) | _BV(TX_DS)); + return rx_len; } /****************************************************************************/ -uint8_t RF24::flush_rx(void) -{ - return spiTrans( FLUSH_RX ); +uint8_t RF24::flush_rx(void) { + return spiTrans(FLUSH_RX); } /****************************************************************************/ -uint8_t RF24::flush_tx(void) -{ - return spiTrans( FLUSH_TX ); +uint8_t RF24::flush_tx(void) { + return spiTrans(FLUSH_TX); } /****************************************************************************/ -uint8_t RF24::spiTrans(uint8_t cmd){ +uint8_t RF24::spiTrans(uint8_t cmd) { + + uint8_t status; - uint8_t status; - - beginTransaction(); - status = _SPI.transfer( cmd ); - endTransaction(); - - return status; + beginTransaction(); + status = _SPI.transfer(cmd); + endTransaction(); + + return status; } /****************************************************************************/ -uint8_t RF24::get_status(void) -{ - return spiTrans(RF24_NOP); +uint8_t RF24::get_status(void) { + return spiTrans(RF24_NOP); } /****************************************************************************/ #if !defined (MINIMAL) -void RF24::print_status(uint8_t status) -{ - printf_P(PSTR("STATUS\t\t = 0x%02x RX_DR=%x TX_DS=%x MAX_RT=%x RX_P_NO=%x TX_FULL=%x\r\n"), - status, - (status & _BV(RX_DR))?1:0, - (status & _BV(TX_DS))?1:0, - (status & _BV(MAX_RT))?1:0, - ((status >> RX_P_NO) & 0x07), - (status & _BV(TX_FULL))?1:0 - ); + +void RF24::print_status(uint8_t status) { + printf_P(PSTR("STATUS\t\t = 0x%02x RX_DR=%x TX_DS=%x MAX_RT=%x RX_P_NO=%x TX_FULL=%x\r\n"), + status, + (status & _BV(RX_DR)) ? 1 : 0, + (status & _BV(TX_DS)) ? 1 : 0, + (status & _BV(MAX_RT)) ? 1 : 0, + ((status >> RX_P_NO) & 0x07), + (status & _BV(TX_FULL)) ? 1 : 0 + ); } /****************************************************************************/ -void RF24::print_observe_tx(uint8_t value) -{ - printf_P(PSTR("OBSERVE_TX=%02x: POLS_CNT=%x ARC_CNT=%x\r\n"), - value, - (value >> PLOS_CNT) & 0x0F, - (value >> ARC_CNT) & 0x0F - ); +void RF24::print_observe_tx(uint8_t value) { + printf_P(PSTR("OBSERVE_TX=%02x: POLS_CNT=%x ARC_CNT=%x\r\n"), + value, + (value >> PLOS_CNT) & 0x0F, + (value >> ARC_CNT) & 0x0F + ); } /****************************************************************************/ -void RF24::print_byte_register(const char* name, uint8_t reg, uint8_t qty) -{ - //char extra_tab = strlen_P(name) < 8 ? '\t' : 0; - //printf_P(PSTR(PRIPSTR"\t%c ="),name,extra_tab); - #if defined (RF24_LINUX) +void RF24::print_byte_register(const char *name, uint8_t reg, uint8_t qty) { + //char extra_tab = strlen_P(name) < 8 ? '\t' : 0; + //printf_P(PSTR(PRIPSTR"\t%c ="),name,extra_tab); +#if defined (RF24_LINUX) printf("%s\t =", name); - #else - printf_P(PSTR(PRIPSTR"\t ="),name); - #endif - while (qty--) - printf_P(PSTR(" 0x%02x"),read_register(reg++)); - printf_P(PSTR("\r\n")); +#else + printf_P(PSTR(PRIPSTR + "\t ="),name); +#endif + while (qty--) + printf_P(PSTR(" 0x%02x"), read_register(reg++)); + printf_P(PSTR("\r\n")); } /****************************************************************************/ -void RF24::print_address_register(const char* name, uint8_t reg, uint8_t qty) -{ +void RF24::print_address_register(const char *name, uint8_t reg, uint8_t qty) { - #if defined (RF24_LINUX) +#if defined (RF24_LINUX) printf("%s\t =",name); - #else - printf_P(PSTR(PRIPSTR"\t ="),name); - #endif - while (qty--) - { - uint8_t buffer[addr_width]; - read_register(reg++,buffer,sizeof buffer); - - printf_P(PSTR(" 0x")); - uint8_t* bufptr = buffer + sizeof buffer; - while( --bufptr >= buffer ) - printf_P(PSTR("%02x"),*bufptr); - } - - printf_P(PSTR("\r\n")); +#else + printf_P(PSTR(PRIPSTR + "\t ="),name); +#endif + while (qty--) { + uint8_t buffer[addr_width]; + read_register(reg++, buffer, sizeof buffer); + + printf_P(PSTR(" 0x")); + uint8_t *bufptr = buffer + sizeof buffer; + while (--bufptr >= buffer) + printf_P(PSTR("%02x"), *bufptr); + } + + printf_P(PSTR("\r\n")); } + #endif + /****************************************************************************/ -RF24::RF24(uint16_t _cepin, uint16_t _cspin): - ce_pin(_cepin), csn_pin(_cspin), p_variant(false), - payload_size(32), dynamic_payloads_enabled(false), addr_width(5),csDelay(5)//,pipe0_reading_address(0) +RF24::RF24(uint16_t _cepin, uint16_t _cspin) : + ce_pin(_cepin), csn_pin(_cspin), p_variant(false), + payload_size(32), dynamic_payloads_enabled(false), addr_width(5), csDelay(5)//,pipe0_reading_address(0) { - pipe0_reading_address[0]=0; + pipe0_reading_address[0] = 0; } /****************************************************************************/ @@ -457,66 +446,79 @@ RF24::RF24(uint16_t _cepin, uint16_t _cspin, uint32_t _spi_speed): /****************************************************************************/ -void RF24::setChannel(uint8_t channel) -{ - const uint8_t max_channel = 125; - write_register(RF_CH,rf24_min(channel,max_channel)); +void RF24::setChannel(uint8_t channel) { + const uint8_t max_channel = 125; + write_register(RF_CH, rf24_min(channel, max_channel)); } -uint8_t RF24::getChannel() -{ - - return read_register(RF_CH); +uint8_t RF24::getChannel() { + + return read_register(RF_CH); } + /****************************************************************************/ -void RF24::setPayloadSize(uint8_t size) -{ - payload_size = rf24_min(size,32); +void RF24::setPayloadSize(uint8_t size) { + payload_size = rf24_min(size, 32); } /****************************************************************************/ -uint8_t RF24::getPayloadSize(void) -{ - return payload_size; +uint8_t RF24::getPayloadSize(void) { + return payload_size; } /****************************************************************************/ #if !defined (MINIMAL) -static const char rf24_datarate_e_str_0[] PROGMEM = "1MBPS"; -static const char rf24_datarate_e_str_1[] PROGMEM = "2MBPS"; -static const char rf24_datarate_e_str_2[] PROGMEM = "250KBPS"; -static const char * const rf24_datarate_e_str_P[] PROGMEM = { - rf24_datarate_e_str_0, - rf24_datarate_e_str_1, - rf24_datarate_e_str_2, +static const char rf24_datarate_e_str_0[] +PROGMEM = "1MBPS"; +static const char rf24_datarate_e_str_1[] +PROGMEM = "2MBPS"; +static const char rf24_datarate_e_str_2[] +PROGMEM = "250KBPS"; +static const char *const rf24_datarate_e_str_P[] +PROGMEM = { + rf24_datarate_e_str_0, + rf24_datarate_e_str_1, + rf24_datarate_e_str_2, }; -static const char rf24_model_e_str_0[] PROGMEM = "nRF24L01"; -static const char rf24_model_e_str_1[] PROGMEM = "nRF24L01+"; -static const char * const rf24_model_e_str_P[] PROGMEM = { - rf24_model_e_str_0, - rf24_model_e_str_1, +static const char rf24_model_e_str_0[] +PROGMEM = "nRF24L01"; +static const char rf24_model_e_str_1[] +PROGMEM = "nRF24L01+"; +static const char *const rf24_model_e_str_P[] +PROGMEM = { + rf24_model_e_str_0, + rf24_model_e_str_1, }; -static const char rf24_crclength_e_str_0[] PROGMEM = "Disabled"; -static const char rf24_crclength_e_str_1[] PROGMEM = "8 bits"; -static const char rf24_crclength_e_str_2[] PROGMEM = "16 bits" ; -static const char * const rf24_crclength_e_str_P[] PROGMEM = { - rf24_crclength_e_str_0, - rf24_crclength_e_str_1, - rf24_crclength_e_str_2, +static const char rf24_crclength_e_str_0[] +PROGMEM = "Disabled"; +static const char rf24_crclength_e_str_1[] +PROGMEM = "8 bits"; +static const char rf24_crclength_e_str_2[] +PROGMEM = "16 bits"; +static const char *const rf24_crclength_e_str_P[] +PROGMEM = { + rf24_crclength_e_str_0, + rf24_crclength_e_str_1, + rf24_crclength_e_str_2, }; -static const char rf24_pa_dbm_e_str_0[] PROGMEM = "PA_MIN"; -static const char rf24_pa_dbm_e_str_1[] PROGMEM = "PA_LOW"; -static const char rf24_pa_dbm_e_str_2[] PROGMEM = "PA_HIGH"; -static const char rf24_pa_dbm_e_str_3[] PROGMEM = "PA_MAX"; -static const char * const rf24_pa_dbm_e_str_P[] PROGMEM = { - rf24_pa_dbm_e_str_0, - rf24_pa_dbm_e_str_1, - rf24_pa_dbm_e_str_2, - rf24_pa_dbm_e_str_3, +static const char rf24_pa_dbm_e_str_0[] +PROGMEM = "PA_MIN"; +static const char rf24_pa_dbm_e_str_1[] +PROGMEM = "PA_LOW"; +static const char rf24_pa_dbm_e_str_2[] +PROGMEM = "PA_HIGH"; +static const char rf24_pa_dbm_e_str_3[] +PROGMEM = "PA_MAX"; +static const char *const rf24_pa_dbm_e_str_P[] +PROGMEM = { + rf24_pa_dbm_e_str_0, + rf24_pa_dbm_e_str_1, + rf24_pa_dbm_e_str_2, + rf24_pa_dbm_e_str_3, }; #if defined (RF24_LINUX) @@ -532,433 +534,435 @@ static const char * const rf24_csn_e_str_P[] = { }; #endif -void RF24::printDetails(void) -{ +void RF24::printDetails(void) { #if defined (RF24_RPi) - printf("================ SPI Configuration ================\n" ); - if (csn_pin < BCM2835_SPI_CS_NONE ){ - printf("CSN Pin \t = %s\n",rf24_csn_e_str_P[csn_pin]); - }else{ - printf("CSN Pin \t = Custom GPIO%d%s\n", csn_pin, - csn_pin==RPI_V2_GPIO_P1_26 ? " (CE1) Software Driven" : "" ); - } - printf("CE Pin \t = Custom GPIO%d\n", ce_pin ); - printf("Clock Speed\t = " ); - switch (spi_speed) - { - case BCM2835_SPI_SPEED_64MHZ : printf("64 Mhz"); break ; - case BCM2835_SPI_SPEED_32MHZ : printf("32 Mhz"); break ; - case BCM2835_SPI_SPEED_16MHZ : printf("16 Mhz"); break ; - case BCM2835_SPI_SPEED_8MHZ : printf("8 Mhz"); break ; - case BCM2835_SPI_SPEED_4MHZ : printf("4 Mhz"); break ; - case BCM2835_SPI_SPEED_2MHZ : printf("2 Mhz"); break ; - case BCM2835_SPI_SPEED_1MHZ : printf("1 Mhz"); break ; - case BCM2835_SPI_SPEED_512KHZ: printf("512 KHz"); break ; - case BCM2835_SPI_SPEED_256KHZ: printf("256 KHz"); break ; - case BCM2835_SPI_SPEED_128KHZ: printf("128 KHz"); break ; - case BCM2835_SPI_SPEED_64KHZ : printf("64 KHz"); break ; - case BCM2835_SPI_SPEED_32KHZ : printf("32 KHz"); break ; - case BCM2835_SPI_SPEED_16KHZ : printf("16 KHz"); break ; - case BCM2835_SPI_SPEED_8KHZ : printf("8 KHz"); break ; - default : printf("8 Mhz"); break ; - } - printf("\n================ NRF Configuration ================\n"); - + printf("================ SPI Configuration ================\n" ); + if (csn_pin < BCM2835_SPI_CS_NONE ){ + printf("CSN Pin \t = %s\n",rf24_csn_e_str_P[csn_pin]); + }else{ + printf("CSN Pin \t = Custom GPIO%d%s\n", csn_pin, + csn_pin==RPI_V2_GPIO_P1_26 ? " (CE1) Software Driven" : "" ); + } + printf("CE Pin \t = Custom GPIO%d\n", ce_pin ); + printf("Clock Speed\t = " ); + switch (spi_speed) + { + case BCM2835_SPI_SPEED_64MHZ : printf("64 Mhz"); break ; + case BCM2835_SPI_SPEED_32MHZ : printf("32 Mhz"); break ; + case BCM2835_SPI_SPEED_16MHZ : printf("16 Mhz"); break ; + case BCM2835_SPI_SPEED_8MHZ : printf("8 Mhz"); break ; + case BCM2835_SPI_SPEED_4MHZ : printf("4 Mhz"); break ; + case BCM2835_SPI_SPEED_2MHZ : printf("2 Mhz"); break ; + case BCM2835_SPI_SPEED_1MHZ : printf("1 Mhz"); break ; + case BCM2835_SPI_SPEED_512KHZ: printf("512 KHz"); break ; + case BCM2835_SPI_SPEED_256KHZ: printf("256 KHz"); break ; + case BCM2835_SPI_SPEED_128KHZ: printf("128 KHz"); break ; + case BCM2835_SPI_SPEED_64KHZ : printf("64 KHz"); break ; + case BCM2835_SPI_SPEED_32KHZ : printf("32 KHz"); break ; + case BCM2835_SPI_SPEED_16KHZ : printf("16 KHz"); break ; + case BCM2835_SPI_SPEED_8KHZ : printf("8 KHz"); break ; + default : printf("8 Mhz"); break ; + } + printf("\n================ NRF Configuration ================\n"); + #endif //Linux - print_status(get_status()); + print_status(get_status()); + + print_address_register(PSTR("RX_ADDR_P0-1"), RX_ADDR_P0, 2); + print_address_register(PSTR("TX_ADDR\t"), TX_ADDR); + + print_byte_register(PSTR("RX_PW_P0-6"), RX_PW_P0, 6); + print_byte_register(PSTR("EN_AA\t"), EN_AA); + print_byte_register(PSTR("EN_RXADDR"), EN_RXADDR); + print_byte_register(PSTR("RF_CH\t"), RF_CH); + print_byte_register(PSTR("RF_SETUP"), RF_SETUP); + print_byte_register(PSTR("CONFIG\t"), NRF_CONFIG); + print_byte_register(PSTR("DYNPD/FEATURE"), DYNPD, 2); + + printf_P(PSTR("Data Rate\t = " + PRIPSTR + "\r\n"),pgm_read_word(&rf24_datarate_e_str_P[getDataRate()])); + printf_P(PSTR("Model\t\t = " + PRIPSTR + "\r\n"),pgm_read_word(&rf24_model_e_str_P[isPVariant()])); + printf_P(PSTR("CRC Length\t = " + PRIPSTR + "\r\n"),pgm_read_word(&rf24_crclength_e_str_P[getCRCLength()])); + printf_P(PSTR("PA Power\t = " + PRIPSTR + "\r\n"), pgm_read_word(&rf24_pa_dbm_e_str_P[getPALevel()])); + +} + +void RF24::print_config(void) { + for (int i = 0; i < 30; i++) { + Serial.print(i, HEX); + Serial.print(" "); + Serial.print(read_register(i), HEX); + Serial.println(" "); + } +} - print_address_register(PSTR("RX_ADDR_P0-1"),RX_ADDR_P0,2); - print_address_register(PSTR("TX_ADDR\t"),TX_ADDR); - print_byte_register(PSTR("RX_PW_P0-6"),RX_PW_P0,6); - print_byte_register(PSTR("EN_AA\t"),EN_AA); - print_byte_register(PSTR("EN_RXADDR"),EN_RXADDR); - print_byte_register(PSTR("RF_CH\t"),RF_CH); - print_byte_register(PSTR("RF_SETUP"),RF_SETUP); - print_byte_register(PSTR("CONFIG\t"),NRF_CONFIG); - print_byte_register(PSTR("DYNPD/FEATURE"),DYNPD,2); +#endif - printf_P(PSTR("Data Rate\t = " PRIPSTR "\r\n"),pgm_read_word(&rf24_datarate_e_str_P[getDataRate()])); - printf_P(PSTR("Model\t\t = " PRIPSTR "\r\n"),pgm_read_word(&rf24_model_e_str_P[isPVariant()])); - printf_P(PSTR("CRC Length\t = " PRIPSTR "\r\n"),pgm_read_word(&rf24_crclength_e_str_P[getCRCLength()])); - printf_P(PSTR("PA Power\t = " PRIPSTR "\r\n"), pgm_read_word(&rf24_pa_dbm_e_str_P[getPALevel()])); +/****************************************************************************/ -} +bool RF24::begin(void) { -void RF24::print_config(void){ - for (int i=0;i<30;i++){ - Serial.print(i,HEX); - Serial.print(" "); - Serial.print(read_register(i),HEX); - Serial.println(" "); - } -} + uint8_t setup = 0; +#if defined (RF24_LINUX) +#if defined (MRAA) + GPIO(); + gpio.begin(ce_pin,csn_pin); #endif -/****************************************************************************/ -bool RF24::begin(void) -{ +#ifdef RF24_RPi + switch(csn_pin){ //Ensure valid hardware CS pin + case 0: break; + case 1: break; + // Allow BCM2835 enums for RPi + case 8: csn_pin = 0; break; + case 7: csn_pin = 1; break; + default: csn_pin = 0; break; + } +#endif - uint8_t setup=0; - - #if defined (RF24_LINUX) - - #if defined (MRAA) - GPIO(); - gpio.begin(ce_pin,csn_pin); - #endif - - #ifdef RF24_RPi - switch(csn_pin){ //Ensure valid hardware CS pin - case 0: break; - case 1: break; - // Allow BCM2835 enums for RPi - case 8: csn_pin = 0; break; - case 7: csn_pin = 1; break; - default: csn_pin = 0; break; - } - #endif - - _SPI.begin(csn_pin); + _SPI.begin(csn_pin); + + pinMode(ce_pin,OUTPUT); + ce(LOW); - pinMode(ce_pin,OUTPUT); - ce(LOW); + delay(100); - delay(100); - - #elif defined(LITTLEWIRE) +#elif defined(LITTLEWIRE) pinMode(csn_pin,OUTPUT); _SPI.begin(); csn(HIGH); - #elif defined(XMEGA_D3) - if (ce_pin != csn_pin) pinMode(ce_pin,OUTPUT); - _SPI.begin(csn_pin); - ce(LOW); - csn(HIGH); - delay(200); - #else +#elif defined(XMEGA_D3) + if (ce_pin != csn_pin) pinMode(ce_pin,OUTPUT); + _SPI.begin(csn_pin); + ce(LOW); + csn(HIGH); + delay(200); +#else // Initialize pins - if (ce_pin != csn_pin) pinMode(ce_pin,OUTPUT); - - #if ! defined(LITTLEWIRE) - if (ce_pin != csn_pin) - #endif - pinMode(csn_pin,OUTPUT); - + if (ce_pin != csn_pin) pinMode(ce_pin, OUTPUT); + +#if !defined(LITTLEWIRE) + if (ce_pin != csn_pin) +#endif + pinMode(csn_pin, OUTPUT); + _SPI.begin(); ce(LOW); - csn(HIGH); - #if defined (__ARDUINO_X86__) - delay(100); - #endif - #endif //Linux - - // Must allow the radio time to settle else configuration bits will not necessarily stick. - // This is actually only required following power up but some settling time also appears to - // be required after resets too. For full coverage, we'll always assume the worst. - // Enabling 16b CRC is by far the most obvious case if the wrong timing is used - or skipped. - // Technically we require 4.5ms + 14us as a worst case. We'll just call it 5ms for good measure. - // WARNING: Delay is based on P-variant whereby non-P *may* require different timing. - delay( 5 ) ; - - // Reset NRF_CONFIG and enable 16-bit CRC. - write_register( NRF_CONFIG, 0x0C ) ; - - // Set 1500uS (minimum for 32B payload in ESB@250KBPS) timeouts, to make testing a little easier - // WARNING: If this is ever lowered, either 250KBS mode with AA is broken or maximum packet - // sizes must never be used. See documentation for a more complete explanation. - setRetries(5,15); - - // Reset value is MAX - //setPALevel( RF24_PA_MAX ) ; - - // check for connected module and if this is a p nRF24l01 variant - // - if( setDataRate( RF24_250KBPS ) ) - { - p_variant = true ; - } - setup = read_register(RF_SETUP); - /*if( setup == 0b00001110 ) // register default for nRF24L01P - { - p_variant = true ; - }*/ - - // Then set the data rate to the slowest (and most reliable) speed supported by all - // hardware. - setDataRate( RF24_1MBPS ) ; - - // Initialize CRC and request 2-byte (16bit) CRC - //setCRCLength( RF24_CRC_16 ) ; - - // Disable dynamic payloads, to match dynamic_payloads_enabled setting - Reset value is 0 - toggle_features(); - write_register(FEATURE,0 ); - write_register(DYNPD,0); - dynamic_payloads_enabled = false; - - // Reset current status - // Notice reset and flush is the last thing we do - write_register(NRF_STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); - - // Set up default configuration. Callers can always change it later. - // This channel should be universally safe and not bleed over into adjacent - // spectrum. - setChannel(76); - - // Flush buffers - flush_rx(); - flush_tx(); - - powerUp(); //Power up by default when begin() is called - - // Enable PTX, do not write CE high so radio will remain in standby I mode ( 130us max to transition to RX or TX instead of 1500us from powerUp ) - // PTX should use only 22uA of power - write_register(NRF_CONFIG, ( read_register(NRF_CONFIG) ) & ~_BV(PRIM_RX) ); - - // if setup is 0 or ff then there was no response from module - return ( setup != 0 && setup != 0xff ); -} - -/****************************************************************************/ - -bool RF24::isChipConnected() -{ - uint8_t setup = read_register(SETUP_AW); - if(setup >= 1 && setup <= 3) - { - return true; - } + csn(HIGH); +#if defined (__ARDUINO_X86__) + delay(100); +#endif +#endif //Linux - return false; + // Must allow the radio time to settle else configuration bits will not necessarily stick. + // This is actually only required following power up but some settling time also appears to + // be required after resets too. For full coverage, we'll always assume the worst. + // Enabling 16b CRC is by far the most obvious case if the wrong timing is used - or skipped. + // Technically we require 4.5ms + 14us as a worst case. We'll just call it 5ms for good measure. + // WARNING: Delay is based on P-variant whereby non-P *may* require different timing. + delay(5); + + // Reset NRF_CONFIG and enable 16-bit CRC. + write_register(NRF_CONFIG, 0x0C); + + // Set 1500uS (minimum for 32B payload in ESB@250KBPS) timeouts, to make testing a little easier + // WARNING: If this is ever lowered, either 250KBS mode with AA is broken or maximum packet + // sizes must never be used. See documentation for a more complete explanation. + setRetries(5, 15); + + // Reset value is MAX + //setPALevel( RF24_PA_MAX ) ; + + // check for connected module and if this is a p nRF24l01 variant + // + if (setDataRate(RF24_250KBPS)) { + p_variant = true; + } + setup = read_register(RF_SETUP); + /*if( setup == 0b00001110 ) // register default for nRF24L01P + { + p_variant = true ; + }*/ + + // Then set the data rate to the slowest (and most reliable) speed supported by all + // hardware. + setDataRate(RF24_1MBPS); + + // Initialize CRC and request 2-byte (16bit) CRC + //setCRCLength( RF24_CRC_16 ) ; + + // Disable dynamic payloads, to match dynamic_payloads_enabled setting - Reset value is 0 + toggle_features(); + write_register(FEATURE, 0); + write_register(DYNPD, 0); + dynamic_payloads_enabled = false; + + // Reset current status + // Notice reset and flush is the last thing we do + write_register(NRF_STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT)); + + // Set up default configuration. Callers can always change it later. + // This channel should be universally safe and not bleed over into adjacent + // spectrum. + setChannel(76); + + // Flush buffers + flush_rx(); + flush_tx(); + + powerUp(); //Power up by default when begin() is called + + // Enable PTX, do not write CE high so radio will remain in standby I mode ( 130us max to transition to RX or TX instead of 1500us from powerUp ) + // PTX should use only 22uA of power + write_register(NRF_CONFIG, (read_register(NRF_CONFIG)) & ~_BV(PRIM_RX)); + + // if setup is 0 or ff then there was no response from module + return (setup != 0 && setup != 0xff); } /****************************************************************************/ -void RF24::startListening(void) -{ - #if !defined (RF24_TINY) && ! defined(LITTLEWIRE) - powerUp(); - #endif - write_register(NRF_CONFIG, read_register(NRF_CONFIG) | _BV(PRIM_RX)); - write_register(NRF_STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); - ce(HIGH); - // Restore the pipe0 adddress, if exists - if (pipe0_reading_address[0] > 0){ - write_register(RX_ADDR_P0, pipe0_reading_address, addr_width); - }else{ - closeReadingPipe(0); - } - - // Flush buffers - //flush_rx(); - if(read_register(FEATURE) & _BV(EN_ACK_PAY)){ - flush_tx(); - } - - // Go! - //delayMicroseconds(100); -} - -/****************************************************************************/ -static const uint8_t child_pipe_enable[] PROGMEM = -{ - ERX_P0, ERX_P1, ERX_P2, ERX_P3, ERX_P4, ERX_P5 -}; +bool RF24::isChipConnected() { + uint8_t setup = read_register(SETUP_AW); + if (setup >= 1 && setup <= 3) { + return true; + } -void RF24::stopListening(void) -{ - ce(LOW); + return false; +} + +/****************************************************************************/ - delayMicroseconds(txDelay); - - if(read_register(FEATURE) & _BV(EN_ACK_PAY)){ - delayMicroseconds(txDelay); //200 - flush_tx(); - } - //flush_rx(); - write_register(NRF_CONFIG, ( read_register(NRF_CONFIG) ) & ~_BV(PRIM_RX) ); - - #if defined (RF24_TINY) || defined (LITTLEWIRE) - // for 3 pins solution TX mode is only left with additonal powerDown/powerUp cycle - if (ce_pin == csn_pin) { - powerDown(); - powerUp(); - } - #endif - write_register(EN_RXADDR,read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[0]))); // Enable RX on pipe0 - - //delayMicroseconds(100); +void RF24::startListening(void) { +#if !defined (RF24_TINY) && !defined(LITTLEWIRE) + powerUp(); +#endif + write_register(NRF_CONFIG, read_register(NRF_CONFIG) | _BV(PRIM_RX)); + write_register(NRF_STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT)); + ce(HIGH); + // Restore the pipe0 adddress, if exists + if (pipe0_reading_address[0] > 0) { + write_register(RX_ADDR_P0, pipe0_reading_address, addr_width); + } else { + closeReadingPipe(0); + } + // Flush buffers + //flush_rx(); + if (read_register(FEATURE) & _BV(EN_ACK_PAY)) { + flush_tx(); + } + + // Go! + //delayMicroseconds(100); } /****************************************************************************/ +static const uint8_t child_pipe_enable[] +PROGMEM = + { + ERX_P0, ERX_P1, ERX_P2, ERX_P3, ERX_P4, ERX_P5 + }; + +void RF24::stopListening(void) { + ce(LOW); + + delayMicroseconds(txDelay); + + if (read_register(FEATURE) & _BV(EN_ACK_PAY)) { + delayMicroseconds(txDelay); //200 + flush_tx(); + } + //flush_rx(); + write_register(NRF_CONFIG, (read_register(NRF_CONFIG)) & ~_BV(PRIM_RX)); + +#if defined (RF24_TINY) || defined (LITTLEWIRE) + // for 3 pins solution TX mode is only left with additonal powerDown/powerUp cycle + if (ce_pin == csn_pin) { + powerDown(); + powerUp(); + } +#endif + write_register(EN_RXADDR, + read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[0]))); // Enable RX on pipe0 + + //delayMicroseconds(100); -void RF24::powerDown(void) -{ - ce(LOW); // Guarantee CE is low on powerDown - write_register(NRF_CONFIG,read_register(NRF_CONFIG) & ~_BV(PWR_UP)); +} + +/****************************************************************************/ + +void RF24::powerDown(void) { + ce(LOW); // Guarantee CE is low on powerDown + write_register(NRF_CONFIG, read_register(NRF_CONFIG) & ~_BV(PWR_UP)); } /****************************************************************************/ //Power up now. Radio will not power down unless instructed by MCU for config changes etc. -void RF24::powerUp(void) -{ - uint8_t cfg = read_register(NRF_CONFIG); +void RF24::powerUp(void) { + uint8_t cfg = read_register(NRF_CONFIG); - // if not powered up then power up and wait for the radio to initialize - if (!(cfg & _BV(PWR_UP))){ - write_register(NRF_CONFIG, cfg | _BV(PWR_UP)); + // if not powered up then power up and wait for the radio to initialize + if (!(cfg & _BV(PWR_UP))) { + write_register(NRF_CONFIG, cfg | _BV(PWR_UP)); - // For nRF24L01+ to go from power down mode to TX or RX mode it must first pass through stand-by mode. - // There must be a delay of Tpd2stby (see Table 16.) after the nRF24L01+ leaves power down mode before - // the CEis set high. - Tpd2stby can be up to 5ms per the 1.0 datasheet - delay(5); - } + // For nRF24L01+ to go from power down mode to TX or RX mode it must first pass through stand-by mode. + // There must be a delay of Tpd2stby (see Table 16.) after the nRF24L01+ leaves power down mode before + // the CEis set high. - Tpd2stby can be up to 5ms per the 1.0 datasheet + delay(5); + } } /******************************************************************/ #if defined (FAILURE_HANDLING) || defined (RF24_LINUX) void RF24::errNotify(){ - #if defined (SERIAL_DEBUG) || defined (RF24_LINUX) - printf_P(PSTR("RF24 HARDWARE FAIL: Radio not responding, verify pin connections, wiring, etc.\r\n")); - #endif - #if defined (FAILURE_HANDLING) - failureDetected = 1; - #else - delay(5000); - #endif +#if defined (SERIAL_DEBUG) || defined (RF24_LINUX) + printf_P(PSTR("RF24 HARDWARE FAIL: Radio not responding, verify pin connections, wiring, etc.\r\n")); +#endif +#if defined (FAILURE_HANDLING) + failureDetected = 1; +#else + delay(5000); +#endif } #endif /******************************************************************/ //Similar to the previous write, clears the interrupt flags -bool RF24::write( const void* buf, uint8_t len, const bool multicast ) -{ - //Start Writing - startFastWrite(buf,len,multicast); - - //Wait until complete or failed - #if defined (FAILURE_HANDLING) || defined (RF24_LINUX) - uint32_t timer = millis(); - #endif - - while( ! ( get_status() & ( _BV(TX_DS) | _BV(MAX_RT) ))) { - #if defined (FAILURE_HANDLING) || defined (RF24_LINUX) - if(millis() - timer > 95){ - errNotify(); - #if defined (FAILURE_HANDLING) - return 0; - #else - delay(100); - #endif - } - #endif - } - - ce(LOW); - - uint8_t status = write_register(NRF_STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); - - //Max retries exceeded - if( status & _BV(MAX_RT)){ - flush_tx(); //Only going to be 1 packet int the FIFO at a time using this method, so just flush - return 0; - } - //TX OK 1 or 0 - return 1; -} - -bool RF24::write( const void* buf, uint8_t len ){ - return write(buf,len,0); -} -/****************************************************************************/ +bool RF24::write(const void *buf, uint8_t len, const bool multicast) { + //Start Writing + startFastWrite(buf, len, multicast); -//For general use, the interrupt flags are not important to clear -bool RF24::writeBlocking( const void* buf, uint8_t len, uint32_t timeout ) -{ - //Block until the FIFO is NOT full. - //Keep track of the MAX retries and set auto-retry if seeing failures - //This way the FIFO will fill up and allow blocking until packets go through - //The radio will auto-clear everything in the FIFO as long as CE remains high + //Wait until complete or failed +#if defined (FAILURE_HANDLING) || defined (RF24_LINUX) + uint32_t timer = millis(); +#endif + + while (!(get_status() & (_BV(TX_DS) | _BV(MAX_RT)))) { +#if defined (FAILURE_HANDLING) || defined (RF24_LINUX) + if(millis() - timer > 95){ + errNotify(); +#if defined (FAILURE_HANDLING) + return 0; +#else + delay(100); +#endif + } +#endif + } + + ce(LOW); + + uint8_t status = write_register(NRF_STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT)); - uint32_t timer = millis(); //Get the time that the payload transmission started + //Max retries exceeded + if (status & _BV(MAX_RT)) { + flush_tx(); //Only going to be 1 packet int the FIFO at a time using this method, so just flush + return 0; + } + //TX OK 1 or 0 + return 1; +} - while( ( get_status() & ( _BV(TX_FULL) ))) { //Blocking only if FIFO is full. This will loop and block until TX is successful or timeout +bool RF24::write(const void *buf, uint8_t len) { + return write(buf, len, 0); +} +/****************************************************************************/ - if( get_status() & _BV(MAX_RT)){ //If MAX Retries have been reached - reUseTX(); //Set re-transmit and clear the MAX_RT interrupt flag - if(millis() - timer > timeout){ return 0; } //If this payload has exceeded the user-defined timeout, exit and return 0 - } - #if defined (FAILURE_HANDLING) || defined (RF24_LINUX) - if(millis() - timer > (timeout+95) ){ - errNotify(); - #if defined (FAILURE_HANDLING) - return 0; - #endif - } - #endif +//For general use, the interrupt flags are not important to clear +bool RF24::writeBlocking(const void *buf, uint8_t len, uint32_t timeout) { + //Block until the FIFO is NOT full. + //Keep track of the MAX retries and set auto-retry if seeing failures + //This way the FIFO will fill up and allow blocking until packets go through + //The radio will auto-clear everything in the FIFO as long as CE remains high + + uint32_t timer = millis(); //Get the time that the payload transmission started + + while ((get_status() & + (_BV(TX_FULL)))) { //Blocking only if FIFO is full. This will loop and block until TX is successful or timeout + + if (get_status() & _BV(MAX_RT)) { //If MAX Retries have been reached + reUseTX(); //Set re-transmit and clear the MAX_RT interrupt flag + if (millis() - timer > + timeout) { return 0; } //If this payload has exceeded the user-defined timeout, exit and return 0 + } +#if defined (FAILURE_HANDLING) || defined (RF24_LINUX) + if(millis() - timer > (timeout+95) ){ + errNotify(); +#if defined (FAILURE_HANDLING) + return 0; +#endif + } +#endif - } + } - //Start Writing - startFastWrite(buf,len,0); //Write the payload if a buffer is clear + //Start Writing + startFastWrite(buf, len, 0); //Write the payload if a buffer is clear - return 1; //Return 1 to indicate successful transmission + return 1; //Return 1 to indicate successful transmission } /****************************************************************************/ -void RF24::reUseTX(){ - write_register(NRF_STATUS,_BV(MAX_RT) ); //Clear max retry flag - spiTrans( REUSE_TX_PL ); - ce(LOW); //Re-Transfer packet - ce(HIGH); +void RF24::reUseTX() { + write_register(NRF_STATUS, _BV(MAX_RT)); //Clear max retry flag + spiTrans(REUSE_TX_PL); + ce(LOW); //Re-Transfer packet + ce(HIGH); } /****************************************************************************/ -bool RF24::writeFast( const void* buf, uint8_t len, const bool multicast ) -{ - //Block until the FIFO is NOT full. - //Keep track of the MAX retries and set auto-retry if seeing failures - //Return 0 so the user can control the retrys and set a timer or failure counter if required - //The radio will auto-clear everything in the FIFO as long as CE remains high +bool RF24::writeFast(const void *buf, uint8_t len, const bool multicast) { + //Block until the FIFO is NOT full. + //Keep track of the MAX retries and set auto-retry if seeing failures + //Return 0 so the user can control the retrys and set a timer or failure counter if required + //The radio will auto-clear everything in the FIFO as long as CE remains high - #if defined (FAILURE_HANDLING) || defined (RF24_LINUX) - uint32_t timer = millis(); - #endif - - while( ( get_status() & ( _BV(TX_FULL) ))) { //Blocking only if FIFO is full. This will loop and block until TX is successful or fail +#if defined (FAILURE_HANDLING) || defined (RF24_LINUX) + uint32_t timer = millis(); +#endif - if( get_status() & _BV(MAX_RT)){ - //reUseTX(); //Set re-transmit - write_register(NRF_STATUS,_BV(MAX_RT) ); //Clear max retry flag - return 0; //Return 0. The previous payload has been retransmitted - //From the user perspective, if you get a 0, just keep trying to send the same payload - } - #if defined (FAILURE_HANDLING) || defined (RF24_LINUX) - if(millis() - timer > 95 ){ - errNotify(); - #if defined (FAILURE_HANDLING) - return 0; - #endif - } - #endif - } - //Start Writing - startFastWrite(buf,len,multicast); + while ((get_status() & + (_BV(TX_FULL)))) { //Blocking only if FIFO is full. This will loop and block until TX is successful or fail - return 1; + if (get_status() & _BV(MAX_RT)) { + //reUseTX(); //Set re-transmit + write_register(NRF_STATUS, _BV(MAX_RT)); //Clear max retry flag + return 0; //Return 0. The previous payload has been retransmitted + //From the user perspective, if you get a 0, just keep trying to send the same payload + } +#if defined (FAILURE_HANDLING) || defined (RF24_LINUX) + if(millis() - timer > 95 ){ + errNotify(); +#if defined (FAILURE_HANDLING) + return 0; +#endif + } +#endif + } + //Start Writing + startFastWrite(buf, len, multicast); + + return 1; } -bool RF24::writeFast( const void* buf, uint8_t len ){ - return writeFast(buf,len,0); +bool RF24::writeFast(const void *buf, uint8_t len) { + return writeFast(buf, len, 0); } /****************************************************************************/ @@ -968,13 +972,13 @@ bool RF24::writeFast( const void* buf, uint8_t len ){ //Otherwise we enter Standby-II mode, which is still faster than standby mode //Also, we remove the need to keep writing the config register over and over and delaying for 150 us each time if sending a stream of data -void RF24::startFastWrite( const void* buf, uint8_t len, const bool multicast, bool startTx){ //TMRh20 +void RF24::startFastWrite(const void *buf, uint8_t len, const bool multicast, bool startTx) { //TMRh20 - //write_payload( buf,len); - write_payload( buf, len,multicast ? W_TX_PAYLOAD_NO_ACK : W_TX_PAYLOAD ) ; - if(startTx){ - ce(HIGH); - } + //write_payload( buf,len); + write_payload(buf, len, multicast ? W_TX_PAYLOAD_NO_ACK : W_TX_PAYLOAD); + if (startTx) { + ce(HIGH); + } } @@ -982,266 +986,267 @@ void RF24::startFastWrite( const void* buf, uint8_t len, const bool multicast, b //Added the original startWrite back in so users can still use interrupts, ack payloads, etc //Allows the library to pass all tests -void RF24::startWrite( const void* buf, uint8_t len, const bool multicast ){ +void RF24::startWrite(const void *buf, uint8_t len, const bool multicast) { - // Send the payload + // Send the payload - //write_payload( buf, len ); - write_payload( buf, len,multicast? W_TX_PAYLOAD_NO_ACK : W_TX_PAYLOAD ) ; - ce(HIGH); - #if defined(CORE_TEENSY) || !defined(ARDUINO) || defined (RF24_SPIDEV) || defined (RF24_DUE) - delayMicroseconds(10); - #endif - ce(LOW); + //write_payload( buf, len ); + write_payload(buf, len, multicast ? W_TX_PAYLOAD_NO_ACK : W_TX_PAYLOAD); + ce(HIGH); +#if defined(CORE_TEENSY) || !defined(ARDUINO) || defined (RF24_SPIDEV) || defined (RF24_DUE) + delayMicroseconds(10); +#endif + ce(LOW); } /****************************************************************************/ -bool RF24::rxFifoFull(){ - return read_register(FIFO_STATUS) & _BV(RX_FULL); +bool RF24::rxFifoFull() { + return read_register(FIFO_STATUS) & _BV(RX_FULL); } + /****************************************************************************/ -bool RF24::txStandBy(){ +bool RF24::txStandBy() { - #if defined (FAILURE_HANDLING) || defined (RF24_LINUX) - uint32_t timeout = millis(); - #endif - while( ! (read_register(FIFO_STATUS) & _BV(TX_EMPTY)) ){ - if( get_status() & _BV(MAX_RT)){ - write_register(NRF_STATUS,_BV(MAX_RT) ); - ce(LOW); - flush_tx(); //Non blocking, flush the data - return 0; - } - #if defined (FAILURE_HANDLING) || defined (RF24_LINUX) - if( millis() - timeout > 95){ - errNotify(); - #if defined (FAILURE_HANDLING) - return 0; - #endif - } - #endif - } +#if defined (FAILURE_HANDLING) || defined (RF24_LINUX) + uint32_t timeout = millis(); +#endif + while (!(read_register(FIFO_STATUS) & _BV(TX_EMPTY))) { + if (get_status() & _BV(MAX_RT)) { + write_register(NRF_STATUS, _BV(MAX_RT)); + ce(LOW); + flush_tx(); //Non blocking, flush the data + return 0; + } +#if defined (FAILURE_HANDLING) || defined (RF24_LINUX) + if( millis() - timeout > 95){ + errNotify(); +#if defined (FAILURE_HANDLING) + return 0; +#endif + } +#endif + } - ce(LOW); //Set STANDBY-I mode - return 1; + ce(LOW); //Set STANDBY-I mode + return 1; } /****************************************************************************/ -bool RF24::txStandBy(uint32_t timeout, bool startTx){ +bool RF24::txStandBy(uint32_t timeout, bool startTx) { - if(startTx){ - stopListening(); - ce(HIGH); - } - uint32_t start = millis(); + if (startTx) { + stopListening(); + ce(HIGH); + } + uint32_t start = millis(); + + while (!(read_register(FIFO_STATUS) & _BV(TX_EMPTY))) { + if (get_status() & _BV(MAX_RT)) { + write_register(NRF_STATUS, _BV(MAX_RT)); + ce(LOW); //Set re-transmit + ce(HIGH); + if (millis() - start >= timeout) { + ce(LOW); + flush_tx(); + return 0; + } + } +#if defined (FAILURE_HANDLING) || defined (RF24_LINUX) + if( millis() - start > (timeout+95)){ + errNotify(); +#if defined (FAILURE_HANDLING) + return 0; +#endif + } +#endif + } - while( ! (read_register(FIFO_STATUS) & _BV(TX_EMPTY)) ){ - if( get_status() & _BV(MAX_RT)){ - write_register(NRF_STATUS,_BV(MAX_RT) ); - ce(LOW); //Set re-transmit - ce(HIGH); - if(millis() - start >= timeout){ - ce(LOW); flush_tx(); return 0; - } - } - #if defined (FAILURE_HANDLING) || defined (RF24_LINUX) - if( millis() - start > (timeout+95)){ - errNotify(); - #if defined (FAILURE_HANDLING) - return 0; - #endif - } - #endif - } - - ce(LOW); //Set STANDBY-I mode - return 1; + ce(LOW); //Set STANDBY-I mode + return 1; } /****************************************************************************/ -void RF24::maskIRQ(bool tx, bool fail, bool rx){ +void RF24::maskIRQ(bool tx, bool fail, bool rx) { - uint8_t config = read_register(NRF_CONFIG); - /* clear the interrupt flags */ - config &= ~(1 << MASK_MAX_RT | 1 << MASK_TX_DS | 1 << MASK_RX_DR); - /* set the specified interrupt flags */ - config |= fail << MASK_MAX_RT | tx << MASK_TX_DS | rx << MASK_RX_DR; - write_register(NRF_CONFIG, config); + uint8_t config = read_register(NRF_CONFIG); + /* clear the interrupt flags */ + config &= ~(1 << MASK_MAX_RT | 1 << MASK_TX_DS | 1 << MASK_RX_DR); + /* set the specified interrupt flags */ + config |= fail << MASK_MAX_RT | tx << MASK_TX_DS | rx << MASK_RX_DR; + write_register(NRF_CONFIG, config); } /****************************************************************************/ -uint8_t RF24::getDynamicPayloadSize(void) -{ - uint8_t result = 0; +uint8_t RF24::getDynamicPayloadSize(void) { + uint8_t result = 0; - #if defined (RF24_LINUX) - spi_txbuff[0] = R_RX_PL_WID; - spi_rxbuff[1] = 0xff; - beginTransaction(); - _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, 2); - result = spi_rxbuff[1]; - endTransaction(); - #else - beginTransaction(); - _SPI.transfer( R_RX_PL_WID ); - result = _SPI.transfer(0xff); - endTransaction(); - #endif +#if defined (RF24_LINUX) + spi_txbuff[0] = R_RX_PL_WID; + spi_rxbuff[1] = 0xff; + beginTransaction(); + _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, 2); + result = spi_rxbuff[1]; + endTransaction(); +#else + beginTransaction(); + _SPI.transfer(R_RX_PL_WID); + result = _SPI.transfer(0xff); + endTransaction(); +#endif - if(result > 32) { flush_rx(); delay(2); return 0; } - return result; + if (result > 32) { + flush_rx(); + delay(2); + return 0; + } + return result; } /****************************************************************************/ -bool RF24::available(void) -{ - return available(NULL); +bool RF24::available(void) { + return available(NULL); } /****************************************************************************/ -bool RF24::available(uint8_t* pipe_num) -{ - if (!( read_register(FIFO_STATUS) & _BV(RX_EMPTY) )){ +bool RF24::available(uint8_t *pipe_num) { + if (!(read_register(FIFO_STATUS) & _BV(RX_EMPTY))) { - // If the caller wants the pipe number, include that - if ( pipe_num ){ - uint8_t status = get_status(); - *pipe_num = ( status >> RX_P_NO ) & 0x07; - } - return 1; - } + // If the caller wants the pipe number, include that + if (pipe_num) { + uint8_t status = get_status(); + *pipe_num = (status >> RX_P_NO) & 0x07; + } + return 1; + } - return 0; + return 0; } /****************************************************************************/ -void RF24::read( void* buf, uint8_t len ){ +void RF24::read(void *buf, uint8_t len) { - // Fetch the payload - read_payload( buf, len ); + // Fetch the payload + read_payload(buf, len); - //Clear the two possible interrupt flags with one command - write_register(NRF_STATUS,_BV(RX_DR) | _BV(MAX_RT) | _BV(TX_DS) ); + //Clear the two possible interrupt flags with one command + write_register(NRF_STATUS, _BV(RX_DR) | _BV(MAX_RT) | _BV(TX_DS)); } /****************************************************************************/ -void RF24::whatHappened(bool& tx_ok,bool& tx_fail,bool& rx_ready) -{ - // Read the status & reset the status in one easy call - // Or is that such a good idea? - uint8_t status = write_register(NRF_STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); +void RF24::whatHappened(bool &tx_ok, bool &tx_fail, bool &rx_ready) { + // Read the status & reset the status in one easy call + // Or is that such a good idea? + uint8_t status = write_register(NRF_STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT)); - // Report to the user what happened - tx_ok = status & _BV(TX_DS); - tx_fail = status & _BV(MAX_RT); - rx_ready = status & _BV(RX_DR); + // Report to the user what happened + tx_ok = status & _BV(TX_DS); + tx_fail = status & _BV(MAX_RT); + rx_ready = status & _BV(RX_DR); } /****************************************************************************/ -void RF24::openWritingPipe(uint64_t value) -{ - // Note that AVR 8-bit uC's store this LSB first, and the NRF24L01(+) - // expects it LSB first too, so we're good. +void RF24::openWritingPipe(uint64_t value) { + // Note that AVR 8-bit uC's store this LSB first, and the NRF24L01(+) + // expects it LSB first too, so we're good. + + write_register(RX_ADDR_P0, reinterpret_cast(&value), addr_width); + write_register(TX_ADDR, reinterpret_cast(&value), addr_width); - write_register(RX_ADDR_P0, reinterpret_cast(&value), addr_width); - write_register(TX_ADDR, reinterpret_cast(&value), addr_width); - - - //const uint8_t max_payload_size = 32; - //write_register(RX_PW_P0,rf24_min(payload_size,max_payload_size)); - write_register(RX_PW_P0,payload_size); + + //const uint8_t max_payload_size = 32; + //write_register(RX_PW_P0,rf24_min(payload_size,max_payload_size)); + write_register(RX_PW_P0, payload_size); } /****************************************************************************/ -void RF24::openWritingPipe(const uint8_t *address) -{ - // Note that AVR 8-bit uC's store this LSB first, and the NRF24L01(+) - // expects it LSB first too, so we're good. +void RF24::openWritingPipe(const uint8_t *address) { + // Note that AVR 8-bit uC's store this LSB first, and the NRF24L01(+) + // expects it LSB first too, so we're good. - write_register(RX_ADDR_P0,address, addr_width); - write_register(TX_ADDR, address, addr_width); + write_register(RX_ADDR_P0, address, addr_width); + write_register(TX_ADDR, address, addr_width); - //const uint8_t max_payload_size = 32; - //write_register(RX_PW_P0,rf24_min(payload_size,max_payload_size)); - write_register(RX_PW_P0,payload_size); + //const uint8_t max_payload_size = 32; + //write_register(RX_PW_P0,rf24_min(payload_size,max_payload_size)); + write_register(RX_PW_P0, payload_size); } -void RF24::openWritingPipe(const uint8_t *address,int len ) -{ - // Note that AVR 8-bit uC's store this LSB first, and the NRF24L01(+) - // expects it LSB first too, so we're good. +void RF24::openWritingPipe(const uint8_t *address, int len) { + // Note that AVR 8-bit uC's store this LSB first, and the NRF24L01(+) + // expects it LSB first too, so we're good. - write_register(RX_ADDR_P0,address, len); - write_register(TX_ADDR, address, len); + write_register(RX_ADDR_P0, address, len); + write_register(TX_ADDR, address, len); - //const uint8_t max_payload_size = 32; - //write_register(RX_PW_P0,rf24_min(payload_size,max_payload_size)); - write_register(RX_PW_P0,payload_size); + //const uint8_t max_payload_size = 32; + //write_register(RX_PW_P0,rf24_min(payload_size,max_payload_size)); + write_register(RX_PW_P0, payload_size); } + /****************************************************************************/ -static const uint8_t child_pipe[] PROGMEM = -{ - RX_ADDR_P0, RX_ADDR_P1, RX_ADDR_P2, RX_ADDR_P3, RX_ADDR_P4, RX_ADDR_P5 -}; -static const uint8_t child_payload_size[] PROGMEM = -{ - RX_PW_P0, RX_PW_P1, RX_PW_P2, RX_PW_P3, RX_PW_P4, RX_PW_P5 -}; +static const uint8_t child_pipe[] +PROGMEM = + { + RX_ADDR_P0, RX_ADDR_P1, RX_ADDR_P2, RX_ADDR_P3, RX_ADDR_P4, RX_ADDR_P5 + }; +static const uint8_t child_payload_size[] +PROGMEM = + { + RX_PW_P0, RX_PW_P1, RX_PW_P2, RX_PW_P3, RX_PW_P4, RX_PW_P5 + }; -void RF24::openReadingPipe(uint8_t child, uint64_t address) -{ - // If this is pipe 0, cache the address. This is needed because - // openWritingPipe() will overwrite the pipe 0 address, so - // startListening() will have to restore it. - if (child == 0){ - memcpy(pipe0_reading_address,&address,addr_width); - } - - if (child <= 6) - { - // For pipes 2-5, only write the LSB - if ( child < 2 ) - write_register(pgm_read_byte(&child_pipe[child]), reinterpret_cast(&address), addr_width); - else - write_register(pgm_read_byte(&child_pipe[child]), reinterpret_cast(&address), 1); +void RF24::openReadingPipe(uint8_t child, uint64_t address) { + // If this is pipe 0, cache the address. This is needed because + // openWritingPipe() will overwrite the pipe 0 address, so + // startListening() will have to restore it. + if (child == 0) { + memcpy(pipe0_reading_address, &address, addr_width); + } - write_register(pgm_read_byte(&child_payload_size[child]),payload_size); + if (child <= 6) { + // For pipes 2-5, only write the LSB + if (child < 2) + write_register(pgm_read_byte(&child_pipe[child]), reinterpret_cast(&address), addr_width); + else + write_register(pgm_read_byte(&child_pipe[child]), reinterpret_cast(&address), 1); - // Note it would be more efficient to set all of the bits for all open - // pipes at once. However, I thought it would make the calling code - // more simple to do it this way. - write_register(EN_RXADDR,read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[child]))); - } + write_register(pgm_read_byte(&child_payload_size[child]), payload_size); + + // Note it would be more efficient to set all of the bits for all open + // pipes at once. However, I thought it would make the calling code + // more simple to do it this way. + write_register(EN_RXADDR, read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[child]))); + } } /****************************************************************************/ -void RF24::setAddressWidth(uint8_t a_width){ +void RF24::setAddressWidth(uint8_t a_width) { - if(a_width -= 2){ - write_register(SETUP_AW,a_width%4); - addr_width = (a_width%4) + 2; - }else{ - write_register(SETUP_AW,0); + if (a_width -= 2) { + write_register(SETUP_AW, a_width % 4); + addr_width = (a_width % 4) + 2; + } else { + write_register(SETUP_AW, 0); addr_width = 2; } @@ -1249,370 +1254,329 @@ void RF24::setAddressWidth(uint8_t a_width){ /****************************************************************************/ -void RF24::openReadingPipe(uint8_t child, const uint8_t *address) -{ - // If this is pipe 0, cache the address. This is needed because - // openWritingPipe() will overwrite the pipe 0 address, so - // startListening() will have to restore it. - if (child == 0){ - memcpy(pipe0_reading_address,address,addr_width); - } - if (child <= 6) - { - // For pipes 2-5, only write the LSB - if ( child < 2 ){ - write_register(pgm_read_byte(&child_pipe[child]), address, addr_width); - }else{ - write_register(pgm_read_byte(&child_pipe[child]), address, 1); - } - write_register(pgm_read_byte(&child_payload_size[child]),payload_size); - - // Note it would be more efficient to set all of the bits for all open - // pipes at once. However, I thought it would make the calling code - // more simple to do it this way. - write_register(EN_RXADDR,read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[child]))); +void RF24::openReadingPipe(uint8_t child, const uint8_t *address) { + // If this is pipe 0, cache the address. This is needed because + // openWritingPipe() will overwrite the pipe 0 address, so + // startListening() will have to restore it. + if (child == 0) { + memcpy(pipe0_reading_address, address, addr_width); + } + if (child <= 6) { + // For pipes 2-5, only write the LSB + if (child < 2) { + write_register(pgm_read_byte(&child_pipe[child]), address, addr_width); + } else { + write_register(pgm_read_byte(&child_pipe[child]), address, 1); + } + write_register(pgm_read_byte(&child_payload_size[child]), payload_size); + + // Note it would be more efficient to set all of the bits for all open + // pipes at once. However, I thought it would make the calling code + // more simple to do it this way. + write_register(EN_RXADDR, read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[child]))); - } + } } /****************************************************************************/ -void RF24::closeReadingPipe( uint8_t pipe ) -{ - write_register(EN_RXADDR,read_register(EN_RXADDR) & ~_BV(pgm_read_byte(&child_pipe_enable[pipe]))); +void RF24::closeReadingPipe(uint8_t pipe) { + write_register(EN_RXADDR, read_register(EN_RXADDR) & ~_BV(pgm_read_byte(&child_pipe_enable[pipe]))); } /****************************************************************************/ -void RF24::toggle_features(void) -{ +void RF24::toggle_features(void) { beginTransaction(); - _SPI.transfer( ACTIVATE ); - _SPI.transfer( 0x73 ); - endTransaction(); + _SPI.transfer(ACTIVATE); + _SPI.transfer(0x73); + endTransaction(); } /****************************************************************************/ -void RF24::enableDynamicPayloads(void) -{ - // Enable dynamic payload throughout the system +void RF24::enableDynamicPayloads(void) { + // Enable dynamic payload throughout the system //toggle_features(); - write_register(FEATURE,read_register(FEATURE) | _BV(EN_DPL) ); + write_register(FEATURE, read_register(FEATURE) | _BV(EN_DPL)); - IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n",read_register(FEATURE))); + IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n", read_register(FEATURE))); - // Enable dynamic payload on all pipes - // - // Not sure the use case of only having dynamic payload on certain - // pipes, so the library does not support it. - write_register(DYNPD,read_register(DYNPD) | _BV(DPL_P5) | _BV(DPL_P4) | _BV(DPL_P3) | _BV(DPL_P2) | _BV(DPL_P1) | _BV(DPL_P0)); + // Enable dynamic payload on all pipes + // + // Not sure the use case of only having dynamic payload on certain + // pipes, so the library does not support it. + write_register(DYNPD, read_register(DYNPD) | _BV(DPL_P5) | _BV(DPL_P4) | _BV(DPL_P3) | _BV(DPL_P2) | _BV(DPL_P1) | + _BV(DPL_P0)); - dynamic_payloads_enabled = true; + dynamic_payloads_enabled = true; } /****************************************************************************/ -void RF24::disableDynamicPayloads(void) -{ - // Disables dynamic payload throughout the system. Also disables Ack Payloads +void RF24::disableDynamicPayloads(void) { + // Disables dynamic payload throughout the system. Also disables Ack Payloads - //toggle_features(); - write_register(FEATURE, 0); + //toggle_features(); + write_register(FEATURE, 0); - IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n",read_register(FEATURE))); + IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n", read_register(FEATURE))); - // Disable dynamic payload on all pipes - // - // Not sure the use case of only having dynamic payload on certain - // pipes, so the library does not support it. - write_register(DYNPD, 0); + // Disable dynamic payload on all pipes + // + // Not sure the use case of only having dynamic payload on certain + // pipes, so the library does not support it. + write_register(DYNPD, 0); - dynamic_payloads_enabled = false; + dynamic_payloads_enabled = false; } /****************************************************************************/ -void RF24::enableAckPayload(void) -{ - // - // enable ack payload and dynamic payload features - // +void RF24::enableAckPayload(void) { + // + // enable ack payload and dynamic payload features + // //toggle_features(); - write_register(FEATURE,read_register(FEATURE) | _BV(EN_ACK_PAY) | _BV(EN_DPL) ); + write_register(FEATURE, read_register(FEATURE) | _BV(EN_ACK_PAY) | _BV(EN_DPL)); - IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n",read_register(FEATURE))); + IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n", read_register(FEATURE))); - // - // Enable dynamic payload on pipes 0 & 1 - // + // + // Enable dynamic payload on pipes 0 & 1 + // - write_register(DYNPD,read_register(DYNPD) | _BV(DPL_P1) | _BV(DPL_P0)); - dynamic_payloads_enabled = true; + write_register(DYNPD, read_register(DYNPD) | _BV(DPL_P1) | _BV(DPL_P0)); + dynamic_payloads_enabled = true; } /****************************************************************************/ -void RF24::enableDynamicAck(void){ - // - // enable dynamic ack features - // +void RF24::enableDynamicAck(void) { + // + // enable dynamic ack features + // //toggle_features(); - write_register(FEATURE,read_register(FEATURE) | _BV(EN_DYN_ACK) ); + write_register(FEATURE, read_register(FEATURE) | _BV(EN_DYN_ACK)); - IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n",read_register(FEATURE))); + IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n", read_register(FEATURE))); } /****************************************************************************/ -void RF24::writeAckPayload(uint8_t pipe, const void* buf, uint8_t len) -{ - const uint8_t* current = reinterpret_cast(buf); +void RF24::writeAckPayload(uint8_t pipe, const void *buf, uint8_t len) { + const uint8_t *current = reinterpret_cast(buf); - uint8_t data_len = rf24_min(len,32); + uint8_t data_len = rf24_min(len, 32); - #if defined (RF24_LINUX) +#if defined (RF24_LINUX) beginTransaction(); uint8_t * ptx = spi_txbuff; uint8_t size = data_len + 1 ; // Add register value to transmit buffer - *ptx++ = W_ACK_PAYLOAD | ( pipe & 0x07 ); + *ptx++ = W_ACK_PAYLOAD | ( pipe & 0x07 ); while ( data_len-- ){ *ptx++ = *current++; } - + _SPI.transfern( (char *) spi_txbuff, size); - endTransaction(); - #else - beginTransaction(); - _SPI.transfer(W_ACK_PAYLOAD | ( pipe & 0x07 ) ); + endTransaction(); +#else + beginTransaction(); + _SPI.transfer(W_ACK_PAYLOAD | (pipe & 0x07)); + + while (data_len--) + _SPI.transfer(*current++); + endTransaction(); - while ( data_len-- ) - _SPI.transfer(*current++); - endTransaction(); - - #endif +#endif } /****************************************************************************/ -bool RF24::isAckPayloadAvailable(void) -{ - return ! (read_register(FIFO_STATUS) & _BV(RX_EMPTY)); +bool RF24::isAckPayloadAvailable(void) { + return !(read_register(FIFO_STATUS) & _BV(RX_EMPTY)); } /****************************************************************************/ -bool RF24::isPVariant(void) -{ - return p_variant ; +bool RF24::isPVariant(void) { + return p_variant; } /****************************************************************************/ -void RF24::setAutoAck(bool enable) -{ - if ( enable ) - write_register(EN_AA, 0x3F); - else - write_register(EN_AA, 0); +void RF24::setAutoAck(bool enable) { + if (enable) + write_register(EN_AA, 0x3F); + else + write_register(EN_AA, 0); } /****************************************************************************/ -void RF24::setAutoAck( uint8_t pipe, bool enable ) -{ - if ( pipe <= 6 ) - { - uint8_t en_aa = read_register( EN_AA ) ; - if( enable ) - { - en_aa |= _BV(pipe) ; - } - else - { - en_aa &= ~_BV(pipe) ; +void RF24::setAutoAck(uint8_t pipe, bool enable) { + if (pipe <= 6) { + uint8_t en_aa = read_register(EN_AA); + if (enable) { + en_aa |= _BV(pipe); + } else { + en_aa &= ~_BV(pipe); + } + write_register(EN_AA, en_aa); } - write_register( EN_AA, en_aa ) ; - } } /****************************************************************************/ -bool RF24::testCarrier(void) -{ - return ( read_register(CD) & 1 ); +bool RF24::testCarrier(void) { + return (read_register(CD) & 1); } /****************************************************************************/ -bool RF24::testRPD(void) -{ - return ( read_register(RPD) & 1 ) ; +bool RF24::testRPD(void) { + return (read_register(RPD) & 1); } /****************************************************************************/ -void RF24::setPALevel(uint8_t level) -{ +void RF24::setPALevel(uint8_t level) { - uint8_t setup = read_register(RF_SETUP) & 0xF8; + uint8_t setup = read_register(RF_SETUP) & 0xF8; - if(level > 3){ // If invalid level, go to max PA - level = (RF24_PA_MAX << 1) + 1; // +1 to support the SI24R1 chip extra bit - }else{ - level = (level << 1) + 1; // Else set level as requested - } + if (level > 3) { // If invalid level, go to max PA + level = (RF24_PA_MAX << 1) + 1; // +1 to support the SI24R1 chip extra bit + } else { + level = (level << 1) + 1; // Else set level as requested + } - write_register( RF_SETUP, setup |= level ) ; // Write it to the chip + write_register(RF_SETUP, setup |= level); // Write it to the chip } /****************************************************************************/ -uint8_t RF24::getPALevel(void) -{ +uint8_t RF24::getPALevel(void) { - return (read_register(RF_SETUP) & (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH))) >> 1 ; + return (read_register(RF_SETUP) & (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH))) >> 1; } /****************************************************************************/ -bool RF24::setDataRate(rf24_datarate_e speed) -{ - bool result = false; - uint8_t setup = read_register(RF_SETUP) ; +bool RF24::setDataRate(rf24_datarate_e speed) { + bool result = false; + uint8_t setup = read_register(RF_SETUP); + + // HIGH and LOW '00' is 1Mbs - our default + setup &= ~(_BV(RF_DR_LOW) | _BV(RF_DR_HIGH)); - // HIGH and LOW '00' is 1Mbs - our default - setup &= ~(_BV(RF_DR_LOW) | _BV(RF_DR_HIGH)) ; - - #if defined(__arm__) || defined (RF24_LINUX) || defined (__ARDUINO_X86__) +#if defined(__arm__) || defined (RF24_LINUX) || defined (__ARDUINO_X86__) txDelay=250; - #else //16Mhz Arduino - txDelay=85; - #endif - if( speed == RF24_250KBPS ) - { - // Must set the RF_DR_LOW to 1; RF_DR_HIGH (used to be RF_DR) is already 0 - // Making it '10'. - setup |= _BV( RF_DR_LOW ) ; - #if defined(__arm__) || defined (RF24_LINUX) || defined (__ARDUINO_X86__) - txDelay=450; - #else //16Mhz Arduino - txDelay=155; - #endif - } - else - { - // Set 2Mbs, RF_DR (RF_DR_HIGH) is set 1 - // Making it '01' - if ( speed == RF24_2MBPS ) - { - setup |= _BV(RF_DR_HIGH); - #if defined(__arm__) || defined (RF24_LINUX) || defined (__ARDUINO_X86__) - txDelay=190; - #else //16Mhz Arduino - txDelay=65; - #endif +#else //16Mhz Arduino + txDelay = 85; +#endif + if (speed == RF24_250KBPS) { + // Must set the RF_DR_LOW to 1; RF_DR_HIGH (used to be RF_DR) is already 0 + // Making it '10'. + setup |= _BV(RF_DR_LOW); +#if defined(__arm__) || defined (RF24_LINUX) || defined (__ARDUINO_X86__) + txDelay=450; +#else //16Mhz Arduino + txDelay = 155; +#endif + } else { + // Set 2Mbs, RF_DR (RF_DR_HIGH) is set 1 + // Making it '01' + if (speed == RF24_2MBPS) { + setup |= _BV(RF_DR_HIGH); +#if defined(__arm__) || defined (RF24_LINUX) || defined (__ARDUINO_X86__) + txDelay=190; +#else //16Mhz Arduino + txDelay = 65; +#endif + } } - } - write_register(RF_SETUP,setup); + write_register(RF_SETUP, setup); - // Verify our result - if ( read_register(RF_SETUP) == setup ) - { - result = true; - } - return result; + // Verify our result + if (read_register(RF_SETUP) == setup) { + result = true; + } + return result; } /****************************************************************************/ -rf24_datarate_e RF24::getDataRate( void ) -{ - rf24_datarate_e result ; - uint8_t dr = read_register(RF_SETUP) & (_BV(RF_DR_LOW) | _BV(RF_DR_HIGH)); - - // switch uses RAM (evil!) - // Order matters in our case below - if ( dr == _BV(RF_DR_LOW) ) - { - // '10' = 250KBPS - result = RF24_250KBPS ; - } - else if ( dr == _BV(RF_DR_HIGH) ) - { - // '01' = 2MBPS - result = RF24_2MBPS ; - } - else - { - // '00' = 1MBPS - result = RF24_1MBPS ; - } - return result ; -} - -/****************************************************************************/ - -void RF24::setCRCLength(rf24_crclength_e length) -{ - uint8_t config = read_register(NRF_CONFIG) & ~( _BV(CRCO) | _BV(EN_CRC)) ; +rf24_datarate_e RF24::getDataRate(void) { + rf24_datarate_e result; + uint8_t dr = read_register(RF_SETUP) & (_BV(RF_DR_LOW) | _BV(RF_DR_HIGH)); - // switch uses RAM (evil!) - if ( length == RF24_CRC_DISABLED ) - { - // Do nothing, we turned it off above. - } - else if ( length == RF24_CRC_8 ) - { - config |= _BV(EN_CRC); - } - else - { - config |= _BV(EN_CRC); - config |= _BV( CRCO ); - } - write_register( NRF_CONFIG, config ) ; + // switch uses RAM (evil!) + // Order matters in our case below + if (dr == _BV(RF_DR_LOW)) { + // '10' = 250KBPS + result = RF24_250KBPS; + } else if (dr == _BV(RF_DR_HIGH)) { + // '01' = 2MBPS + result = RF24_2MBPS; + } else { + // '00' = 1MBPS + result = RF24_1MBPS; + } + return result; } /****************************************************************************/ -rf24_crclength_e RF24::getCRCLength(void) -{ - rf24_crclength_e result = RF24_CRC_DISABLED; - - uint8_t config = read_register(NRF_CONFIG) & ( _BV(CRCO) | _BV(EN_CRC)) ; - uint8_t AA = read_register(EN_AA); - - if ( config & _BV(EN_CRC ) || AA) - { - if ( config & _BV(CRCO) ) - result = RF24_CRC_16; - else - result = RF24_CRC_8; - } +void RF24::setCRCLength(rf24_crclength_e length) { + uint8_t config = read_register(NRF_CONFIG) & ~(_BV(CRCO) | _BV(EN_CRC)); - return result; + // switch uses RAM (evil!) + if (length == RF24_CRC_DISABLED) { + // Do nothing, we turned it off above. + } else if (length == RF24_CRC_8) { + config |= _BV(EN_CRC); + } else { + config |= _BV(EN_CRC); + config |= _BV(CRCO); + } + write_register(NRF_CONFIG, config); } /****************************************************************************/ -void RF24::disableCRC( void ) -{ - uint8_t disable = read_register(NRF_CONFIG) & ~_BV(EN_CRC) ; - write_register( NRF_CONFIG, disable ) ; +rf24_crclength_e RF24::getCRCLength(void) { + rf24_crclength_e result = RF24_CRC_DISABLED; + + uint8_t config = read_register(NRF_CONFIG) & (_BV(CRCO) | _BV(EN_CRC)); + uint8_t AA = read_register(EN_AA); + + if (config & _BV(EN_CRC) || AA) { + if (config & _BV(CRCO)) + result = RF24_CRC_16; + else + result = RF24_CRC_8; + } + + return result; } /****************************************************************************/ -void RF24::setRetries(uint8_t delay, uint8_t count) -{ - write_register(SETUP_RETR,(delay&0xf)< - Added __ARDUINO_X86__ support + +/* spaniakos + Added __ARDUINO_X86__ support */ #ifndef __RF24_CONFIG_H__ #define __RF24_CONFIG_H__ - /*** USER DEFINES: ***/ - //#define FAILURE_HANDLING - //#define SERIAL_DEBUG - //#define MINIMAL - //#define SPI_UART // Requires library from https://github.com/TMRh20/Sketches/tree/master/SPI_UART - //#define SOFTSPI // Requires library from https://github.com/greiman/DigitalIO - - /**********************/ - #define rf24_max(a,b) (a>b?a:b) - #define rf24_min(a,b) (ab?a:b) +#define rf24_min(a, b) (a - #include - // RF modules support 10 Mhz SPI bus speed - const uint32_t RF24_SPI_SPEED = 10000000; + const uint32_t RF24_SPI_SPEED = 10000000; #if defined (ARDUINO) && !defined (__arm__) && !defined (__ARDUINO_X86__) - #if defined SPI_UART - #include - #define _SPI uspi - #elif defined SOFTSPI - // change these pins to your liking +#if defined SPI_UART +#include +#define _SPI uspi +#elif defined SOFTSPI + // change these pins to your liking // - #ifndef SOFT_SPI_MISO_PIN - #define SOFT_SPI_MISO_PIN 9 - #endif +#ifndef SOFT_SPI_MISO_PIN +#define SOFT_SPI_MISO_PIN 9 +#endif - #ifndef SOFT_SPI_MOSI_PIN - #define SOFT_SPI_MOSI_PIN 8 - #endif +#ifndef SOFT_SPI_MOSI_PIN +#define SOFT_SPI_MOSI_PIN 8 +#endif - #ifndef SOFT_SPI_SCK_PIN - #define SOFT_SPI_SCK_PIN 7 - #endif +#ifndef SOFT_SPI_SCK_PIN +#define SOFT_SPI_SCK_PIN 7 +#endif const uint8_t SPI_MODE = 0; - #define _SPI spi - - #else - #include - #define _SPI SPI - #endif +#define _SPI spi + +#else +#include +#define _SPI SPI +#endif #else // Define _BV for non-Arduino platforms and for Arduino DUE - #include - #include - #include - - - #if defined(__arm__) || defined (__ARDUINO_X86__) - #if defined (__arm__) && defined (SPI_UART) - #include - #define _SPI uspi - #else - #include - #define _SPI SPI - #endif - #elif !defined(__arm__) && !defined (__ARDUINO_X86__) +#include +#include +#include + + +#if defined(__arm__) || defined (__ARDUINO_X86__) +#if defined (__arm__) && defined (SPI_UART) +#include +#define _SPI uspi +#else +#include +#define _SPI SPI +#endif +#elif !defined(__arm__) && !defined (__ARDUINO_X86__) extern HardwareSPI SPI; - #endif - - #define _BV(x) (1<<(x)) - #endif - #ifdef SERIAL_DEBUG - #define IF_SERIAL_DEBUG(x) ({x;}) - #else - #define IF_SERIAL_DEBUG(x) - #if defined(RF24_TINY) - #define printf_P(...) - #endif - #endif - +#define _BV(x) (1<<(x)) + +#endif + +#ifdef SERIAL_DEBUG +#define IF_SERIAL_DEBUG(x) ({x;}) +#else +#define IF_SERIAL_DEBUG(x) +#if defined(RF24_TINY) +#define printf_P(...) +#endif +#endif + #if defined (__ARDUINO_X86__) - #define printf_P printf - #define _BV(bit) (1<<(bit)) +#define printf_P printf +#define _BV(bit) (1<<(bit)) #endif - + // Progmem is Arduino-specific // Arduino DUE is arm and does not include avr/pgmspace #if defined (ARDUINO_ARCH_ESP8266) - #include - #define PRIPSTR "%s" +#include +#define PRIPSTR "%s" #elif defined(ARDUINO) && !defined(ESP_PLATFORM) && ! defined(__arm__) && !defined (__ARDUINO_X86__) || defined(XMEGA) - #include - #define PRIPSTR "%S" +#include +#define PRIPSTR "%S" #else - #if ! defined(ARDUINO) // This doesn't work on Arduino DUE - typedef char const char; - #else // Fill in pgm_read_byte that is used, but missing from DUE - #define pgm_read_byte(addr) (*(const unsigned char *)(addr)) - #endif +#if ! defined(ARDUINO) // This doesn't work on Arduino DUE + typedef char const char; +#else // Fill in pgm_read_byte that is used, but missing from DUE +#define pgm_read_byte(addr) (*(const unsigned char *)(addr)) +#endif typedef uint16_t prog_uint16_t; - #define PSTR(x) (x) - #define printf_P printf - #define strlen_P strlen - #define PROGMEM - #define pgm_read_word(p) (*(p)) +#define PSTR(x) (x) +#define printf_P printf +#define strlen_P strlen +#define PROGMEM +#define pgm_read_word(p) (*(p)) - #define PRIPSTR "%s" +#define PRIPSTR "%s" #endif #endif - #endif // __RF24_CONFIG_H__ diff --git a/Software/ATmega32U4/SerialCommunication.h b/Software/ATmega32U4/SerialCommunication.h index 55eae6c..d9a0896 100644 --- a/Software/ATmega32U4/SerialCommunication.h +++ b/Software/ATmega32U4/SerialCommunication.h @@ -18,7 +18,7 @@ 通过CC1101 发射固定码信号 [RF][Transmit]315,1,B710 通过CC1101 发射灯光棒信号 - [RF][Transmit]LigthBar,freq:315,data:2600 + [RF][Transmit]LightBar,freq:315,data:2600 爆破固定码 [RF][Attack]Class2,freq:315,start:B701,end:B710,func:1 通过CC1101 发射FSK调制胎压信号 @@ -45,86 +45,100 @@ */ void SerialCommunication() { - while (Cube_PRINT.available() > 0) { - Cube_PRINT_data += char(Cube_PRINT.read()); - delay(4); - } - if (Cube_PRINT_data.length() > 0) { - if (Cube_PRINT_data.substring(1, 4) == "HID") { //h - hid_attack(); - } else if (Cube_PRINT_data.substring(1, 3) == "RF") { + while (Cube_PRINT.available() > 0) { + Cube_PRINT_data += char(Cube_PRINT.read()); + delay(4); + } + if (Cube_PRINT_data.length() > 0) { + if (Cube_PRINT_data.substring(1, 4) == "HID") { //h + hid_attack(); + } else if (Cube_PRINT_data.substring(1, 3) == "RF") { - if (int(Cube_PRINT_data.indexOf("Jam")) > 0) { - String Jam_Class = Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("class") + 6, Cube_PRINT_data.indexOf(",freq")); - if (Jam_Class == "Smart") { - freq1 = strtoul(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("freq1") + 6, Cube_PRINT_data.indexOf(",freq2")).c_str(), NULL, 10); - freq2 = strtoul(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("freq2") + 6, Cube_PRINT_data.length()).c_str(), NULL, 10); - RF_action = 1; + if (int(Cube_PRINT_data.indexOf("Jam")) > 0) { + String Jam_Class = Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("class") + 6, + Cube_PRINT_data.indexOf(",freq")); + if (Jam_Class == "Smart") { + freq1 = strtoul(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("freq1") + 6, + Cube_PRINT_data.indexOf(",freq2")).c_str(), NULL, 10); + freq2 = strtoul(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("freq2") + 6, + Cube_PRINT_data.length()).c_str(), NULL, 10); + RF_action = 1; - RF_Jam(); - } else if (Jam_Class == "Rude") { - freq = strtoul(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("freq") + 5, Cube_PRINT_data.length()).c_str(), NULL, 10); - //Serial.println(freq); - RF_action = 2; - RF_Jam(); - } + RF_Jam(); + } else if (Jam_Class == "Rude") { + freq = strtoul(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("freq") + 5, + Cube_PRINT_data.length()).c_str(), NULL, 10); + //Serial.println(freq); + RF_action = 2; + RF_Jam(); + } - } else if (int(Cube_PRINT_data.indexOf("TPMS")) > 0) { - CC1101_TPMS_TX(); - } else if (int(Cube_PRINT_data.indexOf("Transmit")) > 0) { - if (int(Cube_PRINT_data.indexOf("LigthBar")) > 0) { - RF_LigthBar(); - } else { - RF_Transmit(); - } - } else if (int(Cube_PRINT_data.indexOf("Attack")) > 0) { - RF_Attack(); - } else if (int(Cube_PRINT_data.indexOf("Switch")) > 0) { - RF_Switch(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("action") + 7, Cube_PRINT_data.indexOf('\r'))); - } else if (int(Cube_PRINT_data.indexOf("Setup")) > 0) { - if (int(Cube_PRINT_data.indexOf("CC1101")) > 0) { - cc1101_Setup(); - } else if (int(Cube_PRINT_data.indexOf("nRF24L01")) > 0) { + } else if (int(Cube_PRINT_data.indexOf("TPMS")) > 0) { + CC1101_TPMS_TX(); + } else if (int(Cube_PRINT_data.indexOf("Transmit")) > 0) { + if (int(Cube_PRINT_data.indexOf("LightBar")) > 0) { + RF_LightBar(); + } else { + RF_Transmit(); + } + } else if (int(Cube_PRINT_data.indexOf("Attack")) > 0) { + RF_Attack(); + } else if (int(Cube_PRINT_data.indexOf("Switch")) > 0) { + RF_Switch(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("action") + 7, + Cube_PRINT_data.indexOf('\r'))); + } else if (int(Cube_PRINT_data.indexOf("Setup")) > 0) { + if (int(Cube_PRINT_data.indexOf("CC1101")) > 0) { + cc1101_Setup(); + } else if (int(Cube_PRINT_data.indexOf("nRF24L01")) > 0) { + } + } + } else if (Cube_PRINT_data.substring(1, 4) == "NFC") { + if (Cube_PRINT_data.substring(6, 16) == "simulation") { + NFC_action = 1; + NFC_VD = atoi(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("vd") + 3, + Cube_PRINT_data.indexOf(",data")).c_str()); + NFC_ID = strtoul(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("data") + 5, + Cube_PRINT_data.length()).c_str(), NULL, 10); + Cube_PRINT.print("VD:"); + Cube_PRINT.print(NFC_VD); + Cube_PRINT.print("ID:"); + Cube_PRINT.println(NFC_ID); + } else if (Cube_PRINT_data.substring(6, 12) == "attack") { + NFC_action = 2; + NFC_VD = atoi(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("vd") + 3, + Cube_PRINT_data.indexOf(",start")).c_str()); + NFC_START = strtoul(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("start") + 6, + Cube_PRINT_data.indexOf(",end")).c_str(), NULL, 10); + NFC_END = strtoul( + Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("end") + 4, Cube_PRINT_data.length()).c_str(), + NULL, 10); + NFC_ID = NFC_START; + Cube_PRINT.print("VD:"); + Cube_PRINT.print(NFC_VD); + Cube_PRINT.print(";Start ID:"); + Cube_PRINT.print(NFC_START); + Cube_PRINT.print(";END ID:"); + Cube_PRINT.println(NFC_END); + } else if (Cube_PRINT_data.substring(6, 12) == "switch") { + NFC_Switch(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("action") + 7, + Cube_PRINT_data.indexOf('\r'))); + } else if (int(Cube_PRINT_data.indexOf("write")) > 0) { + //NFC_action = 3; + NFC_VD = atoi(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("vd") + 3, + Cube_PRINT_data.indexOf(",data")).c_str()); + NFC_ID = strtoul(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("data") + 5, + Cube_PRINT_data.length()).c_str(), NULL, 10); + Cube_PRINT.print("w,VD:"); + Cube_PRINT.print(NFC_VD); + Cube_PRINT.print("ID:"); + Cube_PRINT.println(NFC_ID); + EM4095.Write_ID(NFC_VD, NFC_ID); + } + } else { + Cube_PRINT.print("error:"); + Cube_PRINT.println(Cube_PRINT_data[0], HEX); } - } - } else if (Cube_PRINT_data.substring(1, 4) == "NFC") { - if (Cube_PRINT_data.substring(6, 16) == "simulation") { - NFC_action = 1; - NFC_VD = atoi(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("vd") + 3, Cube_PRINT_data.indexOf(",data")).c_str()); - NFC_ID = strtoul(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("data") + 5, Cube_PRINT_data.length()).c_str(), NULL, 10); - Cube_PRINT.print("VD:"); - Cube_PRINT.print(NFC_VD); - Cube_PRINT.print("ID:"); - Cube_PRINT.println(NFC_ID); - } else if (Cube_PRINT_data.substring(6, 12) == "attack") { - NFC_action = 2; - NFC_VD = atoi(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("vd") + 3, Cube_PRINT_data.indexOf(",start")).c_str()); - NFC_START = strtoul(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("start") + 6, Cube_PRINT_data.indexOf(",end")).c_str(), NULL, 10); - NFC_END = strtoul(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("end") + 4, Cube_PRINT_data.length()).c_str(), NULL, 10); - NFC_ID = NFC_START; - Cube_PRINT.print("VD:"); - Cube_PRINT.print(NFC_VD); - Cube_PRINT.print(";Start ID:"); - Cube_PRINT.print(NFC_START); - Cube_PRINT.print(";END ID:"); - Cube_PRINT.println(NFC_END); - } else if (Cube_PRINT_data.substring(6, 12) == "switch") { - NFC_Switch(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("action") + 7, Cube_PRINT_data.indexOf('\r'))); - } else if (int(Cube_PRINT_data.indexOf("write")) > 0) { - //NFC_action = 3; - NFC_VD = atoi(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("vd") + 3, Cube_PRINT_data.indexOf(",data")).c_str()); - NFC_ID = strtoul(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("data") + 5, Cube_PRINT_data.length()).c_str(), NULL, 10); - Cube_PRINT.print("w,VD:"); - Cube_PRINT.print(NFC_VD); - Cube_PRINT.print("ID:"); - Cube_PRINT.println(NFC_ID); - EM4095.Write_ID(NFC_VD,NFC_ID); - } - } else { - Cube_PRINT.print("error:"); - Cube_PRINT.println(Cube_PRINT_data[0], HEX); + Cube_PRINT_data = ""; } - Cube_PRINT_data = ""; - } } diff --git a/Software/ATmega32U4/attack.h b/Software/ATmega32U4/attack.h index 98a54e3..a19ec6c 100644 --- a/Software/ATmega32U4/attack.h +++ b/Software/ATmega32U4/attack.h @@ -15,67 +15,80 @@ byte syncWord[2] = {0xFF, 0xFF}; void bit1_1() { - digitalWrite(Transmitpin, HIGH); - delayMicroseconds(bit_delay_1); - //digitalWrite(pin, LOW); + digitalWrite(Transmitpin, HIGH); + delayMicroseconds(bit_delay_1); + //digitalWrite(pin, LOW); } + void bit0_1() { - digitalWrite(Transmitpin, LOW); - delayMicroseconds(bit_delay_1); + digitalWrite(Transmitpin, LOW); + delayMicroseconds(bit_delay_1); } void Sync_1() { - // 0101 0101 0101 00 1111111111 - bit0_1(); bit1_1(); - bit0_1(); bit1_1(); - - bit0_1(); bit1_1(); - bit0_1(); bit1_1(); - - bit0_1(); bit1_1(); - bit0_1(); bit1_1(); - - bit0_1(); bit0_1(); - bit1_1(); bit1_1(); bit1_1(); bit1_1(); bit1_1(); bit1_1(); bit1_1(); bit1_1(); bit1_1(); + // 0101 0101 0101 00 1111111111 + bit0_1(); + bit1_1(); + bit0_1(); + bit1_1(); + + bit0_1(); + bit1_1(); + bit0_1(); + bit1_1(); + + bit0_1(); + bit1_1(); + bit0_1(); + bit1_1(); + + bit0_1(); + bit0_1(); + bit1_1(); + bit1_1(); + bit1_1(); + bit1_1(); + bit1_1(); + bit1_1(); + bit1_1(); + bit1_1(); + bit1_1(); } - - - void CC1101_TPMS() { - cc1101.SS_PIN = RF433_CS; - counter = 0; - cc1101.initTmps(); - cc1101.setSyncWord(syncWord); - //cc1101.setCarrierFreq(CFREQ_433); - //setfreqx(430000000); - setfreqx(433925000); - //setfreqx(868000000); - //setfreqx(430000000); - cc1101.disableAddressCheck(); - //cc1101.writeReg(CC1101_PATABLE, 0xc0); + cc1101.SS_PIN = RF433_CS; + counter = 0; + cc1101.initTmps(); + cc1101.setSyncWord(syncWord); + //cc1101.setCarrierFreq(CFREQ_433); + //setfreqx(430000000); + setfreqx(433925000); + //setfreqx(868000000); + //setfreqx(430000000); + cc1101.disableAddressCheck(); + //cc1101.writeReg(CC1101_PATABLE, 0xc0); - /* - const byte paTable[8] = {0x00, 0x12, 0x0e, 0x34, 0x60, 0xc5, 0xc1, 0xc0}; - cc1101.writeBurstReg(CC1101_PATABLE, (byte*)paTable, 8); - */ + /* + const byte paTable[8] = {0x00, 0x12, 0x0e, 0x34, 0x60, 0xc5, 0xc1, 0xc0}; + cc1101.writeBurstReg(CC1101_PATABLE, (byte*)paTable, 8); + */ - cc1101.writeReg(CC1101_MCSM0, 0x08);// + cc1101.writeReg(CC1101_MCSM0, 0x08);// - cc1101.writeReg(CC1101_MDMCFG2, 0x03); //fsk - cc1101.writeReg(CC1101_DEVIATN, 0x35); //fsk freq 20 + cc1101.writeReg(CC1101_MDMCFG2, 0x03); //fsk + cc1101.writeReg(CC1101_DEVIATN, 0x35); //fsk freq 20 - //cc1101.writeReg(CC1101_DEVIATN, 0x24); //fsk freq 20 + //cc1101.writeReg(CC1101_DEVIATN, 0x24); //fsk freq 20 - //cc1101.writeReg(CC1101_IOCFG2, 0x0d);//rssi menu - //cc1101.writeReg(CC1101_AGCCTRL2, 0xB0); + //cc1101.writeReg(CC1101_IOCFG2, 0x0d);//rssi menu + //cc1101.writeReg(CC1101_AGCCTRL2, 0xB0); - //cc1101.writeReg(CC1101_MDMCFG4, 0xf9);// data rate - //cc1101.writeReg(CC1101_MDMCFG3, 0xFF); + //cc1101.writeReg(CC1101_MDMCFG4, 0xf9);// data rate + //cc1101.writeReg(CC1101_MDMCFG3, 0xFF); - // cc1101.cmdStrobe(CC1101_STX); + // cc1101.cmdStrobe(CC1101_STX); } /* @@ -92,191 +105,180 @@ void CC1101_TPMS() { } */ -uint16_t crc_xmodem_update (uint16_t crc, uint8_t data) -{ - int i; +uint16_t crc_xmodem_update(uint16_t crc, uint8_t data) { + int i; - crc = crc ^ ((uint16_t)data << 8); - for (i = 0; i < 8; i++) - { - if (crc & 0x8000) - crc = (crc << 1) ^ 0x1021; //(polynomial = 0x1021) - else - crc <<= 1; - } - return crc; + crc = crc ^ ((uint16_t) data << 8); + for (i = 0; i < 8; i++) { + if (crc & 0x8000) + crc = (crc << 1) ^ 0x1021; //(polynomial = 0x1021) + else + crc <<= 1; + } + return crc; } -uint16_t calc_crc(byte * msg, int n, uint16_t init) -{ - uint16_t x = init; +uint16_t calc_crc(byte *msg, int n, uint16_t init) { + uint16_t x = init; - while (n--) - { - x = crc_xmodem_update(x, (uint16_t) * msg++); - } + while (n--) { + x = crc_xmodem_update(x, (uint16_t) * msg++); + } - return (x); + return (x); } - - int lastbit; + void Transmit_bit1() { - if (lastbit) { - //Cube_PRINT.print("01"); - digitalWrite(Transmitpin, LOW); - delayMicroseconds(bit_delay_1); - digitalWrite(Transmitpin, HIGH); - delayMicroseconds(bit_delay_1); - lastbit = true; - } else { - digitalWrite(Transmitpin, HIGH); - delayMicroseconds(bit_delay_1); - digitalWrite(Transmitpin, LOW); - delayMicroseconds(bit_delay_1); - lastbit = false; - } + if (lastbit) { + //Cube_PRINT.print("01"); + digitalWrite(Transmitpin, LOW); + delayMicroseconds(bit_delay_1); + digitalWrite(Transmitpin, HIGH); + delayMicroseconds(bit_delay_1); + lastbit = true; + } else { + digitalWrite(Transmitpin, HIGH); + delayMicroseconds(bit_delay_1); + digitalWrite(Transmitpin, LOW); + delayMicroseconds(bit_delay_1); + lastbit = false; + } } + void Transmit_bit0() { - if (lastbit) { - digitalWrite(Transmitpin, LOW); - delayMicroseconds(bit_delay_1 * 2); - lastbit = false; - } else { - digitalWrite(Transmitpin, HIGH); - delayMicroseconds(bit_delay_1 * 2); - lastbit = true; - } + if (lastbit) { + digitalWrite(Transmitpin, LOW); + delayMicroseconds(bit_delay_1 * 2); + lastbit = false; + } else { + digitalWrite(Transmitpin, HIGH); + delayMicroseconds(bit_delay_1 * 2); + lastbit = true; + } } void Transmit_byte_1(byte data) { - for (int a = 0; a < 8; a++) { - if (data & 0x80) - Transmit_bit0(); - else - Transmit_bit1(); - data = data << 1; - } + for (int a = 0; a < 8; a++) { + if (data & 0x80) + Transmit_bit0(); + else + Transmit_bit1(); + data = data << 1; + } } +void Transmit_360(byte *Transmit_data) { + //int len = sizeof (Transmit_data); + int len = 8; + lastbit = true; + //Cube_PRINT.println("Tesxt"); + uint16_t crc_out = calc_crc(Transmit_data, len, 0xffff); + + //Calculate CRC on-the-fly + /*int msb = (crc_out & 0xff00) >> 8; + int lsb = (crc_out & 0x00ff) << 8; + crc_out = msb + lsb;*/ + + int msb = (crc_out & 0xff00) >> 8; + int lsb = (crc_out & 0x00ff); + Transmit_data[8] = lsb; + Transmit_data[9] = msb; + + len += 2; + Sync_1(); + for (int i = 0; i < len; i++) { + Transmit_byte_1(Transmit_data[i]); + //Serial.print(" "); + //Serial.print(Transmit_data[i],HEX); + } + //Serial.println(""); -void Transmit_360(byte * Transmit_data) { - //int len = sizeof (Transmit_data); - int len = 8; - lastbit = true; - //Cube_PRINT.println("Tesxt"); - uint16_t crc_out = calc_crc(Transmit_data, len, 0xffff); - - //Calculate CRC on-the-fly - /*int msb = (crc_out & 0xff00) >> 8; - int lsb = (crc_out & 0x00ff) << 8; - crc_out = msb + lsb;*/ - - int msb = (crc_out & 0xff00) >> 8; - int lsb = (crc_out & 0x00ff) ; - Transmit_data[8] = lsb; - Transmit_data[9] = msb; - - len += 2; - Sync_1(); - for (int i = 0; i < len; i++) { - Transmit_byte_1(Transmit_data[i]); - //Serial.print(" "); - //Serial.print(Transmit_data[i],HEX); - } - //Serial.println(""); - - digitalWrite(Transmitpin, HIGH); - delayMicroseconds(bit_delay_1 * 3); - digitalWrite(Transmitpin, LOW); + digitalWrite(Transmitpin, HIGH); + delayMicroseconds(bit_delay_1 * 3); + digitalWrite(Transmitpin, LOW); } - -void Attack_360_Car(byte * Tansmit_data) { - cc1101.cmdStrobe(CC1101_STX); - delayMicroseconds(802); - //delay(2); - //Transmit_360("0011001101010101001100110010110010101101010100110010101010110100110100110101001010101011010101001011010010101011010101010010101010101010101100110101001101001101111"); - Transmit_360(Tansmit_data); - cc1101.cmdStrobe(CC1101_SIDLE); - delay(65); - cc1101.cmdStrobe(CC1101_STX); - delayMicroseconds(802); - //Transmit_360("0011001101010101001100110010110010101101010100110010101010110100110100110101001010101011010101001011010010101011010101010010101010101010101100110101001101001101111"); - Transmit_360(Tansmit_data); - cc1101.cmdStrobe(CC1101_SIDLE); - delay(65); +void Attack_360_Car(byte *Tansmit_data) { + cc1101.cmdStrobe(CC1101_STX); + delayMicroseconds(802); + //delay(2); + //Transmit_360("0011001101010101001100110010110010101101010100110010101010110100110100110101001010101011010101001011010010101011010101010010101010101010101100110101001101001101111"); + Transmit_360(Tansmit_data); + cc1101.cmdStrobe(CC1101_SIDLE); + delay(65); + cc1101.cmdStrobe(CC1101_STX); + delayMicroseconds(802); + //Transmit_360("0011001101010101001100110010110010101101010100110010101010110100110100110101001010101011010101001011010010101011010101010010101010101010101100110101001101001101111"); + Transmit_360(Tansmit_data); + cc1101.cmdStrobe(CC1101_SIDLE); + delay(65); } - void CC1101_TPMS_TX() { - //detachInterrupt(RF315_att); - - byte TPMS_data[11]; - int a = 0; - for (int i = 10; i < Cube_PRINT_data.length(); i += 2) - { - String bdata = String(Cube_PRINT_data[i]) + String(Cube_PRINT_data[i + 1]); - - TPMS_data[a] = strtoul(bdata.c_str(), NULL, 16); - if (a == 5) - TPMS_data[a] = strtoul(bdata.c_str(), NULL, 10) * 3.2; - else if (a == 6) - TPMS_data[a] = strtoul(bdata.c_str(), NULL, 10) + 0x37; - Cube_PRINT.print(" "); - Cube_PRINT.print(TPMS_data[a], HEX); - a++; - } - //20 93 EF 85 A0 40 58 0 27 31 - //byte TPMS_data_1[11]={0x20,0x95,0x91,0x85,0xb1,0x11,0x52,0x08}; - - Cube_PRINT.println("TPMS_ok"); - Cube_PRINT_data = ""; - - CC1101_TPMS(); - delay(100); - cc1101.cmdStrobe(CC1101_SCAL); - Attack_360_Car(TPMS_data); - delay(100); - Attack_360_Car(TPMS_data); - delay(100); - // mySwitch.enableReceive(1); - cc1101_config(); - // RF315_Setup(); - // delay(4); - // Hackradio.enableReceive(RF315_att); -} - - + //detachInterrupt(RF315_att); + + byte TPMS_data[11]; + int a = 0; + for (int i = 10; i < Cube_PRINT_data.length(); i += 2) { + String bdata = String(Cube_PRINT_data[i]) + String(Cube_PRINT_data[i + 1]); + + TPMS_data[a] = strtoul(bdata.c_str(), NULL, 16); + if (a == 5) + TPMS_data[a] = strtoul(bdata.c_str(), NULL, 10) * 3.2; + else if (a == 6) + TPMS_data[a] = strtoul(bdata.c_str(), NULL, 10) + 0x37; + Cube_PRINT.print(" "); + Cube_PRINT.print(TPMS_data[a], HEX); + a++; + } + //20 93 EF 85 A0 40 58 0 27 31 + //byte TPMS_data_1[11]={0x20,0x95,0x91,0x85,0xb1,0x11,0x52,0x08}; + Cube_PRINT.println("TPMS_ok"); + Cube_PRINT_data = ""; -void CC1101_TPMS_TX_TEST() { - //detachInterrupt(RF315_att); - byte TPMS_data[11] = { - //20 95 91 85 A0 40 63 0 52 8C - 0x20, 0x95, 0x91, 0x85, 0xA0, 20 * 3.2, 44 + 0x37, 0x00 - }; - CC1101_TPMS(); - cc1101.PrintConfig(); - while (1) { + CC1101_TPMS(); + delay(100); cc1101.cmdStrobe(CC1101_SCAL); Attack_360_Car(TPMS_data); delay(100); Attack_360_Car(TPMS_data); delay(100); - delay(1000); - } - + // mySwitch.enableReceive(1); + cc1101_config(); + // RF315_Setup(); + // delay(4); + // Hackradio.enableReceive(RF315_att); } +void CC1101_TPMS_TX_TEST() { + //detachInterrupt(RF315_att); + byte TPMS_data[11] = { + //20 95 91 85 A0 40 63 0 52 8C + 0x20, 0x95, 0x91, 0x85, 0xA0, 20 * 3.2, 44 + 0x37, 0x00 + }; + CC1101_TPMS(); + cc1101.PrintConfig(); + while (1) { + cc1101.cmdStrobe(CC1101_SCAL); + Attack_360_Car(TPMS_data); + delay(100); + Attack_360_Car(TPMS_data); + delay(100); + delay(1000); + } + +} + /* RF Jaming @@ -288,104 +290,37 @@ void Rude_Jam() { void Smart_Jam(unsigned long freq1, unsigned long freq2, int Jam_RSSI = -73) { - cc1101.SS_PIN = RF433_CS; - cc1101.init(); - setfreqx(433920000); - cc1101.cmdStrobe(CC1101_SRX); - //cc1101.writeReg(CC1101_IOCFG2, 0x0d); - //cc1101.writeReg(CC1101_AGCCTRL2, 0xB0); - //cc1101.PrintConfig(); - int a; - unsigned long freq; - bool Jam_flag = false, Out_flag = true; - unsigned long Jam_OutTime; - - while (1) { - - if (a) - freq = freq1; - else - freq = freq2; - a = !a; - cc1101.cmdStrobe(CC1101_SIDLE); - setfreqx(freq); + cc1101.SS_PIN = RF433_CS; + cc1101.init(); + setfreqx(433920000); cc1101.cmdStrobe(CC1101_SRX); - delay(2); - int rssi = cc1101.readrssi(); - signed int RSSI_db; - if (rssi > 128) - RSSI_db = ((rssi - 256) / 2) - 75; - else - RSSI_db = (rssi / 2) - 75; - - if (RSSI_db > Jam_RSSI ) { - //String pinrt_data = String(freq); - //pinrt_data = pinrt_data.substring(0, 3) + "Mhz" + " Jamming..."; - cc1101.cmdStrobe(CC1101_SIDLE); - setfreqx(freq); - cc1101.cmdStrobe(CC1101_STX); - digitalWrite(RF433_GDO0, HIGH); - delay(5); - digitalWrite(RF433_GDO0, LOW); - Jam_flag = true; - Jam_OutTime = millis(); - } - if (Jam_flag && millis() - Jam_OutTime > 100) { - Cube_PRINT.println("Jam_out"); - Out_flag = true; - Jam_flag = false; - } else if (Jam_flag && Out_flag) { - Cube_PRINT.print(RSSI_db); - Cube_PRINT.print(";"); - Cube_PRINT.println(freq); - Out_flag = false; - Jam_flag = false; - } - } -} + //cc1101.writeReg(CC1101_IOCFG2, 0x0d); + //cc1101.writeReg(CC1101_AGCCTRL2, 0xB0); + //cc1101.PrintConfig(); + int a; + unsigned long freq; + bool Jam_flag = false, Out_flag = true; + unsigned long Jam_OutTime; + while (1) { -int RF_action, Jam_RSSI; -unsigned long freq1, freq2, freq = 433920000; -void RF_Jam() { - - cc1101.SS_PIN = RF433_CS; - cc1101.init(); - - cc1101.cmdStrobe(CC1101_SIDLE); - setfreqx(freq); - cc1101.cmdStrobe(CC1101_STX); - digitalWrite(RF433_GDO0, HIGH); - - //cc1101.PrintConfig(); - Jam_RSSI = -73; - int a; - //unsigned long freq; - bool Jam_flag = false, Out_flag = true; - unsigned long Jam_OutTime; - - - while (RF_action) { - - switch (RF_action) { - case 1: { //Smart - if (a) + if (a) freq = freq1; - else + else freq = freq2; - a = !a; - cc1101.cmdStrobe(CC1101_SIDLE); - setfreqx(freq); - cc1101.cmdStrobe(CC1101_SRX); - delay(2); - int rssi = cc1101.readrssi(); - signed int RSSI_db; - if (rssi > 128) + a = !a; + cc1101.cmdStrobe(CC1101_SIDLE); + setfreqx(freq); + cc1101.cmdStrobe(CC1101_SRX); + delay(2); + int rssi = cc1101.readrssi(); + signed int RSSI_db; + if (rssi > 128) RSSI_db = ((rssi - 256) / 2) - 75; - else + else RSSI_db = (rssi / 2) - 75; - if (RSSI_db > Jam_RSSI ) { + if (RSSI_db > Jam_RSSI) { //String pinrt_data = String(freq); //pinrt_data = pinrt_data.substring(0, 3) + "Mhz" + " Jamming..."; cc1101.cmdStrobe(CC1101_SIDLE); @@ -396,40 +331,109 @@ void RF_Jam() { digitalWrite(RF433_GDO0, LOW); Jam_flag = true; Jam_OutTime = millis(); - //2018年12月26日17:03:23 - if (millis() - SerialLastTime < Print_Time-200) { - //return; - } else { - String Jam_DATA = "[RF][Jam]RSSI:" + String(RSSI_db) + "dB,FREQ:" + String(freq).substring(0, 3) + "Mhz"; - Cube_PRINT.println(Jam_DATA); - SerialLastTime=Jam_OutTime=millis(); - } - } - if (Jam_flag && millis() - Jam_OutTime > 200) { - Cube_PRINT.println("[RF][Jam]Not Jamming"); + } + if (Jam_flag && millis() - Jam_OutTime > 100) { + Cube_PRINT.println("Jam_out"); Out_flag = true; Jam_flag = false; - //} else if (Jam_flag && Out_flag) { - } else if (Jam_flag && Out_flag) { - Cube_PRINT.print("[RF][Jam]RSSI:"); + } else if (Jam_flag && Out_flag) { Cube_PRINT.print(RSSI_db); - Cube_PRINT.print("dB,FREQ:"); - Cube_PRINT.print(String(freq).substring(0, 3)); - Cube_PRINT.println("Mhz"); + Cube_PRINT.print(";"); + Cube_PRINT.println(freq); Out_flag = false; Jam_flag = false; - } } - break; - case 2://Rude - //cc1101.cmdStrobe(CC1101_STX); - digitalWrite(RF433_GDO0, HIGH); - break; } - if (Cube_PRINT.available() > 0) { - RF_action = 0; - cc1101_config(); - Cube_PRINT.println("exit"); +} + + +int RF_action, Jam_RSSI; +unsigned long freq1, freq2, freq = 433920000; + +void RF_Jam() { + + cc1101.SS_PIN = RF433_CS; + cc1101.init(); + + cc1101.cmdStrobe(CC1101_SIDLE); + setfreqx(freq); + cc1101.cmdStrobe(CC1101_STX); + digitalWrite(RF433_GDO0, HIGH); + + //cc1101.PrintConfig(); + Jam_RSSI = -73; + int a; + //unsigned long freq; + bool Jam_flag = false, Out_flag = true; + unsigned long Jam_OutTime; + + + while (RF_action) { + + switch (RF_action) { + case 1: { //Smart + if (a) + freq = freq1; + else + freq = freq2; + a = !a; + cc1101.cmdStrobe(CC1101_SIDLE); + setfreqx(freq); + cc1101.cmdStrobe(CC1101_SRX); + delay(2); + int rssi = cc1101.readrssi(); + signed int RSSI_db; + if (rssi > 128) + RSSI_db = ((rssi - 256) / 2) - 75; + else + RSSI_db = (rssi / 2) - 75; + + if (RSSI_db > Jam_RSSI) { + //String pinrt_data = String(freq); + //pinrt_data = pinrt_data.substring(0, 3) + "Mhz" + " Jamming..."; + cc1101.cmdStrobe(CC1101_SIDLE); + setfreqx(freq); + cc1101.cmdStrobe(CC1101_STX); + digitalWrite(RF433_GDO0, HIGH); + delay(5); + digitalWrite(RF433_GDO0, LOW); + Jam_flag = true; + Jam_OutTime = millis(); + //2018年12月26日17:03:23 + if (millis() - SerialLastTime < Print_Time - 200) { + //return; + } else { + String Jam_DATA = + "[RF][Jam]RSSI:" + String(RSSI_db) + "dB,FREQ:" + String(freq).substring(0, 3) + "Mhz"; + Cube_PRINT.println(Jam_DATA); + SerialLastTime = Jam_OutTime = millis(); + } + } + if (Jam_flag && millis() - Jam_OutTime > 200) { + Cube_PRINT.println("[RF][Jam]Not Jamming"); + Out_flag = true; + Jam_flag = false; + //} else if (Jam_flag && Out_flag) { + } else if (Jam_flag && Out_flag) { + Cube_PRINT.print("[RF][Jam]RSSI:"); + Cube_PRINT.print(RSSI_db); + Cube_PRINT.print("dB,FREQ:"); + Cube_PRINT.print(String(freq).substring(0, 3)); + Cube_PRINT.println("Mhz"); + Out_flag = false; + Jam_flag = false; + } + } + break; + case 2://Rude + //cc1101.cmdStrobe(CC1101_STX); + digitalWrite(RF433_GDO0, HIGH); + break; + } + if (Cube_PRINT.available() > 0) { + RF_action = 0; + cc1101_config(); + Cube_PRINT.println("exit"); + } } - } } diff --git a/Software/ATmega32U4/cc1101.cpp b/Software/ATmega32U4/cc1101.cpp index 7ae4e07..296d09e 100644 --- a/Software/ATmega32U4/cc1101.cpp +++ b/Software/ATmega32U4/cc1101.cpp @@ -6,7 +6,7 @@ //#define cc1101_Deselect() bitSet(PORT_SPI_SS, BIT_SPI_SS)//digitalWrite(10,LOW) #define cc1101_Deselect() digitalWrite(SS_PIN,HIGH) //#define wait_Miso() while(bitRead(PORT_SPI_MISO, BIT_SPI_MISO)) -#define wait_Miso() +#define wait_Miso() // Get GDO0 pin state #define getGDO0state() bitRead(GDO0_PIN, BIT_GDO0) // Wait until GDO0 line goes high @@ -18,19 +18,17 @@ const byte paTable[8] = {0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; -CC1101::CC1101(void) -{ +CC1101::CC1101(void) { } -void CC1101::writeReg(byte regAddr, byte value) -{ - cc1101_Select(); // Select CC1101 - wait_Miso(); // Wait until MISO goes low - spi.send(regAddr); // Send register address - spi.send(value); // Send value - cc1101_Deselect(); // Deselect CC1101 +void CC1101::writeReg(byte regAddr, byte value) { + cc1101_Select(); // Select CC1101 + wait_Miso(); // Wait until MISO goes low + spi.send(regAddr); // Send register address + spi.send(value); // Send value + cc1101_Deselect(); // Deselect CC1101 } /** @@ -42,19 +40,18 @@ void CC1101::writeReg(byte regAddr, byte value) * 'buffer' Data to be writen * 'len' Data length */ -void CC1101::writeBurstReg(byte regAddr, byte* buffer, byte len) -{ - byte addr, i; - - addr = regAddr | WRITE_BURST; // Enable burst transfer - cc1101_Select(); // Select CC1101 - wait_Miso(); // Wait until MISO goes low - spi.send(addr); // Send register address - - for(i=0 ; i 0; a--) { - //((val & 0x1) << (a - 1)) - // (x[i] & (1 << a)) >> a; - if (flag & (1 << (a - 1))) { - bit1(); - } else { - bit0(); - } +void EM4095::transmit(int *data) { + Start(); + for (int i = 0; i < 11; i++) { + int flag = data[i]; + for (int a = 5; a > 0; a--) { + //((val & 0x1) << (a - 1)) + // (x[i] & (1 << a)) >> a; + if (flag & (1 << (a - 1))) { + bit1(); + } else { + bit0(); + } + } } - } // Serial.println(""); } - -void EM4095::transmit(unsigned long long data) { - for (int i = 64; i > 0; i--) { - if (data >> (i-1 ) & 1) - bit1(); - else - bit0(); - } +void EM4095::transmit(unsigned long long data) { + for (int i = 64; i > 0; i--) { + if (data >> (i - 1) & 1) + bit1(); + else + bit0(); + } } -void EM4095::simulation_bak(int vd, unsigned long id) { - int x[13]; - int l = 2; - long f = 0xf; - x[0] = (vd & 0xF0)>>4; x[1] = vd & 0x0F; - - for (int i = 7; i >= 0; i--) { - x[l] = (id & f << i * 4) >> i * 4; - l++; - } - transmit(parity_check(x)); -} +void EM4095::simulation_bak(int vd, unsigned long id) { + int x[13]; + int l = 2; + long f = 0xf; + x[0] = (vd & 0xF0) >> 4; + x[1] = vd & 0x0F; + for (int i = 7; i >= 0; i--) { + x[l] = (id & f << i * 4) >> i * 4; + l++; + } + transmit(parity_check(x)); +} -void EM4095::simulation(int vd, unsigned long id) { - int x[13]; - int l = 2; - long f = 0xf; - x[0] = (vd & 0xF0)>>4; x[1] = vd & 0x0F; - for (int i = 7; i >= 0; i--) { - x[l] = (id & f << i * 4) >> i * 4; - l++; - } - int * xx=parity_check(x); - - unsigned long long NFC_DATA=0xFF80000000000000; - //unsigned long NFC_DATA_MSB=0xFF800000; - //int a=55; - unsigned long long temp; - for(int i=0;i<11;i++){ - temp=xx[i]; - temp=temp<<50-i*5;//50= - (9) - (5) - NFC_DATA+=temp; - } - transmit(NFC_DATA); +void EM4095::simulation(int vd, unsigned long id) { + int x[13]; + int l = 2; + long f = 0xf; + x[0] = (vd & 0xF0) >> 4; + x[1] = vd & 0x0F; + for (int i = 7; i >= 0; i--) { + x[l] = (id & f << i * 4) >> i * 4; + l++; + } + int *xx = parity_check(x); + + unsigned long long NFC_DATA = 0xFF80000000000000; + //unsigned long NFC_DATA_MSB=0xFF800000; + //int a=55; + unsigned long long temp; + for (int i = 0; i < 11; i++) { + temp = xx[i]; + temp = temp << 50 - i * 5;//50= - (9) - (5) + NFC_DATA += temp; + } + transmit(NFC_DATA); } -int * EM4095::parity_check(int * x) -{ +int *EM4095::parity_check(int *x) { - for (int i = 0; i < 10; i++) { - int val = 0; - unsigned int flag = x[i]; - while (flag) - { - val ^= flag; - flag >>= 1; - } - x[i] = x[i] << 1; - x[i] = x[i] + (val & 0x1); - } - int yval, da , val = 0; - for (int a = 4; a > 0; a--) { - //val=x[0]+x[1]+x[2]+x[3]+x[4]+x[5]+x[6]+x[7]+x[8]+x[9]+x[10]; - //val=(x[0]&(1<> a; - // Serial.print((x[i]&(1<>a,HEX); - //Serial.print(val&0x01,HEX); - //Serial.print(" "); + int val = 0; + unsigned int flag = x[i]; + while (flag) { + val ^= flag; + flag >>= 1; + } + x[i] = x[i] << 1; + x[i] = x[i] + (val & 0x1); } + int yval, da, val = 0; + for (int a = 4; a > 0; a--) { + //val=x[0]+x[1]+x[2]+x[3]+x[4]+x[5]+x[6]+x[7]+x[8]+x[9]+x[10]; + //val=(x[0]&(1<> a; + // Serial.print((x[i]&(1<>a,HEX); + //Serial.print(val&0x01,HEX); + //Serial.print(" "); + } - da = ((val & 0x1) << (a - 1)); - tempdata += da; - //Serial.print(((val & 0x1) << (a - 1)), HEX); - //Serial.print(da1); - //Serial.print(" "); - val = 0; - } //Serial.println(" "); - x[10] = tempdata << 1; - tempdata = 0; - yval = 0; - - return x; + da = ((val & 0x1) << (a - 1)); + tempdata += da; + //Serial.print(((val & 0x1) << (a - 1)), HEX); + //Serial.print(da1); + //Serial.print(" "); + val = 0; + } //Serial.println(" "); + x[10] = tempdata << 1; + tempdata = 0; + yval = 0; + + return x; } @@ -137,12 +135,13 @@ int * EM4095::parity_check(int * x) 400 125 */ void EM4095::Write_Bit1() { - digitalWrite(MOD, LOW); //GPIO_ResetBits(MOD_PORT, MOD_PIN); - delayMicroseconds(350); - digitalWrite(MOD, HIGH); - delayMicroseconds(150); - digitalWrite(MOD, LOW); + digitalWrite(MOD, LOW); //GPIO_ResetBits(MOD_PORT, MOD_PIN); + delayMicroseconds(350); + digitalWrite(MOD, HIGH); + delayMicroseconds(150); + digitalWrite(MOD, LOW); } + /* +---+ | | @@ -150,12 +149,13 @@ void EM4095::Write_Bit1() { 200 125 */ void EM4095::Write_Bit0() { - digitalWrite(MOD, LOW); //GPIO_ResetBits(MOD_PORT, MOD_PIN); - delayMicroseconds(100); - digitalWrite(MOD, HIGH); - delayMicroseconds(150); - digitalWrite(MOD, LOW); //GPIO_ResetBits(MOD_PORT, MOD_PIN); + digitalWrite(MOD, LOW); //GPIO_ResetBits(MOD_PORT, MOD_PIN); + delayMicroseconds(100); + digitalWrite(MOD, HIGH); + delayMicroseconds(150); + digitalWrite(MOD, LOW); //GPIO_ResetBits(MOD_PORT, MOD_PIN); } + /* +-----+ +---+ +---+ +---+ | | | | | | | | @@ -167,301 +167,267 @@ void EM4095::Write_Bit0() { +-------+ +----+ +----+ + 181 320 90 145 90 145 90 */ -void EM4095::Write_ID_Start() -{ - digitalWrite(MOD, HIGH); //GPIO_SetBits(MOD_PORT, MOD_PIN); - delayMicroseconds(240);//#Delay_us(250); - digitalWrite(MOD, LOW); //GPIO_ResetBits(MOD_PORT, MOD_PIN); - Write_Bit1(); - Write_Bit0(); - Write_Bit0(); +void EM4095::Write_ID_Start() { + digitalWrite(MOD, HIGH); //GPIO_SetBits(MOD_PORT, MOD_PIN); + delayMicroseconds(240);//#Delay_us(250); + digitalWrite(MOD, LOW); //GPIO_ResetBits(MOD_PORT, MOD_PIN); + Write_Bit1(); + Write_Bit0(); + Write_Bit0(); } -void EM4095::Write_ID_Block(uint32_t *ID_Data, uint8_t Data_Nun, uint8_t ID_Addr) -{ - uint32_t i; - Write_ID_Start(); - while (Data_Nun--) - { - for (i = 32; i > 0; i--) - { - if ((*ID_Data >> (i - 1)) & 0x0001) - Write_Bit1(); - else - Write_Bit0(); +void EM4095::Write_ID_Block(uint32_t *ID_Data, uint8_t Data_Nun, uint8_t ID_Addr) { + uint32_t i; + Write_ID_Start(); + while (Data_Nun--) { + for (i = 32; i > 0; i--) { + if ((*ID_Data >> (i - 1)) & 0x0001) + Write_Bit1(); + else + Write_Bit0(); + } + ID_Data++; + } + for (i = 3; i > 0; i--) { + if ((ID_Addr >> (i - 1)) & 0x01) + Write_Bit1(); + else + Write_Bit0(); } - ID_Data++; - } - for (i = 3; i > 0; i--) - { - if ((ID_Addr >> (i - 1)) & 0x01) - Write_Bit1(); - else - Write_Bit0(); - } } - -unsigned long long EM4095::parity_check_write(int vd, unsigned long id) { - int x[13]; - int l = 2; - long f = 0xf; - x[0] = (vd & 0xF0) >> 4; x[1] = vd & 0x0F; - for (int i = 7; i >= 0; i--) { - x[l] = (id & f << i * 4) >> i * 4; - l++; - } - int * xx = parity_check(x); - unsigned long long NFC_DATA = 0xFF80000000000000; - unsigned long long temp; - for (int i = 0; i < 11; i++) { - temp = xx[i]; - temp = temp << 50 - i * 5; //50= - (9) - (5) - NFC_DATA += temp; - } - return NFC_DATA; - /* - unsigned long id_data_MSB=NFC_DATA>>32; - unsigned long id_data_LSB=NFC_DATA&0xffffffff; - Serial.print(id_data_MSB,HEX); - Serial.print(","); - Serial.println(id_data_LSB,HEX);*/ - //transmit(NFC_DATA); +unsigned long long EM4095::parity_check_write(int vd, unsigned long id) { + int x[13]; + int l = 2; + long f = 0xf; + x[0] = (vd & 0xF0) >> 4; + x[1] = vd & 0x0F; + for (int i = 7; i >= 0; i--) { + x[l] = (id & f << i * 4) >> i * 4; + l++; + } + int *xx = parity_check(x); + unsigned long long NFC_DATA = 0xFF80000000000000; + unsigned long long temp; + for (int i = 0; i < 11; i++) { + temp = xx[i]; + temp = temp << 50 - i * 5; //50= - (9) - (5) + NFC_DATA += temp; + } + return NFC_DATA; + /* + unsigned long id_data_MSB=NFC_DATA>>32; + unsigned long id_data_LSB=NFC_DATA&0xffffffff; + Serial.print(id_data_MSB,HEX); + Serial.print(","); + Serial.println(id_data_LSB,HEX);*/ + //transmit(NFC_DATA); } - -void EM4095::Write_ID(uint8_t WriteVD, uint32_t WriteID) -{ - uint32_t Config[2] = {0x264CB9E0, 0x00148040}; - uint32_t Password = 0x00000000; - uint32_t CardType = 0x00148040; - - //digitalWrite(SHD, LOW); //CLR_SHD - digitalWrite(SHD, LOW); //CLR_SHD - delay(36); - Write_ID_Block(Config, 2, 0x00); - delay(16); - Write_ID_Block(&Password, 1, 0x07); - delay(33); - Write_ID_Block(&CardType, 1, 0x00); - delay(16); - unsigned long long CardData = parity_check_write(WriteVD, WriteID); - uint32_t CardDataMSB = CardData >> 32; - uint32_t CardDataLSB = CardData & 0xffffffff; - - Write_ID_Block(&CardDataMSB, 1, 0x01); - delay(16); - Write_ID_Block(&CardDataLSB , 1, 0x02); - delay(16); - digitalWrite(SHD, HIGH); //SET_SHD(); - - - delay(133); - digitalWrite(SHD, LOW); - delay(133); - digitalWrite(SHD, HIGH); - digitalWrite(MOD, HIGH); - delay(100); - digitalWrite(SHD, LOW); - digitalWrite(MOD, LOW); - delay(100); - digitalWrite(SHD, HIGH); - digitalWrite(MOD, HIGH); - delay(100); - digitalWrite(SHD, LOW); - digitalWrite(MOD, LOW); - //digitalWrite(SHD, HIGH); //SET_SHD(); +void EM4095::Write_ID(uint8_t WriteVD, uint32_t WriteID) { + uint32_t Config[2] = {0x264CB9E0, 0x00148040}; + uint32_t Password = 0x00000000; + uint32_t CardType = 0x00148040; + + //digitalWrite(SHD, LOW); //CLR_SHD + digitalWrite(SHD, LOW); //CLR_SHD + delay(36); + Write_ID_Block(Config, 2, 0x00); + delay(16); + Write_ID_Block(&Password, 1, 0x07); + delay(33); + Write_ID_Block(&CardType, 1, 0x00); + delay(16); + unsigned long long CardData = parity_check_write(WriteVD, WriteID); + uint32_t CardDataMSB = CardData >> 32; + uint32_t CardDataLSB = CardData & 0xffffffff; + + Write_ID_Block(&CardDataMSB, 1, 0x01); + delay(16); + Write_ID_Block(&CardDataLSB, 1, 0x02); + delay(16); + digitalWrite(SHD, HIGH); //SET_SHD(); + + + delay(133); + digitalWrite(SHD, LOW); + delay(133); + digitalWrite(SHD, HIGH); + digitalWrite(MOD, HIGH); + delay(100); + digitalWrite(SHD, LOW); + digitalWrite(MOD, LOW); + delay(100); + digitalWrite(SHD, HIGH); + digitalWrite(MOD, HIGH); + delay(100); + digitalWrite(SHD, LOW); + digitalWrite(MOD, LOW); + //digitalWrite(SHD, HIGH); //SET_SHD(); } -bool EM4095::decodeTag(unsigned long &udata,int &ReadVd) -{ - unsigned long outtime= millis(); - - unsigned char i = 0; - unsigned short timeCount; - unsigned char timeOutFlag = 0; - unsigned char row, col; - unsigned char row_parity; - unsigned char col_parity[5]; - int dat; - unsigned char searchCount = 0; - unsigned char j; - //unsigned long udata; - - ReadVd = 0; - while (1) - { - if(millis() - outtime > 100) - return false; - - timeCount = 0; - while (0 == digitalRead(ID_OUT)) //watch for ID_OUT to go low - { - - if (timeCount >= TIMEOUT) //if we pass TIMEOUT milliseconds, break out of the loop - { - break; - } - else - { - timeCount++; - } - } +bool EM4095::decodeTag(unsigned long &udata, int &ReadVd) { + unsigned long outtime = millis(); - if (timeCount >= 1200) - { - return false; - } - timeCount = 0; + unsigned char i = 0; + unsigned short timeCount; + unsigned char timeOutFlag = 0; + unsigned char row, col; + unsigned char row_parity; + unsigned char col_parity[5]; + int dat; + unsigned char searchCount = 0; + unsigned char j; + //unsigned long udata; - delayMicroseconds(DELAYVAL); - if (digitalRead(ID_OUT) == HIGH) - { + ReadVd = 0; + while (1) { + if (millis() - outtime > 100) + return false; - for (i = 0; i < 8; i++) // 9 header bits - { - timeCount = 0; //restart counting - while (1 == digitalRead(ID_OUT)) //while DEMOD out is high + timeCount = 0; + while (0 == digitalRead(ID_OUT)) //watch for ID_OUT to go low { - if (timeCount == TIMEOUT) - { - timeOutFlag = 1; - break; - } - else - { - timeCount++; - } + if (timeCount >= TIMEOUT) //if we pass TIMEOUT milliseconds, break out of the loop + { + break; + } else { + timeCount++; + } } - if (timeOutFlag) - { - break; - } - else - { - delayMicroseconds(DELAYVAL); - /* digitalWrite(PA3,HIGH); - delayMicroseconds(20); - digitalWrite(PA3,LOW);*/ - if ( 0 == digitalRead(ID_OUT) ) - { - break; - } + if (timeCount >= 1200) { + return false; } - } - if (timeOutFlag) - { - timeOutFlag = 0; - return false; - } - if (i == 8) //识别到九个前导码 开始接收数据 - { - - /* digitalWrite(PA3, HIGH); - delayMicroseconds(20); - digitalWrite(PA3, LOW);*/ - - - timeOutFlag = 0; timeCount = 0; - while (1 == digitalRead(ID_OUT)) - { - if (timeCount == TIMEOUT) - { - timeOutFlag = 1; - break; - } - else - { - timeCount++; - } - - if (timeOutFlag) - { - timeOutFlag = 0; - return false; - } - } + delayMicroseconds(DELAYVAL); + if (digitalRead(ID_OUT) == HIGH) { - col_parity[0] = col_parity[1] = col_parity[2] = col_parity[3] = col_parity[4] = 0; - for (row = 0; row < 11; row++) - { - /* digitalWrite(PA3, HIGH); - delayMicroseconds(15); - digitalWrite(PA3, LOW); - */ - row_parity = 0; - j = row - 1; - for (col = 0, row_parity = 0; col < 5; col++) - { - /* digitalWrite(PA3, HIGH); - delayMicroseconds(2); - digitalWrite(PA3, LOW);*/ - delayMicroseconds(DELAYVAL); - if (digitalRead(ID_OUT)) { - dat = 1; - } else { - dat = 0; - } - if (col < 4 && row < 10 && row > 1) + for (i = 0; i < 8; i++) // 9 header bits { - udata = udata << 1; - udata += dat; - } else if (col < 4 && row < 2) { - ReadVd = ReadVd << 1; - ReadVd += dat; + timeCount = 0; //restart counting + while (1 == digitalRead(ID_OUT)) //while DEMOD out is high + { + + if (timeCount == TIMEOUT) { + timeOutFlag = 1; + break; + } else { + timeCount++; + } + } + + if (timeOutFlag) { + break; + } else { + delayMicroseconds(DELAYVAL); + /* digitalWrite(PA3,HIGH); + delayMicroseconds(20); + digitalWrite(PA3,LOW);*/ + if (0 == digitalRead(ID_OUT)) { + break; + } + } } - - - row_parity += dat; - col_parity[col] += dat; - timeCount = 0; - - while (digitalRead(ID_OUT) == dat) - { - if (timeCount == TIMEOUT) - { - timeOutFlag = 1; - break; - } - else - timeCount++; - + if (timeOutFlag) { + timeOutFlag = 0; + return false; } - if (timeOutFlag) - break; - } - - if (row < 10) - { - if ((row_parity & 0x01) || timeOutFlag) //Row parity + if (i == 8) //识别到九个前导码 开始接收数据 { - timeOutFlag = 1; - break; - } - } - } - if ( timeOutFlag || (col_parity[0] & 0x01) || (col_parity[1] & 0x01) || (col_parity[2] & 0x01) || (col_parity[3] & 0x01) ) //Column parity - { - timeOutFlag = 0; - return false; - } - else - { - ReadVd = ReadVd & 0xff; - //Serial.println(ReadVd); - //return (udata); - return true; + + /* digitalWrite(PA3, HIGH); + delayMicroseconds(20); + digitalWrite(PA3, LOW);*/ + + + timeOutFlag = 0; + timeCount = 0; + + while (1 == digitalRead(ID_OUT)) { + if (timeCount == TIMEOUT) { + timeOutFlag = 1; + break; + } else { + timeCount++; + } + + if (timeOutFlag) { + timeOutFlag = 0; + return false; + } + } + + col_parity[0] = col_parity[1] = col_parity[2] = col_parity[3] = col_parity[4] = 0; + for (row = 0; row < 11; row++) { + /* digitalWrite(PA3, HIGH); + delayMicroseconds(15); + digitalWrite(PA3, LOW); + */ + row_parity = 0; + j = row - 1; + for (col = 0, row_parity = 0; col < 5; col++) { + /* digitalWrite(PA3, HIGH); + delayMicroseconds(2); + digitalWrite(PA3, LOW);*/ + delayMicroseconds(DELAYVAL); + if (digitalRead(ID_OUT)) { + dat = 1; + } else { + dat = 0; + } + if (col < 4 && row < 10 && row > 1) { + udata = udata << 1; + udata += dat; + } else if (col < 4 && row < 2) { + ReadVd = ReadVd << 1; + ReadVd += dat; + } + + + row_parity += dat; + col_parity[col] += dat; + timeCount = 0; + + while (digitalRead(ID_OUT) == dat) { + if (timeCount == TIMEOUT) { + timeOutFlag = 1; + break; + } else + timeCount++; + + } + if (timeOutFlag) + break; + } + + if (row < 10) { + if ((row_parity & 0x01) || timeOutFlag) //Row parity + { + timeOutFlag = 1; + break; + } + } + } + if (timeOutFlag || (col_parity[0] & 0x01) || (col_parity[1] & 0x01) || (col_parity[2] & 0x01) || + (col_parity[3] & 0x01)) //Column parity + { + timeOutFlag = 0; + return false; + } else { + ReadVd = ReadVd & 0xff; + //Serial.println(ReadVd); + //return (udata); + return true; + } + }//end receive data + return false; } - }//end receive data - return false; } - } }; diff --git a/Software/ATmega32U4/em4095.h b/Software/ATmega32U4/em4095.h index ce78a66..29718f5 100644 --- a/Software/ATmega32U4/em4095.h +++ b/Software/ATmega32U4/em4095.h @@ -8,28 +8,43 @@ #define TIMEOUT 1000 //standard timeout for manchester decode #define delay_125 250 //standard timeout for manchester decode -class EM4095{ +class EM4095 { public: - int vd; - int tempdata; - bool decodeTag(unsigned long &udata,int &ReadVd); - void Start(); - void bit0(); - void bit1(); - void transmit(int * data); - void transmit(unsigned long long data); - void simulation_bak(int vd, unsigned long id); - void simulation(int vd, unsigned long id); - int * parity_check(int * x); - - void Write_Bit1(); - void Write_Bit0(); - void Write_ID_Start(); - void Write_ID_Block(uint32_t *ID_Data, uint8_t Data_Nun, uint8_t ID_Addr); - unsigned long long parity_check_write(int vd, unsigned long id); - int * parity_check_write(int * x); - void Write_ID(uint8_t WriteVD, uint32_t WriteID); + int vd; + int tempdata; + + bool decodeTag(unsigned long &udata, int &ReadVd); + + void Start(); + + void bit0(); + + void bit1(); + + void transmit(int *data); + + void transmit(unsigned long long data); + + void simulation_bak(int vd, unsigned long id); + + void simulation(int vd, unsigned long id); + + int *parity_check(int *x); + + void Write_Bit1(); + + void Write_Bit0(); + + void Write_ID_Start(); + + void Write_ID_Block(uint32_t *ID_Data, uint8_t Data_Nun, uint8_t ID_Addr); + + unsigned long long parity_check_write(int vd, unsigned long id); + + int *parity_check_write(int *x); + + void Write_ID(uint8_t WriteVD, uint32_t WriteID); private: diff --git a/Software/ATmega32U4/hid.h b/Software/ATmega32U4/hid.h index 32c6123..0e6d874 100644 --- a/Software/ATmega32U4/hid.h +++ b/Software/ATmega32U4/hid.h @@ -4,31 +4,31 @@ #include "Keyboard.h" void hid_attack() { - //if (Cube_PRINT_data[1] == 0x61) { - if (!Cube_PRINT_data.indexOf("[HID]lock")) { - Cube_PRINT.println("lock"); - Keyboard.press(KEY_LEFT_GUI); - Keyboard.press('l'); - delay(1000); - Keyboard.releaseAll(); - Keyboard.write(KEY_RETURN); - } else if (!Cube_PRINT_data.indexOf("[HID]cmatrix")) { - Keyboard.press(KEY_RIGHT_CTRL); - Keyboard.press(KEY_LEFT_ALT); - Keyboard.press('t'); - delay(200); - Keyboard.releaseAll(); - delay(1500); - Keyboard.press(KEY_F11); - delay(300); - Keyboard.releaseAll(); - delay(300); - Keyboard.print("cmatrix"); - delay(100); - Keyboard.write(KEY_RETURN); - } else { - Cube_PRINT_data[0] = ""; - Keyboard.print(Cube_PRINT_data.substring(5, Cube_PRINT_data.length())); - } - Cube_PRINT.println("hid"); + //if (Cube_PRINT_data[1] == 0x61) { + if (!Cube_PRINT_data.indexOf("[HID]lock")) { + Cube_PRINT.println("lock"); + Keyboard.press(KEY_LEFT_GUI); + Keyboard.press('l'); + delay(1000); + Keyboard.releaseAll(); + Keyboard.write(KEY_RETURN); + } else if (!Cube_PRINT_data.indexOf("[HID]cmatrix")) { + Keyboard.press(KEY_RIGHT_CTRL); + Keyboard.press(KEY_LEFT_ALT); + Keyboard.press('t'); + delay(200); + Keyboard.releaseAll(); + delay(1500); + Keyboard.press(KEY_F11); + delay(300); + Keyboard.releaseAll(); + delay(300); + Keyboard.print("cmatrix"); + delay(100); + Keyboard.write(KEY_RETURN); + } else { + Cube_PRINT_data[0] = ""; + Keyboard.print(Cube_PRINT_data.substring(5, Cube_PRINT_data.length())); + } + Cube_PRINT.println("hid"); } diff --git a/Software/ATmega32U4/nfc.h b/Software/ATmega32U4/nfc.h index e6cd43d..9f7171a 100644 --- a/Software/ATmega32U4/nfc.h +++ b/Software/ATmega32U4/nfc.h @@ -2,6 +2,7 @@ * */ #include "em4095.h" + EM4095 EM4095; int NFC_VD; @@ -17,25 +18,25 @@ unsigned long NFC_END; * 通过轮询EM4095的OUT输出引脚解码卡号数据 */ -void SnifferEM4100(){ -int EM4100_VD; -unsigned long EM4100_DATA; - - if (EM4095.decodeTag(EM4100_DATA, EM4100_VD)) { - if (millis() - SerialLastTime < Print_Time) { - //mySwitch.resetAvailable(); - return; - } else if (EM4100_DATA < 1) { - return; +void SnifferEM4100() { + int EM4100_VD; + unsigned long EM4100_DATA; + + if (EM4095.decodeTag(EM4100_DATA, EM4100_VD)) { + if (millis() - SerialLastTime < Print_Time) { + //mySwitch.resetAvailable(); + return; + } else if (EM4100_DATA < 1) { + return; + } + Cube_PRINT.print("[NFC][read]vd:"); + Cube_PRINT.print(EM4100_VD); + Cube_PRINT.print(",data:"); + Cube_PRINT.println(EM4100_DATA); + EM4100_DATA = 0; + EM4100_VD = 0; + SerialLastTime = millis(); } - Cube_PRINT.print("[NFC][read]vd:"); - Cube_PRINT.print(EM4100_VD); - Cube_PRINT.print(",data:"); - Cube_PRINT.println(EM4100_DATA); - EM4100_DATA = 0; - EM4100_VD = 0; - SerialLastTime = millis(); - } } /* @@ -43,70 +44,71 @@ unsigned long EM4100_DATA; */ void simulation() { - unsigned long int udata = 6834998; - EM4095.simulation(0x0c, udata); + unsigned long int udata = 6834998; + EM4095.simulation(0x0c, udata); } /* * 控制EM4095 SHD 和 MOD 引脚,使其进入休眠状态进行低功耗 */ void NFC_Switch(String action) { - //pinMode(11,OUTPUT); - if (action == "off") { - - digitalWrite(MOD, HIGH); - digitalWrite(SHD, HIGH); - //digitalWrite(11,HIGH); - } else if (action == "on") { - digitalWrite(MOD, LOW); - digitalWrite(SHD, LOW); - //digitalWrite(12,LOW); - } else { - } + //pinMode(11,OUTPUT); + if (action == "off") { + + digitalWrite(MOD, HIGH); + digitalWrite(SHD, HIGH); + //digitalWrite(11,HIGH); + } else if (action == "on") { + digitalWrite(MOD, LOW); + digitalWrite(SHD, LOW); + //digitalWrite(12,LOW); + } else { + } } + bool NFC_Action() { - return !digitalRead(MOD); + return !digitalRead(MOD); } /* * 爆破卡号程序 */ -void NFC_attack(int vd, unsigned long start, unsigned long end ) { - //NFC_ID=start; - // 35 Ms / count;15==500MS - for (int i = 0; i < 15; i++) { - EM4095.simulation(NFC_VD, NFC_ID); - } - int NFC_porg = map(NFC_ID, start, end, 0, 100); - if (NFC_porg > 100) - NFC_porg = 100; - Cube_PRINT.print("[NFC][progress]"); - Cube_PRINT.println(NFC_porg); - //Serial.println(NFC_ID); - if (NFC_ID == end ) - NFC_action = 0; - - NFC_ID++; +void NFC_attack(int vd, unsigned long start, unsigned long end) { + //NFC_ID=start; + // 35 Ms / count;15==500MS + for (int i = 0; i < 15; i++) { + EM4095.simulation(NFC_VD, NFC_ID); + } + int NFC_porg = map(NFC_ID, start, end, 0, 100); + if (NFC_porg > 100) + NFC_porg = 100; + Cube_PRINT.print("[NFC][progress]"); + Cube_PRINT.println(NFC_porg); + //Serial.println(NFC_ID); + if (NFC_ID == end) + NFC_action = 0; + + NFC_ID++; } /* * 根据指令去模拟/爆破EM4100系列卡片 */ -void AttackEM4100(){ +void AttackEM4100() { while (NFC_action) { - switch (NFC_action) { - case 1: - EM4095.simulation(NFC_VD, NFC_ID); - break; - case 2: - NFC_attack(NFC_VD, NFC_START, NFC_END); - break; - } - if (Cube_PRINT.available() > 0) { - NFC_action = 0; - Cube_PRINT.println("exit"); + switch (NFC_action) { + case 1: + EM4095.simulation(NFC_VD, NFC_ID); + break; + case 2: + NFC_attack(NFC_VD, NFC_START, NFC_END); + break; + } + if (Cube_PRINT.available() > 0) { + NFC_action = 0; + Cube_PRINT.println("exit"); + } } - } } //String nfcdata="1111111110000011000000000000001100100010100110111001100110010000"; @@ -117,14 +119,15 @@ void AttackEM4100(){ void nfcbit1() { - digitalWrite(MOD, LOW); - delayMicroseconds(250); - digitalWrite(MOD, HIGH); - delayMicroseconds(250); + digitalWrite(MOD, LOW); + delayMicroseconds(250); + digitalWrite(MOD, HIGH); + delayMicroseconds(250); } + void nfcbit0() { - digitalWrite(MOD, HIGH); - delayMicroseconds(250); - digitalWrite(MOD, LOW); - delayMicroseconds(250); + digitalWrite(MOD, HIGH); + delayMicroseconds(250); + digitalWrite(MOD, LOW); + delayMicroseconds(250); } diff --git a/Software/ATmega32U4/printf.h b/Software/ATmega32U4/printf.h index d54e661..ecf892d 100644 --- a/Software/ATmega32U4/printf.h +++ b/Software/ATmega32U4/printf.h @@ -5,7 +5,7 @@ modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. */ - /* Galileo support from spaniakos */ +/* Galileo support from spaniakos */ /** * @file printf.h diff --git a/Software/ATmega32U4/rf.h b/Software/ATmega32U4/rf.h index ca794c6..f6b915a 100644 --- a/Software/ATmega32U4/rf.h +++ b/Software/ATmega32U4/rf.h @@ -188,7 +188,7 @@ void Fixed_Config_433_RX() { /* - LigthBar + LightBar Freq 315 */ int Ligth_Transmitpin = RF315_GDO0; @@ -234,7 +234,7 @@ void ligth_bar_bit_1() { } -void LigthBar_Transmit(unsigned long data) { +void LightBar_Transmit(unsigned long data) { //Serial.println(data,BIN); delay(2); @@ -250,16 +250,16 @@ void LigthBar_Transmit(unsigned long data) { } } } -//[RF][Transmit]LigthBar,freq:315,data:2600 -void RF_LigthBar() { +//[RF][Transmit]LightBar,freq:315,data:2600 +void RF_LightBar() { unsigned int freq = strtoul(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("freq") + 5, Cube_PRINT_data.indexOf(",data")).c_str(), NULL, 10); unsigned long data = strtoul(Cube_PRINT_data.substring(Cube_PRINT_data.indexOf("data:") + 5, Cube_PRINT_data.length()).c_str(), NULL, 16); if (freq == 315) { Ligth_Config_315(); } - LigthBar_Transmit(data); - Cube_PRINT.print("*Transmit LigthBar "); + LightBar_Transmit(data); + Cube_PRINT.print("*Transmit LightBar "); Cube_PRINT.print("Freq:"); Cube_PRINT.print(freq); Cube_PRINT.print(",Data:"); diff --git a/Software/ATmega32U4/rf_rollcode.h b/Software/ATmega32U4/rf_rollcode.h index 20e56c2..f310a82 100644 --- a/Software/ATmega32U4/rf_rollcode.h +++ b/Software/ATmega32U4/rf_rollcode.h @@ -8,25 +8,25 @@ //CC1101 cc1101; -void RF433_Setup_rollcode() { - cc1101.SS_PIN = RF433_CS; - cc1101.init(); - //byte syncWord[2] = {0x00, 0x00}; - //cc1101.setSyncWord(syncWord); - //freq_cc1101=433920000; - setfreqx(freq_cc1101); - //cc1101.setCarrierFreq(CFREQ_433); - - //cc1101.disableAddressCheck(); - cc1101.cmdStrobe(CC1101_SRX); - cc1101.writeReg(CC1101_IOCFG2, 0x0d); - //cc1101.writeReg(CC1101_AGCCTRL2, 0xB0); - //cc1101.writeReg(CC1101_MDMCFG4, 0xc8); - //cc1101.writeReg(CC1101_MDMCFG4, 0xc8); - //cc1101.writeReg(CC1101_MDMCFG3, 0x93); - - cc1101.writeReg(CC1101_MDMCFG4, 0x07);//RFB 200K - cc1101.writeReg(CC1101_MDMCFG3, 0x93); +void rf433_Setup_RollingCode() { + cc1101.SS_PIN = RF433_CS; + cc1101.init(); + //byte syncWord[2] = {0x00, 0x00}; + //cc1101.setSyncWord(syncWord); + //freq_cc1101=433920000; + setfreqx(freq_cc1101); + //cc1101.setCarrierFreq(CFREQ_433); + + //cc1101.disableAddressCheck(); + cc1101.cmdStrobe(CC1101_SRX); + cc1101.writeReg(CC1101_IOCFG2, 0x0d); + //cc1101.writeReg(CC1101_AGCCTRL2, 0xB0); + //cc1101.writeReg(CC1101_MDMCFG4, 0xc8); + //cc1101.writeReg(CC1101_MDMCFG4, 0xc8); + //cc1101.writeReg(CC1101_MDMCFG3, 0x93); + + cc1101.writeReg(CC1101_MDMCFG4, 0x07);//RFB 200K + cc1101.writeReg(CC1101_MDMCFG3, 0x93); } /* @@ -42,23 +42,25 @@ typedef unsigned long u32; typedef unsigned long long u64; uint64_t key = 0x7d093b66b31c374a; #define KeeLoq_NLF 0x3A5C742E -#define bit(x,n) (((x)>>(n))&1) -#define g5(x,a,b,c,d,e) (bit(x,a)+bit(x,b)*2+bit(x,c)*4+bit(x,d)*8+bit(x,e)*16) -uint32_t KeeLoq_Encrypt (const uint32_t data, const uint64_t key) -{ - uint32_t x = data, r; - for (r = 0; r < 528; r++) { - x = (x >> 1) ^ ((bit(x, 0)^bit(x, 16) ^ (uint32_t)bit(key, r & 63)^bit(KeeLoq_NLF, g5(x, 1, 9, 20, 26, 31))) << 31); - } - return x; +#define bit(x, n) (((x)>>(n))&1) +#define g5(x, a, b, c, d, e) (bit(x,a)+bit(x,b)*2+bit(x,c)*4+bit(x,d)*8+bit(x,e)*16) + +uint32_t KeeLoq_Encrypt(const uint32_t data, const uint64_t key) { + uint32_t x = data, r; + for (r = 0; r < 528; r++) { + x = (x >> 1) ^ + ((bit(x, 0) ^ bit(x, 16) ^ (uint32_t)bit(key, r & 63) ^ bit(KeeLoq_NLF, g5(x, 1, 9, 20, 26, 31))) << 31); + } + return x; } -uint32_t KeeLoq_Decrypt (const uint32_t data, const uint64_t key) -{ - uint32_t x = data, r; - for (r = 0; r < 528; r++) { - x = (x << 1)^bit(x, 31)^bit(x, 15) ^ (uint32_t)bit(key, (15 - r) & 63)^bit(KeeLoq_NLF, g5(x, 0, 8, 19, 25, 30)); - } - return x; + +uint32_t KeeLoq_Decrypt(const uint32_t data, const uint64_t key) { + uint32_t x = data, r; + for (r = 0; r < 528; r++) { + x = (x << 1) ^ bit(x, 31) ^ bit(x, 15) ^ (uint32_t)bit(key, (15 - r) & 63) ^ + bit(KeeLoq_NLF, g5(x, 0, 8, 19, 25, 30)); + } + return x; } @@ -66,43 +68,44 @@ uint32_t KeeLoq_Decrypt (const uint32_t data, const uint64_t key) receive Keeloq data */ #include "HackRadio.h" + HackRadio Hackradio = HackRadio(); void SnifferRollcode() { - if (Hackradio.available()) { - - detachInterrupt(RF315_att); - // if(mySwitch.getsn()=="39182da"){ - // Cube_PRINT.println("* Receive"); - unsigned long rfdata = strtoul(Hackradio.getkey().c_str(), NULL, 16); - //uint32_t datadc = KeeLoq_Decrypt(rfdata, key); - Cube_PRINT.print("[RF][Sniffer]"); - Cube_PRINT.print("freq:"); - Cube_PRINT.print(String(freq_cc1101).substring(0, 3)); - Cube_PRINT.print(",protocol:keeloq,modulation:ask,"); - Cube_PRINT.print("data:"); - Cube_PRINT.print(Hackradio.getkey()); - Cube_PRINT.print(",SerialNumber:"); - Cube_PRINT.print(Hackradio.getsn()); - /* Cube_PRINT.print(" Func:"); - Cube_PRINT.println(""); - Cube_PRINT.print("Decrypt:"); - Cube_PRINT.print(datadc, HEX); - Cube_PRINT.print("-->Func:"); - unsigned int Func = datadc >> 28; - //Func=Func<<28; - Cube_PRINT.print(Func, HEX); - Cube_PRINT.print(" Distinguish Code:"); - uint32_t Distinguish = datadc << 6; - Distinguish = Distinguish >> 22; - Cube_PRINT.print(Distinguish, HEX); - Cube_PRINT.print(" Sync Counter Value:"); - uint32_t SyncCounterValue = datadc << 16; - SyncCounterValue = SyncCounterValue >> 16; - Cube_PRINT.print(SyncCounterValue, HEX); - //u8g.drawRFrame(10,12, 30,20, 5);*/ - Cube_PRINT.println(""); - Hackradio.resetAvailable(); - Hackradio.enableReceive(RF315_att); - } + if (Hackradio.available()) { + + detachInterrupt(RF315_att); + // if(mySwitch.getsn()=="39182da"){ + // Cube_PRINT.println("* Receive"); + unsigned long rfdata = strtoul(Hackradio.getkey().c_str(), NULL, 16); + //uint32_t datadc = KeeLoq_Decrypt(rfdata, key); + Cube_PRINT.print("[RF][Sniffer]"); + Cube_PRINT.print("freq:"); + Cube_PRINT.print(String(freq_cc1101).substring(0, 3)); + Cube_PRINT.print(",protocol:keeloq,modulation:ask,"); + Cube_PRINT.print("data:"); + Cube_PRINT.print(Hackradio.getkey()); + Cube_PRINT.print(",SerialNumber:"); + Cube_PRINT.print(Hackradio.getsn()); + /* Cube_PRINT.print(" Func:"); + Cube_PRINT.println(""); + Cube_PRINT.print("Decrypt:"); + Cube_PRINT.print(datadc, HEX); + Cube_PRINT.print("-->Func:"); + unsigned int Func = datadc >> 28; + //Func=Func<<28; + Cube_PRINT.print(Func, HEX); + Cube_PRINT.print(" Distinguish Code:"); + uint32_t Distinguish = datadc << 6; + Distinguish = Distinguish >> 22; + Cube_PRINT.print(Distinguish, HEX); + Cube_PRINT.print(" Sync Counter Value:"); + uint32_t SyncCounterValue = datadc << 16; + SyncCounterValue = SyncCounterValue >> 16; + Cube_PRINT.print(SyncCounterValue, HEX); + //u8g.drawRFrame(10,12, 30,20, 5);*/ + Cube_PRINT.println(""); + Hackradio.resetAvailable(); + Hackradio.enableReceive(RF315_att); + } } diff --git a/Software/ESP8266/APScan.cpp b/Software/ESP8266/APScan.cpp index 5bef85f..128af21 100644 --- a/Software/ESP8266/APScan.cpp +++ b/Software/ESP8266/APScan.cpp @@ -6,152 +6,159 @@ APScan::APScan() { } bool APScan::start() { - if (debug) { - Serial.println("starting AP scan..."); - Serial.println("MAC - Ch - RSSI - Encrypt. - SSID - Hidden");// - Vendor"); - } - aps._clear(); - results = 0; - for (int i = 0; i < maxAPScanResults; i++){ - selected[i] = false; - String("").toCharArray(names[i], 33); - } - results = WiFi.scanNetworks(false, true); // lets scanNetworks return hidden APs. (async = false & show_hidden = true) - if(results > maxAPScanResults) results = maxAPScanResults; - - if (debug) Serial.println("Scan results: "+(String)results); - - for (int i = 0; i < results && i < maxAPScanResults; i++) { - Mac _ap; - _ap.set(WiFi.BSSID(i)[0], WiFi.BSSID(i)[1], WiFi.BSSID(i)[2], WiFi.BSSID(i)[3], WiFi.BSSID(i)[4], WiFi.BSSID(i)[5]); - aps.add(_ap); - channels[i] = WiFi.channel(i); - rssi[i] = WiFi.RSSI(i); - encryption[i] = WiFi.encryptionType(i); - hidden[i] = WiFi.isHidden(i); - String _ssid = WiFi.SSID(i); - _ssid.toCharArray(names[i], 33); - //data_getVendor(WiFi.BSSID(i)[0],WiFi.BSSID(i)[1],WiFi.BSSID(i)[2]).toCharArray(vendors[i],9); if (debug) { - Serial.print((String)i); - Serial.print(" - "); - _ap._print(); - Serial.print(" - "); - Serial.print(channels[i]); - Serial.print(" - "); - Serial.print(rssi[i]); - Serial.print(" - "); - Serial.print(getEncryption(encryption[i])); - Serial.print(" - "); - Serial.print(names[i]); - Serial.print(" - "); - Serial.print(hidden[i]); - //Serial.print(" - "); - //Serial.print(vendors[i]); - Serial.println(); + Serial.println("starting AP scan..."); + Serial.println("MAC - Ch - RSSI - Encrypt. - SSID - Hidden");// - Vendor"); } - delay(50); - } - - //for debugging the APScan crash bug - /* - if(debug){ - for(int i=results;i