text:
ESP8266 - error after board update to 3.1.1
I'm using a Ubuntu 22.04 and Arduino IDE 1.8.19 for my ESP8266 Projects.
Yesterday I upgraded to 3.1.1 (using board library manager), and right after that - I got the following message (few seconds after compilation start):
Traceback (most recent call last):
  File "/home/guy/snap/arduino/85/.arduino15/packages/esp8266/hardware/esp8266/3.1.1/tools/mkbuildoptglobals.py", line 846, in <module>
    sys.exit(main())
  File "/home/guy/snap/arduino/85/.arduino15/packages/esp8266/hardware/esp8266/3.1.1/tools/mkbuildoptglobals.py", line 759, in main
    if time.time_ns() < os.stat(commonhfile_fqfn).st_mtime_ns:
AttributeError: module 'time' has no attribute 'time_ns'
exit status 1
Error compiling for board LOLIN(WEMOS) D1 R2 & mini.

Steps done to find the reason:

Empty Sketch - occurs.
Any other ESP8266 board - occurs.
Going back to prior version, 3.1.0 - occurs.
Going back to 3.0.2 - OK!
Checking 3.1.1 on Mac, same IDE version - OK!

Any ideas why ?
Am I the only one ?
Guy

The error tells you, that the time.time_ns() python function does not exist. This function was added to the python time lib with Python3 version 3.7. The most likely scenario I can imagin here is, that a python 3.6 or lower version is installed on your ubuntu and therefor the board software does not find the requiered function. Open a terminal and enter python --version or python3 --version, and make sure you have at least python V 3.7 installed. I would recommend to install 3.10+ to have the newest version and avoid missing other libs and language features.

@PeterPaulKiefer Typing guy@linux:~$ python3 --version returned
Python 3.10.6

i have the same problem
Ubuntu 22.04
IDE 1.8.19
Python 3.10.6
Error occurs after upgrading board esp8266 to 3.1.1

Sorry for my late answer. You installed the Arduino IDE with snap?!  It is possible, that Snap has its own python dependencies. I often had such problems when using snap instead of installing the software with apt or manually with a tarball. Now I always install Arduino using the tarball. There are many doc in the internet, here is one example: https://linuxopsys.com/topics/install-arduino-ide-on-ubuntu-20-04

@PeterPaulKiefer yes, from Snap

I had the same problem, although having python 3.8 installed, and I also installed Arduino through Snap. After removing the Snap installation and installing the one from arduino's website (the .AppImage file) - the issue with time_ns went away. Tnx@PeterPaulKiefer. You transform your comment into an answer and I'd gladly vote for it.

@PeterPaulKiefer please post it as an answer

The error tells you, that the time.time_ns() python function does not exist. This function was added to the python time lib with Python3 version 3.7.
The most likely scenario I can imagin here is, that a python 3.6 or lower version is installed on your ubuntu and therefore the board software does not find the required function.
Depending on how the ARDUINO IDE is configured, the globally installed python or a special installation of python is used. We dicussed these two possibilities in the chat and realized that in your case, snap installs its own dependency of python. I assume that the version of this python was below 3.7 and therefore the plugin was unable to find the required time function.
If the Arduino IDe would have been depent on the global python installation, it would have been enough to install a newer python (e.g. 3.10+) globally.
In you case (dependency defined by snap), the only solution I have, is to install the IDE not with snap but with the manual installation or by using apt. There are instruction in the internet like https://www.computingpost.com/how-to-install-arduino-ide-on-ubuntu-22-04-lts/.
Please check the comment of @userfuser (about usíng an .AppImage file) in the dicussion below the question also.

My symptoms are exactly the same.
Following uses of snap for installation or Arduino 1.8.19, I have found snap core recently updated core-18 from Ubuntu 22.04. The consequence since are drastic, starting with only Python 3.10, everything was almost working but I found the error inside mkbuildoptglobals.py inside the Arduino IDE output:
-----------------------
*** Traceback (most recent call last):
  File "/home/maxiste/snap/arduino/71/.arduino15/packages/esp8266/hardware/esp8266/3.1.2/tools/mkbuildoptglobals.py", line 831, in <module>
    rc = main()
  File "/home/maxiste/snap/arduino/71/.arduino15/packages/esp8266/hardware/esp8266/3.1.2/tools/mkbuildoptglobals.py", line 744, in main
    from time import time_ns
ImportError: cannot import name 'time_ns'
-----------------------

Adding a few lines inside the Python code to allow having an output to see. The surprise tell Python 3.6 and not 3.10, so mkbuildoptglobals.py stops.
Here is the sample starting line 200:
if PYTHON_REQUIRES[0] < int(sys.version_info[0]) :
    raise SystemExit(f"{__file__}\nMinimal supported version of Python is {PYTHON_REQUIRES[0]}")
elif PYTHON_REQUIRES[1] > int(sys.version_info[1]) :
    raise SystemExit(f"{__file__}\nMajor version of Python required is {PYTHON_REQUIRES[0]}.{PYTHON_REQUIRES[1]}, your version {sys.version_info[0]}.{sys.version_info[1]}.\n")
else:
    from sys import stdout
    sys.stdout.write(f"\nArduino Board project use Python version {sys.version_info[0]}.{sys.version_info[1]}\n\n")
    pass

And it shows me also a Python 3.6 and searching inside snap path of your home you should find:
/snap/gnome-3-28-1804/199/usr/bin/python3.6
/snap/gnome-3-28-1804/199/usr/share/binfmts/python3.6
/snap/gnome-3-28-1804/199/usr/share/lintian/overrides/python3.6
/snap/core18/2810/usr/bin/python3.6
/snap/core18/2810/usr/share/binfmts/python3.6
/snap/core18/2810/usr/share/lintian/overrides/python3.6

In my case it's update of gnome-3-28 and updating core18 from snap that push and under version of Python for Arduino.
And what is worse, for all those are trying Ubuntu 22.04, it automatically updates components in snap without touching it. I have even Chromium updating to a version automatically and left the compatibility with TASMOTA and package for esp-s2/s3, rsp-c3 and esp32 also.
The rest to help to pass the pill I do have to change platform.txt with following hack:

As one line of recipe tell information about uses of Python here what change back to point on your Python3.10 .

recipe.hooks.sketch.prebuild.pattern="{runtime.tools.python3.path}/python3" -I "{runtime.tools.signing}" --mode header --publickey "{build.source.path}/public.key" --out "{build.path}/core/Updater_Signing.h"

and where you found
{runtime.tools.python3.path}/python3

you change it for
{runtime.tools.python3.path}/../../../../../usr/bin/python3.10

Where my snap root is: /snap/gnome-3-28-1804/199/usr/bin and all runtime application from Arduino had moved here.
So it's matter of recipe and wrong draw back from Ubuntu.


text:
Doest a local struct variable get destroyed?
For a RF project I need to split payload for a max predefined chunk size.
For that I created a RFmsg struct.
The unexplained part I need help in is why when I create a local instance  of RFmsg, its contents are remain in tact after function is recalled? is it a struct "thing"? or something else I'm missing ?
To solve that I know that wiping struct content after initiating will solve that, but I'm want to be sure.
for that I share a minimal code that:

void newMSG(char *msg) simulates the splitting part of a long msg input.
void printStrcut_content(RFmsg &_payload) prints struct's content.
output show that only after boot, its content are gibberish, but after that, it shows the content of last struct update.

CODE:
#include <Arduino.h>
#define MSG_LEN 10
#define DEVNAME_LEN 8

char *devName = "TEST";

struct RFmsg
{
    int msg_num;
    int tot_msgs;
    int tot_len;
    char payload[MSG_LEN];
    char dev_name[DEVNAME_LEN];
};

void newMSG(char *msg)
{
    RFmsg _payload;
    printStrcut_content(_payload);

    _payload.tot_len = strlen(msg);
    strcpy(_payload.dev_name, devName);
    _payload.tot_msgs = (int)(_payload.tot_len / MSG_LEN);

    if (_payload.tot_len % MSG_LEN > 0)
    {
        _payload.tot_msgs++;
    }

    for (uint8_t i = 0; i < _payload.tot_msgs; i++)
    {
        strcpy(_payload.payload, "");
        for (uint8_t n = 0; n < MSG_LEN; n++)
        {
            _payload.payload[n] = (char)msg[n + i * MSG_LEN];
        }
        _payload.payload[MSG_LEN] = '\0';

        Serial.print("chunk #");
        Serial.print(i);
        Serial.print(": ");
        Serial.println(_payload.payload);
    }
}
void printStrcut_content(RFmsg &_payload)
{
    Serial.print("LEN: ");
    Serial.println(_payload.tot_len);
    Serial.print("PAyLOAD: ");
    Serial.println(_payload.payload);
    Serial.print("name: ");
    Serial.println(_payload.dev_name);
    Serial.print("tot_msgs: ");
    Serial.println(_payload.tot_msgs);
}

void setup()
{
    Serial.begin(115200);
    while (!Serial)
        ;
    Serial.println("\nStart");
}
void loop()
{
    newMSG("1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    delay(5000);
}

OUTPUT:
Start
LEN: 36
PAyLOAD: UVWXYZ
name:
tot_msgs: 4
chunk #0: 1234567890
chunk #1: ABCDEFGHIJ
chunk #2: KLMNOPQRST
chunk #3: UVWXYZ
LEN: 36
PAyLOAD: UVWXYZ
name:
tot_msgs: 4
chunk #0: 1234567890
chunk #1: ABCDEFGHIJ
chunk #2: KLMNOPQRST
chunk #3: UVWXYZ
LEN: 36
PAyLOAD: UVWXYZ
name:
tot_msgs: 4
chunk #0: 1234567890
chunk #1: ABCDEFGHIJ
chunk #2: KLMNOPQRST
chunk #3: UVWXYZ

I also would guess that the struct just always lands on the same memory space, thus retaining the value. Though you cannot count on that. You don't have any control over that.

@Juraj since it is a tiny part of much larger code, I was shocked to see this behavior repeats, at it was intentionally kept some how. what do you recommend ?

Just initialize the struct variable with known values at the start of your function. You just did see that behavior because you didn't do that. You should always initialize variables in functions. Only global variables get initialized implicitly.

As described in the comments: Your local struct variable probably always is placed in the same space in memory and this part of the memory isn't overwritten by your program. When declaring local variables they are not implicitly initialized (written with a value). If you don't initialize the variable yourself, its value will be whatever data is currently in that memory space.
The compiler optimizes your code and also decides on where to place variables on the stack. In this case it is always placed at the same memory space, but you cannot count on that. It is undefined behavior and any change to your program can also change that fact. And you don't have any control over that.
This is the reason, why you should always initialize local variables before reading them.

what do you recommend ?

Just initialize the members of that struct variable before using them. Set all members to a value. You can even do that in one step together with declaring it:
RFmsg _payload = {1, 2, 3, "payload", "devname"};

Just to clarify, undefined behaviour does not necessarily mean there will be zeroes there or any specific thing at all. And under certain circumstances what is there might be the same thing that was there the previous time the function was called. If you decide to not bother initialising variables because "it seemed to work last time" you will eventually find that a change to your code will come back to bite you.

source: Stack Exchange

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

sort: votes


text:
Arduino - Push Button State Problem
My problem is I want the buzzer to stop after a certain amount of time, regardless if it is still pressed or not.
I have tried to implement a boolean statement to the code but to no avail(I'm not very good at this)
Can someone shed some light as to how I do this?
The code already times out after 1000ms when your finger is lifted off the buttin so I got that far but cant get any further.
Here is what I have.
Any other suggestions are also welcome as I know its not the prettiest or best implemented but i was just happy it worked for me.
// Setting The Pin Numbers
const int touchsensor = 2;                      // the number of the touchsensor pin
const int buzzer =  4;                          // the number of the LED pin

// variables:
int touchsensorState = 0;                       // variable for reading the
touchsensor status
unsigned long timestamp = 0;
unsigned long timeout = 1000;

void setup() {

  pinMode(buzzer, OUTPUT);                      // initialize the buzzer as an output
  pinMode(touchsensor, INPUT);                  // initialize the touchsensor as an input
 }
void loop() {

   touchsensorState = digitalRead(touchsensor);  // read state of the pushbutton value:

   if (touchsensorState == HIGH) {                 // check if the touch sensor is pressed. If it is, the touchsensorState is HIGH:
     digitalWrite(buzzer, HIGH);                 // buzzer will emit sound:
     timestamp = millis();                       // Timing button press
   }

   if(millis() - timestamp > timeout) {
   digitalWrite(buzzer, LOW);                  // buzzer will not sound:
   }
}

you will need to implement a edge sensor. Add a previousTouchsensorState to the globals and replace the if where you check the sensor state with:
if(previousTouchsensorState == LOW && touchsensorState == HIGH) {
     // check if the touch sensor is pressed and wasn't the last time though the loop.
     // If it is, the touchsensorState is HIGH and previousTouchsensorState is LOW:
     digitalWrite(buzzer, HIGH); // buzzer will emit sound:
     timestamp = millis();       // Timing button press
}
previousTouchsensorState  = touchsensorState;

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


text:
How can i check for valid fingerprint and no finger detected?
i am working in arduino fingerprint sensor with adafruit. i am using two leds to check if fingerprint is valid. my problem is that i need three cases instead of two.
1 case: when fingerprint is valid. turn on green led and turn off red led.
2 case: when fingerprint is not valid. turn on red led and turn off green led. i put a finger but was a not valid finger.
3 case: when there is no finger detected, turn off both leds.
Is there a way to do that?
i am using adafruit library and fingerprint sensor, with fingerprint.ino and using pin 11 and 12 for output.

it is unclear what you are asking ... are you asking about turning on LEDs? ... or are you asking about reading fingerprints? ... the two things are not really related at all

When there is no finger on the sensor, the function Adafruit_Fingerprint.getImage() from the Adafruit Fingerprint library returns the constant FINGERPRINT_NOFINGER. You can execute the function in a loop and setting the LED outputs in a switch statement according to the return value. Refer to the examples of the Adafruit Fingerprint Sensor Library. There you have directly the code for checking the sensor (since the full check for a valid fingerprint is longer than this one function call, you can use the getFingerprintIDez() function from the fingerprint example, or a variation of it).

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


text:
Getting 3.3v on 5v pin in Arduino Uno
When interfacing my Arduino Uno with a relay I was facing reliability issues, and while investigating it with a multimeter, I found something strange.
I noticed that in the 5V power pin (with which I was powering my circuit) is producing only 3.3V when using the power adapter. However, when connected via the USB-A port, the 5V pin was producing the expected 5V voltage.
I tried powering it in many ways - computer-to-USB-A, computer-to-barrel-jack, phone-charger-to-USB-A, phone-charger-to-barrel-jack and an external 5V DC power supply. In all cases, the above observation held true - powering the board through the barrel jack made the 5V power pins produce only 3.3V.
Question: Why is this happening? Does that mean my board is faulty? Is there any way to fix this?

What voltage are you putting into the barrel jack? Is it 5V?

Yes, I'm using a 5V barrel jack power input - in one trial from a phone charger, and in another trial from a computer's USB output. I measured it with a multimeter and checked that it is indeed 5V.

and an external 5V DC power supply

OK, assuming you are putting 5V into the barrel jack this is exactly what you expect to happen.
From the Arduino Uno specifications you are supposed to supply a recommended 7V to 12V. Your supply of 5V is too low.
The barrel jack first goes through a M7 protection diode which would have about a 0.7V forward voltage drop, and then through a NCP1117ST50T3G voltage regulator which has a dropout voltage of (typically) 0.95V at 100 mA.
Thus you have:
5V input - 0.7V - 0.95V = 3.35V

That is what you are finding.

Solutions

If you have a proper, regulated, 5V DC supply you can put that directly onto the 5V pin of the Arduino. Better get the wires around the right way because you are bypassing the protection diode!
Get a DC supply in the range 7V to 12V and put that into the barrel jack.
Another simple idea is to just get a wall-wart that is used for charging phones via USB and run a USB cable into the Arduino USB port.

Empirical test
I put 5V into the barrel jack of my Uno and read 3.33V on the 5V pin, which is pretty-much what you got. I measured a 0.77V drop over the M7 diode.

Thanks for explaining this. Indeed my barrel jack input is 5V, and I forgot that the input needs to be 7V to 12V. I'll change the barrel jack input to a 7V input. But I'd like to learn more... could you please talk more about how I can built a "properly regulated 5V DC power supply" from 4 AA batteries? Some starting links would help - I'll dig into it more.

Tempted as I am to amend my answer to respond to this, I think this is a whole new (and quite interesting) question. If you would be kind enough to make a new question out of it then I'm sure you'll get some interesting responses. Possibly one of them would be that this is purely an electronics question, and not an Arduino one, but we can only hope that people don't do that. :)

For example, make a question along the lines of: how I can built a properly regulated 5V DC power supply for my Arduino Uno from batteries? Answers might then discuss one battery, two batteries, four batteries, a 12V car battery, a LiPo batttery, etc.

While Nick's answer is 100% (technically) correct.
Functionally, it's a much easier story (given you feed 5V into the barrel jack).
Check the Arduino's product page.
Microcontroller ATmega328P
Operating Voltage   5V
Input Voltage (recommended) 7-12V

So yes, while the Arduino runs on 5V (and does so over USB). The recommended input voltage is 7-12V. You're simply not supplying a high enough voltage.
The difference, as per Nick's answer, is the protection circuit and regulator snooping off a few volts (which is bypassed when using USB).


text:
Ring topology by using arduino and Bluetooth
I want to connect Bluetooth in a circular ring is it possible to contect 8 arduino with each other via Bluetooth hc05 or hc06  and share data into tha ring..

Its probably possible, but I don't think it would be a good idea.
Each Arduino is going to have to forward information it receives that is not for it.  This is a drain on processing power.  Add to that you are going to need to give the devices an identity, so they know what data is for them, and a inform them of the topology of the network so they know how to connect to the adjacent nodes.
Depending on what problem you are trying to solve you might want to look at direct radio coms implementing a mesh network, or the simplest of all solutions Wifi.  You could use an ESP8266 to form an access point and others to connect to it.  I believe there might be a limit to the number of connections an ESP8266 can have at any one time but this could be mitigated by dropping the connection after the message has been sent.

Every arduino needs two HC05 since it's only BT 3.0.
A BT 4.1 or 4.2 can pair multiple devices, only one BT hardware is needed.


text:
Arduino HC-SR04 water experiment
I am working on an experiment with the HC-SR04 sound sensor, and i am using it to record the speed of sound. I successfully measured the speed of sound in air, but when measuring it in water, I encountered a small problem. The sound waves emitted by the sensor are both absorbed and reflected off the water. Obviously, the reflected sound waves are the first ones to reach the sensor, and therefore are the ones used for calculating the speed of sound. Is there a way to code the Arduino program in order to ignore the first set of waves and only record the set of waves that were absorbed by the water? I was thinking of increasing the delay time for the pulse, but I'm not sure that would work.
Thanks.

Are you submerging your HC-SR04?

I am not, I'm signaling from outside the water, and thats why the wave is reflected back. I believe if I submerged it, it would work, but I cant find a way of submerging it without breaking it.

All you need to do is ignore any reading within the first  milliseconds.  Off the top of my head there is a delay statement before reading from this sensor, just alter that.  You can work out how long it needs to be by working out how fast sound waves travel through the air and measuring the distance between the sensor and the source of the reflection.  I think you might know how to do that :)


text:
Where is CLKPR located on Ubuntu 16.04 with Arduino 1.8.3
I would like to see the definition of CLKPR. I guess that similarly to PORTB and other registers, it should be defined by the toolchain? (see Where is PORTB defined? )

Am I right?
Where should I look for this toolchain on Ubuntu 16.04? I tried locate and find commands in terminal with various strings relating to the toolchain expected path / files, but could not find it (tips and tricks on how I may look for such paths in the future would be welcome ;) ).

grep is the command you want:
foo@bar:~/arduino-1.8.2$ grep -r CLKPR .
Binary file ./hardware/tools/avr/avr/lib/avr35/crtattiny167.o matches
Binary file ./hardware/tools/avr/avr/lib/avr35/crtat90usb82.o matches
Binary file ./hardware/tools/avr/avr/lib/avr35/crtatmega8u2.o matches
...
Binary file ./hardware/tools/avr/avr/lib/avr5/crtat90pwm161.o matches
Binary file ./hardware/tools/avr/avr/lib/avr5/crtatmega649p.o matches
Binary file ./hardware/tools/avr/avr/lib/avr5/crtatmega168pa.o matches
./hardware/tools/avr/avr/include/avr/io90pwm216.h:#define CLKPR   _SFR_MEM8(0x61)
./hardware/tools/avr/avr/include/avr/iom329.h:#define CLKPR   _SFR_MEM8(0x61)
./hardware/tools/avr/avr/include/avr/iom165p.h:#define CLKPR   _SFR_MEM8(0x61)
...
./hardware/tools/avr/avr/include/avr/iom48p.h:#define CLKPR _SFR_MEM8(0x61)
./hardware/tools/avr/avr/include/avr/iom644pa.h:#define CLKPR _SFR_MEM8(0x61)
./hardware/tools/avr/avr/include/avr/ioa6289.h:#define CLKPR _SFR_IO8(0x3C)
./hardware/arduino/avr/bootloaders/caterina-Arduino_Robot/Caterina.h:       #define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n))
./hardware/arduino/avr/bootloaders/caterina-LilyPadUSB/Caterina.h:      #define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n))
./hardware/arduino/avr/bootloaders/caterina/Caterina.h:     #define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n))

So it's defined in the IO header for the chip you are using (hardware/tools/avr/avr/include/avr/io[chip].h). So for the '328p that's hardware/tools/avr/avr/include/avr/iom328p.h.

This is great, thank you! A couple of noobs questions: -1: this is not the toolchain, isn t it? -2: so for an Arduino Mega 1280, I should look at iom1280.h isn t it? But there is no CLKPR in it (grep CLKPR iom1280.h returns nothing while in the right folder), while I am quite sure it is also called CLKPR for the 1280 (I checked in the datasheet). Where is CLKPR defined for the Mega then?

Yes, that is the toolchain. It will be in that file, but it may be called something else. Edit the file and browse through it.

iom1280.h includes the standard file iomxx0_1.h.  That defines CLKPR as _SFR_MEM8(0x61).


text:
How to add prefactor to clock frequency at compile time?
I want to use an Arduino Mega at 8MHz because my power supply is bad and I have only 4.3V (no way I can fix that), which is outside the operation range of the ATMega1280 at 16MHz. I think the right way to do it is to put a pre-factor 2 on CLKPR (tell me if I am wrong)? I know that several pages explain how to do so in a sketch: see How can you reduce the clock frequency of an Arduino Mega? , https://playground.arduino.cc/Code/Prescaler .
However, both those methods reduce the Mega frequency at run time, by setting the CLKPR register during the setup loop or another function, mess up with the millis(), delay(), Serial etc, and in addition I guess this means that the Mega is running at an out-of-spec 16MHz until the prefactor is set in the setup loop (?). So my question (I searched for it but found no answer) is:

Can one set the clock prefactor at compile time, so that:

the compiler knows about it,
the millis(), delay(), Serial and similar are not disturbed
the register is set immediately at boot (i.e. no need to change the registers in the setup)

?

1 and 3 can be solved by putting it in one of the initialization sections. 2 can be solved by creating and using a board.txt entry with the appropriate FCPU.
#include <avr/power.h>

void __attribute__((naked, section(".init1"))) preprescale(void)
{
  clock_prescale_set(clock_div_2);
}

avr-gcc 4.9.2 tells me “error: attributes are not allowed on a
function-definition”. I took the liberty to edit your code into a form
that this version of gcc accepts. 2. I would normally use .init3 for
that, but it appears that clock_prescale_set() does not rely on r1
being zero, so init1 is fine.

@EdgarBonet: Thank you for fixing it, it's been a while since I've had to actually do this.

Clock speed is controlled by fuse settings and as such can be set at compile time - whether that will conflict with your bootloader is anyone's guess.
Gcc-avr allows fuse settings but you will need to burn it separately. F_CPU needs to be changed accordingly.

All the CKDIV8 fuse does though is start with the prescaler at /8 instead of /1.


text:
Why UDP does not work after analogRead() on esp8266-12N module?
Consider my loop() in Arduino be:
void loop(){
  for(int i = 0; i<100; i++){
   Value[i] = analogRead(A0);
   delayMicroseconds(62);
  }
   //delay(2) //when I use this line esp8266 works properly
   Udp.beginPacket(IP, Port);
   Udp.write(Value, 100);
   Udp.endPacket();
}

after analogRead() UDP can't send packets and crash occur after a moment. But when I use delay(2) line in the above code it works properly. I want to record samples of microphone with 16000 sample rate and I use 62 microseconds for this. Thus in my application it is not possible for delay 2 milliseconds. How can I fix this without delay?

hard use of A0 disturbs WiFi signal measuring done by SDK with the same ADC. use external ADC for continues measurement with esp8266

Thank you for replying.

+1 for the excellent answer Juraj. I did not know that hard use of the ADC would cause issues with the WiFi signal :)

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


text:
Using MPU-6050 without I2C
My target is to use multiple MPU-6050 at once, I searched on the internet and found that they can be hooked up really simply. Just connect in parallel and use I2C-Scanner. Then get those addresses and use normally.
But I can't find another address, there appears to be just one address 0x68, that is the reason why, I want to connect my other MPU-6050 in other pins.
How this can be achieved ?

The MPU-6050 has 1 pin to change 1 bit of the address. Means, that you can connect 2 MPU-6050 to the same I2C bus.

How, can you describe ?? Please

from datasheet "the address of the one of the devices should be b1101000 (pin AD0 is logic low) and the address of the other should be b1101001 (pin AD0 is logic high)"

As you can read in the MPU-6050's datasheet, it uses the I2C address 0b110100X, where X is the state of the pin AD0. If you wire AD0 to ground, the address will be 0b1101000, whereas if you wire it to Vcc it will be 0b1101001. That is equivalent to the addresses 0x68 and 0x69.
That means, that - depending on how you wire AD0 - you can have 2 distinct MPU-6050's on the same I2C bus (you cannot have devices with the same address).
If you really need to connect more than 2 of them, you have to use an I2C multiplexer like PCA9544A, which will divide the bus down to sub-busses.

EDIT: Usually the address pins of I2C devices are set permanently by wiring them either to ground or Vcc. The sense of the address system is, that a slave device will stay at it's address, not changing it. But as Jot reported in the comments and as the Arduino Playground site of the MPU-6050 confirms, you can actually set the address pin of the MPU-6050 during operation.
You need 1 digital output pin on your Uno for each MPU, which then get's tied to the MPU's AD0 pin via a voltage divider. The last part is important: You need a voltage divider, because the MPU is a 3.3V device, while the Uno works with 5V. To avoid frying the address pin, you need to step down the voltage.
Then you would use the address pins to set all MPU's to one address (let's say 0x69). When you need to communicate with one of them, you toggle it's address pin, which will change it's address (in this case to 0x68). Then you can use the normal I2C workflow with this address (0x68). When you are done, you can put this MPU back to the other address by again toggling the address pin. You can repeat this with any of the connected MPU's, which can be many (I think the limit here is the I2C bus itself with it's wires capacity).
This is a workaround and not really, what the I2C bus is meant for. But it seems to be valid solution. Just be sure, that the addresses, that you communicate with, are always unique. Contacting an address, which belongs to more than 1 device, will block your I2C bus.

It means, using a loop toggling value of AD0, I can access both ?

I don't think, that the MPU continously checks AD0, but that it checks it at power on. (Though I didn't found that clearly in the datasheet) That means, that you cannot change the address without power cycling the MPU. Either way, you won't be able to address more than 2 MPU's on the same bus.

@chrisl I have read somewhere that AD0 is used runtime. It is possible to have many mpu6050 sensors and select them one by one via its AD0 pin (keep them at 0x69 and use one at 0x68). This can not be done with an arduino uno, since a pin with 5v would blow the mpu6050 via the AD0 pin.

@Jot Can you maybe remember, where you read that? Would be good to have some reference for that.

For example here: https://forum.arduino.cc/index.php?topic=545257.msg3716437#msg3716437 I have not tested it myself.

This solution is also being reported as working at the Arduino Playground site of the MPU-6050. I will add that to my answer tomorrow.

You can connect more than 2 in serial by using the Address bit like a chip select.
Say you had 8 of them. Use a shift register with the 8 outputs going to the 8 chips. Now output 0b00000001 and use I2C address 0x69, only the one device with a 1 on its address line will reply. Then use 0b00000010 for the 2nd device, 0b00000100 for the 3d, etc. up to 0b10000000 for the 8th.


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

check the datasheet

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

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


text:
Calling class member from .h file
In .ino file I have a class defined (called IPmonitoring).Also, inside the same .ino file, I call a .h file ( which is located "above" class IPmonotoring).
When I try to call members of IPmonitoring inside .h file - I get an error, which usually I solve using extern, but seemingly it is not the same for classes.
What should be done ?
Guy

the class definition is then not included in the .h file. So normally you would define that class in another .h file and then let the first .h file include the second .h file with the class definition.

I don't know what you mean by "call a .h file."  You mean #include it?

You should not have code in a .h file unless it's inline or a template class.

@timemage - yes

You need to re-think your layout, and your usage of the .h file.

You should never have code in a .h file unless it is either inline or part of a template class.

A .h file should only contain hints about where other things are. Those things should then be in .cpp or .ino files.
For example your IPmonitoring class would be declared in a .h file, and defined (or implemented) in a .cpp file (or .ino file if you prefer). Any place you want to use that class you #include the .h file. In one place you may choose to create an instance of that class. It is that instance that you then reference with extern.
In the Arduino world it is common to create a single instance of the class in the class's .cpp file and extern it in the .h file so everywhere that you include the .h file instantly has access to that single instance of the object.
This is how most libraries are written.
For example:
// IPMonitoring.h

class IPMonitoring {
    public:
        void doStuff();
};

extern IPMonitoring ipMon;

And:
// IPMonitoring.cpp

#include <IPMonitoring.h>

IPMonitoring ipMon;

void IPMonitoring::doStuff() {
    // Do something
}

And finally:
// mySketch.ino

#include <IPMonitoring.h>

void setup() {
    ipMon.doSomething();
}

void loop() {
}

class templates are instantiated to create classes; likewise for function templates and functions.  The involvement of a template doesn't affect things beyond being an incentive to inline, since the export keyword never really took off and then was later removed from the standard.

Majenko  -Thank you. It all started as .ino file with functions. During writing the code I gathered all function into class, since I wanted 3 instances of it. And the .h file  gathers all the function I used for my wifi and MQTT of other class I'm constantly using... well thing started to get messy :)


text:
Connection Pro-Mini & ESP8266 using Serial
I wish to create a system consists of WEMOS mini & Pro-Mini sharing info using Serial ( one MCU is dedicated to react input-output, and second for MQTT commands ) sharing same Power input. From what I read in tutorials, at boot Serial wires have to be disconnected, in order to accomplish boot.
A) is that true that at boot Serial has to be disconnected?
B) is there a way that 2 MCU can be connected at all times, including reboot when needed ( such as power failures ) ?

A) no B) no problem. why do you ask?

@Juraj since when I tried rebooting 2 MCUs connected in Serial ( Tx-> Rx , Rx->Tx ), failed. It succeeded only when wires removed

ground was connected?

@Juraj - Yes GND was connected

A) is that true that at boot Serial has to be disconnected?

No, that is not true. However if you are using Serial to communicate on the Pro Mini you will need to disconnect the ESP8266 in order to program the Pro Mini as it will interfere with serial communication to the PC.

B) is there a way that 2 MCU can be connected at all times, including reboot when needed ( such as power failures ) ?

Given that A) is a no, then B) is irrelevant. It will just boot.
The only caveat is that the ESP8266 will squirt some boot messages out of serial as it boots at 74880 baud, so you have to be able to cope with that noise in whatever protocol you design between the two boards.

Perhaps your first sentence was what I recalled when disconnecting the wires was needed. Regarding Serial "noise" - you are right... some maneuvers were done to overcome ESP8266 boots

A) is that true that at boot Serial has to be disconnected?

Not exactly, if you're careful about what is communicating with what and when.  That you protect against multiple things driving the same connection, etc.  And you don't mind being very confused a lot of the time.  And that you're holding one board in reset while the other is being programmed.

B) is there a way that 2 MCU can be connected at all times, including
reboot when needed ( such as power failures ) ?

If you don't have a compelling reason to avoid it, you may be better off using I2C between the two of them.  Then your serial is left alone on both boards to behave as it normally does.  You don't need to sort out conflicts between boards trying to use serial to talk to each other and trying to use their serial transceivers to talk to the host and the conclusion that results from the host and both boards all see traffic from different things.  And you have an open collector setup between your two boards which makes independently powering them somewhat less of a problem.
If you do try to use the Pro Mini and ESP8266 USARTs connected together, you should have some series resistance in the connection between the FTDI (or whatever) TX signal and the RX on the Pro Mini. Or between the Pro Mini RX and the WEMOS TX.  In other words, anywhere you have two pins driving what would otherwise by the same node in the circuit, you need some current limiting in case they drive in opposite directions, as will happen if you connect their serial connections together.  If you look at the Wemos D1 mini schematic or the Arduino UNO, Nano, etc schematics you'll see they've inserted some resistance there for that reason.  If you look at the Pro Mini schematic you'll see the FTDI TX line is connected directly to the AVR's RX.
Below you asked why you would need the FTDI connection.  If you're not programming the Pro Mini and not using it power the Pro Mini, then you don't.
However, if you're thinking you're going to be able to program the Pro Mini using the serial transceiver on the Wemos and the connection between them, that isn't going to work.  The Wemos serial transceiver's TX would be connected to its ESP8266's RX, which would be connected over to the Pro Mini's TX (not RX) because project is operating normally it needs to receive data from the Pro Mini on that pin.  Allowing the Wemos serial transceiver to talk to the Pro Mini's RX would require you to wire it in a way that the two boards couldn't use their USARTs to talk to each other.  The two usages are only compatible with two different wiring schemes.

I'm assuming your Pro-Mini is a 3.3V version.  If it's a 5V version you should really shouldn't be connecting its TX directly to the ESP8266.

A) I didn't think of using I2C.... How do I share text/JSON in such manner ?
B) Why Should FTDI is needed ? Can't I connect Tx/Rx directly ? ( on my test bench a Nano or Pro-Micro is used )

I2C doesn't care what you send over it.  The design of the Arduino Wire library is such that it needs to be broken up into small chunks.  I will try to address "Why Should FTDI" (to the extent that I understand it) in the answer.   Regarding "Can't I connect Tx/Rx directly": in the general case you don't connect 5V and 3.3V signals directly together,  particularly not a 5V output to a 3.3V input; sometimes you can do that, not always.  It's something you can write an entire chapter on.

Will consider using i2c : here's a tutorial https://www.instructables.com/I2C-between-Arduinos/


text:
Display upTime using `millis()` - Arduino Uno
I want to use the following function to display MCU's uptime, but after several hours I get error.
void uptime(char *ret_clk)
{
  byte days = 0;
  byte hours = 0;
  byte minutes = 0;
  byte seconds = 0;

  int sec2minutes = 60;
  int sec2hours = (sec2minutes * 60);
  int sec2days = (sec2hours * 24);

  unsigned long time_delta = millis() / 1000UL;

  days = (int)(time_delta / sec2days);
  hours = (int)((time_delta - days * sec2days) / sec2hours);
  minutes = (int)((time_delta - days * sec2days - hours * sec2hours) / sec2minutes);
  seconds = (int)(time_delta - days * sec2days - hours * sec2hours - minutes * sec2minutes);

  sprintf(ret_clk, "%01dd %02d:%02d:%02d", days, hours, minutes, seconds);
}

after 2:55 hours I got a correct answer : 0d 02:55:27
also after 4 hours, a correct answer : 0d 04:06:44
but roughly after 12 hours i get an error: 1d 02:01:27
and after roughly 20 hours I get : 2d 23:74:26
What is wrong in uptime ?

On an 8-bit Arduino an int can only hold values in the range -32768 to +32767. One day's worth of seconds is 86400, which is far outside that range.
You should replace your sec2... variables with literals, maybe #defined - and don't forget to force the length for longer values:
#define SEC2MINUTES 60
#define SEC2HOURS 3600
#define SEC2DAYS 86400UL

what is the bennefit define it using #define ? whould define as usgined long save the problem ?

@Guy.D If you put it in a variable and use that variable to calculate other variables to do your calculations with it has to calculate them every single iteration. By using #define (or you could use const unsigned long if you wish) it calculates it at compile time (which I shortcut by just calculating it myself).

what might be that cause getting this result :upTime[0d 10:123:33] ? code was corrected as you suggested

The millis function increments rapidly, hence it easily exceeds the maximum value of int -  -32768 to +32767.
So, use unsigned long data types for millis and other stuff that's large.
4 billion and some change is the max value that unsigned long data types can store, hence no overflowing till about 49 days.


text:
Unexplained behavior of char array after using `deserializeJson`
I'm using RF24 library to send messages between 2 MCU's : 1) ESP8266 (no Wifi, same code can be compiled to any Arduino board) 2) pro-Micro.
Message is sent in JSON format, while using ArduinoJSON library to serialize and deserialize messages.
Altough entire code works as expected, I get an error in "RFread" function, which _readmsg array loses its content after using deserializeJson.
Attached below  relevant part of "RFread" function. Explanations in code below. Please notice "Mark [X]" in code and Serial output:
char _readmsg[32];                                <---- Storing input in this array
    char t2[32];                                  <---- variable to clone value
    radio.read(&_readmsg, sizeof(_readmsg));      <---- getting RF input and store it in `_readmsg`
    strcpy(t2, _readmsg);                         <---- cloning, part of error seeking

    Serial.print("first: ");                      <---- printing initial value stored. OK. marked [A] in Serial output
    Serial.println(_readmsg);
    Serial.print("duplicate: ");                  <---- printing clone. OK. marked [B] in Serial output
    Serial.println(t2);

    if (key != nullptr)                           <--- check if "msg" key was sent in message
    {
      StaticJsonDocument<80> DOC;
      deserializeJson(DOC, _readmsg);             <---- **error beyond this point**
      Serial.print("second: ");
      Serial.println(_readmsg);                   <---- printing wrong value. marked [C] in Serial output

      if (DOC.containsKey(key))
      {
        const char *outmsg = DOC[key];
        if (out != nullptr)
        {
          strcpy(out, outmsg);
          return true;
        }
      }
      else
      {
        Serial.print("third: ");
        Serial.println(_readmsg);              <---- still error. marked [D] in Serial output
        Serial.print("duplicate2: ");
        Serial.println(t2);                    <---- clone variable is OK. marked [E] in Serial output
        strcpy(out, t2); // if key not present, return entire message
        return 0;
      }

and in Serial port:
message sent OK   <---- irrelevant for debug

15:18:14.934 -> first: {"id":"Port","msg":"fff"}       <----[A]

15:18:14.934 -> duplicate: {"id":"Port","msg":"fff"}   <----[B]

15:18:14.934 -> second: id                             <----[C]

15:18:14.934 -> third: id                              <----[D]

15:18:14.934 -> duplicate2: {"id":"Port","msg":"fff"}  <----[E]

15:18:14.934 -> Error. no such key. got reply: {"id":"Port","msg":"fff"}

Is there a reason for that ? is it a bug ?

Please see: Why is the input modified?

Also, please check the error code returned by deserializeJson()

@BenoitBlanchon Error gets "OK"

When you pass a char* input to deserializeJson(), it alters the input to avoid making useless copies.
This is the "zero-copy" mode of ArduinoJson.
In this mode, the JSON parser modifies the input in-place. The following modifications are performed:

'\0' are inserted at the end of each string
Escaped special characters (like \n) are unescaped

Example:
char[] json = "{\"hello\":\"world\"}";
deserializeJson(doc, json);

After executing the line above, the input variable probably contains something like: "hello\0world\0".
You can find more details in the documentation

Thank you for your reply - I don't understand why _readmsg changes ( as a concept ). Whould you recommend to clone that variable as I did using t2 ?

To sum up Benoit Blanchon answer:
in original code:
deserializeJson(DOC, _readmsg);

changes to:
deserializeJson(DOC, (const char *)_readmsg);


text:
RS485 Serial Communication not working with Arduino
I am trying to control 2 devices with my arduino using RS485 communication.
Basically switch on device 1 for 5 seconds when I send 'g' to the master. And switch on device 2 for e3 seconds when I send 'h' to the master.
I have a similar setup working with delays in the code I cannot use delays in the final version.
Here is the code I am using -
Master -
#include<SoftwareSerial.h>

#define NL 10
#define CR 13

SoftwareSerial Serial1(10,11); //RX, TX

String inputString = "";         // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete
char prevChar = (char) 0;
char inChar = (char) 0;

void setup() {
  // put your setup code here, to run once:
  Serial1.begin(9600);
  Serial.begin(9600);
  pinMode(8, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  char getdata = 'm';
  digitalWrite(8, LOW);

  if (stringComplete) {
    Serial.println(inputString);
    inputString.trim();
    //Serial.println("abc");
    if (inputString.length() == 1 && inputString.charAt(0) == 'g')  {
      Serial.println("Starting laser 1.");
      digitalWrite(8, HIGH);
      Serial1.print('1');
      //Serial1.print('h');
      Serial1.print(CR);
      Serial1.print(NL);
      Serial1.flush();
      digitalWrite(8, LOW);
    }
    else if (inputString.length() == 1 && inputString.charAt(0) == 'h')  {
      Serial.println("Starting laser 2.");
      digitalWrite(8, HIGH);
      Serial1.print('2');
      //Serial1.print('h');
      Serial1.print(CR);
      Serial1.print(NL);
      Serial1.flush();
      digitalWrite(8, LOW);
    }
    inputString = "";
    stringComplete = false;
  }

  if (Serial1.available()) {
    while(Serial1.available() && getdata != '\n') {
      getdata = Serial1.read();
      Serial.print(getdata);
    }
    Serial.println("");
  }
}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    prevChar = inChar;
    inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    //Serial.println(inputString);
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n' && prevChar == '\r') {
      stringComplete = true;
    }
  }
}

Slave -
#include <TimerOne.h>

bool isLightOn = false;
int counter = 0;

int address = 2;

String inputString = "";         // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete
char prevChar = (char) 0;
char inChar = (char) 0;

void timerISR() {
  if (isLightOn) {
    counter = counter+1;
    if (counter >= 20) {
      counter = 0;
      isLightOn = false;
      digitalWrite(5, LOW);
      digitalWrite(13, LOW);
    }
  }
}

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

  Timer1.initialize(100000);
  Timer1.attachInterrupt(timerISR);

  pinMode(5, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(8, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  //digitalWrite(13, LOW);
  digitalWrite(8, LOW);
  if (stringComplete) {
    inputString.trim();
    //if (inputString.length() == 1 && inputString.toInt() == address) {
      isLightOn = true;
      digitalWrite(5, HIGH);
      digitalWrite(13, HIGH);
    //}
  }

  while (Serial.available()) {
    // get the new byte:
    prevChar = inChar;
    inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n' && prevChar == '\r') {
      stringComplete = true;
    }
  }
}
/*
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    prevChar = inChar;
    inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n' && prevChar == '\r') {
      stringComplete = true;
    }
  }
}
*/

My connections are something like this -

Master - Uno,
Slave 1 - Uno,
Slave 2 - Nano

Serial1.println("1"); sends "1\r\n". no need to print the characters separately. inputString = Serial.readStringUnil('\n'); reads all the input from Serial Monitor. but if you send only one character, why do you read into String?


text:
How can I make a data logging multimeter?(harvesting energy from human motion)
I’m an industrial design major working on a studio project that involves electronics that are kind of out of my league. I have a few low power generators like piezos, thermoelectric (peltier) tiles etc... In order to progress with my project I need a way to measure the output of each one individually when harvesting human motion. As far as I know, I need a multimeter to hook up directly to these devices, and then I think there may be a way to record the results with an arduino. My question is more about specifically how to do this, or even if this is a feasible plan. Are there any plans for this sort of thing already out there? Any feedback will be greatly appreciated!

If these electronics are out of your league, how would adding more electronics (Arduino) aid on achieving your goal?

I think using a regular multimeter (potentially with logging capacity) will be easier than making such a thing yourself...

I'd suggest starting with an oscilloscope. Use that to examine the patterns of signals you're getting from each sensor, and then you might need help from somebody with a decent understanding of analog circuit design to design circuits to measure the inputs from the various sensors.

you could use an INA219 to measure voltage with an ardunio, like a DMM but for voltage and current only.


text:
Push and hold on/off switch for arduino
Many electronic devices turn on/off, or more correctly on/sleep, by pressing a button and holding it for two or three seconds. I would like to put this ability into a project using an Adafruit Feather board.  The sleep side is easy, I can detect a level and if it stays there for some time, run the code to put the processor to sleep.  My question involves the wake up side. The chip wakes up via an interrupt.
The question then becomes, how do I generate the interrupt source only after the button has been held for the designated time? I've considered two options:
1) Use a level interrupt and an RC circuit to do the delay.
2) Have the processor wake up immediately and then implement logic to determine if it has been held "long enough" and go back to sleep if not.
Am I missing an easy option? Is there a general consensus on the best way to do this? It seems like such a normal thing that I'm surprised my searches haven't turned up any tutorials.

Can't you just wait for the button to be released, and then to go to sleep? You could even disable the interrupt while awake, on only turn it on, right before going to sleep.

The problem with that is that random bumps get treated as requests to sleep/wakeup.  Press and hold for "long enough" is very desirable.

Oh, you want to have press-and-hold, for wake-up as well. In that case, have the MCU wake up from sleep by the button; wait till the button is released; if it's less than 3 seconds, go back to sleep.

I would go for option 2.
You can wake up the controller immediately, but only the processor.
Then just start waiting for the "long enough" time that you defined, regulary checking the button state. If the button is still pushed, then initiate full wake up. If it is released, go back to sleep.
This is the easy option, requiring no extra hardware, and only a dozen of so of lines of code.
Another option, that exist and have a somewhat similar behaviour, is to have your processor wake up regulary on timer, and checking the state of the input. This is what is done for "radio controled" devices, for example (Where the "button" is a radio circuit that need to be switch on and off).
Given a sufficiently long sleep between check, on average you will get the "long enough" delay.
This option is useful when you don't have available interrupt pins, or you need something more complex that a button as the input.

Waking up would up the power consumption by a lot. The wake up frequency would have to be, oh probably 3x the button press time to be good for a human.

It would indeed not be the best option, but I wanted to include it for completness. As I said, if possible, go for the other one.


text:
Ultra Long Range (200-500km) Arduino Communication using a Gibson Girl
I came across this article on Hackaday showing a simple AM transmitter sending a morse code tone 700km!
I'm looking into a EPIRB for myself while deep in the bush / outback hunting or camping, just to send a message to my wife. (a true EPIRB wouldn't be useful to let her know I'm all good, or ask her to call my mate to come pull my truck out of a bog hole)
I plan on sending short text messages via Morse Code, or probably just 8 bit ascii - so speed is not important. If a 50 character message takes 5 minutes to send - so be it... It's meant for check ins, not rapid messaging.
I'll take care of the screen and keyboard side of it - but just interested if anyone has any thoughts or experience using a long range AM signal generator like in the link, and interfacing an Arduino as a transceiver...
https://hackaday.com/2014/12/19/gibson-girl-emergency-beacon-built-from-a-wind-up-flashlight/

40 meters is considered one of the most reliable all-season long distance communication (DX) bands.  7.023 MHz  https://www.youtube.com/watch?v=9Oicqr28xLk  you may need a directional coupler or VSWR meter to trim each 20m wire length for best results

SPOT Gen3 Satellite GPS Tracker can have you send a message that all is okay, besides calling in an SOS. But it can only send a single type of message, so it's can send any arbitrary text. You could agree with your wife to some message schema, like regular "I'm okay" message will only be send at 20:00h. All other times mean, that I would require some non-emergency help.

Not sure if I would trust my life on a self made AM transmitter. But as an addition would be a good idea. Depending on your location you might need to have a license to transmit (HAM-license in the USA).


text:
Arduino with Ethernet Shield with PC to upload data to Microsoft Azure
i am a student doing a project related to datalogging. My project is a rehabilitation device that uses 2 rotary encoders to record data for rotation and linear movement of a human arm. The data extract is store inside the PC, but my supervisor wants me to upgrade it, he gave me an Arduino Ethernet Shield to attach it on Arduino Mega and he wants me to upload the data obtained from the device to Microsoft Azure database. I'm still new in both Arduino Ethernet Shield and Azure...can anyone help me?
What can i do with the Ethernet Shield? I mean we normally use the USB cable to work with Arduino, so this mean I have to connect both?
Thanks in advance!

what Azure service? does it support non encrypted access

I'm still learning about Azure service, Azure has various features. 1 of the features is the database.

Assuming that you mean the SQL Database of Azure, a quick google search found me this library, which might work for you. You should start with the provided examples, as mostly they are a good starting point for a new library. There might be more to use out there. You just have to search for it. Try keywords involving sql / mysql combined with Arduino.

thank you very much, I will follow the example and try out.


text:
powering arduino with a voltage divider to increase lifespan
I have a chinese arduino nano that I'm planning to use to open a door using a numeric keypad.
My power source is 12V and I want it running 24/7. I have read that the first thing to fail on an arduino is the voltage regulator due to the heat of lowering the voltage to something the arduino can use.
I have think of buying two big resistors of around 1W each to build a voltage divider and only feed 7V to the Vin pin of the arduino, so it will increase its lifespan.
Is this a good idea?

It's basically another load to the battery. Some low power DC-DC voltage regulator (12V -> 5V) will be much better.

that is a very good idea ... doing experiments with the Arduino is the best way to learn

READ THIS: https://hackingmajenkoblog.wordpress.com/2016/08/30/why-you-cant-use-resistors-as-a-voltage-regulator/

How much current do you expect to use? If you know that you can calculate how much power is converted to heat. If your circuit is only using a few tens of milliamperes, the voltage regulator will only need to dissipate a few tenths of a watt of heat.

Thanks for the comments guys, things are clearer now. I will buy a regulator and use it.
Gerben: it will only use around 50mA, but I wanted to build it very durable so thats why I though on the big resistors.

@Majenko Nice off-site explanation! You could make it an answer! (Copy/paste, upload images).

Or I could hunt down one of the many duplicates and close it ;)

Terminating voltage by dropping it over large power resistors is a bad idea, efficiency wise. There are better options.
Switch-mode Buck (=step down) converters are usually far more efficient than linear regulators. A linear regulator dumps the excess voltage in a resistor which converts the energy mainly into heat. A switch-mode converter works by switching on/off an inductance at the right time, which is far more efficient.
For step-up/step-down DC-DC converter theory look here, here and here. For a comparison for switch-mode against linear regulators look here.
A step-down converter module like the ones with a LM2596 should be good enough for you. See here on ebay.


text:
Is it possible to disable functions/methods?
I recently started using the TimeAction library (which allows for proto-threading) and I noticed it has a really useful function for enabling/disabling threads. I want to use the same idea but apply it to a general function, though I haven't been able to find a possible solution to doing such a task on the internet. Here is a potential way for how I would like to implement it:
#include <TimedAction.h>

boolean disableCheck = false;
boolean checking = false;
boolean state = false;
const int motionPin = 5;
void checkMotion();
void motion();
void DisableCheckMotion();

TimedAction checkable = TimedAction(6000, DisableCheckMotion);

void setup() {
   pinMode(motionPin, INPUT);
   Serial.begin(9600);
}

void loop() {
  checkMotion(); //this will be the function I wish to enable and disable

  if(checking == true)
  {
    motion();
  }
  if(disableCheck == true)
  {
    checkable.check();
  }

}
void checkMotion()
{
   checking = true;
}
void motion()
{
   if(digitalRead(motionPin) == HIGH)
{
   Serial.println("motion");
   checking = false;
   checkable.check();
}
}
void DisableCheckMotion()
{
  state ? state = true : state = false;
  if(state == false)
{
  checkMotion.disable(); //this is where I would like to disable the function
  disableCheck = true;
}

  if(state == true)
{
  checkMotion.enable(); //this is where I would like to enable the function
  disableCheck = false;
}
}

The purpose of this task is to output one value for whenever a PIR scanner (set at pin 5) picks up motion. Without any form of delaying it will flood the output with values (which is undesirable). A thread is used to offer this delay, I cannot put the code for checking for motion within the thread as I could risk the chance of a reading being missed.
The ideal setup would be for the Arduino board to receive the input and then delay the input from being received again for a period of time while not delaying the entire program. What would be the best way to implement this?

" I cannot put the code for checking for motion within the thread as I could risk the chance of a reading being missed" Wouldn't you miss a reading when the function is a disabled?

You probably don't want threads for this. Instead, check elapsed time in your main loop, and call the less frequent functions only if enough time has elapsed since you last ran them.

@ChrisStratton That's basically what TimedAction.h does. It does the same thing as SimpleTimer.h - it just encapsulates a check of millis() and runs functions when the required delay passes. Nothing you can't do with a simple check of millis() in your main loop. Ideal if you don't have a clue about simple programming...

If you don't want a function to run you can just return at the start of that function:
void myFunction() {
    if (!myFunctionShouldRun) return;
    ... rest of function ...
}

If myFunctionShouldRun is false the if will be true (due to the !) and the function will return.  If it's true the rest of the function will execute.


text:
Problems bluetoothing float values
I have two Arduino Unos, one of which is connected to a HC-05 bluetooth device and a temperature reader, the other has just a HC-05 bluetooth and is expected to output temperature readings in serial monitor.
This is first device:
#include <SoftwareSerial.h>
const int tempPin = 1;
SoftwareSerial BTSerial(10, 11);

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

}

void loop() {
int value = analogRead(tempPin);
float mv = value * (3300/1024);
float x = (mv - 500)/100;
Serial.print("Temperature is: ");
Serial.println(x);
BTSerial.print(x);
delay(5000);
}

This is the second device:
#include<SoftwareSerial.h>
void setup() {
BTSerial.begin(38400);
Serial.begin(9600);
}
void loop() {
if(BTSerial.available())
{
float x = BTSerial.read();
Serial.println(x);
}
}

The first program is able to give me accurate readings (around (15 degress Celsius) but the second program gives readings between 40 - 60 *C (as well as that it spits out 5 different readings between delay intervals). Why is that? How should I change this so both devices output the same readings

Two problems:
Your first program sends an ASCII representation of the temperature with no line ending.  So after a few readings you get something like:
20.2520.2520.5021.0021.25

etc.  You need some line endings in there to break them up.
Secondly your second program reads one byte at a time as a number (float) and prints it - so would get something like:
50.00
48.00
46.00
50.00
53.00
50.00
48.00
... etc ...

You need to, in association with sending line endings in your first program, read each character of a single line either into a string and then parse that as a float (with dtostrf()) or directly into a float using a state machine.
You can read more about working with serial here and working with a number reading state machine here.

Hi, thanks for the response!
Just a quick question; by line ending do you mean something along the lines of a "println()" statement or something else? thanks for the tips, will look into working with serial now

Hi, I just read through your article. Okay I understand, still wrapping my head around the code but I understand the theory behind it. Thank you, this helps a lot!


text:
understanding timer overflow detection code
I am trying to understand in details the (great tutorial and) code of Nick Gammon ''Improved sketch using Timer 1'', available here: http://www.gammon.com.au/forum/?id=12075 . I post the whole code at the end of this in the case the web page would go down.
I find the code quite clear: Nick wants to estimate the value of a capacitor by measuring its characteristic discharge time. For this he uses one of the Arduino timers, together with an interrupt raised by the analog comparator. As the Arduino timer he uses is only 16 bits and he uses a pre-factor of 1 at 16MHz, he expects overflow of the timer to occur so he keeps track of the number of overflows that happened:
ISR (TIMER1_OVF_vect)
{
  ++overflowCount;               // count number of Counter1 overflows
}  // end of TIMER1_OVF_vect

However, what I do not understand is why he tries to find a 'missed overflow' in the ISR raised by the analog comparator (this is in the ISR (ANALOG_COMP_vect) function body):
// if just missed an overflow
    if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
      overflowCopy++;

So my questions are:

How could a missed overflow happen? 'Naively' I would guess that, as soon as the analog comparator ISR is called, the timer stops incrementing so that it should not overflow after the comparator ISR fires, am I wrong?
If there is a timer overflow happening, I understand why one wants to check TIFR1 at TOV1 (this is the overflow flag, set automatically at timer overflow, which should be cleared as a side-effect of execution of ISR(TIMER1_0VF_vect) according to datasheet), why add also the && timer1CounterValue < 256 in the if condition? I understand that 256 is a 'small' value, any reason for this exact numerical value?

Copy of the whole code:
/*
Capacitance meter

Author: Nick Gammon
Date:   27 June 2013

Pulse pin (D2): Connect to capacitor via 10K resistor.

Reference voltage of 0.632 of output pin (pulsePin) connected to D7.
In my case I used 3.06V because I measured 4.84 on the 5V pin.

Measure pin (D6) connected to first leg of capacitor, other leg connected to Gnd.

Like this:

Capacitor to test:

D2  ----> 10K ----> D6 ----> capacitor_under_test ----> Gnd

Reference voltage:

+5V ----> 1.8K ---> D7 ---> 3.1K ----> Gnd

*/

const byte pulsePin = 2;
const float resistance = 10000.0;

volatile boolean triggered;
volatile boolean active;

volatile unsigned long timerCounts;
volatile unsigned long overflowCount;

ISR (TIMER1_OVF_vect)
{
  ++overflowCount;               // count number of Counter1 overflows
}  // end of TIMER1_OVF_vect

ISR (ANALOG_COMP_vect)
  {
  // grab counter value before it changes any more
  unsigned int timer1CounterValue;
  timer1CounterValue = TCNT1;  // see datasheet, page 117 (accessing 16-bit registers)
  unsigned long overflowCopy = overflowCount;

  if (active)
    {
    // if just missed an overflow
    if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
      overflowCopy++;
    // calculate total count
    timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
    triggered = true;
    digitalWrite (pulsePin, LOW);  // start discharging capacitor
    }
  }  // end of ANALOG_COMP_vect

void setup ()
  {
  pinMode (pulsePin, OUTPUT);
  digitalWrite (pulsePin, LOW);

  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS0) | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on rising edge)
   }  // end of setup

void startTiming ()
  {
  active = true;
  triggered = false;

  // prepare timer
  overflowCount = 0;            // no overflows yet
  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;      // Counter to zero
  TIFR1 = bit (TOV1);  // clear overflow bit
  // Timer 1 - counts clock pulses
  TIMSK1 = bit (TOIE1);   // interrupt on Timer 1 overflow

  // get on with it
  digitalWrite (pulsePin, HIGH);  // start charging capacitor
  // start Timer 1, no prescaler
  TCCR1B =  bit (CS10);

  } // end of startTiming

void finishTiming ()
  {
  active = false;
  Serial.print ("Capacitance = ");
  float capacitance = (float) timerCounts * 1000.0 / 16.0 / resistance;
  Serial.print (capacitance);
  Serial.println (" nF");
  triggered = false;
  delay (3000);
  }  // end of finishTiming

void loop ()
  {
  // start another test?
  if (!active)
    startTiming ();

  // if the ISR noted the time interval is up, display results
  if (active && triggered)
    finishTiming ();

  }  // end of loop

'Naively' I would guess that, as soon as the analog comparator ISR is
   called, the timer stops incrementing

It doesn't. The timer stops only when you ask it to stop.
Now, consider this scenario:

overflowCount = 0, TCNT1 = 0xfffc
the ANALOG_COMP interrupt fires, which automatically disables
servicing nested interrupts
while ISR(ANALOG_COMP_vect) is executing its prologue (saving the
execution context), Timer 1 overflows, which sets the TOV1 flag, but
the corresponding interrupt is for now pending
when timer1CounterValue = TCNT1; gets executed, TCNT1 is now
0x0008.

At this point, we have overflowCount = 0 and timer1CounterValue =
0x0008. If we have no provision for detecting the overflow, we will
grossly underestimate the time. This can be fixed by accounting for the
missed overflow as
// if just missed an overflow
if (TIFR1 & bit(TOV1))
    overflowCopy++;

The is still an issue however. Think of what would happen if the timer
overflows after executing timer1CounterValue = TCNT1; but before
reading the TOV1 flag. Then we would unduly increment overflowCopy.
This is why the code tests for
(TIFR1 & bit(TOV1)) && timer1CounterValue < 256. There is no reason
for choosing this particular small value, other than the test being
easier to perform in assembly. The compiler is probably smart enough to
notice it doesn't need to do a subtraction for this particular value.

Great, thank you! I had always thought that timers were not working in interrupts and that this is why you cannot use delay() there, am I wrong?

Sorry, now I may understand: actually, the problem is not that timers were stopped in interrupts, but that delay() relies on an interrupt itself; is this right?

Mmh, no, this is not it: delay does not seem to have rely on any interrupt: ```void delay(unsigned long ms)
{
uint32_t start = micros();
    while (ms > 0) {
            yield();
            while ( ms > 0 && (micros() - start) >= 1000) {
                    ms--;
                    start += 1000;
            }
    }

}```

@Zorglub29: delay() relies on micros() which relies on timer0_overflow_count which is updated by the TIMER0_OVF interrupt.


text:
Esp32 Https Problem
I am working on a project in which i have to send GET request to my Company's  Https server. I have successfully sent the GET request using NodeMCU v 1.0 (ESP 12E). The NodeMCU 1.0 (ESP 12E) Arduino library uses SSL certificate Fingerprint ,host name and url to send the GET request. it is easy to find the fingerprint of Certificate using this website ->  https://www.grc.com/fingerprints.htm
But in ESP 32 Arduino Library i have to pass the SSL certificate . I have no idea how to find the SSL certificate of my Company's website.
The format of the SSL certificate used in ESP 32 Arduino library is given below :
/*
const char* ca = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/\n" \
"MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n" \
"DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow\n" \
"SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT\n" \
"GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC\n" \
"AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF\n" \
"q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8\n" \
"SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0\n" \
"Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA\n" \
"a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj\n" \
"/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T\n" \
"AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG\n" \
"CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv\n" \
"bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k\n" \
"c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw\n" \
"VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC\n" \
"ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz\n" \
"MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu\n" \
"Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF\n" \
"AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo\n" \
"uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/\n" \
"wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu\n" \
"X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG\n" \
"PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6\n" \
"KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==\n" \
"-----END CERTIFICATE-----\n";
*/

Is there any easy way to find the SSL certificate of any website which uses Https instead of simple http ?
Thanks in advance

in chrome:

press [F12]
click the "Security" tab
click the "View Certificate" button under "Security overview"
click the "details" tab on the "Certificate" popup
click the "Copy to File..." button
click the "Next" button
check the "base64 encoded x509" option
click the "Next" button
click the "Browse" button and choose a folder for the export
enter a file name in the provided space
click the "Next" button
click the "Finish" button
browse to the folder and open the export using a text editor

The export file has the same format, you just need to convert to a C literal usiing end-of-line slashes and quotes, an exercise i'll let you handle. There might be some fancy tool that does all this for you, I'd love to hear about one, but I know this is a fairly universal way to get it done.

Using e.g., openssl is possible. The command could go like this from the shell:
openssl s_client -showcerts -servername www.theserver.io -connect www.theserver.io:443 -certform DER
Including >mycertif.der at the end of the command, you get the information in a file so you can cut-paste that part of the command output.
Best,

Even if it's an old question... I suggest not rely on methods describe here. Of course you can get the SSL certificate from the browser and copy-paste it into your code. But each time the server will renews the certificate, the key change!
If you have a "free" certificate, like the one from Let's Encrypt, used for example in all the shared hosting of all major web hosting companies, the key will change every... 3 months! So you'll have to update your ESP code each 3 months... For testing purpose, that's OK but for real "application" it's not a good option.
So,how can we do?

Option 1: add a module on your web server, allowing to have a pre-defined SSL key. You just set the key for a specific folder and copy it to your ESP. My server is an Apache one and it seems this modules don't exist for Apache.

Options 2: edit your Apache conf (commonly at etc/apache2/) for your serveur. In many cases, each time a customer access your server with http, Apache will change the call to https.
This is made with a rewrite rule. You can change this like that:
  RewriteCond %{HTTPS} off
  RewriteCond %{THE_REQUEST} !/XXXXXX [NC]
  RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

  RewriteCond %{HTTPS} on
  RewriteCond %{THE_REQUEST} /XXXXXX [NC]
  RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

where XXXX is the name fo the folder in which you will put the script called by your ESP. With that all folder on your site are using https except the one you use with your ESP. Of course this mean your ESP call is done using http and not https but in many cases we have to use ESP+https not for real security reason but because the web site is in https.


text:
Timer Prescaler problem
I am working on a project which requires use of 16bit timer . I am using Arduino Uno (Atmega 328p) board and Timer_1 (16 bit timer ) in Overflow mode. i want to use 1024 prescaler settings.
According to the datasheet of the controller i have to set [b]CS10 and CS12[/b] bits to use 1024 prescaler but the problem is OverFlow interrupt routine is never fired when 1024 or 256 prescaler is selected .
The Following code works just fine with Prescaler set to 8 or 64.
#include <inttypes.h>

volatile uint8_t sCount = 0;

void setup()
{
      Timer_one_16_init(); // configure the timer

      pinMode(13,OUTPUT);

}

void loop()
{
    // do nothing
}

void Timer_one_16_init(){

    TCCR1A = 0;

    // set the pre-scaler to 1024 (slowest)

    TCCR1B |= (1<<CS12)|(1<<CS10);

    // set the bottom / starting value

    TCNT1 = 0x00;

    // set Overflow interrupt

    TIMSK1 |= (1<<TOIE1);

    // enable global interrupt
    sei();

}

ISR(TIMER1_OVF_vect){

    sCount++;

    if (sCount == 60)
    {
        digitalWrite(13,!digitalRead(13));
        sCount = 0;

    }

}

i have no idea why this is happening. i have done everything which is given in the datasheet .
Am i doing something wrong ?
Thanks in advance

You must write the clock-select bits to the correct value. The simplest
way to do it is to write the proper configuration into the TCCR1B
register:
TCCR1B = (1<<CS12)|(1<<CS10);

In your program, you used |= instead of =. This doesn't write the
bits appropriately: it only sets (writes to 1) the bits CS12 and
CS10 but doesn't clear CS11. Since the Arduino core library sets the
prescaler to 64 (CS11 and CS10 set), you end up with all the
clock-select bits sets, in which case the timer is clocked by an
external signal on the T1 pin. Not what you want.

Edit: Judging from the comments, it appears that at least dannyf did
not understand my answer, I am therefore adding a clarification. There
are two scenarios when you may want to tweak the control registers of a
peripheral:

The peripheral is normally controlled by the Arduino core library,
and you want to use it through that library. Typical case: you want
to use a timer to analogWrite(), or the ADC to analogRead(), but
you want to clock the peripheral at a frequency which is not the
core's default.
You want to use a peripheral directly rather than through the Arduino
core. Either you are going to “take it over” from the core, or it's a
peripheral the core doesn't use in the first place.

In the first case, you should only touch those bits of the control
registers that you must change. The other bits should be left alone, at
whatever values the core has set them to. This is the approach of
dannyf's answer.
In the second case, it is wiser to not rely on the core's default
setting, and instead write every single bit of the control registers
to the values appropriate for your application. This is the scenario of
the original question, and the solution proposed in my answer.
For the particular case of this question, the TCCR1B register would
be set to: ICNC1 = 0†, ICES1 = 0, reserved bit = 0, WGM13
= 0, WGM12 = 0, CS12 = 1, CS11 = 0 and CS10 = 1. Combining those bits
together gives the setting TCCR1B = 0x05;. However, for readability
reasons, I prefer to write that value (1<<CS12)|(1<<CS10), as in the
question and in my original answer. Some people may prefer to explicitly
write every bit, like
TCCR1B = (0<<ICNC1) | (0<<ICES1) | (0<<5)    | (0<<WGM13)
       | (0<<WGM12) | (1<<CS12)  | (0<<CS11) | (1<<CS10);

Whichever version you prefer is up to you. I personally don't find this
latter version any easier to read.
†: The values of ICNC1 and ICES1 are actually
irrelevant in this case.

Thanks  it solved my problem. i have just checked the default value of TCCR1B . it is 0x33 . But in the datasheet default value of TCCR1B = 0x00. i was expecting the value of CS11 bit to be 0.

" i have just checked the default value of TCCR1B . it is 0x33 ." that means the code is setting WGM13. With the proposed "beginner" approach, WGM13 is cleared. To the extent that your code uses anything that requires WGM13 being set, like PWM, it wouldn't work.

"But in the datasheet default value of TCCR1B = 0x00. i was expecting the value of CS11 bit to be 0." you should never rely on the default values. and your code should only change the registers / bits to the extent that you need. For example, if you want to change prescalers, change only those registers / bits that are related to the registers / bits that need to be changed. Otherwise, your code may have unexpected impact on other parts of your code.

It is because of that, the code proposed to you is very dangerous: it is a bomb that will explode in your face when the conditions are "unexpectedly" right.

@parasbhanot: “But in the datasheet default value of TCCR1B = 0x00”. This only applies after a reset. You can rely on this default if you do not use a bootloader nor the Arduino core. The Uno's bootloader does its best to leave every register at its reset state, but it could be unwise to rely on this. And if you use the main() from Arduino core (the “normal” Arduino practice, where you write setup() and loop() but not your own main()), then many registers will end up in the Arduino's default setting, which is not the same as the hardware-defined default.

// set the pre-scaler to 1024 (slowest)

TCCR1B |= (1<<CS12)|(1<<CS10);

that approach presumes for the CS11 bit. in this case, if CS11 is set, the clock source is routed to the CKI pin, and if you don't apply a clock to that pin, the timer will never overflow.
Two options:
1) do it via two steps: set CS12/CS10 and clear CS11; or
2) do it in one step:
TCCR1B = (TCCR1B &~0x07) | (ps & 0x07);

ps would be whatever prescaler setting you wish to use.
the proposed solution below,
TCCR1B = (1<<CS12)|(1<<CS10);

is a typical beginner mistake, and a very dangerous one, as it clears other TCCR1B bits without the programmer even realizing it.

“TCCR1B = (1<<CS12)|(1<<CS10); is a typical beginner mistake.” No, it's the right thing to do. If you are configuring a timer for your own usage, you should not rely on whatever settings the Arduino core left in the control registers. Instead, you should set every bit of the control register to the value appropriate for your application. You could do that bit by bit, if you enjoy useless complexity, but the simplest solution is just control_register = the_value_I_want;.


text:
Different behavior when Arduino Micro powered by laptop USB vs portable charger USB
I'm working on a project that uses an LM35 temperature sensor to control a few LEDs. Above 97 degrees, one LED should switch on. Below 95 degrees, it should switch off and the other should switch on. In between those temperatures, the LED state should remain unchanged.
When the Arduino Micro is plugged into my Macbook USB port, everything functions as I expect, however when I plug the same USB cable into a different USB power supply (like a portable cell phone charger), the LEDs tend to blink back and forth at the frequency at which I tell the Arduino to check which state the LEDs should be in.
The only thing I can think of that is different between the laptop USB and battery is the lack of serial data being read by the battery. Unclear, though how I can fix this issue. Any suggestions would be appreciated.

Can you show a schematic of your wiring of the sensor (complete circuit would be most helpful), as well as your code?


text:
Is a solenoid piston strong enough to lock a water tubling?
My question is about hardware that i'll control with my arduino... Not Arduino itself (So I don't know if I'm in the right section ... :s)
My project is to create a cocktail machine at the cheapest price.
I was wondering if this kind of solenoid piston would be strong enough to seals a plastic pipe like this one ?
My idea from now is to use only 1 water pump (as this one) and connect all the pipes from the bottles with some Y and control which one is giving the liquid by controling pistons that are going to compress the tube.
I'm open to all advices you could give me and new ideas ... I saw that there's also solenoid valves ... But I only find it in 12V ... Does it exist in 5V ?

Unlikely at best. You should either use proper valves or consider a geared motor / servo (not a model one) to rotate a cam to compress the tube.

If you can't find what you want in 5V then you will need to control them with the correct voltage. It's not rocket surgery.

You'll crack the pipe.


text:
Debouncing Switch Issue
I’m trying to use a LDR to monitor the light levels and if the LDR is covered and the button is pressed, the LED should switch on. I’m in the process of adding debouching but every time I run the code, the it goes in the if (val > 421) part the led is on, but the button hasn’t been pressed and the code stops.
I’m suspecting it may be a logic issue with the states. I’m using the millis function for the debouncing so the code should ignore the first 200ms of when the button is pressed. I just help in regard to the debouncing so when the LDR is covered and the switch is pressed , the LED should turn on.
The code is shown below:
const int buttonPin = 8;
const int ldrPin = 0;
const int LEDPin = 13;

boolean buttonState = 0;
boolean NEWbuttonState = 0;
boolean LEDState = 0;
int bounce_time = 200;
unsigned long my_time;

boolean on;

int val = 0;

void showValue(float myval)
{
  Serial.print(myval);
  Serial.print(" lightstatus ");
  Serial.println(LEDState);
}

void setup()
{
  pinMode(buttonPin, INPUT);
  pinMode(LEDPin, INPUT_PULLUP);
  on = false;
  analogReference(DEFAULT);
  pinMode(ldrPin, INPUT);
  Serial.begin(9600);
  my_time = millis();
}

void loop()
{

  val = analogRead(ldrPin);

  NEWbuttonState = digitalRead(buttonPin);

  if ((millis() - my_time) > bounce_time)
  {
    digitalWrite(LEDPin, LOW);

    if (buttonState != NEWbuttonState)
    {
      buttonState = NEWbuttonState;

      //if button is pressed
      if (NEWbuttonState == 1 && LEDState == 0)
      {
        buttonState = NEWbuttonState;

        if (val > 421)
        {
          my_time = millis();

          digitalWrite(LEDPin, 1);
          LEDState = 1;
          showValue(val);
          Serial.print("button press");
        }

        if (val < 420)
        {
          my_time = millis();

          digitalWrite(LEDPin, 0);
          LEDState = 0;
          showValue(val);
        }
        buttonState = 1;
      }
      else
      {
        if (NEWbuttonState == 0)
        {
          buttonState = 0;

        }
      }
    }
  }
}

Look for the Bounce2 library in the IDE library manager.

you described what you want to happen when the button is pressed, but you forgot to say what should happen when the button is released

If your Arduino is an uno or nano or similar, const int ldrPin = 0; conflicts with Serial. Or, if it's intended for analogRead, you should avoid pinMode(ldrPin, INPUT);  Better use  const byte ldrPin = A0;

Please show us how you have connected the LDR to the Arduino.

Bouncing of a mechanical switch happens in very few milliseconds, faster than you can see a led shine.
So, for your task, you don't need any debouncing.
The description or your task lacks what should happen "if not". I assume the led should shine while both button is pressed and ldr is covered. If either button is not pressed, or ldr is lit, the led should remain off.
This one is too simple:
void loop() {
  bool ldrDark = analogRead(A0) < MAX_LDRBRIGHT;
  digitalWrite(led, ldrDark && digitalRead(buttonPin));
}

To add a delay (led goes on only when button is pressed some time) is easy as well.
const byte LED = LED_BUILTIN; // 13 on UNO

const byte BUTTON = 8;  // Button connects to GND
const byte PRESSED = LOW; // due to INPUT_PULLUP
const int DELAY = 300; // ms
bool btnState; // true = HIGH when presse

const byte LDR = A0; // LDR to 5V, Resistor to GND : Low values when dark
const int MIN_LDRBRIGHT= 420; // depends on resistor and LDR

void setup() {
   pinMode (LED, OUTPUT);
   pinMode (BUTTON, INPUT_PULLUP);
}

void loop() {
  static unsigned long lastOpen;
  if (digitalRead(BUTTON) == PRESSED) {
    if (millis() - lastOpen > DELAY)
      btnState = HIGH;
    else btnState = LOW;
  } else {
      lastOpen = millis(); // to remember last moment button was released
      btnState = LOW;
  }

  bool ldrDark = analogRead(A0) < MIN_LDRBRIGHT;

  digitalWrite(LED, ldrDark && btnState);
}

You should see led follow the covered ldr (while button remains pressed) faster than button changes.  If that's the intention of this exercise.


text:
Using CoolTerm to receive Serial Data into a saveable file
Have functional code that reads data from sensors. Found that I need to use a terminal program to grab the data from the serial output using CoolTerm by Roger Meier.
Wasn't able to test it with my code yet because of this issue: (No Data Received on Serial Port & Unable to DFU Reset. Advice?).
Watched some videos and read some tutorials - does CoolTerm only come into play once I'm running the code? Can you write code for the arduino to automatically save stuff?

CoolTerm can save incoming data to a text file. In the help section, you can read about "Received data can be recorded to textfile using Connection/Capture to Textfile.", "Capture Text Options", "Leave File open while capturing" and "Add timestamps to received data".

VE7JRO - No, I get that CoolTerm can save data to a .txt file. But you have to open the CoolTerm GUI to do that right?

The CoolTerm app has to be running to capture data. Closing the app closes the serial connection and stops data logging. I un-checked the "Leave file open while capturing" check box under options > receive so I could open the text file and read it's contents while it's logging.

VE7JRO - Cool. Will do.


text:
How to create parametric variable in class decleration
I hope the subject of this question if correct.
in timeOUT constructor, 3 more instances of other class are defined:
endTimeOUT_inFlash(key1),
inCodeTimeOUT_inFlash(key2),
updatedTimeOUT_inFlash(key3).
// ~~~~~~~~~~~ TimeOut Class ~~~~~~~~~~~~
timeOUT::timeOUT(char *sw_num, int def_val,char *key1, char *key2, char *key3)
        : endTimeOUT_inFlash (key1), inCodeTimeOUT_inFlash(key2), updatedTimeOUT_inFlash(key3)

I'm looking for a way that key1 to key3 will be predefined keys, and sw_num will serve as a prefix to those keys.
For example :
#define key1 "endTO"
#define key2 "inCodeTO"
#define key3 "updatedTO"

and using sw_num's value will be concatenate as: SW0_endTO( for key1 and so on . sw_num=SW0 ofcourse).
This way contructor will be :
// ~~~~~~~~~~~ TimeOut Class ~~~~~~~~~~~~
    timeOUT::timeOUT(char *sw_num, int def_val)
            : endTimeOUT_inFlash (key1), inCodeTimeOUT_inFlash(key2), updatedTimeOUT_inFlash(key3)

Why do you need this? Anyway you can use sw_num as String and make those concatenations like  sw_num + '_' + key1 ... (that's ugly solution). Or you can have two parameters in constructors and build the string inside of class. Or you can create child classes for each key...  But with knowing context, it might be something completely different

@KIIV as far as I understand ( tried ), nothing can come before constructor to do such "concatenate"

@Guy.D, read KIIV's comment again and slow

This smacks of an X-Y Problem. You should more clearly define what you want to achieve, and forget how you think you want to achieve it.


text:
String compare when using Serial
I try to detect commands given by user in Serial Monitor, but strcmp fails to flag as identical.
What do I do wrong ?
Is there a better way not reading as String and convert to char for comparison ?
Guy
char* additional_callbacks [] = {"command_1", "command_2", "command_3"};

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

void loop() {
  if (Serial.available() > 0) {
    char tmpchar[50];

    Serial.print("entered_text:");
    String str = Serial.readString();
    str.toCharArray(tmpchar, 50);
    Serial.println(tmpchar);

    for (int i = 0; i < sizeof(additional_callbacks) / sizeof(char*); i++) {
      if (strcmp(tmpchar, additional_callbacks[i]) == 0) {
        Serial.println("match");
      }
    }
    Serial.flush();
  }
  delay(50);
}

are you sure the input string is exactly one of the "command"s ... i.e. is there a end-of-line character being sent for example

We don't use the Serial.readString because it sometimes waits for data, although it has a timeout. The Serial.flush can not be used to clear the input buffer: https://www.arduino.cc/en/Serial/Flush At this moment it is best to write your own code to read data from the serial port.

you can use readBytesUntil to read text from Serial to char array

@JaromandaX I send ‘command_1’ as input and get no match

Guy D. we know that you send that command and we know that the sketch does not work. The serial monitor might add extra charaters after the 'command_1', a line feed or carriage return character. Even if you fix that, there is still a synchronization problem, the sketch does not know the start or the end of the characters of a command.

In your for() loop, use Serial.println() to display both strings before the compare. You'll be able to see why the compare is failing.
Update:

it seemed identical.

Something has to be different for the test to fail. If the strings look identical then there must be some non-printing characters that differ: \r, \n, , , missing \0 ), etc.
Try printing your buffers byte-by-byte in hex for a few more bytes than the string length, to be sure there is an  where it should be.
Or print the buffers with this hexdump function which lists a specified memory range in both ASCII and hex:
/***

Name:       hexdump

Function:   Dump memory contents to terminal

Description:Dump a specified range of memory in hex and ASCII

Parameters: byte *mem       - starting address
            uint16_t len    - # of bytes

Returns:    void

Notes:      Based on: http://grapsus.net/blog/post/Hexadecimal-dump-in-C
            Formats with sprintf(); outputs with Serial.print().
            Modified to print ...0 - ...F of each hex-block containing
            any of the requested memory range. Data not in the range are
            not shown.

***/

void hexdump(byte *mem, uint16_t len)
{
   byte *p, *pfirst, *plast;    // -> curr byte, first & last hex-blocks to print from
   char buf[10+1];              // sprintf o/p buffer

   // Print entire hex-blocks that contain the requested mem range,
   // except only show data within the range.
   pfirst = (byte *)((uint16_t)mem & 0xFFF0);           // beg of 1st  hex-block
   plast = (byte *)((uint16_t)(mem + len) | 0xF);       // end of last hex-block

   for( p = pfirst;  p <= plast;  ++p ){

      /* Print block addr */
      if( ((byte *)((uint16_t)p & 0xF)) == 0 ){
         sprintf_P(buf, PSTR("%06X: "), (unsigned int)p);
         Serial.print(buf);
      }

      // Print hex data, or if outside mem range, print spaces
      if( mem <= p && p < (mem + len) ){
         sprintf_P(buf, PSTR("%02hhX "), *p);
         Serial.print(buf);
      }
      else
         Serial.print("   ");                   // outside requested range - just spaces

      // Maybe print gutters and/or ASCII data
      if( ((uint16_t)p & 0xF) == 0x7 )
         Serial.print(" ");                     // narrow gutter after 8 bytes
      // If at end of hex block, print a gutter & re-print the block as ASCII
      if( ((uint16_t)p & 0xF) == 0xF ){
         Serial.print("  ");                    // wide gutter after 16 bytes

         // Print as ASCII.
         // Note: In this loop, we re-use the outer loop's index, 'p', to rescan
         // the hex block. We must leave 'p' as we found it!
         for( p = (byte *)((uint16_t)p & 0xFFF0);  ; ++p ){
            if( !(mem <= p && p < mem+len) )
               Serial.print(' ');               // not in requested mem range
            else if( !isprint(*p) )
               Serial.print('.');               // not printable
            else
               Serial.print(*(char *)p);        // print as ASCII

            if( ((uint16_t)p & 0xF) == 0xF ){
               break;                           // end of hex-block
            }
         }
         Serial.print('\n');
      }
   }
}

Already test, and it seemed identical.  Perhaps what Martin say has something to do with it ( will try it later )

You try to compare Serial input

command_1\r\n

with

command_1

and these two are not equal.

Can you elaborate, to make this a proper answer rather than a comment?

Thanks Michael, i will regard this next time.