text:
NodeMCU Exception 28 - intermitent problem
I am SOMETIMES getting exception 28 when running a web upload (over a very unstable rural internet CPE link - wifi is fine, but feed goes on and off):
Decoding stack results
0x40213b8c: dns_gethostbyname at core/dns.c line 1472
0x40204d95: ESP8266WiFiGenericClass::hostByName(char const*, IPAddress&, unsigned int) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266WiFi/src/ESP8266WiFiGeneric.cpp line 468
0x40208d7c: HardwareSerial::write(unsigned char const*, unsigned int) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/HardwareSerial.h line 159
0x4020519c: WiFiClient::connect(char const*, unsigned short) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266WiFi/src/WiFiClient.cpp line 98
0x40208fe0: Print::println(char const*) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.cpp line 190
0x402040c4: uploadAgrigis(char const*) at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 360
0x40208f41: Print::write(char const*) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.h line 60
0x40208f6c: Print::println() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.cpp line 178
0x40204a2b: loop() at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 258
0x402074f0: TwoWire::endTransmission() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/Wire/Wire.cpp line 151
0x40203a04: BH1750_Init(int) at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 1121
0x40209d3c: loop_wrapper() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/core_esp8266_main.cpp line 125

My code at line 360 is
if (client.connect(serverName,80)) {

My current strategy is to keep the wifi connection open all the time.  Should I test for connection before attempting to connect to the server?

Exception 28 is, according to the exception list document:

Access to invalid address

The most common cause is trying to read or write from/to a NULL pointer.
It could be because you have debugging turned on, and that debugging is trying to print something that didn't get returned properly from another function call (the call failed) - most likely looking up a host name (hostByName()) due to your intermittent internet connection.
This may sound counter intuitive, but try turning off debugging to see if that helps reduce the number of crashes.

counterintuitive makes sense.  lemme give a couple of days' benchmarking and I'll get back.  UPVOTED, pending ACCEPTANCE.

didnt solve the issue.  trying lwIP level change to 1.4 as per https://github.com/esp8266/Arduino/issues/4078

that didnt help either...  stumped

@tonygil You should cut your program down to the absolute minimum and add in different parts until it starts failing.

tks.  will do.  will run separate rigs with different levels of complexity.


text:
A recommendation for a fast-response-time-resolution-mp3-module for arduino
I am working with Arduino which activates a box which is similar to a Skinner Box. Some of the output sound stimuli are sine waves with duration of less then 5 milliseconds. I output the sounds using the MP3 module DFR0299.
However there are too much problems using this module: it seems like the module has a wakening delay of around 100 ms, so it is not working well with this duration and below (the response time of the module is important).
So, I was thinking of buying a better module. However, I am far from being an expert in these things..
I can look for other modules in the internet, but, just from looking at the datasheets, I cant tell if the quality of the module is what I need.
I would be grateful if any of you could give me names of modules that might feet my requirements (or even advice me at what to look in the datasheets)
Thanks!

Why do you want to use MP3 for this? Are your sounds complex or just simple sine waves? (The complexity of the sound is rather limited in a time of 5ms) In that case it is easier and faster to generate them on the Arduino without using something as complex as MP3

I think the OP is referring to a hardware module for replay of the mp3 file, which effectively uses arduino only as a control mechanism rather than a processing device.

@chrisl, for now I use simple sine waves using a function generator, triggered by the Arduino. However, in the future I will need to switch to more complex waves.. Thanks

I'm going to suggest that you stay away from these mp3 modules. It is perfectly reasonable to use a stand-alone arduino unit to directly generate sound using the digital output pins with a low-pass filter RC circuit. This is the most efficient way of doing this and will give you a very low activation latency.
https://playground.arduino.cc/Code/PwmFrequency/
The other option is to connect a DAC circuit and simply build a sample table for the wave outputs you need for each tone.

OK thanks I will have a look. I tried a similar thing (I think), I created the basic arduino square wave and added resistors and capacitors to "smooth" it to a sine form, But somehow the result (shown in the scope) looked very noisy.. maybe will give it another shot. Thanks

MP3 modules are way to complex for this project. Tracks of 5ms at max may even be stored directly on the Arduino in raw wave format (without any compression)(depending on the resolution and sample frequency), and then outputted by it.
Since the PWM with low-pass filter method is rather noisy and not very accurate (especially for higher frequencies), you may want to use an external DAC chip. These are available with parallel input port or with SPI. I would suggest using SPI, which is fast and does only need 3 pins (+1 for slave select, if needed). Put the raw wave values into an array and send them to the DAC to output. Depending on available memory and number and size of your tracks you may be able to save them directly on the Arduino. If not, you may want to use an SD card, to save a library of tracks, which then get loaded onto the Arduino and played. This way you would only need to hold 1 or 2 (if double buffered) tracks in the Arduino's RAM.

If you have an Arduino with a SAMD21 on it: I have written a small library for doing just that using the built-in DAC. Early days and version yet, but it works. It's here and it's free: https://github.com/ocrdu/Arduino_SAMD21_Audio_Player

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Can't fetch arduino param on server, Using POST method via arduino wifi shield
I am creating a slot sensor, using photoresistor.
The goal is to send the photoresistor value, via analog read, pin A0 to my web server, so I can stored it in my database.
void loop() {
  int sensorvalue = analogRead(A0);// LightValue, read from sensor pin A0
  data = "sensorValue=" + (sensorvalue);
  //there is a car parked
  if(sensorvalue >=1000){
    if(flagstatus == false){
            if (client.connect(server, 80)){
              Serial.println("Connected to Host Server");
              client.println("POST /dataPost.php/HTTP/1.1");
              client.print("Host:");
              client.println(server);
              client.println("Content-Type: application/x-www-form-urlencoded");
              client.print("Content-Length: ");
              client.println(data.length());
              client.println();
              client.print(data);
I've been trying to send mock data via postman, and it works like a charm, so I can eliminate my server side from the equation. Been guessing using : or = on sensorvalue=analogread(a0) or sensorvalue:analogread(a0). Or I made mistake on the code? I don't know much in Arduino, and this issue kinda frustrate me.

the Image just for confirmation only, of course I installed the protoboard correctly.
Connect to SSID: Adamar
IP Address: 192.168.1.14
Connect to server...
Connected with network---------
Connected to Host Server
sensorvalue:1007
There is still a car parked
sensorvalue:1007
There is still a car parked
sensorvalue:1008

I manage to get this result from my serial monitor, so I think there is no wrong reading from my setup.

Before you start writing software that generates HTTP requests, you really should learn the format of an HTTP request.

hi, thank you for your friendly reminder :) Any suggestion? been go back and forth around this topic without any clear answer. About format, all snippets code, and example code from arduino written that way :)

You might want to look at the line "POST /dataPost.php/HTTP/1.1"

thank you for the hint on POST /dataPost.php/HTTP/1.1 , could you please be more elaborate?

The correct format is POST /dataPost.php HTTP/1.1

Hi, thank you for spotting my mistake. I already update my arduino sketch. It almost took my breathe away, but I hate to say this. The issue persist.
client.connect("the******tem.com", 80)){       client.println("POST /dataPost.php HTTP/1.1");        client.println("Host: the******tem.com");       client.println("Content-Type: application/x-www-form-urlencoded");       client.print("Content-Length: ");        client.println(data.length());       client.println();       client.print(data);       client.stop();
already double check with http request format. Any idea about this?

you have not said anything about any errors that you are or are not getting

@jsotola Hi, thank you for highlight this. But I am really sorry, I didn't get any errors report.

print the response

hi @Juraj it is nice to meet you here. I read a lot your answers. You are such a big help for community.  What kind of response do you need?
It confuse me, since we still can see sensor value from serial monitor.
I would like to update this issue, it may be because of server hosting fault. I can manage to store data via GET although I understand it is not the best practice.

Thank you @Majenko :)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Adding bootloader to Feather M0 Bluefruit LE
I want to make a custom Feather M0 Bluefruit LE. I know this means that I will have to add a bootloader to the ATSAMD21G18.
I have seen that there are many useful articles in relation to adding bootloader to this chip like
https://www.instructables.com/id/ATSAMD21g18-Bootloader-With-J-link-Debugger/
and
https://learn.adafruit.com/proper-step-debugging-atsamd21-arduino-zero-m0/restoring-bootloader
and
https://learn.adafruit.com/compiling-m0-atsamd21-bootloader/compile
I wanted to make sure that the bootloader will allow me to access the Bluetooth module on the board. Does anyone know if this bootloader will do that? Or is there another type of bootloader I need? Also, do I need a J-link connection on the custom board? can I just use USB?

it is unclear what this means ... allow me to access the Bluetooth module

purpose of bootloader is to load the application over USB. bootloader has nothing to do with BLE. you can't load the bootloader over USB. bootloader is what makes upload over USB possible

Hi @jsotola I didn't know if I had to set a specific module in Bootloader or if I can just use the generic bootloader files I found on those links above and then upload firmware to access the BLE afterwords.


text:
Changing I2C address of MPU-6050
Is it possible to change I2C address of MPU-6050 ?
I am trying to connect a bunch of MPU-6050 to my Arduino.
Almost all of them are running on the same address. Few are running on different address.
Can anyone tell me how to change I2C address of MPU-6050 if it is possible ?

check the datasheet

The MPU-6050 has a pin that allows control the LSB of the I2C address. This pin can be used to allow multiple devices. For 1-2 devices use the pin directly. For >2 devices use a GPIO pin per device. Web-search "multiple MPU-6050".

The MPU-6050 has an address pin, marked as A0, which can be used to set the LSB (least significant bit) of the address. So if you connect A0 to ground, the address will be 0b1101000, if you connect it to Vcc it will be 0b1101001. You can find this information in the table under capter 6.4 in the MPU-6050 datasheet (page 15). Normally this pin is getting hardwired, but you can also connect A0 to a digital output pin of your Arduino and dynamically change the address of the MPU.
So with this pin you can have 2 different MPU-6050's on the bus. If you need more, you can keep all MPU's on one address, while pulling the MPU, that you want communicate with, to the other address. I described this principle at the end of my answer to this question. It is about a different chip, but the principle is the same.
It is important, that you cannot have multiple devices with the same address on one I2C bus, unless you never communicate with that address. When you try to use an address, where multiple devices will answer, the I2C bus most likely will get stuck, or the data will get corrupted. As long as such an address is never called, everything is fine.


text:
WiFiServer Stops After Reconnection to WiFi
In the following code, the Arduino is reconnecting to the WiFi after several loops. The idea is to check and re-establish WiFi connection every 30 minutes or so.
However, the WiFiServer seems to stop working after the reconnecting to the WiFi network. At least I get a timeout, if I try to request data by calling the Arduino's IP address.
#include <SPI.h>
#include <WiFi101.h>

// the IP address for the shield:
IPAddress ip(12,34,56,78);

char ssid[] = "wifinetwork";
char pass[] = "correcthorsebatterystaple";

int status = WL_IDLE_STATUS;
int count = 0;
int retries;

WiFiServer server(80);

void setup()
{
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  connectToWiFi();

  server.begin();
  Serial.println("Server Started");
}

void loop () {
  count++;
  Serial.println(count);
  WiFiClient client = server.available();

  if(client) {
    Serial.print("Connected to a client : ");

    if(client.connected()) {
        Serial.println("Response Sent to Client");
        client.println("Data");
    }

    delay(5);
    client.stop();
    Serial.println("Client is disconnected");
  }

  if (count > 10) {
    Serial.println("Reconnect to WiFi");
    connectToWiFi();
    server.begin();
    count = 0;
  }

  delay(2000); // Wait for 2 seconds before starting to listen again
}

void connectToWiFi(){
  WiFi.config(ip);
  retries = 0;

  // attempt to connect to Wifi network:
  do {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
    retries++;
    delay(2000);
  } while(status != WL_CONNECTED && retries < 3);

  if (WiFi.status() == 3) {
    Serial.println("Connected");
  }
}

begin() it again

Already tried that, but unfortunately did not change anything. I edited the code above.

why do you reconnect?

I can't guarantee a stable/continuous WiFi connection. Hence, the Arduino shall search and reconnect to the WiFi network every few minutes, because it may lost connection.

you could try to reinitialize the server object with server = WiFiServer(80) and then begin() it. (the assignment copies the content of the temporary object into the existing instance.)

Unfortunately, this does not solve the issue.


text:
Effective Controlling of Continous Servo Motor
I have difficulty in controlling a MG995 continuous motor. For I know I can control the speed of the motor as writing servo1.write(p) , where the value of p changes the speed of the motor. When the value of p is set to 90 then the motor stops ,whereas 0 and 180 values allows it to move in the top speed in C.W and Anti C.W direction respectively.
...........** I had difficulty in writing a code where I can rotate the servo motor for 180 degrees then rotating back again to 0 and whenever my ultrasonic sensor finds any object the servo should stop at that point for further action. ** ........
(I think this value could be useful :Operating speed: 0.2 s/60º (4.8 V), 0.16 s/60º (6 V))

You want to rotate at any speed that you want, or you want to rotate to any angle that you want?

I want to rotate at a specific angle .

Then you need some form of feedback from the motor's shaft to know what angle it is at. Normally if you want an angle then you don't want a continuous rotation servo.

I have a feeling that by using time functions we can rotate it at any angle .If my calculations are correct then for every angle it takes 3 milliseconds to turn.Well I don't know if we can use this

You can get an approximation, but it will drift over time. That's a "nominal" speed, not taking into account acceleration and deceleration and variances in manufacturing.

what are you trying to do ... your question says nothing about the end goal of your project

I am trying to make a Radar type mechanism which will sweep to a particular angle and help the ultrasonic sonic sensor to locate an object .....

According to your project description, it sounds like you need a typical non-continuous servo motor - one that rotates to a specific angle. Do you actually need rotational speed control? You could do both with a continuous, speed-controlled servo but it is only going to servo on rotational speed; you'll need to do the control on angle with a shaft encoder and software.

Initially I wanted a typical non-continuous servo but instead amazon got me a continuous servo even when the description had clearly mentioned of a non-continuous servo.

Have you been able to rotate the servo to a position, stop and go back to the initial position? Could you try doing it with the "servo1.write" function and the delay function (or using a busy-loop)?


text:
Why Buzzer interfere with PWM?
This is the code:
#define TMST A2 // Thermistor
#define BZR 10  // Buzzer
#define FanP 11 // Fan

void setup() {
  DDRD = B11000000;
  DDRB = B00001111;
  DDRC = B00000000;
  TCCR2B = TCCR2B & B11111000 | B00000101; // pin 3 & 11 -> 245Hz
  T0 = 25 + 273.15;
}

void loop() {
  if (hallState > magnetDistance) {
    PORTB &= ~(1 << 0); // port manipulation -> LOW
    strcpy(WPStatus, "OFF");
    if (Alarm == 1) { // this will be set in setting menu
      if ((millis() - BZRT) > 500) {
        tone(BZR, 2300);
        BZRT = millis();
      }
      if ((millis() - BZRT) > 250) {
        noTone(BZR);
      }
    }
    else {
      noTone(BZR);
    }
  }
  else {
    PORTB |= (1 << 0); // port manipulation -> HIGH
    noTone(BZR);
    strcpy(WPStatus, " ON");
  }

  if ((millis() - fanTimer) > 2000) { // checks every 2 seconds if temperature changed
    Thermistor();
    if (TX <= 32) {
      analogWrite(FanP, 60); // Fan spinning speed
    }
    if (TX > 32 && TX <= 36) {
      analogWrite(FanP, 120);
    }
    if (TX > 36) {
      analogWrite(FanP, 255);
    }
    fanTimer = millis();
  }
}
float Thermistor() { // reading and calculating from thermistor
  VRT = analogRead(TMST);
  VRT = (5.00 / 1023.00) * VRT;
  VR = 5 - VRT;
  RT = VRT / (VR / 10000);
  ln = log(RT / 10000);
  TX = (1 / ((ln / 3977) + (1 / T0)));
  TX = TX - 273.15;
  return TX; // returning the temperature
}

The 5V buzzer connected to a PWM pin with a 100 ohm resistor, thermistor and fan are connected to Arduino like this:

simulate this circuit – Schematic created using CircuitLab
Why When buzzer is alarming fan stops spinning?

I have an idea why, but from that code snippet I cannot be certain. You need to post your whole code, since the part that will tell me if I am right in my surmise or not is the part you have replace with the comment "// defined Variables and stuff".

@Majenko the whole code is too long, but i added the part you mentioned.

Ta. Also, which Arduino are you using for this?

@Majenko Arduino UNO

"Use of the tone() function will interfere with PWM output on pins 3 and 11." https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/

the pin for tone() doesn't need to be a pwm pin

The tone() command uses Timer2 to generate the square wave (it triggers an interrupt which toggles an IO pin).
However Timer2 is also used to generate the PWM signal on pins 3 and 11.
Thus you cannot use tone() and PWM on pins 3 or 11 simultaneously.
The simple fix: use PWM from pins 5, 6, 9 or 10 to control your fan.

an off topic question; since i can't use that pin anymore and other pins are occupied, is it better to use a series of diodes to reduce the fan speed or a high wattage resistor would work?

A high wattage resistor would work. That is basically what is used in mains fans with the buttons that change the speed.

you're the best.

@newbie, you can use pin 10 for fan and pin 11 or any other pin for tone()

@Juraj then i have to rework the whole PCB, i already spent almost 2 month on this project. that's enough. thanks for the suggestion.

If you don't mind your sketch blocking while playing a tone there is TimerFreeTone

or you can change the timer used by the tone() library


text:
GY91 IMU module, Interrupt?
Are there interrupt Pin in the GY91 Module?
If not, are there good alternative for periodic sensor reading?
(apart from mcu schedule/external timer)

No. The INT pin of the MPU-9250 is not presented on the IO header of the GY-91.
The only way of knowing what is going on inside the MPU-9250 at any time is to go and look. I.e., periodic polling of the sensor.
If you want to use the interrupt pin you will have to shop around for a different module that gives you access to that pin.


text:
flash read err, 1000
I know this question has been asked multiple times but solutions giving there hasn't been working,
I've got an esp32 soldered to my own designed PCB board with a UART to USB converter all that is working fine, I can get connected to my esp from the Serial monitor.
But it prints every about 0.5s:
rst:0x10 (RTCWDT_RTC_RESET)
boot:0x13 (SPI_FAST_FLASH_BOOT)
flash read err, 1000 ets_main.c
371 ets Jun 8 2016 00:22:57

Solutions have been to make sure to have 3.3v on the esp. I find it unlikely to have anything to do with it, 'cause its voltage range goes from 2.6v to 3.6v, but anyway I have tested it with an advanced transformer and a multimeter to check that there was 3.3v on the Vcc pin (didn't change anything).
All help would be appreciated.
Here is a bit more info:
I've also connected a 10uF capacitor (someone told me to try that).
If I pull IO0 to ground, it prints waiting for download in the serial monitor and I can almost upload the program, this is what I get:

THERE IS NO CONNECTION BETWEEN NEIGHBORING PINS

(I have checked with multimeter)
PCB board:

Please provide images of your custom PCB

I had this kind of error sometimes and it always seemed to be related to a broken flash in the esp32. Do you have anything connected to the SPI pins?

@SimSon could you explain what the SPI pins is? (sorry for my lack of knowledge)

The esp chip itself doesn't have an internal flash to store the program but uses an external flash instead. Communication with this flash happens via serial peripheral interface (SPI) which also is available on the esp's pins. Obviously you haven't connected anything except the serial lines.

How did you assemble the esp on that pcb? Reflow? Solder iron? I just wonder why the surface looks a bit demolished...

solder iron and flux, the "demolished" is left overs from the flux

@SimSon the tutorial on hooking up your esp with usb, does not need or contain any "SPI", but do i have to connect the SPI i pins to something? and does they only need to be connected during upload?

@MariusWanscher there's no need for anything like that, the esp is connected to the flash internally and its firmware/bootload manages everything

@MariusWanscher ok, I just couldn't see wether it was flux or the pcb might have become too hot during reflow. From my experience the flash is the least temperature-tolerant part inside the esp. Was flashing actually ever possible on this individual?

@MariusWanscher no, not the spi pins!

How do you actually flash it without having the flash- and reset-pins connected to your pcb? Also your pcb is missing pull-up resistors. Have you taken a look at a minimal circuit? https://www.14core.com/wiring-and-flashing-programming-esp-32-esp32s-with-usb-ttl-uart/?cn-reloaded=1

No, I haven't gotten it to fully flash, ArduinoIDE says that it has uploaded the whole program but afterwards, the serial monitor goes quiet, if I restart the chip(by pulling EN to ground) it just starts spitting out the ram 1000 err

I simply take a jumper cable and connect it with ground and touch either io0 or EN

ok, the solution was to add a 10k pull-up resistor to the EN pin, as shown HERE
No capacitor needed

Your PCB is lacking in the majority of things you need to get the module working. These modules are not "simple" in that you provide power and forget about it. You must add all the required support components. Those support components are NOT optional. For example: you aren't setting the boot mode properly with the right pullups. You lack a capacitor on the power pins (I told you to add one already. Where is it?). Also your power traces are too thin. The impedance is too high.

there is a 10uF capacitor added, its the second black and red wire you see on the image, I have moved it directly on the power pins, still not working

and what do you mean by "I'm not setting the boot mode properly", serial monitor literally says it's in boot mode

There's many ways of booting the ESP32. You haven't selected one. Read section 2.4 "Strapping Pins" in the ESP32 datasheet.

And you can't have a decoupling capacitor on the end of a pair of wires. It makes it pointless. Solder it directly on to the power pins of the module. https://photos.app.goo.gl/rjTESshnQGQjjtmdA


text:
Lipo Battery level display using nodemcu
I'm designing a connected collar for pets for a project, for this I am using a nodemcu on ESP8266 powered by a Lipo battery I'm guessing around 1000mAh of capacity is enough for a respectable autonomy (? any advices).
Lipo model : https://www.lipolbattery.com/lithium%20polymer%20battery.html
In order to charge the battery I have found this USB LiPo charger (https://learn.sparkfun.com/tutorials/lipo-usb-charger-hookup-guide/all), my first question is: Is it still usable for higher capacity LiPo batteries (1400mA)?
Also I would like to display the battery level via and RGB LED (example: green is for battery FULL battery and RED for LOW battery level in need of charging) is there any way to do this? Thank you

Measuring LiPo capacity is tricky. I would suggest investing in a "Fuel Gauge" chip to measure it for you. (Eg: https://www.sparkfun.com/products/10617)

I found his project any suggestions?
https://www.teachmemicro.com/arduino-lipo-battery-monitor/

It is still usable for higher capacities. I recommend you tp4056 and some step up converter.
You can use resistor divider (that drops safely voltage to nodemcu 3.3v) and connect its output to an analog pin of your nodemcu. Values of resistors must be high, like 10k.
You can simply connect your diode to nodemcu and code if voltage is less than 3.2v let the red diode turn on, when above 3.8v let the green diode turn on

Answering the second question "Also I would like to display the battery level...?" (next time, please open a new question for that):
To measure the module voltage level (a.k.a. VCC) of a NodeMCU (which is just a board containing an ESP8266 chip) programmed in Arduino IDE (which I assume given that you ask on the arduino stackexchange), this here applies:

To read VCC voltage, use ESP.getVcc() and ADC pin must be kept unconnected.
  Additionally, the following line has to be added to the sketch:
ADC_MODE(ADC_VCC);
This line has to appear outside of any functions, for instance right after the
  #include lines of your sketch.

Source: ESP8266 Arduino reference
So you could just drive a red and a green LED (don't forget the mandatory current limiting resistor) from any other two pins of your NodeMCU. Then switch them in your sketch if VCC falls below 3.2V (you may need to experiment with that because of measurement tolerances; a sketch to start with that would be here.


text:
What is the format specifier for string in arduino
I have a string formattedDate.
When I am trying to give sprintf(payload,"{\"timestamp\":\"%s\",\"temperature\":%f,\"humidity\":%f}",formattedDate,t,h);
Its not printing the date and time.

Are you certain that formattedDate contains data?

is formattedDate a String? then use formattedDate.c_str()

When I use this I am able to print date and time --> Serial.println(formattedDate);

Actually, I am trying to send DHT11 data to AWS cloud. I am able to send temperature and humidity. I want time also to get imported for visualization. I am using NTP for date and time, so included the NTP libraries and this is working --> formattedDate = timeClient.getFormattedDate();
Serial.println(formattedDate);  --> But i want it to print in JSON format. So I am printing like this sprintf(payload,"{"timestamp":%s,"temperature":%f,"humidity":%f}",formattedDate,t,h); But here i am unable to print date and time some random boxes and question marks are being printed.

println has a version for String sprintf doesn't

Can you please give me an idea to print the formatted date in JSON format so that I can visualise the data in quicksight

read my first comment


text:
Arduino Uno not turning on
I have bought an arduino uno but when i plugged in the arduino to my laptop its not turned on (the built-in LED was off) and at the arduino IDE I wasnt able to change the port (the port button was unavalible)
what should I do for the arduino uno board to work?

Check your USB cable first. If that is fine, check your USB port. If that is fine then, if it's a genuine Arduino return it for a replacement or refund. If it's a cheap Chinese clone then throw it in the bin and buy a real Arduino.

If you have an Arduino clone with a CH340G chip, you need to install a CH340G driver.

Not having the driver won't keep it from powering on tho, that will just prevent comm's.

@CrossRoads, true indeed.

I second @Majenko; cheap clones are very prone to fail out-of-the-box. That said, what laptop do you have? What Operating System? How is your laptop powered (ie. perhaps USB isn't able to handle the electricity needed)? What happens if you power it from a power supply connected to your household mains voltage?

You could check (measure with a DMM) whether you see 5V at the 5V pin.


text:
Arduino HTTP Request Fails Slow Cellular Connection
Setup:

Arduino Mega 2560 w/ Wiznet W5500 Ethernet Sheild
Using TP-Link TL-MR6400 LTE router to connect to internet over cellular connection in Uganda.

Using an HTTP Post with the following,

client.println("POST /hook HTTP/1.1");
client.print("Host: "); client.println(server);
client.println("Accept: */*");
client.print("Content-Type: text/html;");
client.println("User-Agent: Arduino/1.0");
client.println("Connection: close");
client.print("Content-Length: ");
client.println(PostData.length());
client.println();
client.println(PostData);

where PostData is a String and Ethernet2 is the library used.
This works just fine from the US to the same AWS server, or a https://requestbin.com/ instance.

When testing from Uganda using a Raspberry Pi and curl it works fine.
$ curl -vs -d 'ABCDEFG' -H "User-Agent: Arduino/1.0"  -H "Content-Type: text/html" -H "Connection: close"   http://<server here>/hook
*   Trying <ip here>...
* TCP_NODELAY set
* Connected to <server here> (<ip here>) port 80 (#0)
> POST /tg HTTP/1.1
> Host: <server here>
> Accept: */*
> User-Agent: Arduino/1.0
> Content-Type: text/html
> Connection: close
> Content-Length: 7
>
* upload completely sent off: 7 out of 7 bytes
< HTTP/1.1 200 OK
< Access-Control-Allow-Origin: *
< Content-Type: application/json; charset=utf-8
< Date: Tue, 06 Aug 2019 21:06:49 GMT
< x-pd-status: sent to primary
< X-Powered-By: Express
< Content-Length: 16
< Connection: Close
<
* Curl_http_done: called premature == 0
* Closing connection 0
{"success":true}

I even tried an HTTP GET example from the Ethernet2 library,
https://www.arduino.cc/en/Tutorial/WebClientRepeating
It worked just fine in the US but in Uganda I get,
My IP address: 192.168.1.177

connecting...

connecting...

connecting...

I increased the time between requests here to 100 seconds where it is listening for the whole time inbetween.
It seems that client.connect(server, 80) is successful and the client.print messages go through but the message never reaches the server so there is no response. My AWS server does not recieve the request and this is the same for the requestbin instance. This behavior is mirrored in all my Arduino tests.
I thought the ISP might be blocking but the RPi can send nearly the same message. I thought maybe a timeout somewhere but I can not find where with my tests. I thought my message was too long but I reduced the size to only 10 characters with the same results.

Trying to figure out why the Arduino HTTP request cannot reach any webhooks from Uganda and how to fix it if possible. Different ISP, slower connection, cellular connection?
Any help would be appreciated.

@jsotola yes, I am able to connect to either server using a raspberry pi on the same network as the arduino in Uganda (connected to the same router). I am also able to connect to both servers with both attempted Arduino sketches from the US. I am here considering a raspberry pi as a computer.

my apologies, i did not read your post carefully ... you already explained that the Pi is connecting correctly

try the Ethernet library

The only things I can think of to try HTTP/1.0 instead of HTTP/1.1. Or maybe combining all the client.prints so everything is send in a single packet, instead of possibly multiple (I couldn't figure out if that is even the case).

yes, use buffering https://github.com/jandrassy/StreamLib/blob/master/README.md

@Juraj Your solution worked for me, if you post an answer I will accept it. As background, I tried the Ethernet lib vs. Ethernet2, I tried HTTP/1.0 vs HTTP/1.1, also adding just a client.flush() statement after my requests. I tried using just an IP address to avoid the DNS requests and speeding things up by using a different, faster, DNS like 1.1.1.1 or 8.8.8.8. Finally the two things that helped were, keeping the connection open whenever possible with Connection: Keep-Alive and the StreamLib library ChunkedPrint example.

Buffering and flush()
Many arduino libraries suffer of slow communication because the authors didn't use buffering. To not to send every small piece of data over a connection with overhead of protocol bytes use buffering. Data are collected until the buffer is full and then the collected data are send and the buffer is ready for next bytes. The flush() functions sends the buffer even if it is not full, but you do not have more data. (The flush() 'dilemma' was resolved and in Arduino core classes the flush() method is declared in Print class which is the Arduino standard interface for output streams.)
My StreamLib library offers a BufferedPrint class which wraps the target stream and buffers the data to be send over the target stream. Of course, do not forget to use flush() after last data printed.

HTTP data length
It is common practice in Arduino sketches to not to send the Content-length header with POST requests. In most cases it is because when the HTTP headers are send, the size of data is not known. The WebServer then doesn't know if it received all the data and waits until the connection is closed or timeout is reached. It leads to long time until a Web Server sends the response to requesting Arduino sketch.
If the data can be prepared to a string in memory, fill the Content-length HTTP header.
If the data to be send as response or in POST request wouldn't fit into available memory, ChunkedPrint from my StreamLib can be used with HTTP chunked Transfer-Encoding. And ChunkedPrint is an extension of BufferedPrint so the Web Server handles your request without hesitating.


text:
Udp.endPacket fails
I am trying to send measurements over UDP, but the function Udp.endPacket continuously fails.
I use an Arduino Uno WiFi rev 2, WiFiNINA library version 1.4.0 and WiFiNINA firmware version 1.2.1 which seems to be the latest available.
WiFi connection setup works, obtaining a correct IP address in the 192.168.3.0/24 network.
This is a snippet of my code:

const char* udpDestIP = "192.168.3.126";
const int udpDestPort = 1844;
WiFiUDP Udp;

void loop() {
  // establish variables for distance result:
  long cm;

  // execute measurement
  cm = measureDistance();

  // check for false measurements and repeat if necessary
  if(minDist < cm && cm < maxDist) {
    Serial.print(cm);
    Serial.print(" cm");
    Serial.println();

    // Check WiFi connection and reconnect if necessary
    if (WiFi.status() != WL_CONNECTED) {
      connectToWifi();
    }

    // Send over UDP
    //if(!Udp.beginPacket("192.168.3.255", udpDestPort)) {
    if(!Udp.beginPacket(udpDestIP, udpDestPort)) {
      Serial.println("beginPacket fail");
    }
    String msg = "water_distance:";
    msg += cm;
    byte size = Udp.write(msg.c_str(), msg.length());
    if(DEBUG){
      Serial.print("Sending this message over UDP: ");
      Serial.println(msg);
      Serial.print("udp write: ");
      Serial.println(size);
    }
    if(!Udp.endPacket()) Serial.println("endPacket fail");

    delay(delayTime);
  }
}

Terminal output is as follows:
151 cm
Sending this message over UDP: water_distance:151
udp write: 18
endPacket fail
151 cm
Sending this message over UDP: water_distance:151
udp write: 18
endPacket fail
33 cm
Sending this message over UDP: water_distance:33
udp write: 17
endPacket fail
34 cm
Sending this message over UDP: water_distance:34
udp write: 17
endPacket fail
153 cm
Sending this message over UDP: water_distance:153
udp write: 18
endPacket fail

Which makes me conclude the beginPacket, and udp.write functions are executed correctly, but I see no reason why the endPacket function keeps failing. Does anyone have an idea? Thanks a lot.

add Udp.begin() to setup(). if it works I write an answer with explanation

This works, thanks a lot! As UDP is a connectionless protocol, is there any reason why one should open a port to listen for incoming UDP packets while the device is only acting as a client emitting UDP fragments?

The UDP packets have to come from somewhere. They don't just appear from nowhere. Like a faucet has to exist and be turned on for the water to come out of it.

The UDP.begin() function requires a source port as argument. For just sending UDP packets, it doesn't matter from which port the packets are coming, the OS can just select a random unused port. Just like it's done in Python or Java. Is there a way to make UDP.begin() use a random unused port as source?

UDP.begin(random(1024, 65536));

The Arduino Ethernet and WiFi library implementations require to specify the outgoing port with UDP.begin(port) before calling UDP.beginPacket().
But UDP.begin(port) starts listening for UDP messages on this port too, so it is not a clean API. Call UDP.end() to stop listening for incoming messages.

Top answer, thanks.

You can accept the answer to mark the question solved


text:
I am working on a thermometer and humidity why am i getting this error
Arduino: 1.8.9 (Windows 10), Board: "Arduino/Genuino Uno"
In file included from C:\Users\Admin\Documents\Arduino\libraries\DHT-sensor-library-master\DHT_U.cpp:15:0:
C:\Users\Admin\Documents\Arduino\libraries\DHT-sensor-library-master\DHT_U.h:36:29: fatal error: Adafruit_Sensor.h: No such file or directory
compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Uno.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

This indicates your IDE is missing the "Adafruit Unified Sensor" library as outlined here.
To install it, select "Tools" -> "Manage Libraries" and search for "Adafruit Unified Sensor". You can install the library by selecting it and pressing "Install".


text:
Arduino detect order of objects
I'm trying to find a way to detect blocks being placed on grid on a table. The table will have fixed places where you can place the blocks, but the user is allowed to place the blocks in any free slot. I would like to have an Arduino poll the slots on the table and tell me which blocks are placed where.
I'm going to design the blocks with magnetic connections on the top and bottom to create a circuit as soon as they are placed.
What kind of chips can I use so that the arduino can give me the topology of the blocks when placed?

You need to constrain your problem further.  For example, if the Arduino is monitoring the placement of blocks the order of the stack can be inferred through inspection of the history of sensor activation.  However, if the Arduino needs to detect the order with out history - then the problem becomes difficult.

Interesting approach to use the timing / history.
However I'm not even sure how to detect the blocks at all at the moment. I don't know what chips to integrate into the table or the blocks to be able to detect them.

This is a situation where OneWire ROMs with unique serial numbers would be good.

"OneWire ROMs", I'll have to google that.  At the opposite end of the spectrum you can key the blocks (cut off a corner) to ensure their orientation with respect to the table and place magnets in unique places for each type.  Then use Hall Effect devices to sense them.

fixing the orientation is definitely a step in the right direction @st2000 !

I did look into a OneWire solution for arduino. It turns out that you can 'scan' for connected devices on OneWire, but it seems to be hard to use more than 1 arduino pin. I guess that would me I require 1 arduino per placement cell of the table @Majenko ?

It shouldn't be hard to have more than one pin - just have more than one OneWire object, each with a different pin. How many tile positions are you wanting to have?

@Majenko it's going to be like a chessboard, so a total of 64 positions. Stacks of objects could be up to 8 high.

That's quite a lot of pins to use for OneWire buses. I'd suggest maybe splitting the project down into sections. Maybe make a single strip of 8 controlled by a small Arduino (nano or micro or something) then put 8 of them together and have them communicate with a master one.

"64 positions. Stacks of objects could be up to 8 high" So... Wow, that's 512 objects.  I think you just left the Arduino realm and entered into Raspberry Pi using a camera and OpenCV.  You did say you would like a completely software defined solution. Well check out OpenCV.  You can look a projects like this and that for ideas.

You need to track unique objects in an 8x8 grid of slots? How many unique objects?
If the total number of objects is 112 or less, you could give each one a unique I2C address.
You'd add 4 circular electrical contacts in a "bulls-eye" configuration on the top and bottom of each object so that all the I2C pins would connect regardless of orientation. All objects in the same stack would be connected together on that stack's I2C bus.
You'd have an 8x8 multiplexer to connect to the I2C bus for each of your 64 grid positions in turn, and poll that bus for each of the possible I2C addresses. (Send a ping for each address and look for ACKs.)

Alternately, you could give every object a unique weight, varied by a power-of-two amount. (first object weighs 1000 grams. Second weighs 1001 grams (1000+2^0)) third object weighs 1002 grams (1000+2^1). Fourth object weighs 1004 grams (1000+2^2). Etc.)
Then you'd put a scale on each pad. Weigh the objects, modulo 1000 grams. That result, in binary, would give you flags for every object on that pad.

Or 2 circular electrical contacts on the top and bottom of each object, with resistors that have unique power-of-two resistance on each one, as Juraj suggests in their comment. Measure the resistance and you can figure out which set of objects is present.
The math would be simpler if you rigged the objects so that they made a series circuit through all objects present (put a normally closed switch on the top that shorts the top contacts of that object through its resistor if there's no object on top of it. If there is an object, the switch would open, and the objects on top would close the circuit.)

Or do you need to know where objects are located top-to-bottom in each stack?

Thanks @Duncan!
Luckily I don't need to know the order of the objects, as long as I have the count for each stack.
I'm going to try your I2C approach first, since I prefer a 'software' solution over a physical solution like weight and resistance.

How many unique objects do you need to deal with? Is it less than the 112 unique objects I2C supports?

@GuusBaggermans, I deleted my comment about the solution with resistors, because it would not detect individual objects, only the count on each stack. The I2C solution is not a software solution. You need to put a powered chip with I2C address in each block and you would still not detect the ordering. So the resistor is much simpler and requires only two interchangeable contacts on each side interchangeable side.


text:
Arduino Mega TIMER1 one second interval
Is this timer set correctly for Arduino Mega? It should count exactly one second. And why when I print in serial monitor (seconds_passed++) is it incremented by 2 not by 1?
Full code on Pastebin: LINK
noInterrupts();
//set and initialize the TIMER1

TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0; // set entire TCCR1B register to 0
TCCR1B |= (1 << CS12);
TIMSK1 |= (1 << TOIE1);
TCNT1 = 3036;

attachInterrupt(digitalPinToInterrupt(ignition_pin), ignitionSignal, CHANGE);
interrupts();

ISR(TIMER1_OVF_vect) {
  //TIMER1 overflow interrupt -- occurs every 1sec --
  instantSpeed();
  LPG_Consumption();
  LPG_injector_open_duration = 0;
  unleadedConsumption();
  unleadinj_Open_Duration = 0;
  seconds_passed++;
  vss_pulses = 0;
  TCNT1 = 3036;
}

I am not an expert on this, but Mega runs at 16 MHz. your prescaler is 256 so TCMT1 should be 16000000/256 for 1 second?

You asked a new question about the same topic, instead of improving your previous question. At least delete your previous question now

Your timer configuration is ok so far. Never the less I recommend using the TIMER1_COMPA_vect interrupt vector instead of TIMER1_OVF_vect which has the advantage of better readability (in my oppinion) and TCNT1 doesn't have to be reset in the ISR (instead, OCR1A is just initialized with 62500 once in setup()). Therefore, TIMER0 has to run in CTC (clear timer on compare match) mode and WGM12 has to be set in TCCR1B.
The reason why seconds_passed is incremented twice is because you Serial.print(seconds_passed++) in instantSpeed(). Printing on the serial interface is damn slow and using it in an ISR is a no-go!

Thanks, do you mean something like this:                                                                                TCCR1A = 0;            // undo the Arduino's timer configuration
TCCR1B = 0;            // ditto
TCNT1  = 0;            // reset timer
OCR1A  = 62500 - 1;    // period = 62500 clock tics
TCCR1B = _BV(WGM12)    // CTC mode, TOP = OCR1A
| _BV(CS12);    // clock at F_CPU/256
TIMSK1 = _BV(OCIE1A);  // interrupt on output compare A

I can't guarantee because I don't have an atmega2560 available right now, so there might be little things to fix. What is TOP=OCR1A supposed to do? I don't think that's neccessary. Also I think, OCR1A=62500 is theoretically correct (there is no "tick" at 0), but probably you won't recognize any difference...

It is only comment.

Allright! I suggest you try this standalone by blinking an led, just to see. If it doesn't work, feel free to ask!

@Adam: Avoid writing code in comments: it's not very readable. Post a link instead. @SimSon: 1. Adam copy-pasted from this answer. 2. The timer counts from 0 to OCR1A inclusive. If you want a period of 62500, then OCR1A should be set to 62500−1=62499.

@EdgarBonet so practically resetting TCNT is one tick?


text:
Difficulty getting Arduino data via puTTY
I am working on a project with a simple particulate matter sensor hooked up to an Arduino Uno. I'm using puTTY to log the sensor's output. My Arduino program converts the data to a numerical format, then prints it to the serial monitor every 30 to 31 seconds. I want to use puTTY to log this data to a file over a period of weeks. My problem now is that when I run it using puTTY, it stops after about 30-90 mins and "Fatal error: error reading from serial device" pops up. The wires connecting my sensor to the Arduino, and the USB cable connecting the Arduino to my computer all appear fine. Here is the code on the Arduino:
int pin = 8;
unsigned long duration;
unsigned long starttime;
unsigned long sampletime_ms = 30000;
unsigned long lowpulseoccupancy = 0;
float ratio = 0;
float concentration = 0;

void setup() {
  Serial.begin(9600);
  pinMode(8,INPUT);
  starttime = millis();
  Serial.print("Data is collected roughly every ");
  Serial.print(sampletime_ms/1000);
  Serial.println(" seconds.");
}

void loop() {
  duration = pulseIn(pin, LOW);
  lowpulseoccupancy = lowpulseoccupancy+duration;
  if ((millis()-starttime) >= sampletime_ms)
  {
    ratio = lowpulseoccupancy/(sampletime_ms);
    concentration = 1.1*pow(ratio,3)-3.8*pow(ratio,2)+520*ratio+0.62;
    Serial.print("Concentration = ");
    Serial.print(concentration);
    Serial.print(" pcs/0.01cf at ");
    Serial.print(millis()/1000);
    Serial.println(" seconds.");
    lowpulseoccupancy = 0;
    starttime = millis();
  }
}

I'm using the shinyei PPD42 particulate matter sensor.
Can anyone tell me what's going on, and if there's any sort of workaround I can use? I don't necessarily need to use puTTY, I just need to log the serial output from my Arduino.
Thanks!

Genuine Uno or a Chinese clone with a CH340G USB chip?

It's a genuine Uno board.

Does this happen if you use Arduino Serial Monitor only?


text:
How do I upload an Arduino STM32 binary from the Mac command line?
I've compiled an Arduino program via a Makefile and have the resulting hex file.
From the Mac command line, how do I upload this hex file to my STM32 Cortex M3 board?  For an ATMEL processor I would use avrdude.

There are several different tools for uploading binaries to a Cortex M3.  Depending on the board (not chip) configuration, they include (ht: Majenko):

dfu-util through an FT232 adapter
stm32flash through serial
micronucleus through the Micronucleus bootloader
stlink through an STLink programmer

Many Arduino flavors use a board with some kind of USB or FT232 adapter.  In this case:
the STM32 line of processors include a DFU (device firmware update) bootloader in ROM.
The dfu-util project supports a Mac version of dfu-util, their command line DFU tool.
Note that this answer is identical for any binaries which run on the processor, be they Arduino sketches or programs developed with other frameworks.


text:
Programming ESP32 MCUs for production
Before committing to learning about the ESP32 and how to program it, I would like to know if the ESP can be programme the same way for production as it can on évaluation boards (with the Arduino IDE).
Since it obviusly much easier than most for microcontrollers, I was wondering if a product is eventually mass produced, if the code used to program the evaluation board (such as this one https://makeradvisor.com/tools/esp32-dev-board-wi-fi-bluetooth/) could be used on the final product.

Yes. Most manufacturers would just require a binary (or HEX depending on MCU) file of your compiled code. If it's not a system they already know how to handle you will also need to provide a procedure for them to follow to program the device. What form that takes depends on the manufacturer.
You can also generally order pre-programmed MCUs and modules direct from the manufacturer where they (for a small fee) will program the chips for you before they are then sent to the board manufacturer for population.
If there is no facility on the MCU manufacturer's website then just email their sales department and I am sure they would be happy to quote you. Again, all they will require is a HEX or BIN file (depending on manufacturer) for programming.

Perfect Answer, thank you! To follow up, I'm assumant this means that using VSC, Atom, or the Arduino IDE, there is a procédure to build the code into a binary for the ESP32. Could you point me in the direction of such a procedure ? (research so far has gotten me to annexe articles such as 'how to make the binary smaller' etc...)\

Just compile your code as normal - then you just need to grab the binary from wherever it ends up (turn on verbose compiling to find where that is).


text:
I2C master/slave maximum requestEvent message size
Using a NodeMCU master and an Arduino slave (Wire.h on both sides), is there a maximum message size (32 bytes?) for the answer that the slave sends from requestEvent()?
If so, is there any solution to circumvent such a restriction WITHOUT the use of other libraries (like I2C_Anything, for example)?

What libraries do you use on both sides? Wire on the Arduino? And what library on the NodeMCU?

The I2C protocol itself does not have a transmission size restriction. But the implementation in the Wire library only reserves a specific amount of RAM for the buffers. This site mentiones 32 bytes for normal Arduinos (couldn't find the source code currently) and I found 128 bytes for the ESP8266 in the source code.
You cannot have unlimited message length, since the buffer has to hold the whole message and the RAM on normal Arduinos is very limited.
But you can make the buffers of the libraries bigger by changing the corresponding defines in the header files to a bigger value. Keep in mind, that the actual used memory space is with a factor 2, since the buffer size gets used for both send and receive buffer.

If you need bigger messages, than is fitting in the available RAM, you should either change to a board with more RAM, or develop a way to process one part of a message, deleting it and then process the next part (multi part message). Though that raises the question, why the messages have to be that big in the first place.

I tested and the limit, without tinkering with the Wire.h library and it didnt work.

What exactly did you test how and what exactly didn't work?

i increased the char array to 64, instead of 32 bytes.  Master did not receive message.  Changed back to 32 bytes and it starts receiving again.

https://github.com/arduino/ArduinoCore-avr/blob/7a2e1cd815266fef3012a5c9b48f88d78551f838/libraries/Wire/src/Wire.h#L1

apparently, yes, the Wire.hlibrary must be tinkered with, which would make the sketch implementation non-standard.  There is no guarantee that future versions of this library will accept such tinkering.

Of course, there is never a guarantee. But it is very probable, that future implementation will still allow this, since there is no sane way to get around a fixed buffer size (dynamic allocation is bad on microcontrollers). And they already have one single define for that, so it is not very probable, that they change that to a less good way of setting the buffer size.


text:
Cannot make sense of values from Bluetooth HC-01
I have a simple script that listens on pin 0 for input, and if it gets anything, it Serial.prints it. But I cannot make sense of the results. I have a basic app that sends text over Bluetooth (in the code I see utf8.encode(message) if that helps), and I'm able to validate that the message is not corrupted by the module, by simply touching the RX and TX pins together, the app receives the same message it sent. But the Arduino cannot understand it.
Here's my code:
void setup() {
    Serial.begin(9600);
}

void loop() {
    if (Serial.available() > 0) {
        Serial.print("New value: ");
        Serial.println(Serial.read());
    }
}

The TX on the HC-01 is connected to pin 0, and the RX is connected to pin 1. Power and ground are connected to the Arduino's (and I even tried different grounds just in case that one was fried). The Arduino is powered by USB and I'm using the Serial moniter. Here is some sample input-output:
Me through the app: a. Arduino: 255
Me through the app: a. Arduino: 254
Me through the app: a. Arduino: 254
Me through the app: a. Arduino: 254
Me through the app: a. Arduino: 254
Me through the app: a. Arduino: 255
Me through the app: aa. Arduino: 254
Me through the app: aaa. Arduino: 252
Me through the app: aaaa. Arduino: 252

I just don't understand any of it. Please help me out.

What is the model if the arduino you are using? On some pins 0 and 1 are also connected to the USB port connected to your PC. If this is the case you may have a conflicted usage of the port.

So should I take out the USB and just power with a battery? I can also have like an LCD print the value. Would that work?

And for reference, I'm using the latest UNO   and kept pin 1 disconnected for that reason

So how did you disconnect pin 0 from the USB? Remeber the PC will be sending a signal on this connection which will likely interfere with the signal coming in from the HC-01. Even if there is no USB activity it will still be LOW or HIGH electrically. FWIW, in your question you imply both TX and RX on the HC-01 are connected to pins 0 and 1 on the arduino. Did you try using a mega or leonardo (Serial1 for the HC-01) if you have them? Or possibly SoftwareSerial on Uno (again FWIW I have never successfully got s/w serial to work reliably but it should be ok for testing)

You may have better luck with the LCD Approach, but it will be harder to debug (no serial monitor). If you have a mega (or something else with two serial ports) life might be easier at least in the "WTF is going on here? phase you are in right now! In my case I always use my leonardo to test bluetooth, xbee and similar "Serial devices" then if appropriate move it over to Uno (cos I've got lots of them) for "production".

Yeah so I did connect both pins and experimented with unplugging pin 1. I also used SoftwareSerial on pins 10 & 11. I have a nano I could hook up... Idk if that will help since SoftwareSerial didn't work.

Glad it's not just me that has problems with it. :-) so my next suggestion would be to replicate the test where you shorted the tx and rx on the HC-01 but in software. That is, 1) connect pins 0 and 1 to tx and ex. Then 2) change your program to read Serial.print(Serial.read()); in place of the prints you have inside the if statement. 3) To be safe, you will need to upload the program, disconnect the USB, then power your arduino via the round power connector (or if you are comfortable/brave enough) via the vin and gnd pins. Then repeat your loop back test you mentioned in your question...

Let us continue this discussion in chat.


text:
how do I detect a data connection?
on an ardunio, is there a way to detect if a data connection (vs power only) is present? I want to have my arduino behave differently if connected to a pc, or on stand alone power.
specifically, I have a project that sends keystrokes to a midi piano program I wrote, but when a pc is not connected, I would like to have the arduino send the notes to a peizo buzzer attached to the circuit instead.
Im using a teensy, or a leonardo, or an Uno.

You could have the main code run when a signal is sent over the serial monitor...

Teensy and Leonardo, probably yes. Uno - no.

for sending keystrokes, no on the uno, but I still think it may be possible to get a status indication. useful for other projects. does the arduino look at the rx/tx pins of the usb?

Are you using the Keyboard class to send HID reports, or are you using Serial and then your program is interpreting it as key presses?

In this project I am using the keyboard class. I was thinking the arduino would have a data pin I could monitor.


text:
Powering Motor shield and Arduino Mega Separately
I'm trying to build a fire fighting robot, that uses 2 BO DC motors, 2 Servos - MG996R and SG90. For them I'm using Motor Shield v1 of Adafruit's make that uses 2 L293D IC's and a 74HC595 shift registers.
Now, I'm placing the motor shield over Arduino Mega and trying to connect other components such as Flame Sensor, Ultrasonic Sensor and submersible DC Water Pump.
As soon as I try to power up ultrasonic sensor, the power indicating LED's on both the shield and Mega goes off.
I've been testing this with simple USB connected power supply and to my understanding the power being supplied is insufficient.
Since it would be a moving cart, I would like to know whether there is any way to power up Shield and Mega separately by a 9v Battery?

On the side of the DC Motor Shield v1, there is an external power - +  2 pin terminal.
This can be used to supplement the shield with power.
Adafruit: "The motor controllers on this shield are designed to run from 4.5V to 25V.
MOST 1.5-3V MOTORS WILL NOT WORK"
If you are lucky to have the motor specs and ratings on hand, you will be able to account for how much power your motor(s) will need in your application.
Adafruit: "The motor driver chips that come with the kit are designed to provide up to 600 mA per motor, with 1.2A peak current. Note that once you head towards 1A you'll probably want to put a heatsink on the motor driver, otherwise you will get thermal failure, possibly burning out the chip."
Here is an important tid-bit for your scenario... (So no 9v Batteries for the motors!):
Adafruit: "You can't run motors off of a 9V battery so don't even waste your time/batteries! Use a big Lead Acid or NiMH battery pack. Its also very much suggested that you set up two power supplies (split supply) one for the Arduino and one for the motors. 99% of 'weird motor problems' are due to noise on the power line from sharing power supplies and/or not having a powerful enough supply!"
...
So makes sense,  get the Arduino powered, by itself, then get another power source for your motor shield.
Your sensors might be able to hop on the Arduino power supply if it's providing enough power.  I'd keep them separate from the motor power line, due to noise interference as suggested.
Try this, and see if the Arduino stays powered.
There is a lot of helpful info here, some new things I've learned just now.
https://learn.adafruit.com/adafruit-motor-shield/power-requirements


text:
ESP8266 (Huzzah Feather) I2C scanner finds nothing
I am trying to address an I2C device on my Huzzah Feather (Adafruit) ESP8266, but the I2C scanner tool does not detect anything.  All is sufficiently powered and quadruple checked the wiring.
Is there something I am missing for this board in regards to I2C connections?
I've had no issue on an Arduino, which uses the 2 pins on the Analog rail for I2C...
The Huzzah has no Analogue But the one pin, regardless, Huzzah Feather has different (still pin 4 & 5 tho) I2C,  and not via A0 A1 like on the Uno.
Do I need to dig deep and change some pin configurations for the Huzzah?
Thought I would ask before wasting more time on trial and error experiments.
Update Note:
I failed to mention there is a Feather Neopixel board (4x32) hard soldered to the board. Which I suspect is not the culprit as this issue also persists on same board without the neopixel shield attached.
Update
The soldering job was good, but discovered a faulty wire.  This allowed the I2C scanner to detect the i2C controller (LCD2004) at the address of 0x3F...
I checked with a I2c LCD library example, and I don't get any characters to come up... This is the same with both Huzzah Feather boards, one with Neopixel shield and the other is bare.

use Wire.begin(SDA_PIN, SCL_PIN);

@Juraj The Wire library has an overloaded ::begin() that does that for you for the default pins SDA and SCL.

@Majenko, the begin() without parameters uses pins defined in variant. but, yes, I checked it now and the Huzzah Feather has 4 and 5 defined

I tried this Wire.begin(4,5);   and issue persists.

This particular issue was due to a faulty wire on the I2C bus. I replaced the wire and I was able to scan and get an address to the I2C LCD controller.
I still cannot get text to the LCD.  I will start a new question for that.
EDIT:
Upon scrapping my I2C_LCD_DISPLAY library, I downloaded one that was linked in a ESP32/8266 tutorial for the LCD, and finally got it working.


text:
Difficulties programming Arduino uno for 24 hour cycle
I am trying to program my Arduino Uno board for a 24 hour cycle.
I have the Arduino board and two relays.
The aim is; every 24 hours relay 1 has to switch on for 5 seconds, and 1 second later relay 2 has to switch on for 15 seconds.
I have a sketch for a 12 hour cycle, and that works fine, but when I try for a 24 hour cycle, by changing the const unsigned int totalTime from 43200 seconds to 86400 seconds, everything goes wrong.
24 hour sketch - what is wrong?
//turn relays on and off at certain times.
//when the digital output pin is HIGH, then the relay is off.
//when the digital output pin is LOW, then the relay is on.

enum actioEnum {
  RELAY1_ON,
  RELAY1_OFF,
  RELAY2_ON,
  RELAY2_OFF,
};

struct tableStruct{
  unsigned int time;
  actionEnum action;
}
const table [] = {
  {0,RELAY1_ON},
  {5,RELAY1_OFF},
  // remaining 86395 for a total of 86400.
  {0,RELAY2_OFF}, // not needed, it is already off.
  {6,RELAY2_ON},
  {6+15,RELAY2_OFF},
  // remaining 86379 for a total of 86400.
};

const unsigned int totalTime = 86400; // total amount for sequence
unsigned int seconds;

unsigned long previousMillis;
const unsigned long interval = 1000; // 1000 ms; // 1000 ms is one second

const int relay1Pin = 2;
const int relay2Pin = 3;

void setup() {
   serial.begin(9600);

  // the relay is off when the pin is high.
  // turn output high before setting the pinMode.
  // then the output changes from a floating pin to high,
  // and the relays will not be activated.
  digitalWrite (relay1Pin, HIGH);
  pinMode (relay1Pin, OUTPUT);
  digitalWrite (relay2Pin, HIGH);
  pinMode (relay2Pin, OUTPUT);
}

void loop () {
  // a one second timer with millis
  if (millis() - previousMillis >= interval) {
    previousMillis += interval;
    // scan table
    for ( int i = 0; i < int (sizeof(table) / sizeof (tableStruct)); i++) {
      if (table [i] . time == seconds) {
        switch (table [i] . action) {
          case RELAY1_ON:
            Serial.println("Relay 1 on");
            digitalWrite (relay1Pin, LOW); // low is relay on.
            break;
          case RELAY1_OFF:
            Serial.println("Relay 1 off");
            digitalWrite (relay1Pin, HIGH); // high is relay off.
            break;
          case RELAY2_ON:
            Serial.println("Relay 2 on");
            digitalWrite (relay2Pin, LOW); // low is relay on.
            break;
          case RELAY2_OFF:
            Serial.println ("Relay 2 off");
            digitalWrite (relay2Pin, HIGH); // high is relay off.
            break;
          default:
            Serial.println ("Error, a bug in the scketch");
        }
      }
    }
    seconds++;
    if (seconds >= totalTime) {
      seconds = 0;
    }
  }
}

Why you are not using a RTC module?

The Uno isn't the most accurate in time keeping, and can drift by a few minutes every day. Depending on your application this might not matter. However, if it does, use an RTC like newbie suggested.

On the Uno unsigned int is a 16 bit number. That means, that it can hold values between (and including) 0 and 65535. If you try to write a bigger value to this variable, it will cut of the higher bits, so that the rest fits into 16 bits. That gives you a totally different value, which is significantly small than 24h.
The solution is to use a bigger variable type for totalTime.
 You can use unsigned long, which has 32 bits and can hold way bigger values ( 0 to 4,294,967,295 (2^32 - 1)). That should be plenty enough for all your cases.

Hi, your solution is to use unsigned long instead of totalTime. how do I change this in my sketch? Regards, Martinus.

No, not instead of totalTime, but as the type of it. In your sketch you wrote const unsigned int totalTime = 86400;, but instead you should write const unsigned long totalTime = 86400;. That changes the type of the variable totalTime from unsigned int to unsigned long.


text:
esp8266- how to use GPIO0 as an input?
First, my setup:
I have an Arduino Uno with an Adafruit Audio Shield.  I have a Wemos D1 Mini controlling the project.
I need for the D1 to know when a file is playing.
I have a GPIO pin on the Uno programmed to be high when a file is playing.  Low otherwise.  I have two GPIO pins on the Wemos that are unused, D3 and D4 (GPIO0 and GPIO2).  (I use a divider circuit of a 10K over a 20K resistor to bring the 5V from the Uno down to 3v3 for the Wemos). D4 is already a problem because it has to be high to boot and the GPIO from the Uno is normally low. D3 (GPIO0) has to be high to boot and has an internal pullup.
Here's my problem.  How do I turn off the pullup on GPIO0? Even when the Uno GPIO is low (0V), the GPIO0 measures 2.4V, which my sketch sees as a logical 1.
Any tips would be appreciated.  (I thought of reversing the polarity on the Uno so that low=true, but even when the Uno is driving the pin low, the Wemos GPIO0 pin is still at 2.4V, so low-true logic won't work either.).

Don't use the voltage divider and never set the Uno pin HIGH.
Pull io 0 of esp8266 LOW with pinMode of the Uno pin.
pinMode(TO_ESP_IO0, OUTPUT); // sets the pin LOW

pinMode(TO_ESP_IO0, INPUT); // let it to the io0 pull-up resistor


text:
how to use keypad button multiple integer value input
I have been working on water flow sensor which measures volume then i need to restrict the amount of water which disperse from depend on the user input form the keypad so how can i store the input form the keypad into a variable.

Various tutorials about keypads can be found on the web. Have you tried one of these? What didn't you understand?

When you use the keypad library, there is a command to read a key:
 myKeypad.getKey();

Store these keys in a (string) buffer, and after a certain key is pressed (e.g. #), parse the string buffer to retrieve the integer (with the c function atoi, see here for a description).


text:
MAX7219 only displaying on first digit
I'm trying to display a scrolling number on my MAX7219 display using the LedControl library, but can only ever get the first digit (digit 0) updating. When I reference digits 1-7 the 7 segments don't light up.
This also happens even with the example sketch LCDemo7Segment. Is there an issue with my display unit perhaps?
Using an Uno board and this module. Using pin 11 for DataIn, 13 for CLK, and 12 for Load.

Can you post more data on the display you are using (model, schematic, picture, link)?

Done now :) I know the link doesn't provide a great deal of data but it's all you get from the supplier

Did you try the software the producer is giving you, of course making the connections suggested by him (DIN 4, CS 5, CLK 6)?

Alright I get all displays lighting up now, so it's not a hardware issue, just software. Is there anything I can change in the LedControl library to restore function?

honestly I do not know that library. Maybe you can try comparing the two codes, and make changes until the library works...

Maybe you should ask the author of the library by creating an issue on the Github repository


text:
please tell me how do I fix this code down here(please tell in my easy English)
 LiquidCrystal 1cd(12, 11, 5, 4, 3, 2);

 void setup() {
   1cd.begin(16, 2);
   1cd.print"abbu, kya, chalrelaye!");
 }

 void loop() {

 }

What is the question?

Variable names MUST NOT start with a digit. Only '_' and a-z are allowed!
1cd really should be lcd with an 'ell' instead of a one (1).

what did we learn here about Arduino? upvoters, how is this useful for you?

The compiler for Arduino is just working the way as any other C/C++ compiler. ;)

I down-vote Answers to a Question originating in an typographical error, because this kind of question has no value and without answer it would be deleted.

I suggest you modify the LiquidCrystal "Hello World" sketch:

Here is the example code:
// include the library code:
#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

Good luck!


text:
Programming the ATMega328P without Arduino board always returns the error: avrdude: stk500_recv(): programmer is not responding
I have a microcontroller: ATMega328P.
I don't have any Arduino Uno board.
I want to program the ATMega328P using my FTDI programmer.
But when I try to program the ATMega328P without Arduino board I always get this error:
avrdude: stk500_recv(): programmer is not responding
I've followed this YouTube Tutorial to build this.
And ended up with this diagram:

All the connections seems OK.
I choose the board: "Arduino Pro or Pro Mini" because only with this one I can choose the correct processor: "ATMega328P (5V, 16MHz)"
The port is correct: "/dev/ttyUSB0"
And as for the the programmer I've choose: "USBasp", which I don't know if this is correct. I've used this FTDI programmer to program the STM32 microcontroller and the programmer was "Serial", which I don't see the very same option here.
I'm lost, what am I missing up here?
BTW I've seen this, this and this but couldn't get it fixed.

What happens if you try to program it as a Arduino Uno?

The same @VE7JRO. Using as Arduino Uno with programmer USBasp I get the same error (stk500_revc() programmer is not responding)

For the programmer, please try "AVRISP mkll".

same result :((

If you are certain the IC has a boot loader installed, you could try to use a button or jumper wire from the reset pin to GND instead of the FDTI programmer. The trick is to connect the reset pin to GND, press the upload button in the Arduino IDE, then disconnect the reset pin from GND when the IDE says it starting to upload.

A new chip cannot be programmed in that manner until it has the Bootloader installed. The Bootloader starts after a reset and monitors the serial interface to see if something is attempting to download code via the serial port.
Selecting a Programmer has no effect on serial download, that only comes into play when Programming via the SPI pins SCK/MOSI/MISO/Reset/Power/Gnd.
Your "design" needs a couple more parts: 0.1uF caps between VCC and Gnd, and AVCC and Gnd.
The Cryslal and 22pF caps could also be a lot closer to the device - like right next to it.
I can't read the FTDI markings, so I can't tell if you have Rx and Tx swapped there.

I already have a 0.1uF caps between VCC and Gnd. So I need to place another one between AVCC and GND?

I've put the Crystal and the caps closer to the device but the result is the same. Can I force the reset pin to be on? Something like: put 5V (dont know if it is 5V tolerant) and then try right away to upload the code?

If the chip does not have a Bootloader programmed in it already, it will not be able to  upload via the FTDI module.

no bootloader was programmed! thank you!


text:
Node mcu does not connect
im trying to connect to my wifi with mit Nodemcu, i recently got a new router and since then i can't connect anymore. I use simple example sketches from esp library but it will not connect. Instead i get a lot of dots in the console. I disabled firewalls of my router, mac filter is disabled(as i tried to manually add the nodemcus mac to mac filter it said "invalid macadress" ) if intry to connect to my phones hotspot, everything is fine.but i can't connect to my home wifi, ssid and Passwort are 100% correct. My hardware is fine, i ordered a second nodemcu and it has the same problems as the old one.
Can someone help me please, i've set my entire rooms ligthing on the node mcu and now im living in the dark ...

is the new AP 5 GHz WiFi?

No i have 2.4 ghz and 5 ghz but i disabled 5ghz :/

This goes to show that one shouldn't ever rely on a single point of failure to make a home 'smart'.

You'll need to review the logs of your access point device to see why it is failing your requests. If it's a low-end residential device, it probably doesn't have any logs for you to review. What have you tried on the MCU side code-wise, to observe what may be happening on its side of things?

Turn on all the debugging you can in the IDE to see what your code is doing over the serial port


text:
HTTP request is not being executed in Arduino script for sending sensor data to Thingspeak cloud
I am trying to send the data from DHT sensor (temperature and humidity on 2 channels of Thingspeak cloud server) and firstly display them on Thingspeak cloud. Afterwards I will need to get those data from the cloud and use them with Python in order to make some calculations. Sensor data is sent via SIM900 GSM module.
I succeeded to send some constant value to Thingspeak by executing AT commands, one by one, which I put later in this code: https://pastebin.com/4bP6hgk7 EDIT: Here is the code:

#include <SoftwareSerial.h>
#include "DHT.h"

#define DHTPIN 2
#define DHTTYPE DHT11

// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);

// Create global varibales to store temperature and humidity
float t; // temperature in celcius
float f; // temperature in fahrenheit
float h; // humidity

SoftwareSerial gsm(7, 8);

void setup() {
  // put your setup code here, to run once:
  dht.begin();

  gsm.begin(9600);
  Serial.begin(9600);

  gsm.println("AT+IPR=9600");
  delay(1000);

  gsm.println("AT+CGATT=1");
  delay(1000);

  gsm.println("AT+SAPBR=1,1");
delay(1000);

  ShowSerialData();

  gsm.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
  delay(1000);

  ShowSerialData();

  gsm.println("AT+SAPBR=3,1,\"APN\",\"prepaidnet\"");
  delay(1000);

  ShowSerialData();

  gsm.println("AT+SAPBR=3,1,\"USER\",\"mts\"");
  delay(1000);

  ShowSerialData();

  gsm.println("AT+SAPBR=3,1,\"PWD\",\"064\"");
  delay(1000);

  ShowSerialData();

  gsm.println("AT+SAPBR=1,1");
  delay(1000);

  ShowSerialData();

  gsm.println("AT+SAPBR=2,1");
  delay(1000);

   ShowSerialData();

   gsm.println("AT+HTTPTERM");
  delay(1000);

   ShowSerialData();

  gsm.println("AT+HTTPINIT");
  delay(2000);

  ShowSerialData();

  gsm.println("AT+HTTPPARA=\"CID\",1");
  delay(3000);

  ShowSerialData();

}

void loop() {
  // put your main code here, to run repeatedly:
  while(gsm.available()) {
    Serial.write(gsm.read());
  }
  if(Serial.available()) {
    gsm.write(Serial.read());
}

 t=readTemp();
h=readHum();

gsm.print("AT+HTTPPARA=\"URL\",\"https://api.thingspeak.com/update?api_key=Z1Q5633A4S1GHIHU&field1=26");
//gsm.print(t);
//gsm.println();
delay(5000);
//gsm.println((char)26);

ShowSerialData();

delay(1000);
gsm.println("AT+HTTPPARA=\"REDIR\",1");
delay(3000);
gsm.println("AT+HTTPSSL=1");
delay(3000);
gsm.println("AT+HTTPACTION=0");  /* Start POST session */
delay(5000);
gsm.println("AT+HTTPREAD");
delay(3000);
gsm.println("AT+HTTPTERM"); /* Terminate HTTP service */
delay(5000);
gsm.println("AT+SAPBR=0,1");
delay(3000);
ShowSerialData();

}

float readTemp() {
  // Read temperature as Celsius
  t = dht.readTemperature();
  //Read humidity
  h = dht.readHumidity();

  // Compute temperature values in Celcius
  t = dht.computeHeatIndex(t,h,false);

  // Check if any reads failed and exit early (to try again).
  if (isnan(t)) {
    Serial.println("Failed to read temp from DHT sensor!");
    return 1;
  }

  return t;
}

float readHum() {
  //Read humidity
  h = dht.readHumidity();
  // Read temperature as Celsius
  t = dht.readTemperature();

  // Compute temperature values in Celcius
  t = dht.computeHeatIndex(t,h,false);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h)) {
    Serial.println("Failed to read hum from DHT sensor!");
    return 1;
  }

  return h;
}

void ShowSerialData()
{
  while(gsm.available()!=0)
    Serial.write(gsm.read());
    if(Serial.available()) {
    gsm.write(Serial.read());
  }
}

The problem is that not the whole script is executed - AT+HTTPPARA command with the parameter "URL" and the URL where the data should be sent is not being executed. I have read many answers but could't find the answer for this. Could anybody help with this issue? Thanks in advance!

Line 99 should be a gsm.println not a gsm.print.

Thanks for the suggestion, but putting println didn't resolve the problem.


text:
Serial connection two devices two power supplies
I'm trying to connect an ESP32-CAM to a 3d printer using a serial connection.
When powering the ESP from the 5V rail on the 3D printer(and using 3.3V zener diodes between tx, rx & gnd), everything works fine. The ESP expects 3.3V on the serial pins, hence the diodes.

circuit diagram
Common ground not shown.
Then when I try to run the ESP32 from its own 5v power supply, I cannot establish a serial connection, regardless of whether I connect the gnd from the 5v from the 3d printer with that of the ESP power supply.
In fact, the ESP doesn't function then.
Any suggestions?
PS: the ESP has its own power since it should trigger a relay to cut power to the printer.

use a logic level converter

The 3.3V zener diodes are connected backwards. The anode should be connected to ground and the cathode (banded end) to the GPIO signal. Zener diodes work in reverse bias...as you have them connected now they are forward biased and will clamp the signals to about 0.7V.
The zener diode on the line for data transmitted at 3.3V to a 5V input doesn't do any good. You need to increase that signal voltage to a proper 5V logic level. The best thing to do would be to get rid of the zener diodes altogether and use a proper logic level converter.
Also, you really should have resistors between GPIO output pins and the zener diodes, to limit the current through the zeners when the GPIO pin is at 5V.


text:
Monitoring Power Down Using Arduino UNO and ZMPT101B
I am in the process of implementing power down alerting system suing Arduino UNO and ZMPT101B Single phase relay.
My code as follows,
#include <Filters.h> //Easy library to do the calculations

float testFrequency = 50;                     // test signal frequency (Hz)
float windowLength = 40.0/testFrequency;     // how long to average the signal, for statistist

int Sensor = 0; //Sensor analog input, here it's A0

float intercept = -0.04; // to be adjusted based on calibration testing
float slope = 0.0405; // to be adjusted based on calibration testing
float current_Volts; // Voltage

unsigned long printPeriod = 1000; //Refresh rate
unsigned long previousMillis = 0;

void setup() {
    Serial.begin( 9600 );    // start the serial port
}

void loop() {

    RunningStatistics inputStats;                //Easy life lines, actual calculation of the RMS requires a load of coding
    inputStats.setWindowSecs( windowLength );

    while( true ) {
        Sensor = analogRead(A0);  // read the analog in value:
        inputStats.input(Sensor);  // log to Stats function

        if((unsigned long)(millis() - previousMillis) >= printPeriod) {
            previousMillis = millis();   // update time every second

            Serial.print( "\n" );

            current_Volts = intercept + slope * inputStats.sigma(); //Calibartions for offset and amplitude
            current_Volts= current_Volts*(40.3231);                //Further calibrations for the amplitude

            Serial.print( "\tVoltage: " );
            Serial.print( current_Volts ); //Calculation and Value display is done the rest is if you're using an OLED display

            if (current_Volts <229) {
                test_loop();
            }
        }
    }
}

void test_loop(){
    Serial.print( "Warning!! Server Room Power Down" );
    delay(1000);
}

I am getting the correct voltage reading. When power down it says power down. But when power got up, it still shows power down with older reading. I think the reason for this because my code unable to stop the loop. And if I remove the delay (1000) in test_loop function it works, But my intention to use this sms alerting system and for that I need this delay to stop unnecessary alerts.
My code for SMS Alerting,
Serial.print( "\tVoltage: " );
Serial.print( current_Volts ); //Calculation and Value display is done the rest is if you're using an OLED display

if (current_Volts <229) {
    SendMessage();
}

void test_loop() {
    mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
    delay(1000);  // Delay of 1000 milli seconds or 1 second
    mySerial.println("AT+CMGS=\"xxxxxxxxx\"\r"); // Replace x with mobile number
    delay(1000);
    mySerial.println("Warning!! Server Room Power Down");
    delay(100);
    mySerial.println((char)26);// ASCII code of CTRL+Z
    delay(150000);
    mySerial.println("AT+CMGD=2");
}

This code works for the very first outage but after power up also it send power down. First part of serial priniting in test_loop code of Serial.print is used for debugging.

Got a answer for the issue,
Attaching code for anyone interested.
/*
   Design by Vinod Amarathunga 26.08.2018
   FSSG R&D Team
*/

#include <OneWire.h>
#include <DallasTemperature.h>
#include <SoftwareSerial.h>
#define ONE_WIRE_BUS 2
SoftwareSerial mySerial(11, 10); //SIM800L Rx Tx
char msg;
String textMessage;

bool D7_alarmSent = false;
bool Temp_alarmSent = false;

OneWire oneWire(ONE_WIRE_BUS);

DallasTemperature sensors(&oneWire);

void setup()
{
  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
}

void PowerSMS()
{
  Serial.println("Warning!! Server Room Power Down");
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No1\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Power Down");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No2\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Power Down");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No3\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Power Down");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

}

void SendMessage()
{

  Serial.println("Warning!! Server Room Temperature is Critical");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No1\"\r"); // Replace x with mobile number
  delay(1000);
  mySerial.println("Warning!! Server Room Temperature is Critical");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No2\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Temperature is Critical");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No3\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Temperature is Critical");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

}

void loop()
{
  sensors.requestTemperatures(); // Send the command to get temperature readings
  delay(1000);
  Serial.println(String("Temp Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  Serial.println(String("Voltage Digital: ") + digitalRead(7));
  Serial.println(Temp_alarmSent ? "True" : "False" );
  Serial.println(D7_alarmSent ? "True" : "False" );
  Serial.println("***********");
  ReceiveMessage();

  if (digitalRead(7) == 1 || sensors.getTempCByIndex(0) > 29 || D7_alarmSent == true || Temp_alarmSent == true ) {
    if (digitalRead(7) == 1 ) {
      if (!D7_alarmSent) {
        D7_alarmSent = true;
        PowerSMS();
      }

    }

    else if (sensors.getTempCByIndex(0) > 29 ) {
      if (!Temp_alarmSent) {
        Temp_alarmSent = true;
        SendMessage();
      }

    }

    else {

      if (D7_alarmSent){                  //alarmSent == true means that previous state was "Power Down"
          SendMessage_After_Power_Down();          //Send message
          D7_alarmSent = false;
          Temp_alarmSent = false;             //Reset alarmstate
        }

    }
  }

}

void SendMessage_Normal()
{
  Serial.println("Temperature and Power is OK");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No1\"\r");
  delay(1000);
  mySerial.println("Temperature and Power is OK");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No2\"\r");
  delay(1000);
  mySerial.println("Temperature and Power is OK");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No3\"\r");
  delay(1000);
  mySerial.println("Temperature and Power is OK");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

}
void SendMessage_After_Power_Down(){

  Serial.println("Power Back Online");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No1"\r");
  delay(1000);
  mySerial.println("Power Back Online");
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No2\"\r");
  delay(1000);
  mySerial.println("Power Back Online");
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No3\"\r");
  delay(1000);
  mySerial.println("Power Back Online");
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  }

void ReceiveMessage()
{
  if (mySerial.available() > 0)
  {
    mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to recieve a live SMS
    delay(1000);
    textMessage = mySerial.readString();
    Serial.print(textMessage);
    delay(10);
  }
  if (textMessage.indexOf("Status") >= 0) {
    SendMessage_Normal();
    mySerial.println("AT+CMGD=2");

  }
}

It is OK to accept your own answer as the solution.


text:
Communication with sensor KMX63 in I2C
I trying to use a new sensor the KMX63 with a Arduino Uno board, my sensor is on a evaluation board made by kionix.
For the connexion il linked as follows:
| Pin Uno | Pin evaluation board |
| A5 | 5 |
| A4 | 7 |
| 3.3 | 1 |
| GND | 8 |
Here the schematic of the evaluation board:

I found a technical note from the constructor that advice to do some steps after the power up of the sensor to insure it's well functioning I wrote a code following it:
#include <Wire.h>
#include "KMX62.h"

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

  Serial.println(F("Starting"));

  byte error=7;
  byte id=0;
  byte command=0;
  delay(60);
  Wire.beginTransmission(KMX62_I2C_ADD_2);
  Wire.write(0x7F);
  Serial.println(F("Write 0x7F"));
  Wire.write(0x00);
  Serial.println(F("Write 0x00"));
  delay(100);
  error=Wire.endTransmission();
  Serial.print(F("retour 1 : "));
  Serial.println(error);
  if( error==0 ){
    Wire.beginTransmission(KMX62_I2C_ADD_2);
    Wire.write(CNTL2);
    Wire.write(0x00);
    error=Wire.endTransmission();
    if( error==0 ){
      Wire.beginTransmission(KMX62_I2C_ADD_2);
      Wire.write(CNTL1);
      Wire.write(0x80);
      error=Wire.endTransmission();
      if(error==0){
        delay(5);
        Wire.beginTransmission(KMX62_I2C_ADD_2);
        Wire.write(WHO_AM_I);
        Wire.endTransmission(false);
        Wire.requestFrom(KMX62_I2C_ADD_2,1);
        id=Wire.read();
        error=Wire.endTransmission();
        if(id==0x18||id==0x2D){
          Wire.beginTransmission(KMX62_I2C_ADD_2);
          Wire.write(COTR);
          Wire.endTransmission(false);
          Wire.requestFrom(KMX62_I2C_ADD_2,1);
          command=Wire.read();
          error=Wire.endTransmission();
          if(command==0x55){
            Serial.println(F("device ok"));
          }else{
            Serial.println(F("Issue with the sensor step e : need to be rebooted"));
          }
        }else{
          Serial.println(F("Issue with the sensor step d id=wrong : need to be rebooted"));
        }
      }else{
        if(error==2||error==3){
        Serial.println(F("Issue with the sensor step c : need to be rebooted"));
        }
      }
    }else{
      if(error==2||error==3){
        Serial.println(F("Issue with the sensor step b : need to be rebooted"));
      }
    }
  }
}

void loop(){

}

but i have an issue the steps , the program seem to freeze when i try to write into the register 0x7F.
I don't get any trace that i should have after the wire.endtransmission().
Here the trace i obtain :
09:56:35.477 -> Starting
09:56:35.511 -> Write 0x7F
09:56:35.511 -> Write 0x00

i have use the I2C scanner to check if the sensor appear, i had to modify the scanner to add a delay before Wire.beginTransmission and the Wire.endTransmission to avoid the scanner to be freeze too at the first address tried. After the modification i did saw the sensor at the address it was mean to be.
here the trace for the I2C scanner :
Scanning...
I2C device found at address 0x0F  !
done

Anyone have an idea of why i can't write anything to my sensor without making my program freeze indefinitely each time ?
PS : After the advice of chrisl i rerunned all my programs on a arduino mini pro on 3.3V / 8Mhz and got the same result.

Can you explain the "delay(100)" before "Wire.endTransmission()"? You know that the "endTransmission" is actually the start of transmission.

Does the evaluation board run on 3.3V?

i didn't had understood that the transmission started only after the endTransmission. I have added the delay() because into the I2C scanner i had to add a delay(100) between the beginTransmission and endTransmission or the scanner was blocking at the address tryed

@chrisl i tryed with the both alimentation pin of the Uno the 3.3 and the 5V and got the same result

But the Uno will try to raise SDA and SCL to 5V, while the evaluation board would only raise it to 3.3V. So there will be a cross current. If you want to connect a 5V and a 3.3V device via I2C, you definitely need a level shifter.

And does that mean, that you power the evaluation board over the 3.3V pin of the Uno? You have to check, how much current the board needs. It might be too much for the 3.3V regulator on the Uno. Please check these things first and don't connect 5V to a 3.3V device, unless you really know, that it can tolerate that. You might destroy the device otherwise.

yes i powered the evaluation board with the 3.3V of the UNO, i juste do a supplement test with a mini pro 3.3V 8MHZ and i obtain the same result my program freeze but the scanner I2C does find the sensor I2C address : 0x0F

BW: What register is 0x7F? Could you add a link to the product spec you are using? The one I found did not have this register. This might be the issue. Could it be register 0x7A that you mean?

http://kionixfs.kionix.com/en/document/TN005-Power-On-Procedure.pdf
This is the technical note concerning the power on procedure for the sensor. It did looked strange for me when i read the address register 0x7F but i guessed it may be a register that we normally don't need to touch

Did you try the startup sequence from this https://github.com/ROHMUSDC/ROHM_SensorPlatform_Multi-Sensor-Shield/blob/master/Platform%20Code/Arduino_UNO_FirmwareExample/ROHM_SENSORSHLD1-EVK-101_10-20-2016/ROHM_SENSORSHLD1-EVK-101_TerminalDemo_11-10-2016/ROHM_SENSORSHLD1-EVK-101_TerminalDemo_11-10-2016.ino?

@MikaelPatel I didn't know that i try this startup sequence using the wire library but got the same result, programe seem locked with the first writing. Does the issue can come from the wire library ?

There are several hardware issues here before assuming it is software.

I finally found where the problem was, i had made a error on the reading of the schematic of the evaluation board. I thought that the pin J1-9 was already wired in intern but it was wrong. I wired it to the VCC output of my board and it work perfectly now.


text:
3.3v pin on a 5v Pro Micro?
I have a arduino pro micro that runs on 5v.
I also have a Max4466 that needs 3.3v, however the pro micro doesn't seem to have a 3.3v VCC.
Is there any way to attach the max4466 to the Board?

You need to add an external 3.3V voltage regulator. You can get these quite cheap on eBay (etc) as a module - some even come in a breadboard friendly format.
Power it from the 5V from the Arduino, then power your MAX4466.
However, the MAX4466 can run at up to 5.5V, so I fail to see why you think you need 3.3V.

Thanks for giving a solution, so upvoted. The solution is missing from the link of my deleted answer. For completeness, I repeat your mentioned link here: https://majenko.co.uk/blog/why-you-cant-use-resistors-voltage-regulator