text:
Nano damaged. Power LED OK. USB Detected. No Sketch upload. No Program running
seems i damaged one of my Nanos. i have to say i am new to Arduino and have basic electronik skills and i realized after shopping via amazon that the Nanos i have are clones with CH340G.
never the less they are working. i was building a light driven open/close circuit for my chickens. using L293D motordriver, LCD, photocell. my sketch was just reading the photocell and outputting it on the LCD. not yet using the L293D in the sketch but assembled it already (without Motors and MV+).
The program was running for ~ 2 minutes. i was testing the reading for the photocell and was wondering why at low light the reading was still quite high ~ 600+. then all disappeared from the LCD apart of the background light.
as i couldnt get it running i tried to upload Blink again -> not working
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x96 code here
...
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x96
Problem beim Hochladen auf das Board. Hilfestellung dazu unter http://www.arduino.cc/en/Guide/Troubleshooting#upload.

after a while i was reading about programmers so i turned another Nano into a ArduinoISP trying to write either Booloader or Sketch via ISP bypassing USB (as i understood the different articles)
which gave
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x15
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x15

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x14

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x01
avrdude: stk500_initialize(): (a) protocol error, expect=0x14, resp=0x10
avrdude: initialization failed, rc=-1
     Double check connections and try again, or use -F to override
     this check.

avrdude: stk500_disable(): unknown response=0x12
Der ausgewählte serielle Port avrdude: stk500_disable(): unknown response=0x12
 ist nicht vorhanden oder das Board ist nicht angeschlossen

then i used Atmega_Board_Detector and Atmega_Board_Programmer which both seem to work.
output of Boarddetector:
    Atmega chip detector.
    Written by Nick Gammon.
    Version 1.20
    Compiled on Dec 27 2018 at 15:13:27 with Arduino IDE 10808.
    Attempting to enter ICSP programming mode ...
    Entered programming mode OK.
    Signature = 0x1E 0x95 0x0F
    Processor = ATmega328P
    Flash memory size = 32768 bytes.
    LFuse = 0xFF
    HFuse = 0xDE
    EFuse = 0xFD
    Lock byte = 0xEF
    Clock calibration = 0x9E
    Bootloader in use: Yes
    EEPROM preserved through erase: No
    Watchdog timer always on: No
    Bootloader is 512 bytes starting at 7E00

    Bootloader:

    7E00: 0x11 0x24 0x84 0xB7 0x14 0xBE 0x81 0xFF 0xF0 0xD0 0x85 0xE0 0x80 0x93 0x81 0x00
    7E10: 0x82 0xE0 0x80 0x93 0xC0 0x00 0x88 0xE1 0x80 0x93 0xC1 0x00 0x86 0xE0 0x80 0x93
    7E20: 0xC2 0x00 0x80 0xE1 0x80 0x93 0xC4 0x00 0x8E 0xE0 0xC9 0xD0 0x25 0x9A 0x86 0xE0
    7E30: 0x20 0xE3 0x3C 0xEF 0x91 0xE0 0x30 0x93 0x85 0x00 0x20 0x93 0x84 0x00 0x96 0xBB
    7E40: 0xB0 0x9B 0xFE 0xCF 0x1D 0x9A 0xA8 0x95 0x81 0x50 0xA9 0xF7 0xCC 0x24 0xDD 0x24
    7E50: 0x88 0x24 0x83 0x94 0xB5 0xE0 0xAB 0x2E 0xA1 0xE1 0x9A 0x2E 0xF3 0xE0 0xBF 0x2E
    7E60: 0xA2 0xD0 0x81 0x34 0x61 0xF4 0x9F 0xD0 0x08 0x2F 0xAF 0xD0 0x02 0x38 0x11 0xF0
    7E70: 0x01 0x38 0x11 0xF4 0x84 0xE0 0x01 0xC0 0x83 0xE0 0x8D 0xD0 0x89 0xC0 0x82 0x34
    7E80: 0x11 0xF4 0x84 0xE1 0x03 0xC0 0x85 0x34 0x19 0xF4 0x85 0xE0 0xA6 0xD0 0x80 0xC0
    7E90: 0x85 0x35 0x79 0xF4 0x88 0xD0 0xE8 0x2E 0xFF 0x24 0x85 0xD0 0x08 0x2F 0x10 0xE0
    7EA0: 0x10 0x2F 0x00 0x27 0x0E 0x29 0x1F 0x29 0x00 0x0F 0x11 0x1F 0x8E 0xD0 0x68 0x01
    7EB0: 0x6F 0xC0 0x86 0x35 0x21 0xF4 0x84 0xE0 0x90 0xD0 0x80 0xE0 0xDE 0xCF 0x84 0x36
    7EC0: 0x09 0xF0 0x40 0xC0 0x70 0xD0 0x6F 0xD0 0x08 0x2F 0x6D 0xD0 0x80 0xE0 0xC8 0x16
    7ED0: 0x80 0xE7 0xD8 0x06 0x18 0xF4 0xF6 0x01 0xB7 0xBE 0xE8 0x95 0xC0 0xE0 0xD1 0xE0
    7EE0: 0x62 0xD0 0x89 0x93 0x0C 0x17 0xE1 0xF7 0xF0 0xE0 0xCF 0x16 0xF0 0xE7 0xDF 0x06
    7EF0: 0x18 0xF0 0xF6 0x01 0xB7 0xBE 0xE8 0x95 0x68 0xD0 0x07 0xB6 0x00 0xFC 0xFD 0xCF
    7F00: 0xA6 0x01 0xA0 0xE0 0xB1 0xE0 0x2C 0x91 0x30 0xE0 0x11 0x96 0x8C 0x91 0x11 0x97
    7F10: 0x90 0xE0 0x98 0x2F 0x88 0x27 0x82 0x2B 0x93 0x2B 0x12 0x96 0xFA 0x01 0x0C 0x01
    7F20: 0x87 0xBE 0xE8 0x95 0x11 0x24 0x4E 0x5F 0x5F 0x4F 0xF1 0xE0 0xA0 0x38 0xBF 0x07
    7F30: 0x51 0xF7 0xF6 0x01 0xA7 0xBE 0xE8 0x95 0x07 0xB6 0x00 0xFC 0xFD 0xCF 0x97 0xBE
    7F40: 0xE8 0x95 0x26 0xC0 0x84 0x37 0xB1 0xF4 0x2E 0xD0 0x2D 0xD0 0xF8 0x2E 0x2B 0xD0
    7F50: 0x3C 0xD0 0xF6 0x01 0xEF 0x2C 0x8F 0x01 0x0F 0x5F 0x1F 0x4F 0x84 0x91 0x1B 0xD0
    7F60: 0xEA 0x94 0xF8 0x01 0xC1 0xF7 0x08 0x94 0xC1 0x1C 0xD1 0x1C 0xFA 0x94 0xCF 0x0C
    7F70: 0xD1 0x1C 0x0E 0xC0 0x85 0x37 0x39 0xF4 0x28 0xD0 0x8E 0xE1 0x0C 0xD0 0x85 0xE9
    7F80: 0x0A 0xD0 0x8F 0xE0 0x7A 0xCF 0x81 0x35 0x11 0xF4 0x88 0xE0 0x18 0xD0 0x1D 0xD0
    7F90: 0x80 0xE1 0x01 0xD0 0x65 0xCF 0x98 0x2F 0x80 0x91 0xC0 0x00 0x85 0xFF 0xFC 0xCF
    7FA0: 0x90 0x93 0xC6 0x00 0x08 0x95 0x80 0x91 0xC0 0x00 0x87 0xFF 0xFC 0xCF 0x80 0x91
    7FB0: 0xC0 0x00 0x84 0xFD 0x01 0xC0 0xA8 0x95 0x80 0x91 0xC6 0x00 0x08 0x95 0xE0 0xE6
    7FC0: 0xF0 0xE0 0x98 0xE1 0x90 0x83 0x80 0x83 0x08 0x95 0xED 0xDF 0x80 0x32 0x19 0xF0
    7FD0: 0x88 0xE0 0xF5 0xDF 0xFF 0xCF 0x84 0xE1 0xDE 0xCF 0x1F 0x93 0x18 0x2F 0xE3 0xDF
    7FE0: 0x11 0x50 0xE9 0xF7 0xF2 0xDF 0x1F 0x91 0x08 0x95 0x80 0xE0 0xE8 0xDF 0xEE 0x27
    7FF0: 0xFF 0x27 0x09 0x94 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0x04 0x04

    MD5 sum of bootloader = 0xFB 0xF4 0x9B 0x7B 0x59 0x73 0x7F 0x65 0xE8 0xD0 0xF8 0xA5 0x08 0x12 0xE7 0x9F
    Bootloader name: optiboot_atmega328

    First 256 bytes of program memory:

    00: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    10: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    20: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    30: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    40: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    50: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    60: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    70: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    80: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    90: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    A0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    B0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    C0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    D0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    E0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    F0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF

    Programming mode off.

Output of Board Programmer:
    Atmega chip programmer.
    Written by Nick Gammon.
    Version 1.38
    Compiled on Dec 27 2018 at 15:15:38 with Arduino IDE 10808.
    Attempting to enter ICSP programming mode ...
    Entered programming mode OK.
    Signature = 0x1E 0x95 0x0F
    Processor = ATmega328P
    Flash memory size = 32768 bytes.
    LFuse = 0xFF
    HFuse = 0xDE
    EFuse = 0xFD
    Lock byte = 0xEF
    Clock calibration = 0x9E
    Type 'L' to use Lilypad (8 MHz) loader, or 'U' for Uno (16 MHz) loader ...
    Using Uno Optiboot 16 MHz loader.
    Bootloader address = 0x7E00
    Bootloader length = 512 bytes.
    Type 'Q' to quit, 'V' to verify, or 'G' to program the chip with the bootloader ...
    Erasing chip ...
    Writing bootloader ...
    Committing page starting at 0x7E00
    Committing page starting at 0x7E80
    Committing page starting at 0x7F00
    Committing page starting at 0x7F80
    Written.
    Verifying ...
    No errors found.
    Writing fuses ...
    LFuse = 0xFF
    HFuse = 0xDE
    EFuse = 0xFD
    Lock byte = 0xEF
    Clock calibration = 0x9E
    Done.
    Programming mode off.
    Type 'C' when ready to continue with another chip ...

other observations:
when trying to upload a sketch the rx LED blinks where thin a few times but not bright and at the speed it usually does. the L LED blinks at power on a few times.
i have 2 questions:

can you see anything in my circuit that could have damaged the NANO?
any idea to recover the NANO?

i am more curious on the first question as i don't want to take out another one. the second is more curiosity what can be done on a Nano.
and i am clueless why it died as i run all the experiments individually on an UNO
attached pictures and my fight with Fritzing for the schematics.

Many Thanks already
UPDATE:
just recognized that also my working NANOs can not be programmed via ArduinoISP Sketch using a Programmer NANO. so as the tools from Nick Gammon.
are working https://github.com/nickgammon/arduino_sketches. i assume my chip is working and it is up to the USB Chip or connection.
UPDATE2:
my NANO is fully back in live. what ever happened seems to have corrupted my flash. so after the TIPs from @Majenko with the 10uF Cap between Reset and GND i was able to programm via a "Programmernano". but here is another catch
when you first flash bootloader and then right away flash a sketch via programmer as well, this erases again the bootloader. you can check this with the
Atmega chip detector.
Written by Nick Gammon.
    Bootloader is 2048 bytes starting at 7800

    Bootloader:

    7800: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    7810: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    7820: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    7830: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF

So i just flash the Bootloader via ArduinoISP and then connect the NANO directly to USB to flash a sketch

Is GND connected in there somewhere on the protoboard.

yes it is not visible on the second picture as it is below the LCD. you can see it on the first picture

The orange wire at row 52 it looks like?  The right hand button does not appear to connect to anything at row 46, if that makes a difference.  Hard to say what a floating input pin would do without your code (could be read as High, or Low, leading to erratic behavior).

right hand button is connected to D6 under the nano board

new bootloader or old bootloader? and the selection in Tools menu?

originally it was old bootloader. i did run the  Atmega_Board_Programmer via my programmer nano and this might have updated it. i could choose lilyboot or UNO. ive choosen UNO

If you remove the Nano from the breadboard does it start working? 2. Did you disable reset on your "programming" Arduino?

I don't think the button is connected - looks to me like the wire is off by 1 hole in each picture.

@Majenko 1. it does not work even when everything is removed. 2. no i didnt do. ill search how to do this

@CrossRoads it is really hard to see at the picture but the brown cable goes into the line of the button but the metal is visible above the line before

10uf capacitor between reset and gnd.

@Majenko Many Thanks Programming with ArduinoISP is now working. Programming via USB still not ill now research the Diode

Ch340g is probably dead then

we had it here once already. after bootloader burn, tempted to upload a sketch over ISP too and deleting bootloader in the process

Try replacing the diode as in this link, it worked for me: https://forum.arduino.cc/index.php?topic=166089.0
A short on VCC might damage the diode.
As for the answer to the first question, yes there is a flaw in the design, if the external power is lost the LCD and the L293D will be powered from USB through the above diode.
"Small change" , see Juraj's comment below.

i just measured the diode with multimeter and it seems ok. same values as a working nano. as far as i read when the Diode dies the whole power via USB is dead. isnt it?

@MG52441 Yes but it can be "almost dead" at the point that the LED is still lit.  Can you check the 5V pin with a voltmeter when USB is connected? For a quick test you can short the diode keeping only the nano with USB power no external circuit and no external power.

5v Pin shows 4.67V. it will take a bit of time to the test with shortening the diode.

@MG52441 4.67V looks good to me. Is the power LED flickering when  you try to program the board? Do you use external power while programming (see the above issue)?

no not at all. when i connect usb Power LED shines bright. L LED flashes shortly. then when programming the rx led blinks w very sort and not bright at all.

i am just searching how much current the LCD and the L293D will draw. do you think it will exceed the limits posted here https://electronics.stackexchange.com/questions/67092/how-much-current-can-i-draw-from-the-arduinos-pins

ok found this http://forum.arduino.cc/index.php?topic=255472.0 seems that the LCD with backlight can draw up to 160 mA. so probably i exceeded the max. current.

i shorted the diode no change likely the CH340G is dead. thx for the Tip. ill read up on using external power

@MG52441 Tnks, I don't know if it helps but my Arduino CH340g clone needs a setting in Tools, Processor, Processor"ATmega328P" ATmega328P old bootloader to work properly.

@MG52441, why did you accept this answer?

@Juraj It seems that this was the original fault , drawing to much current from 5V line, then he messed up the bootloader. But if the OP thinks that a different answer is better I made a small change to allow him to remove his choice. Do you have a better answer to question no 1?

@Juraj probably a bit my fault as i did asked 2 questions. what is wrong with my circuit and what can be done to recover the NANO. acutally Dorians second part of the Answer was probably closest to what my main question was. i should use other power source. neverthe less i measured now the current drain and on the backlight of the LCD i have ~ 20 mA on the +5v i have ~ 46mA i didnt measured the individual Digital Pins yet. it should be still within the boundaries of what the Board can handle. so i might have accidently shortend something. i was now giving it another try and it runs well now.

Based on the output from my sketches that you have posted, the CPU chip is fine (Atmega328P). Since you cannot program via the USB port is looks likely that the CH340G is damaged.
A fall-back position is to use another one of the sketches (Atmega_Hex_Uploader) in the link you posted, and upload code via the SPI interface. To make this work you need to purchase a micro-SD card interface as described here for around $US 15.
As for why it failed, this should be investigated promptly. Possibly the answer by Dorian will help.


text:
Measure Sofware Serial write() time
As you probably know, SoftwareSerial uses Interrupts to do some of the timing stuff of the Serial communication.
What I am trying to accomplish is to measure the time that it takes SoftwareSerial.write() to write/send one byte.
Obviously, I started trying with timestamps based on millis(), but found out that SoftwareSerial messes with the millis() timer and it simply doesn't count properly.
I have something like this:
timestamp = millis();
HC12.write(endByte); //HC12 is a SoftwareSerial object

//After sending waits for the answer
while (HC12.available() > 0) {
  byte r = HC12.read();
  if (r == (byte) 254) { //The other HC12 module sends 0xFE
    unsigned long received = millis() - timestamp;
    Serial.println(received);
  }
...

Any suggestion on how I could measure this?
I am trying to implement a half-duplex communication with HC12 433MHz modules and I am testing some theoretical/real timing values for the communication between two boards.

the time is dependent on the baud rate (bits/second) ..... at least 10 bits are sent .... one start bit, 8 data bits and one stop bit ........ the stop bit has to be at least one bit-length, but it could be longer

@jsotola, Hi. Thanks for your help.
Well, I know :-). The thing is, that's theoretical. Also, I want to try with more bytes and I don't think that the timings are exacly the same of calculations based on baud rate.

actually the solution is quite simple ..... the transmitting arduino is actually stand-alone ..... there does not have to be a receiving arduino ........ connect the two arduinos  together using one of the digital pins  ...... the transmitting arduino sets the digital pin, sends software serial byte and clears the digital pin ...... the other arduino measures the time between setting and clearing of the pin .............. you could also time the software serial pin itself

try this .... https://github.com/gillham/logic_analyzer

@juraj, The snippet is now correct. What do you mean the title of the question doesn't match the question?

@jsotola, great idea! Thank you very much.

It is very simple, and you don't need any code to work it out.
SoftwareSerial is completely synchronous (i.e., blocking) when writing.  That means that the amount of time taken to peform the write is the time taken to send the data on the line plus a small function call overhead.
That means the time taken is:
1 / baud * 10 seconds

So at 9600 baud one bit is sent in 1/9600 of a second, and there are 10 bits (1 start, 8 data, and 1 stop bit), so it takes 1/960th of a second.
That's about 1ms per byte, plus a few extra clock cycles for calling the actual functions.
To put it in more detail, when you send a byte this happens:

Set the line level to the start bit level
Wait 1/9600th of a second
Set the line level to the first data bit level
Wait 1/9600th of a second
Repeat 3&4 for the rest of the data bits
Set the line level to the stop bit level
Wait 1/9600th of a second
Set the line level to the idle level

So you have 10 "wait 1/9600th of a second" in total, or a total time of 1/960th of a second.
The same can be said of receiving data. When the start bit arrives it triggers a pin change interrupt.  A synchronous blocking interrupt routine then executes that does the same as above but with reading instead of writing. So that takes about 1ms to execute at 9600 baud - plus some extra to insert the incoming byte into a circular buffer, which you then read from in your sketch.
So the round-trip time of a single byte from unit A to unit B then from unit B to unit A can be estimated as:
1/960 + 1/960 + overheads

That means the minimum time will be 1/480 seconds plus whatever time is spent at the remote unit processing the byte to send data back to you, and a little bit for the function call overheads.
Incidentally, it's that last operation in the interrupt, the "adding the byte to a circular buffer" that means you can't reliably receive at 115200 baud with SoftwareSerial. That takes more time to process than the typical gap between bytes (could be zero - just the width of the stop bit...) that the next byte could have already started to arrive at the GPIO pin before the Arduino is capable of triggering the ISR again, so it misses the start bit.

Hi,
Awesome explanation. Thanks for your time!

source: Stack Exchange

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

sort: votes


text:
NodeMCU with digital sound sensor - Can't find examples or good documentation
I'm very new to this world, and trying to hack one of my first projects have proven hard without solid documentation or examples to copy like I usually do.
I've got a https://www.gearbest.com/transmitters-receivers-module/pp_366523.html NodeMCU ESP8266 board that I'm trying to pair with a Sound Sensor. I wanted digital and simple solution, but I'm thinking I might need a library to make it work?
The closes examples I've found are DHT11/22-sensors using the DHTlib library.
The Waveshare-Wiki contains the following expample that I've tried to modify without any luck.
int sound_din=2;
int sound_ain=A0;
int ad_value;
void setup()
{
  pinMode(sound_din,INPUT);
  pinMode(sound_ain,INPUT);
  Serial.begin(9600);
}
void loop()
{
  ad_value=analogRead(sound_ain);
  if(digitalRead(sound_din)==LOW)
  {
    Serial.println("Noise!");
    Serial.println(ad_value);
  }
  else
  {
    Serial.println("Quiet!");
  }
  delay(500);
}

I've also tried to modify/simplify this code to just print the digital output:
#include <ESP8266WiFi.h>

int dig_in=4; //Using D2-pin on my NodeMCU-board
int dig_value;

void setup()
{
  pinMode(dig_in,INPUT);
  Serial.begin(115200);
}

void loop()
{
  Serial.println(digitalRead(dig_in));

  delay(1000);
}

This results in varius gibborish and junk. I've seen plenty of various errors, and the board seems to crash quite a lot. I've tried swapping out the NodeMCU and the Sound level sensor with new ones, but still seem to be getting the same problems.
Any pointers? Thanks!
UPDATE: I've gotten further by using the following code from this example:
// Program: Sound Level Measurement
#include <ESP8266WiFi.h>

int num_Measure = 1280 ; // Set the number of measurements
int pinSignal = A0; // pin connected to pin O module sound sensor
long Sound_signal;    // Store the value read Sound Sensor
long sum = 0 ; // Store the total value of n measurements
long level = 0 ; // Store the average value

void setup ()
{
  pinMode (pinSignal, INPUT); // Set the signal pin as input
  Serial.begin (74880);
}

void loop ()
{
  // Performs 128 signal readings
  for ( int i = 0 ; i <num_Measure; i ++)
  {
   Sound_signal = analogRead (pinSignal);
    sum =sum + Sound_signal;
  }

  level = sum / num_Measure; // Calculate the average value
  Serial.print("Sound Level: ");
  Serial.println (level);
  sum = 0 ; // Reset the sum of the measurement values
  delay(1000);
}

The result is an output that seems to be pretty close to the relative sound level in the room. I've got a couple of issues that I'm still working on:

NodeMCU randomly crashing. The stacks are not exactly alike, but I've copied one of them down below. I've yet to decode this.
Pretty high noise floor. I.e. anything below around 60dB reads as 3/4/5. I've got to test this some more, it might just be the microphone is not sensitive enough.

Exception (0):
  epc1=0x40103861 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000
  depc=0x00000000
ctx: sys
  sp: 3ffffcd8 end: 3fffffb0 offset: 01a0
stack
  3ffffe78:  3fffc200 00000022 00000000 03c4345f
  3ffffe88:  00000000 4000050c 3fffc278 4010268c
  3ffffe98:  3fffc200 00000022 3ffffeb0 00000000
  3ffffea8:  000002ea 00000000 40000f68 00000030
  3ffffeb8:  0000001e ffffffff 40000f58 00000000
  3ffffec8:  00000020 00000000 3ffe91f0 c06301dc
  3ffffed8:  3ff20a00 c0000000 00003000 00000000
  3ffffee8:  00000058 3fffdab0 00000000 3fffdcc0
  3ffffef8:  3ffe8b88 00000030 00000000 00000000
  3fffff08:  00000020 40101612 3ffe8ae0 40203ebb
  3fffff18:  3fff01ac 40106fb4 00000000 40208a24
  3fffff28:  3ffed518 40222a2d 3ffef904 3ffef900
  3fffff38:  01331819 40105e3e 00000000 00000000
  3fffff48:  60000600 00000100 00000058 00000001
  3fffff58:  4010483a 3ffecc60 3fff01ac 401011a6
  3fffff68:  00000001 00000000 402187a8 40100f73
  3fffff78:  00000000 00000000 40100fae 00000000
  3fffff88:  00000002 3fffdcb0 40203b76 3fffdab0
  3fffff98:  00000000 40202303 3ffe8b88 40000f49
  3fffffa8:  3fffdab0 40000f49 40000e19 40001878
  stack

Where did you copy and paste from to get that question title?

Found it. Crosspost from: http://forum.arduino.cc/index.php?topic=587394.0

the schematic on the wiki shows that the module has two outputs ..... one is an analog output and the other is digital ..... the digital output is generated by amplifying the analog output by a large amount and clipping the result ..... the digital signal leading and trailing edges probably coincide with the zero crossings of the analog signal

Majenko: did I mess up the title when crossposting? :)
@jsotola so I guess I can just as well go with the the analog signal only? I spent a lot of time last night trying to figure this out, and I've gotten a lot further I think. I'm updating the original post.

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


text:
Detect power interruption on NodeMCU
Im using a 5v 1A power supply and connected to VIN pin on the NodeMCU. I also use 18650 battery to keep NodeMCU running in case the power supply shuts off due to power interruption.
I'm planning to use the 5V from power supply, convert it to 3.3V with voltage divider and connect it to the gpio to detect power interruption.
Is it possible? Can the NodeMCU handle the current from the power supply?

try to take a look to this answer: https://electronics.stackexchange.com/questions/372717/how-to-detect-power-failure-and-make-micro-controller-save-data-in-eeprom

Yes, you can.  You need to convert the 5V down to 3.3V with a voltage divider. You also need to consider how you are going to operate the ESP8266 when there is no power.

Can the gpio handle the 1A current?

That question makes no sense.

What about the current of the power supply? I'm worried that it may damage the NodeMCU

What about the current of the power supply? Why do you think that factors into anything?

@Tobot What Majenko is trying to say, in the most condescending way that can be conjured at this time, is that you need to do some reading on the fundamentals of electricity. The GPIO pin determines what current it draws from the power supply, not the other way round. A supply could be rated for 1A or 1000A: if a connected device only needs 1uA, it will only draw 1uA.

I really need to do some reading. Thanks @CharlieHanson


text:
Arduino MKR GSM 1400 SSL client example fails to connect
I am using the GsmSSLWebClient example which comes with the MKRGSM library.
The original example works just fine, I get the arduino ascii logo. But when I change the URL the arduino doesn't get any answer:
//char server[] = "arduino.cc";
//char path[] = "/asciilogo.txt";
char server[] = "wepardi.fi";
char path[] = "/robots.txt";

Starting Arduino web client.
connecting...
connected
GET /robots.txt HTTP/1.1
Host: wepardi.fi
Connection: close

disconnecting.

From Firefox https://www.wepardi.fi/robots.txt is displayed correctly.
I tried also some other sites, and from some of them I get the ascii file content correctly, and from some others not.
Something wrong with my settings?
Prints from debug mode:
connecting...

...
AT+USECMNG=0,0,"VeriSign_Class_3_Public_Primary_Certification_Authority_G5",1239
>
+USECMNG: 0,0,"VeriSign_Class_3_Public_Primary_Certification_Authority_G5","cb17e431673ee209fe455793f30afa1c"

OK
AT+USOCR=6

+USOCR: 0

OK
AT+USOSEC=0,1,0

OK
AT+USECPRF=0,0,1,4,"www.wepardi.fi"

OK
AT+USOCO=0,"www.wepardi.fi",443

ERROR

+UUSOCL: 0
AT+USOCL=0

ERROR
connected
GET /robots.txt HTTP/1.1
Host: www.wepardi.fi
Connection: close

disconnecting.

Command
    AT+USOCO=0,"www.wepardi.fi",443
fails
GsmWebClient (no SSL) example works fine with any hosts I have tried.

in browser you enter www.wepardi.fi and in arduino only wepardi.fi

I finally found a solution to this problem. Disabling certificate validation in MKRGSM library makes the SSL connection succeed also to this site. In MKRGSM/src/GSMClient.cpp I changed
//     MODEM.sendf("AT+USECPRF=0,0,1,4,\"%s\"", _host);
       MODEM.sendf("AT+USECPRF=0");

to use modem factory settings. I still don't know what was the problem with the certificates.
Thanks to everyone who tried to help with this.

The problem you have is that of redirection.
You connect to wepardi.fi and request the file /robots.txt from that host. It immediately tells you "Ok, but that file is actually on www.wepardi.fi/robots.txt. Go get it from there.
But it won't.
You have to go direct to the source.
Here's a trace:
GET /robots.txt HTTP/1.1
Host: wepardi.fi
Connection: close

HTTP/1.1 302 Found
Date: Tue, 08 Jan 2019 14:26:51 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.0.32
Strict-Transport-Security: max-age=63072000; includeSubdomains;
X-Powered-By: PHP/7.0.32
Location: https://www.wepardi.fi/
Cache-Control: max-age=1296000
Expires: Wed, 23 Jan 2019 14:26:51 GMT
Content-Length: 0
Connection: close
Content-Type: text/html; charset=UTF-8

And when you change to www.wepardi.fi:
GET /robots.txt HTTP/1.1
Host: www.wepardi.fi
Connection: close

HTTP/1.1 200 OK
Date: Tue, 08 Jan 2019 14:27:49 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.0.32
Strict-Transport-Security: max-age=63072000; includeSubdomains;
X-Powered-By: PHP/7.0.32
X-Robots-Tag: noindex, follow
Link: <https://www.wepardi.fi/wp-json/>; rel="https://api.w.org/"
Cache-Control: max-age=300
Expires: Tue, 08 Jan 2019 14:32:49 GMT
Content-Length: 67
Connection: close
Content-Type: text/plain; charset=utf-8

User-agent: *
Disallow: /wp-admin/
Allow: /wp-admin/admin-ajax.php
read:errno=0

Thanks, but still I don't get the file content: Starting Arduino web client.
connecting...
connected
GET /robots.txt HTTP/1.1
Host: www.wepardi.fi
Connection: close
disconnecting.

Can you get any sort of feedback to the request?


text:
WORDS in ATmega328 datasheet note
I came across something strange while reading the datasheet for the microcontroller in the Arduino Uno board.
It is the (8) note in pg.296-297 of this datasheet: what does WORDS mean in that context?

Daniel - I suggest that you change your acceptance to jwpat7's answer. | My answer is correct re address word BUT
his points out that "Words" are being addressed and not bytes.  While my answer is not wrong, his is more likely to be what the writer meant in his excessively cryptic footnote.

The notation is being used to indicate that the 16-bit address (as formed by the central bytes of a Write Program Memory Page instruction) is the address of a program-memory word, rather than a  program-memory byte.
The size of program memory is specified in bytes, but it often is addressed as words.  For example, the PC (program counter) register contains word addresses.
For some instructions, when the Z register is used to address program memory, it contains a word number and a byte selector:

The Z-register in the Register File is used to access the Program memory. This 16 bits register pair is used as a 16 bits pointer to the Program memory. The 15 most significant bits selects the word address in Program memory. Because of this, the word address is multiplied by two before it is put in the Z-register. ... The least significant bit of the Z Address Register selects either Low byte (0) or High
  byte(1) of the Program memory word. — AVR108: Setup and Use of the LPM Instruction, page 1

Note: Some of the low bits of the word address in a “Write Program memory page” serial programming instruction are treated as don't-cares.  The number of don't-care bits depends on flash page size, which in Atmel AVR devices is 32, 64 or 128 words, depending on device series.
For example (as shown in Table 129 on page 304 of doc2467.pdf) the ATmega128 with 128-word (256-byte) flash pages has seven don't-care bits in the low byte of the address.
Table 129. SPI Serial Programming Instruction Set
                 -----------Instruction Format----------
 Instruction       Byte 1    Byte 2    Byte 3    Byte 4    Operation

Write Program    0100 1100 aaaa aaaa bxxx xxxx xxxx xxxx
Memory Page                                              Write Program Memory
                                                         Page at address a:b.

Thanks for the answer! I tried to upvote, but I don't have 15 rep yet. Could you please take a look at the follow-up question I posted as a comment under Russell's answer?

I suspect your answer is closer to what is meant than mine. I'm not used to the specific hardware and your quoted passage suggests that your interpretation is superior. I don't just say "I'm wrong" (although I may be) as what I pointed out is correct per se - but Occcam's Razor says your answer should be chosen :-).

@DanielArmengod, I added a note re don't-cares in flash page addresses

@jwpat7 Thank you so very much for the note you added afterwards! It helped me a lot. I'm trying to program an Arduino to serve as a programmer for other MCUs (now I'm targeting the same atmega328p from another Arduino, but my end-goal is (with the help of some external circuitry) to program a PIC18F.

See jwpat7's answer.
My answer is correct re address word BUT
his points out that "Words" are being addressed and not bytes.  While my answer is not wrong, his is more likely to be what the writer meant in his excessively cryptic footnote.
A Byte is most usually used to refer to an 8 bit quantity.
A "word" is usually used to refer to a multi-Byte variable with the length depending on both processor type and context.
In this case, on page 296, table 28-19 information is given on the format of 4 byte Instructions. These instructions are NOT referred to as Words although in some other contexts they might be.
However,  the "Write Program memory page" instruction contains the address of a memory page. This address is made up of a 16 bit field comprised of 2 Bytes - an MSB and an LSB.
The notation "Words" is shown against the MSB and the LSB to denote (not very clearly) that a single 16 bit "Address Word"is formed by the MSB + LSB combination.

I believe I understand what WORDS means in this context now. However, I have a new question: if the Write Program Memory Page instruction writes the page buffer to a page in the program Flash, why does it require the address of a program Word?

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


text:
Digital input on one pin is copied to other pins
I am working on a phase detection project in which i am trying to find the order in which the incoming signal comes. I converted the 240v 50hz Ac signal to a 7v 50hz square pulse. when i connect one(7v 50hz) of the three lines to a digital pin on arduino it is properly detecting, but the problem is if i check the unconnected pins via oscilloscope i am getting the same signal which i connected as input, so when i connect another line to any other pin the two signals are getting added.

(Image 1)this is what i see in the DSO when i connect one line to the arduino pin and observe other pins
.(Image 2)this is what i get after i give another line as input to arduino and observe the pins.
i tried with 2 to 3 boards but i still get the same problem.

simulate this circuit – Schematic created using CircuitLab
this is the schematic i used for converting the sine wave into square wave, i used 4n33 optocoupler for this purpose.

7V into a 5V input pin...?  It's not the input pin that you're seeing the noise on, it's the entire Arduino.  If you operate out of specs then you can expect strange things to happen.

actually i converted 7v to 5v and tried but still i got the same result, so i tot it was not the problem.

Is your signal purely positive, or is it ±7V?

what exactly is the project that you are trying to build?

it is +7v only .

An input pin has a very high impedance. It is so high, that it can read a signal from a nearby pin. Everything changes when you connect a oscilloscope to that pin. You know that the ground wire of a oscilloscope is connected to earth ground of the power plug? You are trying to read the mains 50Hz and that oscilloscope introduces probably the most 50Hz noise. Can you show us a schematic or drawing of your circuit?

i have added the schematic .i hope its helpful for providing a solution.

Set all unused pins as input with pull-up or output then see again the results.


text:
code for OLED display suddenly crashes arduino Nano
Today i've been playing with my monochrome oled 128x64 adafruit screen. I've got it connected using SPI. Previously today i had no problems att all and i was able to print messages and variables on the screen. But suddenly my functions causes the arduino Nano to restart and initialise Setup() again!
It is very frustrating and i cannot figure out what part of my code is causing the crash!
I have tried running the adafruit example code to test the screen and it is working, so the screen is not broken and the wires must be correct.
Here is the code for my display:
display.h :
#include <Adafruit_GFX.h>  // Include core graphics library for the display
#include <Adafruit_SSD1306.h>  // Include Adafruit_SSD1306 library to drive the display

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Define SPI pins:

#define OLED_MOSI   9
#define OLED_CLK   6
#define OLED_DC    7
#define OLED_CS    8
#define OLED_RESET 13

// Create display
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT,
  OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

#include <Fonts/FreeMonoBold12pt7b.h>  // Add a custom font
#include <Fonts/FreeMono9pt7b.h>  // Add a custom font

void initDisplay(){

  delay(100);

  display.begin(SSD1306_SWITCHCAPVCC);

  display.clearDisplay();  // Clear the buffer

  display.setTextColor(WHITE);  // Set color of the text

  display.setRotation(0);  // Set orientation. Goes from 0, 1, 2 or 3

  display.setTextWrap(false);  // By default, long lines of text are set to automatically “wrap” back to the leftmost column.
                               // To override this behavior (so text will run off the right side of the display - useful for
                               // scrolling marquee effects), use setTextWrap(false). The normal wrapping behavior is restored
                               // with setTextWrap(true).

  display.dim(0);  //Set brightness (0 is maximun and 1 is a little dim)

  Serial.println("Display initiated..");

}

void printMessage(String message){
  display.setFont(&FreeMono9pt7b);  // Set a custom font
  display.setTextSize(0);  // Set text size. We are using a custom font so you should always use the text size of 0
  display.setTextColor(WHITE);
  display.setCursor(0,50);
  display.clearDisplay();
  display.print(message);
  display.display();
  Serial.println("printing message on display");
  delay(1000);

}
void printTemp(long temp){

  display.setFont(&FreeMono9pt7b);  // Set a custom font
  display.setTextSize(0);  // Set text size. We are using a custom font so you should always use the text size of 0

  display.clearDisplay();  // Clear the display so we can refresh
  // Print text:
  display.setCursor(25, 15);  // (x,y)
  display.println("temp:");  // Text or value to print
  // Draw rectangle:
  display.drawRect(79, 0, 35, 27, WHITE);  // Draw rectangle (x,y,width,height,color)
                                           // It draws from the location to down-right

  display.setFont(&FreeMonoBold12pt7b);  // Set a custom font
  // Print variable with left alignment:
  display.setCursor(83, 20);  // (x,y)
  display.println(temp);  // Text or value to print

  display.display();  // Print everything we set previously
  Serial.println("Printing temp..");

}

main.ino:
#include "display.h";
#include "DHT.h";
#include "Radiocom.h";

long temperature;

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

  initDHT();
  initDisplay();
  //initRF();
}

void loop()
{
  //temperature = readTemp();
  //delay(1000);
  //printTemp(temperature);
  String message = "123456789abc";
  printMessage(message);
  //sendMsg();
  //RFlisten();
  delay(1000);
}

If anyone can help me out in any way, i would be really thankfull!

W/o looking closely at the code, my go to answer for such situations is to make sure your power supply can handle the maximum current demand.  Especially when the display is totally lit up.  Hum, what happens when your code prints nothing (dark screen) to the OLED display?

Well it was working earlier today and the adafruit example code makes the display work.

To be clear, are you saying you changed nothing in the code?  And now it is not working?   But the Adafruit example code is working?  Well, other possibilities: 1) You did accidentally change something in your code. 2) You updated the libraries (supporting code) for your platform and changed something.  3) You updated the libraries (supporting code) from Adafruit and changed something.  4) You really are not running your code (uploading it to the Arduino) for some reason. Follow up on these and try to come up w/a few of your own.

Where's the rest of your code? Rarely is it the case that the bit you think is the problem actually is the problem. We need all your code.

Okay i will add the rest of the relevant code

I edited in the code in the original post

Well, that String use will be making a mess of your heap - a heap already crowded with the SSD1306 buffer.

The graphic library, the fonts, the radiocom, the String, it is probably a memory problem. Do you have a arduino mega 2560 or a arduino zero or arduino mkr? When it is not a memory problem then it is still a memory problem but also a power problem.

Aha! a memory problem seems plausible.. Is there a better way to manage the text than using strings? The program is running on an arduino nano ch340

When i replace "display.begin(SSD1306_SWITCHCAPVCC)" with "  if(!display.begin(SSD1306_SWITCHCAPVCC)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}  "
as they use in the adafruit example sketch, i get "SSD1306 allocation failed" in the console.. not sure what causes this

The arduino does not crash and restart anymore. I stripped away the custom fonts. But it still wont turn the display on or print my message..

https://majenko.co.uk/blog/evils-arduino-strings


text:
What is the voltage between Vin & GND?
I have NodeMCU ESP8266N Lolin V3, my 5V relay is powered from Vin of the NodeMCU.
The NodeMCU is powered from 5V USB.
My difficulty is when I measure voltage between Vin & GND, it is of 1.9V, but supposed to be around 5V as it is directly attached with usb 5V supply. Actually my relay is not working with the power tapped from Vin, but relay's led & NodeMCU  led are blinking but relay coil does not trip.
Please confirm is my NodeMCU having problems as voltage between vin & GND read 1.9V.
https://drive.google.com/file/d/1Z6jYX4sCLmRxnWbtBYZCNW6LpckokaC9/view?usp=drivesdk

Vin ... the in is the clue - I wouldn't use it as a Vout

possibly duplicate of https://arduino.stackexchange.com/questions/51873/nodemcu-vin-pin-as-5v-output - there is an answer there that suggests using the VV pin for your requirements ... however, don't be surprised if your setup is unstable, due to the power requirements of the NodeMCU and the Relay

I afraid you could not understand, i m not going to use vin as output similar to digital output of GPIO pin, i am just taking input 5v from Vin to power my relay. There in my image, i have given digital output as D4  to relay in1 from nodmcu D4 pin, but relay's coil not get trip but led blinks for both relay & nodmcu. Found no solution anywhere

Yeah sorry but there was info in that questions answers that seemed relevant .. i.e. regarding voltage

Vin does not provide enough current to operate a relay ..... Vin is an input to a voltage regulator .... the voltage regulator cannot be used in reverse

on some nodemcu boards, apparently, Vin is directly connected to USB +5 @jsotola - however, I think there's about as many "NodeMCU" variations as there are stars in the sky ... I have two different types, neither of which have a VV pin ... so that's 3 different NodeMCU boards referenced in one sentence :p

@SumitRoy - you have a Lolin V3 board - I can tell that because below A0 you have GND and VV instead of Rsv and Rsv - VV is "V USB Power output" ... use that with a decent USB power supply (not from a PC as that probably wont supply enough current) ... as I mentioned 5 hours ago ... USE VV

Sorry ... it's VU ... not VV ... I'm old and my back is blind and my eyes are bent :p

Lolin is former Wemos not NodeMcu

Ooo, I know!  All my CH340-based nodeMCU's have a "broken" vin pin, giving only a couple volts. The same pin on all my CP2102-based nodeMCUs (amica) and wemos D1 minis provides about 4.4v (5v in - a diode drop). They work fine with such relay modules. That's why I refuse to buy the CH340-based ESPs anymore, even if they are a lot cheaper... Replace the devkit and it will work fine as-wired, like it should.

The voltage on Vin when you power that board thru USB is not relevant ... Vin is not the pin you are looking for
You clearly have a Lolin NodeMCU (V3) board - the existence of Gnd and VU (looks like VV in your picture!!) between A0 and S3 pins indicates that
In documentaion easily found by searching for Lolin V3 pinout - VU is described a USB power output

Use this pin to connect to JD-VCC on the relays
I've just now successfully done this with a 4 relay board
I would connect (nodemcu -> relay)

3V3 to VCC
VU to JD-VCC
Gnd to Gnd
Dn to INm - i.e. choose a D pin on the NodeMCU and connect to an IN pin on the relay

Thanks a lot to give me solution from your precious time, sir, i have tried this solution in the morning, but fail, could you pls provide some link or email so that i can post the video i recorded, sir just for sake of confirmation, i just want to mention that i gave power to relay by doing as follows , VV of nodmcu to JD- VCC of relay, G of nodmcu to left-hand side GND of relay , and D4 of nodmcu to in1 of relay, pls tell am i correctly doing connection, thanks in advance

You need to connect the 3V pin to the VCC pin on the relay board. JD-VCC is just for the relay coils. Vcc is used for the optocouplers which currently don't have power at all, looking at the picture.

I think the grey wire in the picture probably goes to vcc ... no wait ... that picture is hard to see ... the other issue the OP has is the lack of VCC as you poinbt3ed out @Gerben - that other VCC can be 3v3 (I know, because that's how I connected mine)

Gray goes to IN2. Most of these boards have a jumper between VCC and JD-VCC. But you probably don't want that here. The opto-isolators led could light up if the pin is set to HIGH (3.3V) on the ESP. So the led will see 1.7V across it.

https://drive.google.com/file/d/1Z6jYX4sCLmRxnWbtBYZCNW6LpckokaC9/view?usp=drivesdk

pls see the video, also pls guide me the connection of relay & nodmcu with usb charger..pls

answer edited with suggestions for connections

Thanks for connection @Jaromanda X , i shall try and let you know. Did u just see the video i posted on the link

Manyyyyyyy manyyyyyyy manyyyy THANKS A LOT @Jaromanda, I salute you, hats off to you... In this universe, i have tried solution everywhere but you in this forum gave me working solution.         It got worked as per your connection. Thanks once again. i am so happy

@SumitRoy - no I did not watch the video

It is hard to tell from your pictures but I don't think you have your relay connected properly.
Some problems i see:

Your esp8266n seems to be a 3 Volt device; it has 3V output pins
Vin usually feeds a regulator; the +V rail is usually after it
Your relay needs 5V but you only have 3V for power and signal

You will need a level shifter, and another powersupply to run your relay. You should be able to put 5v into Vin on your ESP and have it be powered, then you will need a level shifter to connect to the IN1 or IN2 of the realy so that you can control it with 3v. And the relay Vcc and GND also connected to the same power supply.

Sir, could you please get to know that just connecting relay Vcc with 3.3V Vcc of esp8266 , lot of youtube video demonstrates that relay of 5v works even on 3.3 V. Just Google it pls. There is no external power supply required other than tapping power from esp8266 to power relay. Pls let me know what's the voltage between Vin & ground is it 1.9V!

the voltage on your particular board is what you measure @SumitRoy - when powered thru USB, mine is 4.74 volts with nothing connected to it - but none of my nodemcu boards are Lolin brand, and neither have a pin labelled VV which I suggested you use 5 hours ago - did you try that at all?


text:
RFID-RC522 not working with Arduino Uno clone
I am using this library https://github.com/miguelbalboa/rfid, and using DumpInfo.ino from it:
/*
 * --------------------------------------------------------------------------------------------------------------------
 * Example sketch/program showing how to read data from a PICC to serial.
 * --------------------------------------------------------------------------------------------------------------------
 * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
 *
 * Example sketch/program showing how to read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
 * Reader on the Arduino SPI interface.
 *
 * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
 * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
 * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
 * will show the ID/UID, type and any data blocks it can read. Note: you may see "Timeout in communication" messages
 * when removing the PICC from reading distance too early.
 *
 * If your reader supports it, this sketch/program will read all the PICCs presented (that is: multiple tag reading).
 * So if you stack two or more PICCs on top of each other and present them to the reader, it will first output all
 * details of the first and then the next PICC. Note that this may take some time as all data blocks are dumped, so
 * keep the PICCs at reading distance until complete.
 *
 * @license Released into the public domain.
 *
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10         // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
    Serial.begin(9600);     // Initialize serial communications with the PC
    while (!Serial);        // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init();     // Init MFRC522
    mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
    Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

void loop() {
    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }

    // Dump debug info about the card; PICC_HaltA() is automatically called
    mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}

When I connect everything correctly and upload that sketch, this shows up in my Serial Monitor:
I have tried this with another cheap Arduino Uno, I connected it exactly the same and scanned one card, everything works perfectly fine:
So I guess RC522 module is working fine, and there is probably issue with that Arduino Uno board.
What I tried next without any success is:

Copy bootloader from working Arduino Uno to this Arduino Uno that is not working.
Switch ATMEGA328P from working Arduino Uno to this Arduino Uno that is not working.

I tested all pins (on board that is not working) for PWM and Digital Output functionality with Firmata Test, and everything is fine in this test.
You can take a look on images of this Arduino Uno board here.
So my question is: something is wrong with the board itself or I am doing something wrong?
Thanks!

reduce you sketch to the minimum code required to demonstrate the failure and post the sketch

@jsotola I posted a code that I am using. I think I can't reduce it, its example code from RC522 library. What confuses me the most is that why the code is not working on that Arduino Uno but works perfectly fine on another very identical Arduino Uno.

thanks  for including the code .... actually, you can reduce the code .... delete everything in the loop() block .... the failure already exists in setup() ............ please  recheck your wiring ...... if you are using a breadboard, then rebuild the circuit on another part of the breadboard

@jsotola I reduced a code as you say and checked wiring (I am using a direct connection from module to a reader with a female to male cables), still same results.

Try using this code:
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>

#define SS_PIN 10
#define RST_PIN 9

#define SERVO_PIN 3
Servo myservo;

#define ACCESS_DELAY 2000
#define DENIED_DELAY 1000
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

void setup()
{
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();          // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522

  myservo.attach(SERVO_PIN);
  myservo.write( 70 );
  delay(7500);
  myservo.write( 0 );
  Serial.println("Put your card to the reader...");
  Serial.println();

}
void loop()
{
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "69 C8 E2 2A") //change here the UID of the card
  {
    Serial.println("Authorized access");
    Serial.println();
   myservo.write( 70 );
 delay(7500);
  myservo.write( 0 );

  }

 else   {
    Serial.println(" Access denied");

    delay(DENIED_DELAY);

  }
}


text:
Digispark Attiny85 draws more power for digital input than expected
I'm trying to figure out why my attiny85 (on a digistump developer board) draws around 3mA at 3V when setting up a pin as INPUT and connecting it straight to ground. The current is measured with a multimeter between said pin and ground (thus only the current sunk by that pin is measured). I would assume that without a pullup resistor it would consume a lot less but it seems, regardless if I configure the button as INPUT or INPUT_PULLUP the current is the same.
Sketch:
void setup() {
  pinMode(3, INPUT);
  //According to datasheet pin needs to be low to disable internal pullup
  digitalWrite(3, LOW);
}

void loop() {
  digitalRead(3);
  delay(100);
}

I would like to design a circuit that can detect a normally closed switch being opened, but the idle power consumption is way to high at the moment. I was planing on using a very high external pullup but it seems I can't disable the internal one...

That seems odd, and not expected. The inputs on a CMOS device like an Arduino should be capacitive, and draw almost no current once they settle on their state. (It takes a small amount of current to drive the capacitor on the input to the high state, but then once it's charged, current flow should drop to the leakage current of the capacitor.)

Could you put the pin through a 10K resistor to ground when your switch is closed? That should be enough to pull the pin low, but greatly reduce the current flow.

You write that the "attiny85 draws around 3mA", so did you measure the current that is sunk by the pin or is it the current consumption of the entire chip? Does it change when you don't configure anything? Also, measuring current to detect the state of a switch seems way too complicate, you could probably read the voltage level at the switch directly.

3 mA is a normal current draw for an ATtiny85 @ 3 V and 8 MHz. This has nothing to do with the input pin, it's just the current the AVR core needs to execute whatever instructions you ask it to execute.

You can use sleep mode to reduce the overall current draw...

I updated the question to reflect that the 3ma is measured using a multimeter hanging between ground and the INPUT configured pin (not the overall attiny consumption). Also added that this happens on a digistump developer board (that has a USB port).

It is the first time, I see digitalWrite to disable a pullup. Normally you have just pinMode(3, INPUT)or pinMode(3, INPUT_PULLUP) to set or unset the pullup. Pin 3 is also an analog input, could be that with pin 0 or 1, you can "save" some current. It is important also to write which board-component you used (there are 3-4 for Arduino IDE).

On your devboard PB3  is connected to +5V over two resistors (1.5 k + 66.5) Ohms. That's the reason for the high current. Not the PU Resistor. ;-) See the scematics https://s3.amazonaws.com/digistump-resources/files/97a1bb28_DigisparkSchematic.pdf (5/1560 = 0.0032051)

It is possible that you have a 3 Volt version, but I did not find any schematics for that. I think in the three Volt version the resistors have lower values.

@PeterPaulKiefer you've got it right - switching to P2 now only draws 146 µA and also without the INPUT_PULLUP leaves the pin floating. Pls formulate this as a quick answer so I can accept it!

The schematics of the digistump developer board shows that PB3 is connected to +5V over two resistors (1.5 k + 66.5) Ohms. That's the reason for the high current (5V / 1560 Ohm = 0.0032051 A). See the schematics https://s3.amazonaws.com/digistump-resources/files/97a1bb28_DigisparkSchematic.pdf
As you mentioned in a reply on my comment above, using PB2 shows the expected behavior of an AT85 IO pin.

Input pin only needs 1uA to pull it high or low.
What else is hooked up?
The internal pullup, 30K to 50K, would only draw 0.1mA.
Turn it on and try it, measure the Vcc current with the pin open and then Gnd'ed.

I came to the same conclusion that it should only draw 0.1mA with those 30-50k internal pullups. Also I probably wasn't precise saying the attiny draws 3mA - rather that pin sinks 3mA when measuring with a multimeter between the pin and ground. Now that I write this - I will have to check my multimeter, maybe it's measurement is simply off I haven't checked switching it to the µA setting!

I removed the soic IC from board and used it on my own board. I mounted two identical SMT boards, one with a generic chinese pdip and the other with the soic removed, both chips soldered, and I used the same battery supply. The soic from digispark consumed 6 times more current than pdip, in sleep mode: 812uA vs 137uA. I suspect of fake chips. In this base, it is hard to speculate.


text:
FreeRTOS single thread vs Function call
Good day to everyone,
I am currently working on project using ATmega2560. I want to use threading, that is why I decided to use FreeRTOS. However, I cannot make one thread to work fine, so that I start writing second one. So, I have following code:
#include <stdlib.h>
#include <avr/wdt.h>
#include <Arduino_FreeRTOS.h>
#include <semphr.h>

void setup()
{
    pinMode(car_state_pin, INPUT);
    pinMode(battery_pin, INPUT);

    Serial.begin(9600);
    Serial2.begin(9600);
    Serial3.begin(9600);

    watchdogSetup(); //setup WD for 8 secs

    Serial.println("Create Tasks");

    Serial.flush();
    Serial2.flush();
    Serial3.flush();

    xTaskCreate(collect_data, (const portCHAR *) "GPS_Collect_Data", 128, NULL, 1, NULL);

    //collect_data(NULL);
}

And I have function collect_data which should run as thread:
void collect_data(void *pvParameters)
{

    (void)pvParameters;
    uint8_t len;
    char *tmp;

    for (;;)
    {
        millis_delay(2000);

        if (digitalRead(car_state_pin) == HIGH)
        {

            Serial.println("Collecting Data");
            tmp = (char *) calloc(50, sizeof(char));

            do
            {
                wdt_reset();
                len = gps_get_data(tmp);
                Serial.println("Len < 15!");
                millis_delay(100);
            } while (strlen(tmp) < 15);

            /* Add imei and state of the car into the data string */
            len += sprintf(tmp + len, "%s,%d,%d", imei, digitalRead(car_state_pin), digitalRead(battery_pin));
            tmp[len] = 0;

#ifdef DEBUG
            Serial.print("TMP IS: ");
            Serial.println(tmp);

            Serial.print("Len is: ");
            Serial.println(len);
#endif

            free(tmp);
        }
    }
}

The problem is, this current code does not work properly, it resets automatically after printing "Collecting Data" and it just repeats forever (So output is:
Creating Tasks
Collecting Data
Creating Tasks
Collecting Data

and so on).
However, when I comment xTaskCreate and do normal function call (uncomment the last line of setup), it works perfect. Can there be any reason, why thread wouldn't work as normal function call? I guessed maybe because of stacksize, but I've increased it and still no result.

What is wdt_reset() supposed to do?

@SimSon The watchdog handling is activated for RTOS and you have to ensure that it is triggered in between the watchdog time interval (here 8 sec ?). If these triggers do not occur, the MCU assumes a hanging interrupt and resets the MCU. I'm more concerned about the cmalloc without a free.

You use cmalloc without freeing the memory. The task needs memory. The greater the stack is, the more memory is used by the task, the less memory you can allocate. If you use more stack memory there is not enough memory for the second malloc. Why do you allocate the buffer in the loop? If you need it, be sure to free the tmp variable after usage. Use a smaller stack size. You only need space for the task frame and the local variables.

@PeterPaulKiefer ahh, I remember. Thanks for reminding!

@PeterPaulKiefer thanks for your answer. However, decreasing stack size and free-ing tmp did not change anything. Again, function call works fine, however, thread fails. I already made changes to the code snippet


text:
Is it possible to upload and run code from EEPROM during boot time?
I am having problems while writing custom bootloader, so that it uploads code from EEPROM (for now internal, as I have no external memory in my hands) and writes into flash. After ~2 weeks of struggling I encountered these question and answers. After that, I realized that I made a mistake not checking the possibility of it. However, I am still confused about several things:

If Harvard Architecture limits what I want, how come optiboot can flash the memory from incoming UART data, which is not even a memory?

If UART reads and flashes memory accordingly, cant I do the same with EEPROM? Read bytes, erase flash, write bytes.

If it is not possible, given two answers in above link, then how does this work? I guess, it is the same logic as I want, using external memory and rewriting flash. Does it mean Harvard Architecture limits only internal memory exchange?

UPDATE: Here is what I have done for now:
In separate sketch, EEPROM is filled with binary code. Bootloader (edited optiboot v8):
  // Set up watchdog to trigger after desired timeout
  watchdogConfig(WDTPERIOD);
#if BIGBOOT

  if ((eeprom_read(0x000) == 0x0C) && (eeprom_read(0x001) == 0x94))
  {
    //while (EECR & (1 << EEPE)); //wait if previous data is still being written
    uint8_t i, j;

    for (i = 0; i < 8; ++i) // 8 pages total
    {
      uint8_t *code;
      code = buff.bptr;
      address.word = (i * 128);

      for (j = 0; j < 128; ++j)  // 128 words at a time
      {
        if (j % 64 == 0)
          LED_PORT ^= _BV(LED);

        *code++ = eeprom_read(address.word + j);
      }

#ifdef VIRTUAL_BOOT_PARTITION
      virtualBootPartition(buff, address);
#endif

      writebuffer(0x46, buff, address, 128);
    }

    while(1); // wait for WDT
  }
#endif

#if (LED_START_FLASHES > 0) || LED_DATA_FLASH || LED_START_ON
  /* Set LED pin as output */
  LED_DDR |= _BV(LED);
#endif

while my function looks like this:
#if BIGBOOT
static uint8_t eeprom_read(uint16_t addr)
{
  EEAR = addr; //read from that address
  EECR |= (1 << EERE); //enable reading

  return EEDR;
}
#endif

I use make atmega328 BIGBOOT=1 to generate hex file. It does not work + UART uploading also fails. If I set BIGBOOT to 0 and generate, UART uploading works fine.
P.S. virtualBootPartition is function which is called in STK_PROG_PAGE case. In order to not repeat the same piece of code, I collected that part into the function.
#ifdef VIRTUAL_BOOT_PARTITION
/*
 *              How the Virtual Boot Partition works:
 * At the beginning of a normal AVR program are a set of vectors that
 * implement the interrupt mechanism.  Each vector is usually a single
 * instruction that dispatches to the appropriate ISR.
 * The instruction is normally an rjmp (on AVRs with 8k or less of flash)
 * or jmp instruction, and the 0th vector is executed on reset and jumps
 * to the start of the user program:
 * vectors: jmp startup
 *          jmp ISR1
 *          jmp ISR2
 *             :      ;; etc
 *          jmp lastvector
 * To implement the "Virtual Boot Partition", Optiboot detects when the
 * flash page containing the vectors is being programmed, and replaces the
 * startup vector with a jump to te beginning of Optiboot.  Then it saves
 * the applications's startup vector in another (must be unused by the
 * application), and finally programs the page with the changed vectors.
 * Thereafter, on reset, the vector will dispatch to the beginning of
 * Optiboot.  When Optiboot decides that it will run the user application,
 * it fetches the saved start address from the unused vector, and jumps
 * there.
 * The logic is dependent on size of flash, and whether the reset vector is
 * on the same flash page as the saved start address.
 */

#if FLASHEND > 8192
/*
 * AVR with 4-byte ISR Vectors and "jmp"
 * WARNING: this works only up to 128KB flash!
 */
#if FLASHEND > (128*1024)
#error "Can't use VIRTUAL_BOOT_PARTITION with more than 128k of Flash"
#endif
  if (address.word == RSTVEC_ADDRESS) {
    // This is the reset vector page. We need to live-patch the
    // code so the bootloader runs first.
    //
    // Save jmp targets (for "Verify")
    rstVect0_sav = buff.bptr[rstVect0];
    rstVect1_sav = buff.bptr[rstVect1];

        // Add "jump to Optiboot" at RESET vector
        // WARNING: this works as long as 'main' is in first section
    buff.bptr[rstVect0] = ((uint16_t)pre_main) & 0xFF;
    buff.bptr[rstVect1] = ((uint16_t)pre_main) >> 8;

#if (SAVVEC_ADDRESS != RSTVEC_ADDRESS)
// the save_vector is not necessarilly on the same flash page as the reset
//  vector.  If it isn't, we've waiting to actually write it.
  }
  else if (address.word == SAVVEC_ADDRESS) {
      // Save old values for Verify
      saveVect0_sav = buff.bptr[saveVect0 - SAVVEC_ADDRESS];
      saveVect1_sav = buff.bptr[saveVect1 - SAVVEC_ADDRESS];

      // Move RESET jmp target to 'save' vector
      buff.bptr[saveVect0 - SAVVEC_ADDRESS] = rstVect0_sav;
      buff.bptr[saveVect1 - SAVVEC_ADDRESS] = rstVect1_sav;
  }
#else
        // Save old values for Verify
        saveVect0_sav = buff.bptr[saveVect0];
    saveVect1_sav = buff.bptr[saveVect1];

        // Move RESET jmp target to 'save' vector
        buff.bptr[saveVect0] = rstVect0_sav;
        buff.bptr[saveVect1] = rstVect1_sav;
}
#endif

#else
/*
 * AVR with 2-byte ISR Vectors and rjmp
 */
  if (address.word == rstVect0) {
    // This is the reset vector page. We need to live-patch
    // the code so the bootloader runs first.
    //
    // Move RESET vector to 'save' vector
      // Save jmp targets (for "Verify")
    rstVect0_sav = buff.bptr[rstVect0];
    rstVect1_sav = buff.bptr[rstVect1];
    addr16_t vect;
    vect.word = ((uint16_t)pre_main-1);
    // Instruction is a relative jump (rjmp), so recalculate.
    // an RJMP instruction is 0b1100xxxx xxxxxxxx, so we should be able to
    // do math on the offsets without masking it off first.
    // Note that rjmp is relative to the already incremented PC, so the
    //  offset is one less than you might expect.
    buff.bptr[0] = vect.bytes[0]; // rjmp to start of bootloader
    buff.bptr[1] = vect.bytes[1] | 0xC0;  // make an "rjmp"
#if (SAVVEC_ADDRESS != RSTVEC_ADDRESS)
  }
  else if (address.word == SAVVEC_ADDRESS) {
    addr16_t vect;
    vect.bytes[0] = rstVect0_sav;
    vect.bytes[1] = rstVect1_sav;
    // Save old values for Verify
    saveVect0_sav = buff.bptr[saveVect0 - SAVVEC_ADDRESS];
    saveVect1_sav = buff.bptr[saveVect1 - SAVVEC_ADDRESS];

    vect.word = (vect.word-save_vect_num); //substract 'save' interrupt position
  // Move RESET jmp target to 'save' vector
  buff.bptr[saveVect0 - SAVVEC_ADDRESS] = vect.bytes[0];
  buff.bptr[saveVect1 - SAVVEC_ADDRESS] = (vect.bytes[1] & 0x0F)| 0xC0;  // make an "rjmp"
  }
#else

  // Save old values for Verify
  saveVect0_sav = buff.bptr[saveVect0];
  saveVect1_sav = buff.bptr[saveVect1];

  vect.bytes[0] = rstVect0_sav;
  vect.bytes[1] = rstVect1_sav;
  vect.word = (vect.word-save_vect_num); //substract 'save' interrupt position
  // Move RESET jmp target to 'save' vector
  buff.bptr[saveVect0] = vect.bytes[0];
  buff.bptr[saveVect1] = (vect.bytes[1] & 0x0F)| 0xC0;  // make an "rjmp"
  // Add rjmp to bootloader at RESET vector
  vect.word = ((uint16_t)pre_main-1); // (main) is always <= 0x0FFF; no masking needed.
  buff.bptr[0] = vect.bytes[0]; // rjmp 0x1c00 instruction
}

#endif
#endif // FLASHEND
#endif // VBP

You can only run code from flash memory. Only the bootloader can write to flash memory. When the bootloader "exits", it will run the code on the "regular" section of flash memory. The bootloader can get the code from input it want, UART, IR, I2C, SPI. It just has to implement it, and probably some protocol on top of it, so it knows when program data start and stops. It could read from EEPROM, but that would mean your code can only be as large as the EEPROM, which is 1k, if I remember correctly, for the 328, while flash memory is 32k (minus the size of your bootloader).

I found this bootloaders: https://github.com/mysensors/DualOptiboot. It get it's program from SPI-EEPROM (where the main program downloads it from somewhere and puts it in EEPROM. Then, after a "reboot", the bootloader transfers it from EEPROM to Flash memory).

Thanks for the answer. I have thoroughly analyzed serial communication between PC and Arduino upon uploading. The code size for atmega328p (I dont know for other MCUs) is exactly 1K. I wrote EEPROM in another sketch for once, which is binary file. Then, I edited bootloader, so that, if EEPROM has anything, read and upload it, as it does when receiving UART sequence. But, unfortunately it was unsuccessful. I guess, external memory will solve this problem.

you can store that 1 kB in flash too. see the do_spm function in Optiboot 7 https://github.com/Optiboot/optiboot/blob/master/optiboot/examples/demo_dospm/demo_dospm.ino

I sound like your on the right track. Not sure why it was unsuccessful. Though your emphasis on 'serial communication' and 'upload' makes me a bit confused. I don't see how it would all of a sudden work with external EEPROM.

@Juraj I don't think that works if you want to rewrite the entire sketch itself. But maybe it can work for OP.

@Gerben, to rewrite the sketch there is my copy_flash_pages function in bootloader to bootload from upper half of the flash. https://github.com/jandrassy/ArduinoOTA/blob/master/src/InternalStorageAVR.cpp  https://github.com/Optiboot/optiboot/pull/269

Related: Is it possible to use extra AVR Flash memory as non-volatile EEPROM-like Flash memory storage?.

What you're trying to do may require editing the linker script (not even sure where that's located for Arduino at the moment).

Looks like the linker script files are located in, for example: arduino-1.8.13/hardware/tools/avr/avr/lib/ldscripts/avr1.x. I'm grasping at straws here though--not sure how to tell which one is for the ATmega328. Anyone know? Also, here's the optiboot code. It's worth studying I think to see exactly how it works, to try and see how it works, what its limitations are, and go from there: https://github.com/arduino/ArduinoCore-avr/blob/master/bootloaders/optiboot/optiboot.c. It will probably have clues to track down in datasheets and Atmel/Microchip white papers too.

I edited my post and include more explaination and pieces of code.

@GabrielStaples why would I need linker script?

to use BIGBOOT with 328p, you must change the fuses https://github.com/jandrassy/my_boards/blob/14f363387bbe70bfe66e1b6c2b7a398338d92533/avr/boards.txt#L89 while burning the bootloader

And I was thinking, why BIGBOOT without my code is not working). Thanks!

read my answer below for more know-how

If you have a sketch which can write its updated version into EEPROM of ATmega328p and then boootload from the EEPROM, then you can use the flash for the same purpose. The ATmega328p has 32kB of flash and only 1kB EEPROM.
For my ArduinoOTA library I developed a way to store the uploaded binary in upper half of the flash and then let the bootloader copy the binary to address 0 and reset the MCU.
The Optiboot 8 has do_spm() function. This function can be called from the sketch to write to flash memory.
To copy the binary stored in upper half of the flash to address 0, I wrote a new function for the Optiboot. It is called copy_flash_pages and has an extra boolean parameter to request a reset of MCU after copying the pages.
For network upload the sketch size is larger then half of the flash of 328p because of the networking library. So ArduinoOTA is only for ATmega with more then 64kB flash.
If you have a way how to get the binary of size less then half of the 328p flash, then you can write it to the upper half of the flash and then use my copy_flash_pages function to bootload it.
Resources:

header file to access the Optiboot functions from sketch
boards definition and bootloader for 328p with Optiboot with copy_flash_pages function in my_boards (note the changed fuses in boards.txt for Uno/Nano/Mini)
the InternalStorageAVR class in ArduinoOTA library as example how to store and apply the binary

Example of InternalStorage use:
  if (!InternalStorage.open(length)) {
    Serial.println("There is not enough space to store the update. Can't continue with update.");
    return;
  }
  byte b;
  while (length > 0) {
    if (!source.readBytes(&b, 1)) // reading a byte with timeout
      break;
    InternalStorage.write(b);
    length--;
  }
  InternalStorage.close();
  if (length > 0) {
    Serial.print("Timeout downloading update file at ");
    Serial.print(length);
    Serial.println(" bytes. Can't continue with update.");
    return;
  }
  Serial.println("Sketch update apply and reset.");
  InternalStorage.apply(); // this doesn't return

This almost solves my problem. However, I did not understand this: "If you have a way how to get the binary of size less then half of the 328p flash, then you can write it to the upper half of the flash and then use my copy_flash_pages function to bootload it.". ATmega328p has 32k flash and binary size is 1k.

@MiradilZeynalli, to make the next upload the uploaded code must support the upload. can you make this code so small?

Moreover, I mostly would like to solve this with bootloader as my question implies. Because, having binary in flash + program itself + bootloader can have limitations for bigger programs (without using your network library). In my case, I would like to use bootloader max of 1k (I am even planning to delete STK500 support, so I can reduce it to 0.5k).

then why do you want to go over EEPROM? the bootloader can write directly to flash. I don't understand the process you try to achieve. how is the binary transferred?

I just have to test it, to be honest :). But, I think, from your experience, you have failed to do so. Then, please correct me if I got you wrong. Even if I have already array of values (let's say I got it from bluetooth) of binary file, I can flash memory and upload code with your InternalStorageAVR class and its functions

yes. similar to this example https://github.com/jandrassy/ArduinoOTA/blob/master/examples/Advanced/OTASketchDownload/OTASketchDownload.ino

I am using internal EEPROM for now, as I don't have external one right now. What I want to achieve, is to read from eeprom and rewrite flash DURING bootloader. In application code, read binary - store binary to EEPROM - reset yourself.

I analyzed your code and as you said, it is good for small programs or larger flash MCUs. If I understand your code correctly, you are using upper half of flash as temporary storage for code and then copy it to actual program section, which is why, you need your code to be less than the size of the flash. Then my question is: is it possible to store binary not in flash but in EEPROM (or in other external memory device) and then copy it to flash using your functions?

the code to write to EEPROM is simple. then in bootloader you check if EEPROM contains a new binary and copy it to flash. and as I understand you have the code, but the new binary doesn't start?

the problem with external device is that you must code the communication over SPI or similar and it makes the code larger

Yes, I am trying to read from eeprom during bootloader and write to flash (as optiboot does). But, it seems to fail. I have included all the needed code pieces in the question.

Everything was working correctly, I was just testing it wrong. As you said, with your library I can store heavier code than EEPROM. I will still use external EEPROM, but still your answer is correct, so I marked it (despite the fact that it has been 6 months)


text:
Arduino Mini and USB2Serial not uploading sketch
I am trying to upload my sketch to an Arduino Mini Pro.
My programmer is the Arduino USB2Serial.
I am running the Windows store app on a Windows 10 machine.
I wired everything up according to the Arduino Mini guide.

I got different errors just stating something like "error while trying to upload the sketch" before but now I'm always getting this error message after the programmer takes a very long time trying to upload:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x68
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I also didn't forget the capacitor. I added one that is well above the required 100nF and the reset seems to work as the mini came preloaded with the blink example and it briefly stops before the programmer tries to upload.
I did also try to manually reset at different times before and after klicking the upload button.
I also noticed the programmers RX LED lights up briefly flashing three times shortly after resetting the Arduino but the TX one never lights up.
I also checked if there was an error with the programmer but whenever send something through the serial console while connecting the RX and TX of the programmer it always returns what I typed and both LEDs light up so it should work.
I also manually installed the Arduino USB drivers. The programmer now shows up as "Arduino USB Serial Light Adapter" in the device manager.
I did set the arduino Mini board in the Arduiono IDE settings and also the right port. Though I am not really sure which programmer to choose. I tried pretty much all of them that made sense to me with exactly the same results in every case.
In my memory when playing with these components years ago I thought it was also possible to just connect an Arduino Mini "upside down" like this (I am so sure I remember this working but it won't when trying now):

So right now I don't know what else to try. I even tried multiple different Arduino Minis from different manufacturers and tried resoldering all pins to make sure I didn't mess up.
I also tried pretty much everything from the troubleshooting guide mentioned in the error message.
Any suggestions what else I could try?
Update: I now also tried using an old Arduino Uno as programmer like described in the Arduino Mini guide and I tried different versions of the Arduino IDE down to ver 1.0.1 all with the same results.
I even tried installing the drivers from the older versions but Windows 10 wouldn't let me and insisted that the default drivers were suited best.
I managed installing drivers from the newest Arduino IDE but it didn't change anything.
I read in this question That it might be an issue having to do with older Arduino Mini boards (mine are a few years old). But the fixes suggested there did nothing for me.
The only thing I can think of left to try would be using a machine running an older version of windows in order to be able to use older drivers. But I'm really not sure if it's worth the trouble.
I'm also starting to suspect that my programmer might be broken. But then again why did it work looping back serial messages?

the USB adapter is not a programmer. the Upload button in IDE does a Serial upload over USB (virtual com port) and doesn't care about Programmer selection it Tools menu. (In Sketch menu there is an option "Upload with programmer" for upload over a programmer connected to the ICSP header)

the wiring on second picture (reset on adapter to DTR pin on Mini) should work. I don't know if Minis had different bootloaders, but you could try to burn a current bootloader, if you have a ISP programmer or a working Arduino (for Arduino as ISP)

the Arduino USB to TTL adapter uses FTDI chip which is supported by everything. any OS, any version

Ok I'm gonna try to burn the bootloader next time


text:
How to write http response from HttpClient to Serial monitor with a ESP32 (Wemos Lolin32)?
With my ESP32 Board, Wemos Lolin32, I would like to make a http GET request to "http://www.arduino.cc/asciilogo.txt", read the text file and print the text file to the serial monitor.
The question is: Why isn't basically the txt file written to the serial monitor? How can it be achieved? Do I need some kind of conversion of the char?
I am using similar code to that from this example https://www.arduino.cc/en/Tutorial/HttpClient.
Basically the code can be reduced to this minimal example:
#include <WiFi.h>
#include <HttpClient.h>

void setup() {

  Serial.begin(9600);

  WiFi.begin(ssid, password);
  Serial.println("Connecting to WiFi..");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println(".");
  }
  Serial.println("Connected to the WiFi network");

  pinMode(LED_BUILTIN, OUTPUT);
  Serial.println("SETUP FINISHED");
}

void loop() {
  Serial.println("Connecting to httpClient");

 HttpClient httpClient;
  httpClient.get("http://arduino.cc/asciilogo.txt");
  while (httpClient.available()) {
    char c = httpClient.read();
    //Serial.print(c);
    Serial.write(c);
  }
}

The expected result is: I would like to see the characters from the txt file (https://www.arduino.cc/asciilogo.txt) in the serial monitor.
The actual result is: The connection to the WiFi can be established. In the serial monitor either question marks or strange symbols are displayed.
I have checked the baud and it is the same in the code and in the monitor. I tried to change this value, but it did not help.

When switching from HttpClient to HTTPClient and using String payload = http.getString(); Serial.println(payload); I can achieve the expected result.

it is http://arduino.cc/asciilogo.txt. without www. www is redirected to https. you can verify it from a browser

I have edited the URL, the result is the same.

Serial.write(c); if you read raw byte, then write raw byte. print converts number to text

The server also gzip encodes the content. He needs to add a Accept-Encoding: identity header.

Unfortunately it does not work.

Yes, I did change it to Serial.write(c);

It is pretty strange. Serial.write(c) and Serial.print(c) are producing exactly the same output.

When switching from HttpClient to HTTPClient and using String payload = http.getString(); Serial.println(payload); I can achieve the expected result.

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - From Review

@MichelKeijzers, there is no link. it is the right URL to use in the sketch in question

@Juraj ... sorry I am wrong; I was under assumption the link itself was the answer. Upvoted instead now :-)


text:
Can I use this pinhole camera with arduino?
The pinhole camera is a 420TVL, 3.7mm Passive Infrared Detector Color Covert Security Camera. Can I use this camera with an arduino creation?
Things I don't know to answer the question:

Does the power need something special arduino can't offer?
Is the arduino powerful enough to push the video feed/photos to a computer or any other method to video/photos.

Here are some specs from the site:

Sensor   1/3" Sony Super HAD II CCD
Picture Elements  NTSC 768x494
PAL 752x582
Horizontal Resolution 420 TVL
Minimum Illumination  0.001 Lux
S/N Ratio more than 50dB
Scanning System   2:1 interlace
Synchronous System    Internal, Negative sync
Auto Electronic Shutter   NTSC 1/60s ~ 1/100,000s
PAL 1/50s ~ 1/100,000s
Gamma Characteristics 0.45
Video Output  1 Vpp, 75 ohms
Auto Gain Control Auto
Power / Current   DC 12V (±10%) / 150mA
Lens  3.7mm Taper Pinhole Lens

Is it possible? They're on sale but I don't want to throw money away and find out that they don't work with any arduino. Also, I don't have any setup for this to be plugged into. Therefore, I'm not tied down to previous creations the cameras need to fit in.

Without looking at it, it sounds like it has a composite output, therefore the Arduino would not be involved with it at all.

The problem with your question is you need to define "use" because you definitely can connect that camera to an Arduino in a few different ways. For example, you could use an Arduino to simply send the video stream to an SD card, making a cheap camcorder. You could use the Arduino to analyze the images too, but that's obviously going to be more complicated. You need to describe your application. I'll remove my down-vote when you do that.

No, you really can't use it, definitely not directly nor indirectly in any advantageous way.  The problem is not with the question which is innocently uninformed, but with the mistaken suggestion that it could be used.

No, you cannot use this with an Arduino without additional hardware in between, and even with it, not as more than a still camera (or maybe low quality video for one of the ARM- rather than ATmega-based boards).
The first problem is that this camera has a high speed analog output called composite video.  It is basically what would be fed into a modulator to produce an old-style analog TV signal.  Capturing this digitally requires an Analog to Digital converter (ADC) capable of several million measurements per second, while that on the classic ATmega-based Arduino tops out at around ten thousand.
But let's say you had an additional Analog-to-digital converter to put in between this and your arduino.  The next problem is that the data rate out of the camera will be too high, and the Arduino won't have enough RAM memory to buffer it.
In theory, you could get a "frame grabber" consisting of an ADC and its own buffer memory, which would take a still snapshot of the video and allow the arduino to read it out more slowly.  But you can buy cameras which already do that with their onboard electronics, and allowing something like an Arduino to read the still image data out over a moderate speed serial interface.
Even the ARM-based arduino boards would be taxed to keep up with the output of a video ADC and do much of anything useful with the results - typical digital cameras do not record raw images to SD card, but do JPEG compression within a frame.  When cheap digital cameras operate in video mode, they compress each frame of the video before storing it (just as with stills - they do not compress between frames in the manner of real video recorders), and are able to get that processing done in time because the actual computing hardware is optimized for it in a way that none of the Arduinos are.
If you want to experiment with a camera on a development platform, there is one with a high speed digital interface sold as an add-on for the Raspberry Pi board.  Or you can use a more inexpensive USB webcam with that.

So, Radio Shack is flat out full of crap about this then? http://blog.radioshack.com/2013/01/radioshack-camera-shield-for-arduino-boards/

Yes, I expect you can use radio shack's serial, digital interface camera to record stills to a card, even slowly with an Uno, and have allowed for such modules in my explanation.  But this question is not about radio shack's module, and radio shack's module does not suggest any reasonable means of interfacing the analog camera which this is about.

There is an ANALOG camera on the freeking board, do you not get that!?

The connection from the camera to the other IC is, in fact, digital, not analog.  The other IC then sends but cannot receive a composite output for external consumers.  That RS board is not the topic of this question anyway - if you have concerns about it, post your own question.

Regardless, at some point, with EVERY camera, there is a CMOS or CCD sending an analog signal. You can figure out how that's done and you can do whatever you want at that point. I'm sorry if you don't like that, but it's a fact.

@Jasmine - when that is done within the "camera" chip such that the analog signal is not exposed and not read by anything else on the board (unlike you, I read the actual IC data sheets to determine this fact), it's not in any way helpful for someone such as the poster trying to work with a camera which has only an analog output.  What you presented has possible merit as a complete alternative, but it is not a solution which would make the answer to the question actually asked "yes".

Thank you. I can't stand it when people say something can't be done when they are looking at a device that does it.

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


text:
Manual TCP connection using WiFi ESP8266 module mistyped command
The command is working fine if I type it directly to the serial interface
AT+CIPSTART="TCP","192.168.1.5",1647

But if I want to make it automatic and send it whenever I want from inside the code is not working at all.
Used this but it's not working (Serial1 is from the hardware sp)
Serial1.println("AT+CIPSTART="TCP","192.168.1.5",1647")

Any way to arrange the data?

You need to escape your quotes:
Serial1.println("AT+CIPSTART=\"TCP\",\"192.168.1.5\",1647");

Man that was fast! Thanks Majenko it worked perfectly!


text:
Does the SIM800L works in the US?
I want to know if the SIM800L works on US soil? I can´t get it to work on the H2O network! Does it work wit ATT or I only need the APN settings? If so what are the commands for data connection and configuration? Does the SIM800C works then?

I wanted to post an update in April 2021 on the status of this question.
The SIM800L will work in the US, but T-Mobile is the only carrier that it can interface with. AT&T shut down its compatible towers in 2017. T-mobile will shut down its 2G network at the end of 2022.
So, the SIM800L is only good for another year and a half. Maybe you're better off finding a different module!

Both SIM800C and SIM800L (you mention both modules in your question) are compatible with the US GSM networks. It is not possible for me to tell if H2O or AT&T have GSM coverage whereever you are trying to use the module. AT&T is planning to shut down their GSM network by the end of 2016. If you issue the AT+COPS=? command, the module will list all available networks at your location.
Documentation on the commands required to handle voice calls, SMS or internet connections can be found in the 'SIM800 Series AT Command
Manual'.

Is that so... Then I should be moving to CDMA? or is there another network available? What chip could be useful? I´m planning to deploy this in a long term! Btw I did search for all available networks but none of them appeared and the signal was low or none existent! Why? No GSM/GPRS? I activated both
I appreciate your help!

Why don't you simply do a network search with a regular cell phone? It will list which operators and which network types are available where you are. There are plenty of cellular modems for 3G and 4G networks as well, but they are quite a bit more expensive than the GSM modules.

Well there are plenty of networks around and I can confirm that H2O use AT&T network towers and the GSM network is present on all carriers. I saw that GPRS with 3g is available too but to my understanding it´s part of the GSM network, right?
I saw different types of connections around the web... Do I need to use the reset pin? And what is the DTR pin? I got a battery at 3.7v with 2000mA connected so there is no problem with the ESD function of the chip

Does the SIM800L supports 3g? I mean from what I saw it does support 3g

As far as I know 2G and 3G is still around however ATT and Verizon are not taking on anymore subscribers for 2G and 3G. However you might still could use a 3rd party such as ting.


text:
What does "Update of OCR1x at" mean in the WGM table of ATMEGA328?
I just finished a reading a couple of online guides on how to use timer registers with pulse width modulation, so I'm still new to its concept.  When I looked in the ATMEGA328 specification sheet, I see this table:

The column that I'm not completely clear on is the "Update of OCR1x at".  I circled row 14 as an example.  If you're operating in mode 14 (ie. setting WGM 13, 12 and 11 to high), then you'll be in Fast PWM.  By setting a value for ICR1, you are effectively setting the TOP value, which will control the period of the pulse waves.  And the overflow flag on the timer will be set when the timer reaches the TOP value.
So does "Update of OCR1x at" mean that only when when the pulse wave form has reached the value of BOTTOM (or the end of a period), that's when the value of OCR1x will be passed on to the OCx pins if COMx bits are set?

The pwm can be changed while it is running. You may write a new value to the OCR1x register without stopping the pwm. That could cause glitches, so it is double buffered. The "update" is when the new value (written by you) is set into the OCR1x register. I don't know how that effects the pwm output, but apparently they have thought this through and have decided which moment is the best.

look for a  diagram  in the datasheet that shows a graphical representation of a sawtooth waveform

So does "Update of OCR1x at" mean that only when when the pulse wave form has reached the value of BOTTOM (or the end of a period), that's when the value of OCR1x will be passed on to the OCx pins...

Yes, that's what it means. To prevent glitches in the PWM output, you frequently do NOT want the PWM waveform to change immediately the instant you update an OCR1A value, for instance, to change the PWM output on output pin A. So, the PWM value you set is double-buffered and only updates the inner buffer used by the output pins once it finishes its current PWM period and reaches the BOTTOM value again, which would be a counter value of 0 in this case. Now, by allowing a previous PWM period to finish before the hardware reads the latest value from the OCR1A/B register (outer buffer) to its inner buffer (which inner buffer actually determines the pin state), you have a nice, clean, glitch-free PWM transition from one value to the next regardless of when you updated the OCR1A or OCR1B output register.