text:
sleep and wake up arduino mega according to ds3231 interrupt
how can I make my arduino mega sleep during 6pm-7am..and wakes or stay up during 7am-6pm and doing its job like activating the solenoid valve based on my soil moisture sensor reading.this is for my backyard farm.anyone can help me making a code for it? please i really need it.
here is my code
#include <DS3231.h>
#include <Wire.h>
#include <avr/sleep.h>

 int wakePin = 2;   // pin used for waking up
 int led = 13;

 DS3231 clock;
 RTCDAteTime dt;

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

 // initialize DS3231
 Serial.println("Initailize DS3231");
 delay(100);
  clock.begin();
  pinMode(wakePin,INPUT_PULLUP);
  pinMode(led,OUTPUT);

   //Disarm alarms and clear alarms for this example, beacuse alarms is battery backed.
   //Under normal conditions, the settings should be reset after power and restart microcontroller
   clock.armAlarm(false);
   clock.clearAlarm();

   //Set Alarm1 - Every 20s in each minute
   // setAlarm1(date or day,hour,minute,second,Mode,Arrmed=True)
     clock.setAlarm1(0,0,0,20,DS3231_MATCH_S);
     attachInterrupt(0,wakeUpNow,LOW);

   //check alarm settings
    checkAlarms();
  }

   void checkAlarms()
  {
   RTCAlarmTimea1;
   RTCAlarmTimea2;

    if (clock.isArmed1())
   {
    a1 = clock.getAlarm1();

     Serial.print("Alarm1 is triggered:);
     switch(clock.getAlarmType1())
    {

       case DS3231_MATCH_S:
       Serial.print("When seconds match: ');
       Serial.println(clock.dateFormat("_ _:_:s",a1));
       delay(100);
        break;
        default:
         Serial.println("UNKNOWN RULE");
         break;
     }
    }
   }

       void wakeUpNow()
   {
       //execute code here after wake-up before returning to the loop() function
      //timers and code using timers(serial.print and more...)will not work here.
     //we don`t really need to execute any special functions here, since we
     //just want the thing to wake up
      Serial.print("Woke up");
     delay(100);
     }

      void sleepNow()
     {
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);  //sleep mode is set here
      sleep_enable();   //enables  the sleep bit in the mcucr register
      attachInterrupt(0,wakeUpNow,FALLING); //use interrupt 0(pin2) and run function
      sleep_mode();
         // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

         sleep_disable();  //first thing after waking from sleep: disable sleep
         detachInterrupt(0); //disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running
          time.
        }

         void loop()
        {
           dt=clock.getDateTime();

             Serial.println(clock.dateFormat("d-m-Y H:i:s-I",dt));
              delay(100);
           //Call isAlarm1(false)if you want clear alarm1 flag manualy by                     cleaAlarm1();
              if(clock.isAlarm1())
           {
                 Serial.println("ALARM 1 TRIGGERED!");
                 digitalWrite(led,HIGH);
                   delay(1000);
                  digitalWrite(led,LOW);
                  Serial.println("Entering Sleep");
                    delay(100); //sleep fucntion called here
                     sleepNow();
               }
                delay(900);
               }

It depends what you mean by sleep here. There are methods for putting the chip into an inactive sleep state for extreme power savings in battery powered applications. I guess here you simply mean that during a certain period of the day, as determined from the real time clock, you want to suppress the sensor monitoring and the solenoid valve activity. Is that correct or is your goal to minimise power consumption in a battery powered application ?

both..is it possible??

Yes it's possible. For extreme power saving techniques with AVR (which Arduino Mega) look at http://www.gammon.com.au/power . However, if your application includes a solenoid valve then shaving a few microamps from the power consumption through cpu sleep/wakeup cycles may not make a big difference to the overall power consumption. I'd start by reading the  RTC in the loop, determining if is day or night, reading the sensor and switching the valves as necessary, then as a later activity, optimising the power consumption.

i have separate power supply for my solenoid valve

can you help me fixing a code for it? I will send you my sketch and you can change it and send it back. please help me.

If you've currently (a) got some code and (b) have some specific questions about correcting or adding features to it, then post these here.

First, Arduino Mega does not have an RTC (Real Time Clock) built-in. So, to program it the way you like, would mean either using a module like DS3231 or similar, or have the Mega connected to internet, with a network card module like ENC28J60 and getting the time from there. If you don't use any of those methods basing your scheduler only on the Arduino internal timer (using sleep for example) will result in program needing to set the correct time each time Arduino is powered.

i have RTC ds3231 and Arduino mega 2560, solenoid valve, soil mosure sensor

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


text:
Why isn't pin 6 on my Adafruit Feather RP2040 being sent high when I ask it to?
I have an Adafruit Feather RP2040 (pinouts) connected via pin 6 to a relay. The code (below) triggers the relay when a separate color sensor returns "enough" red values.
The color sensor works (confirmed by the serial print statements); the on-board LED (connected internally to pin 13) lights up when it should; but I don't get any voltage on pin 6 when I should. I'm testing the voltage with a standard multimeter. If I move my connecting wire from pin 6 to pin 13, I get voltage (and the relay activates). Why doesn't pin 6 get voltage? What else can I do to diagnose the issue?
Software versions:

Arduino.CC IDE v2.2.1 (latest)
Arduino IDE Board manager: added https://github.com/earlephilhower/arduino-pico, version 3.6.0 (latest)
Adafruit APDS9960 Library from https://github.com/adafruit/Adafruit_APDS9960, version 1.2.3, released Jan 30 of this year. According to https://github.com/adafruit/Adafruit_APDS9960/tags there is a version 1.2.4 released on May 12th, but since this is just the light sensor code, which is behaving correctly, I don't believe the issue lies here.

Code:
// copied & modified from the source at:
// https://github.com/adafruit/Adafruit_APDS9960/blob/master/examples/color_sensor/color_sensor.ino

#include "Adafruit_APDS9960.h"
Adafruit_APDS9960 apds;

// the pin on the feather that we're using to talk to the relay
#define PIN_TO_RELAY 6

#define BUCKET_FULL_RED 50

void setup() {
  // enable Serial communication
  Serial.begin(115200);

  // try to start the color sensor
  if(!apds.begin()) {
    Serial.println("failed to initialize device! Please check your wiring.");
  }
  else {
    // Assume success
    // Serial.println("Device initialized!");

    // we want color readings
    apds.enableColor(true);
  }

  // define the relay pin as an OUTPUT pin
  pinMode(PIN_TO_RELAY, OUTPUT);
  // start with the relay "open" AKA not running the pump
  digitalWrite(PIN_TO_RELAY, LOW);

  // use the built-in LED as an external signal for "pumping"
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  // create some variables to store the color data in; unused, except for 'red'
  uint16_t red, green, blue, clear;

  // for checking the relay pin state
  int relay_pin_state = 0;

  // for extra printing
  int debug = 1;

  // wait for color data to be ready
  while (!apds.colorDataReady()) {
    delay(5);
  }
  // get fresh data; we only care about the red, but we have to read them all
  apds.getColorData(&red, &green, &blue, &clear);

  if (debug) {
    Serial.print("current red value is:"); Serial.println(red);
  }

  if (debug > 2) {
    relay_pin_state = digitalRead(PIN_TO_RELAY);
    if (relay_pin_state == HIGH) {
      Serial.println("steadystate: Relay pin is HIGH / enabled");
    } else {
      Serial.println("steadystate: Relay pin is LOW / disabled");
    }
  }

  if (red > BUCKET_FULL_RED) {
    if (debug) {
      Serial.println("start the pump (for 5 sec)");
    }

    // light up the built-in LED
    digitalWrite(LED_BUILTIN, HIGH);
    // "close" the relay to turn on the pump
    digitalWrite(PIN_TO_RELAY, HIGH);

    if (debug > 2) {
      relay_pin_state = digitalRead(PIN_TO_RELAY);
      if (relay_pin_state == HIGH) {
        Serial.println("pumping: Relay pin is HIGH / enabled");
      } else {
        Serial.println("pumping: Relay pin is LOW / disabled");
      }
    }

    // wait for a while for the pump to do its work
    // 5 sec in ms; TODO: eventually circa 4 min
    delay(5 * 1000);

    if (debug) {
      Serial.println("stop the pump");
    }

    // turn off the built-in LED
    digitalWrite(LED_BUILTIN, LOW);
    // "open" the relay to turn off the pump
    digitalWrite(PIN_TO_RELAY, LOW);
  }
  // no need to cycle quickly; wait 1 sec in ms
  delay(1 * 1000);
}

I just looked more closely at the pinouts page again, and was surprised to see the hole labeled "6" on the front is labeled "GP08" on the back, which corresponds to "GPIO8" in https://learn.adafruit.com/assets/107203. I wonder if I'm sending the "D4" pin HIGH ("GPIO6") instead of the one I'm expecting.

Before getting to far into debugging your code, make sure all your supporting software & libraries are up to date.  I've had early versions of Adafruit libraries act just terribly.

probably because you are not telling it to go high ... set all pins high ... if the pin goes high, then set 1/2 of the pins low ...etc

@st2000 good callout; I've edited the post to include the software versions I'm aware of that could impact this. If there's anything else I could check, please let me know. Thank you!

@jsotola I'm confused; I'm specifically telling pin 6 to go "HIGH" with the digitalWrite(PIN_TO_RELAY, HIGH); line, and then telling it to go "LOW" later. The surrounding lines for the LED_BUILTIN are working correctly, so I assumed that telling pin 6 to go HIGH would work the same way. Maybe not?

A closer look at the pinout chart indicates that "pin 6" may not be the thing that's labeled "6"; will be retesting with pin 8.

... and that was it. What do you all think? Close as a typo for pin "6" vs GPIO pin 8, or put up a self-answer as a warning to others?

I don't know what you should do, but this is a recurring pattern with boards where there are D-numbers and actual proper GPIO-numbers, particularly on ESP8266 boards. You may find this file enlightening. The Philhower stuff may (or may not) have a map in it somewhere from D# to GPIO#

It would be nice if you put up a self-answer, preferably with a photo to make it clear how you were confused by "8" looking like "6" on a PCB.

Turns out I misled you with my ignorance. I took for granted that the thing labeled "6" on the front was in fact Pin 6, but it's not:

Indeed, if I turn it over, that's "GP08":

... and so my code needs to use pin 8, not pin 6.
User timemage pointed out similar confusion on a recent post: D1 mini ESP8266 no sound on speaker where the silk-screened label on the front of the board did not match the actual pin number. They additionally point out a file that I would have never stumbled upon, but demonstrates this mapping: https://github.com/adafruit/circuitpython/blob/16c8c9a739cfe0db2c712696eb340de2d7944d41/ports/raspberrypi/boards/adafruit_feather_rp2040/pins.c#L24, namely:
    { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO2) },
    { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO3) },
    { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO7) },
    { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO8) },  /* right here */
    { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) },
    { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) },

The description of the pinout still contains some misleading information, in my opinion:

D6/GP08 - Digital I/O pin 6. It is also SPI1 MISO, UART1 TX, I2C0 SDA and PWM4 A.

Here, it seems to me that this spot is still being called "pin 6".

Doesn't Arduino have defines for pins? E.g. can't you simply type "D6" (or "GPIO_8")? I know it used to have that...

It's a whole new world for me, Daniël! I feel like I'm slowly learning the "language" of things, and being new -- I just took things at face value. It sounds like there's a translation that happens with the MP_QSTR_D6 term, but I don't yet know what that turns into, and if it's obvious at all that it relates to "the thing on the front of the board that says 6".

@DaniëlvandenBerg you linked to unrelated platform

@Juraj whoops... Seems like the library mentioned by adafruit does indeed include the pin definitions: https://github.com/earlephilhower/arduino-pico/blob/db7ba160ae238534ac1d89381748db3ed3b6dfe9/variants/generic/common.h and https://github.com/earlephilhower/arduino-pico/blob/db7ba160ae238534ac1d89381748db3ed3b6dfe9/variants/adafruit_feather/pins_arduino.h , but then it's still D8, not D6. I would've expected D6 to refer to the silk screen up-front, and translate to the correct GPIO number... Odd...

The pin labeled as GP06 on the bottom side of the PCB is labeled as D4 on the top side of the PCB. It is pin 4.
from https://learn.adafruit.com/adafruit-feather-rp2040-pico/pinouts

D4/GP06 - Digital I/O pin 4. It is also SPI0 SCK, I2C1 SDA and PWM3 A.

source: Stack Exchange

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

sort: votes


text:
Some of my <include> statements do not work
I'm trying to include the thing...
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

BLEServer* pServer = NULL;

void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}

But it simply doesn't see what's inside the .h files:
C:\Users\void\AppData\Local\Temp\.arduinoIDE-unsaved20231028-7016-1na7gr9.y1do\sketch_nov28b\sketch_nov28b.ino:6:1: error: 'BLEServer' does not name a type; did you mean 'Server'?
 BLEServer* pServer = NULL;                        // Pointer to the server
 ^~~~~~~~~
 Server

May it be, I bought the wrong board? I've set it as lolin s2 mini.

The thing.....?

Yes, the thing!

Many of the ESP32 variants have Bluetooth/BLE support. The ESP32-S2 board/module you're trying to use does not. The module has WiFi, but not Bluetooth.

So you need another board, Lolin seems to have an -S3 version of your board. But many other boards would work.
The majority of the <BLEServer.h> header's contents are conditionally compiled based on whether or not CONFIG_BLUEDROID_ENABLED is #defined.
And this only done for modules that have support for Bluetooth. The Lolin S3 version of the Mini would have Bluetooth support and in the configuration file it would use you can see it defined. In the one for the S2 board you are trying to use it is missing.
In effect, although you're including the header, it is as though it were blank. So no definition of the BLEServer type. It would have been nice if they'd handled this a different way, but this is not uncommon.

They told me it supports BLE... Thank you anyway.

LOL. I understand the frustration. I wouldn't put it quite that way though. That same group of people also makes the datasheets. While their technical documentation is something I've railed about before, there's no mention of Bluetooth/BLE in the ESP32S2 datasheet. I'd be surprised if Expressif would tell you they support BLE support. Ebay/alibaba/amazon-markplace/dx/etc/etc, not so much.

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


text:
Capturing frequency using a photodiode
I've just bought the following photodiode (here) and I am trying to make a simple Arduino circuit/code so that the photodiode is able to record an LED blinking at an arbitrary refresh rate (frequency).
I have an Arduino Uno driving the sensor, and a Raspberry Pi driving the LED at a given frequency.
I would like some help as my knowledge in signal processing is minimal, and I would appreciate any feedback or tips on whether what I am doing is correct or not.
Here is the Arduino code:
CODE UPDATED!!
//#include <TimerOne.h>
#include <Arduino.h>

const unsigned long ONESEC = 1000000; // microseconds
const int size = 600;
int sensorValue[size];
int dly = 1000000 / size; // delay so to fill N samples during 1 complete second (1,000,000 microseconds)

int maxValue = 0;
int minValue = 1000000;
double Alpha = 0.1; // [0.0 - 1.0] weight parameter
double filteredValue = 0.0;
double prevValue = 0.0;
double avgsum = 0.0;

int total = 0;
int avgtotal = 0;
const int s = 10;
int rounds = size / s;
int tmparr[s];

const int btnPin = 7;
const int sensorPin = A0;  // sensor pin

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

  // init tmparr
  for(int i=0;i<s;i++){
    tmparr[i] = 0;
  }
}

void waitForButton(int btnPin){
  Serial.println("Waiting...");
  while(digitalRead(btnPin) != 1){
    continue;
    }
  Serial.println("Button has been pressed!");
}

void loop() {  // code that loops forever

  int i = 0;
  unsigned long curTime = micros();
  unsigned long prevTime, startTime;
  prevTime = curTime;
  startTime = curTime;
  while(curTime - startTime <= ONESEC){ // sofar the time between the current and the start time is less than 1 second, keep recording data
    if(curTime - prevTime < dly){ // sofar the current and the previous time stamp has a differene of less than N seconds, do not record anything
      curTime = micros();
      continue;
    }
    sensorValue[i++] = analogRead(sensorPin);

    if(i > size){
      break;
    }
    prevTime = curTime;
    curTime = micros();
  }

  ///////////////////////
  ///////////////////////
  // Data processing ////
  ///////////////////////
  ///////////////////////

  // filter the signal and find maximum/minimum and avg

  for(int i=0;i<size;i++){
    int v = sensorValue[i];
    filteredValue = (v * Alpha) + (prevValue * (1-Alpha)); // exponential filtering
    sensorValue[i] = filteredValue; // re-writing the sensor data !! RAW DATA ARE BEING OVERWRITTEN !!
    avgsum = avgsum + filteredValue;
    prevValue = filteredValue;

    if(maxValue < filteredValue){
      maxValue = filteredValue;
    }
    if(minValue > filteredValue){
      minValue = filteredValue;
    }
  }
  avgsum = avgsum / size;

  // plotting and segregating the signal
  int peaks = 0;
  int prevState = -1;

  for(int i=0;i<rounds;i++){
    for(int j=0;j<s;j++){
      int v = sensorValue[(i*s)+j];
      total = total - tmparr[j];
      total = total + v;
      avgtotal = total / s;
      tmparr[j] = v;
      Serial.print(avgtotal); // new filtered value
      Serial.print(",");
      Serial.print(avgsum);
      Serial.print(",");
      Serial.println(v); // filtered value

      if(avgtotal > avgsum + (avgsum*0.01)){
        // Serial.println(1);
        if(prevState != 1){
          peaks++;
          prevState = 1;
        }
      }
      else{
        // Serial.println(0);
        prevState = 0;
      }
    }
  }
  Serial.print("peaks:");
  Serial.println(peaks);

}

So far I am getting somewhere close I guess.
Down are some of the recorded measurements. Filtering the signal, I suspect, is not optimal to make clear distinction between peaks and trough in the signal.
Also I am not sure if the shape of the signal is proper representation of the actual input signal given that the filtering influence that in a way or another based on the used parameters.
Any tips for what I should do and how I should proceed to make it more reliable and accurate?

Update 1:
Here is the Pi code:
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
from time import sleep # Import the sleep function from the time module

GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set initial value to low (off)

freq = 5.0 # Hz
cycle = 1.0/freq
hcycle = cycle / 2.0

while True: # Run forever
 GPIO.output(8, GPIO.HIGH) # Turn on
 sleep(hcycle) # Sleep for N second
 GPIO.output(8, GPIO.LOW) # Turn off
 sleep(hcycle)

Update 2:
After updating the code, for very low frequencies I get kinda nicely shaped-signal
example of 5 Hz signal

Things start to get messier with high frequency (not that high) at 30 Hz for instance, where trying to segregate the signal based on the total average line does not result in informative value for how many peaks and troughs there are, for several peaks can be under the lines and several troughs can be above the line. Output reads 25 peaks here.
so I am starting to think that the filtering technique I am using maybe is not the best. Any suggestions?

If you are seeing 1 extra peak at 15 Hz, and then 3 extra at 50 Hz (3x15 ~ 50), so at least it is consistent. You haven't posted your Pi code, which may or may not have an issue. Are you sure the Pi is flashing at 15 Hz and not 16 Hz? Maybe try 5 Hz to see if that is more accurate, and then slowly ramp up the rate. Have you tried flashing the LED using the Arduino (maybe by using interrupts) to see if the number of peaks change (or become more accurate)..?

I've just updated the question with some info, please check.
I am very new to all this circuitry and I was not sure how to use the LED and the sensor simultaneously to measure the LED flashing as both would be sequential in the same loop(), so I decided to use another circuit to control the LED.

Could you update the units on the figures? Are you sure you are taking measurements every second? Or what is your time-scale like?

Why are you doing an analog read on what is basically a digital input? The LED is on, or off isn't it?

@NickGammon I am not interested in the LED per se, it is here only as a mean to test how to do proper reading using a photodiode sensor which has an analogue input

@NickS. I have just updated the code using a different strategy for capturing data over EXACTLY one second. please have a look

What are we looking at here? What is that red line?

the legend is mentioned in the figure above each in thier corresponding color

Consider this loop:
for(int i=0; i< size;i++){
  // Read sensor value
  sensorValue[i] = analogRead(sensorPin);
  // wait between readings for N microseconds
  delayMicroseconds(dly);
}

The time taken by each iteration is the sum of the times taken by each
individual operation (compare i to size, read the ADC, delay,
increment i and jump to the start of the loop). Other than the delay,
the longest operation here is analogRead(), as it blocks in a busy
loop while the ADC performs its conversion. This can take anywhere
between 104 µs and 112 µs. Even neglecting everything but
analogRead() and delayMicroseconds(), you expect your loop to be
about 6–7% too slow.
You should get better timings if you use micros() instead of
delayMicroseconds(). Check the Arduino tutorial “Blink without delay”
to see how you can manage your timings without delaying. You still won't
get metrology-class timings though, as micros() is only as good as the
ceramic resonator clocking your Uno, which should be roughly 0.1%
accurate in its frequency. If you need anything better, you will have to
find a better frequency standard.

Edit: Addressing the updated question.
There are a few issues I would like to address:
First, the way the updated code handles the acquisition timing is a bit
convoluted. Furthermore, updating the time with prevTime = curTime; is
prone to timing drift: you cannot count on curTime being exactly the
time at which the ADC reading was scheduled, it can be a few
microseconds later. Actually, curTime will always be later, as the
acquisition period (1,666 µs) is not a multiple of the micros()
resolution (4 µs). This timing drift can be avoided by making
prevTime represent the time when the previous acquisition was
scheduled (not when it was performed):
// Data acquisition.
unsigned long prevTime = micros();
for (int i = 0; i < size; i++) {
    while (micros() - prevTime < dly) continue;  // wait until it's time
    prevTime += dly;                         // update scheduled time
    sensorValue[i] = analogRead(sensorPin);  // acquire data
}

The limited resolution of micros() will still cause some jitter, but
updating with prevTime += dly; ensures there is no systematic drift.
Second, I would avoid doing any kind of filtering on the Arduino itself.
If the data is meant to be transferred to the PC anyway, just transfer
the raw data. This gives you the chance of processing it on your PC,
interactively experimenting with different types of filters, with the
comfort of your favorite programming language or data-processing
package. If the complete project requires the filtering to be done on
the Arduino, do that later, once you have found the most appropriate
filter on the PC.
Third, as filtering goes, you seem to have a lot of 50 Hz noise
here. Maybe the noise is already present in the luminous flux, or maybe
it is introduced somewhere between the photodiode and the Arduino. I
would check the cabling to see whether there is a way to reduce
inductive noise pickup. Are you using long cables between the photodiode
and the Arduino? If so, is that a twisted pair? Is everything properly
grounded? Are there any ground loops?
If you cannot get rid of the mains noise at the source, it will be very
difficult to identify signals that are anywhere close to 50 Hz, as
your 30 Hz experiment shows. You may want to try a notch filter
specifically tuned to kill any 50 Hz component.
Fourth, you may want to try, at least once, to acquire at a faster rate:
let's say with a 200 µs period. If that acquisition reveals a lot
of high-frequency noise, then it may be worth using some decimating
filter. For example, you could store, in each array position, the sum of
eight samples taken at 200 µs intervals. That should give less
noisy data, with a period of 1.6 ms per array cell (round value
close to the current 1.666 ms). Note that this technique will be
absolutely useless against 50 Hz noise though.
Fifth, it is possible to trigger the ADC from a timer, which gives very
accurate and consistent timing. This, however, requires low-level
programming, and digging into the ATmega datasheet. I would not care
about perfect timings now, at least not until the above issues are
fixed. It is, however, a possibility you may want to keep in mind in
case in the future you want to get the best possible timings.

thanks for the tip. I have just updated the code using the suggested method for capturing data within 1 second. But my main inquiry about how to process the recorded signal so to make informative reading out of it is still confusing me

@wisdom This isn't really a forum, and making major edits to your question in response to answers is trying to turn it into one. I think your original question has been answered, and further questions about such things as processing the signal should really be turned into new questions in their own right. Otherwise this particular thread will become quite confusing to read. Amended questions / amended answers, don't make for a good reading flow.

Counting in a loop like that is fine if you have a very low frequency signal, and are getting the hang of how loops, and reading from input pins, work. But there will be a lot of overheads. As Edgar Bonet points out in his answer there can be an overhead of between 104 µs and 112 µs for doing an analogRead call. Plus the overhead of the loop. And the delay won't be accurate to the microsecond. All this adds up.
There are two ways you can find a frequency:

Count "ticks" over a known interval. For example, counting 50 ticks over a second would give you 50 Hz.

Measure the period. In other words, find out how long elapses between a rising edge and a falling edge (and double that time). For example for 50 Hz the period would be 20 ms (1 / 50).

As I mention on my page about timers there are ways of doing that. To avoid giving a link-only answer I'll paste some of that code.
Count pulses
// Timer and Counter example
// Author: Nick Gammon
// Date: 17th January 2012

// Input: Pin D5

// these are checked for in the main program
volatile unsigned long timerCounts;
volatile boolean counterReady;

// internal to counting routine
unsigned long overflowCount;
unsigned int timerTicks;
unsigned int timerPeriod;

void startCounting (unsigned int ms)
  {
  counterReady = false;         // time not up yet
  timerPeriod = ms;             // how many 1 ms counts to do
  timerTicks = 0;               // reset interrupt counter
  overflowCount = 0;            // no overflows yet

  // reset Timer 1 and Timer 2
  TCCR1A = 0;
  TCCR1B = 0;
  TCCR2A = 0;
  TCCR2B = 0;

  // Timer 1 - counts events on pin D5
  TIMSK1 = bit (TOIE1);   // interrupt on Timer 1 overflow

  // Timer 2 - gives us our 1 ms counting interval
  // 16 MHz clock (62.5 ns per tick) - prescaled by 128
  //  counter increments every 8 µs.
  // So we count 125 of them, giving exactly 1000 µs (1 ms)
  TCCR2A = bit (WGM21) ;   // CTC mode
  OCR2A  = 124;            // count up to 125  (zero relative!!!!)

  // Timer 2 - interrupt on match (ie. every 1 ms)
  TIMSK2 = bit (OCIE2A);   // enable Timer2 Interrupt

  TCNT1 = 0;      // Both counters to zero
  TCNT2 = 0;

  // Reset prescalers
  GTCCR = bit (PSRASY);        // reset prescaler now
  // start Timer 2
  TCCR2B =  bit (CS20) | bit (CS22) ;  // prescaler of 128
  // start Timer 1
  // External clock source on T1 pin (D5). Clock on rising edge.
  TCCR1B =  bit (CS10) | bit (CS11) | bit (CS12);
  }  // end of startCounting

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

//******************************************************************
//  Timer2 Interrupt Service is invoked by hardware Timer 2 every 1 ms = 1000 Hz
//  16Mhz / 128 / 125 = 1000 Hz

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

  // see if we have reached timing period
  if (++timerTicks < timerPeriod)
    return;  // not yet

  // if just missed an overflow
  if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
    overflowCopy++;

  // end of gate time, measurement ready

  TCCR1A = 0;    // stop timer 1
  TCCR1B = 0;

  TCCR2A = 0;    // stop timer 2
  TCCR2B = 0;

  TIMSK1 = 0;    // disable Timer1 Interrupt
  TIMSK2 = 0;    // disable Timer2 Interrupt

  // calculate total count
  timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
  counterReady = true;              // set global flag for end count period
  }  // end of TIMER2_COMPA_vect

void setup ()
  {
  Serial.begin(115200);
  Serial.println("Frequency Counter");
  } // end of setup

void loop ()
  {
  // stop Timer 0 interrupts from throwing the count out
  byte oldTCCR0A = TCCR0A;
  byte oldTCCR0B = TCCR0B;
  TCCR0A = 0;    // stop timer 0
  TCCR0B = 0;

  startCounting (500);  // how many ms to count for

  while (!counterReady)
     { }  // loop until count over

  // adjust counts by counting interval to give frequency in Hz
  float frq = (timerCounts *  1000.0) / timerPeriod;

  Serial.print ("Frequency: ");
  Serial.print ((unsigned long) frq);
  Serial.println (" Hz.");

  // restart timer 0
  TCCR0A = oldTCCR0A;
  TCCR0B = oldTCCR0B;

  // let serial stuff finish
  delay(200);
  }   // end of loop

This is actually not so great for low frequencies because if the count is out by even one tick, your frequency is wrong by 2%. However it can count accurately (more or less) up to 5 kHz.
Measure the period
The other technique is to measure the period, like this:
// Frequency timer
// Author: Nick Gammon
// Date: 10th February 2012

// Input: Pin D2

volatile boolean first;
volatile boolean triggered;
volatile unsigned long overflowCount;
volatile unsigned long startTime;
volatile unsigned long finishTime;

// here on rising edge
void isr ()
{
  unsigned int counter = TCNT1;  // quickly save it

  // wait until we noticed last one
  if (triggered)
    return;

  if (first)
    {
    startTime = (overflowCount << 16) + counter;
    first = false;
    return;
    }

  finishTime = (overflowCount << 16) + counter;
  triggered = true;
  detachInterrupt(0);
}  // end of isr

// timer overflows (every 65536 counts)
ISR (TIMER1_OVF_vect)
{
  overflowCount++;
}  // end of TIMER1_OVF_vect

void prepareForInterrupts ()
  {
  // get ready for next time
  EIFR = bit (INTF0);  // clear flag for interrupt 0
  first = true;
  triggered = false;  // re-arm for next time
  attachInterrupt(0, isr, RISING);
  }  // end of prepareForInterrupts

void setup ()
  {
  Serial.begin(115200);
  Serial.println("Frequency Counter");

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  // Timer 1 - interrupt on overflow
  TIMSK1 = bit (TOIE1);   // enable Timer1 Interrupt
  // zero it
  TCNT1 = 0;
  overflowCount = 0;
  // start Timer 1
  TCCR1B =  bit (CS10);  //  no prescaling

  // set up for interrupts
  prepareForInterrupts ();

  } // end of setup

void loop ()
  {

  if (!triggered)
    return;

  unsigned long elapsedTime = finishTime - startTime;
  float freq = F_CPU / float (elapsedTime);  // each tick is 62.5 ns at 16 MHz

  Serial.print ("Took: ");
  Serial.print (elapsedTime);
  Serial.print (" counts. ");

  Serial.print ("Frequency: ");
  Serial.print (freq);
  Serial.println (" Hz. ");

  // so we can read it
  delay (500);

  prepareForInterrupts ();
}   // end of loop

This is better for low frequencies. Since this uses hardware timers you need to connect your input up to a specific pin as noted in the code. No doing analog reads, the time taken to do that would swamp any accuracy that you might get.

There is a race in your isr() function: if the timer overflows right before you read TCNT1, TIMER1_OVF_vect will not be called right away (because we are already in interrupt context), and you will miss an overflow.

both codes work brilliantly for LED (though with margin of error up to 6% as I've noticed).... but maybe I was not too clear in my intentions that I strictly want to use a photodiode sensor to read frequencies off displays at the end,  and I am using an LED for now just as a mean of testing and experimenting for how to design the code.

also I am interested in the waveform for how the signal rise and fall regardless of what is the light source (e.g. PC monitor, LED, projector, ...etc.). So I need to use a photodiode for that as well

@EdgarBonet You mean in the second piece of posted code? It looks like you are right. I had the test in TIMER2_COMPA_vect in the first piece of code. You could add that test where it says if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256) ... into the second one.

@wisdom The measurements should be more accurate than 6%, possibly the test frequency you are sending it  is not all that accurate. You are again using a loop and not a hardware generated frequency, so that the overhead of the loop is likely to affect the overall result. You really want a proper hardware-generated signal for testing, not code running on a processor using a while loop.

ok I see.... last bit of question: am I able to run hardware-generated signal-reading for the photodiode sensor in a way or another? if so could you please just point me to the direction?

Er, other than the code I posted above? My tests of that (first one) had an error of 0.02%. Isn't that good enough?

I understood that your code to be used in place of the photodiode to estimate the frequeny of an incoming signal (i.e. the LED blinking), and when I connected the other end of the LED to the mentioned PIN in your code, your code gives me accurate reading of the frequency of the blinking LED. But I was not sure how to use the photodiode signal instead as input instead of the LED directly so that the sequence is (LED >> Photodiode >> Arduino Pin) for I need to use the photodiode, this is the whole purpose of the question.

A bit of hardware than can turn the photodiode into an on/off signal?


text:
ESP01 flashing error
I am trying to program an ESP8266-01 WiFi module using an Arduino Uno as a USB to TTL programmer.
I have removed the ATmega and grounded the RESET pin (quite useless without the uC though).
Then, using esptool.py I tried to upload a Bare minimum sketch with the Arduino IDE and later using the following:
python esptool.py -b 57600 -p /dev/cu.usbport write_flash 0x000000 "nodemcu.bin"

However, both ways give me the same output:
A fatal error occurred: Failed to connect to ESP8266: Invalid head of packet ('\x08')

I have tried sending AT commands to the ESP01 like "AT" or "AT+GMR" and everything works fine, but I cannot upload any sketch because of that error.
I also followed esp8266 official forum advice to edit the Python script according to the following, but without success.
Line 43 ESP RAM BLOCK = 0x1800 //change this to 180
Line 44 ESP RAM BLOCK = 0x400 //change this to 40

The level conversion from 5v TTL to 3.3v is done through simple resistor node (2k and 1k), while RST is kept at Vcc through 10k pull-up resistor and a push button to ground it.

Are you sure 57600 is the correct baud rate? Wasn't it 115200?

Your wiring sounds wrong.
Tie CHPD to Vcc (3.3v) to enable the device.
Tie GPIO0 to ground as you power up, to put it into programming mode.
RST can be left floating, or PULL (not tie!) up to Vcc through a resistor, say 10k.
That diode level shifter arrangement is unusual. A potential divider on the ESP's RxD is all you need - say 1k and 2k.

I tried and I still get the same error

Could you post a circuit diagram of what you tried, please?

Sure, check it out now

According to your new schematic, RST is tied to GND. Is that just a mistake in the drawing?

Yes it was a mistake, RST goes to Vcc through a 10k resistor as you suggested and to GND via push button

An addition to Mark's answer, from Uploading sketch to ESP8266

Before download, pull both GPIO0 and RST to ground. Release the pull
  down on RST, but keep GPIO0 low. When the IDE has finished uploading,
  release GPIO0 from low.

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


text:
ESP01 unsuccessful code execution
I am trying to upload the Blink example from the Arduino IDE to a ESP8266-01 module using an Arduino Uno as serial programmer.
Now, the upload is successful but, upon restart (and disconnecting GPIO0 from GND), nothing happens. I have tried with different example sketches but it seems code was not uploaded.
My Board manager configuration

Board: Generic ESP8266 Module
Flash mode: QIO
Flash frequency: 40 MHz
CPU frequency: 80 MHz
Flash size: 1M (128K SPIFFS)
Debug port: Serial
Debug level: none
Reset method: ck (tried nodemcu too without success)
Upload speed: 115200
USB port

As an addition, here's what I get from the ESP01 through the Arduino IDE Serial monitor:
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld
e:
 ets Jan  8 2013,rst cause:3, boot mode:(3,7)

ets_main.c

and here's the IDE console window output:
sptool.py v1.3
Connecting..........
Auto-detected Flash size: 8m
Running Cesanta flasher stub...
Flash params set to 0x0020
Writing 229376 @ 0x0... 0 (0 %)1024 [...]
Wrote 229376 bytes at 0x0 in 39.0 seconds (47.0 kbit/s)...
Writing 229376 @ 0x10000... 0 (0 %)1024 [...]
Wrote 229376 bytes at 0x10000 in 39.0 seconds (47.0 kbit/s)...
Leaving...

The sketch I am using
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                    // but actually the LED is on; this is because
                                    // it is acive low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

The standard blink example from the Arduino IDE uses pin 13. Have you modified it to use an equivalent pin on the ESP8266 to which a led has been attached ? You may also find that for uploading a sketch, it is necessary only to have GPIO0 pulled low during the reset/restart. Afterwards, you may then pull it high to load the sketch and run it.

Yes, I am using the LED_BUILTIN macro

try using 1 instead of the macro

@dandavis nothing, I have also tried to upload a different sketch for a Captive portal but code doesn't seem to be running.

If you are using an ESP01 I don't think you should be using GPIO1 as the output pin, its my understanding that they don't have GPIO1.
I think they have GPIO0 and GPIO2, so you should have attached the LED to GPIO2 and use digitalWrite(2, HIGH); in you code.
Have a look at this page and see if what its on about is what you are trying to do.
http://iot-playground.com/blog/2-uncategorised/38-esp8266-and-arduino-ide-blink-example

I guess it may be better to use a sketch which writes to the serial console to see signs of life from it if the led method is not conclusive. Incidentally, connecting a Uno directly to the ESP01 (which the OP appears to be doing)  will result possibly in 5v at the ESP01 RX pin and some sort of level shifting is recommended.

Exactly, that is what I thought and apparently serial communication within the sketch is not working (the code was just sending a string over serial, no leds involved).

GPIO1 is also known as TX, and on the ESP-01 it can be used as a digital output. Note that the blue on-board LED is also tied to GPIO1, as an inverted on-low configuration. You can't use Serial.begin if you use TX as an output.

I'm using this sketch: void setup() { Serial.begin(9600); } void loop(){ Serial.println("Hello World!"); delay(1000); }

@Anelito - 1. Are you connecting via Arduino? 2. Can you connect direct to PC/Mac? 3. Have you got a second ESP-01? 4. Are you using level shifting?

I am using an Arduino UNO as serial programmer (I have removed the Atmega) and a resistor-based level switch (2k and 1k). I have tried using esptool directly from command line and the output doesn't change. Unfortunately it's the only ESP module I got

Resistor based level switchers don't work for serial at 9600.  You can try 2400 baud, but are better off with a proper level shifter.

I know resistor switchers aren't the best choice but they worked when I was using the AT commands. I have tried with Serial and led sketches, so I believe there is a problem in uploading the code to the ESP or in running it.


text:
No code, but Fatal exception (0): epc1=0x402066ac, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000 in Serial Monitor
I have a Wemos d1 mini, and when I upload nothing or anything to it, the built-in LED always lights up and the serial monitor gets a lot of garbage at every baudrate.  I have supplied it with 4 AA batteries and the board has a built in voltage regulator of 3.3V at the 5V pin.
The Wemos d1 mini contains the esp8266 chip.
Please help me!  I have searched everywhere.  This just happened all of a sudden, the board was working perfectly fine before too.

do you have anything hooked up to the pins?

No, nothing is hooked up besides the power cables.

Garbage on the serial port when you power the board up or otherwise reset it is normal. It's the bootloader boot messages at a strange baud rate. You can ignore them.

@NathanRamanathan - You have power cables and USB?  It will draw power from the USB, you don't need external power too.  Like Majenko says ESPs always dump garbage on start-up, so it might be OK.  Have you checked you have the Reset switch in the correct place?  Have you grounded GPIO-0 (not D0) during boot up and corrupted the firmware?

Yes, Code Gorilla.  You figured it out!  I might have accidentally grounded pin d3, GPIO-0, during boot up.  What do I do?  I never heard of reflashing a wemos D1 mini.

Three words.  "You Bricked it"
Before you go surfing on the web for days and days, I'm just going to say the module is bricked.  I've been there and found out that you should never use these devices on breadboards and with funky power sources.  There is this chip within the module called eFuse,  which is basically an electronic fuse that's really easy to destroy.  Just use the Arduino YUN or other certified or Chinese clonable modules. Those Italians are smarter than you think. That's probably more reliable because you won't have any power issues or frying issues.
I'm also assuming that you are getting a fatal exception (0) in the Serial Monitor.  In that case, your module's death sentence is officially sealed.
Congrats. :(

For me, this was not true! I was able to "revive" the ESP-01 by simply flashing it again using Arduino IDE. I was getting the same message from the Serial Monitor prior to this, after I've tried flashing new firmware.


text:
Open drain without pull-up
Looks like I didn't make myself clear, sorry. Update to clarify things / TL;DR version:

4 Arduino UNO pins are connected to respective DE-9 pins, responsible for UP, DOWN, LEFT, RIGHT directions
Arduino sketch simulates joystick actions
DE-9 device acts as a slave - I set respective Arduino pins to OUTPUT LOW (DE-9 device registers movement) or keep them as INPUT (DE-9 device registers no movement)

Question: what are the cons of exploiting open drain OUTPUT without pull-up in HIGH state for each pin, regarding this scenario?
Pros are: no more INPUT / OUTPUT switching, pin is disconnected and doesn't take any current what simulates original joystick state.

I have a small project interfacing the Atari joystick port (DE-9) used in retro computers. Basically, all DE-9 direction pins are in HIGH state. To trigger a movement the corresponding pin(s) must be pulled LOW.
At first I used Arduino pins in OUTPUT mode / HIGH state. This was probably not the best way, so now I keep them in INPUT mode and switch to OUTPUT when needed. But the more I read, the more ideas come to mind. I've learned that in open drain OUTPUT the pin is either LOW or switched off (floating). There is the usual recommendation to use a pull-up resistor so that the pin has a known state. But in my case this isn't necessary. I don't need to read the state of the DE-9 pins at all. I just need to pull them LOW or don't touch them at all. Open drain seems best for this purpose as I wouldn't have to switch between modes. Just LOW to trigger a move or HIGH to turn the pin off and cancel movement on DE-9.
Is this a good idea? Are there any side effects regarding lack of pull-up I should be aware of? I know this is a creative way, but this is a personal project and I don't have to follow strict rules.

Well, on an Arduino, it would be normal to use pinMode( myPin, INPUT_PULLUP ) in the case of interfacing to an open drain input device. On some MCUs, the process of writing HIGH to an input pin can force the pin's internal pull up resistor to be active which is also what you would want.  As said in the first answer below, some sort of pull up is mandatory for an open drain/open collector type input to an MCU.

you did not say what you are doing ... are you using the Arduino to read an Atari joystick, or are you using the Arduino to emulate an Atari joystick? ... please update your post with a clarification

Yeah, apparently I didn't make myself clear enough. Post updated!

We can differentiate these alternatives, omitting others that would need extra hardware:

Set the pins in OUTPUT mode, and switch between HIGH and LOW.

This will produce short circuits when the controlled computer shares the pins between multiple joysticks or mice. For example, the Atari ST does this.
Do not connect another joystick or mouse in this case. Neither for the same input, nor for another input.

Switch the pin between OUTPUT mode with a LOW level and INPUT mode.

This will work just fine.
If you happen to use the Arduino unconnected, the pins will float during INPUT mode. Since you do not plan to read the pins, it does not matter. However, supply current could increase when an input is "in between" in the illegal voltage range.
The MCU's pin protection usually avoids damage. However, discharging your electric charge on a sparking touch could be too much. Think "x-mas time" and "woolen pullover."

Use open-drain mode, and switch between HIGH and LOW.

You need direct SFR access for implementation instead of Arduino library functions.
The rest is like above.

Switch the pin between OUTPUT mode with a LOW level and INPUT_PULLUP mode.

This will work just fine, too.
The levels are defined when unconnected.
Of course the Arduino's pull-ups will be in parallel to the ones of the controlled computer. But because of the high resistor value, it makes no problem.

So, to answer your question ("Is this [open-drain mode] a good idea?"): Yes, it is. You might want to consider using a pull-up, though.
Note 1: Consider the small interval when switching the pin mode and the pin level. Make sure you do not create a short circuit, instead accept a short interval of floating.
Note 2: Make sure you connect "ground" as the fifth connection. You did not mention it in your question.

Thank you for the detailed explanation. This is exactly what I needed. You also nailed some details I wasn't aware of! GND is connected just like the fire button.

A pull-up resistor is absolutely needed for open-drain communication.
Whether you read the pin or not is irrelevant, as someone has to read
it, otherwise there would be no communication. If the device at the
other end of the link provides its own pull-up, then you don't need to
add your own. If it doesn't, then you will have to provide it.
You have to watch out for the voltage levels. The pull-up should pull to
the logic level of the reader. If that voltage is greater than the logic
level of the writer (the Arduino), you need a proper level shifter.
Otherwise a simple connection should work fine. In the later case, you
can write by switching the pin between the INPUT state and the
OUTPUT LOW state.


text:
MAX485 communication between multiple Arduinos
I purchased multiple Arduino Mini Pros and MAX485 TTL boards and now I'm trying to make them communicate together, but the problem is that I need that everyone can send and receive when needed.
I mean, normally, the "Master" request something and then the right "Client" responds. But in my application everyone's master and everyone can send at anytime to anyone. Is there a library, that synchronizes the Read/Write between those Arduinos, so that when one is sending (at anytime) that the other ones won't send, until the transmission of the Arduino who's sending is over?
If there's no library, could I attach one more pin between all Arduinos that act like a PTT switch? When one want to send, it pulls the pin X high and if some other Arduino want to send, it checks for that high pin: If it's high, it will wait. Could that work too? Or maybe this isn't reliable?
Any suggestion or help are highly appreciated.

everyone's master and everyone can send at anytime to the master... just think about that for a second and ask yourself if that makes sense.

sorry about the redundancy... but I hope you got the point @dannyf :)

I tried to write a helpful answer but failed.  Your PTT idea won't work, what happens when multiple devices pull it high at the same time?   You do need some sort of co-ordination to prevent collisions, but apart from a central master device I can't think or how you could do it without writing a big protocol library.

I just wrote my own protocol in theory here, it should work. If it works, I'll answer my own question. Basically MODBUS, the only difference is that the client can send something without the Master requesting first. The client sends a request to talk to the line, then the master accepts it and at the same time the other Arduinos will know that they should "shut up" until the master says that the message was received. If the client requests to talk and it fail (the master don't reply accepting it), it will timeout (20-XXms) and try to request again.

It's me from the future: This won't work. One needs to be master and all the others slave, so the master can coordenate all the others.


text:
Lifespan of a hot microchip
I'm currently building my own Home Automation System with a bunch of Arduinos and Relais, all of them wired to Ethernet "Shields". The casing I am printing on a 3D printer.
The Arduinos work great with those Ethernet "Shields", but the ENC28J60 chip on those Ethernet boards get quite hot. I am measuring 79.5°C approx.
In the plastic casing, I expect that they reach higher temperatures (because it's closed and has no ventilation whatsoever).

Since I am building this as a permanent solution (House wiring is now all newly adapted and I have no way back), which lifespan can I expect from those Ethernet boards?
The datasheet of that chip is saying that it's rated up to 85°C, but what does this upper rating mean? Will it stop working at this point, or only begin to degrade it's lifetime at this point?
EDIT: I have no space to put a dissipation block on those chips, because the casing is so tight.

I'm voting to close this question as off-topic because it is entirely about the ENC28J60 and not about Arduino at all.

This would appear to be a malfunction, either due to past damage or miswiring, for example mishandling of the Ethernet transformer bias.  With full engineering detail included, on a site like Electronics Stack Exchange it could perhaps be addressed, but doesn't belong here.

At the outset, you wrote “The casing I am printing on a 3D printer”, and at the end, “I have no space to put a dissipation block on those chips, because the casing is so tight”.  So, redesign the case with either more room or an opening for a heat sink to protrude.

I agree this is not about Arduino.  Remember the rule of thumb about chips, though:  Every 18 degrees F cuts their lifetimes in half.

FALSE POSITIVE... Sorry and thanks to all the suggestions given, but the meter was not calibrated. The calibrated one shows 46°C... I think that's acceptable. (Today I noticed something was wrong when the floor was 50°C and I was like wtf?!?

The reliability data is typically not in the product datasheet but in pen whitepapers. Generally speaking life span goes down exponentially as temperature rises. For some high temperature semi conductors ( designed specifically for high temperature applications) you are talking about hubdreds or thousands of hours at rated temperatures.
That should give you some sense as to what to expect.


text:
Arduino and custom pcb
I am looking to minimize the size and assembly complexity of my arduino projects. Is there any easy way to integrate something like an esp8266 onto my own pcb. I don't want to have to solder it on. In the end I would like to have a custom pcb with all my electronics and instead of then having to solder my esp 8266 onto that board, it would already be integrated. I am quite a noob. I know that you can integrate the esp8266 chip onto a pcb, but is there a way to integrate like the chip and all of the other stuff that's usually on an esp8266 module in one step. Like the port for uploading and the voltage regulator etc. Thanks for all the advice in advance

A custom PCB is - well - custom. The whole principle is, that you are doing it yourself. If you don't want to solder it yourself, you can use an assembly service of a PCB manufacturer. They will place and solder the components for you, so that you get a ready to use PCB.

It is unclear to me what you are asking. You want or don't want to use a ready made esp8266 board as part of your project? If you get a Wemos D1 mini you can put it ioto female headers integrated into your PCB.

Is this what you want?

I don't want to solder a D1 mini or something similar onto my printed pcb. What I am looking for is to integrate the esp8266 IC onto my own pcb. (so instead of soldering esp module pcb onto my pcb, they are both on the same pcb) I would have a company smd solder it onto the pcb.

It is unclear, what your actual problem is. Sure, you can put the ESP8266 directly on your PCB. The same with voltage regulator and USB port. What is the actual problem in creating this PCB?

Well I have no idea what all I need. I have never done something like this before and I thought this community was for people that need guidance

Almost every chip or module come with datasheet or hardware design guide, you need to read those to understand what you need prior to the design of your custom board. For ESP8266, read the ESP8266 Hardware Design Guidelines. If you are new to hardware design, consider to use readily-made module such as ESP-12S.

Instead of soldering the module directly onto the board, you could design a slot or socket for an ESP8266 module like the ESP-12. This would allow you to easily place and replace the module without direct soldering.

You can buy ESP8266 modules pre-assembled with pin headers. Like this
one for example (not a specific recommendation, just the first
organic Google result). You can then solder this module on your PCB just
like you would solder any DIP package. Alternatively, you can solder a
DIP socket on your PCB, and then plug the module on the socket.


text:
How do you remove a number of characters from a parsed string?
Using this code - advertisedDevice.getServiceDataUUID().toString().c_str()); returns the following string -
0000feaa-0000-1000-8000-00805f9b34fb
How can I adjust the code to do that it omits the first nine characters leaving only -
0000-1000-8000-00805f9b34fb
Thank you.

not an arduino question ... it is a general programming question

Note: Even if this question is about general C++ programming, this might help other Arduino users, too. Better ask at StackOverflow the next time. ;-)
The result of your chain of method calls returns a pointer to non-writable chars. You can add any offset to this, in the range from 0 to the number of characters.
In your case:
const char* result = advertisedDevice.getServiceDataUUID().toString().c_str() + 9;


text:
ESP32: Is the networking stack running in separate thread? Can you safely block task executed from loop() for longer time? (>3s)
With ESP8266 there is a requirement to not block the CPU execution for longer than few ms and then yield to networking stack and internal functions that are executed after each iteration of loop(). If you block CPU for too long, network will misbehave. If you block it for longer than ~3 seconds SWDT resets the MCU.
Now with ESP32 you have 2 CPU cores and RTOS running in the background that has full multithreading support. Is the Arduino framework for ESP32 taking advantage of this? Is the whole "user program" running as separate task besides the network and system stack? Would blocking the CPU in main loop cause similar problems as ESP8266?
From xPortGetCoreID() we can see that both setup and loop run always from core 1, not core 0, so I assume that user program is by default pinned to core 1 and network stack runs on core 0? Can someone confirm that?
This is just hypothetical question, I am just curious about internal ESP32 architecture and Arduino implementation, not making anything specific.

In the Arduino IDE you can select on which core the user program shall run, but yes, the default is 1.

@PMF ok, but does that mean the network stack is running separately in core 0, or is it done in same "everything in 1 thread" way as in ESP8266?

As far as I know it runs on its own thread (the ESP32 uses a FreeRTOS kernel in the back). I have a project where I run quite expensive operations on the "user" core while a connection is maintained automatically. It should be easy to test this, shouldn't it?


text:
Is it possible to use multiple I2C sensors with Arduino without an I2C multiplexer?
I have an IMU sensor and a Bluerobotics temperature sensor, both have different I2C addresses.
I want to integrate both with an Arduino UNO, I know I can do this with an I2C multiplexer but I don't have access to one right now.
Is it possible to integrate them with arduino without a multiplexer, i.e., by just connecting them parallelly on the A4 and A5 pins of Arduino? (This didn't work though when I tried, the temperature sensor was giving values but the values of IMU sensor were only zeros on the Arduino Serial Monitor)
I've found some videos on it on YT, some have connected pull up resistors to the sensors, but this method doesn't seem to work.
So before delving deeper into it, I'd like to know if this is even possible to do without a multiplexer, because my time is precious since I have a project deadline.

Yes, I2C is a bus designed for connecting multiple i2c devices via the same bus as long as the i2c devices have different i2c address. If you can read the temperature sensor, but not the IMU, run the i2c scanner to see if you can detect it first. You will definitely need pull-up resistors on both i2c lines if your Arduino or your sensors do not have it.

also asked on Arduino forum https://forum.arduino.cc/t/is-it-possible-to-use-multiple-i2c-sensors-with-arduino-without-an-i2c-multiplexer/1027277

first of all , you said they have different I2C addresses , so you don't need I2C
multiplexer , I2C multiplexer is only used when having more than one device having same I2C address , and refer to Adafruit I2C multiplexer as they say :

Finally, a way to get up to 8 same-address I2C devices hooked up to one microcontroller

which means it can handle 8 devices having the same address , but in your case , the addresses already are different , so why you need I2C multiplexer.
your problem needs to dig deep into debugging , you can get your self a cheap logic analyzer like this cheap 10$ saleae clone analyzer to see what data is actually put into the bus , the analyzer will make your debugging way more easy than you think , like the below picture obtained from saleae official website and also this cheap saleae clone works perfect with logic software offered from saleae:

but for your problem , I am guessing that it's due to pull resistors and the parasitic capacitance between the 2 buses , reading from I2C specification file, at section 7.1 , there is equation from minimum and maximum allowed pull up resistors according to nodes connected to the bus :

Rp(min) = (Vdd - Vol(max)) / Iol
Rp(max) = tr / (0.8473 * Cb)

where Vdd is 5V when using arduino , tr is the rise time maximum and it depends on MCU, Cb is  estimated bus capacitance and you can get that from datasheet of every component in your bus line as for arduino its capacitance is specified in datasheet at page 264 saying

Capacitance for each I/O pin Ci – 10 pF

other symbols , you can get from the I2C specifications mentioned above , but your problem is due to pull up resistors I guess and you can't really know without debugging. I recommend you using logic analyzers.

But when I connect 4.7k resistors to SDA and SCL lines and Vcc, which comes in the range, the Serial monitor screen is totally white and shows no value.
And when I do not connect any resistor, the temperature sensor is giving correct values but IMU sensor is giving fixed and wrong values.
The temperature sensor I'm using is a module, the Bluerobotics Celsius Fast Response module, and the IMU sensor (MPU 9250) is a 'bare sensor', not a module. Could the problem be because of this? maybe the temperature module already has a built in pull up resistor and the IMU sensor doesn't?

@ssmalik ، if you are adding external pull-up resistors then make sure to turn off the arduino(Atmega328p)  internal pull up resistors because if there is more than one pull up resistor on the same bus with different values , this will give you errors in reading data on the bus , also solving the problem requires debugging using things like logic analyzers as I said

Since you did not give links I went on line and checked them. Be sure the I2C modules do not have pull up resistors. If so note the value.  Adjust your external so the pull up to 3V3 is about 3.1K. You will need a level translator for both the IMU module and the Bluerobotics temperature sensor they are both 3V3 boars. Good news one set of level translators will work for both. Remember you will need pull ups on both sides of the translators, check as not all do.
Since you are just getting started you can pick one of the fine 3V3 micros in the Arduino or ESP series of boards. Simple starting point rule for pull up on I2C: 3.1K for 3V3 and 4.7K for 5V. Let us know how you do.
Bad News it is possible you damaged one or both of the I2C boards with 5V.


text:
Is my nrf24l01 radio module broken?
I was trying to use two Arduino Nano connected to two RF24 modules to build a remote control boat. I self-assembled both the remote and the receiver circuit following the skematic suggested in that page (NRF24 and Arduino Nano Every usage).
VCC - 5V (via adapter)
GND - GND
10 pin - CE
A3 - CSN
11 pin - MOSI
12 pin - MISO
13 pin - SCK
not connected - IRQ
(I double and triple checked that I connected all the cables as in the skematic)
Then, as always suggested in the link above, I checked my connection using that sketch:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(10,A3);  // for arduino nano every
//RF24 radio(9,10); // for arduino uno

const uint8_t num_channels = 128;
uint8_t values[num_channels];
void setup(void)
{
  Serial.begin(9600);
  printf_begin();
  radio.begin();
  radio.setAutoAck(false);
  radio.startListening();

  radio.printDetails();
  delay(5000);

  radio.stopListening();
  int i = 0;
  while ( i < num_channels )  {
    printf("%x",i>>4);
    ++i;
  }
  printf("\n\r");
  i = 0;
  while ( i < num_channels ) {
    printf("%x",i&0xf);
    ++i;
  }
  printf("\n\r");
}
const int num_reps = 100;

void loop(void)
{
  memset(values,0,sizeof(values));
  int rep_counter = num_reps;
  while (rep_counter--) {
    int i = num_channels;
    while (i--) {
      radio.setChannel(i);
      radio.startListening();
      delayMicroseconds(128);
      radio.stopListening();
      if ( radio.testCarrier() )
        ++values[i];
    }
  }
  int i = 0;
  while ( i < num_channels ) {
    printf("%x",min(0xf,values[i]&0xf));
    ++i;
  }
  printf("\n\r");
}
int serial_putc( char c, FILE * ) {
  Serial.write( c );
  return c;
}

void printf_begin(void) {
  fdevopen( &serial_putc, 0 );
}

And that's what I found for the RX:
STATUS       = 0xff RX_DR=1 TX_DS=1 MAX_RT=1 RX_P_NO=7 TX_FULL=1
RX_ADDR_P0-1     = 0xffffffffff 0xffffffffff
RX_ADDR_P2-5     = 0xff 0xff 0xff 0xff
TX_ADDR      = 0xffffffffff
RX_PW_P0-6   = 0xff 0xff 0xff 0xff 0xff 0xff
EN_AA        = 0xff
EN_RXADDR    = 0xff
RF_CH        = 0xff
RF_SETUP     = 0xff
CONFIG       = 0xff
DYNPD/FEATURE    = 0xff 0xff
Data Rate    = 1MBPS
Model        = nRF24L01
CRC Length   = 16 bits
PA Power     = PA_MAX
00000000000000001111111111111111222222222222222233333333333333334444444444444444555555555555555566666666666666667777777777777777

0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef

So that means the RF24 module isn't connected properly to the board, the correct output in the second line would be something like that: RX_ADDR_P0-1 = 0xf0f0f0f0d2 0xc2c2c2c2c2
I used a tester to check the power supply and the antenna receives 3.3V as it should.
I checked also the soldering and I didn't find any poor connections nor short circuits.
I tried all the analog pins between the A0 and A5 for the CSN for perhaps the A3 was not working.
Well, now I ran out of ideas and I'm tempted to think that my radio module is broken, but maybe I overlooked something, can you please write any ideas that you think could help?
Thankyou in advance

this may help ... https://duckduckgo.com/?q=arduino+nrf24l01+hello+world&ia=qa


text:
ESP32 nodemcu serialbt sending data
I'm currently trying to send data from esp32 to my android app that I made. The sensor readings are showing in the serial monitor, however, what's showing on my app are either @ or &. Please help and thank you. I'm new to bluetooth coding.
Here's the code:
#include "BluetoothSerial.h"
int sensorPin = 35;
int sensorreading;

BluetoothSerial SerialBT;

void  setup ()
{
    Serial.begin(115200);
    SerialBT.begin("ESP32_ABO");
    pinMode (sensorPin, INPUT);
}
void  loop ()
{
   sensorreading = analogRead(sensorPin);
   String toSend = String (sensorreading);
   sendData(toSend);}

void sendData(String textToSend){

   Serial.print(sensorreading);
   SerialBT.write(textToSend[sensorreading]);
}
delay(1000);}

You see very different output via bluetooth and Serial Monitor, because you are sending completely different things. On the Serial Monitor you see the sensor reading, since that is exactly, what you send:
Serial.print(sensorreading);

The print() function will convert the integer variable sensorreading into human readable text (meaning ASCII encoded text) and send this over Serial.
But then you do this:
SerialBT.write(textToSend[sensorreading]);

textToSend is a String object here. So with the parentheses [ ] you are taking one character of that string. You try to use the sensorreadingth character. Since sensorreading comes from an analogRead(), it is most likely, that is value is rather big, meaning bigger than the length of the string. So you are basically reading some random memory, that happens to lie behind your string variable. The write() function will then send that random data out over your bluetooth serial interface, without any conversion.
I guess you want to transmit the data over bluetooth also in human readable form. So just use the same code as with the Serial interface (for the Serial Monitor).
And remove all that manual conversion of the measured analog value to a String. That is not needed. If you want to also display some text, you can just use multiple print() commands, like this:
Serial.print("Value: ")
Serial.print(sensorreading);
Serial.print(" units");

Note, that it is rather bad to use the String object at all. The String class uses dynamic memory allocation, which leads to memory fragmentation, which can eat up your available memory. This is not as important on chips with rather big memory (as the ESP32) than on chips with smaller memory (like the Atmega328p, which is used in Arduino Uno and Nano), but you should still keep that in mind. Instead of the String class you would work with char arrays, aka C-strings.

thank you sir. i tried a different approach using serialbt.write(sensorreading); instead of SerialBT.write(textToSend[sensorreading]); i get values that displays ranges from 2300 to 2400 on my serial monitor. When I try to connect it to another app, serial terminal bluetooth app which i downloaded on playstore. in the app it just displays random letters this time.

this is my current code:
#include "BluetoothSerial.h"
int sensorPin = 35;
int sensorreading = 0;
BluetoothSerial SerialBT;
void  setup ()
{
Serial.begin(115200);
SerialBT.begin("ESP32_ABO");
pinMode (sensorPin, INPUT);
}
void  loop ()
{
sensorreading = analogRead(sensorPin);
Serial.print(sensorreading);
Serial.println("mV");
SerialBT.write(sensorreading);
delay(1000);}
sorry i'm really new to arduino

thank you so much for your help sir! what is was lacking was a serialBT.print(sensorreading); to display it to the device app thnk you very much for your help

Thats great. As mentioned in the answer, SoftwareSerial.write() will send out the data untouched, meaning, that you send that data as binary (just the binary representation of the number). SoftwareSerial.print() instead creates an ASCII encoded representation of the number, which is human readable text. The app on your phone just receives the data from serial and interprets it as ASCII encoded text. So you get some random characters, when sending binary data.

If that answered your question, you can accept my answer as correct


text:
How to restart a counter in a program using a push button in a LDR Tripwire setup
So, trying to configure this code so that when I push the button, the person counter will go to zero and just as it goes, the counter will increase when the LDR will get tripped and again when the button is pressed, the counter will go to 0.
#include <LiquidCrystal.h>

int laser=8;
int pushbutton=12;
int flag=0;
int myCounter = 0;
LiquidCrystal lcd(7,6,5,4,3);

void setup()
{
    pinMode(laser,OUTPUT); pinMode(pushbutton,INPUT);
    lcd.begin(16, 2);
    lcd.print("Person Counter:"); lcd.setCursor(0,1);
    lcd.print(0);
}

void loop()
{
    lcd.setCursor(0, 1);
    digitalWrite(laser,HIGH);

    if(analogRead(A0) < 600) //A0= LDR
    {
        flag = 1;
    }

    if(analogRead(A0) > 600 && flag == 1)
    {
        myCounter++;
        delay(200);
        lcd.print(myCounter);
        delay(20);
        flag=0;
    }
}

Try out this code. I made some modification and also comment out that things.
#include <LiquidCrystal.h>

LiquidCrystal lcd(7, 6, 5, 4, 3);

int laser = 8;
int pushbutton = 12;
int flag = 0;
int myCounter = 0;

void setup()
{
  pinMode(laser,OUTPUT);
  pinMode(pushbutton,INPUT_PULLUP); // Provide pull-up

  lcd.begin(16, 2);
  lcd.print("Person Counter:");
  lcd.setCursor(0,1);
  lcd.print(0);
}

void loop()
{
  lcd.setCursor(0, 1);
  digitalWrite(laser,HIGH);

  if(analogRead(A0) < 600) //A0= LDR
  {
    flag = 1;
  }

  if(analogRead(A0) > 600 && flag == 1)
  {
    myCounter++;
    delay(200);
    lcd.print(myCounter);
    delay(20);
    flag = 0;
  }

  if(digitalRead(pushbutton) == LOW) // When button pressed
  {
    myCounter = 0; // Set counter to 0
  }
}

Glad to help you.


text:
Help Led matix isn't lighting up correctly Is it a Hardware or software issue?
I am trying to reverse engineer the project from this video: https://youtu.be/zc1zbwheyE0?t=50s.
From the video a visible 10 wires are going from the LEDs to the Arduino mega, i am assuming that they are wired in a 5x5 matrix (5 rows, 5 columns) given that there are 25 keys on the Midi controller so there most be 25 LEDs.
I reconstructed the project the best a could from observing the video, but my issue is when i press 3 keys 5 LEDs light up unlike in the original video where 3 keys are pressed and 3 LEDs light up(as seen @ 0:50 of the video).
This is the issue i am having : https://i.sstatic.net/ppLJn.jpg.
I am thinking the issue is related to how i have my LEDs wired, but my LEDs are wired exactly the same as in the video. isn't it ? is there something i might have missed? How is the project in the video able to light up 3 LEDs without having an issue with extra LEDs lighting up in their matrix? how can i fix my circuit to replicate the video?
Here is some of my coed for turning on an LED when a key is pressed:
<include MIDI.h>

MIDI_CREATE_DEFAULT_INSTANCE();

byte anodes[5] = {30, 32, 34, 36,38};

byte cathodes[5] = {31, 33, 35, 37,39};

byte data1 = 0;

void setPinTo5V(byte pin) //set a pin given to this function to a 5V voltage source

{
    pinMode(pin, OUTPUT);
    digitalWrite(pin, HIGH);
}

void setPinToGND(byte pin) //set a pin given to this function to a GROUND (GND pin)
{
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);
}

void loop() {
    MIDI.read();
}

void MyHandleNoteOn(byte channel, byte pitch, byte velocity)
{
    data1 = MIDI.getData1();

    if (data1==48){//C3
        setPinTo5V(anodes[0]);//set pin 30 to 5V
        setPinToGND(cathodes[0]);//set pin 31 to GND

        delay(1); //do nothing for 1 ms
    } //this is done for all 25 keys

}

any help would be appreciated Thanks.

duplicate of http://electronics.stackexchange.com/questions/294435/help-led-matix-isnt-lighting-up-correctly-is-it-a-hardware-or-software-issue

Please edit your question, formatting your code and adding your circuit diagram. Thanks.

Also, break the problem down into parts: if you add some trace (serial.print(...);) into your MyHandleNoteOn() function, you'll be able to tell whether you're detecting too many keys, or lighting too many LEDs.

This was what i was able to come up with, once a notes is press the blink function turns the LED on and off really fast. i am now have trouble getting the led to turn off once the notes is being pressed am not sure if the code is exiting from the while loop.
include
MIDI_CREATE_DEFAULT_INSTANCE();
define LedR 3   //
define LedC 4 //pin for each led
byte data1 = 0;
unsigned long previousMillisR[2]; //[x] = number of leds
unsigned long previousMillisC[2]; //[x] = number of leds
int Status [25];
void setup() {
MIDI.begin(MIDI_CHANNEL_OMNI);
MIDI.setHandleNoteOn(MyHandleNoteOn);
MIDI.setHandleNoteOff(MyHandleNoteOff);
pinMode(LedR, OUTPUT);
pinMode(LedC, OUTPUT);
}
void loop() {
MIDI.read();
//BlinkLedR(LedR,2000, 0);   //BlinkLed( which led, interval, one of the
stored prevMillis
//BlinkLedC(LedC, 10, 0);  //last parameters must be different for each
led
}
void BlinkLedR (int led, int interval, int array){
//(long) can be omitted if you dont plan to blink led for very long time I think
if (((long)millis() - previousMillisR[array]) >= interval){
previousMillisR[array]= millis(); //stores the millis value in the

selected array
digitalWrite(led, !digitalRead(led)); //changes led state
}
}
void BlinkLedC (int led, int interval, int array){
//(long) can be omitted if you dont plan to blink led for very long
time I think
if (((long)millis() - previousMillisC[array]) >= interval){
previousMillisC[array]= millis(); //stores the millis value in the

selected array
digitalWrite(led, !digitalRead(led)); //changes led state

}
}
void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
data1 = MIDI.getData1();
if (data1==48){//C3
Status[0]=1;
while(Status[0]==1) {
BlinkLedR(LedR, 10, 0);   //BlinkLed( which led, interval, one of the
stored prevMillis
BlinkLedC(LedC, 1, 0);  //last parameters must be different for each led
if (Status==!1){
break;
}
}
}
}
void MyHandleNoteOff(byte channel, byte pitch, byte velocity) {
data1 = MIDI.getData1();
if (data1==48){//C3
Status[0]=0;
}
}

Your code is incomplete, so it's impossible to be sure, but I suspect your problem is with the way you are lighting the LEDs in the matrix.
Think about it conceptually: your LEDs are on the junctions of rows (anodes) and columns (cathodes).  To light an LED you make the row high and the column low.
Let's call the rows R1, R2, R3, R4 and R5, and the columsn C1...C5.
Let's say the first LED you want to light is at the junction of R1 and C1.  You make R1 high and C1 low.
Now you want to light an LED on the junction of R3 and C3.  You make R3 high and C3 low.
What happens?  Four lights light up.  Why?  You have R1 and R3 high, and C1 and C3 low.  The circuit doesn't "know" that you want only two LEDs lit: it will light R1C1, R1C3, R3C1 and R3C3.
What is the solution?  Remember which LEDs you want lit.  Cycle through the matrix and deal with one row at a time: light all the LEDs you want lit in that row.  Then move to the next row and repeat.  Do this very fast.  Your LEDs will be flashing, but if you write your code properly they'll do it so fast you won't be able to see it.

This was what i was able to come up with, once a notes is press the blink function turns the LED on and off really fast. i am now have trouble getting the led to turn off once the notes is being pressed am not sure if the code is exiting from the while loop.


text:
Arduino Interrupt example not working
The example program is from here: https://www.arduino.cc/en/Reference/attachInterrupt
When I paste in the code and run it, the LED is on all the time (It's supposed to blink):
const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}

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

void blink() {
  state = !state;
}

This is my setup:

I think you misunderstood this example: it is not expected to automatically blink!
The LED is suposed to change state at every change of level on pin 2. This supposes that you wired something (e.g. a push button) to pin 2 and that this will make pin 2 change level when something happens (e.g. you press the button or you release it).
On your diagram, there is nothing wired on pin 2, so what you observe is just normal.
If you want to see attachInterrupt in practice, then connect pin 2 to a button with the other button lead connected to GND.
Then you can observe what happens when you play with that button.

I didn't have a button but I connected an ultrasonic distance sensor and the LED starts to blink whenever the distance changes. Thank you :)

if you want to blink your LED by giving interrupt by push button then you can try this..
int pushButton = 2;
int LED = 13;
volatile bool flag = false;
volatile byte state = LOW;

void setup()
{
    pinMode(pushButton, INPUT_PULLUP);
    pinMode(LED,OUTPUT);
    attachInterrupt(digitalPinToInterrupt(pushButton), &setFlag, FALLING);
}

void loop()
{
    if (flag)
    {
        digitalWrite(LED, state);
        delay(100);
        state = !state;
    }
}

void setFlag()
{
    flag = true;
}

An error with the code you show:   setFlag is not defined.  Also, some of the closing braces aren't indented in the code as shown, and the last one isn't shown as part of the code block

@jwpat7 Sorry for the code I have edited this code now..check it. Up

And it will blink too fast to be visible.

@EdgarBonet  add some delay() then problem will be solved

your code is a little bit too complicated. in the "if (flag)" portion of the code, flip the LED via "digitalWrite(LED, !digitalRead(LED));" and then clear the flag. No delay needed.

@dannyf, without a delay(), the LED gets toggled every pass through loop(), ie the  “blink too fast to be visible” problem Edgar Bonet mentioned.  With the delay, it still toggles every pass through loop(), so blinks at a 10 Hz rate.  That's still too fast, but will be visible.  Of course, once it starts blinking it never stops -- flag starts out false, but once it's set it never gets unset.  A problem!

to expand on my comments to Prayuktibid's code,  here is what I would propose in the loop:
void loop()
{
    if (flag)
    {
        //blink the led
        digitalWrite(LED, !digitalRead(LED));   //digitalWrite(LED, state);
        //delay(100);
        //reset the flag
        flag = false;                           //state = !state;
    }
}

the rest remains unchanged.
here is how it works:

it works as you would expect, without resorting to delays.
edit: btw, the approach shown above (of setting a flag in the isr, processing that flag in the main loop, and resetting the flag after the processing) is a fairly standard way of utilizing interrupts - pretty much the #1 choice unless you have some special reasons to deviate from it.
edit2: to just follow up on that state above (about trying to process the flag in the main loop).
for something this simple, you can also do it in the isr, making the code much closer to your original code:
void loop()
{
        digitalWrite(LED, flag);                //digitalWrite(LED, state);
}

void setFlag()
{
    //flip the flag
    flag = !flag;                               //flag = true;
}

the code above produced the same waveform as the code posted earlier.
the lessons learned: there is more than one way to solve a problem, as long as you do it right, :)


text:
Use input capture for multiple sensors simultaneously
I want to accurately time multiple digital input channels (readings from sensors) for the rising and falling edges. I need the precision of the Timer1 Input Capture. As far as I know the input capture only listens to pin D8 (for ATmega8). So, is there anyway to capture the inputs of multiple sensors?

Update:
I would like the reading to be as accurate as possible since I'm using the values to calculate motion tracking information. Concretely, I'm trying to build my own tracker for StreamVR's light house.

How accurately? (in microseconds)

As accurate as possible... see my edited question. BTW, I've read your note on Arduino's interrupt... That is very valuable! Thanks! :D

"As accurately as possible" is too vague. You may as well say you want to have "as much money as possible" in a job interview. Do you want accuracy down to 1 ns? 1 µs? 1 ms? 10 ms? Let's say your answer is "1 ns". Then the ATmega8 isn't the chip for you.

If you use pin-change interrupts, then you will get "as much accuracy as possible" that pin-change interrupts will give you.

Then you better use the ATmega328P, because the ATmega8 doesn't have "PCINT" (Pin Change Interrupt).
Some older sensors use frequency output, because a microcontroller could read that. However, today there is I2C and SPI interface. If you can't get another interface than a frequency output and you want the best accuracy, then you have to add extra hardware to read those signals.

If you want input capture (i.e. single cycle) accuracy on multiple input channels, you will need multiple input capture units. The Atmega2560 (powering the Arduino Mega 2560) has four of them, one in each 16-bit timer.


text:
'SoftwareSerial' does not name a type in Adafruit Feather M0 Bluefruit LE
I am trying to create a software serial connection between Arduino Uno & Adafruit Feather M0 Bluefruit LE.
I am getting the following error in the M0 sketch:
Arduino: 1.8.1 (Windows 10), Board: "Adafruit Feather M0"

atcommand:60: error: 'SoftwareSerial' does not name a type

 SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);

 ^

atcommand:62: error: 'bluefruitSS' was not declared in this scope

 Adafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,

                               ^

exit status 1
'SoftwareSerial' does not name a type

Here are the modifications I did to the atcommand sketch (in Adafruit BluefruitLE nRF51 library) before uploading to the M0:
#include <Arduino.h>
#include <SPI.h>
#if not defined (_VARIANT_ARDUINO_DUE_X_) && not defined (_VARIANT_ARDUINO_ZERO_)
  #include <SoftwareSerial.h>
#endif

#include "Adafruit_BLE.h"
#include "Adafruit_BluefruitLE_SPI.h"
#include "Adafruit_BluefruitLE_UART.h"

#include "BluefruitConfig.h"

// Create the bluefruit object, either software serial...uncomment these lines

SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);

Adafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,
                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);

/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */
// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);

/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */
//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);

/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */
//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,
//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,
//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);

I  tried to comment the if statement before #include <SoftwareSerial.h>, I got the following error:
Arduino: 1.8.1 (Windows 10), Board: "Adafruit Feather M0"

C:\Users\hadeel\AppData\Local\Temp\arduino_modified_sketch_612073\atcommand.ino:18:30: fatal error: SoftwareSerial.h: No such file or directory

   #include "SoftwareSerial.h"

                              ^

compilation terminated.

exit status 1
Error compiling for board Adafruit Feather M0.

What is the problem?

SoftwareSerial is not available for the Zero core. There are so many HardwareSerial ports to use instead :) https://forum.arduino.cc/index.php?topic=341054.0

THANK YOU .. It finally works .. really appreciate your help ..


text:
Confusion about String handling
I am trying to execute some webbased calls, but my string keep "disappearing", and I am highly confused about why.
I can println a string directly, but if I have it in a variable, it will disappear :I
I tried googling around, but could not find a reason for it. Is it because of the curly brackets ? Is it a memory issue ?
I feel I really can't code on and juggle web calls, if I can't even handle regular string commands..
Code:
Serial.println(" - CONSOLE/STRING WEIRDNESS - ");
String message = "Testing time {0}";
Serial.println(message);
Serial.println(String(message));
Serial.println("Testing time {0}");
Serial.println(message.substring(3,6));

Response:
- CONSOLE/STRING WEIRDNESS -
(nothing)
(nothing)
Testing time {0}
(nothing)

Update
This seems to happen whenever there is a number inside a string, it even happends with a simple string like this:
Code:
Serial.println(" - CONSOLE/STRING WEIRDNESS - ");
String message = "Testing time here is a number 0";
Serial.println(message);
Serial.println(String(message));
Serial.println("Testing time here is a number 0");
Serial.println(message.substring(3,6));

Response:
- CONSOLE/STRING WEIRDNESS -
(nothing)
(nothing)
Testing time here is a number 0
(nothing)

Out of memory? Looks like the String constructor failed to allocate storage on the heap.

Give this article a read, it highlights how strings are actually stored in the Arduino memory, and explains how strings should be used.
https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

Turned out it was string weirdness indeed. Thank you so much for this, I will be cautious with the String class from now on.

Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference. Feel free to add a more complete answer that directly answers the question.

The {0} denotes an extra parameter (which you want to print), it seems you just want to print the string without any variable 'value' so you can remove the {0}.
I'm not so familiar with using {0} in C++, but in C# {0} means argument number 0 (after the initial string), since this argument is not given, probably an empty string is created ... it would be more intuitive if the compiler give an error or warning (maybe it gives a warning and you can check for it).
Also converting a string to String() does not do anything but I think it was just for debugging/checking purposes.
Also in Arduino to save SRAM space, normally it is wise to add before each string, the F function like:
Serial.println(F("Some string to print"));

This will create a memory in Flash and will not be copied to SRAM which is normally quite scarce.
To print out arguments you can simply use multiple print commands (which does not add a new line) and the last part of the line with println, like:
Serial.print(F("Test time: ");
Serial.println(test_time);

I can see why "{0}" would cause weirdness, but the fact that just having a number in it, and it still disappears, really confuses me... http://i.imgur.com/EzNmxOU.png

{0} is the argument number (I edited the answer).

Roger that, but did you see my update about a pure string with an integer in it (no curly brackets), and that still fails. Can I really have no numeric characters in a string ?

I don't have a compiler, but normally  it should work like Serial.println("Test time {0}, test_time);    where test_time is the variable (not sure if you have to cast it to a string, I don't think so.