This commit is contained in:
xin
2025-07-08 08:54:35 +08:00
parent bc81bd41ac
commit 6de3458dfc
376 changed files with 68605 additions and 246 deletions

5
default.csv Normal file
View File

@ -0,0 +1,5 @@
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x140000,
app1, app, ota_1, 0x150000,0x140000,
spiffs, data, spiffs, 0x290000,0x170000,
1 nvs data nvs 0x9000 0x5000
2 otadata data ota 0xe000 0x2000
3 app0 app ota_0 0x10000 0x140000
4 app1 app ota_1 0x150000 0x140000
5 spiffs data spiffs 0x290000 0x170000

View File

@ -0,0 +1,46 @@
Thank you for opening an issue on an Adafruit Arduino library repository. To
improve the speed of resolution please review the following guidelines and
common troubleshooting steps below before creating the issue:
- **Do not use GitHub issues for troubleshooting projects and issues.** Instead use
the forums at http://forums.adafruit.com to ask questions and troubleshoot why
something isn't working as expected. In many cases the problem is a common issue
that you will more quickly receive help from the forum community. GitHub issues
are meant for known defects in the code. If you don't know if there is a defect
in the code then start with troubleshooting on the forum first.
- **If following a tutorial or guide be sure you didn't miss a step.** Carefully
check all of the steps and commands to run have been followed. Consult the
forum if you're unsure or have questions about steps in a guide/tutorial.
- **For Arduino projects check these very common issues to ensure they don't apply**:
- For uploading sketches or communicating with the board make sure you're using
a **USB data cable** and **not** a **USB charge-only cable**. It is sometimes
very hard to tell the difference between a data and charge cable! Try using the
cable with other devices or swapping to another cable to confirm it is not
the problem.
- **Be sure you are supplying adequate power to the board.** Check the specs of
your board and plug in an external power supply. In many cases just
plugging a board into your computer is not enough to power it and other
peripherals.
- **Double check all soldering joints and connections.** Flakey connections
cause many mysterious problems. See the [guide to excellent soldering](https://learn.adafruit.com/adafruit-guide-excellent-soldering/tools) for examples of good solder joints.
- **Ensure you are using an official Arduino or Adafruit board.** We can't
guarantee a clone board will have the same functionality and work as expected
with this code and don't support them.
If you're sure this issue is a defect in the code and checked the steps above
please fill in the following fields to provide enough troubleshooting information.
You may delete the guideline and text above to just leave the following details:
- Arduino board: **INSERT ARDUINO BOARD NAME/TYPE HERE**
- Arduino IDE version (found in Arduino -> About Arduino menu): **INSERT ARDUINO
VERSION HERE**
- List the steps to reproduce the problem below (if possible attach a sketch or
copy the sketch code in too): **LIST REPRO STEPS BELOW**

View File

@ -0,0 +1,26 @@
Thank you for creating a pull request to contribute to Adafruit's GitHub code!
Before you open the request please review the following guidelines and tips to
help it be more easily integrated:
- **Describe the scope of your change--i.e. what the change does and what parts
of the code were modified.** This will help us understand any risks of integrating
the code.
- **Describe any known limitations with your change.** For example if the change
doesn't apply to a supported platform of the library please mention it.
- **Please run any tests or examples that can exercise your modified code.** We
strive to not break users of the code and running tests/examples helps with this
process.
Thank you again for contributing! We will try to test and integrate the change
as soon as we can, but be aware we have many GitHub repositories to manage and
can't immediately respond to every request. There is no need to bump or check in
on a pull request (it will clutter the discussion of the request).
Also don't be worried if the request is closed or not integrated--sometimes the
priorities of Adafruit's GitHub code (education, ease of use) might not match the
priorities of the pull request. Don't fret, the open source community thrives on
forks and GitHub makes it easy to keep your changes in a forked repo.
After reviewing the guidelines above you can delete this text from the pull request.

View File

@ -0,0 +1,33 @@
name: Arduino Library CI
on: [pull_request, push, repository_dispatch]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/setup-python@v4
with:
python-version: '3.x'
- uses: actions/checkout@v3
- uses: actions/checkout@v3
with:
repository: adafruit/ci-arduino
path: ci
- name: Install the prerequisites
run: bash ci/actions_install.sh
- name: Check for correct code formatting with clang-format
run: python3 ci/run-clang-format.py -e "ci/*" -e "bin/*" -r .
- name: Check for correct documentation with doxygen
env:
GH_REPO_TOKEN: ${{ secrets.GH_REPO_TOKEN }}
PRETTYNAME : "Adafruit Bus IO Library"
run: bash ci/doxy_gen_and_deploy.sh
- name: Test the code on supported platforms
run: python3 ci/build_platform.py main_platforms zero feather32u4

View File

@ -0,0 +1 @@
{"type": "library", "name": "Adafruit BusIO", "version": "1.15.0", "spec": {"owner": "adafruit", "id": 6214, "name": "Adafruit BusIO", "requirements": null, "uri": null}}

View File

@ -0,0 +1,365 @@
#include <Adafruit_BusIO_Register.h>
#if !defined(SPI_INTERFACES_COUNT) || \
(defined(SPI_INTERFACES_COUNT) && (SPI_INTERFACES_COUNT > 0))
/*!
* @brief Create a register we access over an I2C Device (which defines the
* bus and address)
* @param i2cdevice The I2CDevice to use for underlying I2C access
* @param reg_addr The address pointer value for the I2C/SMBus register, can
* be 8 or 16 bits
* @param width The width of the register data itself, defaults to 1 byte
* @param byteorder The byte order of the register (used when width is > 1),
* defaults to LSBFIRST
* @param address_width The width of the register address itself, defaults
* to 1 byte
*/
Adafruit_BusIO_Register::Adafruit_BusIO_Register(Adafruit_I2CDevice *i2cdevice,
uint16_t reg_addr,
uint8_t width,
uint8_t byteorder,
uint8_t address_width) {
_i2cdevice = i2cdevice;
_spidevice = nullptr;
_addrwidth = address_width;
_address = reg_addr;
_byteorder = byteorder;
_width = width;
}
/*!
* @brief Create a register we access over an SPI Device (which defines the
* bus and CS pin)
* @param spidevice The SPIDevice to use for underlying SPI access
* @param reg_addr The address pointer value for the SPI register, can
* be 8 or 16 bits
* @param type The method we use to read/write data to SPI (which is not
* as well defined as I2C)
* @param width The width of the register data itself, defaults to 1 byte
* @param byteorder The byte order of the register (used when width is > 1),
* defaults to LSBFIRST
* @param address_width The width of the register address itself, defaults
* to 1 byte
*/
Adafruit_BusIO_Register::Adafruit_BusIO_Register(Adafruit_SPIDevice *spidevice,
uint16_t reg_addr,
Adafruit_BusIO_SPIRegType type,
uint8_t width,
uint8_t byteorder,
uint8_t address_width) {
_spidevice = spidevice;
_spiregtype = type;
_i2cdevice = nullptr;
_addrwidth = address_width;
_address = reg_addr;
_byteorder = byteorder;
_width = width;
}
/*!
* @brief Create a register we access over an I2C or SPI Device. This is a
* handy function because we can pass in nullptr for the unused interface,
* allowing libraries to mass-define all the registers
* @param i2cdevice The I2CDevice to use for underlying I2C access, if
* nullptr we use SPI
* @param spidevice The SPIDevice to use for underlying SPI access, if
* nullptr we use I2C
* @param reg_addr The address pointer value for the I2C/SMBus/SPI register,
* can be 8 or 16 bits
* @param type The method we use to read/write data to SPI (which is not
* as well defined as I2C)
* @param width The width of the register data itself, defaults to 1 byte
* @param byteorder The byte order of the register (used when width is > 1),
* defaults to LSBFIRST
* @param address_width The width of the register address itself, defaults
* to 1 byte
*/
Adafruit_BusIO_Register::Adafruit_BusIO_Register(
Adafruit_I2CDevice *i2cdevice, Adafruit_SPIDevice *spidevice,
Adafruit_BusIO_SPIRegType type, uint16_t reg_addr, uint8_t width,
uint8_t byteorder, uint8_t address_width) {
_spidevice = spidevice;
_i2cdevice = i2cdevice;
_spiregtype = type;
_addrwidth = address_width;
_address = reg_addr;
_byteorder = byteorder;
_width = width;
}
/*!
* @brief Write a buffer of data to the register location
* @param buffer Pointer to data to write
* @param len Number of bytes to write
* @return True on successful write (only really useful for I2C as SPI is
* uncheckable)
*/
bool Adafruit_BusIO_Register::write(uint8_t *buffer, uint8_t len) {
uint8_t addrbuffer[2] = {(uint8_t)(_address & 0xFF),
(uint8_t)(_address >> 8)};
if (_i2cdevice) {
return _i2cdevice->write(buffer, len, true, addrbuffer, _addrwidth);
}
if (_spidevice) {
if (_spiregtype == ADDRESSED_OPCODE_BIT0_LOW_TO_WRITE) {
// very special case!
// pass the special opcode address which we set as the high byte of the
// regaddr
addrbuffer[0] =
(uint8_t)(_address >> 8) & ~0x01; // set bottom bit low to write
// the 'actual' reg addr is the second byte then
addrbuffer[1] = (uint8_t)(_address & 0xFF);
// the address appears to be a byte longer
return _spidevice->write(buffer, len, addrbuffer, _addrwidth + 1);
}
if (_spiregtype == ADDRBIT8_HIGH_TOREAD) {
addrbuffer[0] &= ~0x80;
}
if (_spiregtype == ADDRBIT8_HIGH_TOWRITE) {
addrbuffer[0] |= 0x80;
}
if (_spiregtype == AD8_HIGH_TOREAD_AD7_HIGH_TOINC) {
addrbuffer[0] &= ~0x80;
addrbuffer[0] |= 0x40;
}
return _spidevice->write(buffer, len, addrbuffer, _addrwidth);
}
return false;
}
/*!
* @brief Write up to 4 bytes of data to the register location
* @param value Data to write
* @param numbytes How many bytes from 'value' to write
* @return True on successful write (only really useful for I2C as SPI is
* uncheckable)
*/
bool Adafruit_BusIO_Register::write(uint32_t value, uint8_t numbytes) {
if (numbytes == 0) {
numbytes = _width;
}
if (numbytes > 4) {
return false;
}
// store a copy
_cached = value;
for (int i = 0; i < numbytes; i++) {
if (_byteorder == LSBFIRST) {
_buffer[i] = value & 0xFF;
} else {
_buffer[numbytes - i - 1] = value & 0xFF;
}
value >>= 8;
}
return write(_buffer, numbytes);
}
/*!
* @brief Read data from the register location. This does not do any error
* checking!
* @return Returns 0xFFFFFFFF on failure, value otherwise
*/
uint32_t Adafruit_BusIO_Register::read(void) {
if (!read(_buffer, _width)) {
return -1;
}
uint32_t value = 0;
for (int i = 0; i < _width; i++) {
value <<= 8;
if (_byteorder == LSBFIRST) {
value |= _buffer[_width - i - 1];
} else {
value |= _buffer[i];
}
}
return value;
}
/*!
* @brief Read cached data from last time we wrote to this register
* @return Returns 0xFFFFFFFF on failure, value otherwise
*/
uint32_t Adafruit_BusIO_Register::readCached(void) { return _cached; }
/*!
* @brief Read a buffer of data from the register location
* @param buffer Pointer to data to read into
* @param len Number of bytes to read
* @return True on successful write (only really useful for I2C as SPI is
* uncheckable)
*/
bool Adafruit_BusIO_Register::read(uint8_t *buffer, uint8_t len) {
uint8_t addrbuffer[2] = {(uint8_t)(_address & 0xFF),
(uint8_t)(_address >> 8)};
if (_i2cdevice) {
return _i2cdevice->write_then_read(addrbuffer, _addrwidth, buffer, len);
}
if (_spidevice) {
if (_spiregtype == ADDRESSED_OPCODE_BIT0_LOW_TO_WRITE) {
// very special case!
// pass the special opcode address which we set as the high byte of the
// regaddr
addrbuffer[0] =
(uint8_t)(_address >> 8) | 0x01; // set bottom bit high to read
// the 'actual' reg addr is the second byte then
addrbuffer[1] = (uint8_t)(_address & 0xFF);
// the address appears to be a byte longer
return _spidevice->write_then_read(addrbuffer, _addrwidth + 1, buffer,
len);
}
if (_spiregtype == ADDRBIT8_HIGH_TOREAD) {
addrbuffer[0] |= 0x80;
}
if (_spiregtype == ADDRBIT8_HIGH_TOWRITE) {
addrbuffer[0] &= ~0x80;
}
if (_spiregtype == AD8_HIGH_TOREAD_AD7_HIGH_TOINC) {
addrbuffer[0] |= 0x80 | 0x40;
}
return _spidevice->write_then_read(addrbuffer, _addrwidth, buffer, len);
}
return false;
}
/*!
* @brief Read 2 bytes of data from the register location
* @param value Pointer to uint16_t variable to read into
* @return True on successful write (only really useful for I2C as SPI is
* uncheckable)
*/
bool Adafruit_BusIO_Register::read(uint16_t *value) {
if (!read(_buffer, 2)) {
return false;
}
if (_byteorder == LSBFIRST) {
*value = _buffer[1];
*value <<= 8;
*value |= _buffer[0];
} else {
*value = _buffer[0];
*value <<= 8;
*value |= _buffer[1];
}
return true;
}
/*!
* @brief Read 1 byte of data from the register location
* @param value Pointer to uint8_t variable to read into
* @return True on successful write (only really useful for I2C as SPI is
* uncheckable)
*/
bool Adafruit_BusIO_Register::read(uint8_t *value) {
if (!read(_buffer, 1)) {
return false;
}
*value = _buffer[0];
return true;
}
/*!
* @brief Pretty printer for this register
* @param s The Stream to print to, defaults to &Serial
*/
void Adafruit_BusIO_Register::print(Stream *s) {
uint32_t val = read();
s->print("0x");
s->print(val, HEX);
}
/*!
* @brief Pretty printer for this register
* @param s The Stream to print to, defaults to &Serial
*/
void Adafruit_BusIO_Register::println(Stream *s) {
print(s);
s->println();
}
/*!
* @brief Create a slice of the register that we can address without
* touching other bits
* @param reg The Adafruit_BusIO_Register which defines the bus/register
* @param bits The number of bits wide we are slicing
* @param shift The number of bits that our bit-slice is shifted from LSB
*/
Adafruit_BusIO_RegisterBits::Adafruit_BusIO_RegisterBits(
Adafruit_BusIO_Register *reg, uint8_t bits, uint8_t shift) {
_register = reg;
_bits = bits;
_shift = shift;
}
/*!
* @brief Read 4 bytes of data from the register
* @return data The 4 bytes to read
*/
uint32_t Adafruit_BusIO_RegisterBits::read(void) {
uint32_t val = _register->read();
val >>= _shift;
return val & ((1 << (_bits)) - 1);
}
/*!
* @brief Write 4 bytes of data to the register
* @param data The 4 bytes to write
* @return True on successful write (only really useful for I2C as SPI is
* uncheckable)
*/
bool Adafruit_BusIO_RegisterBits::write(uint32_t data) {
uint32_t val = _register->read();
// mask off the data before writing
uint32_t mask = (1 << (_bits)) - 1;
data &= mask;
mask <<= _shift;
val &= ~mask; // remove the current data at that spot
val |= data << _shift; // and add in the new data
return _register->write(val, _register->width());
}
/*!
* @brief The width of the register data, helpful for doing calculations
* @returns The data width used when initializing the register
*/
uint8_t Adafruit_BusIO_Register::width(void) { return _width; }
/*!
* @brief Set the default width of data
* @param width the default width of data read from register
*/
void Adafruit_BusIO_Register::setWidth(uint8_t width) { _width = width; }
/*!
* @brief Set register address
* @param address the address from register
*/
void Adafruit_BusIO_Register::setAddress(uint16_t address) {
_address = address;
}
/*!
* @brief Set the width of register address
* @param address_width the width for register address
*/
void Adafruit_BusIO_Register::setAddressWidth(uint16_t address_width) {
_addrwidth = address_width;
}
#endif // SPI exists

View File

@ -0,0 +1,105 @@
#ifndef Adafruit_BusIO_Register_h
#define Adafruit_BusIO_Register_h
#include <Arduino.h>
#if !defined(SPI_INTERFACES_COUNT) || \
(defined(SPI_INTERFACES_COUNT) && (SPI_INTERFACES_COUNT > 0))
#include <Adafruit_I2CDevice.h>
#include <Adafruit_SPIDevice.h>
typedef enum _Adafruit_BusIO_SPIRegType {
ADDRBIT8_HIGH_TOREAD = 0,
/*!<
* ADDRBIT8_HIGH_TOREAD
* When reading a register you must actually send the value 0x80 + register
* address to the device. e.g. To read the register 0x0B the register value
* 0x8B is sent and to write 0x0B is sent.
*/
AD8_HIGH_TOREAD_AD7_HIGH_TOINC = 1,
/*!<
* ADDRBIT8_HIGH_TOWRITE
* When writing to a register you must actually send the value 0x80 +
* the register address to the device. e.g. To write to the register 0x19 the
* register value 0x99 is sent and to read 0x19 is sent.
*/
ADDRBIT8_HIGH_TOWRITE = 2,
/*!<
* ADDRESSED_OPCODE_LOWBIT_TO_WRITE
* Used by the MCP23S series, we send 0x40 |'rd with the opcode
* Then set the lowest bit to write
*/
ADDRESSED_OPCODE_BIT0_LOW_TO_WRITE = 3,
} Adafruit_BusIO_SPIRegType;
/*!
* @brief The class which defines a device register (a location to read/write
* data from)
*/
class Adafruit_BusIO_Register {
public:
Adafruit_BusIO_Register(Adafruit_I2CDevice *i2cdevice, uint16_t reg_addr,
uint8_t width = 1, uint8_t byteorder = LSBFIRST,
uint8_t address_width = 1);
Adafruit_BusIO_Register(Adafruit_SPIDevice *spidevice, uint16_t reg_addr,
Adafruit_BusIO_SPIRegType type, uint8_t width = 1,
uint8_t byteorder = LSBFIRST,
uint8_t address_width = 1);
Adafruit_BusIO_Register(Adafruit_I2CDevice *i2cdevice,
Adafruit_SPIDevice *spidevice,
Adafruit_BusIO_SPIRegType type, uint16_t reg_addr,
uint8_t width = 1, uint8_t byteorder = LSBFIRST,
uint8_t address_width = 1);
bool read(uint8_t *buffer, uint8_t len);
bool read(uint8_t *value);
bool read(uint16_t *value);
uint32_t read(void);
uint32_t readCached(void);
bool write(uint8_t *buffer, uint8_t len);
bool write(uint32_t value, uint8_t numbytes = 0);
uint8_t width(void);
void setWidth(uint8_t width);
void setAddress(uint16_t address);
void setAddressWidth(uint16_t address_width);
void print(Stream *s = &Serial);
void println(Stream *s = &Serial);
private:
Adafruit_I2CDevice *_i2cdevice;
Adafruit_SPIDevice *_spidevice;
Adafruit_BusIO_SPIRegType _spiregtype;
uint16_t _address;
uint8_t _width, _addrwidth, _byteorder;
uint8_t _buffer[4]; // we won't support anything larger than uint32 for
// non-buffered read
uint32_t _cached = 0;
};
/*!
* @brief The class which defines a slice of bits from within a device register
* (a location to read/write data from)
*/
class Adafruit_BusIO_RegisterBits {
public:
Adafruit_BusIO_RegisterBits(Adafruit_BusIO_Register *reg, uint8_t bits,
uint8_t shift);
bool write(uint32_t value);
uint32_t read(void);
private:
Adafruit_BusIO_Register *_register;
uint8_t _bits, _shift;
};
#endif // SPI exists
#endif // BusIO_Register_h

View File

@ -0,0 +1,317 @@
#include "Adafruit_I2CDevice.h"
//#define DEBUG_SERIAL Serial
/*!
* @brief Create an I2C device at a given address
* @param addr The 7-bit I2C address for the device
* @param theWire The I2C bus to use, defaults to &Wire
*/
Adafruit_I2CDevice::Adafruit_I2CDevice(uint8_t addr, TwoWire *theWire) {
_addr = addr;
_wire = theWire;
_begun = false;
#ifdef ARDUINO_ARCH_SAMD
_maxBufferSize = 250; // as defined in Wire.h's RingBuffer
#elif defined(ESP32)
_maxBufferSize = I2C_BUFFER_LENGTH;
#else
_maxBufferSize = 32;
#endif
}
/*!
* @brief Initializes and does basic address detection
* @param addr_detect Whether we should attempt to detect the I2C address
* with a scan. 99% of sensors/devices don't mind, but once in a while they
* don't respond well to a scan!
* @return True if I2C initialized and a device with the addr found
*/
bool Adafruit_I2CDevice::begin(bool addr_detect) {
_wire->begin();
_begun = true;
if (addr_detect) {
return detected();
}
return true;
}
/*!
* @brief De-initialize device, turn off the Wire interface
*/
void Adafruit_I2CDevice::end(void) {
// Not all port implement Wire::end(), such as
// - ESP8266
// - AVR core without WIRE_HAS_END
// - ESP32: end() is implemented since 2.0.1 which is latest at the moment.
// Temporarily disable for now to give time for user to update.
#if !(defined(ESP8266) || \
(defined(ARDUINO_ARCH_AVR) && !defined(WIRE_HAS_END)) || \
defined(ARDUINO_ARCH_ESP32))
_wire->end();
_begun = false;
#endif
}
/*!
* @brief Scans I2C for the address - note will give a false-positive
* if there's no pullups on I2C
* @return True if I2C initialized and a device with the addr found
*/
bool Adafruit_I2CDevice::detected(void) {
// Init I2C if not done yet
if (!_begun && !begin()) {
return false;
}
// A basic scanner, see if it ACK's
_wire->beginTransmission(_addr);
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.print(F("Address 0x"));
DEBUG_SERIAL.print(_addr);
#endif
if (_wire->endTransmission() == 0) {
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.println(F(" Detected"));
#endif
return true;
}
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.println(F(" Not detected"));
#endif
return false;
}
/*!
* @brief Write a buffer or two to the I2C device. Cannot be more than
* maxBufferSize() bytes.
* @param buffer Pointer to buffer of data to write. This is const to
* ensure the content of this buffer doesn't change.
* @param len Number of bytes from buffer to write
* @param prefix_buffer Pointer to optional array of data to write before
* buffer. Cannot be more than maxBufferSize() bytes. This is const to
* ensure the content of this buffer doesn't change.
* @param prefix_len Number of bytes from prefix buffer to write
* @param stop Whether to send an I2C STOP signal on write
* @return True if write was successful, otherwise false.
*/
bool Adafruit_I2CDevice::write(const uint8_t *buffer, size_t len, bool stop,
const uint8_t *prefix_buffer,
size_t prefix_len) {
if ((len + prefix_len) > maxBufferSize()) {
// currently not guaranteed to work if more than 32 bytes!
// we will need to find out if some platforms have larger
// I2C buffer sizes :/
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.println(F("\tI2CDevice could not write such a large buffer"));
#endif
return false;
}
_wire->beginTransmission(_addr);
// Write the prefix data (usually an address)
if ((prefix_len != 0) && (prefix_buffer != nullptr)) {
if (_wire->write(prefix_buffer, prefix_len) != prefix_len) {
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.println(F("\tI2CDevice failed to write"));
#endif
return false;
}
}
// Write the data itself
if (_wire->write(buffer, len) != len) {
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.println(F("\tI2CDevice failed to write"));
#endif
return false;
}
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.print(F("\tI2CWRITE @ 0x"));
DEBUG_SERIAL.print(_addr, HEX);
DEBUG_SERIAL.print(F(" :: "));
if ((prefix_len != 0) && (prefix_buffer != nullptr)) {
for (uint16_t i = 0; i < prefix_len; i++) {
DEBUG_SERIAL.print(F("0x"));
DEBUG_SERIAL.print(prefix_buffer[i], HEX);
DEBUG_SERIAL.print(F(", "));
}
}
for (uint16_t i = 0; i < len; i++) {
DEBUG_SERIAL.print(F("0x"));
DEBUG_SERIAL.print(buffer[i], HEX);
DEBUG_SERIAL.print(F(", "));
if (i % 32 == 31) {
DEBUG_SERIAL.println();
}
}
if (stop) {
DEBUG_SERIAL.print("\tSTOP");
}
#endif
if (_wire->endTransmission(stop) == 0) {
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.println();
// DEBUG_SERIAL.println("Sent!");
#endif
return true;
} else {
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.println("\tFailed to send!");
#endif
return false;
}
}
/*!
* @brief Read from I2C into a buffer from the I2C device.
* Cannot be more than maxBufferSize() bytes.
* @param buffer Pointer to buffer of data to read into
* @param len Number of bytes from buffer to read.
* @param stop Whether to send an I2C STOP signal on read
* @return True if read was successful, otherwise false.
*/
bool Adafruit_I2CDevice::read(uint8_t *buffer, size_t len, bool stop) {
size_t pos = 0;
while (pos < len) {
size_t read_len =
((len - pos) > maxBufferSize()) ? maxBufferSize() : (len - pos);
bool read_stop = (pos < (len - read_len)) ? false : stop;
if (!_read(buffer + pos, read_len, read_stop))
return false;
pos += read_len;
}
return true;
}
bool Adafruit_I2CDevice::_read(uint8_t *buffer, size_t len, bool stop) {
#if defined(TinyWireM_h)
size_t recv = _wire->requestFrom((uint8_t)_addr, (uint8_t)len);
#elif defined(ARDUINO_ARCH_MEGAAVR)
size_t recv = _wire->requestFrom(_addr, len, stop);
#else
size_t recv = _wire->requestFrom((uint8_t)_addr, (uint8_t)len, (uint8_t)stop);
#endif
if (recv != len) {
// Not enough data available to fulfill our obligation!
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.print(F("\tI2CDevice did not receive enough data: "));
DEBUG_SERIAL.println(recv);
#endif
return false;
}
for (uint16_t i = 0; i < len; i++) {
buffer[i] = _wire->read();
}
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.print(F("\tI2CREAD @ 0x"));
DEBUG_SERIAL.print(_addr, HEX);
DEBUG_SERIAL.print(F(" :: "));
for (uint16_t i = 0; i < len; i++) {
DEBUG_SERIAL.print(F("0x"));
DEBUG_SERIAL.print(buffer[i], HEX);
DEBUG_SERIAL.print(F(", "));
if (len % 32 == 31) {
DEBUG_SERIAL.println();
}
}
DEBUG_SERIAL.println();
#endif
return true;
}
/*!
* @brief Write some data, then read some data from I2C into another buffer.
* Cannot be more than maxBufferSize() bytes. The buffers can point to
* same/overlapping locations.
* @param write_buffer Pointer to buffer of data to write from
* @param write_len Number of bytes from buffer to write.
* @param read_buffer Pointer to buffer of data to read into.
* @param read_len Number of bytes from buffer to read.
* @param stop Whether to send an I2C STOP signal between the write and read
* @return True if write & read was successful, otherwise false.
*/
bool Adafruit_I2CDevice::write_then_read(const uint8_t *write_buffer,
size_t write_len, uint8_t *read_buffer,
size_t read_len, bool stop) {
if (!write(write_buffer, write_len, stop)) {
return false;
}
return read(read_buffer, read_len);
}
/*!
* @brief Returns the 7-bit address of this device
* @return The 7-bit address of this device
*/
uint8_t Adafruit_I2CDevice::address(void) { return _addr; }
/*!
* @brief Change the I2C clock speed to desired (relies on
* underlying Wire support!
* @param desiredclk The desired I2C SCL frequency
* @return True if this platform supports changing I2C speed.
* Not necessarily that the speed was achieved!
*/
bool Adafruit_I2CDevice::setSpeed(uint32_t desiredclk) {
#if defined(__AVR_ATmega328__) || \
defined(__AVR_ATmega328P__) // fix arduino core set clock
// calculate TWBR correctly
if ((F_CPU / 18) < desiredclk) {
#ifdef DEBUG_SERIAL
Serial.println(F("I2C.setSpeed too high."));
#endif
return false;
}
uint32_t atwbr = ((F_CPU / desiredclk) - 16) / 2;
if (atwbr > 16320) {
#ifdef DEBUG_SERIAL
Serial.println(F("I2C.setSpeed too low."));
#endif
return false;
}
if (atwbr <= 255) {
atwbr /= 1;
TWSR = 0x0;
} else if (atwbr <= 1020) {
atwbr /= 4;
TWSR = 0x1;
} else if (atwbr <= 4080) {
atwbr /= 16;
TWSR = 0x2;
} else { // if (atwbr <= 16320)
atwbr /= 64;
TWSR = 0x3;
}
TWBR = atwbr;
#ifdef DEBUG_SERIAL
Serial.print(F("TWSR prescaler = "));
Serial.println(pow(4, TWSR));
Serial.print(F("TWBR = "));
Serial.println(atwbr);
#endif
return true;
#elif (ARDUINO >= 157) && !defined(ARDUINO_STM32_FEATHER) && \
!defined(TinyWireM_h)
_wire->setClock(desiredclk);
return true;
#else
(void)desiredclk;
return false;
#endif
}

View File

@ -0,0 +1,36 @@
#ifndef Adafruit_I2CDevice_h
#define Adafruit_I2CDevice_h
#include <Arduino.h>
#include <Wire.h>
///< The class which defines how we will talk to this device over I2C
class Adafruit_I2CDevice {
public:
Adafruit_I2CDevice(uint8_t addr, TwoWire *theWire = &Wire);
uint8_t address(void);
bool begin(bool addr_detect = true);
void end(void);
bool detected(void);
bool read(uint8_t *buffer, size_t len, bool stop = true);
bool write(const uint8_t *buffer, size_t len, bool stop = true,
const uint8_t *prefix_buffer = nullptr, size_t prefix_len = 0);
bool write_then_read(const uint8_t *write_buffer, size_t write_len,
uint8_t *read_buffer, size_t read_len,
bool stop = false);
bool setSpeed(uint32_t desiredclk);
/*! @brief How many bytes we can read in a transaction
* @return The size of the Wire receive/transmit buffer */
size_t maxBufferSize() { return _maxBufferSize; }
private:
uint8_t _addr;
TwoWire *_wire;
bool _begun;
size_t _maxBufferSize;
bool _read(uint8_t *buffer, size_t len, bool stop);
};
#endif // Adafruit_I2CDevice_h

View File

@ -0,0 +1,10 @@
#ifndef _ADAFRUIT_I2C_REGISTER_H_
#define _ADAFRUIT_I2C_REGISTER_H_
#include <Adafruit_BusIO_Register.h>
#include <Arduino.h>
typedef Adafruit_BusIO_Register Adafruit_I2CRegister;
typedef Adafruit_BusIO_RegisterBits Adafruit_I2CRegisterBits;
#endif

View File

@ -0,0 +1,508 @@
#include "Adafruit_SPIDevice.h"
//#define DEBUG_SERIAL Serial
/*!
* @brief Create an SPI device with the given CS pin and settings
* @param cspin The arduino pin number to use for chip select
* @param freq The SPI clock frequency to use, defaults to 1MHz
* @param dataOrder The SPI data order to use for bits within each byte,
* defaults to SPI_BITORDER_MSBFIRST
* @param dataMode The SPI mode to use, defaults to SPI_MODE0
* @param theSPI The SPI bus to use, defaults to &theSPI
*/
Adafruit_SPIDevice::Adafruit_SPIDevice(int8_t cspin, uint32_t freq,
BusIOBitOrder dataOrder,
uint8_t dataMode, SPIClass *theSPI) {
#ifdef BUSIO_HAS_HW_SPI
_cs = cspin;
_sck = _mosi = _miso = -1;
_spi = theSPI;
_begun = false;
_spiSetting = new SPISettings(freq, dataOrder, dataMode);
_freq = freq;
_dataOrder = dataOrder;
_dataMode = dataMode;
#else
// unused, but needed to suppress compiler warns
(void)cspin;
(void)freq;
(void)dataOrder;
(void)dataMode;
(void)theSPI;
#endif
}
/*!
* @brief Create an SPI device with the given CS pin and settings
* @param cspin The arduino pin number to use for chip select
* @param sckpin The arduino pin number to use for SCK
* @param misopin The arduino pin number to use for MISO, set to -1 if not
* used
* @param mosipin The arduino pin number to use for MOSI, set to -1 if not
* used
* @param freq The SPI clock frequency to use, defaults to 1MHz
* @param dataOrder The SPI data order to use for bits within each byte,
* defaults to SPI_BITORDER_MSBFIRST
* @param dataMode The SPI mode to use, defaults to SPI_MODE0
*/
Adafruit_SPIDevice::Adafruit_SPIDevice(int8_t cspin, int8_t sckpin,
int8_t misopin, int8_t mosipin,
uint32_t freq, BusIOBitOrder dataOrder,
uint8_t dataMode) {
_cs = cspin;
_sck = sckpin;
_miso = misopin;
_mosi = mosipin;
#ifdef BUSIO_USE_FAST_PINIO
csPort = (BusIO_PortReg *)portOutputRegister(digitalPinToPort(cspin));
csPinMask = digitalPinToBitMask(cspin);
if (mosipin != -1) {
mosiPort = (BusIO_PortReg *)portOutputRegister(digitalPinToPort(mosipin));
mosiPinMask = digitalPinToBitMask(mosipin);
}
if (misopin != -1) {
misoPort = (BusIO_PortReg *)portInputRegister(digitalPinToPort(misopin));
misoPinMask = digitalPinToBitMask(misopin);
}
clkPort = (BusIO_PortReg *)portOutputRegister(digitalPinToPort(sckpin));
clkPinMask = digitalPinToBitMask(sckpin);
#endif
_freq = freq;
_dataOrder = dataOrder;
_dataMode = dataMode;
_begun = false;
}
/*!
* @brief Release memory allocated in constructors
*/
Adafruit_SPIDevice::~Adafruit_SPIDevice() {
if (_spiSetting)
delete _spiSetting;
}
/*!
* @brief Initializes SPI bus and sets CS pin high
* @return Always returns true because there's no way to test success of SPI
* init
*/
bool Adafruit_SPIDevice::begin(void) {
if (_cs != -1) {
pinMode(_cs, OUTPUT);
digitalWrite(_cs, HIGH);
}
if (_spi) { // hardware SPI
#ifdef BUSIO_HAS_HW_SPI
_spi->begin();
#endif
} else {
pinMode(_sck, OUTPUT);
if ((_dataMode == SPI_MODE0) || (_dataMode == SPI_MODE1)) {
// idle low on mode 0 and 1
digitalWrite(_sck, LOW);
} else {
// idle high on mode 2 or 3
digitalWrite(_sck, HIGH);
}
if (_mosi != -1) {
pinMode(_mosi, OUTPUT);
digitalWrite(_mosi, HIGH);
}
if (_miso != -1) {
pinMode(_miso, INPUT);
}
}
_begun = true;
return true;
}
/*!
* @brief Transfer (send/receive) a buffer over hard/soft SPI, without
* transaction management
* @param buffer The buffer to send and receive at the same time
* @param len The number of bytes to transfer
*/
void Adafruit_SPIDevice::transfer(uint8_t *buffer, size_t len) {
//
// HARDWARE SPI
//
if (_spi) {
#ifdef BUSIO_HAS_HW_SPI
#if defined(SPARK)
_spi->transfer(buffer, buffer, len, nullptr);
#elif defined(STM32)
for (size_t i = 0; i < len; i++) {
_spi->transfer(buffer[i]);
}
#else
_spi->transfer(buffer, len);
#endif
return;
#endif
}
//
// SOFTWARE SPI
//
uint8_t startbit;
if (_dataOrder == SPI_BITORDER_LSBFIRST) {
startbit = 0x1;
} else {
startbit = 0x80;
}
bool towrite, lastmosi = !(buffer[0] & startbit);
uint8_t bitdelay_us = (1000000 / _freq) / 2;
for (size_t i = 0; i < len; i++) {
uint8_t reply = 0;
uint8_t send = buffer[i];
/*
Serial.print("\tSending software SPI byte 0x");
Serial.print(send, HEX);
Serial.print(" -> 0x");
*/
// Serial.print(send, HEX);
for (uint8_t b = startbit; b != 0;
b = (_dataOrder == SPI_BITORDER_LSBFIRST) ? b << 1 : b >> 1) {
if (bitdelay_us) {
delayMicroseconds(bitdelay_us);
}
if (_dataMode == SPI_MODE0 || _dataMode == SPI_MODE2) {
towrite = send & b;
if ((_mosi != -1) && (lastmosi != towrite)) {
#ifdef BUSIO_USE_FAST_PINIO
if (towrite)
*mosiPort = *mosiPort | mosiPinMask;
else
*mosiPort = *mosiPort & ~mosiPinMask;
#else
digitalWrite(_mosi, towrite);
#endif
lastmosi = towrite;
}
#ifdef BUSIO_USE_FAST_PINIO
*clkPort = *clkPort | clkPinMask; // Clock high
#else
digitalWrite(_sck, HIGH);
#endif
if (bitdelay_us) {
delayMicroseconds(bitdelay_us);
}
if (_miso != -1) {
#ifdef BUSIO_USE_FAST_PINIO
if (*misoPort & misoPinMask) {
#else
if (digitalRead(_miso)) {
#endif
reply |= b;
}
}
#ifdef BUSIO_USE_FAST_PINIO
*clkPort = *clkPort & ~clkPinMask; // Clock low
#else
digitalWrite(_sck, LOW);
#endif
} else { // if (_dataMode == SPI_MODE1 || _dataMode == SPI_MODE3)
#ifdef BUSIO_USE_FAST_PINIO
*clkPort = *clkPort | clkPinMask; // Clock high
#else
digitalWrite(_sck, HIGH);
#endif
if (bitdelay_us) {
delayMicroseconds(bitdelay_us);
}
if (_mosi != -1) {
#ifdef BUSIO_USE_FAST_PINIO
if (send & b)
*mosiPort = *mosiPort | mosiPinMask;
else
*mosiPort = *mosiPort & ~mosiPinMask;
#else
digitalWrite(_mosi, send & b);
#endif
}
#ifdef BUSIO_USE_FAST_PINIO
*clkPort = *clkPort & ~clkPinMask; // Clock low
#else
digitalWrite(_sck, LOW);
#endif
if (_miso != -1) {
#ifdef BUSIO_USE_FAST_PINIO
if (*misoPort & misoPinMask) {
#else
if (digitalRead(_miso)) {
#endif
reply |= b;
}
}
}
if (_miso != -1) {
buffer[i] = reply;
}
}
}
return;
}
/*!
* @brief Transfer (send/receive) one byte over hard/soft SPI, without
* transaction management
* @param send The byte to send
* @return The byte received while transmitting
*/
uint8_t Adafruit_SPIDevice::transfer(uint8_t send) {
uint8_t data = send;
transfer(&data, 1);
return data;
}
/*!
* @brief Manually begin a transaction (calls beginTransaction if hardware
* SPI)
*/
void Adafruit_SPIDevice::beginTransaction(void) {
if (_spi) {
#ifdef BUSIO_HAS_HW_SPI
_spi->beginTransaction(*_spiSetting);
#endif
}
}
/*!
* @brief Manually end a transaction (calls endTransaction if hardware SPI)
*/
void Adafruit_SPIDevice::endTransaction(void) {
if (_spi) {
#ifdef BUSIO_HAS_HW_SPI
_spi->endTransaction();
#endif
}
}
/*!
* @brief Assert/Deassert the CS pin if it is defined
* @param value The state the CS is set to
*/
void Adafruit_SPIDevice::setChipSelect(int value) {
if (_cs != -1) {
digitalWrite(_cs, value);
}
}
/*!
* @brief Write a buffer or two to the SPI device, with transaction
* management.
* @brief Manually begin a transaction (calls beginTransaction if hardware
* SPI) with asserting the CS pin
*/
void Adafruit_SPIDevice::beginTransactionWithAssertingCS() {
beginTransaction();
setChipSelect(LOW);
}
/*!
* @brief Manually end a transaction (calls endTransaction if hardware SPI)
* with deasserting the CS pin
*/
void Adafruit_SPIDevice::endTransactionWithDeassertingCS() {
setChipSelect(HIGH);
endTransaction();
}
/*!
* @brief Write a buffer or two to the SPI device, with transaction
* management.
* @param buffer Pointer to buffer of data to write
* @param len Number of bytes from buffer to write
* @param prefix_buffer Pointer to optional array of data to write before
* buffer.
* @param prefix_len Number of bytes from prefix buffer to write
* @return Always returns true because there's no way to test success of SPI
* writes
*/
bool Adafruit_SPIDevice::write(const uint8_t *buffer, size_t len,
const uint8_t *prefix_buffer,
size_t prefix_len) {
beginTransactionWithAssertingCS();
// do the writing
#if defined(ARDUINO_ARCH_ESP32)
if (_spi) {
if (prefix_len > 0) {
_spi->transferBytes((uint8_t *)prefix_buffer, nullptr, prefix_len);
}
if (len > 0) {
_spi->transferBytes((uint8_t *)buffer, nullptr, len);
}
} else
#endif
{
for (size_t i = 0; i < prefix_len; i++) {
transfer(prefix_buffer[i]);
}
for (size_t i = 0; i < len; i++) {
transfer(buffer[i]);
}
}
endTransactionWithDeassertingCS();
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.print(F("\tSPIDevice Wrote: "));
if ((prefix_len != 0) && (prefix_buffer != nullptr)) {
for (uint16_t i = 0; i < prefix_len; i++) {
DEBUG_SERIAL.print(F("0x"));
DEBUG_SERIAL.print(prefix_buffer[i], HEX);
DEBUG_SERIAL.print(F(", "));
}
}
for (uint16_t i = 0; i < len; i++) {
DEBUG_SERIAL.print(F("0x"));
DEBUG_SERIAL.print(buffer[i], HEX);
DEBUG_SERIAL.print(F(", "));
if (i % 32 == 31) {
DEBUG_SERIAL.println();
}
}
DEBUG_SERIAL.println();
#endif
return true;
}
/*!
* @brief Read from SPI into a buffer from the SPI device, with transaction
* management.
* @param buffer Pointer to buffer of data to read into
* @param len Number of bytes from buffer to read.
* @param sendvalue The 8-bits of data to write when doing the data read,
* defaults to 0xFF
* @return Always returns true because there's no way to test success of SPI
* writes
*/
bool Adafruit_SPIDevice::read(uint8_t *buffer, size_t len, uint8_t sendvalue) {
memset(buffer, sendvalue, len); // clear out existing buffer
beginTransactionWithAssertingCS();
transfer(buffer, len);
endTransactionWithDeassertingCS();
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.print(F("\tSPIDevice Read: "));
for (uint16_t i = 0; i < len; i++) {
DEBUG_SERIAL.print(F("0x"));
DEBUG_SERIAL.print(buffer[i], HEX);
DEBUG_SERIAL.print(F(", "));
if (len % 32 == 31) {
DEBUG_SERIAL.println();
}
}
DEBUG_SERIAL.println();
#endif
return true;
}
/*!
* @brief Write some data, then read some data from SPI into another buffer,
* with transaction management. The buffers can point to same/overlapping
* locations. This does not transmit-receive at the same time!
* @param write_buffer Pointer to buffer of data to write from
* @param write_len Number of bytes from buffer to write.
* @param read_buffer Pointer to buffer of data to read into.
* @param read_len Number of bytes from buffer to read.
* @param sendvalue The 8-bits of data to write when doing the data read,
* defaults to 0xFF
* @return Always returns true because there's no way to test success of SPI
* writes
*/
bool Adafruit_SPIDevice::write_then_read(const uint8_t *write_buffer,
size_t write_len, uint8_t *read_buffer,
size_t read_len, uint8_t sendvalue) {
beginTransactionWithAssertingCS();
// do the writing
#if defined(ARDUINO_ARCH_ESP32)
if (_spi) {
if (write_len > 0) {
_spi->transferBytes((uint8_t *)write_buffer, nullptr, write_len);
}
} else
#endif
{
for (size_t i = 0; i < write_len; i++) {
transfer(write_buffer[i]);
}
}
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.print(F("\tSPIDevice Wrote: "));
for (uint16_t i = 0; i < write_len; i++) {
DEBUG_SERIAL.print(F("0x"));
DEBUG_SERIAL.print(write_buffer[i], HEX);
DEBUG_SERIAL.print(F(", "));
if (write_len % 32 == 31) {
DEBUG_SERIAL.println();
}
}
DEBUG_SERIAL.println();
#endif
// do the reading
for (size_t i = 0; i < read_len; i++) {
read_buffer[i] = transfer(sendvalue);
}
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.print(F("\tSPIDevice Read: "));
for (uint16_t i = 0; i < read_len; i++) {
DEBUG_SERIAL.print(F("0x"));
DEBUG_SERIAL.print(read_buffer[i], HEX);
DEBUG_SERIAL.print(F(", "));
if (read_len % 32 == 31) {
DEBUG_SERIAL.println();
}
}
DEBUG_SERIAL.println();
#endif
endTransactionWithDeassertingCS();
return true;
}
/*!
* @brief Write some data and read some data at the same time from SPI
* into the same buffer, with transaction management. This is basicaly a wrapper
* for transfer() with CS-pin and transaction management. This /does/
* transmit-receive at the same time!
* @param buffer Pointer to buffer of data to write/read to/from
* @param len Number of bytes from buffer to write/read.
* @return Always returns true because there's no way to test success of SPI
* writes
*/
bool Adafruit_SPIDevice::write_and_read(uint8_t *buffer, size_t len) {
beginTransactionWithAssertingCS();
transfer(buffer, len);
endTransactionWithDeassertingCS();
return true;
}

View File

@ -0,0 +1,143 @@
#ifndef Adafruit_SPIDevice_h
#define Adafruit_SPIDevice_h
#include <Arduino.h>
#if !defined(SPI_INTERFACES_COUNT) || \
(defined(SPI_INTERFACES_COUNT) && (SPI_INTERFACES_COUNT > 0))
// HW SPI available
#include <SPI.h>
#define BUSIO_HAS_HW_SPI
#else
// SW SPI ONLY
enum { SPI_MODE0, SPI_MODE1, SPI_MODE2, _SPI_MODE4 };
typedef uint8_t SPIClass;
#endif
// some modern SPI definitions don't have BitOrder enum
#if (defined(__AVR__) && !defined(ARDUINO_ARCH_MEGAAVR)) || \
defined(ESP8266) || defined(TEENSYDUINO) || defined(SPARK) || \
defined(ARDUINO_ARCH_SPRESENSE) || defined(MEGATINYCORE) || \
defined(DXCORE) || defined(ARDUINO_AVR_ATmega4809) || \
defined(ARDUINO_AVR_ATmega4808) || defined(ARDUINO_AVR_ATmega3209) || \
defined(ARDUINO_AVR_ATmega3208) || defined(ARDUINO_AVR_ATmega1609) || \
defined(ARDUINO_AVR_ATmega1608) || defined(ARDUINO_AVR_ATmega809) || \
defined(ARDUINO_AVR_ATmega808) || defined(ARDUINO_ARCH_ARC32) || \
defined(ARDUINO_ARCH_XMC) || defined(ARDUINO_SILABS)
typedef enum _BitOrder {
SPI_BITORDER_MSBFIRST = MSBFIRST,
SPI_BITORDER_LSBFIRST = LSBFIRST,
} BusIOBitOrder;
#elif defined(ESP32) || defined(__ASR6501__) || defined(__ASR6502__)
// some modern SPI definitions don't have BitOrder enum and have different SPI
// mode defines
typedef enum _BitOrder {
SPI_BITORDER_MSBFIRST = SPI_MSBFIRST,
SPI_BITORDER_LSBFIRST = SPI_LSBFIRST,
} BusIOBitOrder;
#else
// Some platforms have a BitOrder enum but its named MSBFIRST/LSBFIRST
#define SPI_BITORDER_MSBFIRST MSBFIRST
#define SPI_BITORDER_LSBFIRST LSBFIRST
typedef BitOrder BusIOBitOrder;
#endif
#if defined(__IMXRT1062__) // Teensy 4.x
// *Warning* I disabled the usage of FAST_PINIO as the set/clear operations
// used in the cpp file are not atomic and can effect multiple IO pins
// and if an interrupt happens in between the time the code reads the register
// and writes out the updated value, that changes one or more other IO pins
// on that same IO port, those change will be clobbered when the updated
// values are written back. A fast version can be implemented that uses the
// ports set and clear registers which are atomic.
// typedef volatile uint32_t BusIO_PortReg;
// typedef uint32_t BusIO_PortMask;
//#define BUSIO_USE_FAST_PINIO
#elif defined(ARDUINO_ARCH_XMC)
#undef BUSIO_USE_FAST_PINIO
#elif defined(__AVR__) || defined(TEENSYDUINO)
typedef volatile uint8_t BusIO_PortReg;
typedef uint8_t BusIO_PortMask;
#define BUSIO_USE_FAST_PINIO
#elif defined(ESP8266) || defined(ESP32) || defined(__SAM3X8E__) || \
defined(ARDUINO_ARCH_SAMD)
typedef volatile uint32_t BusIO_PortReg;
typedef uint32_t BusIO_PortMask;
#define BUSIO_USE_FAST_PINIO
#elif (defined(__arm__) || defined(ARDUINO_FEATHER52)) && \
!defined(ARDUINO_ARCH_MBED) && !defined(ARDUINO_ARCH_RP2040) && \
!defined(ARDUINO_SILABS)
typedef volatile uint32_t BusIO_PortReg;
typedef uint32_t BusIO_PortMask;
#if !defined(__ASR6501__) && !defined(__ASR6502__)
#define BUSIO_USE_FAST_PINIO
#endif
#else
#undef BUSIO_USE_FAST_PINIO
#endif
/**! The class which defines how we will talk to this device over SPI **/
class Adafruit_SPIDevice {
public:
#ifdef BUSIO_HAS_HW_SPI
Adafruit_SPIDevice(int8_t cspin, uint32_t freq = 1000000,
BusIOBitOrder dataOrder = SPI_BITORDER_MSBFIRST,
uint8_t dataMode = SPI_MODE0, SPIClass *theSPI = &SPI);
#else
Adafruit_SPIDevice(int8_t cspin, uint32_t freq = 1000000,
BusIOBitOrder dataOrder = SPI_BITORDER_MSBFIRST,
uint8_t dataMode = SPI_MODE0, SPIClass *theSPI = nullptr);
#endif
Adafruit_SPIDevice(int8_t cspin, int8_t sck, int8_t miso, int8_t mosi,
uint32_t freq = 1000000,
BusIOBitOrder dataOrder = SPI_BITORDER_MSBFIRST,
uint8_t dataMode = SPI_MODE0);
~Adafruit_SPIDevice();
bool begin(void);
bool read(uint8_t *buffer, size_t len, uint8_t sendvalue = 0xFF);
bool write(const uint8_t *buffer, size_t len,
const uint8_t *prefix_buffer = nullptr, size_t prefix_len = 0);
bool write_then_read(const uint8_t *write_buffer, size_t write_len,
uint8_t *read_buffer, size_t read_len,
uint8_t sendvalue = 0xFF);
bool write_and_read(uint8_t *buffer, size_t len);
uint8_t transfer(uint8_t send);
void transfer(uint8_t *buffer, size_t len);
void beginTransaction(void);
void endTransaction(void);
void beginTransactionWithAssertingCS();
void endTransactionWithDeassertingCS();
private:
#ifdef BUSIO_HAS_HW_SPI
SPIClass *_spi = nullptr;
SPISettings *_spiSetting = nullptr;
#else
uint8_t *_spi = nullptr;
uint8_t *_spiSetting = nullptr;
#endif
uint32_t _freq;
BusIOBitOrder _dataOrder;
uint8_t _dataMode;
void setChipSelect(int value);
int8_t _cs, _sck, _mosi, _miso;
#ifdef BUSIO_USE_FAST_PINIO
BusIO_PortReg *mosiPort, *clkPort, *misoPort, *csPort;
BusIO_PortMask mosiPinMask, misoPinMask, clkPinMask, csPinMask;
#endif
bool _begun;
};
#endif // Adafruit_SPIDevice_h

View File

@ -0,0 +1,11 @@
# Adafruit Bus IO Library
# https://github.com/adafruit/Adafruit_BusIO
# MIT License
cmake_minimum_required(VERSION 3.5)
idf_component_register(SRCS "Adafruit_I2CDevice.cpp" "Adafruit_BusIO_Register.cpp" "Adafruit_SPIDevice.cpp"
INCLUDE_DIRS "."
REQUIRES arduino)
project(Adafruit_BusIO)

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2017 Adafruit Industries
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.

View File

@ -0,0 +1,8 @@
# Adafruit Bus IO Library [![Build Status](https://github.com/adafruit/Adafruit_BusIO/workflows/Arduino%20Library%20CI/badge.svg)](https://github.com/adafruit/Adafruit_BusIO/actions)
This is a helper library to abstract away I2C & SPI transactions and registers
Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit!
MIT license, all text above must be included in any redistribution

View File

@ -0,0 +1 @@
COMPONENT_ADD_INCLUDEDIRS = .

View File

@ -0,0 +1,21 @@
#include <Adafruit_I2CDevice.h>
Adafruit_I2CDevice i2c_dev = Adafruit_I2CDevice(0x10);
void setup() {
while (!Serial) { delay(10); }
Serial.begin(115200);
Serial.println("I2C address detection test");
if (!i2c_dev.begin()) {
Serial.print("Did not find device at 0x");
Serial.println(i2c_dev.address(), HEX);
while (1);
}
Serial.print("Device found on address 0x");
Serial.println(i2c_dev.address(), HEX);
}
void loop() {
}

View File

@ -0,0 +1,41 @@
#include <Adafruit_I2CDevice.h>
#define I2C_ADDRESS 0x60
Adafruit_I2CDevice i2c_dev = Adafruit_I2CDevice(I2C_ADDRESS);
void setup() {
while (!Serial) { delay(10); }
Serial.begin(115200);
Serial.println("I2C device read and write test");
if (!i2c_dev.begin()) {
Serial.print("Did not find device at 0x");
Serial.println(i2c_dev.address(), HEX);
while (1);
}
Serial.print("Device found on address 0x");
Serial.println(i2c_dev.address(), HEX);
uint8_t buffer[32];
// Try to read 32 bytes
i2c_dev.read(buffer, 32);
Serial.print("Read: ");
for (uint8_t i=0; i<32; i++) {
Serial.print("0x"); Serial.print(buffer[i], HEX); Serial.print(", ");
}
Serial.println();
// read a register by writing first, then reading
buffer[0] = 0x0C; // we'll reuse the same buffer
i2c_dev.write_then_read(buffer, 1, buffer, 2, false);
Serial.print("Write then Read: ");
for (uint8_t i=0; i<2; i++) {
Serial.print("0x"); Serial.print(buffer[i], HEX); Serial.print(", ");
}
Serial.println();
}
void loop() {
}

View File

@ -0,0 +1,38 @@
#include <Adafruit_I2CDevice.h>
#include <Adafruit_BusIO_Register.h>
#define I2C_ADDRESS 0x60
Adafruit_I2CDevice i2c_dev = Adafruit_I2CDevice(I2C_ADDRESS);
void setup() {
while (!Serial) { delay(10); }
Serial.begin(115200);
Serial.println("I2C device register test");
if (!i2c_dev.begin()) {
Serial.print("Did not find device at 0x");
Serial.println(i2c_dev.address(), HEX);
while (1);
}
Serial.print("Device found on address 0x");
Serial.println(i2c_dev.address(), HEX);
Adafruit_BusIO_Register id_reg = Adafruit_BusIO_Register(&i2c_dev, 0x0C, 2, LSBFIRST);
uint16_t id;
id_reg.read(&id);
Serial.print("ID register = 0x"); Serial.println(id, HEX);
Adafruit_BusIO_Register thresh_reg = Adafruit_BusIO_Register(&i2c_dev, 0x01, 2, LSBFIRST);
uint16_t thresh;
thresh_reg.read(&thresh);
Serial.print("Initial threshold register = 0x"); Serial.println(thresh, HEX);
thresh_reg.write(~thresh);
Serial.print("Post threshold register = 0x"); Serial.println(thresh_reg.read(), HEX);
}
void loop() {
}

View File

@ -0,0 +1,38 @@
#include <Adafruit_BusIO_Register.h>
// Define which interface to use by setting the unused interface to NULL!
#define SPIDEVICE_CS 10
Adafruit_SPIDevice *spi_dev = NULL; // new Adafruit_SPIDevice(SPIDEVICE_CS);
#define I2C_ADDRESS 0x5D
Adafruit_I2CDevice *i2c_dev = new Adafruit_I2CDevice(I2C_ADDRESS);
void setup() {
while (!Serial) { delay(10); }
Serial.begin(115200);
Serial.println("I2C or SPI device register test");
if (spi_dev && !spi_dev->begin()) {
Serial.println("Could not initialize SPI device");
}
if (i2c_dev) {
if (i2c_dev->begin()) {
Serial.print("Device found on I2C address 0x");
Serial.println(i2c_dev->address(), HEX);
} else {
Serial.print("Did not find I2C device at 0x");
Serial.println(i2c_dev->address(), HEX);
}
}
Adafruit_BusIO_Register id_reg = Adafruit_BusIO_Register(i2c_dev, spi_dev, ADDRBIT8_HIGH_TOREAD, 0x0F);
uint8_t id=0;
id_reg.read(&id);
Serial.print("ID register = 0x"); Serial.println(id, HEX);
}
void loop() {
}

View File

@ -0,0 +1,29 @@
#include <Adafruit_SPIDevice.h>
#define SPIDEVICE_CS 10
Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice(SPIDEVICE_CS, 100000, SPI_BITORDER_MSBFIRST, SPI_MODE1);
//Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice(SPIDEVICE_CS, 13, 12, 11, 100000, SPI_BITORDER_MSBFIRST, SPI_MODE1);
void setup() {
while (!Serial) { delay(10); }
Serial.begin(115200);
Serial.println("SPI device mode test");
if (!spi_dev.begin()) {
Serial.println("Could not initialize SPI device");
while (1);
}
}
void loop() {
Serial.println("\n\nTransfer test");
for (uint16_t x=0; x<=0xFF; x++) {
uint8_t i = x;
Serial.print("0x"); Serial.print(i, HEX);
spi_dev.read(&i, 1, i);
Serial.print("/"); Serial.print(i, HEX);
Serial.print(", ");
delay(25);
}
}

View File

@ -0,0 +1,39 @@
#include <Adafruit_SPIDevice.h>
#define SPIDEVICE_CS 10
Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice(SPIDEVICE_CS);
void setup() {
while (!Serial) { delay(10); }
Serial.begin(115200);
Serial.println("SPI device read and write test");
if (!spi_dev.begin()) {
Serial.println("Could not initialize SPI device");
while (1);
}
uint8_t buffer[32];
// Try to read 32 bytes
spi_dev.read(buffer, 32);
Serial.print("Read: ");
for (uint8_t i=0; i<32; i++) {
Serial.print("0x"); Serial.print(buffer[i], HEX); Serial.print(", ");
}
Serial.println();
// read a register by writing first, then reading
buffer[0] = 0x8F; // we'll reuse the same buffer
spi_dev.write_then_read(buffer, 1, buffer, 2, false);
Serial.print("Write then Read: ");
for (uint8_t i=0; i<2; i++) {
Serial.print("0x"); Serial.print(buffer[i], HEX); Serial.print(", ");
}
Serial.println();
}
void loop() {
}

View File

@ -0,0 +1,192 @@
/***************************************************
This is an example for how to use Adafruit_BusIO_RegisterBits from Adafruit_BusIO library.
Designed specifically to work with the Adafruit RTD Sensor
----> https://www.adafruit.com/products/3328
uisng a MAX31865 RTD-to-Digital Converter
----> https://datasheets.maximintegrated.com/en/ds/MAX31865.pdf
This sensor uses SPI to communicate, 4 pins are required to
interface.
A fifth pin helps to detect when a new conversion is ready.
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Example written (2020/3) by Andreas Hardtung/AnHard.
BSD license, all text above must be included in any redistribution
****************************************************/
#include <Adafruit_BusIO_Register.h>
#include <Adafruit_SPIDevice.h>
#define MAX31865_SPI_SPEED (5000000)
#define MAX31865_SPI_BITORDER (SPI_BITORDER_MSBFIRST)
#define MAX31865_SPI_MODE (SPI_MODE1)
#define MAX31865_SPI_CS (10)
#define MAX31865_READY_PIN (2)
Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice( MAX31865_SPI_CS, MAX31865_SPI_SPEED, MAX31865_SPI_BITORDER, MAX31865_SPI_MODE, &SPI); // Hardware SPI
// Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice( MAX31865_SPI_CS, 13, 12, 11, MAX31865_SPI_SPEED, MAX31865_SPI_BITORDER, MAX31865_SPI_MODE); // Software SPI
// MAX31865 chip related *********************************************************************************************
Adafruit_BusIO_Register config_reg = Adafruit_BusIO_Register(&spi_dev, 0x00, ADDRBIT8_HIGH_TOWRITE, 1, MSBFIRST);
Adafruit_BusIO_RegisterBits bias_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 7);
Adafruit_BusIO_RegisterBits auto_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 6);
Adafruit_BusIO_RegisterBits oneS_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 5);
Adafruit_BusIO_RegisterBits wire_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 4);
Adafruit_BusIO_RegisterBits faultT_bits = Adafruit_BusIO_RegisterBits(&config_reg, 2, 2);
Adafruit_BusIO_RegisterBits faultR_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 1);
Adafruit_BusIO_RegisterBits fi50hz_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 0);
Adafruit_BusIO_Register rRatio_reg = Adafruit_BusIO_Register(&spi_dev, 0x01, ADDRBIT8_HIGH_TOWRITE, 2, MSBFIRST);
Adafruit_BusIO_RegisterBits rRatio_bits = Adafruit_BusIO_RegisterBits(&rRatio_reg, 15, 1);
Adafruit_BusIO_RegisterBits fault_bit = Adafruit_BusIO_RegisterBits(&rRatio_reg, 1, 0);
Adafruit_BusIO_Register maxRratio_reg = Adafruit_BusIO_Register(&spi_dev, 0x03, ADDRBIT8_HIGH_TOWRITE, 2, MSBFIRST);
Adafruit_BusIO_RegisterBits maxRratio_bits = Adafruit_BusIO_RegisterBits(&maxRratio_reg, 15, 1);
Adafruit_BusIO_Register minRratio_reg = Adafruit_BusIO_Register(&spi_dev, 0x05, ADDRBIT8_HIGH_TOWRITE, 2, MSBFIRST);
Adafruit_BusIO_RegisterBits minRratio_bits = Adafruit_BusIO_RegisterBits(&minRratio_reg, 15, 1);
Adafruit_BusIO_Register fault_reg = Adafruit_BusIO_Register(&spi_dev, 0x07, ADDRBIT8_HIGH_TOWRITE, 1, MSBFIRST);
Adafruit_BusIO_RegisterBits range_high_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 7);
Adafruit_BusIO_RegisterBits range_low_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 6);
Adafruit_BusIO_RegisterBits refin_high_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 5);
Adafruit_BusIO_RegisterBits refin_low_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 4);
Adafruit_BusIO_RegisterBits rtdin_low_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 3);
Adafruit_BusIO_RegisterBits voltage_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 2);
// Print the details of the configuration register.
void printConfig( void ) {
Serial.print("BIAS: "); if (bias_bit.read() ) Serial.print("ON"); else Serial.print("OFF");
Serial.print(", AUTO: "); if (auto_bit.read() ) Serial.print("ON"); else Serial.print("OFF");
Serial.print(", ONES: "); if (oneS_bit.read() ) Serial.print("ON"); else Serial.print("OFF");
Serial.print(", WIRE: "); if (wire_bit.read() ) Serial.print("3"); else Serial.print("2/4");
Serial.print(", FAULTCLEAR: "); if (faultR_bit.read() ) Serial.print("ON"); else Serial.print("OFF");
Serial.print(", "); if (fi50hz_bit.read() ) Serial.print("50HZ"); else Serial.print("60HZ");
Serial.println();
}
// Check and print faults. Then clear them.
void checkFaults( void ) {
if (fault_bit.read()) {
Serial.print("MAX: "); Serial.println(maxRratio_bits.read());
Serial.print("VAL: "); Serial.println( rRatio_bits.read());
Serial.print("MIN: "); Serial.println(minRratio_bits.read());
if (range_high_fault_bit.read() ) Serial.println("Range high fault");
if ( range_low_fault_bit.read() ) Serial.println("Range low fault");
if (refin_high_fault_bit.read() ) Serial.println("REFIN high fault");
if ( refin_low_fault_bit.read() ) Serial.println("REFIN low fault");
if ( rtdin_low_fault_bit.read() ) Serial.println("RTDIN low fault");
if ( voltage_fault_bit.read() ) Serial.println("Voltage fault");
faultR_bit.write(1); // clear fault
}
}
void setup() {
#if (MAX31865_1_READY_PIN != -1)
pinMode(MAX31865_READY_PIN ,INPUT_PULLUP);
#endif
while (!Serial) { delay(10); }
Serial.begin(115200);
Serial.println("SPI Adafruit_BusIO_RegisterBits test on MAX31865");
if (!spi_dev.begin()) {
Serial.println("Could not initialize SPI device");
while (1);
}
// Set up for automode 50Hz. We don't care about selfheating. We want the highest possible sampling rate.
auto_bit.write(0); // Don't switch filtermode while auto_mode is on.
fi50hz_bit.write(1); // Set filter to 50Hz mode.
faultR_bit.write(1); // Clear faults.
bias_bit.write(1); // In automode we want to have the bias current always on.
delay(5); // Wait until bias current settles down.
// 10.5 time constants of the input RC network is required.
// 10ms worst case for 10kω reference resistor and a 0.1µF capacitor across the RTD inputs.
// Adafruit Module has 0.1µF and only 430/4300ω So here 0.43/4.3ms
auto_bit.write(1); // Now we can set automode. Automatically starting first conversion.
// Test the READY_PIN
#if (defined( MAX31865_READY_PIN ) && (MAX31865_READY_PIN != -1))
int i = 0;
while (digitalRead(MAX31865_READY_PIN) && i++ <= 100) { delay(1); }
if (i >= 100) {
Serial.print("ERROR: Max31865 Pin detection does not work. PIN:");
Serial.println(MAX31865_READY_PIN);
}
#else
delay(100);
#endif
// Set ratio range.
// Setting the temperatures would need some more calculation - not related to Adafruit_BusIO_RegisterBits.
uint16_t ratio = rRatio_bits.read();
maxRratio_bits.write( (ratio < 0x8fffu-1000u) ? ratio + 1000u : 0x8fffu );
minRratio_bits.write( (ratio > 1000u) ? ratio - 1000u : 0u );
printConfig();
checkFaults();
}
void loop() {
#if (defined( MAX31865_READY_PIN ) && (MAX31865_1_READY_PIN != -1))
// Is conversion ready?
if (!digitalRead(MAX31865_READY_PIN))
#else
// Warant conversion is ready.
delay(21); // 21ms for 50Hz-mode. 19ms in 60Hz-mode.
#endif
{
// Read ratio, calculate temperature, scale, filter and print.
Serial.println( rRatio2C( rRatio_bits.read() ) * 100.0f, 0); // Temperature scaled by 100
// Check, print, clear faults.
checkFaults();
}
// Do something else.
//delay(15000);
}
// Module/Sensor related. Here Adafruit PT100 module with a 2_Wire PT100 Class C *****************************
float rRatio2C(uint16_t ratio) {
// A simple linear conversion.
const float R0 = 100.0f;
const float Rref = 430.0f;
const float alphaPT = 0.003850f;
const float ADCmax = (1u << 15) - 1.0f;
const float rscale = Rref / ADCmax;
// Measured temperature in boiling water 101.08°C with factor a = 1 and b = 0. Rref and MAX at about 22±2°C.
// Measured temperature in ice/water bath 0.76°C with factor a = 1 and b = 0. Rref and MAX at about 22±2°C.
//const float a = 1.0f / (alphaPT * R0);
const float a = (100.0f/101.08f) / (alphaPT * R0);
//const float b = 0.0f; // 101.08
const float b = -0.76f; // 100.32 > 101.08
return filterRing( ((ratio * rscale) - R0) * a + b );
}
// General purpose *********************************************************************************************
#define RINGLENGTH 250
float filterRing( float newVal ) {
static float ring[RINGLENGTH] = { 0.0 };
static uint8_t ringIndex = 0;
static bool ringFull = false;
if ( ringIndex == RINGLENGTH ) { ringFull = true; ringIndex = 0; }
ring[ringIndex] = newVal;
uint8_t loopEnd = (ringFull) ? RINGLENGTH : ringIndex + 1;
float ringSum = 0.0f;
for (uint8_t i = 0; i < loopEnd; i++) ringSum += ring[i];
ringIndex++;
return ringSum / loopEnd;
}

View File

@ -0,0 +1,34 @@
#include <Adafruit_BusIO_Register.h>
#include <Adafruit_SPIDevice.h>
#define SPIDEVICE_CS 10
Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice(SPIDEVICE_CS);
void setup() {
while (!Serial) { delay(10); }
Serial.begin(115200);
Serial.println("SPI device register test");
if (!spi_dev.begin()) {
Serial.println("Could not initialize SPI device");
while (1);
}
Adafruit_BusIO_Register id_reg = Adafruit_BusIO_Register(&spi_dev, 0x0F, ADDRBIT8_HIGH_TOREAD);
uint8_t id = 0;
id_reg.read(&id);
Serial.print("ID register = 0x"); Serial.println(id, HEX);
Adafruit_BusIO_Register thresh_reg = Adafruit_BusIO_Register(&spi_dev, 0x0C, ADDRBIT8_HIGH_TOREAD, 2, LSBFIRST);
uint16_t thresh = 0;
thresh_reg.read(&thresh);
Serial.print("Initial threshold register = 0x"); Serial.println(thresh, HEX);
thresh_reg.write(~thresh);
Serial.print("Post threshold register = 0x"); Serial.println(thresh_reg.read(), HEX);
}
void loop() {
}

View File

@ -0,0 +1,9 @@
name=Adafruit BusIO
version=1.15.0
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=This is a library for abstracting away I2C and SPI interfacing
paragraph=This is a library for abstracting away I2C and SPI interfacing
category=Signal Input/Output
url=https://github.com/adafruit/Adafruit_BusIO
architectures=*

View File

@ -0,0 +1,46 @@
Thank you for opening an issue on an Adafruit Arduino library repository. To
improve the speed of resolution please review the following guidelines and
common troubleshooting steps below before creating the issue:
- **Do not use GitHub issues for troubleshooting projects and issues.** Instead use
the forums at http://forums.adafruit.com to ask questions and troubleshoot why
something isn't working as expected. In many cases the problem is a common issue
that you will more quickly receive help from the forum community. GitHub issues
are meant for known defects in the code. If you don't know if there is a defect
in the code then start with troubleshooting on the forum first.
- **If following a tutorial or guide be sure you didn't miss a step.** Carefully
check all of the steps and commands to run have been followed. Consult the
forum if you're unsure or have questions about steps in a guide/tutorial.
- **For Arduino projects check these very common issues to ensure they don't apply**:
- For uploading sketches or communicating with the board make sure you're using
a **USB data cable** and **not** a **USB charge-only cable**. It is sometimes
very hard to tell the difference between a data and charge cable! Try using the
cable with other devices or swapping to another cable to confirm it is not
the problem.
- **Be sure you are supplying adequate power to the board.** Check the specs of
your board and plug in an external power supply. In many cases just
plugging a board into your computer is not enough to power it and other
peripherals.
- **Double check all soldering joints and connections.** Flakey connections
cause many mysterious problems. See the [guide to excellent soldering](https://learn.adafruit.com/adafruit-guide-excellent-soldering/tools) for examples of good solder joints.
- **Ensure you are using an official Arduino or Adafruit board.** We can't
guarantee a clone board will have the same functionality and work as expected
with this code and don't support them.
If you're sure this issue is a defect in the code and checked the steps above
please fill in the following fields to provide enough troubleshooting information.
You may delete the guideline and text above to just leave the following details:
- Arduino board: **INSERT ARDUINO BOARD NAME/TYPE HERE**
- Arduino IDE version (found in Arduino -> About Arduino menu): **INSERT ARDUINO
VERSION HERE**
- List the steps to reproduce the problem below (if possible attach a sketch or
copy the sketch code in too): **LIST REPRO STEPS BELOW**

View File

@ -0,0 +1,26 @@
Thank you for creating a pull request to contribute to Adafruit's GitHub code!
Before you open the request please review the following guidelines and tips to
help it be more easily integrated:
- **Describe the scope of your change--i.e. what the change does and what parts
of the code were modified.** This will help us understand any risks of integrating
the code.
- **Describe any known limitations with your change.** For example if the change
doesn't apply to a supported platform of the library please mention it.
- **Please run any tests or examples that can exercise your modified code.** We
strive to not break users of the code and running tests/examples helps with this
process.
Thank you again for contributing! We will try to test and integrate the change
as soon as we can, but be aware we have many GitHub repositories to manage and
can't immediately respond to every request. There is no need to bump or check in
on a pull request (it will clutter the discussion of the request).
Also don't be worried if the request is closed or not integrated--sometimes the
priorities of Adafruit's GitHub code (education, ease of use) might not match the
priorities of the pull request. Don't fret, the open source community thrives on
forks and GitHub makes it easy to keep your changes in a forked repo.
After reviewing the guidelines above you can delete this text from the pull request.

View File

@ -0,0 +1,32 @@
name: Arduino Library CI
on: [pull_request, push, repository_dispatch]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/setup-python@v4
with:
python-version: '3.x'
- uses: actions/checkout@v3
- uses: actions/checkout@v3
with:
repository: adafruit/ci-arduino
path: ci
- name: pre-install
run: bash ci/actions_install.sh
- name: test platforms
run: python3 ci/build_platform.py main_platforms
- name: clang
run: python3 ci/run-clang-format.py -e "ci/*" -e "bin/*" -r .
- name: doxygen
env:
GH_REPO_TOKEN: ${{ secrets.GH_REPO_TOKEN }}
PRETTYNAME : "Adafruit MLX90614 Arduino Library"
run: bash ci/doxy_gen_and_deploy.sh

View File

@ -0,0 +1 @@
{"type": "library", "name": "Adafruit MLX90614 Library", "version": "2.1.5", "spec": {"owner": "adafruit", "id": 782, "name": "Adafruit MLX90614 Library", "requirements": null, "uri": null}}

View File

@ -0,0 +1,178 @@
/***************************************************
This is a library for the MLX90614 Temp Sensor
Designed specifically to work with the MLX90614 sensors in the
adafruit shop
----> https://www.adafruit.com/products/1747 (3V)
----> https://www.adafruit.com/products/1748 (5V)
These sensors use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#include "Adafruit_MLX90614.h"
Adafruit_MLX90614::~Adafruit_MLX90614() {
if (i2c_dev)
delete i2c_dev;
}
/**
* @brief Begin the I2C connection
* @param addr I2C address for the device.
* @param wire Pointer to Wire instance
* @return True if the device was successfully initialized, otherwise false.
*/
bool Adafruit_MLX90614::begin(uint8_t addr, TwoWire *wire) {
_addr = addr; // needed for CRC
if (i2c_dev)
delete i2c_dev;
i2c_dev = new Adafruit_I2CDevice(addr, wire);
return i2c_dev->begin();
}
/**
* @brief Read the raw value from the emissivity register
*
* @return uint16_t The unscaled emissivity value or '0' if reading failed
*/
uint16_t Adafruit_MLX90614::readEmissivityReg(void) {
return read16(MLX90614_EMISS);
}
/**
* @brief Write the raw unscaled emissivity value to the emissivity register
*
* @param ereg The unscaled emissivity value
*/
void Adafruit_MLX90614::writeEmissivityReg(uint16_t ereg) {
write16(MLX90614_EMISS, 0); // erase
vTaskDelay(10);
write16(MLX90614_EMISS, ereg);
vTaskDelay(10);
}
/**
* @brief Read the emissivity value from the sensor's register and scale
*
* @return double The emissivity value, ranging from 0.1 - 1.0 or NAN if reading
* failed
*/
double Adafruit_MLX90614::readEmissivity(void) {
uint16_t ereg = read16(MLX90614_EMISS);
if (ereg == 0)
return NAN;
return ((double)ereg) / 65535.0;
}
/**
* @brief Set the emissivity value
*
* @param emissivity The emissivity value to use, between 0.1 and 1.0
*/
void Adafruit_MLX90614::writeEmissivity(double emissivity) {
uint16_t ereg = (uint16_t)(0xffff * emissivity);
writeEmissivityReg(ereg);
}
/**
* @brief Get the current temperature of an object in degrees Farenheit
*
* @return double The temperature in degrees Farenheit or NAN if reading failed
*/
double Adafruit_MLX90614::readObjectTempF(void) {
return (readTemp(MLX90614_TOBJ1) * 9 / 5) + 32;
}
/**
* @brief Get the current ambient temperature in degrees Farenheit
*
* @return double The temperature in degrees Farenheit or NAN if reading failed
*/
double Adafruit_MLX90614::readAmbientTempF(void) {
return (readTemp(MLX90614_TA) * 9 / 5) + 32;
}
/**
* @brief Get the current temperature of an object in degrees Celcius
*
* @return double The temperature in degrees Celcius or NAN if reading failed
*/
double Adafruit_MLX90614::readObjectTempC(void) {
return readTemp(MLX90614_TOBJ1);
}
/**
* @brief Get the current ambient temperature in degrees Celcius
*
* @return double The temperature in degrees Celcius or NAN if reading failed
*/
double Adafruit_MLX90614::readAmbientTempC(void) {
return readTemp(MLX90614_TA);
}
float Adafruit_MLX90614::readTemp(uint8_t reg) {
float temp;
temp = read16(reg);
if (temp == 0)
return NAN;
temp *= .02;
temp -= 273.15;
return temp;
}
/*********************************************************************/
uint16_t Adafruit_MLX90614::read16(uint8_t a) {
uint8_t buffer[3];
buffer[0] = a;
// read two bytes of data + pec
bool status = i2c_dev->write_then_read(buffer, 1, buffer, 3);
if (!status)
return 0;
// return data, ignore pec
return uint16_t(buffer[0]) | (uint16_t(buffer[1]) << 8);
}
byte Adafruit_MLX90614::crc8(byte *addr, byte len)
// The PEC calculation includes all bits except the START, REPEATED START, STOP,
// ACK, and NACK bits. The PEC is a CRC-8 with polynomial X8+X2+X1+1.
{
byte crc = 0;
while (len--) {
byte inbyte = *addr++;
for (byte i = 8; i; i--) {
byte carry = (crc ^ inbyte) & 0x80;
crc <<= 1;
if (carry)
crc ^= 0x7;
inbyte <<= 1;
}
}
return crc;
}
void Adafruit_MLX90614::write16(uint8_t a, uint16_t v) {
uint8_t buffer[4];
buffer[0] = _addr << 1;
buffer[1] = a;
buffer[2] = v & 0xff;
buffer[3] = v >> 8;
uint8_t pec = crc8(buffer, 4);
buffer[0] = buffer[1];
buffer[1] = buffer[2];
buffer[2] = buffer[3];
buffer[3] = pec;
i2c_dev->write(buffer, 4);
}

View File

@ -0,0 +1,68 @@
/***************************************************
This is a library for the MLX90614 Temp Sensor
Designed specifically to work with the MLX90614 sensors in the
adafruit shop
----> https://www.adafruit.com/products/1747 (3V)
----> https://www.adafruit.com/products/1748 (5V)
These sensors use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit in any redistribution
****************************************************/
#include <Adafruit_I2CDevice.h>
#include <Arduino.h>
#define MLX90614_I2CADDR 0x5A
// RAM
#define MLX90614_RAWIR1 0x04
#define MLX90614_RAWIR2 0x05
#define MLX90614_TA 0x06
#define MLX90614_TOBJ1 0x07
#define MLX90614_TOBJ2 0x08
// EEPROM
#define MLX90614_TOMAX 0x20
#define MLX90614_TOMIN 0x21
#define MLX90614_PWMCTRL 0x22
#define MLX90614_TARANGE 0x23
#define MLX90614_EMISS 0x24
#define MLX90614_CONFIG 0x25
#define MLX90614_ADDR 0x2E
#define MLX90614_ID1 0x3C
#define MLX90614_ID2 0x3D
#define MLX90614_ID3 0x3E
#define MLX90614_ID4 0x3F
/**
* @brief Class to read from and control a MLX90614 Temp Sensor
*
*/
class Adafruit_MLX90614 {
public:
~Adafruit_MLX90614();
bool begin(uint8_t addr = MLX90614_I2CADDR, TwoWire *wire = &Wire);
double readObjectTempC(void);
double readAmbientTempC(void);
double readObjectTempF(void);
double readAmbientTempF(void);
uint16_t readEmissivityReg(void);
void writeEmissivityReg(uint16_t ereg);
double readEmissivity(void);
void writeEmissivity(double emissivity);
private:
Adafruit_I2CDevice *i2c_dev = NULL; ///< Pointer to I2C bus interface
float readTemp(uint8_t reg);
uint16_t read16(uint8_t addr);
void write16(uint8_t addr, uint16_t data);
byte crc8(byte *addr, byte len);
uint8_t _addr;
};

View File

@ -0,0 +1,51 @@
# Adafruit-MLX90614-Library [![Build Status](https://github.com/adafruit/Adafruit-MLX90614-Library/workflows/Arduino%20Library%20CI/badge.svg)](https://github.com/adafruit/Adafruit-MLX90614-Library/actions)[![Documentation](https://github.com/adafruit/ci-arduino/blob/master/assets/doxygen_badge.svg)](http://adafruit.github.io/Adafruit-MLX90614-Library/html/index.html)
This is a library for the MLX90614 temperature sensor
<a href="https://www.adafruit.com/products/1747"><img src="https://cdn-shop.adafruit.com/970x728/1747-00.jpg" width="500px"></a>
Designed and tested to work with the MLX90614 sensors in the adafruit shop
* https://www.adafruit.com/products/1747 3V version
* https://www.adafruit.com/products/1748 5V version
Check out the links above for our tutorials and wiring diagrams
Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit!
# Installation
To install, use the Arduino Library Manager and search for "Adafruit-MLX90614-Library" and install the library.
# Contributing
Contributions are welcome! Please read our [Code of Conduct](https://github.com/adafruit/Adafruit-MLX90614-Library/blob/master/CODE_OF_CONDUCT.md>)
before contributing to help this project stay welcoming.
## Documentation and doxygen
Documentation is produced by doxygen. Contributions should include documentation for any new code added.
Some examples of how to use doxygen can be found in these guide pages:
https://learn.adafruit.com/the-well-automated-arduino-library/doxygen
https://learn.adafruit.com/the-well-automated-arduino-library/doxygen-tips
## Formatting and clang-format
This library uses [`clang-format`](https://releases.llvm.org/download.html) to standardize the formatting of `.cpp` and `.h` files.
Contributions should be formatted using `clang-format`:
The `-i` flag will make the changes to the file.
```bash
clang-format -i *.cpp *.h
```
If you prefer to make the changes yourself, running `clang-format` without the `-i` flag will print out a formatted version of the file. You can save this to a file and diff it against the original to see the changes.
Note that the formatting output by `clang-format` is what the automated formatting checker will expect. Any diffs from this formatting will result in a failed build until they are addressed. Using the `-i` flag is highly recommended.
### clang-format resources
* [Binary builds and source available on the LLVM downloads page](https://releases.llvm.org/download.html)
* [Documentation and IDE integration](https://clang.llvm.org/docs/ClangFormat.html)
## About this Driver
Written by Limor Fried for Adafruit Industries.
BSD license, check license.txt for more information
All text above must be included in any redistribution

View File

@ -0,0 +1,127 @@
# Adafruit Community Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and leaders pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level or type of
experience, education, socio-economic status, nationality, personal appearance,
race, religion, or sexual identity and orientation.
## Our Standards
We are committed to providing a friendly, safe and welcoming environment for
all.
Examples of behavior that contributes to creating a positive environment
include:
* Be kind and courteous to others
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Collaborating with other community members
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and sexual attention or advances
* The use of inappropriate images, including in a community member's avatar
* The use of inappropriate language, including in a community member's nickname
* Any spamming, flaming, baiting or other attention-stealing behavior
* Excessive or unwelcome helping; answering outside the scope of the question
asked
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate
The goal of the standards and moderation guidelines outlined here is to build
and maintain a respectful community. We ask that you dont just aim to be
"technically unimpeachable", but rather try to be your best self.
We value many things beyond technical expertise, including collaboration and
supporting others within our community. Providing a positive experience for
other community members can have a much more significant impact than simply
providing the correct answer.
## Our Responsibilities
Project leaders are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project leaders have the right and responsibility to remove, edit, or
reject messages, comments, commits, code, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any community member for other behaviors that they deem
inappropriate, threatening, offensive, or harmful.
## Moderation
Instances of behaviors that violate the Adafruit Community Code of Conduct
may be reported by any member of the community. Community members are
encouraged to report these situations, including situations they witness
involving other community members.
You may report in the following ways:
In any situation, you may send an email to <support@adafruit.com>.
On the Adafruit Discord, you may send an open message from any channel
to all Community Helpers by tagging @community helpers. You may also send an
open message from any channel, or a direct message to @kattni#1507,
@tannewt#4653, @Dan Halbert#1614, @cater#2442, @sommersoft#0222, or
@Andon#8175.
Email and direct message reports will be kept confidential.
In situations on Discord where the issue is particularly egregious, possibly
illegal, requires immediate action, or violates the Discord terms of service,
you should also report the message directly to Discord.
These are the steps for upholding our communitys standards of conduct.
1. Any member of the community may report any situation that violates the
Adafruit Community Code of Conduct. All reports will be reviewed and
investigated.
2. If the behavior is an egregious violation, the community member who
committed the violation may be banned immediately, without warning.
3. Otherwise, moderators will first respond to such behavior with a warning.
4. Moderators follow a soft "three strikes" policy - the community member may
be given another chance, if they are receptive to the warning and change their
behavior.
5. If the community member is unreceptive or unreasonable when warned by a
moderator, or the warning goes unheeded, they may be banned for a first or
second offense. Repeated offenses will result in the community member being
banned.
## Scope
This Code of Conduct and the enforcement policies listed above apply to all
Adafruit Community venues. This includes but is not limited to any community
spaces (both public and private), the entire Adafruit Discord server, and
Adafruit GitHub repositories. Examples of Adafruit Community spaces include
but are not limited to meet-ups, audio chats on the Adafruit Discord, or
interaction at a conference.
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. As a community
member, you are representing our community, and are expected to behave
accordingly.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 1.4, available at
<https://www.contributor-covenant.org/version/1/4/code-of-conduct.html>,
and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html).
For other projects adopting the Adafruit Community Code of
Conduct, please contact the maintainers of those projects for enforcement.
If you wish to use this code of conduct for your own project, consider
explicitly mentioning your moderation policy or making a copy with your
own moderation policy so as to avoid confusion.

View File

@ -0,0 +1,47 @@
/*
* See app note:
* https://www.melexis.com/en/documents/documentation/application-notes/application-note-mlx90614-changing-emissivity-setting
*
* 1. Write 0x0000 to address 0x04 (erase the EEPROM cell)
* 2. Write the new value to address 0x04
* 3. Read the value in address 0x04 in order to check that the correct value is stored
* 4. Restart the module
*
*/
#include <Adafruit_MLX90614.h>
//== CHANGE THIS ============
double new_emissivity = 0.95;
//===========================
Adafruit_MLX90614 mlx = Adafruit_MLX90614();
void setup() {
// Serial.begin(9600);
// while (!Serial);
Serial.println("Adafruit MLX90614 Emissivity Setter.\n");
// init sensor
if (!mlx.begin()) {
Serial.println("Error connecting to MLX sensor. Check wiring.");
while (1);
};
// read current emissivity
Serial.print("Current emissivity = "); Serial.println(mlx.readEmissivity());
// set new emissivity
Serial.print("Setting emissivity = "); Serial.println(new_emissivity);
mlx.writeEmissivity(new_emissivity); // this does the 0x0000 erase write
// read back
Serial.print("New emissivity = "); Serial.println(mlx.readEmissivity());
// done
Serial.print("DONE. Restart the module.");
}
void loop() {
}

View File

@ -0,0 +1,46 @@
/***************************************************
This is a library example for the MLX90614 Temp Sensor
Designed specifically to work with the MLX90614 sensors in the
adafruit shop
----> https://www.adafruit.com/products/1747 3V version
----> https://www.adafruit.com/products/1748 5V version
These sensors use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#include <Adafruit_MLX90614.h>
Adafruit_MLX90614 mlx = Adafruit_MLX90614();
void setup() {
Serial.begin(9600);
while (!Serial);
Serial.println("Adafruit MLX90614 test");
if (!mlx.begin()) {
Serial.println("Error connecting to MLX sensor. Check wiring.");
while (1);
};
Serial.print("Emissivity = "); Serial.println(mlx.readEmissivity());
Serial.println("================================================");
}
void loop() {
Serial.print("Ambient = "); Serial.print(mlx.readAmbientTempC());
Serial.print("*C\tObject = "); Serial.print(mlx.readObjectTempC()); Serial.println("*C");
Serial.print("Ambient = "); Serial.print(mlx.readAmbientTempF());
Serial.print("*F\tObject = "); Serial.print(mlx.readObjectTempF()); Serial.println("*F");
Serial.println();
delay(500);
}

View File

@ -0,0 +1,10 @@
name=Adafruit MLX90614 Library
version=2.1.5
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=Arduino library for the MLX90614 sensors in the Adafruit shop
paragraph=Arduino library for the MLX90614 sensors in the Adafruit shop
category=Sensors
url=https://github.com/adafruit/Adafruit-MLX90614-Library
architectures=*
depends=Adafruit BusIO

View File

@ -0,0 +1,26 @@
Software License Agreement (BSD License)
Copyright (c) 2020 Limor Fried for Adafruit Industries
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''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 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.

5
lib/ArduinoHttpClient/.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.development
examples/node_test_server/node_modules/
*.DS_Store
*/.DS_Store
examples/.DS_Store

View File

@ -0,0 +1 @@
{"type": "library", "name": "ArduinoHttpClient", "version": "0.4.0", "spec": {"owner": "arduino-libraries", "id": 798, "name": "ArduinoHttpClient", "requirements": null, "uri": null}}

View File

@ -0,0 +1,33 @@
## ArduinoHttpClient 0.4.0 - 2019.04.09
* Added URLEncoder helper
## ArduinoHttpClient 0.3.2 - 2019.02.04
* Changed Flush return value resulting in compilation error. Thanks @forGGe
## ArduinoHttpClient 0.3.1 - 2017.09.25
* Changed examples to support Arduino Create secret tabs
* Increase WebSocket secrect-key length to 24 characters
## ArduinoHttpClient 0.3.0 - 2017.04.20
* Added support for PATCH operations
* Added support for chunked response bodies
* Added new beginBody API
## ArduinoHttpClient 0.2.0 - 2017.01.12
* Added PATCH method
* Added basic auth example
* Added custom header example
## ArduinoHttpClient 0.1.1 - 2016.12.16
* More robust response parser
## ArduinoHttpClient 0.1.0 - 2016.07.05
* Initial release

View File

@ -0,0 +1,25 @@
# ArduinoHttpClient
ArduinoHttpClient is a library to make it easier to interact with web servers from Arduino.
Derived from [Adrian McEwen's HttpClient library](https://github.com/amcewen/HttpClient)
## Dependencies
- Requires a networking hardware and a library that provides transport specific `Client` instance, such as:
- [WiFiNINA](https://github.com/arduino-libraries/WiFiNINA)
- [WiFi101](https://github.com/arduino-libraries/WiFi101)
- [Ethernet](https://github.com/arduino-libraries/Ethernet)
- [MKRGSM](https://github.com/arduino-libraries/MKRGSM)
- [MKRNB](https://github.com/arduino-libraries/MKRNB)
- [WiFi](https://github.com/arduino-libraries/WiFi)
- [GSM](https://github.com/arduino-libraries/GSM)
## Usage
In normal usage, handles the outgoing request and Host header. The returned status code is parsed for you, as is the Content-Length header (if present).
Because it expects an object of type Client, you can use it with any of the networking classes that derive from that. Which means it will work with WiFiClient, EthernetClient and GSMClient.
See the examples for more detail on how the library is used.

View File

@ -0,0 +1,66 @@
/*
GET client with HTTP basic authentication for ArduinoHttpClient library
Connects to server once every five seconds, sends a GET request
created 14 Feb 2016
by Tom Igoe
modified 3 Jan 2017 to add HTTP basic authentication
by Sandeep Mistry
modified 22 Jan 2019
by Tom Igoe
this example is in the public domain
*/
#include <ArduinoHttpClient.h>
#include <WiFi101.h>
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
/////// Wifi Settings ///////
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
char serverAddress[] = "192.168.0.3"; // server address
int port = 8080;
WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
void setup() {
Serial.begin(9600);
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
}
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
Serial.println("making GET request with HTTP basic authentication");
client.beginRequest();
client.get("/secure");
client.sendBasicAuth("username", "password"); // send the username and password for authentication
client.endRequest();
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
Serial.println("Wait five seconds");
delay(5000);
}

View File

@ -0,0 +1,3 @@
#define SECRET_SSID ""
#define SECRET_PASS ""

View File

@ -0,0 +1,91 @@
/*
Custom request header example for the ArduinoHttpClient
library. This example sends a GET and a POST request with a custom header every 5 seconds.
based on SimpleGet example by Tom Igoe
header modifications by Todd Treece
modified 22 Jan 2019
by Tom Igoe
this example is in the public domain
*/
#include <ArduinoHttpClient.h>
#include <WiFi101.h>
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
/////// Wifi Settings ///////
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
char serverAddress[] = "192.168.0.3"; // server address
int port = 8080;
WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
void setup() {
Serial.begin(9600);
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
}
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
Serial.println("making GET request");
client.beginRequest();
client.get("/");
client.sendHeader("X-CUSTOM-HEADER", "custom_value");
client.endRequest();
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("GET Status code: ");
Serial.println(statusCode);
Serial.print("GET Response: ");
Serial.println(response);
Serial.println("Wait five seconds");
delay(5000);
Serial.println("making POST request");
String postData = "name=Alice&age=12";
client.beginRequest();
client.post("/");
client.sendHeader(HTTP_HEADER_CONTENT_TYPE, "application/x-www-form-urlencoded");
client.sendHeader(HTTP_HEADER_CONTENT_LENGTH, postData.length());
client.sendHeader("X-CUSTOM-HEADER", "custom_value");
client.endRequest();
client.write((const byte*)postData.c_str(), postData.length());
// note: the above line can also be achieved with the simpler line below:
//client.print(postData);
// read the status code and body of the response
statusCode = client.responseStatusCode();
response = client.responseBody();
Serial.print("POST Status code: ");
Serial.println(statusCode);
Serial.print("POST Response: ");
Serial.println(response);
Serial.println("Wait five seconds");
delay(5000);
}

View File

@ -0,0 +1,3 @@
#define SECRET_SSID ""
#define SECRET_PASS ""

View File

@ -0,0 +1,103 @@
/*
Dweet.io GET client for ArduinoHttpClient library
Connects to dweet.io once every ten seconds,
sends a GET request and a request body. Uses SSL
Shows how to use Strings to assemble path and parse content
from response. dweet.io expects:
https://dweet.io/get/latest/dweet/for/thingName
For more on dweet.io, see https://dweet.io/play/
created 15 Feb 2016
updated 22 Jan 2019
by Tom Igoe
this example is in the public domain
*/
#include <ArduinoHttpClient.h>
#include <WiFi101.h>
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
/////// Wifi Settings ///////
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
const char serverAddress[] = "dweet.io"; // server address
int port = 80;
String dweetName = "scandalous-cheese-hoarder"; // use your own thing name here
WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
void setup() {
Serial.begin(9600);
while (!Serial);
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
}
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
// assemble the path for the GET message:
String path = "/get/latest/dweet/for/" + dweetName;
// send the GET request
Serial.println("making GET request");
client.get(path);
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
/*
Typical response is:
{"this":"succeeded",
"by":"getting",
"the":"dweets",
"with":[{"thing":"my-thing-name",
"created":"2016-02-16T05:10:36.589Z",
"content":{"sensorValue":456}}]}
You want "content": numberValue
*/
// now parse the response looking for "content":
int labelStart = response.indexOf("content\":");
// find the first { after "content":
int contentStart = response.indexOf("{", labelStart);
// find the following } and get what's between the braces:
int contentEnd = response.indexOf("}", labelStart);
String content = response.substring(contentStart + 1, contentEnd);
Serial.println(content);
// now get the value after the colon, and convert to an int:
int valueStart = content.indexOf(":");
String valueString = content.substring(valueStart + 1);
int number = valueString.toInt();
Serial.print("Value string: ");
Serial.println(valueString);
Serial.print("Actual value: ");
Serial.println(number);
Serial.println("Wait ten seconds\n");
delay(10000);
}

View File

@ -0,0 +1,3 @@
#define SECRET_SSID ""
#define SECRET_PASS ""

View File

@ -0,0 +1,79 @@
/*
Dweet.io POST client for ArduinoHttpClient library
Connects to dweet.io once every ten seconds,
sends a POST request and a request body.
Shows how to use Strings to assemble path and body
created 15 Feb 2016
modified 22 Jan 2019
by Tom Igoe
this example is in the public domain
*/
#include <ArduinoHttpClient.h>
#include <WiFi101.h>
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
/////// Wifi Settings ///////
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
const char serverAddress[] = "dweet.io"; // server address
int port = 80;
WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
void setup() {
Serial.begin(9600);
while(!Serial);
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
}
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
// assemble the path for the POST message:
String dweetName = "scandalous-cheese-hoarder";
String path = "/dweet/for/" + dweetName;
String contentType = "application/json";
// assemble the body of the POST message:
int sensorValue = analogRead(A0);
String postData = "{\"sensorValue\":\"";
postData += sensorValue;
postData += "\"}";
Serial.println("making POST request");
// send the POST request
client.post(path, contentType, postData);
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
Serial.println("Wait ten seconds\n");
delay(10000);
}

View File

@ -0,0 +1,3 @@
#define SECRET_SSID ""
#define SECRET_PASS ""

View File

@ -0,0 +1,98 @@
/* HueBlink example for ArduinoHttpClient library
Uses ArduinoHttpClient library to control Philips Hue
For more on Hue developer API see http://developer.meethue.com
To control a light, the Hue expects a HTTP PUT request to:
http://hue.hub.address/api/hueUserName/lights/lightNumber/state
The body of the PUT request looks like this:
{"on": true} or {"on":false}
This example shows how to concatenate Strings to assemble the
PUT request and the body of the request.
modified 15 Feb 2016
by Tom Igoe (tigoe) to match new API
*/
#include <SPI.h>
#include <WiFi101.h>
#include <ArduinoHttpClient.h>
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
/////// Wifi Settings ///////
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
int status = WL_IDLE_STATUS; // the Wifi radio's status
char hueHubIP[] = "192.168.0.3"; // IP address of the HUE bridge
String hueUserName = "huebridgeusername"; // hue bridge username
// make a wifi instance and a HttpClient instance:
WiFiClient wifi;
HttpClient httpClient = HttpClient(wifi, hueHubIP);
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial); // wait for serial port to connect.
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
}
// you're connected now, so print out the data:
Serial.print("You're connected to the network IP = ");
IPAddress ip = WiFi.localIP();
Serial.println(ip);
}
void loop() {
sendRequest(3, "on", "true"); // turn light on
delay(2000); // wait 2 seconds
sendRequest(3, "on", "false"); // turn light off
delay(2000); // wait 2 seconds
}
void sendRequest(int light, String cmd, String value) {
// make a String for the HTTP request path:
String request = "/api/" + hueUserName;
request += "/lights/";
request += light;
request += "/state/";
String contentType = "application/json";
// make a string for the JSON command:
String hueCmd = "{\"" + cmd;
hueCmd += "\":";
hueCmd += value;
hueCmd += "}";
// see what you assembled to send:
Serial.print("PUT request to server: ");
Serial.println(request);
Serial.print("JSON command to server: ");
// make the PUT request to the hub:
httpClient.put(request, contentType, hueCmd);
// read the status code and body of the response
int statusCode = httpClient.responseStatusCode();
String response = httpClient.responseBody();
Serial.println(hueCmd);
Serial.print("Status code from server: ");
Serial.println(statusCode);
Serial.print("Server response: ");
Serial.println(response);
Serial.println();
}

View File

@ -0,0 +1,3 @@
#define SECRET_SSID ""
#define SECRET_PASS ""

View File

@ -0,0 +1,77 @@
/*
POST with headers client for ArduinoHttpClient library
Connects to server once every five seconds, sends a POST request
with custome headers and a request body
created 14 Feb 2016
by Tom Igoe
modified 18 Mar 2017
by Sandeep Mistry
modified 22 Jan 2019
by Tom Igoe
this example is in the public domain
*/
#include <ArduinoHttpClient.h>
#include <WiFi101.h>
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
/////// Wifi Settings ///////
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
char serverAddress[] = "192.168.0.3"; // server address
int port = 8080;
WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
void setup() {
Serial.begin(9600);
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
}
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
Serial.println("making POST request");
String postData = "name=Alice&age=12";
client.beginRequest();
client.post("/");
client.sendHeader("Content-Type", "application/x-www-form-urlencoded");
client.sendHeader("Content-Length", postData.length());
client.sendHeader("X-Custom-Header", "custom-header-value");
client.beginBody();
client.print(postData);
client.endRequest();
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
Serial.println("Wait five seconds");
delay(5000);
}

View File

@ -0,0 +1,3 @@
#define SECRET_SSID ""
#define SECRET_PASS ""

View File

@ -0,0 +1,68 @@
/*
Simple DELETE client for ArduinoHttpClient library
Connects to server once every five seconds, sends a DELETE request
and a request body
created 14 Feb 2016
modified 22 Jan 2019
by Tom Igoe
this example is in the public domain
*/
#include <ArduinoHttpClient.h>
#include <WiFi101.h>
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
/////// Wifi Settings ///////
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
char serverAddress[] = "192.168.0.3"; // server address
int port = 8080;
WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
void setup() {
Serial.begin(9600);
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
}
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
Serial.println("making DELETE request");
String contentType = "application/x-www-form-urlencoded";
String delData = "name=light&age=46";
client.del("/", contentType, delData);
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
Serial.println("Wait five seconds");
delay(5000);
}

View File

@ -0,0 +1,3 @@
#define SECRET_SSID ""
#define SECRET_PASS ""

View File

@ -0,0 +1,62 @@
/*
Simple GET client for ArduinoHttpClient library
Connects to server once every five seconds, sends a GET request
created 14 Feb 2016
modified 22 Jan 2019
by Tom Igoe
this example is in the public domain
*/
#include <ArduinoHttpClient.h>
#include <WiFi101.h>
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
/////// Wifi Settings ///////
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
char serverAddress[] = "192.168.0.3"; // server address
int port = 8080;
WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
void setup() {
Serial.begin(9600);
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
}
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
Serial.println("making GET request");
client.get("/");
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
Serial.println("Wait five seconds");
delay(5000);
}

View File

@ -0,0 +1,3 @@
#define SECRET_SSID ""
#define SECRET_PASS ""

View File

@ -0,0 +1,133 @@
// (c) Copyright 2010-2012 MCQN Ltd.
// Released under Apache License, version 2.0
//
// Simple example to show how to use the HttpClient library
// Get's the web page given at http://<kHostname><kPath> and
// outputs the content to the serial port
#include <SPI.h>
#include <WiFi101.h>
#include <ArduinoHttpClient.h>
// This example downloads the URL "http://arduino.cc/"
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
/////// Wifi Settings ///////
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
// Name of the server we want to connect to
const char kHostname[] = "arduino.cc";
// Path to download (this is the bit after the hostname in the URL
// that you want to download
const char kPath[] = "/";
// Number of milliseconds to wait without receiving any data before we give up
const int kNetworkTimeout = 30*1000;
// Number of milliseconds to wait if no data is available before trying again
const int kNetworkDelay = 1000;
WiFiClient c;
HttpClient http(c, kHostname);
void setup()
{
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// attempt to connect to Wifi network:
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
// unsuccessful, retry in 4 seconds
Serial.print("failed ... ");
delay(4000);
Serial.print("retrying ... ");
}
Serial.println("connected");
}
void loop()
{
int err =0;
err = http.get(kPath);
if (err == 0)
{
Serial.println("startedRequest ok");
err = http.responseStatusCode();
if (err >= 0)
{
Serial.print("Got status code: ");
Serial.println(err);
// Usually you'd check that the response code is 200 or a
// similar "success" code (200-299) before carrying on,
// but we'll print out whatever response we get
// If you are interesting in the response headers, you
// can read them here:
//while(http.headerAvailable())
//{
// String headerName = http.readHeaderName();
// String headerValue = http.readHeaderValue();
//}
int bodyLen = http.contentLength();
Serial.print("Content length is: ");
Serial.println(bodyLen);
Serial.println();
Serial.println("Body returned follows:");
// Now we've got to the body, so we can print it out
unsigned long timeoutStart = millis();
char c;
// Whilst we haven't timed out & haven't reached the end of the body
while ( (http.connected() || http.available()) &&
(!http.endOfBodyReached()) &&
((millis() - timeoutStart) < kNetworkTimeout) )
{
if (http.available())
{
c = http.read();
// Print out this character
Serial.print(c);
// We read something, reset the timeout counter
timeoutStart = millis();
}
else
{
// We haven't got any data, so let's pause to allow some to
// arrive
delay(kNetworkDelay);
}
}
}
else
{
Serial.print("Getting response failed: ");
Serial.println(err);
}
}
else
{
Serial.print("Connect failed: ");
Serial.println(err);
}
http.stop();
// And just stop, now that we've tried a download
while(1);
}

View File

@ -0,0 +1,3 @@
#define SECRET_SSID ""
#define SECRET_PASS ""

View File

@ -0,0 +1,66 @@
/*
Simple POST client for ArduinoHttpClient library
Connects to server once every five seconds, sends a POST request
and a request body
created 14 Feb 2016
modified 22 Jan 2019
by Tom Igoe
this example is in the public domain
*/
#include <ArduinoHttpClient.h>
#include <WiFi101.h>
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
/////// Wifi Settings ///////
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
char serverAddress[] = "192.168.0.3"; // server address
int port = 8080;
WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
void setup() {
Serial.begin(9600);
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
}
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
Serial.println("making POST request");
String contentType = "application/x-www-form-urlencoded";
String postData = "name=Alice&age=12";
client.post("/", contentType, postData);
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
Serial.println("Wait five seconds");
delay(5000);
}

View File

@ -0,0 +1,3 @@
#define SECRET_SSID ""
#define SECRET_PASS ""

View File

@ -0,0 +1,66 @@
/*
Simple PUT client for ArduinoHttpClient library
Connects to server once every five seconds, sends a PUT request
and a request body
created 14 Feb 2016
modified 22 Jan 2019
by Tom Igoe
this example is in the public domain
*/
#include <ArduinoHttpClient.h>
#include <WiFi101.h>
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
/////// Wifi Settings ///////
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
char serverAddress[] = "192.168.0.3"; // server address
int port = 8080;
WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
void setup() {
Serial.begin(9600);
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
}
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
Serial.println("making PUT request");
String contentType = "application/x-www-form-urlencoded";
String putData = "name=light&age=46";
client.put("/", contentType, putData);
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
Serial.println("Wait five seconds");
delay(5000);
}

View File

@ -0,0 +1,3 @@
#define SECRET_SSID ""
#define SECRET_PASS ""

View File

@ -0,0 +1,80 @@
/*
Simple WebSocket client for ArduinoHttpClient library
Connects to the WebSocket server, and sends a hello
message every 5 seconds
created 28 Jun 2016
by Sandeep Mistry
modified 22 Jan 2019
by Tom Igoe
this example is in the public domain
*/
#include <ArduinoHttpClient.h>
#include <WiFi101.h>
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
/////// Wifi Settings ///////
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
char serverAddress[] = "echo.websocket.org"; // server address
int port = 80;
WiFiClient wifi;
WebSocketClient client = WebSocketClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
int count = 0;
void setup() {
Serial.begin(9600);
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
}
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
Serial.println("starting WebSocket client");
client.begin();
while (client.connected()) {
Serial.print("Sending hello ");
Serial.println(count);
// send a hello #
client.beginMessage(TYPE_TEXT);
client.print("hello ");
client.print(count);
client.endMessage();
// increment count for next message
count++;
// check if a message is available to be received
int messageSize = client.parseMessage();
if (messageSize > 0) {
Serial.println("Received a message:");
Serial.println(client.readString());
}
// wait 5 seconds
delay(5000);
}
Serial.println("disconnected");
}

View File

@ -0,0 +1,3 @@
#define SECRET_SSID ""
#define SECRET_PASS ""

View File

@ -0,0 +1,13 @@
{
"name": "node_test_server",
"version": "0.0.1",
"author": {
"name": "Tom Igoe"
},
"dependencies": {
"body-parser": ">=1.11.0",
"express": ">=4.0.0",
"multer": "*",
"ws": "^1.1.1"
}
}

View File

@ -0,0 +1,67 @@
#######################################
# Syntax Coloring Map For HttpClient
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
ArduinoHttpClient KEYWORD1
HttpClient KEYWORD1
WebSocketClient KEYWORD1
URLEncoder KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
get KEYWORD2
post KEYWORD2
put KEYWORD2
patch KEYWORD2
startRequest KEYWORD2
beginRequest KEYWORD2
beginBody KEYWORD2
sendHeader KEYWORD2
sendBasicAuth KEYWORD2
endRequest KEYWORD2
responseStatusCode KEYWORD2
readHeader KEYWORD2
skipResponseHeaders KEYWORD2
endOfHeadersReached KEYWORD2
endOfBodyReached KEYWORD2
completed KEYWORD2
contentLength KEYWORD2
isResponseChunked KEYWORD2
connectionKeepAlive KEYWORD2
noDefaultRequestHeaders KEYWORD2
headerAvailable KEYWORD2
readHeaderName KEYWORD2
readHeaderValue KEYWORD2
responseBody KEYWORD2
beginMessage KEYWORD2
endMessage KEYWORD2
parseMessage KEYWORD2
messageType KEYWORD2
isFinal KEYWORD2
readString KEYWORD2
ping KEYWORD2
encode KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
HTTP_SUCCESS LITERAL1
HTTP_ERROR_CONNECTION_FAILED LITERAL1
HTTP_ERROR_API LITERAL1
HTTP_ERROR_TIMED_OUT LITERAL1
HTTP_ERROR_INVALID_RESPONSE LITERAL1
TYPE_CONTINUATION LITERAL1
TYPE_TEXT LITERAL1
TYPE_BINARY LITERAL1
TYPE_CONNECTION_CLOSE LITERAL1
TYPE_PING LITERAL1
TYPE_PONG LITERAL1

View File

@ -0,0 +1,12 @@
{
"name": "ArduinoHttpClient",
"keywords": "http, web, client, ethernet, wifi, GSM",
"description": "Easily interact with web servers from Arduino, using HTTP and WebSocket's.",
"repository": {
"type": "git",
"url": "https://github.com/arduino-libraries/ArduinoHttpClient.git"
},
"frameworks": "arduino",
"platforms": "*",
"version": "0.4.0"
}

View File

@ -0,0 +1,10 @@
name=ArduinoHttpClient
version=0.4.0
author=Arduino
maintainer=Arduino <info@arduino.cc>
sentence=[EXPERIMENTAL] Easily interact with web servers from Arduino, using HTTP and WebSocket's.
paragraph=This library can be used for HTTP (GET, POST, PUT, DELETE) requests to a web server. It also supports exchanging messages with WebSocket servers. Based on Adrian McEwen's HttpClient library.
category=Communication
url=https://github.com/arduino-libraries/ArduinoHttpClient
architectures=*
includes=ArduinoHttpClient.h

View File

@ -0,0 +1,12 @@
// Library to simplify HTTP fetching on Arduino
// (c) Copyright Arduino. 2016
// Released under Apache License, version 2.0
#ifndef ArduinoHttpClient_h
#define ArduinoHttpClient_h
#include "HttpClient.h"
#include "WebSocketClient.h"
#include "URLEncoder.h"
#endif

View File

@ -0,0 +1,867 @@
// Class to simplify HTTP fetching on Arduino
// (c) Copyright 2010-2011 MCQN Ltd
// Released under Apache License, version 2.0
#include "HttpClient.h"
#include "b64.h"
#define LOGGING
// Initialize constants
const char* HttpClient::kUserAgent = "Arduino/2.2.0";
const char* HttpClient::kContentLengthPrefix = HTTP_HEADER_CONTENT_LENGTH ": ";
const char* HttpClient::kTransferEncodingChunked = HTTP_HEADER_TRANSFER_ENCODING ": " HTTP_HEADER_VALUE_CHUNKED;
HttpClient::HttpClient(Client& aClient, const char* aServerName, uint16_t aServerPort)
: iClient(&aClient), iServerName(aServerName), iServerAddress(), iServerPort(aServerPort),
iConnectionClose(true), iSendDefaultRequestHeaders(true)
{
Serial.println("aaaa"+String(iServerName));
resetState();
Serial.println("aaaa"+String(iServerName));
}
HttpClient::HttpClient(Client& aClient, const String& aServerName, uint16_t aServerPort)
: HttpClient(aClient, aServerName.c_str(), aServerPort)
{
}
HttpClient::HttpClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort)
: iClient(&aClient), iServerName(NULL), iServerAddress(aServerAddress), iServerPort(aServerPort),
iConnectionClose(true), iSendDefaultRequestHeaders(true)
{
resetState();
}
void HttpClient::resetState()
{
iState = eIdle;
iStatusCode = 0;
iContentLength = kNoContentLengthHeader;
iBodyLengthConsumed = 0;
iContentLengthPtr = kContentLengthPrefix;
iTransferEncodingChunkedPtr = kTransferEncodingChunked;
iIsChunked = false;
iChunkLength = 0;
iHttpResponseTimeout = kHttpResponseTimeout;
}
void HttpClient::stop()
{
iClient->stop();
resetState();
}
void HttpClient::connectionKeepAlive()
{
iConnectionClose = false;
}
void HttpClient::noDefaultRequestHeaders()
{
iSendDefaultRequestHeaders = false;
}
void HttpClient::beginRequest()
{
iState = eRequestStarted;
}
int HttpClient::startRequest(const char* aURLPath, const char* aHttpMethod,
const char* aContentType, int aContentLength, const byte aBody[])
{
// iServerName="82.156.1.111";
if (iState == eReadingBody || iState == eReadingChunkLength || iState == eReadingBodyChunk)
{
flushClientRx();
resetState();
}
//Serial.println("here !");
tHttpState initialState = iState;
if ((eIdle != iState) && (eRequestStarted != iState))
{
return HTTP_ERROR_API;
}
//Serial.println("here !!");
if (iConnectionClose || !iClient->connected())
{
if (iServerName)
{
if (!iClient->connect(iServerName, iServerPort) > 0)
{
#ifdef LOGGING
Serial.println("Connection failed"+String(iServerName)+":"+String(iServerPort)+String(aURLPath));
#endif
return HTTP_ERROR_CONNECTION_FAILED;
}
}
else
{
if (!iClient->connect(iServerAddress, iServerPort) > 0)
{
#ifdef LOGGING
Serial.println("Connection failed"+String(iServerName)+":"+String(iServerPort)+String(aURLPath));
#endif
return HTTP_ERROR_CONNECTION_FAILED;
}
}
}
else
{
#ifdef LOGGING
Serial.println("Connection already open");
#endif
}
// Now we're connected, send the first part of the request
int ret = sendInitialHeaders(aURLPath, aHttpMethod);
if (HTTP_SUCCESS == ret)
{
if (aContentType)
{
sendHeader(HTTP_HEADER_CONTENT_TYPE, aContentType);
}
if (aContentLength > 0)
{
sendHeader(HTTP_HEADER_CONTENT_LENGTH, aContentLength);
}
bool hasBody = (aBody && aContentLength > 0);
if (initialState == eIdle || hasBody)
{
// This was a simple version of the API, so terminate the headers now
finishHeaders();
}
// else we'll call it in endRequest or in the first call to print, etc.
if (hasBody)
{
write(aBody, aContentLength);
}
}
return ret;
}
int HttpClient::sendInitialHeaders(const char* aURLPath, const char* aHttpMethod)
{
#ifdef LOGGING
Serial.println("Connected");
#endif
// Send the HTTP command, i.e. "GET /somepath/ HTTP/1.0"
iClient->print(aHttpMethod);
iClient->print(" ");
iClient->print(aURLPath);
iClient->println(" HTTP/1.1");
if (iSendDefaultRequestHeaders)
{
// The host header, if required
if (iServerName)
{
iClient->print("Host: ");
iClient->print(iServerName);
if (iServerPort != kHttpPort)
{
iClient->print(":");
iClient->print(iServerPort);
}
iClient->println();
}
// And user-agent string
sendHeader(HTTP_HEADER_USER_AGENT, kUserAgent);
}
if (iConnectionClose)
{
// Tell the server to
// close this connection after we're done
sendHeader(HTTP_HEADER_CONNECTION, "close");
}
// Everything has gone well
iState = eRequestStarted;
return HTTP_SUCCESS;
}
void HttpClient::sendHeader(const char* aHeader)
{
iClient->println(aHeader);
}
void HttpClient::sendHeader(const char* aHeaderName, const char* aHeaderValue)
{
iClient->print(aHeaderName);
iClient->print(": ");
iClient->println(aHeaderValue);
}
void HttpClient::sendHeader(const char* aHeaderName, const int aHeaderValue)
{
iClient->print(aHeaderName);
iClient->print(": ");
iClient->println(aHeaderValue);
}
void HttpClient::sendBasicAuth(const char* aUser, const char* aPassword)
{
// Send the initial part of this header line
iClient->print("Authorization: Basic ");
// Now Base64 encode "aUser:aPassword" and send that
// This seems trickier than it should be but it's mostly to avoid either
// (a) some arbitrarily sized buffer which hopes to be big enough, or
// (b) allocating and freeing memory
// ...so we'll loop through 3 bytes at a time, outputting the results as we
// go.
// In Base64, each 3 bytes of unencoded data become 4 bytes of encoded data
unsigned char input[3];
unsigned char output[5]; // Leave space for a '\0' terminator so we can easily print
int userLen = strlen(aUser);
int passwordLen = strlen(aPassword);
int inputOffset = 0;
for (int i = 0; i < (userLen+1+passwordLen); i++)
{
// Copy the relevant input byte into the input
if (i < userLen)
{
input[inputOffset++] = aUser[i];
}
else if (i == userLen)
{
input[inputOffset++] = ':';
}
else
{
input[inputOffset++] = aPassword[i-(userLen+1)];
}
// See if we've got a chunk to encode
if ( (inputOffset == 3) || (i == userLen+passwordLen) )
{
// We've either got to a 3-byte boundary, or we've reached then end
b64_encode(input, inputOffset, output, 4);
// NUL-terminate the output string
output[4] = '\0';
// And write it out
iClient->print((char*)output);
// FIXME We might want to fill output with '=' characters if b64_encode doesn't
// FIXME do it for us when we're encoding the final chunk
inputOffset = 0;
}
}
// And end the header we've sent
iClient->println();
}
void HttpClient::finishHeaders()
{
iClient->println();
iState = eRequestSent;
}
void HttpClient::flushClientRx()
{
while (iClient->available())
{
iClient->read();
}
}
void HttpClient::endRequest()
{
beginBody();
}
void HttpClient::beginBody()
{
if (iState < eRequestSent)
{
// We still need to finish off the headers
finishHeaders();
}
// else the end of headers has already been sent, so nothing to do here
}
int HttpClient::get(const char* aURLPath)
{
return startRequest(aURLPath, HTTP_METHOD_GET);
}
int HttpClient::get(const String& aURLPath)
{
return get(aURLPath.c_str());
}
int HttpClient::post(const char* aURLPath)
{
return startRequest(aURLPath, HTTP_METHOD_POST);
}
int HttpClient::post(const String& aURLPath)
{
return post(aURLPath.c_str());
}
int HttpClient::post(const char* aURLPath, const char* aContentType, const char* aBody)
{
return post(aURLPath, aContentType, strlen(aBody), (const byte*)aBody);
}
int HttpClient::post(const String& aURLPath, const String& aContentType, const String& aBody)
{
return post(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str());
}
int HttpClient::post(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[])
{
return startRequest(aURLPath, HTTP_METHOD_POST, aContentType, aContentLength, aBody);
}
int HttpClient::put(const char* aURLPath)
{
return startRequest(aURLPath, HTTP_METHOD_PUT);
}
int HttpClient::put(const String& aURLPath)
{
return put(aURLPath.c_str());
}
int HttpClient::put(const char* aURLPath, const char* aContentType, const char* aBody)
{
return put(aURLPath, aContentType, strlen(aBody), (const byte*)aBody);
}
int HttpClient::put(const String& aURLPath, const String& aContentType, const String& aBody)
{
return put(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str());
}
int HttpClient::put(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[])
{
return startRequest(aURLPath, HTTP_METHOD_PUT, aContentType, aContentLength, aBody);
}
int HttpClient::patch(const char* aURLPath)
{
return startRequest(aURLPath, HTTP_METHOD_PATCH);
}
int HttpClient::patch(const String& aURLPath)
{
return patch(aURLPath.c_str());
}
int HttpClient::patch(const char* aURLPath, const char* aContentType, const char* aBody)
{
return patch(aURLPath, aContentType, strlen(aBody), (const byte*)aBody);
}
int HttpClient::patch(const String& aURLPath, const String& aContentType, const String& aBody)
{
return patch(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str());
}
int HttpClient::patch(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[])
{
return startRequest(aURLPath, HTTP_METHOD_PATCH, aContentType, aContentLength, aBody);
}
int HttpClient::del(const char* aURLPath)
{
return startRequest(aURLPath, HTTP_METHOD_DELETE);
}
int HttpClient::del(const String& aURLPath)
{
return del(aURLPath.c_str());
}
int HttpClient::del(const char* aURLPath, const char* aContentType, const char* aBody)
{
return del(aURLPath, aContentType, strlen(aBody), (const byte*)aBody);
}
int HttpClient::del(const String& aURLPath, const String& aContentType, const String& aBody)
{
return del(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str());
}
int HttpClient::del(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[])
{
return startRequest(aURLPath, HTTP_METHOD_DELETE, aContentType, aContentLength, aBody);
}
int HttpClient::responseStatusCode()
{
if (iState < eRequestSent)
{
return HTTP_ERROR_API;
}
// The first line will be of the form Status-Line:
// HTTP-Version SP Status-Code SP Reason-Phrase CRLF
// Where HTTP-Version is of the form:
// HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT
int c = '\0';
do
{
// Make sure the status code is reset, and likewise the state. This
// lets us easily cope with 1xx informational responses by just
// ignoring them really, and reading the next line for a proper response
iStatusCode = 0;
iState = eRequestSent;
unsigned long timeoutStart = millis();
// Psuedo-regexp we're expecting before the status-code
const char* statusPrefix = "HTTP/*.* ";
const char* statusPtr = statusPrefix;
// Whilst we haven't timed out & haven't reached the end of the headers
while ((c != '\n') &&
( (millis() - timeoutStart) < iHttpResponseTimeout ))
{
if (available())
{
c = read();
if (c != -1)
{
switch(iState)
{
case eRequestSent:
// We haven't reached the status code yet
if ( (*statusPtr == '*') || (*statusPtr == c) )
{
// This character matches, just move along
statusPtr++;
if (*statusPtr == '\0')
{
// We've reached the end of the prefix
iState = eReadingStatusCode;
}
}
else
{
return HTTP_ERROR_INVALID_RESPONSE;
}
break;
case eReadingStatusCode:
if (isdigit(c))
{
// This assumes we won't get more than the 3 digits we
// want
iStatusCode = iStatusCode*10 + (c - '0');
}
else
{
// We've reached the end of the status code
// We could sanity check it here or double-check for ' '
// rather than anything else, but let's be lenient
iState = eStatusCodeRead;
}
break;
case eStatusCodeRead:
// We're just waiting for the end of the line now
break;
default:
break;
};
// We read something, reset the timeout counter
timeoutStart = millis();
}
}
else
{
// We haven't got any data, so let's pause to allow some to
// arrive
delay(kHttpWaitForDataDelay);
}
}
if ( (c == '\n') && (iStatusCode < 200 && iStatusCode != 101) )
{
// We've reached the end of an informational status line
c = '\0'; // Clear c so we'll go back into the data reading loop
}
}
// If we've read a status code successfully but it's informational (1xx)
// loop back to the start
while ( (iState == eStatusCodeRead) && (iStatusCode < 200 && iStatusCode != 101) );
if ( (c == '\n') && (iState == eStatusCodeRead) )
{
// We've read the status-line successfully
return iStatusCode;
}
else if (c != '\n')
{
// We must've timed out before we reached the end of the line
return HTTP_ERROR_TIMED_OUT;
}
else
{
// This wasn't a properly formed status line, or at least not one we
// could understand
return HTTP_ERROR_INVALID_RESPONSE;
}
}
int HttpClient::skipResponseHeaders()
{
// Just keep reading until we finish reading the headers or time out
unsigned long timeoutStart = millis();
// Whilst we haven't timed out & haven't reached the end of the headers
while ((!endOfHeadersReached()) &&
( (millis() - timeoutStart) < iHttpResponseTimeout ))
{
if (available())
{
(void)readHeader();
// We read something, reset the timeout counter
timeoutStart = millis();
}
else
{
// We haven't got any data, so let's pause to allow some to
// arrive
delay(kHttpWaitForDataDelay);
}
}
if (endOfHeadersReached())
{
// Success
return HTTP_SUCCESS;
}
else
{
// We must've timed out
return HTTP_ERROR_TIMED_OUT;
}
}
bool HttpClient::endOfHeadersReached()
{
return (iState == eReadingBody || iState == eReadingChunkLength || iState == eReadingBodyChunk);
};
int HttpClient::contentLength()
{
// skip the response headers, if they haven't been read already
if (!endOfHeadersReached())
{
skipResponseHeaders();
}
return iContentLength;
}
String HttpClient::responseBody()
{
int bodyLength = contentLength();
String response;
if (bodyLength > 0)
{
// try to reserve bodyLength bytes
if (response.reserve(bodyLength) == 0) {
// String reserve failed
return String((const char*)NULL);
}
}
// keep on timedRead'ing, until:
// - we have a content length: body length equals consumed or no bytes
// available
// - no content length: no bytes are available
while (iBodyLengthConsumed != bodyLength)
{
int c = timedRead();
if (c == -1) {
// read timed out, done
break;
}
if (!response.concat((char)c)) {
// adding char failed
return String((const char*)NULL);
}
}
if (bodyLength > 0 && (unsigned int)bodyLength != response.length()) {
// failure, we did not read in reponse content length bytes
return String((const char*)NULL);
}
return response;
}
bool HttpClient::endOfBodyReached()
{
if (endOfHeadersReached() && (contentLength() != kNoContentLengthHeader))
{
// We've got to the body and we know how long it will be
return (iBodyLengthConsumed >= contentLength());
}
return false;
}
int HttpClient::available()
{
if (iState == eReadingChunkLength)
{
while (iClient->available())
{
char c = iClient->read();
if (c == '\n')
{
iState = eReadingBodyChunk;
break;
}
else if (c == '\r')
{
// no-op
}
else if (isHexadecimalDigit(c))
{
char digit[2] = {c, '\0'};
iChunkLength = (iChunkLength * 16) + strtol(digit, NULL, 16);
}
}
}
if (iState == eReadingBodyChunk && iChunkLength == 0)
{
iState = eReadingChunkLength;
}
if (iState == eReadingChunkLength)
{
return 0;
}
int clientAvailable = iClient->available();
if (iState == eReadingBodyChunk)
{
return min(clientAvailable, iChunkLength);
}
else
{
return clientAvailable;
}
}
int HttpClient::read()
{
if (iIsChunked && !available())
{
return -1;
}
int ret = iClient->read();
if (ret >= 0)
{
if (endOfHeadersReached() && iContentLength > 0)
{
// We're outputting the body now and we've seen a Content-Length header
// So keep track of how many bytes are left
iBodyLengthConsumed++;
}
if (iState == eReadingBodyChunk)
{
iChunkLength--;
if (iChunkLength == 0)
{
iState = eReadingChunkLength;
}
}
}
return ret;
}
bool HttpClient::headerAvailable()
{
// clear the currently store header line
iHeaderLine = "";
int i = 0;
while (!endOfHeadersReached())
{
// read a byte from the header
int c = readHeader();
if (c == '\r' || c == '\n'||c==-1)
{
if (iHeaderLine.length())
{
// end of the line, all done
break;
}
else
{
// ignore any CR or LF characters
continue;
}
}
// append byte to header line
iHeaderLine += (char)c;
i++;
if(i>20000) return true;
}
return (iHeaderLine.length() > 0);
}
String HttpClient::readHeaderName()
{
int colonIndex = iHeaderLine.indexOf(':');
if (colonIndex == -1)
{
return "";
}
return iHeaderLine.substring(0, colonIndex);
}
String HttpClient::readHeaderValue()
{
int colonIndex = iHeaderLine.indexOf(':');
int startIndex = colonIndex + 1;
if (colonIndex == -1)
{
return "";
}
// trim any leading whitespace
while (startIndex < (int)iHeaderLine.length() && isSpace(iHeaderLine[startIndex]))
{
startIndex++;
}
return iHeaderLine.substring(startIndex);
}
int HttpClient::read(uint8_t *buf, size_t size)
{
int ret =iClient->read(buf, size);
if (endOfHeadersReached() && iContentLength > 0)
{
// We're outputting the body now and we've seen a Content-Length header
// So keep track of how many bytes are left
if (ret >= 0)
{
iBodyLengthConsumed += ret;
}
}
return ret;
}
int HttpClient::readHeader()
{
char c = read();
if (endOfHeadersReached())
{
// We've passed the headers, but rather than return an error, we'll just
// act as a slightly less efficient version of read()
return c;
}
// Whilst reading out the headers to whoever wants them, we'll keep an
// eye out for the "Content-Length" header
switch(iState)
{
case eStatusCodeRead:
// We're at the start of a line, or somewhere in the middle of reading
// the Content-Length prefix
if (*iContentLengthPtr == c)
{
// This character matches, just move along
iContentLengthPtr++;
if (*iContentLengthPtr == '\0')
{
// We've reached the end of the prefix
iState = eReadingContentLength;
// Just in case we get multiple Content-Length headers, this
// will ensure we just get the value of the last one
iContentLength = 0;
iBodyLengthConsumed = 0;
}
}
else if (*iTransferEncodingChunkedPtr == c)
{
// This character matches, just move along
iTransferEncodingChunkedPtr++;
if (*iTransferEncodingChunkedPtr == '\0')
{
// We've reached the end of the Transfer Encoding: chunked header
iIsChunked = true;
iState = eSkipToEndOfHeader;
}
}
else if (((iContentLengthPtr == kContentLengthPrefix) && (iTransferEncodingChunkedPtr == kTransferEncodingChunked)) && (c == '\r'))
{
// We've found a '\r' at the start of a line, so this is probably
// the end of the headers
iState = eLineStartingCRFound;
}
else
{
// This isn't the Content-Length or Transfer Encoding chunked header, skip to the end of the line
iState = eSkipToEndOfHeader;
}
break;
case eReadingContentLength:
if (isdigit(c))
{
iContentLength = iContentLength*10 + (c - '0');
}
else
{
// We've reached the end of the content length
// We could sanity check it here or double-check for "\r\n"
// rather than anything else, but let's be lenient
iState = eSkipToEndOfHeader;
}
break;
case eLineStartingCRFound:
if (c == '\n')
{
if (iIsChunked)
{
iState = eReadingChunkLength;
iChunkLength = 0;
}
else
{
iState = eReadingBody;
}
}
break;
default:
// We're just waiting for the end of the line now
break;
};
if ( (c == '\n') && !endOfHeadersReached() )
{
// We've got to the end of this line, start processing again
iState = eStatusCodeRead;
iContentLengthPtr = kContentLengthPrefix;
iTransferEncodingChunkedPtr = kTransferEncodingChunked;
}
// And return the character read to whoever wants it
return c;
}

View File

@ -0,0 +1,392 @@
// Class to simplify HTTP fetching on Arduino
// (c) Copyright MCQN Ltd. 2010-2012
// Released under Apache License, version 2.0
#ifndef HttpClient_h
#define HttpClient_h
#include <Arduino.h>
#include <IPAddress.h>
#include "Client.h"
static const int HTTP_SUCCESS =0;
// The end of the headers has been reached. This consumes the '\n'
// Could not connect to the server
static const int HTTP_ERROR_CONNECTION_FAILED =-1;
// This call was made when the HttpClient class wasn't expecting it
// to be called. Usually indicates your code is using the class
// incorrectly
static const int HTTP_ERROR_API =-2;
// Spent too long waiting for a reply
static const int HTTP_ERROR_TIMED_OUT =-3;
// The response from the server is invalid, is it definitely an HTTP
// server?
static const int HTTP_ERROR_INVALID_RESPONSE =-4;
// Define some of the common methods and headers here
// That lets other code reuse them without having to declare another copy
// of them, so saves code space and RAM
#define HTTP_METHOD_GET "GET"
#define HTTP_METHOD_POST "POST"
#define HTTP_METHOD_PUT "PUT"
#define HTTP_METHOD_PATCH "PATCH"
#define HTTP_METHOD_DELETE "DELETE"
#define HTTP_HEADER_CONTENT_LENGTH "Content-Length"
#define HTTP_HEADER_CONTENT_TYPE "Content-Type"
#define HTTP_HEADER_CONNECTION "Connection"
#define HTTP_HEADER_TRANSFER_ENCODING "Transfer-Encoding"
#define HTTP_HEADER_USER_AGENT "User-Agent"
#define HTTP_HEADER_VALUE_CHUNKED "chunked"
class HttpClient : public Client
{
public:
static const int kNoContentLengthHeader =-1;
static const int kHttpPort =80;
static const char* kUserAgent;
// FIXME Write longer API request, using port and user-agent, example
// FIXME Update tempToPachube example to calculate Content-Length correctly
HttpClient(Client& aClient, const char* aServerName, uint16_t aServerPort = kHttpPort);
HttpClient(Client& aClient, const String& aServerName, uint16_t aServerPort = kHttpPort);
HttpClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort = kHttpPort);
/** Start a more complex request.
Use this when you need to send additional headers in the request,
but you will also need to call endRequest() when you are finished.
*/
void beginRequest();
/** End a more complex request.
Use this when you need to have sent additional headers in the request,
but you will also need to call beginRequest() at the start.
*/
void endRequest();
/** Start the body of a more complex request.
Use this when you need to send the body after additional headers
in the request, but can optionally call endRequest() when
you are finished.
*/
void beginBody();
/** Connect to the server and start to send a GET request.
@param aURLPath Url to request
@return 0 if successful, else error
*/
int get(const char* aURLPath);
int get(const String& aURLPath);
/** Connect to the server and start to send a POST request.
@param aURLPath Url to request
@return 0 if successful, else error
*/
int post(const char* aURLPath);
int post(const String& aURLPath);
/** Connect to the server and send a POST request
with body and content type
@param aURLPath Url to request
@param aContentType Content type of request body
@param aBody Body of the request
@return 0 if successful, else error
*/
int post(const char* aURLPath, const char* aContentType, const char* aBody);
int post(const String& aURLPath, const String& aContentType, const String& aBody);
int post(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]);
/** Connect to the server and start to send a PUT request.
@param aURLPath Url to request
@return 0 if successful, else error
*/
int put(const char* aURLPath);
int put(const String& aURLPath);
/** Connect to the server and send a PUT request
with body and content type
@param aURLPath Url to request
@param aContentType Content type of request body
@param aBody Body of the request
@return 0 if successful, else error
*/
int put(const char* aURLPath, const char* aContentType, const char* aBody);
int put(const String& aURLPath, const String& aContentType, const String& aBody);
int put(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]);
/** Connect to the server and start to send a PATCH request.
@param aURLPath Url to request
@return 0 if successful, else error
*/
int patch(const char* aURLPath);
int patch(const String& aURLPath);
/** Connect to the server and send a PATCH request
with body and content type
@param aURLPath Url to request
@param aContentType Content type of request body
@param aBody Body of the request
@return 0 if successful, else error
*/
int patch(const char* aURLPath, const char* aContentType, const char* aBody);
int patch(const String& aURLPath, const String& aContentType, const String& aBody);
int patch(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]);
/** Connect to the server and start to send a DELETE request.
@param aURLPath Url to request
@return 0 if successful, else error
*/
int del(const char* aURLPath);
int del(const String& aURLPath);
/** Connect to the server and send a DELETE request
with body and content type
@param aURLPath Url to request
@param aContentType Content type of request body
@param aBody Body of the request
@return 0 if successful, else error
*/
int del(const char* aURLPath, const char* aContentType, const char* aBody);
int del(const String& aURLPath, const String& aContentType, const String& aBody);
int del(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]);
/** Connect to the server and start to send the request.
If a body is provided, the entire request (including headers and body) will be sent
@param aURLPath Url to request
@param aHttpMethod Type of HTTP request to make, e.g. "GET", "POST", etc.
@param aContentType Content type of request body (optional)
@param aContentLength Length of request body (optional)
@param aBody Body of request (optional)
@return 0 if successful, else error
*/
int startRequest(const char* aURLPath,
const char* aHttpMethod,
const char* aContentType = NULL,
int aContentLength = -1,
const byte aBody[] = NULL);
/** Send an additional header line. This can only be called in between the
calls to beginRequest and endRequest.
@param aHeader Header line to send, in its entirety (but without the
trailing CRLF. E.g. "Authorization: Basic YQDDCAIGES"
*/
void sendHeader(const char* aHeader);
void sendHeader(const String& aHeader)
{ sendHeader(aHeader.c_str()); }
/** Send an additional header line. This is an alternate form of
sendHeader() which takes the header name and content as separate strings.
The call will add the ": " to separate the header, so for example, to
send a XXXXXX header call sendHeader("XXXXX", "Something")
@param aHeaderName Type of header being sent
@param aHeaderValue Value for that header
*/
void sendHeader(const char* aHeaderName, const char* aHeaderValue);
void sendHeader(const String& aHeaderName, const String& aHeaderValue)
{ sendHeader(aHeaderName.c_str(), aHeaderValue.c_str()); }
/** Send an additional header line. This is an alternate form of
sendHeader() which takes the header name and content separately but where
the value is provided as an integer.
The call will add the ": " to separate the header, so for example, to
send a XXXXXX header call sendHeader("XXXXX", 123)
@param aHeaderName Type of header being sent
@param aHeaderValue Value for that header
*/
void sendHeader(const char* aHeaderName, const int aHeaderValue);
void sendHeader(const String& aHeaderName, const int aHeaderValue)
{ sendHeader(aHeaderName.c_str(), aHeaderValue); }
/** Send a basic authentication header. This will encode the given username
and password, and send them in suitable header line for doing Basic
Authentication.
@param aUser Username for the authorization
@param aPassword Password for the user aUser
*/
void sendBasicAuth(const char* aUser, const char* aPassword);
void sendBasicAuth(const String& aUser, const String& aPassword)
{ sendBasicAuth(aUser.c_str(), aPassword.c_str()); }
/** Get the HTTP status code contained in the response.
For example, 200 for successful request, 404 for file not found, etc.
*/
int responseStatusCode();
/** Check if a header is available to be read.
Use readHeaderName() to read header name, and readHeaderValue() to
read the header value
MUST be called after responseStatusCode() and before contentLength()
*/
bool headerAvailable();
/** Read the name of the current response header.
Returns empty string if a header is not available.
*/
String readHeaderName();
/** Read the vallue of the current response header.
Returns empty string if a header is not available.
*/
String readHeaderValue();
/** Read the next character of the response headers.
This functions in the same way as read() but to be used when reading
through the headers. Check whether or not the end of the headers has
been reached by calling endOfHeadersReached(), although after that point
this will still return data as read() would, but slightly less efficiently
MUST be called after responseStatusCode() and before contentLength()
@return The next character of the response headers
*/
int readHeader();
/** Skip any response headers to get to the body.
Use this if you don't want to do any special processing of the headers
returned in the response. You can also use it after you've found all of
the headers you're interested in, and just want to get on with processing
the body.
MUST be called after responseStatusCode()
@return HTTP_SUCCESS if successful, else an error code
*/
int skipResponseHeaders();
/** Test whether all of the response headers have been consumed.
@return true if we are now processing the response body, else false
*/
bool endOfHeadersReached();
/** Test whether the end of the body has been reached.
Only works if the Content-Length header was returned by the server
@return true if we are now at the end of the body, else false
*/
bool endOfBodyReached();
virtual bool endOfStream() { return endOfBodyReached(); };
virtual bool completed() { return endOfBodyReached(); };
/** Return the length of the body.
Also skips response headers if they have not been read already
MUST be called after responseStatusCode()
@return Length of the body, in bytes, or kNoContentLengthHeader if no
Content-Length header was returned by the server
*/
int contentLength();
/** Returns if the response body is chunked
@return true if response body is chunked, false otherwise
*/
int isResponseChunked() { return iIsChunked; }
/** Return the response body as a String
Also skips response headers if they have not been read already
MUST be called after responseStatusCode()
@return response body of request as a String
*/
String responseBody();
/** Enables connection keep-alive mode
*/
void connectionKeepAlive();
/** Disables sending the default request headers (Host and User Agent)
*/
void noDefaultRequestHeaders();
// Inherited from Print
// Note: 1st call to these indicates the user is sending the body, so if need
// Note: be we should finish the header first
virtual size_t write(uint8_t aByte) { if (iState < eRequestSent) { finishHeaders(); }; return iClient-> write(aByte); };
virtual size_t write(const uint8_t *aBuffer, size_t aSize) { if (iState < eRequestSent) { finishHeaders(); }; return iClient->write(aBuffer, aSize); };
// Inherited from Stream
virtual int available();
/** Read the next byte from the server.
@return Byte read or -1 if there are no bytes available.
*/
virtual int read();
virtual int read(uint8_t *buf, size_t size);
virtual int peek() { return iClient->peek(); };
virtual void flush() { iClient->flush(); };
// Inherited from Client
virtual int connect(IPAddress ip, uint16_t port) { return iClient->connect(ip, port); };
virtual int connect(const char *host, uint16_t port) { return iClient->connect(host, port); };
virtual void stop();
virtual uint8_t connected() { return iClient->connected(); };
virtual operator bool() { return bool(iClient); };
virtual uint32_t httpResponseTimeout() { return iHttpResponseTimeout; };
virtual void setHttpResponseTimeout(uint32_t timeout) { iHttpResponseTimeout = timeout; };
public:
/** Reset internal state data back to the "just initialised" state
*/
void resetState();
/** Send the first part of the request and the initial headers.
@param aURLPath Url to request
@param aHttpMethod Type of HTTP request to make, e.g. "GET", "POST", etc.
@return 0 if successful, else error
*/
int sendInitialHeaders(const char* aURLPath,
const char* aHttpMethod);
/* Let the server know that we've reached the end of the headers
*/
void finishHeaders();
/** Reading any pending data from the client (used in connection keep alive mode)
*/
void flushClientRx();
// Number of milliseconds that we wait each time there isn't any data
// available to be read (during status code and header processing)
static const int kHttpWaitForDataDelay = 1000;
// Number of milliseconds that we'll wait in total without receiveing any
// data before returning HTTP_ERROR_TIMED_OUT (during status code and header
// processing)
static const int kHttpResponseTimeout = 30*1000;
static const char* kContentLengthPrefix;
static const char* kTransferEncodingChunked;
typedef enum {
eIdle,
eRequestStarted,
eRequestSent,
eReadingStatusCode,
eStatusCodeRead,
eReadingContentLength,
eSkipToEndOfHeader,
eLineStartingCRFound,
eReadingBody,
eReadingChunkLength,
eReadingBodyChunk
} tHttpState;
// Client we're using
Client* iClient;
// Server we are connecting to
const char* iServerName;
IPAddress iServerAddress;
// Port of server we are connecting to
uint16_t iServerPort;
// Current state of the finite-state-machine
tHttpState iState;
// Stores the status code for the response, once known
int iStatusCode;
// Stores the value of the Content-Length header, if present
int iContentLength;
// How many bytes of the response body have been read by the user
int iBodyLengthConsumed;
// How far through a Content-Length header prefix we are
const char* iContentLengthPtr;
// How far through a Transfer-Encoding chunked header we are
const char* iTransferEncodingChunkedPtr;
// Stores if the response body is chunked
bool iIsChunked;
// Stores the value of the current chunk length, if present
int iChunkLength;
uint32_t iHttpResponseTimeout;
bool iConnectionClose;
bool iSendDefaultRequestHeaders;
String iHeaderLine;
};
#endif

View File

@ -0,0 +1,53 @@
// Library to simplify HTTP fetching on Arduino
// (c) Copyright Arduino. 2019
// Released under Apache License, version 2.0
#include "URLEncoder.h"
URLEncoderClass::URLEncoderClass()
{
}
URLEncoderClass::~URLEncoderClass()
{
}
String URLEncoderClass::encode(const char* str)
{
return encode(str, strlen(str));
}
String URLEncoderClass::encode(const String& str)
{
return encode(str.c_str(), str.length());
}
String URLEncoderClass::encode(const char* str, int length)
{
String encoded;
encoded.reserve(length);
for (int i = 0; i < length; i++) {
char c = str[i];
const char HEX_DIGIT_MAPPER[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
if (isAlphaNumeric(c) || (c == '-') || (c == '.') || (c == '_') || (c == '~')) {
encoded += c;
} else {
char s[4];
s[0] = '%';
s[1] = HEX_DIGIT_MAPPER[(c >> 4) & 0xf];
s[2] = HEX_DIGIT_MAPPER[(c & 0x0f)];
s[3] = 0;
encoded += s;
}
}
return encoded;
}
URLEncoderClass URLEncoder;

View File

@ -0,0 +1,25 @@
// Library to simplify HTTP fetching on Arduino
// (c) Copyright Arduino. 2019
// Released under Apache License, version 2.0
#ifndef URL_ENCODER_H
#define URL_ENCODER_H
#include <Arduino.h>
class URLEncoderClass
{
public:
URLEncoderClass();
virtual ~URLEncoderClass();
static String encode(const char* str);
static String encode(const String& str);
private:
static String encode(const char* str, int length);
};
extern URLEncoderClass URLEncoder;
#endif

View File

@ -0,0 +1,372 @@
// (c) Copyright Arduino. 2016
// Released under Apache License, version 2.0
#include "b64.h"
#include "WebSocketClient.h"
WebSocketClient::WebSocketClient(Client& aClient, const char* aServerName, uint16_t aServerPort)
: HttpClient(aClient, aServerName, aServerPort),
iTxStarted(false),
iRxSize(0)
{
}
WebSocketClient::WebSocketClient(Client& aClient, const String& aServerName, uint16_t aServerPort)
: HttpClient(aClient, aServerName, aServerPort),
iTxStarted(false),
iRxSize(0)
{
}
WebSocketClient::WebSocketClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort)
: HttpClient(aClient, aServerAddress, aServerPort),
iTxStarted(false),
iRxSize(0)
{
}
int WebSocketClient::begin(const char* aPath)
{
// start the GET request
beginRequest();
connectionKeepAlive();
int status = get(aPath);
if (status == 0)
{
uint8_t randomKey[16];
char base64RandomKey[25];
// create a random key for the connection upgrade
for (int i = 0; i < (int)sizeof(randomKey); i++)
{
randomKey[i] = random(0x01, 0xff);
}
memset(base64RandomKey, 0x00, sizeof(base64RandomKey));
b64_encode(randomKey, sizeof(randomKey), (unsigned char*)base64RandomKey, sizeof(base64RandomKey));
// start the connection upgrade sequence
sendHeader("Upgrade", "websocket");
sendHeader("Connection", "Upgrade");
sendHeader("Sec-WebSocket-Key", base64RandomKey);
sendHeader("Sec-WebSocket-Version", "13");
endRequest();
status = responseStatusCode();
if (status > 0)
{
skipResponseHeaders();
}
}
iRxSize = 0;
// status code of 101 means success
return (status == 101) ? 0 : status;
}
int WebSocketClient::begin(const String& aPath)
{
return begin(aPath.c_str());
}
int WebSocketClient::beginMessage(int aType)
{
if (iTxStarted)
{
// fail TX already started
return 1;
}
iTxStarted = true;
iTxMessageType = (aType & 0xf);
iTxSize = 0;
return 0;
}
int WebSocketClient::endMessage()
{
if (!iTxStarted)
{
// fail TX not started
return 1;
}
// send FIN + the message type (opcode)
HttpClient::write(0x80 | iTxMessageType);
// the message is masked (0x80)
// send the length
if (iTxSize < 126)
{
HttpClient::write(0x80 | (uint8_t)iTxSize);
}
else if (iTxSize < 0xffff)
{
HttpClient::write(0x80 | 126);
HttpClient::write((iTxSize >> 8) & 0xff);
HttpClient::write((iTxSize >> 0) & 0xff);
}
else
{
HttpClient::write(0x80 | 127);
HttpClient::write((iTxSize >> 56) & 0xff);
HttpClient::write((iTxSize >> 48) & 0xff);
HttpClient::write((iTxSize >> 40) & 0xff);
HttpClient::write((iTxSize >> 32) & 0xff);
HttpClient::write((iTxSize >> 24) & 0xff);
HttpClient::write((iTxSize >> 16) & 0xff);
HttpClient::write((iTxSize >> 8) & 0xff);
HttpClient::write((iTxSize >> 0) & 0xff);
}
uint8_t maskKey[4];
// create a random mask for the data and send
for (int i = 0; i < (int)sizeof(maskKey); i++)
{
maskKey[i] = random(0xff);
}
HttpClient::write(maskKey, sizeof(maskKey));
// mask the data and send
for (int i = 0; i < (int)iTxSize; i++) {
iTxBuffer[i] ^= maskKey[i % sizeof(maskKey)];
}
size_t txSize = iTxSize;
iTxStarted = false;
iTxSize = 0;
return (HttpClient::write(iTxBuffer, txSize) == txSize) ? 0 : 1;
}
size_t WebSocketClient::write(uint8_t aByte)
{
return write(&aByte, sizeof(aByte));
}
size_t WebSocketClient::write(const uint8_t *aBuffer, size_t aSize)
{
if (iState < eReadingBody)
{
// have not upgraded the connection yet
return HttpClient::write(aBuffer, aSize);
}
if (!iTxStarted)
{
// fail TX not started
return 0;
}
// check if the write size, fits in the buffer
if ((iTxSize + aSize) > sizeof(iTxBuffer))
{
aSize = sizeof(iTxSize) - iTxSize;
}
// copy data into the buffer
memcpy(iTxBuffer + iTxSize, aBuffer, aSize);
iTxSize += aSize;
return aSize;
}
int WebSocketClient::parseMessage()
{
flushRx();
// make sure 2 bytes (opcode + length)
// are available
if (HttpClient::available() < 2)
{
return 0;
}
// read open code and length
uint8_t opcode = HttpClient::read();
int length = HttpClient::read();
if ((opcode & 0x0f) == 0)
{
// continuation, use previous opcode and update flags
iRxOpCode |= opcode;
}
else
{
iRxOpCode = opcode;
}
iRxMasked = (length & 0x80);
length &= 0x7f;
// read the RX size
if (length < 126)
{
iRxSize = length;
}
else if (length == 126)
{
iRxSize = (HttpClient::read() << 8) | HttpClient::read();
}
else
{
iRxSize = ((uint64_t)HttpClient::read() << 56) |
((uint64_t)HttpClient::read() << 48) |
((uint64_t)HttpClient::read() << 40) |
((uint64_t)HttpClient::read() << 32) |
((uint64_t)HttpClient::read() << 24) |
((uint64_t)HttpClient::read() << 16) |
((uint64_t)HttpClient::read() << 8) |
(uint64_t)HttpClient::read();
}
// read in the mask, if present
if (iRxMasked)
{
for (int i = 0; i < (int)sizeof(iRxMaskKey); i++)
{
iRxMaskKey[i] = HttpClient::read();
}
}
iRxMaskIndex = 0;
if (TYPE_CONNECTION_CLOSE == messageType())
{
flushRx();
stop();
iRxSize = 0;
}
else if (TYPE_PING == messageType())
{
beginMessage(TYPE_PONG);
while(available())
{
write(read());
}
endMessage();
iRxSize = 0;
}
else if (TYPE_PONG == messageType())
{
flushRx();
iRxSize = 0;
}
return iRxSize;
}
int WebSocketClient::messageType()
{
return (iRxOpCode & 0x0f);
}
bool WebSocketClient::isFinal()
{
return ((iRxOpCode & 0x80) != 0);
}
String WebSocketClient::readString()
{
int avail = available();
String s;
if (avail > 0)
{
s.reserve(avail);
for (int i = 0; i < avail; i++)
{
s += (char)read();
}
}
return s;
}
int WebSocketClient::ping()
{
uint8_t pingData[16];
// create random data for the ping
for (int i = 0; i < (int)sizeof(pingData); i++)
{
pingData[i] = random(0xff);
}
beginMessage(TYPE_PING);
write(pingData, sizeof(pingData));
return endMessage();
}
int WebSocketClient::available()
{
if (iState < eReadingBody)
{
return HttpClient::available();
}
return iRxSize;
}
int WebSocketClient::read()
{
byte b;
if (read(&b, sizeof(b)))
{
return b;
}
return -1;
}
int WebSocketClient::read(uint8_t *aBuffer, size_t aSize)
{
int readCount = HttpClient::read(aBuffer, aSize);
if (readCount > 0)
{
iRxSize -= readCount;
// unmask the RX data if needed
if (iRxMasked)
{
for (int i = 0; i < (int)aSize; i++, iRxMaskIndex++)
{
aBuffer[i] ^= iRxMaskKey[iRxMaskIndex % sizeof(iRxMaskKey)];
}
}
}
return readCount;
}
int WebSocketClient::peek()
{
int p = HttpClient::peek();
if (p != -1 && iRxMasked)
{
// unmask the RX data if needed
p = (uint8_t)p ^ iRxMaskKey[iRxMaskIndex % sizeof(iRxMaskKey)];
}
return p;
}
void WebSocketClient::flushRx()
{
while(available())
{
read();
}
}

View File

@ -0,0 +1,99 @@
// (c) Copyright Arduino. 2016
// Released under Apache License, version 2.0
#ifndef WebSocketClient_h
#define WebSocketClient_h
#include <Arduino.h>
#include "HttpClient.h"
static const int TYPE_CONTINUATION = 0x0;
static const int TYPE_TEXT = 0x1;
static const int TYPE_BINARY = 0x2;
static const int TYPE_CONNECTION_CLOSE = 0x8;
static const int TYPE_PING = 0x9;
static const int TYPE_PONG = 0xa;
class WebSocketClient : public HttpClient
{
public:
WebSocketClient(Client& aClient, const char* aServerName, uint16_t aServerPort = HttpClient::kHttpPort);
WebSocketClient(Client& aClient, const String& aServerName, uint16_t aServerPort = HttpClient::kHttpPort);
WebSocketClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort = HttpClient::kHttpPort);
/** Start the Web Socket connection to the specified path
@param aURLPath Path to use in request (optional, "/" is used by default)
@return 0 if successful, else error
*/
int begin(const char* aPath = "/");
int begin(const String& aPath);
/** Begin to send a message of type (TYPE_TEXT or TYPE_BINARY)
Use the write or Stream API's to set message content, followed by endMessage
to complete the message.
@param aURLPath Path to use in request
@return 0 if successful, else error
*/
int beginMessage(int aType);
/** Completes sending of a message started by beginMessage
@return 0 if successful, else error
*/
int endMessage();
/** Try to parse an incoming messages
@return 0 if no message available, else size of parsed message
*/
int parseMessage();
/** Returns type of current parsed message
@return type of current parsedMessage (TYPE_TEXT or TYPE_BINARY)
*/
int messageType();
/** Returns if the current message is the final chunk of a split
message
@return true for final message, false otherwise
*/
bool isFinal();
/** Read the current messages as a string
@return current message as a string
*/
String readString();
/** Send a ping
@return 0 if successful, else error
*/
int ping();
// Inherited from Print
virtual size_t write(uint8_t aByte);
virtual size_t write(const uint8_t *aBuffer, size_t aSize);
// Inherited from Stream
virtual int available();
/** Read the next byte from the server.
@return Byte read or -1 if there are no bytes available.
*/
virtual int read();
virtual int read(uint8_t *buf, size_t size);
virtual int peek();
private:
void flushRx();
private:
bool iTxStarted;
uint8_t iTxMessageType;
uint8_t iTxBuffer[128];
uint64_t iTxSize;
uint8_t iRxOpCode;
uint64_t iRxSize;
bool iRxMasked;
int iRxMaskIndex;
uint8_t iRxMaskKey[4];
};
#endif

View File

@ -0,0 +1,72 @@
// Simple Base64 code
// (c) Copyright 2010 MCQN Ltd.
// Released under Apache License, version 2.0
#include "b64.h"
/* Simple test program
#include <stdio.h>
void main()
{
char* in = "amcewen";
char out[22];
b64_encode(in, 15, out, 22);
out[21] = '\0';
printf(out);
}
*/
int b64_encode(const unsigned char* aInput, int aInputLen, unsigned char* aOutput, int aOutputLen)
{
// Work out if we've got enough space to encode the input
// Every 6 bits of input becomes a byte of output
if (aOutputLen < (aInputLen*8)/6)
{
// FIXME Should we return an error here, or just the length
return (aInputLen*8)/6;
}
// If we get here we've got enough space to do the encoding
const char* b64_dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
if (aInputLen == 3)
{
aOutput[0] = b64_dictionary[aInput[0] >> 2];
aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)];
aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2|(aInput[2]>>6)];
aOutput[3] = b64_dictionary[aInput[2]&0x3F];
}
else if (aInputLen == 2)
{
aOutput[0] = b64_dictionary[aInput[0] >> 2];
aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)];
aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2];
aOutput[3] = '=';
}
else if (aInputLen == 1)
{
aOutput[0] = b64_dictionary[aInput[0] >> 2];
aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4];
aOutput[2] = '=';
aOutput[3] = '=';
}
else
{
// Break the input into 3-byte chunks and process each of them
int i;
for (i = 0; i < aInputLen/3; i++)
{
b64_encode(&aInput[i*3], 3, &aOutput[i*4], 4);
}
if (aInputLen % 3 > 0)
{
// It doesn't fit neatly into a 3-byte chunk, so process what's left
b64_encode(&aInput[i*3], aInputLen % 3, &aOutput[i*4], aOutputLen - (i*4));
}
}
return ((aInputLen+2)/3)*4;
}

View File

@ -0,0 +1,6 @@
#ifndef b64_h
#define b64_h
int b64_encode(const unsigned char* aInput, int aInputLen, unsigned char* aOutput, int aOutputLen);
#endif

View File

@ -0,0 +1,15 @@
compile:
# Choosing to run compilation tests on 2 different Arduino platforms
platforms:
- uno
- due
# - zero # SAMD covered by M4
# - leonardo # AVR covered by UNO
- m4
# - esp32 # errors on OneWire => util/crc16.h vs rom/crc.h
- esp8266
# - mega2560 # AVR covered by UNO
unittest:
# These dependent libraries will be installed
libraries:
- "OneWire"

1
lib/DallasTemperature/.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
* text=auto

View File

@ -0,0 +1,13 @@
name: Arduino-lint
on: [push, pull_request]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: arduino/arduino-lint-action@v1
with:
library-manager: update
# compliance: strict

View File

@ -0,0 +1,17 @@
---
name: Arduino CI
on: [push, pull_request]
jobs:
runTest:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: ruby/setup-ruby@v1
with:
ruby-version: 2.6
- run: |
gem install arduino_ci
arduino_ci.rb

View File

@ -0,0 +1,18 @@
name: JSON check
on:
push:
paths:
- '**.json'
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: json-syntax-check
uses: limitusus/json-syntax-check@v1
with:
pattern: "\\.json$"

16
lib/DallasTemperature/.gitignore vendored Normal file
View File

@ -0,0 +1,16 @@
.idea
classes
target
out
build
*.iml
*.ipr
*.iws
*.log
*.war
.idea
.project
.classpath
.settings
.gradle
.vscode

View File

@ -0,0 +1 @@
{"type": "library", "name": "DallasTemperature", "version": "3.11.0", "spec": {"owner": "milesburton", "id": 54, "name": "DallasTemperature", "requirements": null, "uri": null}}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,346 @@
#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 <inttypes.h>
#ifdef __STM32F1__
#include <OneWireSTM.h>
#else
#include <OneWire.h>
#endif
// Model IDs
#define DS18S20MODEL 0x10 // also DS1820
#define DS18B20MODEL 0x28 // also MAX31820
#define DS1822MODEL 0x22
#define DS1825MODEL 0x3B // also MAX31850
#define DS28EA00MODEL 0x42
// Error Codes
// See https://github.com/milesburton/Arduino-Temperature-Control-Library/commit/ac1eb7f56e3894e855edc3353be4bde4aa838d41#commitcomment-75490966 for the 16bit implementation. Reverted due to microcontroller resource constraints.
#define DEVICE_DISCONNECTED_C -127
#define DEVICE_DISCONNECTED_F -196.6
#define DEVICE_DISCONNECTED_RAW -7040
#define DEVICE_FAULT_OPEN_C -254
#define DEVICE_FAULT_OPEN_F -425.199982
#define DEVICE_FAULT_OPEN_RAW -32512
#define DEVICE_FAULT_SHORTGND_C -253
#define DEVICE_FAULT_SHORTGND_F -423.399994
#define DEVICE_FAULT_SHORTGND_RAW -32384
#define DEVICE_FAULT_SHORTVDD_C -252
#define DEVICE_FAULT_SHORTVDD_F -421.599976
#define DEVICE_FAULT_SHORTVDD_RAW -32256
// 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 <class T>
operator T *() const {
return 0;
}
template <class C, class T>
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);
struct request_t {
bool result;
unsigned long timestamp;
operator bool() {
return result;
}
};
// sends command for all devices on the bus to perform a temperature conversion
request_t requestTemperatures(void);
// sends command for one device to perform a temperature conversion by address
request_t requestTemperaturesByAddress(const uint8_t*);
// sends command for one device to perform a temperature conversion by index
request_t requestTemperaturesByIndex(uint8_t);
// returns temperature raw value (12 bit integer of 1/128 degrees C)
int32_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);
static uint16_t millisToWaitForConversion(uint8_t);
uint16_t millisToWaitForConversion();
// 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(int32_t);
// convert from Celsius to raw
static int16_t celsiusToRaw(float);
// convert from raw to Fahrenheit
static float rawToFahrenheit(int32_t);
#if REQUIRESNEW
// initialize memory area
void* operator new(unsigned int);
// delete memory reference
void operator delete(void*);
#endif
void blockTillConversionComplete(uint8_t);
void blockTillConversionComplete(uint8_t, unsigned long);
void blockTillConversionComplete(uint8_t, request_t);
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
int32_t calculateTemperature(const uint8_t*, 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

View File

@ -0,0 +1,80 @@
[![Arduino CI](https://github.com/milesburton/Arduino-Temperature-Control-Library/workflows/Arduino%20CI/badge.svg)](https://github.com/marketplace/actions/arduino_ci)
[![Arduino-lint](https://github.com/milesburton/Arduino-Temperature-Control-Library/actions/workflows/arduino-lint.yml/badge.svg)](https://github.com/RobTillaart/AS5600/actions/workflows/arduino-lint.yml)
[![JSON check](https://github.com/milesburton/Arduino-Temperature-Control-Library/actions/workflows/jsoncheck.yml/badge.svg)](https://github.com/RobTillaart/AS5600/actions/workflows/jsoncheck.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/milesburton/Arduino-Temperature-Control-Library/blob/master/LICENSE)
[![GitHub release](https://img.shields.io/github/release/milesburton/Arduino-Temperature-Control-Library.svg?maxAge=3600)](https://github.com/milesburton/Arduino-Temperature-Control-Library/releases)
# 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
* MAX31850
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 <miles@mnetcs.com> originally developed this library.
Tim Newsome <nuisance@casualhacker.net> 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
Additional documentation may be found here
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

View File

@ -0,0 +1,161 @@
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
// arrays to hold device addresses
DeviceAddress insideThermometer, outsideThermometer;
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// Start up the library
sensors.begin();
// locate devices on the bus
Serial.print("Found ");
Serial.print(sensors.getDeviceCount(), DEC);
Serial.println(" devices.");
// search for devices on the bus and assign based on an index.
if (!sensors.getAddress(insideThermometer, 0)) Serial.println("Unable to find address for Device 0");
if (!sensors.getAddress(outsideThermometer, 1)) Serial.println("Unable to find address for Device 1");
// show the addresses we found on the bus
Serial.print("Device 0 Address: ");
printAddress(insideThermometer);
Serial.println();
Serial.print("Device 0 Alarms: ");
printAlarms(insideThermometer);
Serial.println();
Serial.print("Device 1 Address: ");
printAddress(outsideThermometer);
Serial.println();
Serial.print("Device 1 Alarms: ");
printAlarms(outsideThermometer);
Serial.println();
Serial.println("Setting alarm temps...");
// alarm when temp is higher than 30C
sensors.setHighAlarmTemp(insideThermometer, 30);
// alarm when temp is lower than -10C
sensors.setLowAlarmTemp(insideThermometer, -10);
// alarm when temp is higher than 31C
sensors.setHighAlarmTemp(outsideThermometer, 31);
// alarn when temp is lower than 27C
sensors.setLowAlarmTemp(outsideThermometer, 27);
Serial.print("New Device 0 Alarms: ");
printAlarms(insideThermometer);
Serial.println();
Serial.print("New Device 1 Alarms: ");
printAlarms(outsideThermometer);
Serial.println();
}
// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
for (uint8_t i = 0; i < 8; i++)
{
if (deviceAddress[i] < 16) Serial.print("0");
Serial.print(deviceAddress[i], HEX);
}
}
// function to print the temperature for a device
void printTemperature(DeviceAddress deviceAddress)
{
float tempC = sensors.getTempC(deviceAddress);
Serial.print("Temp C: ");
Serial.print(tempC);
Serial.print(" Temp F: ");
Serial.print(DallasTemperature::toFahrenheit(tempC));
}
void printAlarms(uint8_t deviceAddress[])
{
char temp;
temp = sensors.getHighAlarmTemp(deviceAddress);
Serial.print("High Alarm: ");
Serial.print(temp, DEC);
Serial.print("C/");
Serial.print(DallasTemperature::toFahrenheit(temp));
Serial.print("F | Low Alarm: ");
temp = sensors.getLowAlarmTemp(deviceAddress);
Serial.print(temp, DEC);
Serial.print("C/");
Serial.print(DallasTemperature::toFahrenheit(temp));
Serial.print("F");
}
// main function to print information about a device
void printData(DeviceAddress deviceAddress)
{
Serial.print("Device Address: ");
printAddress(deviceAddress);
Serial.print(" ");
printTemperature(deviceAddress);
Serial.println();
}
void checkAlarm(DeviceAddress deviceAddress)
{
if (sensors.hasAlarm(deviceAddress))
{
Serial.print("ALARM: ");
printData(deviceAddress);
}
}
void loop(void)
{
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print("Requesting temperatures...");
sensors.requestTemperatures();
Serial.println("DONE");
// Method 1:
// check each address individually for an alarm condition
checkAlarm(insideThermometer);
checkAlarm(outsideThermometer);
/*
// Alternate method:
// Search the bus and iterate through addresses of devices with alarms
// space for the alarm device's address
DeviceAddress alarmAddr;
Serial.println("Searching for alarms...");
// resetAlarmSearch() must be called before calling alarmSearch()
sensors.resetAlarmSearch();
// alarmSearch() returns 0 when there are no devices with alarms
while (sensors.alarmSearch(alarmAddr))
{
Serial.print("ALARM: ");
printData(alarmAddr);
}
*/
}

View File

@ -0,0 +1,143 @@
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
// arrays to hold device addresses
DeviceAddress insideThermometer, outsideThermometer;
// function that will be called when an alarm condition exists during DallasTemperatures::processAlarms();
void newAlarmHandler(const uint8_t* deviceAddress)
{
Serial.println("Alarm Handler Start");
printAlarmInfo(deviceAddress);
printTemp(deviceAddress);
Serial.println();
Serial.println("Alarm Handler Finish");
}
void printCurrentTemp(DeviceAddress deviceAddress)
{
printAddress(deviceAddress);
printTemp(deviceAddress);
Serial.println();
}
void printAddress(const DeviceAddress deviceAddress)
{
Serial.print("Address: ");
for (uint8_t i = 0; i < 8; i++)
{
if (deviceAddress[i] < 16) Serial.print("0");
Serial.print(deviceAddress[i], HEX);
}
Serial.print(" ");
}
void printTemp(const DeviceAddress deviceAddress)
{
float tempC = sensors.getTempC(deviceAddress);
if (tempC != DEVICE_DISCONNECTED_C)
{
Serial.print("Current Temp C: ");
Serial.print(tempC);
}
else Serial.print("DEVICE DISCONNECTED");
Serial.print(" ");
}
void printAlarmInfo(const DeviceAddress deviceAddress)
{
char temp;
printAddress(deviceAddress);
temp = sensors.getHighAlarmTemp(deviceAddress);
Serial.print("High Alarm: ");
Serial.print(temp, DEC);
Serial.print("C");
Serial.print(" Low Alarm: ");
temp = sensors.getLowAlarmTemp(deviceAddress);
Serial.print(temp, DEC);
Serial.print("C");
Serial.print(" ");
}
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// Start up the library
sensors.begin();
// locate devices on the bus
Serial.print("Found ");
Serial.print(sensors.getDeviceCount(), DEC);
Serial.println(" devices.");
// search for devices on the bus and assign based on an index
if (!sensors.getAddress(insideThermometer, 0)) Serial.println("Unable to find address for Device 0");
if (!sensors.getAddress(outsideThermometer, 1)) Serial.println("Unable to find address for Device 1");
Serial.print("Device insideThermometer ");
printAlarmInfo(insideThermometer);
Serial.println();
Serial.print("Device outsideThermometer ");
printAlarmInfo(outsideThermometer);
Serial.println();
// set alarm ranges
Serial.println("Setting alarm temps...");
sensors.setHighAlarmTemp(insideThermometer, 26);
sensors.setLowAlarmTemp(insideThermometer, 22);
sensors.setHighAlarmTemp(outsideThermometer, 25);
sensors.setLowAlarmTemp(outsideThermometer, 21);
Serial.print("New insideThermometer ");
printAlarmInfo(insideThermometer);
Serial.println();
Serial.print("New outsideThermometer ");
printAlarmInfo(outsideThermometer);
Serial.println();
// attach alarm handler
sensors.setAlarmHandler(&newAlarmHandler);
}
void loop(void)
{
// ask the devices to measure the temperature
sensors.requestTemperatures();
// if an alarm condition exists as a result of the most recent
// requestTemperatures() request, it exists until the next time
// requestTemperatures() is called AND there isn't an alarm condition
// on the device
if (sensors.hasAlarm())
{
Serial.println("Oh noes! There is at least one alarm on the bus.");
}
// call alarm handler function defined by sensors.setAlarmHandler
// for each device reporting an alarm
sensors.processAlarms();
if (!sensors.hasAlarm())
{
// just print out the current temperature
printCurrentTemp(insideThermometer);
printCurrentTemp(outsideThermometer);
}
delay(1000);
}

View File

@ -0,0 +1,35 @@
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino, while external pullup P-MOSFET gate into port 3
#define ONE_WIRE_BUS 2
#define ONE_WIRE_PULLUP 3
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire, ONE_WIRE_PULLUP);
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// Start up the library
sensors.begin();
}
void loop(void)
{
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print("Requesting temperatures...");
sensors.requestTemperatures(); // Send the command to get temperatures
Serial.println("DONE");
for (int i = 0; i < sensors.getDeviceCount(); i++) {
Serial.println("Temperature for Device " + String(i) + " is: " + String(sensors.getTempCByIndex(i)));
}
}

View File

@ -0,0 +1,43 @@
#include <OneWire.h>
#include <DallasTemperature.h>
OneWire ds18x20[] = { 3, 7 };
const int oneWireCount = sizeof(ds18x20) / sizeof(OneWire);
DallasTemperature sensor[oneWireCount];
void setup(void) {
// start serial port
Serial.begin(9600);
Serial.println("Dallas Temperature Multiple Bus Control Library Simple Demo");
Serial.print("============Ready with ");
Serial.print(oneWireCount);
Serial.println(" Sensors================");
// Start up the library on all defined bus-wires
DeviceAddress deviceAddress;
for (int i = 0; i < oneWireCount; i++) {
sensor[i].setOneWire(&ds18x20[i]);
sensor[i].begin();
if (sensor[i].getAddress(deviceAddress, 0)) sensor[i].setResolution(deviceAddress, 12);
}
}
void loop(void) {
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print("Requesting temperatures...");
for (int i = 0; i < oneWireCount; i++) {
sensor[i].requestTemperatures();
}
Serial.println("DONE");
delay(1000);
for (int i = 0; i < oneWireCount; i++) {
float temperature = sensor[i].getTempCByIndex(0);
Serial.print("Temperature for the sensor ");
Serial.print(i);
Serial.print(" is ");
Serial.println(temperature);
}
Serial.println();
}

View File

@ -0,0 +1,148 @@
// Include the libraries we need
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2
#define TEMPERATURE_PRECISION 9
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
// arrays to hold device addresses
DeviceAddress insideThermometer, outsideThermometer;
// Assign address manually. The addresses below will need to be changed
// to valid device addresses on your bus. Device address can be retrieved
// by using either oneWire.search(deviceAddress) or individually via
// sensors.getAddress(deviceAddress, index)
// DeviceAddress insideThermometer = { 0x28, 0x1D, 0x39, 0x31, 0x2, 0x0, 0x0, 0xF0 };
// DeviceAddress outsideThermometer = { 0x28, 0x3F, 0x1C, 0x31, 0x2, 0x0, 0x0, 0x2 };
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// Start up the library
sensors.begin();
// locate devices on the bus
Serial.print("Locating devices...");
Serial.print("Found ");
Serial.print(sensors.getDeviceCount(), DEC);
Serial.println(" devices.");
// report parasite power requirements
Serial.print("Parasite power is: ");
if (sensors.isParasitePowerMode()) Serial.println("ON");
else Serial.println("OFF");
// Search for devices on the bus and assign based on an index. Ideally,
// you would do this to initially discover addresses on the bus and then
// use those addresses and manually assign them (see above) once you know
// the devices on your bus (and assuming they don't change).
//
// method 1: by index
if (!sensors.getAddress(insideThermometer, 0)) Serial.println("Unable to find address for Device 0");
if (!sensors.getAddress(outsideThermometer, 1)) Serial.println("Unable to find address for Device 1");
// method 2: search()
// search() looks 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
//
// Must be called before search()
//oneWire.reset_search();
// assigns the first address found to insideThermometer
//if (!oneWire.search(insideThermometer)) Serial.println("Unable to find address for insideThermometer");
// assigns the seconds address found to outsideThermometer
//if (!oneWire.search(outsideThermometer)) Serial.println("Unable to find address for outsideThermometer");
// show the addresses we found on the bus
Serial.print("Device 0 Address: ");
printAddress(insideThermometer);
Serial.println();
Serial.print("Device 1 Address: ");
printAddress(outsideThermometer);
Serial.println();
// set the resolution to 9 bit per device
sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION);
sensors.setResolution(outsideThermometer, TEMPERATURE_PRECISION);
Serial.print("Device 0 Resolution: ");
Serial.print(sensors.getResolution(insideThermometer), DEC);
Serial.println();
Serial.print("Device 1 Resolution: ");
Serial.print(sensors.getResolution(outsideThermometer), DEC);
Serial.println();
}
// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
for (uint8_t i = 0; i < 8; i++)
{
// zero pad the address if necessary
if (deviceAddress[i] < 16) Serial.print("0");
Serial.print(deviceAddress[i], HEX);
}
}
// function to print the temperature for a device
void printTemperature(DeviceAddress deviceAddress)
{
float tempC = sensors.getTempC(deviceAddress);
if (tempC == DEVICE_DISCONNECTED_C)
{
Serial.println("Error: Could not read temperature data");
return;
}
Serial.print("Temp C: ");
Serial.print(tempC);
Serial.print(" Temp F: ");
Serial.print(DallasTemperature::toFahrenheit(tempC));
}
// function to print a device's resolution
void printResolution(DeviceAddress deviceAddress)
{
Serial.print("Resolution: ");
Serial.print(sensors.getResolution(deviceAddress));
Serial.println();
}
// main function to print information about a device
void printData(DeviceAddress deviceAddress)
{
Serial.print("Device Address: ");
printAddress(deviceAddress);
Serial.print(" ");
printTemperature(deviceAddress);
Serial.println();
}
/*
Main function, calls the temperatures in a loop.
*/
void loop(void)
{
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print("Requesting temperatures...");
sensors.requestTemperatures();
Serial.println("DONE");
// print the device information
printData(insideThermometer);
printData(outsideThermometer);
}

View File

@ -0,0 +1,106 @@
//
// FILE: SaveRecallScratchPad.ino
// AUTHOR: GitKomodo
// VERSION: 0.0.1
// PURPOSE: Show DallasTemperature lib functionality to
// save/recall ScratchPad values to/from EEPROM
//
// HISTORY:
// 0.0.1 = 2020-02-18 initial version
//
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
DeviceAddress deviceAddress;
void setup()
{
Serial.begin(9600);
Serial.println(__FILE__);
Serial.println("Dallas Temperature Demo");
sensors.begin();
// Get ID of first sensor (at index 0)
sensors.getAddress(deviceAddress, 0);
// By default configuration and alarm/userdata registers are also saved to EEPROM
// when they're changed. Sensors recall these values automatically when powered up.
// Turn OFF automatic saving of configuration and alarm/userdata registers to EEPROM
sensors.setAutoSaveScratchPad(false);
// Change configuration and alarm/userdata registers on the scratchpad
int8_t resolution = 12;
sensors.setResolution(deviceAddress, resolution);
int16_t userdata = 24680;
sensors.setUserData(deviceAddress, userdata);
// Save configuration and alarm/userdata registers to EEPROM
sensors.saveScratchPad(deviceAddress);
// saveScratchPad can also be used without a parameter to save the configuration
// and alarm/userdata registers of ALL connected sensors to EEPROM:
//
// sensors.saveScratchPad();
//
// Or the configuration and alarm/userdata registers of a sensor can be saved to
// EEPROM by index:
//
// sensors.saveScratchPadByIndex(0);
// Print current values on the scratchpad (resolution = 12, userdata = 24680)
printValues();
}
void loop() {
// Change configuration and alarm/userdata registers on the scratchpad
int8_t resolution = 10;
sensors.setResolution(deviceAddress, resolution);
int16_t userdata = 12345;
sensors.setUserData(deviceAddress, userdata);
// Print current values on the scratchpad (resolution = 10, userdata = 12345)
printValues();
delay(2000);
// Recall configuration and alarm/userdata registers from EEPROM
sensors.recallScratchPad(deviceAddress);
// recallScratchPad can also be used without a parameter to recall the configuration
// and alarm/userdata registers of ALL connected sensors from EEPROM:
//
// sensors.recallScratchPad();
//
// Or the configuration and alarm/userdata registers of a sensor can be recalled
// from EEPROM by index:
//
// sensors.recallScratchPadByIndex(0);
// Print current values on the scratchpad (resolution = 12, userdata = 24680)
printValues();
delay(2000);
}
void printValues() {
Serial.println();
Serial.println("Current values on the scratchpad:");
Serial.print("Resolution:\t");
Serial.println(sensors.getResolution(deviceAddress));
Serial.print("User data:\t");
Serial.println(sensors.getUserData(deviceAddress));
}

View File

@ -0,0 +1,47 @@
//
// This sketch does not use the ALARM registers and uses those 2 bytes as a counter
// these 2 bytes can be used for other purposes as well e.g. last temperature or
// a specific ID.
//
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
int count = 0;
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// Start up the library
sensors.begin();
}
void loop(void)
{
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print("Requesting temperatures...");
sensors.requestTemperatures(); // Send the command to get temperatures
Serial.println("DONE");
Serial.print("Temperature for the device 1 (index 0) is: ");
Serial.println(sensors.getTempCByIndex(0));
count++;
sensors.setUserDataByIndex(0, count);
int x = sensors.getUserDataByIndex(0);
Serial.println(count);
}

View File

@ -0,0 +1,51 @@
// Include the libraries we need
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
/*
* The setup function. We only start the sensors here
*/
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// Start up the library
sensors.begin();
}
/*
* Main function, get and show the temperature
*/
void loop(void)
{
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print("Requesting temperatures...");
sensors.requestTemperatures(); // Send the command to get temperatures
Serial.println("DONE");
// After we got the temperatures, we can print them here.
// We use the function ByIndex, and as an example get the temperature from the first sensor only.
float tempC = sensors.getTempCByIndex(0);
// Check if reading was successful
if (tempC != DEVICE_DISCONNECTED_C)
{
Serial.print("Temperature for the device 1 (index 0) is: ");
Serial.println(tempC);
}
else
{
Serial.println("Error: Could not read temperature data");
}
}

View File

@ -0,0 +1,121 @@
// Include the libraries we need
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
// arrays to hold device address
DeviceAddress insideThermometer;
/*
* Setup function. Here we do the basics
*/
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// locate devices on the bus
Serial.print("Locating devices...");
sensors.begin();
Serial.print("Found ");
Serial.print(sensors.getDeviceCount(), DEC);
Serial.println(" devices.");
// report parasite power requirements
Serial.print("Parasite power is: ");
if (sensors.isParasitePowerMode()) Serial.println("ON");
else Serial.println("OFF");
// Assign address manually. The addresses below will beed to be changed
// to valid device addresses on your bus. Device address can be retrieved
// by using either oneWire.search(deviceAddress) or individually via
// sensors.getAddress(deviceAddress, index)
// Note that you will need to use your specific address here
//insideThermometer = { 0x28, 0x1D, 0x39, 0x31, 0x2, 0x0, 0x0, 0xF0 };
// Method 1:
// Search for devices on the bus and assign based on an index. Ideally,
// you would do this to initially discover addresses on the bus and then
// use those addresses and manually assign them (see above) once you know
// the devices on your bus (and assuming they don't change).
if (!sensors.getAddress(insideThermometer, 0)) Serial.println("Unable to find address for Device 0");
// method 2: search()
// search() looks 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
//
// Must be called before search()
//oneWire.reset_search();
// assigns the first address found to insideThermometer
//if (!oneWire.search(insideThermometer)) Serial.println("Unable to find address for insideThermometer");
// show the addresses we found on the bus
Serial.print("Device 0 Address: ");
printAddress(insideThermometer);
Serial.println();
// set the resolution to 9 bit (Each Dallas/Maxim device is capable of several different resolutions)
sensors.setResolution(insideThermometer, 9);
Serial.print("Device 0 Resolution: ");
Serial.print(sensors.getResolution(insideThermometer), DEC);
Serial.println();
}
// function to print the temperature for a device
void printTemperature(DeviceAddress deviceAddress)
{
// method 1 - slower
//Serial.print("Temp C: ");
//Serial.print(sensors.getTempC(deviceAddress));
//Serial.print(" Temp F: ");
//Serial.print(sensors.getTempF(deviceAddress)); // Makes a second call to getTempC and then converts to Fahrenheit
// method 2 - faster
float tempC = sensors.getTempC(deviceAddress);
if (tempC == DEVICE_DISCONNECTED_C)
{
Serial.println("Error: Could not read temperature data");
return;
}
Serial.print("Temp C: ");
Serial.print(tempC);
Serial.print(" Temp F: ");
Serial.println(DallasTemperature::toFahrenheit(tempC)); // Converts tempC to Fahrenheit
}
/*
* Main function. It will request the tempC from the sensors and display on Serial.
*/
void loop(void)
{
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print("Requesting temperatures...");
sensors.requestTemperatures(); // Send the command to get temperatures
Serial.println("DONE");
// It responds almost immediately. Let's print out the data
printTemperature(insideThermometer); // Use a simple function to print out the data
}
// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
for (uint8_t i = 0; i < 8; i++)
{
if (deviceAddress[i] < 16) Serial.print("0");
Serial.print(deviceAddress[i], HEX);
}
}

View File

@ -0,0 +1,129 @@
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2
#define TEMPERATURE_PRECISION 9 // Lower resolution
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
int numberOfDevices; // Number of temperature devices found
DeviceAddress tempDeviceAddress; // We'll use this variable to store a found device address
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// Start up the library
sensors.begin();
// Grab a count of devices on the wire
numberOfDevices = sensors.getDeviceCount();
// locate devices on the bus
Serial.print("Locating devices...");
Serial.print("Found ");
Serial.print(numberOfDevices, DEC);
Serial.println(" devices.");
// report parasite power requirements
Serial.print("Parasite power is: ");
if (sensors.isParasitePowerMode()) Serial.println("ON");
else Serial.println("OFF");
// Loop through each device, print out address
for (int i = 0; i < numberOfDevices; i++)
{
// Search the wire for address
if (sensors.getAddress(tempDeviceAddress, i))
{
Serial.print("Found device ");
Serial.print(i, DEC);
Serial.print(" with address: ");
printAddress(tempDeviceAddress);
Serial.println();
Serial.print("Setting resolution to ");
Serial.println(TEMPERATURE_PRECISION, DEC);
// set the resolution to TEMPERATURE_PRECISION bit (Each Dallas/Maxim device is capable of several different resolutions)
sensors.setResolution(tempDeviceAddress, TEMPERATURE_PRECISION);
Serial.print("Resolution actually set to: ");
Serial.print(sensors.getResolution(tempDeviceAddress), DEC);
Serial.println();
} else {
Serial.print("Found ghost device at ");
Serial.print(i, DEC);
Serial.print(" but could not detect address. Check power and cabling");
}
}
}
// function to print the temperature for a device
void printTemperature(DeviceAddress deviceAddress)
{
// method 1 - slower
//Serial.print("Temp C: ");
//Serial.print(sensors.getTempC(deviceAddress));
//Serial.print(" Temp F: ");
//Serial.print(sensors.getTempF(deviceAddress)); // Makes a second call to getTempC and then converts to Fahrenheit
// method 2 - faster
float tempC = sensors.getTempC(deviceAddress);
if (tempC == DEVICE_DISCONNECTED_C)
{
Serial.println("Error: Could not read temperature data");
return;
}
Serial.print("Temp C: ");
Serial.print(tempC);
Serial.print(" Temp F: ");
Serial.println(DallasTemperature::toFahrenheit(tempC)); // Converts tempC to Fahrenheit
}
void loop(void)
{
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print("Requesting temperatures...");
sensors.requestTemperatures(); // Send the command to get temperatures
Serial.println("DONE");
// Loop through each device, print out temperature data
for (int i = 0; i < numberOfDevices; i++)
{
// Search the wire for address
if (sensors.getAddress(tempDeviceAddress, i))
{
// Output the device ID
Serial.print("Temperature for device: ");
Serial.println(i, DEC);
// It responds almost immediately. Let's print out the data
printTemperature(tempDeviceAddress); // Use a simple function to print out the data
}
//else ghost device! Check your power requirements and cabling
}
}
// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
for (uint8_t i = 0; i < 8; i++)
{
if (deviceAddress[i] < 16) Serial.print("0");
Serial.print(deviceAddress[i], HEX);
}
}

View File

@ -0,0 +1,77 @@
//
// FILE: Timing.ino
// AUTHOR: Rob Tillaart
// VERSION: 0.0.3
// PURPOSE: show performance of DallasTemperature lib
// compared to datasheet times per resolution
//
// HISTORY:
// 0.0.1 2017-07-25 initial version
// 0.0.2 2020-02-13 updates to work with current lib version
// 0.0.3 2020-02-20 added timing measurement of setResolution
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensor(&oneWire);
uint32_t start, stop;
void setup()
{
Serial.begin(9600);
Serial.println(__FILE__);
Serial.print("DallasTemperature Library version: ");
Serial.println(DALLASTEMPLIBVERSION);
sensor.begin();
}
void loop()
{
float ti[4] = { 94, 188, 375, 750 };
Serial.println();
Serial.println("Test takes about 30 seconds for 4 resolutions");
Serial.println("RES\tTIME\tACTUAL\tGAIN");
for (int r = 9; r < 13; r++)
{
start = micros();
sensor.setResolution(r);
Serial.println(micros() - start);
start = micros();
sensor.setResolution(r);
Serial.println(micros() - start);
uint32_t duration = run(20);
float avgDuration = duration / 20.0;
Serial.print(r);
Serial.print("\t");
Serial.print(ti[r - 9]);
Serial.print("\t");
Serial.print(avgDuration, 2);
Serial.print("\t");
Serial.print(avgDuration * 100 / ti[r - 9], 1);
Serial.println("%");
}
delay(1000);
}
uint32_t run(int runs)
{
float t;
start = millis();
for (int i = 0; i < runs; i++)
{
sensor.requestTemperatures();
t = sensor.getTempCByIndex(0);
}
stop = millis();
return stop - start;
}

View File

@ -0,0 +1,45 @@
//
// FILE: TwoPin_DS18B20.ino
// AUTHOR: Rob Tillaart
// VERSION: 0.1.00
// PURPOSE: two pins for two sensors demo
// DATE: 2014-06-13
// URL: http://forum.arduino.cc/index.php?topic=216835.msg1764333#msg1764333
//
// Released to the public domain
//
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS_1 2
#define ONE_WIRE_BUS_2 4
OneWire oneWire_in(ONE_WIRE_BUS_1);
OneWire oneWire_out(ONE_WIRE_BUS_2);
DallasTemperature sensor_inhouse(&oneWire_in);
DallasTemperature sensor_outhouse(&oneWire_out);
void setup(void)
{
Serial.begin(9600);
Serial.println("Dallas Temperature Control Library Demo - TwoPin_DS18B20");
sensor_inhouse.begin();
sensor_outhouse.begin();
}
void loop(void)
{
Serial.print("Requesting temperatures...");
sensor_inhouse.requestTemperatures();
sensor_outhouse.requestTemperatures();
Serial.println(" done");
Serial.print("Inhouse: ");
Serial.println(sensor_inhouse.getTempCByIndex(0));
Serial.print("Outhouse: ");
Serial.println(sensor_outhouse.getTempCByIndex(0));
}

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