text:
Where are these junk characters (from serial) coming from?
I currently have 2 Arduinos both hooked up to HC-12s and have successfully got them communicating. But I am now trying to be able to process the data sent across and store it as a variable so as to make comparisons. But I'm getting junk data that comes over with the code, which prevents me from being able to do these comparisons.
For example, from one arduino when I sent "stop" I received
stop<⸮=l⸮⸮⸮

I cant figure out what this junk is from, also, I've limited the receivedChars to a size of 4, why am I getting more than 4 characters?
The code from the sender
#include <SoftwareSerial.h>

SoftwareSerial HC12(3, 2); // HC-12 TX Pin, HC-12 RX Pin

void setup() {
  Serial.begin(9600);             // Serial port to computer
  HC12.begin(9600);               // Serial port to HC12
  Serial.print("Checking HC-12 module: ");
  HC12.write("AT");               //Check for response(this is sending data to the HC, the SET pin must be low for this to work)
  delay(1000);
  HC12.write("AT+RX");            //Gets configs of HC-12
}

void loop() {
  while (HC12.available()) {        // If HC-12 has data
    Serial.write(HC12.read());      // Send the data to Serial monitor
  }
  while (Serial.available()) {      // If Serial monitor has data
    HC12.write(Serial.read());      // Send that data to HC-12
  }
}

The simplified receiving code
    #define BYTELENGTH 4 //Limited to 4 chars
       #define ENDMARKER '\n'  //To know when stop stop reading serial

       SoftwareSerial HC12(3, 2); // HC-12 TX Pin, HC-12 RX Pin

  Serial.begin(9600); //Fastest it can be on the nano
  HC12.begin(9600); // Serial port to HC12s

      char receivedChars[BYTELENGTH - 1];
      int byteIndex;
      char curChar;

      while (HC12.available()) {        // If HC-12 has data
        curChar = HC12.read();
        if(curChar != ENDMARKER){
          receivedChars[byteIndex] = curChar;
          byteIndex++;
        }
      }
      if(strcmp(receivedChars,"") != 0){
        Serial.println(receivedChars);
        receivedChars[0] = 0;
      }

Btw: 9600 baud is not the fastest, that the Nano can get. The HardwareSerial interface Serial can also work with baudrates of up to 2 Megabaud. The problem with these baudrates is only, that you cannot provide the data in that speed. But 9600 baud is rather slow, even for the Nano. The real bottleneck here is the SoftwareSerial library. I think it can handle up to 38400 baud without problems. 11520 baud might also work, though I think that is very hard at the limit.

The software serial is temporary, just for testing. I did have everything at 115200 baud but was running into issues. That would explain that one!

I would say you are printing data outside of your char array, because you didn't terminate the C-string in it and the size of your array is too small.
You have
#define BYTELENGTH 4 //Limited to 4 chars
char receivedChars[BYTELENGTH - 1];

so your char array is only 3 elements big. When you want to save a string in that array, you always need to terminate it with a null character \0 (which is also zero in decimal representation). So in that char array you only have space for 2 characters. But your message "stop" is 4 characters long, so you need a char array with at least 5 elements. If you are not in an extreme tight memory situation I would suggest using a buffer with a bit headroom above your biggest message (to be sure, that nothing breaks, if you later use messages that are a bit longer). So more like this:
#define BYTELENGTH 10 //Limited to 4 chars
char receivedChars[BYTELENGTH + 1]; // message length + null character termination

And then you need to change your receiving code to add a null character at the end of the message. Also you might want to actually use the newline character \n as message delimiting (which you are currently not doing):
bool full_message_received = false;

void loop(){
    while (HC12.available()) {        // If HC-12 has data
        curChar = HC12.read();
        if(curChar != ENDMARKER){
          receivedChars[byteIndex] = curChar;
          byteIndex++;
        } else {
          receivedChars[byteIndex] = '\0'; // terminating the c-string
          full_message_received = true; // marking the message as fully received
        }
    }
    if(full_message_received){
        Serial.println(receivedChars);
        receivedChars[0] = 0;
        full_message_received = false;
    }
}

What happens, if I don't terminate the string with a null character? All the functions, that handle C-strings (like strcmp() or also Serial.print()) use the null character to determine, at which point the string is at its end. They don't know the size of your array, so they just read byte after byte, until they reach the null character. They even read more data than is in your array. The junk characters are most likely exactly, what currently is placed in the memory directly after your array. Serial.print() doesn't know, that they don't belong to the C-string, since you didn't use the null character to tell it that. It just keeps printing characters, until it reaches a byte, that is zero.
You even wrote data to memory outside of the array. Depending on what comes directly after your array in the memory this can be without any problems, but you might also overwrite some other data, without knowing, what that data is. That can lead to very weird and hard to debug problems. Be sure to never write outside of your array. You might break things in weird ways.

So when ENDMARKER is reached (in this case \n), you are telling it to terminate the rest of the array. Then when I print it out or do anything with it, I shouldn't be reaching into additional memory spaces. But then I'm not even seeing the \n because the array length is too short.
So to fix it, I need to make sure my array can fit at least 4 chars, + the \n (which should be sent by the other Arduinos serial monitor right?), then have my code searching for it and terminate the array after it. Am I understanding correctly?

nearly correct.  You need your array to fit 4 chars + the terminating null character. In my code above I don't include the \n in the array. Normally you don't need that character in there, since it is only used for delimiting individual messages on the serial interface. And the \n is also read and printed, if your array is too small. But then this data overwrites the memory space after the array, which can be very bad.

So for preventing writing and reading outside the array you need to make the array big enough for every possible message, that you might get. You read until the \n to only read one full message at a time (each individual message delimited by the \n on the serial interface). And for using the received data as a c-string (for example for printing) you need to terminate it with a null character.

It appears you have a baud rate problem. I am surprised you are getting anything. You need software to start the serial port such as SoftwareSerial mySerial(rxPin, txPin) then in setup  mySerial.begin(9600); You need that in each application and the baud rates need to be the same.
I have used SC16IS750 I2C/SPI-to-UART devices as an external UART, they work great and have many nice features such as a 64 bytes of transmit and receive FIFOs. Some versions of this have been obsoleted but they are still available and work fine. You get 8 additional I/Os as well.

I do have it, just excluded it to avoid posting all my code. Just made the edit. Im guessing there is either something about serial or the char array that im missing thats adding the extra junk

The softwareserial operates in half duplex. It is interrupt driven and if other interrupts are occuring that can cause problems. Here is a link/discussion that may help you a lot. https://electronics.stackexchange.com/questions/23265/arduino-software-serial-full-duplex. The more information given generally the better. If there is additional hardware connected post a schematic with links showing technical information on the devices.

That is actually an issue I've noticed, I'm hoping to get rid of software serial altogether. It just made programming simpler for the time being, but it seems to be causing some issues so I might need to expedite moving over.

According to this vidéo in French it appeared that the problems comes from the SoftwareSerial library which if not reliable enough to provide accurate timings for your transmission. There are alternate software serial libraries (like AltSoftSerial), which use hardware timers, but I can't tel you more because I didn't try to use it.
All I can say, is that I my case removing SoftwareSerial to use the defaut hardware serial port solved the problems I had.
Alternatively, you can use I²C ⇒ UART IC like MAX3100, in order to provide aother hardware UART (With MAX3100 you'll need to add a 3.6468 or 1.8234 MHz crystal and 2×22pf capacitors) - I also didn't try it yet (Chip and crystal are ordered though. Or also you should be able to make the i2c ⇒ UART conversion with one more Arduino.

SoftwareSerial is ok at 9600 baud. the accepted answer explains the true problem.

This is not true, @Juraj. It largely depends on transmission speed. Even at 9600 bps, I got character losses, when I didn't add delays to slow it down. This didn't arises with the hardware port.


text:
SPI - different implementation / timing
I'm a little bit confused. I'm running the same code on a ESP32 (Adafruit Huzzah32) and an Arduino (SparkFun Pro Micro). It works on the ESP32 but not on the Arduino.
Are there different API implementations?
It seems that the timings are not the same. The Arduino does not have the gaps between the bytes.

Maybe the other side you didn't mention is a problem. There is possibility it needs more time to prepare result (before you start sending dummy bytes). But as you didn't mention what is the other side, nobody knows.

Thanks for your answer. I'm not waiting for results. The 2 '0's are just attached to make it more clear. I'm asking because i'm wondering why there are no gaps between the bytes ...

should there be wider gaps? ... the logic analyzer doen not appear to need wider gaps

No, but my SPI module seems not to understand the commands if there are not any delays. The second picture shows the same command without any delays between the bytes. My main question is, why does the ESP32 have delays and the Arduino does not? and how can i fix this without rewrite the SPI commands?

the speed is not the same

I've checked the speeds. the arduino sends with 125MHz but i need 80kHz. I didn't look at it because i've set the spi settings SPISettings _spiSettings( 80000, MSBFIRST, SPI_MODE0 ).  I played around with SPI.setClockDivider() but i cant achieve such a low rate. Any suggestions?

https://www.arduino.cc/en/Reference/SPI

source: Stack Exchange

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

sort: votes


text:
How can I rewrite Arduino Code using SPI library into C++?
The issue is that I have code using an Arduino library and need to convert it into C++ so I can use it with a raspberry pi on ROS (Robot operating system). Does anyone know the best way to change it over or know of good resources?
I know that Arduino is essentially C++ but I am uncertain about how to make Arduino libraries into C++.

Arduino libraries already are C++.

Thank you! So I do not need to rewrite anything to use Arduino code in C++? Or do I just need to call the library differently?

Depending on the library you may need to reimplement standard Arduino API calls, like digitalWrite, etc. Or just implement your own copies of whatever functions are needed using whatever ROS provides.

The Arduino API is just a collection of C++ functions and classes. If a library needs one of those functions or classes then just implement it (if ROS doesn't already provide it. No idea what or who ROS is).

Ok, that helps. I am trying to get a grasp on the differences between Arduino and generic C++. (ROS is Robot Operating system and works only on Linux so Arduino doesn't work with it so I am transforming code to work with it on a Rasberry pi).

The Arduino compiler is a GNU C++ compiler HOWEVER there is no c runtime library (which is not part of the compiler).
Probably more significant to the question is that the Arduino compiler supplies support for the ATMEL hardware. This is incompatible with the Raspberry Pi.
The Arduino is a real time microcontroller and has unrestricted access to its hardware, the Pi usually runs a multi-tasking OS, the hardware is not directly accessible from user space, so many tasks need to be written differently; often this means relying on a OS supplied kernel driver.
Any practicable Arduino program would require extensive changes to work on the Raspberry Pi. The effort involved is likely to be more than writing a Raspberry Pi program from scratch.

The sometimes-called "Arduino Language" is C++, but with some upfront work - primarily supplying file inclusions - done for you if you don't.
The Arduino compiler is a GNU C++ compiler. If you write or supply standard C++ to the Arduino IDE, it will compile it.

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


text:
how to interrupt the loop function and restart it?
I have a project with some NeoPixels and other LEDs and an Arduino UNO.
Once switched on, the defaultLEDAnimation with colors and blinking, etc. starts.
I want to trigger some other animations, so I connected two buttons to the Arduino. Whenever you press button1, the Arduino should stop everything it is doing and run animation1. The same goes for button2. if you press it, the Arduino should run animation2. All animations are quite complex and run for several seconds and even minutes.
Now for the challenge: How do I use the two buttons to immediately stop every animation happening and display the appropriate animation?
The tried using interrupts and connected the two buttons to pin 2 and 3.
However, when I press the buttons, the animation starts after several seconds delay. Is there any way to restart the loop function immediately after the interrupt has been made? Or is there another way to trigger my animations with those two buttons?
The code looks something like this:
#define button1 2
#define button2 3

volatile bool shouldPerformButton1Action = false;
volatile bool shouldPerformButton2Action = false;

void setup() {
    attachInterrupt(digitalPinToInterrupt(button1), button1Pressed, RISING);
    attachInterrupt(digitalPinToInterrupt(button2), button2Pressed, RISING);
}

void loop() {
    if (shouldPerformButton1Action) {
        doAnimation1();
        shouldPerformButton1Action = false;
    } else if (shouldPerformButton2Action) {
        doAnimation2();
        shouldPerformButton2Action = false;
    } else {
        runDefaultAnimation();
    }
}

void button1Pressed() {
    shouldPerformButton1Action = true;
}

void button2Pressed() {
    shouldPerformbutton2Action = true;
}

void doAnimation1() {
    for(int i=0; i<10; i++){
        neoPixelStrip.setPixelColor(neoPixelArray[i], neoPixelStrip.Color(255, 0, 0, 255));
        neoPixelStrip.show();
        delay(100);
    }
    delay(1000);
    for(int i=0; i<10; i++){
        neoPixelStrip.setPixelColor(neoPixelArray[i], neoPixelStrip.Color(0, 0, 0, 0));
        neoPixelStrip.show();
        delay(100);
    }
}

The function doAnimation1 is just an example. It will be much more complex.

Make the animation functions non-blocking, so that you can react immediately to the buttons. You don't even need interrupts for this. Please show us an example for the animation functions

You have to show us the animation routines, that's where the magic has to take place. Restarting the loop() is not the way something like that is implemented. You probably have another (blocking) loop in the animations and that's where you have to define an exit clause which has to by triggered by the corresponding button press.

The clean solution, as explained in Duncan C's answer, is to make the animation code non blocking. If this is too inconvenient, you may try to longjmp() directly from the ISR to the main loop.

@EdgarBonet: how exactly do you make the animation code non blocking?

See my answer. I outline in some detail how to make the animation code non-blocking.

Basically you have to make the animation loops return if the condition is met, for example:
void doAnimation1() {
    for(int i=0; i<10; i++){
        if (digitalRead (button1) == HIGH)  // Time to stop?
           return;
        neoPixelStrip.setPixelColor(neoPixelArray[i], neoPixelStrip.Color(255, 0, 0, 255));
        neoPixelStrip.show();
        delay(100);
    }
    delay(1000);
    for(int i=0; i<10; i++){
        if (digitalRead (button1) == HIGH)  // Time to stop?
           return;
        neoPixelStrip.setPixelColor(neoPixelArray[i], neoPixelStrip.Color(0, 0, 0, 0));
        neoPixelStrip.show();
        delay(100);
    }
}

If you don't want to wait for the 100 ms delay (or the 1000 ms delay) then you could replace that with code that waits for 100 ms to elapse, but also checks the button.
Interrupts are not the way to do it. Interrupts let you briefly stop doing something, do something else, then go back to what you were doing before. They don't "interrupt" your entire workflow.
For example, you might interrupt your movie watching to answer the phone, you don't "interrupt" your movie watching to go out to dinner with a friend. That is just a case of doing a different thing.

I thought I can avoid asking for the buttonState in every animation step. That makes things very complex.

Well, most of that code of yours could be put into a function. For example, number of loops, starting colour, ending colour, delay inbetween. Then that function is the one that decides whether to stop or not.

I implemented it exactly like that. Thanks.

"How to interrupt the loop function and restart it?"
You don't. That's not how you write Arduino code. You need to have your loop function call a series of non-blocking functions that check to see if it's time to do something, do a very small bit of work if it is time, or just return if it's not time yet.
What I've done is to create a class ArduinoObject that has a setup function,  a start function, a stop function, a loop function, and a boolean property running. My main program has a global variable that holds an array of ArduinoObjects.
Every time through the loop, I check all the ArduinoObjects in the array, and call their loop functions.
The first thing each object does is check its running flag. If running==false, it exits immediately.
Each object uses unsigned long values to track the next millis() time count when it should do something.
Let's say the object does an animation, so it has an unsigned long nextAnimationStepTime. In the loop() function, if nextAnimationStepTime<millis(), it doesn't do anything. If instead nextAnimationStepTime>=millis(), the object advances the animation to the next step, and sets nextAnimationStepTime = millis() + animationStepDuration. That way, next time the object is called, it will wait until it's time to advance the animation yet another step.
Each object is written to only do a tiny bit of work on each pass through the loop, and return as quickly as possible.
With this design, I can add an arbitrary number of objects/tasks to my loop, and all of them get attention on every pass through the loop. Most objects simply decide they're not running, or it's not time to do anything, and return.
You can then add control logic that starts and stops individual objects based on things like button presses.
With this approach you'd have your button 1 press stop animation 2 if it was running and run animation 1. Conversely, pressing button 2 would stop animation 1 if


text:
Software I2C - ATmega8
I am using ATmega8 with 12MHz crystal, on my breadboard. I can use SDA and SCL pins with default arduino library wire.h, and it works. But I want another pins to use I2C protocol.
I tried this library, even on real SDA and SCL pins, but it doesn't work.
I have pull up resistors, I tried with 10k and 4.7k without any success. (But those resistors worked with hardware I2C | TWI)
What am I doing wrong? (All connections is fine, because hardware TWI works but software does not.) Thank you for your help.
(Fuses are ok, because the Atmega won't respond if I remove the crystal oscillator, the LED blinking duration is ok.)
What i want to run (that doesn't work):
#define SDA_PORT PORTC
#define SDA_PIN 4
#define SCL_PORT PORTC
#define SCL_PIN 5

//#define I2C_TIMEOUT 100

#include <SoftI2CMaster.h>

uint8_t ADDR  = 0x68;

void setup(void) {

  Serial.begin(19200);
  Serial.println("Initializing ...");
  i2c_init();

  if (!i2c_start(ADDR | I2C_WRITE)) Serial.println(F("Device does not respond"));
  if (!i2c_write(0x00)) Serial.println(F("Cannot address reg 0"));
  i2c_stop();
}

void loop (void) {
  unsigned int low0, high0, low1, high1;
  unsigned int chan0, chan1;
  unsigned int lux;
  int state1;
  int state2;

  delay(1000);
  i2c_start(ADDR | I2C_WRITE);
  i2c_write(0x00);
  i2c_rep_start(ADDR | I2C_READ);
  low0 = i2c_read(false);
  high0 = i2c_read(false);
  low1 = i2c_read(false);
  high1 = i2c_read(true);
  i2c_stop();
  Serial.print(low0);
}

And the code with hardware TWI that works:
#include "Wire.h"
#define DS3231_I2C_ADDRESS 0x68
// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
  return( (val/10*16) + (val%10) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
  return( (val/16*10) + (val%16) );
}
void setup()
{
  Wire.begin();
  Serial.begin(19200);
  pinMode(13, OUTPUT);
  pinMode(5, INPUT);
}
void readDS3231time(byte *second,
byte *minute,
byte *hour,
byte *dayOfWeek,
byte *dayOfMonth,
byte *month,
byte *year)
{
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0); // set DS3231 register pointer to 00h
  Wire.endTransmission();
  Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
  // request seven bytes of data from DS3231 starting from register 00h
  *second = bcdToDec(Wire.read() & 0x7f);
  *minute = bcdToDec(Wire.read());
  *hour = bcdToDec(Wire.read() & 0x3f);
  *dayOfWeek = bcdToDec(Wire.read());
  *dayOfMonth = bcdToDec(Wire.read());
  *month = bcdToDec(Wire.read());
  *year = bcdToDec(Wire.read());
}

Schematic is the same as: https://www.arduino.cc/en/main/standalone.
Except instead of 16MHz, I use a 12MHz and ch210x serial.
Arduino's bootloader works well, I compiled it from source.

It would help if you posted code and schematics of both situations (hardware and software I2C attempts). Also, to debug I2C effectively, you'd need a logic analyzer or at very least an oscilloscope.

What do you get on the serial output?

Initializing ...
Device does not respond
Cannot address reg 0
SDA - SCL 0 0
Raw values: chan0=65535 SDA - SCL 0 0

actually i should get the ohur:minute:second day/month/year that i can get in hardware twi,

i ve removed some of code, just before he stop function , i get the pinstate to whats happening, so that output is showed

OK let me cry till morning...
i was having this issue during day, but the solution was sooo easy
i need to pay attention more ...

i2c_start(addr | R/W-bit)
  Initiates a transfer to the slave device with the (8-bit) I2C address addr.

what i was trying is to push 7 bit address.
i hope this might help some others.
Thank you for help.

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


text:
Arduino 4G LTE Shield
Is there by any chance a shield that can take an 4G LTE compatible SIM card activated by a carrier and establish a connection?

Googling "4g shield arduino" gave this. It will need a 4G LTE capable SIM, but I guess "it depends" if any 4G LTE SIM will work..

This is a really old post but I also found this LTE shield which is much cheaper than the cooking hacks one.
Be carefully; this module is a dual band only (900/1800 MHz); no 850 or 1900 MHz.

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


text:
Are there any detail examples of Si4463
Recently, I bought two Si4463 chips, but I don't know how to use them. It seems complex. I'd like to know if there are any examples of an Si4463 used with an Arduino?

try this

@ARK   I am just a beginner of Arduino, do you know detail course about how to use 4463 ?

@ARK   In your web, there are many things, in fact, I don't know what is suitable and how to use it .

QAPRS library also on si4436 - thr rado APRS frames beacon example

This seems to be the Chip used on the RFM24. Have a look on the RadioHead Library:
http://www.airspayce.com/mikem/arduino/RadioHead/classRH__RF24.html
I normally use the same libs for the RFM69 (Semtech SX1231) with my Whisper Node and works fine. I would expect the same for the RFM24.
Btw, getting a silicon and building the Radio can be quite complicated. You might would consider starting with a Dev Kit or an assembled module.
Also, I don't think HopeRF produces RFM24 anymore, can't find on their site (http://www.hoperf.com/rf_transceiver/). If you just need it for a single project and does not intent to build a product of that, might be better chose a different/more popular option. Will be easier to find support for it on the Internet.

I've looked at the data sheet for this and I think it is the wrong choice of device for a beginner.  Can I suggest that you start by looking at a relatively simple DPI interfaced device, such as a sensor or RTC.  This will teach you the basics of sending commands via the Wire library.  You might even get the hang of it just by looking at existing libraries.
I can't find a library, so you are going to need to write your own.  The library will need a begin function which initialises you class and a write and read function, which write and read from an address.
void begin(void);
uint8_t read(const uint8_t& address);
void write (const uint8_t& address, const uint8_t& bytesOfData, const uint8_t* pData);

You will need to flesh those functions out, but that's it.  If you want to make you library more useable read the datasheet and create wrapper functions for each of the registers that can be accessed.
// This instruction requires 10 buts spread over two bytes.
void writeFrequencyOffset (const uint8_t& highByte, const uint8_t& lowByte)
{
  write (0x73, lowByte);
  write (0x74, highByte);
}

The process of creating friendly wrappers is a tedious operations, just reading the data sheet and translating that into code.

The part in question is an SPI peripheral, not an I2C one, so the wire library does not apply.

The Si4463 IC from Silicon Labs is a great communication chip with very good sensitivity. However, its onboard MCU uses SPI as a communication interface to communicate with an external microcontroller.
In a module such as an HC-12, an STM8SF103F3 microcontroller which is programmed to act as an SPI to UART bridge. HC-12 modules lets you control all of the internal functionality of the Si4463, even using AT+ commands for things like adjusting baud rate and transmission power. Unfortunately, the code doing the SPI to UART bridging is proprietary, which leaves you at a disadvantage if you're trying to use the Si4463 chips to build a real product.
But perhaps, if you have purchased something like the RFM26W module, or you simply have a bare-bones Si4463 IC to work with, then you will need to communicate with it via the SPI pins. It must be noted that there is no standard Arduino library available for communicating with the Si4463's SPI pins.
Working with SPI pins can get a bit complicated as you're trying to sync the clockwork. If you want to get your hands dirty, then you could go ahead and have a look at the Si4463 datasheet and look at the SPI timing parameters on page 16.
Fortunately, there is a Si4463 library project on GitHub which you can look into and perhaps modify the code to fit your needs.
Here is the GitHub page for the Si4463 Arduino library made by zkemble:
https://github.com/zkemble/Si446x
Here is the blog post where he explains it in more detail:
http://blog.zakkemble.net/si4463-radio-library-avr-arduino/
Here is the documentation for the said library:
https://zkemble.github.io/Si446x/_si446x_8h.html


text:
How do you control the amount of times the void loop loops per second?
int firstAnalogPin = 0;
int secondAnalogPin = 5;
int firstVal = 0;
int secondVal = 0;
void setup(){

  Serial.begin(9600);          //  setup serial

}

void loop(){

firstVal = analogRead(firstAnalogPin);
   // read the input pin

secondVal = analogRead(secondAnalogPin);
   // read the input pin

Serial.print(firstVal);

Serial.print("\t");

Serial.println(secondVal);

}

Basically, I want to know how to convert from the baud rate to the number of times loop() runs per second. How do I control the number of loop()s per second?

You don't. See the answers. Assuming you found that it looped (say) 1000 times per second, and then you added code to do something, knowing that, then the extra code would make it loop 900 times per second. So you allow for that, and then it loops 800 times per second. This is not the way to go about it.

If you don't need precise control, you can simple add a delay at the end of the loop.

how to set code while one loop is completed their work, then after the next loop is executed.

The number of times loop() runs every second depends on the time taken for the execution of the instructions within loop(). For instance, in your code, the time taken for one loop() is roughly equal to the time taken for the MCU to execute all the statements in loop() (more specifically, the time taken for each operation or function from call to return): in your case, the time taken for the Serial.print()s + the time taken for the analogRead()s (not considering any interrupts between statements).
That said, you generally don't want to control the interval between loop()s; I assume you actually want to control the interval between the execution of certain operations within your loop(). Say, you want to set the time between executions of analogRead(0) to 500 ms. This can be done like this:
#define INTERVAL 500   // time between reads
unsigned long lastRead = 0;

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

void loop(){
  //....your other code....

  if (millis() - lastRead >= INTERVAL){  // if INTERVAL has passed
    val = analogRead(0);
    lastRead = millis();
    Serial.println(val);
    //...anything else
  }

  //...your other code...
}

With this code, you now have about 2 analogRead samples every second. Of course, this is only useful if loop() runs faster than your chosen interval. If there are function calls, or any operations otherwise, in loop() (within or outside the IF block) that always take more time than your interval, then this code would serve no purpose.

If your goal is to control how often the sensor is polled and printed to SD card, I would suggest you check out Blink Without Delay https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay it would be a much cleaner way than trying to slow down the loop to a specified time.

Marcello Romani's SimpleTimer library was made for this kind of problem. You let loop() run as fast as possible but only maintain the timers and do other short tasks. The timer library runs your periodic tasks when necessary:
#include <SimpleTimer.h>
SimpleTimer timer;         // creates a set of timers

// A timer call-back function - there can be more than one
void onTimer(void){
   ;   // do stuff here, keep it short
}

void setup(void){
   ;   // Serial.begin() and other setup

   timer.setInterval(1000L, onTimer); // set a 1-sec repeating timer
}

void loop(void){
   timer.run();   // updates timers, maybe calls a callback func
   ;              // whatever other loop code
}


text:
Getting Nrf24l01 modules to work!
I am at my wit's end with these Nrf24l01s. A bit of history: I have ordered about 25 of these, tried the adapter board, read every article, tried every sketch (including Robin's tutorial), powered the modules with a separate power supply.
Has anyone else had these issues? Is there anything anyone has discovered on getting these to work? I am 12 years old and am trying to use these for a science project. Any help is greatly appreciated!!
Tnx,
Ricky
edit:
I went back to just the simplest "hello world" sketch and I can't even get this to work: nothing received in serial monitor (I did notice the Tx LED is lit in the receiver, is this correct?) Sorry if I posted this wrong.
//Include Libraries
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

//create an RF24 object
RF24 radio(9, 8);  // CE, CSN

//address through which two modules communicate.
const byte address[6] = "00001";

void setup()
{
  radio.begin();

  //set the address
  radio.openWritingPipe(address);

  //Set module as transmitter
  radio.stopListening();
}

void loop()
{
  //Send message to receiver
  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));

  delay(1000);
}

Receiver:
//Include Libraries
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

//create an RF24 object
RF24 radio(9, 8);  // CE, CSN

//address through which two modules communicate.
const byte address[6] = "00001";

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

  radio.begin();

  //set the address
  radio.openReadingPipe(0, address);

  //Set module as receiver
  radio.startListening();
}

void loop()
{
  //Read the data if available in buffer
  if (radio.available())
  {
    char text[32] = {0};
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }
}

Has anyone else had these issues? ... you did not describe any issues  .... Is there anything anyone has discovered on getting those to work? ... many people use them, so yes

please describe what you are doing with the modules and describe how your attempts fail .... and, please ask specific questions that do not have a simple yes/no answer

I am building a remote temperature/ humidity sensor. I am using 2 Arduino unos, dht22 sensor and of course the nrf24l01.  On the transmitter uno I can open up the serial monitor and see that the temp/ humidity is being displayed correctly so that part is working.  I am using the dht22 sensor libarary and the Tmrh24 libarary as recommended.  I seem at times to get some Random characters.  It seems when I touch the uno the board led tx does flash and acts differently when I hold the uno in my hand vs not. I am using male to female etc wires for connecting. I have also tryed the nrf24l01+ w ant 2

temperature and humidity values are irrelevant to the communication problem ... reduce your code to transmit and to receive only a single character .... remove the dht22 sensor ... get communication working first ... add the temperature code after .... add the wiring diagram, code and a description of any errors to your post at top of this page.

Posted in answer

Move the modules further apart, or change the power output in code (radio.setPALevel(RF24_PA_MIN)).

Try using one of the TMRh20's library's examples and get communication working there first.

Thanks to all who commented and provided advise. I did go to TMRH20 examples I tryed the simple transmit receive node sketch


text:
analogRead() doesn't read more than 500Hz
I connected a wave generator to the analog pins to read the frequencies of the waves generated. I used different frequencies of sine waves with a minimum of 0V and maximum of 5V.
Whenever the voltage is greater than 2.5V, I made one of the digital pins HIGH, and LOW when less than 2.5V. Now by measuring the square wave from the digital pin, it always has the same frequency as the sine waves until 500Hz.
After 500Hz, the square wave's frequency doesn't agree with the sine wave, which made me think that the problem is in the analogRead(). Is there a way to have higher frequency?
Code:
const int sensorPin1 = A0;
const int sensorPin2 = A1;
const float maximumPower = 2.5;
int calibration = 1;

void setup() {
  Serial.begin(57600);
  pinMode(6, OUTPUT);
  digitalWrite(6, LOW);
}

void loop() {
  int voltage2 = 3;
  int voltage1 = 3;
  int sensorVal = abs(analogRead(sensorPin1) - analogRead(sensorPin2));
  float ratio = abs(analogRead(sensorPin2) / analogRead(sensorPin1));
  float voltageDifference = (sensorVal / 1024.0) * 5.0;
  float power = calibration * voltageDifference;
  if (power >= maximumPower || voltage1 <= 1 || voltage2 <= 1) {
    digitalWrite(6, LOW);
  }
  else {
    digitalWrite(6, HIGH);
  }
}

Have you googled for this? When using terms like "analogread higher sample frequency" or similar, you can find solutions for this (basically just changing the prescaler of the ADCs clock). Have you read some of these results?

500 Hz seems a bit low. I would have expected something like 4 kHz. Do you realize that you need at least two samples per cycle? What Arduino are you using? Can you show us your code? Why are you using analogRead() instead of digitalRead()? What sampling rate would you need for your application? What analog resolution? What are you trying to achieve?

analogRead() is slow. digitalWrite() is slow. Combine the two together and it's slowly slow. Throw floating point maths into the mix (you mention 2.5V not 512) and it crawls to a snail's pace. Why are you using an Arduino at all for this? The same can be done with a simple comparator (op-amp).

@Majenko: Even using floats and digitalWrite(), I still get more than 7200 iterations per second on an Uno.

@EdgarBonet Halve that for nyquist-shannon, so 3600. No mention of what he's running on - it could be a breadboard Arduino off the 1MHz internal (div-8) clock. So divide that by 16, and you're down to a mere 225Hz...

May be relevant: https://arduino.stackexchange.com/q/67295/38721

sorry for late reply. I added the code. Thank you all

You have 4 calls to analogRead() in your loop. At about 112 µs per
call, that's already taking 448 µs. Add to that the time taken by the
floating point calculations, and you are likely to end up with something
in the order of 500 µs per loop iteration. This should give you a
sampling rate close to 2 kHz, which should allow you to detect the highs
and lows of an input signal up to 1 kHz, provided the duty cycle is
close to 50%.
There are a couple of easy optimizations that could be done here. Two of
the calls to analogRead() serve no purpose, as the results are never
used. And the floating point calculations are also pointless. The whole
loop can be simplified to this:
void loop() {
    if (abs(analogRead(A0) - analogRead(A1)) >= 512) {
        digitalWrite(6, LOW);
    } else {
        digitalWrite(6, HIGH);
    }
}

This should take about 224 µs per iteration. If you need to go faster,
you will have to increase the working frequency of the ADC. This can
cost some accuracy, but if accuracy is not critical to your application,
it can be a good trade-off. See Nick Gammon's page on the Arduino
ADC for details. If that's not enough, you will have to use
external components, e.g. an analog subtractor made from an op-amp, and
a couple of comparators.


text:
Pro Micro COM port disappeared after upload
I uploaded a sketch to my Pro Micro and it stopped showing in serial ports. Other Arduinos show up just fine.
I've tried to detect serial devices using pyserial and it's also not seeing anything. I've tried to reset the board by connecting the reset pin to ground twice in quick succession but it's not doing anything.
The board might be broken, but it seems unlikely to me as it's not connected to anything high powered.
The sketch I uploaded does use serial, but that hasn't been a problem before.
Any ideas on how to recover the board?

If it's a variety of pro micro that takes a micro-b cable, make sure you've not been trying to connect it with a power-only type of USB cable.

@timemage It's a mini usb and I've checked a few cables. Couldn't really be the issue as it worked before. I'm afraid it just decided to die on me :/

I wasn't there to observe that the same cable being used twice. "not connected to anything high powered" I would update with details on what happens if it's connected to nothing at all, except USB. If that is impractical I would update a volt meter reading of the 5V/VCC pin. Whether or not your "Other Arduinos" are also of Pro Micro type may be helpful. When you say "does use serial" are you referring to Serial1 (USART) or Serial (as in over USB). If you're leaving it all connected, clear images and wiring diagrams/schematics.

Since Pro-Micro comes as 3.3V and 5V, see past Q of mine

The Pro Micro uses a single processor (ATmega32U4) unlike some of the other Arduinos which have a separate processor for USB communications.
When reset, it will appear as a USB device for a couple of seconds, and then if the sketch does not use Serial, or uses it inappropriately, it could stop responding. For example, if the code went into a loop.
It is highly unlikely that the board just "broke". I suggest keeping the processor in Reset (tie Reset to Ground) while you compile a new sketch, and then release Reset when it tells you it is starting to upload.
You haven't posted your code, but it quite possibly is the problem. For example, you might have disabled interrupts.


text:
Arduino Yún causing power suge warning
Recently I got an Arduino Yún board that sends out a power surge error message everytime I connect it to my laptop through the USB cable. I tried two Arduino Leonardo and one Arduino Uno and there wasn't any problem with them or the USB port. Am I missing something or is the board faulty already?

Use a USB tester to test the current consumption, it should be < 500ma
I recommend using a USB that has power of its own, eg. monitor USB

Yún boards are more powerful boards than your average Arduino. Probably too powerful for your little laptop's USB ports. Use a powered hub or an external power supply to run the board.


text:
Trouble initializing a struct array
The goal for this is to create a struct that includes a name, ID, fileName, and a boolean, then create an array of that structs.
Here's what I came up with:
struct Amiibo
{
  char *aName{};
  char *ID{};
  char *AudioFileName{};
  bool alreadyPlayed{false};
};

Amiibo amii[20] = {

      {"Mario","A5005B00","MARIO",false},                     //0
      {"Meta Knight","A5 00 02 00","MK"},                     //1
      {"Inkling", "A5 00 05 00","INK"},                       //2
      {"Donkey Kong","A5 00 01 00","DK"},                     //3
      {"Lucas","A5 00 0A 00","LUCAS"},                        //4
      {"Duck Hunt", "A5 00 08 00","DUCKH"},                   //5
      {"Ocarina of Time Link","A5 00 01 00","OOTL"},          //6
      {"Breath of The Wild Link","random","BOTWL"},           //7
      {"8-bit Link","random","8BITL"},                        //8
      {"Toon Link","random","TOONL"},                         //9
      {"Mr. Game and Watch","random","GANDW"},                //10
      {"Falco","random","FALCO"},                             //11
      {"King Dedede","random","DEDEDE"},                      //12
      {"Mewtwo","random","MEWTWO"},                           //13
      {"Captain Falcon","random","CAPF"},                     //14
      {"ROB","random","ROB"},                                 //15
      {"PAC-MAN","random","PACMAN"},                          //16
      {"Cloud","random","CLOUD"},                             //17
      {"Ness","random","NESS"},                               //18
      {"Ryu","random","RYU"}                                  //19

};

This gives me the following error:

error: could not convert '{"Mario", "A5005B00", "MARIO", false}' from '' to 'Amiibo'

And the same error for all the other elements of the array.
I tried changing amii[20] to a pointer using *amii[20]. That got me this error:

braces around scalar intializer for type "Amiibo"

I'm not sure what to make of that, since I'm fairly certain this isn't scalar type.
I'd really just like to make a struct array so I can cycle through these at random using a random seed. It shouldn't be that difficult, yet I'm running up against a wall. I'd appreciate any advice you all have to give. Thanks.

If you use default values, you can't use this type of initialization, you have to have proper constructor(s) to get it working. However it'll tricky with that C-strings

Would you mind giving an example of a proper constructor?

struct Amiibo { ... Amiibo(const char* name, const char* id, const char * audio) : aName{ name }, ID{ id }, AudioFileName{ audio } { ; } and another one with 4 parameters... (btw you have to change internal types to const char * too, otherwise it'll yell about discarding qualifier)

Simply omit the default values?!

If you use default values in struct declaration, you have to define also constructors for setting specific elements:
struct Amiibo
{
  const char *aName{};
  const char *ID{};
  const char *AudioFileName{};
  bool alreadyPlayed{false};

  Amiibo() = default;  // default implementation for default constructor

  Amiibo(const char* name, const char* id, const char * audio)  // constructor with three c strings as parameters
  : aName{ name }
  , ID{ id }
  , AudioFileName{ audio }
  { ; }
};

Amiibo amii[] = {
      {"Mario","A5005B00","MARIO"},                           //0
      {"Meta Knight","A5 00 02 00","MK"},                     //1
      {"Inkling", "A5 00 05 00","INK"},                       //2
      {"Donkey Kong","A5 00 01 00","DK"},                     //3
      {"Lucas","A5 00 0A 00","LUCAS"},                        //4
      {"Duck Hunt", "A5 00 08 00","DUCKH"},                   //5
      {"Ocarina of Time Link","A5 00 01 00","OOTL"},          //6
      {"Breath of The Wild Link","random","BOTWL"},           //7
      {"8-bit Link","random","8BITL"},                        //8
      {"Toon Link","random","TOONL"},                         //9
      {"Mr. Game and Watch","random","GANDW"},                //10
      {"Falco","random","FALCO"},                             //11
      {"King Dedede","random","DEDEDE"},                      //12
      {"Mewtwo","random","MEWTWO"},                           //13
      {"Captain Falcon","random","CAPF"},                     //14
      {"ROB","random","ROB"},                                 //15
      {"PAC-MAN","random","PACMAN"},                          //16
      {"Cloud","random","CLOUD"},                             //17
      {"Ness","random","NESS"},                               //18
      {"Ryu","random","RYU"}                                  //19
};

Btw on the older AVRs all those strings will resides also in memory

Thanks a bunch. I may end up just using a switch or something to avoid memory issues.


text:
Arduino OSX Mojave - Serial port only shows sometimes
I've found lots of issues about serial ports not showing up at all, but none about what I'm experiencing.
Sometimes I can see my Arduino Mega 2560 in the ports list, and sometimes I can't. I've tried unplugging, replugging, rebooting my PC, and installing various CH34X USB drivers
Is there some way I can troubleshoot this issue to work out where things are going wrong?
EDIT: I have a Macbook Pro 2017 with Thunderbolt 3.0 ports connected to an adapter that lets me plug in USB. The Mega is a CH340G -> Wemos® Mega +WiFi R3 Module ATmega2560+ESP8266 32Mb Memory USB-TTL CH340G Compatible For Arduino Mega NodeMCU ESP8266.
EDIT #2: It looks like it's working again, all I did was switch around some of the DIP switches and change it from RX/TX0 to RX/TX3, sometimes when that stops working ill change it back to RX/TX0 and itll start working again. I suspect it has something to do with the USB-C adapter but haven't nailed it down yet.

maybe you have a bad usb cable

@jsotola would a bad USB cable only work sometimes but not other times? surely the fact that it was working for a while means the USB cable is okay?

A cable could work "sometimes" if one or more of its connections were poorly soldered (for instance) and conducted or not, depending on how the cable was flexed. I'd certainly call that a bad cable. You could try flexing the cable near either cable-head, or (less likely, but who knows?) along its length, and watch your PC for detection or not. Or simpler: try another cable, especially a known good one if you can. If one works, and one works "sometimes", well ....

Thanks @JRobert I'll try with a couple different USB cables

A colleague at work was struggling with a similar problem just two days ago.
He said he resolved it by reinstalling the USB driver. I did not pay much attention to more details (because I did not have that problem). If you can not work how to reinstall and none can advise how, I can ask him on Monday.
In the meantime here are a couple of reinstall the USB driver links:
https://www.roland.com/global/support/support_news/18091014/
https://forum.arduino.cc/index.php?topic=570440.0
https://support.serato.com/hc/en-us/articles/115001883474-macOS-High-Sierra-10-13-macOS-Mojave-10-14-and-above-driver-install-process
Hopefully one of these will help you.
Here is the link that my colleague followed:
https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver
All I can add is that this one worked for him. He has I have High Sierra (version 10.13.3) and needed to reboot after the installation.

thanks @GMc I've tried reinstalling drivers a couple of times now to no avail

I will try to catch my colleague  tomorrow and ask him for more details about what he did.

@user2620825 I've finally caught up with my colleague and updated my answer with what he did. Hopefully this will help you with your problem,


text:
about how to share one External serial EEprom using two microcontrollers?
strong texti have Vector nav100 IMU sensor that sends data serially UART.I want to receive data from it using ATmega32 and then store data in AT24c1024 EEprom using I2C,then using another ATmega32 to read the saved data on AT24c1024 EEprom using I2C to control a servo motor..so,the AT24c1024 EEprom is then shared between the two microcontrollers...i have serached the internet about how to share one  External serial EEprom,i found that......(On way would be for the two  mcrocontrollers to have an output line as an input to the other. A master that is "using" the EEPROM perhaps pulls his output low (or high - your choice) to say "I'm using it at the moment". The other reads his input first before going near the EEPROM if he finds the line active he backs off until it is set inactive by the other master.i tried this solution but i failed...can any one help me on this solution ?
Thanks in advance......
this is my code
{

    //the first MCU fristly check the pin
    //if high,then write,then set it low to allow read
    //the second MCU fristly check the pin
    //if low ,then write,then set it high to allow write

    //for the MCu that will write
    //first it will check for the pin ,if it is LOW,
    //then it can write data to EEprom
                     DDRA=0x00;//configure portA as input
            if(PINA==0x00)//check for the pin, if LOw,then wirte
    {
        byte_write(data);
        _delay_ms(10);
    //After writing set the pin as high to allow the second MCU to read
        DDRA=0xff;//configure portA as output
        PORTA=0xff;//set the pin as high
        _delay_ms(10);}

    //for the MCu that will read,i set adelay of 10 ms
    // to allow the first MCU to write some data

                         _delay_ms(1000);//delay from the data to be written on the EEprom
                 DDRA=0x00;//configure portA as input
        if(PINA==0x01)//check for the pin, if HIGH,then read
    {
             y=byte_read(data);
            DDRA=0xff;configure portA as output
            PORTA=0x00;//set the pin as high

}

I wonder what the reason is for the EEPROM ... because of temporarily storing data, or as a buffer (timing difference between the writer mcu and reader mcu? Or for other reasons (too)? Otherwise, remove the EEPROM, and send data directly from one MCU to the other (e.g. using UART/SPI/I2C).

@MichelKeijzers to prevent data from loss if the next frame from the sensor came and the microcontroller is still processing the last frame,so the frame will be dropped.

If written correctly, receiving and processing are 2 different things. Also the Wire library does not support multi master. When both controllers try to access the EEPROM simultaneously, the bus will be blocked.

@chrisl OK.that is true..so,.I have searched the internet for that,I have found that On way would be for the two microcontrollers to have an output line as an input to the other. A master that is "using" the EEPROM perhaps pulls his output low (or high - your choice) to say "I'm using it at the moment". The other reads his input first before going near the EEPROM if he finds the line active he backs off until it is set inactive by the other master.I tried this ,but I failed...could me give me pseudo code for this solution?

With what did you fail? You should provide the code in question, so that we can help you with that. Though I'm still not sure, that using an external eeprom is a good idea

@chrisl OK,I will give you the code...but is  there any other way to prevent data from loss?

@chrisl i have connected first pin in portA in both microcontrollers.for the microntroller that will read,i write delay 10ms for the data to be written on the EEprom  DDRA=0xff;
PORTA=0x00;//pin is High
_delay_ms(10);while(1){
for (int i=0;i<10;i++){
DDRA=0x00;
if(PINA==0x01){
y=random_location_byte_read(i,0xA0);
_delay_ms(10);
uart_send(y);
_delay_ms(10);
DDRA=0xff;
PORTA=0x00;

Please include your whole compilable code into the question by editing it. You can format it correctly by selecting it and clicking the {} button

@chrisl i have edited the question and send the code

You didn't show us a complete, minimal, compilable example, so my answer will only cover some important points.

Your indention is way off. It is important to use the correct indention, since it help structure your code and will let you quickly see misplaced brackets. The Arduino IDE even has an autoformat function for this.
You are configuring and checking always the whole PORT A, but you have only connected one of the pins. When you configure the whole port as input (without pullup), the other pins will be floating. Also, if both devices have the pin on input (no pullup), this pin will also be floating. The check cannot work this way. You should only look at the first bit in the port registers, since that is the pin, that you connected. You can set all other bits to zero when reading, by performing a bitwise AND operation: if(PINA & (1<<PA0)). This will execute, when the first bit of PINA is 1. To set a single bit you can use the bitwise OR: DDRA |= 1<<PA0; will set the first bit of DDRA. To erase only that bit from the register, you can use DDRA &= ~(1<<PA0);. The rest of the port will stay untoched with this.
Your current protocol is, that the first MCU will check for LOW, do it' transmission, then drive the pin actively HIGH as a signal for the second MCU to start transmitting. The second MCU will do it's I2C stuff and then drive the pin actively LOW. So now we have an active LOW and active HIGH on the same pin, which in principle is a short. A rather big amount of current will flow from one MCU to the other, most likely destroying at least one of the pins (meaning the output hardware in the MCU, that serves that pin). To avoid this, you can use a principle like that, that the I2C port uses: Open Drain logic. You can start with the first MCU's pin configured as OUTPUT LOW, while the other is INPUT PULLUP. LOW means the first MCU can work. If the first MCU want's the second MCU to do a transmission, it will release the line by setting the PIN to INPUT PULLUP. The second MCU now sees a HIGH level on it's pin and starts it's transmission. When it is finished, it will drive the line actively LOW for a defined duration (enough for the first MCU to react) and then to INPUT PULLUP again. The first MCU will then see a LOW level on it's pin as a signal, that the second MCU is finished. It then itself drives the line actively LOW. Then the play starts again. The important thing is, that a HIGH state is only done by a pullup, not actively driven.

That said, I still don't see the necessity to share an external EEPROM for this use case. You are overthinking the problem. You wrote, that you don't want to miss a frame, if the second MCU is still processing the last frame. There are better ways to do that (especially when you consider the limited lifetime of EEPROM).

You didn't tell us, why you are using 2 MCU's, so maybe your goal can be reached with only 1 MCU, which will eliminate the whole need for transmission.
You could use another UART interface via SoftwareSerial or it's sibling libraries to let the MCU's communicate directly. "Not missing a frame" will still be the case, when you are not disabling interrupts. The library will read the data into a buffer in interrupts, while you are processing the previous frame. Depending on how much data you send, you might want to make the buffer bigger, but that is a simple change in the libraries definitions.
If you want to use I2C to communicate between both MCU's, you have 2 ways of doing it. You can either go the same way as described above for UART, by just letting it fill a big enough buffer, or you can do this through the bus transmissions. The first MCU would be the master, that tries to send the data to the second MCU (slave), when there is new data available. The slave will receive the data normally. When the frame is finished receiving, the slave can leave the bus, until it is finished processing. So, when the master tries to send more data in this time, the transmission will fail at the start, since no slave with that address is on the bus (the slave MCU left the bus for this period of time). You can check the return value of Wire.endTransmission(), which will reflect the corresponding error code. If this error code is returned, the master should wait a bit and try to send this frame again, until it is received successfully. That also means, that the master needs a big enough buffer for storing new data, while waiting for the slave to be ready. Or another way: The master can request 1 byte from the slave, that indicates, if the slave is ready for new data. If not, the master will wait a bit and ask again. If yes, it will transmit the data.

Note: Either way the frequency of data reception and processing must be equal for continuous operation. The whole chain will be as fast as the slowest part. If you receive data faster, than it get's processed, the buffer will fill up fast, until you really have to drop frames. The prinicples above are more about the case, when the processing and receiving may misalign or vary a bit, but at the average staying at the same speed. And for this simple communication buffers, that all communication libraries use, with enough space for maybe 2 to 4 transmissions (depending on the variation) are way enough.


text:
Why won't this code play a converted wav2c header file through an Arduino to my speaker?
I used this converter wav2c to convert a .wav file to a C that I can put in a header file. I was able to put converted audio into the h file but the program where I reference it does not seem to be working correctly. The code compiles and uploads to the Arduino but no sound plays. I used the code here to implement the converted audio. I'm using an 8-ohm 0.25w speaker. I'm no programmer nor an expert at electronics so it's likely something dumb that I did wrong. Any help is much appreciated!
Note: The speaker does work with a simple tone sketch.
The code in the header file (minus the hundreds of lines of values for the audio)

#ifndef _HEADERFILE_H    // Put these two lines at the top of your file.
#define _HEADERFILE_H    // (Use a suitable name, usually based on the file name.)

const int sounddata_length=10000;
//const int sounddata_sampleRate=8000;

const unsigned char sounddata_data[] PROGMEM = {
  15,1,49,0,150,0,138,0,219,255,133,0,176,0,15,1,210,254,16,1,197,255,65,0,9,0,227,0,127,254,87,0,175,1,61,254,132,1,135,255,21,1,72,0,104,1,172,0,122,0,213,1,65,255,188,1,100,1,215,0,210,255,59,2,17,0,193,0,200,2,207,255,203,0,65,1,17,1,169,255,121,2,112,0,193,255,65,255,252,255,232,0,101,255,88,2,4,0,26,255,

//Several hundred lines more of these numbers for the audio

105,108,101,45,49,46,48,46,50,52,41,0,105,100,51,32,42,0,0,0,73,68,51,3,
  0,0,0,0,0,31,84,88,88,88,0,0,0,21,0,0,0,83,111,102,116,119,97,114,101,0,76,97,118,102,53,50,46,57,51,46,48,0,};

#endif // _HEADERFILE_H    // Put this line at the end of your file.

Here is the code that I used from the Arduino Playground page to play the audio from the header file.
#include <stdint.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include <avr/pgmspace.h>

#define SAMPLE_RATE 8000
#include "Test.h"

int ledPin = 3;
int speakerPin = 11; // Can be either 3 or 11, two PWM outputs connected to Timer 2
volatile uint16_t sample;
byte lastSample;

void stopPlayback()
{
    // Disable playback per-sample interrupt.
    TIMSK1 &= ~_BV(OCIE1A);

    // Disable the per-sample timer completely.
    TCCR1B &= ~_BV(CS10);

    // Disable the PWM timer.
    TCCR2B &= ~_BV(CS10);

    digitalWrite(speakerPin, LOW);
}

// This is called at 8000 Hz to load the next sample.
ISR(TIMER1_COMPA_vect) {
    if (sample >= sounddata_length) {
        if (sample == sounddata_length + lastSample) {
            stopPlayback();
        }
        else {
            if(speakerPin==11){
                // Ramp down to zero to reduce the click at the end of playback.
                OCR2A = sounddata_length + lastSample - sample;
            } else {
                OCR2B = sounddata_length + lastSample - sample;
            }
        }
    }
    else {
        if(speakerPin==11){
            OCR2A = pgm_read_byte(&sounddata_data[sample]);
        } else {
            OCR2B = pgm_read_byte(&sounddata_data[sample]);
        }
    }

    ++sample;
}

void startPlayback()
{
    pinMode(speakerPin, OUTPUT);

    // Set up Timer 2 to do pulse width modulation on the speaker
    // pin.

    // Use internal clock (datasheet p.160)
    ASSR &= ~(_BV(EXCLK) | _BV(AS2));

    // Set fast PWM mode  (p.157)
    TCCR2A |= _BV(WGM21) | _BV(WGM20);
    TCCR2B &= ~_BV(WGM22);

    if(speakerPin==11){
        // Do non-inverting PWM on pin OC2A (p.155)
        // On the Arduino this is pin 11.
        TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
        TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
        // No prescaler (p.158)
        TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set initial pulse width to the first sample.
        OCR2A = pgm_read_byte(&sounddata_data[0]);
    } else {
        // Do non-inverting PWM on pin OC2B (p.155)
        // On the Arduino this is pin 3.
        TCCR2A = (TCCR2A | _BV(COM2B1)) & ~_BV(COM2B0);
        TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0));
        // No prescaler (p.158)
        TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set initial pulse width to the first sample.
        OCR2B = pgm_read_byte(&sounddata_data[0]);
    }

    // Set up Timer 1 to send a sample every interrupt.

    cli();

    // Set CTC mode (Clear Timer on Compare Match) (p.133)
    // Have to set OCR1A *after*, otherwise it gets reset to 0!
    TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12);
    TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10));

    // No prescaler (p.134)
    TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

    // Set the compare register (OCR1A).
    // OCR1A is a 16-bit register, so we have to do this with
    // interrupts disabled to be safe.
    OCR1A = F_CPU / SAMPLE_RATE;    // 16e6 / 8000 = 2000

    // Enable interrupt when TCNT1 == OCR1A (p.136)
    TIMSK1 |= _BV(OCIE1A);

    lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1]);
    sample = 0;
    sei();
}

void setup()
{
    pinMode(ledPin, OUTPUT);
    digitalWrite(ledPin, HIGH);
    startPlayback();
}

void loop()
{
    while (true);
}

are you using the correct pin for output?

Put a minumum 125 ohm resistor in series with the pin and the speaker to limit the current out of the pin to 40mA max.  10,000 samples read back at 8,000 Hz = 1.25 second burst of sound. Is that what you are expecting?

This program uses the Timer 2 PWM facility to generate audio output on
pins OC2A or OC2B. On the Arduino Uno, these pins are labeled “11” and
“3” respectively, and the program carries this mapping as an implicit
assumption. You are trying to run the program on an Arduino Mega, which
has a different pinout. For instance, on the Mega:

OC2A = digital 10
OC2B = digital 9

You can easily port the program to the Mega by replacing every reference
to pins 11 and 3 by 10 and 9 respectively. E.g., every occurrence of
if(speakerPin==11){

becomes
if(speakerPin==10){

Make sure to fix the comments so that they remain consistent with the
code.
And you should, of course, choose an appropriate pin for your speaker.
Side note: you are stressing the output pin if you connect it directly
to an 8 Ω speaker. It's fine for a test as long as you don't care
too much about the life span of your Arduino.


text:
Unable to control servo with decoupling capacitor and external power supply, but motor shield works
I'm a hobbyist trying to up my arduino and electronics knowledge.
I can successfully control a hobby servo using an motor driver shield (https://learn.adafruit.com/adafruit-motor-shield/overview) but am running into issues when I try to control it without the shield using standard servo control circuits.
When the servo is connected to the basic, unworking circuit, it generally doesn't move and clicks occasionally, as though underpowered. It works flawlessly with the shield, when powered just through the standard 5V USB connection.
Schematic of circuit that doesn't work:

Schematic of circuit working with shield (shield is approximation from fritzing):

I've tried :

a 470uF or 1000uF decoupling capacitor between ground and +5V. Also tried with no capacitor.
powering the servo and/or arduino from an external power supply.  Grounds are connected correctly.
Different 5V power supplies. (batteries intended for phone charging, 5V from computer, 5V from wall).
Different Arduino Unos.
Different servos.

Code running on Arduino:
#include <Servo.h>

Servo servo;

void setup() {
  servo.attach(10);
}

void loop() {
  servo.write(135);
  delay(500);
  servo.write(45);
  delay(500);
}

I'd like to understand what I'm doing wrong, how to troubleshoot, and/or what the shield is doing that the basic circuit is not.
I'm using Arduino Unos, a hobbytech YM-2765 servo (rated for 4.8-6V), or a 3001HB servo.

The wiring diagram you link to shows the servo on pin 9. Yet your code has the servo on pin 10. Do you actually have the servo on pin 9, or on pin 10? Please show your actual wiring, not a picture of what you think you followed.

Servo is on pin 10, sorry for confusion. Have updated with schematic of wiring. I note that these are still technically a picture of what I think I followed. Let me know if actual images or a circuit schematic would help.

Your schematic shows you feeding 5V to Vin.  Vin feeds the regulator and needs at least 7 volts.  If you have regulated 5V then feed that into the 5V pin.

Switched to 5V pin - same issue. Updated schematic to reflect this.


text:
mqtt library which support softwareSerial on arduino uno with ESP8266
I am using ESP8266 and Arduino with SoftwareSerial. My requirement is to use MQTT protocol with it. So I am using an MQTT library named pubSubClient but the problem is it doesn't support SoftwareSerial. Could anyone tell me how can I use MQTT protocol with it?
#include
#include
SoftwareSerial esp(2, 3); // RX, TX
PubSubClient client(esp);

The error I get is: no matching function for call to 'PubSubClient::PubSubClient(SoftwareSerial&)

Are you using http://pubsubclient.knolleary.net/

Could you please edit your question with the following information:

Why can't you use softwareSerial? What error do you get?
Why cant you use the main UART (serial) port?
What daughter board are you using for the ethernet?

You are asking the wrong question. PubSubClient has nothing at all to do with serial in any form whatsoever. It interfaces with the standard Arduino Client class. What you should be looking for (and maybe asking about) is an ESP8266 library that supports SoftwareSerial and presents the standard Arduino Client interface.

#include
#include
SoftwareSerial esp(2, 3);// RX, TX
PubSubClient client(esp);
Error is:no matching function for call to 'PubSubClient::PubSubClient(SoftwareSerial&)'

As @Majenko says, you need an Arduino PubSubClient that supports SoftwareSerial - you are trying to pass in a SoftwareSerial object which is not a PubSubClient. A brief google failed to find any SoftwareSerial clients but there is a ESP8266 PubSubClient here : https://github.com/knolleary/pubsubclient

In order to use the ESP8266 WiFi module with pubSubCient, you need a library that interfaces with the module with the usual AT commands, while presenting an Arduino Client interface on the surface. A while back, I found this library after a great deal of searching. It supports SoftwareSerial as well as HardwareSerial objects. Its ESP8266 interface provides the standard Client methods of write(), read(), connected(), etc. There are some issues, of course, but its the best I've found so far. You can pass the created Client object to the pubSubClient constructor and you're good to go.

Not sure what you're trying to do - but thought I would offer this since I just spend some time on getting my esp8266 to act as a wifi shield for my arduino.  Basically I wanted to subscribe to an mqtt channel and send the payload to my arduino.  So the esp8266 connected to a broker, upon reading a message, it would simply write it via serial to the arduino (I used software serial on the arduino side so I could use the standard serial for debugging).  If it helps, check out http://mganis.blogspot.com for the details
--Matt


text:
Arduino PWM LED blinking on four pins, each pin's intensity and time period based on the previous pin
I am trying to make four LEDs glow using my Arduino, based on some relationship between them in terms of brightness and the time for which LEDs glow.
For example, the relationships are:
pin_3_value = 250  // LED 1 intensity
pin_5_value = 1.2 * pin_3_value // LED 2 intensity
pin_7_value = 1.1 * pin_5_value  // LED 3 intensity
pin_13_value = 0.59 * pin_7_value  // LED 4 intensity

time_till_led_1_on = 100
time_till_led_2_on = time_till_led_1_on * 1.2
time_till_led_3_on = time_till_led_2_on * 2.4
time_till_led_4_on = time_till_led_3_on * 1.2

I understand that only a fixed set of values are permitted as input to the analogWrite(). Is there some way to implement this relationship on the Arduino? I cannot use a digitalWrite(), as the output of PWM pins are used for something else; making the LED glow is just for testing purposes.
The code I have written so far:
// Brightness level for the four pins

int Brightness_1 = 255;
int Brightness_2 =  Brightness_1 * 2;
int Brightness_3 = Brightness_2 * 3;
int Brightness_4 = Brightness_3 * 4;

// Delay or time between  LED turn off and next LED turn ON

int Delay_1 = 500;
int Delay_2 =  Delay_1 * 1.1;
int Delay_3 = Delay_2 * 1.2;
int Delay_4 = Delay_3 * 1.3;

int pins[] = { 2, 4, 5, 7 }; // An array of pin numbers

void setup()
{
    int i;
    for (i = 0; i < 4; i++) // The array elements are numbered from 0  to num pins - 1
        pinMode(pins[i], OUTPUT); // Set each pin as an output
}

void loop()
{
    // Loop through each pin...
    analogWrite(pins[0], Brightness_1 ); // Turning it on,
    delay(Delay_1);                      // pausing,
    analogWrite(pins[0], 0);             // and turning it off.

    analogWrite(pins[1], Brightness_2); // Turning it on,
    delay(Delay_2);                     // pausing,
    analogWrite(pins[1], 0);            // and turning it off.

    analogWrite(pins[2], Brightness_3); // Turning it on,
    delay(Delay_3);                     // pausing,
    analogWrite(pins[2], 0);            // and turning it off.

    analogWrite(pins[3], Brightness_4); // Turning it on,
    delay(Delay_4);                     // pausing,
    analogWrite(pins[3], 0);            // and turning it off.
}

How can I make this work?

I see this is an old question, and before going into it, I was going to see how you went with coming to a solution. There are several things about this. 1) you're setting the values to a fixed previous value, you'll need to use functions or at the least pointers to retrieve each value dynamically, and 2) ditch the delays unless you're after a fixed rate each loop (again each one is indefinitely a fixed value). Also some indication of what you're expecting it to look like would help. Is it a Knight Rider forward and backward swipe you're after, or one direction only?


text:
Arduino while loop with or condition
How do I write a program to wait (delay) until one out of two buttons pressed? I have written a program to wait until a single button is pressed. It's working fine. However, if I extend it to second button it's not working. Pls help on this.

while (digitalRead(bt_Select) == HIGH) {} -- working.
while (digitalRead(bt_Select) == HIGH || digitalRead(bt_Reject) == HIGH) {} -- Not working.

Complete code:
const int bt_Select = 2;
const int bt_Reject = 3;

void setup() {
  Serial.begin(9600);
  pinMode(bt_Select, INPUT_PULLUP);
  pinMode(bt_Reject, INPUT_PULLUP);
}

void loop() {
  Serial.println("Pl input:");

  while (digitalRead(bt_Select) == HIGH {} // This is the line I change

  if (digitalRead(bt_Select) == LOW) {
    Serial.println("Select Button pressed:");
    delay(250);
    Serial.println("");
  }

  if (digitalRead(bt_Reject) == LOW) {
    Serial.println("Reject Button pressed:");
    delay(250);
    Serial.println("");
  }
}

while (digitalRead(bt_Select)==HIGH||digitalRead(bt_Reject)==HIGH){}
should be
while (digitalRead(bt_Select)==HIGH&&digitalRead(bt_Reject)==HIGH){}
The first loop would break only if you press both buttons at once. I believe you are trying to break if either button is pressed.

yes I try to break if either button is pressed.

Thank you it's working.. 5n

however i confused how it could works?!*

@AkRikas Your code stays in the while loop when one of the buttons is HIGH and the other code when both are HIGH. Does this answer your question?

@Ak Rikas - The condition in the while loop is a continue condition, not a break condition.  You want the loop to break when one OR the other is pressed.  That means it should continue when both are not pressed.  In order to test that both are not pressed you need to use AND.


text:
Two servos for robot (head & chest) movement at different speeds at once
I have an Arduino Uno and two Hi-tec servos (HS-40 & 5055 digital) that I'm using for a basic robot build. I'm trying to have one servo(HS-40) turn the head back and forth (left to right) slightly faster than the other servo (HS-5055) controlling the upper torso.
I would like to have each servo working at the same time but not at the same speed without waiting for one servo to complete its movement.
I tried a sketch with a delay of 45-50 which seems to work fine for the movement speed and 0-75 degrees is ideal for the head travel and 0-65 degrees for the torso travel. I would like to have this movement to be repeated continuously so the robot mimics like it is looking side to side or left to right naturally.
Please help as I tried many sketches but can't find one that works like this. I tried modifying other code but can't get them work. Any help will be greatly appreciated.
How do modify this code so just the second servo runs at 40 which will slow down just enough? Also this is not my code, but it's one that seems to be close to what I'm trying to do.
#include <Servo.h>

Servo servo1;
Servo servo2;

int i = 0;

void setup() {
  servo1.attach(8);
  servo2.attach(9);
}

void loop() {
  for (i = 0; i < 70; i++) {
    servo1.write(i);
    servo2.write(i);
    delay(50);
  }
  for (i = 70; i > 0; i--) {
    servo1.write(i);
    servo2.write(i);
    delay(50);
  }
}

Please post some code that you are using.  Without a starting point it is difficult to offer any help.   But do a google search for "blink without delay" for an approach that might work.

Here is the code. Can a "Delay" command be added to the second servo to slow it down to 40? #include <Servo.h>
Servo servo1;
Servo servo2;
int i = 0;
void setup() {
servo1.attach(8);
servo2.attach(9);
}
void loop() {
for (i = 0; i < 70; i++) {
servo1.write(i);
servo2.write(i);
delay(50);
}
for (i = 70; i > 0; i--) {
servo1.write(i);
servo2.write(i);
delay(50);
}
}

change the line to servo1.write(2*i);

Heres a little sketch you can try.  It uses timing to accomplish the different servo speeds.  It won't give you the exact servo travel each loop but it sounds like you might not mind if it randomly is off by a few degrees each loop.
#include <Servo.h>
Servo servo1;
Servo servo2;
int i = 0;
void setup() {
  Serial.begin(9600);
  servo1.attach(8);
  servo2.attach(9);
}

int sweep_time = 3500; // 70 * 50ms = 3500

int head_degrees = 75; // sweep degrees for the head to move
int body_degrees = 65; // sweep degrees for the body to move

int millis_per_head_move = sweep_time / head_degrees;
int millis_per_body_move = sweep_time / body_degrees;

void loop() {
  int i = 0; int j = 0;
  unsigned long now_millis = 0;
  unsigned long start_sweep = millis(); // mark the time when we start the first sweep

  while ( millis() - start_sweep < sweep_time ) {  // keep moving first sweep until sweep time has elapsed
    now_millis = millis() - start_sweep;
    if (now_millis % millis_per_head_move == 0 ) servo1.write(i++);
    if (now_millis % millis_per_body_move == 0 ) servo2.write(j++);
    delay(1);
  }
  Serial.print(i); Serial.print(" "); Serial.println(j);

  start_sweep = millis();  // mark the time when we start the second/back sweep
  while ( millis() - start_sweep < sweep_time ) {  // keep moving second sweep until sweep time has elapsed
    now_millis = millis() - start_sweep;
    if (now_millis % millis_per_head_move == 0) servo1.write(i--);
    if (now_millis % millis_per_body_move == 0) servo2.write(j--);
    delay(1);
  }
  Serial.print(i); Serial.print(" "); Serial.println(j);
}

Thank you so much for this. I was getting some jittering with the previous code as the head swept back but I think I need to add some weight for ballast to the head & torso to help stabilize them. This code seems to minimize some of the jittering. I did test it with some added weight and it seems to be better now. Hopefully, once I get this project done I'll post a link where you can see it in action.  Again, thanks for all the help!  Much appreciated.

Happy that it works! If my answer solved the issue then please mark it as the accepted answer.

You do that by clicking the check mark by someone's answer.

Thanks for the answer from @tavis
Here is the simulation of their code and it answers your questions aptly.

The code (same as above, except the sweep time change)
#include <Servo.h>
Servo servo1;
Servo servo2;
int i = 0;
void setup() {
  Serial.begin(9600);
  servo1.attach(8);
  servo2.attach(9);
}

int sweep_time = 1000; // 70 * 50ms = 3500

int head_degrees = 75; // sweep degrees for the head to move
int body_degrees = 65; // sweep degrees for the body to move

int millis_per_head_move = sweep_time / head_degrees;
int millis_per_body_move = sweep_time / body_degrees;

void loop() {
  int i = 0; int j = 0;
  unsigned long now_millis = 0;
  unsigned long start_sweep = millis(); // mark the time when we start the first sweep

  while ( millis() - start_sweep < sweep_time ) {  // keep moving first sweep until sweep time has elapsed
    now_millis = millis() - start_sweep;
    if (now_millis % millis_per_head_move == 0 ) servo1.write(i++);
    if (now_millis % millis_per_body_move == 0 ) servo2.write(j++);
    delay(1);
  }
  Serial.print(i); Serial.print(" "); Serial.println(j);

  start_sweep = millis();  // mark the time when we start the second/back sweep
  while ( millis() - start_sweep < sweep_time ) {  // keep moving second sweep until sweep time has elapsed
    now_millis = millis() - start_sweep;
    if (now_millis % millis_per_head_move == 0) servo1.write(i--);
    if (now_millis % millis_per_body_move == 0) servo2.write(j--);
    delay(1);
  }
  Serial.print(i); Serial.print(" "); Serial.println(j);
}

Link to the simulation:
https://wokwi.com/arduino/projects/303847722463527490
Here is another example with three Servo motors running at three different sweep times:
https://wokwi.com/arduino/projects/299552195816194570


text:
Trouble with Arduino Nano Every and radio transmission using RH_RF69.h
I give some help for students working on the Cansat Contest.
I am trying to connect a RFM69 Radio Module to an Arduino Nano Every.
Nothing works : compiling the simpliest program:
#include <RH_RF69.h>

void setup() {}

void loop() {}

gives the answer:
[BlaBlaBla...]
exit status 1
Erreur de compilation pour la carte Arduino Nano Every

while everythings works on arduino M0 Feather Express or Arduino Uno.
Is there a specific problem with the Nano Every?

the BlaBla would be important here. and the link to the library, because now there is nothing to work with

Thanks a lot for your ansmers, I have cutted the Blablabla because it seems very long for a first point of view and introduce the library problem.
I will check the supported boards. But I think it will be confusing to install both the libraries for the M0 feather and the nano on the same compiler. All the students (and me) are complete beginers! It seems unusefull to work with different processors for a first try.
I think I'll buy another uno. It will be easier. (I just need it for a simple reception part).
The files you've shown seems indeed helpfull to check compatibility. Thanks again for y

The Nano Every uses an ATMega4809 processor, so it is different from most Arduino's. It could well be that it isn't supported by the Radiohead library.
The error you shortened to [BlaBlaBla...] could possibly give more information on that.
A full list of what is supported by the Radiohead library is here; you should check if the Arduino Nano Every or the ATMega4809 is on there; alternatively, all the #defines for the supported boards are in the header file.
If it turns out your board is not supported, you could ask the library's authors if they would consider supporting it, or you could use a different board (it should work with an Arduino Nano 33 IoT, I think, but please check first).

so select Every and compile if you know which library

@Juraj: I don't have the library here, and I don't want to install it here. FYI: it's this one: https://www.airspayce.com/mikem/arduino/RadioHead/index.html. Another version here: https://github.com/PaulStoffregen/RadioHead

I was never able to make this work with the RadioHead library but did get it to work with LowPowerLab RFM69 library.  Not here to debate which one is better just stating which one i got to work without having to change any of their code.
The environment used was VSCode on M2 Mac with latest PlatformIO plugin.
Transmitter
MCU = Arduino Nano Every (just because i had it)
Radio = Adafruit RFM69HCW (915Mhz) Breakout
Receiver
MCU+Radio = Adafruit RFM69HCW Feather
For LowPowerLab libary there were two items that where gotchas for me.  The first is that I was trying to use a different IRQ pin.  Once i learned that the default defined in RFM69.h was 2 then things were easy going and more or less followed all the code examples that used no arg constructors for radio.
The second was that i needed to reset the radio.  I got this from some example adafruit(thank you) code.
#define RFM69_RST     4
...
...
...
  pinMode(RFM69_RST, OUTPUT);
  digitalWrite(RFM69_RST, LOW);

  // manual reset
  digitalWrite(RFM69_RST, HIGH);
  delay(10);
  digitalWrite(RFM69_RST, LOW);
  delay(10);

So here is my working receiver code (with a bunch of other junk)
#include <Arduino.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <RFM69.h>
#include <SPI.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// The pins for I2C are defined by the Wire-library.
// On an arduino UNO:       A4(SDA), A5(SCL)
// On an arduino MEGA 2560: 20(SDA), 21(SCL)
// On an arduino LEONARDO:   2(SDA),  3(SCL), ...
#define OLED_RESET     -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#define NETWORKID     0   // Must be the same for all nodes
#define MYNODEID      3   // My node ID
#define FREQUENCY     RF69_915MHZ
#define RFM69_RST     4

// SPIClassMegaAVR ccc(12, 13, 11, RFM69_CS, 0);
RFM69 radio;//(RFM69_CS, RFM69_INT, true, &SPI);

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

  // put your setup code here, to run once:
  // pinMode(LED, OUTPUT);
  // digitalWrite(LED, HIGH);

  pinMode(RFM69_RST, OUTPUT);
  digitalWrite(RFM69_RST, LOW);

  // manual reset
  digitalWrite(RFM69_RST, HIGH);
  delay(10);
  digitalWrite(RFM69_RST, LOW);
  delay(10);

  if(!radio.initialize(FREQUENCY, MYNODEID, NETWORKID)) {
    Serial.println(F("radio init failed"));
    for(;;); // Don't proceed, loop forever
  }
  radio.setHighPower(); // Always use this for RFM69HCW

  if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }
  display.clearDisplay();
  display.display();
  delay(2000); // Pause for 2 seconds

  display.setTextSize(2);      // Normal 1:1 pixel scale
  display.setTextColor(SSD1306_WHITE); // Draw white text
  display.setCursor(0, 0);     // Start at top-left corner
  display.cp437(true);         // Use full 256 char 'Code Page 437' font

  display.print(F("Kris"));
  // display.startscrollright(0x00, 0x0F);

  display.display();
  Serial.println("Starting up");
  // radio.spyMode(true);
}

bool displayOnTop = true;
void displayMsg(char* msg) {
  display.clearDisplay();
  if (displayOnTop)
    display.setCursor(0,0);
  else
    display.setCursor(0, 16);
  displayOnTop = !displayOnTop;
  display.print(msg);
  display.display();
}

void loop() {

    if (radio.receiveDone()) // Got one!
  {
    // Print out the information:

    Serial.print("received from node ");
    Serial.print(radio.SENDERID, DEC);
    Serial.print(", message [");

    // The actual message is contained in the DATA array,
    // and is DATALEN bytes in size:

    for (byte i = 0; i < radio.DATALEN; i++)
      Serial.print((char)radio.DATA[i]);

    // RSSI is the "Receive Signal Strength Indicator",
    // smaller numbers mean higher power.

    Serial.print("], RSSI ");
    Serial.println(radio.RSSI);

    char rssi[12];
    sprintf(rssi, "RSSI: %d\0", radio.RSSI);
    displayMsg(rssi);

    // Send an ACK if requested.
    // (You don't need this code if you're not using ACKs.)

    if (radio.ACKRequested())
    {
      radio.sendACK();
      Serial.println("ACK sent");
    }
  }
}

#platformio
[env:nano_every]
platform = atmelmegaavr
board = nano_every
board_build.mcu = atmega4809
framework = arduino
lib_deps =
    adafruit/Adafruit SSD1306@^2.5.7
    lowpowerlab/RFM69@^1.5.2
monitor_speed = 115200

and here is my working tranmitter code (a little cleaner)
#include <Arduino.h>
#include <Wire.h>
#include <RFM69.h>
#include <SPI.h>

const int LED = 13;

#define NETWORKID     0   // Must be the same for all nodes
#define MYNODEID      4   // My node ID

// RFM69 frequency, uncomment the frequency of your module:

#define FREQUENCY     RF69_915MHZ

#define RFM69_RST     4

RFM69 radio;

void notifyme() {
  Serial.println("I got the call!");
}

void setup() {
radio.setIsrCallback(notifyme);
  Serial.begin(115200);

  // put your setup code here, to run once:
  pinMode(LED, OUTPUT);
  digitalWrite(LED, HIGH);

  pinMode(RFM69_RST, OUTPUT);
  digitalWrite(RFM69_RST, LOW);

  // manual reset
  digitalWrite(RFM69_RST, HIGH);
  delay(10);
  digitalWrite(RFM69_RST, LOW);
  delay(10);

  pinMode(RFM69_INT, INPUT);

  if(!radio.initialize(FREQUENCY, MYNODEID, NETWORKID)) {
    Serial.println(F("radio init failed"));
    for(;;); // Don't proceed, loop forever
  }
  radio.setHighPower(); // Always use this for RFM69HCW

  Serial.println("Starting up");
}

void loop() {
  if (!radio.sendWithRetry(3, "hello", 5, 1)) {
    Serial.println("Failed to send on radio");
    digitalWrite(LED, LOW);
  } else {
    Serial.println("message sent");
    digitalWrite(LED, HIGH);
  }

  delay(5000);
}

Keep in mind, i'm a copy/paste warrior with the mindset of a Donkey.  If I think it can be done then i will find a way, but it won't mean I understand anything about it.  With that in mind, happy to answer any questions.  :-)


text:
rfm69 on M0 Express... init() doesn't work
I have already connected succesfully the rfm69 on my Feather M0 Express... but I cannot do it again.
The connections are (in the order of the rfm69):

Vin -> 3V
Gnd -> Gnd
En  -> (nothing)
G0  -> 9
SCK -> SCK
MISO -> MI
MOSI -> MO
CS  -> 10
RST -> 6

The code of the setup is
#include <SPI.h>
#include <RH_RF69.h>

#define RFM69_CS      10
#define RFM69_INT     9
#define RFM69_RST     6
#define LED           13

// Singleton instance of the radio driver
RH_RF69 rf69(RFM69_CS, RFM69_INT);

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

  Serial.println("Feather RFM69 RX Test!");
  Serial.println();

  // manual reset
  digitalWrite(RFM69_RST, HIGH);
  delay(10);
  digitalWrite(RFM69_RST, LOW);
  delay(10);

  if (!rf69.init())
    //***********************************
    Serial.println("init failed");
  else
    Serial.println("init ok");

  // Defaults after init are 434.0MHz, modulation GFSK_Rb250Fd250, +13dbM (for low power module)
  // No encryption
  if (!rf69.setFrequency(434.0))
    Serial.println("setFrequency failed");
  else
    Serial.println("setFrequency ok");

  // If you are using a high power RF69 eg RFM69HW, you *must* set a Tx power with the
  // ishighpowermodule flag set like this:
  //rf69.setTxPower(14, true);

  // The encryption key has to be the same as the one in the client
  uint8_t key[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
                    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
  rf69.setEncryptionKey(key);

#if 0
  // For compat with RFM69 Struct_send
  rf69.setModemConfig(RH_RF69::GFSK_Rb250Fd250);
  rf69.setPreambleLength(3);
  uint8_t syncwords[] = { 0x2d, 0x64 };
  rf69.setSyncWords(syncwords, sizeof(syncwords));
  rf69.setEncryptionKey((uint8_t*)"thisIsEncryptKey");
#endif
  Serial.println("Fin du Setup");
}

But during the execution, the program stops at //**************************
I do not understand.
Can somebody help me?
Thanks a lot and merry Xmas

To be clear, you are seeing "init failed" printing and then no further output on the Serial Monitor, is that correct?

The "init failed" do not appear. Everything stops at "//******".
I have compared to another RFM69 program.
I have added a line " digitalWrite(RFM69_RST, LOW);" at the begining of the "//manual reset" and it works now.
the sequence
digitalWrite(RFM69_RST, LOW);
digitalWrite(RFM69_RST, HIGH);
delay(10);
digitalWrite(RFM69_RST, LOW);
seems to be more efficient.
... it remains a few mysteriuos for me.
Thank you

You should be able to mark your answer as accepted.

Sorry, I do not understand what you mean... it seems thus I am not able to do it. I almost never use forums.


text:
16/2 arduino I2C lcd display not lighting up?
I am working with an I2C lcd display with an arduino uno board I have connected the gnd pin to gnd of arduino uno and the vcc pin to 5V of arduino uno and the display is not even lighting up there is only a red led lighting up on the back so I tryed connecting the rest of the pins and run a code to detect the i2c display and it worked successfully I got the adress but the lcd did not light up. The lcd display is a new one I bought yesterday here are the pictures:
https://photos.app.goo.gl/x9QPAWig98yLg4DW9
The script I tryed to display text was this one with the NewLiquidCristal library:
//Libraries
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the
LCD I2C address, if it's not working try 0x27.

void setup(){
lcd.begin(16,2);   // iInit the LCD for 16 chars 2 lines
lcd.backlight();   // Turn on the backligt (try lcd.noBaklight() to turn it
off)
lcd.setCursor(0,0); //First line
lcd.print("I2C LCD Tutorial");
lcd.setCursor(0,1); //Second line
lcd.print("*Ardumotive.com*");
}

Here is the model nmber of the I2C: PCF8574A And the lcd is a QAPASS Ui also I don't have a spec sheet and the LCD seems to show empty chars when rotating the pot.

There are tons of different variations of LCD modules. It does look like it's an LCD with an I2C "backpack" on it. Post the model number, a link to the spec sheet if you have it, as well as a link to the specific library you're using and the code you are using to initialize it and send data to it.

From the pictures it looks like the I2C "backpack" has both a backlight adjustment pot (potentiometer) and a jumper on it. Sometimes removing/moving the jumper lets you turn the backlight off, but it appears to have the jumper installed. If it came with instructions or a link to the data sheet, see what it says about the adjustment pot. You might try turning the adjustment pot and see if that causes the backlight to turn on.

did you add lcd.begin(); and lcd.backlight(); to void setup?

I have added all the missing information sorry if late

you have an I2C LCD right? use this: LiquidCrystal_I2C lcd(0x27, 16, 2); instead of LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); .

my adress is actually 0x3F

take a look at the answer.

Try this:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// LiquidCrystal_I2C lcd(0x27, 16, 2);
// OR
LiquidCrystal_I2C lcd(0x3F, 16, 2);

void setup(){
lcd.begin();
lcd.backlight();
lcd.setCursor(5,0);
lcd.print("TA DAA...!");
}
void loop{
// do nothing here
}

If that didn't work probably your LCD have a different address than 0x27 which in that case you should run a I2C scanner to show you the addresses of I2Cs that connected to your Arduino:
#include <Wire.h>
// I2C scanner

void setup()
{
  Wire.begin();

  Serial.begin(9600);
  Serial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      Serial.print("Unknow error at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");

  delay(5000);           // wait 5 seconds for next scan
}

Check the jumper behind the I2C module (plug it out and in again).
Check the voltage of LED using a multimeter if there's no voltage there, maybe it's just a "bad LCD" try replacing it.

Thanks this worked for me!!