text:
Unable to upload to ESP32 LOLIN D32 board
I'm not able to upload a sketch to this board with the Arduino IDE. This is the error during upload:
Arduino: 1.8.5 (Windows 10), Board: "WEMOS LOLIN32, 80MHz, Default, 512000

Build options changed, rebuilding all
Archiving built core (caching) in: C:\Users\Karanbir\AppData\Local\Temp\arduino_cache_223140\core\core_espressif_esp32_lolin32_FlashFreq_80,PartitionScheme_default,UploadSpeed_512000_6da8d55d0c53c0ebef21ae478b9e06ba.a
Sketch uses 178072 bytes (13%) of program storage space. Maximum is 1310720 bytes.
Global variables use 13880 bytes (4%) of dynamic memory, leaving 313800 bytes for local variables. Maximum is 327680 bytes.
C:\Users\Karanbir\Documents\Arduino\hardware\espressif\esp32/tools/esptool/esptool.exe --chip esp32 --port COM3 --baud 512000 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq 80m --flash_size detect 0xe000 C:\Users\Karanbir\Documents\Arduino\hardware\espressif\esp32/tools/partitions/boot_app0.bin 0x1000 C:\Users\Karanbir\Documents\Arduino\hardware\espressif\esp32/tools/sdk/bin/bootloader_dio_80m.bin 0x10000 C:\Users\Karanbir\AppData\Local\Temp\arduino_build_547051/Test.ino.bin 0x8000 C:\Users\Karanbir\AppData\Local\Temp\arduino_build_547051/Test.ino.partitions.bin
esptool.py v2.3.1
Traceback (most recent call last):
  File "esptool.py", line 2637, in <module>
  File "esptool.py", line 2630, in _main
  File "esptool.py", line 2355, in main
  File "esptool.py", line 193, in __init__
  File "site-packages\serial\__init__.py", line 88, in serial_for_url
  File "site-packages\serial\serialwin32.py", line 62, in open
serial.serialutil.SerialException: could not open port 'COM3': WindowsError(5, 'Access is denied.')
Failed to execute script esptool
the selected serial port Failed to execute script esptool
 does not exist or your board is not connected

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

This is displayed on the Arduino IDE's Serial Monitor on pressing the reboot button on the board:
ets Jun  8 2016 00:22:57

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0018,len:4
load:0x3fff001c,len:4436
load:0x40078000,len:0
load:0x40078000,len:11816
entry 0x4007a9fc
[0;32mI (358) cpu_start: Pro cpu up.[0m
[0;32mI (358) cpu_start: Single core mode[0m
[0;32mI (359) heap_init: Initializing. RAM available for dynamic allocation:[0m
[0;32mI (362) heap_init: At 3FFAE6E0 len 00001920 (6 KiB): DRAM[0m
[0;32mI (368) heap_init: At 3FFC4E70 len 0001B190 (108 KiB): DRAM[0m
[0;32mI (374) heap_init: At 3FFE0440 len 00003BC0 (14 KiB): D/IRAM[0m
[0;32mI (380) heap_init: At 3FFE4350 len 0001BCB0 (111 KiB): D/IRAM[0m
[0;32mI (387) heap_init: At 4008DE34 len 000121CC (72 KiB): IRAM[0m
[0;32mI (393) cpu_start: Pro cpu start user code[0m
[0;32mI (187) cpu_start: Starting scheduler on PRO CPU.[0m
OSError: [Errno 2] ENOENT
MicroPython v1.9.3-564-g9254f365 on 2018-04-26; ESP32 module with ESP32
Type "help()" for more information.
>>>

What can be wrong or needs correction?

you might have to connect gpio0 to gnd to flash it, many boards don't have that automated like most of the nodemcus

I will try this and update.

I had the same problems with a USB cable of a length at 30cm
I took an other (10cm) and reduced the upload speed to 512000.
now it works


text:
What happens when I exceed amp limit on Arduino 5v pin?
I'm using an Arduino Uno to power some rgb LEDs.
Each LED takes 20mA (on average).
I have a strand of 400 LEDs.
This should be drawing ~8,000mA.
Arduino Uno has a limit on its 5v pin of 500mA.
**So how many amps is my Arduino outputting? My 8A worth of LEDs are illuminated, just dimly.
Edit:
My Arduino still runs, and the 8,000mA LEDs illuminate, just dimly. I’ve left the setup on for 12 hours, and it all still works.
So it appears the behavior of the Arduino Uno is to limit the amp output of its 5v pin. It does not burn out.
Any explanations for this observed behavior?
Edit 2:
I know how to wire up this setup correctly using power injection. I’m just curious why my Arduino is not burning out as we all expect it to.

You can always make Arduino to control a power MOSFET (or a relay module) that's rated for more that 8A. That way Arduino gives out only several milliamperes.

If the 5V source is the barrel jack, (like from a 7.5V or 9V source), than you may be able to get up to 800mA to 1A from the 5V pin. There is a reverse polarity diode that is rated for 1A. The 5V regulator is only rated for 800mA. It does not have good heatsinking, and will overheat and shut before you see 800mA tho.
USB, well, you may get 500mA from that, if the source doesn't shut down first. If it doesn't, then the 500mA inline fuse should open.
You really need a seperate source for 5V for power to the strands.  Be sure to connect the Gnd from the source to the Arduino Gnd.
What kind of RGB LEDs are you using? WS2812B type LEDs?

If you exceed the amp limit, that can be drawn through (!) the Arduino, some components on the Arduino will be fried (As for most electronic devices. For the Arduino this is practically a short). There is no current limitation there. Which components are fried depends on how you provide the power. If you provide power through the power jack or VIN, the voltage regulator will burn out. If you provide power through USB a diode or the MOSFET will be fried (You can look this up in the Arduino UNOs schematic at this site).
The setup might output a current, that is a bit higher than 500mA, for a short time. But the mentioned components, that are in the currents path, will heat up very quickly and be destroyed. In this short time the LEDs will be very dim, since the Arduino cannot provide a current as big as 8A, not even for a short time.
All great loads have to be powered separately from the Arduino, so that their supply current will not flow through the Arduino. If you are using a powerful USB supply, you have to split the power lines, before giving the voltage to the Arduino. You can connect the USBs 5V pin to the 5V pin of the Arduino and to the LEDs. If you are using a power supply with a higher voltage than possible for your LEDs, you have to buy an extra regulator, that also capable of providing the needed current.
Important note: Since you didn't specify, how you are connecting the RGB LEDs, you also have to take care about the current limit of a single pin. It should not exceed 20mA, 40mA at the absolute maximum. So you cannot drive the LEDs directly. You will need a driver for then anyway. The simplest way is a MOSFET, that is capable of sourcing the corresponding current. It is then controlled by the Arduino, which needs very little current for it.

I thought this too - but I’m drawing far beyond the 5v pins limit, and nothing is fried. The Arduino still works fine after a 12 hour run with an 8A draw.

source: Stack Exchange

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

sort: votes


text:
Help in "An error occurred while uploading the sketch"
Trying to test THIS. Got following error:
esptool v0.4.13 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to nodemcu
    setting baudrate from 115200 to 9600
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
Uploading 356000 bytes from C:\Users\PRAMIT~1\AppData\Local\Temp\arduino_build_521093/testPersWiFiManager.ino.bin to flash at 0x00000000
    erasing flash
    size: 056ea0 address: 000000
    first_sector_index: 0
    total_sector_count: 87
    head_sector_count: 16
    adjusted_sector_count: 71
    erase_size: 047000
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    setting serial port timeouts to 15000 ms
    setting serial port timeouts to 1000 ms
    espcomm_send_command: receiving 2 bytes of data
    writing flash
................................................................................ [ 22% ]
................................................................................ [ 45% ]
................................................................................ [ 68% ]
.......................An error occurred while uploading the sketch

All libraries are included, no compile error.
Steps followed:
1st uploaded the data using Tools>ESP8266 Sketch data upload.
Then Sketch>upload
After failing this, I tried a basic example similar to THIS. This uploaded successfully. The same configuration is used for both scenarios.
What am I missing? I am getting no clue.
Settings:

Any change in Erase Flash settings?

the data upload was successful? try 115200 baud or more for upload

@Juraj, you are right, I updated the baud rate to 115200 and it worked. However, I first tried to change it in the code, but not helped.

upload speed for flashing has nothing to do with the value in sketch.

The upload to esp8266 with esptool used in IDE doesn't work good on slow baudrate. It fails for larger sketches. You can upload to NodeMcu at 921600 baud.

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


text:
Accidentally shorted 5V to GND on Arduino Nano, can I reuse the ATmega328p?
I've shorted 5V to GND and the Arduino Nano (CH340 clone) stopped working (power LED light is dimming). The board had a burning smell, and I also checked if other Arduini on the same USB port worked and they did, so I'm quite sure the Arduino is dead.
After the incident, I de-soldered the TQFP Atmega328p (plus the crystal) to reuse. I'm thinking that if it's only the external circuitry that's damaged, then the chip should be OK. Can I reuse the chip if I solder onto a new board? What components could have been damaged?

It always depends where you created the short circuit. If it was the VCC and GND pin of the ATmega, then you fried everything else but the MCU.

The short circuit was near a class D amplifier which I had misplaced on a breadboard. The amplifier and other components survived, only the arduino stopped working.

Can you show the schematics?

I don't have the schematics for this, I was just testing a few things. It's was a simple circuit though, just a mp3 player module, some LEDs and the PAM8403 amp.

Just draw a picture, how you wired up all the things.

The wiring was fine, I've done the same many times. I just put the amp module in the wrong position and realised the 5V and G input to the module were in the same row, it stayed like that for about 30 seconds until I realised.

If you shorted VCC with Ground and not Pin with Ground it's possible that just the voltage regulator let out the magic smoke. Did you power the Arduino via USB?

Yes, it was powered by USB.

I think the USB connection doesn't use the voltage regulator. I think the easiest for you would be to connect the Nano to USB, take multimeter and check voltage on the Atmega328p pads. If the VCC and GND have 5V they you have 100% certainty that the power circuit works, and MCU is fried. Use datasheet to check pinout http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf

I just did that without the atmega328p (because I already de-soldered it), it's giving me 3V between the 5v pin and Gnd pin...and the LED power led flashes weakly, dimming. So the power circuit is broken.

This means that there is a chance that power circuit failing prevented MCU from burning up. It's impossible to verify that without extensive tests of the ATmega. It's also possible that there is "some" damage that will decrease its lifespan. It's a 50cent part. IMHO it's easier/safer to get a new one.

Great, it's good to know that, thanks Filip. I will keep the MCU in a drawer anyway as spare, but separated from the new ones then.

Think about preparing yourself an overcurrent protection circuit to put between Arduino and breadboard when you prototype.

That is a good suggestion, I will check what I can do for this. Thanks.

is it worth your time to spend hours fixing a part you can replace for $2us?

Try checking the pcb and components for damage. The only thing I can think of that could get damaged in the situation you described would be a PCB trace that’s blown up.

I just had the exact same problem (shorting 5V and ground - not even for long) on two nano clones, and strangely but consistently, both nano's still seemed to work. However, I wasn't able to flash them through USB anymore. Flashing them through ISP still worked, though.

On a Arduino Nano, there is a diode that prevents an external 5V source from back feeding into the USB source. If your clone equivalent has that as well, I suspect that is the part that got fried.


text:
NodeMCU v1.0 high power consumption in deepsleep
I am using a NodeMCU v.1.0 ESP-12 for a small project. It is powered by 3xAA batteries (4.5v) in Vin, but to reduce power consumption I need to put in in deepsleep every now and then.
Running this small sketch:
void setup() {
  Serial.begin(115200);
  Serial.setTimeout(2000);

  // Wait for serial to initialize.
  while(!Serial) { }

  Serial.println("I'm awake.");

  Serial.println("Going into deep sleep for 20 seconds");
  ESP.deepSleep(20e6); // 20e6 is 20 seconds
}

void loop() {
}

I have measured a consumption of 8mA when it goes to deepsleep, and this is not acceptable for my purpose. In order to wake up from sleep I have connected pin GPIO16 (D0) to RST, and it works. I knew that NodeMCU should have only few µA of consumption in deepsleep. How can I fix this?

Have you tried to remove the LED?

Which one? The board has just a tiny blu LED which flashes for a moment when you switch it on, then it turns off. No LEDs are on during operations.

Sorry forget the LED! Look at the LDO,  look at this https://electronics.stackexchange.com/questions/286249/replace-ams1117-5v-3-3v-ldo-on-nodemcu-for-lipo-with-low-quiescent-current

I will read that link, thanks. But I have also made a test powering it directly on the 3V3 pin by an external regulator and the results are the same.

I have read the article. So, you suggest me to remove the internal LDO and use an external MPC1700? I am not a soldering-meister, so I am afraid I will break the device...

how much is used by the usb serial that you don't need after flashing?

The usb serial is not used, after flashing. But I always have the opportunity to update the sketch!

The usb to serial still uses power, even when it isnt used.

Yes, I have replaced an LDO in a similar exercise with an Arduino UNO.

Consider the TI TPL5110 timer chip with power control MOSFET. Set the timer period with a resistor then the TPL5110 powers on the NodeMCU periodically. Deep sleep is not used. RTC RAM will be lost so use SPIFFS for persistent data.
Adafruit has a breakout board. Take a look in Adafruit's forum for user comments because it has a few limitations.

You worried me about your warning "look at comments..", but I can't find anything serious...


text:
NRF24L01+ - After stopListening, can't write data
Okay so this is the code for my receiver.
This is quite confusing so let's dub Receiver = DEVICE 1 and Transmitter = DEVICE 2
DEVICE 1: NRF24L01+, HC-05 (Bluetooth)
DEVICE 2: NRF24L01+
So DEVICE 1 will receive data from DEVICE 2. Also When it receives data from my phone that is connected to the HC-05 module, it will radio.StopListening and radio.write.
But for some reason, after i do radio.StopListening, radio.write doesnt work.
Currently, DEVICE 2 has a very simple code to receive data being sent from DEVICE 1. I've done this just to check if there's any data being sent when DEVICE 1's HC-05 module receives data.
Code:

#include "Arduino.h"
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>

RF24 radio(9, 8);

byte addresses[][6] = {"1Node","2Node"};

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setPALevel(RF24_PA_MIN);
  radio.setDataRate(RF24_2MBPS);
  radio.setChannel(124);

  // Open a writing and reading pipe on each radio, with opposite addresses
  radio.openWritingPipe(addresses[0]);
  radio.openReadingPipe(1, addresses[1]);
}

void loop() {
  unsigned char rf_data; //Make a variable to store the data
  unsigned char bt_data;
  unsigned char tosend;
  radio.startListening();

  if (radio.available()){
    while (radio.available()){
      radio.read(&rf_data, sizeof(rf_data));
      Serial.println(rf_data);
      }
    }

  if (Serial.available()>0){
    while (Serial.available()>0){
      bt_data = Serial.read();
      radio.stopListening();
      Serial.println(bt_data); //----------- I'M ABLE TO SERIAL PRINTLN ----
      radio.write(&bt_data, sizeof(bt_data)); //-------- BUT I'M UNABLE TO PERFORM THIS CODE HERE FOR SOME REASON
      }
    }

}

I've added comments to show which part works and which part doesn't
I hope this question isn't too hard to understand.

naming the Receiver  DEVICE 1 is less confusing?

@jsotola cant u be a bit more helpful

Are the example sketches working? Maybe you have an issue that is not related to your code.

There could be few reasons but, firstly I would like to ask you to check if your write command is working at all. Try to disable reading mode and leave just write mode:
#include "Arduino.h"
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>

RF24 radio(9, 8);

byte addresses[][6] = {"1Node","2Node"};

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setPALevel(RF24_PA_MIN);
  radio.setDataRate(RF24_2MBPS);
  radio.setChannel(124);

  // Open a writing and reading pipe on each radio, with opposite addresses
  radio.openWritingPipe(addresses[0]);
  //radio.openReadingPipe(1, addresses[1]);
}

void loop() {
  unsigned char rf_data; //Make a variable to store the data
  unsigned char bt_data;
  unsigned char tosend;
  //radio.startListening();

 // if (radio.available()){
 //   while (radio.available()){
 //     radio.read(&rf_data, sizeof(rf_data));
 //     Serial.println(rf_data);
 //    }
 //   }

  if (Serial.available()>0){
    while (Serial.available()>0){
      bt_data = Serial.read();
      //radio.stopListening();
      Serial.println(bt_data); //----------- I'M ABLE TO SERIAL PRINTLN ----
      radio.write(&bt_data, sizeof(bt_data)); //-------- BUT I'M UNABLE TO PERFORM THIS CODE HERE FOR SOME REASON
      }
    }

}

Try above code and if it will not work change RF24_2MBPS to RF24_1MBPS and RF24_PA_MIN to RF24_PA_LOW on both modules (transmitter and receiver)


text:
Necessary torque of motor to move a door.
I am building an automatic door opener and for its mechanism I need a motor with a high torque and low speed. My question here is how to measure the torque needed to move the door as I cannot really weigh the door and find its mass. Can anyone help me out?

Ask a moderator to change this to Electronics.stackexchange.

This is more of a question about applied physics, and not about electronics.

You need a "hanging scale" preferably "analog one".

Mount it to any place of the door and slowly pool at 90 degrees. Check what value does the scale show when doors start moving. Static friction is always higher than dynamic friction.
Torque = Radius * Force
Raduis is the distance between mounting place and door hinges.
Force is 9.81 times max value shown by the scale in kilograms.
Do this many times for many mounting points then take average.
Use safety margin of 50% (motor should have at least 150% of required torque)


text:
Reading file from SPIFFS in nodemcu using ArduinoJson
#include <ArduinoJson.h>
#include <FS.h>

/* Set these to desired credentials in runtime */
struct Config {
  String ssid = "";
  String pass = "";
  bool hFlag = false;
};

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("");
  delay(1000);

  //allows serving of files from SPIFFS
  Serial.println("Mounting FS...");
  if (!SPIFFS.begin()) {
    Serial.println("Failed to mount file system");
    return;
  }

  if (readConfigFile("/LaSt.json", false)) {
    Serial.println("Config read");
  } else {
    Serial.println("Failed to read config");
  }
}

bool readConfigFile(char* fileName, bool whichFile)
{
  File configFile = SPIFFS.open(fileName, "r");
  if (!configFile) {
    Serial.println("Failed to open config file");
    return false;
  }

  size_t size = configFile.size();
  if (size > 1024) {
    Serial.println("Config file size is too large");
    return false;
  }

  // Allocate the memory pool on the stack.
  // Use arduinojson.org/assistant to compute the capacity.
  StaticJsonBuffer<256> jsonBuffer;

  // Parse the root object
  JsonObject &root = jsonBuffer.parseObject(configFile);

  if (!root.success())
    Serial.println(F("Failed to read file, using default configuration"));

  // Copy values from the JsonObject to the Config
  Config.ssid = root["ssid"];
  Config.pass = root["pass"];
  if (whichFile)
  {
    Config.hFlag = root["hFlag"];
  }

  // We don't need the file anymore
  configFile.close();

  return true;
}

Compile gives error in Copy values from the JsonObject to the Config section. Error: expected unqualified-id before '.' token.
Want to read file from SPIFFS, and store in variable to use.

Config is type. you do not have an instance of it

Your code at the top:
struct Config {
  String ssid = "";
  String pass = "";
  bool hFlag = false;
};

defines a variable "type". It's like making a new int or bool, but yours is called struct Config.
After making the type, you need to create declare an instance of it.
struct Config cfg;

Then, you refer to the one you created:
  // Copy values from the JsonObject to the Config struct named cfg
  cfg.ssid = root["ssid"];
  cfg.pass = root["pass"];
  if (whichFile)
  {
    cfg.hFlag = root["hFlag"];
  }

Note that a particular issue with ArduinoJSON and Strings is that you may get an error like:
error: ambiguous overload for 'operator=' (operand types are 'String' and 'ArduinoJson::JsonObjectSubscript<const char*>')

There is an ArduinoJSON FAQ entry that states

Most of the time you can rely on implicit casts.
But there is one notable exception: when you convert a JsonVariant to
  a String.
For example:
String ssid = network["ssid"];
ssid = network["ssid"];

The first line will compile but the second will fail with the
  following error:
error: ambiguous overload for 'operator=' (operand types are 'String' and 'ArduinoJson::JsonObjectSubscript<const char*>')

The solution is to remove the ambiguity with any of the following replacement:
ssid = (const char*)network["ssid"];
ssid = network["ssid"].as<const char*>();
ssid = network["ssid"].as<String>();

ambiguous overload for 'operator=' (operand types are 'String' and 'ArduinoJson::Internals::JsonObjectSubscript<const char*>')

link1, link2

Are you  meaning to ask a new question?

No, just mentioned that in the particular case, string variable type will give the error, and the workarounds are given in the links. However, those workarounds also produce warnings.

#include FS.h
#include ESP8266WiFi.h
#include ArduinoJson.h

/* Set these to desired credentials in runtime */

  String ssid = "tttttttt";
  String pass = "ssssssss";

#define fileName "/LaSt.json"

DynamicJsonBuffer jsonBuffer;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("");
  delay(1000);

  //allows serving of files from SPIFFS
  Serial.println("Mounting FS...");
  if (SPIFFS.begin()) {

 if (SPIFFS.exists(fileName)) {

  File subscribedUsersFile = SPIFFS.open(fileName, "r");

  delay(10);

  String file_content = subscribedUsersFile.readString();

  JsonObject& users = jsonBuffer.parseObject(file_content);

           if(users.containsKey("ssid"))          {ssid=users["ssid"].as();}
           if(users.containsKey("pass"))          {pass=users["pass"].as();}

    subscribedUsersFile.close();

    users.prettyPrintTo(Serial);

  }
else  {

   // Create empty file (w+ not working as expect)

   File subscribedUsersFile = SPIFFS.open(fileName, "a+");

   JsonObject& users = jsonBuffer.createObject();

   users.set("ssid", ssid);

   users.set("pass", pass);

  users.printTo(subscribedUsersFile);

  users.printTo(Serial);

  subscribedUsersFile.close();

  Serial.println("New Config File Created...\n");

  users.prettyPrintTo(Serial);

    }

  }
}

Answer could be improved by adding a sentence or two of explanation!!  Please consider.


text:
Sending >255 bytes array to arduino
I am trying to send a 50x50 bitmap bytearray from my python client to arduino where it should be displayed on a screen.
I need to receive 350 bytes to have the data to show the bitmap but as soon as i initialise the array with > 255 elements it does weird things (i guess because of the memory):
When initialising the array with size 254 it does the expected:

Transmission of 350 completed in 2.805466s (arduino) Received: 253
  elements

with size 350 I only get

"Received: 93 elements"

How can i split the bytes i receive with the available memory and then build the bitmap accordingly or what is a better way to do it? I would like to have it transmitted via serial rather than building the qrcode in arduino (as i couldn't get the libraries required working in my setup).
My python client does basically this:
for element in qrCodeBytes:
    countElementsSent+=1
    ser.write(element)
    print("Sending " + str(element))
ser.write("$".encode()) #stop char

My arduino code is based on the popular Serial input basics guide
https://forum.arduino.cc/index.php?topic=288234.0
 const byte numChars = 254;
 byte receivedChars[numChars]; // an array to store the received data

boolean newData = false;

void setup() {
 Serial.begin(114000);
 Serial.setTimeout(10000);
 Serial.println("<Arduino is ready>");
 display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3D (for the 128x64)
 display.clearDisplay();
 display.display();
}

void loop() {
 recvWithEndMarker();
 showNewData();
}

void recvWithEndMarker() {
 static byte ndx = 0;
 char endMarker = '$';
 char rc;

 // if (Serial.available() > 0) {
   while (Serial.available() > 0 && newData == false) {
     rc = Serial.read();
     if (rc != endMarker) {
       receivedChars[ndx] = rc;
       ndx++;
       if (ndx >= numChars) {
         ndx = numChars - 1;
       }
     }
     else {
     receivedChars[ndx] = '$'; // terminate the string
     Serial.println("Received: " + String(ndx) + " elements");
     ndx = 0;
     newData = true;
     }
   }
}

void showNewData() {
 if (newData == true) {
 Serial.println("This just in ... ");
 display.clearDisplay();
 drawBitMap(receivedChars,50,50,0);
 display.display();
 newData = false;
 }
}

void drawBitMap(unsigned char *img, int width, int height, int position){
  if (position ==0){
   display.drawBitmap(128/2-(width/2), 64/2-(height/2), img, width, height, 1);
  } else if (position == 1){
   display.drawBitmap(128-62,1, img, width, height, 1);
  } else if (position == 2){
   display.drawBitmap(0,5, img, width, height, 1);
  }
}

what does this mean ?  it does weird things

Sorry i will clarify in the post,
if i initialise the array with size 254 it does the expected:
Transmission of 350 completed in 2.805466s
(arduino) Received: 253 elements
if i initialise the array with 350 i get "Received: 93 elements"

const byte numChars = 350;? max byte is 255. and you have ndx as byte too.

Thanks for pointing out the byte issue. I found out that the library i am using from adafruit does only support bitmap data located in program memory using the PROGMEM directive. I assume there is not much i can do now with this, i'll have to look for other means of creating this qrcode

You use type byte for the variable ndx. Type byte is 8 bits, so the max value is 255. The variable ndx is incremented and after 255 it continues counting from 0.


text:
Arduino writes file to SD but not content to file
I'm using an Arduino UNO, the Extended Database Library (EDB), and an microSD Card to read/write 2 database tables. I've managed to create both ".db" files on the SD (they show up in Finder when I load the microSD directly onto my Mac).
I can also populate them with placeholder data, but this data does not seem to be actually written to the file (and thus doesn't survive reboot).
Also, trying dbFile = SD.open(db_name1, FILE_WRITE); returns false, even though the files do exist on the drive?
Here's my create code:
#include <SPI.h>
#include <SD.h>
#define SD_PIN 10  //SD read/write pin
#define TABLE_SIZE 8192  //256*32
#include "Arduino.h"
#include <EDB.h>

char* db_name1 = "/DB/SENSOR1.db";
char* db_name2 = "/DB/SENSOR2.db";
File dbFile;

struct sensorLog1 {
  unsigned int id;
  float input;
  unsigned int timestamp;
}
sensorLog1;
struct sensorLog2 {
  unsigned int id;
  float input;
  unsigned int timestamp;
}
sensorLog2;

// Setting up EDB object
inline void writer (unsigned long address, const byte* data, unsigned int recsize) {
  dbFile.seek(address);
  dbFile.write(data,recsize);
  dbFile.flush();
}
inline void reader (unsigned long address, byte* data, unsigned int recsize) {
    dbFile.seek(address);
    dbFile.read(data,recsize);
}
// Create an EDB object with the appropriate write and read handlers
EDB db(&writer, &reader);

void setup() {

  Serial.begin(9600);

  createDB(db_name1, "sensorLog1");
  createDB(db_name2, "sensorLog2");

  dbFile = SD.open(db_name1, FILE_WRITE);  // Doesn't work!
  if (!dbFile) { Serial.println("File does not exist"); }

}

void loop() {}

void createDB(char* db_name, char* table_name) {

  // create file
  dbFile = SD.open(db_name, FILE_WRITE);
  db.create(0, TABLE_SIZE, (unsigned int)sizeof(table_name));

  // populate with placeholder data
  for (unsigned int i = 1; i <= 20; i++) {
    table_name.id = i;
    table_name.input = 0;
    table_name.timestamp = 0;
    EDB_Status result = db.appendRec(EDB_REC table_name);
  }

  // check data
  Serial.println(db.count());  // returns '20'

  // close file to write
  dbFile.close();

}

does the sample work? the sample uses different code for creating and opening an existing database.

@esoterik, yes, the code works if I replace all instances of table_name in the for loop with one of the table names (e.g. sensorLog1), but then obviously the function only works for that particular table...

since your structs are identical except for the name, you should be able to do this with only one struct. sizeof doesn't do reflection, it won't do what your trying to do.

what for inline? how can you have a reference to inline function?

@Juraj, I'm not sure what you're trying to say -- that part comes straight from the EDB code (https://github.com/jwhiddon/EDB/blob/master/examples/EDB_SDCARD_Optimized/EDB_SDCARD_Optimized.ino)

db.create(0, TABLE_SIZE, (unsigned int)sizeof(table_name));

The third parameter is the record size! sizeof doesn't work on data, it works on types, so your getting the size of a char* instead of the size of your sensorlogN struct.
Your code as written shouldn't compile! a char* doesn't have a .id member.
table_name.id = i;
table_name.input = 0;
table_name.timestamp = 0;

Hmm I clearly don't have a perfect understanding of the different variable types yet... How could I make this for loop work, when the two structs are not the same size?

@user1092247 you would have to pass in the size, and a factory function pointer that would create the the correct objects for you, but I don't think that will actually help you accomplish whatever it is your trying to do.

@esoterik, add solution to the answer


text:
What happens if you supply too much voltage to an LED?
Say I have an LED that requires 3.5v. What happens if I power it with more voltage?
For example, my Arduino Uno has a 5v pin. If I power the 3.5v LED from the 5v pin, what will happen?

It depends on if there is a resistor in the circuit, and what the impedance of your voltage source is.

I decided to make a video of this: https://youtu.be/Auuisr9sL-8

In the most simple terms: it will kill the LED.  However things are really not that simple.
First off, an LED is a current driven device, not a voltage driven device. That is, it doesn't really care what the voltage is, but it does care what the current is.  Of course, too much voltage will kill it - but too much current, regardless of the voltage, will kill it.
It's important to understand that an LED is what is known as a non-linear component.  Things like resistors are called linear because they have a linear relationship between voltage and current. Increase the voltage, and the current increases by the same proportion. Increase the resistance and the current decreases by the same proportion.
However an LED is not like that. A typical Voltage-vs-Current graph for an LED looks like this:

Once the voltage reaches the "forward voltage" of the LED the current flowing through it rapidly increases. As you can see it very quickly gets towards infinity. Above a certain point and an increase in voltage has no real difference in the current. In that example the difference between 3V and 5V would be both infinite and zero. In other words, it's pretty meaningless.
But we're still over-simplifying, and that's because we've assumed an ideal power supply. That is, one that can supply a fixed voltage, but infinite current. In other words, a power supply with zero impedance.
No such thing exists, though.
Every fixed-voltage power supply can be seen as an ideal voltage source with an in-line (series) resistor. That resistor limits the amount of current that the supply can provide before the voltage drops too low.  In schematic terms, it looks like this:

simulate this circuit – Schematic created using CircuitLab
If the voltage of the source is above the forward voltage of the LED it will try and draw an infinite amount of current from the source.  That current will lead to a voltage drop across the resistance RZ, which results in the output voltage of the source being reduced.
It will reduce to be the same as the forward voltage of the LED.
We can, of course, calculate the current that would come out of the supply if we know the impedance of the source, but that's not something that is often known.  So you assume it's low and take precautions.
For example, if we happen to know the impedance of the source is 1Ω (maybe it's stated in the datasheet for the power source...) and the voltage is 5V, and we have an LED that has a forward voltage of 2V (I like nice round numbers), we can work out that:

The voltage drop caused by the impedance is 3V (5-2)
The current that causes that drop is 3A (I=V/R, 3/1=3A)

3A is way off the scale for an LED, and it will basically melt internally.
So we add an extra resistance to drop more of the voltage at a lower current.
Now if we take the example of powering an LED directly from an Arduino's GPIO pin without a resistor, we can do the same kind of calculations.
We know that we mustn't draw more than 40mA from a pin (absolute maximum), so if we take that as the current that can come out of a pin before it drops below an acceptable level we can work out an estimate of the impedance. Since the datasheet tells us the output level it shouldn't drop below is 4.2V when powered by 5V, we know that the maximum voltage drop at the maximum current would be 0.8V (5-4.2).  So:

R=V/I = 0.8/0.04 = 20Ω.

There. That's an approximation of the output impedance of a GPIO pin on an Arduino.  So we can plug that into our formulae and connect an LED, and we get:

The voltage drop caused by the impedance is 3V (5-2)
The current that causes that drop is 150mA (I=V/R, 3/20=0.15)

150mA is not massive. It's more than an LED typically wants (20-30mA tops), so the LED won't be happy, but it won't instantly blow at that level. It will be brighter than normal, get hotter than normal, and its lifetime will be much much shorter than normal.
That's not the worrying thing though.  The worst thing is the power dissipation from the impedance:

P=I²R = 0.15²×20 = 0.45W.

That's almost half a watt of heat being generated by the GPIO pin's drivers. If you consider that a half-watt resistor is pretty chunky, if you can picture that power being crammed into the tiny space of a single MOSFET within a silicon chip, you can see how that may become a problem.
It's really not capable of dealing with that level of heat, and the GPIO pin's driver MOSFET goes belly up.  Bye bye MOSFET, bye bye GPIO pin.
As an aside, you would probably also see other strange things happening as the chip tries in vain to deliver large currents to a single GPIO pin. Other areas of the chip get starved of power, power rails drop in voltage, code crashes, etc. All from just one little LED being connected without a resistor.


text:
Using the Arduino compiler, is it possible to use Atmega2560 interrupt pins that are unused by Mega?
Looking into the schematics for the Arduino Mega I noticed that pins PE6 and PE7 are interrupt-enabled (INT6 and INT7 respectively); however, they remain unconnected to any Arduino I/O pin.
I'm designing a custom board based on the Atmega2560 and want to use the Arduino IDE/Compiler to upload my code to it, so I'm pretty much replicating a big part of the Arduino Mega schematic into my board.
However, I would really like to enable these two extra interrupt pins (having 8 interrupt pins in total) in my board, but I'm now sure how to proceed from the software side. How could I enable this new pins in order to use them from the Arduino compiler?

Thanks!

In the original Arduino Mega board variant the unconnected pins aren't defined in it. Just use MegaCore which defines all pins.

Awesome. I didn't know this existed. I'll check it out, so far looks promising. Thank you.

If you are not afraid of getting your hands dirty by touching hardware
registers, you can access those pins bare-metal style, using port
manipulation. You will have to read the datasheet,
specifically the section “External Interrupts” if that's what you are
after.
This works with the stock Arduino core (or even without core), which may
be interesting from a maintenance point of view, but it's not as easy to
use as the Arduino interrupt API.


text:
How would I include Arduino libraries using AVR-gcc without the IDE?
I am writing my own code for the Arduino Uno. I compile my code with AVR-gcc, and then upload it with AVRdude. I am not using the Arduino software, but I do have it installed and working on my PC. I want to include some of the Arduino libraries in my project, like Wire.h for example.
I realise that I could either copy the source file to my current working directory or include the entire path, like: #include "/usr/share/arduino/libraries/Wire/Wire.h" but the issue with that is Wire.h includes Stream.h which includes Print.h which includes...you get the idea. These different libraries are not kept in the same place either. I would have to hunt up and down chains of files, copy them and then use them locally. This does not seem like a good option to me.
Including them like I normally would using the IDE doesn't work at all, which is not surprising.
So, how can I use these libraries in my project without all the pain of finding them manually?

the 'core' is independent from IDE https://github.com/arduino/ArduinoCore-avr

@Juraj: I should have clarified, I am writing my own code, compiling with AVR-gcc and uploading using AVRdude. I am not using the Arduino software at all.

Juraj's comment is still valid. You can include and compile the Arduino AVR Core without ever having to install or open the Arduino IDE. These are just C/C++ header and implementation files. Just delete the ones you don't need, and add it to your include path. Finally, just add the folder to your build system as an external library, and link it against your final executable. If you don't want to add all the extra code for Print and Stream, you'll have to modify or rewrite the Wire library yourself.

@Jǝssǝ You could have a look at the Cosa command line build (https://github.com/mikaelpatel/Cosa/tree/master/build). It is a modification of Arduino-Makefile with a few shell script wrappers to make it easy to use (e.g. do not need to write makefiles). It supports build, upload, serial monitor, etc.

Since you will end up using a significant portion of the Arduino core
library, the easiest path is to accept the idea that you are now writing
“Arduino sketches” rather than plain C++ code. Don't resist, be
assimilated, fire the IDE and write setup() and loop(). ;-)
Once you have something working, the next step is to get rid of the IDE,
which is admittedly not very nice. A couple of ways to do that:

Use Arduino Builder, the command-line tool for building
Arduino sketches. The internals of this are the same as for the
Arduino IDE, but it works on the command line.
Use a Makefile, like Sudar Muthu's Arduino-Makefile. This
is a generic Makefile for building Arduino programs. It is not 100%
compatible with the IDE or Aduino builder, as it does not add function
declarations for you, but it may suit you better if you are used to a
more standard toolchain (it's just make + avr-gcc + avrdude).


text:
How do I make Arduino IDE use a specific version of GCC in Debian?
Using Raspbian Stretch.
I installed gcc-4.9 with specified version. Then I installed arduino (2.1.0.5) which in turn pulled gcc 4.6. When I try to compile Marlin in it, it says

Marlin requires C++11 support (gcc >= 4.7, Arduino IDE >= 1.6.8).
  Please upgrade your toolchain.

How do I make Arduino IDE use the correct version of GCC?

I think this is a question to ask on Debian forum and not here.

Why on earth did you install such an ancient version? Delete it and download the current (i.e., released this decade) version.

@Majenko, these are the newest versions. https://packages.debian.org/stretch/gcc https://packages.debian.org/stretch/arduino

No, those are versions that were submitted to Debian years ago. You don't install Arduino from the Debian repositories. You haven't done for many many years. Download the Arduino IDE from the Arduino website.

As Majenko pointed out, I should have used a tarball from the official site instead of the repositories. Which makes me wonder why that package wasn't deprecated or something...

Installing the Arduino package from the Debian repository (or the one for derived distros like Ubuntu) performs the useful purpose of setting up all the necessary permissions for the Arduino IDE to work. Those permissions are NOT automatically removed when you uninstall the package.
The simplest way to get a working Arduino install:
1. Install Arduino from the repo
2. Immediately uninstall it
3. Get a current version of Arduino from arduino.cc and install that


text:
Memory chip for arduino
I know that you can't expand your ram because it is intern. But I want a extern memory chip (1024KBytes) that is very fast. I know that I need a library to access information on this chip. And functions to read and write data. A shield or breakout board it doesn't matter, and I want that it is compatible with Arduino mega. If the arduino lost power it doesn't matter if I lost the data. It must hold the data when the arduino is powerd.

512mb seems quite unreasonably large for an 8-bit microcontroller. In order to get a better answer, could you explain why you need 512megabits of RAM on a chip that comes with 8kilobytes of SRAM onboard?

I've seen a lot of memory sizes, but I've never encountered a 0.5 bit memory cell. On a more serious note though, assuming you mean 512Mb, that's a ridiculous amount of memory. It would take you tens of minutes to fill up, and processing all that data would take ages. This sounds like an XY-problem.

SPI RAM chips of sizes up to 128 kilobytes seem to be more realistic for you. If you really want megabytes, get a microcomputer (Rasbpi, ..) http://www.microchip.com/design-centers/memory/serial-sram-serial-nvsram

Do you mean 512Mb (Megabit) or 512MB (Megabyte)? The sizes are VERY different.

Sorry, I mean 512 KBytes or 1024KBytes. And that is not true about it is not processable. A SD card is also processable with a capacity of 4GBytes

The point is, that the Arduino would take very long to fill up the space due to it's own speed and the speed of the connection, so it might not be reasonable, to get such high capacity. SD cards for Arduinos are mostly used, because with a simple FAT implementation you can easily copy the saved data to a PC.

Could you tell us what you need it for?  There may be a more appropriate solution than adding RAM.

You can quite easily connect multiple 128kB SPI ram chips to an Arduino. 4 of them together would give you 512kB of extra SPI-connected SRAM.
Access isn't super fast.
Another option is to use a parallel 8-bit SRAM chip. These take a lot more wiring since you need 8 wires for the data, log2(n) wires for the address, plus a couple of control wires (OE, WE, etc). But if you wire it making use of entire IO ports you can get much faster access times.  Also, these come in larger capacities than the SPI SRAM chips.
There is also PSRAM available in even bigger capacities. The same interface as SRAM but it's actually DRAM. The "P" stands for "Pseudo". You can get these in megabyte capacities, although they are usually in a BGA footprint, so you'd need to find one on a breakout board.


text:
Arduino IDE won't upload sketches
I recently updated my Arduino IDE to 1.8.5 from 1.6.9. I am getting issues with uploading sketches. The sketch compiles, but when I try to upload it I get this message:
Arduino: 1.8.5 (Mac OS X), Board: "Arduino/Genuino Mega or Mega 2560,
ATmega2560 (Mega 2560)"

Sketch uses 642 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
java.io.IOException: Cannot run program "___REMOVE___/bin/avrdude": error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at java.lang.Runtime.exec(Runtime.java:620)
    at java.lang.Runtime.exec(Runtime.java:485)
    at processing.app.helpers.ProcessUtils.exec(ProcessUtils.java:11)
    at cc.arduino.packages.Uploader.executeUploadCommand(Uploader.java:129)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:207)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
    at processing.app.SketchController.upload(SketchController.java:713)
    at processing.app.SketchController.exportApplet(SketchController.java:686)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2168)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
    at java.lang.ProcessImpl.start(ProcessImpl.java:134)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    ... 10 more
An error occurred while uploading the sketch

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

I get this message whether or not an Arduino is connected. I also get the same message weather I connect my Arduino Mega or Uno. I tried my sketch, the blink sketch and a completely blank sketch, all with the same results.
Could I please get some help with this issue?

The sketch compiled but it could not be uploaded to the Arduino board.  While I suspect it is not the reason for the error, did you select the correct port and board in the IDE?

yes, I used the usb port and arduino/genuino mega board from the board menu.

You may be able to fix this by taking some drastic action. Be aware this is somewhat advanced and will remove any boards you have installed via Boards Manager:

Click the link on the line following File > Preferences > More preferences can be edited directly in the file. This will open the Arduino15 (or similar name depending on OS) folder.
Delete all files and folders under the Arduino15 folder except for preferences.txt. Please be very careful when deleting things from your computer. When in doubt, back up!
Restart the Arduino IDE.
Verify you can now upload before re-installing any boards via Boards Manager.

where could I find arduino 15 on a mac, I can't seem to find the file

Follow the first step of my instructions exactly.


text:
Connect a TM1627 to ESP32
I want to control a 7 segment display that has a TM1637 integrated with an ESP32.
Some time ago I created a layout that used an ESP12e but I need more GPIO pins so I'm switching over to an ESP32.
This was how I had it hooked up:
CLK -> GPOI14
DIO -> GPIO12

I think I did it this way because I had to use the special CLK pin tou can see in this pinout.
Only I don't know if I need to hook them up with special pins on the ESP32. I can't find a good tutorial and I don't have the parts yet to test with.
Do you guys know which pin(s) are suitable for the TM1637?

any. https://playground.arduino.cc/Main/TM1637. io 14 on esp8266 can be SPI CLK,  for your connection it was gpio

It says I can connect it to any gpio, do I understand that correctly?

The label CLK on esp8266 is in a context of SPI pins CLK, MISO, MOSI, SS. You had no reason to connect TM1637 CLK to this pin, since with TM1637 you can use any GPIO pins of the MCU for CLK and DIO.

Shouldn't TM1637 can use any GPIO pins for CLK and DIO be ESP32 can use any GPIO pins for CLK and DIO?

I edited the answer

IMO still a bit misleading, in my understanding the ESP32 is the active component controlling the TM1637 using any of it's pins to do that.

the protocol is determined by the sensor. it it would be SPI you could use only spi pins of the mcu for that sensor. I answer in a context of the question, adding more refinements doesn't help readability.


text:
Relay does not trigger
Its my first attempt to work with relay
I tried to test my relay with this simple code
int Relay = 2; void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(Relay,OUTPUT);
}

void loop() {

  digitalWrite(Relay,HIGH);
  delay(1000);
  digitalWrite(Relay,LOW);
  delay(1000);
}

Connected to
IN -> Digital 2
GND -> GND
VCC -> 5V
The only thing is happened is the LED of the relay blinking in every sec. but can not hear the clicking sound from the relay box or testing with a multimeter's diode function the two(NC and COM) OUTs aren't close
I tried to test other relays(from the same type) but does not do anything else.
thank you for your help
What can be wrong?

Can you try the relay without arduino? 5V->5V, GND->GND, IN->0V/5V should simulate the arduinos programm. If it does not click, it may be damaged.

NC is "Normally Connected" - this contact is connected to COM ("common") if coil of the relay is not powered - the relay is disconnected.
NO "Normally Open" is connected to COM when the coil of the relay is powered - the relay is connected.
Some relays have the coil powered when the signal from MCU is LOW.
If the coil of the relay doesn't click, but the signaling LED lights up, then VCC is not connected. Check if you plugged the wire really to 5 V on Arduino side.

You need to define Relay.  If the LED on the relay module is blinking, then you must have defined as pin 2 output, but omitted it from the code you posted.  Please post all of the code!
It is good practice for all user variables to start with lowercase, e.g. relay not Relay.  Then the code becomes:
relay = 2;
void setup(){
pinMode(relay,OUTPUT);
digitalWrite(relay,"LOW");
}

void loop(){
digitalWrite(relay,"HIGH");
delay(1000);
digitalWrite(relay,"LOW");
delay(1000);
}

If the relay still does not click on/off, test the microcontoller voltage output on the relay pin using your voltmeter.  Check the relay is not dead or mis-wired.

sorry the relay was defined just made a mistake when copying the source code


text:
Timer interrupt triggers too often
The following question is based on the Arduino Pro Mini (8MHz, 3.3V)
I'm in process of developing (yet another) LED strip driver shield. For that I wrote a simple control loop, that adjusts the channel brightness (PWM duty cycle) to a given target value with a smooth transition.
For testing purposes I configured Timer1 with a 0.5Hz interval to randomly assign new target values. This works almost as intended. When watching the values you can see the constant value periods and completely random, fast changing periods in between (picture generated with Arduino built-in plot). The curved, rather smooth lines are the PWM outputs following the target value (that part is confirmed to work):

The relevant code responsible for the changing of the target value is
ISR(TIMER1_COMPA_vect) //timer1 interrupt 0.5Hz
{
  for(auto it = 0; it < 4; ++it)
        channel_target[it] = random(0, 255);  // assign a random value between 0..255 (max for pwm)
}

My assumption is, that the ISR is called very fast in the fuzzy intervals but since I havn't done much with arduinos yet, I'm not familiar on what kind of background functions might interfere with that.
For completeness the full code:
double          channel[4];
uint8_t         channel_target[4];
const double    channel_k_p[4]      = { 0.001, 0.001, 0.001, 0.001 };
const double    channel_k_i[4]      = { 0.01, 0.01, 0.01, 0.01 };
double          err;
const uint8_t   led_pins[4]         = { 3, 5, 6, 9 };
char            serial_buffer[100];

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

    for(auto it = 0; it < 4; ++it)
        channel[it] = 0;

    for(auto it = 0; it < 4; ++it)
    {
        pinMode(led_pins[it], OUTPUT);   // sets the pin as output
        analogWrite(led_pins[it], 0);
    }

    cli();//stop interrupts

    TCCR1A = 0;// set entire TCCR1A register to 0
    TCCR1B = 0;// same for TCCR1B
    TCNT1  = 0;//initialize counter value to 0
    // set compare match register for 1hz increments
    OCR1A = 15624;// = (8*10^6) / (0.5*1024) - 1 (must be <65536)
    // turn on CTC mode
    TCCR1B |= (1 << WGM12);
    // Set CS10 and CS12 bits for 1024 prescaler
    TCCR1B |= (1 << CS12) | (1 << CS10);
    // enable timer compare interrupt
    TIMSK1 |= (1 << OCIE1A);

    //set timer2 interrupt at 500Hz
    TCCR2A = 0;// set entire TCCR2A register to 0
    TCCR2B = 0;// same for TCCR2B
    TCNT2  = 0;//initialize counter value to 0
    // set compare match register for 8khz increments
    OCR2A = 248;// = (8*10^6) / (500*64) - 1 (must be <256)
    // turn on CTC mode
    TCCR2A |= (1 << WGM21);
    // Set CS21 bit for 64 prescaler
    TCCR2B |= (1 << CS21) | (1 << CS20);
    // enable timer compare interrupt
    TIMSK2 |= (1 << OCIE2A);

    sei();  // reactivate interrupts

    randomSeed(analogRead(0));
}

void loop()
{
    for(auto it = 0; it < 4; ++it)
    {
        sprintf(serial_buffer, "%d ",  channel_target[it]);
        Serial.write(serial_buffer);
    }

    for(auto it = 0; it < 4; ++it)
    {
        sprintf(serial_buffer, "%d ", round(channel[it]));
        Serial.write(serial_buffer);
  }
    Serial.write("\n");

    delay(100);
}

ISR(TIMER2_COMPA_vect)  // timer2 interrupt at 1kHz
{
    // ******************************
    // Channel brightness control loop
    for(auto it = 0; it < 4; ++it)
    {
        err = channel_target[it] - channel[it];

        channel[it] += err * channel_k_p[it];           // proportional
        channel[it] -= err * 0.002 * channel_k_p[it];   // integral

        if(channel[it] > 255)
            channel[it] = 255;
        analogWrite(led_pins[it], floor(channel[it]));
    }
}

ISR(TIMER1_COMPA_vect) //timer1 interrupt 0.5Hz
{
  for(auto it = 0; it < 4; ++it)
        channel_target[it] = random(0, 255);  // assign a random value between 0..255 (max for pwm)
}

Setting the timer register to 0 as the first ISR instruction or deactivating interrupts with
cli();
/* ISR code */
sei();
does not help.

Arduino code doesn't give you an easy control over all interrupts. In this case there is a possibility that Serial.write makes mess with interrupts. I would recommend to take a closer look at this. Also delay() is based on some interrupts.

The analogWrite() function generates a PWM output signal using a
hardware timer. Output on pin 3 is driven by timer 2, whereas
output on pin 9 is driven by timer 1. Here, you are trying to
use these timers for PWM generation and for your own code timing at
the same time. This cannot work. Either you let the Arduino core library
use the timers for analogWrite(), or you take them for you, but not
both.
The solution to your problem is very simple. Nothing in your code really
requires a timer to start with. You can handle both the brightness
control loop and the value changes using the technique of the Blink
Without Delay Arduino tutorial:
const uint32_t TARGET_CHANGE_PERIOD = 500000;
const uint32_t BRIGHTNESS_UPDATE_PERIOD = 1000;

void loop()
{
    uint32_t now = micros();
    static uint32_t last_target_change;
    if (now - last_target_change >= TARGET_CHANGE_PERIOD) {
        last_target_change += TARGET_CHANGE_PERIOD;
        // Change the brightness targets.
    }
    static uint32_t last_brightness_update;
    if (now - last_brightness_update >= BRIGHTNESS_UPDATE_PERIOD) {
        last_brightness_update += BRIGHTNESS_UPDATE_PERIOD;
        // Update the channel brightnesses.
    }
}

Thank you very much.
Is there a documentation for the timer usage somewhere (which timer is used by the arduino system for what)? I knew there are some parts of the arduino system that use various hardware timer, but except the dealy()/millis() <-> timer0 connection I couln't find any information in that regard.

@Patrick: The only authoritative info is probably the source code. It shows timer 0 is used for timekeeping and all three timers for PWM. To match pins to timers, see for example this pinout diagram. Every PWM-capable pin has a label “OCnx”, where n is the timer number (0 – 2) and x is the timer's channel (A or B).


text:
Arduino/ESP8266 - TCP server, connect to AP, receive connections/data
We're trying to use an ESP8266/Arduino Uno as a TCP server, which connects to a wireless AP and then receives commands from other devices on the same network. Currently we got the "connect to AP" part working, but when we try to send data to the ESP/Arduino/TCP server, it doesn't work, refusing all connections to it.
Here's the (relevant parts of the) code we currently use:
#include <SoftwareSerial.h>

SoftwareSerial ESPSerial(2, 3);

void setup() {
    Serial.begin(9600);
    ESPSerial.begin(115200);
    sendToWifi("AT", 10, true);
    sendToWifi("AT+CWMODE=1", 10, true);
    sendToWifi("AT+CWJAP=\""+myAp+"\",\""+myApPassword+"\"", 10, true);
    sendToWifi("AT+CIPMUX=1", 10, true);
    sendToWifi("AT+CIPSERVER=1,80", 10, true);
}

void loop() {
    // The code that would receive data from connecting devices are here
}

String sendToWifi(String command, const int timeout, boolean debug) {
    String response = "";
    ESPSerial.println(command);
    long int time = millis();
    while((time+timeout) > millis) {
        while(ESPSerial.available()) {
            char c = ESPSerial.read();
            response+=c;
        }
    }
    if(debug) {
        Serial.println(response);
    }
    return response;
}

I also have code that's supposed to receive/print data received from the other devices on the network but because no other device can even connect to this TCP server, I felt it was irrelevant for the question. If however you think it's important to include said code, let me know and I'll update my question.
All the solutions we've found online either configures the ESP as the AP, uses the WifiClient library, which we can't seem to get working (even if we could though, we'd rather do it through AT commands) or uses the ESP8266 as a stand-alone module.

and the prints in Serial Monitor indicate the the server started? can you ping the esp8266?

in general, these things are 10x easier to code/debug when you program the ESP directly in ardunio instead of using AT commands. you can then use the uno as the "slave", which makes sense anyway because it's a lot weaker than the ESP.

Did you get any solution? I am facing the same issue…


text:
HC-05 Bluetooth module got virus
We have a problem. Our HC-05 Bluetooth module got virus. We checked it in serial monitor and found out that the output is wrong. It has a mirrored question marks(⸮)and variables(b⸮, bW⸮, k⸮, U) which is not included in our codes. How can we fix it?

It is unlikely this module got a virus. It sounds more like a data rate mismatch or a noisy connection.
If you get ONLY the strange characters and nothing that you would expect, even in part, then confirm that the serial port speeds are equal on both the Arduino and the HC-05 module.
If you get some expected data, with junk characters mixed in, then check that your wires are secure and that you have connected all grounds from the Arduino and HC-05 module together with the power supply ground.

Your module does NOT have a virus (Who would waste their time writing a virus for a bluetooth module...?!?!). You either have a bad baud rate setting, bad wiring, or you are trying to use a high baud rate coupled with SoftwareSerial.

Sorry because it's our first time to encounter this kind of problem so thank you guys for helping me out. Thank you very much!


text:
Can I call functions from a different sketch?
I am a beginner at programming with Arduino and I am unsure on how can I call functions (such as, getData()) for the touchscreen LCD to display that data. The purpose of my device would be to listen to data communications between sensors and a controller and thus I have one RedBoard with CAN-BUS shield with a dataComms.ino sketch, which initialises getting data functions from received data packets and parses them.
Do I need to create another sketch for the display? If so, how can I call functions from another sketch, so that display.ino would have access to received values? Or are there some better ways of displaying data?

You can only use one sketch at a time, meaning one sketch can be stored inside an Arduino to be executed.
This means all your code (and functionality for all devices you want to access) needs to be within that single sketch.
So what you mostly need to do is:

Add a library for every device that you want to use.
Call functions from that library in your .ino file.
If you want to add functions which are not part of a library, you add both the function code and the call (where you need it) in your .ino file.

Also if you are new, don't start with everything at the same time.

First find an example how to control the display (that's probably easier than the CAN shield).
Add the library for the display
Change (or copy from an example) code for the display
Run and debug it until it works.
Create a new sketch for the CAN shield.
Add the library for the CAN shield.
Call functions from that library (or use an example if available).
Once you are convinced you know how to use both devices (display + CAN), combine the sketches (create a new sketch, add both libraries, copy code and make it one sketch).

Thanks a TON! Does it mean that my .ino file acts as a main, through which I need to setup CAN Shield and LCD? Also, I suppose I will need to create .cpp and .h files to create libraries for both of the devices as well, won't I? (For prototypes and variable declarations)

I hope you already have the libraries (or they are existing).. Creating a library for a beginner is far from easy. The Arduino IDE has a mechanism already to add libraries (Manage/Add libraries or something, I don't have the IDE at hand). Your .ino file has two functions: setup (initializing) and loop (run continously). Main is hidden in the framework that Arduino IDE generates and it calls the setup and loop. Check for some basic examples.


text:
DHT11 Sensor : Stand-by or Shut down?
I have an ATmega328P monitoring room temperature and humidity. It is enough for me to monitor every 8 seconds. In these 8 seconds, I am putting my Atmega to sleep.
Now , I want to know : Does shutting down the DHT11 for these 8 seconds affect the performance of the sensor in any way or is it advisable to keep it running (stand by) for these 8 seconds ?
[Shutting down means connecting the Vcc of the sensor to GND by means of digitalWrite(Sensor_pin,LOW);]
Also , (The below question is applicable only if your answer to the above question is to keep it in Stand-by) :-
I want to modify the above project such that Temp & Humidity is measured as and when only an input button is pressed.
In this case too, should I keep the DHT11 running?
Is a running DHT11 sensor more accurate than a instantly powered on DHT11 ?
[And in case you are speculating , yeah,I want to save the 50 micro-amps Standby current of the sensor.(but of course without sacrificing accuracy of the sensor)]

Have you tried to do a practical test? Start the sensor, do some sample readings? And by the way, have you used a search engine and search for "wake up time"?

I searched google.com for "DHT11 wake up time" but got nothing relevant :(

I do switch off DS18B20 as you explain it, because they seem to overheat, if powered constantly. If I do switch off my DHT22 betwean readings, the (first) reading fails about 50% (wrong values, reading error), so I keep i powered.

I googled, "DHT11 wakeup time", found this: https://forum.arduino.cc/index.php?topic=58531.90

@MatsK As I said,  nothing "relevant"

i wouldn't think a room would change that much in 8 seconds, certainly not more than the DHT11's error margin, unless it's some environmental chamber or something; slow that sampling down man...

At times like this it is useful to refer to the datasheet.  You can, in that document, find this paragraph:

4. Power and Pin
DHT11’s power supply is 3-5.5V DC. When power is supplied to the sensor, do not send any instruction to the sensor in within one second in order to pass the unstable status. One capacitor valued 100nF can be added between VDD and GND for power filtering.

So you can see that if you power down the sensor completely you have to wait at least 1 second before you can do anything with it.
With it just in the low power mode it defaults to between readings you can immediately start reading as soon as your ATMega wakes up.
So you have to ask yourself: Does running the ATMega at full power for 1 second consume more or less power than running the DHT11 in low power mode for 8 seconds?
As a rough guestimate - if the ATMega is using 30mA (ballpark figure) for 1 second (that's 30mAs - milliamp-seconds), and the DHT11 uses 50uA for 8 seconds, then you have 0.05*8 = 0.4mAs.
That's 0.4mAs (sleeping) vs 30mAs (powered down). So I'd go for leaving it powered and avoid the one second delay at full power.
Another option that may save more power would be to:

Power off the DHT11
Sleep 8 seconds
Power on the DHT11
Sleep 1 second
Read DHT11
Go to 1

Of course, that means your loop then takes 9 seconds not 8. You could compensate by sleeping for multiple amounts to make 7 seconds:

Sleep 4 seconds
Sleep 2 seconds
Sleep 1 second
Power on the DHT11
Sleep 1 second
Read DHT11
Power off the DHT11
Go to 1

But of course that then makes your sleeping less efficient - so is it really worth it?

"Is a running DHT11 sensor more accurate than a instantly powered on DHT11?" I tried to mean,  is a DHT11 which is running all the time more accurate than instantly (which is being powered on, waited for a second,  taken reading and switched off) powered DHT11?

No, it's no more or less accurate. Because you've had to wait for a second anyway before taking a reading it's been "always on" for the past second anyway.


text:
How to move Servo in between three positions
I want my tower pro 9g servo to start from pos=0, wait there for 1 second, then reach pos=90 wait for 1 second, then reach pos=180 and wait for 1 second. Now it goes back to pos=0 and repeats this cycle. I have written the following code for this purpose:
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(12);  // attaches the servo on pin 9 to the servo object
}

void loop() {

  for (pos = 0; pos <= 180; pos += 90) { // goes from 0 degrees to 180 degrees
    // in steps of 90 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(1000);                       // waits 1s for the servo to reach the position
  }

  for (pos = 180; pos >= 0; pos -= 90) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(1000);                       // waits 1s for the servo to reach the position
  }

}

But the behavior of the servo is not correct. It moves few degree from  initial position and then comes back.
What is wrong with the logic in my code ?

remove the second for loop ... the first loop already does what you want

The logic looks OK to me. But be aware that these servos don't perform well at or close to their limits - mine tend to jitter there but there may be other issues as well. I have 10 of these hobby servos; each has a different jitter-band at the ends of its travel. You may have better success driving them to 10, 90, and 170 degrees.

I think that the servo is too slow. When you ask it to go 90 degrees it starts, than after one second (while it maybe reaches 5 degrees) you ask it to go to 180 degrees it is probably reaching 10 degrees. There it waits again one second.
Than you ask it to go back to 0 (which it does in the same 2 seconds as it moved from 0 to 10 degrees).
Try to adjust the delay times, or use a faster servo.
Also note that in your example (if you wish it would behave like coded), it will end 2 seconds at 0 and 180 degrees, and 1 second at 90 degrees).
Try:
void move_servo(int pos)
{
    myservo.write(pos);
    delay(30000);
}

void loop()
{
    move_servo(  0);
    move_servo( 90);
    move_servo(180);
    move_servo( 90);
}

It will wait 30 seconds between each step, make this less when possible.
To make the servo wait not more than needed, check the old and new servo position and wait as needed, it's probably reasonably linear.


text:
Use lowpower-libary and still use serial connection and other things
I managed to get the LowPower libary working on my Arduino Micro. This code works perfectly:
#include <LowPower.h>

void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);                      // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);                  // wait for a second
}

However. I also tried it with a serial connection, to put out some text periodically. But I think the lowpower-libary does - in order to save power - disable this function. So now I am worried that it also disables some other things I might have to use but won't work. Like OneWire or I2C. It also would be nice to work with a functioning standby-mode while developing where serial output is vital, altough it's not neccessary, because I can simulate it with a simple delay. So my question is: How can I use the lowpower-libary AND have a serial connection. And will this libary affect OneWire or I2C? If so: Is there a way on how to keep these "services" running? Or is there maybe another libary wich also saves power in a similar way, but where you have more abilities to customize what you want to have shut down?

Yes, activating low power does disable the UART - but only while it's sleeping.
To use serial you just need to ensure that you only use it while it's not sleeping - and due to the interrupt and buffered nature of the Serial driver it's not as easy as just printing.
However, it's simple to achieve: just flush the serial before sleeping. This ensures that any pending serial data is sent out through the serial port before you go to sleep:
void loop() {
  Serial.println("Turning LED on");
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  Serial.flush();
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);                      // wait for a second
  Serial.println("Turning LED off");
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  Serial.flush();
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);                  // wait for a second
}

If that doesn't help you may need to turn serial off and on yourself either side of your powerdown:
void loop() {
  Serial.begin(115200);
  Serial.println("Turning LED on");
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  Serial.flush();
  Serial.end();
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);                      // wait for a second
  Serial.begin(115200);
  Serial.println("Turning LED off");
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  Serial.flush();
  Serial.end();
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);                  // wait for a second
}

Update:
I just noticed you're using the Micro. That makes a big difference. The Micro and the Leonardo's Serial object is actually a USB CDC/ACM serial emulation, not UART.  You cannot sustain a USB connection while sleeping. So it will be killed.
To use communication while sleeping you will have to switch to a proper UART connection with a USB to TTL UART (e.g., FT232RL) adaptor to connect to the TX/RX pins and use Serial1 instead.

Unfortunately that didn't work. When looking into the device-manager of windows there isn't any COM-Port shown. Just when resetting the arduino it shortly appears, but then - in both code versions - it gets disabled. Then windows is already blocking my request accessing COMx, responding that there is no such port.

Ah, I see you've tagged it as you're using a Micro. That makes a big difference. That's USB, not UART. And yes, USB will be killed. You will need to use UART not USB.

Well CAN i use UART on the micro somehow??

Yes. I say how in the addendum to my answer.

Or just stick to Idle instead of going into Power-down. The savings will be less, but USB will stay up.


text:
Why are Arduino timer registers not 0?
I'm trying to use the timer registers to do some timing on my Arduino Mega 2560.
The output of the following code confuses me:
void setup ()
{
    // Set up serial connection
    Serial.begin(9600);
    while (!Serial) {}

    // Print control registers of timer 1
    Serial.println(TCCR1A); // Outputs 1
    Serial.println(TCCR1B); // Outputs 3
}

void loop () {}

Why is TCCR1A equal to 1 and TCCR1B equal to 3? The documentation of the chip says the initial values of the registers are zero. I could of course set them to zero, but I want to understand why it works like this. The values are the same for the other 16-bit timers (3, 4 and 5).

The Arduino core does things at startup. One of those things is to configure the timers ready for PWM operation.
Here's the relevant bits from init() in wiring.c:
    // set timer 1 prescale factor to 64
    sbi(TCCR1B, CS11);
#if F_CPU >= 8000000L
    sbi(TCCR1B, CS10);
#endif

#if defined(TCCR1A) && defined(WGM10)
    sbi(TCCR1A, WGM10);
#endif


text:
Can I connect Multiple Devices to One 5V and one GND pin of my Arduino Uno R3
I have made a Bluetooth Controlled Robot Car. Using L298N Motor Driver, HC-05 Bluetooth Module and Arduino R3 I was able to run it by giving one "VIN" and one "GND" to L298N, one "5V" and one "GND" to HC-05 and I gave 12V input to the Arduino Board.
But now I want upgrade it to an upper level by adding IR transceiver as obstacle sensor and a buzzer (as a horn, such that it will sound whenever any obstacle is sensed OR I'll set a button in the GUI to play the horn)
Please Help me. I am a very beginner and assume it as my first project.
Any kind of help would be appreciated.
Thanks in advance.

Yes, you can connect multiple devices to GND and +5 V. You may find that you need to bring one wire from the PCB to an external connector or piece of stripboard so that you can make more reliable connections.
Watch that your total current does not exceed the rating for the voltage regulator or USB power supply.

You can also use a breadboard to “split” the 5V and GND.


text:
Where does arduino IDE store the latest board selection?
I'm building a tool to help me automate my uploading process. How do I know where Arduino stores the current preferences - which board, which com port, what serial speed?
If devs are familiar with using multiple boards in the same system ithey'd know it would be really handy to be able to change that

You might consider switching to Platformio. It's command line-driven with a couple of IDEs available. It's trivial to automate uploads and support multiple boards in it. And it's much faster than the Arduino IDE.
http://platformio.org/

I’d suggest bypassing the Arduino IDE and use avrdude directly. If you enable verbose output on upload you can see the actual avrdude command the IDE is calling.

It is stored in preferences.txt in your Arduino data folder.
You can find more about that file, including where to find it, here.
Some of the keys you may be interested in are:

board=uno
serial.port=COM3
serial.debug_rate=115200

However maybe for your workflow the Arduino IDE isn't the best tool for the job.  You may consider arduino-builder, which is the back-end that the Arduino IDE uses to do the actual compiling, or maybe another IDE entirely, such as PlatformIO or UECIDE.


text:
stk500 getsync() attempt 10 of 10 atmega328pu
I've been getting this very common error on my atmega328pu circuit.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x83
Some things iv'e tried are:

Restarting my comp
Reuploading the bootloader
Redownloading old version of arduino IDE
Using an FTDI chip and placing the chip inside an Uno

After I bootloaded the chip I was able to upload a blink sketch. Then the next time I tried I got this error. Anyone know what could be up? This is driving me crazy!

Where is the edge detector on the reset line? Where are the decoupling caps?

https://arduino.stackexchange.com/a/22541/11529 Does this answer help?


text:
Send out a short signal every 10 seconds to an arduino
In order to reduce power consumption, I want to resume my Arduino from standby mode every 10 seconds. For this a hardware interrupt is necessary.
Is there such a device that can create a quick impulse to trigger that interrupt? It can be anything from 10ms to 2 seconds; doesn't matter. My first thought was to use a 555 timer, but this one can only be on for 10 seconds and off for the same amount of time.
The best solution for me would be an already assembled device that I just have to wire with my Arduino since my knowledge in electronics is very low. Or a detailed assembly plan, then I would be able to build it myself I guess?
UPDATE: I was now able to put the Arduino into standby-mode using the Low-Power library. At first it seemed like it didn't work, because I wanted to print out a text over the serial connection. Instead, I tried to let the internal LED blink every 8 seconds, and this works perfectly.

Your question doesn't say why you don't simply program a second Arduino to do it. This indicates to me that your question may be lacking some vital details about your requirements.

Well the general purpose would be to reduce power consumption. So a second arduino wouldn't be very suitable hence it uses the same amount of power while the other one is in idle state.

You should update the question to include this information.

Yeah that's an important aspect. I updated it

Look into connecting an RTC quartz for use as the wake-up timer, see e.g.: https://steemit.com/science/@techlife/how-to-use-a-quartz-clock-for-real-time-clock-in-avr-microcontroller

While not the subject of the question, keep in mind that a typical "Arduino" will require modification and removal of unneeded parts to achieve low standby power consumption.  You may be better starting with an ATmega and building exactly what you need.

that's a good point.. do you mean something like a bareduino?

@The_javascript_King You can do it with your Mini. See a link in my answer.

A 555 doesn't have to generate a 50% duty cycle. Even if you do want to use a 50% duty cycle, the edge can be RC coupled into the interrupt to reduce the pulse width.
An Arduino can use a slow clock like a 32kHz watch crystal, then it's very low power indeed. This slow one can be used to wake-up your more power-hungry Arduino.
The lowest power and tidiest external solution would be to use a CD4060. These are designed to be very low power, very long period timing devices.
The correct way to do it is to use the internal Watchdog Timer to wake itself up from sleep. This uses an independent internal hardware 128kHz low power oscillator. The longest this can be programmed to wait is 8s. However, if you program it to 5s, then the Arduino can choose to do work, or go straight back to sleep again, on each interrupt.

Well the CD4060 seems promising, but the Watchdog timer solution looks way easier. I always tried it with just that one line to wait 8 seconds: LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF); But doesn't this libary automatically set the watchdog timer or do I have to do this by myself?

@The_javascript_King who knows? How about you ask that specific question on the Arduino forum.

Yeah, your're right. Gonna ask it there. Thanks for your hint with the watchdog timer, I think I'm on the right way

@Neil_UK You cannot program the WDT to 5s. There are only few fixed clock dividers that can be used.

@Maple a valid sub-multiple of 10 then, does it do 2, or 1 second? You can point out problems, or point out solutions.

Umm... I thought I did: "If you need exactly 10 seconds you can write a loop with 5 cycles and call powerDown with 2 seconds sleep"

The best solution for you is to use LowPower library which does not require any external parts. It supports up to 8 seconds sleep. If you need exactly 10 seconds you can write a loop with 5 cycles and call powerDown with 2 seconds sleep.
If you still want to use external interrupt, see this for some chip options.
Also, see this article for some good ideas on reducing power consumption, and this article on how to run Arduino for a year on coin cell.

Well at first I had the same idea, but somehow it doesn't work on my arduino micro. In some forums they said, that even if you use this command: LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
You still have to use an interrupt to start it again. Do you know any working examples?

I don't have micro to try it but from the forums it usually works. Do you by any chance operate WDRF / WDE anywhere in your code? Because that library uses WDT to wakeup. You can also try Enerlib library, which is pretty much the same.

UPDATE: I managed to get it to work with the LowPower libary. I let the internal LED blink and then put it into sleep mode. Before that I always tried to print a strin over the serial port but that doesn't work rigtht after standby. But the LED does :) so problem solved I guess. But still it would be great if serial also works after standby, andy idea how that would be possible?

To achieve minimal power the library disables practically everything in the MCU before going to sleep, including timers (used by serial port). It takes some time for MCU to fully wake up (more than 200 clock cycles in case of power down mode). Try adding a delay after wake up.

Also, I just realized that if you use Arduino you probably have something like serial.begin in your setup. If you use sleep modes it is better to initialize everything after wakeup and shut down everything before going to sleep. Basically - treat "after wakeup" code as if your program just started.

I believe that the LTC2956 was made exactly for this purpose. Directly from the datasheet:

The LTC2956 is a micropower, wide input voltage range,
  configurable  wake-up  timer  with  pushbutton  control.
It  periodically wakes up and turns on a connected system to perform tasks like monitoring temperature or capturing images. After completing the task, the LTC2956 turns the system off to conserve power.
  The wake-up timer period can be adjusted from 250ms to
  39 days using configuration resistors

You can find the datasheet here: LTC2956. It is probably considered expensive at 1.98$ in 1000+ quantity.

Along the lines of mr_sunshine's answer, another chip you could use is commonly known as a 556 timer - it's two 555 timers in a single package.  Run one timer on the normal 50% duty cycle (astable), and have it trigger the other timer in monostable mode to send a short pulse of voltage.  Look for a schematic for a servo controller based on a 556 or two 555's, and change the values to get your 10s delay.  Here's a link to one such page, found with a google search: Servo Exerciser

No, for two reasons.  First the asker is mistaken, a dual timer is not needed, a single 555 could do that job.  But more importantly, even in a CMOS version this will consume 10-25 times more power than appropriate solutions.   That LTC2956 is single digit microamps, this would be 100 uA or worse.


text:
Password.h and keypad.h change pass sketch for Arduino
I have a fixed password. If letter "D" is pressed on the keyboard and the correct password is entered, the fixed password will be then changed. This newly entered password is now the correct password, until the user decides again to change password. It is not working. How to fix it?
#include <Keypad.h>
#include <Password.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns

const char keys[ROWS][COLS] = {
    {'1','2','3','A'},
    {'4','5','6','B'},
    {'7','8','9','C'},
    {'*','0','#','D'}
  };
const byte rowPins[ROWS] = {9,8,7,6};
const byte colPins[COLS] = {5,4,3,2};

Keypad    keypad { makeKeymap(keys), rowPins, colPins, ROWS, COLS };
Password passwd = Password("123A4");
char passwd2;

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

void loop() {

  char key = keypad.getKey();
   if (key != NO_KEY){
      delay(60);
      switch (key){
      case 'D': changepasswd(); break;
      case '*': checkpasswd(); break;
      case '#': passwd.reset(); break;
     default: passwd.append(key);
      }
   }
}

void checkpasswd() {

  Serial.print(passwd2);

   if (passwd.evaluate()){
      Serial.println(" OK.");
   } else {
      Serial.println(" Wrong password!");
   }
   passwd.reset();
}

void changepasswd() {
  char key = keypad.getKey();
      delay(60);
      Serial.print(key);
      passwd2 += key;
      passwd.set(passwd2);

   Serial.print("Password changed to ");
   Serial.println(passwd2);

}

It is not working is not a useful description  of what happens ... please provide a description of what actually happens

You don't have and kind of loop in changepasswd() to get more than one character into the password. Also you are just using the value from geKey() without first checking, if there was really a valid key pressed after the change was initiated. Work out the logic of your functions.

@jsotola The password is not changing. That is the description. The part of entering the default "123A4" is working and the OK message is appearing. If you enter an invalid code, it says "Wrong password". So far so good. But when it comes to changing the password via keyboard, it says "Passord changed to " and show nothing. If you enter the new password, it says "Wrong password"... if you enter the default password, it says "Wrong password".

@chrisl I have been working on this the whole week. I cannot work out the logic of my functions by myself at this point. This code is the best I could do and that's why I am asking for help to fix it, because I can no longer go further.

@LuizVaughan, if you enter the default password, it says "Wrong password" .... so, why do you say that the password is not changing? .... from what you said, it is changing .... you just do not know what it changes to ..... i suggest that  you spend time finding out what the new password is, and change your code so that it saves the actual password that you want

per1234; VE7JRO, sempaiscuba, MatsK and gre_gor. Sorry, but only you guys think this post was unclear. Problem was well understood and, by the way, solved many hours before you all "put on hold".

The logic of your function is garbled:

Function checkpasswd(): Most of the function is ok, but you don't need to send passwd2 through Serial, since it doesn't have anything to do with this function. You only use the variable for setting a new password. You can ditch this print statement.
Function changepasswd(): Here lies the problem. Most likely getKey() returns NO_KEY here, which is defined as the null character. So, when outputting it to Serial, you don't see anything there (The null character marks the end of a string in C/C++). You set the password to be the null character, which cannot every be inputted by the user. Also there lies another pitfall: The Arduino Playground Site for the Password library states for the set() function:

Warning: The new password should be a global variable (not a local
  function variable) as this function copies a pointer to the new
  password into the library, not a copy of the password.

Since the key variable is only local, after the function the Password library has it's internal pointer pointing to a now freed memory space. At some other point in the program this space might be written again, effectively changing to password to something else.
And lastly the function does not contain any loop, so only 1 character will be inputted and the newly set password can only be 1 character long. The buffer variable passwd2 is of type char, so also only 1 character. What you really need there is a char [] (character array).
Here is a bit of code (not tested), that should implement this correctly:
char passwd2[6]=""; //global buffer for new password
                    // 6 bytes, because a C string has to end with the null character

void changepasswd(){
    for(byte i=0;i<5;i++){
        char key = NO_KEY;
        while(key == NO_KEY || key=='*' || key=='#' || key=='D') key = keypad.getKey();
        passwd2[i] = key;
        delay(60);
    }
    passwd2[5] = '\0'; //ensure correct string ending
    passwd.set(passwd2);
}

Note the following points:

This implementation blocks the programs execution, until a full valid password has been typed. It will ignore all invalid characters, that you use for other purposes (#, * and D).
The passwd.set(passwd2) is actually only necessary the first time, we change the password, to let the Password object have a pointer to our buffer. After that we technically can change the password directly in the buffer, without calling the set() function. I included it here for readability and making the code a bit more fail prove (against wrong futher coding).
This is hardcoded to accept only 5-digit passwords. If you want passwords with arbitrary length, you can start programming from this basis.
Debouncing buttons with a simple delay() may be not enough at some point. But as I understand the source code of the Keypad library, it also includes code for debouncing, by only checking every 10ms for a changed button and returning NO_KEY everytime else.

Thank you a lot for your time to make corrections and for your detailed explanations. Your suggestion has been tested and is fully working. Kind regards!


text:
How to convert USB to PS/2?
Objective: To get my USB keyboard to interface with an Arduino Uno board.
Constraints: I can't afford a USB host shield for now for Arduino. Currently available is a keyboard with PS/2 connector. That example is available here. However, it is silly going for such a keyboard, or, buy a USB to PS/2 converter at the moment.
Challenge: USB has VCC, GND, RX/TX. (Rx/Tx also labelled D+/D- respectively). The parallel port connector has the following:

Where will the D- pin go?

USB doesn't have RX/TX.

Is there a reason that you think an USB keyboard would work with a PS2 library? These are not the same but two very different means of communication. When wanting to interface an USB slave, you simply have (!) to implement some kind of an USB master. Thats how USB works.

@chrisl Many USB keyboards can also work as PS/2 keyboards. Plug them into one of those green USB to PS/2 converters and it becomes a PS/2 keyboard. There's no electronics in those converters, it's just a plug. It's down to the keyboard to recognise it's plugged into PS/2 not USB and change its behaviour. Not all keyboards can do it, but certainly most older ones can. I doubt wireless ones would work.

@IgnacioVazquez-Abrams I thought the green/white wires correspond to TX/RX respectively...

@chrisl heard keyboard MCUs do support both protocols...so I have to discover for myself what is the case with my keyboard... :(

@deostroll USB uses "low voltage differential signals". It is half duplex (only sends or receives, never both at once) and sends the signal twice - once normally (D+) and once inverted (D-). At the receiver the two signals are combined (D- is inverted, then added to D+) to cancel out any common mode (inducted) noise. This allows higher speeds over longer distances. RS-485 uses the same technique for traditional UART communications over very long distances.

Many USB keyboards (certainly older ones, though almost certainly not wireless ones) are also PS/2 keyboards.  The wiring of the cable is all that differs, and the chip in the keyboard changes its behaviour depending on how it's wired.
A simple USB to PS/2 adaptor is merely a USB socket and PS/2 plug wired together in a certain way:

So that's:

5V to 5V
D- to Data
D+ to Clock
GND to GND

It may work with your keyboard, or it may not. All you can do is try it and see.