Code updates & harmonization (#1201)

This commit is contained in:
tekka
2018-10-21 16:55:24 +02:00
committed by GitHub
parent b6ab7aaf03
commit 8e8f44b402
101 changed files with 2115 additions and 558 deletions

View File

@@ -18,7 +18,14 @@
*
*/
#if defined(ARDUINO_ARCH_NRF5)
#if defined(ARDUINO_ARCH_SAMD)
/* workaround to prevent compiler error */
.thumb_func
doNothing:
nop
.size doNothing, .-doNothing
#elif defined(ARDUINO_ARCH_NRF5)
/* workaround to prevent compiler error */
.thumb_func
doNothing:

View File

@@ -1641,6 +1641,7 @@
* | @ref MY_SIGNING_SOFT_RANDOMSEED_PIN | Change default software RNG seed pin | "#define" in the top of your sketch | Not supported
* | @ref MY_RF24_ENABLE_ENCRYPTION | Enables encryption on RF24 radios | "#define" in the top of your sketch | @verbatim --my-rf24-encryption-enabled @endverbatim
* | @ref MY_RFM69_ENABLE_ENCRYPTION | Enables encryption on %RFM69 radios | "#define" in the top of your sketch | @verbatim --my-rfm69-encryption-enabled @endverbatim
* | @ref MY_RFM95_ENABLE_ENCRYPTION | Enables encryption on %RFM95 radios | "#define" in the top of your sketch | @verbatim --my-rfm95-encryption-enabled @endverbatim
* | @ref MY_NRF5_ESB_ENABLE_ENCRYPTION | Enables encryption on nRF5 radios | "#define" in the top of your sketch | Not supported
* | @ref MY_NODE_LOCK_FEATURE | Enables the node locking feature | "#define" in the top of your sketch | Not supported
* | @ref MY_NODE_UNLOCK_PIN | Change default unlock pin | "#define" in the top of your sketch | Not supported

View File

@@ -49,7 +49,7 @@
#endif
// HARDWARE
#include "hal/architecture/MyHw.h"
#include "hal/architecture/MyHwHAL.h"
#include "hal/crypto/MyCryptoHAL.h"
#if defined(ARDUINO_ARCH_ESP8266)
#include "hal/architecture/ESP8266/MyHwESP8266.cpp"
@@ -58,7 +58,7 @@
#include "hal/architecture/ESP32/MyHwESP32.cpp"
#include "hal/crypto/ESP32/MyCryptoESP32.cpp"
#elif defined(ARDUINO_ARCH_AVR)
#include "drivers/AVR/DigitalWriteFast/digitalWriteFast.h"
#include "hal/architecture/AVR/drivers/DigitalWriteFast/digitalWriteFast.h"
#include "hal/architecture/AVR/MyHwAVR.cpp"
#include "hal/crypto/AVR/MyCryptoAVR.cpp"
#elif defined(ARDUINO_ARCH_SAMD)
@@ -338,7 +338,7 @@ MY_DEFAULT_RX_LED_PIN in your sketch instead to enable LEDs
#if defined(ARDUINO_ARCH_ESP8266)
#error Soft SPI is not available on ESP8266
#endif
#include "drivers/AVR/DigitalIO/DigitalIO.h"
#include "hal/architecture/AVR/drivers/DigitalIO/DigitalIO.h"
#endif
// SOFTSERIAL
@@ -361,14 +361,14 @@ MY_DEFAULT_RX_LED_PIN in your sketch instead to enable LEDs
// Transport drivers
#if defined(MY_RADIO_RF24)
#include "drivers/RF24/RF24.cpp"
#include "hal/transport/RF24/driver/RF24.cpp"
#include "hal/transport/RF24/MyTransportRF24.cpp"
#elif defined(MY_RADIO_NRF5_ESB)
#if !defined(ARDUINO_ARCH_NRF5)
#error No support for nRF5 radio on this platform
#endif
#include "drivers/NRF5/Radio.cpp"
#include "drivers/NRF5/Radio_ESB.cpp"
#include "hal/transport/NRF5_ESB/driver/Radio.cpp"
#include "hal/transport/NRF5_ESB/driver/Radio_ESB.cpp"
#include "hal/transport/NRF5_ESB/MyTransportNRF5_ESB.cpp"
#elif defined(MY_RS485)
#if !defined(MY_RS485_HWSERIAL)
@@ -380,13 +380,13 @@ MY_DEFAULT_RX_LED_PIN in your sketch instead to enable LEDs
#include "hal/transport/RS485/MyTransportRS485.cpp"
#elif defined(MY_RADIO_RFM69)
#if defined(MY_RFM69_NEW_DRIVER)
#include "drivers/RFM69/new/RFM69_new.cpp"
#include "hal/transport/RFM69/driver/new/RFM69_new.cpp"
#else
#include "drivers/RFM69/old/RFM69_old.cpp"
#include "hal/transport/RFM69/driver/old/RFM69_old.cpp"
#endif
#include "hal/transport/RFM69/MyTransportRFM69.cpp"
#elif defined(MY_RADIO_RFM95)
#include "drivers/RFM95/RFM95.cpp"
#include "hal/transport/RFM95/driver/RFM95.cpp"
#include "hal/transport/RFM95/MyTransportRFM95.cpp"
#endif

View File

@@ -83,9 +83,9 @@
/** @brief Address RF AES encryption key. This is set with @ref SecurityPersonalizer.ino */
#define EEPROM_RF_ENCRYPTION_AES_KEY_ADDRESS (EEPROM_SIGNING_SOFT_SERIAL_ADDRESS + SIZE_SIGNING_SOFT_SERIAL)
/** @brief Address node lock counter. This is set with @ref SecurityPersonalizer.ino */
#define EEPROM_NODE_LOCK_COUNTER (EEPROM_RF_ENCRYPTION_AES_KEY_ADDRESS + SIZE_RF_ENCRYPTION_AES_KEY)
#define EEPROM_NODE_LOCK_COUNTER_ADDRESS (EEPROM_RF_ENCRYPTION_AES_KEY_ADDRESS + SIZE_RF_ENCRYPTION_AES_KEY)
/** @brief First free address for sketch static configuration */
#define EEPROM_LOCAL_CONFIG_ADDRESS (EEPROM_NODE_LOCK_COUNTER + SIZE_NODE_LOCK_COUNTER)
#define EEPROM_LOCAL_CONFIG_ADDRESS (EEPROM_NODE_LOCK_COUNTER_ADDRESS + SIZE_NODE_LOCK_COUNTER)
#endif // MyEepromAddresses_h

View File

@@ -479,9 +479,9 @@ typedef union {
struct {
#endif
uint8_t last; ///< 8 bit - Id of last node this message passed
uint8_t sender; ///< 8 bit - Id of sender node (origin)
uint8_t destination; ///< 8 bit - Id of destination node
uint8_t last; //!< 8 bit - Id of last node this message passed
uint8_t sender; //!< 8 bit - Id of sender node (origin)
uint8_t destination; //!< 8 bit - Id of destination node
/**
* 2 bit - Protocol version<br>
@@ -498,8 +498,8 @@ typedef union {
*/
uint8_t command_ack_payload;
uint8_t type; ///< 8 bit - Type varies depending on command
uint8_t sensor; ///< 8 bit - Id of sensor that this message concerns.
uint8_t type; //!< 8 bit - Type varies depending on command
uint8_t sensor; //!< 8 bit - Id of sensor that this message concerns.
/*
* Each message can transfer a payload. We add one extra byte for string
@@ -507,26 +507,26 @@ typedef union {
* This union is used to simplify the construction of the binary data types transferred.
*/
union {
uint8_t bValue; ///< unsigned byte value (8-bit)
uint16_t uiValue; ///< unsigned integer value (16-bit)
int16_t iValue; ///< signed integer value (16-bit)
uint32_t ulValue; ///< unsigned long value (32-bit)
int32_t lValue; ///< signed long value (32-bit)
struct { //< Float messages
uint8_t bValue; //!< unsigned byte value (8-bit)
uint16_t uiValue; //!< unsigned integer value (16-bit)
int16_t iValue; //!< signed integer value (16-bit)
uint32_t ulValue; //!< unsigned long value (32-bit)
int32_t lValue; //!< signed long value (32-bit)
struct { //!< Float messages
float fValue;
uint8_t fPrecision; ///< Number of decimals when serializing
uint8_t fPrecision; //!< Number of decimals when serializing
};
struct { //< Presentation messages
uint8_t version; ///< Library version
uint8_t sensorType; ///< Sensor type hint for controller, see table above
struct { //!< Presentation messages
uint8_t version; //!< Library version
uint8_t sensorType; //!< Sensor type hint for controller, see table above
};
char data[MAX_PAYLOAD + 1]; ///< Buffer for raw payload data
} __attribute__((packed)); ///< Doxygen will complain without this comment
char data[MAX_PAYLOAD + 1]; //!< Buffer for raw payload data
} __attribute__((packed)); //!< Doxygen will complain without this comment
#if defined(__cplusplus) || defined(DOXYGEN)
} __attribute__((packed));
#else
};
uint8_t array[HEADER_SIZE + MAX_PAYLOAD + 1]; ///< buffer for entire message
uint8_t array[HEADER_SIZE + MAX_PAYLOAD + 1]; //!< buffer for entire message
} __attribute__((packed)) MyMessage;
#endif

View File

@@ -706,7 +706,7 @@ void _nodeLock(const char* str)
{
#ifdef MY_NODE_LOCK_FEATURE
// Make sure EEPROM is updated to locked status
hwWriteConfig(EEPROM_NODE_LOCK_COUNTER, 0);
hwWriteConfig(EEPROM_NODE_LOCK_COUNTER_ADDRESS, 0);
while (1) {
setIndication(INDICATION_ERR_LOCKED);
CORE_DEBUG(PSTR("MCO:NLK:NODE LOCKED. TO UNLOCK, GND PIN %" PRIu8 " AND RESET\n"),
@@ -730,7 +730,7 @@ void _checkNodeLock(void)
{
#ifdef MY_NODE_LOCK_FEATURE
// Check if node has been locked down
if (hwReadConfig(EEPROM_NODE_LOCK_COUNTER) == 0) {
if (hwReadConfig(EEPROM_NODE_LOCK_COUNTER_ADDRESS) == 0) {
// Node is locked, check if unlock pin is asserted, else hang the node
hwPinMode(MY_NODE_UNLOCK_PIN, INPUT_PULLUP);
// Make a short delay so we are sure any large external nets are fully pulled
@@ -738,7 +738,7 @@ void _checkNodeLock(void)
while (hwMillis() - enter < 2) {}
if (hwDigitalRead(MY_NODE_UNLOCK_PIN) == 0) {
// Pin is grounded, reset lock counter
hwWriteConfig(EEPROM_NODE_LOCK_COUNTER, MY_NODE_LOCK_COUNTER_MAX);
hwWriteConfig(EEPROM_NODE_LOCK_COUNTER_ADDRESS, MY_NODE_LOCK_COUNTER_MAX);
// Disable pullup
hwPinMode(MY_NODE_UNLOCK_PIN, INPUT);
setIndication(INDICATION_ERR_LOCKED);
@@ -748,9 +748,9 @@ void _checkNodeLock(void)
hwPinMode(MY_NODE_UNLOCK_PIN, INPUT);
_nodeLock("LDB"); //Locked during boot
}
} else if (hwReadConfig(EEPROM_NODE_LOCK_COUNTER) == 0xFF) {
} else if (hwReadConfig(EEPROM_NODE_LOCK_COUNTER_ADDRESS) == 0xFF) {
// Reset value
hwWriteConfig(EEPROM_NODE_LOCK_COUNTER, MY_NODE_LOCK_COUNTER_MAX);
hwWriteConfig(EEPROM_NODE_LOCK_COUNTER_ADDRESS, MY_NODE_LOCK_COUNTER_MAX);
}
#endif
}

View File

@@ -90,7 +90,7 @@ void stInitTransition(void)
#endif
// Read node settings (ID, parent ID, GW distance) from EEPROM
hwReadConfigBlock((void*)&_transportConfig, (void*)EEPROM_NODE_ID_ADDRESS,
hwReadConfigBlock((void *)&_transportConfig, (void *)EEPROM_NODE_ID_ADDRESS,
sizeof(transportConfig_t));
}
@@ -360,7 +360,7 @@ void stFailureUpdate(void)
}
}
void transportSwitchSM(transportState_t& newState)
void transportSwitchSM(transportState_t &newState)
{
if (_transportSM.currentState != &newState) {
_transportSM.stateRetries = 0u; // state change, reset retry counter
@@ -411,7 +411,6 @@ void resetMessageReceived(void)
_transportSM.msgReceived = false;
}
void transportInitialise(void)
{
_transportSM.failureCounter = 0u; // reset failure counter
@@ -431,6 +430,7 @@ void transportDisable(void)
transportSleep();
}
}
void transportReInitialise(void)
{
if (RADIO_CAN_POWER_OFF == true) {
@@ -443,7 +443,6 @@ void transportReInitialise(void)
}
}
bool transportWaitUntilReady(const uint32_t waitingMS)
{
// check if transport ready
@@ -467,7 +466,6 @@ void transportProcess(void)
transportProcessFIFO();
}
bool transportCheckUplink(const bool force)
{
if (!force && (hwMillis() - _transportSM.lastUplinkCheck) < MY_TRANSPORT_CHKUPL_INTERVAL_MS) {
@@ -717,7 +715,7 @@ void transportProcessMessage(void)
// Is message addressed to this node?
if (destination == _transportConfig.nodeId) {
// prevent buffer overflow by limiting max. possible message length (5 bits=31 bytes max) to MAX_PAYLOAD (25 bytes)
mSetLength(_msg, min(mGetLength(_msg),(uint8_t)MAX_PAYLOAD));
mSetLength(_msg, min(mGetLength(_msg), (uint8_t)MAX_PAYLOAD));
// null terminate data
_msg.data[msgLength] = 0u;
// Check if sender requests an ack back.

View File

@@ -253,7 +253,7 @@ typedef int16_t transportRSSI_t; //!< Datatype for internal RSSI storage
*/
typedef struct {
// SM variables
transportState_t* currentState; //!< pointer to current FSM state
transportState_t *currentState; //!< pointer to current FSM state
uint32_t stateEnter; //!< state enter timepoint
// general transport variables
uint32_t lastUplinkCheck; //!< last uplink check, required to prevent GW flooding
@@ -334,7 +334,7 @@ void stFailureUpdate(void);
* @brief Switch SM state
* @param newState New state to switch SM to
*/
void transportSwitchSM(transportState_t& newState);
void transportSwitchSM(transportState_t &newState);
/**
* @brief Update SM state
*/

View File

@@ -49,8 +49,8 @@
#define MYSENSORS_LIBRARY_VERSION_MAJOR 2 //!< Major release version
#define MYSENSORS_LIBRARY_VERSION_MINOR 3 //!< Minor release version
#define MYSENSORS_LIBRARY_VERSION_PATCH 1 //!< Patch version
#define MYSENSORS_LIBRARY_VERSION_PRERELEASE "beta" //!< Pre-release suffix, i.e. alpha, beta, rc.1, etc
#define MYSENSORS_LIBRARY_VERSION_PRERELEASE_NUMBER 0x01 //!< incremental counter, starting at 0x00. 0xFF for final release
#define MYSENSORS_LIBRARY_VERSION_PRERELEASE "beta" //!< Pre-release suffix, i.e. alpha, beta, rc.1, etc
#define MYSENSORS_LIBRARY_VERSION_PRERELEASE_NUMBER 0x02 //!< incremental counter, starting at 0x00. 0xFF for final release
#if (MYSENSORS_LIBRARY_VERSION_PRERELEASE_NUMBER != 0xFF)

View File

@@ -21,6 +21,9 @@
* THE SOFTWARE.
*/
// Revisions are now tracked on GitHub
// https://github.com/PaulStoffregen/AltSoftSerial
//
// Version 1.2: Support Teensy 3.x
//
// Version 1.1: Improve performance in receiver code
@@ -55,23 +58,45 @@ static uint8_t tx_bit;
static volatile uint8_t tx_buffer_head;
static volatile uint8_t tx_buffer_tail;
#define TX_BUFFER_SIZE 68
static volatile uint8_t tx_buffer[RX_BUFFER_SIZE];
static volatile uint8_t tx_buffer[TX_BUFFER_SIZE];
#ifndef INPUT_PULLUP
#define INPUT_PULLUP INPUT
#endif
#define MAX_COUNTS_PER_BIT 6241 // 65536 / 10.5
void AltSoftSerial::init(uint32_t cycles_per_bit)
{
if (cycles_per_bit < 7085) {
//Serial.printf("cycles_per_bit = %d\n", cycles_per_bit);
if (cycles_per_bit < MAX_COUNTS_PER_BIT) {
CONFIG_TIMER_NOPRESCALE();
} else {
cycles_per_bit /= 8;
if (cycles_per_bit < 7085) {
//Serial.printf("cycles_per_bit/8 = %d\n", cycles_per_bit);
if (cycles_per_bit < MAX_COUNTS_PER_BIT) {
CONFIG_TIMER_PRESCALE_8();
} else {
return; // minimum 283 baud at 16 MHz clock
#if defined(CONFIG_TIMER_PRESCALE_256)
cycles_per_bit /= 32;
//Serial.printf("cycles_per_bit/256 = %d\n", cycles_per_bit);
if (cycles_per_bit < MAX_COUNTS_PER_BIT) {
CONFIG_TIMER_PRESCALE_256();
} else {
return; // baud rate too low for AltSoftSerial
}
#elif defined(CONFIG_TIMER_PRESCALE_128)
cycles_per_bit /= 16;
//Serial.printf("cycles_per_bit/128 = %d\n", cycles_per_bit);
if (cycles_per_bit < MAX_COUNTS_PER_BIT) {
CONFIG_TIMER_PRESCALE_128();
} else {
return; // baud rate too low for AltSoftSerial
}
#else
return; // baud rate too low for AltSoftSerial
#endif
}
}
ticks_per_bit = cycles_per_bit;
@@ -111,7 +136,7 @@ void AltSoftSerial::writeByte(uint8_t b)
if (head >= TX_BUFFER_SIZE) {
head = 0;
}
while (tx_buffer_tail == head) {} // wait until space in buffer
while (tx_buffer_tail == head) ; // wait until space in buffer
intr_state = SREG;
cli();
if (tx_state) {
@@ -131,16 +156,19 @@ void AltSoftSerial::writeByte(uint8_t b)
ISR(COMPARE_A_INTERRUPT)
{
uint8_t state, byte, head, tail;
uint8_t state, byte, bit, head, tail;
uint16_t target;
state = tx_state;
byte = tx_byte;
target = GET_COMPARE_A();
while (state < 9) {
uint8_t bit;
while (state < 10) {
target += ticks_per_bit;
bit = byte & 1;
if (state < 9) {
bit = byte & 1;
} else {
bit = 1; // stopbit
}
byte >>= 1;
state++;
if (bit != tx_bit) {
@@ -157,20 +185,19 @@ ISR(COMPARE_A_INTERRUPT)
return;
}
}
if (state == 9) {
tx_state = 10;
CONFIG_MATCH_SET();
SET_COMPARE_A(target + ticks_per_bit);
return;
}
head = tx_buffer_head;
tail = tx_buffer_tail;
if (head == tail) {
tx_state = 0;
CONFIG_MATCH_NORMAL();
DISABLE_INT_COMPARE_A();
if (state == 10) {
// Wait for final stop bit to finish
tx_state = 11;
SET_COMPARE_A(target + ticks_per_bit);
} else {
tx_state = 0;
CONFIG_MATCH_NORMAL();
DISABLE_INT_COMPARE_A();
}
} else {
tx_state = 1;
if (++tail >= TX_BUFFER_SIZE) {
tail = 0;
}
@@ -178,14 +205,19 @@ ISR(COMPARE_A_INTERRUPT)
tx_byte = tx_buffer[tail];
tx_bit = 0;
CONFIG_MATCH_CLEAR();
SET_COMPARE_A(target + ticks_per_bit);
if (state == 10) {
SET_COMPARE_A(target + ticks_per_bit);
} else {
SET_COMPARE_A(GET_TIMER_COUNT() + 16);
}
tx_state = 1;
// TODO: how to detect timing_error?
}
}
void AltSoftSerial::flushOutput(void)
{
while (tx_state) {}/* wait */
while (tx_state) /* wait */ ;
}
@@ -193,7 +225,6 @@ void AltSoftSerial::flushOutput(void)
/** Reception **/
/****************************************/
ISR(CAPTURE_INTERRUPT)
{
uint8_t state, bit;
@@ -211,27 +242,26 @@ ISR(CAPTURE_INTERRUPT)
state = rx_state;
if (state == 0) {
if (!bit) {
SET_COMPARE_B(capture + rx_stop_ticks);
uint16_t end = capture + rx_stop_ticks;
SET_COMPARE_B(end);
ENABLE_INT_COMPARE_B();
rx_target = capture + ticks_per_bit + ticks_per_bit/2;
rx_state = 1;
}
} else {
uint16_t target;
target = rx_target;
uint16_t target = rx_target;
const uint16_t offset_overflow = 65535 - ticks_per_bit;
while (1) {
int16_t offset;
offset = capture - target;
if (offset < 0) {
const uint16_t offset = capture - target;
if (offset > offset_overflow) {
break;
}
rx_byte = (rx_byte >> 1) | rx_bit;
target += ticks_per_bit;
state++;
if (state >= 9) {
uint8_t head;
DISABLE_INT_COMPARE_B();
head = rx_buffer_head + 1;
uint8_t head = rx_buffer_head + 1;
if (head >= RX_BUFFER_SIZE) {
head = 0;
}
@@ -304,6 +334,9 @@ int AltSoftSerial::peek(void)
if (head == tail) {
return -1;
}
if (++tail >= RX_BUFFER_SIZE) {
tail = 0;
}
return rx_buffer[tail];
}
@@ -330,14 +363,15 @@ void ftm0_isr(void)
{
uint32_t flags = FTM0_STATUS;
FTM0_STATUS = 0;
if (flags & (1<<0) && (FTM0_C0SC & 0x40)) {
altss_compare_b_interrupt();
}
if (flags & (1<<5)) {
altss_capture_interrupt();
}
if (flags & (1<<6)) {
if (flags & (1<<6) && (FTM0_C6SC & 0x40)) {
altss_compare_a_interrupt();
}
if (flags & (1<<0)) {
altss_compare_b_interrupt();
}
}
#endif

View File

@@ -46,11 +46,11 @@ public:
AltSoftSerial() { } //!< Constructor
~AltSoftSerial()
{
end(); //!< Destructor
end(); //!< Destructor
}
static void begin(uint32_t baud)
{
init((ALTSS_BASE_FREQ + baud / 2) / baud); //!< begin
init((ALTSS_BASE_FREQ + baud / 2) / baud); //!< begin
}
static void end(); //!< end
int peek(); //!< peek
@@ -59,47 +59,55 @@ public:
#if ARDUINO >= 100
size_t write(uint8_t byte)
{
writeByte(byte); //!< write
writeByte(byte); //!< write
return 1;
}
void flush()
{
flushOutput(); //!< flush
flushOutput(); //!< flush
}
#else
void write(uint8_t byte)
{
writeByte(byte); //!< write
writeByte(byte); //!< write
}
void flush()
{
flushInput(); //!< flush
flushInput(); //!< flush
}
#endif
using Print::write;
static void flushInput(); //!< flushInput
static void flushOutput(); //!< flushOutput
// for drop-in compatibility with NewSoftSerial, rxPin & txPin ignored
//AltSoftSerial(uint8_t rxPin, uint8_t txPin, bool inverse = false) { }
AltSoftSerial(uint8_t rxPin, uint8_t txPin, bool inverse = false)
{
(void)rxPin; //!< AltSoftSerial
(void)txPin;
(void)inverse;
}
bool listen()
{
return false; //!< listen
return false; //!< listen
}
bool isListening()
{
return true; //!< isListening
return true; //!< isListening
}
bool overflow()
{
bool r = timing_error; //!< overflow
bool r = timing_error; //!< overflow
timing_error = false;
return r;
}
static int library_version()
{
return 1; //!< library_version
return 1; //!< library_version
}
static void enable_timer0(bool enable)
{
(void)enable; //!< enable_timer0
}
static void enable_timer0(bool) { } //!< enable_timer0
static bool timing_error; //!< timing_error
private:
static void init(uint32_t cycles_per_bit);

View File

@@ -1,4 +1,4 @@
#AltSoftSerial Library#
# AltSoftSerial Library
Improved software emulated serial, using hardware timers for precise signal
timing and availability of CPU time for other libraries to respond to interrupts

View File

@@ -55,9 +55,9 @@
//#define OUTPUT_COMPARE_C_PIN 14 // unusable PWM
// Teensy 3.0 & 3.1
// Teensy 3.x
//
#elif defined(__MK20DX128__) || defined(__MK20DX256__)
#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__)
#define ALTSS_USE_FTM0
#define INPUT_CAPTURE_PIN 20 // receive (FTM0_CH5)
#define OUTPUT_COMPARE_A_PIN 21 // transmit (FTM0_CH6)
@@ -123,16 +123,25 @@
// Sanguino
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)
// EnviroDIY Mayfly, Sodaq Mbili
#elif defined ARDUINO_AVR_ENVIRODIY_MAYFLY || defined ARDUINO_AVR_SODAQ_MBILI
#define ALTSS_USE_TIMER1
#define INPUT_CAPTURE_PIN 6 // receive
#define OUTPUT_COMPARE_A_PIN 5 // transmit
#define OUTPUT_COMPARE_B_PIN 4 // unusable PWM
// Sanguino, Mighty 1284
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega1284__)
#define ALTSS_USE_TIMER1
#define INPUT_CAPTURE_PIN 14 // receive
#define OUTPUT_COMPARE_A_PIN 13 // transmit
#define OUTPUT_COMPARE_B_PIN 12 // unusable PWM
// Unknown board
#else
#error "Please define your board timer and pins"
#endif

View File

@@ -24,6 +24,7 @@
#if defined(ALTSS_USE_TIMER1)
#define CONFIG_TIMER_NOPRESCALE() (TIMSK1 = 0, TCCR1A = 0, TCCR1B = (1<<ICNC1) | (1<<CS10))
#define CONFIG_TIMER_PRESCALE_8() (TIMSK1 = 0, TCCR1A = 0, TCCR1B = (1<<ICNC1) | (1<<CS11))
#define CONFIG_TIMER_PRESCALE_256() (TIMSK1 = 0, TCCR1A = 0, TCCR1B = (1<<ICNC1) | (1<<CS12))
#define CONFIG_MATCH_NORMAL() (TCCR1A = TCCR1A & ~((1<<COM1A1) | (1<<COM1A0)))
#define CONFIG_MATCH_TOGGLE() (TCCR1A = (TCCR1A & ~(1<<COM1A1)) | (1<<COM1A0))
#define CONFIG_MATCH_CLEAR() (TCCR1A = (TCCR1A | (1<<COM1A1)) & ~(1<<COM1A0))
@@ -50,6 +51,7 @@
#elif defined(ALTSS_USE_TIMER3)
#define CONFIG_TIMER_NOPRESCALE() (TIMSK3 = 0, TCCR3A = 0, TCCR3B = (1<<ICNC3) | (1<<CS30))
#define CONFIG_TIMER_PRESCALE_8() (TIMSK3 = 0, TCCR3A = 0, TCCR3B = (1<<ICNC3) | (1<<CS31))
#define CONFIG_TIMER_PRESCALE_256() (TIMSK3 = 0, TCCR3A = 0, TCCR3B = (1<<ICNC3) | (1<<CS32))
#define CONFIG_MATCH_NORMAL() (TCCR3A = TCCR3A & ~((1<<COM3A1) | (1<<COM3A0)))
#define CONFIG_MATCH_TOGGLE() (TCCR3A = (TCCR3A & ~(1<<COM3A1)) | (1<<COM3A0))
#define CONFIG_MATCH_CLEAR() (TCCR3A = (TCCR3A | (1<<COM3A1)) & ~(1<<COM3A0))
@@ -76,6 +78,7 @@
#elif defined(ALTSS_USE_TIMER4)
#define CONFIG_TIMER_NOPRESCALE() (TIMSK4 = 0, TCCR4A = 0, TCCR4B = (1<<ICNC4) | (1<<CS40))
#define CONFIG_TIMER_PRESCALE_8() (TIMSK4 = 0, TCCR4A = 0, TCCR4B = (1<<ICNC4) | (1<<CS41))
#define CONFIG_TIMER_PRESCALE_256() (TIMSK4 = 0, TCCR4A = 0, TCCR4B = (1<<ICNC4) | (1<<CS42))
#define CONFIG_MATCH_NORMAL() (TCCR4A = TCCR4A & ~((1<<COM4A1) | (1<<COM4A0)))
#define CONFIG_MATCH_TOGGLE() (TCCR4A = (TCCR4A & ~(1<<COM4A1)) | (1<<COM4A0))
#define CONFIG_MATCH_CLEAR() (TCCR4A = (TCCR4A | (1<<COM4A1)) & ~(1<<COM4A0))
@@ -102,6 +105,7 @@
#elif defined(ALTSS_USE_TIMER5)
#define CONFIG_TIMER_NOPRESCALE() (TIMSK5 = 0, TCCR5A = 0, TCCR5B = (1<<ICNC5) | (1<<CS50))
#define CONFIG_TIMER_PRESCALE_8() (TIMSK5 = 0, TCCR5A = 0, TCCR5B = (1<<ICNC5) | (1<<CS51))
#define CONFIG_TIMER_PRESCALE_256() (TIMSK5 = 0, TCCR5A = 0, TCCR5B = (1<<ICNC5) | (1<<CS52))
#define CONFIG_MATCH_NORMAL() (TCCR5A = TCCR5A & ~((1<<COM5A1) | (1<<COM5A0)))
#define CONFIG_MATCH_TOGGLE() (TCCR5A = (TCCR5A & ~(1<<COM5A1)) | (1<<COM5A0))
#define CONFIG_MATCH_CLEAR() (TCCR5A = (TCCR5A | (1<<COM5A1)) & ~(1<<COM5A0))
@@ -133,11 +137,19 @@
FTM0_SC = FTM_SC_CLKS(1) | FTM_SC_PS(0); \
digitalWriteFast(21, HIGH); \
NVIC_SET_PRIORITY(IRQ_FTM0, 48); \
FTM0_C0SC = 0x18; \
NVIC_ENABLE_IRQ(IRQ_FTM0);
#define CONFIG_TIMER_PRESCALE_8() FTM0_SC = 0; FTM0_CNT = 0; FTM0_MOD = 0xFFFF; \
FTM0_SC = FTM_SC_CLKS(1) | FTM_SC_PS(3); \
digitalWriteFast(21, HIGH); \
NVIC_SET_PRIORITY(IRQ_FTM0, 48); \
FTM0_C0SC = 0x18; \
NVIC_ENABLE_IRQ(IRQ_FTM0);
#define CONFIG_TIMER_PRESCALE_128() FTM0_SC = 0; FTM0_CNT = 0; FTM0_MOD = 0xFFFF; \
FTM0_SC = FTM_SC_CLKS(1) | FTM_SC_PS(7); \
digitalWriteFast(21, HIGH); \
NVIC_SET_PRIORITY(IRQ_FTM0, 48); \
FTM0_C0SC = 0x18; \
NVIC_ENABLE_IRQ(IRQ_FTM0);
#define CONFIG_MATCH_NORMAL() (FTM0_C6SC = 0)
#define CONFIG_MATCH_TOGGLE() (FTM0_C6SC = (FTM0_C6SC & 0xC3) | 0x14)
@@ -149,7 +161,7 @@
CORE_PIN20_CONFIG = PORT_PCR_MUX(4)|PORT_PCR_PE|PORT_PCR_PS
#define ENABLE_INT_COMPARE_A() FTM0_C6SC |= 0x40; \
CORE_PIN21_CONFIG = PORT_PCR_MUX(4)|PORT_PCR_DSE|PORT_PCR_SRE
#define ENABLE_INT_COMPARE_B() (FTM0_C0SC |= 0x40)
#define ENABLE_INT_COMPARE_B() (FTM0_C0SC = 0x58)
#define DISABLE_INT_INPUT_CAPTURE() FTM0_C5SC &= ~0x40; \
CORE_PIN20_CONFIG = PORT_PCR_MUX(1)|PORT_PCR_PE|PORT_PCR_PS
#define DISABLE_INT_COMPARE_A() FTM0_C6SC &= ~0x40; \
@@ -161,7 +173,8 @@
#define GET_COMPARE_A() (FTM0_C6V)
#define GET_COMPARE_B() (FTM0_C0V)
#define SET_COMPARE_A(val) (FTM0_C6V = val)
#define SET_COMPARE_B(val) (FTM0_C0V = val)
#define SET_COMPARE_B(val) if (FTM0_C0SC & FTM_CSC_CHF) FTM0_C0SC = 0x18; \
do { FTM0_C0V = (val); } while (FTM0_C0V != (val));
#define CAPTURE_INTERRUPT altss_capture_interrupt
#define COMPARE_A_INTERRUPT altss_compare_a_interrupt
#define COMPARE_B_INTERRUPT altss_compare_b_interrupt

View File

@@ -1,103 +0,0 @@
// Teensy 2.0
//
#if defined(__AVR_ATmega32U4__) && defined(CORE_TEENSY)
//#define ALTSS_USE_TIMER1
//#define INPUT_CAPTURE_PIN 22 // receive
//#define OUTPUT_COMPARE_A_PIN 14 // transmit
//#define OUTPUT_COMPARE_B_PIN 15 // unusable PWM
//#define OUTPUT_COMPARE_C_PIN 4 // unusable PWM
#define ALTSS_USE_TIMER3
#define INPUT_CAPTURE_PIN 10 // receive
#define OUTPUT_COMPARE_A_PIN 9 // transmit
// Teensy++ 2.0
//
#elif defined(__AVR_AT90USB1286__) && defined(CORE_TEENSY)
#define ALTSS_USE_TIMER1
#define INPUT_CAPTURE_PIN 4 // receive
#define OUTPUT_COMPARE_A_PIN 25 // transmit
#define OUTPUT_COMPARE_B_PIN 26 // unusable PWM
#define OUTPUT_COMPARE_C_PIN 27 // unusable PWM
//#define ALTSS_USE_TIMER3
//#define INPUT_CAPTURE_PIN 17 // receive
//#define OUTPUT_COMPARE_A_PIN 16 // transmit
//#define OUTPUT_COMPARE_B_PIN 15 // unusable PWM
//#define OUTPUT_COMPARE_C_PIN 14 // unusable PWM
// Wiring-S
//
#elif defined(__AVR_ATmega644P__) && defined(WIRING)
#define ALTSS_USE_TIMER1
#define INPUT_CAPTURE_PIN 6 // receive
#define OUTPUT_COMPARE_A_PIN 5 // transmit
#define OUTPUT_COMPARE_B_PIN 4 // unusable PWM
// Arduino Uno, Duemilanove, LilyPad, etc
//
#elif defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
#define ALTSS_USE_TIMER1
#define INPUT_CAPTURE_PIN 8 // receive
#define OUTPUT_COMPARE_A_PIN 9 // transmit
#define OUTPUT_COMPARE_B_PIN 10 // unusable PWM
// Arduino Leonardo & Yun (from Cristian Maglie)
//
#elif defined(ARDUINO_AVR_YUN) || defined(ARDUINO_AVR_LEONARDO)
//#define ALTSS_USE_TIMER1
//#define INPUT_CAPTURE_PIN 4 // receive
//#define OUTPUT_COMPARE_A_PIN 9 // transmit
//#define OUTPUT_COMPARE_B_PIN 10 // unusable PWM
//#define OUTPUT_COMPARE_C_PIN 11 // unusable PWM
#define ALTSS_USE_TIMER3
#define INPUT_CAPTURE_PIN 13 // receive
#define OUTPUT_COMPARE_A_PIN 5 // transmit
// Arduino Mega
//
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
//#define ALTSS_USE_TIMER4
//#define INPUT_CAPTURE_PIN 49 // receive
//#define OUTPUT_COMPARE_A_PIN 6 // transmit
//#define OUTPUT_COMPARE_B_PIN 7 // unusable PWM
//#define OUTPUT_COMPARE_C_PIN 8 // unusable PWM
#define ALTSS_USE_TIMER5
#define INPUT_CAPTURE_PIN 48 // receive
#define OUTPUT_COMPARE_A_PIN 46 // transmit
#define OUTPUT_COMPARE_B_PIN 45 // unusable PWM
#define OUTPUT_COMPARE_C_PIN 44 // unusable PWM
// Sanguino
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)
#define ALTSS_USE_TIMER1
#define INPUT_CAPTURE_PIN 14 // receive
#define OUTPUT_COMPARE_A_PIN 13 // transmit
#define OUTPUT_COMPARE_B_PIN 12 // unusable PWM
// Unknown board
#else
#error "Please define your board timer and pins"
#endif

View File

@@ -1,106 +0,0 @@
#if defined(ALTSS_USE_TIMER1)
#define CONFIG_TIMER_NOPRESCALE() (TIMSK1 = 0, TCCR1A = 0, TCCR1B = (1<<ICNC1) | (1<<CS10))
#define CONFIG_TIMER_PRESCALE_8() (TIMSK1 = 0, TCCR1A = 0, TCCR1B = (1<<ICNC1) | (1<<CS11))
#define CONFIG_MATCH_NORMAL() (TCCR1A = TCCR1A & ~((1<<COM1A1) | (1<<COM1A0)))
#define CONFIG_MATCH_TOGGLE() (TCCR1A = (TCCR1A & ~(1<<COM1A1)) | (1<<COM1A0))
#define CONFIG_MATCH_CLEAR() (TCCR1A = (TCCR1A | (1<<COM1A1)) & ~(1<<COM1A0))
#define CONFIG_MATCH_SET() (TCCR1A = TCCR1A | ((1<<COM1A1) | (1<<COM1A0)))
#define CONFIG_CAPTURE_FALLING_EDGE() (TCCR1B &= ~(1<<ICES1))
#define CONFIG_CAPTURE_RISING_EDGE() (TCCR1B |= (1<<ICES1))
#define ENABLE_INT_INPUT_CAPTURE() (TIFR1 = (1<<ICF1), TIMSK1 = (1<<ICIE1))
#define ENABLE_INT_COMPARE_A() (TIFR1 = (1<<OCF1A), TIMSK1 |= (1<<OCIE1A))
#define ENABLE_INT_COMPARE_B() (TIFR1 = (1<<OCF1B), TIMSK1 |= (1<<OCIE1B))
#define DISABLE_INT_INPUT_CAPTURE() (TIMSK1 &= ~(1<<ICIE1))
#define DISABLE_INT_COMPARE_A() (TIMSK1 &= ~(1<<OCIE1A))
#define DISABLE_INT_COMPARE_B() (TIMSK1 &= ~(1<<OCIE1B))
#define GET_TIMER_COUNT() (TCNT1)
#define GET_INPUT_CAPTURE() (ICR1)
#define GET_COMPARE_A() (OCR1A)
#define GET_COMPARE_B() (OCR1B)
#define SET_COMPARE_A(val) (OCR1A = (val))
#define SET_COMPARE_B(val) (OCR1B = (val))
#define CAPTURE_INTERRUPT TIMER1_CAPT_vect
#define COMPARE_A_INTERRUPT TIMER1_COMPA_vect
#define COMPARE_B_INTERRUPT TIMER1_COMPB_vect
#elif defined(ALTSS_USE_TIMER3)
#define CONFIG_TIMER_NOPRESCALE() (TIMSK3 = 0, TCCR3A = 0, TCCR3B = (1<<ICNC3) | (1<<CS30))
#define CONFIG_TIMER_PRESCALE_8() (TIMSK3 = 0, TCCR3A = 0, TCCR3B = (1<<ICNC3) | (1<<CS31))
#define CONFIG_MATCH_NORMAL() (TCCR3A = TCCR3A & ~((1<<COM3A1) | (1<<COM3A0)))
#define CONFIG_MATCH_TOGGLE() (TCCR3A = (TCCR3A & ~(1<<COM3A1)) | (1<<COM3A0))
#define CONFIG_MATCH_CLEAR() (TCCR3A = (TCCR3A | (1<<COM3A1)) & ~(1<<COM3A0))
#define CONFIG_MATCH_SET() (TCCR3A = TCCR3A | ((1<<COM3A1) | (1<<COM3A0)))
#define CONFIG_CAPTURE_FALLING_EDGE() (TCCR3B &= ~(1<<ICES3))
#define CONFIG_CAPTURE_RISING_EDGE() (TCCR3B |= (1<<ICES3))
#define ENABLE_INT_INPUT_CAPTURE() (TIFR3 = (1<<ICF3), TIMSK3 = (1<<ICIE3))
#define ENABLE_INT_COMPARE_A() (TIFR3 = (1<<OCF3A), TIMSK3 |= (1<<OCIE3A))
#define ENABLE_INT_COMPARE_B() (TIFR3 = (1<<OCF3B), TIMSK3 |= (1<<OCIE3B))
#define DISABLE_INT_INPUT_CAPTURE() (TIMSK3 &= ~(1<<ICIE3))
#define DISABLE_INT_COMPARE_A() (TIMSK3 &= ~(1<<OCIE3A))
#define DISABLE_INT_COMPARE_B() (TIMSK3 &= ~(1<<OCIE3B))
#define GET_TIMER_COUNT() (TCNT3)
#define GET_INPUT_CAPTURE() (ICR3)
#define GET_COMPARE_A() (OCR3A)
#define GET_COMPARE_B() (OCR3B)
#define SET_COMPARE_A(val) (OCR3A = (val))
#define SET_COMPARE_B(val) (OCR3B = (val))
#define CAPTURE_INTERRUPT TIMER3_CAPT_vect
#define COMPARE_A_INTERRUPT TIMER3_COMPA_vect
#define COMPARE_B_INTERRUPT TIMER3_COMPB_vect
#elif defined(ALTSS_USE_TIMER4)
#define CONFIG_TIMER_NOPRESCALE() (TIMSK4 = 0, TCCR4A = 0, TCCR4B = (1<<ICNC4) | (1<<CS40))
#define CONFIG_TIMER_PRESCALE_8() (TIMSK4 = 0, TCCR4A = 0, TCCR4B = (1<<ICNC4) | (1<<CS41))
#define CONFIG_MATCH_NORMAL() (TCCR4A = TCCR4A & ~((1<<COM4A1) | (1<<COM4A0)))
#define CONFIG_MATCH_TOGGLE() (TCCR4A = (TCCR4A & ~(1<<COM4A1)) | (1<<COM4A0))
#define CONFIG_MATCH_CLEAR() (TCCR4A = (TCCR4A | (1<<COM4A1)) & ~(1<<COM4A0))
#define CONFIG_MATCH_SET() (TCCR4A = TCCR4A | ((1<<COM4A1) | (1<<COM4A0)))
#define CONFIG_CAPTURE_FALLING_EDGE() (TCCR4B &= ~(1<<ICES4))
#define CONFIG_CAPTURE_RISING_EDGE() (TCCR4B |= (1<<ICES4))
#define ENABLE_INT_INPUT_CAPTURE() (TIFR4 = (1<<ICF4), TIMSK4 = (1<<ICIE4))
#define ENABLE_INT_COMPARE_A() (TIFR4 = (1<<OCF4A), TIMSK4 |= (1<<OCIE4A))
#define ENABLE_INT_COMPARE_B() (TIFR4 = (1<<OCF4B), TIMSK4 |= (1<<OCIE4B))
#define DISABLE_INT_INPUT_CAPTURE() (TIMSK4 &= ~(1<<ICIE4))
#define DISABLE_INT_COMPARE_A() (TIMSK4 &= ~(1<<OCIE4A))
#define DISABLE_INT_COMPARE_B() (TIMSK4 &= ~(1<<OCIE4B))
#define GET_TIMER_COUNT() (TCNT4)
#define GET_INPUT_CAPTURE() (ICR4)
#define GET_COMPARE_A() (OCR4A)
#define GET_COMPARE_B() (OCR4B)
#define SET_COMPARE_A(val) (OCR4A = (val))
#define SET_COMPARE_B(val) (OCR4B = (val))
#define CAPTURE_INTERRUPT TIMER4_CAPT_vect
#define COMPARE_A_INTERRUPT TIMER4_COMPA_vect
#define COMPARE_B_INTERRUPT TIMER4_COMPB_vect
#elif defined(ALTSS_USE_TIMER5)
#define CONFIG_TIMER_NOPRESCALE() (TIMSK5 = 0, TCCR5A = 0, TCCR5B = (1<<ICNC5) | (1<<CS50))
#define CONFIG_TIMER_PRESCALE_8() (TIMSK5 = 0, TCCR5A = 0, TCCR5B = (1<<ICNC5) | (1<<CS51))
#define CONFIG_MATCH_NORMAL() (TCCR5A = TCCR5A & ~((1<<COM5A1) | (1<<COM5A0)))
#define CONFIG_MATCH_TOGGLE() (TCCR5A = (TCCR5A & ~(1<<COM5A1)) | (1<<COM5A0))
#define CONFIG_MATCH_CLEAR() (TCCR5A = (TCCR5A | (1<<COM5A1)) & ~(1<<COM5A0))
#define CONFIG_MATCH_SET() (TCCR5A = TCCR5A | ((1<<COM5A1) | (1<<COM5A0)))
#define CONFIG_CAPTURE_FALLING_EDGE() (TCCR5B &= ~(1<<ICES5))
#define CONFIG_CAPTURE_RISING_EDGE() (TCCR5B |= (1<<ICES5))
#define ENABLE_INT_INPUT_CAPTURE() (TIFR5 = (1<<ICF5), TIMSK5 = (1<<ICIE5))
#define ENABLE_INT_COMPARE_A() (TIFR5 = (1<<OCF5A), TIMSK5 |= (1<<OCIE5A))
#define ENABLE_INT_COMPARE_B() (TIFR5 = (1<<OCF5B), TIMSK5 |= (1<<OCIE5B))
#define DISABLE_INT_INPUT_CAPTURE() (TIMSK5 &= ~(1<<ICIE5))
#define DISABLE_INT_COMPARE_A() (TIMSK5 &= ~(1<<OCIE5A))
#define DISABLE_INT_COMPARE_B() (TIMSK5 &= ~(1<<OCIE5B))
#define GET_TIMER_COUNT() (TCNT5)
#define GET_INPUT_CAPTURE() (ICR5)
#define GET_COMPARE_A() (OCR5A)
#define GET_COMPARE_B() (OCR5B)
#define SET_COMPARE_A(val) (OCR5A = (val))
#define SET_COMPARE_B(val) (OCR5B = (val))
#define CAPTURE_INTERRUPT TIMER5_CAPT_vect
#define COMPARE_A_INTERRUPT TIMER5_COMPA_vect
#define COMPARE_B_INTERRUPT TIMER5_COMPB_vect
#endif

View File

@@ -0,0 +1,64 @@
Please use this form only to report code defects or bugs.
For any question, even questions directly pertaining to this code, post your question on the forums related to the board you are using.
Arduino: forum.arduino.cc
Teensy: forum.pjrc.com
ESP8266: www.esp8266.com
ESP32: www.esp32.com
Adafruit Feather/Metro/Trinket: forums.adafruit.com
Particle Photon: community.particle.io
If you are experiencing trouble but not certain of the cause, or need help using this code, ask on the appropriate forum. This is not the place to ask for support or help, even directly related to this code. Only use this form you are certain you have discovered a defect in this code!
Please verify the problem occurs when using the very latest version, using the newest version of Arduino and any other related software.
----------------------------- Remove above -----------------------------
### Description
Describe your problem.
### Steps To Reproduce Problem
Please give detailed instructions needed for anyone to attempt to reproduce the problem.
### Hardware & Software
Board
Shields / modules used
Arduino IDE version
Teensyduino version (if using Teensy)
Version info & package name (from Tools > Boards > Board Manager)
Operating system & version
Any other software or hardware?
### Arduino Sketch
```cpp
// Change the code below by your sketch (please try to give the smallest code which demonstrates the problem)
#include <Arduino.h>
// libraries: give links/details so anyone can compile your code for the same result
void setup() {
}
void loop() {
}
```
### Errors or Incorrect Output
If you see any errors or incorrect output, please show it here. Please use copy & paste to give an exact copy of the message. Details matter, so please show (not merely describe) the actual message or error exactly as it appears.

View File

@@ -13,6 +13,8 @@
// Wiring-S 5 6 4
// Sanguino 13 14 12
// This example code is in the public domain.
AltSoftSerial altSerial;
void setup() {

View File

@@ -0,0 +1,56 @@
// AltSoftSerial Receive Test
//
// Transmit data with Serial1 and try to receive
// it with AltSoftSerial. You must connect a wire
// from Serial1 TX to AltSoftSerial RX.
#include <AltSoftSerial.h>
AltSoftSerial altser;
const int mybaud = 9600;
// Board Serial1 TX AltSoftSerial RX
// ----- ---------- ----------------
// Teensy 3.x 1 20
// Teensy 2.0 8 (D3) 10 (C7)
// Teensy++ 2.0 3 (D3) 4 (D4)
// Arduino Leonardo 1 13
// Arduino Mega 18 48
// Serial1 on AVR @ 16 MHz minimum baud is 245
// Serial1 on Teensy 3.2 @ 96 MHz minimum baud is 733
// This example code is in the public domain.
byte sentbyte;
unsigned long prevmillis;
byte testbyte=0xF0;
void setup()
{
delay(200);
Serial.begin(9600);
while (!Serial) ; // wait for Arduino Serial Monitor
Serial1.begin(mybaud); // connect a wire from TX1
altser.begin(mybaud); // to AltSoftSerial RX
Serial.println("AltSoftSerial Receive Test");
prevmillis = millis();
}
void loop()
{
// transmit a test byte on Serial 1
if (millis() - prevmillis > 250) {
sentbyte = testbyte++;
Serial1.write(sentbyte);
prevmillis = millis();
}
// attempt to receive it by AltSoftSerial
if (altser.available() > 0) {
byte b = altser.read();
Serial.println(b);
if (b != sentbyte) {
Serial.println("***** ERROR *****");
}
}
}

View File

@@ -0,0 +1,97 @@
#include <AltSoftSerial.h>
// AltSoftSerial show configuration example
// Will print library configuration to default serial port
// Open your serial monitor to see config for your board
// Printout would repeat every 10sec (just in case you missed it somehow)
// Print Configuration
// -----------------------
// Direct include AltSoftSerial internals to obtaion PIN setup (you do not need this in regular code)
// This example code is in the public domain.
#include <config/AltSoftSerial_Boards.h>
void printAltSoftSerialSetup(Stream &port)
{
#define PRINT_PFX "AltSoftSerial:"
#define PRINT_PIN_NAME(pin,name) { char buffer[128+1]; sprintf(buffer, PRINT_PFX "PIN:%2d %s", (int)pin, (const char*)name); port.println(buffer); }
port.println(PRINT_PFX "Setup info: begin");
#if defined(ALTSS_USE_FTM0)
port.println(PRINT_PFX "USE FTM0");
#endif
#if defined(ALTSS_USE_TIMER1)
port.println(PRINT_PFX "USE TIMER1");
#endif
#if defined(ALTSS_USE_TIMER2)
port.println(PRINT_PFX "USE TIMER2");
#endif
#if defined(ALTSS_USE_TIMER3)
port.println(PRINT_PFX "USE TIMER3");
#endif
#if defined(ALTSS_USE_TIMER4)
port.println(PRINT_PFX "USE TIMER4");
#endif
#if defined(ALTSS_USE_TIMER5)
port.println(PRINT_PFX "USE TIMER5");
#endif
#if defined(INPUT_CAPTURE_PIN)
PRINT_PIN_NAME(INPUT_CAPTURE_PIN,"RX");
#endif
#if defined(OUTPUT_COMPARE_A_PIN)
PRINT_PIN_NAME(OUTPUT_COMPARE_A_PIN,"TX");
#endif
#if defined(OUTPUT_COMPARE_B_PIN)
PRINT_PIN_NAME(OUTPUT_COMPARE_B_PIN,"(unused PWM)");
#endif
#if defined(OUTPUT_COMPARE_C_PIN)
PRINT_PIN_NAME(OUTPUT_COMPARE_C_PIN,"(unused PWM)");
#endif
#if defined(OUTPUT_COMPARE_D_PIN)
PRINT_PIN_NAME(OUTPUT_COMPARE_D_PIN,"(unused PWM)");
#endif
#if defined(OUTPUT_COMPARE_E_PIN)
PRINT_PIN_NAME(OUTPUT_COMPARE_E_PIN,"(unused PWM)");
#endif
#if defined(OUTPUT_COMPARE_F_PIN)
PRINT_PIN_NAME(OUTPUT_COMPARE_F_PIN,"(unused PWM)");
#endif
port.println(PRINT_PFX "Setup info: end");
#undef PRINT_PIN_NAME
#undef PRINT_PFX
}
void setup()
{
// Open default serial to dump config to
Serial.begin(9600);
while (!Serial) ; // wait for serial monitor
printAltSoftSerialSetup(Serial);
}
void loop()
{
// Repeat every 10 sec (just in case)
delay(10000);
Serial.println("");
printAltSoftSerialSetup(Serial);
}

View File

@@ -170,7 +170,7 @@ extern FlashClass Flash;
/** Load Hardwarespecific files */
#ifdef NRF5
#include "drivers/NRF5/Flash.cpp"
#include "hal/architecture/NRF5/drivers/Flash.cpp"
#else
#error "Unsupported platform."
#endif

View File

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

View File

@@ -0,0 +1,32 @@
SPIFlash
========
[![Build Status](https://travis-ci.org/LowPowerLab/SPIFlash.svg?branch=master)](https://travis-ci.org/LowPowerLab/SPIFlash)
[![GitHub release](https://img.shields.io/github/release/LowPowerLab/SPIFlash.svg)](https://github.com/LowPowerLab/SPIFlash)
[![GitHub issues](https://img.shields.io/github/issues/LowPowerLab/SPIFlash.svg)](https://github.com/LowPowerLab/SPIFlash/issues)
[![GitHub pull requests](https://img.shields.io/github/issues-pr/LowPowerLab/SPIFlash.svg)](https://github.com/LowPowerLab/SPIFlash/pulls)
[![license](https://img.shields.io/github/license/LowPowerLab/SPIFlash.svg)](https://github.com/LowPowerLab/SPIFlash/blob/master/LICENSE.txt)
Arduino/Moteino library for read/write access to SPI flash memory chips.
This works with 256byte/page SPI flash memory such as the [4MBIT W25X40CLSNIG](https://lowpowerlab.com/shop/product/72) used on [Moteino](https://www.moteino.com) for data storage and wireless programming.
<br/>
For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes).
<br/>Minimal modifications should allow chips that have different page size to work.
<br/>DEPENDS ON: Arduino native *SPI library*.
<br/>
This library was primarily developed to enable **safe** wireless programming on Moteino nodes and Moteino based applications such as the [SwitchMote](https://lowpowerlab.com/guide/switchmote/). This has been documented at [lowpowerlab](https://lowpowerlab.com/guide/moteino/wireless-programming/). [Dualoptiboot](https://github.com/LowPowerLab/DualOptiboot) (all AVR based Moteinos come with it) and [RFM69_OTA WirelessProgramming library](https://github.com/LowPowerLab/RFM69) are required to be able to wirelessly re-flash a remote Moteino.
### Installation
Copy the content of this library in the "Arduino/libraries/SPIFlash" folder.
<br />
To find your Arduino folder go to File>Preferences in the Arduino IDE.
<br/>
See [this tutorial](https://www.arduino.cc/en/Guide/Libraries) on installing Arduino libraries.
### License
Copyright (c) 2013-2018 by Felix Rusu <felix@lowpowerlab.com>
<br/><br/>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
<br/><br/>
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
<br/><br/>
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.

View File

@@ -9,6 +9,7 @@
// > Selective merge by Felix after testing in IDE 1.0.6, 1.6.4
// > Updated May 19, 2016 D-H-R, added support for SST25/Microchip Flash which does not support Page programming with OPCode 0x02,
// > use define MY_SPIFLASH_SST25TYPE for SST25 Type Flash Memory
// > Updated Sep 07, 2018 tekka, sync with https://github.com/LowPowerLab/SPIFlash
// **********************************************************************************
// License
// **********************************************************************************
@@ -76,7 +77,6 @@ void SPIFlash::select()
SPI.setBitOrder(MSBFIRST);
SPI.setClockDivider(
SPI_CLOCK_DIV4); //decided to slow down from DIV2 after SPI stalling in some instances, especially visible on mega1284p when RFM69 and FLASH chip both present
SPI.begin();
#endif
hwDigitalWrite(_slaveSelectPin, LOW);
}
@@ -105,6 +105,7 @@ bool SPIFlash::initialize()
_SPSR = SPSR;
#endif
hwPinMode(_slaveSelectPin, OUTPUT);
SPI.begin(); // see https://github.com/LowPowerLab/SPIFlash/issues/20
#ifdef SPI_HAS_TRANSACTION
_settings = SPISettings(4000000, MSBFIRST, SPI_MODE0);
#endif
@@ -345,6 +346,15 @@ void SPIFlash::blockErase32K(uint32_t addr)
SPI.transfer(addr);
unselect();
}
/// erase a 64Kbyte block
void SPIFlash::blockErase64K(uint32_t addr)
{
command(SPIFLASH_BLOCKERASE_64K, true); // Block Erase
SPI.transfer(addr >> 16);
SPI.transfer(addr >> 8);
SPI.transfer(addr);
unselect();
}
void SPIFlash::sleep()
{

View File

@@ -9,6 +9,7 @@
// > Selective merge by Felix after testing in IDE 1.0.6, 1.6.4
// > Updated May 19, 2016 D-H-R, added support for SST25/Microchip Flash which does not support Page programming with OPCode 0x02,
// > use define MY_SPIFLASH_SST25TYPE for SST25 Type Flash Memory. Added / changed comments to better suit doxygen
// > Updated Sep 07, 2018 tekka, sync with https://github.com/LowPowerLab/SPIFlash
// **********************************************************************************
// License
// **********************************************************************************
@@ -175,6 +176,7 @@ public:
void chipErase(); //!< erase entire flash memory array
void blockErase4K(uint32_t address); //!< erase a 4Kbyte block
void blockErase32K(uint32_t address); //!< erase a 32Kbyte block
void blockErase64K(uint32_t addr); //!< erase a 64Kbyte block
uint16_t readDeviceId(); //!< Get the manufacturer and device ID bytes (as a short word)
uint8_t* readUniqueId(); //!< Get the 64 bit unique identifier, stores it in @ref UNIQUEID[8]

View File

@@ -0,0 +1,127 @@
// **********************************************************************************
// This sketch is an example of using the SPIFlash library with a Moteino
// that has an onboard SPI Flash chip. This sketch listens to a few serial commands
// Hence type the following commands to interact with the SPI flash memory array:
// - 'd' dumps the first 256bytes of the flash chip to screen
// - 'e' erases the entire memory chip
// - 'i' print manufacturer/device ID
// - [0-9] writes a random byte to addresses [0-9] (either 0xAA or 0xBB)
// Get the SPIFlash library from here: https://github.com/LowPowerLab/SPIFlash
// **********************************************************************************
// Copyright Felix Rusu, LowPowerLab.com
// Library and code by Felix Rusu - felix@lowpowerlab.com
// **********************************************************************************
// License
// **********************************************************************************
// This program is free software; you can redistribute it
// and/or modify it under the terms of the GNU General
// Public License as published by the Free Software
// Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will
// be useful, but WITHOUT ANY WARRANTY; without even the
// implied warranty of MERCHANTABILITY or FITNESS FOR A
// PARTICULAR PURPOSE. See the GNU General Public
// License for more details.
//
// You should have received a copy of the GNU General
// Public License along with this program.
// If not, see <http://www.gnu.org/licenses/>.
//
// Licence can be viewed at
// http://www.gnu.org/licenses/gpl-3.0.txt
//
// Please maintain this license information along with authorship
// and copyright notices in any redistribution of this code
// **********************************************************************************
#include <SPIFlash.h> //get it here: https://github.com/LowPowerLab/SPIFlash
#include <SPI.h>
#define SERIAL_BAUD 115200
char input = 0;
long lastPeriod = -1;
#ifdef __AVR_ATmega1284P__
#define LED 15 // Moteino MEGAs have LEDs on D15
#define FLASH_SS 23 // and FLASH SS on D23
#else
#define LED 9 // Moteinos have LEDs on D9
#define FLASH_SS 8 // and FLASH SS on D8
#endif
//////////////////////////////////////////
// flash(SPI_CS, MANUFACTURER_ID)
// SPI_CS - CS pin attached to SPI flash chip (8 in case of Moteino)
// MANUFACTURER_ID - OPTIONAL, 0x1F44 for adesto(ex atmel) 4mbit flash
// 0xEF30 for windbond 4mbit flash
//////////////////////////////////////////
SPIFlash flash(FLASH_SS, 0xEF30);
void setup()
{
Serial.begin(SERIAL_BAUD);
Serial.print("Start...");
if (flash.initialize()) {
Serial.println("Init OK!");
Blink(LED, 20, 10);
} else {
Serial.println("Init FAIL!");
}
delay(1000);
}
void loop()
{
// Handle serial input (to allow basic DEBUGGING of FLASH chip)
// ie: display first 256 bytes in FLASH, erase chip, write bytes at first 10 positions, etc
if (Serial.available() > 0) {
input = Serial.read();
if (input == 'd') { //d=dump flash area
Serial.println("Flash content:");
int counter = 0;
while(counter<=256) {
Serial.print(flash.readByte(counter++), HEX);
Serial.print('.');
}
Serial.println();
} else if (input == 'e') {
Serial.print("Erasing Flash chip ... ");
flash.chipErase();
while(flash.busy());
Serial.println("DONE");
} else if (input == 'i') {
Serial.print("DeviceID: ");
Serial.println(flash.readDeviceId(), HEX);
} else if (input >= 48 && input <= 57) { //0-9
Serial.print("\nWriteByte(");
Serial.print(input);
Serial.print(")");
flash.writeByte(input-48, (millis()%2) ? 0xaa : 0xbb);
}
}
// Periodically blink the onboard LED while listening for serial commands
if ((int)(millis()/500) > lastPeriod) {
lastPeriod++;
pinMode(LED, OUTPUT);
digitalWrite(LED, lastPeriod%2);
}
}
void Blink(byte PIN, int DELAY_MS, byte loops)
{
pinMode(PIN, OUTPUT);
while (loops--) {
digitalWrite(PIN,HIGH);
delay(DELAY_MS);
digitalWrite(PIN,LOW);
delay(DELAY_MS);
}
}

View File

@@ -0,0 +1,18 @@
SPIFlash KEYWORD1
initialize KEYWORD2
command KEYWORD2
readStatus KEYWORD2
readByte KEYWORD2
readBytes KEYWORD2
writeByte KEYWORD2
writeBytes KEYWORD2
flashBusy KEYWORD2
chipErase KEYWORD2
blockErase4K KEYWORD2
blockErase32K KEYWORD2
readDeviceId KEYWORD2
readUniqueId KEYWORD2
UNIQUEID KEYWORD2
sleep KEYWORD2
wakeup KEYWORD2
end KEYWORD2

View File

@@ -1,9 +1,7 @@
# Arduino External EEPROM Library v3.2 #
# Arduino External EEPROM Library v3.4 #
Original library by http://github.com/JChristensen/extEEPROM
ReadMe file by Jack Christensen Jul 2014
## Introduction ##
**Arduino External EEPROM Library**
@@ -17,6 +15,7 @@ The **extEEPROM Library** has been tested with:
- Microchip 24LC256 (256k bit)
- Microchip 24FC1026 (1M bit, thanks to Gabriele B on the Arduino forum)
- ST Micro M24M02 (2M bit)
- Atmel AT24C256C (32k x 8, thanks to Searobin)
The **extEEPROM Library** will **NOT** work with Microchip 24xx1025 as its control byte does not conform to the following assumptions.
@@ -28,19 +27,26 @@ The **extEEPROM Library** will **NOT** work with Microchip 24xx1025 as its contr
Note that the Arduino Wire library has a buffer size of 32 bytes. This limits the size of physical I/Os that can be done to EEPROM. For writes, one or two bytes are used for the address, so writing is therefore limited to 31 or 30 bytes. Because the **extEEPROM Library** will handle I/O across block, page and device boundaries, the only consequence this has for the user is one of efficiency; arbitrarily large blocks of data can be written and read; however, carefully chosen block sizes may reduce the number of physical I/Os needed.
"Arduino External EEPROM Library" by Jack Christensen is licensed under [CC BY-SA 4.0](http://creativecommons.org/licenses/by-sa/4.0/).
## Installation ##
To use the **extEEPROM Library**:
- Go to http://github.com/JChristensen/extEEPROM, click the **Download ZIP** button and save the ZIP file to a convenient location on your PC.
### Install with the Library Manager
- For Arduino IDE versions 1.6.2 and up, add library by selecting "Manage Libraries..." from the "Include Library" submenu within the Sketch menu.
- The library manager will open and you will find a list of libraries that are already installed or ready for installation. Scroll the list to find **extEEPROM** library and click on it.
- Select the version of the library you want to install.
- Click on install and wait for the IDE to install the new library. Downloading may take time depending on your connection speed.
- Once it has finished, an Installed tag should appear, You can close the library manager.
### Manual Install
- Go to http://github.com/PaoloP74/extEEPROM, click the **Download ZIP** button and save the ZIP file to a convenient location on your PC.
- Uncompress the downloaded file. This will result in a folder containing all the files for the library, that has a name that includes the branch name, usually **extEEPROM-master**.
- Rename the folder to just **extEEPROM**.
- Copy the renamed folder to the Arduino sketchbook\libraries folder.
## Examples ##
The following example sketch is included with the **extEEPROM Library**:
- **eepromReadWrite**
- **eepromTest:** Writes 32-bit integers to the entire EEPROM address space, starting at address 0 and continuing to the topmost address. These are then read back in and verified; any discrepancies are reported to the serial monitor.
- **eepromTest_Wire1**
## Usage notes ##
The **extEEPROM Library** is designed for use with Arduino version 1.0 or later.
@@ -49,11 +55,10 @@ To use the **extEEPROM Library**, the standard [Arduino Wire library](http://ard
#include <Wire.h> //http://arduino.cc/en/Reference/Wire (included with Arduino IDE)
```
## Enumerations ##
###eeprom_size_t
#####Description
### eeprom_size_t
##### Description
EEPROM device size in k-bits. Many manufacturers' EEPROM part numbers are designated in k-bits.
#####Values
##### Values
- kbits_2
- kbits_4
- kbits_8
@@ -65,62 +70,75 @@ EEPROM device size in k-bits. Many manufacturers' EEPROM part numbers are design
- kbits_512
- kbits_1024
- kbits_2048
###twiClockFreq_t
#####Description
### twiClockFreq_t
##### Description
I2C bus speed.
#####Values
- twiClock100kHz
- twiClock400kHz
##### Values
- extEEPROM::twiClock100kHz
- extEEPROM::twiClock400kHz
## Constructor ##
###extEEPROM(eeprom_size_t devCap, byte nDev, unsigned int pgSize, byte busAddr)
#####Description
### extEEPROM(eeprom_size_t devCap, byte nDev, unsigned int pgSize, byte busAddr)
##### Description
Instantiates an external EEPROM object.
#####Syntax
`extEEPROM myEEPROM(eeprom_size_t devCap, byte nDev, unsigned int pgSize, byte busAddr));`
#####Parameters
##### Syntax
`extEEPROM myEEPROM(eeprom_size_t devCap, byte nDev, unsigned int pgSize, byte busAddr);`
##### Parameters
**devCap** *(eeprom_size_t)*: The size of one EEPROM device in k-bits. Choose a value from the eeprom_size_t enumeration above.
**nDev** *(byte)*: The number of EEPROM devices on the bus. Note that if there are multiple EEPROM devices on the bus, they must be identical and each must have its address pins strapped properly.
**pgSize** *(unsigned int)*: The EEPROM page size in bytes. Consult the datasheet if you are unsure of the page size.
**busAddr** *(byte)*: The base I2C bus address for the EEPROM(s). 0x50 is a common value and this parameter can be omitted, in which case 0x50 will be used as the default.
#####Example
##### Example
```c++
extEEPROM myEEPROM(kbits_256, 2, 64); //two 24LC256 EEPROMS on the bus
extEEPROM oddEEPROM(kbits_8, 1, 16, 0x42); //an EEPROM with a non-standard I2C address
```
## Methods ##
###begin(twiClockFreq_t freq)
#####Description
### begin(twiClockFreq_t freq, TwoWire *_comm)
##### Description
Initializes the library. Call this method once in the setup code. begin() does a dummy I/O so that the user may interrogate the return status to ensure the EEPROM is operational.
#####Syntax
##### Syntax
`myEEPROM.begin(twiClockFreq_t freq);`
#####Parameters
**freq** *(twiClockFreq_t)*: The desired I2C bus speed, twiClock100kHz or twiClock400kHz. Can be omitted in which case it will default to twiClock100kHz. **NOTE:** When using 400kHz, if there are other devices on the bus they must all support a 400kHz bus speed. **Secondly**, the other devices should be initialized first, as other libraries may not support adjusting the bus speed. To ensure the desired speed is set, call the extEEPROM.begin() function *after* initializing all other I2C devices.
#####Returns
or
`myEEPROM.begin(twiClockFreq_t freq, TwoWire *_comm);`
##### Parameters
**freq** *(twiClockFreq_t)*: The desired I2C bus speed, `extEEPROM::twiClock100kHz` or `extEEPROM::twiClock400kHz`. Can be omitted in which case it will default to `twiClock100kHz`.
**NOTE:** When using 400kHz, if there are other devices on the bus they must all support a 400kHz bus speed. **Secondly**, the other devices should be initialized first, as other libraries may not support adjusting the bus speed. To ensure the desired speed is set, call the extEEPROM.begin() function *after* initializing all other I2C devices.
**_comm** *(TwoWire * )*: The Used I2C TwoWire channel . Can be omitted in which case it will default to the first Arduino I2C channel `Wire`. If another of the possible I2C channel is used its pointer shall be passed as parameter.
**NOTE:** If another I2C channel is unse, and not the default one, the first parameters **freq** MUST be defined.
##### Returns
I2C I/O status, zero if successful *(byte)*. See the [Arduino Wire.endTransmission() function](http://arduino.cc/en/Reference/WireEndTransmission) for a description of other return codes.
#####Example
##### Examples
```c++
extEEPROM myEEPROM(kbits_256, 2, 64);
byte i2cStat = myEEPROM.begin(twiClock400kHz);
byte i2cStat = myEEPROM.begin(extEEPROM::twiClock400kHz);
if ( i2cStat != 0 ) {
//there was a problem
}
```
###write(unsigned long addr, byte *values, unsigned int nBytes)
#####Description
##### Use of other I2C channel
```c++
extEEPROM myEEPROM(kbits_256, 2, 64);
byte i2cStat = myEEPROM.begin(extEEPROM::twiClock400kHz, &Wire1);
if ( i2cStat != 0 ) {
//there was a problem
}
```
### write(unsigned long addr, byte *values, unsigned int nBytes)
##### Description
Write one or more bytes to external EEPROM.
#####Syntax
##### Syntax
`myEEPROM.write(unsigned long addr, byte* values, byte nBytes);`
#####Parameters
##### Parameters
**addr** *(unsigned long)*: The beginning EEPROM location to write.
**values** _(byte*)_: Pointer to an array containing the data to write.
**nBytes** *(unsigned int)*: The number of bytes to write.
#####Returns
##### Returns
I2C I/O status, zero if successful *(byte)*. See the [Arduino Wire.endTransmission() function](http://arduino.cc/en/Reference/WireEndTransmission) for a description of other return codes. Returns a status of EEPROM_ADDR_ERR if the I/O would extend past the top of the EEPROM address space.
#####Example
##### Example
```c++
byte myData[10];
//write 10 bytes starting at location 42
@@ -135,33 +153,33 @@ if ( i2cStat != 0 ) {
}
}
```
###write(unsigned long addr, byte value)
#####Description
### write(unsigned long addr, byte value)
##### Description
Writes a single byte to external EEPROM.
#####Syntax
##### Syntax
`myEEPROM.write(unsigned long addr, byte value);`
#####Parameters
##### Parameters
**addr** *(unsigned long)*: The EEPROM location to write.
**values** _(byte)_: The value to write.
#####Returns
##### Returns
Same as multiple-byte write() above.
#####Example
##### Example
```c++
//write the value 16 to EEPROM location 314.
byte i2cStat = myEEPROM.write(314, 16);
```
###read(unsigned long addr, byte *values, unsigned int nBytes)
#####Description
### read(unsigned long addr, byte *values, unsigned int nBytes)
##### Description
Reads one or more bytes from external EEPROM into an array supplied by the caller.
#####Syntax
##### Syntax
`myEEPROM.read(unsigned long addr, byte *values, byte nBytes);`
#####Parameters
##### Parameters
**addr** *(unsigned long)*: The beginning EEPROM location to read from.
**values** _(byte*)_: Pointer to an array to receive the data.
**nBytes** *(unsigned int)*: The number of bytes to read.
#####Returns
##### Returns
I2C I/O status, zero if successful *(byte)*. See the [Arduino Wire.endTransmission() function](http://arduino.cc/en/Reference/WireEndTransmission) for a description of other return codes. Returns a status of EEPROM_ADDR_ERR if the I/O would extend past the top of the EEPROM address space.
#####Example
##### Example
```c++
byte myData[10];
//read 10 bytes starting at location 42
@@ -176,17 +194,16 @@ if ( i2cStat != 0 ) {
}
}
```
###read(unsigned long addr)
#####Description
### read(unsigned long addr)
##### Description
Reads a single byte from external EEPROM.
#####Syntax
##### Syntax
`myEEPROM.read(unsigned long addr);`
#####Parameters
##### Parameters
**addr** *(unsigned long)*: The EEPROM location to read from.
#####Returns
##### Returns
The data read from EEPROM or an error code *(int)*. To distinguish error values from valid data, error values are returned as negative numbers. See the [Arduino Wire.endTransmission() function](http://arduino.cc/en/Reference/WireEndTransmission) for a description of return codes. Returns a status of EEPROM_ADDR_ERR if the I/O would extend past the top of the EEPROM address space.
#####Example
##### Example
```c++
int myData;
//read a byte from location 42
@@ -201,8 +218,9 @@ if ( readValue < 0 ) {
}
}
else {
//data read ok
//data read ok
}
```
"Arduino External EEPROM Library" by Jack Christensen is licensed under [CC BY-SA 4.0](http://creativecommons.org/licenses/by-sa/4.0/).
![CC BY-SA](http://mirrors.creativecommons.org/presskit/buttons/80x15/png/by-sa.png)

View File

@@ -0,0 +1,209 @@
/*
Copyright (c) 2014 Arduino. All right reserved.
This library is free software; you can redistribute it and / or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110 - 1301 USA
*/
#include "extEEPROM.h"
extEEPROM myEEPROM(kbits_256, 1, 64, 0x57);
void setup(void)
{
SerialUSB.begin(115200);
while (!SerialUSB) {
;
}
byte i2cStat = myEEPROM.begin(myEEPROM.twiClock100kHz);
if ( i2cStat != 0 ) {
SerialUSB.println(F("I2C Problem"));
}
SerialUSB.println(
F("EEPROM Memory commands: read:(a)(l)(r) , write:(a)(d)(w), next read data (n)"));
SerialUSB.println(F("- Commands TO PRESS:"));
SerialUSB.println(F("\t a : memory address to read / write"));
SerialUSB.println(F("\t d : data to write"));
SerialUSB.println(F("\t l : data to write"));
SerialUSB.println(F("\t r : read command"));
SerialUSB.println(F("\t w : write command"));
}
unsigned long address = 0;
const unsigned int maxDataSize = 1024; //0x8000; // 32 k bytes (32768 = 0x8000) = 256 kbits
byte data[maxDataSize] = {'p', 'i', 'p', 'p', 'o'};
unsigned int dataSize = 5;
void eprom_read_write(bool write)
{
byte i2cStat = 0;
if (write) {
i2cStat = myEEPROM.write(address, data, dataSize);
} else {
memset(data, 0, maxDataSize);
i2cStat = myEEPROM.read(address, data, dataSize);
}
if ( i2cStat != 0 ) {
//there was a problem
SerialUSB.print(F("I2C Problem: "));
if ( i2cStat == EEPROM_ADDR_ERR) {
SerialUSB.println(F("Wrong address"));
} else {
SerialUSB.print(F("I2C error: "));
SerialUSB.print(i2cStat);
SerialUSB.println(F(""));
}
}
}
void parse(char inChar)
{
const char addr_len = 5;
char addr_char[addr_len] = "";
const char data_len = 3;
char data_char[data_len] = "";
char size_char[data_len] = "";
char inc = 0, i = 0, j = 0;
switch (inChar) {
case 'a':
SerialUSB.print(F("Insert Address as 4 Hex chars (without '0x'): "));
while (i < 4) {
while (SerialUSB.available() <= 0)
;
inc = SerialUSB.read();
if (inc == 'q') {
return;
}
addr_char[i] = inc;
++i;
}
address = (unsigned long)strtol(addr_char, NULL, 16);
SerialUSB.println(address);
break;
case 'd':
SerialUSB.print(F("Insert Hex data sequence (without '0x'), return to enter: "));
memset(data, 0, maxDataSize);
while (true) {
while (SerialUSB.available() <= 0)
;
inc = SerialUSB.read();
if (inc == 'q') {
return;
}
if (inc == '\r' || inc == '\n') {
break;
}
if (inc >= 'a' && inc <= 'f') {
data[j] += inc - 'a' + 10;
} else if (inc >= 'A' && inc <= 'F') {
data[j] += inc - 'A' + 10;
} else if (inc >= '0' && inc <= '9') {
data[j] += inc - '0';
} else {
return;
}
if (i % 2) {
j++;
} else {
data[j] = data[j] << 4;
}
i++;
}
dataSize = j;
SerialUSB.println(dataSize);
SerialUSB.println(F(""));
break;
case 'l':
SerialUSB.print(F("Insert data len as 2 Hex chars (without '0x'): "));
while (i < 2) {
while (SerialUSB.available() <= 0)
;
inc = SerialUSB.read();
if (inc == 'q') {
return;
}
size_char[i] = inc;
++i;
if (inc == '\n') {
return;
}
}
dataSize = (unsigned int)strtol(size_char, NULL, 16);
SerialUSB.println(dataSize);
break;
case 'n':
address += dataSize;
/* FALLTHROUGH */
case 'r':
SerialUSB.print(F("reading address: "));
SerialUSB.println(address, HEX);
eprom_read_write(false);
for (i = 0; i < dataSize ; ++i) {
SerialUSB.print(data[i], HEX);
SerialUSB.print(F(" "));
}
SerialUSB.println();
break;
case 'w':
SerialUSB.print(F("writing at address: "));
SerialUSB.print(address, HEX);
SerialUSB.print(F(", len: "));
SerialUSB.println(address, dataSize);
for (i = 0; i < dataSize ; ++i) {
SerialUSB.print(data[i], HEX);
SerialUSB.print(F(" "));
}
eprom_read_write(true);
SerialUSB.println();
break;
case 'T':
SerialUSB.println(F("Memory test: writing and verifying the whole memory"));
break;
default:
break;
}
}
void loop(void)
{
if (SerialUSB.available() > 0) {
char inChar = SerialUSB.read();
SerialUSB.print(inChar);
parse(inChar);
}
delay(10);
}

View File

@@ -3,7 +3,7 @@
//Wire a button from digital pin 6 to ground, this is used as a start button
//so the sketch doesn't do unnecessary EEPROM writes every time it's reset.
//Jack Christensen 09Jul2014
//Paolo Paolucci 17Mar2016
//Paolo Paolucci 17Mar2016 (fix 28Jun2017)
#include <extEEPROM.h> //https://github.com/PaoloP74/extEEPROM
@@ -17,7 +17,7 @@ void setup(void)
{
pinMode(btnStart, INPUT_PULLUP);
Serial.begin(115200);
uint8_t eepStatus = eep.begin(twiClock400kHz); //go fast!
uint8_t eepStatus = eep.begin(eep.twiClock400kHz); //go fast!
if (eepStatus) {
Serial.print(F("extEEPROM.begin() failed, status = "));
Serial.println(eepStatus);

View File

@@ -0,0 +1,233 @@
//Test extEEPROM library.
//Writes the EEPROM full of 32-bit integers and reads them back to verify.
//Wire a button from digital pin 6 to ground, this is used as a start button
//so the sketch doesn't do unnecessary EEPROM writes every time it's reset.
//Jack Christensen 09Jul2014
//Paolo Paolucci 17Mar2016 (fix 28Jun2017)
//Mik 03Jan2017 (configured Library to use the Wire1 as I2C channel)
#include <extEEPROM.h> //https://github.com/PaoloP74/extEEPROM
//One 24LC256 EEPROMs on the bus
const uint32_t totalKBytes = 32; //for read and write test functions
extEEPROM eep(kbits_256, 1, 64, 0x57); //device size, number of devices, page size
const uint8_t btnStart = 6; //start button
void setup(void)
{
uint8_t eepStatus;
pinMode(btnStart, INPUT_PULLUP);
Serial.begin(115200);
while (!SerialUSB) {}
bool channelInsert = false;
Serial.println(F("Select the number of Wire channel use the eeprom"));
Serial.println(F("0 = Wire"));
Serial.println(F("1 = Wire1"));
Serial.println(F("...."));
Serial.println(F("x = WIRE_INTERFACES_COUNT"));
do {
if (Serial.available()) {
char I2Cchannel = Serial.read();
// only number that are less than WIRE_INTERFACES_COUNT are allowed
if ((I2Cchannel > '0') && (I2Cchannel < ('0' + WIRE_INTERFACES_COUNT))) {
channelInsert = true;
}
switch ((I2Cchannel - '0')) {
case 0:
Serial.println(F("Using the default Wire interface"));
eepStatus = eep.begin(eep.twiClock400kHz); //go fast!
break;
case 1:
Serial.println(F("Using the Wire1 interface"));
eepStatus = eep.begin(eep.twiClock400kHz, &Wire1); //go fast!
break;
/*
Uncomment till the number of WIRE_INTERFACES_COUNT of your Arduino board
case 2:
Serial.println(F("Using the Wire2 interface"));
eepStatus = eep.begin(eep.twiClock400kHz, &Wire2); //go fast!
break;
case 3:
Serial.println(F("Using the Wire3 interface"));
eepStatus = eep.begin(eep.twiClock400kHz, &Wire3); //go fast!
break;
case 4:
Serial.println(F("Using the Wire4 interface"));
eepStatus = eep.begin(eep.twiClock400kHz, &Wire4); //go fast!
break;
case 5:
Serial.println(F("Using the Wire5 interface"));
eepStatus = eep.begin(eep.twiClock400kHz, &Wire5); //go fast!
break;*/
default:
Serial.println(F("A wrong channel has been inserted (Arduino manage max 5)"));
break;
}
}
} while (!channelInsert);
if (eepStatus) {
Serial.print(F("extEEPROM.begin() failed, status = "));
Serial.println(eepStatus);
while (1);
}
Serial.println(F("Started !!"));
uint8_t chunkSize =
64; //this can be changed, but must be a multiple of 4 since we're writing 32-bit integers
// eeErase(chunkSize, 0, totalKBytes * 1024 - 1);
eeWrite(chunkSize);
eeRead(chunkSize);
dump(0, 32); //the first 32 bytes
dump(32256, 64); //the last 64 bytes
//dump(32512, 64); //across the device boundary
//dump(65520, 16); //the last 16 bytes
}
void loop(void)
{
}
//write test data (32-bit integers) to eeprom, "chunk" bytes at a time
void eeWrite(uint8_t chunk)
{
chunk &= 0xFC; //force chunk to be a multiple of 4
uint8_t data[chunk];
uint32_t val = 0;
Serial.println(F("Writing..."));
uint32_t msStart = millis();
for (uint32_t addr = 0; addr < totalKBytes * 1024; addr += chunk) {
if ( (addr & 0xFFF) == 0 ) {
Serial.println(addr);
}
for (uint8_t c = 0; c < chunk; c += 4) {
data[c + 0] = val >> 24;
data[c + 1] = val >> 16;
data[c + 2] = val >> 8;
data[c + 3] = val;
++val;
}
eep.write(addr, data, chunk);
}
uint32_t msLapse = millis() - msStart;
Serial.print(F("Write lapse: "));
Serial.print(msLapse);
Serial.println(F(" ms"));
}
//read test data (32-bit integers) from eeprom, "chunk" bytes at a time
void eeRead(uint8_t chunk)
{
chunk &= 0xFC; //force chunk to be a multiple of 4
uint8_t data[chunk];
uint32_t val = 0, testVal;
Serial.println(F("Reading..."));
uint32_t msStart = millis();
for (uint32_t addr = 0; addr < totalKBytes * 1024; addr += chunk) {
if ( (addr & 0xFFF) == 0 ) {
Serial.println(addr);
}
eep.read(addr, data, chunk);
for (uint8_t c = 0; c < chunk; c += 4) {
testVal = ((uint32_t)data[c + 0] << 24) + ((uint32_t)data[c + 1] << 16) + ((
uint32_t)data[c + 2] << 8) + (uint32_t)data[c + 3];
if (testVal != val) {
Serial.print(F("Error @ addr "));
Serial.print(addr + c);
Serial.print(F(" Expected "));
Serial.print(val);
Serial.print(F(" Read "));
Serial.print(testVal);
Serial.print(F(" 0x"));
Serial.println(testVal, HEX);
}
++val;
}
}
uint32_t msLapse = millis() - msStart;
Serial.print(F("Last value: "));
Serial.print(val);
Serial.print(F(" Read lapse: "));
Serial.print(msLapse);
Serial.println(F(" ms"));
}
//write 0xFF to eeprom, "chunk" bytes at a time
void eeErase(uint8_t chunk, uint32_t startAddr, uint32_t endAddr)
{
chunk &= 0xFC; //force chunk to be a multiple of 4
uint8_t data[chunk];
Serial.println(F("Erasing..."));
for (int i = 0; i < chunk; i++) {
data[i] = 0xFF;
}
uint32_t msStart = millis();
for (uint32_t a = startAddr; a <= endAddr; a += chunk) {
if ( (a & 0xFFF) == 0 ) {
Serial.println(a);
}
eep.write(a, data, chunk);
}
uint32_t msLapse = millis() - msStart;
Serial.print(F("Erase lapse: "));
Serial.print(msLapse);
Serial.print(F(" ms"));
}
//dump eeprom contents, 16 bytes at a time.
//always dumps a multiple of 16 bytes.
void dump(uint32_t startAddr, uint32_t nBytes)
{
Serial.print(F("EEPROM DUMP 0x"));
Serial.print(startAddr, HEX);
Serial.print(F(" 0x"));
Serial.print(nBytes, HEX);
Serial.print(F(" "));
Serial.print(startAddr);
Serial.print(F(" "));
Serial.println(nBytes);
uint32_t nRows = (nBytes + 15) >> 4;
uint8_t d[16];
for (uint32_t r = 0; r < nRows; r++) {
uint32_t a = startAddr + 16 * r;
eep.read(a, d, 16);
Serial.print(F("0x"));
if ( a < 16 * 16 * 16 ) {
Serial.print(F("0"));
}
if ( a < 16 * 16 ) {
Serial.print(F("0"));
}
if ( a < 16 ) {
Serial.print(F("0"));
}
Serial.print(a, HEX);
Serial.print(F(" "));
for ( int c = 0; c < 16; c++ ) {
if ( d[c] < 16 ) {
Serial.print(F("0"));
Serial.print(d[c], HEX);
Serial.print( c == 7 ? " " : " ");
}
}
Serial.println(F(""));
}
}

View File

@@ -1,4 +1,4 @@
/*-----------------------------------------------------------------------------*
/*-----------------------------------------------------------------------------*
* extEEPROM.cpp - Arduino library to support external I2C EEPROMs. *
* *
* This library will work with most I2C serial EEPROM chips between 2k bits *
@@ -56,11 +56,10 @@
*-----------------------------------------------------------------------------*/
#include "extEEPROM.h"
#include <Wire.h>
// added for SAMD arch, tekka 2017
#if !defined(BUFFER_LENGTH)
#define BUFFER_LENGTH SERIAL_BUFFER_SIZE
// workaround, BUFFER_LENGTH is not defined in Wire.h for SAMD controllers
#ifndef BUFFER_LENGTH
#define BUFFER_LENGTH 32
#endif
// Constructor.
@@ -75,6 +74,7 @@
extEEPROM::extEEPROM(eeprom_size_t deviceCapacity, byte nDevice, unsigned int pageSize,
uint8_t eepromAddr)
{
communication = NULL;
_dvcCapacity = deviceCapacity;
_nDevice = nDevice;
_pageSize = pageSize;
@@ -104,16 +104,17 @@ extEEPROM::extEEPROM(eeprom_size_t deviceCapacity, byte nDevice, unsigned int pa
//when using a 400kHz bus speed and there are multiple I2C devices on the
//bus (other than EEPROM), call extEEPROM::begin() after any initialization
//calls for the other devices to ensure the intended I2C clock speed is set.
byte extEEPROM::begin(twiClockFreq_t twiFreq)
byte extEEPROM::begin(twiClockFreq_t twiFreq, TwoWire *_comm)
{
Wire.begin();
Wire.setClock(twiFreq);
Wire.beginTransmission(_eepromAddr);
communication = _comm;
communication->begin();
communication->setClock(twiFreq);
communication->beginTransmission(_eepromAddr);
if (_nAddrBytes == 2) {
Wire.write((byte)0); //high addr byte
communication->write((byte)0); //high addr byte
}
Wire.write((byte)0); //low addr byte
return Wire.endTransmission();
communication->write((byte)0); //low addr byte
return communication->endTransmission();
}
//Write bytes to external EEPROM.
@@ -129,21 +130,18 @@ byte extEEPROM::write(unsigned long addr, byte *values, unsigned int nBytes)
}
while (nBytes > 0) {
uint8_t ctrlByte; //control byte (I2C device address & chip/block select bits)
uint16_t nWrite; //number of bytes to write
uint16_t nPage; //number of bytes remaining on current page, starting at addr
nPage = _pageSize - ( addr & (_pageSize - 1) );
const uint16_t nPage = _pageSize - ( addr & (_pageSize - 1) );
//find min(nBytes, nPage, BUFFER_LENGTH) -- BUFFER_LENGTH is defined in the Wire library.
nWrite = nBytes < nPage ? nBytes : nPage;
uint16_t nWrite = nBytes < nPage ? nBytes : nPage;
nWrite = BUFFER_LENGTH - _nAddrBytes < nWrite ? BUFFER_LENGTH - _nAddrBytes : nWrite;
ctrlByte = _eepromAddr | (byte) (addr >> _csShift);
Wire.beginTransmission(ctrlByte);
const uint8_t ctrlByte = _eepromAddr | (byte) (addr >> _csShift);
communication->beginTransmission(ctrlByte);
if (_nAddrBytes == 2) {
Wire.write( (byte) (addr >> 8) ); //high addr byte
communication->write( (byte) (addr >> 8) ); //high addr byte
}
Wire.write( (byte) addr ); //low addr byte
Wire.write(values, nWrite);
txStatus = Wire.endTransmission();
communication->write( (byte) addr ); //low addr byte
communication->write(values, nWrite);
txStatus = communication->endTransmission();
if (txStatus != 0) {
return txStatus;
}
@@ -151,12 +149,12 @@ byte extEEPROM::write(unsigned long addr, byte *values, unsigned int nBytes)
//wait up to 50ms for the write to complete
for (uint8_t i=100; i; --i) {
delayMicroseconds(500); //no point in waiting too fast
Wire.beginTransmission(ctrlByte);
communication->beginTransmission(ctrlByte);
if (_nAddrBytes == 2) {
Wire.write((byte)0); //high addr byte
communication->write((byte)0); //high addr byte
}
Wire.write((byte)0); //low addr byte
txStatus = Wire.endTransmission();
communication->write((byte)0); //low addr byte
txStatus = communication->endTransmission();
if (txStatus == 0) {
break;
}
@@ -183,27 +181,23 @@ byte extEEPROM::read(unsigned long addr, byte *values, unsigned int nBytes)
}
while (nBytes > 0) {
byte ctrlByte;
byte rxStatus;
uint16_t nRead; //number of bytes to read
uint16_t nPage; //number of bytes remaining on current page, starting at addr
nPage = _pageSize - ( addr & (_pageSize - 1) );
nRead = nBytes < nPage ? nBytes : nPage;
const uint16_t nPage = _pageSize - ( addr & (_pageSize - 1) );
uint16_t nRead = nBytes < nPage ? nBytes : nPage;
nRead = BUFFER_LENGTH < nRead ? BUFFER_LENGTH : nRead;
ctrlByte = _eepromAddr | (byte) (addr >> _csShift);
Wire.beginTransmission(ctrlByte);
byte ctrlByte = _eepromAddr | (byte) (addr >> _csShift);
communication->beginTransmission(ctrlByte);
if (_nAddrBytes == 2) {
Wire.write( (byte) (addr >> 8) ); //high addr byte
communication->write( (byte) (addr >> 8) ); //high addr byte
}
Wire.write( (byte) addr ); //low addr byte
rxStatus = Wire.endTransmission();
communication->write( (byte) addr ); //low addr byte
const byte rxStatus = communication->endTransmission();
if (rxStatus != 0) {
return rxStatus; //read error
}
Wire.requestFrom(ctrlByte, nRead);
communication->requestFrom(ctrlByte, nRead);
for (byte i=0; i<nRead; i++) {
values[i] = Wire.read();
values[i] = communication->read();
}
addr += nRead; //increment the EEPROM address

View File

@@ -1,4 +1,4 @@
/*-----------------------------------------------------------------------------*
/*-----------------------------------------------------------------------------*
* extEEPROM.h - Arduino library to support external I2C EEPROMs. *
* *
* This library will work with most I2C serial EEPROM chips between 2k bits *
@@ -55,10 +55,15 @@
* http://creativecommons.org/licenses/by-sa/4.0/ *
*-----------------------------------------------------------------------------*/
/*
* tekka 2018:
* Re-implementing extEEPROM::update(unsigned long addr, byte value);
*/
#ifndef extEEPROM_h
#define extEEPROM_h
#include <Arduino.h>
#include <Wire.h>
//EEPROM size in kilobits. EEPROM part numbers are usually designated in k-bits.
enum eeprom_size_t {
@@ -75,16 +80,24 @@ enum eeprom_size_t {
kbits_2048 = 2048
};
enum twiClockFreq_t { twiClock100kHz = 100000, twiClock400kHz = 400000 };
//EEPROM addressing error, returned by write() or read() if upper address bound is exceeded
const uint8_t EEPROM_ADDR_ERR = 9;
/** extEEPROM class */
class extEEPROM
{
private:
// the private attribute used to comunicate with the correct I2C SERCOM
TwoWire *communication;
public:
/**
* I2C clock frequencies
*/
enum twiClockFreq_t {
twiClock100kHz = 100000, //!< twiClock100kHz
twiClock400kHz = 400000 //!< twiClock400kHz
};
/**
* @brief Constructor
* @param deviceCapacity
@@ -94,7 +107,9 @@ public:
*/
extEEPROM(eeprom_size_t deviceCapacity, byte nDevice, unsigned int pageSize,
byte eepromAddr = 0x50);
byte begin(twiClockFreq_t twiFreq = twiClock100kHz); //!< begin()
// It is ready for every I2C Sercom, by default use the main Wire
byte begin(twiClockFreq_t twiFreq = twiClock100kHz, TwoWire *_comm=&Wire); //!< begin()
byte write(unsigned long addr, byte *values, unsigned int nBytes); //!< write()
byte write(unsigned long addr, byte value); //!< write()
byte read(unsigned long addr, byte *values, unsigned int nBytes); //!< read()

View File

@@ -1,10 +0,0 @@
name=extEEPROM
version=3.3.2
author=Jack Christensen
maintainer=Paolo Paolucci
sentence=Arduino library to support external I2C EEPROMs.
paragraph=This library will work with most I2C serial EEPROM chips between 2k bits and 2048k bits (2M bits) in size. Multiple EEPROMs on the bus are supported as a single address space.
category=Data Storage
url=https://github.com/PaoloP74/extEEPROM
architectures=*
includes=Wire.h,extEEPROM.h

View File

@@ -25,6 +25,9 @@ bool hwInit(void)
{
#if !defined(MY_DISABLED_SERIAL)
MY_SERIALDEVICE.begin(MY_BAUD_RATE);
#if defined(MY_GATEWAY_SERIAL)
while (!MY_SERIALDEVICE) {}
#endif
#endif
return true;
}
@@ -253,19 +256,19 @@ inline void hwRandomNumberInit(void)
randomSeed(seed);
}
bool hwUniqueID(unique_id_t* uniqueID)
bool hwUniqueID(unique_id_t *uniqueID)
{
// padding
(void)memset(uniqueID, MY_HWID_PADDING_BYTE, sizeof(unique_id_t));
// no unique ID for non-PB AVR, use HW specifics for diversification
*((uint8_t*)uniqueID) = boot_signature_byte_get(0x00);
*((uint8_t*)uniqueID + 1) = boot_signature_byte_get(0x02);
*((uint8_t*)uniqueID + 2) = boot_signature_byte_get(0x04);
*((uint8_t*)uniqueID + 3) = boot_signature_byte_get(0x01); //OSCCAL
*((uint8_t *)uniqueID) = boot_signature_byte_get(0x00);
*((uint8_t *)uniqueID + 1) = boot_signature_byte_get(0x02);
*((uint8_t *)uniqueID + 2) = boot_signature_byte_get(0x04);
*((uint8_t *)uniqueID + 3) = boot_signature_byte_get(0x01); //OSCCAL
#if defined(__AVR_ATmega328PB__)
// ATMEGA328PB specifics, has unique ID
for(uint8_t idx = 0; idx < 10; idx++) {
*((uint8_t*)uniqueID + 4 + idx) = boot_signature_byte_get(0xE + idx);
*((uint8_t *)uniqueID + 4 + idx) = boot_signature_byte_get(0xE + idx);
}
return true; // unique ID returned
#else
@@ -329,6 +332,11 @@ uint16_t hwCPUFrequency(void)
return TCNT1 * 2048UL / 100000UL;
}
int8_t hwCPUTemperature(void)
{
return -127; // not implemented yet
}
uint16_t hwFreeMem(void)
{
extern int __heap_start, *__brkval;
@@ -338,9 +346,6 @@ uint16_t hwFreeMem(void)
void hwDebugPrint(const char *fmt, ... )
{
#ifndef MY_DEBUGDEVICE
#define MY_DEBUGDEVICE MY_SERIALDEVICE
#endif
#ifndef MY_DISABLED_SERIAL
char fmtBuffer[MY_SERIAL_OUTPUT_SIZE];
#ifdef MY_GATEWAY_SERIAL
@@ -354,14 +359,14 @@ void hwDebugPrint(const char *fmt, ... )
MY_DEBUGDEVICE.print(F(" "));
#endif
va_list args;
va_start (args, fmt );
va_start(args, fmt);
vsnprintf_P(fmtBuffer, sizeof(fmtBuffer), fmt, args);
#ifdef MY_GATEWAY_SERIAL
// Truncate message if this is gateway node
fmtBuffer[sizeof(fmtBuffer) - 2] = '\n';
fmtBuffer[sizeof(fmtBuffer) - 1] = '\0';
#endif
va_end (args);
va_end(args);
MY_DEBUGDEVICE.print(fmtBuffer);
MY_DEBUGDEVICE.flush();
#else

View File

@@ -39,6 +39,10 @@
#define MY_SERIALDEVICE Serial
#endif
#ifndef MY_DEBUGDEVICE
#define MY_DEBUGDEVICE MY_SERIALDEVICE
#endif
// Define these as macros to save valuable space
#define hwDigitalWrite(__pin, __value) digitalWriteFast(__pin, __value)
#define hwDigitalRead(__pin) digitalReadFast(__pin)

View File

@@ -28,6 +28,9 @@ bool hwInit(void)
{
#if !defined(MY_DISABLED_SERIAL)
MY_SERIALDEVICE.begin(MY_BAUD_RATE, SERIAL_8N1);
#if defined(MY_GATEWAY_SERIAL)
while (!MY_SERIALDEVICE) {}
#endif
#endif
return EEPROM.begin(MY_EEPROM_SIZE);
}
@@ -128,10 +131,9 @@ uint16_t hwCPUFrequency(void)
return static_cast<uint16_t>(ESP.getCpuFreqMHz() * 10);
}
uint8_t hwCPUTemperature(void)
int8_t hwCPUTemperature(void)
{
// CPU temperature in °C
return static_cast<uint8_t>(temperatureRead());
return -127; // not implemented yet
}
uint16_t hwFreeMem(void)
@@ -141,20 +143,20 @@ uint16_t hwFreeMem(void)
void hwDebugPrint(const char *fmt, ...)
{
#ifndef MY_DISABLED_SERIAL
char fmtBuffer[MY_SERIAL_OUTPUT_SIZE];
#ifdef MY_GATEWAY_SERIAL
// prepend debug message to be handled correctly by controller (C_INTERNAL, I_LOG_MESSAGE)
snprintf_P(fmtBuffer, sizeof(fmtBuffer), PSTR("0;255;%d;0;%d;%lu "), C_INTERNAL, I_LOG_MESSAGE,
millis());
MY_SERIALDEVICE.print(fmtBuffer);
snprintf_P(fmtBuffer, sizeof(fmtBuffer), PSTR("0;255;%" PRIu8 ";0;%" PRIu8 ";%" PRIu32 " "),
C_INTERNAL, I_LOG_MESSAGE, hwMillis());
MY_DEBUGDEVICE.print(fmtBuffer);
#else
// prepend timestamp
MY_SERIALDEVICE.print(millis());
MY_SERIALDEVICE.print(" ");
MY_DEBUGDEVICE.print(hwMillis());
MY_DEBUGDEVICE.print(F(" "));
#endif
va_list args;
va_start(args, fmt);
// cppcheck-suppress wrongPrintfScanfArgNum
vsnprintf_P(fmtBuffer, sizeof(fmtBuffer), fmt, args);
#ifdef MY_GATEWAY_SERIAL
// Truncate message if this is gateway node
@@ -162,6 +164,9 @@ void hwDebugPrint(const char *fmt, ...)
fmtBuffer[sizeof(fmtBuffer) - 1] = '\0';
#endif
va_end(args);
MY_SERIALDEVICE.print(fmtBuffer);
MY_SERIALDEVICE.flush();
MY_DEBUGDEVICE.print(fmtBuffer);
MY_DEBUGDEVICE.flush();
#else
(void)fmt;
#endif
}

View File

@@ -47,7 +47,13 @@
#define CRYPTO_LITTLE_ENDIAN
#ifndef MY_SERIALDEVICE
#define MY_SERIALDEVICE Serial
#endif
#ifndef MY_DEBUGDEVICE
#define MY_DEBUGDEVICE MY_SERIALDEVICE
#endif
#define MY_EEPROM_SIZE 1024

View File

@@ -25,6 +25,9 @@ bool hwInit(void)
#if !defined(MY_DISABLED_SERIAL)
MY_SERIALDEVICE.begin(MY_BAUD_RATE, SERIAL_8N1, MY_ESP8266_SERIAL_MODE, 1);
MY_SERIALDEVICE.setDebugOutput(true);
#if defined(MY_GATEWAY_SERIAL)
while (!MY_SERIALDEVICE) {}
#endif
#endif
EEPROM.begin(EEPROM_size);
return true;
@@ -32,7 +35,7 @@ bool hwInit(void)
void hwReadConfigBlock(void *buf, void *addr, size_t length)
{
uint8_t* dst = static_cast<uint8_t*>(buf);
uint8_t *dst = static_cast<uint8_t *>(buf);
int pos = reinterpret_cast<int>(addr);
while (length-- > 0) {
*dst++ = EEPROM.read(pos++);
@@ -41,7 +44,7 @@ void hwReadConfigBlock(void *buf, void *addr, size_t length)
void hwWriteConfigBlock(void *buf, void *addr, size_t length)
{
uint8_t* src = static_cast<uint8_t*>(buf);
uint8_t *src = static_cast<uint8_t *>(buf);
int pos = reinterpret_cast<int>(addr);
while (length-- > 0) {
EEPROM.write(pos++, *src++);
@@ -53,23 +56,23 @@ void hwWriteConfigBlock(void *buf, void *addr, size_t length)
uint8_t hwReadConfig(const int addr)
{
uint8_t value;
hwReadConfigBlock(&value, reinterpret_cast<void*>(addr), 1);
hwReadConfigBlock(&value, reinterpret_cast<void *>(addr), 1);
return value;
}
void hwWriteConfig(const int addr, uint8_t value)
{
hwWriteConfigBlock(&value, reinterpret_cast<void*>(addr), 1);
hwWriteConfigBlock(&value, reinterpret_cast<void *>(addr), 1);
}
bool hwUniqueID(unique_id_t *uniqueID)
{
// padding
(void)memset((uint8_t*)uniqueID, MY_HWID_PADDING_BYTE, sizeof(unique_id_t));
(void)memset((uint8_t *)uniqueID, MY_HWID_PADDING_BYTE, sizeof(unique_id_t));
uint32_t val = ESP.getChipId();
(void)memcpy((uint8_t*)uniqueID, &val, 4);
(void)memcpy((uint8_t *)uniqueID, &val, 4);
val = ESP.getFlashChipId();
(void)memcpy((uint8_t*)uniqueID + 4, &val, 4);
(void)memcpy((uint8_t *)uniqueID + 4, &val, 4);
return true;
}
@@ -142,6 +145,11 @@ uint16_t hwCPUFrequency(void)
return ESP.getCpuFreqMHz()*10;
}
int8_t hwCPUTemperature(void)
{
return -127;
}
uint16_t hwFreeMem(void)
{
return ESP.getFreeHeap();
@@ -149,9 +157,6 @@ uint16_t hwFreeMem(void)
void hwDebugPrint(const char *fmt, ... )
{
#ifndef MY_DEBUGDEVICE
#define MY_DEBUGDEVICE MY_SERIALDEVICE
#endif
#ifndef MY_DISABLED_SERIAL
char fmtBuffer[MY_SERIAL_OUTPUT_SIZE];
#ifdef MY_GATEWAY_SERIAL
@@ -165,7 +170,7 @@ void hwDebugPrint(const char *fmt, ... )
MY_DEBUGDEVICE.print(" ");
#endif
va_list args;
va_start (args, fmt );
va_start(args, fmt);
// cppcheck-suppress wrongPrintfScanfArgNum
vsnprintf_P(fmtBuffer, sizeof(fmtBuffer), fmt, args);
#ifdef MY_GATEWAY_SERIAL
@@ -173,7 +178,7 @@ void hwDebugPrint(const char *fmt, ... )
fmtBuffer[sizeof(fmtBuffer) - 2] = '\n';
fmtBuffer[sizeof(fmtBuffer) - 1] = '\0';
#endif
va_end (args);
va_end(args);
MY_DEBUGDEVICE.print(fmtBuffer);
MY_DEBUGDEVICE.flush();
#else

View File

@@ -29,6 +29,10 @@
#define MY_SERIALDEVICE Serial
#endif
#ifndef MY_DEBUGDEVICE
#define MY_DEBUGDEVICE MY_SERIALDEVICE
#endif
#define EEPROM_size (1024)
// Define these as macros to save valuable space

View File

@@ -147,6 +147,11 @@ uint16_t hwCPUFrequency(void)
return FUNCTION_NOT_SUPPORTED;
}
int8_t hwCPUTemperature(void)
{
return -127;
}
uint16_t hwFreeMem(void)
{
// TODO: Not supported!

View File

@@ -18,13 +18,13 @@
*/
/**
* @file MyHw.h
* @file MyHwHAL.h
*
* MySensors hardware abstraction layer
*/
#ifndef MyHw_h
#define MyHw_h
#ifndef MyHwHAL_h
#define MyHwHAL_h
/**
* @def MY_HWID_PADDING_BYTE
@@ -93,7 +93,7 @@ int8_t hwSleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mo
* @param uniqueID unique ID
* @return True if unique ID successfully retrieved
*/
bool hwUniqueID(unique_id_t* uniqueID);
bool hwUniqueID(unique_id_t *uniqueID);
/**
* CPU voltage
@@ -107,6 +107,12 @@ uint16_t hwCPUVoltage(void);
*/
uint16_t hwCPUFrequency(void);
/**
* Non-calibrated CPU temperature (if available)
* @return CPU temperature in °C
*/
int8_t hwCPUTemperature(void);
/**
* Free memory
* @return free memory in bytes

View File

@@ -33,11 +33,11 @@ volatile uint8_t _wakeUp1Interrupt =
volatile uint8_t _wakeUp2Interrupt =
INVALID_INTERRUPT_NUM; // Interrupt number for wakeUp2-callback.
void wakeUp1() // place to send the interrupts
void wakeUp1(void) // place to send the interrupts
{
_wokeUpByInterrupt = _wakeUp1Interrupt;
}
void wakeUp2() // place to send the second interrupts
void wakeUp2(void) // place to send the second interrupts
{
_wokeUpByInterrupt = _wakeUp2Interrupt;
}
@@ -522,10 +522,15 @@ uint16_t hwCPUFrequency(void)
#elif defined(F_CPU)
return (F_CPU) / 100000UL;
#else
return 16;
return 160;
#endif
}
int8_t hwCPUTemperature(void)
{
return -127; // not implemented yet
}
uint16_t hwFreeMem(void)
{
// TODO: Not supported!
@@ -534,9 +539,6 @@ uint16_t hwFreeMem(void)
void hwDebugPrint(const char *fmt, ...)
{
#ifndef MY_DEBUGDEVICE
#define MY_DEBUGDEVICE MY_SERIALDEVICE
#endif
#ifndef MY_DISABLED_SERIAL
char fmtBuffer[MY_SERIAL_OUTPUT_SIZE];
#ifdef MY_GATEWAY_SERIAL
@@ -550,14 +552,14 @@ void hwDebugPrint(const char *fmt, ...)
MY_DEBUGDEVICE.print(F(" "));
#endif
va_list args;
va_start (args, fmt );
va_start(args, fmt);
vsnprintf(fmtBuffer, sizeof(fmtBuffer), fmt, args);
#ifdef MY_GATEWAY_SERIAL
// Truncate message if this is gateway node
fmtBuffer[sizeof(fmtBuffer) - 2] = '\n';
fmtBuffer[sizeof(fmtBuffer) - 1] = '\0';
#endif
va_end (args);
va_end(args);
MY_DEBUGDEVICE.print(fmtBuffer);
MY_DEBUGDEVICE.flush();
#else

View File

@@ -28,6 +28,14 @@
#define CRYPTO_LITTLE_ENDIAN
#ifndef MY_SERIALDEVICE
#define MY_SERIALDEVICE Serial
#endif
#ifndef MY_DEBUGDEVICE
#define MY_DEBUGDEVICE MY_SERIALDEVICE
#endif
// Define NRF5_SOFTDEVICE when SoftDevice found
#if defined(S110) || defined(S130) || defined(S132) || defined(S140)
#ifndef SOFTDEVICE_PRESENT
@@ -40,8 +48,9 @@
#define ARDUINO_ARCH_NRF5
#endif
#include "drivers/NRF5/nrf5_wiring_digital.c"
#include "drivers/NRF5/wdt.h"
#include "hal/architecture/NRF5/drivers/nrf5_wiring_digital.c"
#include "hal/architecture/NRF5/drivers/wdt.h"
#include "hal/architecture/NRF5/drivers/nrf_temp.h"
#include "drivers/NVM/NVRAM.h"
#include "drivers/NVM/VirtualPage.h"
#include <avr/dtostrf.h>
@@ -116,10 +125,6 @@ void hwRandomNumberInit(void);
ssize_t hwGetentropy(void *__buffer, size_t __length);
#define MY_HW_HAS_GETENTROPY
#ifndef MY_SERIALDEVICE
#define MY_SERIALDEVICE Serial
#endif
/**
* Disable all interrupts.
* Helper function for MY_CRITICAL_SECTION.

View File

@@ -0,0 +1,78 @@
/*
* Copyright (c) 2012 - 2018, Nordic Semiconductor ASA
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef NRF_TEMP_H__
#define NRF_TEMP_H__
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup nrf_temp_hal TEMP HAL
* @{
* @ingroup nrf_temp temperature_example
* @brief Temperature module init and read functions.
*/
#define MASK_SIGN (0x00000200UL) //!< MASK_SIGN
#define MASK_SIGN_EXTENSION (0xFFFFFC00UL) //!< MASK_SIGN_EXTENSION
/**
* @brief Function for preparing the temp module for temperature measurement.
*
* This function initializes the TEMP module and writes to the hidden configuration register.
*/
static __INLINE void nrf_temp_init(void)
{
/**@note Workaround for PAN_028 rev2.0A anomaly 31 - TEMP: Temperature offset value has to be manually loaded to the TEMP module */
*(uint32_t *) 0x4000C504 = 0;
}
/**
* @brief Function for reading temperature measurement.
*
* The function reads the 10 bit 2's complement value and transforms it to a 32 bit 2's complement value.
*/
static __INLINE int32_t nrf_temp_read(void)
{
/**@note Workaround for PAN_028 rev2.0A anomaly 28 - TEMP: Negative measured values are not represented correctly */
return ((NRF_TEMP->TEMP & MASK_SIGN) != 0) ? (int32_t)(NRF_TEMP->TEMP | MASK_SIGN_EXTENSION) :
(NRF_TEMP->TEMP);
}
/** @} */
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -19,7 +19,6 @@
#include "MyHwSAMD.h"
/*
int8_t pinIntTrigger = 0;
void wakeUp() //place to send the interrupts
@@ -43,14 +42,14 @@ ISR (WDT_vect)
void hwReadConfigBlock(void *buf, void *addr, size_t length)
{
uint8_t* dst = static_cast<uint8_t*>(buf);
uint8_t *dst = static_cast<uint8_t *>(buf);
const int offs = reinterpret_cast<int>(addr);
(void)eep.read(offs, dst, length);
}
void hwWriteConfigBlock(void *buf, void *addr, size_t length)
{
uint8_t* src = static_cast<uint8_t*>(buf);
uint8_t *src = static_cast<uint8_t *>(buf);
const int offs = reinterpret_cast<int>(addr);
// use update() instead of write() to reduce e2p wear off
(void)eep.update(offs, src, length);
@@ -68,12 +67,13 @@ void hwWriteConfig(const int addr, uint8_t value)
bool hwInit(void)
{
#if !defined(MY_DISABLED_SERIAL)
MY_SERIALDEVICE.begin(MY_BAUD_RATE);
#if defined(MY_GATEWAY_SERIAL)
while (!MY_SERIALDEVICE) {}
#endif
const uint8_t eepInit = eep.begin(MY_EXT_EEPROM_TWI_CLOCK);
#endif
const uint8_t eepInit = eep.begin(MY_EXT_EEPROM_TWI_CLOCK, &Wire);
#if defined(SENSEBENDER_GW_SAMD_V1)
// check connection to external EEPROM - only sensebender GW
return eepInit==0;
@@ -129,40 +129,44 @@ bool hwUniqueID(unique_id_t *uniqueID)
return true;
}
// Wait for synchronization of registers between the clock domains
static __inline__ void syncADC() __attribute__((always_inline, unused));
static void syncADC()
{
while (ADC->STATUS.bit.SYNCBUSY);
}
uint16_t hwCPUVoltage(void)
{
// disable ADC
while (ADC->STATUS.bit.SYNCBUSY);
ADC->CTRLA.bit.ENABLE = 0x00;
// internal 1V reference (default)
analogReference(AR_INTERNAL1V0);
// 12 bit resolution (default)
analogWriteResolution(12);
// MUXp 0x1B = SCALEDIOVCC/4 => connected to Vcc
ADC->INPUTCTRL.bit.MUXPOS = 0x1B ;
// Set ADC reference to internal 1v
ADC->INPUTCTRL.bit.GAIN = ADC_INPUTCTRL_GAIN_1X_Val;
ADC->REFCTRL.bit.REFSEL = ADC_REFCTRL_REFSEL_INT1V_Val;
syncADC();
// Set to 10 bits reading resolution
ADC->CTRLB.reg = ADC_CTRLB_RESSEL_10BIT | ADC_CTRLB_PRESCALER_DIV256;
syncADC();
// Select MUXPOS as SCALEDIOVCC/4 channel, and MUXNEG as internal ground
ADC->INPUTCTRL.bit.MUXPOS = ADC_INPUTCTRL_MUXPOS_SCALEDIOVCC_Val;
ADC->INPUTCTRL.bit.MUXNEG = ADC_INPUTCTRL_MUXNEG_GND_Val;
syncADC();
// enable ADC
while (ADC->STATUS.bit.SYNCBUSY);
ADC->CTRLA.bit.ENABLE = 0x01;
ADC->CTRLA.bit.ENABLE = 1;
syncADC();
// start conversion
while (ADC->STATUS.bit.SYNCBUSY);
ADC->SWTRIG.bit.START = 1;
// clear the Data Ready flag
ADC->INTFLAG.bit.RESRDY = 1;
syncADC();
// start conversion again, since The first conversion after the reference is changed must not be used.
while (ADC->STATUS.bit.SYNCBUSY);
ADC->SWTRIG.bit.START = 1;
// waiting for conversion to complete
while (!ADC->INTFLAG.bit.RESRDY);
syncADC();
const uint32_t valueRead = ADC->RESULT.reg;
// disable ADC
while (ADC->STATUS.bit.SYNCBUSY);
ADC->CTRLA.bit.ENABLE = 0x00;
ADC->CTRLA.bit.ENABLE = 0;
syncADC();
// value is 1/4 scaled, multiply by 4
return valueRead * 4;
}
@@ -172,6 +176,12 @@ uint16_t hwCPUFrequency(void)
return F_CPU / 100000UL;
}
int8_t hwCPUTemperature(void)
{
return -127; // not implemented yet
}
uint16_t hwFreeMem(void)
{
// TODO: Not supported!
@@ -180,9 +190,6 @@ uint16_t hwFreeMem(void)
void hwDebugPrint(const char *fmt, ... )
{
#ifndef MY_DEBUGDEVICE
#define MY_DEBUGDEVICE MY_SERIALDEVICE
#endif
#ifndef MY_DISABLED_SERIAL
if (MY_DEBUGDEVICE) {
char fmtBuffer[MY_SERIAL_OUTPUT_SIZE];
@@ -197,14 +204,14 @@ void hwDebugPrint(const char *fmt, ... )
MY_DEBUGDEVICE.print(" ");
#endif
va_list args;
va_start (args, fmt );
va_start(args, fmt);
vsnprintf(fmtBuffer, sizeof(fmtBuffer), fmt, args);
#ifdef MY_GATEWAY_SERIAL
// Truncate message if this is gateway node
fmtBuffer[sizeof(fmtBuffer) - 2] = '\n';
fmtBuffer[sizeof(fmtBuffer) - 1] = '\0';
#endif
va_end (args);
va_end(args);
MY_DEBUGDEVICE.print(fmtBuffer);
// MY_SERIALDEVICE.flush();
}

View File

@@ -27,15 +27,24 @@
#define CRYPTO_LITTLE_ENDIAN
#ifndef MY_SERIALDEVICE
#define MY_SERIALDEVICE SerialUSB
#endif
#ifndef MY_DEBUGDEVICE
#define MY_DEBUGDEVICE MY_SERIALDEVICE
#endif
// defines for sensebender gw variant.h
#define MY_EXT_EEPROM_I2C_ADDRESS (0x50u)
#define MY_EXT_EEPROM_SIZE (kbits_512)
#define MY_EXT_EEPROM_PAGE_SIZE (32u)
#define MY_EXT_EEPROM_TWI_CLOCK (twiClock100kHz) // can be set to 400kHz with precaution if other i2c devices on bus
extEEPROM eep(MY_EXT_EEPROM_SIZE, 1, MY_EXT_EEPROM_PAGE_SIZE,
MY_EXT_EEPROM_I2C_ADDRESS); //device size, number of devices, page size
#define MY_EXT_EEPROM_TWI_CLOCK (eep.twiClock100kHz) // can be set to 400kHz with precaution if other i2c devices on bus
#define snprintf_P(s, f, ...) snprintf((s), (f), __VA_ARGS__)
#define vsnprintf_P(s, n, f, ...) vsnprintf((s), (n), (f), __VA_ARGS__)
@@ -49,15 +58,11 @@ extEEPROM eep(MY_EXT_EEPROM_SIZE, 1, MY_EXT_EEPROM_PAGE_SIZE,
bool hwInit(void);
void hwWatchdogReset(void);
void hwReboot(void);
void hwReadConfigBlock(void *buf, void * addr, size_t length);
void hwWriteConfigBlock(void *buf, void * addr, size_t length);
void hwReadConfigBlock(void *buf, void *addr, size_t length);
void hwWriteConfigBlock(void *buf, void *addr, size_t length);
void hwWriteConfig(const int addr, uint8_t value);
uint8_t hwReadConfig(const int addr);
#ifndef MY_SERIALDEVICE
#define MY_SERIALDEVICE SerialUSB
#endif
/**
* Disable all interrupts.
* Helper function for MY_CRITICAL_SECTION.

View File

@@ -46,7 +46,12 @@ bool hwInit(void)
{
#if !defined(MY_DISABLED_SERIAL)
MY_SERIALDEVICE.begin(MY_BAUD_RATE);
#if defined(MY_GATEWAY_SERIAL)
while (!MY_SERIALDEVICE) {}
#endif
#endif
adc_calibrate(ADC1);
if (EEPROM.init() == EEPROM_OK) {
uint16 cnt;
EEPROM.count(&cnt);
@@ -61,7 +66,7 @@ bool hwInit(void)
void hwReadConfigBlock(void *buf, void *addr, size_t length)
{
uint8_t *dst = static_cast<uint8_t*>(buf);
uint8_t *dst = static_cast<uint8_t *>(buf);
int pos = reinterpret_cast<int>(addr);
while (length-- > 0) {
*dst++ = EEPROM.read(pos++);
@@ -70,7 +75,7 @@ void hwReadConfigBlock(void *buf, void *addr, size_t length)
void hwWriteConfigBlock(void *buf, void *addr, size_t length)
{
uint8_t *src = static_cast<uint8_t*>(buf);
uint8_t *src = static_cast<uint8_t *>(buf);
int pos = reinterpret_cast<int>(addr);
while (length-- > 0) {
EEPROM.write(pos++, *src++);
@@ -80,13 +85,13 @@ void hwWriteConfigBlock(void *buf, void *addr, size_t length)
uint8_t hwReadConfig(const int addr)
{
uint8_t value;
hwReadConfigBlock(&value, reinterpret_cast<void*>(addr), 1);
hwReadConfigBlock(&value, reinterpret_cast<void *>(addr), 1);
return value;
}
void hwWriteConfig(const int addr, uint8_t value)
{
hwWriteConfigBlock(&value, reinterpret_cast<void*>(addr), 1);
hwWriteConfigBlock(&value, reinterpret_cast<void *>(addr), 1);
}
int8_t hwSleep(uint32_t ms)
@@ -129,7 +134,7 @@ void hwRandomNumberInit(void)
uint16_t currentValue = 0;
uint16_t newValue = 0;
for (uint8_t i = 0; i<32; i++) {
for (uint8_t i = 0; i < 32; i++) {
const uint32_t timeout = hwMillis() + 20;
while (timeout >= hwMillis()) {
newValue = adc_read(ADC1, 16);
@@ -143,17 +148,17 @@ void hwRandomNumberInit(void)
randomSeed(seed);
}
bool hwUniqueID(unique_id_t* uniqueID)
bool hwUniqueID(unique_id_t *uniqueID)
{
(void)memcpy((uint8_t*)uniqueID, (uint32_t*)0x1FFFF7E0, 16);
(void)memcpy((uint8_t *)uniqueID, (uint32_t *)0x1FFFF7E0, 16); // FlashID + ChipID
return true;
}
uint16_t hwCPUVoltage(void)
{
adc_reg_map *regs = ADC1->regs;
regs->CR2 |= ADC_CR2_TSVREFE; // enable VREFINT and temp sensor
regs->SMPR1 = ADC_SMPR1_SMP17; // sample rate for VREFINT ADC channel
regs->CR2 |= ADC_CR2_TSVREFE; // enable VREFINT and temp sensor
regs->SMPR1 = ADC_SMPR1_SMP17; // sample rate for VREFINT ADC channel
return 1200 * 4096 / adc_read(ADC1, 17);
}
@@ -162,6 +167,11 @@ uint16_t hwCPUFrequency(void)
return F_CPU/100000UL;
}
int8_t hwCPUTemperature(void)
{
return -127; // not implemented yet
}
uint16_t hwFreeMem(void)
{
//Not yet implemented
@@ -170,9 +180,6 @@ uint16_t hwFreeMem(void)
void hwDebugPrint(const char *fmt, ...)
{
#ifndef MY_DEBUGDEVICE
#define MY_DEBUGDEVICE MY_SERIALDEVICE
#endif
#ifndef MY_DISABLED_SERIAL
char fmtBuffer[MY_SERIAL_OUTPUT_SIZE];
#ifdef MY_GATEWAY_SERIAL
@@ -183,7 +190,7 @@ void hwDebugPrint(const char *fmt, ...)
#else
// prepend timestamp
MY_DEBUGDEVICE.print(hwMillis());
MY_DEBUGDEVICE.print(" ");
MY_DEBUGDEVICE.print(F(" "));
#endif
va_list args;
va_start(args, fmt);

View File

@@ -29,6 +29,14 @@
#define CRYPTO_LITTLE_ENDIAN
#ifndef MY_SERIALDEVICE
#define MY_SERIALDEVICE Serial
#endif
#ifndef MY_DEBUGDEVICE
#define MY_DEBUGDEVICE MY_SERIALDEVICE
#endif
// SS default
#ifndef SS
#define SS PA4
@@ -41,10 +49,6 @@
#define printf_P printf
#define yield() // not defined
#ifndef MY_SERIALDEVICE
#define MY_SERIALDEVICE Serial
#endif
#ifndef digitalPinToInterrupt
#define digitalPinToInterrupt(__pin) (__pin)
#endif

View File

@@ -42,9 +42,11 @@ ISR (WDT_vect)
bool hwInit(void)
{
#if !defined(MY_DISABLED_SERIAL)
MY_SERIALDEVICE.begin(MY_BAUD_RATE);
#if defined(MY_GATEWAY_SERIAL)
while (!MY_SERIALDEVICE) {}
#endif
#endif
return true;
}
@@ -91,10 +93,10 @@ int8_t hwSleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mo
bool hwUniqueID(unique_id_t *uniqueID)
{
#if defined(__MKL26Z64__)
(void)memcpy((uint8_t*)uniqueID, &SIM_UIDMH, 12);
(void)memset((uint8_t*)uniqueID + 12, MY_HWID_PADDING_BYTE, 4);
(void)memcpy((uint8_t *)uniqueID, &SIM_UIDMH, 12);
(void)memset((uint8_t *)uniqueID + 12, MY_HWID_PADDING_BYTE, 4);
#else
(void)memcpy((uint8_t*)uniqueID, &SIM_UIDH, 16);
(void)memcpy((uint8_t *)uniqueID, &SIM_UIDH, 16);
#endif
return true;
}
@@ -126,6 +128,11 @@ uint16_t hwCPUFrequency(void)
return F_CPU / 100000UL;
}
int8_t hwCPUTemperature(void)
{
return -127; // not implemented yet
}
uint16_t hwFreeMem(void)
{
// TODO: Not supported!
@@ -144,7 +151,7 @@ ssize_t hwGetentropy(void *__buffer, const size_t __length)
while (!(RNG_SR & RNG_SR_OREG_LVL(0xF)));
const uint32_t rndVar = RNG_OR;
const uint8_t bsize = (__length - pos) > sizeof(rndVar) ? sizeof(rndVar) : (__length - pos);
(void)memcpy((uint8_t*)__buffer + pos, &rndVar, bsize);
(void)memcpy((uint8_t *)__buffer + pos, &rndVar, bsize);
pos += bsize;
}
SIM_SCGC6 &= ~SIM_SCGC6_RNGA; // disable RNG
@@ -167,9 +174,6 @@ void hwRandomNumberInit(void)
void hwDebugPrint(const char *fmt, ...)
{
#ifndef MY_DEBUGDEVICE
#define MY_DEBUGDEVICE MY_SERIALDEVICE
#endif
#ifndef MY_DISABLED_SERIAL
char fmtBuffer[MY_SERIAL_OUTPUT_SIZE];
#ifdef MY_GATEWAY_SERIAL

View File

@@ -39,6 +39,10 @@
#define MY_SERIALDEVICE Serial
#endif
#ifndef MY_DEBUGDEVICE
#define MY_DEBUGDEVICE MY_SERIALDEVICE
#endif
#if defined(__MK64FX512__) || defined(__MK66FX1M0__)
#define RNG_CR_GO_MASK 0x1u
#define RNG_CR_HA_MASK 0x2u

View File

@@ -19,8 +19,8 @@
* version 2 as published by the Free Software Foundation.
*/
#include "drivers/NRF5/Radio.h"
#include "drivers/NRF5/Radio_ESB.h"
#include "hal/transport/NRF5_ESB/driver/Radio.h"
#include "hal/transport/NRF5_ESB/driver/Radio_ESB.h"
#include "drivers/CircularBuffer/CircularBuffer.h"

View File

@@ -1,4 +1,4 @@
#include "drivers/NRF5/Radio.h"
#include "Radio.h"
int16_t NRF5_getTxPowerPercent(void)
{

View File

@@ -1,4 +1,3 @@

/*
* The MySensors Arduino library handles the wireless radio link and protocol
* between your home built sensors/actuators and HA controller of choice.

View File

@@ -17,7 +17,7 @@
* version 2 as published by the Free Software Foundation.
*/
#include "drivers/RF24/RF24.h"
#include "hal/transport/RF24/driver/RF24.h"
#if defined(MY_RF24_ENABLE_ENCRYPTION)
#include "drivers/AES/AES.cpp"

View File

@@ -19,7 +19,7 @@
#if defined(MY_RFM69_NEW_DRIVER)
#include "drivers/RFM69/new/RFM69_new.h"
#include "hal/transport/RFM69/driver/new/RFM69_new.h"
bool transportInit(void)
{
@@ -154,7 +154,7 @@ bool transportSetTxPowerPercent(const uint8_t powerPercent)
#else
#include "drivers/RFM69/old/RFM69_old.h"
#include "hal/transport/RFM69/driver/old/RFM69_old.h"
RFM69 _radio(MY_RFM69_CS_PIN, MY_RFM69_IRQ_PIN, MY_RFM69HW, MY_RFM69_IRQ_NUM);
uint8_t _address;

View File

@@ -74,7 +74,7 @@ LOCAL void RFM69_concludeSPITransaction(void)
#endif
}
LOCAL uint8_t RFM69_spiMultiByteTransfer(const uint8_t cmd, uint8_t* buf, uint8_t len,
LOCAL uint8_t RFM69_spiMultiByteTransfer(const uint8_t cmd, uint8_t *buf, uint8_t len,
const bool aReadMode)
{
uint8_t status;

View File

@@ -400,7 +400,7 @@ void RFM69::sendFrame(uint8_t toAddress, const void* buffer, uint8_t bufferSize,
SPI.transfer(CTLbyte);
for (uint8_t i = 0; i < bufferSize; i++) {
SPI.transfer(((uint8_t*) buffer)[i]);
SPI.transfer(((uint8_t *)buffer)[i]);
}
unselect();

View File

@@ -17,7 +17,7 @@
* version 2 as published by the Free Software Foundation.
*/
#include "drivers/RFM95/RFM95.h"
#include "hal/transport/RFM95/driver/RFM95.h"
#if defined(MY_RFM95_ENABLE_ENCRYPTION)
#include "drivers/AES/AES.h"
#endif
@@ -36,15 +36,15 @@ bool transportInit(void)
#if defined(MY_RFM95_ENABLE_ENCRYPTION)
uint8_t RFM95_psk[16];
#ifdef MY_SIGNING_SIMPLE_PASSWD
memset(RFM95_psk, 0, 16);
memcpy(RFM95_psk, MY_SIGNING_SIMPLE_PASSWD, strnlen(MY_SIGNING_SIMPLE_PASSWD, 16));
(void)memset((void *)RFM95_psk, 0, 16);
(void)memcpy((void *)RFM95_psk, MY_SIGNING_SIMPLE_PASSWD, strnlen(MY_SIGNING_SIMPLE_PASSWD, 16));
#else
hwReadConfigBlock((void*)RFM95_psk, (void*)EEPROM_RF_ENCRYPTION_AES_KEY_ADDRESS, 16);
hwReadConfigBlock((void *)RFM95_psk, (void *)EEPROM_RF_ENCRYPTION_AES_KEY_ADDRESS, 16);
#endif
//set up AES-key
RFM95_aes.set_key(RFM95_psk, 16);
// Make sure it is purged from memory when set
memset(RFM95_psk, 0, 16);
(void)memset((void *)RFM95_psk, 0, 16);
#endif
const bool result = RFM95_initialise(MY_RFM95_FREQUENCY);
@@ -72,12 +72,12 @@ bool transportSend(const uint8_t to, const void *data, const uint8_t len, const
{
#if defined(MY_RFM95_ENABLE_ENCRYPTION)
// copy input data because it is read-only
(void)memcpy(RFM95_dataenc,data,len);
(void)memcpy((void *)RFM95_dataenc, (const void *)data, len);
// has to be adjusted, WIP!
RFM95_aes.set_IV(0);
const uint8_t finalLength = len > 16 ? 32 : 16;
//encrypt data
RFM95_aes.cbc_encrypt(RFM95_dataenc, RFM95_dataenc, finalLength /16);
RFM95_aes.cbc_encrypt(RFM95_dataenc, RFM95_dataenc, finalLength / 16);
if (noACK) {
(void)RFM95_sendWithRetry(to, RFM95_dataenc, finalLength, 0, 0);
return true;
@@ -105,12 +105,12 @@ bool transportSanityCheck(void)
uint8_t transportReceive(void *data)
{
uint8_t len = RFM95_receive((uint8_t*)data, MAX_MESSAGE_LENGTH);
uint8_t len = RFM95_receive((uint8_t *)data, MAX_MESSAGE_LENGTH);
#if defined(MY_RFM95_ENABLE_ENCRYPTION)
// has to be adjusted, WIP!
RFM95_aes.set_IV(0);
// decrypt data
if (RFM95_aes.cbc_decrypt((uint8_t*)(data), (uint8_t*)(data), len > 16 ? 2 : 1) != AES_SUCCESS) {
if (RFM95_aes.cbc_decrypt((uint8_t *)data, (uint8_t *)data, len > 16 ? 2 : 1) != AES_SUCCESS) {
len = 0;
}
#endif

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