diff --git a/1 Подключение железок.md b/1 Подключение железок.md new file mode 100644 index 0000000..3647c44 --- /dev/null +++ b/1 Подключение железок.md @@ -0,0 +1,21 @@ +В проекте я использовала клон Arduino Nano: **ATmega328P** c USB-mini портом. + +В качестве датчика температуры и влажности клон SHT31: на маркетплейсе он был +обозначен как "**SHT31-D**", на плате указано "**SHT3X**". + +Эти две платы необходимо соединить по следующим пинам: + + +|SHT31 | -> | Arduino Nano| +|------|------|--------------| +|Vin |-> | 3V3 | +|GND |-> |GND | +| SCL |-> |A4 | +|SDA |-> |A5 | + +Датчик также работал и при подключении Vin -> +5V, но его работа была +нестабильной и он выдавал повышенные показания. + +Также столкнулась с тем, что плата работает стабильнее при прямом подключении в +USB-порт компьютера, а не через USB-хаб. + diff --git a/2 Прошивка arduino.md b/2 Прошивка arduino.md new file mode 100644 index 0000000..0eb1bfc --- /dev/null +++ b/2 Прошивка arduino.md @@ -0,0 +1,83 @@ +**2. Прошивка Arduino nano** + +В каталоге *arduino* лежит файлы для прошивки arduino nano (ATmega328P). + +Для прошивки: устанавила Arduino IDE (из AUR) + +**yay -S --aur arduino-ide-bin ** + +и пакет для доступа к ней через терминал: + +**sudo pacman -S arduino** + +Разрешаем текущему пользователю доступ к последовательным портам (и +соответсвующим lock файлам) : + +**sudo usermod -a -G uucp $USER sudo usermod -a -G lock $USER** + +Так как при каждом перетыкивании платы в USB-порт linux увеличивает его +значение (USB0, затем USB1, USB2... и т.д.), я добавила правило для именования +порта для arduino, то есть чтобы порт всегда назывался одинаково +("/dev/arduino") и всегда имел права 666: + +выполняем в терминале: + +**lsusb ** + +ищем в нём нашу ардуинку: должно быть что-то вроде: + +*Bus 001 Device 003: **ID** **1a86:7523** QinHeng Electronics CH340 serial +converter* + +запоминаем полученный **ID**! + +выполняем команды: + +**sudo nano /etc/udev/rules.d/99-arduino.rules** + +вставляем код (замените ID **1a86:7523** на ваши, если плата отличается) + +SUBSYSTEM=="tty", ATTRS{idVendor}=="**1a86**", ATTRS{idProduct}=="**7523**", +SYMLINK+="arduino", MODE="0666" + +Выполняем запись и выходим: жмём **Ctrl+O**, затем **Ctrl+X**. + +применяем правило: + +**sudo udevadm control --reload-rules && sudo udevadm trigger** + +проверяем: + +** ls -l /dev/arduino** + +должно вывести примерно так: + +*lrwxrwxrwx 1 root root 7 фев 21 15:54 /dev/arduino -> ttyUSB0* + +**Запускаем Arduino IDE:** + +в **Менеджере плат** (кнопка слева) ищем и устанавливаем: ***Arduino AVR Boards*, ** + +затем (кнопка ниже) ищем и устанавливаем библиотеку: **Adafruit SHT31 Library**. + +Теперь надо **выбрать модель платы**: Инструменты -> Плата -> Менеджер плат -> +Arduino AVR Boards - **Arduino Nano** + +**Выбрать порт**: Инструменты -> Серийный порт: **/dev/tty/USB0** (обычно arduino +IDE сама определяет нужный порт, просто тыкаем в него) + +**Выбираем загрузчик**: Инструменты -> Processor -> **Atmega328P (Old bootloader)** + +Теперь всё должно быть готов для прошивки: вставляем код **sketch_hum_temp.ino **и жмем на кнопку слева (->) "Загрузить на плату". В случае успеха :) ошибок быть не должно и прошивка загрузиться, всё замигает красный светодиод и перестанет - значит данные отправляются в порт USB. + +Для проверки, что данные приходят: или в Arduino IDE тыкаем кнопку "Монитор +порта" (изображена в виде лупы вверху слева)). , +или в терминале вводим: **cat +/dev/arduino** + +должно будет вывести сообщения инициализации датчика и отправлять данные о +температуре и влажности каждые 30 секунд. + +если всё OK, тогда жмем **Ctrl+С** чтобы прервать чтение из порта, закрываем +терминал и закрываем IDE (чтобы освободить порт arduino) + diff --git a/3 Подготовка Десклета.md b/3 Подготовка Десклета.md new file mode 100644 index 0000000..487e284 --- /dev/null +++ b/3 Подготовка Десклета.md @@ -0,0 +1,24 @@ +**3.Декслет для показа данных о температуры и влажности на рабочем столе Cinnamon** + +Он довольно примитивный, при желании вы можете перенастроить его "под себя". + +В текущей версии он показывает температуру и влажность, а также время получения +этих данных (обновляется каждые 30 секунд). + +Для наглядности в декслет добавлены смайлики: + +смайлик довольный, если влажность в пределах нормы: от 40% до 60%. + +смайлик довольный, если температура в пределах комфортной: от 22С до 27С. + +**Установка**. + +Установка заключается в двух действиях: + + скопировать из проекта папку **home-meteo@lina** в папку по адресу: + + **/home/*имя вашего пользователя*/.local/share/cinnamon/desklets** + +после этого на рабочем столе кликенете правой кнопкой мыши "**добавить декслет**", выбрать из списка +**Home Meteo** *Домашняя метеостанция*, нажать "+" для запуска. + diff --git a/README.md b/README.md index dc14c24..60d017d 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,15 @@ # Home-meteo -Мини домашная метеостанция на базе Arduion Nano + датчик SHT3X (SHT30-D) и Arch linux Cinnamon \ No newline at end of file +Мини домашная метеостанция на базе Arduin Nano + SHT31 (SHT31-D) и Arch linux +Cinnamon. + +![Скриншот 1](images/screenshot1.png) + +![Скриншот 2](images/screenshot2.png) + +[1 Подключение железок.md](README_files/1%20Подключение%20железок.md) + +[2 Прошивка arduino.md](README_files/2%20Прошивка%20arduino.md) + +[3 Подготовка Десклета.md](README_files/3%20Подготовка%20Десклета.md) + diff --git a/README_files/1 Подключение железок.md b/README_files/1 Подключение железок.md new file mode 100644 index 0000000..3647c44 --- /dev/null +++ b/README_files/1 Подключение железок.md @@ -0,0 +1,21 @@ +В проекте я использовала клон Arduino Nano: **ATmega328P** c USB-mini портом. + +В качестве датчика температуры и влажности клон SHT31: на маркетплейсе он был +обозначен как "**SHT31-D**", на плате указано "**SHT3X**". + +Эти две платы необходимо соединить по следующим пинам: + + +|SHT31 | -> | Arduino Nano| +|------|------|--------------| +|Vin |-> | 3V3 | +|GND |-> |GND | +| SCL |-> |A4 | +|SDA |-> |A5 | + +Датчик также работал и при подключении Vin -> +5V, но его работа была +нестабильной и он выдавал повышенные показания. + +Также столкнулась с тем, что плата работает стабильнее при прямом подключении в +USB-порт компьютера, а не через USB-хаб. + diff --git a/README_files/2 Прошивка arduino.md b/README_files/2 Прошивка arduino.md new file mode 100644 index 0000000..0eb1bfc --- /dev/null +++ b/README_files/2 Прошивка arduino.md @@ -0,0 +1,83 @@ +**2. Прошивка Arduino nano** + +В каталоге *arduino* лежит файлы для прошивки arduino nano (ATmega328P). + +Для прошивки: устанавила Arduino IDE (из AUR) + +**yay -S --aur arduino-ide-bin ** + +и пакет для доступа к ней через терминал: + +**sudo pacman -S arduino** + +Разрешаем текущему пользователю доступ к последовательным портам (и +соответсвующим lock файлам) : + +**sudo usermod -a -G uucp $USER sudo usermod -a -G lock $USER** + +Так как при каждом перетыкивании платы в USB-порт linux увеличивает его +значение (USB0, затем USB1, USB2... и т.д.), я добавила правило для именования +порта для arduino, то есть чтобы порт всегда назывался одинаково +("/dev/arduino") и всегда имел права 666: + +выполняем в терминале: + +**lsusb ** + +ищем в нём нашу ардуинку: должно быть что-то вроде: + +*Bus 001 Device 003: **ID** **1a86:7523** QinHeng Electronics CH340 serial +converter* + +запоминаем полученный **ID**! + +выполняем команды: + +**sudo nano /etc/udev/rules.d/99-arduino.rules** + +вставляем код (замените ID **1a86:7523** на ваши, если плата отличается) + +SUBSYSTEM=="tty", ATTRS{idVendor}=="**1a86**", ATTRS{idProduct}=="**7523**", +SYMLINK+="arduino", MODE="0666" + +Выполняем запись и выходим: жмём **Ctrl+O**, затем **Ctrl+X**. + +применяем правило: + +**sudo udevadm control --reload-rules && sudo udevadm trigger** + +проверяем: + +** ls -l /dev/arduino** + +должно вывести примерно так: + +*lrwxrwxrwx 1 root root 7 фев 21 15:54 /dev/arduino -> ttyUSB0* + +**Запускаем Arduino IDE:** + +в **Менеджере плат** (кнопка слева) ищем и устанавливаем: ***Arduino AVR Boards*, ** + +затем (кнопка ниже) ищем и устанавливаем библиотеку: **Adafruit SHT31 Library**. + +Теперь надо **выбрать модель платы**: Инструменты -> Плата -> Менеджер плат -> +Arduino AVR Boards - **Arduino Nano** + +**Выбрать порт**: Инструменты -> Серийный порт: **/dev/tty/USB0** (обычно arduino +IDE сама определяет нужный порт, просто тыкаем в него) + +**Выбираем загрузчик**: Инструменты -> Processor -> **Atmega328P (Old bootloader)** + +Теперь всё должно быть готов для прошивки: вставляем код **sketch_hum_temp.ino **и жмем на кнопку слева (->) "Загрузить на плату". В случае успеха :) ошибок быть не должно и прошивка загрузиться, всё замигает красный светодиод и перестанет - значит данные отправляются в порт USB. + +Для проверки, что данные приходят: или в Arduino IDE тыкаем кнопку "Монитор +порта" (изображена в виде лупы вверху слева)). , +или в терминале вводим: **cat +/dev/arduino** + +должно будет вывести сообщения инициализации датчика и отправлять данные о +температуре и влажности каждые 30 секунд. + +если всё OK, тогда жмем **Ctrl+С** чтобы прервать чтение из порта, закрываем +терминал и закрываем IDE (чтобы освободить порт arduino) + diff --git a/README_files/3 Подготовка Десклета.md b/README_files/3 Подготовка Десклета.md new file mode 100644 index 0000000..487e284 --- /dev/null +++ b/README_files/3 Подготовка Десклета.md @@ -0,0 +1,24 @@ +**3.Декслет для показа данных о температуры и влажности на рабочем столе Cinnamon** + +Он довольно примитивный, при желании вы можете перенастроить его "под себя". + +В текущей версии он показывает температуру и влажность, а также время получения +этих данных (обновляется каждые 30 секунд). + +Для наглядности в декслет добавлены смайлики: + +смайлик довольный, если влажность в пределах нормы: от 40% до 60%. + +смайлик довольный, если температура в пределах комфортной: от 22С до 27С. + +**Установка**. + +Установка заключается в двух действиях: + + скопировать из проекта папку **home-meteo@lina** в папку по адресу: + + **/home/*имя вашего пользователя*/.local/share/cinnamon/desklets** + +после этого на рабочем столе кликенете правой кнопкой мыши "**добавить декслет**", выбрать из списка +**Home Meteo** *Домашняя метеостанция*, нажать "+" для запуска. + diff --git a/arduino/libraries/Adafruit_BusIO/Adafruit_BusIO_Register.cpp b/arduino/libraries/Adafruit_BusIO/Adafruit_BusIO_Register.cpp new file mode 100644 index 0000000..f3e8187 --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/Adafruit_BusIO_Register.cpp @@ -0,0 +1,384 @@ +#include + +#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 Create a register we access over a GenericDevice + * @param genericdevice Generic device to use + * @param reg_addr Register address we will read/write + * @param width Width of the register in bytes (1-4) + * @param byteorder Byte order of register data (LSBFIRST or MSBFIRST) + * @param address_width Width of the register address in bytes (1 or 2) + */ +Adafruit_BusIO_Register::Adafruit_BusIO_Register( + Adafruit_GenericDevice *genericdevice, uint16_t reg_addr, uint8_t width, + uint8_t byteorder, uint8_t address_width) { + _i2cdevice = nullptr; + _spidevice = nullptr; + _genericdevice = genericdevice; + _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); + } + if (_genericdevice) { + return _genericdevice->writeRegister(addrbuffer, _addrwidth, buffer, len); + } + 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 number of bytes from a register into a buffer + @param buffer Buffer to read data into + @param len Number of bytes to read into the buffer + @return true on successful read, otherwise false +*/ +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); + } + if (_genericdevice) { + return _genericdevice->readRegister(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 diff --git a/arduino/libraries/Adafruit_BusIO/Adafruit_BusIO_Register.h b/arduino/libraries/Adafruit_BusIO/Adafruit_BusIO_Register.h new file mode 100644 index 0000000..046e04c --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/Adafruit_BusIO_Register.h @@ -0,0 +1,117 @@ +#ifndef Adafruit_BusIO_Register_h +#define Adafruit_BusIO_Register_h + +#include + +#if !defined(SPI_INTERFACES_COUNT) || \ + (defined(SPI_INTERFACES_COUNT) && (SPI_INTERFACES_COUNT > 0)) + +#include +#include +#include + +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); + + Adafruit_BusIO_Register(Adafruit_GenericDevice *genericdevice, + 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); + +#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SERIAL) + void print(Stream *s = &Serial); + void println(Stream *s = &Serial); +#else + void print(Stream *s); + void println(Stream *s); +#endif + +private: + Adafruit_I2CDevice *_i2cdevice; + Adafruit_SPIDevice *_spidevice; + Adafruit_GenericDevice *_genericdevice; + 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 diff --git a/arduino/libraries/Adafruit_BusIO/Adafruit_GenericDevice.cpp b/arduino/libraries/Adafruit_BusIO/Adafruit_GenericDevice.cpp new file mode 100644 index 0000000..37f9cfd --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/Adafruit_GenericDevice.cpp @@ -0,0 +1,90 @@ +/* + Written with help by Claude! + https://claude.ai/chat/335f50b1-3dd8-435e-9139-57ec7ca26a3c (at this time + chats are not shareable :( +*/ + +#include "Adafruit_GenericDevice.h" + +/*! + * @brief Create a Generic device with the provided read/write functions + * @param obj Pointer to object instance + * @param read_func Function pointer for reading raw data + * @param write_func Function pointer for writing raw data + * @param readreg_func Function pointer for reading registers (optional) + * @param writereg_func Function pointer for writing registers (optional) */ +Adafruit_GenericDevice::Adafruit_GenericDevice( + void *obj, busio_genericdevice_read_t read_func, + busio_genericdevice_write_t write_func, + busio_genericdevice_readreg_t readreg_func, + busio_genericdevice_writereg_t writereg_func) { + _obj = obj; + _read_func = read_func; + _write_func = write_func; + _readreg_func = readreg_func; + _writereg_func = writereg_func; + _begun = false; +} + +/*! @brief Simple begin function (doesn't do much at this time) + @return true always +*/ +bool Adafruit_GenericDevice::begin(void) { + _begun = true; + return true; +} + +/*! +@brief Marks the GenericDevice as no longer in use. +@note: Since this is a GenericDevice, if you are using this with a Serial +object, this does NOT disable serial communication or release the RX/TX pins. +That must be done manually by calling Serial.end(). +*/ +void Adafruit_GenericDevice::end(void) { _begun = false; } + +/*! @brief Write a buffer of data + @param buffer Pointer to buffer of data to write + @param len Number of bytes to write + @return true if write was successful, otherwise false */ +bool Adafruit_GenericDevice::write(const uint8_t *buffer, size_t len) { + if (!_begun) + return false; + return _write_func(_obj, buffer, len); +} + +/*! @brief Read data into a buffer + @param buffer Pointer to buffer to read data into + @param len Number of bytes to read + @return true if read was successful, otherwise false */ +bool Adafruit_GenericDevice::read(uint8_t *buffer, size_t len) { + if (!_begun) + return false; + return _read_func(_obj, buffer, len); +} + +/*! @brief Read from a register location + @param addr_buf Buffer containing register address + @param addrsiz Size of register address in bytes + @param buf Buffer to store read data + @param bufsiz Size of data to read in bytes + @return true if read was successful, otherwise false */ +bool Adafruit_GenericDevice::readRegister(uint8_t *addr_buf, uint8_t addrsiz, + uint8_t *buf, uint16_t bufsiz) { + if (!_begun || !_readreg_func) + return false; + return _readreg_func(_obj, addr_buf, addrsiz, buf, bufsiz); +} + +/*! @brief Write to a register location + @param addr_buf Buffer containing register address + @param addrsiz Size of register address in bytes + @param buf Buffer containing data to write + @param bufsiz Size of data to write in bytes + @return true if write was successful, otherwise false */ +bool Adafruit_GenericDevice::writeRegister(uint8_t *addr_buf, uint8_t addrsiz, + const uint8_t *buf, + uint16_t bufsiz) { + if (!_begun || !_writereg_func) + return false; + return _writereg_func(_obj, addr_buf, addrsiz, buf, bufsiz); +} diff --git a/arduino/libraries/Adafruit_BusIO/Adafruit_GenericDevice.h b/arduino/libraries/Adafruit_BusIO/Adafruit_GenericDevice.h new file mode 100644 index 0000000..d5cb326 --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/Adafruit_GenericDevice.h @@ -0,0 +1,56 @@ +#ifndef ADAFRUIT_GENERICDEVICE_H +#define ADAFRUIT_GENERICDEVICE_H + +#include + +typedef bool (*busio_genericdevice_read_t)(void *obj, uint8_t *buffer, + size_t len); +typedef bool (*busio_genericdevice_write_t)(void *obj, const uint8_t *buffer, + size_t len); +typedef bool (*busio_genericdevice_readreg_t)(void *obj, uint8_t *addr_buf, + uint8_t addrsiz, uint8_t *data, + uint16_t datalen); +typedef bool (*busio_genericdevice_writereg_t)(void *obj, uint8_t *addr_buf, + uint8_t addrsiz, + const uint8_t *data, + uint16_t datalen); + +/*! + * @brief Class for communicating with a device via generic read/write functions + */ +class Adafruit_GenericDevice { +public: + Adafruit_GenericDevice( + void *obj, busio_genericdevice_read_t read_func, + busio_genericdevice_write_t write_func, + busio_genericdevice_readreg_t readreg_func = nullptr, + busio_genericdevice_writereg_t writereg_func = nullptr); + + bool begin(void); + void end(void); + + bool read(uint8_t *buffer, size_t len); + bool write(const uint8_t *buffer, size_t len); + bool readRegister(uint8_t *addr_buf, uint8_t addrsiz, uint8_t *buf, + uint16_t bufsiz); + bool writeRegister(uint8_t *addr_buf, uint8_t addrsiz, const uint8_t *buf, + uint16_t bufsiz); + +protected: + /*! @brief Function pointer for reading raw data from the device */ + busio_genericdevice_read_t _read_func; + /*! @brief Function pointer for writing raw data to the device */ + busio_genericdevice_write_t _write_func; + /*! @brief Function pointer for reading a 'register' from the device */ + busio_genericdevice_readreg_t _readreg_func; + /*! @brief Function pointer for writing a 'register' to the device */ + busio_genericdevice_writereg_t _writereg_func; + + bool _begun; ///< whether we have initialized yet (in case the function needs + ///< to do something) + +private: + void *_obj; ///< Pointer to object instance +}; + +#endif // ADAFRUIT_GENERICDEVICE_H diff --git a/arduino/libraries/Adafruit_BusIO/Adafruit_I2CDevice.cpp b/arduino/libraries/Adafruit_BusIO/Adafruit_I2CDevice.cpp new file mode 100644 index 0000000..2633cf1 --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/Adafruit_I2CDevice.cpp @@ -0,0 +1,320 @@ +#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, HEX); +#endif +#ifdef ARDUINO_ARCH_MBED + _wire->write(0); // forces a write request instead of a read +#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 +} diff --git a/arduino/libraries/Adafruit_BusIO/Adafruit_I2CDevice.h b/arduino/libraries/Adafruit_BusIO/Adafruit_I2CDevice.h new file mode 100644 index 0000000..6bda7ba --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/Adafruit_I2CDevice.h @@ -0,0 +1,36 @@ +#ifndef Adafruit_I2CDevice_h +#define Adafruit_I2CDevice_h + +#include +#include + +///< 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 diff --git a/arduino/libraries/Adafruit_BusIO/Adafruit_I2CRegister.h b/arduino/libraries/Adafruit_BusIO/Adafruit_I2CRegister.h new file mode 100644 index 0000000..186850f --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/Adafruit_I2CRegister.h @@ -0,0 +1,10 @@ +#ifndef _ADAFRUIT_I2C_REGISTER_H_ +#define _ADAFRUIT_I2C_REGISTER_H_ + +#include +#include + +typedef Adafruit_BusIO_Register Adafruit_I2CRegister; +typedef Adafruit_BusIO_RegisterBits Adafruit_I2CRegisterBits; + +#endif diff --git a/arduino/libraries/Adafruit_BusIO/Adafruit_SPIDevice.cpp b/arduino/libraries/Adafruit_BusIO/Adafruit_SPIDevice.cpp new file mode 100644 index 0000000..3283de6 --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/Adafruit_SPIDevice.cpp @@ -0,0 +1,512 @@ +#include "Adafruit_SPIDevice.h" + +// #define DEBUG_SERIAL Serial + +#ifdef BUSIO_USE_FAST_PINIO +#define BUSIO_SET_CLOCK_LOW() (*clkPort = *clkPort & ~clkPinMask) +#define BUSIO_SET_CLOCK_HIGH() (*clkPort = *clkPort | clkPinMask) +#define BUSIO_READ_MISO() (*misoPort & misoPinMask) +#define BUSIO_WRITE_MOSI(value) \ + do { \ + if (value) \ + *mosiPort = *mosiPort | mosiPinMask; \ + else \ + *mosiPort = *mosiPort & ~mosiPinMask; \ + } while (0) +#else +#define BUSIO_SET_CLOCK_LOW() digitalWrite(_sck, LOW) +#define BUSIO_SET_CLOCK_HIGH() digitalWrite(_sck, HIGH) +#define BUSIO_READ_MISO() digitalRead(_miso) +#define BUSIO_WRITE_MOSI(value) digitalWrite(_mosi, value) +#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 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)) { + BUSIO_WRITE_MOSI(towrite); + lastmosi = towrite; + } + + BUSIO_SET_CLOCK_HIGH(); + + if (bitdelay_us) { + delayMicroseconds(bitdelay_us); + } + + if (_miso != -1) { + if (BUSIO_READ_MISO()) + reply |= b; + } + + BUSIO_SET_CLOCK_LOW(); + + } else if (_dataMode == SPI_MODE3) { + + if (_mosi != -1) { // transmit on falling edge + BUSIO_WRITE_MOSI(send & b); + } + + BUSIO_SET_CLOCK_LOW(); + + if (bitdelay_us) { + delayMicroseconds(bitdelay_us); + } + + BUSIO_SET_CLOCK_HIGH(); + + if (bitdelay_us) { + delayMicroseconds(bitdelay_us); + } + + if (_miso != -1) { // read on rising edge + if (BUSIO_READ_MISO()) { + reply |= b; + } + } + + } else { // || _dataMode == SPI_MODE1) + + BUSIO_SET_CLOCK_HIGH(); + + if (bitdelay_us) { + delayMicroseconds(bitdelay_us); + } + + if (_mosi != -1) { + BUSIO_WRITE_MOSI(send & b); + } + + BUSIO_SET_CLOCK_LOW(); + + if (_miso != -1) { + if (BUSIO_READ_MISO()) { + 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; +} diff --git a/arduino/libraries/Adafruit_BusIO/Adafruit_SPIDevice.h b/arduino/libraries/Adafruit_BusIO/Adafruit_SPIDevice.h new file mode 100644 index 0000000..82a0281 --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/Adafruit_SPIDevice.h @@ -0,0 +1,149 @@ +#ifndef Adafruit_SPIDevice_h +#define Adafruit_SPIDevice_h + +#include + +#if !defined(SPI_INTERFACES_COUNT) || \ + (defined(SPI_INTERFACES_COUNT) && (SPI_INTERFACES_COUNT > 0)) +// HW SPI available +#include +#define BUSIO_HAS_HW_SPI +#else +// SW SPI ONLY +enum { SPI_MODE0, SPI_MODE1, SPI_MODE2, SPI_MODE3 }; +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) + +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(__MBED__) || defined(__ZEPHYR__) +// Boards based on RTOS cores like mbed or Zephyr are not going to expose the +// low level registers needed for fast pin manipulation +#undef 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_RP2040) && !defined(ARDUINO_SILABS) && \ + !defined(ARDUINO_UNOR4_MINIMA) && !defined(ARDUINO_UNOR4_WIFI) && \ + !defined(PORTDUINO) +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 diff --git a/arduino/libraries/Adafruit_BusIO/CMakeLists.txt b/arduino/libraries/Adafruit_BusIO/CMakeLists.txt new file mode 100644 index 0000000..e45fa69 --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/CMakeLists.txt @@ -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" "Adafruit_GenericDevice.cpp" + INCLUDE_DIRS "." + REQUIRES arduino-esp32) + +project(Adafruit_BusIO) diff --git a/arduino/libraries/Adafruit_BusIO/LICENSE b/arduino/libraries/Adafruit_BusIO/LICENSE new file mode 100644 index 0000000..860e3e2 --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/LICENSE @@ -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. \ No newline at end of file diff --git a/arduino/libraries/Adafruit_BusIO/README.md b/arduino/libraries/Adafruit_BusIO/README.md new file mode 100644 index 0000000..59712ff --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/README.md @@ -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, and 'generic transport' (e.g. UART) 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 diff --git a/arduino/libraries/Adafruit_BusIO/component.mk b/arduino/libraries/Adafruit_BusIO/component.mk new file mode 100644 index 0000000..004b18e --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/component.mk @@ -0,0 +1 @@ +COMPONENT_ADD_INCLUDEDIRS = . diff --git a/arduino/libraries/Adafruit_BusIO/examples/genericdevice_uartregtest/genericdevice_uartregtest.ino b/arduino/libraries/Adafruit_BusIO/examples/genericdevice_uartregtest/genericdevice_uartregtest.ino new file mode 100644 index 0000000..c99b72a --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/examples/genericdevice_uartregtest/genericdevice_uartregtest.ino @@ -0,0 +1,219 @@ +/* + Advanced example of using bstracted transport for reading and writing + register data from a UART-based device such as a TMC2209 + + Written with help by Claude! + https://claude.ai/chat/335f50b1-3dd8-435e-9139-57ec7ca26a3c (at this time + chats are not shareable :( +*/ + +#include "Adafruit_BusIO_Register.h" +#include "Adafruit_GenericDevice.h" + +// Debugging macros +#define DEBUG_SERIAL Serial + +#ifdef DEBUG_SERIAL +#define DEBUG_PRINT(x) DEBUG_SERIAL.print(x) +#define DEBUG_PRINTLN(x) DEBUG_SERIAL.println(x) +#define DEBUG_PRINT_HEX(x) \ + do { \ + if (x < 0x10) \ + DEBUG_SERIAL.print('0'); \ + DEBUG_SERIAL.print(x, HEX); \ + DEBUG_SERIAL.print(' '); \ + } while (0) +#else +#define DEBUG_PRINT(x) +#define DEBUG_PRINTLN(x) +#define DEBUG_PRINT_HEX(x) +#endif + +#define TMC2209_IOIN 0x06 + +class TMC2209_UART { +private: + Stream *_uart_stream; + uint8_t _addr; + + static bool uart_read(void *thiz, uint8_t *buffer, size_t len) { + TMC2209_UART *dev = (TMC2209_UART *)thiz; + uint16_t timeout = 100; + while (dev->_uart_stream->available() < len && timeout--) { + delay(1); + } + if (timeout == 0) { + DEBUG_PRINTLN("Read timeout!"); + return false; + } + + DEBUG_PRINT("Reading: "); + for (size_t i = 0; i < len; i++) { + buffer[i] = dev->_uart_stream->read(); + DEBUG_PRINT_HEX(buffer[i]); + } + DEBUG_PRINTLN(""); + + return true; + } + + static bool uart_write(void *thiz, const uint8_t *buffer, size_t len) { + TMC2209_UART *dev = (TMC2209_UART *)thiz; + DEBUG_PRINT("Writing: "); + for (size_t i = 0; i < len; i++) { + DEBUG_PRINT_HEX(buffer[i]); + } + DEBUG_PRINTLN(""); + + dev->_uart_stream->write(buffer, len); + return true; + } + + static bool uart_readreg(void *thiz, uint8_t *addr_buf, uint8_t addrsiz, + uint8_t *data, uint16_t datalen) { + TMC2209_UART *dev = (TMC2209_UART *)thiz; + while (dev->_uart_stream->available()) + dev->_uart_stream->read(); + + uint8_t packet[4] = {0x05, uint8_t(dev->_addr << 1), addr_buf[0], 0x00}; + + packet[3] = calcCRC(packet, 3); + if (!uart_write(thiz, packet, 4)) + return false; + + // Read back echo + uint8_t echo[4]; + if (!uart_read(thiz, echo, 4)) + return false; + + // Verify echo + for (uint8_t i = 0; i < 4; i++) { + if (echo[i] != packet[i]) { + DEBUG_PRINTLN("Echo mismatch"); + return false; + } + } + + uint8_t response[8]; // sync + 0xFF + reg + 4 data bytes + CRC + if (!uart_read(thiz, response, 8)) + return false; + + // Verify response + if (response[0] != 0x05) { + DEBUG_PRINTLN("Invalid sync byte"); + return false; + } + + if (response[1] != 0xFF) { + DEBUG_PRINTLN("Invalid reply address"); + return false; + } + + if (response[2] != addr_buf[0]) { + DEBUG_PRINTLN("Register mismatch"); + return false; + } + + uint8_t crc = calcCRC(response, 7); + if (crc != response[7]) { + DEBUG_PRINTLN("CRC mismatch"); + return false; + } + + memcpy(data, &response[3], 4); + return true; + } + + static bool uart_writereg(void *thiz, uint8_t *addr_buf, uint8_t addrsiz, + const uint8_t *data, uint16_t datalen) { + TMC2209_UART *dev = (TMC2209_UART *)thiz; + while (dev->_uart_stream->available()) + dev->_uart_stream->read(); + + uint8_t packet[8] = {0x05, + uint8_t(dev->_addr << 1), + uint8_t(addr_buf[0] | 0x80), + data[0], + data[1], + data[2], + data[3], + 0x00}; + + packet[7] = calcCRC(packet, 7); + if (!uart_write(thiz, packet, 8)) + return false; + + uint8_t echo[8]; + if (!uart_read(thiz, echo, 8)) + return false; + + for (uint8_t i = 0; i < 8; i++) { + if (echo[i] != packet[i]) { + DEBUG_PRINTLN("Write echo mismatch"); + return false; + } + } + + return true; + } + + static uint8_t calcCRC(uint8_t *data, uint8_t length) { + uint8_t crc = 0; + for (uint8_t i = 0; i < length; i++) { + uint8_t currentByte = data[i]; + for (uint8_t j = 0; j < 8; j++) { + if ((crc >> 7) ^ (currentByte & 0x01)) { + crc = (crc << 1) ^ 0x07; + } else { + crc = crc << 1; + } + currentByte = currentByte >> 1; + } + } + return crc; + } + +public: + TMC2209_UART(Stream *serial, uint8_t addr) + : _uart_stream(serial), _addr(addr) {} + + Adafruit_GenericDevice *createDevice() { + return new Adafruit_GenericDevice(this, uart_read, uart_write, uart_readreg, + uart_writereg); + } +}; + +void setup() { + Serial.begin(115200); + while (!Serial) + ; + delay(100); + Serial.println("TMC2209 Generic Device register read/write test!"); + + Serial1.begin(115200); + + TMC2209_UART uart(&Serial1, 0); + Adafruit_GenericDevice *device = uart.createDevice(); + device->begin(); + + // Create register object for IOIN + Adafruit_BusIO_Register ioin_reg(device, + TMC2209_IOIN, // device and register address + 4, // width = 4 bytes + MSBFIRST, // byte order + 1); // address width = 1 byte + Serial.print("IOIN = 0x"); + Serial.println(ioin_reg.read(), HEX); + + // Create RegisterBits for VERSION field (bits 31:24) + Adafruit_BusIO_RegisterBits version_bits( + &ioin_reg, 8, 24); // 8 bits wide, starting at bit 24 + + Serial.println("Reading VERSION..."); + uint8_t version = version_bits.read(); + + Serial.print("VERSION = 0x"); + Serial.println(version, HEX); +} + +void loop() { delay(1000); } \ No newline at end of file diff --git a/arduino/libraries/Adafruit_BusIO/examples/genericdevice_uarttest/genericdevice_uarttest.ino b/arduino/libraries/Adafruit_BusIO/examples/genericdevice_uarttest/genericdevice_uarttest.ino new file mode 100644 index 0000000..3989b6f --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/examples/genericdevice_uarttest/genericdevice_uarttest.ino @@ -0,0 +1,98 @@ +/* + Abstracted transport for reading and writing data from a UART-based + device such as a TMC2209 + + Written with help by Claude! + https://claude.ai/chat/335f50b1-3dd8-435e-9139-57ec7ca26a3c (at this time + chats are not shareable :( +*/ + +#include "Adafruit_GenericDevice.h" + +/** + * Basic UART device class that demonstrates using GenericDevice with a Stream + * interface. This example shows how to wrap a Stream (like HardwareSerial or + * SoftwareSerial) with read/write callbacks that can be used by BusIO's + * register functions. + */ +class UARTDevice { +public: + UARTDevice(Stream *serial) : _serial(serial) {} + + // Static callback for writing data to UART + // Called by GenericDevice when data needs to be sent + static bool uart_write(void *thiz, const uint8_t *buffer, size_t len) { + UARTDevice *dev = (UARTDevice *)thiz; + dev->_serial->write(buffer, len); + return true; + } + + // Static callback for reading data from UART + // Includes timeout and will return false if not enough data available + static bool uart_read(void *thiz, uint8_t *buffer, size_t len) { + UARTDevice *dev = (UARTDevice *)thiz; + uint16_t timeout = 100; + while (dev->_serial->available() < len && timeout--) { + delay(1); + } + if (timeout == 0) { + return false; + } + for (size_t i = 0; i < len; i++) { + buffer[i] = dev->_serial->read(); + } + return true; + } + + // Create a GenericDevice instance using our callbacks + Adafruit_GenericDevice *createDevice() { + return new Adafruit_GenericDevice(this, uart_read, uart_write); + } + +private: + Stream *_serial; // Underlying Stream instance (HardwareSerial, etc) +}; + +void setup() { + Serial.begin(115200); + while (!Serial) + ; + delay(100); + + Serial.println("Generic Device test!"); + + // Initialize UART for device communication + Serial1.begin(115200); + + // Create UART wrapper and BusIO device + UARTDevice uart(&Serial1); + Adafruit_GenericDevice *device = uart.createDevice(); + device->begin(); + + // Test write/read cycle + uint8_t write_buf[4] = {0x5, 0x0, 0x0, 0x48}; + uint8_t read_buf[8]; + + Serial.println("Writing data..."); + if (!device->write(write_buf, 4)) { + Serial.println("Write failed!"); + return; + } + + Serial.println("Reading response..."); + if (!device->read(read_buf, 8)) { + Serial.println("Read failed!"); + return; + } + + // Print response bytes + Serial.print("Got response: "); + for (int i = 0; i < 8; i++) { + Serial.print("0x"); + Serial.print(read_buf[i], HEX); + Serial.print(" "); + } + Serial.println(); +} + +void loop() { delay(1000); } \ No newline at end of file diff --git a/arduino/libraries/Adafruit_BusIO/examples/i2c_address_detect/i2c_address_detect.ino b/arduino/libraries/Adafruit_BusIO/examples/i2c_address_detect/i2c_address_detect.ino new file mode 100644 index 0000000..f2e6ba7 --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/examples/i2c_address_detect/i2c_address_detect.ino @@ -0,0 +1,22 @@ +#include + +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() {} diff --git a/arduino/libraries/Adafruit_BusIO/examples/i2c_readwrite/i2c_readwrite.ino b/arduino/libraries/Adafruit_BusIO/examples/i2c_readwrite/i2c_readwrite.ino new file mode 100644 index 0000000..4ac2626 --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/examples/i2c_readwrite/i2c_readwrite.ino @@ -0,0 +1,45 @@ +#include + +#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() {} diff --git a/arduino/libraries/Adafruit_BusIO/examples/i2c_registers/i2c_registers.ino b/arduino/libraries/Adafruit_BusIO/examples/i2c_registers/i2c_registers.ino new file mode 100644 index 0000000..2d44c83 --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/examples/i2c_registers/i2c_registers.ino @@ -0,0 +1,43 @@ +#include +#include + +#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() {} \ No newline at end of file diff --git a/arduino/libraries/Adafruit_BusIO/examples/i2corspi_register/i2corspi_register.ino b/arduino/libraries/Adafruit_BusIO/examples/i2corspi_register/i2corspi_register.ino new file mode 100644 index 0000000..be04606 --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/examples/i2corspi_register/i2corspi_register.ino @@ -0,0 +1,40 @@ +#include + +// 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() {} diff --git a/arduino/libraries/Adafruit_BusIO/examples/spi_modetest/spi_modetest.ino b/arduino/libraries/Adafruit_BusIO/examples/spi_modetest/spi_modetest.ino new file mode 100644 index 0000000..ebf14f9 --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/examples/spi_modetest/spi_modetest.ino @@ -0,0 +1,35 @@ +#include + +#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); + } +} \ No newline at end of file diff --git a/arduino/libraries/Adafruit_BusIO/examples/spi_readwrite/spi_readwrite.ino b/arduino/libraries/Adafruit_BusIO/examples/spi_readwrite/spi_readwrite.ino new file mode 100644 index 0000000..4b9ecf1 --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/examples/spi_readwrite/spi_readwrite.ino @@ -0,0 +1,43 @@ +#include + +#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() {} diff --git a/arduino/libraries/Adafruit_BusIO/examples/spi_register_bits/spi_register_bits.ino b/arduino/libraries/Adafruit_BusIO/examples/spi_register_bits/spi_register_bits.ino new file mode 100644 index 0000000..d11b440 --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/examples/spi_register_bits/spi_register_bits.ino @@ -0,0 +1,268 @@ +/*************************************************** + + 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 +#include + +#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; +} diff --git a/arduino/libraries/Adafruit_BusIO/examples/spi_registers/spi_registers.ino b/arduino/libraries/Adafruit_BusIO/examples/spi_registers/spi_registers.ino new file mode 100644 index 0000000..af6069b --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/examples/spi_registers/spi_registers.ino @@ -0,0 +1,40 @@ +#include +#include + +#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() {} diff --git a/arduino/libraries/Adafruit_BusIO/library.properties b/arduino/libraries/Adafruit_BusIO/library.properties new file mode 100644 index 0000000..1615468 --- /dev/null +++ b/arduino/libraries/Adafruit_BusIO/library.properties @@ -0,0 +1,9 @@ +name=Adafruit BusIO +version=1.17.4 +author=Adafruit +maintainer=Adafruit +sentence=This is a library for abstracting away UART, I2C and SPI interfacing +paragraph=This is a library for abstracting away UART, I2C and SPI interfacing +category=Signal Input/Output +url=https://github.com/adafruit/Adafruit_BusIO +architectures=* diff --git a/arduino/libraries/Adafruit_SHT31_Library/Adafruit_SHT31.cpp b/arduino/libraries/Adafruit_SHT31_Library/Adafruit_SHT31.cpp new file mode 100644 index 0000000..0e5326e --- /dev/null +++ b/arduino/libraries/Adafruit_SHT31_Library/Adafruit_SHT31.cpp @@ -0,0 +1,245 @@ +/*! + * @file Adafruit_SHT31.cpp + * + * @mainpage Adafruit SHT31 Digital Humidity & Temp Sensor + * + * @section intro_sec Introduction + * + * This is a library for the SHT31 Digital Humidity & Temp Sensor + * + * Designed specifically to work with the SHT31 Digital sensor from Adafruit + * + * Pick one up today in the adafruit shop! + * ------> https://www.adafruit.com/product/2857 + * + * 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 andopen-source hardware by purchasing products + * from Adafruit! + * + * @section author Author + * + * Limor Fried/Ladyada (Adafruit Industries). + * + * @section license License + * + * BSD license, all text above must be included in any redistribution + */ + +#include "Adafruit_SHT31.h" + +/*! + * @brief SHT31 constructor using i2c + * @param *theWire + * optional wire + */ +Adafruit_SHT31::Adafruit_SHT31(TwoWire *theWire) { + _wire = theWire; + + humidity = NAN; + temp = NAN; +} + +/** + * Destructor to free memory in use. + */ +Adafruit_SHT31::~Adafruit_SHT31() { + if (i2c_dev) { + delete i2c_dev; // remove old interface + } +} + +/** + * Initialises the I2C bus, and assigns the I2C address to us. + * + * @param i2caddr The I2C address to use for the sensor. + * + * @return True if initialisation was successful, otherwise False. + */ +bool Adafruit_SHT31::begin(uint8_t i2caddr) { + if (i2c_dev) { + delete i2c_dev; // remove old interface + } + + i2c_dev = new Adafruit_I2CDevice(i2caddr, _wire); + + if (!i2c_dev->begin()) { + return false; + } + + reset(); + return readStatus() != 0xFFFF; +} + +/** + * Gets the current status register contents. + * + * @return The 16-bit status register. + */ +uint16_t Adafruit_SHT31::readStatus(void) { + writeCommand(SHT31_READSTATUS); + + uint8_t data[3]; + i2c_dev->read(data, 3); + + uint16_t stat = data[0]; + stat <<= 8; + stat |= data[1]; + // Serial.println(stat, HEX); + return stat; +} + +/** + * Performs a reset of the sensor to put it into a known state. + */ +void Adafruit_SHT31::reset(void) { + writeCommand(SHT31_SOFTRESET); + delay(10); +} + +/** + * Enables or disabled the heating element. + * + * @param h True to enable the heater, False to disable it. + */ +void Adafruit_SHT31::heater(bool h) { + if (h) + writeCommand(SHT31_HEATEREN); + else + writeCommand(SHT31_HEATERDIS); + delay(1); +} + +/*! + * @brief Return sensor heater state + * @return heater state (TRUE = enabled, FALSE = disabled) + */ +bool Adafruit_SHT31::isHeaterEnabled() { + uint16_t regValue = readStatus(); + return (bool)bitRead(regValue, SHT31_REG_HEATER_BIT); +} + +/** + * Gets a single temperature reading from the sensor. + * + * @return A float value indicating the temperature. + */ +float Adafruit_SHT31::readTemperature(void) { + if (!readTempHum()) + return NAN; + + return temp; +} + +/** + * Gets a single relative humidity reading from the sensor. + * + * @return A float value representing relative humidity. + */ +float Adafruit_SHT31::readHumidity(void) { + if (!readTempHum()) + return NAN; + + return humidity; +} + +/** + * Gets a reading of both temperature and relative humidity from the sensor. + * + * @param temperature_out Where to write the temperature float. + * @param humidity_out Where to write the relative humidity float. + * @return True if the read was successful, false otherwise + */ +bool Adafruit_SHT31::readBoth(float *temperature_out, float *humidity_out) { + if (!readTempHum()) { + *temperature_out = *humidity_out = NAN; + return false; + } + + *temperature_out = temp; + *humidity_out = humidity; + return true; +} + +/** + * Performs a CRC8 calculation on the supplied values. + * + * @param data Pointer to the data to use when calculating the CRC8. + * @param len The number of bytes in 'data'. + * + * @return The computed CRC8 value. + */ +static uint8_t crc8(const uint8_t *data, int len) { + /* + * + * CRC-8 formula from page 14 of SHT spec pdf + * + * Test data 0xBE, 0xEF should yield 0x92 + * + * Initialization data 0xFF + * Polynomial 0x31 (x8 + x5 +x4 +1) + * Final XOR 0x00 + */ + + const uint8_t POLYNOMIAL(0x31); + uint8_t crc(0xFF); + + for (int j = len; j; --j) { + crc ^= *data++; + + for (int i = 8; i; --i) { + crc = (crc & 0x80) ? (crc << 1) ^ POLYNOMIAL : (crc << 1); + } + } + return crc; +} + +/** + * Internal function to perform a temp + humidity read. + * + * @return True if successful, otherwise false. + */ +bool Adafruit_SHT31::readTempHum(void) { + uint8_t readbuffer[6]; + + if (!writeCommand(SHT31_MEAS_HIGHREP)) + return false; + + delay(20); + + if (!i2c_dev->read(readbuffer, sizeof(readbuffer))) + return false; + + if (readbuffer[2] != crc8(readbuffer, 2) || + readbuffer[5] != crc8(readbuffer + 3, 2)) + return false; + + int32_t stemp = (int32_t)(((uint32_t)readbuffer[0] << 8) | readbuffer[1]); + // simplified (65536 instead of 65535) integer version of: + // temp = (stemp * 175.0f) / 65535.0f - 45.0f; + stemp = ((4375 * stemp) >> 14) - 4500; + temp = (float)stemp / 100.0f; + + uint32_t shum = ((uint32_t)readbuffer[3] << 8) | readbuffer[4]; + // simplified (65536 instead of 65535) integer version of: + // humidity = (shum * 100.0f) / 65535.0f; + shum = (625 * shum) >> 12; + humidity = (float)shum / 100.0f; + + return true; +} + +/** + * Internal function to perform and I2C write. + * + * @param cmd The 16-bit command ID to send. + */ +bool Adafruit_SHT31::writeCommand(uint16_t command) { + uint8_t cmd[2]; + + cmd[0] = command >> 8; + cmd[1] = command & 0xFF; + + return i2c_dev->write(cmd, 2); +} diff --git a/arduino/libraries/Adafruit_SHT31_Library/Adafruit_SHT31.h b/arduino/libraries/Adafruit_SHT31_Library/Adafruit_SHT31.h new file mode 100644 index 0000000..a720e02 --- /dev/null +++ b/arduino/libraries/Adafruit_SHT31_Library/Adafruit_SHT31.h @@ -0,0 +1,84 @@ +/*! + * @file Adafruit_SHT31.h + * + * This is a library for the SHT31 Digital Humidity & Temp Sensor + * + * Designed specifically to work with the Digital Humidity & Temp Sensor + * -----> https://www.adafruit.com/product/2857 + * + * 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 andopen-source hardware by purchasing products + * from Adafruit! + * + * Limor Fried/Ladyada (Adafruit Industries). + * + * BSD license, all text above must be included in any redistribution + */ + +#ifndef ADAFRUIT_SHT31_H +#define ADAFRUIT_SHT31_H + +#include "Arduino.h" +#include + +#define SHT31_DEFAULT_ADDR 0x44 /**< SHT31 Default Address */ +#define SHT31_MEAS_HIGHREP_STRETCH \ + 0x2C06 /**< Measurement High Repeatability with Clock Stretch Enabled */ +#define SHT31_MEAS_MEDREP_STRETCH \ + 0x2C0D /**< Measurement Medium Repeatability with Clock Stretch Enabled */ +#define SHT31_MEAS_LOWREP_STRETCH \ + 0x2C10 /**< Measurement Low Repeatability with Clock Stretch Enabled*/ +#define SHT31_MEAS_HIGHREP \ + 0x2400 /**< Measurement High Repeatability with Clock Stretch Disabled */ +#define SHT31_MEAS_MEDREP \ + 0x240B /**< Measurement Medium Repeatability with Clock Stretch Disabled */ +#define SHT31_MEAS_LOWREP \ + 0x2416 /**< Measurement Low Repeatability with Clock Stretch Disabled */ +#define SHT31_READSTATUS 0xF32D /**< Read Out of Status Register */ +#define SHT31_CLEARSTATUS 0x3041 /**< Clear Status */ +#define SHT31_SOFTRESET 0x30A2 /**< Soft Reset */ +#define SHT31_HEATEREN 0x306D /**< Heater Enable */ +#define SHT31_HEATERDIS 0x3066 /**< Heater Disable */ +#define SHT31_REG_HEATER_BIT 0x0d /**< Status Register Heater Bit */ + +extern TwoWire Wire; /**< Forward declarations of Wire for board/variant + combinations that don't have a default 'Wire' */ + +/** + * Driver for the Adafruit SHT31-D Temperature and Humidity breakout board. + */ +class Adafruit_SHT31 { +public: + Adafruit_SHT31(TwoWire *theWire = &Wire); + ~Adafruit_SHT31(); + + bool begin(uint8_t i2caddr = SHT31_DEFAULT_ADDR); + float readTemperature(void); + float readHumidity(void); + bool readBoth(float *temperature_out, float *humidity_out); + uint16_t readStatus(void); + void reset(void); + void heater(bool h); + bool isHeaterEnabled(); + +private: + /** + * Placeholder to track humidity internally. + */ + float humidity; + + /** + * Placeholder to track temperature internally. + */ + float temp; + + bool readTempHum(void); + bool writeCommand(uint16_t cmd); + + TwoWire *_wire; /**< Wire object */ + Adafruit_I2CDevice *i2c_dev = NULL; ///< Pointer to I2C bus interface +}; + +#endif diff --git a/arduino/libraries/Adafruit_SHT31_Library/README.md b/arduino/libraries/Adafruit_SHT31_Library/README.md new file mode 100644 index 0000000..32504c5 --- /dev/null +++ b/arduino/libraries/Adafruit_SHT31_Library/README.md @@ -0,0 +1,26 @@ +# Adafruit SHT31-D Temperature and Humidity Sensor Breakout [![Build Status](https://github.com/adafruit/Adafruit_SHT31/workflows/Arduino%20Library%20CI/badge.svg)](https://github.com/adafruit/Adafruit_SHT31/actions)[![Documentation](https://github.com/adafruit/ci-arduino/blob/master/assets/doxygen_badge.svg)](http://adafruit.github.io/Adafruit_SHT31/html/index.html) + + + +This is a library for the SHT31 Digital Humidity + Temp sensor. + +It is designed specifically to work with the SHT31 Digital in the Adafruit shop: + +* https://www.adafruit.com/products/2857 + +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 + +Check out the links above for our tutorials and wiring diagrams + +## Installation + +Use the Arduino Library Manager to install this library. If you're unfamiliar +with how this works, we have a great tutorial on Arduino library installation +at: http://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use diff --git a/arduino/libraries/Adafruit_SHT31_Library/assets/board.jpg b/arduino/libraries/Adafruit_SHT31_Library/assets/board.jpg new file mode 100644 index 0000000..1d02f21 Binary files /dev/null and b/arduino/libraries/Adafruit_SHT31_Library/assets/board.jpg differ diff --git a/arduino/libraries/Adafruit_SHT31_Library/examples/SHT31test/SHT31test.ino b/arduino/libraries/Adafruit_SHT31_Library/examples/SHT31test/SHT31test.ino new file mode 100644 index 0000000..24534f8 --- /dev/null +++ b/arduino/libraries/Adafruit_SHT31_Library/examples/SHT31test/SHT31test.ino @@ -0,0 +1,72 @@ +/*************************************************** + This is an example for the SHT31-D Humidity & Temp Sensor + + Designed specifically to work with the SHT31-D sensor from Adafruit + ----> https://www.adafruit.com/products/2857 + + These sensors use I2C to communicate, 2 pins are required to + interface + ****************************************************/ + +#include +#include +#include "Adafruit_SHT31.h" + +bool enableHeater = false; +uint8_t loopCnt = 0; + +Adafruit_SHT31 sht31 = Adafruit_SHT31(); + +void setup() { + Serial.begin(9600); + + while (!Serial) + delay(10); // will pause Zero, Leonardo, etc until serial console opens + + Serial.println("SHT31 test"); + if (! sht31.begin(0x44)) { // Set to 0x45 for alternate i2c addr + Serial.println("Couldn't find SHT31"); + while (1) delay(1); + } + + Serial.print("Heater Enabled State: "); + if (sht31.isHeaterEnabled()) + Serial.println("ENABLED"); + else + Serial.println("DISABLED"); +} + + +void loop() { + float t = sht31.readTemperature(); + float h = sht31.readHumidity(); + + if (! isnan(t)) { // check if 'is not a number' + Serial.print("Temp *C = "); Serial.print(t); Serial.print("\t\t"); + } else { + Serial.println("Failed to read temperature"); + } + + if (! isnan(h)) { // check if 'is not a number' + Serial.print("Hum. % = "); Serial.println(h); + } else { + Serial.println("Failed to read humidity"); + } + + delay(1000); + + // Toggle heater enabled state every 30 seconds + // An ~3.0 degC temperature increase can be noted when heater is enabled + if (loopCnt >= 30) { + enableHeater = !enableHeater; + sht31.heater(enableHeater); + Serial.print("Heater Enabled State: "); + if (sht31.isHeaterEnabled()) + Serial.println("ENABLED"); + else + Serial.println("DISABLED"); + + loopCnt = 0; + } + loopCnt++; +} diff --git a/arduino/libraries/Adafruit_SHT31_Library/library.properties b/arduino/libraries/Adafruit_SHT31_Library/library.properties new file mode 100644 index 0000000..eb13ade --- /dev/null +++ b/arduino/libraries/Adafruit_SHT31_Library/library.properties @@ -0,0 +1,10 @@ +name=Adafruit SHT31 Library +version=2.2.2 +author=Adafruit +maintainer=Adafruit +sentence=Arduino library for SHT31 temperature & humidity sensor. +paragraph=Arduino library for SHT31 temperature & humidity sensor. +category=Sensors +url=https://github.com/adafruit/Adafruit_SHT31 +architectures=* +depends=Adafruit BusIO diff --git a/arduino/libraries/Adafruit_SHT31_Library/license.txt b/arduino/libraries/Adafruit_SHT31_Library/license.txt new file mode 100644 index 0000000..f6a0f22 --- /dev/null +++ b/arduino/libraries/Adafruit_SHT31_Library/license.txt @@ -0,0 +1,26 @@ +Software License Agreement (BSD License) + +Copyright (c) 2012, 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. diff --git a/arduino/sketch_hum_temp/sketch_hum_temp.ino b/arduino/sketch_hum_temp/sketch_hum_temp.ino new file mode 100644 index 0000000..74f5561 --- /dev/null +++ b/arduino/sketch_hum_temp/sketch_hum_temp.ino @@ -0,0 +1,109 @@ +#include +#include "Adafruit_SHT31.h" + +Adafruit_SHT31 sht31; +uint8_t detectedAddress = 0; // 0 - не найден, иначе 0x44 или 0x45 +unsigned long lastAttempt = 0; +bool sensorOK = false; + +void setup() { + Serial.begin(9600); + pinMode(13, OUTPUT); + Wire.begin(); + Serial.println("Starting SHT31 scanner..."); +} + +void loop() { + // Если датчик не инициализирован или был сбой, пытаемся его найти/переинициализировать каждые 5 секунд + if (!sensorOK) { + if (millis() - lastAttempt > 5000) { + lastAttempt = millis(); + attemptInit(); + } + // Индикация ошибки: быстро мигаем (5 раз в секунду) + digitalWrite(13, HIGH); + delay(100); + digitalWrite(13, LOW); + delay(100); + return; // не идём дальше, пока нет датчика + } + + // Если датчик работает, читаем данные каждые 30 секунд (как у вас) + static unsigned long lastRead = 0; + if (millis() - lastRead > 30000) { + lastRead = millis(); + readAndPrint(); + } + + // Небольшая задержка для устойчивости + delay(10); +} + +// Функция попытки инициализации датчика +void attemptInit() { + Serial.println("Scanning I2C bus for SHT31..."); + + // Массив возможных адресов (вместо {0x44,0x45} с range-for) + uint8_t addresses[] = {0x44, 0x45}; + for (int i = 0; i < 2; i++) { + uint8_t addr = addresses[i]; + if (sht31.begin(addr)) { + // Проверим, действительно ли датчик отвечает (прочитаем что-нибудь) + float t = sht31.readTemperature(); + if (!isnan(t)) { + detectedAddress = addr; + sensorOK = true; + Serial.print("SHT31 found at address 0x"); + Serial.print(addr, HEX); + Serial.println("! Sensor ready."); + digitalWrite(13, LOW); // погасим светодиод + return; + } + } + } + + // Если не нашли, возможно адрес другой. Запустим полный I2C-скан + Serial.println("No SHT31 found at 0x44 or 0x45. Check wiring!"); + Serial.println("Running full I2C scan to see all devices..."); + fullI2CScan(); +} + +// Функция полного сканирования I2C (выводит все найденные устройства) +void fullI2CScan() { + byte error, address; + int nDevices = 0; + for (address = 1; address < 127; address++) { + Wire.beginTransmission(address); + error = Wire.endTransmission(); + if (error == 0) { + Serial.print("I2C device found at address 0x"); + if (address < 16) Serial.print("0"); + Serial.print(address, HEX); + Serial.println(" !"); + nDevices++; + } + } + if (nDevices == 0) + Serial.println("No I2C devices found"); + else + Serial.println("Scan done"); +} + +// Функция чтения и вывода данных +void readAndPrint() { + float temp = sht31.readTemperature(); + float hum = sht31.readHumidity(); + + if (!isnan(temp) && !isnan(hum)) { + Serial.print(temp); + Serial.print(" "); + Serial.println(hum); + // Короткая вспышка при успешном чтении + digitalWrite(13, HIGH); + delay(50); + digitalWrite(13, LOW); + } else { + Serial.println("Read error, reinitializing..."); + sensorOK = false; // Сброс флага, чтобы цикл попытался переинициализировать + } +} \ No newline at end of file diff --git a/home-meteo@lina/desklet.js b/home-meteo@lina/desklet.js new file mode 100644 index 0000000..ff4a596 --- /dev/null +++ b/home-meteo@lina/desklet.js @@ -0,0 +1,187 @@ +const Desklet = imports.ui.desklet; +const St = imports.gi.St; +const GLib = imports.gi.GLib; +const Mainloop = imports.mainloop; +const Settings = imports.ui.settings; +const Gio = imports.gi.Gio; + +function MyDesklet(metadata, desklet_id) { + this._init(metadata, desklet_id); +} + +MyDesklet.prototype = { + __proto__: Desklet.Desklet.prototype, + + _init: function(metadata, desklet_id) { + try { + Desklet.Desklet.prototype._init.call(this, metadata, desklet_id); + + this.settings = new Settings.DeskletSettings(this, this.metadata.uuid, desklet_id); + this.settings.bindProperty(Settings.BindingDirection.IN, "font-size", "fontSize", this._onSettingsChanged, null); + this.settings.bindProperty(Settings.BindingDirection.IN, "custom-color", "customColor", this._onSettingsChanged, null); + this.settings.bindProperty(Settings.BindingDirection.IN, "use-custom-color", "useCustomColor", this._onSettingsChanged, null); + + // Главный контейнер + this.container = new St.BoxLayout({ + style_class: "desklet-with-borders", + vertical: true, + style: "padding: 20px; border-radius: 15px; text-align: center; min-width: 250px;" + }); + + // Горизонтальный контейнер для двух колонок + this.contentBox = new St.BoxLayout({ vertical: false }); + + // Колонка Температуры + this.tempBox = new St.BoxLayout({ vertical: true, style: "margin: 0 15px;" }); + this.labelT = new St.Label({ text: "Температура, °C" }); + this.emojiT = new St.Label({ text: "⏳" }); + this.valT = new St.Label({ text: "00.0" }); + this.tempBox.add_actor(this.labelT); + this.tempBox.add_actor(this.emojiT); + this.tempBox.add_actor(this.valT); + + // Колонка Влажности + this.humBox = new St.BoxLayout({ vertical: true, style: "margin: 0 15px;" }); + this.labelH = new St.Label({ text: "Влажность, %" }); + this.emojiH = new St.Label({ text: "⏳" }); + this.valH = new St.Label({ text: "00.0" }); + this.humBox.add_actor(this.labelH); + this.humBox.add_actor(this.emojiH); + this.humBox.add_actor(this.valH); + + this.contentBox.add_actor(this.tempBox); + this.contentBox.add_actor(this.humBox); + + // Статус внизу + this.updateLabel = new St.Label({ + text: "Запуск системы...", + style: "margin-top: 15px; font-size: 0.8em; opacity: 0.6;" + }); + + this.container.add_actor(this.contentBox); + this.container.add_actor(this.updateLabel); + this.setContent(this.container); + + this._onSettingsChanged(); + + // Запуск чтения через 2 секунды + Mainloop.timeout_add_seconds(2, () => { + this._initArduinoRead(); + return false; + }); + + } catch (e) { + global.logError(e); + } + }, + + _onSettingsChanged: function() { + let fs = this.fontSize || 12; + let color = this.useCustomColor ? this.customColor : "#ffffff"; + + let headerStyle = "color: " + color + "; font-size: " + (fs * 0.9) + "pt; opacity: 0.8;"; + let emojiStyle = "font-size: " + (fs * 2.1) + "pt; margin: 0 0;"; + let valueStyle = "color: " + color + "; font-weight: bold; font-size: " + (fs * 1.4) + "pt;"; + + this.labelT.set_style(headerStyle); + this.labelH.set_style(headerStyle); + this.emojiT.set_style(emojiStyle); + this.emojiH.set_style(emojiStyle); + this.valT.set_style(valueStyle); + this.valH.set_style(valueStyle); + this.updateLabel.set_style("color: " + color + "; font-size: " + (fs * 0.7) + "pt;"); + }, + + _initArduinoRead: function() { + this.arduinoPath = "/dev/arduino"; + + if (this.dataStream) { + try { this.dataStream.close(null); } catch (e) {} + this.dataStream = null; + } + + if (!GLib.file_test(this.arduinoPath, GLib.FileTest.EXISTS)) { + this.updateLabel.set_text("Порт /dev/arduino не найден"); + Mainloop.timeout_add_seconds(5, () => this._initArduinoRead()); + return; + } + + try { + // Настройка порта + GLib.spawn_command_line_sync("stty -F " + this.arduinoPath + " 9600 raw -echo -icanon hupcl"); + + let file = Gio.File.new_for_path(this.arduinoPath); + file.read_async(GLib.PRIORITY_LOW, null, (source, res) => { + try { + let inputStream = source.read_finish(res); + this.dataStream = new Gio.DataInputStream({ base_stream: inputStream }); + this.updateLabel.set_text("Подключено. Ожидание данных..."); + this._readNext(); + } catch (e) { + this.updateLabel.set_text("Ошибка открытия потока"); + Mainloop.timeout_add_seconds(5, () => this._initArduinoRead()); + } + }); + } catch (e) { + this.updateLabel.set_text("Ошибка stty"); + Mainloop.timeout_add_seconds(5, () => this._initArduinoRead()); + } + }, + + _readNext: function() { + if (!this.dataStream) return; + this.dataStream.read_line_async(GLib.PRIORITY_LOW, null, (source, res) => { + try { + let [line, length] = source.read_line_finish(res); + if (line !== null) { + let text = line.toString().trim(); + let matches = text.match(/[-+]?[0-9]*\.?[0-9]+/g); + + if (matches && matches.length >= 2) { + let t = parseFloat(matches[0]); + let h = parseFloat(matches[1]); + let now = GLib.DateTime.new_now_local(); + + this.valT.set_text(t.toFixed(1)); + this.valH.set_text(h.toFixed(1)); + + // Логика для Температуры + if (t > 27) { + this.emojiT.set_text("🥵"); + } else if (t < 22) { + this.emojiT.set_text("🥶"); + } else { + this.emojiT.set_text("😊"); + } + + // Логика для Влажности + if (h < 40) { + this.emojiH.set_text("😮‍💨"); + } else if (h > 60) { + this.emojiH.set_text("😶‍🌫️"); + } else { + this.emojiH.set_text("😊"); + } + + this.updateLabel.set_text("Обновлено: " + now.format("%H:%M:%S")); + } + } + this._readNext(); + } catch (e) { + this.updateLabel.set_text("Переподключение..."); + Mainloop.timeout_add_seconds(2, () => this._initArduinoRead()); + } + }); + }, + + on_desklet_removed: function() { + if (this.dataStream) { + try { this.dataStream.close(null); } catch (e) {} + } + this.settings.finalize(); + } +} + +function main(metadata, desklet_id) { + return new MyDesklet(metadata, desklet_id); +} diff --git a/home-meteo@lina/metadata.json b/home-meteo@lina/metadata.json new file mode 100644 index 0000000..5d4d253 --- /dev/null +++ b/home-meteo@lina/metadata.json @@ -0,0 +1,6 @@ +{ + "uuid": "home-meteo@lina", + "name": "Home Meteo", + "description": "Домашняя метеостанция", + "prevent-decorations": true +} diff --git a/home-meteo@lina/settings-schema.json b/home-meteo@lina/settings-schema.json new file mode 100644 index 0000000..c911ffb --- /dev/null +++ b/home-meteo@lina/settings-schema.json @@ -0,0 +1,21 @@ +{ + "font-size": { + "type": "spinbutton", + "default": 16, + "units": "pt", + "step": 1, + "min": 10, + "max": 72, + "description": "Размер шрифта" + }, + "custom-color": { + "type": "colorchooser", + "default": "rgb(0,0,255)", + "description": "Цвет текста" + }, + "use-custom-color": { + "type": "checkbox", + "default": false, + "description": "Использовать свой цвет" + } +} diff --git a/images/screenshot1.png b/images/screenshot1.png new file mode 100644 index 0000000..8fa3f3a Binary files /dev/null and b/images/screenshot1.png differ diff --git a/images/screenshot2.png b/images/screenshot2.png new file mode 100644 index 0000000..439bd42 Binary files /dev/null and b/images/screenshot2.png differ