Error received nack on transmit of address

Operating environment/Installation (Hass.io/Docker/pip/etc.): Docker ESP (ESP32/ESP8266, Board/Sonoff): ESP8266 / NodeMCU 4MB Flash Affected component: I2C Bus (BME280) Description of problem: I ha...

Operating environment/Installation (Hass.io/Docker/pip/etc.):

Docker

ESP (ESP32/ESP8266, Board/Sonoff):

ESP8266 / NodeMCU 4MB Flash

Affected component:

I2C Bus (BME280)

Description of problem:
I have an NodeMCU ESP8266 (4MB) running ESPHome, it is connected to a BME280 sensor on I2C at address 0x76. The hardware and configuration work, however after some period of time often between 24h to 140h, ESPHome will report errors in the I2C bus and sensor values will no longer be read.

There are a few problems:

  1. Obviously it would be great if this problem didn’t happen at all or if the I2C bus reset itself and recovered on its own.
  2. A reboot does not fix the problem, power must be interrupted to the ESP8266 before the I2C bus detects the sensor and reports values again. This sucks because I can not compensate for this issue by rebooting the ESP.
  3. Don’t know of a way to detect the issue within Home Assistant other than to alert if values stagnate for 3 polling periods or something like that. Does HA have way to read the logs to see NACKs?

Problem-relevant YAML-configuration entries:

i2c:
  sda: D6
  scl: D5
  scan: True
  id: bus_a

sensor:
  # Uptime sensor.
  - platform: uptime
    name: ESP Uptime
    filters:
    - lambda: return x / 3600;
    unit_of_measurement: "h"

  - platform: bme280
    temperature:
      name: "BME280 Temperature"
      id: bme280_temperature
    pressure:
      name: "BME280 Pressure"
      id: bme280_pressure
    humidity:
      name: "BME280 Relative Humidity"
      id: bme280_humidity
    address: 0x76
    update_interval: 30s

Logs (if applicable):

Log from the device of it occurring:

[D][sensor:092]: 'ESP Uptime': Sending state 24.86042 h with 0 decimals of accuracy�
[D][bme280.sensor:197]: Got temperature=21.4°C pressure=995.7hPa humidity=40.0%�
[D][sensor:092]: 'BME280 Temperature': Sending state 21.35000 °C with 1 decimals of accuracy�
[D][sensor:092]: 'BME280 Pressure': Sending state 995.73346 hPa with 1 decimals of accuracy�
[D][sensor:092]: 'BME280 Relative Humidity': Sending state 39.97852 % with 1 decimals of accuracy�
[D][bme280.sensor:197]: Got temperature=21.4°C pressure=995.8hPa humidity=41.0%�
[D][sensor:092]: 'BME280 Temperature': Sending state 21.35000 °C with 1 decimals of accuracy�
[D][sensor:092]: 'BME280 Pressure': Sending state 995.75269 hPa with 1 decimals of accuracy�
[D][sensor:092]: 'BME280 Relative Humidity': Sending state 40.99609 % with 1 decimals of accuracy�
[D][sensor:092]: 'ESP Uptime': Sending state 24.87708 h with 0 decimals of accuracy�
[D][bme280.sensor:197]: Got temperature=21.4°C pressure=995.8hPa humidity=44.7%�
[D][sensor:092]: 'BME280 Temperature': Sending state 21.36000 °C with 1 decimals of accuracy�
[D][sensor:092]: 'BME280 Pressure': Sending state 995.76263 hPa with 1 decimals of accuracy�
[D][sensor:092]: 'BME280 Relative Humidity': Sending state 44.67383 % with 1 decimals of accuracy�
[W][i2c:070]: Received NACK on transmit of address 0x76
[D][sensor:092]: 'ESP Uptime': Sending state 24.89375 h with 0 decimals of accuracy�
[W][i2c:070]: Received NACK on transmit of address 0x76�
[W][i2c:070]: Received NACK on transmit of address 0x76�
[D][sensor:092]: 'ESP Uptime': Sending state 24.91042 h with 0 decimals of accuracy�
[W][i2c:070]: Received NACK on transmit of address 0x76�
[W][i2c:070]: Received NACK on transmit of address 0x76�
[D][sensor:092]: 'ESP Uptime': Sending state 24.92709 h with 0 decimals of accuracy�
[W][i2c:070]: Received NACK on transmit of address 0x76�

Additional information and things you’ve tried:
Regrettably, I don’t really know much about the low-level guts of the I2C bus, though there is seems to be discussions about this @ esp8266/Arduino#1025 and for the BME280 @ finitespace/BME280#78

I may see if there is a way I can chain another ESP to act as a power reset to this one or something like that, so I could at least reliably remotely reset the I2C.

Please be positive and constructive with your questions and comments.

User avatar

chm9871

 
Posts: 7
Joined: Wed Jan 26, 2022 3:03 pm

[BH1750] ERROR: received NACK on transmit of address

Hi there,

I’m making a lot of the same data loggers. When I upload code to some of them (about 1/10) I get the following error :

[BH1750] ERROR: received NACK on transmit of address
[BH1750] ERROR: received NACK on transmit of address
[BH1750] Device is not configured!

As the wiring and code for each datalogger is identical, I have no idea what causes this error (obvs the BH1750) — any insight would be very much appreciated.

Thanks

CM



User avatar

ajithk

 
Posts: 3
Joined: Sat Jul 09, 2022 10:28 am

Re: [BH1750] ERROR: received NACK on transmit of address

Post

by ajithk » Sat Jul 09, 2022 12:57 pm

IIRC, the BH1750 has 2 possible I2C addresses. Perhaps the ADDR pin has a bad solder and/or is seeing different voltages on the non-working units. One defensive option is to modify the code to try both addresses.


User avatar

chm9871

 
Posts: 7
Joined: Wed Jan 26, 2022 3:03 pm

Re: [BH1750] ERROR: received NACK on transmit of address

Post

by chm9871 » Mon Jul 11, 2022 2:33 pm

The sensors are linked via STEMMA QT / Qwiic JST SH 4-pin Cable to a Qwiic Sheild, so I doubt its a bad solder, and other sensors are working fine with the same cable/shield set up.

Changing the address from 0x23 to 0x5c just yields a different flavor of error :

ERROR: Invalid mode
[BH1750] ERROR: undefined error
[BH1750] ERROR: received NACK on transmit of address

Any help would be grand



User avatar

chm9871

 
Posts: 7
Joined: Wed Jan 26, 2022 3:03 pm

Re: [BH1750] ERROR: received NACK on transmit of address

Post

by chm9871 » Tue Jul 12, 2022 12:41 pm

Attached a photo >

IMG_7874.jpg
IMG_7874.jpg (832.02 KiB) Viewed 1146 times

For ref its an adalogger 32u4 https://www.adafruit.com/product/2795 soldered to a qt feather wing https://www.adafruit.com/product/4515 via GND, SCL and SDA, a wire coming off of the A3 pin to 3V3 to control power to the sensors :
BH1750 https://www.adafruit.com/product/4681
SHT40 https://www.adafruit.com/product/4885
PCF8523 https://www.adafruit.com/product/5189
JST PH https://www.adafruit.com/product/4026

w/ a 2500mAh lipo for power.

The code currently powers up, engages 12C, runs a set up for sensors, turns off 12C, powers down, then the loop: powers up, engages 12C, saves sensor data to SD card, turns off 12C and powers down, with a WatchDog loop for the duration of the 32u4 sleep cycle

So far the «failure» rate of the Bh1750s returning a NACK error is 1 in 7 ish


User avatar

mikeysklar

 
Posts: 9591
Joined: Mon Aug 01, 2016 8:10 pm

Re: [BH1750] ERROR: received NACK on transmit of address

Post

by mikeysklar » Tue Jul 12, 2022 4:29 pm

Thanks for the photo they always tell a story.

Can you solder the rest of the pins on the Sparkfun i2c breakout board?

The 3v3 red jumper wire looks pretty well connected, but maybe you can go over that with a soldering iron as I cannot tell if that is a «cold joint». Is the jumper necessary?

To further narrow the issue down it would be helpful to test a BH1750 sensor in isolation (no other devices on the i2c bus) after it has shown the NACK error to see if it continues or is related to the more complex setup.


User avatar

chm9871

 
Posts: 7
Joined: Wed Jan 26, 2022 3:03 pm

Re: [BH1750] ERROR: received NACK on transmit of address

Post

by chm9871 » Tue Aug 30, 2022 12:29 pm

Sorry for the lateness of this reply.

I have soldered extra pins, and gone over 3v3 jumper solders (this wire is to make powering the entire 12c breakout on/off easier).

I largely solved the NACK issue by either daisy chaining the stemma through another sensor or changing the port side for the cable. So maybe faulty connections from the stemma port on the board.

Now my problem is about 85% of the sensors never record a light level when there’s not an external power source (i.e. plugged in via USB). They seem to record lux levels fine during set-up and see through the terminal, but once they’re deployed and running off a Lipo, just record 0s, whilst the LED lights up fine, showing they’re receiving power.

Any suggestions? I’m just using the basic — lightMeter.readLightLevel(); in the code


User avatar

mikeysklar

 
Posts: 9591
Joined: Mon Aug 01, 2016 8:10 pm

Re: [BH1750] ERROR: received NACK on transmit of address

Post

by mikeysklar » Fri Sep 02, 2022 5:57 am

Since the behavior is different using USB versus running off a LiPO I’m suspicious of a power issue. You had mentioned you were using a 2500 mAh LIPO which should easily provide all the current you need.

When you are running from USB what was the power source (computer USB port, or wall dumb wall plug)?

Do you have another LIPO you can swap out for the 2500 you are using?

How many sensors do you need to remove to get full readings from a LIPO?




User avatar

adafruit2

 
Posts: 21368
Joined: Fri Mar 11, 2005 7:36 pm

Re: [BH1750] ERROR: received NACK on transmit of address

Post

by adafruit2 » Mon Sep 05, 2022 11:34 am

a GPIO pin just cannot power 4 sensors, it does not have the current capability for so many sensors. maybe you could power one sensor per GPIO (maybe!) otherwise you are going to get flaky behavoir — you need to have a power circuit to enable/disable the power with at least 50-100mA of output capability


User avatar

chm9871

 
Posts: 7
Joined: Wed Jan 26, 2022 3:03 pm

Re: [BH1750] ERROR: received NACK on transmit of address

Post

by chm9871 » Mon Sep 05, 2022 5:15 pm

Ah. Well, that might explain quite a lot. Thanks a bunch. But it’s a tad troublesome as it potentially involves lots of additional wiring.

Is there another solution for powering the 3v3 pin on the Qwicc Shield? I.e. several GPIO pins to the single Qwicc Shield 3v3 pin? or ( I’ve never found anything on how to do this, but it’s potentially obvious to everyone else..) control the 3v(3) pin on the adalogger to switch the output on/off high/low?


User avatar

adafruit2

 
Posts: 21368
Joined: Fri Mar 11, 2005 7:36 pm

Re: [BH1750] ERROR: received NACK on transmit of address

Post

by adafruit2 » Mon Sep 05, 2022 5:31 pm

as you can tell there isnt a simple way of doing it, its a good idea for a product! some of our current boards have a ‘switchable’ I2C port, like the Feather ESP32 V2 but dont have a SD card so you’d have to wire that instead — bit of a tradeoff but maybe worth it



Please be positive and constructive with your questions and comments.


Offline

Зарегистрирован: 25.02.2018

Приветствую товарищи. 

В общем задался целью освоить библиотеку Wire, пробую общаться с датчиком Bmp180 по I2C шине. Ардуиной увлекся с месяц назад, знаний накопил пока не много так что сильно не ругайте.

Суть проблемы в том что я никак не могу корректно записать в датчик значение байта=0x2E в регистр=0xF4, это нужно сделать для инициализации измерения температуры. Согласно даташиту на датчик после данной записи он должен начать измерение, подготовить их для чтения и переустановить значение байта на 0xE регистра 0xF4. Так вот после выполнения записи в этот регистр я пытаюсь его прочитать и передаю на компьютер прочитанное значение. При чтении получаю 0xA или 0b1010. Подскажите что не так, бьюсь уже целый день… :(

#include <Wire.h>
#define bmp180address 0x77

char mAC1 = 0;
char lAC1 = 0;
int AC1 = 0;

char mAC2 = 0;
char lAC2 = 0;
int AC2 = 0;

char mAC3 = 0;
char lAC3 = 0;
int AC3 = 0;

unsigned char mAC4 = 0;
unsigned char lAC4 = 0;
unsigned int AC4 = 0;

unsigned char mAC5 = 0;
unsigned char lAC5 = 0;
unsigned int AC5 = 0;

unsigned char mAC6 = 0;
unsigned char lAC6 = 0;
unsigned int AC6 = 0;

char mB1 = 0;
char lB1 = 0;
int BB1 = 0;

char mB2 = 0;
char lB2 = 0;
int BB2 = 0;

char mMB = 0;
char lMB = 0;
int MB = 0;

char mMC = 0;
char lMC = 0;
int MC = 0;

char mMD = 0;
char lMD = 0;
int MD = 0;

char chipID = 0;
char CSO = 0;
char MSB = 0, LSB = 0, xLSB = 0;
int UT = 0, UP = 0, PP1 = 0, PP4 = 0, Temper = 0, Press = 0;
unsigned int PP2 = 0, PP3 = 0;

void setup() {
  Wire.begin();
  Serial.begin(9600);
}

void loop() {
  
Wire.beginTransmission(bmp180address);
Wire.write(0xAA);
Wire.endTransmission(false);
Wire.requestFrom(bmp180address, 23, true);

mAC1 = Wire.read();
lAC1 = Wire.read();
mAC2 = Wire.read();
lAC2 = Wire.read();
mAC3 = Wire.read();
lAC3 = Wire.read();
mAC4 = Wire.read();
lAC4 = Wire.read();
mAC5 = Wire.read();
lAC5 = Wire.read();
mAC6 = Wire.read();
lAC6 = Wire.read();
mB1 = Wire.read();
lB1 = Wire.read();
mB2 = Wire.read();
lB2 = Wire.read();
mMB = Wire.read();
lMB = Wire.read();
mMC = Wire.read();
lMC = Wire.read();
mMD = Wire.read();
lMD = Wire.read();
chipID = Wire.read();

AC1 = (mAC1 << 8);
AC1 = (AC1 | lAC1);
AC2 = (mAC2 << 8);
AC2 = (AC2 | lAC2);
AC3 = (mAC3 << 8);
AC3 = (AC3 | lAC3);
AC4 = (mAC4 << 8);
AC4 = (AC4 | lAC4);
AC5 = (mAC5 << 8);
AC5 = (AC5 | lAC5);
AC6 = (mAC6 << 8);
AC6 = (AC6 | lAC6);
BB1 = (mB1 << 8);
BB1 = (BB1 | lB1);
BB2 = (mB2 << 8);
BB2 = (BB2 | lB2);
MB = (mMB << 8);
MB = (MB | lMB);
MC = (mMC << 8);
MC = (MC | lMC);
MD = (mMD << 8);
MD = (MD | lMD);

Wire.beginTransmission(bmp180address);
Wire.write(0xF4);
Wire.write(0x2E);
Wire.endTransmission(true);
delay(50);
Wire.beginTransmission(bmp180address);
Wire.write(0xF4);
Wire.endTransmission(false);
Wire.requestFrom(bmp180address, 1, true);
CSO = Wire.read();

Wire.beginTransmission(bmp180address);
Wire.write(0xF6);
Wire.endTransmission(false);
Wire.requestFrom(bmp180address, 2, true);

MSB = Wire.read();
LSB = Wire.read();

UT = (MSB << 8);
UT = (UT | LSB);

PP1 = ((UT-AC6)*AC5/32768)+(MC*2048/(((UT-AC6)*AC5/32768))+MD);
Temper = (char(PP1)+8)/16;

Serial.println(CSO,BIN);
Serial.println(MSB);
Serial.println(LSB);
Serial.println(UT);
Serial.println(PP1);
Serial.println(Temper);
Serial.println(chipID,BIN);
Serial.println(AC1);
Serial.println(AC2);
Serial.println(AC3);
Serial.println(AC4);
Serial.println(AC5);
Serial.println(AC6);
Serial.println(BB1);
Serial.println(BB2);
Serial.println(MB);
Serial.println(MC);
Serial.println(MD);
  delay(1000);  
}

  1. Здесь нужно смотреть «железные» отличия этих плат. В принципе и там, и там используется модуль ЕСП12, так что в принципе должно работать)))

  2. З наступаючим Новим роком!!!
    Попробовал и у меня не чего не получилось В монитор порта при изменении топика не чего не приходит
    char mqtt_sub2[25]=»Inform/bright»;

    //======================================================================================
    void callback(char* topic, byte* payload, unsigned int length) { // получаем знаковое число с десятичной плавающей запятой
      if(!senss.mqttOn) return;
      String Text;
      for(int i=0; i<length; i++) Text+=((char)payload[i]);
      if((String(topic)==mqtts.mqtt_sub_inform)&&(sgpCo2Livel<sgps.sgpCo2LivelAlarm||sgpTvocLivel<sgps.sgpTvocLivelAlarm)){
        for(byte i=0; i<leds.NUM_MAX0;i++){
          Text+=»   «;
        }
        bip();
        bip();
        bip();
        bip();
        if(senss.printCom){
          printTime();
          Serial.println(«MQTT Incoming Message: «+Text);
        }
        clr(leds.NUM_VER_X);
        refreshAll();
        printStringWithShift(Text.c_str(),30);
        return;
      }
    //======================================================================================
    // управления подсветкой
        if(String(topic) == mqtts.mqtt_sub2) {
          //tMqtt2 = Text.substring(0, length+1).toInt();
            int levelBridhtness = Text.substring(0,length+1).toInt();
          if(senss.printCom){
            printTime();
            Serial.println(«MQTT  Incoming: « + String(levelBridhtness));
          }
            sendCmdAll(CMD_INTENSITY, levelBridhtness);
        }
    //======================================================================================
      for(byte i=0;i<8;i++){
        if(String(topic)==mqtts.mqtt_sub[i]){
          tMqtt[i]=Text.substring(0,length+1).toFloat();
          if(senss.printCom){
            printTime();
            Serial.println(«MQTT «+String(i+1)+» Incoming: « + String(tMqtt[i]));
          }
          counterMqtt[i]=millis();
          counterMqttTimeout[i]=false;
          sensorses();
        }
      }
    }

    //======================================================================================

    Последнее редактирование: 31 дек 2022

  3. C меня прогер не какой, буду ждать ваших правок

    //======================================================================================
    void callback(char* topic,byte* payload,unsigned int length){ // получаем знаковое число с десятичной плавающей запятой
      if(!senss.mqttOn) return;
      String Text;
      for(int i=0;i<length;i++) Text+=((char)payload[i]);
      if((String(topic)==mqtts.mqtt_sub_inform)&&(sgpCo2Livel<sgps.sgpCo2LivelAlarm||sgpTvocLivel<sgps.sgpTvocLivelAlarm)){
        for(byte i=0;i<leds.NUM_MAX0;i++){
          Text+=»   «;
        }
        bip();
        bip();
        bip();
        bip();
        if(senss.printCom){
          printTime();
          Serial.println(«MQTT Incoming Message: «+Text);
        }
        clr(leds.NUM_VER_X);
        refreshAll();
        printStringWithShift(Text.c_str(),30);
        return;
      }

     
     
      if (strcmp(topic,«nodeNTP_1/bright»)==0) {
      String Text;
      for(int i=0; i<length; i++){
        Text+=((char)payload[i]);
        }

        int aNumber = Text.substring(0,length+1).toInt();
        Serial.print(«Brightness set to: «);
        Serial.println(aNumber);

        sendCmdAll(CMD_INTENSITY, aNumber);

         
      }
      for(byte i=0;i<8;i++){
        if(String(topic)==mqtts.mqtt_sub[i]){
          tMqtt[i]=Text.substring(0,length+1).toFloat();
          if(senss.printCom){
            printTime();
            Serial.println(«MQTT «+String(i+1)+» Incoming: « + String(tMqtt[i]));
          }
          counterMqtt[i]=millis();
          counterMqttTimeout[i]=false;
          sensorses();
        }
      }
    }
    //======================================================================================

  4. Для начала нужно определиться где не работает.
    1. Посмотреть приходит ли топик с нашим названием.

    //======================================================================================
    void callback(char* topic, byte* payload, unsigned int length) { // получаем знаковое число с десятичной плавающей запятой
    Serial.print(топик) можно также для ясности вывести и его содержимое и длину.
     

    Если вам приходит правильное название и содержание к примеру «10», то здесь

    // управления подсветкой
        if(String(topic) == mqtts.mqtt_sub2) {
     

    сложить число в одно целое
    if(length<=2){
    int levelBridhtness = Text.substring(0,0).toInt();
    } else {
    int levelBridhtness = Text.substring(0,1).toInt();
    }
    Хотя я конечно же сделал бы проверку на то что первый и второй символы точно — цифры, ведь могут прийти буквы, и фунция тоИнт() — скорее всего вернет «0».
    Можно перед вычислением вывести в ком порт
    Serial.println(String(Text.substring(0,1))) — посмотреть что вы точно то что планируете будете переводить в цифры)))

    В любом месте где не уверенны что получаете необходимый результат ставьте вывод в компорт, так сказать легкий дебаг)))

  5. Добрый день, уважаемые форумчане!
    Давно ничего не делал с часами, теперь вот возникла необходимость обновить прошивку, после некоторых изменений в скетче, но при компиляции постоянно выдаёт ошибки.
    Не могли бы Вы напомнить, при каких настройках среды Ардуино, при компиляции VZ_Clock_v5.0.2 всё компилируется без проблем.
    Интересует конкретно, какая установлена версия ESP8266 и какая версия ArduinoJson.
    Заранее благодарю за помощь!

  6. А где вы взяли VZ_Clock_v5.0.2? На гигхабе 5,0,1
    esp 2,7,4
    ArduinoJson 6.14.1

  7. Спасибо, компиляция прошла успешно (записал чтобы не забыть ;))Не Гитхабом единым жив программист, есть ещё Гугл диск
    VZ_Clock_v5.0.2 на Гугле как минимум с МАЯ 2022г лежит !
    https://drive.google.com/drive/folders/11ziGBp9WEz6XR9jGMwWIMmJEbAhigKyr

    Последнее редактирование: 2 янв 2023

  8. Причём не важно какое отрицательное число выставлено, всё равно выводит одно и тоже фейковое значение.
    Заметил, что если выставить не целое значение (к примеру вместо минус 3 поставить минус 3,01), то тогда отображается всё правильно.
    Почему то косяк именно при целых числах.

    Последнее редактирование: 2 янв 2023

  9. А печатную плату уже ктото делал можете поделится?

  10. Да уже делал по этому

    Минимум доработки, 2 перемычки.
    Эту плату здесь заказал https://www.pcbway.com/project/shareproject/pcb_for_ESP_wifi_clock.html

  11. Давайте с начала я правильно делаю.
    1 добавляю через веб интерфейс топик Inform/bright

    Opera Снимок_2023-01-08_100940_192.168.0.5.png

    потом добавляю в скетч

    void callback(char* topic,byte* payload,unsigned int length){ // получаем знаковое число с десятичной плавающей запятой
      Serial.print(«Inform/bright»);
      if(!senss.mqttOn) return;

    то приходит
    14:13:50.156 -> Inform/bright14:13:47 MQTT 4 Incoming: 7.00

    14:13:46.448 > 14:13:44  fnCount=  11   period[fnCount]=  5     millis()=  8815608     fnTimer=  8820608
    14:13:46.448 > 14:13:44  fnCount=  0   period[fnCount]=  50     millis()=  8815610     fnTimer=  8865609
    14:13:50.156 > Inform/bright14:13:47  MQTT 4 Incoming: 7.00
    14:13:50.156 > 14:13:47  senss.sensors[0](+corr)=0.00
    14:13:50.189 > 14:13:47  senss.sensors[1](+corr)=0.00
    14:13:56.404 > 14:13:54  Publish sensors[0]: 0.00
    14:13:56.404 > 14:13:54  Publish sensors[1]: 0.00
    14:13:56.404 > ======== START GET SENSORS DATA =======================
    14:13:57.206 > 14:13:54  Temperature DS18B20: 20.00 *C
    14:13:57.206 > 14:13:54  senss.sensors[0](+corr)=0.00
    14:13:57.206 > 14:13:54  senss.sensors[1](+corr)=0.00
    14:13:57.206 > ======== END ==========================================

    потом добавил

    после
    char mqtt_sub_inform[25]=»Inform/mess»;
    такую
    char mqtt_sub_bright[25]=»Inform/bright»;
    перед
    for(byte i=0;i<8;i++){

      // управления подсветкой
      if(String(topic) == mqtts.mqtt_sub_bright) {
      if(length<=2){
    int levelBridhtness = Text.substring(0,0).toInt();
    } else {
    int levelBridhtness = Text.substring(0,1).toInt();
    }
    }
    Serial.println(String(Text.substring(0,1)));

    и получил
    15:49:55.818 -> Inform/bright7
    15:49:55.818 -> 15:49:53 MQTT 4 Incoming: 7.00
    15:49:55.818 -> 15:49:53 senss.sensors[0](+corr)=0.00
    15:49:55.852 -> 15:49:53 senss.sensors[1](+corr)=0.00


    Короче у меня не чего не получается

    Последнее редактирование: 8 янв 2023

  12. Всё оказалось просто. Всегда думал, что у меня Wemos D1 mini pro, и в настройках при прошивки выбирал эту плату. Начал сравнивать платы, оказалось у меня просто Wemos D1 mini. Выбрав эту плату все описанные проблемы отпали.

  13. Подскажите а датчик AM2320 должен работать или нет?
    У меня он не заработал. Я подключил его на D1 D2 и подтянул сопротивлением на 10к к +3,в
    Но не чего не помогло

    11:59:40.045 > Huraaa!!! Connected to «Plusnet»(192.168.0.5)
    11:59:40.045 >
    11:59:42.901 > 11:52:32  Proba #1   11:59:42
    11:59:44.572 >           Proba #2   11:59:43
    11:59:45.354 >           Proba #3   11:59:43
    11:59:45.354 > 11:59:43  Save /stime.json: {«hour»:11,«minute»:59,«second»:43,«year»:2023,«month»:1,«day»:12}
    11:59:45.354 > 11:59:43  12.01.2023 DW=5
    11:59:45.354 >           Time update OK.
    11:59:45.354 > Did not find sensor BMP180!
    11:59:45.870 > Did not find sensor BMP280!
    11:59:46.854 > Did not find sensor BME280!
    11:59:47.369 > Did not find sensor Si7021!
    11:59:47.917 > Did not find sensor AHT10 or AHT20!
    11:59:48.431 > [BH1750] ERROR: received NACK on transmit of address
    11:59:48.431 > BH1750 Not Found
    11:59:48.901 > MAX44009 Not Found
    11:59:48.901 > 11:59:46  senss.sensors[0](+corr)=0.00
    11:59:48.901 > 11:59:46  senss.sensors[1](+corr)=0.00
    11:59:48.901 > 11:59:46  senss.sensors[2](+corr)=0.00
    11:59:48.948 > mqtts.mqtt_sub[0]=Ulica/temp
    11:59:48.948 > mqtts.mqtt_sub[1]=Ulica/hum
    11:59:48.948 > mqtts.mqtt_sub[2]=Ulica/press
    11:59:48.948 > Sensor SGP30 not found :(
    11:59:48.948 > ======== START GET SENSORS DATA =======================
    11:59:49.743 > 11:59:47  Temperature DS18B20: 20.63 *C
    11:59:49.743 > 11:59:47  senss.sensors[0](+corr)=0.00
    11:59:49.743 > 11:59:47  senss.sensors[1](+corr)=0.00
    11:59:49.743 > 11:59:47  senss.sensors[2](+corr)=20.63
    11:59:49.743 > ======== END ==========================================
     
  14. Всем доброго времени суток.
    Решил немного допилить прошивку под свои нужды (праздники я хочу :)) и корпус тоже наконец домоделировать до логического конца. Но прежде нужно разобраться как заливать прошивку из Arduino IDE. Мучаю прошивку 5.0.1
    1. Поставил версию 1.8.19 (портабельную)
    2. Поставил драйвера для моей платы NodeMcu
    3. Залил библиотеки тех версий которые тут выкладывали именно для 5.0.1
    4. Настроил IDE чтобы видел мою NodeMcu v3
    5. Стоит ESP8266 Boards (3.0.2) и выбрано NodeMCU 1.0 (ESP-12E Module)
    6. Выбрал в настройках Flash Size: «4MB (FS:1 MB OTA:~1019KB)»
    7. Установил плагин для ESP8266 Sketch Data Upload
    Больше никакие настройки не трогал.
    Открываю проект, компилирую, заливаю. Заливаю раздел DATA. Всё проходит без ошибок.
    Но при коннекте страница настроек дико тормозит. И не отображается в заголовке страницы версия прошивки и текущее время. И в разделе ВРЕМЯ при попытке чтото изменить и сохранить выскакивают поочередно ошибки: «Получены не полные данные» или «Ошибочный запрос».

    Если заливать прошивку из готовых BIN (выложенных тут или на github) с помощью флэшера, то всё работает без проблем.
    Подскажите, пожалуйста, что делаю не так? Спасибо!

    Как только разберусь с этой проблемой оформлю проект корпуса для печати и выложу где-нибудь для общего доступа.
    Фото того что планируется. Повторяю уже за кем-то смоделериванный но не устраивающий по некоторым параметрам проект. Выкладывать буду с исходниками, если кто захочет допилить под свои нужды.

    IMG_6133.JPG

  15. не могу прошить

    Вложения:

    • Screenshot_1.png

  16. Попробуйте программу прошивки разместить в корне диска. Чтобы путь был как можно короче и не было в пути директорий с русскими названиями. Это касается и файлов самой прошивки.

  17. Попробуйте изменить версию ядра. С версией 2.7.4 все работает стабильно

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

microbot.it

Starting Member

  • Total Posts : 57
  • Reward points : 0
  • Joined: 2008/11/20 07:11:47
  • Location: 0
  • Status: offline

Hi,
i’m using PIC16F18323 with MPLAB X IDE V3.60
I send i write command by an Arduino UNO to the PIC, but the PIC responds NACK after the adress byte.
This means that the adress is correct and the communication is going on but it seems also that there is an error.. reading the datasheet it seems there is the buffer full but the SSPOV bit never go up.
I also monitor the arriving of an address byte or a data byte by changing the status of two leds (Arduino sends data every second).

void main(void) {

    // inizializzazione del PIC
    mcu_init();

    // carica le configurazioni iniziali
    load_starting_values();

     while (1) {

        if(SSP1IF) {
            rx_data = SSP1BUF;

            if(D_nA) // Data byte
                OUT1 = !OUT1;
            else
                OUT2 = !OUT2;

            OUT3 = SSPOV;

                        SSP1IF = 0;
            CKP = 1; // Release clock (clock stretch)
        }
    }
}

post edited by microbot.it — 2017/06/27 06:50:03

Nikolay_Po

Super Member

  • Total Posts : 1963
  • Reward points : 0
  • Joined: 2012/04/01 13:49:27
  • Location: Russia, Novorossiysk
  • Status: offline

Re: I2C responds NACK every time


2017/06/26 06:41:54

(permalink)

Hi. You need to show full functions code, all initialization and configuration. The code you’ve shown doesn’t disclosure the functions  mcu_init() and load_starting_values() nor shown the chip configuration bits.

Gort2015

Klaatu Barada Nikto

  • Total Posts : 6043
  • Reward points : 0
  • Joined: 2015/04/30 10:49:57
  • Location: 0
  • Status: offline

Re: I2C responds NACK every time


2017/06/26 07:14:16

(permalink)

You need to initialize, start i2c, stop i2c and you need a device address.

 #define I2C_DS1307_RTC          0xd0 //Maxim real time clock
#define I2C_DS3231_RTC          0xd0 //Maxim Extremely Accurate real time clock

 Your code is not complete by a large margin.

microbot.it

Starting Member

  • Total Posts : 57
  • Reward points : 0
  • Joined: 2008/11/20 07:11:47
  • Location: 0
  • Status: offline

Re: I2C responds NACK every time


2017/06/26 07:56:40

(permalink)

This is the missing code:

#pragma config RSTOSC = HFINT32 // HFINTOSC with 2x PLL (32MHz)
#pragma config FEXTOSC = OFF // External Oscillator not enabled
#pragma config MCLRE = OFF // MCLR/VPP pin function is digital input; MCLR internally disabled
#pragma config WDTE = OFF // WDT disabled
#pragma config PWRTE = ON // PWRT enabled
#pragma config CLKOUTEN = OFF // CLKOUT function is disabled; I/O or oscillator function on OSC2
#pragma config CSWEN = OFF // The NOSC and NDIV bits cannot be changed by user software
#pragma config FCMEN = OFF // Fail-Safe Clock Monitor is disabled
#pragma config LVP = OFF // High-voltage on MCLR/VPP must be used for programming
#pragma config WRT = ALL // 0000h to 07FFh write protected, no addresses may be modified
#pragma config CP = ON // User NVM code protection enabled
#pragma config CPD = ON // Data NVM code protection enabled
#pragma config BOREN = OFF // Brown-out Reset disabled
#pragma config LPBOREN = OFF // Low-Power BOR is disabled
#pragma config BORV = HIGH // Brown-out voltage (Vbor) set to 2.7V
#pragma config STVREN = ON // Stack Overflow or Underflow will cause a Reset
#pragma config DEBUG = OFF // Background debugger disabled
#pragma config PPS1WAY = ON // The PPSLOCK bit can be cleared and set only once; PPS registers remain locked after one clear/set cycle

void load_starting_values(void) {

    OUT1 = 0;
    OUT2 = 0;
    OUT3 = 0;
}

void mcu_init(void) {

     //Internal Oscillator Frequency = 32MHz
 while(!HFOR && !PLLR)
  NOP();

  // Set RA0, RA1, RA2, RA3 as Digital Input; Set RA4 as Digital Output; Set A5 as Analog Input
 TRISA0 = 1; // AD2 / PGD
 ANSA0 = 0;
 TRISA1 = 1; // AD1 / PGC
 ANSA1 = 0;
 TRISA2 = 1; // AD0
 ANSA2 = 0;
// TRISA3 = 1; // AD3 / MCLR
 TRISA4 = 0; // OUT2
 ANSA4 = 0;
 TRISA5 = 1; // IN1
 ANSA5 = 1;

   //Set RC2, RC3 as Analog Input; Set RC4, RC5 as Digital Output
 TRISC2 = 1; // IN2
 ANSC2 = 1;
 TRISC3 = 1; // IN3
 ANSC3 = 1;
 TRISC4 = 0; // OUT3
 ANSC4 = 0;
 TRISC5 = 0; // OUT1
 ANSC5 = 0;

      //ADC Configuration:
 ADFM = 1; // Format Right justified
 ADCON1bits.ADCS = 3; // ADCRC (dedicated RC oscillator) 1.0-6.0 uS
 ADCON1bits.ADPREF = 0; // Positive Voltage Reference is VDD
 ADCON1bits.ADNREF = 0; // Negative Voltage Reference is GND
 ADCON0bits.CHS = 0x0F; // Analog Channel not connected
    ADACT = 0; // No auto-conversion trigger selected
 ADON = 1; // ADC is enabled

 //I2C Configuration:
 TRISC0 = 1; //SCL
 ANSC0 = 0;
 TRISC1 = 1; //SDA
 ANSC1 = 0;
 SEN = 1; // Clock stretching is enabled
 SSPM0 = 0; // I2C Slave mode, 7-bit address
 SSPM1 = 1; // I2C Slave mode, 7-bit address
 SSPM2 = 1; // I2C Slave mode, 7-bit address
 SSPM3 = 0; // I2C Slave mode, 7-bit address
 SSP1ADD = 0x20; // 7-bit I2C Slave address
    SSP1ADDbits.ADD1 = AD0;
    SSP1ADDbits.ADD2 = AD1;
    SSP1ADDbits.ADD3 = AD2;
    SSP1ADDbits.ADD4 = AD3;
 SSPEN = 1; // Enables the serial port and configures the SDA and SCL pins

}

microbot.it

Starting Member

  • Total Posts : 57
  • Reward points : 0
  • Joined: 2008/11/20 07:11:47
  • Location: 0
  • Status: offline

Re: I2C responds NACK every time


2017/06/26 08:03:53

(permalink)

and this is the arduino code:

#include <Wire.h> // library used with I2C protocol

#define I2C_address 0x1F
int led = 13;

void setup()
{
  Wire.begin();
  pinMode(led, OUTPUT);
}

void blink_led()
{
  digitalWrite(led, HIGH);
  delay(25);
  digitalWrite(led, LOW);
  delay(25);
}

void loop()
{
  Wire.beginTransmission(I2C_address);
  Wire.write(0x00);
  Wire.endTransmission();
  blink_led();
  delay(500);
}

Gort2015

Klaatu Barada Nikto

  • Total Posts : 6043
  • Reward points : 0
  • Joined: 2015/04/30 10:49:57
  • Location: 0
  • Status: offline

Re: I2C responds NACK every time


2017/06/26 08:54:05

(permalink)

Still incomplete.  It will never work without the core functions.

 You should write some low level i2c functions like stop, start, restart etc…

microbot.it

Starting Member

  • Total Posts : 57
  • Reward points : 0
  • Joined: 2008/11/20 07:11:47
  • Location: 0
  • Status: offline

Re: I2C responds NACK every time


2017/06/26 09:03:08

(permalink)

Gort2015
Still incomplete.  It will never work without the core functions.

 You should write some low level i2c functions like stop, start, restart etc…

Why?
i always used this way and it worked fine.
At this level i just need to recognize address call (i will have interrupt flag SSP1IF), read the buffer to clear the BF flag and turn on a led to know if the last byte was an address or a data…
What i making wrong?

Gort2015

Klaatu Barada Nikto

  • Total Posts : 6043
  • Reward points : 0
  • Joined: 2015/04/30 10:49:57
  • Location: 0
  • Status: offline

Re: I2C responds NACK every time


2017/06/26 09:33:05

(permalink)

If you are using i2c then you need core functions not just one single piece of code,
otherwise you will get nack/ack problems.

 You are not starting and stoping.

Mysil

Super Member

  • Total Posts : 4604
  • Reward points : 0
  • Joined: 2012/07/01 04:19:50
  • Location: Norway
  • Status: offline

Re: I2C responds NACK every time


2017/06/26 10:31:17

(permalink)

Hi
The original poster is writing Slave code for the PIC16
He already have Master code running in the Arduino.
Writing functions like «stop, start, restart etc…»  for the slave device is beyond misleading.

 Then:

This means that the adress is correct …

This may not be correct at all.
NACK and No Response is the same thing,
the only sure indication that PIC16 slave respond to the address, is:  if (SSP1IF) {…
bit getting set, and code entering the «if …» block.
For this to happen, the correct address must be entered in SSPADD register, and SSP hardware correctly set up and enabled, and PIC16 running.

 I2C address in SSPADD register shall be left-shifted 7 bit address, aka. 8 bit address.
Meaning, the left 7 bits of SSPADD register are compared to left 7 bits of address byte received from the bus.

 One possible experiment is to clear SSPMSK register:  SSP1MSK = 0;
then slave will respond to any address from the master.

 Regards,
   Mysil

qhb

Superb Member

  • Total Posts : 9999
  • Reward points : 0
  • Joined: 2016/06/05 14:55:32
  • Location: One step ahead…
  • Status: offline

Re: I2C responds NACK every time


2017/06/26 13:24:09

(permalink)

microbot.it
I send i write command by an Arduino UNO to the PIC, but the PIC responds NACK after the adress byte.
This means that the adress is correct and the communication is going on

No it doesn’t!
As Mysil stated, «NAK» means the PIC did NOT respond.
That could be caused by all sorts of problems.
** Wrong address
** SDA and SCAL reversed
** SDA and SCL connected to wrong pins

What is this code doing?
You set the address, then immediately overwrite it with something else

SSP1ADD = 0x20; // 7-bit I2C Slave address
SSP1ADDbits.ADD1 = AD0;
SSP1ADDbits.ADD2 = AD1;
SSP1ADDbits.ADD3 = AD2;
SSP1ADDbits.ADD4 = AD3;

microbot.it

Starting Member

  • Total Posts : 57
  • Reward points : 0
  • Joined: 2008/11/20 07:11:47
  • Location: 0
  • Status: offline

Re: I2C responds NACK every time


2017/06/27 00:31:22

(permalink)

Sorry, i wrote not clear enought.

Mysil

This may not be correct at all.
NACK and No Response is the same thing,
the only sure indication that PIC16 slave respond to the address, is:  if (SSP1IF) {…
bit getting set, and code entering the «if …» block…

Yes, the PIC enter the IF block and i see OUT2 changing its status via a LED (it is a define to a pin).
What appens is that it never change the OUT1 status, so never receive DATA byte but it receive ADDRESS byte only, so probably it responde with NACK and master stop the communication.
If a switch OUT1 with OUT2 just OUT1 is blinking.. so both pins have right configuration.

qhb

What is this code doing?
You set the address, then immediately overwrite it with something else

I have setted a default address value and changed it via a four bit dip switch to connect more boards (later).

 About the address, i also used a «i2c scanner» sketch in Arduino and verified that the led attached on OUT2 blinks only on the right address.

microbot.it

Starting Member

  • Total Posts : 57
  • Reward points : 0
  • Joined: 2008/11/20 07:11:47
  • Location: 0
  • Status: offline

Re: I2C responds NACK every time


2017/06/27 05:13:58

(permalink)

Mysil

One possible experiment is to clear SSPMSK register:  SSP1MSK = 0;
then slave will respond to any address from the master.

Just done, OUT2 blink for each adress byte (from 0 to 127) but never accepts data byte (OUT1 never blink)

Gort2015

Klaatu Barada Nikto

  • Total Posts : 6043
  • Reward points : 0
  • Joined: 2015/04/30 10:49:57
  • Location: 0
  • Status: offline

Re: I2C responds NACK every time


2017/06/27 06:39:00

(permalink)

I have a function that scans the i2c bus for addresses and either prints to stdout (List is NULL) or to a byte array (List is addr).  No of devices found is returned

 In 16bit asm so you’ll need to convert to C or 8bit asm.

 int scanI2C     (unsigned char *List);  //write to *List, if null write to stdout, return device cnt

.include "xc.inc"
.global _scanI2C
;----------------------------------------------------
.section i2c_data,data
device_text:    .string "device 0x"
found_text:     .string " foundr"
.section i2c_code,code
;----------------------------------------------------
.equ arg_pList,     w0
.equ tmp,           w2
.equ cnt,           w8
.equ id,            w9
.equ plist,        w10

_scanI2C:   ;int scanI2C(unsigned char *List)
    push.d  w8
    push    w10
    mov     arg_pList,plist
    clr     cnt
    mov     #0xfe,id
loop:
    rcall  _startI2C
    ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
busy:
    mov     I2CCON,tmp
    and     #0x1f,tmp
    bra     nz,busy
    ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    mov     id,I2C1TRN
wait:
    btsc    I2CSTAT,#TRSTAT
    bra     wait
    ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    btsc    I2CSTAT,#ACKSTAT
    bra     next
    ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ;found
    inc     cnt,cnt
    cp0     plist
    bra     z,print
    ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ;to list
    mov.b   id,[plist++]
    bra     next
    ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
print:
    mov     #device_text,w0
    call    _puts
    mov     #16,tmp
    repeat  #17
    div.u   id,tmp
    push    w1
    ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ;high nibble
    cp      w0,#9
    bra     leu,$+4
    add     #7,w0
    add     #48,w0
    call    _putchar
    ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ;low nibble
    pop     w0
    cp      w0,#9
    bra     leu,$+4
    add     #7,w0
    add     #48,w0
    call    _putchar
    ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    mov     #found_text,w0
    call    _puts
    ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
next:
    rcall   _stopI2C
    dec2    id,id
    bra     nz,loop
    mov     cnt,w0
    pop     w10
    pop.d   w8
    return
;----------------------------------------------------
.end

microbot.it

Starting Member

  • Total Posts : 57
  • Reward points : 0
  • Joined: 2008/11/20 07:11:47
  • Location: 0
  • Status: offline

Re: I2C responds NACK every time


2017/06/27 06:46:46

(permalink)
☄ Helpfulby mxhyj 2020/12/15 04:30:54

Ok i solved the problem…
i forgot to assign the PPS registers.
Now it is working adding this code:

    // PPS assignment
    SSP1CLKPPS = 0b10000;
    SSP1DATPPS = 0b10001;
    RC1PPS = 0b11001;
    PPSLOCK = 0x55;
    PPSLOCK = 0xAA;
    PPSLOCKED = 1;

Thank you all

CinziaG

die fucking humans

  • Total Posts : 3183
  • Reward points : 0
  • Joined: 2016/12/07 14:20:36
  • Location: Wien
  • Status: offline

Re: I2C responds NACK every time


2017/06/27 08:08:42

(permalink)

PPS on I2C? Oh, those new PICs… Smile

Gort2015

Klaatu Barada Nikto

  • Total Posts : 6043
  • Reward points : 0
  • Joined: 2015/04/30 10:49:57
  • Location: 0
  • Status: offline

Re: I2C responds NACK every time


2017/06/27 08:40:41

(permalink)

Yes, pps on i2c should have happened on the first pps chips.

CinziaG

die fucking humans

  • Total Posts : 3183
  • Reward points : 0
  • Joined: 2016/12/07 14:20:36
  • Location: Wien
  • Status: offline

Re: I2C responds NACK every time


2017/06/27 08:52:48

(permalink)

I used to know that it was because of open-drain/5V tolerant pins…

mxhyj

New Member

  • Total Posts : 7
  • Reward points : 0
  • Joined: 2020/04/10 00:02:08
  • Location: 0
  • Status: offline

Flagged as Spam (3)

Re: I2C responds NACK every time


2020/12/15 04:33:08

(permalink)

Thank you, I stuck on this problem for days.
Your post solved my problem, appreciate it ^^

ric

Super Member

  • Total Posts : 35931
  • Reward points : 0
  • Joined: 2003/11/07 12:41:26
  • Location: Australia, Melbourne
  • Status: offline

Re: I2C responds NACK every time


2020/12/15 12:22:58

(permalink)

mxhyj
Thank you, I stuck on this problem for days.
Your post solved my problem, appreciate it ^^

Which post?
This reply looks suspiciously like a generic post from a spammer to get a foot into a forum.

I also post at: PicForum
To get a useful answer, always state which PIC you are using!

1and0

Access is Denied

  • Total Posts : 15913
  • Reward points : 0
  • Joined: 2007/05/06 12:03:20
  • Location: Harry’s Gray Matter
  • Status: offline

Re: I2C responds NACK every time


2020/12/15 12:39:48

(permalink)

Agree. Microchip needs to close newly opened accounts after a period of inactivities.

Понравилась статья? Поделить с друзьями:
  • Error received data timeout
  • Error receive read timeout
  • Error recaptcha placeholder element must be an element or id
  • Error reason unhandled exception киберпанк 2077
  • Error reason assert киберпанк