text:
ISR vs state change detection on button
Hi I was wondering if a digitalRead state change detection could be saved in a variable like counter++, just like you can do with an interrupt function.
arent these two operations almost the same?
like have an external circuit with a  reed closed by a magnet, to take the place of a momentary push button,

The 2 techniques described in the question are commonly referred to as "polling" and "interrupt".  Either will work.  Polling is suggested for beginner programmers and when time is not important. Such as scanning an array of human controlled buttons. Whereas interrupts are usually reserved for when time is of the essence.  Such as synchronizing a camera's release switch with a strobe flash.
Also, consider polling as a simple to understand, easy to test sequence of events that will always happen in the expected order.  While interrupts can happen at any time and all interruptible code has to be written to tolerate being interrupted.
Often, debouncing is the more difficult problem when combining mechanical switches and microprocessors.  A good fundamental exercise is to write your own debounce program.  However, an Arduino debounce library is already available.

The fundamental difference between polling (digitalRead()) and interrupts is that of time. Yes, I know we discussed time and interrupts at length in another of your questions, but I'm not talking about recording time here.
With an interrupt you know (pretty much) when an input changed. With polling you can only know that it changed sometime in the past.  An interrupt occurs at the moment an input changes state (what that change is depends on the type of interrupt). That makes it possible for your program to remember that time (by querying millis() for example).
With digitalRead() the only way you can know if an input has changed state is if you manually remember what the old state was and compare it, so all you can know is that it's changed since last time you examined the input, and if those times are far apart all you can say is "sometime in the past X milliseconds it changed state".
If your input changes faster than that polling time you won't know about it. For instance, if you end up polling every 10 milliseconds, and you have a pulse on your input pin that lasts 4 milliseconds (that's an eternity in microcontroller time) but occurs part way between two polls (say from 3ms to 7ms) you'll never see it.
To put it more formally, to detect a signal of frequency f Hz you have to sample the input at minimum 2f Hz (or a period of 1/(2f) seconds. This is known as the Nyquist-Shannon theorem and applies equally to both digital and analog sampling (digital sampling is merely 1-bit analog sampling).
With interrupts, since you're not sampling based on periodic checks, but instead using a hardware trigger to detect an edge (rising, falling, or changing), and assuming you have interrupts enabled at the time an edge arrives on the pin (some code disables interrupts, and interrupts can't trigger while another interrupt routine is running), you instantly know about it regardless of whatever else you are doing.
Interrupts are said to be asynchronous, whilst polling is known as synchronous.
Which method you should choose depends on many factors: the speed of your signals (pulses from sensors, buttons pressed by humans, etc), what else your program is doing, how critical it is that you detect an input state change, etc.  For slow signals, like a button, polling is perfectly fine. For high speed signals, like a hall-effect sensor or a reed switch triggered by a bicycle wheel mounted magnet, interrupts are more suitable.
For some signals (especially things like revolution counters, frequency counters, etc) where you have a large number of brief pulses coming in over a period of time where all you want to do is count them, there are even better options than interrupts.
The internal timer peripherals of the chip can run in a number of modes that are designed just for this scenario.  You can run a timer with the clock source as an IO pin. That means that on each incoming pulse to that IO pin the timer counts up by one. That happens completely independently of your program. You just read the current count from the timer and reset it to 0 to start counting again at a period to suit you.
Another mode is Input Compare mode.  This combines normal interrupts with a timer. The timer runs in the background at a pre-defined rate, and as soon as a specific input changes state (each timer has specific inputs for this) the timer is frozen an interrupt is triggered.  This gives highly accurate time measurement of incoming signals since it's not subject to the time taken to service the interrupt. The timer is frozen immediately and you can query that time when the system is able to service the interrupt.
There is no native support in Arduino for either of those timer modes, though, so you would have to either find an advanced library that configures the timers in that way for you, or read and understand the datasheet and manually configure the timers in the right way.

so, for example, a state change, like a button toggle, is this an example of polling of the digital pin that is being read by digitalRead()? like, if a momentary button is pushed, its useless for a toggle, but if you scan the pin for a change, a HIGH or LOW, and save that change, then toggle off that change, (latch) is this is an example of polling?

Polling is merely the act of using digitalRead.

cool, so the MCU is polling when digitalRead is used, when there is a change, save the change, and thats the state change correct?

Polling means "tell me the state of the port right now". What you do with that information is up to you. By comparing two polled states you can find a change in state.

so whats the difference between a state change and state detection change? How does the MCU tell the difference?

"By comparing two polled states you can find a change in state" so digitalRead polls, then a change occurs, we can save with a variable, then compare with "if"?

I have no idea what a "state detection change" is.

state change detect means like a button press or release. its in the arduino sketch libary examples

A state change detection is what your sketch does with the information returned by successive polls.

static bool lastState = HIGH; bool state = digitalRead(3); if (state != lastState) { lastState = state; if (state == HIGH) { buttonReleased(); } else { buttonPressed(); }}

ive seen it coded allot simplier than that dude, but thats what Im studying

That's pretty much the simplest, however that detects both state changes (HIGH->LOW and LOW->HIGH). If it's only one you need then you don't need the ELSE.

yeah your right, sorry, thats pretty much the same code, just they had it different

a state change, then a state detection change

I still don't know what you mean by a "state detection change". That makes no sense at all. A change in the detection of a state...? How does that work? There's only state changes, and the detection of those changes of state.

The state changes are what you are looking for, and the "detection" is the method of finding them.

state change means a latch, not a momentary push, but the edge detection is the next change to look for, maybe used wrong word

A state change is a change in state. There are only two states that you can get from a digital pin - LOW and HIGH. Detecting those state changes doesn't give you a "latch", it only tells you when (and in what direction) the state changes.  What you do with that information (use it to toggle another "latch" variable, add one to a counter, whatever) is entirely up to you. All that side of things is encapsulated in the "buttonPressed()" and "buttonReleased()" functions in my example just now. Those functions do "whatever you want to do when a button is pressed".

like you want to toggle a button for 2 functions. just a button push does nothing but a glitch, so you got to have states. but you want to do the state change on a button push or release so use edge state detect

why are you using this function buttonReleased()? seems all you have to do is use if digitalRead(pinA) != state{ state = digitalRead(pinA); if (digitalRead(pinA)== HIGH ) { toggle another variable}

That function is a "placeholder". It means "I don't know what you want to do here, so I'll put something in to show where your code would go, and name it appropriately". It is not a function that exists. It is for you to replace with your own code to be run when the state changes in the appropriate way.

That code you replace it with could be "rev++" for example.

my logic is its like a ladder or steps, one condition depends on the previous one, and build from that, like the MCU is polling the pin, if there is a change, save it and build off of that. is that correct?

like if a newb like me is trying to advance from the LED on/off to a button toggle, we got to understand the logic first. and when I mean toggle I mean the LED stays on with one button push.

The LED toggle code is separate from the pin state change detection code. The LED toggle code is triggered by the pin state change detection code, though. "IF the pin has changed state AND that change is LOW->HIGH THEN toggle the LED"

instead of AND just use another nested "if"?

Yes, it has the same effect, with the added benefit of having a simpler "else" if you need it, and splitting out the state saving from the specific HIGH->LOW case.

Comments are not for extended discussion; this conversation has been moved to chat.


text:
Burn bootloader to Arduino Uno using ARM-USB-OCD
I have ARM-USB-OCD created by OLIMEX. I am interested in can I use this to burn a bootloader to Arduino Uno. As I know Atmega 328P can be programmed using JTAG protocol which has also ARM-USB-ODC, so if it really can anyone give the circuit or something like this.
Here is my device (ARM-USB-ODC) manual.

Where did you get that information the Atmega328 supports JTAG? There is only the DebugWire interface. And as far as I remember, the AVR JTAG might be kinda incompatible with anything else. However the programmer is FTDI based, so it might be possible to use it as clasic serial programmer.

Atmega328P does not have JTAG pins.

Probably, but likely not easily
To program an AVR chip you likely want to use the AVR ISP protocol, which is not JTAG, but like JTAG is a synchronous serial protocol with a clock, a data line in each direction, and one additional control pin compared to the several mode/status pins of JTAG.
According to your link, the ARM-USB-OCD is based on an FT2232C USB interface chip.
avrdude documentation indicates that this is an interface it knows how to use, though it will likely take some study to figure out how.
The final question would be wiring - you'll need to figure out which JTAG-style signal names map to which FTDI functional pins, and how those should best be connected to AVR ISP pins in a way which avrdude can use.  Additionally, you'd have to make sure that any buffering between the FTDI chip and the pins is compatible with your needs, both in terms of data direction and voltage level.
Note that you can easily use any ATmega328-based Arduino as an ISP programmer for a same-voltage target - not really production worthy, but if you just need to move your project along today it's a handy option.

source: Stack Exchange

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

sort: votes


text:
Always 255-response in I2C between ATTiny85 (8MHz) and Arduino Uno
I tried to set up an I2C conversation between ab ATTiny85 (8MHz) and an Arduino Uno. However I always get a 255 response from my I2C slave. I am using Arduino 1.8.5.
What am I doing wrong?
ATTiny85-Slave Code:
#include "TinyWireS.h"  // wrapper class for I2C slave
routines
#define I2C_SLAVE_ADDR  0x26 // i2c slave address (38)

byte t=10;

void setup() {
  TinyWireS.begin(I2C_SLAVE_ADDR);  // init I2C Slave mode
  TinyWireS.onRequest(requestEvent);
}

void loop() {
}

void requestEvent() {
  TinyWireS.send(t);
}

Arduino Uno-Master Code:
 #include <Wire.h>
 #define I2C_SLAVE_ADDR  0x26 // i2c slave address (38)

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

void loop() {
  byte num;
  // read 1 byte, from address 0x26
  Wire.requestFrom(I2C_SLAVE_ADDR, 1);
  while(Wire.available()) {
    num = Wire.read();
  }
  Serial.print("num = ");
  Serial.println(num,DEC);
}

Where is the TinyWireS_stop_check ? The value of 255 is when the Wire.read() returns -1 which means that you did not receive valid data from the slave. You could run a i2c scanner and keep it running on the Uno, while trying to fix the wiring or the slave sketch. If that is working, then try to receive or send data.

@Jot - can you explain why Wire.read() would yield -1 when wire.available() is nonzero?

@ChrisStratton you are right, when wire.available shows that there is data, then -1 is not returned. I didn't think that through. I was trying to tell it in a common way, because there is an other possibility: when the slave behaves badly, perhaps the slave aknowledges with a ack to its address, but fails to send data so the sda stays high resulting in 255. Maybe there are even more possibilities when the slave does weird things.

Seems that  am not the only one. https://forum.pjrc.com/threads/48887-HELP-Teensy-3-5-I2C-ATTiny85-20PU-(TinyWireS-OnRequest-not-triggering!) ...strange :-(

It may seem that the current commit of January 2018 from the TinyWire library is corrupt. Try using an older version from 2017, for example this one: https://github.com/rambo/TinyWire/tr...72a13504bbfc4e
This solves the problem for me as well.
Source: Teensy 3.5 - I2C - ATTiny85-20PU (TinyWireS.OnRequest not triggering!) - Post #11

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


text:
List of sketches disappears off the bottom of my screen
v 2:1.0.5
The list of sketches disappears off the bottom of my screen and there is no scroll to reach them. This renders the IDE nearly useless.
Is there a solution?

Yes. Install a version of the IDE that isn't 10 years old.

There are several IDE for Arduino, do you know? Like UECIDE, for example.

get a bigger screen, or move some into a sub-folder

That issue has been fixed since the Arduino IDE 1.5.5 release, 4 years ago.
The version of the Arduino IDE you get from apt-get install arduino has not been able to be updated for years due to licensing issues. The versions available from various package managers may also be modified in ways that introduce new bugs. For this reason you should always install the official Arduino IDE version downloaded from:
https://www.arduino.cc/en/Main/Software

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


text:
SoftwareSerial + Serial.printlen() not working properly
I want to read a SMS message , find it's length and do some "substring();" operation on received SMS. My last two(2) statements do not work . How can I get correct answers? What are correct codes ?
#include <SoftwareSerial.h>
#include <string.h>
#include <ctype.h>
SoftwareSerial mySerial(2,3);

String TelephoneNumberText="";

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

  mySerial.begin(9600);
  Serial.begin(9600);
  delay(100);

  mySerial.println("AT+CMGF=1\r");    //Sets the GSM Module in Text Mode
  delay(500);
}

void loop()
{

 while(mySerial.available())
  {
   char s;
   s = mySerial.read();
   TelephoneNumberText = TelephoneNumberText + s;
   }

 Serial.println(TelephoneNumberText);           // this statement works

 Serial.println(TelephoneNumberText.length());  // this statement dose not works

 Serial.println(TelephoneNumberText.substring(0,3));// this statement dose not works

} // end loop

Serial.println(TelephoneNumberText);           // this statement works
Serial.println(TelephoneNumberText.length());  // this statement dose not works
Serial.println(TelephoneNumberText.substring(0,3));// this statement dose not works      /* please tell me correct codes for above two(2) statements */

Are you sure a string like this can be used?
Better anyway to not each time let a dynamic string be created, but use a fixed string e.g.
char TelephoneNumberText[16];

Set the length of the max number, and change other string functions accordingly.


text:
ESP8266: system_adc_read_fast() always gives 1024 as output
I need to use system_adc_read_fast (uint16 *adc_addr, uint16 adc_num, uint8 adc_clk_div) to get a sampling rate close to 100 ksps. I am able to achieve that using adc_clk_div = 32.
However, when I print out the values stored in adc_addr, I always get 1024. Why is this?
I have a NodeMCU v3. I have connected an electret microphone to it. The +ve terminal is connected to 3.3 V through 10 kΩ; GND is connected to GND. The +ve terminal is connected to A0 on NodeMCU.

simulate this circuit – Schematic created using CircuitLab
It works fine when I use system_adc_read() (except the sampling rate is then 10 ksps which is not desirable).
Sketch:
// Expose Espressif SDK functionality - wrapped in ifdef so that it still
// compiles on other platforms
#ifdef ESP8266
    extern "C" {
        #include "user_interface.h"
    }
#endif

ADC_MODE(ADC_TOUT);

#define num_samples 512
uint16_t adc_addr[num_samples]; // point to the address of ADC continuously fast sampling output
uint16_t adc_num = num_samples; // sampling number of ADC continuously fast sampling, range [1, 65535]
uint8_t adc_clk_div = 32; // ADC working clock = 80M/adc_clk_div, range [8, 32], the recommended value is 8

int i = 0;
unsigned long start = 0;
unsigned long total = 0;
unsigned long tim = 0;

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

void loop() {
    // put your main code here, to run repeatedly:
    #ifdef ESP8266
        // Serial.println(system_get_sdk_version());

        wifi_set_opmode(NULL_MODE);
        system_soft_wdt_stop();
        ets_intr_lock( ); //close interrupt
        noInterrupts();

        start = micros();

        // Serial.println(system_adc_read());
        system_adc_read_fast(adc_addr, adc_num, adc_clk_div);

        unsigned int tot = micros() - start;

        interrupts();
        ets_intr_unlock(); //open interrupt
        system_soft_wdt_restart();

        tim += tot;
        total += num_samples * 1000000.0 / tot;
        i++;

        for (int j=0; j<adc_num;  j++) {
            Serial.println(adc_addr[j]);
        }

        if (i == 100) {
            // Serial.print("Sampling rate: ");
            // Serial.println(total / 100);
            // Serial.print("It lasted: ");
            // Serial.println(tim / 100);

            i = 0;
            tim = 0;
            total = 0;
        }
    #endif
}

Please add a schematic of your wiring: the behaviour you are describing doesn't look correct

the analog pin input range is 0-1.0v - perhaps your circuit results in voltage always > 1?

The ADC works fine when I use system_adc_read(). So, I'm sure the voltage is < 1.

I created a test circuit using an AC transformer to produce a 50 cycles / second sine wave signal and tried a number of variations on the system_adc_read_fast sample program in the Espressif SDK manual "2C-ESP8266_Non_OS_SDK_API_Reference__EN".
The ESP8266 ADC returned realistic values for adc_clk_div = 8 and 16, but, as you found, the values returned were always 1024 when I tried 32.
I found that the ADC unit was capable of performing ADC conversions in about 6-10 microseconds...
In a test program to collect data for a 40 millisecond period (ie two complete sine waves - I used a diode to chop off the negative halves) I called the system_adc_read_fast function 40 times collecting 116 samples in each call (using "number of samples" = 116).
I collected all the readings in a two-dimensional array before printing any values because the Serial.print function causes long delays between calls to the ADC converter. The "gaps" in the chart represent the changes in the sine wave signal between successive calls to the ADC read function.

Wow! Thanks dude. This is awesome. I've been able to verify this myself. Don't know why I missed this in the first place!? Again, thank you so much.

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


text:
Reading Ground/Open signal wire combonations to power specific LED's - Can it be done?
This might be a super easy question to answer. I ordered an Arduino Uno anyways for the sole purpose to understand this. Would not mind getting a jump on things before it's here.
I would like to setup the Arduino Uno to be used as a gear indicator for GM transmissions (specifically right now the GM 4l60e). Below is how it currently tells the computer/cluster what gear it's in.
This uses a range switch. Basically it's a combination of 4 wires that are grounded (low) in a specific order, the computer reads it, and displays what gear the transmission is in. There are 4 signal wires - Signal A,B,C, and P. Below is how the range switch signals it:
Park    - A=low,  B=open, C=open, P=low
Reverse - A=low,  B=low,  C=open, P=open
Neutral - A=open, B=low,  C=open, P=low
OverDrv - A=open, B=low,  C=low,  P=open
Drive 3 - A=low,  B=low,  C=low,  P=low
Drive 2 - A=low,  B=open, C=low,  P=open
Drive 1 - A=open, B=open, C=low,  P=low

I am wondering what would be the best way to go about this? The Arduino would be powered on by ignition. Display would be an LED (9-12V) output from the Arduino to each gear on a floor mount shifter. Total of 7 LEDs.
Hopefully this is easy to understand what I am trying to do. Thanks!

Could you clarify what you want the output to be - is it 7 single LEDs, so exactly one will be on at once? Or perhaps you're not asking about the output - just how to read the input..?

Yup, sorry about that.
7 single, different LED's representing a gear would be the output.
The main question being is it possible for the Arduino to intake 4 wires that could be ground or open at any instance and take that info and make an output to power an LED representing the combination (listed above).

First of all, Arduino is a 5V device, as such to drive the 9-12V LED you will need to use one or more transistors (depending on the LEDs type, number and connection, in series or in parallel).
Also, powering the Arduino from a 9-12V is not the best option: Arduino Uno has an onboard voltage regulator, but goes up to 9V maximum and, unless you go for the original one or a reputable manufacturer (Arduino is an open source project) I wouldn't go above 6V, because non-reputable manufacturers tend to use lower specs devices, like regulators which can get too hot when powered with high voltage: consider that the regulator will have to dissipate any excess energy into heat.
Said that, and knowing nothing more than what you said about the transmission you are describing, I assume the status open stands for open collector, meaning that it is not going to draw any current, so the following circuit is what you should use:

simulate this circuit – Schematic created using CircuitLab
The diagram assumes you are using digital pins 5 to 8 of your Arduino in INPUT mode and the Arduino GND is at the same voltage level as the transmission: this might be a big assumption, depending on how you power your Arduino (not from a battery pack, to be clear).
When node A is in open state, the voltage on Arduino pin 5 will be 5V, or HIGH as Arduino reports it. When node A is in low state then the voltage on Arduino pin 5 will be 0V, or LOW in Arduino lingo.
Resistors from R1 to R4 are there to limit current drawn when the gearbox is in state low.
UPDATE: I'm assuming the gearbox shares the same ground and operates at 5V,a s the Arduino does. If that's not he case and the gearbox operates at an higher voltage or does not share the same ground, the circuit will not work and you risk damaging the Arduino and/or the gearbox.
You can find a simulation of the above circuit where you can play with the different pins here.
The same occurs for the other pins, so your code will have to scan the 4 pins for their state and update your display accordingly, like:
#define PIN_A 5
#define PIN_B 6
#define PIN_C 7
#define PIN_P 8

void setup() {
  pinMode(PIN_A, INPUT);
  pinMode(PIN_B, INPUT);
  pinMode(PIN_C, INPUT);
  pinMode(PIN_P, INPUT);
}

#define PARK 0;
#define DRIVE_1 1;
#define DRIVE_2 2;
#define DRIVE_3 3;
#define OVER_DRIVE 4;
#define REVERSE 5;
#define NEUTRAL 99;
#define UNDEFINED 255;

unsigned int gear = UNDEFINED;
void loop() {
    bool A = digitalRead(PIN_A);
    bool B = digitalRead(PIN_B);
    bool C = digitalRead(PIN_C);
    bool P = digitalRead(PIN_P);

    if (!A && B && C && !P) {
      // Park - A=low, B=open, C=open, P=low
      gear = PARK;
    } else if (!A && !B && C && P) {
      // Reverse - A=low, B=low, C=open, P=open
      gear = REVERSE;
    } else if (A && !B && C && !P) {
      // Neutral - A=open, B=low, C=open, P=low
      gear = NEUTRAL;
    } else if (A && !B && !C && P) {
      // OverDrv - A=open, B=low, C=low, P=open
      gear = OVER_DRIVE;
    } else if (!A && !B && !C && !P) {
      // Drive 3 - A=low, B=low, C=low, P=low
      gear = DRIVE_3;
    } else if (!A && B && !C && P) {
      // Drive 2 - A=low, B=open, C=low, P=open
      gear = DRIVE_2;
    } else if (A && B && !C && !P) {
      // Drive 1 - A=open, B=open, C=low, P=low
      gear = DRIVE_1;
    } else {
      // none of the above
      gear = UNDEFINED;
    }
    // update your display here
}

Please note the above code is NOT the most efficient, but I believe it's easier to read and understand than a version using bitwise operations to identify the possible combinations.

Awesome, this really helps! Power source can be changed. The ECU in the vehicle that this is going to be tested in has plenty of 5v references. So if that would be better I can do that. But this really helps. Kudos! I will jump right on it when it gets here and see what we get, thanks again!

Please consider my update and also consider the fact the gearbox and the Arduino must have a common ground for this circuit to work.

Also consider there are more robust solutions than what I've here described and I would NOT advice to use the circuit I've diagrammed above unless you have double checked the gearbox and it's current draw capabilities. Personally I would opto isolate all interactions diagrammed above between the gearbox and the Arduino: voltage spikes are not uncommon in a vehicle electronics.

It is. It is totally separate. I am just using it to show gear indication. The ECU on the vehicle gets all it's info based on the floor shift. It does not use the range switch on the transmission. The range switch was not even being used. I just thought that I would like to have the indicator lights based on what gear the transmission is actually in vs what the sifter "thinks" it's in the way it is currently lit up as. This whole setup is completely separate from the actual vehicle operation. Just for me to see. It's a hotrod setup.

I've updated my answer based on what you have commented here: if both the gearbox and the Arduino operates at 5V then the whole circuit gets simplified and the shared ground will greatly simplify your circuit. All you need are pullup resistors to bring the voltage level HIGH when the gearbox outputs are open.

@Roberto Lo Giacco - Could he use INPUT_PULLUP instead of INPUT in pinMode() to eliminate the need for external resistors?

I wouldn't go above 6V - actually 7.3V would be about the minimum. There is circuitry to switch between the power jack input and the USB input. It is based on a comparator which compares double 3.3V (there is a voltage divider) from the 3.3V regulator to Vin, after the protection diode. So 6V is too low for it to switch to using the power jack. You would need 6.6V plus the voltage drop over the diode, so really 7.3V would be about the minimum. Possibly with no USB input it would take whatever it got, but still ...

If you have a 5V supply that is regulated and filtered you could put that direct into the 5V line of the Uno (and not into the power jack).

@VE7JRO actually no, those resistors act as pullups but they are also limiting the current sink by the gearbox open collector output when it is turned low: without the external resistors it is possible the gearbox creates a short to ground when turned low. Does it make sense?

@NickGammon that's totally right

@Roberto Lo Giacco - The transmission switch is ONLY providing a ground, so the Arduino Uno internal pull up resistor is providing the excess current protection when the input pin is grounded through the switch. The OP is not using the switch with the PCM connected to 12V as shown in this diagram: http://www.truckforum.org/threads/transmission-problems-4l60e.36202/. Please have a look at the "Park/Neutral Position (PNP) Switch" part of the circuit.

@VE7JRO the ground only connection is what I described as open collector, so I was aware of that. When internal pullup resistor is enabled you are actually connecting the Arduino pin to VCC via a 20k resistor so the final circuit would look like http://tinyurl.com/yd6k8xea
So you are right, good catch!


text:
Problem with PCB running an Arduino program to manage a GY-521 MPU6050 accelerometer
I'm working on a project based on MPU6050 GY-521 board connected to my PCB (running with an ATMega328P). The code was developed in Arduino.
The PCB is the second version. The first one works fine with the same accelerometer.
But with the second version I'm facing problems because it doesn't work and I can't understand the cause.
I did the following tests:

Run the code in an Arduino Nano board connected to the GY-521 MPU6050 board. Works fine.
Use other PCB to dismiss possible problem while soldering process. Doesn't work.
Probe with other GY-521 MPU6050 board. Doesn't work.

Finally I decided to cut some parts of the code trying to understand what part of this crash. My final test makes an LED blink while the rest part of the code ran.
void setup() {
  Serial.begin(115200);
  Wire.begin();
#if ARDUINO >= 157
  Wire.setClock(400000UL);
#else
  TWBR = ((F_CPU / 400000UL) - 16) / 2;
#endif

  i2cData[0] = 7; // Set the sample rate to 1000Hz - 8kHz/(7+1) = 1000Hz
  i2cData[1] = 0x00; // Disable FSYNC and set 260 Hz Acc filtering, 256 Hz Gyro filtering, 8 KHz sampling
  i2cData[2] = 0x00; // Set Gyro Full Scale Range to ±250deg/s
  i2cData[3] = 0x00; // Set Accelerometer Full Scale Range to ±2g
  while (i2cWrite(0x19, i2cData, 4, false)); // Write to all four registers at once

  //line commented in the last test
  //while (i2cWrite(0x6B, 0x01, true));

  //line commented in the last test
  //while (i2cRead(0x75, i2cData, 1));
  if (i2cData[0] != 0x68) { // Read "WHO_AM_I" register
    Serial.print(F("Error reading sensor"));
    while (1);
  }

  delay(100); // Wait for sensor to stabilize

  //line commented in the last test
  //while (i2cRead(0x3B, i2cData, 6));
  accX = (int16_t)((i2cData[0] << 8) | i2cData[1]);
  accY = (int16_t)((i2cData[2] << 8) | i2cData[3]);
  accZ = (int16_t)((i2cData[4] << 8) | i2cData[5]);

  // It is then converted from radians to degrees
#ifdef RESTRICT_PITCH // Eq. 25 and 26
  double roll  = atan2(accY, accZ) * RAD_TO_DEG;
  double pitch = atan(-accX / sqrt(accY * accY + accZ * accZ)) * RAD_TO_DEG;
#else // Eq. 28 and 29
  double roll  = atan(accY / sqrt(accX * accX + accZ * accZ)) * RAD_TO_DEG;
  double pitch = atan2(-accX, accZ) * RAD_TO_DEG;
#endif

  pinMode(7, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);

}

void loop() {
  /* Update all the values */
  //line commented in the last test
  //while (i2cRead(0x3B, i2cData, 14));
  accX = (int16_t)((i2cData[0] << 8) | i2cData[1]);
  accY = (int16_t)((i2cData[2] << 8) | i2cData[3]);
  accZ = (int16_t)((i2cData[4] << 8) | i2cData[5]);
  tempRaw = (int16_t)((i2cData[6] << 8) | i2cData[7]);
  gyroX = (int16_t)((i2cData[8] << 8) | i2cData[9]);
  gyroY = (int16_t)((i2cData[10] << 8) | i2cData[11]);
  gyroZ = (int16_t)((i2cData[12] << 8) | i2cData[13]);;

  double dt = (double)(micros() - timer) / 1000000; // Calculate delta time
  timer = micros();

  // It is then converted from radians to degrees
#ifdef RESTRICT_PITCH // Eq. 25 and 26
  double roll  = atan2(accY, accZ) * RAD_TO_DEG;
  double pitch = atan(-accX / sqrt(accY * accY + accZ * accZ)) * RAD_TO_DEG;
#else // Eq. 28 and 29
  double roll  = atan(accY / sqrt(accX * accX + accZ * accZ)) * RAD_TO_DEG;
  double pitch = atan2(-accX, accZ) * RAD_TO_DEG;
#endif

  double gyroXrate = gyroX / 131.0; // Convert to deg/s
  double gyroYrate = gyroY / 131.0; // Convert to deg/s
  double gyroZrate = gyroZ / 131.0; // Convert to deg/s

#ifdef RESTRICT_PITCH
  // This fixes the transition problem when the accelerometer angle jumps between -180 and 180 degrees
  if ((roll < -90 && kalAngleX > 90) || (roll > 90 && kalAngleX < -90)) {
    kalmanX.setAngle(roll);
    compAngleX = roll;
    kalAngleX = roll;
    gyroXangle = roll;
  } else
    kalAngleX = kalmanX.getAngle(roll, gyroXrate, dt); // Calculate the angle using a Kalman filter

  if (abs(kalAngleX) > 90)
    gyroYrate = -gyroYrate; // Invert rate, so it fits the restriced accelerometer reading
  kalAngleY = kalmanY.getAngle(pitch, gyroYrate, dt);
#else
  // This fixes the transition problem when the accelerometer angle jumps between -180 and 180 degrees
  if ((pitch < -90 && kalAngleY > 90) || (pitch > 90 && kalAngleY < -90)) {
    kalmanY.setAngle(pitch);
    compAngleY = pitch;
    kalAngleY = pitch;
    gyroYangle = pitch;
  } else
    kalAngleY = kalmanY.getAngle(pitch, gyroYrate, dt); // Calculate the angle using a Kalman filter

  if (abs(kalAngleY) > 90)
    gyroXrate = -gyroXrate; // Invert rate, so it fits the restriced accelerometer reading
  kalAngleX = kalmanX.getAngle(roll, gyroXrate, dt); // Calculate the angle using a Kalman filter
#endif

  gyroXangle += gyroXrate * dt; // Calculate gyro angle without any filter
  gyroYangle += gyroYrate * dt;
  //  gyroXangle += kalmanX.getRate() * dt; // Calculate gyro angle using the unbiased rate
  //  gyroYangle += kalmanY.getRate() * dt;

  compAngleX = 0.93 * (compAngleX + gyroXrate * dt) + 0.07 * roll; // Calculate the angle using a Complimentary filter
  compAngleY = 0.93 * (compAngleY + gyroYrate * dt) + 0.07 * pitch;

  // Reset the gyro angle when it has drifted too much
  if (gyroXangle < -180 || gyroXangle > 180)
    gyroXangle = kalAngleX;
  if (gyroYangle < -180 || gyroYangle > 180)
    gyroYangle = kalAngleY;

  // leer el valor analogo que entra
  // filtrarlo
  // determinar si se enciende el led
  sensorValue = analogRead(sensorPin);
  filBattery = myFilterBattery.getFilteredValue(sensorValue);
  if (filBattery < 750) // hacer la prueba con este nuevo valor
  {
    digitalWrite(3, HIGH);
  }
  else
  {
    digitalWrite(3, LOW);
  }
  digitalWrite(5, HIGH);
  delay(500);
  digitalWrite(5, LOW);
  delay(500);
}

With this code the LED blinks fine, but the commented lines are critical to MPU6050 setup and operation.
If someone can help me to understand what happen to my PCB, I'll be grateful.
Thanks in advance

I've given a short answer, based on the information you've given, which seems to point towards a likely area for you to investigate. However there is lots of information that you haven't given e.g. (a) schematic diagram; (b) PCB layouts for v1 and v2; (c) explanation of why you changed from PCB v1 to v2; (d) details of what changes (if any) you were trying to make between PCB v1 & v2; (e) details of your troubleshooting so far using (e.g.) oscilloscope or logic analyser (a multimeter would only show "gross" mistakes on an I²C bus); (f) details of other suggestions you have already tried.

it is also possible that v1 pcb is actually the bad one. some mistake in the design is allowing the code to run. ... i have seen it happen with two pieces of computer equipment. the one that failed to work was actually the good one.

@jsotola - True (+1). I've opted to start with the simple approach (e.g. in the USA, if you hear galloping hooves, first think horses not zebras). The lack of detail & context from the OP, and missing definition of "working" vs. "not working" etc. etc. makes deep analysis inefficient at this stage. Anyway, the comparison between "working" and "not working" as I recommended in my answer, is likely to make progress - even if that progress gives an unexpected result, as you said in your comment - and yes, over decades of troubleshooting, I've seen situations like you describe too :-) Fun!

@SamGibson, you are absolutely correct, the difference in the two versions is the key to the solution

There has been a request to reject the migration from EE.SE. I'm not sure. We need more complete code (where is i2cData declared?). Also we need to see your debugging prints. Saying "not working" doesn't tell us much.

You have explained that PCB v1 works, and PCB v2 does not work. Therefore, it seems likely the problem is in your PCB design and not in the code.
In your code sample which blinks an LED on PCB v2, but does not communicate with the MPU6050, it seems that you have removed the I²C function calls. Therefore if removing those function calls is what allows your code to run, and if the "working" code used on PCB v1 does not run successfully on PCB v2, then it's logical that you have somehow broken your I²C bus on PCB v2.
I suggest you start by comparing your PCB v1 and v2 designs carefully, focussing especially on the I²C bus and the connections to the MPU6050.

Thanks to all people who take time to answer me.
I found the error in the PCB v2. SamGibson, you are right, the error was in the I²C: the path was touching the GND plane. I separete this carefully and now works fine. Regards


text:
using pull-up resistors with A-star 32u4 on putput pins?
Okay probably not the first time this has been asked, but really, I search all over the internet and was not able to find this.
I want to drive LEDs on the output on some of my pins. Is it required to put a pull-up resistor or current limiter resistor on these? or can I just plug the LED into the output, and the other end of the LED to +vcc? Are there example schematics someplace that will show this?
thoughts? suggestions?
thanks.

Have you asked Google?

You always should use a resistor.
Simply the following schematic should be used.
The resistor value can be calculated as follows:
(V + Vfwd = I * R) => R = (V + Vfwd) / I
V is 5.0 V
Vfwd is the forward voltage of the LED (this differs per type/color/brand)
I is normally max. around 20 mA (but can be briefly more if the LED does not continuously lights)
Normally R is between 100 and 500 R, but can differ if you want to add multiple LEDs.

simulate this circuit – Schematic created using CircuitLab


text:
ESP8266 on WiFi without password, possible?
Is it possible to connect to an SSID that does not require a password?
My project using ESP8266-01 modules will sometimes be used in non-password protected guest networks.

yes, just skip the password. it works.

Yes, it works! You can use:
WiFi.begin(ssid, NULL)

or even leave the passphrase empty, because it is optional:
WiFi.begin(ssid)

Reference: https://www.arduino.cc/en/Reference/WiFiBegin


text:
Errors trying to set fuses on bare Atmega328p
I have an Atmega328p on a board that I want to program using an Arduino programmer. I've got the programmer working to program other Arduino's over ICSP header, but when trying to use the same settings to avrdude to read/set the fuses of the bare MCU with oscillator I get the following:
❯❯❯ avrdude -v -p atmega328p -b 19200 -P /dev/cu.wchusbserial213240 -c stk500v1                                                                                ⏎ master

avrdude: Version 6.3, compiled on Sep 18 2017 at 20:31:51
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/usr/local/Cellar/avrdude/6.3/etc/avrdude.conf"
         User configuration file is "/Users/viktor/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/cu.wchusbserial213240
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.08s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.08s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.08s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

I've checked the soldering as good as I can and it seems to be right. I have a 10K pullup on reset, an oscillator with caps. I'm suspecting I might have fried the MCU when soldering or something - is there anything simple I can check?

All PWR connections check out
I've checked the oscillator with a scope and it isn't oscillating, but I'm thinking that is normal since it's a bare chip that I'm trying to set the fuses to use the external crystal? The oscillator is at least connected correctly.

Try using the "burn bootloader" function inside the IDE. That also sets the fuses.

I've done that too. The first thing that menu item does though is actually calling avrdude just like that - I think I actually looked at the verbose log in the IDE to get the params right.

It turned out it was a bit of bad soldering on the MCU. This same msg you'll get if just leaving the ICSP floating.

I'm glad you found a solution, but could you accept this (your own) answer as the solution?
This question just got bumped to the frontpage and actually is already solved.


text:
Arduino Voltage Divider
So am doing a project which involves the reading of voltage and current generated by Solar Panel. Now I learnt that Arduino cant Read Voltage directly above 5V. To read above that you need to add a voltage divider circuit in between. But that's the great solution for a solar panel around 20W.
Now what if i want to read voltages of n number of solar panels which are in a farm in which each solar panel generated around 300-400 W .
1)Will adding voltage divider help?
2) What is the limit of Arduino of Voltage Divider?
3) What registers i would have to use for such big voltage divider?

Are you a electrical engineer and familiar with high voltages and high currents? When you have to ask this question, you better not mess with the solar panels. The solar power inverter has probably a way to get those numbers via a website or a interface.

@Jot no am not an electrical engineer. I do not the how u work with high voltages and current.

1)Will adding voltage divider help?

You will need n voltage dividers, one for each solar panel.

2) What is the limit of Arduino of Voltage Divider?

There is a limit on the equivalent Thévenin resistance of the voltage
source connected to the Arduino analog inputs. It should be no larger
that 10 kΩ, otherwise you risk cross-talk between the channels.
If the solar panels have a low output resistance, then the equivalent
Thévenin resistance is the resistance resulting from setting the two
resistors of the divider in parallel. Setting the smallest resistance
to 10 kΩ will ensure you meet the condition while at the same time
keeping the consumed current quite low.
There is also a limit on the number of solar panels that you can
independently monitor: 16, which is the number of analog inputs on the
Mega.

[...] each solar panel generate[s] around 300-400 W

The power generated is irrelevant: only the voltage is a concern. Your
dividers must output no more than 5 V.

1) Will adding voltage divider help?

Yes.

2) What is the limit of Arduino of Voltage Divider?

The Arduino has no relevance here. You can build voltage dividers to convert thousands or millions of volts down to 5V if you need to.

3) What registers i would have to use for such big voltage divider?

I guess you mean "resistors" here, not "registers"...
Resistors that give no more than 5V out at the peak voltage of the solar panels, and have a high enough voltage tolerance for the maximum voltage across any one resistor.


text:
#include<ESP8266WiFi.h> showing error message
i was trying to send some data to a webpage via esp8266wifi module connected to arduino uno. My sketch contains a header file .After searching online I could get the library Arduino-master.zip from github. I extracted the files and put it in inside the directory arduino->hardware->arduino->avr->libraries.but even then it was showing me the error message like this:

 fatal error: ESP8266WiFi.h: No such file or directory

 #include

                         ^

compilation terminated.

exit status 1
Error compiling for board Arduino/Genuino Uno.

How can I remove this error. please refrain from technical words as i am new to this language. Thank you.
EDIT: After adding esp8266WiFi.h in the library i got out from that error message .But it showed me a new one

C:\Program Files (x86)\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFiType.h:26:19: fatal error: queue.h: No such file or directory

 #include

                   ^

compilation terminated.

exit status 1
Error compiling for board Arduino/Genuino Uno.

I dont know how to come out of this error. some websites give a solution but it didn't worked for me.

That library is part of the ESP8266 core. It's not for the Arduino, but for programming the ESP8266 as a standalone unit without an Arduino connected to it.

ESP8266WiFi part of the project Arduino Core here: https://github.com/esp8266/Arduino Arduino Core provides support for the ESP8266 to be used with Arduino IDE through the boards manager facility. So its libraries are for the ESP8266 not the Uno.
If you are interested in communicating with the ESP8266 over serial using its AT+ command firmware then you just send them as strings over serial.
Serial1.println("AT+GMR");
while(Serial1.available() == 0) {
  delay(1);
}
while(Serial1.available() > 0) {
  Serial.write(Serial1.read());
}

That's a terrible serial routine there...

@Majenko It's an example. Edit in a better one if you want.


text:
Is there any way for one Arduino board to communicate with multiple sensors?
Say a home IoT application to monitor water levels in basement at 4 or 5 different places and transmit that data back to a single Arduino board to be then interfaced with a GUI to do home monitoring?

Yes this could be done using SPI (with separate slave select wires), i2c or daisy chained UART providing a wired solution.

Yes you can ... however, how you transmit the sensor data? If wireless, you need some RF communication, and possibly a microcontroller like Arduino (or ESP) within each sensor module.
With nRF24L01 (2.4GHz) you can use 6 'slaves' (sensor modules in your case) to send data to the master (monitoring module).
Do things one by one:

First make one sensor module
Than make the master to receive data
Than make the GUI screen
Than make the other five sensor modules


text:
How does one get the correct serial port?
I don't have a correct serial port from the resource I'm working from - Getting Started with Arduino by Massimo Banzi and Micheal Shiloh. I'm using the Arduino Uno. I'm a complete noob to Arduino. In this image below, from the resource I'm working from, it specifies to use either of the ports: /dev/cu.usbmodemfa141 or /dev/tty.usbmodem.
Getting started with Arduino by Massimo Banzi and Michael Shiloh - Figure 3-2 shows a list of available serial ports.

I only have two available: /dev/cu.SSDC and /dev/cu.Bluetooth-Incoming-port.
How do I get the 'correct' serial port? Correct being: /dev/cu.usbmodemfa141 or /dev/tty.usbmodem.
Here's some possibly useful information:
I'm using Mac OS - which I'm new to - Sierra version 10.13.2.
I only have two ports on the computer a USB type - C and a headphone jack. So I have an 'adapter' that allows me to 'daisy chain' the USB - B and USB - A for the Arduino cable into the port of my computer. If any additional information is required, feel free to ask for it and I'll try and get back to you ASAP. Thanks.

Is it a genuine Arduino Uno or some cheap Chinese POS?

He or she has asked the same question before, and it's apparently a genuine starter kit

Yes genuine it's a genuine starter kit.

Any sources of information or suggestions would really help.

Sorry guys I solved it. It was really simple I just needed to plug the device in and it then detected the device and port name.

I had the same problem and had even fewer options under my Tools > Port menu. Looked at the user forums but most answers did not work for me. After watching a YouTube video, I fixed the problem by following its suggestion of installing the CH34X driver. There are some other suggested drivers if you search for some other related StackOverflow and StackExchange posts, but I did not test them (once the Mac-Arduino communication worked, I did not want to spend more time on this) and nor can I explain why this solution works.
I wrote a short article on this for myself. If you are interested, please take a quick look.
Best luck! :)


text:
Is output pin set to LOW grounded
If I do following:
pinMode(MYPIN, OUTPUT)
digitalWrite(MYPIN, LOW)

What will happen? Will this effectively ground MYPIN or output some low voltage?

This will effectively connect the pin to ground. Note that the connection is
made by a transistor that has a finite resistance. This output resistance is
not really specified, but from the curves on the “typical characteristics”
section of the datasheet you can infer that the typical value is about
26 Ω.
The only hard specification states that the OUTPUT LOW voltage
should be no larger than 0.9 V, as long as the pin is not sinking
more than 20 mA. C.f. the table “DC characteristics” of the
ATmega2560
datasheet.


text:
http request in time intervals
I'm doing a program that receives data from a web page every so often, but only receives the data once and then receives everything blank. I need help to receive the data every time indefinitely. I am using arduino uno with arduino etherner shield
My code:
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress ip(192, 168, 0, 177);
EthernetClient client;

int REDLed= 2;
int GREENLed= 3;
int BLUELed= 4;

void setup()
{
  pinMode(REDLed, OUTPUT);
  pinMode(GREENLed, OUTPUT);
  pinMode(GREENLed, OUTPUT);
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
  Serial.println("power up" );
  delay(3000);
}

void loop()
{
  Serial.println("SubmitHttpRequest - started" );
  SubmitHttpRequest();
  Serial.println("SubmitHttpRequest - finished" );
  delay(10000);
}

void SubmitHttpRequest()
{
  if (client.connect(server, 80))
  {
    Serial.println("connected");
    client.println("GET /arduino/getstate.php?color=All HTTP/1.1");
    client.println("Host: cybertodo.mx");
    client.println("Connection: close");
    client.println();
  }
  else
  {
    Serial.println("connection failed");
  }
  delay(100);
  changeLed();
}

void changeLed()
{
  String content = "";
  Serial.println(client.available());
  while(client.available()!=0)
  {
    content = content + String(char (client.read()));
  }
  Serial.println(content);
  if(content.substring(30,31)== "1")
  {
    digitalWrite(REDLed, HIGH);
  }
  else if (content.substring(30,31)== "0")
  {
    digitalWrite(REDLed, LOW);
  }

  if(content.substring(31,32)== "1")
  {
    digitalWrite(GREENLed, HIGH);
  }
  else if (content.substring(31,32)== "0")
  {
    digitalWrite(GREENLed, LOW);
  }

  if(content.substring(32,33)== "1")
  {
    digitalWrite(BLUELed, HIGH);
  }
  else if (content.substring(32,33)== "0")
  {
    digitalWrite(BLUELed, LOW);
  }
  content = "";
}

Looks like you might be looping faster than the client.avaiable() is receiving data.  Consider what happens if you only get half the response at a time -- the ifs drop though, you delete the content, then exit the changeLed() and de-allocate content.  Consider making content global, and acting and clearing only when you get a full message.

Immediately after making the request when reading client.available() will be 0 since no data was received yet so:
  while(client.available()!=0)
  {
    content = content + String(char (client.read()));
  }

Will never actually run. Try something like:
unsigned long last = millis();
String content = "";

while(client.connected()) {
  int len = client.available();
  if(len > 0) {
    last = millis();

    char buff[len];
    for(int i = 0; i < len; i++) {
      buff[i] = client.read();
    }
    content += String(buff);

  } else {
    if(millis() - last > 2000) {
      client.stop();
      return;
    }
    delay(1);
  }
}

Also note if you use Connection: close on the client then you must close the connection. This example doesn't do that until 2 seconds have passed. To do this properly you'd need to also add header parsing to your client and close the connection once the amount specified in Content-Length is received.


text:
DAC to play audio samples
I have a buffer which contains 16000 PCM samples of 8Khz 8-bit mono. I am trying to play it using 12 bit MCP4725 DAC. I have tried using micros() to control the write interval for the DAC. Here's my code:
uint8_t soundData[16000] = { 234,206,79,255,249,....,210,222 }; // 8Khz 8-bit mono
long previousMicros = 0; // Sorry for missing this out!!

void setup() {

Serial.begin(115200);
Wire.begin(D2, D1);
delay(100); // delay 100 ms
Serial.flush();
delay(1000);

}

void value_write(uint16_t temp){

  Wire.beginTransmission(0x62);
  Wire.write(64);
  Wire.write(temp >> 4);        // the 8 most significant bits...
  Wire.write((temp & 15) << 4); // the 4 least significant bits...
  Wire.endTransmission();

}

void loop() {

  unsigned long currentMicros = micros();

// 125 uS sampling for 8KHz signal
if(currentMicros - previousMicros > 125) {
  Serial.print("Index: ");
  Serial.println(indx);
  uint16_t temp = map(soundData[indx++], 0, 255, 0, 4095);

  value_write(temp);
}

}

The write should logically be completed within 2 seconds but takes way more time. Any help regarding successfully writing the PCM values to the DAC at 8000Hz is greatly appreciated.

This is going to be a very jittery way to do things.  Typically you'd use a timer interrupt, or even (if you can afford to shut everything else off) a calibrated busy wait.

Can you give me a short example of how can I do this using timer interrupt?

In your code, you never set or update previousMicros value.

sorry for missing that out. I have updated

You need to update previousMicros every time you start a new send task. If previousMicrosnever gets updated, then your loop runs at top speed, and not metered by the if(currentMicros - previousMicros > 125) comparison. Try adding previousMicros += 125; just before the Serial.print("Index: "); line. This will cause your code to trigger approximately every 125 uS.

There was no change. I can observe in the serial monitor, it is approximately displaying 1000 values per second.

Doing a lot of serial printing may be messing up your timing. Do things work better if you disable all the Serial.print(...) commands in loop?

I think I can hear sound only for 2 sec now after disabling all the Serial.print. Also notices a change in write rate no sooner I removed one. The sample is actually unknown to me (the original audio) so could not confirm but could hear the beap only for 2 seconds. When I will be working ahead in the project, i will test it using known voice audio. Anyway, thankyou so much.

If this answered your question, mark it as an accepted answer so the system doesn't keep promoting it as unanswered.

Is Wire.setClock() necessary to code? Or alone this micros can handle the job?

Wire.setClock() sets the speed of the I2C transmission. The default is 100kHz. I believe you can also set it to 400kHz. You only need to use it if you plan to write data at a different bus speed than the default.

Just last question, is it that alone Wire.setClock(8000UL) can do my job without micros()?

No, setting the I2C clock to 8kHz, when you have to transmit several bytes of data per 125 uS will not work. You will have only transmitted 1 or maybe 2 bits of data before you are scheduled to send your next 14-bit command, plus the start/stop packets, etc.

One sample takes 38 I2C clock cycles to write. That's:
1 START
7 Address
1 R/W
1 ACK
8 Byte
1 ACK
8 Byte
1 ACK
8 Byte
1 ACK
1 STOP

At the default 100kHz clock speed that's 100,000/38 = 2631.58 samples per second absolute maximum.
You can increase the clock speed to 400kHz, which would allow you 400,000 / 38 = 10526 samples per second absolute maximum.  That would just about be do-able.
I am unsure what the ESP8266 can support, but the DAC also supports "High Speed" mode - 3.4MHz I2C.  If the ESP8266 supports that you can then run at 3,400,000 / 38 = 89474 samples per second, which is better still.
There's also the matter of the map() function which is just nasty in this situation. You can just bit-shift.
So besides just removing the Serial commands (which will slow things down massively) you should also:

Change the I2C clock to at least 400kHz
Change map() to soundData[indx++] << 4
Consider using a timer to trigger the sending of the samples

But, with all that said. an I2C DAC is really not suited to audio playback. I2C is just too slow and clunky for audio. You'd be better off with an SPI DAC which can run much much faster than I2C. Better still you should investigate I2S on the ESP8266. This is designed specifically for audio, although it's much harder to set up owing to the increased number of special clocks you need to provide ("master" clock, "bit" clock and "l/r" clock). Also the DACs (also known as CODECs) tend to be at least 16 bit or even higher, and capable of proper audio sampling frequencies, like 44100ksps and above.

Thanks @Majenko , I actually don't have to deal with a very high frequency as I am trying to play a voice sample recorded at 8KHz 8 bit mono and sound quality won't be an issue. Do I have to still go for I2S or I2C DAC would do the job for me.? And I would be going for 8000x38 = 304KHz for wire.setClock() but wish to do it using timers. It would be great if you can suggest me some reading

You want the clock frequency to be as fast as you can get. I2C specifications limit you to specific frequencies though - you can't just use any arbitrary value.


text:
Problems recycling c++ lib with templated class for Arduino
I have a header & cpp file located in Arduino\libraries\Parentfolder\Header&Cpp. Arduino IDE recognizes my lib (the class is color coded & Sketch->include library->MyLibrary shows in the dropdown menu and #includes properly).
Problem: Arduino IDE gives undefined reference to MyClass . . . error in my sketch for every reference of the class including function calls. The function fully in other IDEs as header/cpps so I don't think pasting the cody is necessary -- what could I be missing? I've read a million Stack Exchange posts with similar error/watched a million YouTube guides on writing Arduino libs and I can't seem to find the differentiating factors that would make my code not work for Arduino IDE.
tl;dr what are the reasons that a working c++ library (self-made) would not work with Arduino IDE?
/e
Queue.h
#ifndef Queue_h
#define Queue_h

#include "Arduino.h"

template <typename T>
class Queue
{
  public:
    typedef struct node
    {
      T data;
      node * next = nullptr;
    } * nodePtr;

    nodePtr head; // = nullptr;
    nodePtr tail; // = nullptr;
    nodePtr curr; // = nullptr;
    nodePtr temp; // = nullptr;

    unsigned int counter;

    Queue();
    void push(T);
    T& peek();
    T pop();
    int size();
    bool isEmpty();
    void clear();
};

#endif

Queue.cpp
#include "Arduino.h"
#include "Queue.h"

template <typename T>
Queue<T>::Queue()
{
    nodePtr head = nullptr;
    nodePtr tail = nullptr;
    nodePtr curr = nullptr;
    nodePtr temp = nullptr;

    counter = 0;
}

template <typename T>
void Queue<T>::push(T data)
{
  if (head == nullptr)
  {
    head = new node;
    head->data = data;
    tail = head;
  }
  else
  {
    temp = head;
    head = new node;
    head->data = data;
    head->next = temp;
  }
  counter ++;
}

template <typename T>
T& Queue<T>::peek()
{
  if (head == nullptr)
  {
    return 0;
  }
  return head->data;

}

template <typename T>
T Queue<T>::pop()
{
  // Empty
  if (head == nullptr)
  {
    return 0;
  }

  // Head = tail
  if (head == tail)
  {
    T data = head->data;
    delete head;
    return data;
  }

  // Size > 1
  curr = head;
  while (curr->next != tail)
  {
    curr = curr->next;
  }
  T data = curr->next->data;
  tail = curr;
  curr = curr->next;
  delete curr;
  counter --;
  return data;
}

template <typename T>
int Queue<T>::size()
{
  return counter;
}

template <typename T>
bool Queue<T>::isEmpty()
{
  if (counter ==0)
  {
    return true;
  }
  return false;
}

template <typename T>
void Queue<T>::clear()
{
  while (head->data != nullptr)
  {
    temp = head->next;
    delete head;
    head = temp;
  }
  if (head == nullptr)
  {
    return;
  }
  delete head;
  return;
}

.ino
. . .
Queue<float> avgQueue;
. . .

error
. . . In function `__static_initialization_and_destruction_0':
. . . undefined reference to `Queue<float>::Queue()'

SOLVED:
Combining the .cpp contents in the .h and removing the .cpp worked.

Please post a Minimal, Complete, and Verifiable example. Do you have a single sketch file, or have you broken your code into multiple files (eg. cpp/h files)?

The header and cpp are in the forementioned subfolder which is inside of the Arduino library folder. The errors come from a simple sketch meant only to test the (already-working-in-other-IDEs) library.

one thing that jumps out is the ampersand & in the path ... maybe the compiler does not like it

That's not the real path, that's just me saying that both the header&cpp are there.

SOLVED:
Putting the .cpp contents in the .h and removing the .cpp from the lib folder entirely worked.

Yes, tempates are instantiated on demand so you have to have complete class inside of header. However I wonder how the pop works if you have the last element. Your head wasn't set to the nullptr - and delete can't do that for you.

Your code doesn't totally prove the problem, however libraries are not included unless you include them in the .ino file which might be your underlying issue.

This, for example, is not complete code: . . . Queue<float> avgQueue; . . .

@NickGammon fortunately I'm not that much of a noob! The lib was included and everything is now functioning well as a result of the above workaround

I'm glad it is working, however I'm not sure what you did exactly (that didn't work) and what you did (that did work). However this looks relevant.


text:
Battery life calculation using Nano, NRF24L01+ and window magnetic reed switch
I'm trying to make my own home wireless security system.  I will be using probably 3 AA batteries to power these devices.  My problem is that I need to know if the batteries will be enough to power the devices for at least 6 months.
Below are the details of all the devices I will be using:

Mini Nano V3.0 ATmega328P Microcontroller Board w/USB Cable For Arduino
Makerfire Arduino NRF24L01+ 2.4GHz Wireless RF Transceiver Module
uxcell MC 38 Mount Wired Door Window Sensor Magnetic Reed Switch Recessed

Below are some project requirements that might be useful:

For the Nano, I want to put it to sleep using delay(2000) in the loop() function.  The Nano will be the one checking the window sensor.
I will be using a project enclosure of about 4X4 inches.

If this will not be possible maybe someone knows of other devices that use less power that will be more suitable for this project? I would prefer something easy to use like Arduino Nano with USB so I can easily program it.
EDIT: sorry but I just like to add that from the main HUB component, I would like to check the status of the window sensor if it is open/closed.  This will be useful if there is an open window/door around the house when going to sleep. Probably the Nano will broadcast its current window sensor status to the main HUB program. Thanks.

how will you make sure than nobody can jam the radio signal?

@jsotola I addressed this in my answer. Even with "still alive" functionality the sensor should last for many months if programmed properly.

I'm just trying to build my own home security system.  My electronics knowledge is very limited, so for now I don't want to worry about jamming the radio signal.

@Marquinio In that case why not just have just a magnetic reed switch connected to a buzzer? Standby would be next to nothing then.

I want to make a web GUI for the system where I can see the state of all the    door/window sensors.  I also want to be able to armed/disarm the system.  When its armed and triggered then the buzzer will be triggered.

Most alarm reed switches are NC (normally closed). So it will continuously pull the pin low. So you might need to get a higher value pull-up resistor, to lower the current going through the pull-up resistor. Or use an active-high topology.

You should use interrupts for the reed switch and then put the microcontrolller into sleep for a keep alive interval. Your master device should check that the sensor is still active and set off the alarm if its not. You would also want to allow for a battery low condition that might disable the alarm for convince. This still should keep the power consumption low.
The nano is roughly 1mA @ 3.3v while the CPU is running and 72uA when its in sleep. Discounting power consumption in the alarm condition triggered by the interrupt using an interval of 9 seconds using delay or interrupt timers then average consumption then about a second to wake up and send a keep alive over the RF. (0.000072 * 9 + 0.001 * 1) / 10 = 0.0001648 amps. (average over 10 second duty cycle)
My guesstimate of your RF power consumption without knowing what kind of protocol would be somewhere around 128 bytes per transmission taking about 90ms. (0.0001 * 9910 + 0.015 * 90) / 10,000 = 0.0002341 amps.
Total of their averages is: 0.0003989 or 398.9uA.
Alkaline AA cells vary widely. So instead based on some Ni-MH with 2400mAh per cell and 1.2v
3 cells would be 3.6v so you'll "get" most of the mAhs out of the batteries.
2400mAh = 2400000uAh
2400000uAh / 398.9uA ~= 6016.54 hours or 250 days or 8 months.
Power consumption were intentional overestimates. You should be able to make it last a lot longer.
https://www.avrprogrammers.com/howto/atmega328-power
http://harizanov.com/2013/05/nrf24l01-power-consumption-footprint/

Based on your calculations It gives me hope that this will work.  Now what you mean by "put the microcontroller into sleep"? Is this as simple as something like delay(2000) or something more complicated?  If more complicated can you please provide a link so I can follow those steps? Thanks.

It is a bit more complicated. https://playground.arduino.cc/Learning/ArduinoSleepCode and https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

I'll have to read and understand how interrupts work, no easy way around that.  I can now move forward with my project.  Thanks for your help!

It only seems to do one thing: activate an alarm if the reed switch changes.  Power the system through the reed switch. It will have zero standby current and the battery will last the shelf life. That said, you might be able to use an RF module w/o even a MCU, though not that particular one...

Thats pointless because if you jam the RF the sensor is useless. That would make a silly security system.

this is for a home security system. one theoretical attack doesn't make it pointless any more than the existence of locksmiths makes locking your door "pointless". If someone breaking into OP's house is jamming RF signals, they are going to get in one way or the other... Still you could for example, add a 110db alarm to the build and still get "infinite" standby, maybe even with a microphone sensor as an RF backup. Main point: in my experience, analog still beats digital for long-term reliability.

@jdwolf: what's to stop someone from spoofing the RF signal? If you authenticate, that's a ton of complexity to avoid replay attacks, schedule keys, not burn eeprom, etc. Try using a simple spark gap transmitter and a dollar-store AM radio as a detector: you can't jam a spark gap w/o setting off the receiver ;)

Nothing about my answer indicates that encryption wouldn't be used. Signal jamming includes intentionally blocking the signal or destroying the device between its broadcast intervals (which would be easily detectable on the cheapest of hardware) so even spark gap can't help you there. In any case "I'm still alive" style security is how professional security systems actually work.

This will be a basic home security system.  Once I can make the power last a long time I will beef it up and maybe add jamming protection, but for now I will probably have the Nano send an "I'm still alive" to the main HUB like jdwolf mentioned.

You should use a reed switch that is both NC and NO. Then power only the disconnected part of the switch and listen to pin changes and put everything into sleep. This can improve your power consumption. See the answers postet here: Low Power Pin Change Detection


text:
FastLED + structs + PROGMEM strange behavior
I'm afraid I have to post a lengthy bit of code, because I can't pinpoint what's causing my issues – in short, it appears repeatedly adding float position + float speed in a struct ends up borking the whole thing.
The purpose of the code is to animate at most MAX_PARTICLES particles ("pixels") traveling at random speeds across the LED stripe.
The array named particles stores the current list of particles being managed. Each particle in the array is stored as a struct, as defined at the beginning of the code. Particles are added to the array using function addParticle() at the very end of the code. Particles which reach the end of the stripe are killed in the second part of the loop() function (after FastLED.show()).
Here's the code:
#define FASTLED_INTERNAL // Eliminates a compiler warning
#include <FastLED.h>
#include <colorutils.h>
#define NUM_LEDS 149
#define DATA_PIN 6
#define MAX_PARTICLES 5 // This uses up the memory, mostly
CRGB leds[NUM_LEDS];

struct particle {
  float position;
  CRGB color;
  float speed;
  int id;
};
typedef struct particle Particle;
Particle particles[MAX_PARTICLES];
int numParticles = 0;
int maxId = 0;

// Gramma correction tables (Defalt Gamma = 2.8)
const uint8_t PROGMEM gammaR[] = {
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,
    1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,
    2,  2,  2,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,  4,  5,
    5,  5,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  9,
    9,  9, 10, 10, 10, 11, 11, 11, 12, 12, 12, 13, 13, 14, 14, 14,
   15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
   23, 24, 24, 25, 25, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33,
   33, 34, 35, 36, 36, 37, 38, 39, 40, 40, 41, 42, 43, 44, 45, 46,
   46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
   62, 63, 65, 66, 67, 68, 69, 70, 71, 73, 74, 75, 76, 78, 79, 80,
   81, 83, 84, 85, 87, 88, 89, 91, 92, 94, 95, 97, 98, 99,101,102,
  104,105,107,109,110,112,113,115,116,118,120,121,123,125,127,128,
  130,132,134,135,137,139,141,143,145,146,148,150,152,154,156,158,
  160,162,164,166,168,170,172,174,177,179,181,183,185,187,190,192,
  194,196,199,201,203,206,208,210,213,215,218,220,223,225,227,230 };

const uint8_t PROGMEM gammaG[] = {
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,
    1,  1,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,  2,  2,
    2,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,  4,  5,  5,  5,
    5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  9,  9,  9, 10,
   10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16,
   17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25,
   25, 26, 27, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 35, 36,
   37, 38, 39, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 50,
   51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68,
   69, 70, 72, 73, 74, 75, 77, 78, 79, 81, 82, 83, 85, 86, 87, 89,
   90, 92, 93, 95, 96, 98, 99,101,102,104,105,107,109,110,112,114,
  115,117,119,120,122,124,126,127,129,131,133,135,137,138,140,142,
  144,146,148,150,152,154,156,158,160,162,164,167,169,171,173,175,
  177,180,182,184,186,189,191,193,196,198,200,203,205,208,210,213,
  215,218,220,223,225,228,231,233,236,239,241,244,247,249,252,255 };

const uint8_t PROGMEM gammaB[] = {
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
    1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,
    2,  2,  2,  2,  2,  2,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,
    4,  4,  5,  5,  5,  5,  5,  6,  6,  6,  6,  6,  7,  7,  7,  8,
    8,  8,  8,  9,  9,  9, 10, 10, 10, 10, 11, 11, 12, 12, 12, 13,
   13, 13, 14, 14, 15, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 19,
   20, 20, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 27, 27, 28, 28,
   29, 30, 30, 31, 32, 32, 33, 34, 34, 35, 36, 37, 37, 38, 39, 40,
   40, 41, 42, 43, 44, 44, 45, 46, 47, 48, 49, 50, 51, 51, 52, 53,
   54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 69, 70,
   71, 72, 73, 74, 75, 77, 78, 79, 80, 81, 83, 84, 85, 86, 88, 89,
   90, 92, 93, 94, 96, 97, 98,100,101,103,104,106,107,109,110,112,
  113,115,116,118,119,121,122,124,126,127,129,131,132,134,136,137,
  139,141,143,144,146,148,150,152,153,155,157,159,161,163,165,167,
  169,171,173,175,177,179,181,183,185,187,189,191,193,196,198,200 };

void setup() {
  FastLED.addLeds<WS2812B, DATA_PIN, BGR>(leds, NUM_LEDS);
  randomSeed(analogRead(0));
  Serial.begin(115200);
}

void loop() {
  if (numParticles < MAX_PARTICLES && random(10)>8) {
    addParticle();
  }

  for (int i=0; i<numParticles; i++) {
    // Antialiasing
    int basePosition = floor(particles[i].position);
    byte percentOnePos = round(255 * (particles[i].position-basePosition));
    byte percentBasePos = 255 - percentOnePos;
    CRGB color0 = particles[i].color % percentOnePos;
    CRGB color1 = particles[i].color % percentBasePos;

    leds[basePosition] += color0;
    leds[basePosition+1] += color1;
  }

  // Apply gamma correction
  for (int i=0; i<NUM_LEDS; i++) {
    //leds[i] = applyGamma_video(leds[i], 2.2);
    // *** applyGamma_video(2.2) pros and cons:
    // PROs: smoother color transitions
    // CONs: much slower; much worse color calibration
    // TODO: pre-render custom, color calibrated gamma tables

    leds[i].red = pgm_read_byte(&gammaR[leds[i].red]);
    leds[i].green = pgm_read_byte(&gammaG[leds[i].green]);
    leds[i].blue = pgm_read_byte(&gammaB[leds[i].blue]);
  }

  FastLED.show();

  for (int i=0; i<numParticles; i++) {
    int basePosition = floor(particles[i].position);
    leds[basePosition] = CRGB::Black;
    leds[basePosition+1] = CRGB::Black;
    particles[i].position += particles[i].speed;
    if (particles[i].position > (NUM_LEDS+1)) { // We want to render it fading out
      for (int j = i; j<numParticles-1; j++) {
        particles[j] = particles[j+1];
      }
      numParticles--;
      i--; // We want the for() cycle to process the particle we shifted down
    }
  }
  debugParticles();
}

void debugParticles()
{
  for (int i = 0; i<MAX_PARTICLES; i++) {
    if (i>0) {
      Serial.print(", ");
    }

    Serial.print(i);
    Serial.print(",");
    Serial.print(particles[i].id);
    Serial.print(",");
    Serial.print(particles[i].position);
  }
  Serial.println("");
}

void addParticle()
{
  particles[numParticles].color = CHSV(random8(),255,150);
  particles[numParticles].position = 0;
  particles[numParticles].speed = (0.0+random(10))/100+0.01;
  particles[numParticles].id = maxId++;
  numParticles++;
}

For debugging purposes, each unique particle ever created has a unique ID. The debugging output contains the following fields:

[0] the array index for the first entry in the array (always 0)
[1] the unique ID of the particle stored in the first record of the array
[2] the position of the particle stored in the first record of the array
[3] the array index for the second entry in the array (always 1)
[4] the unique ID of the particle stored in the second record of the array
[5] the position of the particle stored in the second record of the array
(and so on – three fields for each record in the particles array)

Finally, here's an interesting excerpt from the output, after ~1,500 records:
0   0   30.36   1   1   30.28   2   2   147.70  3   3   59.04   4   4   73.15
0   0   30.38   1   1   30.30   2   2   147.80  3   3   59.08   4   4   73.20
0   0   30.40   1   1   30.32   2   2   147.90  3   3   59.12   4   4   73.25
0   0   30.42   1   1   30.34   2   2   148.00  3   3   59.16   4   4   73.30
0   0   30.44   1   1   30.36   2   2   148.10  3   3   59.20   4   4   73.35
0   0   8.00    1   1   30.38   2   2   148.20  3   3   59.24   4   4   73.40
0   0   8.00    1   1   30.40   2   2   148.30  3   3   59.28   4   4   73.45
0   0   8.00    1   1   30.42   2   2   148.40  3   3   59.32   4   4   73.50
0   0   8.00    1   1   30.44   2   2   148.50  3   3   59.36   4   4   73.55
0   0   8.00    1   1   30.46   2   2   148.60  3   3   59.40   4   4   73.60
0   0   8.00    1   1   30.48   2   2   148.70  3   3   59.44   4   4   73.65
0   0   8.00    1   1   30.50   2   2   148.80  3   3   59.48   4   4   73.70
0   0   8.00    1   1   30.52   2   2   148.90  3   3   59.52   4   4   73.75
0   0   8.00    1   1   30.54   2   2   149.00  3   3   59.56   4   4   73.80
0   0   8.00    1   1   30.56   2   2   149.10  3   3   59.60   4   4   73.85
0   1   0.00    1   2   149.20  2   3   59.64   3   4   73.90   4   4   73.85
0   1   0.00    1   2   149.30  2   3   59.68   3   4   73.95   4   4   73.85
0   1   0.00    1   2   149.40  2   3   59.72   3   4   74.00   4   4   73.85

Notice how in all but the last three lines, the array index and the particle ID are still in sync (0=>0, 1=>1, 2=>2, 3=>3, 4=>4), which means no particles have died yet (new particles would have larger IDs). I'm trying to say that no particle re-assignment magic has happened yet – for now, we're just running the boring code which moves particles along the strip.
And yet, on the sixth line in the output, the first particle's position becomes mangled – notice how on the first five lines the first particle's position has steadily increased by 0.02 (presumably that particle's speed) up to 30.44, whereas on the sixth line it inexplicably becomes 8.00 (other times I experimented, it becomes 32.00). Not only that, but that 8.00 (the particle's position) never increases again, and three lines from the bottom the code also decides to kill the first particle altogether (notice that the second column becomes 1, which means the first record in the particles array now stores the particle with unique ID 1, instead of unique ID 0).
I have no idea what I'm doing wrong – I've been experimenting with this over and over, killing off all the bugs and warnings I could find, and still no luck.

My guess: not checking position leads into the overwritting memory after the leds (which is variable particles).

I'm afraid I don't follow. All of these are automatic variables, I'm not doing any DIY memory management.

You are using leds[basePosition+1] = ... and if the base position is 148, it means you are writing at the position 149. That means AFTER the space allocated for the CRGB leds[149] as you have 149 elements starting with index 0 and ending by index 148

By George, I think you've got it! Haven't tested yet (and can't until tonight), but I think you've spotted it! Please jot down an answer proper, so we can do this by the numbers.

As you are keeping the particles over the position 149 (because of fading), I'd expect overwritting the memory after the space allocated for the leds variable.
According to the log it started somewhere around position 148, which is earlier, but in your code is this:
int basePosition = floor(particles[i].position);
leds[basePosition] += color0;
leds[basePosition+1] += color1;

So if you have position 148, you are already changing something after the array. It might add zero values in the color1 (for 148.0 and 148.1) so it didn't changed anything but later the value gets nonzero and changes a wrong memory.


text:
ESP8266 SPIFFS file not found
I have a simple HTML file that I have uploaded as sketch data using the ESP8266 sketch data upload tool in arduino IDE. The file is 7k in size.
In the set up, I refer to the following function to read the file:
String readTemplatefile(){
  String retval ="";
  File fr = SPIFFS.open("/templatecfg.htm", "r");

  if(!SPIFFS.exists("/templatecfg.htm")){

    Serial.println("Template file not available ");
    }
    while (fr.available()){
        retval += char(fr.read());
      }

fr.close();
Serial.println("Template file = ");
Serial.println(retval);
return retval;
}

I always get 'Template file not found'. I have
SPIFFS.begin();

at the beginning of the setup function
My board is an ESP8266EX. I have wondered if it the flash size settings in the IDE that could cause this not to be found. Can anyone offer any advice on this issue. I have tried lots of different combinations of Flash size and SPIFF sizes without any luck.
Thanks in advance to any help.

Is the file there?  Is the media formatted in the right format (FAT? rather than NTFS which Windows will default to)

Did you mount the filesystem with SPIFFS.begin()?  Have you tried opening the "/" directory and listing the files, so you can confirm what your sketch sees as the available files?

@CodeGorilla: SPIFFS, not SD ;)

run the included FS browser example sketch and see how it works. yes, your flash settings can affect SPIFFS, if they are wrong. make sure the IDE size (ESP.getFlashChipSize()) and the physical sizes (ESP.getFlashChipRealSize()) match up. google the esp lib functions for docs

SPIFFS will always claim to successfully open a file that begins with a slash even if that file does not exist.  Remove the leading slash.

@dandavis Yes, I had SPIFFS.begin() in my setup routine.
I ran a sample sketch and was able to see the a file on the device, so I routed round the code some more and found than an included library was ending SPIFFS after it had performed a file read. This was the issue. Thanks all for your consideration, but the code I had was fine, just the included library was mis-behaving.

what library? so we learn


text:
Undefined reference to stdlib (strtof) while compiling
I'm trying to run the AzureIoTProtocol_MQTT/esp8266 example, but I get linker errors:

Archiving built core (caching) in:
  /var/folders/fj/y3vtrz597kv4885q1b_5qypr0000gn/T/arduino_cache_934614/core/core_esp8266_esp8266_d1_mini_CpuFrequency_80,UploadSpeed_921600,FlashSize_4M3M_e1e103f2055a19e071ac9522162e1787.a
  libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function sscanfd':
  /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:2826:
  undefined reference tostrtoull'
  libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function
  sscanfllu':
  /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:2826:
  undefined reference tostrtoull'
  libraries/AzureIoTHub/sdk/agenttypesystem.c.o:(.text.CreateAgentDataType_From_String+0xac):
  undefined reference to strtof'
  libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function
  CreateAgentDataType_From_String':
  /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:3571:
  undefined reference to `strtof' collect2: error: ld returned 1 exit
  status

The issue can be broken down to the call to strtof function call. I get the same error with only this very simple code snippet:
#include <stdlib.h>

void setup() {
  char szOrbits[] = "686.97";
  float f;
  f = strtof (szOrbits, NULL);
}

void loop() {
}

Tested environment: Mac OS X 10.13.2 with Arduino 1.8.3 AND Windows 10 with Arduino 1.8.5.

Its because the "strtof" function resides in "stdlib.h",
"Stdio.h" deals with i/o tasks.
Since you din't include you get that undefined reference error.
Correct that and compile again. Hopefully the error shall be resolved, else reply in the comments.

Update1:
After digging around standard gcc stdlib definitions and avr-gcc definitions found out that the above solution works for a gcc and not avr-gcc especially the 8-bit ones which the arduino IDE compiles for uno and the works as expected for 32bit processors like of Due.
Cite:

https://www.arduino.cc/reference/en/language/variables/data-types/double/
https://www.arduino.cc/reference/en/language/variables/data-types/float/

Reason:
The size of the double and float is the same, ie: 4 bytes
and even if you use double its actually the float itself and wont gain any precision advantage.
Solution:
Since the size of the double and the float is same there is not point in having two function definition doing the same job.
so

Use "strtod"  instead of "strtof" or
Define a macro #define strtof(A, B) strtod(A, B) in the begning of your sketch so that the "strtod" handles the functioning of the "strtof".

changed to stdlib.h and same error.

@appsthatmatter i have updated my answer for your error. do check.

thanks for the answer. Since the function is used in a third party library I can not change it easily to float. But anyway, I managed it to run with this steps (replicable on Mac and Windows): 1) clean install of Arduino IDE, 2) install ESP8266 via git (see the README), 3) verify the program once for Board NodeMCU 1.0 (ESP 12-E).

Its because you haven't added the core of esp8266 to the arduino IDE.
you are defaulting it to the "UNO" board and compiling it.
so you get that error for which i have explanation
here: https://arduino.stackexchange.com/a/48719/3557
solution for your problem is simple added the esp8266 core and select the right board and compile again.
Cite: https://learn.sparkfun.com/tutorials/esp8266-thing-hookup-guide/installing-the-esp8266-arduino-addon
Follow above link and install the esp8266 core.


text:
Lifecycle hook in Arduino to know if Arduino is reset or powered down
I am new to Arduino programming and I'm really fascinated with its working. Is there a way to know if an Arduino is getting switched off or being reset? Like a function would be called before the Arduino gets switched off.
I want to detect this event to preserve a value, where a user resets his Arduino, or switches it off. Is it possible?

The simplest thing to do is to turn the problem around, if possible - Instead of doing something when the arduino is switched off, do it when it is switched on again.

If i want to preserve a value, then i have to know when its switched off

In this case, it's simply not possible without some external circuitry that (1) realises the switchoff and (2) keeps the arduino alive for some last gasp actions. Try to save your value in EEPROM if it doesn't update too often. Maybe you can give some more detail what you actually want to do.

EEPROM has a limit of 100,000 write/erase cycles, so we cant do more than that

Shutting off an Arduino is as simple as cutting off the power supply. As the voltage declines the Browout Detection could notice it but there won't be enough time to write any value into the EEPROM or write something out via serial. There simply is no such thing in the Arduino lifecycle. But you can use a pin and a button to externally trigger a write to EEPROM and then cut off the power.

@bukkehariprasad That's why I wrote "if it doesn't update too often" - Then accept it's not possible.

What value do you want to preserve? How often does it change? How big is it?

EEPROM has a limit of 100,000 write/erase cycles, so we cant do more than that

You have 1k bytes of EEPROM and they survive a minimum of 100,000 writes. So that's 102,400,000 writes you could potentially do, if you are saving one byte. Even at one write a second that would be around 3 years.
However the EEPROM page size is 4 bytes, so that is actually 25,600,000 writes you could get away with (of 4 bytes at a time). Still, that is quite a lot of writes.
A while back I tested one of my chip's EEPROM and found that it greatly exceeded the 100,000 writes specified before it starting misreading the data back.
Also, if you refrain from writing if the value hasn't changed (hopefully that's a lot of the time?) then you could probably extend the life to 100 years.

Like a function would be called before the Arduino gets switched off.

No, that's impossible. How would it possibly know it is about to be switched off? Once it is switched off, functions are hardly going to be able to run.

Is there a way to know if an Arduino is getting switched off or being reset?

Once you hit Reset the processor starts again. It doesn't run any functions "just before" or "just after" being reset (using the original variables). That would mean that the reset doesn't actually reset it.

If you are designing some gadget that lets you configure it (eg. with a volume control) then simply save the new setting to EEPROM when it is changed. This is hardly going to happen 24 hours a day.

Reset does not actually clear memory variables; instead default startup code added by the compiler does.  So in fact, code can run "just after reset" and before this happens in the case of a warm reset.

I understand that, however programming in C++ you would have difficulty in retrieving those variables. In any case, I don't see how you would recover variables after the power had been removed.

For a self-confessed novice to retrieve variables after a reset (and be able to tell the difference between valid variables and random data after being powered up) would not be easy.

Many things are difficult, but used.  Passing RAM variable in fixed locations across reboot is one of them.  Writing to persistent memory on loss of input power, before the capacitor your are running off of has drained is another.  Together, they can solve the problem.  But no, it won't be easy.

Writing to persistent memory on loss of input power, before the capacitor your are running off of has drained is another. Together, they can solve the problem. - well, Chris, the "Answer" button is there for you to explain how to achieve this. I'm sure the OP will appreciate your advice.

@NickGammon thanks a lot for the detailed explanation. I am using file system now instead of eeprom to save data. I think its lifetime is more than the default storage provided by arduino.

@bukkehariprasad - actually the eeprom has a longer cycle life that whatever is hosting your file system.  Though a well designed flash translation layer could walk the data through more cells, limiting the wear on each one.  So each individual cell on an SDcard has shorter life, but you can write a given small chunk of data more times to a well engineered sd card system than you can to a small eeprom, since you can write it in different places.  The critical question then becomes if all the pieces of the sd  card system are well engineered: often at least some are not.

@ChrisStratton I am not using an SD card, but using internal memory to store the file. I have changed the process, and this time I am not writing to the memory often. I might read/write to the file once a month or something like that. Hope the file has enough life cycle to handle so many writes.

What "internal memory" ?  The ATmega328 tagged in your question only has eeprom, and program flash, but you can't really put a "file system" in either of those.

Maybe he means RAM.

You can read the MCUSR status register to determine the source of the reset.
Sources can be the Watchdog timer, brownout (too low a voltage), reset (button), or power-cycle.

Can you explain more? Or point to a tutorial about using MCUSR? Thanks

try https://arduino.stackexchange.com/questions/34331/run-different-code-on-different-type-of-reset-in-arduino-nano/34332#34332 .

Also https://arduino.stackexchange.com/search?q=MCUSR

This isn't really an answer to the question asked, so much as a strategy for different goals.  The comments clarify that the desire is for saving state, so this won't help.


text:
Can I get the current connection speed with ESP8266?
Using an ESP8266 I can get the RSSI of the Wifi network using Wifi.getNetworkInfo() or Wifi.RSSI(). But is there a way to know the actual connection speed in Mbps, after joining successfully a WiFi network?

isn't it always 54?

@dandavis Are your phone or laptop always connecting at 350 Mbps on 2.4 GHz or 867 Mbps on 5 GHz? of course not, it depends on the signal strength. That's the MAX connection speed with strong WiFi signals.

no, the ESP can't even talk on 5Ghz. My asus RT-AC68U claims ~54Mbps. Not sure what figure you're actually looking for, since you're never going to get more than a few dozen KB/s throughput.

@dandavis I know that 5 GHz are not supported and that 54 Mbps are the maximum. Still, try to move the ESP far from the station, about the maximum distance that allows you to get a connection, and check in your router if the connection is still 54 Mbps. It shouldn't be, since in the datasheet it's stated that 22 Mbps have a better S/N and allow weaker signals. There will be a distance where 54 Mbps are not physically possible anymore and the connection will be established at 22 Mbps. My router doesn't show me the connection speed, please do this test :)

Wifi modules decide on link speed based on signal strength. So you can estimate the link speed with signal strength, which you can get with WiFi.RSSI(network).
The datasheet of ESP8266 contains a table mapping RSSI to link speed under "Sensitivity":

-98 dBm: 1 Mbps
-93 dBm: 6 Mbps
-91 dBm: 11 Mbps
-75 dBm: 54Mbps
-71 dBm: 65Mbps, 72.2Mbps

Whenever these values are "minimum", "maximum" or "typical" remains unclear. These dBm limits are also quite low, which means the link speed will probably be capped by the other communication peer (your router). Here's the same table for a random D-link router, DI-624.