text:
How to create large progmem arrays and not annoy the linker
I have a rather complex project (PlatformIO, but I've also had this happen in the vanilla IDE) with several nested includes.
Let's say that there are three files and a main sketch.
The main sketch includes #2 and #3.
File #3 includes file #1 and file #2.
If file #2 is a .h file containing something like a font, of the format:
const char foo[] PROGMEM = {0xDE,0xAD,0xBE,0xEF};

Then I get linker errors of multiple definitions of 'foo' in both #3 and main.
Weirdly, the default fonts included in my OLED library are placed in a header file, EXACTLY like how I did it, and yet multiple files including that library (or files that themselves included it) do not cause this issue with the library's header file.
Yes, I do have a working include guard. For some reason it doesn't ever seem to help.
I have been using extern to solve this issue, but it's annoying and I'm not sure that it's proper behavior, either...
Could it have something to do with #include <font.h> vs #include "font.h"? What is the difference? My reference said they mean the same thing, but now I'm not so sure.

the title of your post does not match what your question is about

What is the filename extension of file #3?

They are all .h files except for main. The issue is not really related to main, either--this happens any time #2 is included in multiple files. The other .h files have an associated .cpp file, except for #2.

Include Guards only protect against inclusion of a header file multiple times within the same translation unit.  This is important.  If you include a header file (1) in a source file, then include another header file (2) in the same source file, said header file also including the previous header file (1), then the include guard will perform its function.
If you have two source files and you include the same header in both, then the include guard will do nothing.
If you have a variable or function defined in a header file and you include that header into two different source files, when you link those source files together you will get a multiple definition error, since you have two translation units that have the same thing in them, and the linker doesn't like that.
The only time you should ever define variables or functions in a header file are if they are simple constant types, like a const int or a const char - something where the compiler can replace it verbatim in the code and optimize out the symbol completely (arrays of any kind are not simple), or if the symbol is declared "static", where it will be forced to remain "within" the translation unit and not get exported for linking.
Normally you will only declare your complex constants in the header file, and define them once and once only in a single source file. That way there is only one instance of the symbol in one translation unit.
For example, in the header file you would declare your constant:
extern const char foo[] PROGMEM;

And in your source file define the constant:
#include "foo.h"
const char foo[] PROGMEM = {0xDE,0xAD,0xBE,0xEF};

And in answer to the question "what's the difference between #include <...> and #include "..." - when it comes to Arduino, nothing whatsoever.
Officially it denotes a separation between "system" and "local" headers. That is, headers that are installed in the OS as part of the compiler, and headers that are contained within the project.  However there isn't that distinction with Arduino, and the two mean the same thing - just a header.
And finally a note on terminology - a glossary if you will:

Translation unit - One compilable source file (and any included headers) that forms a single file of object code to be linked.
Declaration (Declare) - The indicating of a symbol's type and any attributes, but not the content of that symbol
Definition (Define) - Associating a symbol, whilst declaring it, with the content of that symbol.
Symbol - the name of any variable, function, class, etc.

Okay, so extern IS the right way to do this. Any idea how the OLED library gets away with doing this, though? It defines AND declares that array in its own .h file and causes no errors. And that library gets included in one I use in multiple places (though it itself is only included once...?) so I think that should cause the error...

Can you point to this OLED library? There's no way I can predict what it's doing without being able to see it.

https://github.com/ThingPulse/esp8266-oled-ssd1306/blob/master/src/OLEDDisplayFonts.h
However it works, that file is included by the SSD1306Wire header, which is included by the SSD1306 header I use.

Maybe different versions of the compiler do things in different ways. I know that recently deduplication of static data (like these big arrays) was added, and that the ESP8266's compiler is new enough for that - maybe that has removed the need for it to complain about it being there more than once, since now it can know that they are all the same data anyway.

Strange that it wouldn't do...whatever it was...for mine, though. I'm still learning the intricacies of how files, headers, and placement of things in them affects where they show up, and then this happens, where at least part of the answer seems to be "because it wants to"... :D


text:
Can someone help me decipher the code for the arduino? I am totally lost
The code is as follows:
void loop(){

    light = analogRead(5);
    Serial.println(light);
    analogWrite(3,light/4);

}

Not really a physics question, but I will answer anyway.
loop() is the standard Arduino function which contains code that the microprocessor runs repeatedly (as opposed to code in setup() which is only run once).
light = analogRead(5); takes an analogue voltage reading from pin 5, encodes it as an integer value (either 10 or 12 bits depending on the Arduino model) and stores the result in the variable light.
Serial.println(light); outputs the value of the variable light to the Arduino's serial port. This is a standard way of outputting data from the Arduino so that it can be displayed on a connected computer.
analogWrite(3, light/4); outputs the value of light/4 as a phase-width modulated (PWM) signal to pin 3. Although Arduino output pins are either on (5 volts) or off (ground) at any point in time, PWM signals allow the Arduino to switch an output pin on and off rapidly so that the average voltage seen on that pin is an intermediate value. The duty cycle of the PWM signal which determines the average voltage on the pin is encoded as an 8 bit integer, so light is probably divided by 4 here to convert it from 10 bits to 8 bits.
So the Arduino will repeatedly read an input voltage from pin 5, output an integer representing this voltage to the serial port, and create a PWM signal on pin 3 that has an average voltage the same as that of the input voltage.
See the Arduino language reference page for more information.

Great answer.  What are all the dollar signs for?

@CrossRoads, The question and the answer were migrated from physics.stackexchange.com. In that forum, the server will use MathJax to render any text enclosed by dollar signs as mathematical equations. It's not unusual for people on that site to use MathJax even for an "equation" that is just a single, literal constant.

To make the answer clearer I have removed the MathJax markup and made other small formatting changes.

source: Stack Exchange

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

sort: votes


text:
Multiple devices on 5v pin
Im soldering an LCD screen to my Arduino as I don't have a breadboard and plan on it being permanent. I'm wondering how I should connect the potentiometer (to control contrast).
If I connect it as the first component in series, will this affect the main power to the LCD?
Should I use both 5v pins on the Arduino instead? (Mine has two anyway, I dont know if the official one does).
Would splitting a cable work?
Im new to electronics so sorry if the questions are stupid.
I intend to use the circuit from: https://www.arduino.cc/en/Tutorial/HelloWorld.
Thanks for any help.

why would the potentiometer be in series with the LCD? ... it is not is series in the circuit that you linked

I meant it as an option as I'm unsure of connecting in parallel. A better question would be how can I connect two things to the 5v. Sorry and thanks!

use two wires ... i do not understand what you are really asking

yes, you can connect several things to the 5v line, within current limits of course.

@dandavis would you mind helping me with this? I would be connecting the vdd and anode pins of the lcd to the 5v aswell as the 5v of a humidity sensor. Is this too much? Thanks

since neither of those devices use very much power, you're good.

Thank you very much!

Related article I wrote: https://www.electricrcaircraftguy.com/2014/02/arduino-power-current-and-voltage.html

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


text:
OTA-program SPIFFS on the ESP8266
Something I'd like information on is whether it is possible to upload a SPIFFS filesystem image to the ESP8266. In theory it might work: It can be uploaded over USB, and according to the logs the flash location changes, but that's about it. PlatformIO also seems to offer an Upload SPIFFS option in a platform that's set to an OTA port, but that could just be it not checking the upload type.
So, what I want to know is how I can configure (or otherwise make) a SPIFFS image OTA-uploadable. I have two main OTA methods: Option One is the default Arduino OTA library, and Option Two is a re-skin of the OTA method-whose-name-is-forgettable where I can upload a file on a webpage hosted by the ESP8266 and it will read the file and update its firmware.
I'm assuming that there's a configuration parameter for this somewhere, but I don't know where to start looking, and the documentation on these libraries has a few very basic examples that don't cover complex or advanced use cases.
(The web server--though essentially unrelated to this issue, it's a great example--is the most egregious of these; the code is complex and now templated too, so I can't make sense of it, and the "examples" consist largely of compressed javascript that doesn't show the user anything. Then you get to the interesting stuff like actually getting the real size of an uploading file, or want to know how uploading things actually works (or why it fails), or you want to serve a file piecemeal by assembling bits of text (in the same way that debug statements usually make use of multiple Serial.print() statements), and there's just nothing)

ESP8266HTTPUpdateServer supports SPIFFS

How is that integrated? Does it detect the image (or does the user use a different upload page/form/button), how does it perform the physical update, etc?

https://github.com/esp8266/Arduino/blob/d600cc7fa6c3fc5c31ed903ec12fd2e2da2c3678/libraries/ESP8266HTTPUpdateServer/src/ESP8266HTTPUpdateServer-impl.h#L14

all ways of OTA updates are applied with Update object from core

Basicly OTA supports the upload of *.bin files. Wether this contains compiled code or a filesystem (SPIFFS/LittleFS) is irrelevant. BUT The space for the OTA (partition) has to be min the size of the *.bin plus an overhead for processing. So with 4MB at all, you would need 2.5MB OTA for 1.5MB App/SPIFFS. To tweak partition sizes (or custom partitions) you have to go into the boards.txt file.OTA - Details and Info here
File system - Details and Info here

Thank you for the links. One of them did hint at the ability, but it's still not clear how it's actually set up, accessed, or used.


text:
How to use HC-05 to recieve data?
I am trying to control an led with a bluetooth module, but it is not working with an if else condition.
When I use this code I found on the internet the led blinks when I send the string from an android app:
    void setup() {
    Serial.begin(9600);
     pinMode(13, OUTPUT); // put your setup code here, to run once:
     }

    void loop() {
      // put your main code here, to run repeatedly:
     if(Serial.available()>0)
       {
          char data= Serial.read(); // reading the data received from the bluetooth module
          switch(data)
          {
            case 'a': digitalWrite(13, HIGH);break; // when a is pressed on the app on your smart phone
            case 'd': digitalWrite(13, LOW);break; // when d is pressed on the app on your smart phone
            default : break;
          }
          Serial.println(data);
       }
       delay(50);
    }

Where as when I use this code that I made myself the code compiles and uploads but the serial does not recieve values and the led does not change state when the strings are sent from the app, can someone help me identify why?:
    void setup() {
    Serial.begin(9600);
     pinMode(13, OUTPUT);
     }

    void loop() {
     if(Serial.available()>0)
       {
          char data= Serial.read();
          if (data == 'a')
          {
            digitalWrite(13, HIGH);
          }
          else if (data == 'b')
          {
            digitalWrite(13, LOW);
          }
          Serial.println(data);
       }
       delay(50);
    }

Thank You

are you certain that something does not print ..... it may be a space or tab or carriage return or newline ....... print the ascii value of data

@jsotola Yes, I am certain nothing prints when I use the if else conditon, but the led on the HC-05 blinks just as I send the data, so I am sure the connection is not at fault.


text:
Is it possible to count rising edges of a 4 MHz clock on an Arduino Due and trigger an interrupt like all 4'000'000 edges?
I am struggling with my Arduino Due and the Timer Counter functionallity. The following is what I am trying to achieve:
I want to execute a function to a specific point of time or more precisley after a specific amount of rising edges given by an external clock signal with a frequency of approx. 4 MHz. Thus I read the Atmel Datasheet, Section 36, Timer Counter. My approach was to trigger an interrupt every rising edge and increment a counter variable until I reached the desired amount of rising edges and call my function then. I can confirm that I am in fact counting rising edges with my current approach but I am reading way too slow. Is there any kind of register or hardware counter which automates the counting process. Like I set the register to a specific value and wait for an overflow, execute my function and reset the register? From my web research I found that this is possible on the Uno and Mega but I could not find anything for the Due and to be honest I am a bit overwhelmed by the Atmel Datasheet. Why not just use an Arduino Due or Mega then? I need the 3.3 Volts of the Due and from what I found the Uno and Mega are 5 V devices.
This is my code:

// define capture channels
#define CAPTURE_TC TC0
#define CAPTURE_CHANNEL 0
#define CAPTURE_IRQn TC0_IRQn
#define CAPTURE_Handler TC0_Handler
#define CAPTURE_ID ID_TC0
#define CAPTURE_PIN 2
#define CAPTURE_CLOCK_SELECTION TC_CMR_TCCLKS_TIMER_CLOCK3

// clock divisors corresponding to CAPTURE_CLOCK_SELECTION
static const uint32_t divisors[5] = { 2, 8, 32, 128, 0};

volatile uint32_t captured_pulses = 0;
volatile uint32_t captured_ra = 0;
volatile uint32_t captured_rb = 0;
volatile float frequency, duty_cycle, active_time;

/*
* Function:  setup
* ------------------------------------------------------------------------------
* Setup code. Will be executed once.
*/
void setup() {

  // init serial connection
  Serial.begin(115200);
  Serial.print("Initializing...");

  // configure the PIO pin as peripheral
  const PinDescription *config = &g_APinDescription[CAPTURE_PIN];
  PIO_Configure(config->pPort, config->ulPinType, config->ulPin, config->ulPinConfiguration);

  // enable timer peripheral clock
  pmc_enable_periph_clk(CAPTURE_ID);

  // configure the timer
  TC_Configure(CAPTURE_TC, CAPTURE_CHANNEL,
    CAPTURE_CLOCK_SELECTION   // Clock Selection
    | TC_CMR_LDRA_RISING      // RA Loading: rising edge of TIOA
    | TC_CMR_LDRB_FALLING     // RB Loading: falling edge of TIOA
    | TC_CMR_ABETRG           // External Trigger: TIOA
    | TC_CMR_ETRGEDG_FALLING  // External Trigger Edge: Falling edge
 );

  // configure TC interrupts
  NVIC_DisableIRQ(CAPTURE_IRQn);
  NVIC_ClearPendingIRQ(CAPTURE_IRQn);
  NVIC_SetPriority(CAPTURE_IRQn, 0);
  NVIC_EnableIRQ(CAPTURE_IRQn);

  // enable interrupts
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_IER = TC_IER_LDRBS;

  // start timer counter
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_CCR = TC_CCR_CLKEN | TC_CCR_SWTRG;

  Serial.println("ready!");

} // setup

/*
* Function:  loop
* ------------------------------------------------------------------------------
* Loop code. Will be executed repeatedly after setup completed.
*/
void loop() {

 // Serial.print("Captured rising edges: "); Serial.println(captured_ra);
} // loop

/*
* Function:  CAPTURE_Handler
* ------------------------------------------------------------------------------
*
*/
void CAPTURE_Handler() {
 if ((TC_GetStatus(CAPTURE_TC, CAPTURE_CHANNEL) & TC_SR_LDRBS) == TC_SR_LDRBS) {
   captured_pulses++;
   // captured_ra = CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_RA;
   // captured_rb = CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_RB;

   if (captured_pulses == 4164303) {
    captured_pulses = 0;
    // specific_function_call();
   }
 }
} // CAPTURE_Handler

Thanks for your time, any help is grealty appreciated.

Atmel Datasheet, Section 36, Timer Counter. My approach was to trigger an interrupt every Are you sure you did read it? The timer is called "Timer Counter" because literally it has an internal... counter... so that you do not need to do something every input.

@KamilCuk As I said I was overwhelmed by it. I guess Section 36.7.2 is the relevant part for me but I usually do scientifc computing, I'm pretty new to all this hardware stuff which is why I am asking for help.

Sure. Aim for the RC compare part, set the the compare counter to that 4164303 and just trigger the interrupt once every 4164303 cycles. Also you could divide input clock by some value.

Thanks for the input, gonna try it.

If I may ask, for what application you need it for ? Btw any microcontroller datasheet is painful to read

@Weldriv  Datasheets are a pain to read, but that's the minimum you need to do to use the devices effectively.  And don't forget to read the erratas.  There are always noce surprises there that may save you a couple of weeks of tries and failures.

First of all excuse my inactivity but as you know it's crazy times right now. However I finally figured it out, it's for sure not the most elegant solution but it meets my requirements. Thanks for your help @KamilCuk.
Here is my code if anyone may ever have the same problem as I did. External signal goes on Digital Pin 2. Works fine with a 4.2 MHz external clock.

// define capture channels
#define CAPTURE_TC TC0
#define CAPTURE_CHANNEL 0
#define CAPTURE_IRQn TC0_IRQn
#define CAPTURE_Handler TC0_Handler
#define CAPTURE_ID ID_TC0
#define CAPTURE_PIN 2
#define CAPTURE_CLOCK_SELECTION TC_CMR_TCCLKS_TIMER_CLOCK3

/*
* Function:  setup
* ------------------------------------------------------------------------------
* Setup code. Will be executed once.
*/
void setup() {

  // init serial connection
  Serial.begin(115200);
  Serial.print("Initializing...");

  // configure the PIO pin as peripheral
  const PinDescription *config = &g_APinDescription[CAPTURE_PIN];
  PIO_Configure(config->pPort, config->ulPinType, config->ulPin, config->ulPinConfiguration);

  // enable timer peripheral clock
  pmc_enable_periph_clk(CAPTURE_ID);

  // configure the timer
  TC_Configure(CAPTURE_TC, CAPTURE_CHANNEL,
    CAPTURE_CLOCK_SELECTION   // Clock Selection
    | TC_CMR_LDRA_RISING      // RA Loading: rising edge of TIOA
    | TC_CMR_ABETRG           // External Trigger: TIOA
    | TC_CMR_CPCTRG           // RC Compare
  );

  // configure TC interrupts
  NVIC_DisableIRQ(CAPTURE_IRQn);
  NVIC_ClearPendingIRQ(CAPTURE_IRQn);
  NVIC_SetPriority(CAPTURE_IRQn, 0);

  // enable interrupts and start counter
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_IER = TC_IER_CPCS;                  // enable RC Compare Interrupt
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_CCR = TC_CCR_CLKEN | TC_CCR_SWTRG;  // the datasheet said I need this
  NVIC_EnableIRQ(CAPTURE_IRQn);                                                  // enable interrupts

  // set the trigger value for RC_Compare
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_RC = 4164303;

  Serial.println("ready!");

} // setup

/*
* Function:  loop
* ------------------------------------------------------------------------------
* Main code. Will be executed repeatedly.
*/
void loop() {

} // loop

/*
* Function:  CAPTURE_Handler respectively TC0_Handler
* ------------------------------------------------------------------------------
* Timer capture trigger. Will be executed if TC0_RA == TC0_RC
*/
void CAPTURE_Handler() {
  // reset status register
  TC_GetStatus(CAPTURE_TC, CAPTURE_CHANNEL);

  // do something
  Serial.println("Trigger");
  // function_call()
}


text:
Vary the Speed of Motor
I am trying to control the speed of motor through VFD using 4-20mA signal.
I generate the 4-20mA signal using Arduino.I use low pas filter to obtain the voltages from Arduino PWM pins as shown in the circuit.
Their is continuous deviation at the output.But the deviation is very small.
Example:
when Input is 1V(from 20% PWM in Arduino Code)--> Then output continuous to vary between 3mA to 4mA.
when Input is 5V(from 100% PWM in Arduino Code)--> Then output continuous to vary  between 19mA to 20mA
Can I implement this circuit practically with VFD?
Will this deviation create problem for VFD to control the speed?
Will this very fast continuous deviation is dangerous for

The sawtooth pattern you're showing looks like what I would expect from incomplete filtering of the PWM signal from the Arduino.
I don't know if the variation is going to affect your motor controller or not.
I suggest using a different low pass filter with a much lower pass frequency. That will slow down the response to changes in speed slightly, but produce smoother output. I'd suggest lowering the pass frequency of your filter by 10X or more.
(The good news is that you want to filter the hell out of your PWM signal. You want it to only pass like 10Hz or so. Using a very low cut-off frequency for your filter will get rid of that sawtooth. The result of that would be an output voltage that would be slower to respond, but that should be fine. If your motor takes 1/10th of a second to adjust speeds, is that a problem in your application?)

No its not the problem.I used a low cutt-off frequency and get rid off saw-tooth wave.But their is still very very minor variations! Is their is any 8-bit ADC module which would give 100% pure DC. Although I achieved almost 95% accuracy.Thanks for Help!

A DAC, not a ADC (digital to analog converter, not analog to digital converter) would probably give better results, but then you'd either need 8 digital pins, or a DAC that uses a serial interface like I2C. A quick search on "I2C DAC" does show a number of options. It looks like there is even an Adafruit breakout ready-made for use in Arduino projects.

Yes, I got it.Thanks

The fact is that the low-speed PWM from an Arduino is noisy as hell, and needs a lot of filtering. That's what you're facing. By lowering the cutoff frequency of your filter you should be fine. You aren't trying to create a complex waveform. You just need to vary the speed of a motor, so the fairly slow-changing signal you get out of a heavily filtered PWM output should be fine for this application.


text:
Add char at intervals in a String
I'm trying to create a function that will take a String as an input, and at every 20 characters, it will instert "\n" so that the string doesn't go off the side of my screen (I'm using an oled with the SSD1306Ascii library).
This is my code so far, but when I run it nothing appears on the screen (I have another part of the code which passes the string to the funtion):
String message = "";
String newMessage = "";

void printMessage(String message) {
  oled.clear();
  if(message.length() > 20) {
    current = 20;
    while(current < message.length()) {
      newMessage = message.substring(current-20, current) + "\n";
      newMessage = newMessage + message.substring(current+1);
      current+20;
    }
    oled.println(newMessage);
  }
  else {
    oled.println(message);
  }
}

Sorry, forgot to mention the variables I have decalered, will change that now

One problem that strikes me is that if the length of the passed message is 20 or less, newMessage will remain empty.

@DarioP Good point, I've updated the code.

I think that your implementation is fundamentally flawed. In the while loop, when you assign newMessage to a message.substring you are discarding all the work done in the previous iterations.
Also I would recommend keeping the splitting and the printing separated. The operator += also is very handy here. This code (untested) should implement your original idea in a correct way
String splitMessage( const String & message, const unsigned limit) {
  String newMessage = "";
  unsigned i = 0;
  while ( i+limit < message.length() ) {
    newMessage += message.substring(i, i+limit);
    newMessage += '\n';
    i += limit;
  }
  newMessage += message.substring(i);
  return newMessage;
}

Then you can do:
whatever.println(splitMessage(myMessage, 20));

Note that I retained the use of String from your original implementation, although, being in an embedded environment, it is likely better to avoid it in favor of stack-allocated c-strings.
I have found a substantial amount of pretty enlightening information in the various answers to this question: Is using malloc() and free() a really bad idea on Arduino?

Ah, thats far better than what I came up with, thanks. Your code worked perfectly, however I did need to change "message.size()" to "message.length()"

String object create a memory block at the heap using malloc(), dynamically create a String object newMessage and return the String object from a function is not a good practise as it could create memory leak in long run because the heap memory for newMessage never get free up. For each call to the splitMessage(), a new block of memory is created at the heap....

@hcheung I got you. I am a C++ programmer still getting familiar with the flaws of Arduino "language". Would it be better to return the result through a non const reference argument? Like void splitMessage(String & out, const String & in, const unsigned limit)?

As a c++ programmer, you should know the pitfall of malloc() and heap usage well. String object behind he scene uses malloc() to create a variable when you do something like String newMessage = "";, and each iteration of concatenation also cause heap fragmentation. The general idea is not to use String in Arduino (with only 2k RAM), if you really want to use it, in this particular case, I would declare it as a global, so that you can free it afterward, but again, if you are doing it that way, it make not much different to just use c array instead of String object.

@hcheung as a C++ programmer I always enforce RAII so that the allocated memory is automatically freed when the variable goes out of scope, and I have no further concerns about the heap.

One issue with both your failed implementation and the previous answer
is that they do loads of dynamic allocations and copies. Every time you
use the String’s + or += operators you are allocating heap memory
for a brand new String, copying the original character data into the
newly allocated space, and eventually destroying the original Strings
when you don’t need them anymore.
The simplest way to avoid all these copies and allocations is to not
build the String you want. Instead, just write() the pieces one after
the other on the display. Here is a zero-copy, zero-dynamic allocation
solution:
void printMessage(const char *message) {
    size_t length = strlen(message);
    while (length > 20) {
        oled.write(message, 20);
        oled.write('\n');
        message += 20;  // point to the rest of the message
        length  -= 20;  // remaining length
    }
    oled.write(message);
}

Note that the method Print::write(const char *, size_t) is used here
to print a slice of the message without ever building it as a string in
memory.
On these memory-constrained devices it is always preferable to avoid
heap allocation, and thus String objects. However, if for whatever
reason you really need to print a String object, then you can use
the following overload to print it’s internal buffer without making any
extra copy:
void printMessage(const String &message) {
    printMessage(message.c_str());
}


text:
Is it possible to get which pin generated interrupt?
I wrote some code that handles rotary encoder using an interrupt, but I would like to get which pin generated the interrupt, so I'll be able to handle many interrupts in a single method.
Something like:
void ISREncoders()
{
  int pin = GetCurentInterruptPin(); // <============= this
  int dataPin = dataPins[pin];
  int data = DigitalRead(dataPin);
  if(data == HIGH)
  {
    encoders[pin] += 1;
  }
  else
  {
    encoders[pin] -= 1;
  }
}

Is it anyhow possible?

As mentioned in the answer this is not possible. Still, after peeking some encoder libraries that use interrupt found out that they do the following:
The Encoder class contains several static ISR methods hard coded.
As you create new objects it increments an internal counter and sets proper ISR method on the interrupt.
This is for sure the best solution available, but this is not at all scalable, for instance if you have an imaginary board with thousand pins that handle thousands encoders you will have to hard code each ISR method.

A common data, clock endoder. (when you rotate it generates a clock, and data contains rotation direction information). The objective is to use a single method to handle multiple encoders, I would like to know wich pin generated the interrupt.

What if user rotates two encoders at the same time, and inspite of possibility, two clock pins are in HIGH state?

keep a list of the states of the interrupt pins ... compare list at an interrupt .... anyway, your question is a general programming question ... there is no Arduino component in your question

Polling clock pin is OK, this is not the problem. The question is how to acquire which pin generated the interrupt, so, using interrupts I don't need to constantly poll clock pins. Posted here because it is an arduino (like) issue, and haven't found any information on this on Google. If anyone closes it I would understand. Thanks for your time and effort.

two clock pins are in HIGH state ... there is a flaw in your thinking (not related to your question though) ... your thinking should be two clock pins transition from LOW to HIGH state (or vice versa)

i said compare list at an interrupt ... do not poll constantly ... check the state of all the pins when interrupt is received ... anyway, it may be possible to determine which pin generated the interrupt through hardware, but that would be hardware dependent ... you said nothing about the hardware you are using

Imagine this scenario: two clock pins are in LOW state, they transact (at the same time) to HIGH state, this would generate two interrupts, which interrupt came from which pin? I should handle both encoders once, and skip next interrupt? This is for sure cumbersome to implement, just getting which pin generated the interrupt is easier and more elegant solution. With all due respect a simple: "No it is not possible actually" would be more useful from your part.

Let us continue this discussion in chat.

It is not possible to know which interrupt caused the ISR to be called. The INTFx flag gets cleared when the interrupt routine is called, so you lose that information (which is a shame).
The closest you could do is to have a separate ISR for each pin which just calls the common routine with a parameter to say which ISR it was executed via. That will add some extra latency though as it has to make an extra function call, but that can be somewhat mitigated by having the common function marked as always_inline, which means the compiler will duplicate it and place it within the code where it's being called from. This reduces latency but increases code size.
static ISREncoder(uint8_t pin) __attribute__ ((always_inline)) {
    // Do stuff with the `pin` variable
}

void ISR0() { ISREncoder(2); }
void ISR1() { ISREncoder(3); }


text:
74HC595 to 5v pin shuts down uno
I'm new to using the SN74HC595 shift register, and trying to follow this tutorial: https://www.arduino.cc/en/tutorial/ShiftOut based on this configuration:

When my arduino Uno R3 is plugged in by USB to my Windows-7 x64 PC, it works (in general etc.), but right when I attach pin 16 or pin 10 of the 74HC595  to the 5V pin on the Uno, as it says to do, the entire arduino shuts off and the computer no longer recognizes it, until I disconnect the jumper wire from pin 16 or 13, from the 5v pin on the Uno, then it starts up again
Also just tested, and the same thing happens when I try to connect any of the 74HC595  pins to the 5v Uno pin (after pin 8 of the 74HC595  is connected to the Uno's GND), the whole Uno shuts off and disconnects from the computer
Am I missing something here?

It sounds like you have a short somewhere on the breadboard with the HC595. Could you describe the simplest way to reproduce the problem?

i tried pluggging the pins directly to the ruino pins, only pins  8 and 16, when the register   was at diferent points on the breadboard (and the breadboard works with other things too), am I getting the configuration right ? does my register match th kind at the tutorial?

So the problem occurs just connecting the HC595 to its power supply? Did you correctly identify pin 1?

Photos, or it didn't happen.

Sound like there is a short somewhere. But it also sound like you are putting in jumper wires while the Arduino is plugged in. Which you shouldn't do in most cases. Also connecting 5v to any of the 74HC595 pins, while no supplying the power to it's Vcc pin (16) is not great, and can damage both the 595 and possibly the Arduino.

when I attach pin 16 or pin 10 of the 74HC595 to the 5V pin on the Uno ... the entire arduino shuts off

This sort of thing usually happens to me when I have made a mistake in the wiring.
This is easy to do as the 595 needs a lot of connections in a small space and it is easy to make a mistake.
In your case it seems you have a wiring mistake that is pulling Vcc low and the ATmega328 IC etc can't run.

I would

Re-check the orientation of the 595
Re-check each wire paying particular attention to the ground wires, especially the one that pulls 595 OE to ground (it's pin 13 on the 595).
If necessary, pull everything off the breadboard and start again with things in a completely different position (turn the IC's round etc) to make me re-think everything.

For fun, I set this up on a Uno clone. I made some mistakes in the wires linking the 595 to the Uno but careful inspection found the problem. I found it easy to mix up the pin-number on the 595 with that on the Uno. Using the same wire colours mentioned in the guide may help.
Here's it working


text:
Arduino Nano - How to add multiple sensors? Lithium battery requirements? LED requirements?
I am new to arduino and need help with a couple projects I am working on. One involves the use of 2 sensors - one pulse sensor, and one vibration sensor. Both need to be plugged into the "5v" pin but there seems to be only one. Is there a way I could split the pins to add multiple sensors? Will data be taken in simultaneously, and be cross compared with each other for code execution? I dont want to use breadboaard and want to wire directly to chip.
Also, I need to wire up a rechargeable lithium battery to both projects, I have a 3.7v 1000 Mah lithium battery and a charging port, but do I need more? Ive seen battery regulators, and other parts people recommend, but I want to make sure it will work with just those 2 parts.
I also need to wire a multicolor LED to the board, but do I need any resistors? I see them often for others people projects, but I do not have any and am wondering if I need them.
Thanks if you can answer any of these questions. Totally new to EE

Try reading some basic tutorials and stuff on Arduino.   This kind of stuff is covered in thousands of different places all over the internet in all different types of presentations.  There’s no need for someone to try to reproduce all of that work here.

it may be much easier for you to develop your project if you have a breadboard available .... you can remove the breadboard when the project is completed

So, if you don't want to use a breadboard, you need to solder.

This is an addition to the answer of Thomas Weller.

Also, I need to wire up a rechargeable lithium battery to both projects, I have a 3.7v 1000 Mah lithium battery and a charging port, but do I need more? Ive seen battery regulators, and other parts people recommend, but I want to make sure it will work with just those 2 parts.

I guess with "charging port" you simply mean a plug, where you can connect a power supply to charge the Li battery. Then the answer is: No, you cannot do it with only the battery and the plug. Lithium batteries are rechargeable, yes, but there is much to consider for charging. You must never ever overcharge the battery or discharge it beyond a certain point. Otherwise the battery gets broken (the result can be between simply holding less and less or no power, to the battery exploding).
Also you need to know the battery level to accurately charge or turn of the device, when the battery is empty. Lithium batteries mostly don't change their voltage enough between the full and empty states. Thus Li battery devices have a circuit, that measures, how much power is coming in (while recharging) and how much power is taken out (for powering a device), to determine the current battery level.
At your stage you cannot build that yourself, and also I wouldn't recommend that to anyone. You can by Li battery charger/regulator boards, which will do all that for you, and they are not expensive. There are also microcontroller boards, that incorporate that support for Li batteries.

For the 5v pin:
If you wire 2 sensors to the 5v pin, it will not effect sensor readings of either sensors, and should return separate sensor values regardless of whether or not they are both wired to the 5v pin.
In order to wire both sensors to 1 5v pin, without involving a breadboard you have 2 options:

wire both sensor pins, and the 5v pin onto a custom pin header PCB that connects 3 or more pin headers together
Strip 3 jumper wires and solder them together (2 for the sensors and 1 for the 5v pin)

For the lithium batteries:
It says on their website: that the operating voltage is 5v, So your battery voltage needs to be at least that. It might be a good idea to get 2
(store.arduino.cc)
For the LEDs:
If it is a standard LED, it should be able to withstand voltages of 3.3v or under. Thus the resistor is only absolutely essential for higher voltages. However, it is recommended to use a resistor even with voltages of 3.3v or below, because low resistance could shorten the lifespan of the LED

Warning: unexperienced experiments even with low voltage may result in dangerous situations. E.g. a typical 10 Ohm resistor on 5 V may get so hot that it starts burning. Make yourself familiar with basic electronics, ideally with the help of someone else who can explain it to you. That person should especially explain the safety instructions first.

Both need to be plugged into the "5v" pin but there seems to be only one.

5 Volts means that this is a voltage source. In an ideal voltage source, you can basically plug in as many components as you like.
A real world voltage source will have a power limit. So you need to find datasheets of all components: the Arduino and the sensors. You can then read how much power the Arduino can provide and you can read how much power the sensors need.
As long as the Arduino can provide more power than the sensors need, that's ok. If it can't stuff will become more complicated, since you'll need another 5 V source and find a way to connect them safely.

Is there a way I could split the pins to add multiple sensors?

One does not split pins, one connects additional wires to a pin.

Will data be taken in simultaneously, and be cross compared with each other for code execution?

The 5V pin is only a voltage source. It will not provide or receive data. You'll need another pin or even multiple other pins to send and receive data.
Sometimes you can only have one device per pin (like a digital out pin), sometimes you can have multiple devices on a few pins (like I²C, SPI, 1Wire).
Typically, you would define what you need and then buy the components so you can build it. This requires a bit of knowledge, so watch some tutorials or introduction videos first.

I dont want to use breadboaard and want to wire directly to chip.

Sorry to be that direct, but at your level of understanding, that's probably not a good idea. Build it on a breadboard first and once it works as intended, make it a soldered circuit.

I need to wire up a rechargeable lithium battery to both projects, I have a 3.7v 1000 Mah lithium battery and a charging port, but do I need more?

As you said your components need 5 V, a 3.7 V battery will not help you at all.
You also need to be careful with the terms: a Mah is something totally different than a mAh. Don't confuse other people by mixing Mega (millions) with milli (1/1000).
Other than that, again, read the data sheets, find out how much current each component needs and sum it up. Then divide the 1000 mAh by the value you found, e.g. 100 mA and you'll get 10 h. That's how long it will last. Maybe it's good for your purpose, maybe not. How should we know that?

I want to make sure it will work with just those 2 parts.

That's great. Just consider all the aspects written in the data sheets of the components and it'll be fine.

I also need to wire a multicolor LED to the board, but do I need any resistors?

Yes. Read the data sheet of the multicolor LED and build a voltage dividor according to the values you find.

Totally new to EE

That's probably true. Maybe you want to start at the beginning and not jump into such a complex project. Get some resistors, measure voltages, measure currents. Make an LED light up. Learn about Ohms law, you'll need it very often. Once you got familiar with the basic stuff, come back to this project.
Honestly, I think you'll destroy components if you start with "a couple of projects".

A multicolor LED as in an RGB LED?
To power and LED you will need current limiting resistors.
For an RGB LED you'll need 3, one each for the red, green, and blue channels. You'll need to do some math to figure out what resistance values you need. You need to know the supply voltage (5V) the voltage drop of the LED, and the current to supply to the LED.
Here is a link to an LED resistor calculator: https://ohmslawcalculator.com/led-resistor-calculator
The formula is R = (source_voltage -  LED_voltage_drop) / LED_current
So if you have a 20 mA LED with a 1.3V voltage drop, and you are powering it from 5V (all fairly common values) you'd get:
(5-1.3)/0.02 = 185 Ω.
Then you would round up to the nearest resistor value.
You can safely use a higher resistance value than what you calculate. That will cause the LED to be dimmer. If you use a lower resistance you risk burning out the LED, or even burning out your Arduino.
For 20% resistors, that would be a 220Ω resistor. (The percent is a tolerance value. 20% resistors can have their actual resistance vary by as much as 20% from one to the next. You can get resistors in 20%, 10%, 5%, 2%, 1% tolerances, and even lower. The lower the tolerance value, the more they cost, and the more resistors you need to have all the possible values.
Don't use that value however. Look up the voltage drop and current for your LED and plug them into the above formula.
If you want to vary the apparent color of an RGB LED through software you can hook each color channel to a different PWM output pin on your Arduino. You then set each color channel to a different "duty cycle" to vary the brightness of that color.


text:
Why my code isn't working?
I wrote this code, but it doesn't work (what I want is that the program choose a random color and turn on or off an RGB led) I use transistors to turn the led strip on or off and analogWrite(pin, random(0, 255) doesn't work
int red = 11;
int green = 10;
int blue = 9;

int color = 1;
int stat = 1;

void setup() {
pinMode(red, OUTPUT);
pinMode(green, OUTPUT);
pinMode(blue, OUTPUT);
}

void loop() {
  color = random(1, 3);
  stat = random(0, 1);

  if (color == 1 and stat == 0) {
    digitalWrite(red, LOW);
  }

  if (color == 1 and stat == 1) {
    digitalWrite(red, HIGH);
  }

  if (color == 2 and stat == 0) {
    digitalWrite(green, LOW);
  }

  if (color == 2 and stat == 1) {
    digitalWrite(green, HIGH);
  }

  if (color == 3 and stat == 0) {
    digitalWrite(blue, LOW);
  }

  if (color == 3 and stat == 1) {
    digitalWrite(blue, HIGH);
  }

  delay(1000);

}

Can you be more specific? "Doesn't work" could mean anything. What happens?

Nothing, nothing happens

From Arduino reference: random
In short:

Syntax
random(max)
random(min, max)
Parameters
min: lower bound of the random value, inclusive (optional).
max: upper bound of the random value, exclusive.
Returns
A random number between min and max-1. Data type: long.

Basically your first random returns values {1,2} and second one is even better {0}

So what I have to change in the code ? (I'm sorry but I don't really understand programming)

@drmarton11 you are turning the transistor on, only if there random(0,1) returns 1 and it never returns 1, it returns zeroes only as 1 is not included. If you want value 0 an 1, you have to use random(0,2) or simply random(2) as min is 0 by default

Thank you ! It works !


text:
Arduino CH340 Driver Problem
I'm trying to connect my Arduino Uno to the Arduino IDE in Windows, but the only way it works is with a CH340 driver.
I am concerned about this as I can only find a download of it published by two Chinese companies- wch.cn or Jiangsu Qinheng Co., Ltd.- maybe they're both 1 company; even when Windows looked for a driver on the web that was the one it downloaded.
When I went to Device Manager to look for the driver in the official Arduino download zip, Windows said it couldn't find any drivers.
I am concerned about the security implications of the driver being Chinese and wonder if there are any other CH340 drivers (unless CH stands for China...)
Anyway thx for answering!!! :)

The CH340 is a Chinese knock-off of FTDI chips. That doesn't mean they are bad or that their drivers are unsafe. It's just what it is. FTDI, on their own, is trying also to "fix" their own drivers to not necessarily work well with CH340 chips. So you may be stuck with their drivers, like it or not. They are drivers and so may run at a trusted level in your computer. If you are serious about such security, then you should also consider that FTDI may be working with still other groups that also may sacrifice your security, too. There's no truly safe haven. Just the feelings of one.

Switch to a Mac. In macOS, the CH340 drivers are provided by Apple themselves and preinstalled on every Mac.

Or switch to a genuine Arduino Uno, which uses the official USB standard for USB-to-serial communication, i.e. a USB CDC device implementing ACM and PSTN protocols.

@jonk what makes you think the CH340 is a FTDI knock-off? They don't use the FTDI drivers at all.

@Passerby Sorry. Perhaps just a difference in perspective. The CH340 showed up in "cheap" boards from China many years ago. At first, none of us understood exactly what had happened, as FTDI was pretty much the only player at first. If you google "knock-off" and "CH340" you'll see I'm not the only person in the world seeing things that way. I don't mean to belittle the device. But it was introduced in order to lower the BOM cost to some players needing an FTDI equivalent. Little doubt about that. If my words offend, my apologies. As I said, "that doesn't mean they are bad." And I meant that.

CH340 is immensely widely used. There may be many drivers or only a few BUT either way they are in use in the very many millions. Note that Arduino Clones are 110% legitimate. What is not meant to be used is the Arduino NAME per se. The design and system software is fully open source.

@jonk by the time the CH430 showed up Silicon labs and Prolific had be making their USB-UART bridges for years (CP2102, PL2304), and people had been making clones of them too.   Arduino used the FTDI chip, but most cheap arduino closes use the CH430 now.

@Jasen Yup. Cheap is the word.

@jonk saying its a knock off just cause its a competing product is just plain wrong.

@Passerby I remember the period of time when it first, unexpectedly, appeared and we hobbyists were struggling hard to find drivers to work with it. It literally took us by surprise as the products hadn't declared its use. We discovered it when the boards arrived, instead, and then had to deal with some difficult hacks to make things work. I have my impressions from that day. You can have the floor on the topic now. I'll leave it for you.

WCH is the manufacturing company that first produced the CH340. They are Chinese.


text:
Estimating CPU load of a task scheduler
First off, I should note that I'm not sure what tags best apply here, and I can't seem to find any that relate to schedulers, etc. Please inform me if they are not the right ones.
I have a simple, portable task scheduler (it only relies on millis(), and runs on different Arduino-supported systems) that is called via a function in loop() and that picks and then runs a function pointer (the "task") from a list of tasks with status, sleep, and priority information.
I would like to have a way to determine and to tell the user how much CPU time is being spent on running tasks vs. being idle.
The problem is that there can be other functions being called from loop(), not just my scheduler. It would thus be a bad idea to track total time vs. time spent in a task. If I did, the CPU use would always read low, since the actual task time cannot use all of the CPU time since the other tasks in loop() would be quietly using some of it.
However, if I specifically track time in the scheduler vs. time spent in task, I run into a new issue. I would use more memory (a few more bytes, but I'm using a lot already...) and more CPU*, since I'd have to keep track of the total so far and also the current runtime for that iteration of the scheduler. That's on top of the similar construct determining the runtime of the task. Mainly, though, the issue is that the loop() function and scheduler run fast enough that the millis() timer can tick slower than the changeover between my scheduler and the loop() function. This causes the timing to also be off, since it would be counted if it ticks in the scheduler even if it was mainly loop()'s fault.
Is there a general methodology for computing the CPU time? It would be difficult to time-slice the scheduler, and that would run slower anyway. I could count the proportion of scheduler calls that run/don't run tasks, but that won't work because tasks take longer than the no-op that happens if a task doesn't run, and it makes no accounting for task length.
*On an AVR system, the 8-bit CPU uses a surprising aggregate time on all those 32-bit operations, between the sleep time calculations (on sleeping tasks only, to be fair) and the elapsed time calculations that fed into my prior CPU use attempt. It wasn't the only cause, but I saw quite a bit of timing slip on one attempt of coding the scheduler because of a similar issue.

Addressing the issue about mills() being too low resolution, you can also use micros() for a microsecond count, though on some Arduino it has 4µs or 8µs resolution and not true microsecond.

I'm considering that, but the same issue can still apply, just not as much. I'm hoping that there's some sort of well-known or popular approach for getting the CPU load that minimizes this, or at least so that mine won't be any worse. It also doesn't answer what's the better approach here for what's less wrong--do I ignore reading too low from including loop() inadvertently, or do I take the overhead and complexity of tracking only the scheduler's runtime, with reading too low for different reasons?

The only metric you have is time. The only thing you can do is compare that time over iterations / task calls. The typical approach is to note the time at the start of a task "tick", and note it at the end. Then add the difference to the total for that task.
When you want to then look at usage percentages you can compare those totals to the total time the system has been running.
The total runtime is already done for you, in the form of millis(), so you don't need to worry about that.
Recording each task's total runtime in microseconds is simple enough, but of course will entail an overhead. That is unavoidable no matter what strategy you take. It's kind of quantum: the act of measuring changes the results.
If you treat your "idle" task the same as any other task (which is the normal way of doing things - the idle task is just a task that does nothing) then the sum of all the time counts for all the tasks = (within a certain granularity) the total amount of time your task scheduler has been running. The difference between that and the system runtime (millis()) is the proportion of the time your scheduler has been running compared to other things happening in loop().
Whether you compare to millis() or micros() for the system runtime is up to you. By storing micros() per task you're getting a reasonable resolution for each tasks's runtime (but with a limit to how long before it wraps - but you can handle that in software by carrying over to another lower resolution counter if you want), but you can then discard some of that resolution when doing your calculations if you don't need it at the time.
Estimating runtime in a co-operative multitasking system like this is never good, and often not bothered with because of that. It's always a guestimate with the results being skewed by the measuring, since the measuring is synchronous with the execution of the tasks.
In a proper context-switching multitasking system you would normally operate on the number of "ticks" of the system rather on time. That is, simply count 1 each time a task is switched in by the context switcher. Since each task has a fixed runtime controlled by the granularity of the scheduler it's then trivial to know that task X has been running for X/TOTAL_TICKS % of the time. Any calculations will be themselves done in a task - maybe the idle task, or a system accounting task.

I think I can get that working. The problem, of course, is that I don't have an idle task; on the event of no task, it simply fails and checks again. It's all in the scheduler itself, not the task. I can't really count zero time, and that skews any measurements I try. But if I can figure out how to make the idle task wait until a task is (almost?) ready, perhaps I can get that working. Or add up the time spent in the scheduler itself, but that's still too small to measure...

The cheapest (in every sense) way I know to display "idleness" is to set an output pin when you enter the scheduler and clear it again when you dispatch a task (other than your idle task, if there is one). Or reverse this, if you want to display load instead. These can be accomplished with a single instruction each. Low impact on your memory, execution time, assembly time, and wallet.
How precisely do you want to report this?

An LED on the output will fade and brighten according to the load. If you need damping (perhaps the load is brief and "peak-y") add an R-C filter to the LED circuit.

Connect a DVM, or even better, a mechanical VOM if you can find one, to the output and read load from the meter. A mechanical meter would do some damping for you. A DVM will probably need the filter from the previous suggestion.

Loop the filtered output back into an analog input and read the load to a precision of ~ 0.1%! That's way more significance than is justified so round it as you see fit.

I can't feasibly use that here, but your idea is quite ingenious. I like it!


text:
RFID-RC522 not working properly?
So I'm working with an arduino uno and I want to read the UID from one card and write it to another with the code of Miguel Balboa but the RC522 doesn't appear to read anything on the serial monitor. However, if I the one below, it actually reads everything. I've also used the hardware checker and it says that everything is working fine. What am I doing wrong or what do I have to do to clone the UID with this code? Thank you very much in advance.
#include <SPI.h>

#define SAD 10
#define RST 5

MFRC522 nfc(SAD, RST);

void setup() {
  SPI.begin();
  // Read a fast as possible. There is a limit for how long we are
  // allowed to read from the tags.
  Serial.begin(115200);

  Serial.println("Looking for MFRC522.");
  nfc.begin();

  // Get the firmware version of the RFID chip
  byte version = nfc.getFirmwareVersion();
  if (! version) {
    Serial.print("Didn't find MFRC522 board.");
    while(1); //halt
  }

  Serial.print("Found chip MFRC522 ");
  Serial.print("Firmware ver. 0x");
  Serial.print(version, HEX);
  Serial.println(".");
}

byte keyA[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, };
byte keyB[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, };

void loop() {
  byte status;
  byte data[MAX_LEN];
  byte serial[5];
  int i, j, pos;

  // Send a general request out into the aether. If there is a tag in
  // the area it will respond and the status will be MI_OK.
  status = nfc.requestTag(MF1_REQIDL, data);

  if (status == MI_OK) {
    Serial.println("Tag detected.");
    Serial.print("Type: ");
    Serial.print(data[0], HEX);
    Serial.print(", ");
    Serial.println(data[1], HEX);

    // calculate the anti-collision value for the currently detected
    // tag and write the serial into the data array.
    status = nfc.antiCollision(data);
    memcpy(serial, data, 5);

    Serial.println("The serial nb of the tag is:");
    for (i = 0; i < 3; i++) {
      Serial.print(serial[i], HEX);
      Serial.print(", ");
    }
    Serial.println(serial[3], HEX);

    // Select the tag that we want to talk to. If we don't do this the
    // chip does not know which tag it should talk if there should be
    // any other tags in the area..
    nfc.selectTag(serial);

    // Assuming that there are only 64 blocks of memory in this chip.
    for (i = 0; i < 64; i++) {
      // Try to authenticate each block first with the A key.
      status = nfc.authenticate(MF1_AUTHENT1A, i, keyA, serial);
      if (status == MI_OK) {
        Serial.print("Authenticated block nb. 0x");
        Serial.print(i, HEX);
        Serial.println(" with key A.");
        // Reading block i from the tag into data.
        status = nfc.readFromTag(i, data);
        if (status == MI_OK) {
          // If there was no error when reading; print all the hex
          // values in the data.
          for (j = 0; j < 15; j++) {
            Serial.print(data[j], HEX);
            Serial.print(", ");
          }
          Serial.println(data[15], HEX);
        } else {
          Serial.println("Read failed.");
        }
      } else {
        // If we could not authenticate with the A key, we will try
        // the B key.
        status = nfc.authenticate(MF1_AUTHENT1B, i, keyB, serial);
        if (status == MI_OK) {
          Serial.print("Authenticated block nb. 0x");
          Serial.print(i, HEX);
          Serial.println(" with key B.");
          status = nfc.readFromTag(i, data);
          if (status == MI_OK) {
            for (j = 0; j < 15; j++) {
              Serial.print(data[j], HEX);
              Serial.print(", ");
            }
            Serial.println(data[15], HEX);
          } else {
            Serial.println("Read failed.");
          }
        } else {
          Serial.print("Access denied at block nb. 0x");
          Serial.println(i, HEX);
        }
      }
    }

    // Stop the tag and get ready for reading a new tag.
    nfc.haltTag();
  }
  delay(2000);
}```

you are not doing anything wrong ... it appears that there is no code for writing to a card

that's the code that i'm using instead of the one from Miguel Balboa, which doesn't work. I was asking for a code to actually write a card with the code i've given


text:
Failed HC-05 Bluetooth sketch upload - (port and board correct)
I'm running this project with HC-05 https://create.arduino.cc/projecthub/millerman4487/view-serial-monitor-over-bluetooth-fbb0e5 and I am getting connection error. I have ensured my port selected and board is accurate but no such luck. The Arduino uno is powered by 3.7v batt (output ~8v with reg) so it is simply just a battery connection and BT module, but when uploading the sketch, it fails. I am relatively new to arduino, and am not sure where to begin this debug.
I am using PC windows, and using a BT dongle receiver for connection (maybe this affects port comm?)
Thanks in advance
Here us the error message
Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Uno"

Sketch uses 1954 bytes (6%) of program storage space. Maximum is 32256 bytes.

Global variables use 250 bytes (12%) of dynamic memory, leaving 1798 bytes for local variables.
Maximum is 2048 bytes.

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for
suggestions.

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x04

when uploading the code, did you ensure disconnecting the Rx, Tx pins from the Arduino? Coz this is a similar error you get when you upload code with your comm pins connected. Try uploading the code with no wires connected.

Ok, disconnected Rx, Tx, and was returned with this error

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x09

Restart your IDE and use a different com port for uploading.

tried, and still no luck


text:
How can i make my MLX90614ESF scan temperature after the MFRC522 scans the RFID tag?
//THIS IS THE RFID CODE

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // 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
    //shows in serial that it is ready to read
}
//*****************************************************************************************//
void loop() {
  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;
  //some variables we need
  byte block;
  byte len;
  MFRC522::StatusCode status;
  //-------------------------------------------

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  byte buffer1[18];

  block = 4;
  len = 18;

  //------------------------------------------- GET FIRST NAME
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 4, &key, &(mfrc522.uid)); //line 834 of MFRC522.cpp file
  if (status != MFRC522::STATUS_OK) {
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer1, &len);
  if (status != MFRC522::STATUS_OK) {
    return;
  }

  //PRINT FIRST NAME
  for (uint8_t i = 0; i < 16; i++)
  {
    if (buffer1[i] != 32)
    {
      Serial.write(buffer1[i]);
    }
  }
  Serial.print(" ");

  //---------------------------------------- GET LAST NAME

  byte buffer2[18];
  block = 1;

  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid)); //line 834
  if (status != MFRC522::STATUS_OK) {
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer2, &len);
  if (status != MFRC522::STATUS_OK) {
    return;
  }

  //PRINT LAST NAME
  for (uint8_t i = 0; i < 16; i++) {
    Serial.write(buffer2[i] );
  }

  //----------------------------------------

  delay(1000); //change value if you want to read cards faster

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}
//*****************************************************************************************//

// AND THIS IS THE MLX90614 CODE
#include <Wire.h>
#include <Adafruit_MLX90614.h>

Adafruit_MLX90614 mlx = Adafruit_MLX90614();

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

  mlx.begin();
}

void loop() {

  Serial.print("*\Body Temperature = "); Serial.print(mlx.readObjectTempC()); Serial.println("*C");

  Serial.println();
  delay(500);
}

Please add some text to your question.  What is happening, why it is not what you expected to happen and what you would like to happen.  Humm, from the looks of it, this code likely does not compile because you have multiple functions using the same name.

It appears that you have simply concatenated the code from the RFID tag Sketch and the code from Temperature Sketch together.  This will not work as both programs contain identically named functions. Specifically "setup()" and "loop()".  What you need to do is integrate the code for each "setup()" function into one "setup()" function.  Similarly, you need to do the same with the "loop()" functions.
Assuming you only want to scan the temperature after you have successfully recovered data from the RFID tag, place the Temperature Sketch loop code immediately before the delay in the RFID tag code.

Someone may actually code a solution up for you @Ace Canacan.  I think you should try for your self first.  Also, it is always better if you try something before asking your question here.  More people will be willing to help if they see you have tried a few times before asking a question.


text:
How to count number of bytes appearing in the Arduino serial?
I need to count the number of bytes appearing in the serial (UART bus) bus, how to count bytes in Arduino with Arduino Serial functions? is this possible?
Application -
RS485 communication with multiple boards without slave ID
slave boards will send data to the master board when,
1st 10 bytes = masters send a 10byte message to all slaves
slaves listening to the bus always until it is the turn to send the data
when byte count is 10, slave 1 sends data 5 bytes to master
when byte count is 15 (10+5), slave 2 sends data 5 bytes to master
when byte count is 20 (15+5), slave 3 sends data 5 bytes to master
max count is 25 known value

if (Serial.available() > 0) { incoming[byteCount] = Serial.read(); byteCount++; } where byteCount counts the number of bytes received and incoming[..]  stores the received bytes, or something like that? Looks like a protocol that's not very fault-tolerant.

@StarCat I am trying to achieve maximum data throughput. 1st master initiates the bus 10-byte message, all slaves listing to the bus, then slaves sending data when its turn comes. so I can reduce waste time on request response time, I have 20 slaves. maybe each slave send some checksum at last of each slaves data packet where the master can decode once data received

Counting is easy, the hard part is knowing when to reset the count.  Assume you will sometimes get out of sync.

@Chris Stratton what did you mean? reset count? i can reset each slave ones the data is sent right? other slaves will wait until there turn

You need to have a reliable, recoverable way to know when to start counting.   Assume the system will occasionally become mis-synchronized for one reason or another, you need to have a design which is self correcting and can get all of the nodes back on board and counting the next cycle together.

Serial.available() returns the number of bytes available for reading in the buffer.
int nBytes=Serial.available();
if (nBytes > x) {
............
............
............
}

Welcome to Arduino:SE.  Just an observation: answers posted here should be written in English.


text:
Understanding Debounce code
I don't understand the following Debounce code. (The complete code is at the bottom.) From what I understand, when the pin reads something, we wait at least 50 milliseconds before performing anything. But doesn't the reading variable get reset every loop iteration, so reading equals zero in the inner if-condition in every iteration.
What I think is the sequence of events: loop(), loop(), loop(), "loop(), button press, reading=1, set lastDebounceTime, first if condition fails because we have to wait, set lastButtonState=1", loop(), loop(),loop(),"loop() enough time has passed, but since no button press at in this iteration and the last few, reading and lastButtonState equal zero", loop(), ... .
However, this code works.
Why do we save reading in a local variable? Won't the code virtually always be this, then:
if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer than the debounce
    // delay, so take it as the actual current state:

    // if the button state has changed:
    if 0 != buttonState) {
      buttonState = 0;

...

Entire code:
/*
  Debounce

  Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
  press), the output pin is toggled from LOW to HIGH or HIGH to LOW. There's a
  minimum delay between toggles to debounce the circuit (i.e. to ignore noise).

  The circuit:
  - LED attached from pin 13 to ground
  - pushbutton attached from pin 2 to +5V
  - 10 kilohm resistor attached from pin 2 to ground

  - Note: On most Arduino boards, there is already an LED on the board connected
    to pin 13, so you don't need any extra components for this example.

  created 21 Nov 2006
  by David A. Mellis
  modified 30 Aug 2011
  by Limor Fried
  modified 28 Dec 2012
  by Mike Walters
  modified 30 Aug 2016
  by Arturo Guadalupi

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/Debounce
*/

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // set initial LED state
  digitalWrite(ledPin, ledState);
}

void loop() {
  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonPin);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH), and you've waited long enough
  // since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer than the debounce
    // delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
  }

  // set the LED:
  digitalWrite(ledPin, ledState);

  // save the reading. Next time through the loop, it'll be the lastButtonState:
  lastButtonState = reading;
}

(Debounce code taken from: https://www.arduino.cc/en/tutorial/debounce.)

What's unclear with the comments?
BTW: The last code line is part of the debouncing algorithm.

Ah, sorry @jsotola. I seem to have copy/paste-d incorrectly

@DataFiddler, I edited the question. I don't understand part of the algorithm. Sorry about that.

think about this .... imagine that you have a stopwatch ... in front of you is an indicator light and a pushbutton ... the light turns on, and off, at random intervals ... your job is to press a button if the state of the lamp does not change for 10 seconds ... how would you accomplish your job? ... the algorithm does the same thing

I edited the question again. Why is reading local?

because reading needs to exist only for the duration of one iteration of loop()

@jsotola, don't we need it for the iteration when lastDebounceTime completes?

there is no lastDebounceTime completes

Let us continue this discussion in chat.

loop() does not need any time and repeats permanently.
lastButtonState is reading from previous loop run.
As long as the button bounces, lastDebounceTime is updated.
Only when the button has settled (either pressed or released), the condition
  ((millis() - lastDebounceTime) > debounceDelay)

becomes true and the code is executed -> if buttonState (the previous debounced state) and reading show a change to HIGH, the led state is toggled.
Not sure if this explanation makes anything clearer, as it is clear already as it stands, IMO.

Why isn't it that we check instead lastButtonState shows a change to high? Reading gets reset every loop() and will virtually always be zero (in my limited understanding).

Why would it always be 0?  It will be whatever the pin reads.  Every time loop repeats it reads the pin again and you get a new reading.  We could check lastButtonState or reading, they will be the same at that point in the code.  If they aren't the same then lastDebounceTime gets set to the current time and we don't enter that second if statement.

If loop takes a microsecond and bouncing takes two milliseconds, reading will be evaluated 2000 times in those 2 ms, and change a couple of times during this period. Only if is stable for 50 ms (you got nearly an infinite number of the same reading values) you accept that as a new debounced button state

What I think is the sequence of events: loop(), loop(), loop(), "loop(), button press, reading=1, set lastDebounceTime, first if condition fails because we have to wait, set lastButtonState=1", loop(), loop(),loop(),"loop() enough time has passed, but since no button press at in this iteration and the last few, reading and lastButtonState equal zero", loop(), ...

@thegoodhunter-9115 seriously think about what i said about the light and the stopwatch .... what would you do with the stopwatch if the light turned on or turned off?

@jsotola, I think I get it now. I (think) couldn't understand it due to my ignorance of how "long" a button press is and how many times loop() would run during a single press. Just to make sure: During the 50 ms (debounceDelay), the button would be remain in the pressed state by the user (even though it was just a click), and during that time, loop() would run multiple times (so, it would "remember" what reading was). I was thinking that the 50 ms would pass in one call of loop(). I could still be wrong in my understanding, but thank you kindly for your help, and sorry for the annoyance.

@DataFiddler Thank you kindly for your help and patience. I elaborated why (I think) I had this misunderstanding in my comment above to jsotola (in this thread). Thank you again.

@thegoodhunter-9115 thank you for the explanation of your misunderstanding ... i learned something from you today ... i now know that the loop() execution time can be the source of confusion

@thegoodhunter-9115 you can do a simple test ... write a sketch that, in setup(), prints the value of millis() and sets a counter to zero .... in loop() increments the counter ... when the counter reaches 1000, prints millis() again .... that will give you an idea of approximately how long 1000 iterations of loop() take

Alright. Thank you again, @jsotola.


text:
Bluetooth no COM port connection? ESP32
I am experiencing issues sending serial data via bluetooth with my ESP32. When the device is plugged in, I am able to call bluetooth, and connect to PC and even obtain the serial data via the registered bluetooth COM port after connecting. Though, once I remove the USB power, and power the ESP32 with a battery, I am still able to connect to the PC, but the COM port disappears therefore leaving me unable to choose the port to send data over.
I've tried adding this device to COM port but when I try to add my ESP connected device, I am returned with "parameter is incorrect".

.
.
Usually the COM port is listed here

I know others have posted about this to other forums but none of seemed to solve the problem cut and dry. I also experienced this issue with HC-05 on Arduino Nano
Would appreciate any help I can get with this. I'm sure there is a simple solution that I just haven't come cross yet, as I'm relatively new to all this
Thx in advance

What battery are you using to power it?

Perhaps the COM-port you're trying to access is the one provided by the USB chip that might not be powered when you use a battery? If you can, get power from a USB power bank or a USB phone charger, and see if the COM port appears again.


text:
AT Commands ESP8266 Arduino IDE serial monitor not print any data from server. It say 408 request timeout
i am new in arduino and ESP8266 module. I am still learning about AT command. But i found this problem:
1.My website code (index.html)-http://nyalalampu.atwebpages.com:

<?php
        ECHO $_GET['subject'];
?>

2.My AT commands (In Arduino IDE Serial Monitor)
AT+CIPSTART="TCP","nyalalampu.atwebpages.com",80

CONNECT

OK
AT+CIPSEND=29

OK
>
Recv 29 bytes

SEND OK

+IPD,391:HTTP/1.1 408 Request Timeout
Date: Sat, 10 Oct 2020 17:00:24 GMT
Server: Apache
Content-Length: 221
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>408 Request Timeout</title>

Request Timeout

Server timeout waiting for the HTTP request from the client.

CLOSED

After > i put
GET /?subject=anis HTTP/1.0

My question is why it not print anis in Arduino IDE Serial Monitor? It just show 408 Request Timeout
I hope someone can tell me what's wrong with my code.TQ

you must end the GET request with \r\n. how do you send it?

Does this answer your question? ESP8266 ESP-01 not show data from server in Arduino IDE serial monitor

I just send like you say sir...but it send back Bad Request when i put \r\n like this GET /?subject=anis HTTP/1.0 \r\n

@Juraj I just send like you say sir...but it send back Bad Request when i put \r\n like this GET /?subject=anis HTTP/1.0 \r\n

@Juraj Yes...i have learn something new...tq sir...what i know is AT+CIPSEND value should same the count of character plus 2

/?subject=anis HTTP/1.0 \r\n the space before \r\n shouldn't be there

@Juraj still get Bad Request after i remove space

you have the GET line in the sketch or you try to send it from Serial Monitor?

@Juraj in Serial Monitor sir

then remove \r\n and after sending the GET line, try to press Enter immediately one more time. does the server accept insecure http? does it accept HTTP 1.0?

you need "host" header


text:
No response in Serial Monitor from es8266 with Arduino nano
I have exactly this model of esp8266:

I removed Atmega328p IC from Arduino, and powered Arduino with USB cable. After all, I made this connection combinations:
1)
ESP Tx > Arudino Tx
ESP Rx > Arduino Rx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd
ESP GPIO0 > GND

2)
ESP Tx > Arudino Rx
ESP Rx > Arduino Tx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd
ESP GPIO0 > GND

3)
ESP Tx > Arudino Tx
ESP Rx > Arduino Rx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd

4)
ESP Tx > Arudino Rx
ESP Rx > Arduino Tx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd

I checked both 9600, and 115200 baud, but on any of them I did not get a reply to the AT command. Have I done something wrong? I get weird characters when disconnecting ESP's GND wire, so some communication exists.

with io 0 LOW the esp8266 starts in flashing mode. add a pull-up resistor for io 0. the TX pin of nano is wired to RX pin of the USB chip. so to have RX to TX wire TX to TX :-)

how did you remove the ATmega from Nano?

If it is not a genuine Arduino (Chinese clone probably) and it has the CH340 USB to Serial converter chip, then it will not work as the digital Signal on TX does not get pulled to ground when transmitting a digital LOW, (if that's the right way to say it). There seem to be resistors on the board that cause this effect, or something. I do not guarantee that this is your problem but it's highly likely.
Use an FTDI USB to Serial board or similar and you might have better results.


text:
My nodemcu esp8266 is heating a lot and the on board LED of gpio16 is On continuously. What's the Reason of heating?
How it happened
Recently I was working on a device with Blynk application in which my device will burn crackers using Blynk. I wanted to create a safe environment for burning crackers. There was a dilemma to power Nodemcu with a battery first I used a 38650 lion battery but it didn't provide sufficient power to Nodemcu. Than I connected two 38650 battery in series than it was working fine for half a minute. But later it started became hot but than I removed the power supply immediately and powered it with 3.3v charger than also it was heating and still.
My research
I researched a lot and also changed the S4 didode with IN4007 but it is still heating and malfunctioning. I checked all the parts but they were not shorted. What's the problem with my Nodemcu why is it heating and not working properly.
With regards
Naman

heating is caused by too much current being drawn

what do you have connected to the nodemcu? ... how is it conected?

How did you connect the batteries? 2. What else is connected to the NodeMCU? 3. Where exactly (which component) does the heat come from?

Ok so my Nodemcu is connected with RELAY of 5v the heat is coming from the microcontroller.

And can you answer question 1? How did you connect the batteries?

What is the output voltage of your Lion batteries? The Nodemcu is a 3.3V device. It's voltage regulator needs an input voltage of  7V - 12V, based on the searching I did. If your batteries put out ≈10V then 2 of them in series is too much for the input of the NodeMCU's voltage regulator.

In series both batteries took out 7

Volt and 4000 mah

Is it too much ??


text:
Can't change pins in AM2320 code, types mismatch
I took a simple A2320 temperature sensor and connected it not to  A4/A5, but to A1/A0 pins. SDA => A1, SCL => A0. (In C code they are number 15 and 14). But I can't call the library to take these pins.
The basic example from the library uses the default values, probably from some tutorial.
I read the .h and .cpp files and see these definitions:
Adafruit_AM2320::Adafruit_AM2320(TwoWire *theI2C, int32_t tempSensorId,
                                 int32_t humiditySensorId)
    : _temp(this, tempSensorId), _humidity(this, humiditySensorId),
      _i2c(theI2C) {}

bool Adafruit_AM2320::begin() {
  _i2caddr = 0x5C; // fixed addr
  _i2c->begin();
  return true;
}

I just tried to make types match. Not even port number.
I declared a TwoWire instance and passed it to AM2320 constructor, but without success:
#include "Wire.h"
...
TwoWire mywire();
Adafruit_AM2320 am2320 = Adafruit_AM2320(mywire, -1, -1); // as the default values

Outputs in error log:
error: no matching function for call to 'Adafruit_AM2320::Adafruit_AM2320(TwoWire (*)(), int, int)'
    Adafruit_AM2320 am2320 = Adafruit_AM2320(&mywire, -1, -1);
In file included from testproj.ino:2:0:
...Adafruit_AM2320.h:52:3: note: candidate: Adafruit_AM2320::Adafruit_AM2320(TwoWire*, int32_t, int32_t)
   Adafruit_AM2320(TwoWire *theI2C = &Wire, int32_t tempSensorId = -1,
   ^~~~~~~~~~~~~~~
...Adafruit_AM2320.h:52:3: note:   no known conversion for argument 1 from 'TwoWire (*)()' to 'TwoWire*'

What am I doing wrong?

Two problems:

When you create an object instance with no parameters you must not have parentheses. You should construct thus:

TwoWire mywire;

The constructor expects a pointer to an object, not an object. Just take the address of the object with & and pass that:

Adafruit_AM2320 am2320 = Adafruit_AM2320(&mywire, -1, -1); // as the default values

However
Most Arduino boards have the I2C pins hard-wired internal to the chip and can't be changed. You would need to use some form of software implementation that is also a polymorphic child of the TwoWire class. If such a thing exists.


text:
Rc switch library display received values only one times using serial monitor
I use Rc switch library to transmit and receive data. It works fine.
The part that sends the data is as follows :
#include <Arduino.h>
#include <RCSwitch.h>

RCSwitch transmitter = RCSwitch();

void setup()
{
    Serial.begin(9600);
    transmitter.enableTransmit(10);
}

void loop()
{
    /* Send data in binary */

    // Go right
    transmitter.send("010101010101010100000011");
    delay(1000);

    // Go left
    transmitter.send("010101010101010100001100");
    delay(1000);
}

And the receiving part is like this:
#include <RCSwitch.h>

RCSwitch receiver = RCSwitch();
int rightLED = 4;
int leftLED = 7;
unsigned long receivedValue;
unsigned long goRight = 5592323;
unsigned long goLeft = 5592332;

void setup()
{
    Serial.begin(9600);
    receiver.enableReceive(0); // Receiver on interrupt 0
    pinMode(rightLED, OUTPUT);
    pinMode(leftLED, OUTPUT);
}

void moveRight()
{
    Serial.println("I'm going right");
}

void moveLeft()
{
    Serial.println("I'm going left");
}

void loop()
{
    if (receiver.available())
    {
        receivedValue = receiver.getReceivedValue();
        if (receivedValue == goRight)
        {
            moveRight();
        }
        if (receivedValue == goLeft)
        {
            moveLeft();
        }
        receiver.resetAvailable();
    }
}

The problem is, when I open a serial monitor and look the output of the received values moveRight and moveLeft functions are called multiple times.
I'm going right
I'm going right
I'm going right
I'm going right
I'm going left
I'm going left
I'm going left
I'm going left
I'm going right
I'm going right
I'm going right
I'm going right

What kind of change should I do in the receiver part so that moveRight and moveLeft functions are called only once.
I'm going right
I'm going left
I'm going right

You can save the previous received value, and only print if it is different from what you just received.
Something like this:
// near the top
const int rightLED = 4;
const int leftLED = 7;
const unsigned long goRight = 5592323;
const unsigned long goLeft = 5592332;

// to hold the state
unsigned long previousValue = 0;

// ...

// loop code
void loop()
{
  if (receiver.available())
  {
    unsigned long receivedValue = receiver.getReceivedValue();
    if (receivedValue != previousValue) {
      // something changed
      if (receivedValue == goRight)
      {
        moveRight();
      }
      if (receivedValue == goLeft)
      {
        moveLeft();
      }
      // remember the current value
      previousValue = receivedValue;
    }
    receiver.resetAvailable();
  }
}

Depending on you application, you might also want to store the time of the last received value, and compare that. Otherwise, when pressing the same button twice, it will ignore the last press.

Old post, I know but I have to add to it.  The statement   "transmitter.enableTransmit(10);" causes the RCSwitch library to send the message 10 times.  You are receiving 4 messages; you should be receiving 10. I have found that when using "receiver.available()" I also get about half of what is expected. Just a hunch, but I think the "receiver.available()" is getting every other message.  The RCSwitch library may have a dwell period after a message is received that holds the receiver in suspense causing every other message to be lost.  "Serial.begin(9600)" also is a bit slow, but I think the buffer can handel it.
The attached image shows my transmitter power consumption.  You can see that 10 messages are sent in about 200 mS.  Your delay(1000) leaves plenty of time for completion of all messages received.


text:
RadioHead library change the state when a new message is received
I would like to control a toy car from the server. I use RadioHead library for communication and it works fine.
The application running on the server side is as follows.
#include <RHReliableDatagram.h>
#include <RH_ASK.h>
#include <SPI.h>

#define SERVER_ADDRESS 1
#define ROBOT_ADDRESS 2
#define GO_RIGHT "Go right"
#define GO_LEFT "Go left"
#define GO_FORWARD "Go forward"
#define GO_BACK "Go back"
#define STOP "Stop"
#define SERVER_DELAY 500

unsigned int transmitterPin = 10;
unsigned int receiverPin = 12;

RH_ASK transmitterServer(2000, receiverPin, transmitterPin, 0);

RHReliableDatagram radioCommunication(transmitterServer, SERVER_ADDRESS);

void setup()
{
    Serial.begin(9600);
    if (!radioCommunication.init())
        Serial.println("Radio communication failed");
}

uint8_t buffer[RH_ASK_MAX_MESSAGE_LEN];

void sendData(uint8_t * data, uint8_t length)
{
    Serial.println("I'm sending commands to the robot");

    // Send a command to the robot
    if (radioCommunication.sendtoWait(data, length, ROBOT_ADDRESS))
    {
        // Now wait for a response from robot
        uint8_t from;
        if (radioCommunication.recvfromAckTimeout(buffer, &length, 2000, &from))
        {
            Serial.print("I've got - ");
            Serial.print((char*) buffer);
            Serial.print(" - message from the robot whose addres is : ");
            Serial.print("0x");
            Serial.println(from, HEX);
        }
        else
        {
            Serial.println("No response. Does the robot works?");
        }
    }
    else
        Serial.println("Attempt to resend data failed.");
    delay(SERVER_DELAY);
}

void loop()
{
    sendData(GO_RIGHT, sizeof(GO_RIGHT));
    sendData(GO_LEFT, sizeof(GO_LEFT));
    sendData(GO_FORWARD, sizeof(GO_FORWARD));
    sendData(STOP, sizeof(STOP));
    sendData(GO_BACK, sizeof(GO_BACK));
    sendData(STOP, sizeof(STOP));
}

The application running on the robot is as follows.
#include <RHReliableDatagram.h>
#include <RH_ASK.h>
#include <SPI.h>

#define SERVER_ADDRESS 1
#define ROBOT_ADDRESS 2
#define GO_RIGHT "Go right"
#define GO_LEFT "Go left"
#define GO_FORWARD "Go forward"
#define GO_BACK "Go back"
#define STOP "Stop"
#define RIGHT_LIGHT 4
#define LEFT_LIGHT 7
#define FORWARD_LIGHT 8

unsigned int receiverPin = 2;
unsigned int transmitterPin = 12;

RH_ASK robotTransmitter(2000, receiverPin, transmitterPin, 0);
RHReliableDatagram radioCommunication(robotTransmitter, ROBOT_ADDRESS);

void setup()
{
    Serial.begin(9600);
    pinMode(RIGHT_LIGHT, OUTPUT);
    pinMode(LEFT_LIGHT, OUTPUT);
    pinMode(FORWARD_LIGHT, OUTPUT);

    if (!radioCommunication.init())
        Serial.println("Radio communication failed");
}

uint8_t buffer[RH_ASK_MAX_MESSAGE_LEN];
uint8_t command[RH_ASK_MAX_MESSAGE_LEN];

void moveRight()
{
    Serial.println("------------");
    Serial.println("I'm going right");
    Serial.println("------------");

    /*
       // Time consuming task

    for (int i = 0; i < 3; ++i)
    {
        digitalWrite(RIGHT_LIGHT, HIGH);
        delay(1000);
        digitalWrite(RIGHT_LIGHT, LOW);
        delay(1000);
    }

    */
}

void moveLeft()
{
    Serial.println("------------");
    Serial.println("I'm going left");
    Serial.println("------------");

    /*
       // Time consuming task

    for (int i = 0; i < 3; ++i)
    {
        digitalWrite(LEFT_LIGHT, HIGH);
        delay(1000);
        digitalWrite(LEFT_LIGHT, LOW);
        delay(1000);
    }

    */
}

void runCommand(char* command)
{
    if (strcmp(command, GO_RIGHT) == 0)
    {
        moveRight();
    }
    else if (strcmp(command, GO_LEFT) == 0)
    {
        moveLeft();
    }
}

void loop()
{
    uint8_t response[] = "OK";
    if (radioCommunication.available())
    {
        uint8_t length = sizeof(buffer);
        uint8_t from;
        if (radioCommunication.recvfromAck(buffer, &length, &from))
        {
            Serial.print("I got - ");
            Serial.print((char*) buffer);
            Serial.print(" - command from the server whose addres is ");
            Serial.print("0x");
            Serial.println(from, HEX);
        }
        // Send the message to the server (with retries) and wait for an ack.
        if (!radioCommunication.sendtoWait(response, sizeof(response), from))
            Serial.println("Repeated attemps to send data to server failed");
        strncpy(command, buffer, sizeof(command));
        runCommand(command);
    }
}

As it stands, the serial output of robot is as follows:

Let's increase the SERVER_DELAY variable to 2000. This way the server will send a command every two seconds.
Besides this, let's run a command that will take some time on the robot. To do this we might uncomment time consuming task lines.
So that, when the robot receives Go right command, it will try to turn on and off lights three times.
After making these changes let's look at the serial output of robot.

What happens is, after receiving the Go left command it tries to blink LEFT_LIGHT three times. But meanwhile it misses Go forward command. And again after receiving the Go right command it tries to blink RIGHT_LIGHT three times but misses Go left command.
What I would like to do is when robot receives a new command, it should stop whatever it was doing and execute the new command.
How should I do this? Any ideas. Thanks.

An easy-enough fix would be to replace your delay calls with something that regularly checks if data is available from the server.
Something like:
/* returns true if the sleep was interrupted by incoming data */
/* warning: does not wait at all if data is available */
bool interruptible_delay(unsigned long ms)
{
  unsigned long end = millis() + ms;
  while (millis() < end) {
    if (radioCommunication.available()) {
      return true;
    }
    delay(10); /* tune to taste */
  }
  return false;
}

This should work as long as the innner delay is much shorter than your communication timeouts.
You will most likely need to handle the case where the sleep was interrupted in your "action" functions if they become more complexe than a led blink. I.e. if your action is a series of complex motor moves, and a message arrives in the middle, you need to design the function so that it is in a safe or neutral state before returning to the main loop.

I was about to figure out that might be related to delay function. Your solution is brilliant. It works like a charm. Thanks.