text:
"SSD1306 allocation failed" when #include SD.h
I'm using the ssd1306_128x64_i2c example file from the 1306's library.
It works perfectly until I add the #include SD.h line, after which it gives the allocation failed error.
Please advise.
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <SD.h>

Adafruit_SSD1306 display(128, 64, &Wire, 4);

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

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
  }

  display.clearDisplay();
  display.display();
  testdrawchar();
}

void loop() {
}

void testdrawchar(void) {
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.cp437(true);

  for(int16_t i=0; i<256; i++) {
    if(i == '\n') display.write(' ');
    else          display.write(i);
  }
  display.display();
}

I had this exact same problem and was glad to see someone had already asked this question.  It is quite shocking that you cannot use SD.h and the adafruit oled library at the same time.

I was able to make it all fit by using the text-only library for the OLED.
SSD1306Ascii Library
Much thanks to Majenko for explaining the problem and greiman for writing the library!

Both the SD library and the SSD1306 libraries want big buffers. That means lots of memory.  You don't have lots of memory.

The SD wants at least 512 bytes for a sector buffer (which is allocated at compile time).
The SSD1306 wants at least 1kiB for a display buffer (which is allocated at runtime).
Serial wants at least 128 bytes for TX and RX buffers (which is allocated at compile time).
The Wire library needs 32 bytes for a TX buffer.

That's 1696 bytes of a total 2048, and that's not taking into account any of the other variables and things that your program, the various libraries, and the Arduino core itself needs, plus the stack (and its specified minimum size safety zone).
There's nothing much you can do about it, short of upgrading your Arduino to one with more memory, or splitting your design across multiple Arduinos.

Is there a way to know exactly how much memory I am over by at runtime?

Not really, no. All you know is that trying to allocate the memory failed.

There is somewhere a "free memory" example / library that can tell you how much free memory there is, though, which could help.


text:
bh1750 lightsesor won't work
ok, im having problems with my bh1750, here is all info i got:
board: esp32s nodeMCU v. 1.1
Pins:

Wiring: (the 2 reds go to pin 21 and 22)

code:
#include <BH1750.h>
#include <Wire.h>

BH1750 lightMeter;

void setup(){

Wire.begin();
Serial.begin(115200);
lightMeter.begin();
if (lightMeter.begin()) {
Serial.println(F("BH1750 initialised"));
}
else {
Serial.println(F("Error initialising BH1750"));
}
}

void loop() {
uint16_t lux = lightMeter.readLightLevel();
Serial.println(lux);
delay(500);
}

Sorry for bad formating
Serial output:
13:01:41.926 -> [BH1750] ERROR: received NACK on transmit of address
13:01:41.926 -> [BH1750] ERROR: received NACK on transmit of address
13:01:41.926 -> Error initialising BH1750
13:01:41.926 -> [BH1750] Device is not configured!
13:01:41.926 -> 65534
13:01:42.430 -> [BH1750] Device is not configured!
13:01:42.430 -> 65534
13:01:42.932 -> [BH1750] Device is not configured!
13:01:42.932 -> 65534
and that goes on forever
Hope someone got an answer :D

hrello still needs help

The SCL and SDA silkscreen was reversed on my chips.
Took an hour of faffing to figure that out.
Never "Just presume" it is correct

Your code looks good. I2C configuration is default which depends on your board manager.
Then your wiring may be wrong.

Using a multimeter to check supply voltage on the BH1750 module. It should be 3.3V
Using a multimeter to check the connection between the BH1750 module with ESP32.
Difference ESP32 vendor may provide a difference I2C pinout. Make sure you connect everything correctly.
Using an oscilloscope or logic analyzer to capture data on an I2C bus.
If everything good, try to use another module.

From your log, I guessed, the power supply is good. I2C connection is your problem.
More, you should use the different color wire for the difference signal. It helps prevent unexpected connections.

source: Stack Exchange

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

sort: votes


text:
Arduino SPI Multiplexer problems
I want to use the ADG731 32 ch multiplexer to read 32 potentiometers, I have wired everything and it works but it doesn't works as fast as I would want.
The problem is that If I turn a potentiometer between the range of 10-90% of the rotation, the analog reading is so slow, for example, if I have my POT at 0, and i turn it to 50%, it goes so slow until it reach the 512 value(like an hysteresis effect), BUT, if I turn the potentiometer back to 0 or up to 1023 it makes the reading as quick as I would expect.
So in resume it reads slowly the values except the edges values.
This is my code(I have set it to read only one potentiometer at pin S16 to test how the ADG731 works:
#include <SPI.h>

void loadDrain(void);
const int slaveSelectPin = 53;
void setup() {
  pinMode(slaveSelectPin, OUTPUT);
  SPI.begin();
  Serial.begin(9600);
}

void loop() {
  loadDrain();
}

void loadDrain(){
  SPI.beginTransaction(SPISettings(30000000, MSBFIRST, SPI_MODE2));
  digitalWrite(slaveSelectPin, LOW);
  SPI.transfer(00001111);
  digitalWrite(slaveSelectPin, HIGH);
  SPI.endTransaction();
  Serial.println(analogRead(A0) >> 3);
}

You should remove the multiplexer from the circuit to see if that is the culprit. (I'm guessing not.) I'd try wiring 1 pot directly to the analog input pin and seeing if the results are still slow to register.

BTW, why do you issue the SPI commands to select the specific pot every time, even though in your test you're reading the same pot every time?

@DuncanC without the MUX it reads properly; Because you must select what channel of the MUX you want to read thru SPI. And now I am only reading one because I only want to read one pot to test if it works correctly and the when I have it working correctly I will add the other 31

What value (ohms) pots are you using?

@Gerben 10K ohms

Are you using Linear taper pots? Or audio/logarithmic taper pots?

@CrossRoads linear

Take a deep look into the library you are using to read the POT. Most HW and / or SW will take many readings & average them to remove the randomness and improve the accuracy of the ADC HW. It could be that your setup is so noisy that the SW is compensating by taking even more readings to average. Hats off the the SW developer who had the foresight to adapt the code to noisier situations. If true, and you think that too much automation, remember you are using the Arduino platform where the libraries are designed to make things simple by abstracting (hiding) the hardware details.

to read the pot I am using the analogRead() standart function, can you give me more information about what you say please, it is interesting to analyze

Remember that the libraries are re-written for each different processor.  What source code you look at depends on the processor.  The point of the libraries is to abstract the differences of each processor such that the Arduino code doesn't have to change or doesn't have to change much when ported to different platforms (processors).

Some things look odd:
Why do this every time? You only need to set these up one time in setup():
SPI.beginTransaction(SPISettings(30000000, MSBFIRST, SPI_MODE2));

Most 16 MHz Arduinos, including the Mega you appear to be using, won't do 3 MHz, choices are 8 MHz, 4,MHz, 2 MHz, 1 MHz  and 3 or 4 more slower speeds.
The chip seems to support higher speeds, 8 MHz should work:

fSCLK 30 MHz max SCLK Cycle Frequency

So run it faster to same on time.
Why take a 10-bit reading and shift it down to 7?
Serial.println(analogRead(A0) >> 3);

You could speed up the reads by doing an 8-bit read instead of 10-bit, and use a faster Serial speed, up to 115200, to send the results out.
Instead of digitalWrite() to control the slaveSelect pin, you could use direct port manipulation to toggle that pin.  You can write a 1 to the Input port to toggle the output bit. From the Atmega2560 datasheet:

Toggling the Pin
Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn. Note that the SBI
instruction can be used to toggle one single bit in a port.

You can modify beginT and endT
// test SPI slave n=1
    SPI.beginTransaction(1, SPISettings(30000000, MSBFIRST, SPI_MODE2));
    SPI.transfer(00001111);
    SPI.endTransaction(1);

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


text:
Prioritizing one sensor
I want to ask is there a possible code to prioritize a specific part of a code? So I'm doing this project where I want to utilize muscle sensor, servo, and a button on an app over Bluetooth. The problem is since all is running in void() loop, even though I am not using the muscle sensor I can't move the servo with the app, since it reads the muscle sensor first. So is there a possible code to make the muscle sensor stop for a period of time after the button is pressed on the app and the servo is moved?
Here is the code:
void loop()
 {
  if(Serial.available()>0)
   {
    char data = Serial.read();

      if (data == 'a')
       {
        myservo.write(15);
       }
  }

int value = analogRead(EMG_PIN);

 if(value > THRESHOLD)
  {
   myservo.write(15);
  }

  else{
       myservo.write(140);
      }

So the first code is a bluetooth code where the servo is controlled through a button on an app. The second one is a muscle sensor. As stated above the problem is it will always read the muscle sensor even though the button is pressed from the app.
#include <Servo.h>

 int increment = 0;

 Servo myservo;

 void setup() {

   myservo.attach(1);

 }

 void loop()
 {

   Serial.println(increment++);

   if (increment > 9);
    {

     if(Serial.available()>0)
      {
       char data = Serial.read();

       if (data == 'a')
       {
        myservo.write(15);
       }
 }

      else if (increment = 0);

      int value = analogRead(EMG_PIN);

      if(value > THRESHOLD)
       {
        myservo.write(15);
       }

     else{
       myservo.write(140);
      }
  }

Your question is too vague to be answerable. The answer is "Yes, there's a way." Provide your current loop code, and highlight the relevant sections where you read the muscle sensor, and where the servo code doesn't get called. It sounds to me like a simple logic problem with your code but we can't tell without seeing the code.

why do you need code to stop the muscle sensor? .... does it have a "stop" function? ....... why don't you simply read it only every10th iteration of loop()?

@DuncanC Ok guys I already edited my post, and putted in my code, i hope it will give you a better hindsight

@jsotola I'm new to this stuff, so I don't really know how to do it :), can you show me an example code from my code above, it would really help thx

@jsotola is it something like that, second code, im still new to thus so a bit confused

something like that .... it looks like to have mismatched braces {}  ..... your indentation levels are messed up so it is not clear just by looking at your code

Note that the line else if (increment = 0); had 3 fatal flaws:

(1) It should use ==, not = (= is an assignment, so it assigns 0 to increment and then the if statement always fails.

(2) you should never put a semicolon after an if statement. That results in if (condition) {do nothing} since a semicolon marks an empty statement.

(3) You are missing a brace after the if statement. Code like if (condition) statement is legal, but confusing and error-prone. That only executes that one statement if the if is true, and then falls through to the statement after the if. If your indentation is wrong, you might think the if statement will only execute ALL the indented code if the if statement is true, but that is not correct.

Ahh ill look into that thx a lot @DuncanC

You have to think of your program as having two distinc modes of
operation:

The "fixed servo" mode is entered when you press the button on the
app. In this mode the servo is kept at a fixed position. The mode
lasts for a predefined delay.
The normal (not fixed servo) mode is the default mode. In this mode
the servo is positioned according to the reading of the sensor.

So you need a boolean variable to remember whether the "fixed servo"
mode is active or not, and the code in loop() should take care of
providing the correct behavior depending on the mode, and updating that
variable when needed. For example:
void loop()
{
    static bool fixed = false;  // whether we are in "fixed servo" mode
    static uint32_t fixed_started;  // when the mode started
    uint32_t now = millis();

    // On button press, start "fixed servo" mode.
    if (Serial.available() && Serial.read() == 'a') {
        servo.write(SERVO_LEFT);
        fixed = true;
        fixed_started = now;
    }

    // Get out of "fixed" mode after some delay.
    if (fixed && now - fixed_started >= FIXED_DELAY) {
        fixed = false;
    }

    // If not in "fixed" mode, react to the sensor.
    if (!fixed) {
        if (analogRead(EMG_PIN) >= THRESHOLD) {
            servo.write(SERVO_LEFT);
        } else {
            servo.write(SERVO_RIGHT);
        }
    }
}

Ahh I see it worked perfectly thx Edgar

Well done, figuring out the OPs intent from that jumble of code.


text:
Motion detection alarm that calls back
I need help. I am making motion detector that calls you when sensor activates
and i have done the code for that, but the thing is i am beginner and i need to make it when it first time boots i send a message with the number that will be called when sensor activates
`
int LED1 = 12;
int GND1 = 13;
int LED2 = 8;
int GND2 = 9;
int pirOutput = 5;
void setup()
{
  Serial.begin(9600);
  pinMode(LED1, OUTPUT);
  pinMode(GND1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(GND2, OUTPUT);
  pinMode(pirOutput, INPUT);

  digitalWrite(pirOutput, LOW);
  digitalWrite(GND1, LOW);
  digitalWrite(GND2, LOW);
  digitalWrite(LED1, LOW);
  digitalWrite(LED2, LOW);
  delay(15000);
  digitalWrite(LED1, HIGH);

}
void loop()
{
  if (digitalRead(pirOutput) == HIGH)
  {
    digitalWrite(LED2, HIGH);
    Serial.println("OK");
    delay(1000);
    Serial.println("ATD+381xxxxxxxx;");
    delay(15000);
    Serial.println("ATH");
    digitalWrite(LED2, LOW);
    delay(1000);
  }
}

that is the code i found and it works fine for me

I that code is fine for you, what exactly is your Question?

what does this mean? i send a message with the number that will be called ..... where are you sending a message?


text:
Passing arrays, global arrays within functions, pointers, and declaring array sizes
I'm super confused right about now!
I've been working on project involving Xbees in API mode, and I need to send different arrays of bytes to the Xbee depending on which buttons I press. Mostly what I have is working fine, but I'm having a lot of issues with the following questions; I figured I'd summarize all my questions first, then further explain them with code examples.

Arduino requires arrays contain to a size. How can I declare byte data[] without a size?
Arrays sizes must be declared with a number, or a const integer. So how come I can declare byte packet[arraySize]; when arraySize is being passed the integer ledOn_len that isn't constant?
How can I create a global array within a function?

I've taken the liberty to condense my code for readability purposes. Everything you see is here is mirroring my issues with my Xbee code.
byte ledOn[] = { 0x7E, 0xAA, 0x1C, 0x3B }; // turn led on
byte ledOff[] = { 0x7E, 0xAB, 0x1D }; // turn led off

int ledOn_len; // to be used for the array size of ledOn[] NOT a constant
int ledOff_len; // to be used for the array size of ledOff[] NOT a constant

// this doesn't work, because the array length must be a constant
//int arrayLength = 4;
//byte rando[arrayLength];

// this works just fine, since arrayLength is now a constant
//const int arrayLength = 4;
//byte rando[arrayLength];

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

  // since using sizeof(data) inside of changeLed() doesn't
  // work (it returns with 2, which is the size of a pointer)
  // set them here, and pass them along.
  ledOn_len = sizeof(ledOn);
  ledOff_len = sizeof(ledOff);
}

void loop()
{
  changeLed(ledOn, ledOn_len);
  delay(1000);
  changeLed(ledOff, ledOff_len);
  delay(1000);
}

void sendToXbee()
{
  //Xbee.write(packet); // packet isn't global, this doesn't work
  // yes I know I didn't include any software serial in this demonstration
}

void changeLed(byte data[], int arraySize)
{
  byte packet[arraySize]; // how does this work???? Pass by value
  memcpy(packet, data, arraySize); // clone data to packet

  // this is all the Serial print code

}

1) I created the function void changeLed() to calculate the checksum (xbee crap). I need to pass it the array ledOn[] or ledOff[] for the checksum calculations to occur. So I simply added void changeLed(byte data[])  (and then void loop calls changeLed(ledOn) ) which works, but why?! Anywhere else if you declare an array without an array size it says you must provide one. Confusing to me, but it still works. . . kinda. When I serial print data[i] byte by byte, it perfectly displays each byte in ledOn[], which is what I'm passing it. But when I call sizeof(data) it says it's only 2 bytes. How can it contain the exact data of 4 bytes I give it while only being 2 bytes? Here is the serial monitor of it. The first line is the printout of data[], following the 4 bytes is the length which it claims is 2. The second line is the array of bytes packet[]. I set packet[] equal to data[] with this: memcpy(packet, data, arraySize);. Now you'll notice that the array size is correct. Interesting.
Update #1: It seems like this all has to do with pointers somehow. I guess data[] is just pointing to or referencing the array ledOn[], and using memcpy(packet, data, arraySize); is actually copying the array ledOn[] to the array packet[]?

2) I try to declare a random array (byte rando[]) using int arrayLength as the size. This does not work because the array size must be a constant. So I simply add const int arrayLength and that works. Great. So how am I able to do byte packet[arraySize];!? ArraySize is being passed ledOn_len which is not a constant, so how come that works?

3) I need to be able to use the array packet[] inside of another function void sendToXbee(). Packet[] will be my final array of bytes to send to the Xbee containing either the array ledOn[] or ledOff[] which are different array lengths. As is, I cannot use packet[] in void sendToXbee() because packet[] is local to void changeLed(). But here's the catch 22: I cannot declare packet[] in the setup making it  global, because I don't have a size for that array yet!! The size of that array must be calculated within void changeLed(), depending on which array I need to send to the Xbee, ledOn[] or ledOff[].
I know this is a lot but I'd appreciate the help! Thanks guys.

Arduino requires arrays contain to a size. How can I declare byte data[] without a size?

You can't. Pure and simple. The compiler can infer a size from a declaration time assignment.

Arrays sizes must be declared with a number, or a const integer. So how come I can declare byte packet[arraySize]; when arraySize is being passed the integer ledOn_len that isn't constant?

It is a feature of C99 which GCC have also included in C++.

How can I create a global array within a function?

Simple: you can't.*
Ok. Now we've to that out of the way, let's look at what you want to do and how you should do it.
First off, you have a number of arrays of data:
uint8_t ledOn[] = { 0x7E, 0xAA, 0x1C, 0x3B }; // turn led on
uint8_t ledOff[] = { 0x7E, 0xAB, 0x1D }; // turn led off

Those arrays have an associated length, which is the size of the array divided by the size of one array entry:
const int ledOn_len = sizeof(ledOn) / sizeof(ledOn[0]);
const int ledOff_len = sizeof(ledOff) / sizeof(ledOff[0]);

At the moment you're getting away with just using sizeof(ledOn) because sizeof(ledOn[0]) is 1. But if you ever do this with arrays of anything other than byte you will come unstuck unless you get into this habit.
Now, those arrays are just blocks of memory with a fixed size, in a fixed location.  That means that the arrays, as well as being arrays, are also pointers.  That is, they are in effect just variables that contain the address where the data for the array is stored.
So you pass the pointer to the array, along with the length of the array, to your function:
void changeLed(const uint8_t *data, int len) {
}

changeLed(ledOn, ledOn_len);

When you have done is pass the address of the array to the function, not the array.
Now you can do things with that array data using that address. What you can't do is change the data (because I've marked it const).
One of the things you can do, though, is just send it.  You know where the data is. You know how long it is. You know where you want to send it to.
So you just do:
void changeLed(const uint8_t *data, int len) {
    Xbee.write(data, len);
}

That is, write len bytes starting at the address pointed to by data.
There is no need to have variable size arrays. There is no need to have global packet buffers. There is no need to copy any data anywhere with memcpy(). Just pass the data and send it.
If you need to send more data than just the content of your array, then just send it.  For example you may have to (I don't know the XBee protocol) add a header and footer to the packet.
void changeLed(const uint8_t *data, int len) {
    Xbee.write(0x01);
    Xbee.write(0x02);
    Xbee.write(len & 0xFF);
    Xbee.write(data, len);
    uint8_t cs = 0;
    for (int i = 0; i < len; i++) {
        cs += data[i];
    }
    Xbee.write(cs);
}

Just because they're not together in the same write function doesn't mean that they aren't "together".  With serial communication, there is no such thing as "together". It's just one byte after another.

I need to be able to use the array packet[] inside of another function void sendToXbee(). Packet[] will be my final array of bytes to send to the Xbee containing either the array ledOn[] or ledOff[] which are different array lengths. As is, I cannot use packet[] in void sendToXbee() because packet[] is local to void changeLed(). But here's the catch 22: I cannot declare packet[] in the setup making it global, because I don't have a size for that array yet!! The size of that array must be calculated within void changeLed(), depending on which array I need to send to the Xbee, ledOn[] or ledOff[].

Why do you think you need to copy the data into a separate packet variable? You already have the data in a variable.
If you really want to do that, then just pass packet to the next function in the same way as you already pass your other arrays.

* Actually there are ways, using dynamic memory allocation, but I won't condone using that

Very helpful! There are a few things that come to mind however. Your second quote of mine says you can't, but the what I meant by I can is that the compiler accepts it, and it works. I was curious as to why the compiler says it's okay to do it like that and why it does work, even though it seems it shouldn't.

Ah, I misread that bit. If it's local then yes, it can be allocated by a variable (since C99 IIRC)

@HavocRC https://stackoverflow.com/questions/30694199/local-variable-length-array

When I say 'together' I'm referring to keeping all of the variables within an array. The reason being is I have to calculate the checksum (addition of all bytes, & it with 0xFF, then subtract that value from 0xFF). I wrote a function that calculates the checksum, based on the bytes within the array. If tried to do the checksum calculation outside of an array, it would be a nightmare. Based on the information you provided I think I have a great path forward to fixing this. Thank you very much!


text:
Pipe serial dump to SD card file
I am using the RFID module to read mifare NFC chips and the library has only methods to send the data to the serial monitor. I need them to be saved to an SD card file. I have been adding custom methods to the library files to return strings that I then write to the SD card but this is a pain; there must be a quicker way to simply pipe all the data automatically but I do not know how to do this in cpp.
Here is an example of the function to dump to serial, that needs to be piped to the file on the SD card.
void MFRC522::PICC_DumpDetailsToSerial(Uid *uid) {
    Serial.print(F("Card UID:"));
    for (byte i = 0; i < uid->size; i++) {
        if(uid->uidByte[i] < 0x10)
            Serial.print(F(" 0"));
        else
            Serial.print(F(" "));
        Serial.print(uid->uidByte[i], HEX);
    }
    Serial.println();

    // SAK
    Serial.print(F("Card SAK: "));
    if(uid->sak < 0x10)
        Serial.print(F("0"));
    Serial.println(uid->sak, HEX);

    // (suggested) PICC type
    PICC_Type piccType = PICC_GetType(uid->sak);
    Serial.print(F("PICC type: "));
    Serial.println(PICC_GetTypeName(piccType));
}

Thanks!

the arduino does not have an operating system, so there is no "pipe" as is in linux ....... maybe there is a way to redefine the Serial object

Have the MFRC522 objects remember where you want them to send the output
by adding a data member to the class like this:
private:
    Print &output;

This is a reference to a Print object, i.e. any object where you can
print() or println() to. This reference should be initialized in the
constructor, like this
MFRC522:MFRC522(...other arguments..., Print &my_output = Serial)
: ...other initializations..., output(my_output)
{
    ...constructor body...
}

Notice that, by default, the output is initialiazed as a reference to
Serial. Thus, unless you explicitly ask for the output to go
elsewhere, the class will behave as before.
Last step is to change, in the implementation of the class, every
reference to Serial by output. This is just a global find and
replace.
At this point, the MFRC522 class can be used exactly as before, and it
will behave identically. This means that every user of the library
should be able to use your modified version with no issues. I thus
encourage you to submit the changes to the original author, so that they
have a chance to be incorporated into the canonical version of the
library.
Now, if you want this debugging output to be sent elsewhere, just
provide the destination as the last argument of the constructor:
MFRC522 my_RFID_module(...other arguments..., my_SD_card_file);

As long as the destination is an instance of the Print virtual class
(basically anything you can print() to should be OK), it should work
as expected.


text:
millis() replace delay() question
// each "event" (LED) gets their own tracking variable
unsigned long previousMillisLED12=0;
unsigned long previousMillisLED13=0;

unsigned long previousMillisLED3=0;

// different intervals for each LED
int intervalLED12 = 500;
int intervalLED13 = 5000;

int intervalLED3 = 2000;

// each LED gets a state varaible
boolean LED13state = false;     // the LED will turn ON in the first iteration of loop()
boolean LED12state = false;     // need to seed the light to be OFF

void setup() {
   pinMode(13, OUTPUT);
   pinMode(12, OUTPUT);

   pinMode(3, OUTPUT);

}
void loop() {
   // get current time stamp
   // only need one for both if-statements
   unsigned long currentMillis = millis();

   // time to toggle LED on Pin 12?
   if ((unsigned long)(currentMillis - previousMillisLED12) >= intervalLED12) {
      LED12state = !LED12state;
      digitalWrite(12, LED12state);
      // save current time to pin 12's previousMillis
      previousMillisLED12 = currentMillis;
   }

// time to toggle LED on Pin 13?
  if ((unsigned long)(currentMillis - previousMillisLED13) >= intervalLED13) {
      LED13state = !LED13state;
      digitalWrite(13, LED13state);
      // save current time to pin 13's previousMillis
      previousMillisLED13 = currentMillis;
  }
}

My questions:

Didn't see the led12 and led13 have 10 times defferency, almost same intervals, why?
How can I use millis() as simple as delay?
Is that a must to use if?

The leds blink with different intervals. Have you connected the leds and resistors in the right way? The function millis can be used as a delay, but not in the same way. When a sketch with delay needs to be transformed to millis, then often a large part of the sketch has to be rewritten.

Note that currentMillis - previousMillisLED12 is an unsigned long. Explicitly casting it to unsigned long is redundant.

What do you mean by 3.?

@Jot Thank you, I just delete the delay(1000) and put 'if    ' section instead of.

@Edgar Bonet I'll change it.

@chrisl, I mean is this the only way to do like: " ' if' ((unsigned long)(currentMillis - previousMillisLED12) >= intervalLED12) {
LED12state = !LED12state; "

Yes, that is the only way. See also the blink-without-delay: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

Your Timing is working, you can test it with the Serial monitor. So your problem is at some other place. Using delay() is from my perspective not a good solution, you did it better the way you already made.
For testing your sketch I included the communication for the Serial Montior (I had to comment out the LED activation since this is working in a different way on my board, and I also made the intervalls Shorter to see better the effect within the test sketch). Here you find the necessary changes and the output of the Serial Monitor.
My recommendation is to look with a simple Sketch if you are able to switch on/off your LEDs sperately without Timing to come closer to your problem. I dont think it is the Timing/use of millis().
#include <M5Stack.h> // needed for my board

// each "event" (LED) gets their own tracking variable
unsigned long previousMillisLED12 = 0;
unsigned long previousMillisLED13 = 0;

unsigned long previousMillisLED3 = 0;

// different intervals for each LED
int intervalLED12 = 50;
int intervalLED13 = 500;

int intervalLED3 = 2000;

// each LED gets a state varaible
boolean LED13state = false;     // the LED will turn ON in the first iteration of loop()
boolean LED12state = false;     // need to seed the light to be OFF

void setup() {
  Serial.begin(9600);
  //  pinMode(13, OUTPUT);
  //  pinMode(12, OUTPUT);
  //  pinMode(3, OUTPUT);
}
void loop() {
  // get current time stamp
  // only need one for both if-statements
  unsigned long currentMillis = millis();

  // time to toggle LED on Pin 12?
  if ((unsigned long)(currentMillis - previousMillisLED12) >= intervalLED12) {
    LED12state = !LED12state;
    // digitalWrite(12, LED12state);
    // save current time to pin 12's previousMillis
    previousMillisLED12 = currentMillis;
  }

  // time to toggle LED on Pin 13?
  if ((unsigned long)(currentMillis - previousMillisLED13) >= intervalLED13) {
    LED13state = !LED13state;
    // digitalWrite(13, LED13state);
    // save current time to pin 13's previousMillis
    previousMillisLED13 = currentMillis;
  }
  Serial.print("LED12: ");
  Serial.print(LED12state);
  Serial.print("  LED13: ");
  Serial.println(LED13state);

}

Thank you RJPlog, I'll test it.


text:
How do you move motor car forward for set amount of time and turning left/right
Am new to Arduino, wanted to know how to give motor direction to move and the duration of those movements. Goal is to move forward for say 5 seconds, turn left, move for 0.5 seconds, turn right, move for 5 seconds.
void loop() {
  //turn on motor A
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  analogWrite(ENA, 100);
  //turn on motor B
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  analogWrite(ENB, 100);
  delay(1000);

  analogWrite(ENA, 100); //speed 0 - 255
  analogWrite(ENB, 100); //speed 0 - 255
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(5000);

  analogWrite(ENA, 100); //speed 0 - 255
  analogWrite(ENB, 100); //speed 0 - 255
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  delay(500);

  analogWrite(ENA, 100); //speed 0 - 255
  analogWrite(ENB, 100); //speed 0 - 255
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(500);

  analogWrite(ENA, 100); //speed 0 - 255
  analogWrite(ENB, 100); //speed 0 - 255
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(5000);

do you have a question about your program? .... it is unclear why you posted the program listing ........... your program looks vaguely familiar ..... you named  the output pins in1, in2 etc.  ..... that sort of thing sticks in memory

Are you following a specific tutorial? There are plenty of good ones available. Let us know what you have achieved so far. For example, have you got a motor connected and spinning? What code did you use for that? Please delete any non-applicable code and give us what you have done so far.


text:
How to modify current driver files in USB_Host_Shield2.0 on github for Arduino Mega ADK USB driver for Epson LQ-310 printer?
At the moment, I am engaged in a project in which I have to drive Epson LQ-310 printer with Arduino Mega ADK (USB Host). There is already a library  USB_Host_Shield_2.0 on Github which includes usb drivers for keyboard, flash drive etc. but not for a printer.
I am thinking to modify the current header files (adk.h and adk.cpp) based on Android drivers to suit for a printer. Do the things workout in this way?
Could anyone of you please suggest me the things to modify to achieve the required functionality?
Thank You

start here https://www.usb.org/sites/default/files/usbprint11a021811.pdf

and you will need this http://gimp-print.sourceforge.net/reference-html/c463.html#AEN474


text:
Create New Serial Class Inheriting from Stream
How should I inherit from Stream, for creating a new class MySerial able to be initialized from a Stream0 instance?.
The error so far is: "cannot declare variable 'mySerial' to be of abstract type 'MySerial'".
If I make a class MySerial not inheriting, but adding a property Stream, everything works fine, except the new call mechanism for the resend() function, created to accept Stream instances.
EDIT: This is the edited code. Current error is: "expected unqualified-id before '=' token".
MySerial.h

class MySerial:public Stream{
    private:
        int param;
    public:
        MySerial(){}; // OK
        MySerial(Stream &Serial0){MySerial=&Serial0} // Here is the question
        // Stream Implementation
        int available(){return available();}
        int read(){return read();}
        int peek(){return peek();}
        size_t write(uint8_t c){return write(c);}
        using Print::write;
};

MySerial.ino
#include <MySerial.h>
#include <SoftwareSerial.h>

SoftwareSerial swSerial(6,7);
MySerial mySerial(swSerial);

void setup(){}
void loop(){
    if (mySerial.available()){
        c=mySerial.read();
        resend(mySerial,c);
    }
}
// This function should accept any Stream: SoftwareSerial, MySerial, Serial...
void resend(Stream &Stream0, char c){
    Stream0.write(c);
}

The Stream class has pure virtual methods which must be implemented in derived not abstract class.
The pure virtual method from base class Print is:
virtual size_t write(uint8_t) = 0;

The pure virtual methods from Stream are:
virtual int available() = 0;
virtual int read() = 0;
virtual int peek() = 0;

additionally add in your class the line
using Print::write;

to pull in overloaded methods write(str) and write(buf, size) fromPrint
Here I have an example of a simple class derived from Stream.

EDIT: Most of your question seemed to focus on wrapping some Stream implementation. Now I see that you maybe want to enhance the SoftwareSerial class and add a new method in the inherited class. It is simple:
MySerial.h
#ifndef _MYSERIAL_H_
#define _MYSERIAL_H_

#include <SoftwareSerial.h>

class MySerial: public SoftwareSerial {
private:
  int param;

public:

  MySerial(uint8_t receivePin, uint8_t transmitPin) :
      SoftwareSerial(receivePin, transmitPin, false) {
    param = 0;
  }

  void resend(char c) {
    write(c);
  }
};
#endif

MySerial.ino
#include "MySerial.h"

MySerial mySerial(6, 7);

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

void loop() {
  if (mySerial.available()) {
    int c = mySerial.read();
    mySerial.resend(c);
  }
}

Thanks. I made the indicated changes. I am still troubled with the constructor declaration, for taking a Stream object as initial object.

Your answers are great just as the last time. I will study this code further.


text:
I am getting blocks on my lcd screen 16*2
When I have tried interfacing my 16*2 LCD with Arduino I am getting only the black coloured boxes on my screen. What might be the problem?
Is there any solution to that? Do I need to connect any additional physical device to avoid that situation?
product is here lcd display 16*2

Hello and welcome to arduino.stackexchange. Your problem is a common one and relates to the contrast settings. PIN3 of your LCD needs a potentiometer which will allow you to change the contrast.

it's very unusual for the lcd being faulty. since there is no pic that shows how you have connected the lcd i cannot say anything. however you can search "dronebot workshop lcd" on YouTube. Mr Bill had explained it very well he also shows how you can control the lcd by only four wires. go and see that video.

You should post a picture of the LCD, name the library you are using to interface it, and post your code that initializes it and attempts to send data to it.

There are two possible problems, and you haven't stated which it is.

A single row of blocks (just the top row)

This is caused by either bad communication (wrong wiring) or incorrect code. Basically, the display isn't being initialized properly by your code for whatever reason.

Two rows of blocks (the entire display full of blocks)

The display is being initialized properly, so both your code and wiring are correct.  However, the contrast setting of the display is wrong. You need to check the wiring for your contrast potentiometer and adjust as necessary.

+1 on the contrast comment.


text:
i am getting an error while working with esp8266
i got an error
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
An error occurred while uploading the sketch
can esp8266anyone rectify this

disconnect the esp8266 from RX/TX. it disturbs the upload

oh i got the solution for the above question
it might be because i used TX AND RX pins of the arduino. what i observed is as tx and rx pins are for serial communication pin during the process of uploading i have to leave that pins disconnected.arduino


text:
Not able to split string into 2 char
I am trying to split an incoming string into 2 integer values since I have to control 2 dc motors with it. The processor is node MCU and I get following error:-
Com Port Reading:-
WiFi connected
Received: "84+62"
"84+62"

Soft WDT reset

>>>stack>>>

ctx: cont
sp: 3ffffd90 end: 3fffffc0 offset: 01b0
3fffff40:  2b343822 00223236 3ffee70c 40204148
3fffff50:  3ffe85ee 3ffee6d8 3ffee70c 402043c5
3fffff60:  3ffe85dc 3ffee70c 3ffee6d8 402043c5
3fffff70:  3ffe85f0 3ffee69c 00000000 00000001
3fffff80:  00000000 40200038 3ffefca4 0000000f
3fffff90:  00000007 00000000 00000001 402048f9
3fffffa0:  3fffdad0 00000000 3ffee744 40204984
3fffffb0:  feefeffe feefeffe 3ffe851c 401009a5
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v951aeffa
~ld

Code:-
if (msg.length() > 0) {
        Serial.print("Received: "); Serial.println(msg);
        char charBuf[50];
        msg.toCharArray(charBuf, 50);
        Serial.println(charBuf);

        char left[3] = {};
        char right[3] = {};
        int n = 0;

        while (charBuf != 0) {
          for (int i = 0; i < strlen(charBuf); i ++) {
            if (charBuf[i] != '+') {
              left[n] += charBuf[i];
              n++;
            }
            else {
              n = 0;
              break;
            }
            right[n] += charBuf[i];
            n++;
          }
        }
        Serial.println("Left Motor: "); Serial.print(left);
        Serial.println("Right Motor: "); Serial.print(right);

    }

My desired result is following:-
Left Motor: 84
Right Motor: 62

So what changes I need to make?

your code loops in while (charBuf != 0) { until watchdog resets the MCU

Use strtok() to split your string.

can you show an example using strtok()

Here's an example sketch that uses strtok().
char charBuf[] = "\"84+62\"";

// Set array size to maximum number of integers you will receive.
uint16_t myArray[2];

void setup(){

  Serial.begin(9600);

  int counter = 0;
  char* pch = strtok(charBuf, "\"+");

  while(pch != NULL){
    myArray[counter] = atoi(pch);
    pch = strtok(NULL, "\"+");
    counter += 1;
  }

  // Print out the contents of the integer array.
  for(int i = 0; i < counter; i++){
    Serial.println(myArray[i]);
  }
}

void loop(){}

myArray[0] contains 84 and myArray[1] contains 62.

You get this memory leak because you overflow the variable right. This does not happen in the for loop itself even though this could be implemented more straight forward. But it's the while loop that doesn't come to an end (charBuf doesn't change and will not become 0) and in the second iteration n will be 1 initially (due to n++ at the end of the for loop). That causes the overflow at right[n] += charBuf[i];.
So: remove the while loop (and use strtok()).

"84+62"

The additional doublequote characters are part of your string and charBuf
    Serial.println(charBuf);  // Text with " and  +

    char* cpl = nullptr;
    char* cpr = nullptr;
    for (char* cp = charBuf; *cp != 0; cp++) {
        if (*cp != '"' && ! cpl )  cpl = cp;
        if (*cp == '"') *cp = 0;
        if (*cp == '+' ) {
          *cp = 0; // split
          cpr = cp+1;
        }
    }
    Serial.println("Left Motor: "); Serial.println(atoi(cpl));
    Serial.println("Right Motor: "); Serial.print(atoi(cpr));


text:
Help with code for pushbutton connected to adafruit motorshield v2
can anybody assist me with a code? I am using arduino uno with adafruit v2 motor shield stacked on top. I am using a pushbutton and one DC motor and I want the state of the push button to change after it has been pushed for a few seconds. That is I want the motor to stop running even though the push button is still pushed down.
Here is the code I'm using:
    /*
This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM
control

For use with the Adafruit Motor Shield v2
---->   http://www.adafruit.com/products/1438
*/

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);

// You can also make another motor on port M2
//Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2);

// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 4;

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Adafruit Motorshield v2 - DC Motor test!");

  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  // Set the speed to start, from 0 (off) to 255 (max speed)
  myMotor->setSpeed(150);
  myMotor->run(FORWARD);
  // turn on motor
  myMotor->run(RELEASE);

}

void loop() {
  uint8_t i;

    // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println(buttonState);
  delay(0);        // delay in between reads for stability

  if (buttonState==1){
     delay(1000);

  myMotor->run(FORWARD);
    myMotor->setSpeed(150);
    delay(1000);

 }

 else if (buttonState==0){
  myMotor->run(FORWARD);
    myMotor->setSpeed(0);

  }

}

stop thinking I want the state of the push button to change after it has been pushed for a few seconds ........ start thinking I want the state of a variable to change when the push button is pressed and I want the state of the variable to remain the same for a few seconds

You need to do various things:
You need to change your logic not to use delay. Search on "Arduino Blink Without Delay" to find examples of doing timed actions with millis() instead of using delay.
Then you need to adjust your logic to start running the motor when the user presses a button, and stop running the motor when either the user releases the button or enough time elapses.


text:
expected unqualified-id before 'if' if (!client.connected() && lastConnected)
#include <PulseSensorPlayground.h>
#include <Timer.h>
#include <SPI.h>
#include <Ethernet.h>

Timer t;
PulseSensorPlayground pulseSensor;

// Local Network Settings
byte mac[] = { 0xD4, 0x28, 0xB2, 0xFF, 0xA0, 0xA1 }; // Must be unique on local network
// ThingSpeak Settings
char thingSpeakAddress[] = "api.thingspeak.com";
String writeAPIKey = "UVGOLIA40B9YHKU8";
const int updateThingSpeakInterval = 16 * 1000; // Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval)
// Variable Setup
const int PulseWire = A0;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
const int LED13 = 13;          // The on-board Arduino LED, close to PIN 13.
int Threshold = 550;           //for heart rate sensor
float myTemp;
int myBPM;
String BPM;
String temp;
int error;
int panic;
int raw_myTemp;
float Voltage;
float tempC;

long lastConnectionTime = 0;
boolean lastConnected = false;
int failedCounter = 0;
// Initialize Arduino Ethernet Client
EthernetClient client;
void setup()
{
  // Start Serial for debugging on the Serial Monitor
  Serial.begin(9600);
  pulseSensor.analogInput(PulseWire);
  pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
  pulseSensor.setThreshold(Threshold);

  // Double-check the "pulseSensor" object was created and "began" seeing a signal.
  if (pulseSensor.begin()) {
    Serial.println("We created a pulseSensor Object !");  //This prints one time at Arduino power-up,  or on Arduino reset.
  }

  // Start Ethernet on Arduino
  void startEthernet();
}
void loop()
{
  // Read value from Analog Input Pin 0
  String analogPin0 = String(analogRead(A0), DEC);
  // Print Update Response to Serial Monitor
  if (client.available())
  {
    char c = client.read();
    Serial.print(c);
  }
  //temp---
  raw_myTemp = analogRead(A1);
  Voltage = (raw_myTemp / 1023.0) * 5000; // 5000 to get millivots.
  tempC = Voltage * 0.1;
  Serial.println(tempC);

  //Serial.print(temp);
  //Serial.print(" ");

  //-----BMP180-----------
  //
  int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".
  // "myBPM" hold this BPM value now.
  if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".

    Serial.println(myBPM);
    char buffer1[10];
    char buffer2[10];
    String BPM = dtostrf(myBPM, 4, 1, buffer1);
    String temp = dtostrf(tempC, 4, 1, buffer2);
    // Print the value inside of myBPM.
  }
}
//----------------
void panic_button() {
  panic = digitalRead(8);
  if (panic == HIGH) {
    Serial.println(panic);
  }
}
// Disconnect from ThingSpeak
if (!client.connected() && lastConnected)
{
  Serial.println("...disconnected");
  Serial.println();
  client.stop();
}
// Update ThingSpeak
if (!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval))
{
  updateThingSpeak("field1=" + BPM + "&field2=" + temp + "&field3=" + panic);
}
// Check if Arduino Ethernet needs to be restarted
if (failedCounter > 3 ) {
  startEthernet();
}
lastConnected = client.connected();
}
void updateThingSpeak(String tsData)
{
  if (client.connect(thingSpeakAddress, 80))
  {
    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: " + UVGOLIA40B9YHKU8 + "\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(tsData.length());
    client.print("\n\n");
    client.print(tsData);
    lastConnectionTime = millis();
    if (client.connected())
    {
      Serial.println("Connecting to ThingSpeak...");
      Serial.println();
      failedCounter = 0;
    }
    else
    {
      failedCounter++;
      Serial.println("Connection to ThingSpeak failed (" + String(failedCounter, DEC) + ")");
      Serial.println();
    }
  }
  else
  {
    failedCounter++;
    Serial.println("Connection to ThingSpeak Failed (" + String(failedCounter, DEC) + ")");
    Serial.println();
    lastConnectionTime = millis();
  }
}
void startEthernet()
{
  client.stop();
  Serial.println("Connecting Arduino to network...");
  Serial.println();
  delay(1000);
  // Connect to network amd obtain an IP address using DHCP
  if (Ethernet.begin(mac) == 0)
  {
    Serial.println("DHCP Failed, reset Arduino to try again");
    Serial.println();
  }
  else
  {
    Serial.println("Arduino connected to network using DHCP");
    Serial.println();
  }
  delay(1000);
}

You did not actually write a question!  Please edit

If you look at this fragment of your code:
void panic_button(){
  panic = digitalRead(8);
    if(panic == HIGH){
    Serial.println(panic);
    }
}
// Disconnect from ThingSpeak
if (!client.connected() && lastConnected)

You see that the function panic_button() stops at the last }, the next is a statement which is not part of a function.
I think the } should be removed, but your code is aligned quite badly, so:

First align all { and }
Indent each level with a tab or 2, 3 or 4 spaces
You will see a misalignment, add/remove a { (like above) or }.


text:
attachInterrupt() corrupting Serial buffer requiring Serial restart
I am working on a proof-of-concept ADC to "explode" what's inside of an ADC chip for teaching purposes.
Currently, I have a sketch that uses a push-button to act as a clock-pulse that counts up (1, 2, 3, 4, ...) for every positive edge using the attachInterrupt() function.
The sketch works great to view the data in the serial monitor.
I am pairing the Arduino (Teensy 3.2) with a Raspberry Pi configured to read data off the Serial line to a text box.
After a good bit of troubleshooting it appears that the attachInterrupt() function corrupts the Serial buffer with garbage for every interrupt. For instance, if I use
Serial1.flush();
Serial1.begin(115200);

immediately after the interrupt and then send out my data using Serial.println() I get my expected decimal value at my output. However, without these lines I just get unicode garbage at my Serial output. See full "fixed" sketch code below:
My question is: why is this happening? I should not need to restart Serial every iteration of the clock.
#define HWSERIAL Serial1

const int numBits = 12;             //Number of bits in ADC (resolution)
const int comparatorPin = 14;       //Pin number of comparator out
const int clockPin = 15;            //Pin number of external clock (square wave) input; expecting clock with 50% duty-cycle
volatile int comparatorState = 0;   //Is comparator high or low?
volatile bool clockState = 0;       //Is clock high or low?
volatile int masterCount = 0;       //Our master count
volatile bool isSameVal = false;    //Is the value of the master count the same value as last cycle?

int outVal = 0;

int masterBinCount[12];     //Array to store binary value of the master count
byte outputPins[12];        //Array to store the numbers associated with the output pin numbers
int maxValue = 0;           //Initialize max counter value to zero

void setup() {
  Serial.begin(115200);       //Begin Serial transmission
  HWSERIAL.begin(115200, SERIAL_8N1);
  HWSERIAL.flush();
  delay(2000);

  defineOutPins(outputPins);  //Assign pin numbers for output pins

  pinMode(14, INPUT);   //Comparator Pin
  pinMode(15, INPUT);   //Clock-in pin

  maxValue = pow(2, numBits);   //Set max counter value to max bit resolution. Ex. for 12 bits --> 4096
}

void loop() {
  attachInterrupt(clockPin, doOnClock, RISING);   //When clock is on a positive-edge execute doOnClock function

  HWSERIAL.flush();
  HWSERIAL.begin(115200);

  if(isSameVal == false) {    //If the master count is NOT the same as the last cycle
    convertDecToBin();        //Convert the master count (dec) to binary
    binaryToPins();           //Send the binary value (via digitalWrite) to output pins
  }
  else {
    //Do nothing
  }
  delay(1000);
}

void defineOutPins(byte pinNos[]) {   //Assign pin numbers to parallel binary out: Teensy 3.2 pin #0 --> #11
  for(byte i = 0; i < numBits; i++) {
    pinNos[i] = {i};      //Assign current pin this value
    pinMode(i, OUTPUT);   //Define pins as outputs
  }
}

void doOnClock() {
  comparatorState = digitalRead(comparatorPin);   //Check comparator state

  if(comparatorState >= 0.5) {            //Check if positive clock pulse
    if(masterCount == (maxValue - 1)) {   //Check if current count value is at "ceiling"
      //Do nothing
    }
    else {            //Else increment count up
      masterCount++;
    }
  }
  else if(comparatorState < 0.5) {    //Check if negative clock pulse
    if(masterCount == 0) {            //Check if current count value is at "floor"
      //Do nothing
    }
    else {
      masterCount--;    //Else decrment count down
    }
  }

  isSameVal = false;    //Set "finished" counting for this clock-pulse
}

void convertDecToBin() {
  for(int j = 0; j < numBits; j++) {
    int tempCnt = bitRead(masterCount, j);
    masterBinCount[numBits - (j+1)] = tempCnt;    //Populate the master binary count array in "reverse" order starting with the LSB at the highest array index
  }
}

void binaryToPins() {
  for(int e = 0; e < numBits; e++) {
    //digitalWrite(outputPins[e], masterBinCount[e]);   //Write our master binary value to output pins
    //Serial.print(masterBinCount[e]);                    //THIS LINE IS FOR TROUBLESHOOTING!!
  }
  isSameVal = true;       //Tell program we wrote the master count to the pins for this clock cycle

  outVal = masterCount;

  Serial.println(outVal);
  HWSERIAL.println(outVal);

  //Serial.print(" decimal: ");   //THIS LINE IS FOR TROUBLESHOOTING!!
  //Serial.print(masterCount);    //THIS LINE IS FOR TROUBLESHOOTING!!
  //Serial.println("");           //THIS LINE IS FOR TROUBLESHOOTING!!
}

not related to your problem .... the attachInterrupt() should be in setup()

I believe your issue is with initializing HWSERIAL.begin(115200); in void loop. I created this simple sketch to verify this. Firstly, I commented out the second initialization of Serial.begin, and you can see I was getting a perfect output to the serial monitor. Then I uncommented the line, re-uploaded the code to the Arduino, and you can see it didn't even make it through one print before it sent a bunch of garbled junk and effectively froze my serial port.
Remove HWSERIAL.begin(115200); from void loop and only set it in void setup.
Hope this helps!
void setup()
{
  Serial.begin(115200);
}

void loop()
{
  Serial.begin(115200);
  Serial.print("Test");
  Serial.print(" - ");
  Serial.println(millis());
}

Thank you! I think that sorted things out.


text:
what is this ets Jan 8 2013,rst cause:4, boot mode:(1,7)
i dont have any idea about this problem. can anyone help me how to fix this?
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
const char *ssid = "NUS";
const char *password = "s006";
int lo=16.3441;
int la=80.5243;
const char *host = "http://smshorizon.co.in";
void setup() {
   delay(1000);
   Serial.begin(115200);
   Serial.println("Start");
   WiFi.mode(WIFI_OFF);
   delay(1000);
   Serial.println("Status");
   WiFi.mode(WIFI_STA);
   Serial.println("Begin...");
   WiFi.begin(ssid, password);
   Serial.println("");
   Serial.print("Connecting");
   while (WiFi.status() != WL_CONNECTED) {
       delay(500);
       Serial.print(".");
    }
   Serial.println("");
   Serial.print("Connected to ");
   Serial.println(ssid);
   Serial.print("IP address: ");

   Serial.println(WiFi.localIP());
 }
 void loop() {

  }

Sometimes it shows boot mode(1,0)

Do some further debugging so you can tell us where this error occures. Remove theWiFi.mode() lines, those should not be necessary in your case. Another vague guess: add a delay in your loop, I'm not sure if the compiler will do anything dump when there is no loop

Something else: 163441 is not an int. But I don't think that's a problem. It simply doesn't make sense

the 1 indicates that you have io 15 LOW, io 2 HIGH and io 0 LOW. and the esp8266 starts in flashing mode. pull io 0 up to start the sketch

reset cause 4 is watchdog reset. your sketch stops so the watchdog resets it


text:
Rfid module on nodemcu
I am trying to connect a mfrc522 module with nodemcu. I have tried all tutorials available in youtube. Everytime it shows firmware version: 0x89 (unknown}.

Can you assume that no one else has tried all the tutorials on youtube, and post your code and how you have it hooked up in your particular situation?

What exactly did you do that resulted in the error to occur. And where does it show "firmware version: 0x89 (unknown}"

well, the "valid" versions of mfrc522 (at least according to the MFRC522 library) are 0x88 for the Fudan Semiconductor FM17522 clone, 0x90 for MFRC522 firmware 0.0, 0x91 for MFRC522 firmware 1.0 and 0x92 for MFRC522 firmware 2.0 - 0x89 is not known in that library, and therefore that library won't deal with it - use the PCD_DumpVersionToSerial to see if your device is supported

Please post an actual question. So what that the firmware version is 89?

My device has a rc522 chip manufactured by nxp. Pcd_dumpverisontoserial shows the version as 0x89. I have done some projects with both nodemcu and arduino. So i am sure about the connections.


text:
ESP8266 WiFiClient connection always returns 0
I am trying to use a NodeMCU as a station to connect to a webserver, however, the WiFiClient connect function always returns 0 for no reason. I am able to connect the NodeMCU to my home WiFi, but it just cannot connect to any server (either with IP address or with URL).
If anyone is interested, the following is the testing code (I did not include the libraries intentionally for the clearness of the code).
int status = WL_IDLE_STATUS;
IPAddress server(74,125,115,105);  // Google

// Initialize the client library
WiFiClient client;

void setup() {
  Serial.begin(9600);
  WiFi.mode(WIFI_STA);
  Serial.println("Connecting to AP specified during programming");
  WiFi.begin("mySSID", "myPassword");
  while (WiFi.status() != WL_CONNECTED) {delay(500); Serial.print("."); }
  Serial.print("\r\nWiFi connected IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println();
}

void loop() {
  Serial.println(client.connect(server,80));
}

I rolled back the question to original version answered by Jaromanda

i tried reaching the IP address in you code, using a web browser, without success ..... no response to ping either ............ please use a valid IP address in your code ...... update your post with corrected info

@JaromandaX, please undelete your answer


text:
Generate a ramp input with an Arduino Uno
Is there anyway to generate a ramp input from an Arduino Uno? A visual depiction of the pulse I am looking for is as follows:

With other microcontrollers, I was able to use their in-built DACs, however I am aware that the Arduino UNO doesn't have any? Is there a way using PWM or analogWrite to output these type of pulses? I'm new to Arduino programming, so I'm a bit unsure. However my next guess would be to use an R-2R ladder to output this type of pulse?

A resistor ladder is a good option. For example 4 pins for 16 steps. What frequency is the signal and how steep and how accurate should the ramp be? The Arduino Uno does not have a analog output. The function analogWrite is PWM (it should be called pwmWrite).

Yea, I was thinking on using an R2R ladder. The rise time should be really fast (around 150 microseconds), and then 50 microseconds of constant voltage. After that, it could drop to 0 instantly. Yea I was fearing that I might need to use an R2R ladder

The function digitalWrite on a arduino uno is 5 microseconds. It can be (a lot) faster when writing directly to output registers of the microcontroller. Together with the function delayMicroseconds and turning off interrupts, then it is possible. The default pwm frequency is 500Hz when using the arduino libraries, that is too slow.

@Jot ahhh, I see. I will try giving it a go. I'm actually generating this pulse to trigger muscles. Okay but instead of directly outputting to the registers, won't digitalWrite alone, also be able to accomplish this rise time?

No, that is very fast and there is no way to slow it down. The 5 microseconds is used to call the function, check if the pin is valid and find the register and bit for that pin: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring_digital.c#L138 Would a pullup resistor and capacitor and transistor be possible? The resistor and capacitor to rise slow, and the transistor to fall fast.

@Jot ahhh I hadn't considered that. Yes, I will definitely give these a try. Yea that is interesting. Would it be possible to show a circuit arrangement of what that type of circuit what look like?

A RC filter will create a slow slewrate.

simulate this circuit – Schematic created using CircuitLab
The circuit creates this signal:

A slow rising signal and a fast falling signal can be created with an extra transistor (the signal will be inverted).

simulate this circuit
For a linear rising and falling edge, a resistor network with a few digital pins is a simple solution. I think it can be created with an opamp circuit as well, but there are also special chips called "slew rate limiter".

This is so incredibly helpful! Thank you so much!

By "ramp", it seems that you mean a square wave with sloping rather than vertical edges between + and -.  Can you clarify the question further: do the sloping parts need to be linear?
Direct synthesis of the waveform could be done using the digital output ports and an R2R ladder, as suggested in the comments.  Each PWM timer output of the AVR can control output of 2 digital pins and definitely with a timing precision better than 1 microsecond.  If high voltage resolution is needed, this method may not be able to produce the result you want.
Other possible solutions:

The waveform as plotted in the original post looks like a truncated sine wave.  Such a waveform could be made by clipping a sine wave with an operational amplifier.  For the sine wave connect the Arduino to a DDS module such as AD9850/1.
Use an external digital-to-analog converter, e.g. MCP48x2
Use an Arduino Zero or other 32-bit microcontroller (e.g. ARM STM32).  These microcontrollers have a true analog output pin, but it's not bipolar.

Yes, it could be any. A sine wave or a sloping square wave. I will update the question. I will take a look at all the solutions that you suggested. Thank you for the help!


text:
several cameras share data lines
There are plenty of projects that connect an OmniVision camera, such as ov7670 , to an Arduino.
A good example would be:
https://www.scribd.com/document/356160003/Beginning-Arduino-Ov7670-Camera-Development
Now, let's say I want to connect 2 of those.
The problem with these cameras is that they require 17 IOs, which is a lot.
They are are:

1 power - cannot be shared
1 external clock (XCLK)
2 I2C lines (DATA, CLK)
8 data lines (D0:D7)
3 sync lines (PCLK, VSYNC, HREF)
2 control lines (RESET , PWD)

(Image attached below)
So, assuming I'm only powering 1 camera at a time, by giving each camera its own power IO, can all other IOs of both cameras be shared? at least some of them? (even if some intermediary simple HW is required)
Thanks!

Though question. Do you know how the datalines behave, when the camera is unpowered? Are they high impendance or may there be a parasite current? I assume you want to process the images in the Arduino, thus using the data lines.

And are you sure, that you want to do this with an UNO? Even a little bit of image processing is a big task for an UNO

No Image processing, only relay. I want to later port it to some Atmel SAMD, I use Arduino for prototyping, and want the SAMD have the same solution, if possible.

I don't know about electric behavior, I was hoping to get suggestions about this.

You might be able to use the Power-down mode pin and set the control register to tri-state data output to allow connecting multiple devices to the same data bus.


text:
How can I create an analog signal which is similar to PMT (Photo Multiplier Tube) pulse using analog write?
I have developed a circuit to process the PMT pulse output. For the testing, I need an artificial signal which is similar to the PMT pulse. How can I use AnalogWrite() to create such type of signal?

Do you mean you are looking for a way to generate a pulse as in the picture? The pulse is 40 ns. The Arduino AVR family of boards will have a hard time doing that!

Or do you mean a cascade of pulses with random width, duration and delay? All in the range of micro-seconds.

The PWM frequency of Arduinoboards is normally 490Hz, that means the shortest puls using analogWrite(PIN, 1) would last 8000ns.

You could write 200 NOPs @ 62.5ns each, assuming a 16MHz clock (minus overheads)

Short answer: You can't.
The Arduino can't do analog output at all, much less matching a specific analog waveform of ≈40ns duration.
PWM on the Arduino simulates constant analog voltages using square wave pulses of variable duty cycle. It has no support for creating analog waveforms of any type, much less ones with such a short duration.
EDIT
As mentioned in this thread: Generate a ramp input with an Arduino Uno
You could use a resistor ladder to create a roll-your-own DAC, and then use direct port register manipulation (not digitalWrite) to set the pins controlling your resistor ladder and get a crude approximation of your waveform.
Edit #2
There is no way you'll be able to generate nanosecond scale waveforms with a normal Arduino. It just isn't fast enough.

I doubt very much AVR-based Arduinos could do that.
SAMD21-based Arduinos do have a DAC, but their conversion time is about 2.85 μs. Their timer/counters can be clocked at 96 MHz, so about 10.5 ns/tick, but would yield a square pulse (that may or may not degenerate into what you need 8-).
Overall, I don't think an Arduino is the right tool for the job. Maybe something like the (very fast) Teensy 4.0 could do it, but I don't know much about those.


text:
Problem with SPI when using rf24 NRF24L01 transceiver with LED matrix MD_MAX72xx
I am currently using Arduino Mega to use a LED matrix and a NRF24L01 transceiver.
for LED matrix, I use MD_MAX72xx library. While for the transceiver I use the RF24 library.
I am already able to interface Arduino using two different LED matrix, and two matrix board is already using the SPI.
But when I try to add the RF24 library, and radio.begin(); the LED matrix isn't working properly anymore.
Here is my whole code:
#include <MD_MAX72xx.h>
#include <SPI.h>
#include <Servo.h>

#include <nRF24L01.h>
#include <RF24.h>

#define PRINT(s, v) { Serial.print(F(s)); Serial.print(v); }

#define BUF_SIZE      75  // text buffer size
#define CHAR_SPACING  3   // pixels between characters
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
#define MAX_DEVICES 4

const int buzzer_pin = 26;
const int servo_pin = 28;

unsigned long buzz_time;
unsigned long sys_time;
String buzz_type = "off";
int buzz_count = 0;
char charr[50];

Servo myservo;

RF24 radio(30, 32); // CE, CSN
const byte address[6] = "GLN71";
//const byte address[5] = {'R','x','A','A','A'};

struct LineDefinition
{
  MD_MAX72XX  mx;
  char    message[BUF_SIZE];
  boolean newMessageAvailable;    // true if new message arrived
};

struct LineDefinition  Line[] =
{
  { MD_MAX72XX(HARDWARE_TYPE, 51, 52, 53, MAX_DEVICES), "MAX", true },
  { MD_MAX72XX(HARDWARE_TYPE, 51, 52,  49, MAX_DEVICES), "MAX", true }
};

#define MAX_LINES   (sizeof(Line)/sizeof(LineDefinition))

void printText(uint8_t lineID, uint8_t modStart, uint8_t modEnd, char *pMsg)
// Print the text string to the LED matrix modules specified.
// Message area is padded with blank columns after printing.
{
  uint8_t   state = 0;
  uint8_t   curLen;
  uint16_t  showLen;
  uint8_t   cBuf[8];
  int16_t   col = ((modEnd + 1) * COL_SIZE) - 1;

  Line[lineID].mx.control(modStart, modEnd, MD_MAX72XX::UPDATE, MD_MAX72XX::OFF);

  do     // finite state machine to print the characters in the space available
  {
    switch(state)
    {
      case 0: // Load the next character from the font table
        // if we reached end of message, reset the message pointer
        if (*pMsg == '\0')
        {
          showLen = col - (modEnd * COL_SIZE);  // padding characters
          state = 2;
          break;
        }

        // retrieve the next character form the font file
        showLen = Line[lineID].mx.getChar(*pMsg++, sizeof(cBuf)/sizeof(cBuf[0]), cBuf);
        curLen = 0;
        state++;
        // !! deliberately fall through to next state to start displaying

      case 1: // display the next part of the character
        Line[lineID].mx.setColumn(col--, cBuf[curLen++]);

        // done with font character, now display the space between chars
        if (curLen == showLen)
        {
          showLen = CHAR_SPACING;
          state = 2;
        }
        break;

      case 2: // initialize state for displaying empty columns
        curLen = 0;
        state++;
        // fall through

      case 3: // display inter-character spacing or end of message padding (blank columns)
        Line[lineID].mx.setColumn(col--, 0);
        curLen++;
        if (curLen == showLen)
          state = 0;
        break;

      default:
        col = -1;   // this definitely ends the do loop
    }
  } while (col >= (modStart * COL_SIZE));

  Line[lineID].mx.control(modStart, modEnd, MD_MAX72XX::UPDATE, MD_MAX72XX::ON);
}

void buzz_start(){
    buzz_count = 5;
    buzz_time = millis();
}

void buzz_call(){
  if(buzz_count > 0){
    if(millis() >= buzz_time){
      if(buzz_type == "off"){
        tone(buzzer_pin, 1000);
        buzz_type = "on";
      }else{
        noTone(buzzer_pin);
        buzz_type = "off";
        buzz_count--;
      }
      buzz_time = millis() + 300;
    }
  }
}

void setup()
{
  Serial.begin(57600);
  pinMode(buzzer_pin, OUTPUT);

  myservo.attach(servo_pin);

  tone(buzzer_pin, 1000);
  Serial.println("BEGIN");

  for (uint8_t i=0; i<MAX_LINES; i++){
    Line[i].mx.begin();
  }

  radio.begin();
  radio.openReadingPipe(20, address);
  radio.setPALevel(RF24_250KBPS);
  radio.startListening();

  String charrr = "STOP";
  charrr.toCharArray(charr, 50);
  printText(1, 0, MAX_DEVICES-1, charr);

  myservo.write(90);
  delay(500);
  myservo.write(180);

  noTone(buzzer_pin);
  sys_time = millis();
}

int counter = 10;
int disp = 0;
void loop()
{
  String charrr = String(counter);
  charrr.toCharArray(charr, 50);
  printText(0, 0, MAX_DEVICES-1, charr);
  if(counter == 0){
    counter = 9;
    if(disp == 0){
     disp = 1;
     String charrr = "  GO";
     charrr.toCharArray(charr, 50);
     printText(1, 0, MAX_DEVICES-1, charr);
     myservo.write(90);
     buzz_start();
    }else{
     disp = 0;
     String charrr = "STOP";
     charrr.toCharArray(charr, 50);
     printText(1, 0, MAX_DEVICES-1, charr);
     buzz_start();
     myservo.write(180);
    }
  }
  if(millis() >= sys_time){
    counter--;
    sys_time = millis() + 1000;
  }

  buzz_call();

}

I think the problem here is not connection, but with the initalization of the RF24, and radio.begin();

I looked into the source code of the MD_MAX72XX library. The constructor with SPI pins starts software SPI.
Use the MD_MAX72XX::MD_MAX72XX(moduleType_t mod, uint8_t csPin, uint8_t numDevices): constructor to work with SPI hardware/library with all devices.
struct LineDefinition  Line[] =
{
  { MD_MAX72XX(HARDWARE_TYPE, 53, MAX_DEVICES), "MAX", true },
  { MD_MAX72XX(HARDWARE_TYPE, 49, MAX_DEVICES), "MAX", true }
};

Or if the MD_MAX72XX worked for you with software SPI, then use some other pins then hardware SPI pins to make hardware SPI free for the NRF24L01.
struct LineDefinition  Line[] =
{
  { MD_MAX72XX(HARDWARE_TYPE, SW_SPI_SI, SW_SPI_CLK, MAX1_CS, MAX_DEVICES), "MAX", true },
  { MD_MAX72XX(HARDWARE_TYPE, SW_SPI_SI, SW_SPI_CLK, MAX2_CS, MAX_DEVICES), "MAX", true }
};

are you suggesting that, to initialize the transciever (rf24), instead of radio.begin();.... I should use MD_MAX72XX::MD_MAX72XX(moduleType_t mod, uint8_t csPin, uint8_t numDevices): ?

Thanks! That did the trick. I changed the SI, and CLK. { MD_MAX72XX(HARDWARE_TYPE, 11, 8, 53, MAX_DEVICES), "MAX", true },   { MD_MAX72XX(HARDWARE_TYPE, 11, 8,  49, MAX_DEVICES), "MAX", true } Then the pins 50,51,52 are now used by the NRF24


text:
Arduino stuck when I disable Timer 2 Interrupt
#define TIM2_EN() (TIMSK2 = 0x02)
#define TIM2_DIS() (TIMSK2 = 0x00)

//HEART SENSOR
// Include Libraries
#include "Arduino.h"

class PulseSensor
{
public:
  static void begin(int pulsePin);

  static volatile int BPM;           // used to hold the pulse rate
  static volatile int Signal;        // holds the incoming raw data
  static volatile int IBI;           // holds the time between beats, must be seeded!
  static volatile boolean QS;        // becomes true when Arduoino finds a beat.
};

// Pin Definitions
#define HEARTPULSE_PIN_SIG  A0

// Global variables and defines

// object initialization
PulseSensor heartpulse;

volatile int rate[10];                        // array to hold last ten IBI values
volatile unsigned long sampleCounter = 0;     // used to determine pulse timing
volatile unsigned long lastBeatTime = 0;      // used to find IBI
volatile int P =512;                          // used to find peak in pulse wave, seeded
volatile int T = 512;                         // used to find trough in pulse wave, seeded
volatile int thresh = 512;                    // used to find instant moment of heart beat, seeded
volatile int amp = 100;                       // used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true;            // used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false;          // used to seed rate array so we startup with reasonable BPM
volatile boolean Pulse = false;               // true when pulse wave is high, false when it's low
volatile int pulsePin;

volatile int PulseSensor::IBI = 600;          // holds the time between beats, must be seeded!
volatile int PulseSensor::BPM;                // used to hold the pulse rate
volatile int PulseSensor::Signal;             // holds the incoming raw data
volatile boolean PulseSensor::QS = false;     // becomes true when Arduino finds a beat

void PulseSensor::begin(int pPin)
{
  pinMode(pulsePin, INPUT);
  pulsePin = pPin;

  // Initializes Timer1 to throw an interrupt every 2ms.
  TCCR1A = 0x00;
  TCCR1B = 0x0C;  // CTC (Compare match mode) and ClockIO/256
  OCR1A = 0x7C;   // 2 ms
  TIMSK1 = 0x02;
  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}

// THIS IS THE TIMER 1 INTERRUPT SERVICE ROUTINE.
// Timer 1 makes sure that we take a reading every 2 miliseconds
ISR(TIMER1_COMPA_vect)
{                         // triggered when Timer1 counts to 124
  cli();                                      // disable interrupts while we do this
  PulseSensor::Signal = analogRead(pulsePin);              // read the Pulse Sensor
  sampleCounter += 2;                         // keep track of the time in ms with this variable
  int N = sampleCounter - lastBeatTime;       // monitor the time since the last beat to avoid noise

  //  find the peak and trough of the pulse wave
  if(PulseSensor::Signal < thresh && N > (PulseSensor::IBI/5)*3){       // avoid dichrotic noise by waiting 3/5 of last IBI
    if (PulseSensor::Signal < T){                        // T is the trough
      T = PulseSensor::Signal;                         // keep track of lowest point in pulse wave
    }
  }

  if(PulseSensor::Signal > thresh && PulseSensor::Signal > P){          // thresh condition helps avoid noise
    P = PulseSensor::Signal;                             // P is the peak
  }                                        // keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
  // signal surges up in value every time there is a pulse
  if (N > 250){                                   // avoid high frequency noise
    if ( (PulseSensor::Signal > thresh) && (Pulse == false) && (N > (PulseSensor::IBI/5)*3) )
    {
      Pulse = true;                               // set the Pulse flag when we think there is a pulse
      PulseSensor::IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
      lastBeatTime = sampleCounter;               // keep track of time for next pulse

      if(secondBeat){                        // if this is the second beat, if secondBeat == TRUE
        secondBeat = false;                  // clear secondBeat flag
        for(int i=0; i<=9; i++){             // seed the running total to get a realisitic BPM at startup
          rate[i] = PulseSensor::IBI;
        }
      }

      if(firstBeat){                         // if it's the first time we found a beat, if firstBeat == TRUE
        firstBeat = false;                   // clear firstBeat flag
        secondBeat = true;                   // set the second beat flag
        sei();                               // enable interrupts again
        return;                              // IBI value is unreliable so discard it
      }

      // keep a running total of the last 10 IBI values
      word runningTotal = 0;                  // clear the runningTotal variable

      for(int i=0; i<=8; i++){                // shift data in the rate array
        rate[i] = rate[i+1];                  // and drop the oldest IBI value
        runningTotal += rate[i];              // add up the 9 oldest IBI values
      }

      rate[9] = PulseSensor::IBI;                          // add the latest IBI to the rate array
      runningTotal += rate[9];                // add the latest IBI to runningTotal
      runningTotal /= 10;                     // average the last 10 IBI values
      PulseSensor::BPM = 60000/runningTotal;               // how many beats can fit into a minute? that's BPM!
      PulseSensor::QS = true;                              // set Quantified Self flag
      // QS FLAG IS NOT CLEARED INSIDE THIS ISR
    }
  }

  if (PulseSensor::Signal < thresh && Pulse == true){   // when the values are going down, the beat is over
    Pulse = false;                         // reset the Pulse flag so we can do it again
    amp = P - T;                           // get amplitude of the pulse wave
    thresh = amp/2 + T;                    // set thresh at 50% of the amplitude
    P = thresh;                            // reset these for next time
    T = thresh;
  }

  if (N > 2500){                           // if 2.5 seconds go by without a beat
    thresh = 512;                          // set thresh default
    P = 512;                               // set P default
    T = 512;                               // set T default
    lastBeatTime = sampleCounter;          // bring the lastBeatTime up to date
    firstBeat = true;                      // set these to avoid noise
    secondBeat = false;                    // when we get the heartbeat back
  }

  sei();                                   // enable interrupts when youre done!
} // end isr

//LDR SENSOR
int sensorPin = A1; // select the input pin for LDR
int sensorValue = 0; // variable to store the value coming from the sensor

//LCD
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16 chars and 2 line display

//DHT
#include "dht.h"
int dht_apin = 2;
dht DHT;

//HEART RATE SENSOR
unsigned long current_time,start_time=0;
int BPM,Interval;

void setup(){

  Serial.begin(115200);
  heartpulse.begin(HEARTPULSE_PIN_SIG);
  delay(1500);
  lcd.init();          // initialize the lcd
  lcd.backlight();
  lcd.print("  INITIALISING");
  delay(2500);
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print(" CHECKING HEART");
  lcd.setCursor(0,1);
  lcd.print(" RATE NOW......");
  delay(2000);
  lcd.clear();
}

void loop() {

  current_time = millis();
  if ( current_time-start_time < 30000 )  {
    BPM = heartpulse.BPM;
    Interval = heartpulse.IBI;
    lcd.print(" SYNCHRONIZING  ");
    lcd.setCursor(0,1);
    lcd.print("   BEATS:");
    lcd.print(BPM);
    lcd.clear();
  } else  {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("BEATS PER MINUTE");
    lcd.setCursor(6,1);
    lcd.print(BPM);
    Serial.print(BPM);
    Serial.println('b');
    delay(4000);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print(" BEAT INTERVAL  ");
    lcd.setCursor(7,1);
    lcd.print(Interval);
    Serial.print(Interval);
    Serial.println('p');
    delay(4000);
    TIM2_DIS(); //Enable TIMER2 Interrupt
    DHT.read11(dht_apin);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("    HUMIDITY    ");
    lcd.setCursor(6,1);
    lcd.print(DHT.humidity);
    lcd.print("%");
    Serial.print(DHT.humidity);
    Serial.println('h');
    delay(4000);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("  TEMPERATURE  ");
    lcd.setCursor(5,1);
    lcd.print(DHT.temperature);
    lcd.print("C");
    Serial.print(DHT.temperature);
    Serial.println('t');
    TIM2_EN(); //Disable TIMER2 Interrupt
    delay(4000);
    sensorValue = analogRead(sensorPin); // read the value from the sensor
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("LIGHT INTENSITY");
    lcd.setCursor(7,1);
    lcd.print(sensorValue);
    Serial.print(sensorValue);
    Serial.println('l');
    delay(4000);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print(" CHECKING HEART");
    lcd.setCursor(0,1);
    lcd.print(" RATE NOW......");
    delay(2000);
    lcd.clear();
    start_time = millis();
  }
}

I am trying to run LDR,PULSE AND DHT11 sensor together. DHT11 was not giving out readings along with pulse sensor before so I searched stack exchange and found out this solution.

DHT11 and Pulse sensor incompatibility?

But now the problem is Arduino gets stuck at the line when I disable timer 2 interupt -
TIM2_EN(); //Disable TIMER2 Interrupt

Any solution?

are you sure that TIM2_EN() disables the interrupt? ......  what does TIM2_DIS() do?

I came up with this idea from here.  https://arduino.stackexchange.com/questions/21489/dht11-and-pulse-sensor-incompatibility?noredirect=1&lq=1 The code given in this works with this solution but my code is stuck and it is not even reading values from DHT

If i remove this line the code isn't stuck anymore- TIM2_EN(); //Disable TIMER2 Interrupt....But still Arduino is not able to read values from DHT11.

I do not know, can you explain in detail.

why would an interrupt enable macro be called TIM2_DIS()? ..... why would the interrupt disable macro be called TIM2_EN()?  ....... perhaps you are turning on the interrupt and it causes the program to hang, so the problem may actually be in the ISR

From Github I got this - TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A. What can I do to read values from DHT11 and pulse sensor in the same program?

look at the very first line of your sketch ..... that confirms that you are enabling the interrupt when you thought that you were disabling it ............... now your focus should be on the ISR() to figure out which part is causing the problem ..... perhaps the ISR is too long         ............... also quit asking What can I do to read values from DHT11 and pulse sensor in the same program? and start asking what is causing the failure?

Got the solution, I was accidentally enabling and disabling timer 2 interrupt when actually I was using timer 1 in my program. Now first I am preventing timer 1 interrupts with TIMSK1 = 0 before reading DHT and again enabling timer 1 with TIMSK1 = 0x02 . Thanks #jsotola for telling me to find the failure ! Anyone wants to add anything about interupts ?


text:
HC-SR04 Echo Pin Fails To Go Low After Trigger Pulse
I have implemented an HC-SR04 distance sensor using an Arduino.  After power up, the sensor operates well when objects are within range of the sensor.  However, if the distance to be measured exceeds the maximum (about 15 feet) distance, the sensor times out (which is what I expect).  However, after a time-out and with the distance between the object and the sensor in range, the Echo pin fails to be set low after a trigger pulse is generated.  The only way to fix this condition is to power down the sensor and power it back up again.  (I have verified the state of the Echo pin by using an oscilloscope.)

Can you post your code?  I might have one kicking around to try this with.   I checked out a basic HC-SR04 hookup guide (https://dronebotworkshop.com/hc-sr04-ultrasonic-distance-sensor-arduino/) and it didn't mention this failure mode.  I'm wondering if the sensor is wonky.   Can you try their code, and see if you get the same effect?

After many hours of research, I discovered that the problem is related to the fact that there is (apparently) a well-known bug in the HC-SR04 which is a Chinese clone of a Devantech SRF04.  I replaced the HC-SR04 with an SRF04 and the problem was solved.  Now, the ECHO pin always goes low after a trigger and after a time-out (i.e. the object is beyond the maximum measurement distance).


text:
Flame sensor and MQ2 sensor not working with Esp8266?
When ever flame is detected sms will be send this is what i am doing,but the  flame and smoke sensor works awesome when they are tested seperately(Without Esp8266) when they are integrated with Esp8266 they are not at all responding to the flame or smoke . I have tested flame Sensor with serial monitor the values are 150,148,147,......
When it is tested without Esp8266 it has given 1000,996.....(Without Flame)
52,64,38.....(With Flame )

Flame sensor Connections:
VCC : 5V
GND : GND
D0 : 7`
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

const char *ssid = "NUS_006";
const char *password = "shankar006";
int flame=7;
void setup() {
    delay(1000);
    pinMode(flame,INPUT);
    Serial.begin(115200);
    WiFi.mode(WIFI_OFF);
    delay(1000);
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    Serial.println("");
    Serial.print("Connecting");
    while (WiFi.status() != WL_CONNECTED) {
           delay(500);
           Serial.print(".");
    }
    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
}

void loop()
{
  Serial.print("Flame= ");
  Serial.println(digitalRead(flame));
  delay(3000);
}

your sketch is for the esp8266. you have an esp-01 module like on the picture? you wired the sensors to Uno and expect that the esp8266 sketch will read them by some magic?

thanks for responding so what should i do to read the sensor values?-Juraj

do you have an esp-01 module? then you can't connect sensors to it and you must work with sensors in Uno. put some firmware into esp-01 and use it as WiFi adapter. (or create your own 'firmware')


text:
Initializing variables of a function
By playing with some examples I found the following construct:
void Show(int nav = 0) // -1 top, 1 bottom
and I wondered what effect it has to initialize the handover parameters in the function declarations, I never noticed such an construct consciously.
So I made a small demo:
#include <M5Stack.h> //necessary for my board
  int a;
  int b;
  int c;

int addFunction(int x = 3, int y = 3){
  int result;
  result = x + y;
  return result;
}

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

  // testcase 1
  a = 1;
  b = 2;
  c = addFunction(a, b);
  Serial.println("testcase 1:");
  Serial.println((String)a + " + " + b + " = " + c);

   // testcase 2
  a = 1;
  b = 2;
  c = addFunction();
  Serial.println("testcase 2:");
  Serial.println((String)a + " + " + b + " = " + c);

   // testcase 3
  a = 1;
  b = 2;
  c = addFunction(a);
  Serial.println("testcase 3:");
  Serial.println((String)a + " + " + b + " = " + c);
}

void loop() {
}

The output was:

So I learnd:

if you hand over parameters, the initialization is ignored, if you call the function without handing over paramters, the functions works with the init values.
if you handover only one parameter it will be assigned to the first in the declaration.

Question:
Is there a syntax possible to only call the function with the second parameter, so that for the first paramter the intialized value of the declaration is used? Spoken for this example with a = 1, b = 2 you only handover b and the expected result would be 5.

Should a single parameter always be for the second parameter (add a overloaded function) or do you want to choose for which parameter?

It is just a general question to understand the syntax.  So I would be interested in an answer of how to do it in general, which means also with more parameters and the possiblity to choose any parameter depending on the purpose (m out of n)

An overloaded function is one option to be able to accept different number of parameters. A pointer can be made nullptr (or NULL) and in the code you could check for nullptr. There must be other options as well.

@Jot tanks for the hint.  I had a look into that, I guess this is for my not working, since x and y are of the same type. I will check if I get it working, maybe with different types.

This is (unfortunately) not an Arduino question. It is actually about the syntax of C++ which is a rather complex language.
The mechanism you have discovered is called default arguments. The function prototype or definition may contain the default values of the arguments. As this is a list the default values are restricted from right to left. It is not possible to use a default parameter for argument to the left of a given argument. The order is strictly right to left.
f(int x = 0, int y = 1, int z = 2)

f(1,2,3) binds x = 1, y = 2, z = 3
f(1,2) equals f(1,2,2) binds x = 1, y = 2, z = 2
f(1) equals f(1,1,2) binds x = 1, y = 1, z = 2
f() equals f(0,1,2) binds x = 0, y = 1, z = 2

There is a syntax for struct initialization (aka aggregate initialization) in C++ that allows naming of struct field values. This type of naming is not allowed for function calls.
Please read https://en.cppreference.com/w/cpp/language/default_arguments, https://en.cppreference.com/w/cpp/language/aggregate_initialization and https://en.cppreference.com/w/cpp/utility/functional/bind for more details. And a good C++ book.
There are languages that allow default arguments and named parameters e.g. C#, Python, Ruby and Smalltalk. Please see https://en.wikipedia.org/wiki/Named_parameter.
Cheers!
(Update)
Below is a rewrite of @VE7JRO Add function class using cast operator to perform the evaluation:
class Add
{
public:
  Add(int x, int y) : m_x(x), m_y(y) {}
  operator int() { return m_x + m_y; }
  void x(int x) { m_x = x; }
  void y(int y) { m_y = y; }
  int print(Print& outp) {
    int res;
    res = outp.print(F("Add(x="));
    res += outp.print(m_x);
    res += outp.print(F(",y="));
    res += outp.print(m_y);
    res += outp.print(F(")"));
    return res;
  }
private:
  int m_x, m_y;
};

Add func(1,2);

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

  func.print(Serial);
  Serial.print(F("="));
  Serial.println(func);

  func.x(12);
  func.print(Serial);
  Serial.print(F("="));
  Serial.println(func);

  func.y(13);
  func.print(Serial);
  Serial.print(F("="));
  Serial.println(func);
}

void loop() {
}

Good explanation and material for further Investigation, thanks also for the extension of @VE7JRO, adds some more interesting details for me. (after I checked that you are using a different baud rate ;-))

Missed the baud rate difference. Changed that to avoid confusion, debugging, etc, between the sketches.

BW: If the member data is made public the syntax func.x = 12 would be allows (after removing the prefix m_).

If your function is inside a class, you can set either variable, both variables or use the defaults.
class Add{

    int a, b;

  public:

    Add(): a(1), b(2){}

    int AddTwoIntegers(){
      return a + b;
    }

    void SetInt1(int int1){
      a = int1;
    }

    void SetInt2(int int2){
      b = int2;
    }

};

Add Test1;

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

  Serial.print("Test default values = ");
  Serial.println(Test1.AddTwoIntegers());

  Test1.SetInt2(4);
  Serial.print("Set b = 4 then add to a = ");
  Serial.println(Test1.AddTwoIntegers());
}

void loop(){}

got it, thanks for the example, helped me a lot in understandig while trying it out


text:
20x4 lcd display problems
I was recently experimenting with 20x4 lcd display with my Arduino Mega board. The connections which I followed are shown in the picture attached. I am very much sure about the connections and code written in the Arduino IDE. Everything is compiled and uploaded properly on my board. However the problem I found is the 20x4 lcd display only shows two alternate block lines and nothing else! To resolve this I tried following things:

I made sure multiple times the hard wire connections between Arduino and display and found all are as per requirement.
I made sure the proper coding with initialization.
I tried changing the value of 10KOhm pot in order to control the contrast setting of lcd.
I made sure about connecting the R/W pin of lcd to ground.
I tried replacing the lcd display with another same unit.

With above troubleshooting the problem still persists. Can anybody will suggest what could be the issue?
Suggestions are highly appreciated!
Thanks and regards,
VK

Two rows of blocks on a 20x4 is the same as 1 row of blocks on a 16x2. It's not initializing the screen. Either your code is wrong or the wiring between the Arduino and the screen is wrong (i.e., it has nothing to do with contrast).

I am very much sure about the connections and code written in the Arduino IDE. -- that cannot be the case. One of those two is wrong. Your wiring looks fine (from what you showed us), so it must be your code that is wrong.

Try wiggling the wires in the breadboard. Breadboard sometimes don't make a good connection with the wire. Could you post an image of your setup, and the code you uploaded? As you've already done everything I would normally suggest.


text:
Multiple definitions of "xxxx"
I really need your help. I use VisualStudio and PlatformIo I still get this error:

Linking .pioenvs\esp12e\firmware.elf
  .pioenvs\esp12e\src\main.cpp.o:(.data.DebugX+0x0): multiple definition of `DebugX'
  .pioenvs\esp12e\src\customFunctions.cpp.o:(.data.DebugX+0x0): first defined here
  collect2.exe: error: ld returned 1 exit status
  *** [.pioenvs\esp12e\firmware.elf] Error 1

I use header guards in my file, so I do not understand why is this part of code redeclared. I had to miss some elementary in cpp programming but I still can't get it to work.
Copy of my project:
https://bitbucket.org/fires/programingtesting/src/master/ESP8266/cpp/RedefinedError/
main.cpp
    #include <Arduino.h>;
    #include "../include/defines.h"
    //#include "../include/customFunctions.h"
    // Time
    uint32_t mTimeToSec = 0;
    uint32_t mTimeSeconds = 0;
    void setup() {
    etc. etc. etc.

customFunction.h
    #pragma once
    #ifndef CUSTOMFUNCTIONS_H
    #define CUSTOMFUNCTIONS_H
    void connectWiFi();
    void initializeOTA();
    #endif

defines.h
    #pragma once
    #ifndef DEFINES_H
    #define DEFINES_H
    #include <jled.h>
    #define BowlingLed 5
    #define StatekLed 4
    int DebugX = 1;
    #endif

Thanks for the help, I read many articles and many issues but I still do not understand why DebugX is redefined if it is in header guard.

In the file defines.h, you declare an integer DebugX. It is not a good idea to declare an integer in a *.h file. The compiler somehow sees two declarations of DebugX. There are no strange characters and there is no typo error. It works in the arduino ide without the pragma. Perhaps the pragma works against the header guard for that specific ide.

Included files are included before compilation, really replacing the #include with the content of the file.
If you write int DebugX = 1; you define a variable. And it is defined in every source file which includes it. Then the linker finds it in more then one unit and ends with "multiple definitions" error.
The variable must be defined only in one compilation unit (.c, .cpp). For example in your case customFunctions.cpp. To make it available in other source files put extern int DebugX; into the .h file.