diff --git a/src/DallasTemperature/DallasTemperature.cpp b/src/DallasTemperature/DallasTemperature.cpp new file mode 100644 index 0000000..8febea5 --- /dev/null +++ b/src/DallasTemperature/DallasTemperature.cpp @@ -0,0 +1,1033 @@ +// 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. + +#include "DallasTemperature.h" + +#if ARDUINO >= 100 +#include "Arduino.h" +#else +extern "C" { +#include "WConstants.h" +} +#endif + +// OneWire commands +#define STARTCONVO 0x44 // Tells device to take a temperature reading and put it on the scratchpad +#define COPYSCRATCH 0x48 // Copy scratchpad to EEPROM +#define READSCRATCH 0xBE // Read from scratchpad +#define WRITESCRATCH 0x4E // Write to scratchpad +#define RECALLSCRATCH 0xB8 // Recall from EEPROM to scratchpad +#define READPOWERSUPPLY 0xB4 // Determine if device needs parasite power +#define ALARMSEARCH 0xEC // Query bus for devices with an alarm condition + +// Scratchpad locations +#define TEMP_LSB 0 +#define TEMP_MSB 1 +#define HIGH_ALARM_TEMP 2 +#define LOW_ALARM_TEMP 3 +#define CONFIGURATION 4 +#define INTERNAL_BYTE 5 +#define COUNT_REMAIN 6 +#define COUNT_PER_C 7 +#define SCRATCHPAD_CRC 8 + +// DSROM FIELDS +#define DSROM_FAMILY 0 +#define DSROM_CRC 7 + +// Device resolution +#define TEMP_9_BIT 0x1F // 9 bit +#define TEMP_10_BIT 0x3F // 10 bit +#define TEMP_11_BIT 0x5F // 11 bit +#define TEMP_12_BIT 0x7F // 12 bit + +#define MAX_CONVERSION_TIMEOUT 750 + +// Alarm handler +#define NO_ALARM_HANDLER ((AlarmHandler *)0) + + +DallasTemperature::DallasTemperature() { +#if REQUIRESALARMS + setAlarmHandler(NO_ALARM_HANDLER); +#endif + useExternalPullup = false; +} + +DallasTemperature::DallasTemperature(OneWire* _oneWire) : DallasTemperature() { + setOneWire(_oneWire); +} + +bool DallasTemperature::validFamily(const uint8_t* deviceAddress) { + switch (deviceAddress[DSROM_FAMILY]) { + case DS18S20MODEL: + case DS18B20MODEL: + case DS1822MODEL: + case DS1825MODEL: + case DS28EA00MODEL: + return true; + default: + return false; + } +} + +/* + * Constructs DallasTemperature with strong pull-up turned on. Strong pull-up is mandated in DS18B20 datasheet for parasitic + * power (2 wires) setup. (https://datasheets.maximintegrated.com/en/ds/DS18B20.pdf, p. 7, section 'Powering the DS18B20'). + */ +DallasTemperature::DallasTemperature(OneWire* _oneWire, uint8_t _pullupPin) : DallasTemperature(_oneWire) { + setPullupPin(_pullupPin); +} + +void DallasTemperature::setPullupPin(uint8_t _pullupPin) { + useExternalPullup = true; + pullupPin = _pullupPin; + pinMode(pullupPin, OUTPUT); + deactivateExternalPullup(); +} + +void DallasTemperature::setOneWire(OneWire* _oneWire) { + + _wire = _oneWire; + devices = 0; + ds18Count = 0; + parasite = false; + bitResolution = 9; + waitForConversion = true; + checkForConversion = true; + autoSaveScratchPad = true; + +} + +// initialise the bus +void DallasTemperature::begin(void) { + + DeviceAddress deviceAddress; + + _wire->reset_search(); + devices = 0; // Reset the number of devices when we enumerate wire devices + ds18Count = 0; // Reset number of DS18xxx Family devices + + while (_wire->search(deviceAddress)) { + + if (validAddress(deviceAddress)) { + devices++; + + if (validFamily(deviceAddress)) { + ds18Count++; + + if (!parasite && readPowerSupply(deviceAddress)) + parasite = true; + + uint8_t b = getResolution(deviceAddress); + if (b > bitResolution) bitResolution = b; + } + } + } +} + +// returns the number of devices found on the bus +uint8_t DallasTemperature::getDeviceCount(void) { + return devices; +} + +uint8_t DallasTemperature::getDS18Count(void) { + return ds18Count; +} + +// returns true if address is valid +bool DallasTemperature::validAddress(const uint8_t* deviceAddress) { + return (_wire->crc8(deviceAddress, 7) == deviceAddress[DSROM_CRC]); +} + +// finds an address at a given index on the bus +// returns true if the device was found +bool DallasTemperature::getAddress(uint8_t* deviceAddress, uint8_t index) { + + uint8_t depth = 0; + + _wire->reset_search(); + + while (depth <= index && _wire->search(deviceAddress)) { + if (depth == index && validAddress(deviceAddress)) + return true; + depth++; + } + + return false; + +} + +// attempt to determine if the device at the given address is connected to the bus +bool DallasTemperature::isConnected(const uint8_t* deviceAddress) { + + ScratchPad scratchPad; + return isConnected(deviceAddress, scratchPad); + +} + +// attempt to determine if the device at the given address is connected to the bus +// also allows for updating the read scratchpad +bool DallasTemperature::isConnected(const uint8_t* deviceAddress, + uint8_t* scratchPad) { + bool b = readScratchPad(deviceAddress, scratchPad); + return b && !isAllZeros(scratchPad) && (_wire->crc8(scratchPad, 8) == scratchPad[SCRATCHPAD_CRC]); +} + +bool DallasTemperature::readScratchPad(const uint8_t* deviceAddress, + uint8_t* scratchPad) { + + // send the reset command and fail fast + int b = _wire->reset(); + if (b == 0) + return false; + + _wire->select(deviceAddress); + _wire->write(READSCRATCH); + + // Read all registers in a simple loop + // byte 0: temperature LSB + // byte 1: temperature MSB + // byte 2: high alarm temp + // byte 3: low alarm temp + // byte 4: DS18S20: store for crc + // DS18B20 & DS1822: configuration register + // byte 5: internal use & crc + // byte 6: DS18S20: COUNT_REMAIN + // DS18B20 & DS1822: store for crc + // byte 7: DS18S20: COUNT_PER_C + // DS18B20 & DS1822: store for crc + // byte 8: SCRATCHPAD_CRC + for (uint8_t i = 0; i < 9; i++) { + scratchPad[i] = _wire->read(); + } + + b = _wire->reset(); + return (b == 1); +} + +void DallasTemperature::writeScratchPad(const uint8_t* deviceAddress, + const uint8_t* scratchPad) { + + _wire->reset(); + _wire->select(deviceAddress); + _wire->write(WRITESCRATCH); + _wire->write(scratchPad[HIGH_ALARM_TEMP]); // high alarm temp + _wire->write(scratchPad[LOW_ALARM_TEMP]); // low alarm temp + + // DS1820 and DS18S20 have no configuration register + if (deviceAddress[DSROM_FAMILY] != DS18S20MODEL) + _wire->write(scratchPad[CONFIGURATION]); + + if (autoSaveScratchPad) + saveScratchPad(deviceAddress); + else + _wire->reset(); +} + +// returns true if parasite mode is used (2 wire) +// returns false if normal mode is used (3 wire) +// if no address is given (or nullptr) it checks if any device on the bus +// uses parasite mode. +// See issue #145 +bool DallasTemperature::readPowerSupply(const uint8_t* deviceAddress) +{ + bool parasiteMode = false; + _wire->reset(); + if (deviceAddress == nullptr) + _wire->skip(); + else + _wire->select(deviceAddress); + + _wire->write(READPOWERSUPPLY); + if (_wire->read_bit() == 0) + parasiteMode = true; + _wire->reset(); + return parasiteMode; +} + +// set resolution of all devices to 9, 10, 11, or 12 bits +// if new resolution is out of range, it is constrained. +void DallasTemperature::setResolution(uint8_t newResolution) { + + bitResolution = constrain(newResolution, 9, 12); + DeviceAddress deviceAddress; + for (uint8_t i = 0; i < devices; i++) { + getAddress(deviceAddress, i); + setResolution(deviceAddress, bitResolution, true); + } +} + +/* PROPOSAL */ + +// set resolution of a device to 9, 10, 11, or 12 bits +// if new resolution is out of range, 9 bits is used. +bool DallasTemperature::setResolution(const uint8_t* deviceAddress, + uint8_t newResolution, bool skipGlobalBitResolutionCalculation) { + + bool success = false; + + // DS1820 and DS18S20 have no resolution configuration register + if (deviceAddress[DSROM_FAMILY] == DS18S20MODEL) + { + success = true; + } + else + { + + // handle the sensors with configuration register + newResolution = constrain(newResolution, 9, 12); + uint8_t newValue = 0; + ScratchPad scratchPad; + + // we can only update the sensor if it is connected + if (isConnected(deviceAddress, scratchPad)) + { + switch (newResolution) { + case 12: + newValue = TEMP_12_BIT; + break; + case 11: + newValue = TEMP_11_BIT; + break; + case 10: + newValue = TEMP_10_BIT; + break; + case 9: + default: + newValue = TEMP_9_BIT; + break; + } + + // if it needs to be updated we write the new value + if (scratchPad[CONFIGURATION] != newValue) + { + scratchPad[CONFIGURATION] = newValue; + writeScratchPad(deviceAddress, scratchPad); + } + // done + success = true; + } + } + + // do we need to update the max resolution used? + if (skipGlobalBitResolutionCalculation == false) + { + bitResolution = newResolution; + if (devices > 1) + { + for (uint8_t i = 0; i < devices; i++) + { + if (bitResolution == 12) break; + DeviceAddress deviceAddr; + getAddress(deviceAddr, i); + uint8_t b = getResolution(deviceAddr); + if (b > bitResolution) bitResolution = b; + } + } + } + + return success; +} + + +// returns the global resolution +uint8_t DallasTemperature::getResolution() { + return bitResolution; +} + +// returns the current resolution of the device, 9-12 +// returns 0 if device not found +uint8_t DallasTemperature::getResolution(const uint8_t* deviceAddress) { + + // DS1820 and DS18S20 have no resolution configuration register + if (deviceAddress[DSROM_FAMILY] == DS18S20MODEL) + return 12; + + ScratchPad scratchPad; + if (isConnected(deviceAddress, scratchPad)) { + switch (scratchPad[CONFIGURATION]) { + case TEMP_12_BIT: + return 12; + + case TEMP_11_BIT: + return 11; + + case TEMP_10_BIT: + return 10; + + case TEMP_9_BIT: + return 9; + } + } + return 0; + +} + + +// sets the value of the waitForConversion flag +// TRUE : function requestTemperature() etc returns when conversion is ready +// FALSE: function requestTemperature() etc returns immediately (USE WITH CARE!!) +// (1) programmer has to check if the needed delay has passed +// (2) but the application can do meaningful things in that time +void DallasTemperature::setWaitForConversion(bool flag) { + waitForConversion = flag; +} + +// gets the value of the waitForConversion flag +bool DallasTemperature::getWaitForConversion() { + return waitForConversion; +} + +// sets the value of the checkForConversion flag +// TRUE : function requestTemperature() etc will 'listen' to an IC to determine whether a conversion is complete +// FALSE: function requestTemperature() etc will wait a set time (worst case scenario) for a conversion to complete +void DallasTemperature::setCheckForConversion(bool flag) { + checkForConversion = flag; +} + +// gets the value of the waitForConversion flag +bool DallasTemperature::getCheckForConversion() { + return checkForConversion; +} + +bool DallasTemperature::isConversionComplete() { + uint8_t b = _wire->read_bit(); + return (b == 1); +} + +// sends command for all devices on the bus to perform a temperature conversion +void DallasTemperature::requestTemperatures() { + + _wire->reset(); + _wire->skip(); + _wire->write(STARTCONVO, parasite); + + // ASYNC mode? + if (!waitForConversion) + return; + blockTillConversionComplete(bitResolution); + +} + +// sends command for one device to perform a temperature by address +// returns FALSE if device is disconnected +// returns TRUE otherwise +bool DallasTemperature::requestTemperaturesByAddress( + const uint8_t* deviceAddress) { + + uint8_t bitResolution = getResolution(deviceAddress); + if (bitResolution == 0) { + return false; //Device disconnected + } + + _wire->reset(); + _wire->select(deviceAddress); + _wire->write(STARTCONVO, parasite); + + // ASYNC mode? + if (!waitForConversion) + return true; + + blockTillConversionComplete(bitResolution); + + return true; + +} + +// Continue to check if the IC has responded with a temperature +void DallasTemperature::blockTillConversionComplete(uint8_t bitResolution) { + + if (checkForConversion && !parasite) { + unsigned long start = millis(); + while (!isConversionComplete() && (millis() - start < MAX_CONVERSION_TIMEOUT )) + yield(); + } else { + unsigned long delms = millisToWaitForConversion(bitResolution); + activateExternalPullup(); + delay(delms); + deactivateExternalPullup(); + } + +} + +// returns number of milliseconds to wait till conversion is complete (based on IC datasheet) +int16_t DallasTemperature::millisToWaitForConversion(uint8_t bitResolution) { + + switch (bitResolution) { + case 9: + return 94; + case 10: + return 188; + case 11: + return 375; + default: + return 750; + } + +} + +// Sends command to one device to save values from scratchpad to EEPROM by index +// Returns true if no errors were encountered, false indicates failure +bool DallasTemperature::saveScratchPadByIndex(uint8_t deviceIndex) { + + DeviceAddress deviceAddress; + if (!getAddress(deviceAddress, deviceIndex)) return false; + + return saveScratchPad(deviceAddress); + +} + +// Sends command to one or more devices to save values from scratchpad to EEPROM +// If optional argument deviceAddress is omitted the command is send to all devices +// Returns true if no errors were encountered, false indicates failure +bool DallasTemperature::saveScratchPad(const uint8_t* deviceAddress) { + + if (_wire->reset() == 0) + return false; + + if (deviceAddress == nullptr) + _wire->skip(); + else + _wire->select(deviceAddress); + + _wire->write(COPYSCRATCH,parasite); + + // Specification: NV Write Cycle Time is typically 2ms, max 10ms + // Waiting 20ms to allow for sensors that take longer in practice + if (!parasite) { + delay(20); + } else { + activateExternalPullup(); + delay(20); + deactivateExternalPullup(); + } + + return _wire->reset() == 1; + +} + +// Sends command to one device to recall values from EEPROM to scratchpad by index +// Returns true if no errors were encountered, false indicates failure +bool DallasTemperature::recallScratchPadByIndex(uint8_t deviceIndex) { + + DeviceAddress deviceAddress; + if (!getAddress(deviceAddress, deviceIndex)) return false; + + return recallScratchPad(deviceAddress); + +} + +// Sends command to one or more devices to recall values from EEPROM to scratchpad +// If optional argument deviceAddress is omitted the command is send to all devices +// Returns true if no errors were encountered, false indicates failure +bool DallasTemperature::recallScratchPad(const uint8_t* deviceAddress) { + + if (_wire->reset() == 0) + return false; + + if (deviceAddress == nullptr) + _wire->skip(); + else + _wire->select(deviceAddress); + + _wire->write(RECALLSCRATCH,parasite); + + // Specification: Strong pullup only needed when writing to EEPROM (and temp conversion) + unsigned long start = millis(); + while (_wire->read_bit() == 0) { + // Datasheet doesn't specify typical/max duration, testing reveals typically within 1ms + if (millis() - start > 20) return false; + yield(); + } + + return _wire->reset() == 1; + +} + +// Sets the autoSaveScratchPad flag +void DallasTemperature::setAutoSaveScratchPad(bool flag) { + autoSaveScratchPad = flag; +} + +// Gets the autoSaveScratchPad flag +bool DallasTemperature::getAutoSaveScratchPad() { + return autoSaveScratchPad; +} + +void DallasTemperature::activateExternalPullup() { + if(useExternalPullup) + digitalWrite(pullupPin, LOW); +} + +void DallasTemperature::deactivateExternalPullup() { + if(useExternalPullup) + digitalWrite(pullupPin, HIGH); +} + +// sends command for one device to perform a temp conversion by index +bool DallasTemperature::requestTemperaturesByIndex(uint8_t deviceIndex) { + + DeviceAddress deviceAddress; + getAddress(deviceAddress, deviceIndex); + + return requestTemperaturesByAddress(deviceAddress); + +} + +// Fetch temperature for device index +float DallasTemperature::getTempCByIndex(uint8_t deviceIndex) { + + DeviceAddress deviceAddress; + if (!getAddress(deviceAddress, deviceIndex)) { + return DEVICE_DISCONNECTED_C; + } + return getTempC((uint8_t*) deviceAddress); +} + +// Fetch temperature for device index +float DallasTemperature::getTempFByIndex(uint8_t deviceIndex) { + + DeviceAddress deviceAddress; + + if (!getAddress(deviceAddress, deviceIndex)) { + return DEVICE_DISCONNECTED_F; + } + + return getTempF((uint8_t*) deviceAddress); + +} + +// reads scratchpad and returns fixed-point temperature, scaling factor 2^-7 +int16_t DallasTemperature::calculateTemperature(const uint8_t* deviceAddress, + uint8_t* scratchPad) { + + int16_t fpTemperature = (((int16_t) scratchPad[TEMP_MSB]) << 11) + | (((int16_t) scratchPad[TEMP_LSB]) << 3); + + /* + DS1820 and DS18S20 have a 9-bit temperature register. + + Resolutions greater than 9-bit can be calculated using the data from + the temperature, and COUNT REMAIN and COUNT PER °C registers in the + scratchpad. The resolution of the calculation depends on the model. + + While the COUNT PER °C register is hard-wired to 16 (10h) in a + DS18S20, it changes with temperature in DS1820. + + After reading the scratchpad, the TEMP_READ value is obtained by + truncating the 0.5°C bit (bit 0) from the temperature data. The + extended resolution temperature can then be calculated using the + following equation: + + COUNT_PER_C - COUNT_REMAIN + TEMPERATURE = TEMP_READ - 0.25 + -------------------------- + COUNT_PER_C + + Hagai Shatz simplified this to integer arithmetic for a 12 bits + value for a DS18S20, and James Cameron added legacy DS1820 support. + + See - http://myarduinotoy.blogspot.co.uk/2013/02/12bit-result-from-ds18s20.html + */ + + if ((deviceAddress[DSROM_FAMILY] == DS18S20MODEL) && (scratchPad[COUNT_PER_C] != 0)) { + fpTemperature = ((fpTemperature & 0xfff0) << 3) - 32 + + (((scratchPad[COUNT_PER_C] - scratchPad[COUNT_REMAIN]) << 7) + / scratchPad[COUNT_PER_C]); + } + + return fpTemperature; +} + +// returns temperature in 1/128 degrees C or DEVICE_DISCONNECTED_RAW if the +// device's scratch pad cannot be read successfully. +// the numeric value of DEVICE_DISCONNECTED_RAW is defined in +// DallasTemperature.h. It is a large negative number outside the +// operating range of the device +int16_t DallasTemperature::getTemp(const uint8_t* deviceAddress) { + + ScratchPad scratchPad; + if (isConnected(deviceAddress, scratchPad)) + return calculateTemperature(deviceAddress, scratchPad); + return DEVICE_DISCONNECTED_RAW; + +} + +// returns temperature in degrees C or DEVICE_DISCONNECTED_C if the +// device's scratch pad cannot be read successfully. +// the numeric value of DEVICE_DISCONNECTED_C is defined in +// DallasTemperature.h. It is a large negative number outside the +// operating range of the device +float DallasTemperature::getTempC(const uint8_t* deviceAddress) { + return rawToCelsius(getTemp(deviceAddress)); +} + +// returns temperature in degrees F or DEVICE_DISCONNECTED_F if the +// device's scratch pad cannot be read successfully. +// the numeric value of DEVICE_DISCONNECTED_F is defined in +// DallasTemperature.h. It is a large negative number outside the +// operating range of the device +float DallasTemperature::getTempF(const uint8_t* deviceAddress) { + return rawToFahrenheit(getTemp(deviceAddress)); +} + +// returns true if the bus requires parasite power +bool DallasTemperature::isParasitePowerMode(void) { + return parasite; +} + +// IF alarm is not used one can store a 16 bit int of userdata in the alarm +// registers. E.g. an ID of the sensor. +// See github issue #29 + +// note if device is not connected it will fail writing the data. +void DallasTemperature::setUserData(const uint8_t* deviceAddress, + int16_t data) { + // return when stored value == new value + if (getUserData(deviceAddress) == data) + return; + + ScratchPad scratchPad; + if (isConnected(deviceAddress, scratchPad)) { + scratchPad[HIGH_ALARM_TEMP] = data >> 8; + scratchPad[LOW_ALARM_TEMP] = data & 255; + writeScratchPad(deviceAddress, scratchPad); + } +} + +int16_t DallasTemperature::getUserData(const uint8_t* deviceAddress) { + int16_t data = 0; + ScratchPad scratchPad; + if (isConnected(deviceAddress, scratchPad)) { + data = scratchPad[HIGH_ALARM_TEMP] << 8; + data += scratchPad[LOW_ALARM_TEMP]; + } + return data; +} + +// note If address cannot be found no error will be reported. +int16_t DallasTemperature::getUserDataByIndex(uint8_t deviceIndex) { + DeviceAddress deviceAddress; + getAddress(deviceAddress, deviceIndex); + return getUserData((uint8_t*) deviceAddress); +} + +void DallasTemperature::setUserDataByIndex(uint8_t deviceIndex, int16_t data) { + DeviceAddress deviceAddress; + getAddress(deviceAddress, deviceIndex); + setUserData((uint8_t*) deviceAddress, data); +} + +// Convert float Celsius to Fahrenheit +float DallasTemperature::toFahrenheit(float celsius) { + return (celsius * 1.8f) + 32.0f; +} + +// Convert float Fahrenheit to Celsius +float DallasTemperature::toCelsius(float fahrenheit) { + return (fahrenheit - 32.0f) * 0.555555556f; +} + +// convert from raw to Celsius +float DallasTemperature::rawToCelsius(int16_t raw) { + + if (raw <= DEVICE_DISCONNECTED_RAW) + return DEVICE_DISCONNECTED_C; + // C = RAW/128 + return (float) raw * 0.0078125f; + +} + +// convert from raw to Fahrenheit +float DallasTemperature::rawToFahrenheit(int16_t raw) { + + if (raw <= DEVICE_DISCONNECTED_RAW) + return DEVICE_DISCONNECTED_F; + // C = RAW/128 + // F = (C*1.8)+32 = (RAW/128*1.8)+32 = (RAW*0.0140625)+32 + return ((float) raw * 0.0140625f) + 32.0f; + +} + +// Returns true if all bytes of scratchPad are '\0' +bool DallasTemperature::isAllZeros(const uint8_t * const scratchPad, const size_t length) { + for (size_t i = 0; i < length; i++) { + if (scratchPad[i] != 0) { + return false; + } + } + + return true; +} + +#if REQUIRESALARMS + +/* + + ALARMS: + + TH and TL Register Format + + BIT 7 BIT 6 BIT 5 BIT 4 BIT 3 BIT 2 BIT 1 BIT 0 + S 2^6 2^5 2^4 2^3 2^2 2^1 2^0 + + Only bits 11 through 4 of the temperature register are used + in the TH and TL comparison since TH and TL are 8-bit + registers. If the measured temperature is lower than or equal + to TL or higher than or equal to TH, an alarm condition exists + and an alarm flag is set inside the DS18B20. This flag is + updated after every temperature measurement; therefore, if the + alarm condition goes away, the flag will be turned off after + the next temperature conversion. + + */ + +// sets the high alarm temperature for a device in degrees Celsius +// accepts a float, but the alarm resolution will ignore anything +// after a decimal point. valid range is -55C - 125C +void DallasTemperature::setHighAlarmTemp(const uint8_t* deviceAddress, + int8_t celsius) { + + // return when stored value == new value + if (getHighAlarmTemp(deviceAddress) == celsius) + return; + + // make sure the alarm temperature is within the device's range + if (celsius > 125) + celsius = 125; + else if (celsius < -55) + celsius = -55; + + ScratchPad scratchPad; + if (isConnected(deviceAddress, scratchPad)) { + scratchPad[HIGH_ALARM_TEMP] = (uint8_t) celsius; + writeScratchPad(deviceAddress, scratchPad); + } + +} + +// sets the low alarm temperature for a device in degrees Celsius +// accepts a float, but the alarm resolution will ignore anything +// after a decimal point. valid range is -55C - 125C +void DallasTemperature::setLowAlarmTemp(const uint8_t* deviceAddress, + int8_t celsius) { + + // return when stored value == new value + if (getLowAlarmTemp(deviceAddress) == celsius) + return; + + // make sure the alarm temperature is within the device's range + if (celsius > 125) + celsius = 125; + else if (celsius < -55) + celsius = -55; + + ScratchPad scratchPad; + if (isConnected(deviceAddress, scratchPad)) { + scratchPad[LOW_ALARM_TEMP] = (uint8_t) celsius; + writeScratchPad(deviceAddress, scratchPad); + } + +} + +// returns a int8_t with the current high alarm temperature or +// DEVICE_DISCONNECTED for an address +int8_t DallasTemperature::getHighAlarmTemp(const uint8_t* deviceAddress) { + + ScratchPad scratchPad; + if (isConnected(deviceAddress, scratchPad)) + return (int8_t) scratchPad[HIGH_ALARM_TEMP]; + return DEVICE_DISCONNECTED_C; + +} + +// returns a int8_t with the current low alarm temperature or +// DEVICE_DISCONNECTED for an address +int8_t DallasTemperature::getLowAlarmTemp(const uint8_t* deviceAddress) { + + ScratchPad scratchPad; + if (isConnected(deviceAddress, scratchPad)) + return (int8_t) scratchPad[LOW_ALARM_TEMP]; + return DEVICE_DISCONNECTED_C; + +} + +// resets internal variables used for the alarm search +void DallasTemperature::resetAlarmSearch() { + + alarmSearchJunction = -1; + alarmSearchExhausted = 0; + for (uint8_t i = 0; i < 7; i++) { + alarmSearchAddress[i] = 0; + } + +} + +// This is a modified version of the OneWire::search method. +// +// Also added the OneWire search fix documented here: +// http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295 +// +// Perform an alarm search. If this function returns a '1' then it has +// enumerated the next device and you may retrieve the ROM from the +// OneWire::address variable. If there are no devices, no further +// devices, or something horrible happens in the middle of the +// enumeration then a 0 is returned. If a new device is found then +// its address is copied to newAddr. Use +// DallasTemperature::resetAlarmSearch() to start over. +bool DallasTemperature::alarmSearch(uint8_t* newAddr) { + + uint8_t i; + int8_t lastJunction = -1; + uint8_t done = 1; + + if (alarmSearchExhausted) + return false; + if (!_wire->reset()) + return false; + + // send the alarm search command + _wire->write(0xEC, 0); + + for (i = 0; i < 64; i++) { + + uint8_t a = _wire->read_bit(); + uint8_t nota = _wire->read_bit(); + uint8_t ibyte = i / 8; + uint8_t ibit = 1 << (i & 7); + + // I don't think this should happen, this means nothing responded, but maybe if + // something vanishes during the search it will come up. + if (a && nota) + return false; + + if (!a && !nota) { + if (i == alarmSearchJunction) { + // this is our time to decide differently, we went zero last time, go one. + a = 1; + alarmSearchJunction = lastJunction; + } else if (i < alarmSearchJunction) { + + // take whatever we took last time, look in address + if (alarmSearchAddress[ibyte] & ibit) { + a = 1; + } else { + // Only 0s count as pending junctions, we've already exhausted the 0 side of 1s + a = 0; + done = 0; + lastJunction = i; + } + } else { + // we are blazing new tree, take the 0 + a = 0; + alarmSearchJunction = i; + done = 0; + } + // OneWire search fix + // See: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295 + } + + if (a) + alarmSearchAddress[ibyte] |= ibit; + else + alarmSearchAddress[ibyte] &= ~ibit; + + _wire->write_bit(a); + } + + if (done) + alarmSearchExhausted = 1; + for (i = 0; i < 8; i++) + newAddr[i] = alarmSearchAddress[i]; + return true; + +} + +// returns true if device address might have an alarm condition +// (only an alarm search can verify this) +bool DallasTemperature::hasAlarm(const uint8_t* deviceAddress) { + + ScratchPad scratchPad; + if (isConnected(deviceAddress, scratchPad)) { + + int8_t temp = calculateTemperature(deviceAddress, scratchPad) >> 7; + + // check low alarm + if (temp <= (int8_t) scratchPad[LOW_ALARM_TEMP]) + return true; + + // check high alarm + if (temp >= (int8_t) scratchPad[HIGH_ALARM_TEMP]) + return true; + } + + // no alarm + return false; + +} + +// returns true if any device is reporting an alarm condition on the bus +bool DallasTemperature::hasAlarm(void) { + + DeviceAddress deviceAddress; + resetAlarmSearch(); + return alarmSearch(deviceAddress); +} + +// runs the alarm handler for all devices returned by alarmSearch() +// unless there no _AlarmHandler exist. +void DallasTemperature::processAlarms(void) { + +if (!hasAlarmHandler()) +{ + return; +} + + resetAlarmSearch(); + DeviceAddress alarmAddr; + + while (alarmSearch(alarmAddr)) { + if (validAddress(alarmAddr)) { + _AlarmHandler(alarmAddr); + } + } +} + +// sets the alarm handler +void DallasTemperature::setAlarmHandler(const AlarmHandler *handler) { + _AlarmHandler = handler; +} + +// checks if AlarmHandler has been set. +bool DallasTemperature::hasAlarmHandler() +{ + return _AlarmHandler != NO_ALARM_HANDLER; +} + +#endif + +#if REQUIRESNEW + +// MnetCS - Allocates memory for DallasTemperature. Allows us to instance a new object +void* DallasTemperature::operator new(unsigned int size) { // Implicit NSS obj size + + void * p;// void pointer + p = malloc(size);// Allocate memory + memset((DallasTemperature*)p,0,size);// Initialise memory + + //!!! CANT EXPLICITLY CALL CONSTRUCTOR - workaround by using an init() methodR - workaround by using an init() method + return (DallasTemperature*) p;// Cast blank region to NSS pointer +} + +// MnetCS 2009 - Free the memory used by this instance +void DallasTemperature::operator delete(void* p) { + + DallasTemperature* pNss = (DallasTemperature*) p; // Cast to NSS pointer + pNss->~DallasTemperature();// Destruct the object + + free(p);// Free the memory +} + +#endif diff --git a/src/DallasTemperature/DallasTemperature.h b/src/DallasTemperature/DallasTemperature.h new file mode 100644 index 0000000..941222a --- /dev/null +++ b/src/DallasTemperature/DallasTemperature.h @@ -0,0 +1,317 @@ +#ifndef DallasTemperature_h +#define DallasTemperature_h + +#define DALLASTEMPLIBVERSION "3.8.1" // To be deprecated -> TODO remove in 4.0.0 + +// 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. + +// set to true to include code for new and delete operators +#ifndef REQUIRESNEW +#define REQUIRESNEW false +#endif + +// set to true to include code implementing alarm search functions +#ifndef REQUIRESALARMS +#define REQUIRESALARMS true +#endif + +#include +#ifdef __STM32F1__ +#include +#else +#include "../OneWire/OneWire.h" +#endif + +// Model IDs +#define DS18S20MODEL 0x10 // also DS1820 +#define DS18B20MODEL 0x28 // also MAX31820 +#define DS1822MODEL 0x22 +#define DS1825MODEL 0x3B +#define DS28EA00MODEL 0x42 + +// Error Codes +#define DEVICE_DISCONNECTED_C -127 +#define DEVICE_DISCONNECTED_F -196.6 +#define DEVICE_DISCONNECTED_RAW -7040 + +// For readPowerSupply on oneWire bus +// definition of nullptr for C++ < 11, using official workaround: +// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2431.pdf +#if __cplusplus < 201103L +const class +{ +public: + template + operator T *() const + { + return 0; + } + template + operator T C::*() const + { + return 0; + } + +private: + void operator&() const; +} nullptr = {}; +#endif + +typedef uint8_t DeviceAddress[8]; + +class DallasTemperature { +public: + + DallasTemperature(); + DallasTemperature(OneWire*); + DallasTemperature(OneWire*, uint8_t); + + void setOneWire(OneWire*); + + void setPullupPin(uint8_t); + + // initialise bus + void begin(void); + + // returns the number of devices found on the bus + uint8_t getDeviceCount(void); + + // returns the number of DS18xxx Family devices on bus + uint8_t getDS18Count(void); + + // returns true if address is valid + bool validAddress(const uint8_t*); + + // returns true if address is of the family of sensors the lib supports. + bool validFamily(const uint8_t* deviceAddress); + + // finds an address at a given index on the bus + bool getAddress(uint8_t*, uint8_t); + + // attempt to determine if the device at the given address is connected to the bus + bool isConnected(const uint8_t*); + + // attempt to determine if the device at the given address is connected to the bus + // also allows for updating the read scratchpad + bool isConnected(const uint8_t*, uint8_t*); + + // read device's scratchpad + bool readScratchPad(const uint8_t*, uint8_t*); + + // write device's scratchpad + void writeScratchPad(const uint8_t*, const uint8_t*); + + // read device's power requirements + bool readPowerSupply(const uint8_t* deviceAddress = nullptr); + + // get global resolution + uint8_t getResolution(); + + // set global resolution to 9, 10, 11, or 12 bits + void setResolution(uint8_t); + + // returns the device resolution: 9, 10, 11, or 12 bits + uint8_t getResolution(const uint8_t*); + + // set resolution of a device to 9, 10, 11, or 12 bits + bool setResolution(const uint8_t*, uint8_t, + bool skipGlobalBitResolutionCalculation = false); + + // sets/gets the waitForConversion flag + void setWaitForConversion(bool); + bool getWaitForConversion(void); + + // sets/gets the checkForConversion flag + void setCheckForConversion(bool); + bool getCheckForConversion(void); + + // sends command for all devices on the bus to perform a temperature conversion + void requestTemperatures(void); + + // sends command for one device to perform a temperature conversion by address + bool requestTemperaturesByAddress(const uint8_t*); + + // sends command for one device to perform a temperature conversion by index + bool requestTemperaturesByIndex(uint8_t); + + // returns temperature raw value (12 bit integer of 1/128 degrees C) + int16_t getTemp(const uint8_t*); + + // returns temperature in degrees C + float getTempC(const uint8_t*); + + // returns temperature in degrees F + float getTempF(const uint8_t*); + + // Get temperature for device index (slow) + float getTempCByIndex(uint8_t); + + // Get temperature for device index (slow) + float getTempFByIndex(uint8_t); + + // returns true if the bus requires parasite power + bool isParasitePowerMode(void); + + // Is a conversion complete on the wire? Only applies to the first sensor on the wire. + bool isConversionComplete(void); + + int16_t millisToWaitForConversion(uint8_t); + + // Sends command to one device to save values from scratchpad to EEPROM by index + // Returns true if no errors were encountered, false indicates failure + bool saveScratchPadByIndex(uint8_t); + + // Sends command to one or more devices to save values from scratchpad to EEPROM + // Returns true if no errors were encountered, false indicates failure + bool saveScratchPad(const uint8_t* = nullptr); + + // Sends command to one device to recall values from EEPROM to scratchpad by index + // Returns true if no errors were encountered, false indicates failure + bool recallScratchPadByIndex(uint8_t); + + // Sends command to one or more devices to recall values from EEPROM to scratchpad + // Returns true if no errors were encountered, false indicates failure + bool recallScratchPad(const uint8_t* = nullptr); + + // Sets the autoSaveScratchPad flag + void setAutoSaveScratchPad(bool); + + // Gets the autoSaveScratchPad flag + bool getAutoSaveScratchPad(void); + +#if REQUIRESALARMS + + typedef void AlarmHandler(const uint8_t*); + + // sets the high alarm temperature for a device + // accepts a int8_t. valid range is -55C - 125C + void setHighAlarmTemp(const uint8_t*, int8_t); + + // sets the low alarm temperature for a device + // accepts a int8_t. valid range is -55C - 125C + void setLowAlarmTemp(const uint8_t*, int8_t); + + // returns a int8_t with the current high alarm temperature for a device + // in the range -55C - 125C + int8_t getHighAlarmTemp(const uint8_t*); + + // returns a int8_t with the current low alarm temperature for a device + // in the range -55C - 125C + int8_t getLowAlarmTemp(const uint8_t*); + + // resets internal variables used for the alarm search + void resetAlarmSearch(void); + + // search the wire for devices with active alarms + bool alarmSearch(uint8_t*); + + // returns true if ia specific device has an alarm + bool hasAlarm(const uint8_t*); + + // returns true if any device is reporting an alarm on the bus + bool hasAlarm(void); + + // runs the alarm handler for all devices returned by alarmSearch() + void processAlarms(void); + + // sets the alarm handler + void setAlarmHandler(const AlarmHandler *); + + // returns true if an AlarmHandler has been set + bool hasAlarmHandler(); + +#endif + + // if no alarm handler is used the two bytes can be used as user data + // example of such usage is an ID. + // note if device is not connected it will fail writing the data. + // note if address cannot be found no error will be reported. + // in short use carefully + void setUserData(const uint8_t*, int16_t); + void setUserDataByIndex(uint8_t, int16_t); + int16_t getUserData(const uint8_t*); + int16_t getUserDataByIndex(uint8_t); + + // convert from Celsius to Fahrenheit + static float toFahrenheit(float); + + // convert from Fahrenheit to Celsius + static float toCelsius(float); + + // convert from raw to Celsius + static float rawToCelsius(int16_t); + + // convert from raw to Fahrenheit + static float rawToFahrenheit(int16_t); + +#if REQUIRESNEW + + // initialize memory area + void* operator new (unsigned int); + + // delete memory reference + void operator delete(void*); + +#endif + +private: + typedef uint8_t ScratchPad[9]; + + // parasite power on or off + bool parasite; + + // external pullup + bool useExternalPullup; + uint8_t pullupPin; + + // used to determine the delay amount needed to allow for the + // temperature conversion to take place + uint8_t bitResolution; + + // used to requestTemperature with or without delay + bool waitForConversion; + + // used to requestTemperature to dynamically check if a conversion is complete + bool checkForConversion; + + // used to determine if values will be saved from scratchpad to EEPROM on every scratchpad write + bool autoSaveScratchPad; + + // count of devices on the bus + uint8_t devices; + + // count of DS18xxx Family devices on bus + uint8_t ds18Count; + + // Take a pointer to one wire instance + OneWire* _wire; + + // reads scratchpad and returns the raw temperature + int16_t calculateTemperature(const uint8_t*, uint8_t*); + + void blockTillConversionComplete(uint8_t); + + // Returns true if all bytes of scratchPad are '\0' + bool isAllZeros(const uint8_t* const scratchPad, const size_t length = 9); + + // External pullup control + void activateExternalPullup(void); + void deactivateExternalPullup(void); + +#if REQUIRESALARMS + + // required for alarmSearch + uint8_t alarmSearchAddress[8]; + int8_t alarmSearchJunction; + uint8_t alarmSearchExhausted; + + // the alarm handler function pointer + AlarmHandler *_AlarmHandler; + +#endif + +}; +#endif diff --git a/src/DallasTemperature/README.md b/src/DallasTemperature/README.md new file mode 100644 index 0000000..728b2d5 --- /dev/null +++ b/src/DallasTemperature/README.md @@ -0,0 +1,72 @@ +# Arduino Library for Maxim Temperature Integrated Circuits + +## Usage + +This library supports the following devices : + + +* DS18B20 +* DS18S20 - Please note there appears to be an issue with this series. +* DS1822 +* DS1820 +* MAX31820 + + +You will need a pull-up resistor of about 5 KOhm between the 1-Wire data line +and your 5V power. If you are using the DS18B20, ground pins 1 and 3. The +centre pin is the data line '1-wire'. + +In case of temperature conversion problems (result is `-85`), strong pull-up setup may be necessary. See section +_Powering the DS18B20_ in +[DS18B20 datasheet](https://datasheets.maximintegrated.com/en/ds/DS18B20.pdf) (page 7) +and use `DallasTemperature(OneWire*, uint8_t)` constructor. + +We have included a "REQUIRESNEW" and "REQUIRESALARMS" definition. If you +want to slim down the code feel free to use either of these by including + + + + #define REQUIRESNEW + +or + + #define REQUIRESALARMS + + +at the top of DallasTemperature.h + +Finally, please include OneWire from Paul Stoffregen in the library manager before you begin. + +## Credits + +The OneWire code has been derived from +http://www.arduino.cc/playground/Learning/OneWire. +Miles Burton originally developed this library. +Tim Newsome added support for multiple sensors on +the same bus. +Guil Barros [gfbarros@bappos.com] added getTempByAddress (v3.5) + Note: these are implemented as getTempC(address) and getTempF(address) +Rob Tillaart [rob.tillaart@gmail.com] added async modus (v3.7.0) + + +## Website + + +You can find the latest version of the library at +https://www.milesburton.com/Dallas_Temperature_Control_Library + +# License + +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 diff --git a/src/DallasTemperature/keywords.txt b/src/DallasTemperature/keywords.txt new file mode 100644 index 0000000..2d17db8 --- /dev/null +++ b/src/DallasTemperature/keywords.txt @@ -0,0 +1,78 @@ +####################################### +# Syntax Coloring Map For DallasTemperature +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### +DallasTemperature KEYWORD1 +OneWire KEYWORD1 +AlarmHandler KEYWORD1 +DeviceAddress KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +setOneWire KEYWORD2 +setPullupPin KEYWORD2 +setResolution KEYWORD2 +getResolution KEYWORD2 +getTemp KEYWORD2 +getTempC KEYWORD2 +toFahrenheit KEYWORD2 +getTempF KEYWORD2 +getTempCByIndex KEYWORD2 +getTempFByIndex KEYWORD2 +rawToCelsius KEYWORD2 +rawToFahrenheit KEYWORD2 +setWaitForConversion KEYWORD2 +getWaitForConversion KEYWORD2 +requestTemperatures KEYWORD2 +requestTemperaturesByAddress KEYWORD2 +requestTemperaturesByIndex KEYWORD2 +setCheckForConversion KEYWORD2 +getCheckForConversion KEYWORD2 +isConversionComplete KEYWORD2 +millisToWaitForConversion KEYWORD2 +isParasitePowerMode KEYWORD2 +begin KEYWORD2 +getDeviceCount KEYWORD2 +getDS18Count KEYWORD2 +getAddress KEYWORD2 +validAddress KEYWORD2 +validFamily KEYWORD2 +isConnected KEYWORD2 +readScratchPad KEYWORD2 +writeScratchPad KEYWORD2 +readPowerSupply KEYWORD2 +saveScratchPadByIndex KEYWORD2 +saveScratchPad KEYWORD2 +recallScratchPadByIndex KEYWORD2 +recallScratchPad KEYWORD2 +setAutoSaveScratchPad KEYWORD2 +getAutoSaveScratchPad KEYWORD2 +setHighAlarmTemp KEYWORD2 +setLowAlarmTemp KEYWORD2 +getHighAlarmTemp KEYWORD2 +getLowAlarmTemp KEYWORD2 +resetAlarmSearch KEYWORD2 +alarmSearch KEYWORD2 +hasAlarm KEYWORD2 +toCelsius KEYWORD2 +processAlarms KEYWORD2 +setAlarmHandler KEYWORD2 +hasAlarmHandler KEYWORD2 +setUserData KEYWORD2 +setUserDataByIndex KEYWORD2 +getUserData KEYWORD2 +getUserDataByIndex KEYWORD2 +calculateTemperature KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + +DEVICE_DISCONNECTED_C LITERAL1 +DEVICE_DISCONNECTED_F LITERAL1 +DEVICE_DISCONNECTED_RAW LITERAL1 diff --git a/src/DallasTemperature/library.json b/src/DallasTemperature/library.json new file mode 100644 index 0000000..eef9d6f --- /dev/null +++ b/src/DallasTemperature/library.json @@ -0,0 +1,40 @@ +{ + "name": "DallasTemperature", + "keywords": "onewire, 1-wire, bus, sensor, temperature", + "description": "Arduino Library for Dallas Temperature ICs (DS18B20, DS18S20, DS1822, DS1820)", + "repository": + { + "type": "git", + "url": "https://github.com/milesburton/Arduino-Temperature-Control-Library.git" + }, + "authors": + [ + { + "name": "Miles Burton", + "email": "miles@mnetcs.com", + "url": "http://www.milesburton.com", + "maintainer": true + }, + { + "name": "Tim Newsome", + "email": "nuisance@casualhacker.net" + }, + { + "name": "Guil Barros", + "email": "gfbarros@bappos.com" + }, + { + "name": "Rob Tillaart", + "email": "rob.tillaart@gmail.com" + } + ], + "dependencies": + { + "name": "OneWire", + "authors": "Paul Stoffregen", + "frameworks": "arduino" + }, + "version": "3.9.0", + "frameworks": "arduino", + "platforms": "*" +} diff --git a/src/DallasTemperature/library.properties b/src/DallasTemperature/library.properties new file mode 100644 index 0000000..acdda8f --- /dev/null +++ b/src/DallasTemperature/library.properties @@ -0,0 +1,10 @@ +name=DallasTemperature +version=3.9.0 +author=Miles Burton , Tim Newsome , Guil Barros , Rob Tillaart +maintainer=Miles Burton +sentence=Arduino Library for Dallas Temperature ICs +paragraph=Supports DS18B20, DS18S20, DS1822, DS1820 +category=Sensors +url=https://github.com/milesburton/Arduino-Temperature-Control-Library +architectures=* +depends=OneWire diff --git a/src/OneWire/OneWire.cpp b/src/OneWire/OneWire.cpp new file mode 100644 index 0000000..38bf4ee --- /dev/null +++ b/src/OneWire/OneWire.cpp @@ -0,0 +1,580 @@ +/* +Copyright (c) 2007, Jim Studt (original old version - many contributors since) + +The latest version of this library may be found at: + http://www.pjrc.com/teensy/td_libs_OneWire.html + +OneWire has been maintained by Paul Stoffregen (paul@pjrc.com) since +January 2010. + +DO NOT EMAIL for technical support, especially not for ESP chips! +All project support questions must be posted on public forums +relevant to the board or chips used. If using Arduino, post on +Arduino's forum. If using ESP, post on the ESP community forums. +There is ABSOLUTELY NO TECH SUPPORT BY PRIVATE EMAIL! + +Github's issue tracker for OneWire should be used only to report +specific bugs. DO NOT request project support via Github. All +project and tech support questions must be posted on forums, not +github issues. If you experience a problem and you are not +absolutely sure it's an issue with the library, ask on a forum +first. Only use github to report issues after experts have +confirmed the issue is with OneWire rather than your project. + +Back in 2010, OneWire was in need of many bug fixes, but had +been abandoned the original author (Jim Studt). None of the known +contributors were interested in maintaining OneWire. Paul typically +works on OneWire every 6 to 12 months. Patches usually wait that +long. If anyone is interested in more actively maintaining OneWire, +please contact Paul (this is pretty much the only reason to use +private email about OneWire). + +OneWire is now very mature code. No changes other than adding +definitions for newer hardware support are anticipated. + +Version 2.3: + Unknown chip fallback mode, Roger Clark + Teensy-LC compatibility, Paul Stoffregen + Search bug fix, Love Nystrom + +Version 2.2: + Teensy 3.0 compatibility, Paul Stoffregen, paul@pjrc.com + Arduino Due compatibility, http://arduino.cc/forum/index.php?topic=141030 + Fix DS18B20 example negative temperature + Fix DS18B20 example's low res modes, Ken Butcher + Improve reset timing, Mark Tillotson + Add const qualifiers, Bertrik Sikken + Add initial value input to crc16, Bertrik Sikken + Add target_search() function, Scott Roberts + +Version 2.1: + Arduino 1.0 compatibility, Paul Stoffregen + Improve temperature example, Paul Stoffregen + DS250x_PROM example, Guillermo Lovato + PIC32 (chipKit) compatibility, Jason Dangel, dangel.jason AT gmail.com + Improvements from Glenn Trewitt: + - crc16() now works + - check_crc16() does all of calculation/checking work. + - Added read_bytes() and write_bytes(), to reduce tedious loops. + - Added ds2408 example. + Delete very old, out-of-date readme file (info is here) + +Version 2.0: Modifications by Paul Stoffregen, January 2010: +http://www.pjrc.com/teensy/td_libs_OneWire.html + Search fix from Robin James + http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295/27#27 + Use direct optimized I/O in all cases + Disable interrupts during timing critical sections + (this solves many random communication errors) + Disable interrupts during read-modify-write I/O + Reduce RAM consumption by eliminating unnecessary + variables and trimming many to 8 bits + Optimize both crc8 - table version moved to flash + +Modified to work with larger numbers of devices - avoids loop. +Tested in Arduino 11 alpha with 12 sensors. +26 Sept 2008 -- Robin James +http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295/27#27 + +Updated to work with arduino-0008 and to include skip() as of +2007/07/06. --RJL20 + +Modified to calculate the 8-bit CRC directly, avoiding the need for +the 256-byte lookup table to be loaded in RAM. Tested in arduino-0010 +-- Tom Pollard, Jan 23, 2008 + +Jim Studt's original library was modified by Josh Larios. + +Tom Pollard, pollard@alum.mit.edu, contributed around May 20, 2008 + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Much of the code was inspired by Derek Yerger's code, though I don't +think much of that remains. In any event that was.. + (copyleft) 2006 by Derek Yerger - Free to distribute freely. + +The CRC code was excerpted and inspired by the Dallas Semiconductor +sample code bearing this copyright. +//--------------------------------------------------------------------------- +// Copyright (C) 2000 Dallas Semiconductor Corporation, All Rights Reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +// IN NO EVENT SHALL DALLAS SEMICONDUCTOR BE LIABLE FOR ANY CLAIM, DAMAGES +// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// +// Except as contained in this notice, the name of Dallas Semiconductor +// shall not be used except as stated in the Dallas Semiconductor +// Branding Policy. +//-------------------------------------------------------------------------- +*/ + +#include +#include "OneWire.h" +#include "util/OneWire_direct_gpio.h" + + +void OneWire::begin(uint8_t pin) +{ + pinMode(pin, INPUT); + bitmask = PIN_TO_BITMASK(pin); + baseReg = PIN_TO_BASEREG(pin); +#if ONEWIRE_SEARCH + reset_search(); +#endif +} + + +// Perform the onewire reset function. We will wait up to 250uS for +// the bus to come high, if it doesn't then it is broken or shorted +// and we return a 0; +// +// Returns 1 if a device asserted a presence pulse, 0 otherwise. +// +uint8_t OneWire::reset(void) +{ + IO_REG_TYPE mask IO_REG_MASK_ATTR = bitmask; + volatile IO_REG_TYPE *reg IO_REG_BASE_ATTR = baseReg; + uint8_t r; + uint8_t retries = 125; + + noInterrupts(); + DIRECT_MODE_INPUT(reg, mask); + interrupts(); + // wait until the wire is high... just in case + do { + if (--retries == 0) return 0; + delayMicroseconds(2); + } while ( !DIRECT_READ(reg, mask)); + + noInterrupts(); + DIRECT_WRITE_LOW(reg, mask); + DIRECT_MODE_OUTPUT(reg, mask); // drive output low + interrupts(); + delayMicroseconds(480); + noInterrupts(); + DIRECT_MODE_INPUT(reg, mask); // allow it to float + delayMicroseconds(70); + r = !DIRECT_READ(reg, mask); + interrupts(); + delayMicroseconds(410); + return r; +} + +// +// Write a bit. Port and bit is used to cut lookup time and provide +// more certain timing. +// +void OneWire::write_bit(uint8_t v) +{ + IO_REG_TYPE mask IO_REG_MASK_ATTR = bitmask; + volatile IO_REG_TYPE *reg IO_REG_BASE_ATTR = baseReg; + + if (v & 1) { + noInterrupts(); + DIRECT_WRITE_LOW(reg, mask); + DIRECT_MODE_OUTPUT(reg, mask); // drive output low + delayMicroseconds(10); + DIRECT_WRITE_HIGH(reg, mask); // drive output high + interrupts(); + delayMicroseconds(55); + } else { + noInterrupts(); + DIRECT_WRITE_LOW(reg, mask); + DIRECT_MODE_OUTPUT(reg, mask); // drive output low + delayMicroseconds(65); + DIRECT_WRITE_HIGH(reg, mask); // drive output high + interrupts(); + delayMicroseconds(5); + } +} + +// +// Read a bit. Port and bit is used to cut lookup time and provide +// more certain timing. +// +uint8_t OneWire::read_bit(void) +{ + IO_REG_TYPE mask IO_REG_MASK_ATTR = bitmask; + volatile IO_REG_TYPE *reg IO_REG_BASE_ATTR = baseReg; + uint8_t r; + + noInterrupts(); + DIRECT_MODE_OUTPUT(reg, mask); + DIRECT_WRITE_LOW(reg, mask); + delayMicroseconds(3); + DIRECT_MODE_INPUT(reg, mask); // let pin float, pull up will raise + delayMicroseconds(10); + r = DIRECT_READ(reg, mask); + interrupts(); + delayMicroseconds(53); + return r; +} + +// +// Write a byte. The writing code uses the active drivers to raise the +// pin high, if you need power after the write (e.g. DS18S20 in +// parasite power mode) then set 'power' to 1, otherwise the pin will +// go tri-state at the end of the write to avoid heating in a short or +// other mishap. +// +void OneWire::write(uint8_t v, uint8_t power /* = 0 */) { + uint8_t bitMask; + + for (bitMask = 0x01; bitMask; bitMask <<= 1) { + OneWire::write_bit( (bitMask & v)?1:0); + } + if ( !power) { + noInterrupts(); + DIRECT_MODE_INPUT(baseReg, bitmask); + DIRECT_WRITE_LOW(baseReg, bitmask); + interrupts(); + } +} + +void OneWire::write_bytes(const uint8_t *buf, uint16_t count, bool power /* = 0 */) { + for (uint16_t i = 0 ; i < count ; i++) + write(buf[i]); + if (!power) { + noInterrupts(); + DIRECT_MODE_INPUT(baseReg, bitmask); + DIRECT_WRITE_LOW(baseReg, bitmask); + interrupts(); + } +} + +// +// Read a byte +// +uint8_t OneWire::read() { + uint8_t bitMask; + uint8_t r = 0; + + for (bitMask = 0x01; bitMask; bitMask <<= 1) { + if ( OneWire::read_bit()) r |= bitMask; + } + return r; +} + +void OneWire::read_bytes(uint8_t *buf, uint16_t count) { + for (uint16_t i = 0 ; i < count ; i++) + buf[i] = read(); +} + +// +// Do a ROM select +// +void OneWire::select(const uint8_t rom[8]) +{ + uint8_t i; + + write(0x55); // Choose ROM + + for (i = 0; i < 8; i++) write(rom[i]); +} + +// +// Do a ROM skip +// +void OneWire::skip() +{ + write(0xCC); // Skip ROM +} + +void OneWire::depower() +{ + noInterrupts(); + DIRECT_MODE_INPUT(baseReg, bitmask); + interrupts(); +} + +#if ONEWIRE_SEARCH + +// +// You need to use this function to start a search again from the beginning. +// You do not need to do it for the first search, though you could. +// +void OneWire::reset_search() +{ + // reset the search state + LastDiscrepancy = 0; + LastDeviceFlag = false; + LastFamilyDiscrepancy = 0; + for(int i = 7; ; i--) { + ROM_NO[i] = 0; + if ( i == 0) break; + } +} + +// Setup the search to find the device type 'family_code' on the next call +// to search(*newAddr) if it is present. +// +void OneWire::target_search(uint8_t family_code) +{ + // set the search state to find SearchFamily type devices + ROM_NO[0] = family_code; + for (uint8_t i = 1; i < 8; i++) + ROM_NO[i] = 0; + LastDiscrepancy = 64; + LastFamilyDiscrepancy = 0; + LastDeviceFlag = false; +} + +// +// Perform a search. If this function returns a '1' then it has +// enumerated the next device and you may retrieve the ROM from the +// OneWire::address variable. If there are no devices, no further +// devices, or something horrible happens in the middle of the +// enumeration then a 0 is returned. If a new device is found then +// its address is copied to newAddr. Use OneWire::reset_search() to +// start over. +// +// --- Replaced by the one from the Dallas Semiconductor web site --- +//-------------------------------------------------------------------------- +// Perform the 1-Wire Search Algorithm on the 1-Wire bus using the existing +// search state. +// Return TRUE : device found, ROM number in ROM_NO buffer +// FALSE : device not found, end of search +// +bool OneWire::search(uint8_t *newAddr, bool search_mode /* = true */) +{ + uint8_t id_bit_number; + uint8_t last_zero, rom_byte_number; + bool search_result; + uint8_t id_bit, cmp_id_bit; + + unsigned char rom_byte_mask, search_direction; + + // initialize for search + id_bit_number = 1; + last_zero = 0; + rom_byte_number = 0; + rom_byte_mask = 1; + search_result = false; + + // if the last call was not the last one + if (!LastDeviceFlag) { + // 1-Wire reset + if (!reset()) { + // reset the search + LastDiscrepancy = 0; + LastDeviceFlag = false; + LastFamilyDiscrepancy = 0; + return false; + } + + // issue the search command + if (search_mode == true) { + write(0xF0); // NORMAL SEARCH + } else { + write(0xEC); // CONDITIONAL SEARCH + } + + // loop to do the search + do + { + // read a bit and its complement + id_bit = read_bit(); + cmp_id_bit = read_bit(); + + // check for no devices on 1-wire + if ((id_bit == 1) && (cmp_id_bit == 1)) { + break; + } else { + // all devices coupled have 0 or 1 + if (id_bit != cmp_id_bit) { + search_direction = id_bit; // bit write value for search + } else { + // if this discrepancy if before the Last Discrepancy + // on a previous next then pick the same as last time + if (id_bit_number < LastDiscrepancy) { + search_direction = ((ROM_NO[rom_byte_number] & rom_byte_mask) > 0); + } else { + // if equal to last pick 1, if not then pick 0 + search_direction = (id_bit_number == LastDiscrepancy); + } + // if 0 was picked then record its position in LastZero + if (search_direction == 0) { + last_zero = id_bit_number; + + // check for Last discrepancy in family + if (last_zero < 9) + LastFamilyDiscrepancy = last_zero; + } + } + + // set or clear the bit in the ROM byte rom_byte_number + // with mask rom_byte_mask + if (search_direction == 1) + ROM_NO[rom_byte_number] |= rom_byte_mask; + else + ROM_NO[rom_byte_number] &= ~rom_byte_mask; + + // serial number search direction write bit + write_bit(search_direction); + + // increment the byte counter id_bit_number + // and shift the mask rom_byte_mask + id_bit_number++; + rom_byte_mask <<= 1; + + // if the mask is 0 then go to new SerialNum byte rom_byte_number and reset mask + if (rom_byte_mask == 0) { + rom_byte_number++; + rom_byte_mask = 1; + } + } + } + while(rom_byte_number < 8); // loop until through all ROM bytes 0-7 + + // if the search was successful then + if (!(id_bit_number < 65)) { + // search successful so set LastDiscrepancy,LastDeviceFlag,search_result + LastDiscrepancy = last_zero; + + // check for last device + if (LastDiscrepancy == 0) { + LastDeviceFlag = true; + } + search_result = true; + } + } + + // if no device found then reset counters so next 'search' will be like a first + if (!search_result || !ROM_NO[0]) { + LastDiscrepancy = 0; + LastDeviceFlag = false; + LastFamilyDiscrepancy = 0; + search_result = false; + } else { + for (int i = 0; i < 8; i++) newAddr[i] = ROM_NO[i]; + } + return search_result; + } + +#endif + +#if ONEWIRE_CRC +// The 1-Wire CRC scheme is described in Maxim Application Note 27: +// "Understanding and Using Cyclic Redundancy Checks with Maxim iButton Products" +// + +#if ONEWIRE_CRC8_TABLE +// Dow-CRC using polynomial X^8 + X^5 + X^4 + X^0 +// Tiny 2x16 entry CRC table created by Arjen Lentz +// See http://lentz.com.au/blog/calculating-crc-with-a-tiny-32-entry-lookup-table +static const uint8_t PROGMEM dscrc2x16_table[] = { + 0x00, 0x5E, 0xBC, 0xE2, 0x61, 0x3F, 0xDD, 0x83, + 0xC2, 0x9C, 0x7E, 0x20, 0xA3, 0xFD, 0x1F, 0x41, + 0x00, 0x9D, 0x23, 0xBE, 0x46, 0xDB, 0x65, 0xF8, + 0x8C, 0x11, 0xAF, 0x32, 0xCA, 0x57, 0xE9, 0x74 +}; + +// Compute a Dallas Semiconductor 8 bit CRC. These show up in the ROM +// and the registers. (Use tiny 2x16 entry CRC table) +uint8_t OneWire::crc8(const uint8_t *addr, uint8_t len) +{ + uint8_t crc = 0; + + while (len--) { + crc = *addr++ ^ crc; // just re-using crc as intermediate + crc = pgm_read_byte(dscrc2x16_table + (crc & 0x0f)) ^ + pgm_read_byte(dscrc2x16_table + 16 + ((crc >> 4) & 0x0f)); + } + + return crc; +} +#else +// +// Compute a Dallas Semiconductor 8 bit CRC directly. +// this is much slower, but a little smaller, than the lookup table. +// +uint8_t OneWire::crc8(const uint8_t *addr, uint8_t len) +{ + uint8_t crc = 0; + + while (len--) { +#if defined(__AVR__) + crc = _crc_ibutton_update(crc, *addr++); +#else + uint8_t inbyte = *addr++; + for (uint8_t i = 8; i; i--) { + uint8_t mix = (crc ^ inbyte) & 0x01; + crc >>= 1; + if (mix) crc ^= 0x8C; + inbyte >>= 1; + } +#endif + } + return crc; +} +#endif + +#if ONEWIRE_CRC16 +bool OneWire::check_crc16(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc) +{ + crc = ~crc16(input, len, crc); + return (crc & 0xFF) == inverted_crc[0] && (crc >> 8) == inverted_crc[1]; +} + +uint16_t OneWire::crc16(const uint8_t* input, uint16_t len, uint16_t crc) +{ +#if defined(__AVR__) + for (uint16_t i = 0 ; i < len ; i++) { + crc = _crc16_update(crc, input[i]); + } +#else + static const uint8_t oddparity[16] = + { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 }; + + for (uint16_t i = 0 ; i < len ; i++) { + // Even though we're just copying a byte from the input, + // we'll be doing 16-bit computation with it. + uint16_t cdata = input[i]; + cdata = (cdata ^ crc) & 0xff; + crc >>= 8; + + if (oddparity[cdata & 0x0F] ^ oddparity[cdata >> 4]) + crc ^= 0xC001; + + cdata <<= 6; + crc ^= cdata; + cdata <<= 1; + crc ^= cdata; + } +#endif + return crc; +} +#endif + +#endif diff --git a/src/OneWire/OneWire.h b/src/OneWire/OneWire.h new file mode 100644 index 0000000..a7bfab7 --- /dev/null +++ b/src/OneWire/OneWire.h @@ -0,0 +1,182 @@ +#ifndef OneWire_h +#define OneWire_h + +#ifdef __cplusplus + +#include + +#if defined(__AVR__) +#include +#endif + +#if ARDUINO >= 100 +#include // for delayMicroseconds, digitalPinToBitMask, etc +#else +#include "WProgram.h" // for delayMicroseconds +#include "pins_arduino.h" // for digitalPinToBitMask, etc +#endif + +// You can exclude certain features from OneWire. In theory, this +// might save some space. In practice, the compiler automatically +// removes unused code (technically, the linker, using -fdata-sections +// and -ffunction-sections when compiling, and Wl,--gc-sections +// when linking), so most of these will not result in any code size +// reduction. Well, unless you try to use the missing features +// and redesign your program to not need them! ONEWIRE_CRC8_TABLE +// is the exception, because it selects a fast but large algorithm +// or a small but slow algorithm. + +// you can exclude onewire_search by defining that to 0 +#ifndef ONEWIRE_SEARCH +#define ONEWIRE_SEARCH 1 +#endif + +// You can exclude CRC checks altogether by defining this to 0 +#ifndef ONEWIRE_CRC +#define ONEWIRE_CRC 1 +#endif + +// Select the table-lookup method of computing the 8-bit CRC +// by setting this to 1. The lookup table enlarges code size by +// about 250 bytes. It does NOT consume RAM (but did in very +// old versions of OneWire). If you disable this, a slower +// but very compact algorithm is used. +#ifndef ONEWIRE_CRC8_TABLE +#define ONEWIRE_CRC8_TABLE 1 +#endif + +// You can allow 16-bit CRC checks by defining this to 1 +// (Note that ONEWIRE_CRC must also be 1.) +#ifndef ONEWIRE_CRC16 +#define ONEWIRE_CRC16 1 +#endif + +// Board-specific macros for direct GPIO +#include "util/OneWire_direct_regtype.h" + +class OneWire +{ + private: + IO_REG_TYPE bitmask; + volatile IO_REG_TYPE *baseReg; + +#if ONEWIRE_SEARCH + // global search state + unsigned char ROM_NO[8]; + uint8_t LastDiscrepancy; + uint8_t LastFamilyDiscrepancy; + bool LastDeviceFlag; +#endif + + public: + OneWire() { } + OneWire(uint8_t pin) { begin(pin); } + void begin(uint8_t pin); + + // Perform a 1-Wire reset cycle. Returns 1 if a device responds + // with a presence pulse. Returns 0 if there is no device or the + // bus is shorted or otherwise held low for more than 250uS + uint8_t reset(void); + + // Issue a 1-Wire rom select command, you do the reset first. + void select(const uint8_t rom[8]); + + // Issue a 1-Wire rom skip command, to address all on bus. + void skip(void); + + // Write a byte. If 'power' is one then the wire is held high at + // the end for parasitically powered devices. You are responsible + // for eventually depowering it by calling depower() or doing + // another read or write. + void write(uint8_t v, uint8_t power = 0); + + void write_bytes(const uint8_t *buf, uint16_t count, bool power = 0); + + // Read a byte. + uint8_t read(void); + + void read_bytes(uint8_t *buf, uint16_t count); + + // Write a bit. The bus is always left powered at the end, see + // note in write() about that. + void write_bit(uint8_t v); + + // Read a bit. + uint8_t read_bit(void); + + // Stop forcing power onto the bus. You only need to do this if + // you used the 'power' flag to write() or used a write_bit() call + // and aren't about to do another read or write. You would rather + // not leave this powered if you don't have to, just in case + // someone shorts your bus. + void depower(void); + +#if ONEWIRE_SEARCH + // Clear the search state so that if will start from the beginning again. + void reset_search(); + + // Setup the search to find the device type 'family_code' on the next call + // to search(*newAddr) if it is present. + void target_search(uint8_t family_code); + + // Look for the next device. Returns 1 if a new address has been + // returned. A zero might mean that the bus is shorted, there are + // no devices, or you have already retrieved all of them. It + // might be a good idea to check the CRC to make sure you didn't + // get garbage. The order is deterministic. You will always get + // the same devices in the same order. + bool search(uint8_t *newAddr, bool search_mode = true); +#endif + +#if ONEWIRE_CRC + // Compute a Dallas Semiconductor 8 bit CRC, these are used in the + // ROM and scratchpad registers. + static uint8_t crc8(const uint8_t *addr, uint8_t len); + +#if ONEWIRE_CRC16 + // Compute the 1-Wire CRC16 and compare it against the received CRC. + // Example usage (reading a DS2408): + // // Put everything in a buffer so we can compute the CRC easily. + // uint8_t buf[13]; + // buf[0] = 0xF0; // Read PIO Registers + // buf[1] = 0x88; // LSB address + // buf[2] = 0x00; // MSB address + // WriteBytes(net, buf, 3); // Write 3 cmd bytes + // ReadBytes(net, buf+3, 10); // Read 6 data bytes, 2 0xFF, 2 CRC16 + // if (!CheckCRC16(buf, 11, &buf[11])) { + // // Handle error. + // } + // + // @param input - Array of bytes to checksum. + // @param len - How many bytes to use. + // @param inverted_crc - The two CRC16 bytes in the received data. + // This should just point into the received data, + // *not* at a 16-bit integer. + // @param crc - The crc starting value (optional) + // @return True, iff the CRC matches. + static bool check_crc16(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc = 0); + + // Compute a Dallas Semiconductor 16 bit CRC. This is required to check + // the integrity of data received from many 1-Wire devices. Note that the + // CRC computed here is *not* what you'll get from the 1-Wire network, + // for two reasons: + // 1) The CRC is transmitted bitwise inverted. + // 2) Depending on the endian-ness of your processor, the binary + // representation of the two-byte return value may have a different + // byte order than the two bytes you get from 1-Wire. + // @param input - Array of bytes to checksum. + // @param len - How many bytes to use. + // @param crc - The crc starting value (optional) + // @return The CRC16, as defined by Dallas Semiconductor. + static uint16_t crc16(const uint8_t* input, uint16_t len, uint16_t crc = 0); +#endif +#endif +}; + +// Prevent this name from leaking into Arduino sketches +#ifdef IO_REG_TYPE +#undef IO_REG_TYPE +#endif + +#endif // __cplusplus +#endif // OneWire_h diff --git a/src/OneWire/docs/issue_template.md b/src/OneWire/docs/issue_template.md new file mode 100644 index 0000000..0610992 --- /dev/null +++ b/src/OneWire/docs/issue_template.md @@ -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 + +// 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. + + diff --git a/src/OneWire/keywords.txt b/src/OneWire/keywords.txt new file mode 100644 index 0000000..bee5d90 --- /dev/null +++ b/src/OneWire/keywords.txt @@ -0,0 +1,38 @@ +####################################### +# Syntax Coloring Map For OneWire +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +OneWire KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +reset KEYWORD2 +write_bit KEYWORD2 +read_bit KEYWORD2 +write KEYWORD2 +write_bytes KEYWORD2 +read KEYWORD2 +read_bytes KEYWORD2 +select KEYWORD2 +skip KEYWORD2 +depower KEYWORD2 +reset_search KEYWORD2 +search KEYWORD2 +crc8 KEYWORD2 +crc16 KEYWORD2 +check_crc16 KEYWORD2 + +####################################### +# Instances (KEYWORD2) +####################################### + + +####################################### +# Constants (LITERAL1) +####################################### diff --git a/src/OneWire/library.json b/src/OneWire/library.json new file mode 100644 index 0000000..c529849 --- /dev/null +++ b/src/OneWire/library.json @@ -0,0 +1,61 @@ +{ + "name": "OneWire", + "description": "Control 1-Wire protocol (DS18S20, DS18B20, DS2408 and etc)", + "keywords": "onewire, 1-wire, bus, sensor, temperature, ibutton", + "authors": [ + { + "name": "Paul Stoffregen", + "email": "paul@pjrc.com", + "url": "http://www.pjrc.com", + "maintainer": true + }, + { + "name": "Jim Studt" + }, + { + "name": "Tom Pollard", + "email": "pollard@alum.mit.edu" + }, + { + "name": "Derek Yerger" + }, + { + "name": "Josh Larios" + }, + { + "name": "Robin James" + }, + { + "name": "Glenn Trewitt" + }, + { + "name": "Jason Dangel", + "email": "dangel.jason AT gmail.com" + }, + { + "name": "Guillermo Lovato" + }, + { + "name": "Ken Butcher" + }, + { + "name": "Mark Tillotson" + }, + { + "name": "Bertrik Sikken" + }, + { + "name": "Scott Roberts" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/PaulStoffregen/OneWire" + }, + "version": "2.3.5", + "homepage": "https://www.pjrc.com/teensy/td_libs_OneWire.html", + "frameworks": "Arduino", + "examples": [ + "examples/*/*.pde" + ] +} diff --git a/src/OneWire/library.properties b/src/OneWire/library.properties new file mode 100644 index 0000000..a7e4ad7 --- /dev/null +++ b/src/OneWire/library.properties @@ -0,0 +1,10 @@ +name=OneWire +version=2.3.5 +author=Jim Studt, Tom Pollard, Robin James, Glenn Trewitt, Jason Dangel, Guillermo Lovato, Paul Stoffregen, Scott Roberts, Bertrik Sikken, Mark Tillotson, Ken Butcher, Roger Clark, Love Nystrom +maintainer=Paul Stoffregen +sentence=Access 1-wire temperature sensors, memory and other chips. +paragraph= +category=Communication +url=http://www.pjrc.com/teensy/td_libs_OneWire.html +architectures=* + diff --git a/src/OneWire/util/OneWire_direct_gpio.h b/src/OneWire/util/OneWire_direct_gpio.h new file mode 100644 index 0000000..0771367 --- /dev/null +++ b/src/OneWire/util/OneWire_direct_gpio.h @@ -0,0 +1,420 @@ +#ifndef OneWire_Direct_GPIO_h +#define OneWire_Direct_GPIO_h + +// This header should ONLY be included by OneWire.cpp. These defines are +// meant to be private, used within OneWire.cpp, but not exposed to Arduino +// sketches or other libraries which may include OneWire.h. + +#include + +// Platform specific I/O definitions + +#if defined(__AVR__) +#define PIN_TO_BASEREG(pin) (portInputRegister(digitalPinToPort(pin))) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint8_t +#define IO_REG_BASE_ATTR asm("r30") +#define IO_REG_MASK_ATTR +#if defined(__AVR_ATmega4809__) +#define DIRECT_READ(base, mask) (((*(base)) & (mask)) ? 1 : 0) +#define DIRECT_MODE_INPUT(base, mask) ((*((base)-8)) &= ~(mask)) +#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)-8)) |= (mask)) +#define DIRECT_WRITE_LOW(base, mask) ((*((base)-4)) &= ~(mask)) +#define DIRECT_WRITE_HIGH(base, mask) ((*((base)-4)) |= (mask)) +#else +#define DIRECT_READ(base, mask) (((*(base)) & (mask)) ? 1 : 0) +#define DIRECT_MODE_INPUT(base, mask) ((*((base)+1)) &= ~(mask)) +#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)+1)) |= (mask)) +#define DIRECT_WRITE_LOW(base, mask) ((*((base)+2)) &= ~(mask)) +#define DIRECT_WRITE_HIGH(base, mask) ((*((base)+2)) |= (mask)) +#endif + +#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__) +#define PIN_TO_BASEREG(pin) (portOutputRegister(pin)) +#define PIN_TO_BITMASK(pin) (1) +#define IO_REG_TYPE uint8_t +#define IO_REG_BASE_ATTR +#define IO_REG_MASK_ATTR __attribute__ ((unused)) +#define DIRECT_READ(base, mask) (*((base)+512)) +#define DIRECT_MODE_INPUT(base, mask) (*((base)+640) = 0) +#define DIRECT_MODE_OUTPUT(base, mask) (*((base)+640) = 1) +#define DIRECT_WRITE_LOW(base, mask) (*((base)+256) = 1) +#define DIRECT_WRITE_HIGH(base, mask) (*((base)+128) = 1) + +#elif defined(__MKL26Z64__) +#define PIN_TO_BASEREG(pin) (portOutputRegister(pin)) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint8_t +#define IO_REG_BASE_ATTR +#define IO_REG_MASK_ATTR +#define DIRECT_READ(base, mask) ((*((base)+16) & (mask)) ? 1 : 0) +#define DIRECT_MODE_INPUT(base, mask) (*((base)+20) &= ~(mask)) +#define DIRECT_MODE_OUTPUT(base, mask) (*((base)+20) |= (mask)) +#define DIRECT_WRITE_LOW(base, mask) (*((base)+8) = (mask)) +#define DIRECT_WRITE_HIGH(base, mask) (*((base)+4) = (mask)) + +#elif defined(__IMXRT1052__) || defined(__IMXRT1062__) +#define PIN_TO_BASEREG(pin) (portOutputRegister(pin)) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint32_t +#define IO_REG_BASE_ATTR +#define IO_REG_MASK_ATTR +#define DIRECT_READ(base, mask) ((*((base)+2) & (mask)) ? 1 : 0) +#define DIRECT_MODE_INPUT(base, mask) (*((base)+1) &= ~(mask)) +#define DIRECT_MODE_OUTPUT(base, mask) (*((base)+1) |= (mask)) +#define DIRECT_WRITE_LOW(base, mask) (*((base)+34) = (mask)) +#define DIRECT_WRITE_HIGH(base, mask) (*((base)+33) = (mask)) + +#elif defined(__SAM3X8E__) || defined(__SAM3A8C__) || defined(__SAM3A4C__) +// Arduino 1.5.1 may have a bug in delayMicroseconds() on Arduino Due. +// http://arduino.cc/forum/index.php/topic,141030.msg1076268.html#msg1076268 +// If you have trouble with OneWire on Arduino Due, please check the +// status of delayMicroseconds() before reporting a bug in OneWire! +#define PIN_TO_BASEREG(pin) (&(digitalPinToPort(pin)->PIO_PER)) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint32_t +#define IO_REG_BASE_ATTR +#define IO_REG_MASK_ATTR +#define DIRECT_READ(base, mask) (((*((base)+15)) & (mask)) ? 1 : 0) +#define DIRECT_MODE_INPUT(base, mask) ((*((base)+5)) = (mask)) +#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)+4)) = (mask)) +#define DIRECT_WRITE_LOW(base, mask) ((*((base)+13)) = (mask)) +#define DIRECT_WRITE_HIGH(base, mask) ((*((base)+12)) = (mask)) +#ifndef PROGMEM +#define PROGMEM +#endif +#ifndef pgm_read_byte +#define pgm_read_byte(addr) (*(const uint8_t *)(addr)) +#endif + +#elif defined(__PIC32MX__) +#define PIN_TO_BASEREG(pin) (portModeRegister(digitalPinToPort(pin))) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint32_t +#define IO_REG_BASE_ATTR +#define IO_REG_MASK_ATTR +#define DIRECT_READ(base, mask) (((*(base+4)) & (mask)) ? 1 : 0) //PORTX + 0x10 +#define DIRECT_MODE_INPUT(base, mask) ((*(base+2)) = (mask)) //TRISXSET + 0x08 +#define DIRECT_MODE_OUTPUT(base, mask) ((*(base+1)) = (mask)) //TRISXCLR + 0x04 +#define DIRECT_WRITE_LOW(base, mask) ((*(base+8+1)) = (mask)) //LATXCLR + 0x24 +#define DIRECT_WRITE_HIGH(base, mask) ((*(base+8+2)) = (mask)) //LATXSET + 0x28 + +#elif defined(ARDUINO_ARCH_ESP8266) +// Special note: I depend on the ESP community to maintain these definitions and +// submit good pull requests. I can not answer any ESP questions or help you +// resolve any problems related to ESP chips. Please do not contact me and please +// DO NOT CREATE GITHUB ISSUES for ESP support. All ESP questions must be asked +// on ESP community forums. +#define PIN_TO_BASEREG(pin) ((volatile uint32_t*) GPO) +#define PIN_TO_BITMASK(pin) (1 << pin) +#define IO_REG_TYPE uint32_t +#define IO_REG_BASE_ATTR +#define IO_REG_MASK_ATTR +#define DIRECT_READ(base, mask) ((GPI & (mask)) ? 1 : 0) //GPIO_IN_ADDRESS +#define DIRECT_MODE_INPUT(base, mask) (GPE &= ~(mask)) //GPIO_ENABLE_W1TC_ADDRESS +#define DIRECT_MODE_OUTPUT(base, mask) (GPE |= (mask)) //GPIO_ENABLE_W1TS_ADDRESS +#define DIRECT_WRITE_LOW(base, mask) (GPOC = (mask)) //GPIO_OUT_W1TC_ADDRESS +#define DIRECT_WRITE_HIGH(base, mask) (GPOS = (mask)) //GPIO_OUT_W1TS_ADDRESS + +#elif defined(ARDUINO_ARCH_ESP32) +#include +#define PIN_TO_BASEREG(pin) (0) +#define PIN_TO_BITMASK(pin) (pin) +#define IO_REG_TYPE uint32_t +#define IO_REG_BASE_ATTR +#define IO_REG_MASK_ATTR + +static inline __attribute__((always_inline)) +IO_REG_TYPE directRead(IO_REG_TYPE pin) +{ + if ( pin < 32 ) + return (GPIO.in >> pin) & 0x1; + else if ( pin < 40 ) + return (GPIO.in1.val >> (pin - 32)) & 0x1; + + return 0; +} + +static inline __attribute__((always_inline)) +void directWriteLow(IO_REG_TYPE pin) +{ + if ( pin < 32 ) + GPIO.out_w1tc = ((uint32_t)1 << pin); + else if ( pin < 34 ) + GPIO.out1_w1tc.val = ((uint32_t)1 << (pin - 32)); +} + +static inline __attribute__((always_inline)) +void directWriteHigh(IO_REG_TYPE pin) +{ + if ( pin < 32 ) + GPIO.out_w1ts = ((uint32_t)1 << pin); + else if ( pin < 34 ) + GPIO.out1_w1ts.val = ((uint32_t)1 << (pin - 32)); +} + +static inline __attribute__((always_inline)) +void directModeInput(IO_REG_TYPE pin) +{ + if ( digitalPinIsValid(pin) ) + { + uint32_t rtc_reg(rtc_gpio_desc[pin].reg); + + if ( rtc_reg ) // RTC pins PULL settings + { + ESP_REG(rtc_reg) = ESP_REG(rtc_reg) & ~(rtc_gpio_desc[pin].mux); + ESP_REG(rtc_reg) = ESP_REG(rtc_reg) & ~(rtc_gpio_desc[pin].pullup | rtc_gpio_desc[pin].pulldown); + } + + if ( pin < 32 ) + GPIO.enable_w1tc = ((uint32_t)1 << pin); + else + GPIO.enable1_w1tc.val = ((uint32_t)1 << (pin - 32)); + + uint32_t pinFunction((uint32_t)2 << FUN_DRV_S); // what are the drivers? + pinFunction |= FUN_IE; // input enable but required for output as well? + pinFunction |= ((uint32_t)2 << MCU_SEL_S); + + ESP_REG(DR_REG_IO_MUX_BASE + esp32_gpioMux[pin].reg) = pinFunction; + + GPIO.pin[pin].val = 0; + } +} + +static inline __attribute__((always_inline)) +void directModeOutput(IO_REG_TYPE pin) +{ + if ( digitalPinIsValid(pin) && pin <= 33 ) // pins above 33 can be only inputs + { + uint32_t rtc_reg(rtc_gpio_desc[pin].reg); + + if ( rtc_reg ) // RTC pins PULL settings + { + ESP_REG(rtc_reg) = ESP_REG(rtc_reg) & ~(rtc_gpio_desc[pin].mux); + ESP_REG(rtc_reg) = ESP_REG(rtc_reg) & ~(rtc_gpio_desc[pin].pullup | rtc_gpio_desc[pin].pulldown); + } + + if ( pin < 32 ) + GPIO.enable_w1ts = ((uint32_t)1 << pin); + else // already validated to pins <= 33 + GPIO.enable1_w1ts.val = ((uint32_t)1 << (pin - 32)); + + uint32_t pinFunction((uint32_t)2 << FUN_DRV_S); // what are the drivers? + pinFunction |= FUN_IE; // input enable but required for output as well? + pinFunction |= ((uint32_t)2 << MCU_SEL_S); + + ESP_REG(DR_REG_IO_MUX_BASE + esp32_gpioMux[pin].reg) = pinFunction; + + GPIO.pin[pin].val = 0; + } +} + +#define DIRECT_READ(base, pin) directRead(pin) +#define DIRECT_WRITE_LOW(base, pin) directWriteLow(pin) +#define DIRECT_WRITE_HIGH(base, pin) directWriteHigh(pin) +#define DIRECT_MODE_INPUT(base, pin) directModeInput(pin) +#define DIRECT_MODE_OUTPUT(base, pin) directModeOutput(pin) +// https://github.com/PaulStoffregen/OneWire/pull/47 +// https://github.com/stickbreaker/OneWire/commit/6eb7fc1c11a15b6ac8c60e5671cf36eb6829f82c +#ifdef interrupts +#undef interrupts +#endif +#ifdef noInterrupts +#undef noInterrupts +#endif +#define noInterrupts() {portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;portENTER_CRITICAL(&mux) +#define interrupts() portEXIT_CRITICAL(&mux);} +//#warning "ESP32 OneWire testing" + +#elif defined(ARDUINO_ARCH_STM32) +#define PIN_TO_BASEREG(pin) (0) +#define PIN_TO_BITMASK(pin) ((uint32_t)digitalPinToPinName(pin)) +#define IO_REG_TYPE uint32_t +#define IO_REG_BASE_ATTR +#define IO_REG_MASK_ATTR +#define DIRECT_READ(base, pin) digitalReadFast((PinName)pin) +#define DIRECT_WRITE_LOW(base, pin) digitalWriteFast((PinName)pin, LOW) +#define DIRECT_WRITE_HIGH(base, pin) digitalWriteFast((PinName)pin, HIGH) +#define DIRECT_MODE_INPUT(base, pin) pin_function((PinName)pin, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)) +#define DIRECT_MODE_OUTPUT(base, pin) pin_function((PinName)pin, STM_PIN_DATA(STM_MODE_OUTPUT_PP, GPIO_NOPULL, 0)) + +#elif defined(__SAMD21G18A__) +#define PIN_TO_BASEREG(pin) portModeRegister(digitalPinToPort(pin)) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint32_t +#define IO_REG_BASE_ATTR +#define IO_REG_MASK_ATTR +#define DIRECT_READ(base, mask) (((*((base)+8)) & (mask)) ? 1 : 0) +#define DIRECT_MODE_INPUT(base, mask) ((*((base)+1)) = (mask)) +#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)+2)) = (mask)) +#define DIRECT_WRITE_LOW(base, mask) ((*((base)+5)) = (mask)) +#define DIRECT_WRITE_HIGH(base, mask) ((*((base)+6)) = (mask)) + +#elif defined(RBL_NRF51822) +#define PIN_TO_BASEREG(pin) (0) +#define PIN_TO_BITMASK(pin) (pin) +#define IO_REG_TYPE uint32_t +#define IO_REG_BASE_ATTR +#define IO_REG_MASK_ATTR +#define DIRECT_READ(base, pin) nrf_gpio_pin_read(pin) +#define DIRECT_WRITE_LOW(base, pin) nrf_gpio_pin_clear(pin) +#define DIRECT_WRITE_HIGH(base, pin) nrf_gpio_pin_set(pin) +#define DIRECT_MODE_INPUT(base, pin) nrf_gpio_cfg_input(pin, NRF_GPIO_PIN_NOPULL) +#define DIRECT_MODE_OUTPUT(base, pin) nrf_gpio_cfg_output(pin) + +#elif defined(__arc__) /* Arduino101/Genuino101 specifics */ + +#include "scss_registers.h" +#include "portable.h" +#include "avr/pgmspace.h" + +#define GPIO_ID(pin) (g_APinDescription[pin].ulGPIOId) +#define GPIO_TYPE(pin) (g_APinDescription[pin].ulGPIOType) +#define GPIO_BASE(pin) (g_APinDescription[pin].ulGPIOBase) +#define DIR_OFFSET_SS 0x01 +#define DIR_OFFSET_SOC 0x04 +#define EXT_PORT_OFFSET_SS 0x0A +#define EXT_PORT_OFFSET_SOC 0x50 + +/* GPIO registers base address */ +#define PIN_TO_BASEREG(pin) ((volatile uint32_t *)g_APinDescription[pin].ulGPIOBase) +#define PIN_TO_BITMASK(pin) pin +#define IO_REG_TYPE uint32_t +#define IO_REG_BASE_ATTR +#define IO_REG_MASK_ATTR + +static inline __attribute__((always_inline)) +IO_REG_TYPE directRead(volatile IO_REG_TYPE *base, IO_REG_TYPE pin) +{ + IO_REG_TYPE ret; + if (SS_GPIO == GPIO_TYPE(pin)) { + ret = READ_ARC_REG(((IO_REG_TYPE)base + EXT_PORT_OFFSET_SS)); + } else { + ret = MMIO_REG_VAL_FROM_BASE((IO_REG_TYPE)base, EXT_PORT_OFFSET_SOC); + } + return ((ret >> GPIO_ID(pin)) & 0x01); +} + +static inline __attribute__((always_inline)) +void directModeInput(volatile IO_REG_TYPE *base, IO_REG_TYPE pin) +{ + if (SS_GPIO == GPIO_TYPE(pin)) { + WRITE_ARC_REG(READ_ARC_REG((((IO_REG_TYPE)base) + DIR_OFFSET_SS)) & ~(0x01 << GPIO_ID(pin)), + ((IO_REG_TYPE)(base) + DIR_OFFSET_SS)); + } else { + MMIO_REG_VAL_FROM_BASE((IO_REG_TYPE)base, DIR_OFFSET_SOC) &= ~(0x01 << GPIO_ID(pin)); + } +} + +static inline __attribute__((always_inline)) +void directModeOutput(volatile IO_REG_TYPE *base, IO_REG_TYPE pin) +{ + if (SS_GPIO == GPIO_TYPE(pin)) { + WRITE_ARC_REG(READ_ARC_REG(((IO_REG_TYPE)(base) + DIR_OFFSET_SS)) | (0x01 << GPIO_ID(pin)), + ((IO_REG_TYPE)(base) + DIR_OFFSET_SS)); + } else { + MMIO_REG_VAL_FROM_BASE((IO_REG_TYPE)base, DIR_OFFSET_SOC) |= (0x01 << GPIO_ID(pin)); + } +} + +static inline __attribute__((always_inline)) +void directWriteLow(volatile IO_REG_TYPE *base, IO_REG_TYPE pin) +{ + if (SS_GPIO == GPIO_TYPE(pin)) { + WRITE_ARC_REG(READ_ARC_REG(base) & ~(0x01 << GPIO_ID(pin)), base); + } else { + MMIO_REG_VAL(base) &= ~(0x01 << GPIO_ID(pin)); + } +} + +static inline __attribute__((always_inline)) +void directWriteHigh(volatile IO_REG_TYPE *base, IO_REG_TYPE pin) +{ + if (SS_GPIO == GPIO_TYPE(pin)) { + WRITE_ARC_REG(READ_ARC_REG(base) | (0x01 << GPIO_ID(pin)), base); + } else { + MMIO_REG_VAL(base) |= (0x01 << GPIO_ID(pin)); + } +} + +#define DIRECT_READ(base, pin) directRead(base, pin) +#define DIRECT_MODE_INPUT(base, pin) directModeInput(base, pin) +#define DIRECT_MODE_OUTPUT(base, pin) directModeOutput(base, pin) +#define DIRECT_WRITE_LOW(base, pin) directWriteLow(base, pin) +#define DIRECT_WRITE_HIGH(base, pin) directWriteHigh(base, pin) + +#elif defined(__riscv) + +/* + * Tested on highfive1 + * + * Stable results are achieved operating in the + * two high speed modes of the highfive1. It + * seems to be less reliable in slow mode. + */ +#define PIN_TO_BASEREG(pin) (0) +#define PIN_TO_BITMASK(pin) digitalPinToBitMask(pin) +#define IO_REG_TYPE uint32_t +#define IO_REG_BASE_ATTR +#define IO_REG_MASK_ATTR + +static inline __attribute__((always_inline)) +IO_REG_TYPE directRead(IO_REG_TYPE mask) +{ + return ((GPIO_REG(GPIO_INPUT_VAL) & mask) != 0) ? 1 : 0; +} + +static inline __attribute__((always_inline)) +void directModeInput(IO_REG_TYPE mask) +{ + GPIO_REG(GPIO_OUTPUT_XOR) &= ~mask; + GPIO_REG(GPIO_IOF_EN) &= ~mask; + + GPIO_REG(GPIO_INPUT_EN) |= mask; + GPIO_REG(GPIO_OUTPUT_EN) &= ~mask; +} + +static inline __attribute__((always_inline)) +void directModeOutput(IO_REG_TYPE mask) +{ + GPIO_REG(GPIO_OUTPUT_XOR) &= ~mask; + GPIO_REG(GPIO_IOF_EN) &= ~mask; + + GPIO_REG(GPIO_INPUT_EN) &= ~mask; + GPIO_REG(GPIO_OUTPUT_EN) |= mask; +} + +static inline __attribute__((always_inline)) +void directWriteLow(IO_REG_TYPE mask) +{ + GPIO_REG(GPIO_OUTPUT_VAL) &= ~mask; +} + +static inline __attribute__((always_inline)) +void directWriteHigh(IO_REG_TYPE mask) +{ + GPIO_REG(GPIO_OUTPUT_VAL) |= mask; +} + +#define DIRECT_READ(base, mask) directRead(mask) +#define DIRECT_WRITE_LOW(base, mask) directWriteLow(mask) +#define DIRECT_WRITE_HIGH(base, mask) directWriteHigh(mask) +#define DIRECT_MODE_INPUT(base, mask) directModeInput(mask) +#define DIRECT_MODE_OUTPUT(base, mask) directModeOutput(mask) + +#else +#define PIN_TO_BASEREG(pin) (0) +#define PIN_TO_BITMASK(pin) (pin) +#define IO_REG_TYPE unsigned int +#define IO_REG_BASE_ATTR +#define IO_REG_MASK_ATTR +#define DIRECT_READ(base, pin) digitalRead(pin) +#define DIRECT_WRITE_LOW(base, pin) digitalWrite(pin, LOW) +#define DIRECT_WRITE_HIGH(base, pin) digitalWrite(pin, HIGH) +#define DIRECT_MODE_INPUT(base, pin) pinMode(pin,INPUT) +#define DIRECT_MODE_OUTPUT(base, pin) pinMode(pin,OUTPUT) +#warning "OneWire. Fallback mode. Using API calls for pinMode,digitalRead and digitalWrite. Operation of this library is not guaranteed on this architecture." + +#endif + +#endif diff --git a/src/OneWire/util/OneWire_direct_regtype.h b/src/OneWire/util/OneWire_direct_regtype.h new file mode 100644 index 0000000..21c4634 --- /dev/null +++ b/src/OneWire/util/OneWire_direct_regtype.h @@ -0,0 +1,52 @@ +#ifndef OneWire_Direct_RegType_h +#define OneWire_Direct_RegType_h + +#include + +// Platform specific I/O register type + +#if defined(__AVR__) +#define IO_REG_TYPE uint8_t + +#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__) +#define IO_REG_TYPE uint8_t + +#elif defined(__IMXRT1052__) || defined(__IMXRT1062__) +#define IO_REG_TYPE uint32_t + +#elif defined(__MKL26Z64__) +#define IO_REG_TYPE uint8_t + +#elif defined(__SAM3X8E__) || defined(__SAM3A8C__) || defined(__SAM3A4C__) +#define IO_REG_TYPE uint32_t + +#elif defined(__PIC32MX__) +#define IO_REG_TYPE uint32_t + +#elif defined(ARDUINO_ARCH_ESP8266) +#define IO_REG_TYPE uint32_t + +#elif defined(ARDUINO_ARCH_ESP32) +#define IO_REG_TYPE uint32_t +#define IO_REG_MASK_ATTR + +#elif defined(ARDUINO_ARCH_STM32) +#define IO_REG_TYPE uint32_t + +#elif defined(__SAMD21G18A__) +#define IO_REG_TYPE uint32_t + +#elif defined(RBL_NRF51822) +#define IO_REG_TYPE uint32_t + +#elif defined(__arc__) /* Arduino101/Genuino101 specifics */ +#define IO_REG_TYPE uint32_t + +#elif defined(__riscv) +#define IO_REG_TYPE uint32_t + +#else +#define IO_REG_TYPE unsigned int + +#endif +#endif diff --git a/src/common.h b/src/common.h new file mode 100644 index 0000000..2c48f31 --- /dev/null +++ b/src/common.h @@ -0,0 +1,138 @@ +#ifndef _MY_STUFF_H_INCLUDED +#define _MY_STUFF_H_INCLUDED + +#include "./DallasTemperature/DallasTemperature.h" +// #include // NAN + +#define _VERSION_MAJOR 0 +#define _VERSION_MINOR 0 +#define _VERSION_MICRO 1 +#define _VERSION_NUMBER _VERSION_MICRO | (_VERSION_MINOR << 6) | (_VERSION_MAJOR << 12) +#define _VERSION_STRING "v0.0.1" + +#define _DEBUG 1 +#define _DEBUG_SENSORS 0 +#define _MODBUS 1 + +#if _DEBUG == 1 +#define _print(x) Serial.print(x) +#define _println(x) Serial.println(x) +#if _DEBUG_SENSORS == 1 +#define _prints(x) Serial.print(x) +#define _printsln(x) Serial.println(x) +#else +#define _prints(x) +#define _printsln(x) +#endif +#else +#define _print(x) +#define _println(x) +#define _prints(x) +#define _printsln(x) +#endif + +#define _REGS_INFRONTOF_EVENTS 6 +#define _MODBUS_MAX_EVENTS 234 // Ergibt sich aus 0xF0 - 0x06 + +#if _MODBUS == 1 +#include "modbus/ModbusRTUSlave.h" +extern bool timeStampOverflow; +extern unsigned long timeStamp; +extern u8 &valves; +extern u16 &eventCounter; +extern u16 modbusData[]; +#define _setModbusValve(index, val)\ + if (bitRead(valves, index) != val) {\ + bitWrite(valves, index, val);\ + bitWrite(modbusData[1], index+8, val);\ + if (eventCounter < _MODBUS_MAX_EVENTS) {\ + /* Die ersten 12 Bits beinhalten den relativen Zeitstempel in Zehntelsekunden */\ + /* Dieser Stempel ist immer 0xFFF, falls schon zuviel Zeit seit der letzten Referenzierung vergangen ist */\ + u16 result = (timeStampOverflow) ? 0xFFF : ((millis() - timeStamp) / 100) & 0xFFF;\ + /* Die Bits 12...14 beinhalten die Nr des geschalteten Ausgangs */\ + result |= index << 12;\ + /* Das MSB gibt an, ob der Ausgang ein- oder ausgeschaltet wurde */\ + result |= val << 15;\ + modbusData[_REGS_INFRONTOF_EVENTS + eventCounter] = result;\ + eventCounter++;\ + }\ + } +#define _setModbusValue(index, val) modbusData[index] = val +#else +#define _setModbusValve(index, val) +#define _setModbusValue(index, val) +#endif // _MODBUS == + +#define _MODBUS_ADDR_MIN 1 +#define _MODBUS_ADDR_MAX 247 // Laut QModMaster letzte Adresse +#define _MODBUS_DELAY_MIN 0 // 1/10 Millisekunden +#define _MODBUS_DELAY_MAX 250 // 1/10 Millisekunden +#define _MODBUS_INVALID_BAUDRATE 4294967295 + +#define _MODBUS_VALVE_T1_INDEX 0 +#define _MODBUS_VALVE_T2_INDEX 1 +#define _MODBUS_VALVE_PR_INDEX 2 +#define _MODBUS_VALVE_PF_INDEX 3 +#define _MODBUS_T1_INDEX 2 +#define _MODBUS_T2_INDEX 3 +#define _MODBUS_P_INDEX 4 + +#define _SENSOR_FAULT 0xFFFF + +#define _STD_TEMP_SETPOINT 400 // Hundertstel +#define _STD_TEMP_HYSTERESIS 10 // Hundertstel +#define _STD_P_SETPOINT 100 // Hundertstel +#define _STD_P_HYSTERESIS 5 // Hundertstel +#define _STD_P_EN_INC 1 +#define _STD_P_EN_DEC 1 +#define _STD_T_EN 1 +#define _STD_C_EN 0 +#define _MIN_TEMP_SETPOINT 10 // Hundertstel +#define _MAX_TEMP_SETPOINT 3000 // Hundertstel +#define _MIN_TEMP_HYSTERESIS 1 // Hundertstel +#define _MAX_TEMP_HYSTERESIS 100 // Hundertstel +#define _MIN_P_SETPOINT 0 // Hundertstel +#define _MAX_P_SETPOINT 300 // Hundertstel +#define _MIN_P_HYSTERESIS 1 // Hundertstel +#define _MAX_P_HYSTERESIS 50 // Hundertstel + +#define _P_SENSOR_1_5V_0_5BAR 1 +#define _P_SENSOR_0_5V_0_6BAR 2 + +enum PSensor : uint8_t { + SMC_1_5V_0_5BAR=1, // Sensor mit Kabel + GEMS_0_5V_0_6BAR // Sensor mit Würfelstecker +}; + +struct parameters { // Prozesswerte + int16_t ts1 = _SENSOR_FAULT; // Soll-Temperatur 1 in 1/100 °C + int16_t th1 = _SENSOR_FAULT; // Hysterese für Temperatur 1 (1/100) + int16_t ts2 = _SENSOR_FAULT; // Soll-Temperatur 2 in 1/100 °C + int16_t th2 = _SENSOR_FAULT; // Hysterese für Temperatur 2 (1/100) + int16_t ps = _SENSOR_FAULT; // Druck in bar + int16_t ph = _SENSOR_FAULT; // Hysterese für Druck + uint8_t tEn = 255; // Kühlung (de)aktiviert + uint8_t pInc = 255; // Drucksteigerung (de)aktiviert + uint8_t pDec = 255; // Druckabfall (de)aktiviert + uint8_t cEn = 255; // Controller (de)aktiviert +}; + +struct values { // aktuelle Messwerte + int16_t t1 = _SENSOR_FAULT; // Temperatur in 1/100 °C + int16_t p = _SENSOR_FAULT; // Druck in 1/100 bar +}; + +struct modbusParameters { // Parameter für Modbus + uint32_t baudrate = _MODBUS_INVALID_BAUDRATE; // Modbus-Baudrate + uint8_t address = 255; // Modbus-Adresse + uint8_t delay = 255; // delay in 1/10 ms vor der Antwort +}; + +struct valveStates { + bool t1; + bool t2; + bool pInc; + bool pDec; +}; + +#endif // _MY_STUFF_H_INCLUDED diff --git a/src/controller/controller.cpp b/src/controller/controller.cpp new file mode 100644 index 0000000..ee92aa1 --- /dev/null +++ b/src/controller/controller.cpp @@ -0,0 +1,219 @@ +#include "controller.h" + +Controller::Controller(const uint8_t pAnalaogPin, + const uint8_t oneWirePin, + parameters *p, + values *v, + Display *d, + PSensor *s, + valveStates *vStates, + const uint8_t t1Pin, + const uint8_t t2Pin, + const uint8_t pRisePin, + const uint8_t pFallPin) + : _aPin(pAnalaogPin) + , _oneWire(oneWirePin) + , _params(p) + , _vals(v) + , _display(d) + , _pSensor(s) + , _vStates(vStates) + , _prPin(pRisePin) + , _pfPin(pFallPin) + , _t1Pin(t1Pin) + , _t2Pin(t2Pin) + , _dallas(&_oneWire) +{ + pinMode(_prPin, OUTPUT); + pinMode(_pfPin, OUTPUT); + pinMode(_t1Pin, OUTPUT); + pinMode(_t2Pin, OUTPUT); + digitalWrite(_prPin, 0); + digitalWrite(_pfPin, 0); + digitalWrite(_t1Pin, 0); + digitalWrite(_t2Pin, 0); + _vStates->pInc = false; + _vStates->pDec = false; + _vStates->t1 = false; +} + +void Controller::init(bool startup=false) +{ + _dallas.begin(); + _dallas.setWaitForConversion(false); + const uint8_t maxDevices = 1; + uint8_t deviceCount = _dallas.getDS18Count(); + if (deviceCount > maxDevices) { + _display->tooMuchOneWireDevicesDetected(deviceCount, maxDevices); + } else if (!deviceCount) { + _display->noOneWireDevicesDetected(); + } else { + _initOk = true; + _dallas.getAddress(_tempAddr1, 0); + _dallas.setResolution(12); + if (!startup) + _display->oneWireDevicesDetected(deviceCount); + } +} + +void Controller::process() +{ + if (_initOk && millis() - _lastConversion > _CONVERSION_DELAY) { + _lastConversion = millis(); + _requestConversion = true; + float temp = _dallas.getTempC(_tempAddr1); + if (temp == DEVICE_DISCONNECTED_C) + _vals->t1 = _SENSOR_FAULT; + else + _vals->t1 = temp * 100; + _prints("Temp: "); _prints(_vals->t1); + if (_vals->t1 != _SENSOR_FAULT && _params->tEn && _params->cEn) { + switch (_tState) { + case stateIdle: + _printsln(", case stateIdle"); + if (_vals->t1 < _params->ts1 - _params->th1) { + _setT1Valve(0, stateRising); + _prints(" -> rising"); + } else if (_vals->t1 > _params->ts1 + _params->th1) { + _setT1Valve(1, stateFalling); + _prints(" -> falling"); + } + _printsln(); + break; + case stateRising: + _prints(", case stateRising"); + if (_vals->t1 > _params->ts1 + _params->th1) { + _setT1Valve(1, stateIdle); + _prints(" -> idle"); + } + _printsln(); + break; + case stateFalling: + _prints(", case stateFalling"); + if (_vals->t1 < _params->ts1 - _params->th1) { + _setT1Valve(0, stateIdle); + _prints(" -> idle"); + } + _printsln(); + break; + } + } else { + _setT1Valve(0, stateIdle); + _printsln(); + } + _setModbusValue(_MODBUS_T1_INDEX, _vals->t1); + } else if (_requestConversion) { + _requestConversion = false; + _dallas.requestTemperatures(); + } + if (millis() - _lastAnalogRead > _ANALOG_READ_DELAY) { + _lastAnalogRead = millis(); + _rawP = analogRead(_aPin); + _prints("_rawP: "); _prints(_rawP); + switch (*_pSensor) { + case SMC_1_5V_0_5BAR: + float p = (float) _rawP / 2.046f; // 1023 / 5 * 100 (0-5 1/100 bar) + p = (p - 1) * 1.25f; // 1...5 V Sensor + _prints(" (Gems), p: "); _prints(p); + if (p < -0.5f) // Sensor ist definitiv nicht angeschlossen + _vals->p = _SENSOR_FAULT; + else if (p < 0) // Bei kleiner Toleranz ein bisschen schwindeln ;-) + _vals->p = 0; + else + _vals->p = p; + break; + case GEMS_0_5V_0_6BAR: + _vals->p = (float) _rawP / 1.705f; // 1023 / 6 * 100 (0-5 1/100 bar) + _prints(" (Gems), p: "); _prints(_vals->p); + } + _setModbusValue(_MODBUS_P_INDEX, _vals->p); + if (_vals->p != _SENSOR_FAULT && _params->cEn) { + switch (_pState) { + case stateIdle: + _prints(", case stateIdle"); + if (_vals->p < _params->ps - _params->ph) { + if (_params->pInc) { + _printsln(" -> stateRising"); + _setPValves(stateRising); + } else { + _printsln(); + _setPValves(stateIdle); + } + } else if (_vals->p > _params->ps + _params->ph) { + if (_params->pDec) { + _printsln(" -> stateFalling"); + _setPValves(stateFalling); + } else { + _printsln(); + _setPValves(stateIdle); + } + } else _printsln(); + break; + case stateRising: + _prints(", case stateRising"); + if ((_params->pInc && _vals->p > _params->ps) || !_params->pInc) { + _prints(" -> stateIdle"); + _setPValves(stateIdle); + } + _printsln(); + break; + case stateFalling: + _prints(", case stateFalling"); + if ((_params->pDec && _vals->p < _params->ps) || !_params->pDec) { + _prints(" -> stateIdle"); + _setPValves(stateIdle); + } + _printsln(); + break; + } + } else { + _printsln(); + _setPValves(stateIdle); + } + _prints("_vStates->pInc: "); _prints(_vStates->pInc); + _prints(", _vStates->pDec: "); _printsln(_vStates->pDec); + } +} + +void Controller::_setT1Valve(uint8_t val, States state) +{ + _tState = state; + digitalWrite(_t1Pin, val); + _vStates->t1 = val; + _setModbusValve(_MODBUS_VALVE_T1_INDEX, val); +} + +void Controller::_setPValves(States state) +{ + _pState = state; + switch (state) { + case stateRising: + digitalWrite(_prPin, 1); + _vStates->pInc = true; + _setModbusValve(_MODBUS_VALVE_PR_INDEX, 1); + digitalWrite(_pfPin, 0); + _vStates->pDec = false; + _setModbusValve(_MODBUS_VALVE_PF_INDEX, 0); + break; + case stateFalling: + digitalWrite(_pfPin, 1); + _vStates->pDec = true; + _setModbusValve(_MODBUS_VALVE_PF_INDEX, 1); + digitalWrite(_prPin, 0); + _vStates->pInc = false; + _setModbusValve(_MODBUS_VALVE_PR_INDEX, 0); + break; + default: // idle valves + digitalWrite(_pfPin, 0); + _vStates->pDec = false; + _setModbusValve(_MODBUS_VALVE_PF_INDEX, 0); + digitalWrite(_prPin, 0); + _vStates->pInc = false; + _setModbusValve(_MODBUS_VALVE_PR_INDEX, 0); + } +} + +// uint16_t Controller::_convertFloat(const float &x) +// { +// return (uint16_t) (x * 100); +// } diff --git a/src/controller/controller.h b/src/controller/controller.h new file mode 100644 index 0000000..947a5af --- /dev/null +++ b/src/controller/controller.h @@ -0,0 +1,66 @@ +#ifndef MY_CONTROLLER_H_INCLUDED +#define MY_CONTROLLER_H_INCLUDED + +#include "../OneWire/OneWire.h" +#include "../DallasTemperature/DallasTemperature.h" +#include "../display/display.h" +#include "../common.h" + +#define _CONVERSION_DELAY 800 +#define _ANALOG_READ_DELAY 500 + +class Controller +{ +private: + const uint8_t _aPin; + parameters *_params; + values *_vals; + Display *_display; + PSensor *_pSensor; + valveStates *_vStates; + uint8_t _prPin; + uint8_t _pfPin; + uint8_t _t1Pin; + uint8_t _t2Pin; + + OneWire _oneWire; + DallasTemperature _dallas; + DeviceAddress _tempAddr1; + + enum States : uint8_t { + stateIdle, stateRising, stateFalling + }; + States _tState = stateIdle; + States _pState = stateIdle; + + bool _initOk = false; + bool _requestConversion; + unsigned long _lastConversion; + unsigned long _lastAnalogRead; + uint16_t _rawP; + + // void _setTState(States curr, States next); + // void _setPState(States curr, States next); + void _setT1Valve(uint8_t, States); + void _setPValves(States); + // uint16_t _convertFloat(const float &x); + + public: + Controller(const uint8_t pAnalaogPin, + const uint8_t oneWirePin, + parameters *p, + values *vals, + Display *d, + PSensor *s, + valveStates *vStates, + const uint8_t pRisePin, + const uint8_t t1Pin, + const uint8_t t2Pin, + const uint8_t pFallPin + ); + + void init(bool startup=false); + void process(); +}; + +#endif // MY_CONTROLLER_H_INCLUDED diff --git a/src/display/display.cpp b/src/display/display.cpp new file mode 100644 index 0000000..c912e92 --- /dev/null +++ b/src/display/display.cpp @@ -0,0 +1,753 @@ +#include +#include "../DallasTemperature/DallasTemperature.h" +#include "display.h" + +Display::Display( + uint8_t cs, + uint8_t btnNext, + uint8_t btnPrev, + uint8_t btnSelect, + uint8_t btnCancel, + uint8_t bgLED, + parameters *params, + values *vals, + modbusParameters *modbus, + PSensor *sensor, + valveStates *vStates) + : U8G2_ST7920_128X64_2_HW_SPI(U8G2_R0, cs) + , btnNext(btnNext) + , btnPrev(btnPrev) + , btnSelect(btnSelect) + , btnCancel(btnCancel) + , bgLed(bgLED) + , _params(params) + , _vals(vals) + , _modbusParams(modbus) + , _pSensor(sensor) + , _vStates(vStates) +{ +} + +void Display::process() +{ + switch (_event()) { + case _BACK_TO_HOME_SCREEN: + _selection = 0; + _home(); + return; + case U8X8_MSG_GPIO_MENU_NEXT: + _nextEvent(); + _select(); + break; + case U8X8_MSG_GPIO_MENU_PREV: + _prevEvent(); + _select(); + break; + case U8X8_MSG_GPIO_MENU_SELECT: + if (_selection) { + parameters params; + modbusParameters modbus; + switch (_selection) { + case _MENU_MAIN: + _saveCursorPosForLevel(MenuLevel_1); + switch (_prevCursor) { + case _POS_TEMPERATURE_MENU: + _select(_MENU_TEMPERATURE); + break; + case _POS_PRESSURE_MENU: + _select(_MENU_PRESSURE); + break; + case _POS_SYSTEM: + _restrictInputValue(0, 255); + _select(_VERIFY_ADMIN); + break; + case _POS_RESET: + _select(_SELECTION_RESET); + break; + } + break; + case _MENU_TEMPERATURE: + _saveCursorPosForLevel(MenuLevel_2); + switch (_prevCursor) { + case _POS_TEMPERATURE_ENABLED: + _cursor = _params->tEn; + _select(_SELECTION_TEMPERATURE_ENABLED); + break; + case _POS_TEMPERATURE_SETPOINT: + _val = _params->ts1; + _restrictInputValue(_MIN_TEMP_SETPOINT, _MAX_TEMP_SETPOINT, Precision_2); + _select(_SELECTION_TEMPERATURE_SETPOINT); + break; + case _POS_TEMPERATURE_HYSTERESIS: + _val = _params->th1; + _restrictInputValue(_MIN_TEMP_HYSTERESIS, _MAX_TEMP_HYSTERESIS, Precision_2); + _select(_SELECTION_TEMPERATURE_HYSTERESIS); + break; + } + break; + case _MENU_PRESSURE: + _saveCursorPosForLevel(MenuLevel_2); + switch (_prevCursor) { + case _POS_PRESSURE_ENABLE_INCREASE: + _cursor = _params->pInc; + _select(_SELECTION_PRESSURE_ENABLE_INCREASE); + break; + case _POS_PRESSURE_ENABLE_DECREASE: + _cursor = _params->pDec; + _select(_SELECTION_PRESSURE_ENABLE_DECREASE); + break; + case _POS_PRESSURE_SETPOINT: + _val = _params->ps; + _restrictInputValue(_MIN_P_SETPOINT, _MAX_P_SETPOINT, Precision_2); + _select(_SELECTION_PRESSURE_SETPOINT); + break; + case _POS_PRESSURE_HYSTERESIS: + _val = _params->ph; + _restrictInputValue(_MIN_P_HYSTERESIS, _MAX_P_HYSTERESIS, Precision_2); + _select(_SELECTION_PRESSURE_HYSTERESIS); + break; + } + break; + case _MENU_SYSTEM: + _saveCursorPosForLevel(MenuLevel_2); + switch (_prevCursor) { + case _POS_MODBUS_MENU: + _select(_MENU_SETTINGS_MODBUS); + break; + case _POS_P_SENSOR_SELECTION: + _cursor = (*_pSensor) - 1; + _select(_SELECTION_P_SENSOR); + break; + } + break; + case _MENU_SETTINGS_MODBUS: + _saveCursorPosForLevel(MenuLevel_3); + switch (_prevCursor) { + case _POS_MODBUS_ADDRESS: + _val = _modbusParams->address; + _restrictInputValue(_MODBUS_ADDR_MIN, _MODBUS_ADDR_MAX); + _select(_SELECTION_MODBUS_ADDRESS); + break; + case _POS_MODBUS_BAUDRATE: + _baudrateCursorPos(); + _select(_SELECTION_MODBUS_BAUDRATE); + break; + case _POS_MODBUS_DELAY: + _val = _modbusParams->delay; + _restrictInputValue(_MODBUS_DELAY_MIN, _MODBUS_DELAY_MAX, Precision_1); + _select(_SELECTION_MODBUS_DELAY); + break; + } + break; + case _SELECTION_TEMPERATURE_ENABLED: + params.tEn = _cursor; + setParams(params); + _select(_MENU_TEMPERATURE, true); + break; + case _SELECTION_TEMPERATURE_SETPOINT: + // Serial.print("\n_val : "); Serial.println((float) _val); + // Serial.print("_val / 100: "); Serial.println(((float) _val) / 100); + params.ts1 = _val; + setParams(params); + _select(_MENU_TEMPERATURE, true); + break; + case _SELECTION_TEMPERATURE_HYSTERESIS: + params.th1 = _val; + setParams(params); + _select(_MENU_TEMPERATURE, true); + break; + case _SELECTION_PRESSURE_ENABLE_INCREASE: + params.pInc = _cursor; + setParams(params); + _select(_MENU_PRESSURE, true); + break; + case _SELECTION_PRESSURE_ENABLE_DECREASE: + params.pDec = _cursor; + setParams(params); + _select(_MENU_PRESSURE, true); + break; + case _SELECTION_PRESSURE_SETPOINT: + params.ps = _val; + setParams(params); + _select(_MENU_PRESSURE, true); + break; + case _SELECTION_PRESSURE_HYSTERESIS: + params.ph = _val; + setParams(params); + _select(_MENU_PRESSURE, true); + break; + case _SELECTION_MODBUS_BAUDRATE: + _setModbusBaudrate(); + _select(_MENU_SETTINGS_MODBUS, true); + break; + case _SELECTION_MODBUS_ADDRESS: + modbus.address = _val; + setModbusParams(modbus); + _select(_MENU_SETTINGS_MODBUS, true); + break; + case _SELECTION_MODBUS_DELAY: + modbus.delay = _val; + setModbusParams(modbus); + _select(_MENU_SETTINGS_MODBUS, true); + break; + case _SELECTION_P_SENSOR: + switch (_cursor) { + case _POS_P_SMC_1_5V_0_5BAR: + setPSensor(SMC_1_5V_0_5BAR); + break; + case _POS_P_GEMS_0_5V_0_6BAR: + setPSensor(GEMS_0_5V_0_6BAR); + break; + } + _restoreCursor(); + _select(_MENU_SYSTEM); + break; + case _VERIFY_ADMIN: + if (_val == _ADMIN_CODE) { + _select(_MENU_SYSTEM); + } else { + _restoreCursor(); + _select(_MENU_MAIN); + } + _val = 0; + break; + case _SELECTION_RESET: + if (_cursor == 1) { + reset(); + } else { + _restoreCursor(); + _select(_MENU_MAIN); + } + break; + } + } + break; + case U8X8_MSG_GPIO_MENU_HOME: + if (_selection) { + _val = 0; + if (!_restoreCursor()) { + _home(); + return; + } + switch (_selection) { + case _MENU_MAIN: + _selection = 0; + _home(); + return; + case _SELECTION_TEMPERATURE_ENABLED: + case _SELECTION_TEMPERATURE_SETPOINT: + case _SELECTION_TEMPERATURE_HYSTERESIS: + _select(_MENU_TEMPERATURE); + break; + case _SELECTION_PRESSURE_ENABLE_INCREASE: + case _SELECTION_PRESSURE_ENABLE_DECREASE: + case _SELECTION_PRESSURE_SETPOINT: + case _SELECTION_PRESSURE_HYSTERESIS: + _select(_MENU_PRESSURE); + break; + case _MENU_SETTINGS_MODBUS: + case _SELECTION_P_SENSOR: + _select(_MENU_SYSTEM); + break; + case _SELECTION_MODBUS_ADDRESS: + case _SELECTION_MODBUS_BAUDRATE: + case _SELECTION_MODBUS_DELAY: + _select(_MENU_SETTINGS_MODBUS); + break; + default: + _select(_MENU_MAIN); + } + } + break; + } + if (millis() - _prevT > 250) { + _prevT = millis(); + if (!_selection) { + _home(); + } + } +} + +void Display::_select(const uint8_t selection, const bool restoreCursor=false) +{ + if (restoreCursor) + _restoreCursor(); + _selection = selection; + _select(); +} + +void Display::_select() +{ + setFont(_SEL_FONT); + setFontRefHeightAll(); + _inputValueActive = false; + _stepSize = 1; + switch (_selection) { + case _MENU_MAIN: + _menu_depth = 0; + sprintf(_text, "Hauptmenü (%s)", _VERSION_STRING); + _selCnt = my_UserInterfaceSelectionList(&u8g2, _text, _cursor, "Temperatur\nDruck\nSystem\nReset"); + break; + case _MENU_TEMPERATURE: + _menu_depth = 1; + _selCnt = my_UserInterfaceSelectionList(&u8g2, "Temperatur", _cursor, "Kühlung de/aktivieren\nSollwert\nHysterese"); + break; + case _SELECTION_TEMPERATURE_ENABLED: + _menu_depth = 2; + _selCnt = my_UserInterfaceMessage(&u8g2, "Kühlung", nullptr, "aktivieren", " nein \n ja ", _cursor); + break; + case _SELECTION_TEMPERATURE_SETPOINT: + _menu_depth = 2; + _inputValue(5, "Temperatur\nSollwert", "__float__"); + break; + case _SELECTION_TEMPERATURE_HYSTERESIS: + _menu_depth = 2; + _inputValue(5, "Temperatur\nHysterese", "__float__"); + break; + case _MENU_PRESSURE: + _menu_depth = 1; + _selCnt = my_UserInterfaceSelectionList(&u8g2, "Druck", _cursor, "Drucksteigerung\nDruckabfall\nSollwert\nHysterese"); + break; + case _SELECTION_PRESSURE_ENABLE_INCREASE: + _menu_depth = 2; + _selCnt = my_UserInterfaceMessage(&u8g2, "Drucksteigerung", nullptr, "aktivieren", " nein \n ja ", _cursor); + break; + case _SELECTION_PRESSURE_ENABLE_DECREASE: + _menu_depth = 2; + _selCnt = my_UserInterfaceMessage(&u8g2, "Druckabfall", nullptr, "aktivieren", " nein \n ja ", _cursor); + break; + case _SELECTION_PRESSURE_SETPOINT: + _menu_depth = 2; + _inputValue(5, "Druck\nSollwert", "__float__"); + break; + case _SELECTION_PRESSURE_HYSTERESIS: + _menu_depth = 2; + _inputValue(5, "Druck\nHysterese", "__float__"); + break; + case _VERIFY_ADMIN: + _menu_depth = 1; + _inputValueActive = true; + sprintf(_text, "%d", _val); + my_UserInterfaceInputValueString(&u8g2, "Systemeinstellungen\nBerechtigung\nnachweisen:", nullptr, _text); + break; + case _MENU_SYSTEM: + _menu_depth = 1; + _selCnt = my_UserInterfaceSelectionList(&u8g2, "System", _cursor, "Modbus\nDrucksensor"); + break; + case _MENU_SETTINGS_MODBUS: + _menu_depth = 2; + _selCnt = my_UserInterfaceSelectionList(&u8g2, "Modbus", _cursor, "Adresse\nBaudrate\nAntwort-Delay"); + break; + case _SELECTION_MODBUS_BAUDRATE: + _menu_depth = 3; + _selCnt = my_UserInterfaceSelectionList(&u8g2, "Baudrate", _cursor, "300\n1200\n2400\n4800\n9600\n19200\n38400\n57600\n115200"); + break; + case _SELECTION_MODBUS_ADDRESS: + _menu_depth = 3; + sprintf(_text, "Dezimal: %d", _val); + _inputValue(1, "Modbus Adresse"); + break; + case _SELECTION_MODBUS_DELAY: + _menu_depth = 3; + sprintf(_text, "%d.%.d", _val / 10, _val % 10); + _inputValue(1, "Modbus\nAntwort-Verzögerung\nin Millisekunden"); + break; + case _SELECTION_P_SENSOR: + _menu_depth = 2; + _selCnt = my_UserInterfaceSelectionList(&u8g2, "Drucksensor", _cursor, "SMC: 1-5V,0-5 bar\nGems: 0-5V,0-6 bar"); + break; + case _SELECTION_RESET: + _menu_depth = 1; + _selCnt = my_UserInterfaceMessage(&u8g2, "Controller neustarten", "--------------------", "Wirklich neustarten?", " nein \n ja ", _cursor); + break; + default: + _menu_depth = 0; + } +} + +void Display::_home() +{ + // Das Display hat eine Auflösung von 128 x 64 Pixel + // Mit der Schriftart u8g2_font_ncenB10_te stellt \xb0 das °-Zeichen dar + int ts1a = _params->ts1 / 100; + int ts1b = _params->ts1 % 100; + int th1a = _params->th1 / 100; + int th1b = _params->th1 % 100; + int psa = _params->ps / 100; + int psb = _params->ps % 100; + int pha = _params->ph / 100; + int phb = _params->ph % 100; + bool cEn = _params->cEn; + bool tEn = (!cEn) ? false : _params->tEn; + bool pInc = (!cEn) ? false : _params->pInc; + bool pDec = (!cEn) ? false : _params->pDec; + bool pEn = pInc || pDec; + uint8_t pState = (_vStates->pInc) ? 1 : (_vStates->pDec) ? 2 : 0; + bool tState = _vStates->t1; + // %u in sprintf() geht nur bis uint16_t + String baudStr(_modbusParams->baudrate); + firstPage(); + do { + setFont(u8g2_font_fub20_tf); + if (_vals->t1 == _SENSOR_FAULT) + sprintf(_text, "--.-- \xb0\C"); + else + sprintf(_text, "%d.%.2d \xb0\C", _vals->t1 / 100, _vals->t1 % 100); + drawStr(0, 27, _text); + if (_vals->p == _SENSOR_FAULT) + sprintf(_text, "--.-- bar"); + else + sprintf(_text, "%d.%.2d bar", _vals->p / 100, _vals->p % 100); + drawStr(0, 57, _text); + //drawHLine(0, 57, 128); + setFont(u8g2_font_micro_tr); + //setFont(u8g2_font_5x7_tr); + sprintf(_text, "%d.%.2d+-%d.%.2d Regelung %saktiv", ts1a, ts1b, th1a, th1b, (tEn) ? "": "in"); + drawStr(0, 5, _text); + sprintf(_text, "%d.%.2d+-%d.%.2d P+ %s P- %s", psa, psb, pha, phb, (pInc) ? "ein": "aus", (pDec) ? "ein": "aus"); + drawStr(0, 35, _text); + // sprintf(_text, "Modbus Adr. %u, Baudr. %u", _modbusParams->address, _modbusParams->baudrate); + sprintf(_text, "Modbus Adr. %u, Baudr. %s", _modbusParams->address, baudStr.c_str()); + drawStr(0, 64, _text); + if (cEn) { + if (tEn) { + if (tState) { + setFont(u8g2_font_open_iconic_arrow_2x_t); + drawStr(112, 25, "\x58"); // Kreislaufsymbol + } + } else { + setFont(u8g2_font_open_iconic_check_2x_t); + drawStr(112, 25, "\x42"); // X in schwarzem Kreis + } + if (!pEn) { + setFont(u8g2_font_open_iconic_check_2x_t); + drawStr(112, 55, "\x42"); // X in schwarzem Kreis + } else if (pState == 1) { + setFont(u8g2_font_open_iconic_arrow_2x_t); + drawStr(112, 55, "\x4b"); // Pfeil rauf + } else if (pState == 2) { + setFont(u8g2_font_open_iconic_arrow_2x_t); + drawStr(112, 55, "\x48"); // Pfeil runter + } + } else { + setFont(u8g2_font_open_iconic_check_2x_t); + // drawStr(112, 25, "\x42"); // X in schwarzem Kreis + // drawStr(112, 55, "\x42"); // X in schwarzem Kreis + drawStr(112, 22, "\x42"); // X in schwarzem Kreis + drawStr(112, 58, "\x42"); // X in schwarzem Kreis + setFont(u8g2_font_open_iconic_embedded_2x_t); + drawStr(113, 40, "\x4e"); // Power-Symbol + // drawLine(0, 0, 128, 64); + // drawLine(128, 0, 0, 64); + } + + } while (nextPage()); +} + +void Display::init() +{ + pinMode(bgLed, OUTPUT); + digitalWrite(bgLed, true); + begin(btnSelect, btnNext, btnPrev, U8X8_PIN_NONE, U8X8_PIN_NONE, btnCancel); +} + +void Display::modbusProblem() +{ + firstPage(); + do { + setFont(_STD_FONT); + uint8_t y = _FIRS_LINE_Y; + drawStr(0, y, "Problem:"); + y += _STD_LINEHEIGHT; + drawStr(0, y, "Fehler Modbus"); + } while (nextPage()); +} + +void Display::oneWireDevicesDetected(uint8_t count) +{ + setFont(_SEL_FONT); + setFontRefHeightAll(); + sprintf(_text, "%u", count); + userInterfaceMessage("OneWire-Sensoren", "Erfolgreich erkannt:", _text, " OK "); +} + +void Display::tooMuchOneWireDevicesDetected(uint8_t actual, uint8_t max) +{ + setFont(_SEL_FONT); + setFontRefHeightAll(); + sprintf(_text, "%u (max: %u)", actual, max); + userInterfaceMessage("Fehler OneWire", "Zu viele Sensoren:", _text, " OK "); +} + +void Display::noOneWireDevicesDetected() +{ + setFont(_SEL_FONT); + setFontRefHeightAll(); + userInterfaceMessage("Fehler OneWire", "Keine Sensoren", "erkannt", " OK "); +} + +void Display::greeting() +{ + firstPage(); + do { + setFont(_STD_FONT); + uint8_t y = _FIRS_LINE_Y; + drawStr(0, y, "Dreher"); + y += _STD_LINEHEIGHT; + drawStr(0, y, "Brauanlagen"); + } while (nextPage()); +} + +void Display::bgLight(uint8_t value) +{ + _bgLightAnalog = value; + _bgLightBool = (value > 0) ? true : false; + analogWrite(bgLed, value); +} + +void Display::bgLight(bool state) +{ + _bgLightAnalog = (state) ? 255 : 0; + _bgLightBool = state; + digitalWrite(bgLed, state); +} + +bool Display::bgLightIncrease(uint8_t step) +{ + _bgLightBool = true; + if (_bgLightAnalog == 255) { + return true; + } + int val = (int) _bgLightAnalog; + if (val + step >= 255) { + _bgLightAnalog = 255; + digitalWrite(bgLed, true); + return true; + } else { + _bgLightAnalog += step; + analogWrite(bgLed, _bgLightAnalog); + } + return false; +} + +bool Display::bgLightDecrease(uint8_t step) +{ + if (_bgLightAnalog == 0) { + _bgLightBool = false; + return true; + } + int val = (int) _bgLightAnalog; + if (val - step <= 0) { + _bgLightAnalog = 0; + _bgLightBool = false; + digitalWrite(bgLed, false); + return true; + } else { + _bgLightBool = true; + _bgLightAnalog -= step; + analogWrite(bgLed, _bgLightAnalog); + } + return false; +} + +uint8_t Display::bgLightAnalog() +{ + return _bgLightAnalog; +} + +bool Display::bgLightState() +{ + return _bgLightBool; +} + +void Display::_baudrateCursorPos() +{ + switch (_modbusParams->baudrate) { + case 300: _cursor = _POS_BAUDRATE_300; break; + case 1200: _cursor = _POS_BAUDRATE_1200; break; + case 2400: _cursor = _POS_BAUDRATE_2400; break; + case 4800: _cursor = _POS_BAUDRATE_4800; break; + case 19200: _cursor = _POS_BAUDRATE_19200; break; + case 38400: _cursor = _POS_BAUDRATE_38400; break; + case 57600: _cursor = _POS_BAUDRATE_57600; break; + case 115200: _cursor = _POS_BAUDRATE_115200; break; + default: _cursor = _POS_BAUDRATE_9600; + } +} + +void Display::_setModbusBaudrate() +{ + modbusParameters params; + switch (_cursor) { + case _POS_BAUDRATE_300: params.baudrate = 300; break; + case _POS_BAUDRATE_1200: params.baudrate = 1200; break; + case _POS_BAUDRATE_2400: params.baudrate = 2400; break; + case _POS_BAUDRATE_4800: params.baudrate = 4800; break; + case _POS_BAUDRATE_19200: params.baudrate = 19200; break; + case _POS_BAUDRATE_38400: params.baudrate = 38400; break; + case _POS_BAUDRATE_57600: params.baudrate = 57600; break; + case _POS_BAUDRATE_115200: params.baudrate = 115200; break; + default: params.baudrate = 9600; + } + setModbusParams(params); +} + +uint8_t Display::_event() +{ + uint8_t event = getMenuEvent(); + if (event) + return event; + bool next = !digitalRead(btnNext); + bool prev = !digitalRead(btnPrev); + bool cancel = !digitalRead(btnCancel); + if (next || prev || cancel) { + if (millis() - _checkFastStepTime > _BEGIN_FAST_STEPS_DELAY) { + if (millis() - _lastFastStep > _FAST_STEP_MS) { + _lastFastStep = millis(); + if (next) + event = U8X8_MSG_GPIO_MENU_NEXT; + else if (prev) + event = U8X8_MSG_GPIO_MENU_PREV; + else if (cancel) + event = _BACK_TO_HOME_SCREEN; + if (millis() - _checkFastStepTime > _BEGIN_BIG_STEPS_DELAY) + _enableBigSteps = true; + } + } + } else { + _checkFastStepTime = millis(); + _enableBigSteps = false; + } + return event; +} + +void Display::_nextEvent() +{ + if (_selection) { + if (_inputValueActive) { + if (_val > _valMin) { + int step = (_enableBigSteps) ? _BIG_STEP * _stepSize : _stepSize; + if (_val - step > _valMin) + _val -= step; + else + _val = _valMin; + } + } else { + _cursor++; + if (_cursor >= _selCnt) { + _cursor = 0; + } + } + } else { + _selection = _MENU_MAIN; + } +} + +void Display::_prevEvent() +{ + if (_selection) { + if (_inputValueActive) { + if (_val < _valMax) { + int step = (_enableBigSteps) ? _BIG_STEP * _stepSize : _stepSize; + if (_val < step) + _val = step; + else if (_val + step < _valMax) + _val += step; + else + _val = _valMax; + } + } else { + if (_cursor == 0) { + _cursor = _selCnt; + } + _cursor--; + } + } else { + _selection = _MENU_MAIN; + } +} + +void Display::_saveCursorPosForLevel(MenuLevel level) +{ + switch (level) { + case MenuLevel_1: + _cur_l1 = _cursor; + break; + case MenuLevel_2: + _cur_l2 = _cursor; + break; + case MenuLevel_3: + _cur_l3 = _cursor; + break; + } + _prevCursor = _cursor; + _cursor = 0; +} + +void Display::_restrictInputValue(int min, int max, Precision p=Precision_0) +{ + char s1[10]; + char s2[10]; + switch (p) { + case Precision_1: + if (min % 10 == 0) + sprintf(s1, "%d", min / 10); + else + sprintf(s1, "%d.%.1d", min / 10, min % 10); + if (max % 10 == 0) + sprintf(s2, "%d", max / 10); + else + sprintf(s2, "%d.%.1d", max / 10, max % 10); + break; + case Precision_2: + if (min % 100 == 0) + sprintf(s1, "%d", min / 100); + else + sprintf(s1, "%d.%.2d", min / 100, min % 100); + if (max % 100 == 0) + sprintf(s2, "%d", max / 100); + else + sprintf(s2, "%d.%.2d", max / 100, max % 100); + break; + default: + sprintf(s1, "%d", min); + sprintf(s2, "%d", max); + } + _valMin = min; + _valMax = max; + sprintf(_text2, "min: %s, max: %s", s1, s2); +} + +void Display::_inputValue(const uint8_t stepSize, const char *title, const char *val=nullptr, const char *text=nullptr) +{ + if (!val) { + val = _text; + } else if (val == "__float__") { + sprintf(_text, "%d.%.2d", _val / 100, _val % 100); + val = _text; + } + if (!text) + text = _text2; + _inputValueActive = true; + _stepSize = stepSize; + my_UserInterfaceInputValueString(&u8g2, title, text, val); +} + +uint8_t Display::_restoreCursor() +{ + switch (_menu_depth) { + case 1: + _cursor = _cur_l1; + break; + case 2: + _cursor = _cur_l2; + break; + case 3: + _cursor = _cur_l3; + break; + default: + _cursor = 0; + _selection = 0; + } + return _menu_depth; +} diff --git a/src/display/display.h b/src/display/display.h new file mode 100644 index 0000000..449bd3d --- /dev/null +++ b/src/display/display.h @@ -0,0 +1,178 @@ +#ifndef MY_DISPLAY_H_INCLUDED +#define MY_DISPLAY_H_INCLUDED + +#include +#include "../common.h" + +//#define _STD_FONT u8g2_font_ncenB10_te +//#define _FIRS_LINE_Y 11 +//#define _STD_LINEHEIGHT 12 +#define _STD_FONT u8g2_font_fub11_tf +#define _FIRS_LINE_Y 12 +#define _STD_LINEHEIGHT 13 +#define _SEL_FONT u8g2_font_6x10_tf +#define _FIRS_LINE_Y 12 +#define _STD_LINEHEIGHT 13 +// Mit der Schriftart u8g2_font_ncenB10_te stellt \xb0 das °-Zeichen dar + +#define _BEGIN_FAST_STEPS_DELAY 500 +#define _BEGIN_BIG_STEPS_DELAY 3000 +#define _FAST_STEP_MS 50 +#define _BIG_STEP 10 + +#define _BACK_TO_HOME_SCREEN 1 + +#define _MENU_MAIN 1 +#define _MENU_SYSTEM 10 +#define _MENU_SETTINGS_MODBUS 11 +#define _MENU_TEMPERATURE 12 +#define _MENU_PRESSURE 13 +#define _SELECTION_TEMPERATURE_ENABLED 100 +#define _SELECTION_TEMPERATURE_SETPOINT 101 +#define _SELECTION_TEMPERATURE_HYSTERESIS 102 +#define _SELECTION_PRESSURE_ENABLE_INCREASE 110 +#define _SELECTION_PRESSURE_ENABLE_DECREASE 111 +#define _SELECTION_PRESSURE_SETPOINT 115 +#define _SELECTION_PRESSURE_HYSTERESIS 116 +#define _SELECTION_MODBUS_BAUDRATE 150 +#define _SELECTION_MODBUS_ADDRESS 151 +#define _SELECTION_MODBUS_DELAY 152 +#define _SELECTION_P_SENSOR 200 +#define _SELECTION_RESET 255 + +#define _VERIFY_ADMIN 253 +#define _ADMIN_CODE 42 + +#define _POS_TEMPERATURE_MENU 0 +#define _POS_TEMPERATURE_ENABLED 0 +#define _POS_TEMPERATURE_SETPOINT 1 +#define _POS_TEMPERATURE_HYSTERESIS 2 +#define _POS_PRESSURE_MENU 1 +#define _POS_PRESSURE_ENABLE_INCREASE 0 +#define _POS_PRESSURE_ENABLE_DECREASE 1 +#define _POS_PRESSURE_SETPOINT 2 +#define _POS_PRESSURE_HYSTERESIS 3 +#define _POS_SYSTEM 2 +#define _POS_MODBUS_MENU 0 +#define _POS_MODBUS_ADDRESS 0 +#define _POS_MODBUS_BAUDRATE 1 +#define _POS_MODBUS_DELAY 2 +#define _POS_P_SENSOR_SELECTION 1 +#define _POS_P_SMC_1_5V_0_5BAR 0 +#define _POS_P_GEMS_0_5V_0_6BAR 1 +#define _POS_RESET 3 + +#define _POS_BAUDRATE_300 0 +#define _POS_BAUDRATE_1200 1 +#define _POS_BAUDRATE_2400 2 +#define _POS_BAUDRATE_4800 3 +#define _POS_BAUDRATE_9600 4 +#define _POS_BAUDRATE_19200 5 +#define _POS_BAUDRATE_38400 6 +#define _POS_BAUDRATE_57600 7 +#define _POS_BAUDRATE_115200 8 + +extern "C" uint8_t my_UserInterfaceMessage(u8g2_t *u8g2, const char *title1, const char *title2, const char *title3, const char *buttons, uint8_t cursor); +extern "C" uint8_t my_UserInterfaceSelectionList(u8g2_t *u8g2, const char *title, uint8_t start_pos, const char *sl); +// extern "C" void my_UserInterfaceInputValue(u8g2_t *u8g2, const char *title, const char *pre, uint8_t value, uint8_t digits, const char *post); +extern "C" void my_UserInterfaceInputValueString(u8g2_t *u8g2, const char *title, const char *sub, const char *text); + +class Display : public U8G2_ST7920_128X64_2_HW_SPI +{ + +private: + enum MenuLevel : int8_t { + MenuLevel_1, MenuLevel_2, MenuLevel_3 + }; + enum Precision : int8_t { + Precision_0, Precision_1, Precision_2 + }; + + uint8_t _bgLightAnalog = 255; // Wie stark die Displaybeleuchtung ist + bool _bgLightBool = true; // Ob die Displaybeleuchtung an ist (egal wie stark) + char _text[50]; // Buffer für Texte + char _text2[30]; // Buffer für Texte + uint8_t _selection; // welche Auswahl gerendert werden soll + uint8_t _cursor; // aktuelle Auswahl-Cursorposition + uint8_t _prevCursor; // letzte Auswahl-Cursorposition + uint8_t _cur_l1; // Cursorposition in Ebene 1 + uint8_t _cur_l2; // Cursorposition in Ebene 2 + uint8_t _cur_l3; // Cursorposition in Ebene 3 + uint8_t _menu_depth; // Im wievielten Untermenü man gerade ist + uint8_t _selCnt; // Anzahl der Auswahlmöglichkeiten + bool _inputValueActive; // Ob gerade ein Wert eingegeben wird + int _val; // Der eingegebene Wert + int _valMin; // Der kleinstmögliche einzugebende Wert + int _valMax; // Der größtmögliche einzugebende Wert + unsigned long _prevT; + bool _enableBigSteps; // Ob große Schritte (_BIG_STEP) durchgeführt werden sollen + unsigned long _checkFastStepTime; // letzte Zeit, zu der ein entsprechender Button NICHT gedrückt war + unsigned long _lastFastStep; // letzte Zeit, zu der ein schneller Schritt ausgeführt wurde + int _stepSize; // Um wieviel der entsprechende Wert auf einmal geändert werden soll + // String _str1, _str2; + + parameters *_params; + values *_vals; + modbusParameters *_modbusParams; + PSensor *_pSensor; + valveStates *_vStates; + + void _saveCursorPosForLevel(MenuLevel); + uint8_t _restoreCursor(); + void _baudrateCursorPos(); + void _setModbusBaudrate(); + void _select(); + void _select(const uint8_t, const bool restoreCursor=false); + uint8_t _event(); + void _nextEvent(); + void _prevEvent(); + void _home(); + void _inputValue(const uint8_t stepSize, const char *title, const char *text=nullptr, const char *val=nullptr); + void _restrictInputValue(int min, int max, Precision p=Precision_0); + +public: + + const uint8_t btnNext; + const uint8_t btnPrev; + const uint8_t btnSelect; + const uint8_t btnCancel; + const uint8_t bgLed; + + Display(uint8_t cs, + uint8_t btnNext, + uint8_t btnPrev, + uint8_t btnSelect, + uint8_t btnCancel, + uint8_t bgLED, + parameters*, + values*, + modbusParameters*, + PSensor*, + valveStates*); + + void init(); + void process(); + + void modbusProblem(); + void oneWireDevicesDetected(uint8_t count); + void tooMuchOneWireDevicesDetected(uint8_t actual, uint8_t max); + void noOneWireDevicesDetected(); + void greeting(); + + void bgLight(uint8_t); + void bgLight(int val) {bgLight((uint8_t) val);}; + void bgLight(bool); + bool bgLightIncrease(uint8_t step=1); + bool bgLightDecrease(uint8_t step=1); + uint8_t bgLightAnalog(); + bool bgLightState(); + + void (*reset)() = 0; + + /* Callback-Funktionen */ + void(*setParams)(const parameters&); + void(*setModbusParams)(const modbusParameters&); + void(*setPSensor)(const PSensor&); +}; + +#endif // MY_DISPLAY_H_INCLUDED diff --git a/src/display/nonblockingUserinterface.cpp b/src/display/nonblockingUserinterface.cpp new file mode 100644 index 0000000..3a0dcf6 --- /dev/null +++ b/src/display/nonblockingUserinterface.cpp @@ -0,0 +1,340 @@ +/* + + nonblockingUserinterface.cpp + + These original files were modified to this file by brunotic: + U8g2/src/clib/u8g2_message.c + U8g2/src/clib/u8g2_selection_list.c + U8g2/src/clib/u8g2_input_value.c + + |---------------- + | ORIGINAL TEXT: + |---------------- + + Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) + + Copyright (c) 2016, olikraus@gmail.com + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. + + * 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. + + 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. + +*/ + +#include + +extern "C" { + +#define SPACE_BETWEEN_BUTTONS_IN_PIXEL 6 +#define SPACE_BETWEEN_TEXT_AND_BUTTONS_IN_PIXEL 3 + +static uint8_t my_draw_button_line(u8g2_t *u8g2, u8g2_uint_t y, u8g2_uint_t w, uint8_t cursor, const char *s) +{ + u8g2_uint_t button_line_width; + uint8_t i; + uint8_t cnt; + uint8_t is_invert; + u8g2_uint_t d; + u8g2_uint_t x; + cnt = u8x8_GetStringLineCnt(s); + /* calculate the width of the button line */ + button_line_width = 0; + for( i = 0; i < cnt; i++ ) { + button_line_width += u8g2_GetUTF8Width(u8g2, u8x8_GetStringLineStart(i, s)); + } + button_line_width += (cnt-1)*SPACE_BETWEEN_BUTTONS_IN_PIXEL; /* add some space between the buttons */ + /* calculate the left offset */ + d = 0; + if ( button_line_width < w ) { + d = w; + d -= button_line_width; + d /= 2; + } + /* draw the buttons */ + x = d; + for( i = 0; i < cnt; i++ ) { + is_invert = 0; + if ( i == cursor ) + is_invert = 1; + u8g2_DrawUTF8Line(u8g2, x, y, 0, u8x8_GetStringLineStart(i, s), 1, is_invert); + x += u8g2_GetUTF8Width(u8g2, u8x8_GetStringLineStart(i, s)); + x += SPACE_BETWEEN_BUTTONS_IN_PIXEL; + } + /* return the number of buttons */ + return cnt; +} + +/* + title1: Multiple lines,separated by '\n' + title2: A single line/string which is terminated by '\0' or '\n' . "title2" accepts the return value from u8x8_GetStringLineStart() + title3: Multiple lines,separated by '\n' + buttons: one more more buttons separated by '\n' and terminated with '\0' + cursor: highlighted cursor position + returns the number of buttons + side effects: + u8g2_SetFontDirection(u8g2, 0); + u8g2_SetFontPosBaseline(u8g2); +*/ + +uint8_t my_UserInterfaceMessage(u8g2_t *u8g2, const char *title1, const char *title2, const char *title3, const char *buttons, uint8_t cursor) +{ + uint8_t height; + uint8_t line_height; + u8g2_uint_t pixel_height; + u8g2_uint_t y, yy; + uint8_t button_cnt; + /* only horizontal strings are supported, so force this here */ + u8g2_SetFontDirection(u8g2, 0); + /* force baseline position */ + u8g2_SetFontPosBaseline(u8g2); + /* calculate line height */ + line_height = u8g2_GetAscent(u8g2); + line_height -= u8g2_GetDescent(u8g2); + /* calculate overall height of the message box in lines*/ + height = 1; /* button line */ + height += u8x8_GetStringLineCnt(title1); + if ( title2 != NULL ) + height++; + height += u8x8_GetStringLineCnt(title3); + /* calculate the height in pixel */ + pixel_height = height; + pixel_height *= line_height; + /* ... and add the space between the text and the buttons */ + pixel_height += SPACE_BETWEEN_TEXT_AND_BUTTONS_IN_PIXEL; + /* calculate offset from top */ + y = 0; + if ( pixel_height < u8g2_GetDisplayHeight(u8g2) ) { + y = u8g2_GetDisplayHeight(u8g2); + y -= pixel_height; + y /= 2; + } + y += u8g2_GetAscent(u8g2); + u8g2_FirstPage(u8g2); + do { + yy = y; + /* draw message box */ + yy += u8g2_DrawUTF8Lines(u8g2, 0, yy, u8g2_GetDisplayWidth(u8g2), line_height, title1); + if ( title2 != NULL ) { + u8g2_DrawUTF8Line(u8g2, 0, yy, u8g2_GetDisplayWidth(u8g2), title2, 0, 0); + yy+=line_height; + } + yy += u8g2_DrawUTF8Lines(u8g2, 0, yy, u8g2_GetDisplayWidth(u8g2), line_height, title3); + yy += SPACE_BETWEEN_TEXT_AND_BUTTONS_IN_PIXEL; + button_cnt = my_draw_button_line(u8g2, yy, u8g2_GetDisplayWidth(u8g2), cursor, buttons); + } while( u8g2_NextPage(u8g2) ); + return button_cnt; +} + +#define MY_BORDER_SIZE 1 + +/* + selection list with string line + returns line height +*/ +// static u8g2_uint_t my_draw_selection_list_line(u8g2_t *u8g2, u8sl_t *u8sl, u8g2_uint_t y, uint8_t idx, const char *s) U8G2_NOINLINE; +static u8g2_uint_t my_draw_selection_list_line(u8g2_t *u8g2, u8sl_t *u8sl, u8g2_uint_t y, uint8_t idx, const char *s) +{ + u8g2_uint_t yy; + uint8_t border_size = 0; + uint8_t is_invert = 0; + u8g2_uint_t line_height = u8g2_GetAscent(u8g2) - u8g2_GetDescent(u8g2) + MY_BORDER_SIZE; + /* calculate offset from display upper border */ + yy = idx; + yy -= u8sl->first_pos; + yy *= line_height; + yy += y; + /* check whether this is the current cursor line */ + if ( idx == u8sl->current_pos ) + { + border_size = MY_BORDER_SIZE; + is_invert = 1; + } + /* get the line from the array */ + s = u8x8_GetStringLineStart(idx, s); + /* draw the line */ + if ( s == NULL ) + s = ""; + u8g2_DrawUTF8Line(u8g2, MY_BORDER_SIZE, y, u8g2_GetDisplayWidth(u8g2) - 2 * MY_BORDER_SIZE, s, border_size, is_invert); + return line_height; +} + +static void my_DrawSelectionList(u8g2_t *u8g2, u8sl_t *u8sl, u8g2_uint_t y, const char *s) +{ + uint8_t i; + for( i = 0; i < u8sl->visible; i++ ) + { + y += my_draw_selection_list_line(u8g2, u8sl, y, i + u8sl->first_pos, s); + } +} + + +/* + title: NULL for no title, valid str for title line. Can contain mutliple lines, separated by '\n' + start_pos: default position for the cursor, first line is 1. + sl: string list (list of strings separated by \n) + returns the number of options (depending on sl) + side effects: + u8g2_SetFontDirection(u8g2, 0); + u8g2_SetFontPosBaseline(u8g2); + +*/ +uint8_t my_UserInterfaceSelectionList(u8g2_t *u8g2, const char *title, uint8_t start_pos, const char *sl) +{ + u8sl_t u8sl; + u8g2_uint_t yy; + u8g2_uint_t line_height = u8g2_GetAscent(u8g2) - u8g2_GetDescent(u8g2) + MY_BORDER_SIZE; + uint8_t title_lines = u8x8_GetStringLineCnt(title); + uint8_t display_lines; + // if ( start_pos > 0 ) /* issue 112 */ + // start_pos--; /* issue 112 */ + if ( title_lines > 0 ) + { + display_lines = (u8g2_GetDisplayHeight(u8g2) - 3) / line_height; + u8sl.visible = display_lines; + u8sl.visible -= title_lines; + } + else + { + display_lines = u8g2_GetDisplayHeight(u8g2) / line_height; + u8sl.visible = display_lines; + } + u8sl.total = u8x8_GetStringLineCnt(sl); + u8sl.first_pos = 0; + u8sl.current_pos = start_pos; + if ( u8sl.current_pos >= u8sl.total ) + u8sl.current_pos = u8sl.total - 1; + if ( u8sl.first_pos + u8sl.visible <= u8sl.current_pos ) + u8sl.first_pos = u8sl.current_pos - u8sl.visible + 1; + u8g2_SetFontPosBaseline(u8g2); + u8g2_FirstPage(u8g2); + do { + yy = u8g2_GetAscent(u8g2); + if ( title_lines > 0 ) + { + yy += u8g2_DrawUTF8Lines(u8g2, 0, yy, u8g2_GetDisplayWidth(u8g2), line_height, title); + u8g2_DrawHLine(u8g2, 0, yy-line_height- u8g2_GetDescent(u8g2) + 1, u8g2_GetDisplayWidth(u8g2)); + yy += 3; + } + my_DrawSelectionList(u8g2, &u8sl, yy, sl); + } while( u8g2_NextPage(u8g2) ); + return u8sl.total; +} + +void my_UserInterfaceInputValueString(u8g2_t *u8g2, const char *title, const char *sub, const char *text) +{ + uint8_t line_height; + uint8_t height; + u8g2_uint_t pixel_height; + u8g2_uint_t x, y, yy; + u8g2_uint_t pixel_width; + /* only horizontal strings are supported, so force this here */ + u8g2_SetFontDirection(u8g2, 0); + /* force baseline position */ + u8g2_SetFontPosBaseline(u8g2); + /* calculate line height */ + line_height = u8g2_GetAscent(u8g2); + line_height -= u8g2_GetDescent(u8g2); + /* calculate overall height of the input value box */ + height = 1; /* value input line */ + height += u8x8_GetStringLineCnt(title); + height += u8x8_GetStringLineCnt(sub); + /* calculate the height in pixel */ + pixel_height = height; + pixel_height *= line_height; + /* calculate offset from top */ + y = 0; + if ( pixel_height < u8g2_GetDisplayHeight(u8g2) ) + { + y = u8g2_GetDisplayHeight(u8g2); + y -= pixel_height; + y /= 2; + } + /* calculate offset from left for the label */ + x = 0; + pixel_width = u8g2_GetUTF8Width(u8g2, text); + if ( pixel_width < u8g2_GetDisplayWidth(u8g2) ) { + x = u8g2_GetDisplayWidth(u8g2); + x -= pixel_width; + x /= 2; + } + u8g2_FirstPage(u8g2); + do { + yy = y; + yy += u8g2_DrawUTF8Lines(u8g2, 0, yy, u8g2_GetDisplayWidth(u8g2), line_height, title); + yy += u8g2_DrawUTF8Lines(u8g2, 0, yy, u8g2_GetDisplayWidth(u8g2), line_height, sub); + u8g2_DrawUTF8(u8g2, x, yy, text); + } while( u8g2_NextPage(u8g2) ); +} + +// void my_UserInterfaceInputValue(u8g2_t *u8g2, const char *title, const char *pre, uint8_t value, uint8_t digits, const char *post) +// { +// uint8_t line_height; +// uint8_t height; +// u8g2_uint_t pixel_height; +// u8g2_uint_t y, yy; +// u8g2_uint_t pixel_width; +// u8g2_uint_t x, xx; +// /* only horizontal strings are supported, so force this here */ +// u8g2_SetFontDirection(u8g2, 0); +// /* force baseline position */ +// u8g2_SetFontPosBaseline(u8g2); +// /* calculate line height */ +// line_height = u8g2_GetAscent(u8g2); +// line_height -= u8g2_GetDescent(u8g2); +// /* calculate overall height of the input value box */ +// height = 1; /* value input line */ +// height += u8x8_GetStringLineCnt(title); +// /* calculate the height in pixel */ +// pixel_height = height; +// pixel_height *= line_height; +// /* calculate offset from top */ +// y = 0; +// if ( pixel_height < u8g2_GetDisplayHeight(u8g2) ) +// { +// y = u8g2_GetDisplayHeight(u8g2); +// y -= pixel_height; +// y /= 2; +// } +// /* calculate offset from left for the label */ +// x = 0; +// pixel_width = u8g2_GetUTF8Width(u8g2, pre); +// pixel_width += u8g2_GetUTF8Width(u8g2, "0") * digits; +// pixel_width += u8g2_GetUTF8Width(u8g2, post); +// if ( pixel_width < u8g2_GetDisplayWidth(u8g2) ) { +// x = u8g2_GetDisplayWidth(u8g2); +// x -= pixel_width; +// x /= 2; +// } +// u8g2_FirstPage(u8g2); +// do { +// yy = y; +// yy += u8g2_DrawUTF8Lines(u8g2, 0, yy, u8g2_GetDisplayWidth(u8g2), line_height, title); +// xx = x; +// xx += u8g2_DrawUTF8(u8g2, xx, yy, pre); +// xx += u8g2_DrawUTF8(u8g2, xx, yy, u8x8_u8toa(value, digits)); +// u8g2_DrawUTF8(u8g2, xx, yy, post); +// } while( u8g2_NextPage(u8g2) ); +// } + +} //extern "C" diff --git a/src/modbus/LICENSE b/src/modbus/LICENSE new file mode 100644 index 0000000..9cecc1d --- /dev/null +++ b/src/modbus/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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 . + +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: + + {project} Copyright (C) {year} {fullname} + 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 +. + + 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 +. diff --git a/src/modbus/ModbusRTUSlave.cpp b/src/modbus/ModbusRTUSlave.cpp new file mode 100644 index 0000000..7928872 --- /dev/null +++ b/src/modbus/ModbusRTUSlave.cpp @@ -0,0 +1,491 @@ +#include "ModbusRTUSlave.h" +#include "utility/LinkedList.h" + + +ModbusRTUSlave::ModbusRTUSlave(HardwareSerial* serialport, const uint8_t controlPinArg) + : ser(serialport) + , controlPin(controlPinArg) + , isReading(true) + , rWords(new wordsList()) + , rBits(new bitsList()) + , rwWords(new wordsList()) + , rwBits(new bitsList()) +{ + pinMode(controlPin, OUTPUT); + digitalWrite(controlPin, LOW); +} + +void ModbusRTUSlave::begin(byte address, uint32_t baudrate) +{ + if (connected) { + ser->end(); + } + slaveAddress = address; + ser->begin(baudrate); + ResCnt=0; + connected = true; +} + +void ModbusRTUSlave::end() +{ + if (connected) { + ser->end(); + connected = false; + } +} + +bool ModbusRTUSlave::addCoilArea(u16 address, u8* values, int cnt) +{ + if(getBitAddress(rwBits, address)==NULL) + { + rwBits->add(new ModbusRTUSlaveBitAddress(address, values, cnt)); + return true; + } + return false; +} + +bool ModbusRTUSlave::addDiscreteInputArea(u16 address, u8* values, int cnt) +{ + if(getBitAddress(rBits, address)==NULL) + { + rBits->add(new ModbusRTUSlaveBitAddress(address, values, cnt)); + return true; + } + return false; +} + +bool ModbusRTUSlave::addHoldingRegisterArea(u16 address, u16* values, int cnt) +{ + if(getWordAddress(rwWords, address)==NULL) + { + rwWords->add(new ModbusRTUSlaveWordAddress(address, values, cnt)); + return true; + } + return false; +} + +bool ModbusRTUSlave::addInputRegisterArea(u16 address, u16* values, int cnt) +{ + if(getWordAddress(rWords, address)==NULL) + { + rWords->add(new ModbusRTUSlaveWordAddress(address, values, cnt)); + return true; + } + return false; +} + +ModbusRTUSlaveWordAddress* ModbusRTUSlave::getWordAddress(wordsList *words, u16 Addr) +{ + ModbusRTUSlaveWordAddress* ret=NULL; + for(int i = 0; i < words->size(); i++) + { + ModbusRTUSlaveWordAddress* a = words->get(i); + if(a!=NULL && Addr >= a->addr && Addr < a->addr + a->len) ret=a; + } + return ret; +} +ModbusRTUSlaveBitAddress* ModbusRTUSlave::getBitAddress(bitsList *bits, u16 Addr) +{ + ModbusRTUSlaveBitAddress* ret=NULL; + for(int i = 0; i < bits->size(); i++) + { + ModbusRTUSlaveBitAddress* a = bits->get(i); + if(a!=NULL && Addr >= a->addr && Addr < a->addr + (a->len*8)) ret=a; + } + return ret; +} + +ModbusRTUSlaveWordAddress* ModbusRTUSlave::getWordAddress(wordsList *words, u16 Addr, u16 Len) +{ + ModbusRTUSlaveWordAddress* ret=NULL; + for(int i = 0; i < words->size(); i++) + { + ModbusRTUSlaveWordAddress* a = words->get(i); + if(a!=NULL && Addr >= a->addr && Addr+Len <= a->addr + a->len) ret=a; + } + return ret; +} +ModbusRTUSlaveBitAddress* ModbusRTUSlave::getBitAddress(bitsList *bits, u16 Addr, u16 Len) +{ + ModbusRTUSlaveBitAddress* ret=NULL; + for(int i = 0; i < bits->size(); i++) + { + ModbusRTUSlaveBitAddress* a = bits->get(i); + if(a!=NULL && Addr >= a->addr && Addr+Len <= a->addr + (a->len*8)) ret=a; + } + return ret; +} + + +void ModbusRTUSlave::process() +{ + bool bvalid = true; + while(isDataAvail()) + { + byte d = doRead(); + + lstResponse[ResCnt++]=d; + if(ResCnt>=4) + { + requestedSlave = lstResponse[0]; + if(requestedSlave == slaveAddress) + { + fnCode = lstResponse[1]; + requestedRegister = (lstResponse[2] << 8) | lstResponse[3]; + receivedLastRequest = micros(); + switch(fnCode) + { + case 1: // read coils + if(ResCnt >= 8) + { + readCoilOrDiscreteInput(rwBits, bvalid); + } + break; + case 2: // read discrete inputs + if(ResCnt >= 8) + { + readCoilOrDiscreteInput(rBits, bvalid); + } + break; + case 3: // read holding registers + if(ResCnt >= 8) + { + readHoldingOrInputRegister(rwWords, bvalid); + } + break; + case 4: // read input registers + if(ResCnt >= 8) + { + readHoldingOrInputRegister(rWords, bvalid); + } + break; + case 5: // write single coil + if(ResCnt >= 8) + { + u16 Data = (lstResponse[4] << 8) | lstResponse[5]; + byte hi = 0xFF, lo = 0xFF; + getCRC(lstResponse,300, 0, 6, &hi, &lo); + ModbusRTUSlaveBitAddress *a = getBitAddress(rwBits, requestedRegister); + if (a != NULL && lstResponse[6] == hi && lstResponse[7] == lo) + { + u16 stidx = (requestedRegister - a->addr) / 8; + + bitWrite(a->values[stidx], (requestedRegister - a->addr)%8, Data==0xFF00); + + byte ret[8]; + ret[0]=requestedSlave; + ret[1]=fnCode; + ret[2]=((requestedRegister&0xFF00)>>8); + ret[3]=((requestedRegister&0x00FF)); + ret[4]=((Data&0xFF00)>>8); + ret[5]=((Data&0x00FF)); + byte hi = 0xFF, lo = 0xFF; + getCRC(ret, 8, 0, 6, &hi, &lo); + ret[6]=hi; + ret[7]=lo; + doWrite(ret, 8); + + ResCnt=0; + } + else bvalid = false; + } + break; + case 6: // write single register + if(ResCnt >= 8) + { + u16 Data = (lstResponse[4] << 8) | lstResponse[5]; + byte hi = 0xFF, lo = 0xFF; + getCRC(lstResponse,300, 0, 6, &hi, &lo); + ModbusRTUSlaveWordAddress *a = getWordAddress(rwWords, requestedRegister); + if (a != NULL && lstResponse[6] == hi && lstResponse[7] == lo) + { + u16 stidx = requestedRegister - a->addr; + + a->values[stidx] = Data; + + byte ret[8]; + ret[0]=requestedSlave; + ret[1]=fnCode; + ret[2]=((requestedRegister&0xFF00)>>8); + ret[3]=((requestedRegister&0x00FF)); + ret[4]=((Data&0xFF00)>>8); + ret[5]=((Data&0x00FF)); + byte hi = 0xFF, lo = 0xFF; + getCRC(ret, 8, 0, 6, &hi, &lo); + ret[6]=hi; + ret[7]=lo; + doWrite(ret, 8); + + ResCnt=0; + } + else bvalid = false; + } + break; + case 15: // write multiple coils + if(ResCnt >= 7) + { + u16 Length = (lstResponse[4] << 8) | lstResponse[5]; + u8 ByteCount = lstResponse[6]; + if(ResCnt >= 9+ByteCount) + { + byte hi = 0xFF, lo = 0xFF; + getCRC(lstResponse,300, 0, 7 + ByteCount, &hi, &lo); + if(lstResponse[(9 + ByteCount - 2)] == hi && lstResponse[(9 + ByteCount - 1)] == lo) + { + ModbusRTUSlaveBitAddress *a = getBitAddress(rwBits, requestedRegister, Length); + if (a != NULL) + { + u16 stidx = (requestedRegister - a->addr) / 8; + int ng=(requestedRegister - a->addr) % 8; + int ns=stidx; + + for(int i=7; i<7+ByteCount;i++) + { + byte val = lstResponse[i]; + for(int j=0;j<8;j++) + { + bitWrite(a->values[ns], ng++, bitRead(val,j)); + if(ng==8){ns++;ng=0;} + } + } + + if(bvalid) + { + byte ret[8]; + ret[0]=requestedSlave; + ret[1]=fnCode; + ret[2]=((requestedRegister&0xFF00)>>8); + ret[3]=((requestedRegister&0x00FF)); + ret[4]=((Length&0xFF00)>>8); + ret[5]=((Length&0x00FF)); + byte hi = 0xFF, lo = 0xFF; + getCRC(ret, 8, 0, 6, &hi, &lo); + ret[6]=hi; + ret[7]=lo; + doWrite(ret, 8); + + ResCnt=0; + } + } + } + else bvalid=false; + } + } + break; + case 16: // write multiple registers + if(ResCnt >= 7) + { + u16 Length = (lstResponse[4] << 8) | lstResponse[5]; + u8 ByteCount = lstResponse[6]; + if(ResCnt >= 9+ByteCount) + { + byte hi = 0xFF, lo = 0xFF; + getCRC(lstResponse,300, 0, 7 + ByteCount, &hi, &lo); + if(lstResponse[(9 + ByteCount - 2)] == hi && lstResponse[(9 + ByteCount - 1)] == lo) + { + for(int i=7; i<7+ByteCount;i+=2) + { + u16 data = lstResponse[i] << 8 | lstResponse[i+1]; + ModbusRTUSlaveWordAddress *a = getWordAddress(rwWords, requestedRegister + ((i-7)/2)); + if (a != NULL) { a->values[(requestedRegister + ((i-7)/2)) - a->addr] = data; } + else { bvalid=false; break; } + } + if(bvalid) + { + byte ret[8]; + ret[0]=requestedSlave; + ret[1]=fnCode; + ret[2]=((requestedRegister&0xFF00)>>8); + ret[3]=((requestedRegister&0x00FF)); + ret[4]=((Length&0xFF00)>>8); + ret[5]=((Length&0x00FF)); + byte hi = 0xFF, lo = 0xFF; + getCRC(ret, 8, 0, 6, &hi, &lo); + ret[6]=hi; + ret[7]=lo; + doWrite(ret, 8); + + ResCnt=0; + } + } + else bvalid=false; + } + } + break; + } + } + else bvalid = false; + } + lastrecv = millis(); + } + if(!bvalid && ResCnt>0) ResCnt=0; + if(ResCnt>0 && (millis()-lastrecv > 200 || millis() < lastrecv)) ResCnt=0; +} +/* +void ModbusRTUSlave::getCRC(LinkedList* pby, int startindex, int nSize, byte* byFirstReturn, byte* bySecondReturn) +{ + int uIndex; + byte uchCRCHi = 0xff; + byte uchCRCLo = 0xff; + for (int i = startindex; i < startindex + nSize && isize(); i++) + { + uIndex = uchCRCHi ^ pby->get(i); + uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex]; + uchCRCLo = auchCRCLo[uIndex]; + } + (*byFirstReturn) = uchCRCHi; + (*bySecondReturn) = uchCRCLo; +} +*/ +void ModbusRTUSlave::getCRC(byte* pby, int arsize, int startindex, int nSize, byte* byFirstReturn, byte* bySecondReturn) +{ + int uIndex; + byte uchCRCHi = 0xff; + byte uchCRCLo = 0xff; + for (int i = startindex; i < startindex + nSize && iflush(); + digitalWrite(controlPin, LOW); + isReading = true; + } +} + +bool ModbusRTUSlave::isDataAvail() +{ + switchToReadingIfNotReadingNow(); + return ser->available(); +} + +int ModbusRTUSlave::doRead() +{ + switchToReadingIfNotReadingNow(); + return ser->read(); +} + +void ModbusRTUSlave::doWrite(byte* buffer, int const length) +{ + if (isReading) + { + digitalWrite(controlPin, HIGH); + isReading = false; + } + if (waitWithAnswerMicroS) { + unsigned long t = micros() - receivedLastRequest; + if (t < waitWithAnswerMicroS) + delayMicroseconds(waitWithAnswerMicroS - t); + } + ser->write(buffer, length); +} + +void ModbusRTUSlave::readCoilOrDiscreteInput(bitsList *bits, bool &valid) +{ + u16 Length = (lstResponse[4] << 8) | lstResponse[5]; + byte hi = 0xFF, lo = 0xFF; + getCRC(lstResponse,300, 0, 6, &hi, &lo); + ModbusRTUSlaveBitAddress *a = getBitAddress(bits, requestedRegister, Length); + if (Length > 0 && a != NULL && lstResponse[6] == hi && lstResponse[7] == lo) + { + u16 stidx = (requestedRegister - a->addr) / 8; + u16 nlen = ((Length-1) / 8)+1; + + byte dat[nlen]; + memset(dat,0,nlen); + + int ng=(requestedRegister - a->addr) % 8; + int ns=stidx; + for(int i=0;ivalues[ns], ng++)) bitSet(val,j); + if(ng==8){ns++;ng=0;} + } + dat[i]=val; + } + + byte ret[3+nlen+2]; + ret[0]=requestedSlave; + ret[1]=fnCode; + ret[2]=nlen; + for(int i=0;i 0 && a != NULL && lstResponse[6] == hi && lstResponse[7] == lo) + { + u16 stidx = requestedRegister - a->addr; + u16 nlen = Length * 2; + + byte ret[3+nlen+2]; + ret[0]=requestedSlave; + ret[1]=fnCode; + ret[2]=nlen; + for(int i=stidx;ivalues[i] & 0xFF00) >> 8); + ret[3+((i-stidx)*2)+1]=((a->values[i] & 0xFF)); + } + byte hi = 0xFF, lo = 0xFF; + getCRC(ret, 3+nlen+2, 0, 3+nlen, &hi, &lo); + ret[3+nlen]=hi; + ret[3+nlen+1]=lo; + doWrite(ret, 3+nlen+2); + + ResCnt=0; + } + else valid = false; +} + + +bool getBit(u8* area, int index) +{ + u16 stidx = index / 8; + return bitRead(area[stidx], index%8); +} + +void setBit(u8* area, int index, bool value) +{ + u16 stidx = index / 8; + bitWrite(area[stidx], index%8, value); +} + +ModbusRTUSlaveBitAddress::ModbusRTUSlaveBitAddress(u16 address, u8* value, int cnt) +{ + addr = address; + values = value; + len = cnt; +} + +ModbusRTUSlaveWordAddress::ModbusRTUSlaveWordAddress(u16 address, u16* value, int cnt) +{ + addr = address; + values = value; + len = cnt; +} diff --git a/src/modbus/ModbusRTUSlave.h b/src/modbus/ModbusRTUSlave.h new file mode 100644 index 0000000..d25a206 --- /dev/null +++ b/src/modbus/ModbusRTUSlave.h @@ -0,0 +1,117 @@ +#ifndef _MODBUS_RTU_SLAVE_H +#define _MODBUS_RTU_SLAVE_H + +#include "Arduino.h" +#include "utility/LinkedList.h" + +class ModbusRTUSlaveWordAddress +{ + public : + u16 addr; + byte len; + u16 *values; + ModbusRTUSlaveWordAddress(u16 Address, u16* value, int cnt); +}; + +class ModbusRTUSlaveBitAddress +{ + public : + u16 addr; + byte len; + u8 *values; + ModbusRTUSlaveBitAddress(u16 Address, u8* value, int cnt); +}; + +using wordsList = LinkedList; +using bitsList = LinkedList; + +class ModbusRTUSlave +{ + public : + ModbusRTUSlave(HardwareSerial*, const uint8_t); + void begin(byte address, uint32_t baudrate); + void end(); + bool addCoilArea(u16 Address, u8* values, int cnt); + bool addDiscreteInputArea(u16 Address, u8* values, int cnt); + bool addHoldingRegisterArea(u16 Address, u16* values, int cnt); + bool addInputRegisterArea(u16 Address, u16* values, int cnt); + void process(); + unsigned long waitWithAnswerMicroS = 0; + + private: + byte slaveAddress; + byte requestedSlave; + u16 requestedRegister; + bool connected = false; + HardwareSerial * const ser; + u8 const controlPin; + bool isReading; + unsigned long receivedLastRequest; + + // LinkedList *rWords; + // LinkedList *rBits; + wordsList *rWords; + bitsList *rBits; + wordsList *rwWords; + bitsList *rwBits; + ModbusRTUSlaveWordAddress* getWordAddress(wordsList*, u16 Addr); + ModbusRTUSlaveBitAddress* getBitAddress(bitsList*, u16 Addr); + ModbusRTUSlaveWordAddress* getWordAddress(wordsList*, u16 Addr,u16 Len); + ModbusRTUSlaveBitAddress* getBitAddress(bitsList*, u16 Addr,u16 Len); + byte lstResponse[300]; + byte fnCode; + int ResCnt=0; + unsigned long lastrecv; + void getCRC(byte* pby, int arsize, int startindex, int nSize, byte* byFirstReturn, byte* bySecondReturn); + + void switchToReadingIfNotReadingNow(); + bool isDataAvail(); + int doRead(); + void doWrite(byte*, int); + void readCoilOrDiscreteInput(bitsList*, bool&); + void readHoldingOrInputRegister(wordsList*, bool&); +}; + +const byte auchCRCHi[] = { + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, + 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, + 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, + 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, + 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, + 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, + 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, + 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, + 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, + 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, + 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, + 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, + 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, + 0x40}; + +const byte auchCRCLo[] = { + 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4, + 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, + 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, + 0x1D, 0x1C, 0xDC, 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, + 0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, 0x36, 0xF6, 0xF7, + 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, + 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, + 0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, + 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2, + 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, + 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, + 0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, + 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, 0x50, 0x90, 0x91, + 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, + 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88, + 0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, + 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80, + 0x40}; + +bool getBit(u8* area, int index); +void setBit(u8* area, int index, bool value); +#endif diff --git a/src/modbus/README.md b/src/modbus/README.md new file mode 100644 index 0000000..b903b61 --- /dev/null +++ b/src/modbus/README.md @@ -0,0 +1,7 @@ +# ModbusRTU_Slave +This is a modified version of ModbusRTU_Slave_RS485 version 1.0.2 by Łukasz Ślusarczyk + +https://github.com/lucasso/ModbusRTUSlaveArduino + +## License +See ./LICENSE file (GNU GPL v3.0 or later) diff --git a/src/modbus/utility/HashMap.h b/src/modbus/utility/HashMap.h new file mode 100644 index 0000000..327be8a --- /dev/null +++ b/src/modbus/utility/HashMap.h @@ -0,0 +1,112 @@ +/* +|| +|| @file HashMap.h +|| @version 1.0 Beta +|| @author Alexander Brevig +|| @contact alexanderbrevig@gmail.com +|| +|| @description +|| | This library provides a simple interface for storing data with an associate key +|| # +|| +|| @license +|| | 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; version +|| | 2.1 of the License. +|| | +|| | 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 +|| # +|| +*/ + +#ifndef HASHMAP_H +#define HASHMAP_H + +#include "Arduino.h" + +/* Handle association */ +template +class HashType { +public: + HashType(){ reset(); } + + HashType(hash code,map value):hashCode(code),mappedValue(value){} + + void reset(){ hashCode = 0; mappedValue = 0; } + hash getHash(){ return hashCode; } + void setHash(hash code){ hashCode = code; } + map getValue(){ return mappedValue; } + void setValue(map value){ mappedValue = value; } + + HashType& operator()(hash code, map value){ + setHash( code ); + setValue( value ); + } +private: + hash hashCode; + map mappedValue; +}; + +/* +Handle indexing and searches +TODO - extend API +*/ +template +class HashMap { +public: + HashMap(HashType* newMap,byte newSize){ + hashMap = newMap; + size = newSize; + for (byte i=0; i& operator[](int x){ + //TODO - bounds + return hashMap[x]; + } + + byte getIndexOf( hash key ){ + for (byte i=0; i* hashMap; + byte size; +}; + +#endif + +/* +|| @changelog +|| | 1.0 2009-07-13 - Alexander Brevig : Initial Release +|| # +*/ \ No newline at end of file diff --git a/src/modbus/utility/HashMap.h.bak b/src/modbus/utility/HashMap.h.bak new file mode 100644 index 0000000..c2fa631 --- /dev/null +++ b/src/modbus/utility/HashMap.h.bak @@ -0,0 +1,113 @@ +/* +|| +|| @file HashMap.h +|| @version 1.0 Beta +|| @author Alexander Brevig +|| @contact alexanderbrevig@gmail.com +|| +|| @description +|| | This library provides a simple interface for storing data with an associate key +|| # +|| +|| @license +|| | 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; version +|| | 2.1 of the License. +|| | +|| | 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 +|| # +|| +*/ + +#ifndef HASHMAP_H +#define HASHMAP_H + +#include "Arduino.h" + +/* Handle association */ +template +class HashType { +public: + HashType(){ reset(); } + + HashType(hash code,map value):hashCode(code),mappedValue(value){} + + void reset(){ hashCode = 0; mappedValue = 0; } + hash getHash(){ return hashCode; } + void setHash(hash code){ hashCode = code; } + map getValue(){ return mappedValue; } + void setValue(map value){ mappedValue = value; } + + HashType& operator()(hash code, map value){ + setHash( code ); + setValue( value ); + } +private: + hash hashCode; + map mappedValue; +}; + +/* +Handle indexing and searches +TODO - extend API +*/ +template + +class HashMap { +public: + HashMap(HashType* newMap,byte newSize){ + hashMap = newMap; + size = newSize; + for (byte i=0; i& operator[](int x){ + //TODO - bounds + return hashMap[x]; + } + + byte getIndexOf( hash key ){ + for (byte i=0; i* hashMap; + byte size; +}; + +#endif + +/* +|| @changelog +|| | 1.0 2009-07-13 - Alexander Brevig : Initial Release +|| # +*/ \ No newline at end of file diff --git a/src/modbus/utility/LinkedList.h b/src/modbus/utility/LinkedList.h new file mode 100644 index 0000000..4af00f0 --- /dev/null +++ b/src/modbus/utility/LinkedList.h @@ -0,0 +1,417 @@ +/* + LinkedList.h - V1.1 - Generic LinkedList implementation + Works better with FIFO, because LIFO will need to + search the entire List to find the last one; + For instructions, go to https://github.com/ivanseidel/LinkedList + Created by Ivan Seidel Gomes, March, 2013. + Released into the public domain. +*/ + + +#ifndef LinkedList_h +#define LinkedList_h + +#include + +template +struct ListNode +{ + T data; + ListNode *next; +}; + +template +class LinkedList{ + +protected: + int _size; + ListNode *root; + ListNode *last; + + // Helps "get" method, by saving last position + ListNode *lastNodeGot; + int lastIndexGot; + // isCached should be set to FALSE + // everytime the list suffer changes + bool isCached; + + ListNode* getNode(int index); + + ListNode* findEndOfSortedString(ListNode *p, int (*cmp)(T &, T &)); + +public: + LinkedList(); + LinkedList(int sizeIndex, T _t); //initiate list size and default value + ~LinkedList(); + + /* + Returns current size of LinkedList + */ + virtual int size(); + /* + Adds a T object in the specified index; + Unlink and link the LinkedList correcly; + Increment _size + */ + virtual bool add(int index, T); + /* + Adds a T object in the end of the LinkedList; + Increment _size; + */ + virtual bool add(T); + /* + Adds a T object in the start of the LinkedList; + Increment _size; + */ + virtual bool unshift(T); + /* + Set the object at index, with T; + */ + virtual bool set(int index, T); + /* + Remove object at index; + If index is not reachable, returns false; + else, decrement _size + */ + virtual T remove(int index); + /* + Remove last object; + */ + virtual T pop(); + /* + Remove first object; + */ + virtual T shift(); + /* + Get the index'th element on the list; + Return Element if accessible, + else, return false; + */ + virtual T get(int index); + + /* + Clear the entire array + */ + virtual void clear(); + + /* + Sort the list, given a comparison function + */ + virtual void sort(int (*cmp)(T &, T &)); + + // add support to array brakets [] operator + inline T& operator[](int index); + inline T& operator[](size_t& i) { return this->get(i); } + inline const T& operator[](const size_t& i) const { return this->get(i); } + +}; + +// Initialize LinkedList with false values +template +LinkedList::LinkedList() +{ + root=NULL; + last=NULL; + _size=0; + + lastNodeGot = root; + lastIndexGot = 0; + isCached = false; +} + +// Clear Nodes and free Memory +template +LinkedList::~LinkedList() +{ + ListNode* tmp; + while(root!=NULL) + { + tmp=root; + root=root->next; + delete tmp; + } + last = NULL; + _size=0; + isCached = false; +} + +/* + Actualy "logic" coding +*/ + +template +ListNode* LinkedList::getNode(int index){ + + int _pos = 0; + ListNode* current = root; + + // Check if the node trying to get is + // immediatly AFTER the previous got one + if(isCached && lastIndexGot <= index){ + _pos = lastIndexGot; + current = lastNodeGot; + } + + while(_pos < index && current){ + current = current->next; + + _pos++; + } + + // Check if the object index got is the same as the required + if(_pos == index){ + isCached = true; + lastIndexGot = index; + lastNodeGot = current; + + return current; + } + + return NULL; +} + +template +int LinkedList::size(){ + return _size; +} + +template +LinkedList::LinkedList(int sizeIndex, T _t){ + for (int i = 0; i < sizeIndex; i++){ + add(_t); + } +} + +template +bool LinkedList::add(int index, T _t){ + + if(index >= _size) + return add(_t); + + if(index == 0) + return unshift(_t); + + ListNode *tmp = new ListNode(), + *_prev = getNode(index-1); + tmp->data = _t; + tmp->next = _prev->next; + _prev->next = tmp; + + _size++; + isCached = false; + + return true; +} + +template +bool LinkedList::add(T _t){ + + ListNode *tmp = new ListNode(); + tmp->data = _t; + tmp->next = NULL; + + if(root){ + // Already have elements inserted + last->next = tmp; + last = tmp; + }else{ + // First element being inserted + root = tmp; + last = tmp; + } + + _size++; + isCached = false; + + return true; +} + +template +bool LinkedList::unshift(T _t){ + + if(_size == 0) + return add(_t); + + ListNode *tmp = new ListNode(); + tmp->next = root; + tmp->data = _t; + root = tmp; + + _size++; + isCached = false; + + return true; +} + + +template +T& LinkedList::operator[](int index) { + return getNode(index)->data; +} + +template +bool LinkedList::set(int index, T _t){ + // Check if index position is in bounds + if(index < 0 || index >= _size) + return false; + + getNode(index)->data = _t; + return true; +} + +template +T LinkedList::pop(){ + if(_size <= 0) + return T(); + + isCached = false; + + if(_size >= 2){ + ListNode *tmp = getNode(_size - 2); + T ret = tmp->next->data; + delete(tmp->next); + tmp->next = NULL; + last = tmp; + _size--; + return ret; + }else{ + // Only one element left on the list + T ret = root->data; + delete(root); + root = NULL; + last = NULL; + _size = 0; + return ret; + } +} + +template +T LinkedList::shift(){ + if(_size <= 0) + return T(); + + if(_size > 1){ + ListNode *_next = root->next; + T ret = root->data; + delete(root); + root = _next; + _size --; + isCached = false; + + return ret; + }else{ + // Only one left, then pop() + return pop(); + } + +} + +template +T LinkedList::remove(int index){ + if (index < 0 || index >= _size) + { + return T(); + } + + if(index == 0) + return shift(); + + if (index == _size-1) + { + return pop(); + } + + ListNode *tmp = getNode(index - 1); + ListNode *toDelete = tmp->next; + T ret = toDelete->data; + tmp->next = tmp->next->next; + delete(toDelete); + _size--; + isCached = false; + return ret; +} + + +template +T LinkedList::get(int index){ + ListNode *tmp = getNode(index); + + return (tmp ? tmp->data : T()); +} + +template +void LinkedList::clear(){ + while(size() > 0) + shift(); +} + +template +void LinkedList::sort(int (*cmp)(T &, T &)){ + if(_size < 2) return; // trivial case; + + for(;;) { + + ListNode **joinPoint = &root; + + while(*joinPoint) { + ListNode *a = *joinPoint; + ListNode *a_end = findEndOfSortedString(a, cmp); + + if(!a_end->next ) { + if(joinPoint == &root) { + last = a_end; + isCached = false; + return; + } + else { + break; + } + } + + ListNode *b = a_end->next; + ListNode *b_end = findEndOfSortedString(b, cmp); + + ListNode *tail = b_end->next; + + a_end->next = NULL; + b_end->next = NULL; + + while(a && b) { + if(cmp(a->data, b->data) <= 0) { + *joinPoint = a; + joinPoint = &a->next; + a = a->next; + } + else { + *joinPoint = b; + joinPoint = &b->next; + b = b->next; + } + } + + if(a) { + *joinPoint = a; + while(a->next) a = a->next; + a->next = tail; + joinPoint = &a->next; + } + else { + *joinPoint = b; + while(b->next) b = b->next; + b->next = tail; + joinPoint = &b->next; + } + } + } +} + +template +ListNode* LinkedList::findEndOfSortedString(ListNode *p, int (*cmp)(T &, T &)) { + while(p->next && cmp(p->data, p->next->data) <= 0) { + p = p->next; + } + + return p; +} + +#endif diff --git a/tank_controller.ino b/tank_controller.ino new file mode 100644 index 0000000..cd992b1 --- /dev/null +++ b/tank_controller.ino @@ -0,0 +1,510 @@ +#include +#include "src/OneWire/OneWire.h" +#include "src/DallasTemperature/DallasTemperature.h" +#include "src/display/display.h" +#include "src/controller/controller.h" + +const uint8_t BTN_PWR = 7; + +modbusParameters modbusParams; +parameters params; // Prozessparameter +values vals; // aktuelle Messwerte +PSensor pSensor; // verwendeter Drucksensor +valveStates vStates; // Zustände der Ausgänge +bool paramsChangedByUI; // true, außer ein Wert wurde über Modbus geändert +bool timeStampOverflow = false; // true, wenn mehr als 0xFFF Zehntelsekunden vergangen sind +unsigned long timeStamp; +u16 lastRefTime = 0xFFFF; + +#if _MODBUS == 1 +#include "src/modbus/ModbusRTUSlave.h" + +u8 modbusStates[1]; // Bit0: tEn, Bit1: pInc, Bit2: pDec, Bit3: cEn +u8 modbusValves[1]; // Bit0: Temp1, Bit1: Temp2, Bit2: Druck +// 0: Event-Counter, 1: high: modbusValves[0], low: modbusStates[0], 2...4: Temp 1, 2, Druck, ab5: gespeicherte Schaltvorgänge +u16 modbusData[_REGS_INFRONTOF_EVENTS + _MODBUS_MAX_EVENTS]; +u16 modbusMiscReadable[2]; // Version, Kühlzonen +u16 modbusSetpoints[6]; // Temp1, 2, Druck jeweils Sollwert + Hysterese +u16 modbusRefTime[1]; // setzt bei Änderung Event-Counter und -Timer zurück + +u8 &states = modbusStates[0]; +u8 &valves = modbusValves[0]; +u16 &eventCounter = modbusData[0]; +u16 &refTime = modbusRefTime[0]; + +ModbusRTUSlave mb(&Serial1, 2); + +void checkParamINT16(int *source, int *target, const int &std, const int &min, const int &max) { + _print("source: "); _print(*source); + if (*source == _SENSOR_FAULT) { + *source = *target = std; + } else if (*source > max) { + *source = *target = max; + } else if (*source < min) { + *source = *target = min; + } else if (*source == min || *source == max) { + *target = *source; + } else { + u8 mod = *source % 5; + _print(", modulo: "); _print(mod); + if (mod == 0) + *target = *source; + else { + int tempVal = *source - mod; + _print(", tempVal: "); _print(tempVal); + if (mod > 2) { // runde auf den nächsten 5er Schritt bzw. setze auf max + if ((tempVal + 5) > max) { + *source = *target = max; + _print(" ... auf max setzen"); + } else { + *source = *target = tempVal + 5; + _print(" ... aufrunden"); + } + } else { // runde auf den vorigen 5er Schritt bzw. setze auf min + if (tempVal < min) { + *source = *target = min; + _print(" ... auf min setzen"); + } else { + *source = *target = tempVal; + _print(" ... abrunden"); + } + } + } + } + _print(", target: "); _print(*target); _print(", source: "); _println(*source); +} + +void checkParamUINT8(u8 *source, u8 *target, const u8 &std) { + _print("checkParamUINT8 source vorher: "); _print(*source); + if (*source > 1) { + *source = *target = std; + } else { + *target = *source; + } + _print(", target: "); _print(*target); _print(", source: "); _println(*source); +} + +void checkParamBool(u8 &p, const u8 &bitNr, u8 *p2=nullptr) { + u8 *p_ = (p2) ? p2 : &p; + if (paramsChangedByUI) { + _print("UI -> Modbus - vorher: "); _print(bitRead(modbusStates[0], bitNr)); + bitWrite(modbusStates[0], bitNr, *p_); + _print(", nachher: "); _println(bitRead(modbusStates[0], bitNr)); + } else { + _print("Modbus -> UI - vorher: "); _print(*p_); + p = bitRead(modbusStates[0], bitNr); + _print(", nachher: "); _println(p); + } + bitWrite(modbusData[1], bitNr, bitRead(modbusStates[0], bitNr)); +} + +void checkModbusParams() { + parameters p; + if (modbusSetpoints[0] != params.ts1) { + if (paramsChangedByUI) { + _print("ts1 - UI -> Modbus - "); + checkParamINT16(¶ms.ts1, &modbusSetpoints[0], _STD_TEMP_SETPOINT, _MIN_TEMP_SETPOINT, _MAX_TEMP_SETPOINT); + } else { + _print("ts1 - Modbus -> UI - "); + checkParamINT16(&modbusSetpoints[0], ¶ms.ts1, _STD_TEMP_SETPOINT, _MIN_TEMP_SETPOINT, _MAX_TEMP_SETPOINT); + p.ts1 = params.ts1; + } + } + if (modbusSetpoints[1] != params.th1) { + if (paramsChangedByUI) { + _print("th1 - UI -> Modbus - "); + checkParamINT16(¶ms.th1, &modbusSetpoints[1], _STD_TEMP_HYSTERESIS, _MIN_TEMP_HYSTERESIS, _MAX_TEMP_HYSTERESIS); + } else { + _print("th1 - Modbus -> UI - "); + checkParamINT16(&modbusSetpoints[1], ¶ms.th1, _STD_TEMP_HYSTERESIS, _MIN_TEMP_HYSTERESIS, _MAX_TEMP_HYSTERESIS); + p.th1 = params.th1; + } + } + if (modbusSetpoints[4] != params.ps) { + if (paramsChangedByUI) { + _print("ps - UI -> Modbus - "); + checkParamINT16(¶ms.ps, &modbusSetpoints[4], _STD_P_SETPOINT, _MIN_P_SETPOINT, _MAX_P_SETPOINT); + } else { + _print("ps - Modbus -> UI - "); + checkParamINT16(&modbusSetpoints[4], ¶ms.ps, _STD_P_SETPOINT, _MIN_P_SETPOINT, _MAX_P_SETPOINT); + p.ps = params.ps; + } + } + if (modbusSetpoints[5] != params.ph) { + if (paramsChangedByUI) { + _print("ph - UI -> Modbus - "); + checkParamINT16(¶ms.ph, &modbusSetpoints[5], _STD_P_HYSTERESIS, _MIN_P_HYSTERESIS, _MAX_P_HYSTERESIS); + } else { + _print("ph - Modbus -> UI - "); + checkParamINT16(&modbusSetpoints[5], ¶ms.ph, _STD_P_HYSTERESIS, _MIN_P_HYSTERESIS, _MAX_P_HYSTERESIS); + p.ph = params.ph; + } + } + u8 bitNr = 0; + if (bitRead(modbusStates[0], bitNr) != params.tEn) { + _print("tEn - "); + checkParamBool(p.tEn, bitNr, ¶ms.tEn); + } + bitNr++; + if (bitRead(modbusStates[0], bitNr) != params.pInc) { + _print("pInc - "); + checkParamBool(p.pInc, bitNr, ¶ms.pInc); + } + bitNr++; + if (bitRead(modbusStates[0], bitNr) != params.pDec) { + _print("pDec - "); + checkParamBool(p.pDec, bitNr, ¶ms.pDec); + } + bitNr++; + if (bitRead(modbusStates[0], bitNr) != params.cEn) { + _print("cEn - "); + checkParamBool(p.cEn, bitNr, ¶ms.cEn); + } + if (!paramsChangedByUI) { + setParams(p); + } + paramsChangedByUI = false; +} +#endif // _MODBUS == + +// EEPROM Adressen: + +#define _EEPROM_OFFSET 0 // Falls sich die Register nicht mehr beschreiben lassen +#define _EEPROM_MODBUS_ADDRESS 0 + _EEPROM_OFFSET // 1 byte +#define _EEPROM_MODBUS_BAUDRATE 1 + _EEPROM_OFFSET // 4 bytes +#define _EEPROM_MODBUS_DELAY 5 + _EEPROM_OFFSET // 1 byte +#define _EEPROM_TEMP_SETPOINT 6 + _EEPROM_OFFSET // 4 bytes +#define _EEPROM_TEMP_HYSTERESIS 10 + _EEPROM_OFFSET // 4 bytes +#define _EEPROM_P_SETPOINT 14 + _EEPROM_OFFSET // 4 bytes +#define _EEPROM_P_HYSTERESIS 18 + _EEPROM_OFFSET // 4 bytes +#define _EEPROM_P_EN_INC 22 + _EEPROM_OFFSET // 1 byte +#define _EEPROM_P_EN_DEC 23 + _EEPROM_OFFSET // 1 byte +#define _EEPROM_P_SENSOR 24 + _EEPROM_OFFSET // 1 byte +#define _EEPROM_BG_LIGHT 25 + _EEPROM_OFFSET // 1 byte +#define _EEPROM_T_EN 26 + _EEPROM_OFFSET // 1 byte +#define _EEPROM_CONTROL_EN 27 + _EEPROM_OFFSET // 1 byte + +// cs, btnNext, btnPrev, btnSelect, btnCancel, bgLed, Parameter, Messwerte, Modbus, Drucksensor +Display d(10, 3, 4, 5, 6, 9, ¶ms, &vals, &modbusParams, &pSensor, &vStates); +// Analogeingang Druck, OneWire-Pin, Parameter, Messwerte, Display, Drucksensor, Ausgangszustände +// nach vStates: t1Pin, t2Pin, pRisePin, pFallPin +Controller c(A0, 8, ¶ms, &vals, &d, &pSensor, &vStates, 55, 56, 57, 58); + +#if _MODBUS == 1 +void beginModbus() { + mb.begin(modbusParams.address, modbusParams.baudrate); + mb.waitWithAnswerMicroS = modbusParams.delay * 100; // 1/10 ms -> us +} +#endif + +void getParams() { + parameters p; + EEPROM.get(_EEPROM_TEMP_SETPOINT, p.ts1); + EEPROM.get(_EEPROM_TEMP_HYSTERESIS, p.th1); + EEPROM.get(_EEPROM_P_SETPOINT, p.ps); + EEPROM.get(_EEPROM_P_HYSTERESIS, p.ph); + EEPROM.get(_EEPROM_P_EN_INC, p.pInc); + EEPROM.get(_EEPROM_P_EN_DEC, p.pDec); + EEPROM.get(_EEPROM_T_EN, p.tEn); + EEPROM.get(_EEPROM_CONTROL_EN, p.cEn); + _println("getParams() vor Validierung:"); + _print(" Temperatur Sollwert: "); _println(p.ts1); + _print(" Temperatur Hysterese: "); _println(p.th1); + _print(" Druck Sollwert: "); _println(p.ps); + _print(" Druck Hysterese: "); _println(p.ph); + _print(" Temp-Regelung aktiv: "); _println(p.tEn); + _print(" Drucksteigerung aktiv: "); _println(p.pInc); + _print(" Druckabfall aktiv: "); _println(p.pDec); + _print(" Regler aktiv: "); _println(p.cEn); + _print("ts1 - UI -> Modbus - "); + checkParamINT16(&p.ts1, ¶ms.ts1, _STD_TEMP_SETPOINT, _MIN_TEMP_SETPOINT, _MAX_TEMP_SETPOINT); + _print("th1 - UI -> Modbus - "); + checkParamINT16(&p.th1, ¶ms.th1, _STD_TEMP_HYSTERESIS, _MIN_TEMP_HYSTERESIS, _MAX_TEMP_HYSTERESIS); + _print("ps - UI -> Modbus - "); + checkParamINT16(&p.ps, ¶ms.ps, _STD_P_SETPOINT, _MIN_P_SETPOINT, _MAX_P_SETPOINT); + _print("ph - UI -> Modbus - "); + checkParamINT16(&p.ph, ¶ms.ph, _STD_P_HYSTERESIS, _MIN_P_HYSTERESIS, _MAX_P_HYSTERESIS); + _print("tEn - "); + checkParamUINT8(&p.tEn, ¶ms.tEn, _STD_T_EN); + _print("pInc - "); + checkParamUINT8(&p.pInc, ¶ms.pInc, _STD_P_EN_INC); + _print("pDec - "); + checkParamUINT8(&p.pDec, ¶ms.pDec, _STD_P_EN_DEC); + _print("cEn - "); + checkParamUINT8(&p.cEn, ¶ms.cEn, _STD_C_EN); + _println("getParams() nach Validierung:"); + _print(" Temperatur Sollwert: "); _println(params.ts1); + _print(" Temperatur Hysterese: "); _println(params.th1); + _print(" Druck Sollwert: "); _println(params.ps); + _print(" Druck Hysterese: "); _println(params.ph); + _print(" Temp-Regelung aktiv: "); _println(params.tEn); + _print(" Drucksteigerung aktiv: "); _println(params.pInc); + _print(" Druckabfall aktiv: "); _println(params.pDec); + _print(" Regler aktiv: "); _println(params.cEn); +} + +void setParams(parameters &p) { + if (p.ts1 != _SENSOR_FAULT) { + _print("ts1 alt: "); _print(params.ts1); _print(", neu: "); _println(p.ts1); + checkParamINT16(&p.ts1, ¶ms.ts1, _STD_TEMP_SETPOINT, _MIN_TEMP_SETPOINT, _MAX_TEMP_SETPOINT); + EEPROM.put(_EEPROM_TEMP_SETPOINT, params.ts1); +} + if (p.th1 != _SENSOR_FAULT) { + _print("th1 alt: "); _print(params.th1); _print(", neu: "); _println(p.th1); + checkParamINT16(&p.th1, ¶ms.th1, _STD_TEMP_HYSTERESIS, _MIN_TEMP_HYSTERESIS, _MAX_TEMP_HYSTERESIS); + EEPROM.put(_EEPROM_TEMP_HYSTERESIS, params.th1); + } + if (p.ps != _SENSOR_FAULT) { + _print("ps alt: "); _print(params.ps); _print(", neu: "); _println(p.ps); + checkParamINT16(&p.ps, ¶ms.ps, _STD_P_SETPOINT, _MIN_P_SETPOINT, _MAX_P_SETPOINT); + EEPROM.put(_EEPROM_P_SETPOINT, params.ps); + } + if (p.ph != _SENSOR_FAULT) { + _print("ph alt: "); _print(params.ph); _print(", neu: "); _println(p.ph); + checkParamINT16(&p.ph, ¶ms.ph, _STD_P_HYSTERESIS, _MIN_P_HYSTERESIS, _MAX_P_HYSTERESIS); + EEPROM.put(_EEPROM_P_HYSTERESIS, params.ph); + } + if (p.pInc < 2) { + _print("pInc alt: "); _print(params.pInc); _print(", neu: "); _println(p.pInc); + params.pInc = p.pInc; + EEPROM.put(_EEPROM_P_EN_INC, params.pInc); + } + if (p.pDec < 2) { + _print("pDec alt: "); _print(params.pDec); _print(", neu: "); _println(p.pDec); + params.pDec = p.pDec; + EEPROM.put(_EEPROM_P_EN_DEC, params.pDec); + } + if (p.tEn < 2) { + _print("tEn alt: "); _print(params.tEn); _print(", neu: "); _println(p.tEn); + params.tEn = p.tEn; + EEPROM.put(_EEPROM_T_EN, params.tEn); + } + if (p.cEn < 2) { + _print("cEn alt: "); _print(params.cEn); _print(", neu: "); _println(p.cEn); + params.cEn = p.cEn; + EEPROM.put(_EEPROM_CONTROL_EN, params.cEn); + } + paramsChangedByUI = true; +} + +void getModbusParams() { + uint8_t addr = EEPROM.read(_EEPROM_MODBUS_ADDRESS); + if (addr < _MODBUS_ADDR_MIN || addr > _MODBUS_ADDR_MAX) + modbusParams.address = _MODBUS_ADDR_MIN; + else + modbusParams.address = addr; + uint32_t baudrate; + EEPROM.get(_EEPROM_MODBUS_BAUDRATE, baudrate); + switch (baudrate) { + case 115200: break; + case 57600: break; + case 38400: break; + case 19200: break; + case 9600: break; + case 4800: break; + case 2400: break; + case 1200: break; + case 300: break; + default: baudrate = 9600; + } + modbusParams.baudrate = baudrate; + uint8_t delay_ = EEPROM.read(_EEPROM_MODBUS_DELAY); + if (delay_ < _MODBUS_DELAY_MIN) + modbusParams.delay = _MODBUS_DELAY_MIN; + else if (delay_ > _MODBUS_DELAY_MAX) + modbusParams.delay = _MODBUS_DELAY_MAX; + else + modbusParams.delay = delay_; +} + +void setModbusParams(const modbusParameters &p) { + bool changed = false; + if (p.address <= _MODBUS_ADDR_MAX) { + EEPROM.put(_EEPROM_MODBUS_ADDRESS, p.address); + modbusParams.address = p.address; + changed = true; + } + if (p.baudrate != _MODBUS_INVALID_BAUDRATE) { + EEPROM.put(_EEPROM_MODBUS_BAUDRATE, p.baudrate); + modbusParams.baudrate = p.baudrate; + changed = true; + } + if (p.delay <= _MODBUS_DELAY_MAX) { + EEPROM.put(_EEPROM_MODBUS_DELAY, p.delay); + modbusParams.delay = p.delay; + changed = true; + } + if (changed) { +#if _MODBUS == 1 + beginModbus(); +#endif + } +} + +PSensor getPSensor() { + uint8_t val; + EEPROM.get(_EEPROM_P_SENSOR, val); + switch (val) { + case SMC_1_5V_0_5BAR: + pSensor = SMC_1_5V_0_5BAR; + break; + case GEMS_0_5V_0_6BAR: + pSensor = GEMS_0_5V_0_6BAR; + break; + default: + pSensor = SMC_1_5V_0_5BAR; + EEPROM.put(_EEPROM_P_SENSOR, pSensor); + } + return pSensor; +} + +void setPSensor(const PSensor &sensor) { + EEPROM.put(_EEPROM_P_SENSOR, sensor); + pSensor = sensor; +} + +void setup() { +#if _DEBUG == 1 + Serial.begin(19200); + // char test[60]; + // sprintf(test, "test: %u, %u, %u", 115200, 57600, 38400); + // Serial.println(test); +#endif + pinMode(53, OUTPUT); // Mega CS-Pin (um Slave-Betrieb zu vermeiden) + + paramsChangedByUI = true; + + d.init(); + d.bgLight(true); + d.setModbusParams = setModbusParams; + d.setPSensor = setPSensor; + d.setParams = setParams; + + getModbusParams(); + _print("ModbusAddress: "); + _println(modbusParams.address); + _print("ModbusBaudrate: "); + _println(modbusParams.baudrate); + getPSensor(); + getParams(); + + pinMode(BTN_PWR, INPUT_PULLUP); + +#if _MODBUS == 1 + bool modbusFail = false; + if (!mb.addDiscreteInputArea(0xD0, modbusValves, 1)) + modbusFail = true; + if (!modbusFail && !mb.addHoldingRegisterArea(0xA0, modbusSetpoints, 6)) + modbusFail = true; + if (!modbusFail && !mb.addCoilArea(0xB0, modbusStates, 1)) + modbusFail = true; + if (!modbusFail && !mb.addHoldingRegisterArea(0xC0, modbusRefTime, 1)) + modbusFail = true; + if (!modbusFail && !mb.addInputRegisterArea(0x00, modbusData, _REGS_INFRONTOF_EVENTS + _MODBUS_MAX_EVENTS)) + modbusFail = true; + if (!modbusFail && !mb.addInputRegisterArea(0xF0, modbusMiscReadable, 2)) + modbusFail = true; + if (modbusFail) { + d.modbusProblem(); + while(1); + } + modbusData[0] = 0; // EventCounter + modbusData[1] = 0x8000; // setze das MSB. Das Bit wird durch setzen von modbusRefTime[0] zurückgesetzt + modbusData[2] = _SENSOR_FAULT; // Temp1 in 100stel-°C + modbusData[3] = _SENSOR_FAULT; // Temp2 in 100stel-°C, noch nicht implementiert + modbusData[4] = _SENSOR_FAULT; // Druck in 100stel bar + modbusData[5] = 0; // Zehntelsekunden seit Reglerstart / letzter Referenzierung + modbusMiscReadable[0] = _VERSION_NUMBER; + modbusMiscReadable[1] = 1; // Aktuell ist nur eine Kühlzone implementiert + modbusRefTime[0] = 0xFFFF; + beginModbus(); +#endif + + d.greeting(); + + delay(1000); + c.init(true); + if (params.cEn) + d.bgLight(true); + else + d.bgLight(100); + + timeStamp = millis(); +} + +bool readPwrBtn() { + const uint8_t debounceDelay = 20; + static unsigned long lastDebounceTime; + static bool lastBounceState; + static bool steadyState; + bool currentState = !digitalRead(BTN_PWR); + if (currentState != lastBounceState) { + lastDebounceTime = millis(); + lastBounceState = currentState; + } + if ((millis() - lastDebounceTime) > debounceDelay) + steadyState = currentState; + if (steadyState && (millis() - lastDebounceTime) > 3000) + d.reset(); + return steadyState; +} + +void loop() { + static bool pwrBtnPressed; + bool currentPwrBtnState = readPwrBtn(); + if (!pwrBtnPressed && currentPwrBtnState) { + _println("pwrButton pressed"); + pwrBtnPressed = true; + } else if(pwrBtnPressed && !currentPwrBtnState) { + _println("pwrButton released"); + pwrBtnPressed = false; + parameters p; + p.cEn = !params.cEn; + if (p.cEn) + d.bgLight(true); + else + d.bgLight(100); + setParams(p); + } + +#if _MODBUS == 1 + mb.process(); + checkModbusParams(); + if (refTime != lastRefTime) { + lastRefTime = refTime; + timeStamp = millis(); + modbusData[5] = 0; + eventCounter = 0; + timeStampOverflow = false; + // Setze das 'Timer-Überlauf'-Bit zurück (falls es gesetzt war) + bitClear(modbusData[1], 14); + // Nachden die 'ReferenzZeit' erstmalig gesetzt wurde, wird dieses Bit gelöscht + bitClear(modbusData[1], 15); + _println("Der 12 Bit Timer wurde zurückgesetzt"); + } + if (!timeStampOverflow && (millis() - timeStamp) / 100 > 0xFFF) { +#if _DEBUG == 1 + u16 passed = (millis() - timeStamp) / 100; + _print("Der 12 Bit Timer ist übergelaufen. Vergangene Sekunden: "); + _print(passed / 10); _print("."); _println(passed % 10); +#endif // _DEBUG == + timeStampOverflow = true; + bitSet(modbusData[1], 14); + } + modbusData[5] = (millis() - timeStamp) / 100; +#endif // _MODBUS == + c.process(); + d.process(); + +#if 0 + static unsigned long counter = 0; + static unsigned long tl = millis(); + if (millis() - tl > 1000) { + tl = millis(); + _print("Loops: "); _println(counter); + counter = 0; + } else { + counter++; + } +#endif +}