text:
digitalWrite giving different output voltages between programs
I'm using an arduino uno R3 for lighting a few LEDs in response to coputer control. I've written two programs, the first to try an Object Oriented style, and the second to split up the code into more manageable chunks. They both implement the same function, turning one led on, then off and repeat for the other led. I'd also put 100uF capacitors between the anode and ground of each led for a fade effect. When running with the first sketch this works fine, but I noticed with the second sketch, the fade no longer works and the leds are much brighter. There was no change in hardware between sketches, and reverting to either doesn't change anything. On inspection with a multimeter there appears to be a large difference in output voltage (1.6v -> 5.2v) between programs. I've tried changing pins and this seems to have no effect. Is it the code or have I missed something obvious with the hardware?
Program 1
#include "Arduino.h"
// create signal class
class two_aspect_signal {
  //store pin numbers
  const int danger_aspect;
  const int clear_aspect;

  public:
    two_aspect_signal(int danger_pin, int clear_pin):
      danger_aspect(danger_pin),
      clear_aspect(clear_pin)
    {}
    void setup(){
      //set to output
      pinMode(danger_aspect,OUTPUT);
      pinMode(clear_aspect,OUTPUT);
    }

    void danger(){
      //turn red light on, green light off
      digitalWrite(danger_aspect,HIGH);
      digitalWrite(clear_aspect,LOW);
    }

    void cleaR(){
      //turn red light off, green light on
      digitalWrite(danger_aspect,LOW);
      digitalWrite(clear_aspect,HIGH);
    }
};
//create signal object
two_aspect_signal sig(7,8);
void setup() {
}
void loop() {
  //turn red light on, green off
  sig.danger();
  delay(2000);
  //turn green light on, red light off
  sig.cleaR();
  delay(2000);
}

Program 2
#include "sig2.h"
//create signal object
two_aspect sig(7,8);
void setup(){}
void loop() {
  // set red light on, green off
  sig.danger();
  delay(2000);
  // set green on, red off
  sig.cleaR();
  delay(2000);
}

Program 2 (sig2.cpp)
#include "Arduino.h"
#include "sig2.h"

two_aspect::two_aspect(int clear_pin, int danger_pin)
{
  //set pins to output and store
  pinMode(danger_pin,OUTPUT);
  pinMode(clear_pin,OUTPUT);
  _danger_pin = danger_pin;
  _clear_pin = clear_pin;
}

void two_aspect::danger()
{
  //set red light on, green off
  digitalWrite(_danger_pin,HIGH);
  digitalWrite(_clear_pin,LOW);
}
void two_aspect::cleaR()
{
  //set green led on, red led off
  digitalWrite(_danger_pin,LOW);
  digitalWrite(_clear_pin,HIGH);
}

Program 2 (sig2.h)
#ifndef sig2_h
#define sig2_h

#include "Arduino.h"

class two_aspect
{
  public:
    two_aspect(int clear_pin, int danger_pin);
    void danger();
    void cleaR();
  private:
    int _clear_pin;
    int _danger_pin;
};

#endif

Please let me know if this should've been in the electronics forum, thanks for reading.

The difference is, that in your first sketch you never call two_aspect_signal.setup(), thus the pins are never set as output. By default pins are configured as inputs. Doing digitalWrite() while the pin is configured as input will enable or disable the internal pullup resistor of that pin.
So in your first sketch you are powering the LEDs through the internal pullup resistor (if I correctly remember about 10kOhm). Thus they are rather dim. Also it takes some time for the capacitor to be charged through the big pullup resistor.
In your second sketch you configure the pins as output. So the LEDs will now  be actively driven through the pins output driver. It can provide way more current than the pullup resistor, thus the LEDs light up brigther. And the bigger current can also charge the capacitor in way less time (a time so small, that you don't even see it). Thus you don't see any fading (the fading is there, but just too fast for your eyes).
What to do know? You can of course just use the pullup resistor (and not configuring the pins as output). Or you can configure the pins as outputs and add a current limiting resistor between the pin and the LED/capacitor bundle. With your second sketch and the current circuit you are risking to damage the output drivers of that pin (through the LED current and through the high inrush current until the capacitor is charged). The sizing of that resistor depends on your needs. Make sure, that the current never exceeds 20mA (sustainable pin max current) (for 5V this would be R=U/I=5V/20mA=250Ohm as minimum resistance). The higher the resistance, the dimmer the LED will be and the longer the capacitor needs to charge. After that you can also change the capacitance. The higher the capacitance, the longer it will take to charge it (so longer fade effect).

Thank you! I'd put a 1k resistor before ground and thought that would be enough, I've now put 10k resistors on the outputs and it works great.


text:
Simple FastLED sketch that crashes when led strip is long but not when its shorter
I have a pretty simple sketch that crashes, and crashes hard (Platform.io console says "Disconnected (read failed: [Errno 6] Device not configured)" and I need to power off/on the Arduino to continue.
The sketch does not crash and seems to work fine when I use a smaller number of LEDS but crashes after a few seconds when I use a longer number of LEDS.  Seems like a strange hardware issue because the sketch looks simple! I have added a lot of Serial.print(ln)'s to verify it is doing what I think it is, and it does... until the crash!
This will run forever, but if I change cNumLeds from 60 to 160 it crashes (and my actual LED strip has 300 LEDs and I use all of them in other sketches).
#include <Arduino.h>
#include <FastLED.h>

const uint16_t cDataPin = 15;
const uint16_t cNumLeds = 60;

CRGB leds[cNumLeds];

void setup() {
   Serial.begin(9600);
   FastLED.addLeds<WS2812B, cDataPin, GRB>(leds, cNumLeds).setCorrection(TypicalLEDStrip).setDither(true);
   FastLED.setBrightness(127);
   FastLED.clear();
   FastLED.show();
   FastLED.delay(100);
}

uint16_t offset = 0;
CRGB colors[] = {CRGB::White, CRGB::Red, CRGB::White, CRGB::Green, CRGB::White, CRGB::Black};
byte numColors = sizeof(colors)/sizeof(colors[0]);
uint32_t cycle = 75;

void loop() {
  EVERY_N_MILLISECONDS(cycle) {
    for (uint16_t i = 0; i < cNumLeds; i++) {
        leds[i] = colors[(i + offset) % numColors];
    }
    offset = (1 + offset) % cNumLeds;
  }
  FastLED.show();
}

Any tips for debugging greatly appreciated ! (And apologies in advance for my C++ style, I am a confirmed C programmer trying not to do any damage in C++)

How are you powering the LED strip? Sounds like either your power supply is not strong enough or you are providing power through the Arduino

Yes @chrisl, guilty as charged, powering from the 5V Arduino pin. I guess that's what the extra red and black wire on the strip are for : ) TIme to learn soldering, I guess.

But i have run other sketches, much more complex, on the whole of the 300 led strip, so not sure I get why this sketch is having a power issue.

powering from the 5V Arduino pin.

You should not do this. You can fry the voltage regulator or the protection diode doing this (depending on how you supply the power).
When you draw more current from a power source than it can supply, first the voltage will drop. If the voltage drops enough the Arduino will brown out and reset as soon as the voltage is up again. If you keep drawing that much power, you can fry parts of the power source (in this case your Arduino). Sometimes this is reversible, when the power source has some kind of emergency shutdown (like the voltage regulator of a genuine Arduino Uno). Otherwise it will get destroyed.
When controlling power hungry devices like LED strips you should connect their power lines directly to your power supply (given it has the correct voltage). That way the current doesn't have to flow through the Arduino. Also you need a power supply, that can handle your peak current. The RGB strips with WS2812 drivers can draw up to 60mA per LED (on white in full brightness). So for a strip with 160 of them it would be a current of 60mA * 160 = 9.6A. Add a little headroom and you would need a power supply, that can at least provide 10A of current.

But i have run other sketches, much more complex, on the whole of the 300 led strip, so not sure I get why this sketch is having a power issue.

We haven't seen your previous sketches. But most likely you had a lower current, because you didn't light up all LEDs at once and/or only at lower brightness. The drawn current depends on how bright you set each LED (to be specific each color of each LED, since one RGB LED is actually 3 LEDs with the colors red, green and blue in one casing). So your current was low enough to not brown out the power from the Arduino.

Appreciate it @chrisl.... not that I had any reason to doubt you but I re-ran my sketch at a ridiculously low brightness and it ran forever.

@PaulM Your observation confirms the answer.

source: Stack Exchange

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

sort: votes


text:
Arduino IDE Auto Format Error
Whenever I try to format a sketch in the IDE (1.8.19) I get this output in the terminal:
Exception in thread "AWT-EventQueue-0" java.lang.UnsatisfiedLinkError: 'java.lang.String cc.arduino.packages.formatter.AStyleInterface.AStyleMain(java.lang.String, java.lang.String)'
          at cc.arduino.packages.formatter.AStyleInterface.AStyleMain(Native Method)
          at cc.arduino.packages.formatter.AStyle.run(AStyle.java:80)
          at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313)
          at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770)
          at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
          at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
          at java.base/java.security.AccessController.doPrivileged(Native Method)
          at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
          at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:740)
          at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
          at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
          at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
          at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
          at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
          at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

...And formatting fails.
I can use astyle from the command line (linux mint) and it works well.
Guessing that some basic package was missing, or corrupted, I reinstalled Arduino, but the issue remained.
I don't precisely recall any specific changes made to my system prior to encountering this behavior, as it's been like this for at least 8 or 9 months now. I hadn't used Arduino for some time up until that point and it may have been a fresh instal.
Since I just started a new project for a buddy of mine and encountered the bug again I decided maybe it was time to see about a better solution.
Any help troubleshooting this would be greatly appreciated.

https://github.com/arduino/Arduino/issues/11728 might be similar (from package manager it didn't work, downloaded from arduino.cc worked)

Thanks. Yes, the version from https://www.arduino.cc/en/software does work.

I googled the first line of stack trace and found similar issue on github (but for SUSE linux). In this issue the Arduino IDE was installed by system package manager and after downloading latest package from arduino.cc/en/software it started working.
In general Arduino IDE linux packages are somehow problematic (as far as I know Ubuntu has still version around 1.0.6) and it's better to use latest version directly from arduino.cc

I'm not sure that it's a version issue, maybe something in the dependencies... I installed from the Ubuntu Jammy package, and got Arduino 1.8.19, which yielded the error in the original post, on multiple installations. Then I installed that same version from the Arduino site and it worked fine.

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


text:
Can't upload sketch after overheating
I'm using an Arduino nano, after an unfortunate event, The mega chip heat up and when I tried touching it, it burned my finger. After that, I connected to my laptop's USB port and the computer recognized it. But after I hit the upload button, the RX light flash 3 times and stop, no Loader light and it just stop there, and the IDE says this:
Arduino: 1.8.19 (Windows 10), Board: "Arduino Nano, ATmega328P (Old Bootloader)"

Sketch uses 2806 bytes (9%) of program storage space. Maximum is 30720 bytes.

variables use 44 bytes (2%) of dynamic memory, leaving 2004 bytes for local variables.
Maximum is 2048 bytes.

An error occurred while uploading the sketch

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x84

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Any advice?

Get a new one? It's possible the USB bridge survived, but the actual MCU did not.

"Any advice?¨ I'm not sure what you're going to find as acceptable advice.So, you may want to make that clear. As is the advice is something like: buy a new board..

make an assumption that the issue is just a coincidence and do all necessary troubleshooting ... only it all fails, declare the device to be dead

Right, getta new one then

Not sure what you did but you probably either overvoltage it or connected it backwards. The odds are extremely high you fried the mega chip. Good news, it is not a total waste, you learned something not to do. It is still good for practicing troubleshooting, if you find what failed great or if you cannot fix it,  you will have learned something useful. Atthis point use it for practicing SMD soldering. In the end remove the parts and use the PCB for a template. The recommended solution is to purchase two more, that way if one fails the wate time will be shorter.

Yea, It might be because when I plug it into the board, the Arduino is reversed and d10/d12 is plugged to 5v/gnd instead of gnd and vcc. Or maybe I moved it back a pin so the rst/gnd is plugged to the 5v/gnd. I honestly can't be sure about it as how panicked I was back then.


text:
On Linux Min21, unable to access tools/port (grayed out)
I have dual boot laptop, Windows 11 & Linux Mint 21 (default boot).  when running Arduino IDE 1.8.19 using Linux the port not accessible [from tools/port], but if I boot as windows, I can access the port from the Arduino IDE.
Other applications running in Linux can access the USB drive without issue (eg FreeCAD, PrusaSlicer). Arduino IDE is the only app so far with this USB issue.
"dialout" is in my list of groups
Arduino IDE was installed using apt
If I run lsusb when the nano is connected, i see the following extra entry
Bus 003 Device 009: ID 1a86:7523 QinHeng Electronics CH340 serial converter

On another post it suggested running ls -l /dev/ttyUSB* and ls -l /dev/ttyACM*. For both I get the response "No such file or directory". The following files starting with tty* are in the /dev directory
tty    tty11  tty15  tty19  tty22  tty26  tty3   tty33  tty37  tty40  tty44  tty48  tty51  tty55  tty59  tty62  tty9       ttyS10  ttyS14  ttyS18  ttyS21  ttyS25  ttyS29  ttyS4  ttyS8
tty0   tty12  tty16  tty2   tty23  tty27  tty30  tty34  tty38  tty41  tty45  tty49  tty52  tty56  tty6   tty63  ttyprintk  ttyS11  ttyS15  ttyS19  ttyS22  ttyS26  ttyS3   ttyS5  ttyS9
tty1   tty13  tty17  tty20  tty24  tty28  tty31  tty35  tty39  tty42  tty46  tty5   tty53  tty57  tty60  tty7   ttyS0      ttyS12  ttyS16  ttyS2   ttyS23  ttyS27  ttyS30  ttyS6
tty10  tty14  tty18  tty21  tty25  tty29  tty32  tty36  tty4   tty43  tty47  tty50  tty54  tty58  tty61  tty8   ttyS1      ttyS13  ttyS17  ttyS20  ttyS24  ttyS28  ttyS31  ttyS7

If I tail the system log and plug the nano into the usb drive I get the following (the answer my be here but I cant see it).
Oct  7 17:17:14 HP-Envyl kernel: [ 8949.381626] usb 3-4: new full-speed USB device number 14 using xhci_hcd
Oct  7 17:17:14 HP-Envyl kernel: [ 8949.599105] usb 3-4: New USB device found, idVendor=1a86, idProduct=7523, bcdDevice= 2.64
Oct  7 17:17:14 HP-Envyl kernel: [ 8949.599107] usb 3-4: New USB device strings: Mfr=0, Product=2, SerialNumber=0
Oct  7 17:17:14 HP-Envyl kernel: [ 8949.599108] usb 3-4: Product: USB Serial
Oct  7 17:17:14 HP-Envyl kernel: [ 8949.601365] ch341 3-4:1.0: ch341-uart converter detected
Oct  7 17:17:14 HP-Envyl mtp-probe: checking bus 3, device 14: "/sys/devices/pci0000:00/0000:00:14.0/usb3/3-4"
Oct  7 17:17:14 HP-Envyl mtp-probe: bus: 3, device: 14 was not an MTP device
Oct  7 17:17:14 HP-Envyl kernel: [ 8949.601888] usb 3-4: ch341-uart converter now attached to ttyUSB0
Oct  7 17:17:14 HP-Envyl systemd[1]: Starting Braille Device Support...
Oct  7 17:17:14 HP-Envyl brltty[12613]: BRLTTY 6.4 rev BRLTTY-6.4 [https://brltty.app/]
Oct  7 17:17:14 HP-Envyl brltty[12613]: BRLTTY 6.4 rev BRLTTY-6.4 [https://brltty.app/]
Oct  7 17:17:14 HP-Envyl brltty[12613]: executing as the invoking user: root
Oct  7 17:17:14 HP-Envyl brltty[12613]: brltty: executing as the invoking user: root
Oct  7 17:17:14 HP-Envyl mtp-probe: checking bus 3, device 14: "/sys/devices/pci0000:00/0000:00:14.0/usb3/3-4"
Oct  7 17:17:14 HP-Envyl mtp-probe: bus: 3, device: 14 was not an MTP device
Oct  7 17:17:14 HP-Envyl brltty[12613]: CLDR open error: No such file or directory: /usr/share/unicode/cldr/common/annotations/en.xml
Oct  7 17:17:14 HP-Envyl brltty[12613]: brltty: CLDR open error: No such file or directory: /usr/share/unicode/cldr/common/annotations/en.xml
Oct  7 17:17:14 HP-Envyl brltty[12613]: brltty: possible cause: the package that defines the CLDR annotations directory is not installed
Oct  7 17:17:14 HP-Envyl brltty[12613]: brltty: emoji substitutiion won't be performed
Oct  7 17:17:14 HP-Envyl brltty[12613]: brltty: BrlAPI Server: release 0.8.3
Oct  7 17:17:14 HP-Envyl brltty[12613]: possible cause: the package that defines the CLDR annotations directory is not installed
Oct  7 17:17:14 HP-Envyl systemd[1]: Started Braille Device Support.
Oct  7 17:17:14 HP-Envyl brltty[12613]: emoji substitutiion won't be performed
Oct  7 17:17:14 HP-Envyl brltty[12613]: BrlAPI Server: release 0.8.3
Oct  7 17:17:14 HP-Envyl brltty[12613]: Linux Screen Driver:
Oct  7 17:17:14 HP-Envyl brltty[12613]: brltty: Linux Screen Driver:
Oct  7 17:17:14 HP-Envyl kernel: [ 8950.123164] input: BRLTTY 6.4 Linux Screen Driver Keyboard as /devices/virtual/input/input49
Oct  7 17:17:15 HP-Envyl brltty[12613]: USB configuration set error 16: Device or resource busy
Oct  7 17:17:15 HP-Envyl brltty[12613]: brltty: USB configuration set error 16: Device or resource busy
Oct  7 17:17:15 HP-Envyl brltty[12613]: USB interface in use: 0 (ch341)
Oct  7 17:17:15 HP-Envyl brltty[12613]: brltty: USB interface in use: 0 (ch341)
Oct  7 17:17:15 HP-Envyl ModemManager[1013]: <info>  [base-manager] port ttyUSB0 released by device '/sys/devices/pci0000:00/0000:00:14.0/usb3/3-4'
Oct  7 17:17:15 HP-Envyl ModemManager[1013]: <info>  [base-manager] couldn't check support for device '/sys/devices/pci0000:00/0000:00:14.0/usb3/3-4': Operation was cancelled
Oct  7 17:17:15 HP-Envyl kernel: [ 8950.239032] usb 3-4: usbfs: interface 0 claimed by ch341 while 'brltty' sets config #1
Oct  7 17:17:15 HP-Envyl kernel: [ 8950.239683] ch341-uart ttyUSB0: ch341-uart converter now disconnected from ttyUSB0
Oct  7 17:17:15 HP-Envyl kernel: [ 8950.239693] ch341 3-4:1.0: device disconnected
Oct  7 17:17:15 HP-Envyl brltty[12613]: NoSpeech Speech Driver:
Oct  7 17:17:15 HP-Envyl brltty[12613]: brltty: NoSpeech Speech Driver:
Oct  7 17:17:18 HP-Envyl rtkit-daemon[3252]: Supervising 10 threads of 3 processes of 1 users.

Does anyone have any idea what can cause this issue?

Do you use brltty?

Uninstall brlttyfor a start.

OK, i can close this. brtty was the problem. I disabled it (found instructions below on another post)
systemctl stop brltty-udev.service
sudo systemctl mask brltty-udev.service
systemctl stop brltty.service
systemctl disable brltty.service

After logout and login, it works now.
Thanks for the help. I did not have this issue on Mint 20, so i am guessing that brtty was automatic in Mint 21

In a couple of days you'll be able to "accept" your own post. Unless a different one shows up that you like better, you probably should.


text:
Connect OLED SSD1306 to Elegoo Uno R3
I'm trying to connect the OLED SSD1306 screen to my Elegoo Uno R3 and display something using Arduino IDE. However, nothing shows up on the screen for some reason.
I have connected every pin in the following way:

VCC: 3.3V
GND: GND
SCL: A5
SDA: A4

You can see the setup in the following pictures:

Then, I'm using the code from this tutorial, that is, this code, to see if the setup is correct, but nothing shows up on the screen. My question is: does anybody know if this is right way to do it? Even though I'm using analog pins and the screen needs digital ones, I read online that it doesn't matter:

The analog input pins can be used as digital pins, referred to as A0, A1, etc. The exception is the Arduino Nano, Pro Mini, and Mini’s A6 and A7 pins, which can only be used as analog inputs.

I also saw in Elegoo Uno R3's guide that the A4 and A5 pins are used for the I2C protocol, which is the one that this OLED screen uses:

So as far as I know, from the hardware point of view, everything seems to be correct, right?

Did you check that your code uses the correct I2C address for your particular OLED display? If you're not sure about the address, you could run the I2C scan example sketch to find it. You can find it in the Arduino IDE in Examples->Wire->WireScan.

@StarCat Yes, it's the 0x3C address: Scanning... I2C device found at address 0x3C! done

Did you need to change any parameters in the sample code to match your display e.g. SCREEN_HEIGHT ?

Many of these modules have their own onboard 3.3V regulator. You appear to power it from 3.3V while the tutorial you cited is powering it from 5V. Perhaps it "works" enough with 3.3V minus regulator-dropout to respond to I2C but not enough to actually light the display.

Well, I found one of my own displays with similar (not same) looking design, which I can see has a regulator. It didn't seem to care whether it was powered it from 5V or 3.3V. Worked with your code in both cases.  I don't know how definitive that is though. If yours is a type designed to operate with 5V into VCC I would still try it. I wouldn't have used the colors where you did, but I don't see anything technically wrong with your wiring.  My display also responds to 3C.

You are close. Looks like you have a run-of-the-mill, clone [not Adafruit], 128x64 LCD with / I2C interface.

Determine the I2C address by flipping it over and seeing which side a 0 ohm resistor or solder blob is on - either 0 or 1. If it is on the '0' side, the address is 0x3C if it is on the '1' side, it is 0x3D.

Here is a photo of the back and with the address of 0x3c.

If the back of yours looks very different, locate and run an I2C device scanner to find the address of your display.

Do not use the code that you linked.

From the Arduino IDE, install or update the the Adafruit SSD1306 library, Version 2.57 is what I used to test this.
Once the library is in place, load the example SSD1306_128X64_I2C
Locate this line (near the beginning of the code):
#define SCREEN_ADDRESS 0x3D ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Change 0x3D to 0x3C if you need to (as determined earlier). I don't think it is an Adafruit screen, so you can ignore the comment.

Triple check your 4 connections

Run demo and audibly gasp - "cool".
PS: Mine works on either 3.3V or 5V


text:
wemos d1 mini keeps resetting while using SIM800L
I am trying to do a small project with SIM800L with Wemos d1 mini. It is a DTMF based project. The problem here is, every time I make a call the d1 mini is getting reset. This is my first project with d1 mini. For the past few days I have googled, trying to find a solution. But I failed. I will be very grateful if you can provide the solution.
I am getting these errors in the serial monitor:
 ets Jan  8 2013,rst cause:4, boot mode:(3,7)

wdt reset
load 0x4010f000, len 3460, room 16
tail 4
chksum 0xcc
load 0x3fff20b8, len 40, room 4
tail 4
chksum 0xc9
csum 0xc9
v00043b40
~ld

I am using Arduino IDE. Version: 1.8.8
Here is my project code.
#include <SoftwareSerial.h>

#define rxPin D3
#define txPin D4
SoftwareSerial sim800L(rxPin, txPin);

#define RELAY_1 D7
#define RELAY_2 D8
boolean relay1_state = false;
boolean relay2_state = false;

//stores incomming data from sim800l
String buff;
String dtmf_cmd;
boolean is_call = false;
String ownerNumber = "xxxxxxxxxxxxxxx";

void setup()
{
  pinMode(RELAY_1, OUTPUT);
  pinMode(RELAY_2, OUTPUT);

  //Begin serial communication with (Serial Monitor)
  Serial.begin(115200);

  //Begin serial communication with (SIM800L)
  sim800L.begin(9600);
  Serial.println("Begin serial communication with (SIM800L)");
  delay(500);

  sim800L.println("AT"); //send AT
  delay(500);

  sim800L.println("AT+DDET=1"); //Enable DTMF
  delay(500);

  sim800L.println("AT+CLIP=1"); // Enable CallerID
  delay(500);
}

void loop()
{
  while (sim800L.available()) {
    buff = sim800L.readString();
    Serial.println("Raw: " + buff);

    if (is_call == true) {
      if (int index = buff.indexOf("+DTMF:") > -1 ) {
        index = buff.indexOf(":");
        dtmf_cmd = buff.substring(index + 1, buff.length());
        dtmf_cmd.trim();
        Serial.println("dtmf_cmd: " + dtmf_cmd);
        doAction();
      }
      if (buff.indexOf("NO CARRIER") > -1) {
        sim800L.println("ATH");
        is_call = false;
      }
    }
    if (buff.indexOf("RING") > -1) {

      // Now check the caller number
      if (buff.indexOf("+CLIP:")) {
        unsigned int index, index1;

        index = buff.indexOf("\"");
        index1 = buff.indexOf("\"", index + 1);

        String temp = buff.substring(index + 2, index1);
        temp.trim();

        if (ownerNumber == "+" + temp) {
          Serial.println("Number matched");
          delay(2000);
          sim800L.println("ATA");
          is_call = true;
        } else {
          Serial.println("Number not matched");
        }
      }
    }
  }

  while (Serial.available())  {
    sim800L.println(Serial.readString());
  }
}

void doAction() {
  if (dtmf_cmd == "1") {
    relay1_state = !relay1_state;
    digitalWrite(RELAY_1, relay1_state);
    if (relay1_state == true)
    {
      Serial.println("Relay 1 has been ON");
    }
    else
    {
      Serial.println("Relay 1 has been OFF");
    }
  }
  else if (dtmf_cmd == "2") {
    relay2_state = !relay2_state;
    digitalWrite(RELAY_2, relay2_state);
    if (relay2_state == true)
    {
      Serial.println("Relay 2 has been ON");
    }
    else
    {
      Serial.println("Relay 2 has been OFF");
    }
  }
}

rst cause:4, is a watchdog reset. Add yield() inside your loop() to allow "breathing" at each loop.

I tried, nothing changed.


text:
Nucleo F446ZE VS Nucleo F446RE
I don't know if this is the right forum to ask this, but I can't find people that want to help, so let's try it here...
First I had an F446RE, and program it in PlatformIO with an Arduino Framework...
Now I have a Nucleo F446ZE and want to program it, but in PlatformIO I can't choose Arduino Framework.
Can I change that? or  what else to use?
CMSIS
Nbed
STM32Cube
libopencm3
Zephyr RTOS
thanks!

Unfortunately, STM32duino (STM32 Arduino Core) supports F446RE, but not F446ZE yet. Depend on your skill, STM32 Arduino Core wiki has description on how to create your own custom board, but it is not for beginner. For non-Arduino, I would suggest to use STM32CubeIDE.

And who put them in the STM32 arduimo Core?

As an open source project, anyone can help out to create the variant and submit a pull request to add the variant via STM32duino github, in fact ST maintain a long list of boards that they hope someone could help to add the variant for supporting various boards.


text:
FastLED WS2812B with Esp8266 Wemos D1 mini shows 1 first led only
I'm working with WS2812B LED Strip (and Ring), Esp8266 Wemos D1 mini and FastLED library. I want to show  leds with same solid color in every startup.
There is a strange behavior that only the first 1 Led lights up. The code is very simple:
#include <FastLED.h>

#define NUM_LEDS 24
#define DATA_PIN D6

CRGB leds[NUM_LEDS];
void setup()
{
  uint8_t i = 0;
  FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(50);

  for (i = 0; i < NUM_LEDS; i++) {
    leds[i] = CRGB::Black;
  }

  for (i = 0; i < 7; i++) {
    leds[i] = CRGB::Red;
  }
  FastLED.show();  //1 show() lights up only first led
}

void loop() {
}

If I add one more show() call, it works as expected.
#include <FastLED.h>

#define NUM_LEDS 24
#define DATA_PIN D6

CRGB leds[NUM_LEDS];
void setup()
{
  uint8_t i = 0;
  FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(50);

  for (i = 0; i < NUM_LEDS; i++) {
    leds[i] = CRGB::Black;
  }

  for (i = 0; i < 7; i++) {
    leds[i] = CRGB::Red;
  }
  FastLED.show();   //1st show()
  FastLED.show();   //2nd show() works as expected
}

void loop() {
}

I'm not sure what the correct way to show LEDs is. This is just a short code from my bigger project, I made it minimal for debugging. Please help me this.
Thank you.

have you tried example code that is included with the library?

@jsotola the example codes are color animation. I just want to show solid color. Could you please let me know what I am missing?

does the example code work as expected?

@jsotola The example code animation run so fast so I don't know what the first color is expected.

I tried Blink example with little changes
void loop() {
// Turn the LED on, then pause
leds[0] = CRGB::Red;
leds[1] = CRGB::Red;  //Added
FastLED.show();
delay(500);
// Now turn the LED off, then pause
leds[0] = CRGB::Black;
leds[1] = CRGB::Black;  //Added
FastLED.show();
delay(500);
}
At start up, it shows only the first LED, after that 2 LEDs are blinking -> The same issue with mine

@hcheung it's not a proper way to put show() into for loop. As I mentioned, this is just a small part of my bigger project where has hundreds of leds. Moving show() into loop cause the system very slow

@hcheung as per my understanding, show() will clock ALL data out. It means if there is 500 leds, one show() will clock 500 data out. Therefore, if you put show() in loop, it will clock out 500*500 data - 250000 data which will cause system hanged up. Have you tried with lednum = 500 and print the execution time after a loop?

Not sure if it's relevant but I recall hearing/seeing/reading somewhere that you should "clear" (turn off) all LEDS (using .show()) before displaying what you want ... so, it kinda means that the minimum number of calls to .show would be two

@JaromandaX Wow... that's a useful information that I've never read before. Do you remember that the "clear" show() should be called everytime or just the first time in setup()?

just once in setup of course ... you don't want to keep "blanking" the LED, that would be annoying ... since most uses of WLED are in the loop(), most would not probably notice that the "first" show() doesn't work right ... but, again, I'm not 100% sure of the veracity of my comment

@JaromandaX ok, thank you very much for your information


text:
How to trigger a function by detecting voltage change?
#define monitor_pin 14

void setup()
{
  pinMode(monitor_pin , INPUT);
}

void loop()
{
    unsigned long d1 = pulseIn(14, HIGH);
    if (d1>0){//trigger function}
}

I know there is a function pulseIn(), but it doesnt really solve my problem. I just want to trigger a function when voltage change from LOW to HIGH/HIGH to LOW. pulseIn() need to wait for the voltage to back to original level which in my case will exceed 3 minutes and cause timeout.
How can  I detect a voltage change other than pulseIn()?

The length of the pulse is of no interest to you at all?

@timemage yes, i dont need the pulse length at all.

You can save the previous state of the pin and then trigger the function when the current state is different from the previous state:
#define monitor_pin 14
int previous_state;

void setup()
{
  pinMode(monitor_pin , INPUT);
  previous_state = digitalRead(monitor_pin); // Initialize previous state with initial reading of the pin
}

void loop()
{
  int current_state = digitalRead(monitor_pin);
  if(current_state != previous_state){
    // Execute your code here
    previous_state = current_state; // update previous state
  }
}


text:
how to transfer json to string?
I am getting a json object from aws iot MQTT. Assuming that json from aws is {status:opened}.
Here is my code.
#include <ArduinoJson.h>
void messageHandler(char *topic, byte *payload, unsigned int length)
{
  StaticJsonDocument<32> doc;
  deserializeJson(doc, payload);
  const char *status = doc["status"];
  Serial.println(status);//opened
  if (status == "opened")
  {
    Serial.println("door is opened");//not excute
  }
  else if (status == "closed")
  {
    Serial.println("door is closed");
  }
}

Why the if condition is not being excute?

what's printed in the serial monitor?

That's one of the peculiarities of the C language: the == operator compares the string addresses, not their content. It makes sense when you think of them as pointers, but it can be confusing for beginners.
To fix this, you can use strcmp() like so:
if (strcmp(status,"opened") == 0)
Alternatively, you can change the type of status to JsonVariant, like so:
JsonVariant status = doc["status"]
It works with JsonVariant because I overloaded the == operator to support string comparison.

if (strcmp(status,"opened") == 0)  You know probably knew this and just forgot, but for the benefit of anyone else, strcmp returns 0 for equality, and some negative and positive numbers for the other relative orderings. So, you'll want the == 0. Upvote.

Thanks, I updated the answer.

Disclaimer: I appreciate your work on this library. This and your answer are good and helpful. -- However, overloading operators in such a way is one of the many reasons I still dislike C++ after 40+ years of software development in many languages. It hides a lot of things up-front and (mis)leads to weird constructs, making it hard for non-experts to grasp good programming. C++ is therefore not an adequate programming language for beginners.


text:
Where to store struct used for driver initialization
I'm doing a small project with ESP32 board. When initializing a driver, multiple structs are passed to initialization functions. I know that there are two ways to store such structs:

Storing structs on heap (with calloc or malloc)

adc_continuous_config_t cfg = calloc(1, sizeof(adc_continuous_config_t));

cfg->sample_freq_hz = 4500;
cfg->conv_mode = ADC_CONV_SINGLE_UNIT_1;
cfg->format = ADC_DIGI_OUTPUT_FORMAT_TYPE;

adc_continuous_config(*handle, cfg);
free(cfg);

Storing structs on stack

adc_continuous_config_t cfg = {
    .sample_freq_hz = 4500,
    .conv_mode      = ADC_CONV_SINGLE_UNIT_1,
    .format         = ADC_DIGI_OUTPUT_FORMAT_TYPE1,
};

adc_continuous_config(*handle, &cfg)

I was wondering which approach is encouraged.

It depends on several details, like: What is the requested lifetime of the data? Will the data be reused later? Are the values of the structure known at compile time? And probably some more. So this question cannot be answered in general.

I think the struct is only used for driver initialization which will only happen once in the machine's lifetime which means it will not be reused until reboot. All the values of the struct are simply predefined constants so they are known at compile time.

Then go with Edgar's solution, placing the structure in flash memory.

You seem to be initializing this struct with constants. In such a case,
I would use neither the heap nor the stack, but a third option: the
“read-only data” section of the program. At global scope:
const adc_continuous_config_t cfg = {
    .sample_freq_hz = 4500,
    .conv_mode      = ADC_CONV_SINGLE_UNIT_1,
    .format         = ADC_DIGI_OUTPUT_FORMAT_TYPE1,
};

Rationale: The constants you are using to fill the struct have to be
stored somewhere in the flash when the program is not running. Although
I do not know the details of the machine language of the ESP32, it seems
to me the compiler has only two options to compile your example code. It
could say:

load a CPU register with the immediate value 4500
store that register at the address of cfg->sample_freq_hz
load a CPU register with the immediate value ADC_CONV_SINGLE_UNIT_1
etc.

Then the values are stored as immediate operands of machine
instructions. The other option would be to store an anonymous version of
the initialized struct in the read-only data section of the program, and
issue a memcpy() to initialize the allocated space at run time.
If you instead store the initialized struct as a global constant, it
will go straight into the read-only data section of the program (like in
the second compiler strategy), and you will use it from there. No extra
copy needed. No extra machine instruction for initializing space
allocated on the heap or stack.
Caveat: I assume adc_continuous_config() expects its second
parameter to be of type “pointer to const data”. If it expects it to
be a pointer to modifiable data, then this will not work.


text:
How to compile Arduino-ESP32 core with ESP_LOGx
Why?
In Arduino IDE you can set the core debug level, however, this only sets debug level for files in Arduino-esp32 but the core which is distributed as a precompiled library in .sdk files, located in your Arduinio installation folder, is unaffected - the debug level remains the default “error”.

What?
If you want to change the core code or debug level, you need to clone the repo: https://github.com/espressif/esp32-arduino-lib-builder, make the modifications there, compile and apply the changes (automatically by the build script).
How?
There are 2 basic approaches. Both of them involve editing file esp32-arduino-lib-builder/configs/defconfig.common.
The first option is to edit the file directly and then build.
Later you can git restore configs/defconfig.common to go back.
The second option is to copy the file cp configs/defconfig.common configs/defconfig.debug, edit the debug version and then compile.
Open the defconfig file
vim configs/defconfig.common or vim configs/defconfig.debug
Edit line 45 containing by default CONFIG_LOG_DEFAULT_LEVEL_ERROR=y to one of the following lines depending on your desired log level:
CONFIG_LOG_DEFAULT_LEVEL_NONE=y # No output
CONFIG_LOG_DEFAULT_LEVEL_ERROR=y # Errors - default
CONFIG_LOG_DEFAULT_LEVEL_WARN=y # Warnings
CONFIG_LOG_DEFAULT_LEVEL_INFO=y # Info
CONFIG_LOG_DEFAULT_LEVEL_DEBUG=y # Debug
CONFIG_LOG_DEFAULT_LEVEL_VERBOSE=y # Verbose - All of the above

Then simply build the libs for all SoCs or one specific SoC. Note that building for all SoCs takes a lot of time, so if you work only with one specific SoC, build only for that one.
If you have copied the defconfig file and the debug settings are in file configs/defconfig.debug add flag debug
example : ./build.sh debug
Build all SoCs: ./build.sh
Build only selected SoC: ./build.sh -t <soc>
The exact text to choose the SoC:

esp32
esp32s2
esp32c3
esp32s3
Example: ./build.sh -t esp32
A wrong format or non-existing SoC will result in the error sed: can't read sdkconfig: No such file or directory


text:
ESP & Servo not communicating well
I have a mystery I was unable to solve and would greatly appreciate it if anyone could shed some light on this.
I have a servo DSS-M15S 270 which I managed to run perfectly fine with Arduino Uno (code below). I need only 2 cables for this - output & ground. The power cable is connected to batteries and the analog is irrelevant (although I managed to connect it as well just fine).
Same exact code on an ESP8266 NodeMCU fails to run the servo. I validated the right GPIO with a different sensor (PIR) that worked fine with the ESP, but the motor wouldn't work - it slightly jitters after a few minutes but nothing works. I already tried changing between different GPIOs and seeing different reactions but still nothing.
Eventually, I connected a new ESP32 with the same code and it almost worked! the servo works during the calibration function but ANY attempt to move it again OUTSIDE the calibration function fails. so I cancelled the calibration function and the servo works perfectly fine now with the ESP32 ! I have no idea how or what is happening.. if anyone could help me get it to work on ESP8266, that would be amazing.
Based on all those tests I reckon it's related to the different servo libraries of the chips somehow.
https://youtube.com/shorts/fZlu8wdeRGQ
In this second video I just return the cables back to the Arduino and everything works again (same code, same connection pins) -
https://youtube.com/shorts/Jvr1oZV1AKI
#include <Servo.h>

Servo myservo;

// Control and feedback pins
byte servoPin = 4;
int feedbackPin = A0;

// Calibration values
int minDegrees;
int maxDegrees;
int minFeedback;
int maxFeedback;
int tolerance = 2;  // max feedback measurement error

void calibrate(Servo servo, int analogPin, int minPos, int maxPos) {
    // Move to the minimum position and record the feedback value
    servo.write(minPos);
    minDegrees = minPos;
    delay(2000);  // make sure it has time to get there and settle
    minFeedback = analogRead(analogPin);

    // Move to the maximum position and record the feedback value
    servo.write(maxPos);
    maxDegrees = maxPos;
    delay(2000);  // make sure it has time to get there and settle
    maxFeedback = analogRead(analogPin);
}

int getPos(int analogPin) {
    return abs(map(analogRead(analogPin), minFeedback, maxFeedback, minDegrees, maxDegrees));
}

void ServoSetup() {
    Serial.println("Setting output");
    pinMode(servoPin, OUTPUT);

    Serial.println("Attaching");
    myservo.attach(servoPin);

    Serial.println("Calibrating");
    calibrate(myservo, feedbackPin, 0, 270);
}

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

void loop() {
    Serial.println(analogRead(A0));
    myservo.write(270);
    Serial.println("270");
    delay(2000);
    Serial.println(analogRead(A0));
    myservo.write(0);
    Serial.println("0");
    delay(2000);
}

The final code is basically like the above but without the calibration and different pins for the ESP32
Any ideas on what's happening here and how to make this work with ESP8266 would be great
Thanks,
Shay

Isn't the UNO running with 5V and the ESPs with only 3.3V? I suspect the servo needs 5V on the control input. It may work a bit with ESP32 but not with ESP8266 because the boards may give slightly different GPIO voltage?

I thought voltage makes a difference only for VCC and not GPIOs but it makes sense I suppose.. thanks

How can you tell the voltage consumption of a GPIO? should that be specified somewhere??

A GPIO does not have a voltage consumption. It can only source or sink current. A ESP8266 can not deliver more than 12 mA on a GPIO, while the ESP can deliver up to 40 mA per pin. That could explain that it works a bit better with ESP32. Both work on 3.3 V. But the UNO works on 5V - which is compatible with the servo's datasheet. I think your problem does NOT lie in the libraries or software. Show how did you wired everything up!


text:
Arduino: Camera streaming
I want to make Arduino to stream video by camera thru bluetooth to android.

Is Arduino powerfull enough to stream it without lag(Sorry if the question is stupid)
Are there any good cameras, I have been searching before, but only found        one 0.3 mp camera, so are there other cameras with better quality?
What is better, to use Arduino or Rasberry Pi for that job?

Not even close
In light of 1 it doesn't matter
Get a Pi if you want to do video

Assuming a 0.3 MP camera, that means 300,000 pixels. The Arduino (Uno) has a few KB of SRAM, so you need much more. External SRAM might be an option, but even 300.000 pixels need a lot (like multiple 23LC1024 SRAMs).
Also the Arduino is 16 MHz. This means 16.000.000 cycli/s. That means for every pixel processing only 53 cycli are available. And using those external SRAMs will probably need much more.
A Raspberry is much more suitable for this task.

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


text:
L and ON keeps blinking
I am not sure why the ON LED and the L LED keeps blinking on my Arduino.
I was just trying to implement a simple circuit using breadboard, and everything worked fine until I unplugged one wire with the power turned on. I accidentally made the wire touch something in the Arduino, and the LED in the breadboard became extremely bright. Then the ON LED and the L LED in the Arduino started to keep blinking, and I cannot download code to Arduino anymore. I am using IAR and IAR says AT91SAM3 reset: Communication breakdown after resetting target. Abort debug session?.
I think maybe there is a short cut when the wire touched the Arduino... But how can I determine what the problem is? Thank you very much, I am totally new to Arduino and has very limited knowledge about hardware...

It's dead. Buy another.

You should split your problem in pieces. Like you cannot get communication with your Arduino again, so check first:

If you plug in the Arduino / USB, do you get a message on your computer?
Is it visible in the systems manager?
Is it visible by the IDE?
If you connect an adapter (12 or 9V), does it make a difference?
If you try another Arduino, does it work like it should be?

If you are a beginner, always make sure:

Never change any wiring with the Arduino on
Never have dangling wires, if you do not need a wire for the time being, either remove it completely or put it in a breadboard hole that is not used
Never change components with the Arduino on
After rewiring/adding/changing components, double check first

Update for comment below because it does not fit as comment:
To buy a cheap/fake (but working) Arduino uno, e.g.
Arduino Uno from Aliexpress

Hi, thanks for your advice! The Arduino is visible to the IDE, and I will get another Arduino to check tomorrow. It worked fine before, everything changed since the touch.

I'm afraid something is not working in the Arduino anymore ... and unless you are more expert it might be useful to try to fix it, otherwise buy a new one ... I bought some from China, much cheaper and if something breaks it cost just a few euro.

What an expensive lesson:-(
Is it proper to ask how buy it from China here, can you tell me? I am at Sweden.

First I want to say not everybody likes it and it has some disadvantages. First you have to wait from 2 to 10 weeks, also they are fake (so might have some small differences, so far I didn't have many problems). But you can go to e.g. aliexpress and buy the one in my link (does not fit). Also these have a different chip and you probably need to install CH340G drivers (very easy to install).

Another method to avoid having to buy a new board when you screw something up, is get one with a microcontroller that can be taken out. Half the time, you'll only have damaged the controller and the board survived. Controller is less expensive than a full board. All the first ones had it, not sure about the later ones. Often times you don't need the M3 and an Atmega would've been fine.

@Mast Good comment ... I noticed most cheap ones don't have a separate chip. However, you can use use the programmed chip without the Uno in a finished project.

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


text:
Error Starting SPIFFS
There is a problem running a simple SPIFFS file system code on different versions of the Arduino IDE, as code shown below. In Arduino IDE version 1.8.4, works fine. No longer version 1.8.9, can not run.
ESP8266
IDE Arduino version 1.8.9
#include <FS.h>

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println("Init...");
  Serial.println();

  // Always get ERROR on init SPIFFS
  if (!SPIFFS.begin()) {
    Serial.println("SPIFFS.begin error...");
  } else {
    Serial.println("SPIFFS.begin OK!");
  }
}

So you have spiffs turned on in the IDE settings?

Where can I check that in IDE?

in Tools menu the "Flash size" option

OK. It works: Tools -> Flash size 4M (1M SPIFFS). Thanks!!!!


text:
Notifications in constant loop (Blynk) trying to trigger along with serial function
This is an extension from a previous thread that was getting lengthy and off the original topic. I have the following code which monitors the state of a float switch (high or low). I upload the sketch, turn on the serial monitor and manually move the float switch up and down. The serial monitor output represents what I'm doing with the switch. The issue is that I get a constant loop of blynk notifications, every 15 seconds or so. Furthermore, if i move the switch to it's low position, the first blynk notification i get is correct reading "low", the following notifications are "high" thereafter. When the switch is moved to the high position, blynk just loops stating it's "high". I know it's weird and took quite a while to even establish what is going on here. but the biggest issue is the loop of notifications every 15 seconds.
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
BlynkTimer timer;

char auth[] = "710a4af9b1d82412fa477705bf642c634";
char ssid[] = "ssid";
char pass[] = "pwd";
int flag=0;
int floatSavedState = -1;      // initial float low state indicates not yet known

void notifyOnButtonPress()
{
  // pin D1 will be 1 if float has dropped due to low water level
  // pin D1 will be 0 if water level is high enough
  int floatLevelLow = digitalRead(D1);  // read the float low indicator pin

  if (floatLevelLow && floatLevelLow != floatSavedState) {
       // send notification if this is first time or if the float level has
       // changed since the last notification.
       Serial.println("Resevoir Water is Low!");
       Blynk.notify("Alert : Water Level low.");
       floatSavedState = floatLevelLow;
  } else if (floatLevelLow != floatSavedState)
     // send notification if this is first time or if the float level has
     // changed since the last notification.
     Serial.println("Resevoir Water is High!");
     Blynk.notify("Alert : Water level high");
     floatSavedState = floatLevelLow;

}
void setup()
{
  // Debug console
  Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
  // Setup notification button on pin D1
  pinMode(D1,INPUT_PULLUP);
 timer.setInterval(16000L,notifyOnButtonPress);

}
void loop()
{
  Blynk.run();
  timer.run(); // Initiates BlynkTimer
}

Your code:
timer.setInterval(16000L,notifyOnButtonPress);

Is calling this function every 16s.
This code:
if (floatLevelLow && floatLevelLow != floatSavedState) {

needs some parentheses to force your desired order-of-operations. As it stands now, you are asking the result of floatLevelLow && floatLevelLow and comparing if that is not equal to floatSavedState. That's likely not what you want.
Did you mean:
if (floatLevelLow && (floatLevelLow != floatSavedState)) {

EDIT:
Also, your if/else is missing brackets around the 2nd clause and should be:
} else if (floatLevelLow != floatSavedState) {
     // send notification if this is first time or if the float level has
     // changed since the last notification.
     Serial.println("Resevoir Water is High!");
     Blynk.notify("Alert : Water level high");
     floatSavedState = floatLevelLow;
}

Thank you for your help with this! I added the parentheses and it is still acting in the same manner. If I comment out the timer function and the call for it, the sketch does not work at all once compiled.

Your code doesn't have brackets on the 2nd part of the if statement, so your code is calling Serial.println("Resevoir Water is High!"); if the if` is true, but it's always calling the remaining lines. I will update my answer to address this also.

You nailed it!!!! thank you so much, I've spent far too many hours on this!!!!


text:
I2C missing last byte during transmission- solution isn't clear
I am using a Nodemcu-32S to communicate with an I2C device (touchpads). I noticed while uploading the configuration, the CRC (checksum) always comes back incorrect. After doing a little digging with a logic analyzer, I realized that it never transmits the final byte from my configuration array, which is the checksum value. The function I use for writing to the I2C bus is as follows:
bool writeI2C(uint16_t address, uint8_t command, uint8_t *data, uint8_t dataLen)
{
    byte err;
    uint8_t dataPos = 0;
    Wire.beginTransmission(address);
    Wire.write(command);
    for (dataPos; dataPos < dataLen; dataPos++)
    {
        Wire.write(data[dataPos]);
    }
    delay(70);
    err = Wire.endTransmission();
    if (err > 0)
    {
        Serial.printf("writeI2C Error Code: 0x0%d\n", err);
        return false;
    }
    else
        return true;
}

With the following function call:
uint8_t config[128] = {0}; <- (the array is filled with values before the function call)

if (!writeI2C(SLAVE_ADDR, command, config, 128))
        {
            Serial.println("Failed to update config.");
            continue; // try again
        }

According to the logic in my function, it should transmit the address, then the register (command in this case) followed by 128 bytes of data (130 bytes total). With my logic analyzer, however, I get only 129 'chunks' of data. So I figured I'd add dummy writes if dataLen met a condition:
bool writeI2C(uint16_t address, uint8_t command, uint8_t *data, uint8_t dataLen)
{
    byte err;
    uint8_t dataPos = 0;
    Wire.beginTransmission(address);
    Wire.write(command);
    for (dataPos; dataPos < dataLen; dataPos++)
    {
        Wire.write(data[dataPos]);
    }
    if (dataLen > 100)
    {
        Wire.write(0x00);
        Wire.write(0x00);
        Wire.write(0x00);
        Wire.write(0x00);
        Wire.write(0x00);
    }
    err = Wire.endTransmission();
    delay(70);
    if (err > 0)
    {
        Serial.printf("writeI2C Error Code: 0x0%d\n", err);
        return false;
    }
    else
        return true;
}

None of the dummy writes are outputting and the behavior is the same. The final two bytes should be: config[126] = 0x45 and config[127] = 0xC9, but my logic analyzer is shows that the transmission stops at 0x45 + ACK.

Within Wire.h.:
#define I2C_BUFFER_LENGTH 128

Changed the buffer length to 140 and it's working just fine.


text:
Why does the Leonardo take 8 seconds to restart?
My problem is, that my system takes 8 seconds to start the programm after I push the Reset button on my Leonardo.
During that period the L-LED is pulsating.
What could be the problem?

That's the firmware waiting for a programming connection. If you want alternate behavior them burn SparkFun's ATmega32U4 firmware to it. One press of Reset will reset the device, and two presses will put it into programming mode.


text:
How to get a character from a serial Parsed http response?
I am a web developer and I am struggling with C code on Arduino. So this is What I have:
I have a backend written on PHP that returns a 0 or 1 depending of wether a pin should be high or low. I have an Arduino UNO with a W5100 Ethernet shield mounted, and I'm currently connecting correctly to my server, this is my Arduino code:
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.api-qa1.enerzoo.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

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

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /api/DeviceState/1 HTTP/1.1");
    client.println("Host: www.api-qa1.enerzoo.com");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

And this is the response it outputs:
connecting...
connected
HTTP/1.1 200 OK
Server: nginx/1.10.3 (Ubuntu)
Content-Type: application/json
Transfer-Encoding: chunked
Connection: close
Vary: Accept-Encoding
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With
Cache-Control: no-cache
Date: Fri, 17 Nov 2017 23:36:14 GMT
Set-Cookie: laravel_session=eyJpdiI6ImIzTDJzQk1BUm1qY1BuZ1BJXC83Mk5BPT0iLCJ2YWx1ZSI6IlwvNjlmXC9FZWxDSW9vbGNcL1JZUU5tbTFvOVVXVjcxV0hHaDRKUzVGVVZCSmFCM1BcLzlSR2x5MmN4cnZ1ZHRvZmlcLzNSUWMrZEFDMTQzR05ORTk5R3dBUGc9PSIsIm1hYyI6IjM4ZjVhY2IxOWVmZTMzMGY2OGE1MTNmZWY0NzczNGVhNWJhZjVkYzlkYzY4ODg3ZGI0OWVhNDYwOTkwYjgxYTAifQ%3D%3D; expires=Sat, 18-Nov-2017 01:36:14 GMT; Max-Age=7200; path=/; HttpOnly

1a
||0||
0

disconnecting.

I need to get that zero that is enclosed between the double pipes

||0||

Any help would be really appreciated

This is how I solved it. I avoided using regex expressions and "complex" functions such as substring in order to save memory. I just detected two consecutive pipes and get the next character (in this case 0 or 1) using a counter. Since I need to continuously be checking the status of the device, I reset the counter to 0 once I get the current state.
  if (client.available()) {
    char c = client.read();
    if(c == '|' || counter == 2){
      counter++;
      if(counter == 3){
        counter = 0;
      }
      if(c == '1' || c == '0'){
        Serial.print(c);
      }
    }
  }

You can send json format instead of pipes enclosed and parse the value. Else use regex expression to match ||0|| or ||1|| .


text:
Arduino: incorrect calculation of long integer
I'm doing a simple calculation with integers (on Arduino with ESP8266 12E), but I can't get the expected result and can't find the error. Can someone guide me?
#define A      200
#define B      A * 62
#define C      500

void setup() {
   Serial.begin(9600);
   Serial.println("");

   unsigned long aux = 0;

   aux = (B * 500) / C;    // (12400 * 500) / 500 = 12400
   Serial.printf("aux = %d\n", aux);
   aux = aux * C;          // 12400 * 500 = 6200000
   Serial.printf("aux = %d\n", aux);

   // ERROR: Should result in "500", but is resulting in "1922000"
   aux = aux / B;          // 6200000 / 12400 = 500

   Serial.printf("aux = %d\n", aux); // It's printing "1922000"
}

Fully-parenthesizing macros (as noted in answer by dmz) solves one class of problem.
Another thing you should do is, in any arithmetic expression which involves literal constants, use the L suffix on at least one of the constants involved if there's any chance the result will exceed 32767 (the maximum guaranteed-representable value for int). The type of an arithmetic operation in C is based on the types of the operands of that operation only; the type of the variable to which the result is assigned is irrelevant.
(edit)
For example:
long q, r;
unsigned char v = 231;
unsigned char w = 197;

q = v * w * 5;
r = v * w * 5L;

q might contain 30927, since after the Usual Arithmetic Conversions (6.3.1.8) [in this case, the Integer Promotions (6.3.1.1-2)] all operands are of type int and it's possible for INT_MAX to be 32767 in which case each operation would be performed modulo 32768.
r will contain 227535, since the constant 5L is of type long and thus all operations in this expression will be performed on values of type long.

...and the format specifier for an unsigned long is %lu not %d - the compiler for the asker's esp8266 uses a 32-bit int so they get away with some things they would not on an ATmega-based Arduino where an int is the minimum 16 bit size allowed by the specification.

@mlp usually I use a typecast on almost everything. Example: int J = -1, typecast (unsigned char) J  //prints 255. When you talk about the suffix L, what do you mean? Can you give an example?

As explained in previous answers, fully parenthesizing the macros is the
standard solution to this problem in C. However, on Arduino you are
programming in C++, and in C++ it is considered good practice to replace
this usage of #define by explicit constants:
const int A = 200;
const int B = A * 62;
const int C = 500;

Not only this makes the initial problem go away, it also provides some
type safety: you can choose to give these constants other types (e.g.
long) if appropriate.

Some compilers will interpret "const" as a variable going into program memory which then in turn results in issues with memory spaces.
Consts offer type protection, which can also be (partially) achieved by casting inside the define "#define A ((int)200)" for instance.

@le_top: Do you have a specific example of the kind of “issues with memory spaces” you can get? I doubt you could find an example that does not invoke undefined behavior.

Something along these lines for example:  "const int a=100; int b=200; void setB(const int *c) {b=c;}  void ex1() {setB(&a);}" .  But there are other cases.  When "const" puts "a" in ROM, some embedded compilers can not cope with this kind of assignment and do not report all violating cases.  So I tend to put "CONST" if there is a future risk for this.  (with a "#define CONST const" if possible).

@le_top: I guess you mean b=*c. This sounds like a compiler bug to me. What compiler had issues with this? I tried your code on avr-gcc, and it had no issues, even when I replaced const by __flash const, which has the effect of putting a in flash.

Yes, b=*c.  It will depend on the compiler and the uC.  I file reports when I find bugs - when the compiler does not warn about it it is a bug, but otherwise it is a documented limitation.On Arduino you should use PROGMEM rather than __flash.  I do not want to put a specific compilrer forward, my comment was mainly about warning that there are compilers for embedded systems that interpret const in a way that breaks code compatibility.  That's also why you're required to add "__flash" to get the variable in FLASH - keeping it in RAM eases code generation (and speed) for those processors.


text:
Error handling strings and chars
I'm having an error in buffers that handle strings and I can not figure out what the problem is. The example below shows what is happening. Can someone help me?
void setup() {
   char* ss1 = "";
   char* ss2 = "";
   String txt = "";

   Serial.begin(115200);

   txt = "1234560001a";
   txt.toCharArray(ss1, txt.length());

   Serial.printf("\n\n");
   Serial.printf("ss1 = %s\n", ss1); // It prints "1234560001" whithout last char "a"

   // Force incorrectly "ss1" to be equal to "ss2" and still removes the last character.
   txt = "abcdef";
   txt.toCharArray(ss2, txt.length());

   Serial.printf("ss1 = %s\n", ss1); // It prints "abcde" whithout last char "f"
   Serial.printf("ss2 = %s\n", ss2); // It prints "abcde" too
}

see what happens if you make a change in this line  ... txt.toCharArray(ss1, txt.length()); .... think about it

What kind of change do you mean? There are two problems occurring in the code: 1) the string is removing the last character when copying; 2) The contents of the second variable are overwriting the contents of the first variable.

I understand that you meant that It have problem in length() and that doing length() + 1 works. if string = 'abc', then string.length () should be 3, isn't it? But I insist: So is this an IDE problem? About the second problem, the pointers, why are they overwriting the contents?

strings are null terminated .... the char array must have space for that null

i am not sure about the ss1 and ss2 pointers ..... maybe, because the ss1 and ss2 are created without a size, ss2 points to memory ss1+0

found this ... https://stackoverflow.com/questions/13294067/how-to-convert-string-to-char-array-in-c#13294114

Copy works correctly with these modes of operation, but they are still overwriting the contents of the variables. I can not understand ... Thanks!

Read: https://majenko.co.uk/blog/arrays-pointers-what-c

Great article! But I have not been able to solve the problem that is overwriting the contents of the variables, since the use of the pointers in my example seems to be correct according to your article. Thanks.

toCharArray is alias for getBytes. getBytes is documented as "Copies the String’s characters to the supplied buffer." You did not allocate the memory for the copied characters.
the right use of 'getBytes' and 'toCharArray' is
char buffer[BUFF_SIZE];
str.getBytes(buffer, sizeof[buffer]);

note: getBytes functions sets the terminating zero of the c-string in buffer

About the problem with losing the last character:
As already said in the comments, the toCharArray() method is only an alias for the getBytes() method of string objects. We can see it's implementation in the IDEs folder under hardware/arduino/avr/cores/arduino/WString.cpp:
void String::getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index) const
{
    if (!bufsize || !buf) return;
    if (index >= len) {
        buf[0] = 0;
        return;
    }
    unsigned int n = bufsize - 1;
    if (n > len - index) n = len - index;
    strncpy((char *)buf, buffer + index, n);
    buf[n] = 0;
}

We give the length as parameter, which is then reduced by 1. The function strncpy(), that is used here, will only copy n = bufsize - 1 bytes. In the end, the nth byte will be set to 0 as the terminating null character.
This means, that the length, that we give as parameter, already includes the space for the null character. But the method String::length() will not include the null character in length calculation (in most cases this is not wanted). So you can simply add 1 to the length before giving it to toCharArray().
About the overwriting problem:
As stated in this question's answer and in several other discussions about C/C++ (for example here), string literals are meant to be immutable. The mentioned sources say, it is different, if you define a string variable as
char *str = "test";

or
char str[] = "test";

In the second case a normal mutable array is created. In the first case the string will be placed in read only memory. From your problem I read, that on Arduino this is placed in RAM, thus technically mutable. But the compiler thinks of it as immutable. A common optimization, when dealing with immutable strings, is to let every used string literal with the same content be saved at the same memory address.
In your code you are initializing 2 strings with only the terminating null character in them. The compiler thinks "Oh, wait, these two string literals are immutable and equal, so I can save memory by only saving it once and let both pointers point to this memory address". When writing to the strings in Arduino the behavior doesn't seem to be defined. As the Arduino cannot throw an exception it will most likely do the write. Since both pointers are pointing to the same memory address, they show both the same content. Also, when writing a string longer than the initialized value, memory space outside from the original string will be written. If other variables are saved there, they will get overwritten. This is the reason, by you should always explicitely allocate the memory (static or dynamic) for a string, until another function does it for you. When using a dynamic allocation of memory, you should also consider heap fragmentation, which can easily lead to strange behavior.
If you turn on verbose output for compilation, the compiler also warns you, that you try to convert a constant string literal to a non-constant char pointer:
sketch_jul09a.ino:3:15: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

To conclude, you should not declare string variables like this. If you have a variable string buffer with initialized values, you should use
char str[]="test";

If you want to define a constant string, use the keyword const:
const char *str = "test";

Then writing to it will result in a compiler error, so that you sense, if you are doing this.

Thank you for your tips. I have not yet solved the second problem either, but I'm using a palliative solution (even against my own will, for lack of a better option). I'm using a fixed length buffer and copying the string with getBytes as pointed out by @Juraj. Thanks.


text:
Possible way to interface a TFT touch panel with Arduino
I have a salvaged 40-pin TFT touch panel, and I am trying to see if I can control it with an Arduino. What are my chances of getting a driver for it ? I bought a RA8875 Driver Board from Adafruit, but the pin layout did not match.
Any suggestions are appreciated. Thank you

You could see under the cover of the PCB and try to identify the part number of the controller. If its a standard one you might be able to find information about it. Though if this was from consumer hardware this is  not very likely. These parts often have custom chips or the labels on the chips is removed. And with an Uno you won't have much luck driving this. I guess the connections on the ribbon cable are all needed to drive it. The Uno most likely doesn't have enough pins for that.

I don't think the panel has a driver, that is the reason why I am looking for one.

Then I would ask what is on that PCB? But the result is the same. You need to find out what function each pin has. For that you can only look at the PCB. Reverse engineering is a very complex task. We cannot really help with that.


text:
Keyboard commands not working?
So I've been trying to use Mouse.move();
and Keyboard.press();. Every time I try to send it to my Arduino(mega 2560) it says keyboard or mouse was not declared. Any solutions?
  #include <Keyboard.h>
void setup() {

  pinMode(2, INPUT);

}

void loop() {

  if (digitalRead(2) == HIGH) {
    Keyboard.begin();
    Keyboard.press(KEY_LEFT_ARROW);
  }
if(digitalRead(2)==LOW){
  Keyboard.end();

}

}

Yes, don't use a Mega2560. Instead use one of the boards the Keyboard and Mouse libraries are designed to work with. I.e., one that actually has a USB connection...!


text:
Serial communication with 2 Arduinos and one optocoupler
I just started working with Arduinos on Tinkercad in a school assignment and have non preexisting electrical knowledge. Tried to read up on the subject and I think I've gotten some of the facts straight but i still can't get them to communicate when using the optocoupler. It works fine with the code if i connect them to each other directly with the tx/rx pins.
//Sender code
char string[5] = {'h', 'e', 'l', 'l', 'o'};
void setup()
{
  Serial.begin(9600);
}
void loop()
{
  Serial.write(string,5);
  delay(1000);
}

//Reciving arduino code

char text[10];

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

void loop()
{
  Serial.readBytes(text,5);
  Serial.println(text);
  delay(1000);
}

My guess is I've done something wrong connecting the receiving Arduino but i can't find whats wrong. Any feedback is immensely appreciated!

How about the schematic? You could invert the signal, or it's connected in a way that even 9600 bauds/s are too fast for it

Try this as you have a logic inversion. If the Arduino is connected to the cathode, connect it to the anode or visa versa. This will cause a double logic inversion and get the signals back to working.

EDIT: Even though the OP may be long gone, I wanted to finish what I started with my response.

This circuit works fine for me using two UNOs (and one UNO and a serial board for a PC). It is, essentially, the same as in the first response by @hcheung. I used 4.7K and 10K for R2/R4 and they worked fine. I tested it using this program running on both UNOs.
    #include <SoftwareSerial.h>

SoftwareSerial SSerial(4,5); // RX, TX

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

}

void loop() {
  // display whatever comes in through software serial on the Arduino monitor
  if(SSerial.available()) {
    Serial.write(SSerial.read());
  }
  // send whatever comes in on serial to software serial
  if(Serial.available()) {
    SSerial.write(Serial.read());
  }
}

Note that the programs use software serial and both Tx and Rx are isolated.
If you use this for the hardware serial port on two UNOs, take care. First, don't hang things on 0/1 until after the program loads and how much you can get away with is unclear to me.
Second, if you use a simple program like this, on both UNOs, you will quickly see that the first bytes sent will ping-pong and causes problems.
    void setup() {
  Serial.begin(9600);
}

void loop() {
  if(Serial.available()){
    Serial.write(Serial.read());
  }
}

I note that the OP was only using one end.
Personally, I found several junk box 4N25s that would not work - that took me a bit of time to figure out. Finally, I don't see the point of optically isolating two UNOs as I did for example, but that is another story.
______ older msg is below _______________________________
A typical way of doing this is illustrated here .

// *** I am leaving my original text below, but I want to back off of this a bit. I spent a few hours on this today and I am not happy with the results or my understanding. If I come to any worthwhile conclusions, I will post them. I do like getting to the bottom of things, but I was premature. It is simply not working the way I would expect when I get into 9600 speed and I need to investigate further. Yes, I am accounting for the UNO 0&1 involvement with USB.
// ***
The advantage is that you will not be inverting the line on the receiving end. The choice of R1 and R2 is important. I used R1=330 and R2=1K and transmission was fine at 9600 using a junk box 4N25. My testing was with a single UNO and after uploading a simple program.
See https://github.com/pepaslabs/Electronics/wiki/Designing-a-TTL-Serial-Opto-isolator for a good discussion on exactly this topic.
PS: As mentioned you should have submitted a schematic and you could have used a meter to see what voltages you were getting - those are good steps to understanding things.

You connected Uno2 RX connecting to GND in your diagram.

@hcheung Yes, thanks - very sloppy of me - corrected

Here is a diagram that I would suggest you to to try it out. The transmitting Arduino pin will turn the internal infrared LED on or off depend on the whether the pin is at LOW or HIGH. When the infrared LED is on, it will turn on the phototransistor, and produce a LOW at the receiving arduino pin.
The LED is optional but it gives you a visual clue on whether you are receiving the data or not.

simulate this circuit – Schematic created using CircuitLab


text:
reading strings from multiple Arduinos
So I have 5 Nanos all trying to crack a password, the idea is each one has one fifth of the list so they can test 5 at a time, then when it is found, I want it to be displayed on a screen I have, the idea is to connect them all to a hub which would be the arduino uno, the Uno would then take the char was sent, and send it to the screen, it does not know which Arduino will send the char and the idea is to use serial.write but I am open to other options. What is the best way to go about accomplishing this task, is there some way I can have it reading the serial from all 5 Nanos, and can this be done without it being plugged into a computer?

I'm curious. For what purpose are you trying to build a password cracker based on Arduino? And why do you need to cluster them? Have you already tried with one Nano and it took to long? That is not a common thing to do with an Arduino

tbh I don't have a reason, I just had a bunch of nanos lying around, i was planning on using raspberry Pis for it originally but I realized I already had a bunch of nanos lying around. idk where the cluster idea came from, but really the project is mainly about the cluster, I wanted to see if I could achieve something like this. the cluster idea is just to speed things up, having more arduinos just increases the amount that can be tried drastically, Im just trying to get back into arduino after about a year

It's probably more straight forward if you use a multi-slave bus, like I2C, SPI, ...

I'd probably use RS485 or Ethernet for something like this (though ethernet is probably overkill for this application).

in your case you can simply wire all the serial pins together, nothing fancy or special. btw, a desktop can check more passwords in a second than a nano would in a day.

Presumably you will avoid having two Nanos try the same item from the
list. Then, only one Nano can find the answer, and only one will try to
transmit data at any given time. In such a situation, yes, you could
connect all five Nanos to the same serial link:

Connect the Uno's TX directly to the RX each Nano. They will all
receive the data transmitted by the Uno.
Connect the Uno's RX to the TX of each Nano through this circuit:

simulate this circuit – Schematic created using CircuitLab
As long as at most one Nano tries to Serial.print() (or
Serial.write()) at any given time, the Uno will receive the data just
fine, although it will not be able to tell which of the Nanos sent it.


text:
Send batch info to com port?
I'm trying yo get a .bat file to send my cpu data to the com port my arduino is on. I've tried multiple google results (including one from this site) and everything I found will just... erase all the variable tied to the com port. The arduino is hooked up to an lcd (not really because arduino microview, but basically that) which displays the variables I want and works as expected when I put the data into the serial monitor manually, but when I run anything that's supposed to send the info they all go blank when I have nothing in my sketch that clears them.
The file is getting the data how it should. If I run this
wmic /namespace:\\root\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature
then I get the temperature as normal. But If I try to send that to the com port...
wmic /namespace:\\root\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature > COM3
The arduino reads whatever it's getting as literally nothing and blanks the variables.

download and install com0com from https://sourceforge.net/projects/com0com/ ... that will create two linked virtual serial ports ... connect a serial monitor, such as PuTTy, or arduino IDE console to one port ... send the WMIC output to the other port ... see what is being sent from WMIC

what is your specific question? ... you have not provided any information that could be used to debug the problem

The problem is that the batch file sends literally nothing (to the point where the arduino sets its variables to nothing, not even "0", just nothing) the moment I run the .bat file, even though when I just request the info normally it gives me the correct value.

(@jsotola see above, forgot to reply)

The Arduino may be resetting itself each time you open the serial port.

The variables cannot be blanked. They always have a value. Do you know what exactly the wmic command sends in what format? This sounds like your Arduino code expects one format (like ASCII formatted text in a specific form) but the command sends in a different format. You need to make sure that the wmic command is sending exactly what you expect from it.

As Edgar has noted in the comments the Arduino resets every time you open the serial port.
Every time you perform a redirect the serial port is opened afresh, which resets the Arduino into the bootloader. There is then a brief delay while the bootloader looks for suitable communication for uploading new code, and then your existing program gets started afresh.
Coupled with that is the problem of baud rate: you need to ensure that the serial port is configured for the same baud rate as your program is expecting.
All together that means that a simple redirect like you are using is really not the best way of communicating with an Arduino. Instead you will need to write a proper program that opens the serial port, waits for the Arduino to reset, then starts periodically probing for and sending the information that you need it to.
Python and PySerial is a common choice for beginners as is easy to get started with and has plenty of examples.


text:
Arduino Wire communication with MCP23008 GPIO pin expander to turn on an LED with a button press
I am using an Arduino Uno and an MCP23008 GPIO pin expander, I have a momentary button connected to GPIO 2 on the MCP23008 and an LED light connected to GPIO 1 on the MCP23008. What I want is for the LED to turn on when the button is pressed down, and off otherwise. The code I currently have is this:
   #include "Wire.h"       //import Wire library
   byte inVal;             //declare byte variable

   void setup() {

      Serial.begin(9600);
      Wire.begin();
      Wire.beginTransmission(0x20);   //MCP23008 i2c addr
      Wire.write(0x00);               //MCP23008 internal register addr for I.O.dir
      Wire.write(00000010);           //set all pins as output, except for #2 as input
      Wire.endTransmission();
    }

    void loop() {

      Wire.begin();
      Wire.beginTransmission(0x20);   //MCP23008 i2c addr
      Wire.write(0x09);               //MCP23008 internal register addr for GPIO access
      //Wire.write(0xFF);             //set all output pins to HIGH, commented out for now.
      Wire.endTransmission();
      Wire.requestFrom(0x20,1);       //get one byte of input input from MCP23008
      inVal=Wire.read();              //set pyte as variable

      //Serial.println(inVal,BIN);    //output byte to serial monitor, commented out for now

      Serial.println(bitRead(inVal, 1)); //output second bit from byte(1 or 0, for HIGH or LOW, depending on the press of the momentary button.
      if((bitRead(inVal, 1)==1))      //if the bit from the button is high,
      {
        Wire.beginTransmission(0x20);
        Wire.write(0x09);
        Wire.write(0xFF);             //then set all output pins as HIGH
        Wire.endTransmission();
      }

      else if((bitRead(inVal, 1)==0))  //if the bit from the button is low,
      {
        Wire.beginTransmission(0x20);
        Wire.write(0x09);
        Wire.write(0x00);             //then set all output pins as LOW
        Wire.endTransmission();
      }
    }

I don't know as much Arduino as I do Python, and I have even less experience with i2c connections and the Wire library, but this looks to me like it should be working.
The bit printed on the serial monitor is HIGH, until I press the button once, then it stays LOW forever until I modify and re-upload the code to the Arduino.
Not sure what's going wrong here. Anything helps, thanks.

I see one major thing wrong at first glance:
  Wire.write(00000010);           //set all pins as output, except for #2 as input

That doesn't set GPIO 1 (which you call number 2 - counting starts at 0 not 1) to be an input, that sets GPIO 3 (number 4) as an input.  Numbers starting with 0 are octal, not binary. For binary the prefix is 0b:
  Wire.write(0b00000010);           //set all pins as output, except for #2 as input

And then you read using:
bitRead(inVal, 1)

which would have read GPIO 1 which is configured as an output.
So you have a switch on GPIO 1 which is an output, which you then drive high (causing a short internally which can damage the pin), and as a result you drive the pin HIGH internally. Now it's always high, so a read of the pin sees the HIGH you are driving from it. Hence it gets stuck at 1.
Fixing your IODIR write should help solve that problem.

I changed the IODir to Binary, but it still isn't working, and in the same way. (At one point,  the led started blinking every second, I don't know why, and I have been unable to replicate this. What I want is to get high/low input from pin 1, if it is high, set pin 0 out as high, if it is low, set pin 0 out low. Been stuck on this for weeks now, and I don't get why. What am I missing? Thanks.


text:
Honeywell HPMA115S0, sensor not start again after stop
I use HPMA115S0 sensor with Arduino for Nodemcu, i can read it value but face one problem. The sensor not work after send stop measure command (fan not start too).
const int StartPmMeasure[4] = {0x68, 0x01, 0x01, 0x96};
const int StopPmMeasure[4] =  {0x68, 0x01, 0x02, 0x95};
...
void stopSensor() {
  if (isSensorStart) {
   Serial.println("INFO: Stop sensor");
   sendCommand(AutoSendOff);
   sendCommand(StopPmMeasure);
   isSensorStart = false;
 }
}

void startSensor() {
 if (!isSensorStart) {
  Serial.println("INFO: Start sensor");
  sendCommand(StartPmMeasure);
  sendCommand(AutoSendOn);
  isSensorStart = true;
 }
}

what do you do then? do you have to replace the sensor?

I have the same problem here. I'm using a HPMA115S0 with an ESP8266 and found out that the sensor don't respond in general if you are doing a deep sleep with the ESP. If the ESP wakes up, the sensor does not respond on commands till you remove the 5 volts of the HPMA for a short time to make an "hard reset" of the sensor.
I think there is a problem with the ttl-level on the UART-RX-line of the HPMA. Because if you're pulling the rx-line of the sensor manually to ground (maby the ESP is doing this if he goes to deep sleep or wakes up), the sensor does not respond after that.
I spend very much time in this phenomenon. I used different pins on the ESP for software UART and used the hardware UART, problem still exists.
I assume that the ESP pulls all his pins on ground level for too long. That means that the stop bit (high-level), which the sensor wants after 8 bits are transmitted, is not present. This leads to strange behavior of the sensor.
I don't have a digital storage scope to see the level on rx-line, so this is only a presumption. But I don't have this problem, if the ESP idles with an sleep-command.
Maby you are also doing a deepsleep with your ESP which results in the same problem?
Best regards

Yes, that is my same setup, it can not work after send stop measure command. If you make esp deep sleep and not send stop command it still work with "continuous mode". Honeywell support service is very bad too, they ignore my email.  I end this buy use other sensor and find that this sensor HPMA115S0 very inaccurate, it give random result in 1 minute in stable environment. So Plantower PMS7003/PMS5003 is the solution and it is very accurate, stable and cheaper than Honeywell one.

Exactly.If you let the sensor push his measured results (autosend enable=default) you could let the ESP8266 sleep. But the problem in this case is the higher power consumption of the sensor which is not a solution for me, because this device should be battery powered. Thanks for the tip of the Plantower sensor! This sensor also has an reset pin to reset the sensor if something goes wrong.


text:
Nodemcu connecting to Wi-Fi Problem
I am trying to connect to Wi-Fi with Digital pin declaration in setup() function it's not connecting to wi-fi. But connecting to wi-fi without digital pin diclaration. `
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
int m1 = 5;
int m2 = 6;
const char* ssid = "KS Infotech";
const char* password = "kalamsalam";
String readc = "";
void setup () {
pinMode(m1, OUTPUT);
digitalWrite(m1, LOW);
pinMode(m2, OUTPUT);
digitalWrite(m2, LOW);
Serial.begin(9600);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {

delay(1000);
Serial.print("Connecting..");

}

}

void loop() {
while (Serial.available()){  //Check if there is an available byte to read
delay(10); //Delay added to make thing stable
char c = Serial.read();
String T = String(readc);
    Serial.println(T);
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

HTTPClient http;  //Declare an object of class HTTPClient

http.begin("http://ksinfotech.co/kslab/write_to_database.php?incoming="+T+"&UID=surya");  //Specify request destination
int httpCode = http.GET();

if (httpCode > 0) { //Check the returning code

  String payload = http.getString();   //Get the request response payload
  Serial.println(payload);                     //Print the response payload
  if (payload == 'N');
  {
  digitalWrite(m1, HIGH);
  digitalWrite(m2, LOW);
  delay(2000);
  digitalWrite(m1, LOW);
  digitalWrite(m1, LOW);
}
      if (payload == 'F');
  {
  digitalWrite(m1, LOW);
  digitalWrite(m2, HIGH);
  delay(2000);
  digitalWrite(m1, LOW);
  digitalWrite(m1, LOW);
}

http.end();   //Close connection

}

delay(30000);    //Send a request every 30 seconds

}

The above code not working but the below code working.
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "KS Infotech";
const char* password = "kalamsalam";
String readc = "";
void setup () {

Serial.begin(9600);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {

delay(1000);
Serial.print("Connecting..");

}

}

void loop() {
while (Serial.available()){  //Check if there is an available byte to read
delay(10); //Delay added to make thing stable
char c = Serial.read();
if (c == '#'){
  break;                   //Stop the loop once # is detected after a word
}//Conduct a serial read
readc += c; //build the string- "forward", "reverse", "left" and "right"
}
String T = String(readc);
    Serial.println(T);
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

HTTPClient http;  //Declare an object of class HTTPClient

http.begin("http://ksinfotech.co/kslab/write_to_database.php?incoming="+T+"&UID=surya");  //Specify request destination
int httpCode = http.GET();
 //Send the request

if (httpCode > 0) { //Check the returning code

  String payload = http.getString();   //Get the request response payload
  Serial.println(payload);                     //Print the response payload

}

http.end();   //Close connection

}

delay(30000);    //Send a request every 30 seconds

}

Pins 5 and 6 are not what you think they are. 5 != D5 6 != D6

posted on arduino forum http://forum.arduino.cc/index.php?topic=527272

Thanks for your answers and suggestions. My problem solved.

use D5 and D6, not 5 and 6. D5 is IO 14, D6 is IO 12. IO 5 is D1 and IO 6 is SDIO_CLK for the flash memory and that is your problem.
the reference

I think GPIO06 is connected to flash and that's why it fails.

yes. I edited the answer. it is is SDIO_CLK for the flash memory

but pin5 is the best pin on board, tied with pin4...

then please mark the answer as accepted


text:
My ESP32 WROOM clone will not register touch sensor when using a 5v power bank with usb cable
I have a very simple touch sensor program that works fine and lights an led to show the sensor works; while hooked up to the computer via usb cable it works fine.  When using a power bank with the same usb cable the board lights up but does not read the touch sensor.  I have tried other cables with the same result.

what is your specific question?

What is your schematic? What is this "touch sensor" of which you speak?

My specific question is about the esp32 touch sensors which are built in touch sensors on the esp32.  Is this normal behavior when trying to use a 5 volt external supply with a usb cable? Has anyone experienced this problem when using the touch sensors? I don't know how to upload the code or a schematic.

Perhaps this is the wrong forum to ask this question.  I use the Arduino ide to program my esp32 as well as some Arduino boards.

@JerryG1112 This is the right forum, but I suspect you are looking at the wrong problem.  "Everything" works fine when the board is powered by the PC, but your touch sensor doesn't work (but the board does?) when running off the battery pack.
So whats the difference?  Whats the output of your battery pack (Volts and Amps)?  My first though was there wasn't enough juice.
A drawing/photo would help, because I'm wondering if you have the touch sensor connected directly to the power supply somehow.  Like wise details of the touch sensor will help, because not all touch sensor are equal :)

@JerryG1112 - Can you run blink on your board on the battery pack?

touch doesn't work as well with battery-powered things or things that are outside. for a motorcycle, consider a cheap microwave radar motion detector module.

I have considered and tried the other types of motion detectors [motion pir, radar, sound, }but they have too many false alarms. i am only trying to prevent gasoline theft.  My last resort will be laser alarm but it is so difficult to setup. Yes blink works.  Gil has provided the path to a solution, but i have yet to complete it.  My current problem is using a larger cap sensor than a wire because I cannot differentiate the touch/no touch states with even a kitchen pot or pan.

This is hard to explain but your problem in not unique. I hope this helps. It is your ground reference. When connected to the computer which is grounded either/or a ground wire or capacitive coupling to earth. Your body is capacitively connected to ground that way and when you touch the switch it is recognized.  To make it work with the battery pack you need to couple to the person touching it. You can do that capacitively by adding a ground plain to your circuit. This can be a conductive plate that will capacitively couple the ground to the atmosphere or any other practical means.

I am using Touch0  which is on GPIO 4.  The led is on  GPIO22 as digital output pin.  I uploaded a blink sketch and it does work on the battery.  The board powers onbaord led under battery power but will not respond to a touch, so I think Gil has the right solution.  i just don't know how to make a conductive plate. Perhaps if I connect the touch wire to my motorcycle it will work as I intend.  (a burglar alarm)

Anything conductive would work. If you power it from the motorcycle the ground plane becomes the frame no other connections needed unless the electrical system is isolated but I doubt it.

I will try that solution tomorrow.  Thank you for the help.


text:
How do I fix my code so that it reads text from the serial monitor?
I have created a code that should print out "Enter true to deactivate alarm" in the serial monitor, then store the user's answer and print "alarm off" if they enter true and "alarm on" otherwise. However, it is returning "alarm on" every time, even if I enter true. Here is my code:
String deactivate = "";
void setup() {
  Serial.println("Enter \"true\" to deactivate alarm");
}
void loop() {
  while (Serial.available() == 0){}
  deactivate = Serial.readString();
  if (deactivate.equals("true"))
  {
    Serial.println("alarm off");
  }
  else
  {
    Serial.println("alarm on");
  }
}

Any help here would be greatly appreciated, I'm new to Arduino and we've been stuck on this step for weeks; I am just really at a loss trying to figure out why it isn't working.

Often is the case coders will add "debugging" print statements to aid in understanding what is occurring in their code.  Printing out what you received may help in understanding unexpected results.
That said, consider using Serial.readStringUntil() in place of Serial.readString().  From the linked to page:

Returns
The entire String read from the serial buffer, up to the terminator
character

You didn't set the Serial port:
Serial.begin(9600);

Add this in the setup function.
Also check in your serial monitor if the speeds are equal.
If this still doesn't work, print the deactivate variable after assigning, and its length, and every character to see if it adds a newline character or any other unexpected character.
Then if it is a whitespace character, use a function to strip the whitespace, or change the comparison.