text:
Current Sensor ACS712 not changing its value even when connected bulb is lit
My task is to find the amount of current a light bulb uses, with that motive I used ACS712 current sensor of 30A connected all the connections properly as shown in the circuit diagram below

I tried all different codes available to calculate current...
Arduino Code :
void setup(){
    Serial.begin(9600);
}

void loop(){
  int rVal = 0;
  int sampleDuration = 100;       // 100ms
  int sampleCount = 0;
  unsigned long rSquaredSum = 0;
  int rZero = 511;                // For illustrative purposes only - should be measured to calibrate sensor.

  uint32_t startTime = millis();  // take samples for 100ms
  while((millis()-startTime) < sampleDuration)
  {
    rVal = analogRead(A0) - rZero;
    rSquaredSum += rVal * rVal;
    sampleCount++;
  }

  double voltRMS = 5.0 * sqrt(rSquaredSum / sampleCount) / 1024.0;

  // x 1000 to convert volts to millivolts
  // divide by the number of millivolts per amp to determine amps measured
  // the 20A module 100 mv/A (so in this case ampsRMS = 10 * voltRMS
  double ampsRMS = voltRMS * 10.0;
  Serial.println(ampsRMS);
  Serial.println(analogRead(A0));
}

Output

The output remains the same, even when the bulb is still lighting up.
Thank You in advance :)

print the values of rSquaredSum / sampleCount and voltRMS

How much current does your bulb actually use?  Or put differently: what percentage of 30A is that?

@timemage, on the picture it is 230 V / 100 W.  it should make a difference in my experience. but it could be lost in calculation

That is in part what I'm thinking, but also to make sure his expectations are in line with what the sensor will actually do.

do 10 readings at less than 100 ms intervals between readings ... do not do any calculation with the values ... store them in an array ... after the readings are completed, print the values to serial

Try to tell us the different types of code and the tutorials you followed so we can better narrow down the answer.

In a comment about rZero = 511;, you wrote:

For illustrative purposes only - should be measured to calibrate
sensor.

This may well be the cause of your problem. If, instead of 511, the
“zero” of your measurement is around 445, then you end up measuring a
non-existing DC current of about 3.23 A. When you turn on the light
bulb, you add roughly 435 mA (100 W / 230 V) of AC
current. The total RMS current you see is then:
√(3.232 + 0.4352) ≈ 3.26 A
Barely visible at the resolution at which you are printing the result.
And this is assuming you are using a 100 W bulb, as shown in the
diagram. These bulbs are getting hard to come by. If you are using
anything less powerful, you may not see any change in the displayed
value.
As a quick and dirty fix, you may replace 511 by 445. A better
solution would be to compute the quadratic average of the AC part of the
signal alone. In other words, compute:
√(average(current2) − average(current)2)

how did you conclude that the zero is 445? the time between those measurements is more then 100 milliseconds. it could simply catch the same part of the wave

@Juraj: A constant reading yielding 3.23 A must be 511±66, but the values shown in the serial monitor are only consistent with 511−66.


text:
Will plugging in a 12v power supply in the wrong polarity to a CNC SHIELD fry my circuit or damage my power supply?
I'm currently in the process of making a DIY pen plotter using an Arduino CNC Shield and GRBL Code. Right now I'm connecting the power supply to the shield. I got a standard 12v supply and I cut off the barrel connector so I can connect the supply directly to the CNC Shield. I can't seem to figure out which wire is negative and which is positive. I don't have a multimeter on me so can't test it but I have attached a picture of the information on the power supply which I think should be able to give someone with more knowledge, insight onto the polarity. I think the left wire is negative but not one hundred percent sure. If I risk a test will this damage my circuits or power supply ? Sorry for such an easy question I just don't want to accidentally fry my circuits as have been working on this for a really long time !!
Thank you so much,
Arav

It depends on the shield. If there is a protection diode then it will be safe. If there isn't then you will end up with a smoking shield. Please link to the exact shield you are using.

https://www.amazon.co.uk/gp/product/B07CQRPFFW/ref=ppx_yo_dt_b_asin_title_o05_s01?ie=UTF8&psc=1 - Here is the link for the shield I bought. Sorry I probably should have included it in my first post! Thank you for such a quick reply

I don't see any diodes on there (or anything much at all other than some capacitors). There is no protection. Get it wrong and things will die. Maybe even exploding capacitors, which is fun....

You need a DMM or something else that's polarized to identify which wire is which. An LED and resistor could be used.

If you wire the power into that shield wrongly you risk killing things - and with those big electrolytics reverse polarity could get very messy indeed.
You need to identify the polarity before you wire it in, and to do that you need something that is sensitive to polarity.
If you don't have a DMM you can do it with a simple resistor and LED in series - an LED will only work if the polarity is right.
Take a normal LED of the 5mm type (they're easier to identify) and look for the flat edge on the flange around the base. That indicates which is the "negative" or cathode of the LED.  Alternatively look for which of the legs is the shorter of the two, which is also an indication of which is the cathode.
Connect a resistor to this identified negative leg. You want the resistor to be at least 1kΩ, but no more than 10kΩ. You don't need the LED to be bright...
Connect your wires, one to the LED and the other to the resistor.
If the LED lights up then the wire connected to the LED is positive and the wire connected to the resistor is negative.  If it doesn't light up then the wires are reversed.  In this case check it by swapping the wires over - the LED should now light up.

Hi, Thank you so much for the answer! I currently only have a RGB LED and a ton of 220Ω resistors whichI guess I could connect to the power supply (with a very messy circuit :)). Is there no way of knowing the polarity of the wires from the info on the power supply. It says its a centre-positive supply does this not mean anything ?

That only relates to the connector at the end (which you have now cut off). The wire with the stripe might be negative, but it might not. You can only tell by testing it.  For the RGB LED you need to know if it's "common anode" or "common cathode" to know how to wire it up

Oh yes I completely forgot about that!! Would connecting the RGB LED to a single double AA battery (as you can see my supplies are very very limited :) )  work to test if its a cathode or anode  ?

You would need 2 batteries and small resistor to get the polarity of the LED. 1.5V won't be enough.

Thank you so much I followed all the steps and i've got the polarity now !!

source: Stack Exchange

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

sort: votes


text:
Intterupts For Arduino
I am making a moving robot that will be autonomous in many respects. However if something goes wrong I want to be able to use a remote to push a button and it stop in its tracks no matter what function its in.  My understanding is that interrupts can do that. The official site I did not find to be helpful. Any ideas? Or if the scheduler library would be of use.

Yes, you could use an interrupt for this. Anything else?

An interrupt can not always stop the code, although that is almost always the case. Certainly having an interrupt based kill switch would be better than a "regular code" polled one, which would still be better than nothing. If possible I would feel safest with a cut-power-to-the-whole-thing style safety switch.
Many functions that have sensitive timing constrains disable interrupts while they are active. It is rare for any of these to take a noticable amount of time, but it is possible that a bug in an interrupt dissabled function or another interrupt function could cause it to block and in that case your stop switch wouldn't work. rare, but possible.
I suppose you could turn on the chip watchdog timer, have a regular timer based interrupt reset the watchdog timer at a certain interval, and have your interrupt safety switch enabled. Then if interrupts ever stopped firing for too long the chip would reset itself. Checkout AVR132: Using the Enhanced Watchdog Timer. I've never used the watchdog myself, but it exists for a reason.
I don't have enough experience with a scheduler system to know if they would be helpful.

Is there an overview of arduino functions that disable interrupts for a (short) period?
Anyway, watchdog-timer would be the most professional way to handle this. Though you should try to handle the it and only reset when needed. Then make sure the robot won't move after a reset. And that it's easy to see when it has resetted (so you know it was due the WDT).
I would reset the watch-dog timer in software though, because if your main code dead-locks, the timer interrupts might still work and reset the WDT. But an interrupt will do well generally. Don't use too much code that disables interrupts?

A clear overview of intterupts was what I was looking for although I appreciate advice given.

If you are using an arduino uno, pin 2 and 3 are the hardware interrupt pins. You may send rising , falling, high or low signals to these pins using a Bluetooth module (for eg). Say for eg when you press the remote switch, Bluetooth gets a low signal and triggers an interrupt. If the output of Bluetooth is connected to pin 2, then in the setup you have to declare
attachInterrupt(0, stoprobo, LOW);

And in the function stoprobo, you can write the code to stop your robot.

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


text:
Arduino Nano For Home Automation
My question is about the arduino Nano or Micro and the smallest and cheapest way to control a bigger power source. I would wire it with a socket so that I could send a command from the board and a light would turn on for example.

A relay is a common way to allow a smaller power source to safely control a larger one. A relay is like a switch.
Here's some reference material about using a relay with a microcontroller. You shouldn't have much trouble finding more material now that you know what you're looking for.

So your question is: "How to control a bigger power source using the Arduino Nano or Micro".
This tutorial on youtube gives an explanation:
https://www.youtube.com/watch?v=sOz41WQF7wE
It's about a motor, but the answer is the same.
You should use a relais/mosfet
This one is actually pretty great also:
https://www.youtube.com/watch?v=Te5YYVZiOKs

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


text:
Dagu Mini Driver Board Issues
I have the Dagu Mini Driver board which is based on the atmega8 and I uploaded the code here. It uploaded perfectly and I wired 4x AA pack to the battery terminals making sure to observe polarity.
I then attached two DC motors to the ML and MR pins just like it said in the picture. I turned the board on, making sure the switch was set to on also.
The red light lighted up and the blue light flickered for a second. The motors did not move. I tried different motors. To check if it was a corrupt bootloader I tried to upload the hello world blink sketch. That worked perfectly.
I got my multi-meter out and tested the wires I was using...all good! Tested the battery...6.31v! That's within specs. I have the jumpers correctly inserted on the D7 - 10 pins. Here's my setup:

What in the world could be wrong? The code is supposed to make it turn in a rough square. I checked it over and over and it looks right. Any ideas?

What +V selector are you using? Battery or 5V. My guess is that you have it in the 5V setting and the regulator cannot driver the motors. The load is too high. http://www.generationrobots.com/media/RS027-mini-driver-instruction-manual.pdf

Switching the selector did not help. I received a new one which worked perfectly following the steps from before. Apparently the issue was hardware related, possibly a cold solder joint preventing the motor driver section to work while still letting everything else continue normally.

This is a generic debugging advice, but maybe it can still be of help:
have you tried driving the led from the loop, to check that it doesn't get stuck for some reason?
Other thing you could do is to get the datasheet of the motor driver, find out the inputs from the ATMega and see how they look like.
At least that would allow you to bisect the problem answering the question:
"Does the ATMega generate the expected signal?"

It looks to me like the "motor driver" is a pair of H bridges built out of discrete MOSFETs.  Hard to work out which one of the 14 MOSFETs is which.  Simpler to look at the digital IO pins that are documented as the control pins for the bridges.

If you mean the "hello world" blink sketch that blinks the D13 LED, I uploaded that and it works. I'll look at the data sheet.


text:
Arduino Watchdog Timer
I want to work with interrupts and heard that the watchdog timer is effective way to deal with them.  I haven't been able to find a good tutorial on them though and was wondering if someone could head me in the right direction or give me a couple tips and an example.

Which part of the datasheet are you having trouble with?

Watchdogtimer is NOT a recommended way of dealing with interrupts. It is dedicated to restarting the system on timeout. Most or all other timers are able to do this much more flexibly.

Look at the TimerOne library.

For the Uno, you can set an interrupt on digital pins 2 and 3.  Check out http://www.arduino.cc/en/Reference/attachInterrupt for more details.
Here is the example code from that page:
int pin = 13;
volatile int state = LOW;

void setup()
{
  pinMode(pin, OUTPUT);
  attachInterrupt(0, blink, CHANGE);
}

void loop()
{
  digitalWrite(pin, state);
}

void blink()
{
  state = !state;
}

In this case, blink() will be called anytime pin 0 changes state.  If you only want the rising or falling edge, change the call to attachInterrupt to say RISING or FALLING instead of CHANGE.

I know that but I don't understand how to integrate the code and the offical site is not helping me.

There is an example on that page -- if you take the blink function and replace it with your code, it will be called anytime pin 0 changes state.  You can also change the interrupt to only be called on the rising or falling edge as well in the attachInterrupt call.  I'll add the example to my answer as well.

Since you talk about the watchdog I presume you want timer interrupts. (There are also I/O interrupts, for instance when the level of a pin changes state.)
Like Russell McMahon says the watchdog is not a good source. The ATmega has several timers (8-bit and 16-bit) which serve your exact purpose. Let's view some example code:
// timer interrupts
// adapted from code by Amanda Ghassaei
// June 2012
// http://www.instructables.com/id/Arduino-Timer-Interrupts/

/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
*/

// timer setup for timer0, timer1, and timer2.
// For arduino uno or any board with ATMEL 328/168.. diecimila,
// duemilanove, lilypad, nano, mini...

// this code will enable all three arduino timer interrupts.
// timer0 will interrupt at 2kHz
// timer1 will interrupt at 1Hz
// timer2 will interrupt at 10kHz

// storage variables
boolean toggle0 = 0;
boolean toggle1 = 0;
boolean toggle2 = 0;

void setup() {

  // set pins as outputs
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(13, OUTPUT);

  cli(); // stop interrupts

  // set timer0 interrupt at 2kHz
  TCCR0A = 0; // set entire TCCR2A register to 0
  TCCR0B = 0; // same for TCCR2B
  TCNT0  = 0; // initialize counter value to 0
  // set compare match register for 2khz increments
  OCR0A = 124; // = (16*10^6) / (2000*64) - 1 (must be <256)
  // turn on CTC mode
  TCCR0A |= (1 << WGM01);
  // Set CS01 and CS00 bits for 64 prescaler
  TCCR0B |= (1 << CS01) | (1 << CS00);
  // enable timer compare interrupt
  TIMSK0 |= (1 << OCIE0A);

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

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

  sei(); // enable interrupts

} // end setup

ISR(TIMER0_COMPA_vect){ // timer0 interrupt 2kHz toggles pin 8
  // generates pulse wave of frequency 2kHz/2 = 1kHz (takes two cycles
  // for full wave- toggle high then toggle low)
  toggle0 = HIGH - toggle0;
  digitalWrite(8, toggle0);
}

ISR(TIMER1_COMPA_vect) { // timer1 interrupt 1Hz toggles pin 13 (LED)
  // generates pulse wave of frequency 1Hz/2 = 0.5kHz (takes two cycles
  // for full wave- toggle high then toggle low)
  toggle1 = HIGH - toggle1;
  digitalWrite(13, toggle1);
}

ISR(TIMER2_COMPA_vect) { // timer1 interrupt 10kHz toggles pin 9
  // generates pulse wave of frequency 10kHz/2 = 5kHz (takes two cycles
  // for full wave- toggle high then toggle low)
  toggle2 = HIGH - toggle2;
  digitalWrite(9, toggle2);
}

void loop() {
  // do other things here
}

This sets up 3 different timers: one at 500 µs, one at 1 s, one at 100 µs. For the details about each timer, look up the registers in the datasheet.
With each timer goes a timer interrupt service routine (ISR). These perform the action required when an interrupt occurs. It's a good practice to exit an ISR as quickly as possible. Only do the things which are really time-critical, but for the rest set a flag to indicate that the interrupt occurred. Then in the main loop you continuously check that flag, and when it is set, perform the necessary actions. Don't forget to clear the flag when you're done.

I appreciate the code here but I want to do hardware interrupts. I wasn't able to make it clear because I didn't know but I want to make the robot stop when it senses the edge of a table. Therefore I believe that would be a hardware intterupt with a rising edge or something.

@EinsteinJr.: then could you please remove reference to the watchdog timer in your question? It's misleading to say the least.


text:
Simulink Legacy Code Tool - custom Arduino servo write block problem
I'm trying to create my own servo.write block in Simulink for Arduino DUE deployment (and External Mode). Before you ask why if there is one available inside the Simulink Arduino Support Package, generally my final goal is to create a block that will use Arduino servo.writeMicroseconds function (there is no out of the box block for this one) but first i want to try with something simple to debug to see if i can get it to work....
I've been using this  guide (https://www.mathworks.com/matlabcentral/fileexchange/39354-device-drivers) and one of working examples in there as a template and started modifying it (originally it implemented Digital Output driver). I took the LCT approach.
The the original digitalio_arduino.cpp/h files from the guide (example with digital read/out) were the files I modified as they were working without any issues out-of-the-box. Step by step i made following modifications:

Remove DIO read (leave only write) from CPP and H files

Change StartFcnSpec to digitalIOSetup and make changes in H file so port is always in OUTPUT mode

Include Servo.h library within CPP file and create Servo object

Up to this point, all edits went fine, no compile errors, all header files were detected by Simulink and diode kept blinking as it should so the code actually worked (i ran it in External Mode).
But as soon as i made the final modification and replaced pinMode() with myservo.attach() and digitalWrite() with myservo.write() (of course i changed the data type in writeDigitalPin function from boolean to uint8_T) the code, despite compiling and building without any issue didn't work at all. Specified servo port was completely dead, as it even wasn't initialised. Changing value on S-Function input didn't yield any results.
Of course If i replaced custom block with built in Servo Write block from Hardware Support Package, everything worked fine so its not hardware issue.
I'm completely out of ideas what could be wrong, especially that there are no errors so not even a hint where to look.
Here is the LCT *.m script used for generating S-Function:
def = legacy_code('initialize');
def.SFunctionName  = 'dout_sfun';

def.OutputFcnSpec  = 'void NO_OP(uint8 p1, uint8 u1)';
def.StartFcnSpec   = 'void NO_OP(uint8 p1)';
legacy_code('sfcn_cmex_generate', def);
legacy_code('compile', def, '-DNO_OP=//')

def.SourceFiles     = {fullfile(pwd,'..','src','digitalio_arduino.cpp')};
def.HeaderFiles     = {'digitalio_arduino.h'};
def.IncPaths        = {fullfile(pwd,'..','src'), 'C:\ProgramData\MATLAB\SupportPackages\R2021b\aIDE\libraries\Servo\src'};
def.OutputFcnSpec  = 'void writeDigitalPin(uint8 p1, uint8 u1)';
def.StartFcnSpec   = 'void digitalIOSetup(uint8 p1)';
legacy_code('sfcn_cmex_generate', def);
legacy_code('sfcn_tlc_generate', def);
legacy_code('rtwmakecfg_generate',def);
legacy_code('slblock_generate',def);

Here is digitalio_arduino.CPP file
#include <Arduino.h>
#include <Servo.h>
#include "digitalio_arduino.h"
Servo myservo;

// Digital I/O initialization
extern "C" void digitalIOSetup(uint8_T pin)
{
    //pinMode(pin, OUTPUT);
    myservo.attach(pin);
}

// Write a logic value to pin
extern "C" void writeDigitalPin(uint8_T pin, uint8_T val)
{
    //digitalWrite(pin, val);
    myservo.write(val);
}

// [EOF]

And here is digitalio_arduino.H file
#ifndef _DIGITALIO_ARDUINO_H_
#define _DIGITALIO_ARDUINO_H_
#include "rtwtypes.h"

#ifdef __cplusplus
extern "C" {
#endif

void digitalIOSetup(uint8_T pin);
void writeDigitalPin(uint8_T pin, uint8_T val);

#ifdef __cplusplus
}
#endif
#endif //_DIGITALIO_ARDUINO_H_

As I mentioned I've been using a working example as a reference. So I've modified it step by step to see if maybe there is a point when suddenly some error comes up but everything compiles yet does not work :/
I was wondering maybe if there is an issue with the Servo.h library or the Servo object and did some tinkering with these, like  i removed Servo myservo; line of code to see if anything happens and just like expected, i started receiving errors that Servo is not defined. If I did not include Servo.h at all or forget to add IncPath to Servo.h as before compile errors about Servo not being supported symbol or not being able to find Servo.h library - so actually the code seems to be "working" in a way, it seems to have everything it needs to work :/
I also looked at the MathWorks implementation of Servo Write block, the MWServoReadWrite to see how Arduino API is being used and no surprise, it's being used in the same way as I've been trying to. They include Servo.h, they are using servo.attach() and servo.write() to control the servo port. And that's it. Yet for them it works, for me does not :/
When I inspect generated C code that runs on Arduino (with my custom S-Function block in it), it seems that all the functions are placed exactly where they are supposed to be, they receive correct arguments. I expected at least that I'll find a hint in there, i.e.  missing code or anything else.

I'm not familiar with the Simulink Arduino plugin. Is there a main program file for the Arduino side? If yes, can you provide a link to it? Then we can look how it works. Is this compiled from inside Simulink? And also uploaded to the Arduino? Can you do basic debugging in the Arduino code, for example by turning on an LED right before writing to the servo?

Hey, the main program is generated on Simulink side too but you gave me an idea, i uncommented the digitalWrite code to see if the problem is only with servo and it turned out the cause of issue os on the Simulink side
Apparently, the generated main function is missing some routine that enables Arduino timers to control servos (Simulink decides to not enable it since it does not detect its own blocks.
Ill have to inspect how the code looks with built in Servo Blocks (of SImulink) and what is missing when I'm using custom blocks.

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


text:
I2S pins don't output audio in ESP8266
I am trying to use the ESP8266 to output some audio, but I'm having trouble making it work. I downloaded the library ESP8266Audio and am testing one of the examples they have in the repo, namely streaming MP3 from HTTP, (link). There is nothing however outputted from the I2S pins, D1 and D2, but only from RX pin. I have a dual amplifier, so I need the analog signals, not the digital. So I want to ask if there is something extra I need to add in the program, or if I'm using the wrong pins. Any help is appreciated :)

I2S is a digital protocol that controls a CODEC chip which you need in between your ESP8266 and the amplifier.

Shouldn't there be a built-in I2S module in the ESP8266? I'm using the Nodemcu model, according to the docs, there is one accessible through pins D1 and D2. I'm quite new to microcontrollers so pardon me.

I'm not familiar with the internals of the ESP8266. I know there is one in the ESP32, but it's awful because of noise from the WiFi. If there is one in the ESP8266 it will be as bad.

There might be a built-in I2S module, but an I2S module does not output an analog signal. The ESPs have no DAC, so you definitely need additional hardware in form of a I2C-DAC/codec IC. There's no software solution.


text:
What is the minimum sampling rate in ADC in Arduino due?
I am looking for a very low frequency application like below 300Hz. What is the minimum sampling rate in Arduino due? I am very new to this. I see in the datasheet that max sampling rate is 20MHz.

The minimum sampling rate is one sample per eternity.

Don't you mean maximum sample frequency instead of minimum?

No i meant Like maximum sampling rate is there a minimum sampling rate?

Why should there be a minimum sampling rate? You trigger each sample yourself. The sample rate gets smaller when you wait longer between the samples. You can wait as long as you like, so you can get a samling rate arbitrarily small. No minimum limit there

Think about it: if you configure the Due to sample at 20Msps but only enable the ADC long enough to perform just one sample, what is the sample rate?

There is no "minimum" sampling rate.
You can better understand why that would be if you first understand how Successive Approximation ADCs operate.
An SAR ADC is simply a small capacitor, a DAC, and a comparator - along with a number of digital switches. When you perform a sampling the capacitor is first connected to the IO pin for an amount of time. The capacitor then charges up to the level of the incoming signal. Then the capacitor is disconnected from the IO pin and instead connected to the comparator. The DAC is then used to generate a sequence of voltages which the comparator then compares against the voltage in the capacitor - one voltage for each bit of resolution.
The maximum sampling rate is defined by how long the capacitor takes to be charged up by the incoming voltage. A bigger capacitor will take longer to charge up and thus give you a lower maximum sampling speed. A smaller capacitor charges faster, giving you higher sampling speeds.
However there is a big caveat: a smaller capacitor holds its charge for a shorter length of time, so getting an accurate reading from it when you have to hold the voltage for a number of cycles while you do successive comparisons can be hard. For this reason it's common to reduce the sampling resolution for higher sampling speeds: switch in a smaller capacitor, but take less time to sample it with less bits of data.
So from that it stands to reason that there is a minimum amount of time that you want the capacitor connected to the IO pin, and a predefined amount of time required to perform the comparisons, but there is no lower limit on how long the capacitor can be connected to the IO pin - it will just track the voltage changes for a while until the moment it's switched to conversion mode and the current voltage is captured (successive approximation ADCs are also known as sample-and-hold for this reason). And of course there is no requirement to immediately start a new sampling of the IO pin immediately you have finished a conversion. You can wait any amount of time before triggering a new ADC conversion. Seconds, weeks, decades...
This of course is all for manual triggering of the ADC. If you want automatic triggering from one of the internal timers then the minimum sampling speed will be whatever you can configure the timer to. And we can't tell you that, since timers can be configured to run from different clock sources, including your own external clock signal running at whatever speed you like.
So for automatic conversions you should not be looking at the ADC, other than to find what clock sources and interrupts can be used to trigger a conversion, and instead look at the relevant timer sections in the datasheet to work out what frequency you can configure those for to suit your needs.


text:
Nema 17 stepper motor speed problem
This code is quoted from here. May I know how to increase the speed of the NEMA 17 stepper motor further? I tried to increase the step speed to 2000rpm but it does not even work. It only works for less than 300rpm in my case.  The max rpm of the Nema 17 should be 5000rpm I googled. I used a 20V power supply lithium ion battery on the L298N motor driver. How do I solve this problem so that the Nema 17 can be faster? I believe the problem its with the code.
Thank you for reading and have a nice day :)

#include <Stepper.h>

const int stepsPerRevolution = 100;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  // set the speed at 60 rpm:
  myStepper.setSpeed(300);
  // initialize the serial port:
  Serial.begin(9600);
}

void loop() {
  // step one revolution  in one direction:
  Serial.println("clockwise");
  myStepper.step(stepsPerRevolution);
  //delay(500);
}

I tried to increase the step speed to 2000rpm ... how did you do that?

@jsotolamy Stepper.setSpeed(2000) ?

have you tried any of the stepper example code in the Arduino IDE?

Yes this is the code?

Stepper motors need to be gradually brought up to speed. If you try to go from zero rpm to anything over a few hundred rpm they will often just sit there and hum. Try AccelStepper (https://www.arduino.cc/reference/en/libraries/accelstepper/). This library provides functions to accelerate a stepper and move it to a certain position.
Also, I think you should know that Many stepper motors won't go over around 1000 rpm (this is dependant on your stepper and driver of course). It's also equally important to note that as you increase the speed of a stepper motor its available torque will decrease, so even if you are able to coax 1000+ rpm out of a nema 17 the torque available will be too low to use.


text:
Turn off backlight on 2.4" TFT screen
I have an Arduino Due and a 2.4" TFT screen shield this one.  I'm trying to turn off the backlight to save power but not having any luck.  I'm using the super nice MCUFriend library:
#include <Adafruit_GFX.h>
#include <MCUFRIEND_kbv.h>
MCUFRIEND_kbv tft;

It has worked great to make buttons and graphics, it's just the backlight I can't figure out.  There's a datasheet for the driver chip and it has the following section to Write CTRL Display, which is what I imagine I need:

So I have been trying to send 0x00 to register 0x53, but the display stays lit.  I've tried using MCUFriend_kbv to set it, then thought maybe I'm doing something wrong so I tried their sample LCD_ID_readreg.ino and added some lines:
readReg(0x54, 3, "Read CTRL Display");
lcdWriteRegister(0x53, 0x00);
readReg(0x54, 3, "Read CTRL Display after update");

I am not sure if I'm just misunderstanding something but the results show:
reg(0x0054) 00 00 00    Read CTRL Display
reg(0x0054) 00 00 00    Read CTRL Display after update

I guess I was expecting the register to say the backlight was on before I update it, but it says 00 even before I make the update- yet the backlight is clearly on.  Any idea what I'm missing?  Maybe it's the comment there about "control lines must be low"?  I have no idea what that means.  If you search the document for "control lines" nothing comes up.
The read above to 0x54 is because that's apparently where you read that register (unlike some where you call the same address to read/write):

the datasheet shows multiple backlight controls

I was recently also experimenting with this kind of display (ILI9341) and found this particular command not to do anything. I ended up controlling the backlight with a PWM signal, but it seems that your breakout board does not expose the backlight wire.

@jsotola yeah I saw those, but wondered if they did nothing too.  Like the driver chip supports it, but isn't physically wired up to the display or something.

@PMF there's certainly no pin with a label like that for sure.

That screen has no backlight control. The same chip is used on many LCDs and whether the inbuilt backlight control registers are used very much depends on the screen the chip is attached to.
If you want to control the backlight you will have to modify the shield to allow access to the right signal. I can't get a schematic for that specific screen, but from the images it looks like R2 on the underside may be a current limiting resistor for the backlight. Removing that resistor may turn off the back light, in which case you could replace it with a suitable transistor and similar resistor (you will have to check if it's high-side or low-side switched - does it provide power to the LEDs or sink it to ground) which you can control from a free GPIO pin.

Thank you very much for the clear answer with options :-) It makes a lot of sense.  I guess I'll just end up not using it as a shield so I can use a GPIO pin to just turn the whole display off when it's idle.


text:
How can I tell which pins I will have left available by looking at a shield?
I'm very new to Arduino and came to a point where I'm interested in playing with shields, such as LCDs.
For example, I really like the looks of "LCD 1602 with keypad" module, but it seems to be using a lot of pins.

By looking at a module / shield, how can I tell (or at least estimate) which pins will be used and which ones I will have left if I stack them with my Uno or Mega without printed schematics?

look at datasheet

My question is asking about figuring out (or estimating) by looking at a module.

If you look in the 'Tutorials' section of this page you can see the pins used. All of the buttons come through in one analogue input and you'll need a further 7 digital I/O pins. So 8 in total which would leave 5 analogue and 4 digital (I think) pins on an Uno.
As for how to tell which ones, does it matter in advance? I would just map the I/O in the sketch to suit. If you need to plan that far in advance though, it seems that J5 in this schematic shows which pins travel through the shield (i.e. are available to use in conjunction with the shield). Also J6 shows the 5 remaining analogue pins.

why dont you use an i2c adapter for this type of display?
search for i2c display module.
i2c only needs 2 wires for data and clock and 2 for power.
you can also easily locate the SDA and SCL pins on your arduino


text:
PWM signaling with Arduinos: What is the reason for the ground connection?
This may sound like a very dumb question and I apologise in advance.
I've gone through reading about PWM and working on some example sketches to control PC fan speeds using PWM and Arduino.
In all documents I read, it is mentioned that "PWM is a signal".
My questions:

Is PWM really a signal? To me, it looks like an electric current turned on and kept on for a certain time, then off for a while repeatedly. What makes this a "signal"?
If PWM is a signal, why do we need to connect the Ground from Arduino to the ground of the device to which "PWM signal" is being sent to?

This is confusing me because in my mind, for example, radio signals do not need a ground connection. The signal comes and gets read.

The ground wire going from my h bridge to arduino worked itself free recently (bottom left wire connection in the image) while my project was running. The arduino was sending PWM output to the h bridge at the time. The board overheated and died a permanent death in about 2 minutes. I assume this lack of grounding caused the board to overheat?

Is PWM really a signal? To me, it looks like an electric current turned on and kept on for a certain time, then off for a while repeatedly. What makes this a "signal"?

At the most basic, it is a signal because we call it such. Even a constant voltage can be a signal, signalling that e.g. a window has not been broken. A PWM signal indicates that we want to apply a certain fraction of full power to a load.

If PWM is a signal, why do we need to connect the Ground from Arduino to the ground of the device to which "PWM signal" is being sent to?

Because it is a voltage-based signal, and ground serves as the reference for this voltage. Voltage only exists between two points.

This is confusing me because in my mind, for example, radio signals do not need a ground connection. The signal comes and gets read.

Radio signals are photon-based; the oscillation of photons at a given frequency being broadcast from a location are what define the signal. Since frequencies are absolute, they can be discriminated without a (relative) reference.

Even in radio, the signal voltage is the instantaneous antenna voltage referenced to ground.


text:
What are the fundemental differences of different Bluetooth modules for beginners?
I'm a beginner to microcontrollers and electronics, albeit not really to computers and programming.
Starting out with the Arduino, I came to a point whereby I'm really interested in getting my prototype to talk to a mobile device or a computer to send and receive data (for example, send sensor data or receive commands).
Looking out, I've found out that there are different bluetooth modules with varying pricing points. Further research into differences did not reveal much to me as being a beginner, I am struggling to understand what to look out for or how to choose.
My question here is:
What are the fundemental differences of different Bluetooth modules for beginners, such as:

HC-05
HC-06
HC-07

And what should one look for when buying a simple Bluetooth module for Arduino?

As far as simplicity is concerned, HC05 would be the way to go. It is by far the most popular and there are a tonne of tutorials on using it (just a quick google search).
As for the differences:

The HC-05 module can build a connection to other modules. E.g. a Robot being a master and connecting to slave bluetooth module. Or in slave mode to make a wireless bridge to a notebook.
The HC-06 module only can be a slave. This makes it only useful for say connecting a notebook as a master to a robot with a slave module e.g. for a wireless serial bridge.
As for the HC07, support seems low so I would recommend sticking with HC05 or HC06

At the end of the day it comes down to your requirements. If you are only wanting to talk between the phone and your arduino than the HC06 would work fine, however if at some point in time you want to talk to another arduino, than hc05 would be the way to go.

Thanks Caleb, great answer! Do you have experience on Xbee BT modules?

I don't really know the differences but I've used the HC-06 modules. They are slave-mode only but that is what you need to replace a hard-wired terminal to your Arduino, such as your PC and and a USB cable, with a Bluetooth terminal. That probably covers 99% of cases where an Arduino or other MCU-based device needs to communicate to a PC or tablet that already has Bluetooth built in. For device to device communication, one of them would have to be a master, and I think that requires an HC-05.

Thanks @JRobert! Didn't know it was possible, very cool! Are you using your HC-05 to upload sketches, AND share data during operation (such as sensor info)?

The hc05 is master and slave, hc06 is only slave. The only real difference is the firmware which can be flashed, but not an easy task for a beginner.

Yes, I have uploaded sketches but it was too painfully slow to pursue it. But yes, these are designed as drop-in replacements for a wired terminal. @CalebBramwell - thank you for clearing that up. I haven't played with the different HC-0x variants yet.


text:
How to choose between AM230x and DHT22 temperature and humidity sensors?
I'm looking forward to getting an accurate humidity and temperature sensor.
Right when I decided to go with a DHT22 module, I saw AM230x (AM2301, for example).

How do I choose between DHT22 and AM2301?

Also check out the AM2320 which uses I2C.

The AM2301 and the DHT22(AM2303) are similar in a number of ways, both in price, specs, ranges and power consumption. They are usually cased a bit of a differently, with the DHT22/AM2303 being packaged with four pins (only three are in use), and the AM2301 (formerly called DHT21) is packaged with three cables and a small plug inside of the case.
I would choose based on the usage, if I'm going to use the sensor on a breadboard or a socket (going for the DHT22 pinned version), or if I'm going to have it standalone (the cabled one).
Here are links to the datasheets:
https://kropochev.com/downloads/humidity/AM2301.pdf
https://www.adafruit.com/datasheets/DHT22.pdf

Thank you @JeanROdegard. Could you please give information on their usage as well? Which one has easier to use libraries, more info on the web in your experience? Which one uses more energy? Etc. Thanks!

They both use the same library, accessible via the arduino.cc site, which makes them identical in the way of usage. That being said, it really seems to me that there is most information on the DHT22/AM2303 around on the web. Searching for the DHTXX series, the most information you're going to find is based on the DHT11 sensor, but I recon that's because it's half the price (its very, very slow thought). I must admit, in my opinion, I go for the DHT22 as it simply looks better. Difference in energy usage between the two, I don't have a clue, sorry to say.

The AM2302 has a built-in pull-up resistor, whereas the DHT22 does not. Apart of that and de different housing they should be technically identical.


text:
What is differences in usage between a HC-05 bluetooth module and a Zigbee HC-05 module?
I have seen commercial Xbee / Zigbee clones using HC-05 integrated inside.
Are they any different than regular HC-05 bluetooth modules?

What is differences in usage between a HC-05 bluetooth module and a Zigbee HC-05 module?

Bluetooth and Zigbee are two different communication protocols. The Xbee clones you are talking about a called BTbee.
As far as im aware the BTbee modules are the same hardware/firmware wise as the hc05/hc06 modules. The only difference being the BTbee modules are in the Xbee footprint, allowing you to plug them into Xbee/Zigbee sockets.

I see! That's precisely what I was wondering though, cheers! Are there any Zigbee clones that do not use Bluetooth?


text:
How to choose between Lithium-ion vs NiMH batteries to power Arduino on the go.
For my next project I'd like to use a battery pack to power my Arduino.
I would also like to get a small solar panel and charging module to charge these batteries when possible (during the day).

What is the right type of battery for this kind of application?
What are the differences given this context?
What are the factors I need to consider when choosing a rechargeable battery for this application?

Both viable. LiIon easier to manage well if managed well. Easier to destroy if managed badly. As LiIOn cell has 3V-4.2V range probably need an inverter with 1 cell or buck regulator with 2 which is annoying. Nimh give 1.0 - 1.2 V/cell so eg  6 give 6 - 7.2V for 5V system and 4 give 4 - 4.8V for 3V3 system. NimH are easier overall to build half well and get half good reults. LiIon are very unforgiving of bad treatment past a certain point.

@RussellMcMahon if you could post this as an answer I'd like to mark it as accepted. Thank you for these explanations.

Look at Battery University for many good ideas.
Both NimH and LiIon are viable for your application.
LiIon are easier to manage well if managed well.
ie do it right and they are easy to manage, but cut corners and they are easier to destroy.
NimH can be abused more with a slow degradation in capacity - although complete destruction is possible.
As a LiIOn cell has a ~= 3.0V to 4.2V range you'd probably probably need a step up inverter with 1 cell, or a buck regulator with 2 cells, which is 'annoying'. If you are prepared to use the cell over say a 3.4V to 4.2V range with an LDO regulator for a 3.3V system then you lose a significant amount of available capacity but increase battery cycle life substantially.
Nimh give 1.0 - 1.2 V/cell so eg

6 cells give 6 - 7.2V for a 5V system,
5 cells give say 5.25V - 7V if run down to 1.05V for a 5V system with a suitable LDO regulator, and
4 cells give 4 - 4.8V for a 3V3 system.

NimH are easier overall to build half well and get half good results.
LiIon are slightly harder to get going with in most cases, work very well if treated well, and are VERY unforgiving of bad treatment past a certain point.

In some applications you can forgo any regulator and run the Arduino directly off the battery, if you're willing to accommodate doing so.


text:
Serial communication between Arduinos
I'm trying to send data from Arduino Mega to UNO.
The master code sends characters 'x' and 'a' every half second to the slave Arduino UNO.
Slave receives the characters and switches the state of the onboard LED.
Here I'm trying to print some text in the beginning of the loop and the characters received.
Instead of the letters it is printing numbers as given below.
Why this line Serial.println('Soft serial avaialble') prints numbers?
How to print real text received from the master?
> 27749
> 97
> 27749
> 120
> 27749

Master code:
// Include the Software Serial library
#include <SoftwareSerial.h>
// Define a Software Serial object and the used pins
SoftwareSerial softSerial(8, 9);  // RX, TX
void setup()  {
    Serial.begin(9600);
    softSerial.begin(9600);
}
void loop()  {
    // Sends characters 'x' and 'a' every half second.
    if (Serial.available())  {
        softSerial.write('x');
        delay(500);
        digitalWrite(LED, LOW);
        delay(500);
    }
}

Slave code:
// Include the Software Serial library
#include <SoftwareSerial.h>
// Define a Software Serial object and the used pins
SoftwareSerial softSerial(8, 9);
// LED Pin
int LED = 13;

void setup()  {
    softSerial.begin(9600);
    Serial.begin(9600);
    pinMode(LED, OUTPUT);

}
void loop()  {
    Serial.println('Soft serial avaialble');
    if (softSerial.available())  {
        int com = softSerial.read();
        if (com == 'x')  {
            Serial.println(com);
            digitalWrite(LED, LOW);
        } else if (com == 'a'){
            Serial.println(com);
            digitalWrite(LED, HIGH);
        }
    }
}

In your slave, you've declared com as an int, so Serial.println() interprets it that way. If you want to keep it as int except for printing, cast Serial.println()'s argument to char:
Serial.println((char)com);

Thanks. It works!

In addition to JRobert's remark, note that strings in C++ are delimited by double quotes, thus:
Serial.println("Soft serial avaialble");

Thanks a lot. I wasn't aware of that.

Good catch, @EdgarBonet - I missed that one.


text:
connecting a small motor to arduino using a transistor
I want to connect a small motor (water pump) to an arduino, and I am not sure about the circuit.
The pump is small, works with 3.3V, but consumes 0.1A so I decided to use a transistor. The one I have is BF547, an NPN type small transistor. It supports currents up to 100 mA.
I measured the hfe (beta) of the transistor, and it is 370. The Vcc is 3.3V, and the current through the motor is 0.1 A, therefore:
A. the Ib equals to Ic/hfe = 0.1A/370 giving Ib = 0,00027A
B. with the Vb at 3.3V(pin voltage) and Vbe at 0.7 (datasheet) the Rb = (Vb-Vbe)/Ib = 9558 Ohm (10kOhm)
My questions are:

Did I calculate the base resistance correctly?
Do I need any additional resistor for the collector, next to the pump? Is it possible that more current flows through the collector-emitter?
According to the datasheet of BF457 100mA is the max Ic it can take. Should I limit the pump by adding a small (10 Ohm) resistor to it (33 Ohm[motors resitance] + 10 Ohm for 3.3 V gives a current of 76 mA)

I am attaching the schematics (linear voltage regulator is there only to stabilise the Vcc provided by an old dc power source I found)
Thanks a lot for any suggestions!

use a MOSFET for switching loads; cooler, simpler, more powerful, etc.

I like your thought process (even though it might not be completely correct), I've seen how little thought were put in for such simple circuit design in the Arduino community, including from some Youtuber celebrity who teaching Arduino and claims to have an EE degree.
BF547 is an RF amplifier transistor, not for switching application, it would be better to use an NPN transistor such as 2N3904 which is designed for switching application and has a Ice of 200mA.
Your resistor value is too high. If your motor is designed to operate at 100mA 3.3v condition, you would want your driver to provide AT LEAST that current. Assuming your are driving the transistor with 5V out from an Arduino, a 1k bias resistor would limited the Ibe to (5 - 0.7Vbe)/1000=4.3mA, take a very conservative DC current gain of 30 (it typically in the range of 30 - 80 for switching transistor, and hfe could be in the range of 100 - 300 when frequency go up, but this will not be the case for Arduino even you drive the motor using PWM), which will capable to deliver Ice of 4.3 x 30 = 129mA. This should meet your Motor requirements.
You would need a protection diode connected between 3.3V and collector with its cathode connect to 3.3V and its anode connect to the collector of the transistor. An 1N4148 (max If=200mA) would be okay for this specific motor, or even better, use any Schottky diode with current and voltage limit higher than your application).

4.6V - 1.2V (2 diode drops of 0.7V) = 3.4V, close enough for the motor if you are using a MOSFET as a driver. You can use a UIS rated MOSFET with a Vgs of less than 4 and it will work perfectly. the transistor will give you an additional voltage drop of about 0.7 Volts and needs a base resistor. If you want to guarantee the motor will not start during reset and setup() add a 10K resistor from the port pin to ground.


text:
Can Arduino take 19.5 V
I have a 19.5 V power adapter, can I safely connect it to my Arduino? I don't want to damage it. It is very simple, just lights some LEDs, and I don't want to burn the LEDs either.

probably not, but 19.5 V is not enough information ... what is written on the power adapter label?

You may want to say which Arduino you have, because there is some variation in a specific answer based on that.

45 W 19.5 V = 2.31 A
thats exactly what it says

I have a Arduino Uno Rev3

https://store.arduino.cc/arduino-uno-rev3 see the Tech Specs tab

You can do it but you will have nothing left from the regulator for LEDs etc. The best solution is to invest in a buck converter, they are only a few dollars from your favorite china supplier, sometimes even less then a buck. While you are at it purchase two or three you can then use them to generate other voltages as you progress with the Arduino. I use this method a lot, it is a way to use my old laptop power supplies. If you do not have one your next purchase should be a multimeter, even a cheap one is better than none. Then a logic analyzer, again less than $10.00 US. You could also purchase a 8 to 12V wall wart with maybe about 2 amp output and be safe while probably costing less then the buck converter. Have fun!

The Arduino Uno has a maximum voltage range of 6 to 20 v and a recommended range of 7 to 12 v
Using it at 19.5 v may work if the power supply is well regulated but it is uncomfortably close to the limits and dropping nearly 15v across the linear regulator on the Uno may cause it to get fairly hot.


text:
playTone function of Buzzer
I am making "Simon says" game using Arduino on TinkerCad.
I am facing issue in Buzzer sound function.
I want something like this:

Use the following steps to generate the tone for the red LED:
Play 440 Hz for 150ms
Wait for 1136us
Play 440 Hz for 150ms

Use the following steps to generate the tone for the yellow LED:
Play 784 Hz for 150ms
Wait for 638us
Play 784 Hz for 150ms

Use the following steps to generate the tone for the blue LED:
Play 587 Hz for 150ms
Wait for 851us
Play 587 Hz for 150ms

Use the following steps to generate the tone for the green LED:
Play 880 Hz for 150ms
Wait for 568us
Play 880 Hz for 150ms

I have following functions for the above:
 void playTone2(int tone, int duration) {
  Serial.println(tone);
  for (long i = 0; i < duration * 1000L; i += tone * 2) {
    digitalWriteGeneric(buzzer, true);
    delayMicroseconds(tone);
    digitalWriteGeneric(buzzer, false);
    delayMicroseconds(tone);
  }
}

void playTone(int tone1) {
  Serial.println(tone1);
  if (tone1 == 440) {
    playTone2(440, 150);
    delayMicroseconds(1136);
    playTone2(440, 150);
  }
  if (tone1 == 784) {
    playTone2(784, 150);
    delayMicroseconds(638);
    playTone2(784, 150);
  }
  if (tone1 == 587) {
    playTone2(587, 150);
    delayMicroseconds(851);
    playTone2(587, 150);
  }
  if (tone1 == 880) {
    playTone2(880, 150);
    delayMicroseconds(568);
    playTone2(880, 150);
  }
  if (tone1 == 2700) {
    playTone2(250, 250);
    delay(250);
    playTone2(150, 250);
  }

}

First there was only playTone code but I needed different values for different LEDs so I included playTone function and called playTone2 to it.
But the tones that I am getting are not accurate may be because of two functions. I will be able to resolve it if I could understand the working of playTone2 function. I tried but no use, kindly share how exactly playtone2 functions here so that I can edit my playTone function accordingly.

what's the specific problem? ... all you said is facing issue and not accurate, neither of which describe the actual problem

The problem is that the Buzzer sound with these functions is not accurate the delay is longer than expected.

you already said  not accurate

please run a simple sketch that plays the scale

Here is a simple sketch to test the tones used for each color of LED. I have not tested it with a speaker, but it compiles in the Arduino IDE, so perhaps it will work as is.
The call to delayMicroseconds() is "blocking" code, so you may want to change it to use "non-blocking" code, e.g. Use the BlinkWithoutDelay example in the IDE to make a micros() based timer.
/* Arduino Uno. IDE 1.8.9
   Sketch uses 2540 bytes (7%) of program storage space.
   Global variables use 28 bytes (1%) of dynamic memory.

   red    LED: Play 440 Hz for 150ms Wait for 1136us Play 440 Hz for 150ms
   yellow LED: Play 784 Hz for 150ms Wait for 638us Play 784 Hz for 150ms
   blue   LED: Play 587 Hz for 150ms Wait for 851us Play 587 Hz for 150ms
   green  LED: Play 880 Hz for 150ms Wait for 568us Play 880 Hz for 150ms
*/
byte tonePin = 8;

void setup(){
  pinMode(tonePin, OUTPUT);
  RedLEDSound();
  YellowLEDSound();
  BlueLEDSound();
  GreenLEDSound();
}

void loop(){}

void PlayTone(unsigned int m_frequency, unsigned long m_duration, unsigned long m_pause){
  tone(tonePin, m_frequency, m_duration);
  delayMicroseconds(m_pause);
  noTone(tonePin);
}

void RedLEDSound(){
  PlayTone(440, 150, 1136);
  PlayTone(440, 150, 0);
}

void YellowLEDSound(){
  PlayTone(784, 150, 638);
  PlayTone(784, 150, 0);
}

void BlueLEDSound(){
  PlayTone(587, 150, 851);
  PlayTone(587, 150, 0);
}

void GreenLEDSound(){
  PlayTone(880, 150, 568);
  PlayTone(880, 150, 0);
}


text:
How to enable exception handling on the Arduino Due?
While the question here gives some hints, the solution provided there does not directly work on the Due, since it uses a different compiler and toolkit. Also, the Due has more than enough flash for most projects, so that the extra code required for exception handling is acceptable. But as with the AVR-based boards, "-fno-exceptions" is automatically added to the compiler flags when using the Arduino IDE, preventing any throw or catch instructions to compile.
How can I enable exception support on the Due?

First, we must make sure the "-fno-exceptions" compiler flag is overwritten with "-fexceptions". In addition, we must link a separate library that includes the compiler support functions for stack unwinding.
Navigate to C:\Users\<UserName>\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.12 and create a new file platform.local.txt with this content:

compiler.cpp.extra_flags=-fexceptions
linker.elf.extralibs=-lsupc++

recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" -mcpu={build.mcu} -mthumb {compiler.c.elf.flags} "-T{build.variant.path}/{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.c.elf.extra_flags} -o "{build.path}/{build.project_name}.elf" "-L{build.path}" -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--start-group {compiler.combine.flags} {object_files} "{build.variant.path}/{build.variant_system_lib}" "{build.path}/{archive_file}" -Wl,--end-group -lm -lgcc {linker.elf.extralibs}

The last line should match the corresponding line in platform.txt, with an extra {linker.elf.extralibs} at the end (upgrading the toolkit might update that line, so you may need to compare the other parameters).
These lines add the -fexceptions to the compiler command line and the supc++ library to the linker input (otherwise you'll get errors about unresolved externals). After these changes, you can rebuild your project and use exception handling.
Some usage hints
The exception support on the Due requires about 40k of extra flash memory. Given it has 512k, this is usually acceptable. A bit of extra RAM is also used, but that seems to be small enough as well.
Since there are no standard exception classes defined (and the ArduinoSTL library doesn't compile on the due out-of-the-box), you'll have to write your own exception classes, i.e something like this:
class Exception
{
  private:
  const char* _msg;
  public:
  Exception(const char* msg)
  {
    _msg = msg;
  }

  const char* Message() const
  {
    return _msg;
  }
};

Use as:

void ThrowExceptionFunc()
{
  throw Exception("Something bad happened");
}

void ValidateExceptionHandling()
{
  try
  {
    ThrowExceptionFunc();
    Serial.print("Exception was not thrown:");
  }
  catch(Exception& ex)
  {
    Serial.print("Exception happened:");
    Serial.println(ex.Message());
  }
}

Note that Unhandled exceptions will terminate the program. An unhandled exception will cause the due to output a corresponding message to the serial console and then enter a deadend fail state.

Interesting.  I half-expected you'd have to create all of the "personality" routines also.

@timemage Me too. I have only tested it with the small example so far, but will be using it in a larger code base and then see whether it really works as expected. The project is really getting so big that using return codes all over the place is no longer an option.


text:
ESP32 TCP disconnect takes very long to be recognized
I'm using the following class to create a stream from a WiFi (server) connection. The client (a PC application) connects to the ESP32 and then issues commands over this connection. This works fine. When the client disconnects gracefully, the connection is reset and the ESP32 is ready for another connection. Only one client can connect at a time, but that's ok for now.
The problem arises when the client disconnects unexpectedly (e.g. if I just kill the process on the PC). The connection remains open for a very long time (10 minutes or so) until the ESP32 detects that the connection died. Within that time, no new connection can be established. In that state, I can still see it printing "Still connected" messages to the serial console, with reducing pace (the number of messages per second drops significantly until it finally gives up).
Is there a way to reduce the timeout on a dead connection? The (working) connection itself might be idle for long times as well, so just because no messages are received doesn't mean we can drop the connection from the ESP32 end.
The Connect() function below is called from loop() and in normal mode, it just prints "New client connected" and "client disconnected" messages.

class WifiCachingStream : public Stream
{
private:
    WiFiServer _server;
    WiFiClient _activeClient;
    bool _hasActiveClient;
public:
    WifiCachingStream(int port) :
    _server(port), _activeClient()
    {
        _hasActiveClient = false;
    }

    void Init()
    {
        _server.begin();
    }

    bool Connect();

    int read() override;

    size_t write(byte b) override;

    void maintain();

    int available() override
    {
        return _activeClient.available();
    }

    int peek() override
    {
        return _activeClient.peek();
    }

    void flush() override
    {
        // Do nothing. The implementation of WifiClient clears the _INPUT_ queue instead of the output queue!
        // _activeClient.flush();
    }

    bool isConnected() const
    {
        return _hasActiveClient;
    }
};

int idx = 0; // for testing only
bool WifiCachingStream::Connect()
{
    if (_activeClient.available() || _activeClient.connected())
    {
        if ((idx ++) % 10000 == 0)
        {
            // For testing: This is printed to the console, even after the communication has been killed on the PC
            Serial.println("Still connected");
            // This (attempts to) send a message over the link, which I would expect to cause the implementation to detect that the connection was dropped.
            Firmata.sendString(F("Still connected"));
        }
        return true;
    }

    _activeClient.stop();
    _activeClient = _server.accept();

    if (_activeClient)
    {
        Serial.println("New client connected");
        WiFi.setSleep(false);
        _hasActiveClient = true;
        return true;
    }

    if (_hasActiveClient)
    {
        _hasActiveClient = false;
        Serial.println("Client disconnected - entering WiFi low-power mode");
        // Low-power mode significantly increases round-trip time, but when nobody
        // is connected, that's ok.
        WiFi.setSleep(true);
    }

    return false;
}

// Other functions irrelevant

It's more or less a fact of life that having TCP detect a lost connection (ungraceful disconnect) takes a long time when nothing is being sent over it.
There may be some quaint and curious keepalive and time-out settings in the protocol itself, but implementing a heartbeat (call it an application-level keep-alive) that is sent by the client, and closing the connection from the ESP32-end when no heartbeat/keep-alive message has been received for a certain period, is probably your best bet and it will also give you precise control over the time-out time.

I'll consider this, but I don't really have control over the protocol. Adding a heartbeat message has been discussed, but not approved yet. I need to check that thread.


text:
rfid module not working (rc522)
i brought a rfid module which is rc 522 but when i upload the code it is not reading the card  even when i upload example code i have returned it 2 times and got it replaced but the same problem may i know the solution
#include "SPI.h" // SPI library
#include "MFRC522.h" // RFID library (https://github.com/miguelbalboa/rfid)

const int pinRST = 9;
const int pinSDA = 10;

MFRC522 mfrc522(pinSDA, pinRST); // Set up mfrc522 on the Arduino

void setup() {
  SPI.begin(); // open SPI connection
  mfrc522.PCD_Init(); // Initialize Proximity Coupling Device (PCD)
  Serial.begin(9600); // open serial connection
}

void loop() {
  if (mfrc522.PICC_IsNewCardPresent()) { // (true, if RFID tag/card is present ) PICC = Proximity Integrated Circuit Card
    if(mfrc522.PICC_ReadCardSerial()) { // true, if RFID tag/card was read
      Serial.print("RFID TAG ID:");
      for (byte i = 0; i < mfrc522.uid.size; ++i) { // read id (in parts)
        Serial.print(mfrc522.uid.uidByte[i], HEX); // print id as hex values
        Serial.print(" "); // add space between hex blocks to increase readability
      }
      Serial.println(); // Print out of id is complete.
    }
  }
}

this is one of the many codes i used

What gets printed? You have a lot of serial prints there, can you please edit the question and share what you see?

i just see nothing

Possibly you have wired it incorrectly. Without seeing any photos, links to the module you bought, or schematics, it is very hard, if not impossible, to say.

SDA                           10,
SCK                            13,
MOSI                      11,
MISO                     12,
IRQ                          UNUSED,
GND                      GND,
RST                                   9,
3.3V                                 3.3V,  i dont feel they are wrong


text:
Unable to write, or read a sensor's registers. Do I have an error in my code?
I'm trying to write to register the change some settings for a sensor I'm using (BNO055) and then read the same register to verify if the changes are successful.
However, the only value I'm able to read from the register is 1. Is the issue with my code or something to do with the sensor?
Thank you for your help. I've included what I think the relevant code is.
/**************************************************************************/
void write_register(uint8_t sensor_address, uint8_t register_address, uint8_t register_value) {
  wire_custom.beginTransmission (sensor_address);
  wire_custom.write(register_address);
  wire_custom.write(register_value);
  wire_custom.endTransmission ();
}

/**************************************************************************/
byte read_register(uint8_t sensor_address, uint8_t register_address, uint8_t bytes) {
  uint8_t result;
  wire_custom.beginTransmission (sensor_address);
  wire_custom.write(register_address);
  wire_custom.endTransmission ();
  wire_custom.requestFrom(sensor_address, bytes);
  result = wire_custom.read();
  return result;
}

/**************************************************************************/
void setup(void)
{
  wire_custom.begin(I2C_SDA, I2C_SCL, 400000);

  Serial.begin(115200);

  if (!bno.begin())
  {
    Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
    while (1);
  }
  delay(1000);
  bno.setExtCrystalUse(true);

  // updating range
  bno.setMode(Adafruit_BNO055::OPERATION_MODE_CONFIG);
  delay(1000);
  write_register (0x28, 0x0A, 0b00111000);
  // bno.setMode(Adafruit_BNO055::OPERATION_MODE_GYRONLY);
  delay(1000);
  register_1 = read_register (0x28, 0x0A, 1);
}

/**************************************************************************/
void loop(void)
{
  sensor_calibration ();

  sensor_data (x_placeholder, y_placeholder);

  // printing register 1
  Serial.print(register_1);
  Serial.print("\n");
}

I'm not familiar with the BNO055 but from the datasheet it looks like there are two register map pages (which can be changed via register #7) that can be either 0 (which is the default configuration at boot) or 1. The register you attempt to write (0x0A) is the low byte of the Y axis acceleration data (which presumably is read-only) when register page #0 (default) is selected or the Gyroscope configuration in page #1. Make sure the correct register page is selected.

Thank you for the assistance. I will experiment with this and update with the outcome.

Seems the setMode function from the library I'm using isn't working, so I will investigate that. Happy to accept the comment as an answer to the question, but isn't letting me. Thanks for your help.


text:
Clicking a mouse based on dwell time / how to code a rolling total of sensor measurements
I'm trying to write code that should result in a click of the mouse, based on dwell time. I'm getting data from a gyroscope to move the mouse around. I'm not sure what the best way is to approach this from a coding perspective.
My current thinking in pseudocode is below. Basically it should be a rolling total of the last X sensor measurements, which is then compared to a dwell size/radius variable.
On a high level, what would be a feasible approach? I tried a couple of times with for loops and different code, but didn't get anywhere close. I would really appreciate advice about whether my high-level approach is even feasible. Thank you!
update array with sensor measurements for (i =  dwell time) ();
    update sum of the array = + i measurement; - (i - size of the array) measurement at each sensor measurement
if at last element of array
    if sum of the array < dwell radius; click
    loop to the beginning of the array

Though I'm not sure if (i - size of the array) measurement is even possible to do, since it could result in negative i values.

where is the Arduino part of your question?

Well it's using an Arduino board, it is more of a C++ question but I was hoping to find an answer here because people might have dealt with similar issues on other arduino projects. Should ask in the C++ stock exchange?

you are correct, it is completely a C++ question ... i would start with long button press code ... instead of sensing a button press,  sense stop of motion ... after a time interval, desired event is asserted

Yes this is what I'm struggling with, how to sense the cessation of motion while working with the gyroscope data. I wait a bit for the suggestions here and then if required post in the other stack exchange.

that is not the problem you asked about ... please focus your question to the actual problem ... how to sense cessation of motion? ... remove all irrelevant references to mouse motion and dwell time


text:
Wire library causing samd21 based board to stop working
A bit of a general question, but asking in case someone has stumbled onto a similar problem before. A friend and I designed a custom PCB board based on the ATSAMD21G microprocessor. The board has a accelerometer connected on I2C and a NRF24 connected on SPI.
The rest of the functionality of the board is working as expected. My friend, who lives in a different country is able to use his copies of the board (all 5 copies were made by the same manufacturer in the same batch) without issue. But on my end, attempting to call the wire library causes loop to not execute. We wonder, if we are missing a potential software issue. We already checked that the core for the boards, the IDE and libraries are the same. And I have previously used the IDE for other wire.h based projects.

Does your board run your friend's .hex file ok?

Using J-flash (j-link programmer) I get a "cannot download file" error when I try to flash the .bin, .hex of the sketch he sent me. I will explore other options, but not sure how to flash atm. J-flash did work for flashing the bootloader.

why you don't upload over USB bootloader if you flashed it?

I wasn't aware this could be done in the IDE. Done some googling. So I should try to upload it via the command prompt, instead of j-link?

maybe try "Upload with programmer" from the Sketch menu

It turns out the microprocessor somehow got  locked when I was trying to upload the bootloader, and unable to get it fixed. I will have to let it go for now since I tried everything I could find online and couldn't unlock and erase it,


text:
How to efficiently code a long duration timer
I'm working on a battery-powered project. I'm trying to write code, which checks the battery voltage every 30 minutes and changes the color of a LED accordingly. Should I still be using millis() or is there a more efficient way to create a timer which tracks these longer time periods? Should I be concerned that the value of millis resets every 50 days, with an example timer like this:
bool timer(unsigned long &last_time, unsigned long period)
{
  unsigned long now = millis();
  if (now - last_time >= period) {
    last_time = now;
    return true;
  }
  return false;
}

Should I still be using millis() or is there a more efficient way to create a timer which tracks these longer time periods?

For longer time periods you really should use an RTC. You will get much better accuracy (assuming accuracy is what you want). You can also use an alarm on the RTC and use it to trigger an interrupt every 30 minutes and wake the MCU from sleep (so as to save precious battery power) to check the voltage.

Should I be concerned that the value of millis resets every 50 days, with an example timer like this:

Using that method, where you subtract the previous time from the current time, no, there is nothing to worry about. That is the recommended method to work around the wrapping of the millis() count.

thank you for responding. The board is based on the SAMD21G18A microprocessor (arduino zero). Do you think the following library will work, or would I need an external RTC? https://www.arduino.cc/reference/en/libraries/rtczero/

@ZhelyazkoGrudov That should work fine.

Thank you so much :)

A library I like for this kind of task is Ticker
#include <Ticker.h>

void batterycheck() {
    // called by battcheck ticker every 30 minutes
    // read_voltage...
    // set_led_color...
}

Ticker battcheck(batterycheck, 30*60*1000, 0);

setup() {
    battcheck.start();
}

loop() {
    battcheck.update();
}

There's no advantage over doing it manually but I found this library after writing almost exactly the same code for a project that had a bunch of timers running concurrently.

Thanks for linking this, I'll give it a test

There are various notions of efficiency, depending on what resource you
want to optimize for. For a battery-powered project, the most relevant
is likely to be energy-efficiency. Then, your code may not be the main
issue.
If you plan for your LED to be turned on continuously, this is going to
significantly tax your battery. Your first concern should then be to
minimize the power drain of the LED itself: make the current through it
as low as convenient, and maybe consider powering it through a DC-DC
converter in order to avoid wasting too much energy in the series
resistor. If your Arduino has a power-indicator LED, you should also
unsolder it. If it has a second microcontroller that it always on (like
the Uno), you should find a way to disable it.
Regarding the energy consumption of the CPU running your code, the only
way to be energy-efficient is to have it sleep most of the time, and
wake it up only when there is useful job to do. Unfortunately, the
Arduino core provides no standard way to sleep. You may have to look
into architecture-specific solutions, or search for a library that
abstracts this for you. On an AVR, for example, you may be able to
significantly lower the consumption by calling
sleep_mode() once within your loop(). This will put your
device in a “shallow” sleep mode, and it will be woken up by the next
timer interrupt (these happen every 1.024 ms). If you want to go to
deep sleep, you will have to arrange a wake-up source other than the
timer interrupt. An RTC could be an option. However, if you do not need
the 30 minute period to be accurate, you may as well use the
watchdog timer (which is ultra-low power) as an interrupt source.
There are many other things to be aware of when you care about power
consumption. I recommend reading Power saving techniques for
microprocessors, by Nick Gammon, which covers most of the
relevant issues. Note, however, that it discusses mostly AVR.

Thanks for the detailed answer, Edgar. Lots to unpack and consider. It's a SAMD21 based board, so I can use its library to put it into sleep, and then interrupt from the Bosch sensor to wake it up. For now will try to power LED through PWM to avoid hardware change, maybe that helps? The accuracy of the timer is not essential, so will explore watchdog vs rtc. And thank you for linking the article.

@ZhelyazkoGrudov: Yes, with PWM you can control the average current through the LED, which affects both its brightness and the battery usage.

Amazing, thank you!

Your posted code will never fail.
See http://gammon.com.au/millis
Let me put it this way. Does your clock "fail" at midnight?
Subtracting the start time from time now always works (even after 50 days) because of the way unsigned integers work.

Didn't know the article existed! Thanks for posting! Ashamed to admit I became one of those people asking the question. :)

Thank you @NickGammon for writing your millis article.  I use this instead of having to explain it with my arduino friends.  I figured this out myself many years ago ago and then stumbled on your explanation in your forum a few days later.  If I had just read it sooner you would have saved me some introspective head scratching.  My summary has always been "never compare times, compare durations" and "later minus earlier always works to compute durations - as long as the maximum durations of interest are within the range of the counter."


text:
Is it bad practice to multitask without timing constraints
Going through resources such as several things at the same time and with some greatly appreciated assistance on here I'm finally getting a grasp on how to multitask a microcontroller.
Most examples use the millis() approach to nonblocking programming. However, even in the link above the button state is being polled every loop (from what I understood).
So what confuses me is: is it bad practice to write functions, which poll sensor(s) and input(s) without timing constraints, i.e. at every iteration of loop?
Is this still consider nonblocking programming?
I've written some mock code to better illustrate what I mean. Thank you very much for reading through.
void loop() {
    Button();
    Sensor();
    LED();
    // ...
}

void Button() {
  // Read button(s)
  button_state = digitalRead(button_pin);
  if (button_state == LOW) {
    // ...
  };
};

void Sensor() {
  // Read sensor
  int sensor_state = analogRead(sensor_pin);
  if (sensor_state >= 150) {
    // ...
  };
};

Everything blocks a little bit, right? The point is that a delay() is (usually) a pointless blocking that could be better handled. It's better to use interrupts to monitor sensors, when practical. That gets by some of the "single thread" limitations of a sketch and lets the MCU do >1 things at a time.

Like often, the answer is: It depends.
Generally it is non-blocking programming, when you do only short things on each loop. What exactly can be considered short depends on the situation, meaning, what else you want to do.
For example: You are reading an analog value on every loop. The analogRead() will take about 100us (reference). I assume, that your sensor value is rather slow (so the time of signal above 150 would be rather long). Also you are reading a button with digitalRead(). The read takes about 3.6us (reference). So in total you have a loop of - lets say - 150us (with overhead and loop() iteration included). But the event, that you want to catch - the button press - will be in the ballpark of 100ms, which is a factor 667 greater, than the total time of your loop() (when no event happened). So in relation to the shortest event (the button press) all the reads can be considered non-blocking. (Though you could still get blocking through the code inside the if statements. Thats on you to investigate)
Non assume, that you don't have a button, but a digital signal, and you want to sense pulses down to 80us. Then your analogRead() would take too long and you could miss a pulse event. In this case analogRead() might be considered blocking.
So, to check if you are really using non-blocking code, you would need to ask yourself: Am I giving every code part enough time to execute right and to catch all the intended events? If yes, then you are non-blocking. If no, then you are blocking.

As a side note: Often polling is described as bad, but it really depends on the situation. In your case you poll the inputs sequentially, so every input gets polled at the same (total) rate at which your loop() runs. You are doing nothing else, so why should you lower the processing time by not use polling? The saved time cannot be used better on a microcontroller (in contrast to a PC, where the saved CPU time could be given to a different program).

Hi Chris, thank you for the answer. It was very clear and helped me understand the thought process behind the decision-making so now I have a better framework to work off of.

If you are running off battery, then you should consider having the
microcontroller sleep as much as possible, and not poll the sensors more
often than needed. AFAIK, the Arduino core library provides no facility
for managing sleep, but some third-party libraries are available for
that purpose.
If you project runs off mains power, then there is no point in adding
the complexity of sleep management. Unless your sensors are really slow,
polling them at each loop iteration is generally fine. Specifically, for
a push button, the documentation of the Bounce2 library states that
the button update method should be called on every loop iteration.

Hi Edgar, thanks for responding again. It's going to be running off of a battery so I will have a think about how to implement.

@ZhelyazkoGrudov: Achieving low power consumption is a vast subject. I suggest you start by reading Power saving techniques for microprocessors, by Nick Gammon.

Oh sweet! Thanks for the pointer, I'm sure I would have had another great moment just starting in the middle of nowhere otherwise.


text:
Writing to partially reserved registers of sensors
I'm trying to change the range of a gyroscope I'm using and there is the following guideline:

it is recommended to mask out
(logical and with zero) reserved bits of registers which are partially marked as reserved.

I tried reading about bit masking with the bitwise operators and I feel I understand it for trying to read only certain bits, but not for writing.
For example, how would I write to the following register, masking out the 2 bits which are reserved?

You always write a whole byte when you set the register. You only need to "mask out" those bits if there's a danger that you may inadvertently set them to 1, for instance through some value over flow from other bits when combining values together to form that byte.
If you're not doing that then there's nothing to mask out.  For instance if you just want to set a specific set of bits then just set that value - 0b00101001 is going to be 0b00101001 whether you mask it or not.
If you decide you really want to mask a value, for instance if you are writing a library and you have no control over what an end user may decide to pass to a function, then & (or &=) is your friend:
uint8_t val = 0x55; // 0b01010101 in binary
val &= 0b00111111; // or 0x3F if you want to use HEX
// val is now 0x15 since bit 6 has been "masked" to 0.

Thank you for the detailed and informative answer. In your example, do you mean bit 7 and bit 8 are masked out?

6 and 7. You start counting bits from 0.

Thank you again :)


text:
Issue with simple timer based on millis()
Sorry to bother but I am at my wits end. I'm experimenting with timers, and starting very simple. The following code is supposed to print the content of a variable each time an interval of time has passed, then update that variable. But for some reason I'm getting no output on the serial monitor.
I have used the serial monitor before on other projects without issue, so I'm not sure what the problem could be.
Is there any error in my code?
unsigned long previousMillis = 0;
unsigned long currentMillis = millis();
const long interval = 1000;

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

void loop() {
  if (currentMillis - previousMillis >= interval) {
    Serial.println(previousMillis);
    previousMillis = currentMillis;
  }
  else {
    ;
  }
}

//  previousMillis += interval;

Simple problem: You are not updating the currentMillis variable anywhere. Its value does not magically update, when you have once assigned the value of millis() to it. Insert currentMillis = millis() right at the start of the loop() function.

Thank you for your response. I thought it automatically updated with the latest value of millis() constantly. So it would only update at each iteration of the loop? If you would like to post this is an answer I can accept it if that makes any difference to you, because it is very helpful to me.

Since currentMillis is just a simple variable, it will not automatically update. In fact the initialization with millis() in global scope is unnecessary. Just initialize the value with 0. At the time, where the global variables are created, the time is 0ms anyways.
You need to update the currentMillis variable everytime, before using it. So just insert
currentMillis = millis();

right at the start of the loop() function.

Thanks again for your help.


text:
Serial connection between Processing and Arduino doesn't work
I'm trying to connect an Arduino Nano Every and Processing via serial. I'm getting no errors on either side, and the arduino serial functionality works otherwise on the arduino IDE.
I'm connecting on the right port, and the port is busy while the processing code is running (as you would expect), however, the variable inside the arduino is not updating. In fact, the whole if serial.available statement is not executing.
Arduino:
int var;

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

void loop() {
  if (Serial.available()) {
    var = Serial.read();
  }
  Serial.println(var);
  delay(100);
}

Processing:
import processing.serial.*;

// The serial port
Serial myPort;

void setup() {
  // List all the available serial ports:
  printArray(Serial.list());
  // open port
  myPort = new Serial(this, Serial.list()[2], 9600);
}

void draw() {
  try {
    myPort.write(1);
  }
  catch(Exception e) {
    // Print detailed error information to the console.
    System.err.println(e);
    e.printStackTrace();
  }
  delay(50);
}

PS. Asked moderator to close previous post on topic.

How do you know that it doesn't work? I don't see you reading anything from the serial interface in the processing sketch. What are you actually seeing?

I read the variable in the arduino IDE serial monitor, after waiting a few seconds and stopping the processing app. If the processing app successfully writes to the arduino, then var = 1, however, it's = 0.

how would you ever know the value of var?

I print it on the serial monitor in arduino IDE. Am I missing sth fundamental?

I'm not sure how it is with the Nano Every, but other Arduinos reset every time that you reopen the serial port. And that happens when you close the processing program and open the Serial Monitor. If that is also the case with the Nano Every, then you cannot every get anything other than zero, because the value send by the processing sketch is already forgotten due to the reset of the Arduino. You would need to read and print from serial inside your processing sketch

Thanks for the comment Chris. But wouldn't the variable be updated and stay updated? So it gets set to a value, and even if there is no serial open it should stay at the value it was set? My understanding is, I'm sending a value with my processing code to the arduino, and storing that value in a variable. Then, I close down serial connection with processing and try to read the value of the variable. However, the variable has not been updated as I would expect it to.

Most Arduinos (and the Nano Every is one of them) will reset when the serial connection is reopened (You close it by closing the processing sketch and open it again with the Serial Monitor). Variables are stored in RAM, which gets wiped and reinitialized after a reset or power loss.
So this basically happens: You send the data from processing over serial to the Arduino. The Arduino puts the received value into the variable in its RAM. Then you close the processing sketch, effectively closing the serial connection. Then you open the Serial Monitor, which opens the serial connection again. This triggers the reset of the Arduino and wipes the previous variable value from the RAM. You will only ever see the initial variable value (zero) this way.
You can prevent a reset over serial if you connect a capacitor between the Reset pin and ground.
Though I would say this is probably not what you really should do. Instead just read the data from serial inside your processing sketch. After you have read it you can print it.

As a side note: The reset-on-serial-reconnect functionality is used for programming the Arduino over serial (through the USB cable). The new program is written into the program memory (flash) by the bootloader. The bootloader runs directly after a reset/power-on. So to upload a new program to the Arduino the Arduino IDE has to first reset the Arduino to talk to the bootloader.

Well this is something I would have never thought to consider. Thank you so much, Chris. I was completely stuck here!

I suppose this reset only happens if you open/close the serial connection from the PC. Since repeatedly opening and closing the serial monitor from the IDE doesn't cause the same reset?

If you open your Processing sketch and send the data to the Arduino without opening the serial monitor in the Arduino IDE, the data gets through. Here is your Arduino sketch which is slightly modified. Disclaimer - tested on an Uno.
There are other options for serial monitors which may work (varies by OS), as well as other options to interface between Processing and Arduino, such as Firmata
int var;

void setup() {
  Serial.begin(9600);
  pinMode(2, OUTPUT);
  digitalWrite(2, LOW);
}

void loop() {
  if (Serial.available()) {
    var = Serial.read();
    digitalWrite(2, HIGH);
    delay(50);
    digitalWrite(2, LOW);
  }
  Serial.println(var);
  delay(100);
}

EDIT
Arduino IDE version 1.0.6.2 with Processing 2.2-ish would let you open the serial monitor in the Arduino IDE and "monitor" the data. Since you can't do this anymore, what about making your Processing app open 2 windows. One window could be a home brewed serial monitor, and the other the sketch you are working on. Using Processing version 3.5.3, it is only 15 lines of code to open up 2 windows. I'm sure the actual implementation of such a system would be a good challenge.

@Zhelyazko Grudov - Another way to open 2 windows: https://gist.github.com/atduskgreg/666e46c8408e2a33b09a Just copy and paste both sketches into ONE sketch and try it :)

Thanks @ve7JRO for the answer. I think the issue was what Chris mentioned below with the reset. However, this is very useful information for debugging, so thank you for sharing.


text:
How can i develop a fish tank automation using arduino
As a part of my final year Engineering project I would like to develop a  fish tank automation system. In my project I need to check the quality  of water concurrently and also I need to check the sedimentation of my fish tank. Which are the different types of sensors  used for this?
How can i connect it to my arduno uno?

Have you tried googling for corresponding sensors? What were the results and how exactly didn't they help you? What have you already tried to design your project?

what does quality of water mean? ... what factors are you checking? ... what does sedimentation mean? ... what are you checking?

you can check turbidity with a shielded light sensor and a light emitter; like an analog beam interruption sensor.

You can try water temperature controlling idk if you are in a winter season having zone in earth like auto turning on the heater, can auto turn on UV light when dark etc.or may be filter status by connectivity measurements or pH level you have to draw a diagram of what you will do before going to electronic programming.what will you do so on

You're starting from the wrong end of the problem (the electronics).
First, you need to decide the requirements for your system.

Write down what your system is supposed to do: measure something? When & how often? Save or display the measurements? Control something based on the data? How precise must that control be (e.g. +/- .5 degC) (precision can be expensive)? Control something based on something other than measurements (except, perhaps, time?

Once you understand the requirements, then you can write down the steps the system should take to meet them; it doesn't need to be code (and probably shouldn't be, just yet).

Decide on what to measure and how to measure it. Can't figure out a sensor for something? Maybe you can infer it from something you can sense. Or perhaps learn how quickly or how often that 'something' goes out of spec and restore it without a measurement (e.g. you presumably already know how often and how much to food to dispense).

Now you can start thinking about electronics, sensors, and code, having a pretty good idea of what you will need to know, to acquire, and to create, to build your project (whether or not you'll be expected to actually build one).

This is an Engineering approach to design and it is almost certain your project is intended to show that you know how to do this, much more than to show you can run a fish tank.


text:
Arduino Uno + SIM808 EVB 3.2.4 not working properly?
So recently I found this tutorial online about the SIM808. It looked super cool so I ordered the sim808 evb 3.2.4 off amazon. Hooked up the module and connected the RX (11) and (10) TX pins.
Here is the code I'm working with tried to follow along as best I could with the tutorial but now I am completely confused, purchased a SIM card activated the SIM card and it seems to be connecting just fine
In the serial monitor sometimes I receive this: 14:05:06.243 -> Init Success, please send SMS message to me!
But most of the time I'm receiving this: 14:04:37.586 -> Sim808 init error
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>
#define MESSAGE_LENGTH 160
char message[MESSAGE_LENGTH];
int messageIndex = 0;
char MESSAGE[300];
char lat[12];
char lon[12];
char wspeed[12];
char phone[16];
char datetime[24];
#define PIN_TX 10
#define PIN_RX 11
SoftwareSerial mySerial(PIN_TX,PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,
void sendSMS();
void getGPS();
void readSMS();
void setup()
{
mySerial.begin(9600);
Serial.begin(9600);
//******** Initialize sim808 module *************
while(!sim808.init())
{
Serial.print("Sim808 init error\r\n");
delay(1000);
}
delay(3000);
Serial.println("SIM Init success");
Serial.println("Init Success, please send SMS message to me!");
}
void loop()
{
//*********** Detecting unread SMS ************************
messageIndex = sim808.isSMSunread();
//*********** At least, there is one UNREAD SMS ***********
if (messageIndex > 0)
{
  readSMS();
  getGPS();
  sendSMS();

  //************* Turn off the GPS power ************
  sim808.detachGPS();

  Serial.println("Please send SMS message to me!");

}
}
void readSMS()
{
Serial.print("messageIndex: ");
Serial.println(messageIndex);
sim808.readSMS(messageIndex, message, MESSAGE_LENGTH, phone, datetime);
//*In order not to full SIM Memory, is better to delete it
sim808.deleteSMS(messageIndex);
Serial.print("From number: ");
Serial.println(phone);
Serial.print("Datetime: ");
Serial.println(datetime);
Serial.print("Recieved Message: ");
Serial.println(message);
}
void getGPS()
{
while(!sim808.attachGPS())
{
Serial.println("Open the GPS power failure");
delay(1000);
}
delay(3000);
Serial.println("Open the GPS power success");
while(!sim808.getGPS())
{
}
Serial.print(sim808.GPSdata.year);
Serial.print("/");
Serial.print(sim808.GPSdata.month);
Serial.print("/");
Serial.print(sim808.GPSdata.day);
Serial.print(" ");
Serial.print(sim808.GPSdata.hour);
Serial.print(":");
Serial.print(sim808.GPSdata.minute);
Serial.print(":");
Serial.print(sim808.GPSdata.second);
Serial.print(":");
Serial.println(sim808.GPSdata.centisecond);
Serial.print("latitude :");
Serial.println(sim808.GPSdata.lat);
Serial.print("longitude :");
Serial.println(sim808.GPSdata.lon);
Serial.print("speed_kph :");
Serial.println(sim808.GPSdata.speed_kph);
Serial.print("heading :");
Serial.println(sim808.GPSdata.heading);
Serial.println();
float la = sim808.GPSdata.lat;
float lo = sim808.GPSdata.lon;
float ws = sim808.GPSdata.speed_kph;
dtostrf(la, 4, 6, lat); //put float value of la into char array of lat. 4 = number of digits before decimal sign. 6 = number of digits after the decimal sign.
dtostrf(lo, 4, 6, lon); //put float value of lo into char array of lon
dtostrf(ws, 6, 2, wspeed);  //put float value of ws into char array of wspeed
sprintf(MESSAGE, "Latitude : %s\nLongitude : %s\nWind Speed : %s kph\nMy Module Is Working. Mewan Indula Pathirage. Try With This Link.\nhttp://www.latlong.net/Show-Latitude-Longitude.html\nhttp://maps.google.com/maps?q=%s,%s\n", lat, lon, wspeed, lat, lon);
}
void sendSMS()
{
Serial.println("Start to send message ...");
Serial.println(MESSAGE);
Serial.println(phone);
sim808.sendSMS(phone,MESSAGE);
}`

the code is a mess. please format it properly so that it is legible

why are you asking if it is working properly? ... do you not know what you want it to do and what it is doing?

I recommend you to use AT command ..then using some kind of library. You need to dig into library for better information.
https://randomnerdtutorials.com/sim900-gsm-gprs-shield-arduino/
Go through this link....this will give you a rough idea.