text:
Arduino code to control 4 led's from 4 buttons
This is my very first arduino sketch and it's causing me a bit of a headache.
Sounds so simple really all I want the sketch to do is digitalread from one of 4 digital input pins and then digitalwrite to one of 4 output pins in essence.
So that when button 1 is pressed LED 1 lights up, button 2 pressed led 2 lights up and so on.
I've added a serial write so I could check that the buttons are actually working when pressed.
The code I've written:
const int buttonPin1 = 7;     // number of pushbutton 1 pin
int buttonState1 = LOW;       // set the default variable value for pushbutton1 status
const int ledPin1 =  6;       // number of the LED 1 pin
const int buttonPin2 = 8;     // number of pushbutton 2 pin
int buttonState2 = LOW;       // set the default variable value for pushbutton2 status
const int ledPin2 =  9;       // number of the LED 2 pin
const int buttonPin3 = 4;     // number of pushbutton 3 pin
int buttonState3 = LOW;       // set the default variable value for pushbutton3 status
const int ledPin3 =  5;       // number of the LED 3 pin
const int buttonPin4 = 2;     // number of pushbutton 4 pin
int buttonState4 = LOW;       // set the default variable value for pushbutton4 status
const int ledPin4 =  3;       // number of the LED 4 pin
void setup() {                  // Set Pins to Outputs Or Inputs
  pinMode(buttonPin1, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin1, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin2, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin2, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin3, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin3, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin4, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin4, OUTPUT);     // initialize the LED pins as an outputs:
  Serial.begin(9600);           // initialize serial communication at 9600 baud
}
void loop() {
buttonState1 = digitalRead(buttonPin1);  // read current states of the pushbutton value:
  buttonState2 = digitalRead(buttonPin2);  // read current states of the pushbutton value:
  buttonState3 = digitalRead(buttonPin3);  // read current states of the pushbutton value:
  buttonState4 = digitalRead(buttonPin4);  // read current states of the pushbutton value:
// check if the pushbutton is pressed buttonState# == HIGH/LOW
  // if pressed change buttonState == HIGH to turn on ledPin#
  // else if buttonState == LOW then digitalWrite(ledPin#, LOW) Keeps Led off.
if (buttonState1 == HIGH) {    //check buttonState
digitalWrite(ledPin1, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin1, LOW);   // turn LED off:
}
Serial.println(buttonState1); //Print buttonState to serial
if (buttonState2 == HIGH) {   //check buttonState
digitalWrite(ledPin2, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin2, LOW);   // turn LED off:
delay(10);
}
Serial.println(buttonState2); //Print buttonState to serial
if (buttonState3 == HIGH) {   //check buttonState
digitalWrite(ledPin3, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin3, LOW);   // turn LED off:
delay(10);
Serial.println(buttonState3); //Print buttonState to serial
}
if (buttonState4 == HIGH) {   //check buttonState
digitalWrite(ledPin4, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin4, LOW);   // turn LED off:
delay(10);
Serial.println(buttonState4); //Print buttonState to serial
}

The Leds all have a common GND and the buttons all have a common GND.
Buttons are connected to +5V & Input pin# so one terminal has got two wires,
Led's are connected to digital output pins then resistor and straight to GND.
What happens is that ALL of the LED's come on when any one of the 4 buttons in pressed.
I've attempted to edit some of the code in the example sketches to get this to work.
Can anyone suggest anything that I'm doing wrong?
Or ammend the code sp that I can see where I'm going wrong.

They way you have wired the buttons is probably not right. They also require resistors or else the digital input is open when a button is not pressed. An open input can do anything, it can even go along with a nearby pin.

It is likely you have connected the switches incorrectly.  Normally, people use single poll single throw (SPST) switches connected to 5 volts and the input pin of the Arduino.  This will pull the input pin to 5 volts when the switch is closed.  Then, to pull the input pin to ground when the switch is open, people add a large resistor between ground and the same processor pin.

Almost any large resistor will work here.  Consider using 10K ohms (10,000 ohms) or there abouts.
Of course, if you are using a 3 volt Arduino, do not connect the switch to a 5 volt source.  Instead connect it to a 3 volt source.
Alternatively, a pull up resistor inside the processor, if available, can be activated.  Look at this arduino.cc web page. There this sample code shows how to activate the processor's pull up on pin number 2:
pinMode(2,INPUT_PULLUP);

Because not all processors have a "pull up" feature on all input pins & because the range of internal to the processor pull up resistances can vary (for example 50,000 ohms to 150,000 ohms), it may be more useful and universal to use an external pull up resistor.

That's obviously the problem, the reisitor I'm using on switches isn't big enough. They are wired exactly as above except I'm not using a 10k resistor. It's of a smaller value. without cracking the multimeter out I can't remeber off the to of my head what rating I used. Does the code look alright though? I've broken it down into logical steps and done a flow chart to work out the logic. So was hoping that there was nothing wrong with the code.....

Didn't see any obvious problems with the code.  But you should always start with something simple that works then build from there.  The 10ms delays will not make much difference.  Likely it will take longer to print out the serial data.

Using a smaller resistor should work as well.  But this will uselessly increase the current draw.  It is possible you have used such a small resistor that you have exceeded the current capacity of your power supply or batteries.  In such a case the voltage will drop and cause unexpected results.  In extreme cases you can cause damage.

"Normally, people use single poll single throw (SPST) switches connected to 5 volts and the input pin of the Arduino. "  No, normally th internal pullup resistor is used, and the button only connectst the pin to Gnd.

Get rid of the external resistors, use the internal pullup resistor.
In setup():
pinMode (pinX, INPUT_PULLUP);
Wire the button between input pin pinX and Gnd, then test for a LOW to see if the button is pressed in loop():
if (digitalRead (pinX) == LOW){ // button is pressed
// do something
}
else { // button is not pressed
// do something else
}

I would suggest taking the resistor/s off the switches, so the button connects to digital inputs to the 3v/5v line. Then use 470ohm resistors for the leds(to limit the current) on the digital outputs.


text:
Purpose of this resistor in Arduino Nano schematic
I was looking at the Arduino Nano's schematic and noticed a resistor that seems to be pointless (RP2C on this picture).

Also there is numbers 6 and 3 on it, does it mean that resistor is connected to pins 6 and 3 on FT232 or to the same pins on Atmega328?

I have very limited electric knowledge.. I seen on some circuits a small capacitor between VCC and GND (pins 6 and 3), but never a resistor without any other component in between.

It's an unused element of resistor array RP2. Both ends are grounded in order to reduce noise.

I get it now, thanks! And numbers represent pins of the resistor array.

What noise are you talking about?

https://en.wikipedia.org/wiki/Johnson%E2%80%93Nyquist_noise

@IgnacioVazquez-Abrams, for better clarity: I think what you mean to say is: "Because this resistor in the array is unused, both ends are grounded in order to reduce noise." Right?

The resistor is one of 4 resistors that make up an SMD resistor array, RP2. It is seen on the board here:

The resistor array works like this:

The resistor on this array is spare, so both terminals are grounded.

Can you please provide me any link regarding this resistor array,mine got faulty.I need to replace it!

The marking says 102 so that means each resistor in the array is 1k ohms. The size looks like a 1206 package. Digikey: https://www.digikey.com/product-detail/en/panasonic-electronic-components/EXB-V8V102JV/Y4102CT-ND/155159, RS/Allied: http://au.rs-online.com/web/p/array-resistors/5225406/, Farnel/Newark/Element14: http://au.element14.com/vishay/cra06p0831k00jta/resistor-resistor-array-1kohm/dp/1886553

Best answer: this part you said is key for my understanding: "The resistor on this array is spare, so both terminals are grounded."

source: Stack Exchange

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

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

sort: votes


text:
Use callbacks in Arduino with pointers to functions (will functions persist in memory?)
As I been learning Arduino (micro controllers, c++, etc) I have learned that memory is very limited. I already understand how memory works when it comes to variables. But I do not understand how memory works when it comes to functions. Since I am a backed developer I try to stay away from interrupts and instead use callback functions. Another reason why I prefer to use callback functions is because I love the visual studio IDE. I create my core functionality of whatever project I am building on a c++ project targeted for Windows. Once my algorithms/logic works the way I want it I reference those libraries on Arduino.
Anyways I am using lambdas to pass functions to my helper libraries. That way I do not use the delay function to wait for a response and I am always listening for events. Basically my question is if it is correct to have code like this (function SendEvent):
/* MyRadioLibrary.h */
// I am not including all the code of `MyRadioLibrary` because that makes it hard to
// understand what I am asking. Instead I will try to use a lot of pseudo-code. Let me
// know if you want me to post the code as an edit.

class MyRadioLibrary
{

public:

    static void SendEvent(int typeOfEvent, void(*onEventCompleted)(bool x))
    {
        // I have an array of pointers to functions
        void(*onEventCompletedBuffer[10])(bool x);

        // I enqueue that event with a queue helper class

        // Send event ....

        // DO NOW WAIT FOR RESPONSE SINCE CALL BACK IS ALREADY SAVED
    }

    static void loop() {

         // listen for radio messages
         if(radio.available()){
                // get response
                // dequeue pointer to call back
                // execute call back
          }

    }
};

And my arduino sketch contains this code:
#include <MyRadioLibrary.h>

void setup()  {
    // setup pins etc..
}

void loop()
{

    if (isButton1Pressed())
    {
        MyRadioLibrary::SendEvent(1, [](bool didEventCompletedSuccessfully) {

            if (didEventCompletedSuccessfully)
            {
                // turn on green LED
            }
            else {

                // turn on red led
            }

        });
    }
    else if (isButton2Pressed())
    {
        MyRadioLibrary::SendEvent(2, [](bool didEventCompletedSuccessfully) {

             // call back function

        });
    }

    MyRadioLibrary::loop(); // listen for response events. When we get one fire call back.
}

Now the question
When I call the SendEvent function I am passing 2 things (1) an integer and (2) a pointer to a function that is the call back. The integer (1) is passed as value and that will be part of the stack of the SendEvent function. The pointer (2) will be stored on an array of pointers. But what about the lambda function? where will that be stored? Instead of using a lambda function should I declare those functions in global scope and pass the global function instead of a lambda? Will I run the risk of the pointer (2) pointing to a function that no longer exists if I use this way of coding?

Re “pass the global function instead of a lambda”: Once it's translated into machine code, it makes no difference whether it's a lambda or a regular function.

Your functions won't cease to exist. All of the code in your compiled and linked code image gets loaded into code-memory (Flash) and it stays there throughout the run, through resets, and through power-cycles, until another image is loaded over it.
Are you confusing pointers to functions with pointers to a function's local variables which occupy RAM memory, specifically within the function's stack-frame which is transient, being created and "destroyed" as the function gets called and returns - and successive stack-frames won't necessarily be created in the same place.

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


text:
ESP32 open "captive portal" on connected
I am using the default example SimpleWiFiServer that comes as an example from the ESP32:
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>

#define LED_BUILTIN 2   // Set the GPIO pin where you connected your test LED or comment this line out if your dev board has a built-in LED

// Set these to your desired credentials.
const char *ssid = "MyNetwork";
//const char *password = "YourPassword";

WiFiServer server(80);

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);

  Serial.begin(115200);
  Serial.println();
  Serial.println("Configuring access point...");

  // You can remove the password parameter if you want the AP to be open.

  //tcpip_adapter_dns_info_t dns_info;
  //dns_info.ip.u_addr.ip4.addr = IPAddress(192,168,4,1);
  //tcpip_adapter_set_dns_info(TCPIP_ADAPTER_IF_AP, TCPIP_ADAPTER_DNS_MAIN, &dns_info);

  WiFi.softAP(ssid);
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
  server.begin();

  Serial.println("Server started");
}

void loop() {
  WiFiClient client = server.available();   // listen for incoming clients

  if (client) {                             // if you get a client,
    Serial.println("New Client.");           // print a message out the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        if (c == '\n') {                    // if the byte is a newline character

          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println();

            // the content of the HTTP response follows the header:
            client.print("Click here to turn ON the LED.
");
            client.print("Click here to turn OFF the LED.
");

            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            break;
          } else {    // if you got a newline, then clear currentLine:
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }

        // Check to see if the client request was "GET /H" or "GET /L":
        if (currentLine.endsWith("GET /H")) {
          digitalWrite(LED_BUILTIN, HIGH);               // GET /H turns the LED on
        }
        if (currentLine.endsWith("GET /L")) {
          digitalWrite(LED_BUILTIN, LOW);                // GET /L turns the LED off
        }
      }
    }
    // close the connection:
    client.stop();
    Serial.println("Client Disconnected.");
  }
}

That initializes the ESP32 as an Access Point. On my phone I am able to see the network MyNetwork. If I connect to it and then open a my browser and go to 192.168.4.1 I am able to see the default page.
How can I change that code so that when I connect to that network it automatically open my browser going to http://192.168.4.1 ?
When researching on the internet I found this library that does that WiFiManager . That library helps you connect to an existing WiFi network. I do not want to do that. I only want that when I connect to MyNetwork my default page opens up just like when you connect to guest networks on hotels etc.
Other people on the internet have modified WiFiAPP.cpp and added these three lines of code:
tcpip_adapter_dns_info_t dns_info;
dns_info.ip.u_addr.ip4.addr = IPAddress(192,168,4,1);
tcpip_adapter_set_dns_info(TCPIP_ADAPTER_IF_AP, TCPIP_ADAPTER_DNS_MAIN, &dns_info);

That only makes my esp32 crash and does not work.
Has someone figure out a simple way to open a popup window (captive portal) pointing to http://192.168.4.1 once you connect to the ESP32 access point?
Lastly I found this example but that is using esp8266.

How you get things like automatic browser opening on an wifi connection event to happen depends on your operating system. It's not something I have ever heard of. The normal thing to do is set up a "captive portal" that redirects all requests to itself, so you open a browser and wherever you try and go to it responds with the portal page. There's an example in the bundled DNSServer library that does that.

Sorry I meant to say "captive portal" English is not my first language. @Majenko

@Majenko i have an Android v8 phone ... at AP connection it automatically browses to the captive portal page ... my previous phone required manual browsing to any unencrypted (http:) webpage

@jsotola That's usually something the phone does by itself. Apples try opening the page http://captive.apple.com/hotspot-detect.html and if it returns anything other than "Success" it opens the browser for you to log in.

@Majenko♦ i understand that the phone does it on its own ... i misunderstood your first comment ... thanks for the useful apple.com link

Thanks to @Majenko I was able to find what I was looking for on the internet from this link. When I googled "captive portal" instead of the phrases that I was using I found a lot more examples.
This code opens a "captive portal" once I connect to the esp32 access point.
#include <WiFi.h>
#include <DNSServer.h>

const byte DNS_PORT = 53;
IPAddress apIP(192, 168, 1, 1);
DNSServer dnsServer;
WiFiServer server(80);

String responseHTML = ""
  "<!DOCTYPE html><title>CaptivePortal</title>"
  "
Hello World!

This is a captive portal example. All requests will "
  "be redirected here.
";

void setup() {
  WiFi.disconnect();   //added to start with the wifi off, avoid crashing
  WiFi.mode(WIFI_OFF); //added to start with the wifi off, avoid crashing
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
  WiFi.softAP("DNSServer CaptivePortal example");

  // if DNSServer is started with "*" for domain name, it will reply with
  // provided IP to all DNS request
  dnsServer.start(DNS_PORT, "*", apIP);

  server.begin();
}

void loop() {
  dnsServer.processNextRequest();
  WiFiClient client = server.available();   // listen for incoming clients

  if (client) {
    String currentLine = "";
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (c == '\n') {
          if (currentLine.length() == 0) {
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println();
            client.print(responseHTML);
            break;
          } else {
            currentLine = "";
          }
        } else if (c != '\r') {
          currentLine += c;
        }
      }
    }
    client.stop();
  }
}

When providing HTTP server you generally have two options:

Using WebServer class and set handlers for roots. The parsing and handling of HTTP header is done by the library.
Use WifiServer and receive the HTTP message with header included and handler everything by your own.

If you are doing number 1 and pretend using by connecting with an Android device I suggest adding a handler for the error case showing the captive portal:
server.onNotFound(handleRoot);

I noticed that for Android 10, to properly detect the captive portal and make the phone to show "Touch to log in the network" message is necesary. If not you must navigate to any HTTP address and let the DNS do the job for you (not HTTPS).


text:
Binary to decimal using bitwise operators
I am trying to convert some binary data to decimal numbers. I succeeded to convert binary to hex, but now I want to do the same with binary to decimal. I want to use bitwise operators and NO array.
See my code from binairy to hex. The incoming data is 8 bits. This code first calculates the most significant number, and then, the least significant number. This works good, but I cannot figure it out for bin to dec
The function console_print_char is sort of the printf function of my program.
    void console_print_hex_char(unsigned char data){
    unsigned char temp;

    if(data){
        temp = (data >> 4);
        if(temp){
            if(temp> 9) console_print_char(temp + ('A'- 10));
            else console_print_char(temp + '0');
        }
        temp = data & 0x0F;
        if(temp> 9) console_print_char(temp + ('A'- 10));
        else console_print_char(temp + '0');
    }
    else{
        console_print_char('0');
    }
}

your question is a general programming question that is not related to the Arduino ... please delete your post and go here https://stackoverflow.com/questions

note: you have a stray }, that is outside of the "code area"  of your post

@jsotola is right, you might need to push this over to SO. Anyway, the conversion of a binary number into decimal is most simply done with modulo (%) and divide (/) if you don't want to use library functions. Additionally, there is an algorithm that involves shifting bit by bit, and some conditional adding of 3. Unfortunately I don't have an URL at hand.

Binary is spelled B-I-N-A-R-Y. It's bi-na-ry, not bin-air-y.

You can google Binary to BCD conversion. There are pretty short algorithms that do this. After the conversion each decimal digit is stored in a nibble.

You cannot do what you are trying to do. There is no direct correspondence between some number of bits and a decimal digit.
With hexadecimal, every 4 bits corresponds to exactly 1 hex digit. That is why hex is used for computers.
One hex digit represents exactly 4 bits. Every time you add another hex digit, you add 4 bits.
Two hex digits corresponds to exactly a byte. 00h to FFh represents a value from 0 to 255.
There is no such direct correspondence between binary and decimal. If you have 4 bits, it takes 1 or 2 decimal digits to represent it (0-15) If you have 8 bits, it takes 1, 2, or 3 decimal digits to represent it, but there are 3 digit decimal values (values > 255) that you can't represent with 8 bits.
Binary  Hex Decimal
0000    0   0
0001    1   1
0010    2   2
0011    3   3
0100    4   4
0101    5   5
0110    6   6
0111    7   7
1000    8   8
1001    9   9
1010    A   10
1011    B   11
1100    C   12
1101    D   13
1110    E   14
1111    F   15

You simply cannot convert a binary number to decimal using bit shifting and masking.
As @Kwasmich says in their answer, the closest you're likely to come would be to convert your binary value to BCD (Binary coded decimal) where each 4 bits holds a decimal digit. You could convert THAT to decimal character output using masking and shifting.

here's the c++ code
    vector<int> b={1,0,1,0,1,0,1};
        int sum=0;
        for(int i=b.size()-1, j=0; i>=0; i--, j++){
            sum+=b[j]*(1<<i);
        }
        return sum;

That is a way to convert a series of bits to decimal. Note the it uses multiplication and arrays, both of which the OP wants to avoid.

BTW, it's silly to use b[j] * (1<<i). That's an unneeded multiplication. Just use sum += b[j]<<iIfb[j]is 0, it shifts nothing for that bit. Ifb[j]` is a 1 bit, it shifts a one to the appropriate magnitude, without the need of a multiply.


text:
Why does analogRead(A0) deliver different Values when called in a library file vs calling it in the sketch directly
I wanted to write a library representing a sensor to later on have an array of sensors.
I generated a file MoistureSensor.h:
#ifndef MoistureSensor_h
#define MoistureSensor_h

#include <Arduino.h>

class MoistureSensor {
  private:
    uint8_t sensPin;
    int sensValue;
    int sensId;

  public:
    MoistureSensor(uint8_t pin,int id);
    int getValue();
    int getId();
};

#endif

and MoistureSensor.cpp:
    // MoistureSensor.cpp
#include "MoistureSensor.h"

MoistureSensor::MoistureSensor(uint8_t pin, int id) {
  sensPin = pin;
  sensId  = id;
}

int MoistureSensor::getValue() {
  sensValue = analogRead(sensPin);
  return sensValue;
}
int MoistureSensor::getId() {
  return sensId;
}

this is the main sketch running on a Arduino Mega:
#include "MoistureSensor.h"

MoistureSensor sens1("A0", 1);

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

void loop() {
  Serial.println("Value from analogread:");
  Serial.println(analogRead(A1));
  Serial.println("Value from library:");
  Serial.println(sens1.getValue());
  Serial.println("End");
  delay(1000);

}

So when I run this the serial monitor shows:
Value from analogread:
600
Value from library:
496
End

Why doesn't this print the same value?
Does the .cpp file interpret the data from analogRead() different than the sketch?
Also both values where moving up and down depending on the response of the sensor.
Thanks in advance.

it should be MoistureSensor sens1(A0, 1);, not MoistureSensor sens1("A0", 1);. we don't write analogRead("A0")

In simple terms it has to use more memory to call the library. When you read it in the sketch it is one line. If in a library function you have to call the library, this causes the system to save its location in RAM then it executes the instruction. You are doing many more instructions with the library.

Trying to compile your sketch, I get the following compiler warning:
warning: invalid conversion from 'const char*' to 'uint8_t {aka unsigned char}'
 MoistureSensor sens1("A0", 1);
                             ^
note:   initializing argument 1 of 'MoistureSensor::MoistureSensor(uint8_t, int)'

This means that, whereas the MoistureSensor() constructor expected its
first argument to be of type uint8_t, you provided a const char*
instead. Indeed, a string literal like "A0" decays to a const char*
pointer when you pass it as a function argument.
The fix is to pass the actual pin number to your constructor:
MoistureSensor sens1(A0, 1);

But then, there is a second issue. In your test sketch, you have your
MoistureSensor object read A0, whereas the direct analogRead()
reads pin A1. If you want to get the same value, you should read the
same pin.
Side note: the change from uint8_t to byte has absolutely
nothing to do with your issue. These two types are synonyms.

I found a solution:
changing the parameter of the constructor
MoistureSensor::MoistureSensor(uint8_t pin, int id, int rawMax, int rawMin)`` from uint8_t tobytesolved this issue for me. I also changed the parameterization to MoistureSensor sens1(1, 1);`

there is no difference between byte and uint8_. it just a different name for the same thing.


text:
Sparkfun CCS811 Air Quality Sensor is just not working
I have an Arduino Uno board and a SparkFun ccs811 sensor. I tried to reproduce the howto from the SparkFun homepage (https://learn.sparkfun.com/tutorials/ccs811-air-quality-breakout-hookup-guide?_ga=2.45231532.967238096.1560976781-258902726.1560976781), including the error states part.
I uploaded one picture of the wiring (updated). I also tried to use an alternative hardware connection with SDA to A4 and SCL to A5, as mentioned in the code comments (see homepage).
However, it is just not working, and I always get this error code in the serial monitor beginCore exited with: I2C_ERROR
Here is my code (without the top comment block):
#include <Wire.h>

#include "SparkFunCCS811.h" //Click here to get the library: http://librarymanager/All#SparkFun_CCS811

#define CCS811_ADDR 0x5B //Default I2C Address
//#define CCS811_ADDR 0x5A //Alternate I2C Address

CCS811 mySensor(CCS811_ADDR);

void setup()
{
Serial.begin(9600);
Serial.println("CCS811 Basic Example");

Wire.begin(); //Inialize I2C Harware

//It is recommended to check return status on .begin(), but it is not
//required.
CCS811Core::status returnCode = mySensor.begin();
Serial.print("beginCore exited with: ");
switch ( returnCode )
{
case CCS811Core::SENSOR_SUCCESS:
 Serial.println("SUCCESS");
 break;
case CCS811Core::SENSOR_ID_ERROR:
 Serial.println("ID_ERROR");
 break;
case CCS811Core::SENSOR_I2C_ERROR:
 Serial.println("I2C_ERROR");
 break;
case CCS811Core::SENSOR_INTERNAL_ERROR:
 Serial.println("INTERNAL_ERROR");
 break;
case CCS811Core::SENSOR_GENERIC_ERROR:
 Serial.println("GENERIC_ERROR");
 break;
default:[enter image description here][2]
 Serial.println("Unspecified error.");
}

if (returnCode != CCS811Core::SENSOR_SUCCESS)
{
Serial.println(".begin() returned with an error.");
while (1); //Hang if there was a problem.
}
}

void loop()
{
//Check to see if data is ready with .dataAvailable()
if (mySensor.dataAvailable())
{
//If so, have the sensor read and calculate the results.
//Get them later
mySensor.readAlgorithmResults();

Serial.print("CO2[");
//Returns calculated CO2 reading
Serial.print(mySensor.getCO2());
Serial.print("] tVOC[");
//Returns calculated TVOC reading
Serial.print(mySensor.getTVOC());
Serial.print("] millis[");
//Simply the time since program start
Serial.print(millis());
Serial.print("]");
Serial.println();
}

delay(10); //Don't spam the I2C bus
}

Can it be, that your ground connection to the sensor is at the wrong place? On the image it looks like the violet wire is connected one pin to the right of the ground pin

You were right; i just fixed it and uploaded a new image. But its still not working.

You need to solder those headers to the breakout. Just inserting them into the plated-through-holes doesn't give a reliable connection.

So simple, though hard to recognize :D


text:
Arduino uno R4 vs ESP32 Dev board
I was wondering what product would work best for my application. I need a web server interface to control several digital outputs connected to my board, and it needs to be as polished as it can be.
In the past I have extensively used ESP32 Dev boards with async web server and often used the integrated memory to save both html and image files to make the web server interface nicer. I was going to buy an ESP32 Dev board once again but then the uno R4 came out and now I am a bit confused on what to choose.
In short, my questions are:

can I load a source file alongside images and html files on the new uno like I did with the ESP32 (since from what I understand you could not do that in previous revisions of the uno)?
can I use the uno R4's ESP32 GPIO pins alongside the ones already provided on the uno?
is there any real advantage of the uno R4 over the ESP32 Dev board for the application I described?
Thanks in advance and sorry if the question is ill posed, I am not really practical with some of the hardware concepts involved!

first of all, the Uno R4 has a 5 V MCU and esp32 is a 3.3 V CPU. The Uno R4 WiFi has esp32-s3 as second MCU, but only as a WiFi adapter with AT firmware. (the Uno R4 Minima doesn't have WiFi.)

I did not test the UNO R4 yet, so this is completely based on the technical documents.
For a polished web interface, you will need some space to save all the data. Remember you need some space for the code, too, so these numbers are an upper bound and free space for HTML, CSS and images is a good portion less.

Standard ESP32 Dev Board: mostly 4 MB flash ROM (but can be 8 or 16).
UNO R4: 256 kB Flash ROM on the main chip, 384 kB ROM on the ESP32-S3-Mini-1-N8 that is used for WiFi.

This suggests that you do have way more space on the ESP32 DevBoard, making it more future-proof.
Another point that may be of interest is interrupts. WiFi does not like to be blocked by interrupt handlers, so if your code relies on interrupts, you may like multiple cores: That way, your code is not hampered by transferring the website.

The ESP32 has two cores, but you may need to keep an eye on which threads run on which cores. (I sometimes do have problems with time-critical applications like updating a string of WS2812b LEDs while loading the control website.)
The UNO R4 has completely separate chips for your sketch and the WiFi stack, but to run the web interface completely from its ESP32-S3-Mini-1-N8, I assume that you have to re-flash it with your own sketch. This probably (again, I'm interpolating from datasheets) means that you have program the UNO R4 as if it has two completely separate chips on it; and you'd have to create their communication protocol by yourself.

For your needs, this sounds as if you're better off using ESP32 DevBoards; maybe two if you run into the same problem as me.
Now, to directly answer your questions:

For serving files via webserver from Arduino UNO R4, I did not find much. Presumably the LittleFS filesystem works on Arduino UNO; and "just serving files" on ESP8266/ESP32 requires them to be in SPIFFS or LittleFS (to my knowledge). It may be that library support for this use case will improve with the release of the UNO R4, but for now, it looks like ESP32 is your best bet.
You may be able to use the GPIOs of the ESP on the UNO R4, but I'd assume that you will have to provide your own sketch/firmware for the ESP. Also, keep in mind that the UNO itself has 5V GPIOs, while the ESP has 3.3V GPIOs and you must not mix those voltages.
The only advantage of the UNO R4 over a ESP32 that I can see for you is: The GPIOs have 5V and you can run the board on 7-24V or USB. This makes the board more compatible with a lot of modules sold "for Arduino".

In the end, I probably would go for ESP32 and design every periphery on 3.3V or with level shifters; and add a second ESP32 if you run into the problem of the web interface interfering with your basic operation.


text:
Arduino Uno WiFi Rev2 is sending serial data to IDE, but not to C# program
I have an Arduino Uno WiFi Rev2 which I am trying to read data over the serial port from (using C#). The Arduino program periodically emits data to the serial port (for testing purposes). Whenever the Arduino writes to the serial, it also toggles the onboard LED to prove it is still running.
Everything seems to run fine. The LED periodically blinks and thus proves the loop runs as expected. Using the Serial Monitor on the Arduino IDE also correctly echoes the data that the Arduino emits.
Here is the program:
int keepAlive = 500;
unsigned long lastKeepAlive = 0;
char ledState = 0;

void setup() {
  Serial.begin(115200);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  if (millis() > lastKeepAlive + keepAlive) {
    lastKeepAlive = millis();
    Serial.println("Alive");
    if (ledState == 0) ledState = 1; else ledState = 0;
    digitalWrite(LED_BUILTIN, ledState);
  }
  delay(5);
}

Another reason why I know it works is because the TX LED on the Arduino blinks whenever it writes on the port.
However, once I close the IDE, the Arduino "stops" writing to the serial port. Maybe because it doesn't have to - there is no connection. Fine with me. Also: the TX-LED stops blinking while the onboard-LED keeps toggling on and off. So the loop still runs fine.
Now I'd like to read out the serial data via C#. For that I've written a simple program like so:
var port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
port.Open();
port.Write("123");
while (true)
{
  Console.WriteLine(port.BytesToRead);
  await Task.Delay(1000);
}

I expect this program to tell me how many bytes are waiting to be read. But it keeps printing 0 endlessly. Also: the TX-LED does not light up on the Arduino. On the other hand, note that little port.Write in the program - it's a test to verify the communication between the Arduino and C#. In fact: I can briefly see the RX-LED on the Arduino light up when my program sends the 123. I reckon the port and it's settings are correct then.
When I close my program, and the open up the IDE again, the Arduino starts to emit serial data again, the TX-LED starts blinking again and data arrives in the Serial Monitor.
All the while the onboard-LED keeps toggling on and off merrily.
What am I doing wrong? Why is the Arduino talking to the IDE but not to my program? Do I have to initiate some kind of handshake?

something wrong with the C# program ... that is off topic here

the arduino cannot choose which program receives data from the serial port on your computer ... find a C# tutorial about receiving data from the serial port

@jsotola Did you notice the statement "the TX-LED stops blinking while the onboard-LED keeps toggling on and off"? To me, the problem might not be the PC program. Since I don't have hardware available, I cannot reproduce, but it seems that some kind of hardware handshake is blocking.

I have solved the issue and @jsotola was correct in pointing out the problem lay with the C# program.
What mislead me was the fact that the TX and RX leds apparently only blink when data is read from the respective buffer, not when it is written to. In other words: the Arduino kept happily writing to the serial port (as expected) but the TX led did not light up because no one was reading what it wrote. I dind't know that.
For anyone else having this issue: I had to set DtrEnable to true. This is still a little confusing to me though. I am not new to programming in C# and with serial ports at all. Yet, I have never had to do this. Also, according to documentation this flag is used when using XOn/XOff or RTS handshake. None of which I am using.
I also tried with PuTTY. I did not configure anything aside from the port name and the baud rate and it worked right away. Investigating, I found that PuTTY apparently defaults to XOn/XOff.
So I'm guessing it really is XOn/XOff then ...
I updated my program like this:
var port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
port.DtrEnable = true;
port.Open();
...


text:
problem conversion value
I have two functions that return an int16_t but I need to convert the ints to
char* is for an attiny13
It would be something like this
const char* msg = "value1()"+','+"value2()"+','+"value3()"

like example
#include "TinyRF_TX.h"

void setup(){
  // transmitter default pin is pin #2. You can change it by editing Settings.h
  setupTransmitter();
}

void loop(){

  const char* msg = "Hello from far away!";

  //send function accepts an array of bytes as first argument
  //second argument is the length of the array
  send((byte*)msg, strlen(msg));

  //make sure there's at least a TX_DELAY_MICROS delay between transmissions
  //otherwise the receiver's behavior will be undefined
  delayMicroseconds(TX_DELAY_MICROS);

What are you going to do with this string? If you are going to send it somewhere with Something.print() or Something.write(), you probably don't need to build it in the first place.

thanks for your answer, you will see I need to send that string using tinyRF from what I see it only allows sending strings type pchar*

You will need to build the string yourself. Probably the easiest way is using the sprintf() function which will take a bunch of arguments and convert them to a string based on formatting instructions you give it.
An apropos article here...
https://www.programmingelectronics.com/sprintf-arduino/

"for an attiny13" Code with nothing but avrlibc snprintf()ing of an int to a buffer takes about 1.5k of the available 1k of flash space on an attiny13. This is without involving the Arduino core or serial or anything else. This might work for an attiny85, or 45, or even 25 with not a lot of room to spare. But for an attiny13 you're going to need to do something tighter.


text:
Wave file will not play with Teensy 3.5
I am attempting to play a wav file from an SD card using a Teensy 3.5. I am using this buzzer and I have the following code currently:
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>

// GUItool: begin automatically generated code
AudioPlaySdWav           playSdWav1;     //xy=557,157
AudioOutputPWM           pwm1;           //xy=889,184
AudioConnection          patchCord1(playSdWav1, 0, pwm1, 0);
AudioConnection          patchCord2(playSdWav1, 1, pwm1, 0);
// GUItool: end automatically generated code

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

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("Play");
  playSdWav1.play("sound.wav");
  delay(100);
  while (playSdWav1.isPlaying()) {
    delay (100);
  }
}

I don't know which pin is supposed to be outputting the PWM signal. I tried searching "patchCord1" to see what the parameters for it are, but was unsuccessful. The code was generated by The Audio System Design Tool.
As for the hardware configuration, I am attempting to wire the I/O pin to various PWM pins (to check for output) with no success. I have GND to Analog Ground and VCC to 3.3V (250 mA max). This is according to this diagram.
Which PIN is the Teensy supposed to output the pulses to?
Edit:
I can get the buzzer to work by using manual PWM (analogWrite), so I know that it functions.

I will edit the question to add a little bit of specifics. But, my question is first, which pin is supposed to be connected to I/O. And second, am I doing this right at all?

The documentation implies you have to combine pins 3 and 4.
Here is a circuit diagram:
https://www.pjrc.com/teensy/gui/img/pwmdualcircuit.jpg

Source:
https://www.pjrc.com/teensy/gui/?info=AudioOutputPWM

After wiring it this way, I still receive no sound. But, I am noticing that the serial monitor is constantly entering "Play." But, it seems it shouldn't do that until the sound has completed? The sound is 5 seconds and it's doing about 10 per second.


text:
ESP32 runtime error in 2d array
I am trying to serial print the value of b[0][0].
Has to be zero but it dose not work!
Here is the code
void setup() {
  Serial.begin(115200);
  byte b[321][241];
  Serial.println(b[0][0]);
}

void loop() {

}

If the array is small like b[2][2] it dose work
In theory esp32 has ram of  520 KiB SRAM so can this be a problem?
Here is the error code
rst:0x8 (TG1WDT_SYS_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1216
ho 0 tail 12 room 4
load:0x40078000,len:9720
ho 0 tail 12 room 4
load:0x40080400,len:6352
entry 0x400806b8

The code complies fine but the error gets when esp32 is running
esp32 version for arduino is 1.0.4

what about b[2][241] or b[321][2] ?

Stack size is usually much smaller than RAM, especially if it's running under RTOS, so I'd expect problems with it.

@jsotola for b[321][2] I get the value 165 as output shouldn't it be zero also for b[2][241] is 165

The ESP32 uses FreeRTOS to run everything, and that includes the Arduino API. Your code is running in a thread of its own ("loopTask"), and that task by default has 8192 bytes of stack allocated to it.
xTaskCreateUniversal(loopTask, "loopTask", 8192, NULL, 1, &loopTaskHandle, CONFIG_ARDUINO_RUNNING_CORE);

You cannot create local variables and other stack data that totals more than 8192 bytes.
Instead you will either have to have the variable as a global variable (or static local) so it gets allocated in the global data segment, or use new or malloc to create it on the heap (and don't forget the corresponding delete or free call when you're done with it).

creating the variable as global seems to solve the problem.

This may be due to serial buffer size.
ESP32 may wrire new data before finshing previous transfer. Add a delay after print line and see.

nop that did not work


text:
I2C master's output is always 255
we are using 2 Arduino UNO as a master/slave for this i2c protocol. we used the first Arduino(slave) as a sensor that will input dummy data (in this case, temperature data). the Arduino(master) should be able to output what the slave has input, but every time we run it, the output is always 255 instead of the temperature data. We don't know what is wrong with the code, but we what to read the real data. Can anyone help us? Thank you.
Here was the code we use for the Master.
// Include Arduino Wire library for I2C
#include <Wire.h>

// Define Temp Slave I2C Address
#define TEMP_ADDRESS 9

void setup()
{
  Wire.begin(); // Initialize I2C communications as Master
  Serial.begin(9600); // Setup serial monitor
  Serial.println(">>>MASTER IS READY<<<");
  Serial.println('\n');
}

void loop()
{
//Temperature
  delay(50);
  Wire.requestFrom(TEMP_ADDRESS, 12);
  Serial.print("TEMP ADDRESS: ");
  Serial.println(TEMP_ADDRESS);
  Serial.println("Receive data from TEMP Slave");
  byte MasterReceivedTemp = Wire.read();
  Serial.print("Temperature = ");
  Serial.println(MasterReceivedTemp);
  Serial.println('\n');
}

You're requesting 12 bytes from the slave? Is the slave expecting you to ask for 12 bytes?

Chances are you're "reading" -1 (which is 255 when squeezed into a byte)n which means "no data available to read".

Are you sure,you are really reaching the slave? You are reading data with Wire.read(), without checking, if there is actually data in the buffer. If there isn't, read will return -1, which then gets to be 255, when downcasted to byte. Print out the return value of Wire.requestFrom(), which shows the number of actually read bytes. Have you checked with the I2C Scanner example, if the slave is really found at that address?


text:
Running a DC motor for a set amount of time
I am trying to run a DC motor for 100ms and then turn it off completely. Here is my code any suggestions on why it might not be working?
My Code
const int pirPin = 9;
const int motorPin = 2;
int switchState = 0;
// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(motorPin , OUTPUT);
  pinMode(pirPin, INPUT);
}
void loop() {
  while (digitalRead(pirPin) == HIGH) {
    digitalWrite(motorPin, HIGH);
    delay(100);
    digitalRead(pirPin) == LOW;
    break;
  }
}

What is the voltage of the DC motor are you using any driver IC or transistor becasue if you are not using any then it may damage your arduino also. Can you please share the connections also

So what u exactly want is that the motor runs when the pirpin is high and it should continue to run for extra 100 ms after the pin goes low

Please share a proper code and not a picture. Dose the motor run?

Please explain how the motor is supposed to react to pirPin. Also, have a look at digitalRead(pirPin) == LOW; which will evaluate to true or false and isn't used anywhere.

So what you want is to be explained how the motor will react to pir pin and you want to run the motor when the pir pin is high and run for 100ms and then go off when the pir pin is low

Please reply to that and is your motor currently turning using the Arduino.

The line digitalRead(pirPin) == LOW; has no effect. And you never do a digitalWrite(motorPin, LOW);

What I believe he is thinking is that on digitalRead(pirPin) == LOW;  the program will get out of the while loop and the motor will stop spinning

#include <Arduino.h>

const int pirPin = 9;
const int motorPin = 2;
int switchState = 0;
// the setup routine runs once when you press reset:
void setup()
{
 // initialize the digital pin as an output.
 pinMode(motorPin, OUTPUT);
 pinMode(pirPin, INPUT);
}
void loop()
{
 while (digitalRead(pirPin) == HIGH)//this part of the code gets executed if the pir
 //pin is read high
 {
   digitalWrite(motorPin, HIGH);//the motor pin is set high so if a motor is connected
   //the motor will start turning.
 }
 while (digitalRead(pirPin) == LOW)//this part of the code gets executed if the pir
 //pin is read low
 {
   delay(100);// so your motor stop after running for extra 0.1 seconds
   digitalWrite(motorPin, LOW);//the pin gets low and the motor should stop turning
 }
}

I have commented all the lines
Hope this helps.


text:
i need help my coding for my fyp
how my coding works = 1 rfid card detect on first rfid reader and 2 rfid card detect on second rfid reader after that servo go to 90
my second rfid not detect
this is my coding
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
Servo  myservo;
int pos = 0;
int angle = 0;
int angle11 = 0;

#define RST_PIN2           8          // Configurable, see typical pin layout above
#define SS_PIN           9          // Configurable, see typical pin layout above
#define SS_PIN2          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN2 );   // Create MFRC522 instance.
MFRC522 mfrc522_2(SS_PIN2, RST_PIN2);   // Create MFRC522 instance.

void setup()
{
  Serial.begin(9600); // Initialize serial communications with the PC
  SPI.begin();        // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card
  mfrc522_2.PCD_Init(); // Init MFRC522 card
  Serial.println("Approximate your card to the reader...");
  Serial.println();
   myservo.attach(5);

}
void loop()
 {

// Look for new cards

if ( ! mfrc522.PICC_IsNewCardPresent()) {

return;

}

 // Select one of the cards

if ( ! mfrc522.PICC_ReadCardSerial()) {

return;

}

// Dump debug info about the card; PICC_HaltA() is automatically called

mfrc522.PICC_DumpToSerial(&(mfrc522.uid));

  delay(1000);
  // Look for new cards

  if ( ! mfrc522_2.PICC_IsNewCardPresent()) {

    return;

  }
  // Select one of the cards

  if ( ! mfrc522_2.PICC_ReadCardSerial()) {

    return;

    mfrc522_2.PICC_DumpToSerial(&(mfrc522.uid));

  }

  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "09 99 55 B2") //change here the UID of the card/cards that you want to give access
 {
String content= "1";
  byte letter;
  for (byte ii = 0; ii < mfrc522_2.uid.size; ii++)
  {
     Serial.print(mfrc522_2.uid.uidByte[ii] < 0x10 ? " 0" : "1 ");
     Serial.print(mfrc522_2.uid.uidByte[ii], HEX);
     content.concat(String (mfrc522_2.uid.uidByte[ii] < 0x10 ? " 0" : "1 "));
     content.concat(String (mfrc522_2.uid.uidByte[ii], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "09 99 55 B3") //change here the UID of the card/cards that you want to give access

      myservo.write(angle); delay(3000);
   for(angle = 0; angle > 90; angle11)
    myservo.write(angle11);
    delay(3000);

    myservo.write(angle11); delay(3000);
   for(angle = 90; angle11 > 0; angle)
    myservo.write(angle);
    delay(3000);
    }

 else
 {
    Serial.println(" Access denied");
    delay(3000);

    }
  }

I don't quite understand your problem. Please explain more and with good english. If you are not good enough in english, you can ask someone, who can write english better.

change your logic a bit  ... use flags ... pseudo code if card_1_is_present and card_1_is_read, then raise flag_1   .... do not exit, do not stop, do not do anything more than setting the value of flag_1 .... next do the same thing for card_2 flag_2 ......... next, check flag_1 and flag_2 ... proceed with program if both are raised

Right at the start of your loop you have this (and other similar constructs):
if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
}

That means that if no new card is present on reader 1 then the rest of the loop is ignored. Nothing else can happen.
You need to restructure your whole program so that it works in the complete opposite way - instead of saying "If there's no card do nothing" you should say "If there is a card then do something".


text:
Use ISRs inside a library more elegantly
At the moment I try to make a library which uses attachInterrupt(?,?,RISING) to read a sensor. The article of Nick Gammon on Calling an ISR from a class helped me a lot, but his "Glue routines" get pretty ugly with more than 30 potential Interrupt Pins on the ESP32, which all need their own static void. Has anyone got a more elegant idea how to do this "Gluing"?

Can you give more details about the kind of interrupts you want to handle? Type of board? In general, you will need one glue function per interrupt, not necessarily one per interrupt pin. This can make a difference if several pins share an interrupt, which is the case for the pin change interrupts on AVR.

An "Arduino" library, which is ESP32 specific, is a bit problematic. An ESP32 isn't an Arduino at all, strictly speaking.

How about going more low level? attachInterrupt() uses different interrupt types depending on the used pin. Most chips only have 1 or 2 external interrupt pins, so the rest is done via pin change interrupts, which cover a whole port, meaning 1 interrupt for a group of 8 pins. You could configure these interrupts directly via their control registers. Though I'm not sure, how this is organized on an ESP.

As a matter of efficiency, I would favor chrisl’s advise to use the
platform's low-level interrupts if at all possible. This, however, comes
at the cost of portability: you would need an implementation specialized
for each platform you want to support. If you don't want to or cannot
maintain all this platform-specific code, attachInterrupt() may be a
reasonable option.
Then, you will absolutely need all those glue routines: since the
interrupt system calls your handlers with no parameters, you will not be
able to share handlers between interrupts, and you end up with as many
handlers as interrupts you are going to use.
There is, however, an elegant way of creating all these specialized
functions without writing them explicitly: you can ask the compiler to
write them for you on the basis of a template you provide.
Below is a version of Nick Gammon's example code modified to use a
template class. Note that you do not necessarily need a class to use
templates: you could use template functions as interrupt handlers if
that is appropriate for your use case.
template <uint8_t pin>
class myClass
{
    static volatile bool switchChanged;

public:
    static void begin()
    {
        pinMode(pin, INPUT_PULLUP);
        attachInterrupt(digitalPinToInterrupt(pin),
                        switchPressed, FALLING);
    }

    static void switchPressed()
    {
        switchChanged = true;
    }
};

template <uint8_t pin>
volatile bool myClass<pin>::switchChanged;

myClass<2> foo;
myClass<3> bar;

void setup()
{
    foo.begin();
    bar.begin();
}

void loop(){}

Note also that myClass<2> and myClass<3> are two different classes:
you actually have a different class for each pin. This means that
foo::switchChanged and bar::switchChanged are two different class
members even though both are static. Since you should (in principle)
have at most one instance of each pin-specific class, you can make
everything within the class static.
The main caveat of this method is that the pin numbers have now to be
compile-time constants. The great advantage is that you will have a
class created for each interrupt that is actually used: no need for an
array of 32 instances on an ESP32 if only a handful of interrupt pins
are going to be actually used.

Thanks a lot! It works brilliant for me. I mostly got what you did, but there's one question left: Why do we have to initialize our private volatile bool myClass<pin>::switchChanged; outside the class definition?

It's not an initialization, it's a definition. Static class members are declared within the class definition but have to be defined outside of it. Otherwise you get the link-time error “undefined reference to myClass<(unsigned char)2>::switchChanged” (and the same for myClass<3>).


text:
i build quadcopter using USB HOST SHIELD + NRF24L01 but the data transmit is wrong
I am building mini Arduino quadcopter project. I am using USB host shield for joystick support and nrf24l01 to transmit the data. Unfortunately, I got wrong data transmitted at the receiver and tried many things but doesn't work. I hope you can help me to further my understanding. It is my own first arduino project and it means a lot for me to keep this momentum. Please, guide me. So, i am using maniac library for nrf24l01 https://github.com/maniacbug/RF24/archive/master.zip . USB host shield is use https://www.arduinolibraries.info/libraries/usb-host-shield-library-2-0 . Help me to find out how to get the value that i send instead of getting error value on serial monitor...
This is the serial monitor GettingStarted from tmrh library

Now sending 26291...ok...Failed, response timed out.

Now sending 27494...ok...Got response 27494, round-trip delay: 22

Now sending 28518...ok...Got response 28518, round-trip delay: 22

Now sending 29541...ok...Failed, response timed out.

Now sending 30742...ok...Failed, response timed out.

Now sending 31944...ok...Got response 31944, round-trip delay: 23

Now sending 32968...ok...Got response 32968, round-trip delay: 23

Now sending 33991...ok...Got response 33991, round-trip delay: 23

Now sending 35014...ok...Failed, response timed out.

Now sending 36215...ok...Got response 36215, round-trip delay: 23

Now sending 37239...ok...Got response 37239, round-trip delay: 23

Now sending 38262...ok...Got response 38262, round-trip delay: 23

Now sending 39285...ok...Failed, response timed out.

Now sending 40486...ok...Got response 40486, round-trip delay: 23

Now sending 41510...ok...Failed, response timed out.

This is the output I send from transmitter (Now, I'm using maniac library, because tmrh give irrelevant response and only a joystick response to this, pretty sure)
X: 128   Y: 32   Hat: 0  Twist: 128  Slider: 15  Buttons A: 128  Buttons B: 0
X: 128   Y: 32   Hat: 0  Twist: 128  Slider: 15  Buttons A: 128  Buttons B: 0
X: 128   Y: 32   Hat: 0  Twist: 128  Slider: 15  Buttons A: 128  Buttons B: 0
X: 0     Y: 32   Hat: 0  Twist: 128  Slider: 15  Buttons A: 128  Buttons B: 0
X: 0     Y: 32   Hat: 0  Twist: 128  Slider: 15  Buttons A: 128  Buttons B: 0
X: 0     Y: 32   Hat: 0  Twist: 128  Slider: 15  Buttons A: 128  Buttons B: 0
X: 0     Y: 32   Hat: 0  Twist: 128  Slider: 15  Buttons A: 128  Buttons B: 0

This is what I receive
Throttle: 0    Yaw: 127    Pitch: 127    Roll: 127    Aux1: 0    Aux2: 0
Throttle: 0    Yaw: 127    Pitch: 127    Roll: 127    Aux1: 0    Aux2: 0
Throttle: 0    Yaw: 127    Pitch: 127    Roll: 127    Aux1: 0    Aux2: 0
Throttle: 0    Yaw: 32    Pitch: 0    Roll: 128    Aux1: 15    Aux2: 128
Throttle: 0    Yaw: 32    Pitch: 0    Roll: 128    Aux1: 15    Aux2: 128
Throttle: 0    Yaw: 32    Pitch: 0    Roll: 128    Aux1: 15    Aux2: 128
Throttle: 0    Yaw: 32    Pitch: 0    Roll: 128    Aux1: 15    Aux2: 128
Throttle: 0    Yaw: 32    Pitch: 0    Roll: 128    Aux1: 15    Aux2: 128

Here is my transmitter coding
#include <usbhid.h>
#include <hiduniversal.h>
#include <usbhub.h>

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

#include "le3dp_rptparser.h"

RF24 radio(9, 8); // select  CSN  pin
const byte address[6] = "00001"; //IMPORTANT: The same as in the receiver

//byte throttle = 512;       // min: 0 | max: 1023 | center: 512
//byte yaw = 512;       // min: 0 | max: 1023 | center: 512
//byte pitch = 8;       // up: 0 | right-up: 1 | right: 2 | right-down: 3 | down: 4 | left-down: 5 | left: 6 | left-up: 7 | center: 8
//byte roll = 128;   // min: 0 | max: 255 | center: 128
//byte AUX1 = 0;    // min: 0 | max: 255
//byte AUX2 = 0;
//byte joyButtonsB = 0;

  byte throttle ;
  byte yaw ;
  byte pitch ;
  byte roll;
  byte AUX1;
  byte AUX2;
  byte joyButtonsB;

struct MyData {
  byte throttle;
  byte yaw;
  byte pitch;
  byte roll;
  byte AUX1;
  byte AUX2;
};

MyData data;

void resetData()
{
  //This are the start values of each channal
  // Throttle is 0 in order to stop the motors
  //127 is the middle value of the 10ADC.

  data.throttle = 0;
  data.yaw = 127;
  data.pitch = 127;
  data.roll = 127;
  data.AUX1 = 0;
  data.AUX2 = 0;
}

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB                                             Usb;
USBHub                                          Hub(&Usb);
HIDUniversal                                    Hid(&Usb);
JoystickEvents                                  JoyEvents;
JoystickReportParser                            Joy(&JoyEvents);

void setup()
{
  //Start everything up
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();

//  radio.setPayloadSize(32);
  resetData();

  Serial.begin( 115200 );
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  Serial.println("Start");

  if (Usb.Init() == -1)
      Serial.println("OSC did not start.");

  delay( 200 );

  if (!Hid.SetReportParser(0, &Joy))
      ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1  );

}

void loop()
{
    //Print all the values into the serial monitor:
    Usb.Task();

  data.throttle = throttle;
  data.yaw      = yaw;
  data.pitch    = pitch;
  data.roll     = roll;
  data.AUX1     = AUX1;
  data.AUX2     = AUX2;
    radio.write(&data, sizeof(MyData));

    Serial.print("X: ");
    Serial.print(data.throttle);
    Serial.print("\t Y: ");
    Serial.print(data.yaw);
    Serial.print("\t Hat: ");
    Serial.print(data.pitch);
    Serial.print("\t Twist: ");
    Serial.print(data.roll);
    Serial.print("\t Slider: ");
    Serial.print(data.AUX1);
    Serial.print("\t Buttons A: ");
    Serial.print(data.AUX2);
    Serial.print("\t Buttons B: ");
    Serial.println(joyButtonsB);
}

void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
  //Put the values from the joystick in another variable:
  throttle = evt->x;
  yaw = evt->y;
  pitch = evt->hat;
  roll = evt->twist;
  AUX1 = evt->slider;
  AUX2 = evt->buttons_a;
  joyButtonsB = evt->buttons_b;
}

This is the receiver

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
const byte address[6] = "00001";

RF24 radio(9, 8);

struct MyData {
byte throttle; //We define each byte of data input, in this case just 6 channels
byte  yaw;
byte pitch;
byte roll;
byte AUX1;
byte AUX2;
};

MyData data;

void resetData()
{

data.throttle = 0;
data.yaw = 127;
data.pitch = 127;
data.roll = 127;
data.AUX1 = 0;
data.AUX2 = 0;

}

/**************************************************/

void setup()
{
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}

/**************************************************/

unsigned long lastRecvTime = 0;

void recvData()
{
while ( radio.available() ) {
radio.read(&data, sizeof(MyData));
lastRecvTime = millis(); //here we receive the data
}
}

/**************************************************/

void loop()
{
recvData();
unsigned long now = millis();
//Here we check if we've lost signal, if we did we reset the values
if ( now - lastRecvTime > 1000 ) {
// Signal lost?
resetData();
}

Serial.print("Throttle: "); Serial.print(data.throttle);  Serial.print("    ");
Serial.print("Yaw: ");      Serial.print(data.yaw);       Serial.print("    ");
Serial.print("Pitch: ");    Serial.print(data.pitch);     Serial.print("    ");
Serial.print("Roll: ");     Serial.print(data.roll);      Serial.print("    ");
Serial.print("Aux1: ");     Serial.print(data.AUX1);      Serial.print("    ");
Serial.print("Aux2: ");     Serial.print(data.AUX2);      Serial.print("\n");

}

/**************************************************/

What is the actual result that you are getting? What values are you receiving and how do they correspond to the values that you are sending?  Break your project down to get each bit working properly first. eg, try sending static data instead of data read from the joystick.

Maniacbug's RF24 is rather ancient. Could you please update to TMRh20's RF24, run the GettingStarted sketch on your boards and post the output?

@majenko sure i will post the result I m getting

they give random value only when I turn a joystick to the left
Throttle: 0    Yaw: 127    Pitch: 127    Roll: 127    Aux1: 0    Aux2: 0 Throttle: 0    Yaw: 127    Pitch: 127    Roll: 127    Aux1: 0    Aux2: 0 Throttle: 0    Yaw: 32    Pitch: 0    Roll: 128    Aux1: 15    Aux2: 128 Throttle: 0    Yaw: 32    Pitch: 0    Roll: 128    Aux1: 15    Aux2: 128
this is example I'm sending from transmitter
 X: 128  Y: 32  Hat: 0  Twist: 128  Slider: 15  Buttons A: 128  Buttons B: 0 X: 24  Y: 0  Hat: 0  Twist: 128  Slider: 15  Buttons A: 128  Buttons B: 0

@Avamander i tried both and found out the same output from here tmrh http://tmrh20.github.io/RF24/
I have done the testing for simple code, and it works. the difference i made for this, i think the integer value is assuming the value from joystick is byte and sending it and try to receive it in same byte value. but doesn't work, i still don't get it ... please, really need your helps...

 I have done the testing for simple code, and it works. well then you have made a mistake in your code. Are you aware that there's a limit to how big one payload can be?

correct me if i m wrong, theoretically, 32 bytes maximum, i m sending 6 variable uint8_t cost 4 bytes each total of 24 bytes. I think the value from joystick is not in uint8_t format, i dont know how to know the type of integer of joystick value that I m getting from USB host shield..

can anyone help me, i m so stuck right now, please!


text:
Understanding the variation of Arduino's current consumption with respect to the voltage supply
Even though this is already a well-debated topic, I couldn't find an extensive discussion about what really is drawing so much power in Arduino's board.
Here is the preamble: I have an Arduino Mega 2560, I measured its power consumption in a steady state with just a red LED turned on with a 560Ohm series resistor.
The power supply (Vcc) was given to Arduino from the Vin pin and the measurement were as follows (below the schematic set-up):

30mA @Vcc = 5.2V;
65mA @Vcc = 8.3V.

What I would like to understand is:

From a hardware perspective, I don't see what is drawing all of this current in Arduino's board;
Why the current drawn from the power supply changes so much with the power supply's value (i.e. what part of the board changes its consumption with the power supply value);
It also seems that turning on an LED through a digital output of Arduino draws a higher current with a higher power supply (Vcc). Why is that?

Note that, by looking at the datasheet of the ATmega2560, the uC mounted on my Arduino, I saw that the current Icc drawn from the power supply is max 14mA (I suppose when no output is sourcing current, I couldn't find the test conditions, unfortunately). I thought the microcontroller was the major cause of power consumption, but it doesn't seem to be so!
Another thing I considered is the onboard LDO, but the input voltage should change the power dissipated by the LDO, not the current drawn from its output.
It's even more strange if you think that regardless of the Vin, all the electronics after the LDO is working at the same voltage.
EDIT1
After Majenko pointed out a big flaw in my set-up with his answer, I re-measured with Vcc = 12.1V and I measured approximately the same Icc observed at Vcc = 8.1V.
I completely agree with Majenko's answer and I would just like to go a bit more in details about what happens while the board is working under voltage.
Here is my analysis:
The minimum operating condition when supplied from Vin is 7V, and that's the "knee" point in Majenko's answer.
However, the maximum quiescent current of the LDO is 10mA, and the Icc of the ATmega2560 is 15mA, so even if we suppose they don't draw any current at Vcc=5.2V, and then draw 25mA together at the minimum operating voltage at 7V, this doesn't add up to the actual increase of 40 or 50 mA that Majenko calculated I observed from 5.2 to 8.3 (which should be the same as from 5.2 to 7V).
And we're not even taking into account that at 5.2V the micro is perfectly able to turn on and keep on the LED, so it's somewhat working and already drawing some current.
Other things that we can take into account, but don't change the facts, are:

a second LDO (LP2985) to generate the 3V3, whose quiescent current should be around 100uA since the circuit is not drawing any current from the 3V3.
a second microcontroller related to the USB programming, whose Icc may be up to 20mA but this one is OFF when supplying from Vin.  -->  Edgar Bonet correctly pointed out that this is not true!
Some voltage dividers and comparators.

So what is the cause of this increase in current consumption from 5 to 7V?

There is one major flaw in your measurements: 5.2V is below the minimum input voltage for the board, so the regulator won't be regulating to 5V. Create more data points over the voltage range and draw yourself a graph. I'll bet it won't be a straight line.

It's not clear from your question how you are measuring the board's current. If you are measuring current draw at the Vin pin, that is still on the input or power-supply side of the LDO, not on the regulated side. If this is the case, increasing current draw (disspiation!) with increasing supply voltage is to be expected. A diagram of how you are measuring the board's current draw would help greatly.

There is a second MCU on the board, used as an USB–serial bridge, which draws its share of current.

Re “this [second microcontroller] is OFF when supplying from Vin”: No, it's ON. See the schematic.

Ah you're right! I checked the schematic but the UVCC pin tricked me :-)

There is a basic error in your methodology which leads to incorrect conclusions.
You cannot determine what is going on from just two data points. Instead you need far more.
Here is a voltage sweep from 5V to 12V with a 0.05V resolution (overkill, but the default setting for the script I use) connected to a Mega:

As you can see the current steadily climes in a pretty linear fashion up to a certain point, then it flattens out.
Everything up to the point where it flattens is below the minimum input voltage for the board. During this time the voltage regulator isn't getting enough voltage, so can't regulate its output voltage to 5V. So the board is running under voltage at this point.  Once it reaches that "knee" point the voltage regulator can regulate the voltage properly - so most of the components on the board start seeing a steady 5V and their current consumption flattens out.
There are a handful of components on the high-voltage side of the regulator - most notably the voltage divider for detecting the input voltage and feeding it to the comparator that drives the P-channel FET to turn the USB power on and off - which will consume slightly more current when the voltage increases, but that is only very small amounts.
So, in short, by comparing a voltage that is below the minimum input voltage for the board with one that is above the minimum input voltage, you are comparing an invalid result with a valid result and inferring that everything in between is valid.

You're right about the big flaw in my set-up! I updated the question with new results at Vcc=12.1V and also extended the question thanks to your considerations. I hope you can share your thoughts about my analysis because something is still not in the right place. Also, how did you calculate the current consumption? I didn't know about any "mathematical" model.

@Elia I didn't calculate anything. It's what my bench power supply reported as being consumed. It's all scripted through a USB connection to control the power supply.

@Elia As for the under voltage scenario, just think about Ohm's Law and what it means.

I thought it was a simulation, it's even better then! :-) I thought about it in terms of Ohm's law, also because the increase is quite linear, but if you consider 40mA at 5V and roughly 90mA at 7V, you get a differential resistance of roughly 40Ohm in that range, and I don't see anything that may show this resistance. Also, there are many semiconductors components that don't strictly follow ohm's law.

@Ella Think about the simplest thing: the power LED. You have an LED with a forward voltage that is fixed. You have a resistor in series with it with a resistance that is fixed. You increase the supply voltage - what happens to that bit of the circuit?

On the Mega R3, the Power LED is driven by 5V, so that will stay the same.  The 5V regulator will dissipate more power as heat; Power dissipated = (Vin - 5V) x current draw.  Vin is after the reverse polarity protection diode D1, which will also be dissipating some power as current flows thru it.

@CrossRoads Not when the input voltage is too low to regulate. That is the whole point here.

Yes, below around 6.7V the regulator is not doing much for you (did the chart above use Vin, or the barrel jack to power the board?)  I prefer in my designs to just power from a 5V wallwart and leave the 5V regulator off altogether.  Need a power supply no matter what - why not use 5V to start?

@CrossRoads the barrell jack, so yes, includes the diode drop.  Personally I use a TPS82130SILT when possible in my projects. Zero dropout and high efficiency.


text:
Arduino interrupt not called using PinChangeInterrupt
I am new to Arduino and I was trying to figure out how to use an interrupt. When I ran this it would read my magnet but the interrupt would never be called and I couldn't figure out if anyone can help me that would be great.
Thanks.
Here is the code
#include <PinChangeInterrupt.h>

//#define INTERRUPT_PIN 12
#include <Math.h>

#define RADIUS 3
const int hallPin = 7; // the number of the hall effect sensor pin
const int ledPin =  13; // the number of the LED pin
// variables will change:
int hallState = 0; // variable for reading the hall sensor status
double inital_val = 0.0;
double distance = inital_val;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  pinMode(hallPin, INPUT);
  //attachInterrupt(hallPin, calc_distance, HIGH);
  // initialize the hall effect sensor pin as an input:
  attachInterrupt(digitalPinToInterrupt(hallPin), calc_distance , HIGH);
  Serial.begin(9600);
}

void loop() {
  //read the state of the hall effect sensor:
  hallState = digitalRead(hallPin);
  if (hallState == LOW) {
    // turn LED on:
    Serial.print("Main Loop: HallState LOW\n");
    digitalWrite(ledPin, HIGH);
    Serial.print(distance, 2);
    Serial.print("\n");
  } else {
    Serial.print("Main Loop: HallState HIGH\n");
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

void calc_distance() {
  Serial.print("INTERRUPT! \n");
  if (digitalRead(hallPin) == HIGH) {
    Serial.print("YES!\n");
    distance += PI * 2 * RADIUS;
  } else {
    Serial.print("NO!\n");
  }
}

Are you sure hallPin=7 has an interrupt on your particular board?  Unos interrupt on 2,3 only.

The attachInterrupt function is only for normal interrupts. Read the reference: attachInterrupt
When you need the Pin Change Interrupts, there is a library for that: EnableInterrupt
Try to keep the interrupt routine as short as possible. Do not use the Serial functions in calc_distance because the Serial functions themself use also interrupts.
The Arduino Mega does not have 'double' floating point variables, the compiler changes it into 32-bit 'float' variables. You are reading the interrupt pin for a test ? I don't understand why you do that. Please make "distance" a volatile variable. In the loop function, the interrupts should be turned off when reading "distance". Because "distance" is a 4 bytes 'float' variable and the Arduino Mega is a 8-bits microcontroller. An interrupt could occur when the "distance" is only read for a part from memory.

Yes to moving the serial stuff out of the interrupt, but attachInterrupt should be able to handle pin changes just fine.  Maybe  attachInterrupt(digitalPinToInterrupt(hallPin),calc_distance , RISING);  or attachInterrupt(digitalPinToInterrupt(hallPin),calc_distance , CHANGE); would be better than whenever it is HIGH.

The attachInterrupt function is only for pin 2 and 3 for an Arduino Uno, according to the reference. Because it uses the normal interrupts. The special "Pin Change Interrupt" (PCINT) requires specific code or a library. When a library is used, the functions from that library should be used for the interrupt. This code seems to use a little of both.

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


text:
Simple GET request with ESP8266HTTPClient
I am trying to do a simple GET request. But I always get status code -1. Here is my complete code.
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

WiFiClient client;
#define AP_SSID "CCR"
#define AP_PASSWORD  "ccrxxxxx"

void wifiConnect() {
  Serial.print("Connecting to AP");
  WiFi.begin(AP_SSID, AP_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
}

void setup() {
  Serial.begin(9600);
  pinMode(0,1);
  Serial.begin(9600);
  delay(300);
  Serial.println("starting");
  WiFi.disconnect();
  Serial.println("disconnected");
  wifiConnect();
  Serial.println("Connected");
}

void loop() {
  HTTPClient http;
  http.begin("https://calm-falls-41696.herokuapp.com/api/v1/cards");
  http.addHeader("Content-Type", "application/json");
  int httpCode = http.GET();
  Serial.println(httpCode);
  if(httpCode == HTTP_CODE_OK) {
  Serial.print("HTTP response code ");
    Serial.println(httpCode);
    String response = http.getString();
    Serial.println(response);
  }
  http.end();
}

Wifi connection was successful. But in my serial terminal I always see -1. I am using PlatfromIO in Visual Studio code.
Update 1: The URL was corrected.
 http.begin("https://calm-falls-41696.herokuapp.com/api/v1/cards.json");

I tested it with google.com too. But it is still returning -1.

@LookAlterno I have posted my complete code.

AFAIK, ESP8266HTTPClient doesn't support HTTPS. Also, why are you using a Content-Type header together with the GET method? That doesn't make any sense, because GET requests don't have a body.

I believe you need to supply the website certificate footprint to http.begin

Hi All,
i have a issue in http.post with timeout error.
I am getting data in chunks within 2 second from my device. I need to send that data to my web server. Example:
12 KB... then 1 sec wait.. then 12 KB data.. It's sending 2 separate files in this request, instead of maintaining connection and having 24 KB of file on web server. I am using httpclient for this and tried passing content-length as well. But doesn't work. Please guide / help / support.

As Musa said, I needed to suply the website certificate footprint to http.begin.
void loop() {
  HTTPClient http;
  String thumbprint="08:3B:71:72:02:43:6E:CA:ED:42:86:93:BA:7E:DF:81:C4:BC:62:30";
  String path = "https://calm-falls-41696.herokuapp.com/api/v1/cards.json";
  http.begin(path, thumbprint);
  int httpCode = http.GET();
  Serial.println(httpCode);
  if(httpCode == HTTP_CODE_OK) {
    Serial.print("HTTP response code ");
    Serial.println(httpCode);
    String response = http.getString();
    Serial.println(response);
 }
  http.end();
  delay(1000);
}


text:
ESP8266, Arduino IDE vs Lua?
I'm planning to buy an ESP8266. Do I really need to learn Lua to play with it? I have seen some people using it with the standard Arduino IDE.
Do you need a custom firmware to use the Arduino IDE instead of Lua?
The Arduino IDE seems better for me because I already know the syntax. Is there any downside to using the Arduino IDE instead of NodeMCU with Lua?

Using the Arduino IDE is custom firmware. That's what you're writing. You don't need any new firmware because the new firmware is what you are writing.
I can't think of any downsides to using C++ to program the ESP8266 instead of Lua - in fact it can only be a benefit since you are not using an interpreted language which is going to be slower than natively compiled code.

so why are most people using NodeMCU with Lua ?

@n0tis Because it's pre-installed and very easy to use. Also they're told to use it when they buy it and don't know any better.

so I should use this lua? I'm planning to make a mini robot using small motor, small battery and pwm

@n0tis I have only ever programmed them in C++ and wouldn't do anything else. At the end of the day you can always re-install the LUA interpreter firmware and go back to LUA if you don't get on with the Arduino-style programming of it. Nothing is permanent - you can change your mind any time you like.

It's Lua not LUA. It is not an acronym. See What's in a name?. How are you using Lua on the Arduino?

@NickGammon wHaTeVeR ;) - The NodeMCU comes with a Lua interpreter preinstalled and executes Lua script uploaded form the NodeMCU IDE.  That Lua firmware can be replaced using the Arduino IDE and the ESP8266 plugin.

@NickGammon Anyway, I refer to LUA not Lua. LUA stands for Least-ever Usable Argot ;)

Is using the Arduino IDE with a fresh out of the box ESP8266 as simple as compiling and uploading or do you need to "clean out" the ESP first? I've held off on buying an ESP because I'm not clear on what I need to do to make it work with the Arduino IDE.

Yes, you just compile and upload. The lua firmware, or the AI thnker AT firmware are both just programs uploaded to the board: one to interpret Lua script, the other to interpret AT commands. Just like your Arduino sketches.

Lua, like many scripting languages, tends to make you a lot more
productive as a programmer: things become far easier as you work at a
higher abstraction level and do not worry about trivial things like
memory management. You achieve the same goals with far less lines of
code. On the other hand, whereas it makes development faster, it also
makes program execution slower. Whether this is a good trade-off or not
is very dependent on the particular application you want to write.
In your particular case, you also have to consider the fact that you do
not know Lua, and you already know both the C++ language and the Arduino
API. Then you may not rip the benefits of Lua on a single project,
because of the time needed to learn the language. You may consider
learning the language as an investment, probably worth it if you are
going to program a lot on this platform, probably not worth it if it's
only for a single, simple enough project. If unsure, I suggest you take
a look at the API provided with Lua on this platform: how well does it
fit your project? Is it a significantly better fit than the Arduino API?

I STRONGLY RECOMMEND TO STAY WITH THE ARDUINO IDE!
Despite programming in C++ not being as friendly and versatile as Lua (working with Esplorer is really a dream come true!), Lua is VERY UNSTABLE AND UNPREDICTABLE!!!
You can run a simple program of ten lines and it works ok for a day... two... and suddenly, on the 3rd day the chip hangs unexpectedly, and with no reason!
If you are lucky, the chip will reboot and program will start running again... that WAS NOT the case with me. I had to reload the program again! After 3 cycles like this, I decided to abandon Lua... FOREVER.

Yeah. Lua as a language is an interesting experience. On NodeMCU, mostly a frustrating one..

I like lua and the REPL.  I also like js on the ESP8266 (espruino) and its small footprint.  As a programmer of embedded systems, it is very clear that many of the Arduino libraries are written by non-embedded programmers wasting and/or fragmenting valuable memory.  I do use Arduino but do things like using my own string management from C rather than that ugly C++ class.  Memory is a commodity to appreciate not abuse.

I learned a little trick.:.in your loop routine add a millisecond delay at the very bottom.....this will allow the chip to do its wifi 'homework' ..yóur code will not notice that...and problem solved!.....  ;)

Sorry for bumping, but this thread helped me to decide for Arduino IDE.
I started with Arduino IDE but couldn't get it to work with ESP-07.
Moved on to NodeMCU and Lua with Esplorer. Took me a while to get it working there also due to the odd bootloader baud rate. First it seemed so easy to set up a WEB-server, but problem was that all the examples found were based on an ancient FW 0.96, and trying with the latest 2.1 didn't work at all. So realising that people hadn't done much with newer FW gave me second thoughts.
Now with Arduino IDE things start to work the way they should! :)


text:
Recommendations for limit switches for Arduino
I'm looking for a limit switch to use with the Arduino. In my project I want to count how many times my turntable makes a full 360° rotation. An object (wheel, pipe, whatever) will be sticking out the side of the turntable and when it comes in contact with the limit switch that will be right next to the turntable, it should notify the Arduino.
Any suggestions on which limit switch I should get?
Thanks so much in advance!

Are you sure you want a limit switch? A limit switch is used to stop the motion at a specific point, not count rotations. For that you would use some kind of encoder, interrupter, hall effect sensor, reed switch, etc.

Indeed, a magnet under the turntable could activate a hall-effect sensor as it passes over it.

Maybe tell us a bit more about what you want to accomplish, then we can think about the problem – rather than just think about a device. From the photo of the turntable I'm thinking that you're planning to do object movies or panoramas. For that you might actually do better with a stepper motor.

I'd use a photo reflective sensor, and stick a white dot on the side of the turntable. You could add dots to get half, quarter, etc. rotation resolution

@Majenko I do want it to send a signal to my Arduino to stop the electricity going to the turntable, and then hopefully each time that signal occurs the Arduino can just increase a counter.

@NickGammon  I'll look into that.  Thanks!

@dlu I'm trying to do 360 photography, and the turntable needs to stop at the exact same spot in each rotation.

@Gerben I'll look into that for sure.  Thanks!

I don't think you could get it to stop at the same location using a regular turntable. As the turntable will continue spinning a bit after you kill the power to the motor (due to inertia). I think you would be better of replacing the DC motor in the turntable with a stepper-motor.

Besides the problem @Gerben mentioned  you may find that a switch does not give you the precision of position that you want/need. Definitely consider a stepper if you can.

Great points.  You're both right. I'll move forward with a stepper-motor for version 2 of my setup.
I'm just going this route because I was provided with an automated turntable to first work with.
Maybe I can open it up and change out some parts...

A $2 microswitch with a roller would be OK for a million revs or so.

You would put a little ramp on the diameter and use it to trigger the switch.
Non-contact magnetic or optical could be better for more cycles or faster operation.

Literally a million? That's impressive.

Honeywell's PDF at http://sensing.honeywell.com/honeywell-sensing-micro-switch-sx-basic-switch-product-sheet-004968-2-en.pdf says 10,000,000 cycles.    But one probably needs to check the datasheet.  Googling a bit, I saw some specs of 1M-5M cycles on a single switch, depending on load, but also some cheap mini ones rated for 10,000 cycles.    Also, for a 33rpm audio turntable even a million isn't long: 1,000,000/33/60/24 = 21 days

@DaveX do you have a link to a brand in particular you recommend?

I do not have a recommendation on the brand.

Beware that a physical switch will probably exhibit contact bounce.  One can filter that in software, but it requires thought.

Well, @Dlu; @Dave X is right on this point, if your project involves being used for longer duration including testing etc. My suggestion would be dont go for this solution at all. Else if its just for a couple of 10s of usage, this shouldn't be a issue.

Instead of a limit switch a hall effect sensor with a moving magnet is an optimal soltuntion since it is contact less there will be no frictional side effects on your application.
But there is one more better way to it, try to use an rotary encoder, something like a 400/600 ppr should also be fine for this, doing this way you have more positional data of the turntable,
You can calculate no of turn, arcs etc.
For eg:

A 400ppr would give you a resolution of 0.9 degree per pulse, and
600ppr would give you 0.6degree per pulse of accuracy.

Although you can go for even higher ppr encoders but you can get these at very low cost.
Pic from: https://m.ebay.co.uk/itm/400BM-Rotary-Encoder-Module-LPD3806-360-6mm-Shaft-Arduino-Pi-Flux-Workshop-/112607725039?_mwBanner=1
Note: Just an example, price may be different at other webites, haven't checked the price while writing this solution.


text:
How to count the number of button presses then play a sequence?

When I press the button once, sequence s1() plays.
When I press the button twice, sequence s2() plays.
When I press the button thrice, sequence s3() plays.
When I press the button 4 times, sequence s4() plays.

const int buttonPin = 10;
int buttonState = 0;

void setup(){
  Serial.begin(9600);
  //initialize pin 2 - 9 as output
  for(int i=2;i<=9;i++){
    pinMode(i,OUTPUT);
  }
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    s1();
    s2();
    s3();
    s4();
  }
}

void s1() {
  int i = 2 ;
  for(int z=0;z<=1;z++) {
    for(int x=i;x<=9;x++) {
      digitalWrite(i,HIGH);
      digitalWrite(x-1,LOW);
      delay(500);
      i = i + 1;
    }
    i = 2;
    if(i = 2) {
      digitalWrite(9,LOW);
    }
  }
}

void s2(){
  int y = 9;
  for(int i=0;i<=1;i++) {
    for(int x=2;x<=5;x++) {
      if(y>=1) {
        digitalWrite(x,HIGH);
        digitalWrite(y,HIGH);
        delay(500);
        y = y - 1;
      }
    }
    off();
    y = 9;
    delay(500);
  }
}

void s3() {
  for(int i=0;i<=2;i++) {
    for(int z=2; z<=9;z++) {
      if(z % 2 == 0) {
        digitalWrite(z,HIGH);
      }
    }
    delay(500);
    for(int z=2; z<=9;z++) {
      if(z % 2 == 0) {
        digitalWrite(z,LOW);
      }
    }
    delay(500);
    for(int z=2; z<=9;z++) {
      if(z % 2 != 0) {
        digitalWrite(z,HIGH);
      }
    }
    delay(500);
    for(int z=2; z<=9;z++) {
      if(z % 2 != 0) {
        digitalWrite(z,LOW);
      }
    }
    delay(500);
  }
}

void s4() {
  for(int i=0;i<=2;i++) {
    for(int x=2;x<=9;x++) {
      digitalWrite(x,HIGH);
      delay(500);
    }
    off();
    delay(500);
  }
}

void off() {
  for(int i=2;i<=9;i++) {
    digitalWrite(i,LOW);
  }
}

You should tell us the preblem you are having.

You didn't like my solution on [so] so you have to crosspost this question here?

Someone suggested on his question http://stackoverflow.com/questions/39388020/arduino-count-the-number-of-button-press-then-play-sequence/ that he take it here. However cross-posting is normally discouraged.

That's not that complex, please have a look at the following code: not the most elegant solution ever, but should be working (I didn't compile it as I'm currently on launch break in the office)
#define LONGEST_PAUSE 1000
unsigned long lastClick;
unsigned int counter;

void loop() {
  if (digitalRead(buttonPin) == HIGH) {
    // button is pressed
    while(digitalRead(buttonPin) == HIGH)) {
      delay(1); // wait until button released
    }
    lastClick = millis();
    counter++;
  }
  if (counter > 0 && (millis() - lastClick) >= LONGEST_PAUSE) { // 1s passed since last click: let's play!
    switch(counter) {
      case 1:
        s1(); break;
      case 2:
        s2(); break;
      case 3:
        s3(); break;
      case 4:
        s4(); break;
      default:
        // what if I keep clicking?!?
    }
    counter = 0; // reset the counter
  }
}

is there a way to break the loop when i press the button when the loop is running?

The OP apparently wishes to (and I'm quoting him) "break the loop when I press the button the the loop is running"
While this might be a question on it's own...
NO, if you exit the loop() function then (by default) your Arduino stops doing anything and just sits there dissipating energy into heat, not much though. With some little effort you can instruct it to reboot.

If my answer solved the problem stated into your question you should accept it and create a new question accordingly to your updated needs.

I prefer you to use pinchange interrupt or simple INT0 interrupt for the buttons to count the press.
Check this link.
on ISR, you can count the press.
int count=0;

void setup() {
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), countFn, CHANGE);
}

void loop() {
  switch(count){
      // all cases here
  }
  count=0;
  delay(2000); // this delay is important to give enough time for a number of presses for the user
}

void countFn() {
  count++;
}


text:
How to find gain for this device?
I am doing a project with Arduino to find CO2 in an environment. For this purpose, I bought a breakout board with an MG811 sensor on it. I bought it from eBay and it came with no datasheet. I searched on the internet and found the datasheet for the MG811.
With the help of the datasheet, I also found the formula to convert the input voltage to PPM. But later I realized that the device also has an amplifier on it, which is giving me higher voltages. I searched thoroughly and found the original device on Taobao.
Can someone please tell me how can I determine the gain so that I can convert the values I read to original values?
One more question. On the given web link, I also found that this device comes with a pin called TCM and with Google translate, I found that it shows temperature compensated output. Can you please explain me the use of this pin as well? If it is more advantageous for me, I'll use this instead of the normal analog output pin.

The amplifier is there for a reason, why would you want to convert them back to original values? Can't you just work with the values the device is giving you?

@Len what you said is true but I don't know the extremes of my values so that I can draw a new plot and find a new equation. The company who manufactured the device have tested it and gave a graph to me with which I can find proper equations. For this purpose I want to know the gain.

I assume the values are given in analogue values? If that is the case, you can just use a volt meter to detect which one is changing when the device is exposed to CO² (i.e. from your breath). If you know the gain, just read out the values of the gain and the one the devices gives to the Arduino. Get multiple readings of multiple values, then map the values the Arduino receives to the ones desired or similar to that of the datasheet.

Measure the voltage before the amplifier. Measure the voltage after the amplifier. Divide the second value by the first. There's your gain.

@Majenko do it twice to establish offset

The MG811 spec gives you the range of measurement, but without the values and connections of the surface mount op amp on the board the only way to determine the voltage output for each CO2 concentration is with a Voltmeter and an already calibrated CO2 PPM meter, which you could perhaps borrow from a lab or university.  Once you have the CO2 values and Voltages that correspond, you can build a formula or function to convert the digital values to voltages and then to CO2 concentrations.
The other option is to trace the tracks on the PCB and create a schematic and then post the spec above and the schematic with resistor values included on the electronics Stack Exchange.

authors: راشد الراجحي