text:
LCD displays an "A" instead of 0
I am trying to make a timer that has a accuracy up to 1 tenth of a second. However when it is suppose to print "0", it will print an "A". For example, when printing "10", it will print "1A".
This program only lasts up to seconds. Any suggestion is highly appreciated, thank you!
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
unsigned long time2 = 0;
int x = 0;
int a = 0;
int b = 0;
void setup() {
  lcd.begin(16,2);
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.print("00:00:00:0      ");
  Serial.begin(9600);
}

void loop() {
  unsigned long time1;
  time1 = millis();
  if (time1 - time2 > 100){
    time2 = time1;
    lcd.setCursor (9,0);
    x=x+1;
    lcd.print(x," ");
  }
  if (x>=10){
    x=0;
    a=a+1;
    lcd.setCursor(7,0);
    lcd.print(a,":");
  }
  if (a>=10){
    a=0;
    b=b+1;
    lcd.setCursor(6,0);
    lcd.print(b+a);
  }
}

Hint: Check and correct the statement lcd.print(a,":");

https://www.arduino.cc/reference/en/language/functions/communication/serial/print/

Here is my Suggestion: In cases a clear answer could not be seen, you have to remove any weaknesses step by step to further encircle the problem. Since there is now answer for more than a month, I assume this as an appropriate proceeding.
One weakness I see in your coding is, that you are counting your values x, a, b, up to ten and you are printing them bevor reseting them to Zero, so your are printing 'x' even if it is ten. If for any reason in the further handling your display shows HEX values, you will end up displaying an 'A'. Change your Code so that values > 9 are not printed out, than this weakness will be removed.


text:
Connect SD card to Arduino with or without a level shifter
I have some audio files in an SD card and I want to play them using Arduino, thus connect the SD card to the Arduino. Since the transfer of the data will be from the SD card (+3.3V) to the Arduino (+5.0V) and not vice versa, is a level shifter necessary?

You can't use SD card without level conversion from 5 V to 3.3 V. Clock and CS line are driven by the master, and the master must request over MOSI the data to read.

.... your answer should be yes, to match the rest of your answer

i have a cheap generic chinese off-brand sd Card module and it does not even work if i do connect vcc to 3v3 so i use it with 5v. and i do not bother to add a Level shifter on the bus lines. and writing text to a file on the sd Card does work like a charm this way. so i would say no you not neccesarily Need the Level shifter but feel free to add it anyway and see if it works this way too.

this is funny, do you have many microSD cards?

less than a handfull -- and they are still working...

but there may be different variants of sd Card modules out in the wild...

source: Stack Exchange

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

sort: votes


text:
Audio Signal to LED Lights Code Speed Improvement
I wrote this code that inputs audio from a jack (DC offset at 2.5V), performs the fft on a portion of the data, and then outputs a signal to an LED light strip dependent upon which frequency has the highest magnitude. It works but it would be nice if it was faster. Can anyone help out?
#include <arduinoFFT.h>
#include <FastLED.h>

arduinoFFT FFT = arduinoFFT();

const uint16_t samples = 128; //This value MUST ALWAYS be a power of 2
const double samplingFrequency = 16000;
double vReal[samples];
double vImag[samples];

int freqBounds[] = {0,300,500,800,2000,8000};

int colorValue = 0;
int sensorValue = 0;

#define SCL_INDEX 0x00
#define SCL_TIME 0x01
#define SCL_FREQUENCY 0x02
#define SCL_PLOT 0x03

#define LED_PIN   7
#define NUM_LEDS  5

CRGB leds[NUM_LEDS];

void setup()
{
  Serial.begin(115200);
  pinMode(A0, INPUT);
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
  for(int i = 0; i < NUM_LEDS ; i++) {
      leds[i] = CRGB(0,0,0);
  }
  FastLED.show();
}

void loop()
{

  for (uint16_t i = 0; i<samples; i++){
    vReal[i] = int8_t(analogRead(A0));
    vImag[i] = 0.0;
    delay(1/samplingFrequency);
  }

  FFT.Windowing(vReal, samples, FFT_WIN_TYP_HAMMING, FFT_FORWARD);  /* Weigh data */
  FFT.Compute(vReal, vImag, samples, FFT_FORWARD); /* Compute FFT */
  FFT.ComplexToMagnitude(vReal, vImag, samples); /* Compute magnitudes */
  double x;
  double v;
  FFT.MajorPeak(vReal, samples, samplingFrequency, &x, &v);

  if (v>300){

    if (x>=freqBounds[0] && x<freqBounds[1]){
      Serial.print("BASE ");
      colorValue = (x - freqBounds[0]) * 255 / (freqBounds[1] - freqBounds[0]);
      leds[0] = CRGB(0,colorValue,255);
    }
    if (x>=freqBounds[1] && x<freqBounds[2]){
      Serial.print("TWO  ");
      colorValue = (x - freqBounds[1]) * 255 / (freqBounds[2] - freqBounds[1]);
      leds[0] = CRGB(0,255,255-colorValue);
    }
    if (x>=freqBounds[2] && x<freqBounds[3]){
      Serial.print("MID  ");
      colorValue = (x - freqBounds[2]) * 255 / (freqBounds[3] - freqBounds[2]);
      leds[0] = CRGB(colorValue,255,0);
    }
    if (x>=freqBounds[3] && x<freqBounds[4]){
      Serial.print("FOUR ");
      colorValue = (x - freqBounds[3]) * 255 / (freqBounds[4] - freqBounds[3]);
      leds[0] = CRGB(255,255-colorValue,0);
    }
    if (x>=freqBounds[4] && x<=freqBounds[5]){
      Serial.print("HIGH ");
      colorValue = (x - freqBounds[4]) * 255 / (freqBounds[5] - freqBounds[4]);
      leds[0] = CRGB(255,0,colorValue);
    }

    Serial.print(x,6);
    Serial.print(", ");
    Serial.println(v, 6);
  } else {
    leds[0] = CRGB(0,0,0);
  }
  for(int i = (NUM_LEDS - 1); i > 0 ; i--) {
      leds[i] = leds[i-1];
  }
  FastLED.show();
}

the answer to your question is yes ..... is that really all you want to ask?   ..............  btw: you can remove the serialPrint() calls to speed up the code

use a faster MCU

Does the code work as it is? The delay near the top looks wrong to me - it will always delay(0). Anyway, how fast does it currently run, how fast do you need it to run, and which parts of the process take the most time?

Ad some code that prints how much micros each part of your code uses. Something tells me that the FFT calculations will take 90% of the loop time, and there is no easy way of optimizing that. You can always use electronic circuits instead of digital MCU logic to calculate the FT at half of speed of light. I found a nice source here http://sound.whsites.net/project136.htm

Use an integer fft algorithm instead of a floating point one.

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


text:
How to use millis instead of delay on Arduino for independent time intervals for two output pins
I wanted to use millis for the code below but stuck in between . can anyone help to change the given code to millis? Code here:
    void set(){
    digitalWrite(on, HIGH);   // turn the motor on (HIGH is the voltage level)
  delay(1500);
  digitalWrite(on, LOW);
  delay(ont);               //waits for given time
  digitalWrite(off, HIGH );    // stop the motor
  delay(500);
  digitalWrite(off, LOW );
  delay(offt);                  //wait for different

See https://www.arduino.cc/en/tutorial/BlinkWithoutDelay I see four different things. Use a counter from 0...3 and adjust the interval for each of the four situations. Can you give that a try and show a working sketch (so we can try your sketch). Do you have different pins for turning the motor on and off?

Here is the code for changing pin value without delay. Read it and try it.
#define on 2
#define off 3

//delay times
const unsigned int ont = {1500,  500};
const unsigned int offt = {500, 300};

//last millis
unsigned long last_tm_on = 0;
unsigned long last_tm_off = 0;

//position
byte pos_on = 0;
byte pos_off = 0;

void setup(){
  pinMode(on, OUTPUT);
  pinMode(off, OUTPUT);
}

void loop(){
  if(millis() - last_tm_on >= ont[pos_on]){   //check if millis() - last millis() is bigger than wanted time
    last_tm_on = millis();   //save last millis()
      if(pos_on == 0) digitalWrite(on, HIGH);
      if(pos_on == 1) digitalWrite(on, LOW);

      pos_on ++;   //add position
      if(pos_on > 1) pos_on = 0;   //check max position
  }

 if(millis() - last_tm_off >= offt[pos_off]){
    last_tm_off = millis();
      if(pos_off == 0) digitalWrite(off, HIGH);   // turn the motor on (HIGH is the voltage level)
      if(pos_off == 1) digitalWrite(off, LOW);

      pos_off ++;
      if(pos_off > 1) pos_off = 0;
  }
}

Matej, there is only one motor and you have two independent software timers with millis.

@Jot I thought, that on is one motor and off second. Lol


text:
please help with my arduino
My problem is when I run code like this:
char directioN;

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

void loop()
{
  if (Serial.available())
  {
    directioN = Serial.read();

    switch (directioN)
    {
      case 'F':
        break;

      case 'B':
        break;

      case 'R':
        break;

      case 'L':
        break;

      default :
        break;
    }

    Serial.print("direction is:");
    Serial.println(directioN);
  }
}

My serial monitor add another input, but the second one is empty; this happened here with char both as with int.
But when i tried the same code in tinkercad it worked fine.
So do I really need a new ATMEGA328 or it can be done by software or something?
**I use an Arduino Uno

what have you set in Serial Monitor as line ending to send?

So why you don't just ignore it?
if(directionN >= 32){   //check if char is readable ascii character
  Serial.print("direction is:");
  Serial.println(directioN);
}

How i ignore. it affect how my code run cause a specific input do a specific function so the following zero or null input which im talking about here cause the wanted function to end

@nouralbrmky Like in the code i posted, null input is probably newline.

It worked fine thank you .do u have any idea what may cause some thing like that to happen and i 'll be more thankful

@nouralbrmky It's probably caused by newline character which is sent after text. Newline decimal value in ascii table is smaller than 32 and that's why this code ignores it.


text:
How to use power led from arduino-pro-micro?
In my project I need 3 leds. I would like to use on-board leds if possible.
I know how to use PB0 and PD5 red on-board leds, and I would like to hack the board somehow to use the green power led.
If I do not find a way to use the power led from MCU, I'm planning to destroy it anyway, because it is constantly on, which is harmful in my project.

refer to the schematic

The power led is connected directly to the 5V line. So you'd need to modify the board (cut a trace and add a tiny wire).

There are 34-pin atmega32u4-based boards. They have 3 leds. So use them instead of pro-micro board.


text:
How can I reduce current drawn by micro SD card module?
I am using a servo along with a sensor and micro SD card module and speaker in arduino uno in order to play a wav file at certain conditions . But when i run the whole system the sd card module is consuming high current and the servo stops working as the current in that is in order of some micro amps. So please help me to solve the problem.

SD cards do use a lot of current. You just need to supply more to your circuit.

I think the problem is somewhere else. Most likely the SD library you are using is blocking all interrupts while it's reading the SD card. When there are no interrupts the servos don't get any signal for a moment, and will stop working.

another good practice might be to add a Transistor to your Systems so that you can physically disconnect parts of your System from the power rail while not in use. this will obviously decrease power consumption...

Don't try to drive all of that from the Arduino regulator. The answer is to get a higher current power supply. You might even need to add filter capacitors on the 5V rails "right in front" of your different systems to protect them from voltage drops when other systems suddenly draw large amounts of current from the 5V rail.


text:
Passing non-static member function using bind
I'm using the GxEPD2 library to communicate with an E-Paper display. I now wanted to use the drawPaged method of this library with an object display.
I also have written my own class from which I want to print stuff on the display.
Here's the relevant code for the MyClass.h:
class MyClass{
    //some variables and methods
    void drawClass(); //this is public
    void drawClassCallback(const void* v1); //this is private
    //    this is actually a uint8_t --^
}

And here's the MyClass.cpp:
void MyClass::drawClass(){
    //some display preparation
    uint8_t var; //A variable to pass information from the callback to this method since it is needed later
    display.drawPaged(std::bind(&MyClass::drawClassCallback, this, &var));
    //some code where I need var with info from the callback
}

I'm getting the following error:

no matching function for call to 'GxEPD2_BW::drawPaged(std::_Bind_helper::type)'
note: candidate: void GxEPD2_BW::drawPaged(void ()(const void), const void*) [with GxEPD2_Type = GxEPD2_290; short unsigned int page_height = 296u]
       void drawPaged(void (drawCallback)(const void), const void* pv)

I've also tried display.drawPaged(std::bind(&MyClass::drawClassCallback, this, std::placeholders::_1), &var) without success.
I've stumbled upon this post already, however the solution presented there (and the one used above) does not work in this case.
Why is that?

In your MyClass example, the drawPaged() call is given only a single argument, while according to the library, it needs two:
void drawPaged(void (*drawCallback)(const void*), const void* pv)

The first argument is the function pointer (or the one wrapped by std::bind!). The second argument seems to be some data that will be passed on to that function. (according to the [linked API)
The error actually explains it, it suspects that you are trying to call void GxEPD2_BW::drawPaged(void ()(const void), const void*). Hence it mentions this as a candidate.
What you need to do is something like this:
display.drawPaged(std::bind(&MyClass::drawClassCallback, this, std::placeholders::_1), &var);

std::placeholders::_1 is the placeholder that represents the var argument that will be passed on when it is called.


text:
How to trigger NodeMCU sketch from Arduino Leonardo Micro Pro?
So this is probably a very simple question. I have my NodeMCU set up and working where it connects to wifi and sends a push notification. Currently it does that automatically when connected to power.
What I want to do is connect it to my Leonardo Micro so that at a part in the Leonardo sketch it sends a signal to the NodeMCU to run the sketch to trigger the push notification. So simply, which ports should I connect and what code should I change.
Here is my working NodeMCU code.
    #include <ESP8266WiFi.h>

// Wifi Settings
const char* ssid = "MySSID";
const char* password = "MyPassword";
// Pushover settings
char pushoversite[] = "api.pushover.net";
char apitoken[] = "MyAPIToken";
char userkey [] = "MyUserKey";
int length;
WiFiClient client;
void setup() {
  Serial.begin(9600);
  delay(10);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Print the IP address
  Serial.print(WiFi.localIP());

}

void loop()
{
 pushover("OMG, Yes it works!!!");
 delay(60000);
}

byte pushover(char *pushovermessage)
{
 String message = pushovermessage;

 length = 81 + message.length();

if(client.connect(pushoversite,80))
 {
   client.println("POST /1/messages.json HTTP/1.1");
   client.println("Host: api.pushover.net");
   client.println("Connection: close\r\nContent-Type: application/x-www-form-urlencoded");
   client.print("Content-Length: ");
   client.print(length);
   client.println("\r\n");;
   client.print("token=");
   client.print(apitoken);
   client.print("&user=");
   client.print(userkey);
   client.print("&message=");
   client.print(message);
   while(client.connected())
   {
     while(client.available())
     {
       char ch = client.read();
       Serial.write(ch);
     }
   }
   client.stop();
 }
}

And my Leonardo code
#include <Keyboard.h>
#include <Mouse.h>
char returnKey = KEY_RETURN;
char tabKey = KEY_TAB;
void setup() {
  Keyboard.begin();
  Mouse.begin();

  delay(4000); //Testing Delay
// Language Select Screen
  Keyboard.write(returnKey);
  delay(30000);
// Welcome Screen
  Mouse.click(MOUSE_LEFT);
  delay(100);
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(' ');
  delay(2000);
// Select Keyboard
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(' ');
  delay(2000);
  TELL NODEMCU TO SEND PUSH NOTIFICATION HERE
}

void loop() {
}

As a reminder the pinout on my boards are as follows.
Leonardo:

NodeMCU:

First make it work from a button. Then replace the button with the Leonardo.

HW part:
It's like button, simply connect arduino micro pin to nodeMCU pin and GND of arduino to GND of nodeMCU.
It's also good idea to use two resistors as voltage divider because arduino micro works with 5V and ESP8266 (nodeMCU) with 3V3. 5V can destroy ESP8266 but this thing is still not really clear.
Resistor divider connect as in this link link about resistor divider for uart but instead of TX put arduino micro and instead of RX nodeMCU.
resistor divider schematic

Code part:
On the arduino micro part use:

In void setup():
pinMode(PIN, OUTPUT);

In your marked place:

digitalWrite(PIN, HIGH);
delay(100);   //short wait time
digitalWrite(PIN, LOW);

nodeMCU part:

In void setup():
pinMode(PIN, INPUT);

Remove everything from void loop() and put there this:

if(digitalRead(PIN) == 1) pushover("OMG, Yes it works!!!");

In both codes select the PIN according to your choice.

Thanks Matej, exactly what I was looking for and I think i'm beginning to understand things a bit more now too. Resisters are still something I need to read up on. I'd bought a rechargeable battery shield I was going to use to power the mini and the NodeMCU but I guess even if it's powered that way I still need the resister between the digital pins?

@DannyShepherd Resistor is simple thing, it causes voltage drop which you can calculate from ohm law (U = R*I). In this case it's not so simple because we are working with mcu pins which current consumption is really low - few micro amps.

@DannyShepherd If we want to put 5V logic to 3V3 logic, we need to have voltage drop 1.7V (5-3.3) on first resistor, that means on second resistor will be voltage drop 3V3 (between nodeMCU pin and GND). But why two resistor? Because if you use just one, current is so small that value of resistor will be so big to achieve voltage drop equal to 1.7V. So we simple take two resistor in series and they can create proper current. We can apply formula U1/U2 = R1/R2 which came from using ohm law and then trim current from it because in serial connection current is same.

@DannyShepherd So if both arduinos will have same voltage level you don't have to use voltage divider or level shifter. Als some MCUs are 5V tolerant but specially ESP8266 is not or it's not still clear. So is this answer for your question? :)

Hey @Matej, that's really well explained thanks. Just picked up a back of resisters so I will play around with this and hopefully not fry any boards!
Just to double check something if I have a shield that powers the Leonardo with 5v and the NodeMCU with 3.3v - the digital pinout from the Arduino would still try to send 5V down as well (and thus need the resister) I assume so, just checking the basics of the current flow. Thanks!

@DannyShepherd Yeah, if Leonardo is powered with 5V you will still need voltage divider from two resistors.

a little off the original topic here, but I just check my recharageble shield I want to use to power and it only had 5v out. So I presume I can wire it direct to my Pro Micro VCC port, and then I can take from the same output to the NodeMCU but use the resistors to make it 3.3v correct?

@DannyShepherd Yes but keep in my to do not power ESP8266 with 5V, you have to use stabilizer which boards like nodeMCU have included onboard. On nodeMCU you can put 5V to VIN pin, I think. And yes, for converting logic level 5V to 3V3 use resistor voltage divider.

ah I didn't know that, ok that makes life a little easier then. So just to double check the way to do it would be, for example. Pin 5 out on the Pro Micro to Pin 5 on the nodeMCU with a 10kOhm resister in better and ground on each board connected together with a 20kOhm resister in between?

@DannyShepherd I don't know if you mean this but GND will be directly connected to GND and between digital pins you will have one resistor and second between nodeMCU and GND.

Hi Matej, I got this working, one change I needed to make to the code though was to have the MCU have pinMode(PIN, INPUT); instead of OUTPUT. (Oh and I used a logic level shifter board in the end for the 5v to 3.3v to be a bit safer)

@DannyShepherd Hey, great! You are right, I had mistake in my answer. Edited.


text:
firebase arduino uno + esp8266
I am trying to make a project that can read data from usbsheild connected to arduino uno board then send them to firebase through esp8266.
But the libraries of firebase and esp8266wifi that i found are not for arduino uno but for the esp8266 board can anyone help me in this problem ?

The best way you can do is connect it to a web and then use firebase-php library

https://github.com/ktamas77/firebase-php/blob/master/README.md

insert this
Follow this as your guide

https://stilllot2learn.wordpress.com/2017/11/18/arduino_gps_gsm/comment-page-1/#comment-47

Don't forget to create your FIREBASE ACCOUNT

look for database secret as your TOKEN under User and Permissions
  TAB


text:
two dimensional array
how can i store serial port available test to a two dimensional array. strings are separated with Z and end of text with #
pls help if anyone alrdy a solution
i am posting my program here
  String readstr;
  String finalstr;
  char *messages[][20] = { "" };
  int i, k = 0, lp;
  char chArray[] = "hai";
  String str(chArray);

  void setup() {
      Serial.begin(9600);
      Serial.println("System ready........"); // so I can keep track of what is loaded
  }

  void loop()
  {
      int flag = 0;
      while (Serial.available() > 0)
      {
          char c = Serial.read();  //gets one byte from serial buffer
          if (c == '#')
          {
              finalstr = readstr;
              readstr = "";
              flag = 1;
          }                 // I am getting data here on #
          else    // and is available with finalstr
          {
              readstr += c;     //makes the string readstr
          }
      }

      if (flag == 1)    // once data is available and terminated with #
      {
          int j = 0, l = 0;
          flag = 0;
          //Serial.print(finalstr.length());
          for (i = 0; i < finalstr.length(); i++)     //want to split in to strings
          {
              //Serial.println(finalstr.length());
              // Serial.println(i);
              if ((finalstr[i] != 'Z'))          // if any char is Z, then split
              {
                  // Serial.println(finalstr[3]);
                  messages[j][l] = finalstr[i];          // rearanging in to String messages
                  chArray[j] = finalstr[i];
                  messages[j][l] = '\0';
                  Serial.println(messages[j][i]);    // here it is not working
                  l++;
                  // Serial.println(j);
              }
              else
              {
                  l = 0;
                  j++;
                  String str(chArray);
                  // strncpy(messages[k],chArray,str.length());   // this is not working need help
                  //  Serial.println(messages[0]);
                  //delay(2000);
                  Serial.println(k);
                  k++;
                  //Serial.println(str);
              }

          }
          for (i = 0; i < j; i++)
          {
              Serial.println(messages[i]);    // I am getting here garbage value
          }
          k = 0;
          j = 0;
          l = 0;
      }
  }

is this a school assignment? ........... what is the problem?  ....... do you get errors? ..... please use the edit button to add information to your post

Hi sir,  thinks for your reply.
I want to split serially available text data to number of strings based on the separator character Z and end of data #
pls advice me to save the character data parsed to string array


text:
timer interrupts on an esp8266
Folks.
I'm working on an ESP8266 and keen to switch to using:

an object approach -> sorted;
physical interrupts on the hardware pins -> sorted;
timer interrupts -> driving me crazy!

My problems are that:

There are so many timer libraries
I can't find one that works on my set-up; either they don't compile, or they have unfulfilled dependencies
Some look promising, but then it turns out something needs to be polled to see if the timer has triggered

Can anyone help me out here please?  I just want a straight-forward approach to setting a simple timer on the 8266 that will trigger an ISR where I can switch off an output now and then tidy up later.
Regards, David (Southampton)

Have you looked at the Ticker class (the one included in ESP8266 platform?)

Brilliant - it's simple yet flexible, it compiles - and it does the job.  Thank you!


text:
Trying to understand Classes
I have searched about class and int but I still don't understand.
I have seen this code online I want to understand it
class Motor {

  int enablePin;
  int directionPin1;
  int directionPin2;
  public:

  //Method to define the motor pins
  Motor(int ENPin,int dPin1,int dPin2){
    enablePin = ENPin;
    directionPin1 = dPin1;
    directionPin2 = dPin2;
};

here is an interactive web page that may help ... http://www.cplusplus.com/doc/tutorial/classes/

which part are you having problems with?

class Motor {

This says to start defining a class. A class is like a "container" that holds both data and functions (methods). After defining the class, it becomes like a new variable type that you can declare multiple instances of.
  int enablePin;
  int directionPin1;
  int directionPin2;

These define the 3 integer variables (int=integer; whole numbers like 2, 3, 1000, -5, etc.) that belong to the class and have the identifiers given (enablePin, etc.) Since not otherwise specified, these variables are private, meaning that only other functions in the class can access them. Other parts of the program are not allowed to access these variables.
public:

This means that the following definitions are accessible by parts of the program that exist outside the class.
Motor(int ENPin,int dPin1,int dPin2) {
  enablePin = ENPin;
  directionPin1 = dPin1;
  directionPin2 = dPin2;
}

This defines the only "member function" in this class and because it shares the same name as the class (Motor), it is called a "Constructor", and allows you to pass arguments to an object created from the class -- in this case, if you declare an object of class Motor by myMotor = Motor(1, 2, 3);, the constructor is called with parameters 1, 2, and 3. This constructor happens to just set the private variables to be the same as the arguments passed in.
But... All of this is basic C++, so a book or course on C++ programming would be better in-depth resource to understand this.
The code snippet also is incorrect because it has unbalanced curly-braces -- there is one to open the definition of the class and one to open the definition of the constructor, but only one closing brace.


text:
Power Arduino Mega ESP85266
Is it possible to Power a Arduino Mega 2560 and a NodeMCU V2 ESP8266 ESP-12E from a single 9V Block?
What would be the best solution?

Can i power the ESP8266 directly via the Arduino Mega 5V output? (3.3V Output seems to weak)
Is a Power Converter like this for the ESP8266 necessary?
Should i use another external Power source for the ESP8266?

Thanks for any Help :)

Is it possible to Power a Arduino Mega 2560 and a NodeMCU V2 ESP8266 ESP-12E from a single 9V Block?

Yes. Assuming the "block" can provide enough current.

Can i power the ESP8266 directly via the Arduino Mega 5V output? (3.3V Output seems to weak)

No.

Is a Power Converter like this for the ESP8266 necessary?

Yes if you are powering it from more than 3.3V.

Should I use another external Power source for the ESP8266?

Not necessary if the 9V one can provide enough current as I mentioned above.

*Can i power the ESP8266 directly via the Arduino Mega 5V output? (3.3V Output seems to weak)
No* - why not? I'm not questioning your answer, just wanted a reason why the Mega 5v can't be used to power a nodemcu via the nodemcu's Vin

The mega can only provide Max 800mA. That has to include what the mega uses, which leaves only just enough for the esp8266. You really need 1A for the nodemcu to work reliably.

fair enough, I thought the Mega could provide 1A - but that seems to be the spec for an Uno

It varies from model to model. The actual limit actually is dependant on the incoming voltage and how much heat that generates in the regulator. In practice you can't get more than a few hundred milliamps before it gets hot if you have 9v or more on the input.

The "1A" is the rating of the regulator. That is only achievable with good heat sinking and minimal difference between input and output voltages. With anything over about 9V half your power (or more) is being converted to heat - and there isn't good heatsinking. So it gets too hot and shuts down. On an Arduino I wouldn't want to draw more than maybe 400mA with >9V on the input.


text:
ATmega 32A and 2560 R3 register to pin mapping?
I've been doing research for the last few hours trying to determine the mapping of physical pins to memory-mapped I/O registers for the Arduino Mega board (which is an ATmega 2560 R3).

My code is on GitHub in a pull request, but hasn't been merged yet because I'm not finished yet.
This is the upstream example I'm working from, which was written for an ATmega 32A.
Here is Arduino's 2560 pin mapping which doesn't tell which registers are mapped to which pins.
Here is avr/iomxx0_1.h which defines the ports with simple numbers that I can't make heads or tails of.
Here is a collection of links relevant to my research.
I broke down and cross-referenced all of the uses of memory-mapped I/O registers in the upstream example.

Some of the registers used include CS11, DDB4, DDRA, DDRB, GICR, INT0, INT1, ISC00, ISC10, MCUCR, PA0, PB5, PB7, PD2, PD3, PIND, PORTA, PORTD, SPCR, SPDR, SPIF, SPSR, TCCR1B, and TCNT1. I can't figure out which pins these are and/or what they do.
Here is a diagram provided by the upstream example:

Unfortunately, I'm not very good at reading these diagrams so I'm doing my best.
How can I determine the mapping of these registers to physical ports on both the ATmega 32A, which is the board the example was originally written for, and the ATmega 2560 R3, which is the board I'm currently working with?

Here is an alternative GPIO mapping: https://github.com/mikaelpatel/Arduino-GPIO/blob/master/src/Hardware/AVR/Board.h#L225, Please note the Register and Pin bit mapping, names, etc.

What is ATmega2560 R3? There is ATmega2560 MCU or Arduino Mega R3. do you want the mapping of pins of Arduino Mega or the pins of the ATmega2560 MCU.
The mapping of pins of the ATmega 2560 chip is in the datasheet.
The mapping of the Arduino Mega pins to ATmega2560 pins and registers is in the schema of the board or in the Arduino AVR boards package variants mega folder.
The link "Arduino's 2560 pin mapping" in your question shows the mapping too. Registers are PA, PB,... and every register covers to 8 pins with the 8 bits of the register. For example PB3 is pin 50 of the board.

This is the exact board that I bought, and I'm looking for a reference on which pins on the board correspond with which registers exposed in the avr C library. The schema doesn't seem to list things like PORTA and so on that are referenced in the code I'm working from.

it is an Arduino Mega clone. the link to schema is in answer.

Because I'm porting code that I did not write. I need to understand what the code is actually doing before I can start porting it to my board.

but the schema clearly shows the register to board pin mapping. and that is what you asked. and the link "Arduino's 2560 pin mapping" in your question shows it too

I added something to the answer

@NaftuliKay, did it help?

Atmega32A is a 44 pin TQFP part with 4 8-bit IO ports.
It is kind of a crippled Atmega1284P. You may have an easier time just switching to a 1284P chip (also 44 pin TQFP) to take advantage of its 16K byte SRAM and 128K byte flash. There's an easy to use add-in to the Arduino IDE to use it.
https://github.com/MCUdude/MightyCore
I do a lot of 1284P designs and use it all the time.
Atmega2560 is 100 pin TQFP part with 10 8-bit and one 6-bit IO ports.
As your schematic only uses a few IO pins, the electrical connections will be simple - SPI for bootloading or downloading code
- 2 pins for serial
- 2 pins for other IO
If you look at the Arduino Mega2560 schematic, you can pick those out pretty readily.  The rest you will have to tweak up in your code.

he has a Mega. nothing special

I'm hoping to start with the board that I have (mega 2550) and then use conditional compilation to support other boards. I'm having a hard time with the schematic, as it doesn't seem to list which registers map to which pins, e.g. what is PORTA and what is it mapped to in avr's C library and what does it do? Is there a reference I can look at to determine this?

The IDE already does that mapping. For example, on  '328P board, Port D is D7-D0, PORT B is D13 to D8 (upper two bits not used as IO), Port C 9 is D19 to D14. (upper two bit not used as IO).  Used to be that you could look at pins_arduino.h (I think that's the name) in the IDE folders for a particular board and read the mapping from PINx/PORTx to the IO pins.  I can't access arduino.cc from here to provide links to the specific boards, and I don't have them on this computer.


text:
AVR software reset without watchdog
I wrote a generic avr program wrapper which already use the watchdog timer to restart - and after the watchdog reset - recover the the bad situation.
After this recover process i have to restart the avr. Everything i've found in topic "software reset arduino" is about to set the shortest watchdog (15ms) timeout, then spins the CPU (for(;;);) until it cause watchdog reset.
But this results to enter the recovery process which is already done in this point.
It is any elegant way to achieve this?
Some non or less elegant way:

I can bind a digital pin to the reset and pull up with a resistor.
I can write to a fixed address in the flash or eeprom (but this maybe happens frequently) before soft restart, to prevent entering to recovery mode.

Is there any register that "survives" soft resets?
Edit:
I add mock example code to hint what i trying to do.
In the actual code, in the recovering the microcontroller connect to the serial bus, waits for commands then resets itselft in oder to return to application mode.
/*************************** Application wrapper ******************************/

//define call_application and call_recover as weak empty functions
//so they can be rewritten.

bool isWatchdogReset()
{
    return MCUSR == 8;
}

void softwareReset()
{
    //  wdt_enable(WDTO_15MS);for(;;);// (this way enters recovery mode)
    //or
    //  asm ("jmp 0x0");// (this way function registers not being resetted)
}

bool isSoftwareReset()
{
    //???
}

int main()
{
    bool needRecover = isWatchdogReset() && !isSoftwareReset();
    MCUSR = 0;
    init_board();
    wdt_enable(WDTO_1S);
    while(1)
    {
        if(!needRecover)
        {
            call_application();
        }
        else
        {
            call_recover();
        }
        wdt_reset();
    }
}

/********************************* Application ********************************/

void call_application()
{
    if(randomTrue())
    {
        //stuck more that 1 secounds, that results WDT reset
    }
    else
    {
        //proper operation
    }
}

/********************************** Recover ***********************************/

void call_recover()
{
    //initialize UART, attach interrupts, Write flash and EEPROM, modify
    //function registers.

    //recovering completed, returning to the original application as like
    //nothing's happened.
    softwareReset();
}

Edit:
I try explain short to spot the point:
1) I already use the watchdog timer to detect when the application code is flawed.
2) soft reset is an inproper solution, because it doesn't reset the registers. So onyl the program will be resetted, the state of the microcontroller doesn't.
3) To commit a proper reset, the solution is to timeout the watchdog timer. But see point 1), it is already used, so how can you make the difference of a requested reset and a flawed code recovery reset?

and why is the second wdt reset a problem? or why you can"t continue without reset?

I've read you question three times, but I still don't get what it is you are describing. What is this "recovery process" you are talking about? Are "recovering" stuff in a WDT interrupt routine.

The reset is basically jumping to the reset vector address 0x0000 (if you don't have the bootloader, or you don't want to start it).
There is also the MCUSR register, indicating which reset source caused the reset. It won't be set if you do simple jump to the reset adress.
The memory is also preserved, but C/C++ init code takes place and initialize your global variables. This can be ommited by placing variable/variables into the .noinit section. But it's not defined, what is there after the reset. With combination with MCUSR register you can init the variables for regular reset sources and keep it unchanged if you jump to the reset vector address.
Also the regular reset sources jumps to the bootloader, so it can use the same memory locations as your .noinit variables and trash them.

I check MCUSR register right after start to identify the source of reset/power up. Now I've tried this way of reset (void sw_reset(){asm("jmp 0x0");}). It's works, but - as i disassembled - it just resets the stack pointer, which results to start the program again from the main(), but  port, timers, UART settings are remains

@DankóDávid So you don't want to restart it? Maybe it's an XY Problem?

Note also that a hardware reset sets all the I/O registers to their initial value, which a jump to 0x0000 doesn't. Only very few registers, like MCUSR have no defined initial value.

@EdgarBonet yes, that might be a problem in the middle of TWI communication or so. But initialization code should be written as there is already something configured. Definitely in this case.

I've edited the question and added an example what the exact problem i trying to solve. 1) I already use the watchdog timer to detect malfunction. 2) I'd like to reset the AVR completely (resetting all function register what the recovery function touched and i can't track), but the only way i've found is to use WDT timeout which results not just to restart, but to recognise as a "malfunction restart". More simplified: I need a malfunction reset (WDT) and an intentional software reset, which not share the same mechanism of reset. Or differentiate the two way of resetting the AVR.

The logic of you applications is wrong. You set the needRecover at the beginning of main, but test it in your infinite while (1) loop. The needRecover value will not change in the loop.
Do your initialization first no matter if normal power-up or watchdog restart and then do stuff in the infinite loop.
You could put the initialization in a function called setup and the infinite loop in a function called loop. And have a main function like this:
int main( void )
{
  setup();

  for (;;)
  {
    loop();
  }

  return 0;
}

wait, a saw this somewhere already :-)

The recovery process should restart the microcontroller. But now this uses watchdog timer to do this. Which cause to enter again into the recovery mode and not to the application mode.

@DankóDávid, use watchdog interrupt instead of watchdog. make the arrangements in the interrupt and then reset with wdt_enable(WDTO_15MS); my is here: https://github.com/jandrassy/Regulator/blob/b6ef120c6f8963979268d8d17b56e5632336f317/Regulator/Watchdog.ino#L24

you could use this library https://github.com/nadavmatalon/WatchDog I plan to replace my watchdog handling with it


text:
What is the voltage between Vin & GND?
I have NodeMCU ESP8266N Lolin V3, my 5V relay is powered from Vin of the NodeMCU.
The NodeMCU is powered from 5V USB.
My difficulty is when I measure voltage between Vin & GND, it is of 1.9V, but supposed to be around 5V as it is directly attached with usb 5V supply. Actually my relay is not working with the power tapped from Vin, but relay's led & NodeMCU  led are blinking but relay coil does not trip.
Please confirm is my NodeMCU having problems as voltage between vin & GND read 1.9V.
https://drive.google.com/file/d/1Z6jYX4sCLmRxnWbtBYZCNW6LpckokaC9/view?usp=drivesdk

Vin ... the in is the clue - I wouldn't use it as a Vout

possibly duplicate of https://arduino.stackexchange.com/questions/51873/nodemcu-vin-pin-as-5v-output - there is an answer there that suggests using the VV pin for your requirements ... however, don't be surprised if your setup is unstable, due to the power requirements of the NodeMCU and the Relay

I afraid you could not understand, i m not going to use vin as output similar to digital output of GPIO pin, i am just taking input 5v from Vin to power my relay. There in my image, i have given digital output as D4  to relay in1 from nodmcu D4 pin, but relay's coil not get trip but led blinks for both relay & nodmcu. Found no solution anywhere

Yeah sorry but there was info in that questions answers that seemed relevant .. i.e. regarding voltage

Vin does not provide enough current to operate a relay ..... Vin is an input to a voltage regulator .... the voltage regulator cannot be used in reverse

on some nodemcu boards, apparently, Vin is directly connected to USB +5 @jsotola - however, I think there's about as many "NodeMCU" variations as there are stars in the sky ... I have two different types, neither of which have a VV pin ... so that's 3 different NodeMCU boards referenced in one sentence :p

@SumitRoy - you have a Lolin V3 board - I can tell that because below A0 you have GND and VV instead of Rsv and Rsv - VV is "V USB Power output" ... use that with a decent USB power supply (not from a PC as that probably wont supply enough current) ... as I mentioned 5 hours ago ... USE VV

Sorry ... it's VU ... not VV ... I'm old and my back is blind and my eyes are bent :p

Lolin is former Wemos not NodeMcu

Ooo, I know!  All my CH340-based nodeMCU's have a "broken" vin pin, giving only a couple volts. The same pin on all my CP2102-based nodeMCUs (amica) and wemos D1 minis provides about 4.4v (5v in - a diode drop). They work fine with such relay modules. That's why I refuse to buy the CH340-based ESPs anymore, even if they are a lot cheaper... Replace the devkit and it will work fine as-wired, like it should.

The voltage on Vin when you power that board thru USB is not relevant ... Vin is not the pin you are looking for
You clearly have a Lolin NodeMCU (V3) board - the existence of Gnd and VU (looks like VV in your picture!!) between A0 and S3 pins indicates that
In documentaion easily found by searching for Lolin V3 pinout - VU is described a USB power output

Use this pin to connect to JD-VCC on the relays
I've just now successfully done this with a 4 relay board
I would connect (nodemcu -> relay)

3V3 to VCC
VU to JD-VCC
Gnd to Gnd
Dn to INm - i.e. choose a D pin on the NodeMCU and connect to an IN pin on the relay

Thanks a lot to give me solution from your precious time, sir, i have tried this solution in the morning, but fail, could you pls provide some link or email so that i can post the video i recorded, sir just for sake of confirmation, i just want to mention that i gave power to relay by doing as follows , VV of nodmcu to JD- VCC of relay, G of nodmcu to left-hand side GND of relay , and D4 of nodmcu to in1 of relay, pls tell am i correctly doing connection, thanks in advance

You need to connect the 3V pin to the VCC pin on the relay board. JD-VCC is just for the relay coils. Vcc is used for the optocouplers which currently don't have power at all, looking at the picture.

I think the grey wire in the picture probably goes to vcc ... no wait ... that picture is hard to see ... the other issue the OP has is the lack of VCC as you poinbt3ed out @Gerben - that other VCC can be 3v3 (I know, because that's how I connected mine)

Gray goes to IN2. Most of these boards have a jumper between VCC and JD-VCC. But you probably don't want that here. The opto-isolators led could light up if the pin is set to HIGH (3.3V) on the ESP. So the led will see 1.7V across it.

https://drive.google.com/file/d/1Z6jYX4sCLmRxnWbtBYZCNW6LpckokaC9/view?usp=drivesdk

pls see the video, also pls guide me the connection of relay & nodmcu with usb charger..pls

answer edited with suggestions for connections

Thanks for connection @Jaromanda X , i shall try and let you know. Did u just see the video i posted on the link

Manyyyyyyy manyyyyyyy manyyyy THANKS A LOT @Jaromanda, I salute you, hats off to you... In this universe, i have tried solution everywhere but you in this forum gave me working solution.         It got worked as per your connection. Thanks once again. i am so happy

@SumitRoy - no I did not watch the video

It is hard to tell from your pictures but I don't think you have your relay connected properly.
Some problems i see:

Your esp8266n seems to be a 3 Volt device; it has 3V output pins
Vin usually feeds a regulator; the +V rail is usually after it
Your relay needs 5V but you only have 3V for power and signal

You will need a level shifter, and another powersupply to run your relay. You should be able to put 5v into Vin on your ESP and have it be powered, then you will need a level shifter to connect to the IN1 or IN2 of the realy so that you can control it with 3v. And the relay Vcc and GND also connected to the same power supply.

Sir, could you please get to know that just connecting relay Vcc with 3.3V Vcc of esp8266 , lot of youtube video demonstrates that relay of 5v works even on 3.3 V. Just Google it pls. There is no external power supply required other than tapping power from esp8266 to power relay. Pls let me know what's the voltage between Vin & ground is it 1.9V!

the voltage on your particular board is what you measure @SumitRoy - when powered thru USB, mine is 4.74 volts with nothing connected to it - but none of my nodemcu boards are Lolin brand, and neither have a pin labelled VV which I suggested you use 5 hours ago - did you try that at all?


text:
Arduino nano -> 74HC595 -> LCD display
Greeting to all,
Newbie in the contraption above (Arduino nano -> 74HC595 -> LCD display); I would like some help from the experts.
I connect the 74HC595 to the LCD display using the 4 wires as described on the net.
I download one of the sample sketch and "voilà" the "World welcomed me".
But .... I would like to make use of Q0, Q1, Q2 and Q3 on the 595 for other functions like flashing an LED or connecting a 5V buzzer even if the lcd screen blink for a fraction of second.
ie.:
lcd.setCursor(0, 1);
lcd.print("Welcome to the world");

// flash the LED

delay(100);

lcd.setCursor(0, 1);
lcd.print("Welcome to the world");

Is it possible and (please) HOW?
Thank you for your support.
Eric

Could you post a schematic? It would make helping you much simpler.

The 74hc595 latches the output, so if the RS and E pins stay the same, the display will not blink. Please post a schematic and your sketch as well.


text:
Using ERASE button as PIO on Due
I'm working on a demo program for which I want to use minimal resources: all I need is one LED and one pushbutton.
I'd very much like to use on-board resources. The user LED (PB27) is fine (I'd have liked one more, but there it is).
I read in the datasheet that the ERASE button can be used as an input (PC0) provided that I clear the SYSIO12 bit in the System I/O Configuration Register CCFG_SYSIO.
I find that if I do this I can push the ERASE button without erasing flash (!), but PC0 always reads as 0 (even if I enable pullup; ought to be already enabled, you'd think).
I should say that PC1 works just fine.
Has anyone else got ERASE => PC0 to work? is there documentation I've missed? (in ASF, some of the other boards in sam/applications/getting_started/ disable the ERASE button, but not this one).


text:
RFID scanner- HZ 1050 Module
I just bought a rfid scanner hz 1050 module at $5 to add to my project,in the module I see a lot of pins to male my connections.
Am getting stuck on the ones to use for arduino.
I will be glad to anyone who helps me out.Thank you.

Link: Quick web-search gave a link to Nick Gammon's excellent blog. Start here: http://forum.arduino.cc/index.php?topic=316450.0

You haven't even told us what the pins are or what connection type the scanner is ... serial? I2C? SPI? something else?

The pins are the 5V GND,D1,DO,TXD..Am getting troubled in the  the last three pins. The module is to be connected to arduino and LCD 12c..


text:
Where are the implementations of the SdFat BlockDriver methods?
This is most probably more of a C++ question than an Arduino question; but since this is an Arduino library, I am asking here.
I am using the SdFat library for my project. The library defines a BlockDriver object in one of its header file which only declares the typedef of BaseDriver to some other classes.
#if ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
typedef BaseBlockDriver BlockDriver;
#else  // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
typedef SdSpiCard BlockDriver;
#endif  // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
#endif // BlockDriver_h

typedef SdSpiCard BlockDriver; makes sense to me. But if ENABLE_EXTENDED_TRANSFER_CLASS or ENABLE_SDIO_CLASS are defined, BlockDriver is typedeffed into BaseBlockDriver. BaseBlockDriver is an abstract base class (as defined here). An instance of the BlockDriver object is later used directly in the FatVolume class here.
My question is, how does BlockDriver's method get defined when it abstract base class BaseBlockDriver is typedeffed to BlockDriver?

did you read the answer?

I read it. It does not fully clarify it for me, so I am reluctant to accept it.

what is unclear in the answer?

I am not so good with programming which makes it difficult for me to understand. Basically I do not understand what "The typedef in BlockDriver.h is only for pointer type, not for instance of the object." means or implies. Even though we are declaring it as a pointer, we later call methods on it. How do those method work when BlockDriver is a BaseBlockDriver. Hope that clarified my confusion.

the SdSpiCard class should be derived from the BaseBlockDriver. but for AVR this consumed memory. so the author decided to leave out the base class for AVR. but then everywhere in the code where BaseBlockDriver was used as parameter type, an object of type SdSpiCard could not be used as value. He solved it with creating a macro BlockDriver which is BaseBlockDriver or SdSpiCard

I think I understand. Unfortunately, it is not clear for me yet on account of lack of understanding of OOP. I will accept your answer, but kindly elaborate on it and provide more background if you can find some time. Thanks for your patience and contribution.

there is nothing more. did you read my question to Bill Greiman and his answer on GitHub?

yes i did. Your answer does not explain the thing in detail and I believe can be improved. It takes for granted that the reader is well versed in OOP.
I still do not get how one can call virtual methods. I.e. when BlockDriver is a BaseBlockDriver object, what are its actual methods? If my BlockDriver points to a BaseBlockDriver object (which in itself shouldnt be possible as that is an Abstract class), how do its methods get called. you tell me "The object is always of type SdSpiCard" whereas the typedef i quoted in my question clearly shows thats not the case.

if BaseBlockDriver class it not excluded, it is a base class for SdSpiCard. a pointer type to base class can point to an instance of a derived class. like you can refer to some Labrador as "a dog".

I think I now have some kind of understanding on this. Thank you for bearing with me. I will accept this answer. However, I still feel the answer could be much clearer.

The typedef in BlockDriver.h is only for pointer type, not for instance of the object. The object is always of type SdSpiCard, but in one case it is not an implementation of BlockDriverBase, so the function parameters can't refer it by base type.
#if ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
class SdSpiCard : public BaseBlockDriver {
#else  // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
class SdSpiCard {

use of BlockDriver typedef
class FatFileSystem : public  FatVolume {
 public:
  bool begin(BlockDriver* blockDev, uint8_t part = 0) {

I was curious why the version without BaseBlockDriver. I asked the author Bill Greiman and he answered:

This is due to history. Long ago using a virtual base class cost lots
  of RAM and flash so I did this mainly for 328 boards


text:
Sketch works on MEGA 2560 timer2, but does not work on timer1
I set the PWM frequency on MEGA 2560 like this:
  TCCR2A = 0;
  TCCR2B = 0;
  TCNT2  = 0;

  TCCR2A = _BV(COM2A1)
           | _BV(COM2B1)
           | _BV(WGM20);
     TCCR2B = (TCCR2B & 0b11111000) | 0x02;

it works good, now I want to use timer1 on PWM and I changed the code like follow but no work:

TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;

  TCCR1A = _BV(COM1A1)
           | _BV(COM1B1)
           | _BV(WGM10);

  TCCR1B = (TCCR1B & 0b11111000) | 0x02;

What's wrong with the changes?
I added 'TOP = ICR1', and when I tested, the ICR1's value effected both the PWM's frequency and duty cycle, how to avoid ICR1 effect dutu cycle?

what is your question? ..... what does this mean? but no work ................ are the two timers interchangeable?

I don't know much, I just mechanically changed 2 as 1 relatively.

Thank you jsotola. I'm using a pair RC remote control module to test some thing, when I set Timer2 on MEGA 2560 , the communication is OK. It is no communication when I modified the timer set from timer2 to timer1.


text:
give a class's function name as a parameter
I'm trying code using FastLed library to have a 3 state ( color or brightness ) led strip, using a physical input switch, while each press will change leds color, using a predefined list.
code below demonstrate  1) create a colorPallete of two colors 2) try to use it in loop with no success.
#include <FastLED.h>

// How many leds in your strip?
#define NUM_LEDS 1

// For led chips like Neopixels, which have a data line, ground, and power, you just
// need to define DATA_PIN.  For led chipsets that are SPI based (four wires - data, clock,
// ground, and power), like the LPD8806 define both DATA_PIN and CLOCK_PIN
#define DATA_PIN 3
//#define CLOCK_PIN 13

// Define the array of leds
CRGB leds[NUM_LEDS];
int colorSelctor = 0;
int birughtSelector = 25;
int inputPin = 13;
char *colorPallete[2] = {"Red","Blue"};

void setup() {
  // FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
  pinMode(inputPin, INPUT_PULLUP);
}

void loop() {
  // Turn the LED on, then pause
  leds[0] = CRGB::colorPallete[0];
  FastLED.show();
  delay(500);
  // Now turn the LED off, then pause
  leds[0] = CRGB::Black;
  FastLED.show();
  delay(500);
}

I don't see the color palette being used in your loop function and I wonder how a string based name could work as color definition. The only way I can interpret this question is "I need to do something, can you do it for me?" which is not the intention of StackExchange

CRGB::Red, etc, are just numbers. You need to treat them as such.
uint32_t colorPallette[2] = { CRGB::Red, CRGB::Blue };

And then:
leds[0] = colorPallete[0];

From pixeltypes.h:
/// Predefined RGB colors
typedef enum {
    AliceBlue=0xF0F8FF,
    Amethyst=0x9966CC,
    AntiqueWhite=0xFAEBD7,
    Aqua=0x00FFFF,
    Aquamarine=0x7FFFD4,
    Azure=0xF0FFFF,
    Beige=0xF5F5DC,
    Bisque=0xFFE4C4,
    Black=0x000000,
      ... etc ...
} HTMLColorCode;

It's a great workaround! (especially since I didn't understand the solution above). TNX!!!


text:
Arduino Power project question?
I saw a project on the Internet (the one in the photo), and I wonder, would it be a problem for me to connect the Vin and GND of the Arduino to the same place where the Servo Motors are being powered? (to power the Arduino together without having to connect it to another source or USB)
And if instead of the batteries I use one of those Breadboard Power Module (photo two) and connect a 12V / 1A power supply in it, would it have problem ? (connect the 4 Servo + the Arduino in it)

The peak current (when starting to rotate) for a servo motor can be 0.5 amps. When you have extra strong servo motors, then it can be a few amps. The arduino should be powered via the barrel jack with at least 7.5v or else a current can flow into the usb port of the computer.

Please provide more information about the power module, or at least a link to it.
But you could supply 12v directly to the Arduino's DC-In barrel-jack. It's not ideal; the Arduino's regulator is likely to get warm, but it would work. This module looks like it regulates its input down to 5v or 3.3v (jumper-selectable). If that is so, then its 5v output would be just right for the Arduino's 5v-In pin. Just make sure your the motors and the Arduino are each directly connected to whatever supply(s) you use. What you need to avoid is trying to power the motors through the Arduino. Your first photo has it right.
Update:
After reading about the supply (using your link), I see that its output is limited to 700ma. Some of that will have to go to power the Arduino (you can use the power supply's USB port for that), leaving a little less for the motors. That will be marginal for one motor and insufficient if the motor is stalled or moving more than a trivial load. It won't be sufficient for more than one motor at a time without scheduling them to prevent simultaneous starts.
You haven't described your motors, so I looked up the Tower-Pro SG-90 hobby servos, one of the simplest and least expensive of the hobby servos. I found a very similar looking one (maybe a clone?) described as being similar to the Tower-Pro, the only one for which I could find current specs. At 5 volts, it draws 100mA with no load and 700ma when stalled. With a stalled motor, the output voltage would likely drop, possibly stopping and resetting the Arduino.
So bottom line is, this supply is marginal, even for one hobby servo in a mechanism that won't stall it. With a larger motor or a heavier load, I don't think it will do the job.

The power module It's like this: https://www.amazon.com/JBtek-Breadboard-Supply-Arduino-Solderless/dp/B010UJFVTU
I know I can use the 4 Servo Motors with it (it was used in the project video).
My question is whether I can power the Arduino together the 4 Servo Motors (In the same place of power through his Vin.), or if I could run out of current for everything and damage something.


text:
How to declare a global variable in the .h file?
I have a .h library file in which I want to declare a global variable that can be read in the program loop and in the library's .cpp file.
The question is, is it possible to declare a variable in the .h file and make it global?

.h file is included by the compilation preprocessor as text into the .c or .cpp file. It is included as if you would replace the #include preprocessor instruction with the content of the .h file. (The Arduino .ino file is converted to cpp file before preprocessing.)
After the inclusion the cpp file is compiled to 'object' (.o file). If the cpp file contains a variable definition the variable is defined in this object file. If your .h file contained a variable definition, the it is also in this object file.
If two cpp files included the .h file with the definition of the variable, then the variable will be in two object files and the linker will exit with an error, because of two variables with the same name.
If only one cpp/ino files includes the variable definition, then it is OK. It is not a good practice, but sometimes a necessary compromise. (example of it)
To have one global variable made accessible by a .h file, the variable should be only declared in the .h file and be defined in one cpp file. Usually it is a pair of .h and .cpp file with same name.
An example of global variable is Serial. It is a global object of type HardwareSerial declared in HardwareSerial.h as
extern HardwareSerial Serial;
and defined in HardwareSerial0.cpp as
HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
Do you see the difference? The declaration has the keyword extern and the definition has in this case parameters for the constructor of the object. The declaration with extern keyword makes object Serial visible in all cpp files which include HardwareSerial.h (or an include file which includes HardwareSerial.h like Arduino.h included by ino to cpp conversion).

You can declare the variable as a static variable inside an inline function, and then just call this function to get a reference to this variable. Example:
inline int& getMyInteger()
{
    static int x;
    return x;
}

This definition can be in a header file, included into multiple *.cpp files, and any call to getMyInteger will return reference to the same object. You don't need any extern, nor to actually put the variable in any compilation unit as you would need with a simple namespace-scope variable. This trick just uses the linker's ability to de-duplicate inline functions.
See also: static variables in an inlined function question on StackOverflow.


text:
5V DC Mini Water Pump with Arduino Mega 2560?
First of all, it is my first topic and i want to say hi to you all!! Secondly, i am really a terrible noob and sorry for that  :(
I need to make a smart greenhouse project with Arduino Mega 2560, and i found a video to help me with my servomotor(MG996R) which will start working when raindrops module detect rain and 12v DC Fan which will start working when LM35 sensor calculates the weather as hot. However, my third actuator, 5V DC Mini Water Pump, which needs to become turned on when soil humidity sensor measures the soil as dry, is where i am left without an opinion. All the water pumps people use is 12 V, so i dont know which specific components i should use. I researched a bit and found that people use transistors and diodes for it. Which ones should i use and how to make the connections?
I would appreciate if someone helps me what components, specifically, should i buy and how to connect them together with Arduino 2560? It would be great if you can draw it, like with fritzing or something.
Thanks if you read this far :)

Welcome to arduino.stackexchange.com .
As motor is usually a high current load, controlling a switch to control the motor's power is the solution.
If you are not interested in h/w design just want to use a interface out of box you can use relay module like this relay. For only one load connection will be simple and I don't think Arduino current supply limit will be a problem.
see this answer for example connection using relay. It is almost similar use case I think. Also here is a Fritzing image using the relay in the first link. I have used four 3V battery pack as 12V source. It doesn't have to be battery.

If you like to do from scratch, you can use BJT(Bi polar junction transistor) or MOSFET.
Here is a possible schematic.

simulate this circuit – Schematic created using CircuitLab
Different power supplies are used for Arduino and Motor because recommended voltage range is 7-12V in Vin pin. Different sources, voltage levels like 5V from USB may be used according to your ease.
node b, c and e are base, collector and emitter of the BJT. Diode D1 is called flyback diode.
Let, the current needed for motor IL, motor voltage needed VL, collector current Ic and base current Ib and the resistor between arduino and base Rb. Note that IL = Ic
Operating mode of transistor will be saturation mode. So, the base current (supplied by arduino) will be,

Ibe = (current gain at saturation)*Ic

How to find the current gain? Look through the datasheet of transistor for hfe(sat) which is basically Ic/Ib at saturation mode. Some datasheet may use α instead of hfe(sat)
Then find the Vbe(sat) as you will be operating in saturation mode. Find the needed base resistor value Rb,

Ib = 5-Vbe/Rb

While designing this you have to be careful about these condition (I am talking about design using BJT)

Vce(max)(max) > VL
Ice(max) > IL
Arduino digital pin max I > Ib

All the devices should have same ground. Be sure to use the diode(D1) mentioned in the design as motor is an inductive load, sudden powering down may create large voltage across motor.


text:
White squares LCD display
for a school project I need to program a display. I've got in almost working.
I made a setup screen in the setup() that just says our groupname and the name of our project for 8 seconds (this works perfectly). After the 8 seconds, I used lcd.clear() and tried to type another line. But after the 8 seconds all it shows are 32 white squares. Anyone has any idea how to fix this?
#include <SoftwareSerial.h> // use the software uart

include <Wire.h>

include <LCD.h>

include <LiquidCrystal_I2C.h>  // F Malpartida's NewLiquidCrystal library

define I2C_ADDR       0x3F // Define I2C Address (use i2c scanner if >necessary)

define BACKLIGHT_PIN  3

define En_pin         2

define Rw_pin         1

define Rs_pin         0

define D4_pin         4

define D5_pin         5

define D6_pin         6

define D7_pin         7

define LED_OFF        0

define LED_ON         1

int x = 5;

/*-----( Declare objects )-----*/

LiquidCrystal_I2C
lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

SoftwareSerial bluetooth(10, 9); // RX, TX

int CurrentCommandASCII = 0; // dit is het commando in ASCII

char CurrentCommand ;// Hier wordt het commando omgezet naar Letters

void setup() {
  bluetooth.begin(9600); // start bluetooth

  Wire.begin();

  delay(200);

  Serial.begin(9600); // start seriele monitor

     pinMode(13, OUTPUT);

   digitalWrite(13, HIGH);

      lcd.begin (16,2);  // initialize the lcd

    // Switch on the backlight

    lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);

    lcd.setBacklight(LED_ON);

        // Reset the display

    lcd.clear();

    lcd.home();

    lcd.setCursor(4,0); // Start at character 0 on line 0

    lcd.print("Test");

    delay(1000);

    lcd.setCursor(5,1); // Start at character 0 on line 1

    lcd.print("Test");

    delay(8000);

 lcd.clear();

32 white squares: Is that the entire display, or just part of it? (how many characters can it display in total?) Perhaps the contrast should be adjusted?

Add your sketch.

Jose can u c It is a 16x2 display so indeed the whole screen is filled with white blocks. I btw use a lcd display with backpack. i tried adjusting contrast but it doesn't work

Please add a schematic as to how exactly everything is connected.

your code is incomplete


text:
Length of uint8_t* const array
I've an array of type uint8_t* const with 6 items, defined like this
uint8_t* const neighbourSet[] = {PEER1, PEER2, PEER3, PEER4, PEER5, PEER6};

Whereas each element in this array is static uint8_t defined like this
static uint8_t PEER1[] {0x86, 0xF3, 0xEB, 0x7A, 0xE8, 0x3B};
static uint8_t PEER2[] {0x86, 0xF3, 0xEB, 0x7A, 0xA1, 0x09};
static uint8_t PEER3[] {0x84, 0x0D, 0x8E, 0x03, 0x95, 0xED};
static uint8_t PEER4[] {0x84, 0x0D, 0x8E, 0x03, 0x99, 0xD5};
static uint8_t PEER5[] {0x80, 0x7D, 0x3A, 0xC5, 0x2B, 0x79};
static uint8_t PEER6[] {0x84, 0x0D, 0x8E, 0x03, 0x95, 0x1D};

When I do
  Serial.print("size:");
  Serial.println(sizeof(neighbourSet));

I get size:24. I am expecting the size to be 6. could someone explain ?
I don't want to hardcode the total number of PEER in a separate integer variable. I want my for loop to run through each element till the total size of array.
    for (int i = 0; i < sizeof(neighbourSet); i++) {
         //do something for each PEER.
         delay(50);
    }

uint8_t* is a pointer. on AVR it is 2 bytes. on 32bit architectures 4 bytes

you want const uint8_t* const neighbourSet?

Hint: sizeof() gives the number of bytes. You are looking for membersof(). It is often defined as #define membersof(x) (sizeof(x) / sizeof(x[0])).

int totalPeers = (sizeof(neighbourSet) / sizeof(neighbourSet[0])); worked. Thanks Mikael !

@MikaelPatel you should post that as an answer. I was going to post the same, but then I saw your comment.

sizeof() gives the number of bytes. You are looking for membersof(). It is often defined as:
#define membersof(x) (sizeof(x) / sizeof(x[0]))

And in the example above:
for (int i = 0; i < membersof(neighbourSet); i++) {
     //do something for each PEER.
     delay(50);
}

For more practical C/C++ macro and type extensions please see the Cosa Types.h file.

Sizeof doesn't work for pointers


text:
Accelstepper.runToPosition() is working fine. Accelstepper.run() does nothing
I have a complex sketch with Arduino Uno, Bluetooth Serial Com using altSoftSerial, serial com using SoftwareSerial and Serial communication with PC.
I want to move one stepper motor and stop it when a signal is received.
I use A4988 Pololu driver and NEMA 17 bipolar stepper motor.
This code is working fine.
      MyStepper.moveTo(position);
      MyStepper.runToPosition();
If I change the code to
      MyStepper.moveTo(position);
      MyStepper.run();
so that the running does not block my code the motor does nothing
Absolutely no movement.
The ground of the motor power supply is connected with the ground of Arduino. The motor is working fine with blocking movements.

read the library documentation for the run() function

You didn't include any code for us to see what the actual issue is, but I'm willing to guess that you didn't take into account that the run command requires repeated firing.
If your program comes to a point where there's an instance of runToPosition, the blocking function stops the program until the stepper reaches the position specified.
When your program comes to an instance of run(), it fires off a pulse and carries on reading. So you have to use a loop.
stepperMotor.moveTo(3000);
stepperMotor.runToPosition();
// reaches destination

stepperMotor.moveTo(3000);
stepperMotor.run();
// moves a single step

stepperMotor.moveTo(3000);
while (stepperMotor.distanceToGo > 0) {
stepperMotor.run();
}
// reaches destination

The reason you'd use run over runToPosition is to allow for continuous operations / parameters to be executed. For example, two stepper motors running simultaneously:
stepperMotor1.moveTo(5000);
stepperMotor2.moveTo(3000);
while ((stepperMotor1.distanceToGo > 0) && (stepperMotor2.distanceToGo > 0)) {
stepperMotor1.run();
stepperMotor2.run();
}
// Both motors will run, but will both stop when either of them reaches their destination.

Depending on the speed of your microprocessor, you can create some sophisticated instruction sets for your motor(s).

The problem is at blocking delays. The Run function is interrupted by any other action of program. So you have to call it all the time. A call to run is required in the loop and I wrote a simple mydelay function which solves the problem if you have to use delay for bluetooth communication or other purpose.
int mydelay(int j) {
  long endmillis;
  endmillis = millis() + j;
  while (millis() < endmillis) {
  MyStepper.run();
  }

I hope I help someone because it took me a while to figure this out as a newbie to Arduino.

i downvoted your answer because you wrote a blocking function to solve a problem caused by another blocking function ..... it may work for you, which is great, but blocking functions should be avoided .... i upvoted your question because you solved it yourself...... also, your solution suffers from the rollover bug and it may mess up after a 49 day run ..... read https://arduino.stackexchange.com/questions/12587/how-can-i-handle-the-millis-rollover

In my case I need to wait for bluetooth to send a whole string. If I send the string "12345", The if bluetoothserial.available() catches the 1, maybe 2, loses 3 4 5 which arrive in a few ms. I need a small delay about 10ms. My device is never going to work for 50 days that the clock timer will reset. Anyway this was the solution to my problem and I managed to move the stepper controlled by mobile, it moves smoothly and while it is moving I can change the target position and it will change it's direction with proper accelerations. I really couldn't find a better way and I searched a lot.

that is why i said that it is great that it works for you .... the reason for downvote is because other people will do research for a problem that they may have and they will find your answer ..... it is important that they think about possible problems if they adopt your solution

about the bluetooth comm ..... if you send a "12345", is there an end-of-line character like a CR or NL at the end?

Yes there is 12345#. Sometimes I send big strings GOTO#1500#. @jsotola Your question triggered my mind and I tried removing the delay and read until # is received. It did not work initially, then I added while incoming!="#", if bluetooth available read incoming and it works. I try to add code in the comment but Ctrl+K does not work so I won't add code for now.


text:
expected unqualified-id before '.' token
//my coding
#include<DHT.h>              // Including library for dht
#include<LiquidCrystal.h>
LiquidCrystal lcd(14,15,16,17,18,19);
#include<Timer.h>
Timer t;
#include <SoftwareSerial.h>
SoftwareSerial Serial1(2, 3);

#define dht_dpin 12
#define heart 13

DHT dht;

char *api_key="0UXHCZ777V0PAWPW";     // Enter your Write API key from ThingSpeak
static char postUrl[150];
int humi,tem;
void httpGet(String ip, String path, int port=80);

void setup()
{
 lcd.begin(16, 2);
 lcd.clear();
 lcd.print("   Humidity   ");
 lcd.setCursor(0,1);
 lcd.print("  Measurement ");
 delay(2000);
 lcd.clear();
 lcd.print("Circuit Digest ");
 lcd.setCursor(0,1);
 lcd.print("Welcomes You");
 delay(2000);
 Serial1.begin(9600);
 Serial.begin(9600);
 lcd.clear();
 lcd.print("WIFI Connecting");
 lcd.setCursor(0,1);
 lcd.print("Please wait....");
 Serial.println("Connecting Wifi....");
 connect_wifi("AT",1000);
 connect_wifi("AT+CWMODE=1",1000);
 connect_wifi("AT+CWQAP",1000);
 connect_wifi("AT+RST",5000);
 connect_wifi("AT+CWJAP=\"1st floor\",\"muda1884\"",10000);
 Serial.println("Wifi Connected");
 lcd.clear();
 lcd.print("WIFI Connected.");
 pinMode(heart, OUTPUT);
 delay(2000);
 t.oscillate(heart, 1000, LOW);
 t.every(20000, send2server);
}

void loop()
{
***DHT.read11(dht_dpin);     error in this line***
  lcd.setCursor(0,0);
  lcd.print("Humidity");
 **humi=DHT.Humidity;**   error in this line

  lcd.print(humi);   // printing Humidity on LCD
  lcd.print(" %    ");
  lcd.setCursor(0,1);
  lcd.print("Temperature");
**tem=DHT.Temperature;**  error in this line
  lcd.print(tem);   // Printing temperature on LCD
  lcd.write(1);
  lcd.print("C   ");
  delay(1000);
  t.update();
}

void send2server()
{
  char tempStr[8];
  char humidStr[8];
  dtostrf(tem, 5, 3, tempStr);
  dtostrf(humi, 5, 3, humidStr);
  sprintf(postUrl, "update?api_key=%s&field1=%s&field2=%s",api_key,humidStr,tempStr);
  httpGet("api.thingspeak.com", postUrl, 80);
}

//GET https://api.thingspeak.com/update?api_key=0UXHCZ777V0PAWPW&field1=0
void httpGet(String ip, String path, int port)
{
  int resp;
  String atHttpGetCmd = "GET /"+path+" HTTP/1.0\r\n\r\n";
  //AT+CIPSTART="TCP","192.168.20.200",80
  String atTcpPortConnectCmd = "AT+CIPSTART=\"TCP\",\""+ip+"\","+port+"";
  connect_wifi(atTcpPortConnectCmd,1000);
  int len = atHttpGetCmd.length();
  String atSendCmd = "AT+CIPSEND=";
  atSendCmd+=len;
  connect_wifi(atSendCmd,1000);
  connect_wifi(atHttpGetCmd,1000);
}

void connect_wifi(String cmd, int t)
{
  int temp=0,i=0;
  while(1)
  {
    lcd.clear();
    lcd.print(cmd);
    Serial.println(cmd);
    Serial1.println(cmd);
    while(Serial1.available())
    {
      if(Serial1.find("OK"))

      i=8;
    }
    delay(t);
    if(i>5)
    break;
    i++;
  }
  if(i==8)
  {
   Serial.println("OK");
        lcd.setCursor(0,1);
      lcd.print("OK");
  }
  else
  {
   Serial.println("Error");
         lcd.setCursor(0,1);
      lcd.print("Error");
  }
}

The arduino example seems to suggest you have the capitalization the wrong way around. Try  #include <dht.h> and dht DHT; instead.

You declare an object of type DHT and name dht. Then you try to call a method of DHT.read11().
Instead, you should be using the object name, dht.read11(), or as @Gerben points out, change the way you declare the object:  DHT dht;.


text:
ESP8266 deep sleep and MQTT
I am working on a project were I am putting my board into deep sleep mode, and it wakes up with an interrupt from a sensor.  When it wakes from deep sleep I would like to send a message to my MQTT broker.  The wiring works, the interrupt works, however, the code does not.
When I use the posted code, everything looks fine in the console, I get all my print statements which would make me assume it is working.  However, my MQTT broker does not show any messages.  But, if I move "sendMQTTMessage()" to the loop function it works fine and the messages come through to my broker.
Any suggestions would be greatly appreciated
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = "*";
const char* ss_pswd = "*";
const char* mqtt_server = "*";
WiFiClient EspClient;
PubSubClient client(EspClient);

void wifi_setup() {
  Serial.print("Connecting to: ");
  Serial.println(ssid);
  WiFi.begin(ssid, ss_pswd);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String ClientId = "ESP8266";
    ClientId += String(random(0xffff), HEX);
    if (client.connect(ClientId.c_str())) {
      Serial.println("connected");
      client.publish("outtopic", "hello world, finally");
      client.subscribe("/room/test");
    } else {
      Serial.print("failed, rc=");
      Serial.println(client.state());
      Serial.println("Try again...");
      delay(5000);
    }
  }
}
void sendMQTTMessage() {
  Serial.println("sending your message");
  if (!client.connected()) {
    reconnect();
  }
  client.publish("belmont/sensor/pir/hallway", "on");
}
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived: ");
  Serial.println(topic);
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
}
void setup() {
  Serial.begin(115200);
  wifi_setup();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  sendMQTTMessage();
  Serial.println("going into deep sleep");
  ESP.deepSleep(10 * 1000000);
}

void loop() {
//  sendMQTTMessage();
//  delay(5000);
}

messages come through to my broker ..... so, what is the actual problem and what is your question?

They only come through my broker, when I place "sendMQTTMessage()" inside of the loop function WITHOUT putting it into a deep sleep.  The minute I start using deep sleep I get no messages on broker.

does any of Attempting MQTT connection... get output?

try a delay after send

The answer for this actually goes to Juraj.  It was the fact that I was missing a delay.  In hindsight it makes sense, as even though I am competing tasks in order, the system is shutting down, before the actual message is sent.  I added a delay(1000) between the "sendMQTTMessage()" and "ESP.deepsleep()" and it worked.


text:
FIltering, FXOS8700, FXAS21002C optimization
I'm working on an inverse pendulum project, and am using an adafruit NXP_FXOS8700_FXAS21002 along with an Arduino due, and an esp8266 (two separate projects, same code however). I'm using a Magdwick filter, which works pretty ok, however I've noticed that small angle displacements (less than 0.1 rads) don't seem to show up. Since I'm working on the inverse pendulum, even the smallest of displacements need to be seen and I think my coding and/or filter is likely the culprit, Filtering of course is required, but it can't be too aggressive because it'll add a phase shift and my regulator won't work.
So My question is, is there a better way to filter/acquire my angle displacements/measurements than what I'm currently doing now? I did at one point completely remove the filter and calculate the angle via:
theta = atan2(ay, ax);

However there were angle "spikes" for lack of a better word during quick angle changes that caused the regulator to over compensate and be completely unstable
Here is my truncated code relevant to sensor and the Madgwick filter, however I can include if requested, the entire program.
update
As noted in the comments, I am using the the Adafruit implementation of the Madgwick filter. However I am of course completely willing to use another filter, (kalman?) or any other.
On top of that, here is a youtube video of the system hanging in the stable equilibrium, Here the regulator works in the current code implementation, however for small disturbances, the angle doesn't update accurately enough, in this position it doesn't matter, however in the inverse (angle Pi) this is critical and the cause of my initial question.
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Madgwick.h>
#define NXP_FXOS8700_FXAS21002
#include <Adafruit_FXAS21002C.h>
#include <Adafruit_FXOS8700.h>
Madgwick filter;
float offsetAngle, offsetOmega;
Adafruit_FXAS21002C gyro = Adafruit_FXAS21002C(0x0021002C);
Adafruit_FXOS8700 accelmag = Adafruit_FXOS8700(0x8700A, 0x8700B);

// Offsets applied to raw x/y/z mag values
float mag_offsets[3]            = { -1.28F, -39.23F, -1.78F };
// Soft iron error compensation matrix
float mag_softiron_matrix[3][3] = { {  0.940,  0.056,  0.012 },
  {  0.056,  0.932, -0.023 },
  {  0.012, -0.023,  1.146 }
};
float mag_field_strength        = 42.35F;
// Offsets applied to compensate for gyro zero-drift error for x/y/z
float gyro_zero_offsets[3]      = { 0.0F, 0.0F, 0.0F };

in setup()
  Serial.println(F("Adafruit AHRS Fusion Example")); Serial.println("");
  // Initialize the sensors.
  if (!gyro.begin())
  {
    /* There was a problem detecting the gyro ... check your connections */
    Serial.println("Ooops, no gyro detected ... Check your wiring!");
    while (1);
  }
  if (!accelmag.begin(ACCEL_RANGE_2G))
  {
    Serial.println("Ooops, no FXOS8700 detected ... Check your wiring!");
    while (1);
  }
 filter.begin(50);

And in void()
  sensors_event_t gyro_event;
  sensors_event_t accel_event;
  sensors_event_t mag_event;
  gyro.getEvent(&gyro_event);
  accelmag.getEvent(&accel_event, &mag_event);

  float ax = accel_event.acceleration.x;
  float ay = accel_event.acceleration.y;
  float az = accel_event.acceleration.z;

  // Apply mag offset compensation (base values in uTesla)
  float x = mag_event.magnetic.x - mag_offsets[0];
  float y = mag_event.magnetic.y - mag_offsets[1];
  float z = mag_event.magnetic.z - mag_offsets[2];

  // Apply mag soft iron error compensation
  float mx = x * mag_softiron_matrix[0][0] + y * mag_softiron_matrix[0][1] + z * mag_softiron_matrix[0][2];
  float my = x * mag_softiron_matrix[1][0] + y * mag_softiron_matrix[1][1] + z * mag_softiron_matrix[1][2];
  float mz = x * mag_softiron_matrix[2][0] + y * mag_softiron_matrix[2][1] + z * mag_softiron_matrix[2][2];

  // Apply gyro zero-rate error compensation
  float gx = gyro_event.gyro.x + gyro_zero_offsets[0];
  float gy = gyro_event.gyro.y + gyro_zero_offsets[1];
  float gz = gyro_event.gyro.z + gyro_zero_offsets[2];

  // The filter library expects gyro data in degrees/s, but adafruit sensor
  // uses rad/s so we need to convert them first (or adapt the filter lib
  // where they are being converted)
  gx *= 57.2958F;
  gy *= 57.2958F;
  float gzz = gz * 57.2958F;
  // Update the filter
  filter.update(gx, gy, gzz, ax, ay, az, mx, my, mz);
  theta = ((filter.getPitch() * (PI / 180)) - PI / 4);

I greatly appreciate the help!

Do you use this: https://github.com/adafruit/Adafruit_AHRS Please add a link to that in your question. Some sensors have a filter inside to reduce noise. Can you test the raw values from the sensors? All the libraries and the calculations are with float, you gonna lose some accuracy. The Arduino Due can use double precision. There is a weird calculation in invSqrt. Can someone look into that to see if that bit operation on a float is correct? https://github.com/adafruit/Adafruit_AHRS/blob/master/Madgwick.cpp#L231 Where are the sensors located? Can you show a photo or draw a picture?

Ah, yes that was my madgwick implementation, I will add it to the question...I did mention that in the question, I did use raw accel values to calculate the pitch, resulting in a 'spike' for lack of better word before the actual angle is then correctly displayed/calculated.
Yes, I will add a photo/video.

An accelerometer is sensitive for small changes and vibrations (and is noisy). The gyro drifts. When also a magnetometer is added, the AHRS filter can make a good steady output. The AHRS filter is for objects like a plane. You only need the angle (in one dimension).

Ahh, yes, actually that makes sense, my system is a 1 dof system, in reality I only need the angle...the suggestion would be to only filter the resulting calculated angle from atan2? to reduce noise? or filtering the accel ax and ay components then calculating?

Is the module powered with 3.3v? Are sda and scl the pink and grey wires? Then please split those wires, the i2c bus has troubles with crosstalk. How long are the wires to the esp8266? If the i2c fails, will that be detected? I think that the main problem is the motor vibrations. The accelerometer is very sensitive for that. The magnetometer might also be influenced by the motor. That adds up to 7 possible problems, and I might have overlooked the real cause.

I don't have the machine in front of me at the moment, however, I will look at all your mentioned points, and also capture some screen shots and consider a more specific question, though, I'll wait a bit and see if someone has an answer. Thanks for the suggestions!

I was hoping that someone else joined, but so far no luck. There is too much going on. You can wait for someone else. You could try to eliminate a few possible problems in your project. For example dampen the motor or the sensor with rubber/foam for a test. You have to be sure that i2c problems are detected and that you always get real data from the sensor. Perhaps the magnetometer does more harm than good due to magnetic noise by the motor. You might start a new question how to measure the angle better. Perhaps there are precise rotary encoders.


text:
Can't add board for RFDuino in Arduino IDE
I tried to upload sketch to my RFDuino. I can select the RFDuino port. But I can't upload cos I can't select the RFDuino board.
I followed the installation steps listed here
but I don't see RFduino package in Board Manager after I finished the steps above.
I am using Mac Mojave and Arduino IDE v1.8.9. I have tried it with v1.6.6 but results the same.

I get Error downloading http://rfduino.com/package_rfduino166_index.json

the company RFDigital is gone. no support. try a manual install

I had this problem with STM32 package. Go to Arduino15 folder(%appdata%) and delete download cache

@SilvioCro, did you try it?

@Juraj When I did those steps(in my case it was STM32 package - this link, it worked. Go AppData\Local\Arduino15 and delete package_index.json.sig and package_index.json files

@Juraj No. Sorry, I was on the phone(when I wrote 1st comment) so it was messy. My bad.

Turns out that rfduino.com's domain is gone, so the link will always return with an error downloading. After reading this thread arduino.cc, @pert posted a link for the .json file that used to be at the website you have. I used this link on MacOS Mojave and Arduino v1.8.9 and it worked perfectly!


text:
Combining 2 sensors in one code with 1 push button
I am trying to create a circuit with one tactile pushbutton, and LCD and two sensors: 1) temperature, and 2) pulse sensor. When the circuit is on, the LCD initially shows the reading from the temp sensor, when the button is pressed the LCD shows the reading from the pulse sensor.
The code compiles, the LCD shows both of the temperature function and pulse reading work.
I attached a picture of the schematic of the circuit.
The problem is that when the button is pressed, it takes many pushing of the button for the circuit to go from temperature reading to pulse reading. I thought maybe debouncing the button was unnecessary so I tried to write a code without the code, but it made no difference. My coding skills are still in the beginner side but I am trying my best for my coding to make sense. I just need some guidance and advice on what the problem could be and how I can tackle the problem. My code is attached here:
#include <LiquidCrystal.h>
#define BUTTON 2

const int rs = 12, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4;
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

//TEMPERATURE
const int tempPin = A0;              // LM35 in A0

int T1=60;

//PULSE
#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.

int PulseWire = A1;                 // Pulse Sensor purple wire connected to analog pin A0
int blinkPin = 13;                // pin to blink led at each beat
int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
// Use the "Gettting Started Project" to fine-tune Threshold Value beyond default setting.
// Otherwise leave the default "550" value.
PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"

//=========BUTTON DEBOUNCE============
boolean lastButton = LOW;     // last button state
boolean currentButton = LOW; // current button state
int switchMode = 1;             //cycle between function
//====================================
void setup()
{

  lcd.begin(16, 2);
  // Configure the PulseSensor object, by assigning our variables to it.
  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.

  }//end if

}//end void setup()

//Debouncing Function
boolean debounce(boolean last) {
  boolean current = digitalRead(BUTTON);
  if (last != current)
  {
    delay(T1);         //wait #ms
    current = digitalRead(BUTTON); //read it again
  }//end if
  return current;     //return the current value
}//end boolean debounce

void setMode(int mode) {

  //TEMP ON
  if (mode == 1)
  {
    Serial.begin(9600);
    int value = analogRead(tempPin); // read the value from the sensor
    lcd.setCursor(0, 1);
    float millivolts = (value / 1024.0) * 5000;
    float celsius = millivolts / 10;
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Temp = "); lcd.print((celsius * 9) / 5 + 32);  lcd.print((char) 223); //turning the celsius into fahrehait
    lcd.print("F");
    lcd.setCursor(7, 2);
    lcd.print(celsius); lcd.print((char) 223);
    lcd.print("C");
    delay(1600);

    lcd.clear();
    delay(T1);
  }//end if TEMP ON

  //RED ON
  else if (mode == 2) {
    {
      Serial.begin(9600);
      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("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
        Serial.print("BPM: ");                        // Print phrase "BPM: "
        Serial.println(myBPM);                        // Print the value inside of myBPM.

        lcd.setCursor(0, 0);
        lcd.print("HeartBeat Found!");
        lcd.setCursor(4, 1);
        lcd.print("BPM: "); lcd.print(myBPM);

        delay(1600);
        lcd.clear();
        delay(T1);
      }//end if
    }//end setMode void function
  }
}
    void loop()
    {
      currentButton = debounce(lastButton); //read debounced state
      if (lastButton == LOW && currentButton == HIGH) /// if it was pressed
      {
        switchMode++;
      }
      //if cycled through the different options,
      //reset the counter to 0
      if (switchMode == 3) switchMode = 1;
      setMode(switchMode);
    }//end loop

I also considered doing a switch case statement, but so far it hasn't worked either. Please let me know some ideas!
Thank you!!

While we wait for 1 more person to approve the edits made to this question...  @LG_18, You need to research what a state machine is and apply that to de-bouncing your button.

the code that you posted does not compile (@matej made some corrections) ..... i think that the code on your computer also does not compile ...... i also think that you are editing your code, and you think that you are compiling and uploading after the edit, but the compile fails and your arduino does not get updated with a new sketch ..... then you run a test on the arduino and it still behaves as it did before

Your code has various issues, but the main one is that you can’t use delay() when you’re trying to more than one thing at a time. Delay causes your program to freeze, and not do anything else.
(Basically you should forget about the delay() function and never write any Arduino code that uses it. It is a code smell.)
You need to rewrite your code to record the value of millis() and then check back the next time through your loop function to see if enough time has passed. Do a Google search on “Arduino blink without delay” for an explanation of how to do this. Here’s an example article: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/using-millis-for-timing
(Note that some solutions suggest that you increment a counter every time through your loop and see if some magic number of counts has gone past based on how frequently you expect your loop to be called. That is a bad approach. You want to use the millis() function.

Also note that you should not call Serial.begin() more than once in your program. You should put that code in your setup function.

Your loop function needs to call debounce() and setMode() as often as possible, and none of your functions must use delay(). Instead, they compute the time elapsed since the last action, and if it is greater than what you now use as a delay value, perform its next action; otherwise, it should just return.
Just as a curiosity, your present code will probably function (better...) if you press and hold the button until you get a response, instead of press-and-releasing multiple times, hoping to get one. The latter way depends on your pressing the button just as the system is reading it, but the system reads it too infrequently for that to be workable, as you found out. The delay() calls are the reason.


text:
Can't Interface SIM900a With Arduino Uno
I've got the following module of SIM900a.

My connections are:
VCC -> External 5 Volt 1.5 Amp Supply
GND -> Common GND
TX -> Arduino RX (Pin 0)
RX -> Arduino TX (Pin 1)

I hear a ring when I call on the sim card that has inserted there. So it can register to a network successfully. I've uploaded a blank code in Arduino Uno to test AT Commands. But I'm not getting any response when I type AT on Serial Monitor. What am I doing wrong here?

Share some code with us!

I've uploaded the blank code for testing AT commands.

maybe the baud rate is incorrect

I've tried all different baud rates. No luck :/

At first, make sure that the sim has connected to the network. For this, you can call to the sim number from another phone. If not ringing that means the sim wasn't able to connect with the network. For this check power supply, antenna etc. If ringing then there something wrong in connection or code. So cross check the connection and send AT to the module and wait for returned data. If no data returned, then there check connection again. If the returned data is OK, then it is ready to use. and if returned data is ERROR then Arduino have connected to sim module but sim network, power supply etc problem happening.

I've already mentioned in the question that I can hear a ring back.

I think you use hardware serial for communicating with pc for serial monitor and gsm. For this, it may conflict with each other. Try to use SoftwareSerial.h for gsm communication.

I was facing the same issue and solved this issue when I have used softwareSerial.h library and used to connect TXD of sim900A with pin 13 and RXD of sim900A withpin 12 of ardunio MEGA.
You can also use 10 and 11 pins of mega instade of 12 and 13 i.e.
#include <SoftwareSerial.h>      // Configure software serial por
SoftwareSerial SIM900A(10, 11);  // (sim 900 connections RXD=>10 & TXD=>11)