text:
Arduino Mega upload issue
I have made my own version of an Arduino Mega and I am encountering some issues. Whenever I try to upload any sketch to the Mega, I get the following error message:
avrdude: stk500v2 ReceiveMessage(): timeout
I can upload just fine to the 16u2 as well as the 2560 using ICSP and Nick Gammons Atmega_Board_Programmer sketch. I have the correct board and COM port selected, and the cable, computer, and USB(2.0) port can upload to other Arduino boards just fine.
I have had some other troubles with the board that have been solved, but this issue remains. Please see my Arduino forum post for more details on these issues.
My current guess is that there may some sort of issue with the transmission lines between the 16u2 and the 2560. Here is a picture of the pcb traces. Can anyone look them over to see if there are issues with the traces?
If the traces seem fine, can anyone think of another reason why the upload does not work?

Comments are not for extended discussion; this conversation has been moved to chat.

So as of right now the problem has been solved. The issue was that the decoupling capacitor on the reset line near the 2560 was designed to be a 22pF capacitor, but I had put a 100nF capacitor, which increases the time constant by a factor of 5000, prohibiting the auto-reset circuitry from operating correctly. Removing the 100nF and putting in the 22pF seems to have solved the issue of only being able to upload once after burning the bootloader.
Thank you everyone for your support.

Can you elaborate? A decoupling capacitor is usually between Vcc and Gnd, so it wouldn't be "on the reset line". The capacitor in series with Reset (and usually going to RTS on the FTDI header) should work fine as 100nF. If you really have a decoupling capacitor on Reset (between Reset and Gnd) then you shouldn't have it.

Example schematic, which has always worked for me (this is the Atmega328P but it is the same concept).

Sorry for delay. For the reset connection between the 16u2 and the 2560, I have a 10k pull-down resistor on the 16u2 side, then a 100nF capacitor in series from the 16u2 to the 2560, a 10k pullup resistor on the 2560 side, and a 22pF shunt capacitor (shunt is a better word than decoupling). The shunt capacitor was a 100nF and that was causing the auto-reset to not work correctly.

Whatever word you use, you don't need that capacitor between Reset and ground. The schematic I linked to above shows a diode between Reset and Vcc which should suppress any inadvertent pulses which might put it into high-voltage programming mode, but that probably won't be required unless you have problems with it not resetting.

So there are some issues. I made three boards. One of them works correctly, the other two do not. I can manually program each chip (16u2 and 2560) with FLIP, Arduino as ISP, and your board programmer sketch. The circuitry is the same in each of the three boards. I have checked the resonators of each chip and they are functioning at 16MHz. Is the capacitor in question the culprit? The capacitor is populated on genuine Mega boards so I made sure to have it in mine. I have also noticed that when I program the blink sketch to the 2560 using ArduinoISP, The LED will stay on for 1s and off for 0.5s

OK, I see what you mean. The schematic has the 22 pF capacitor on the main chip but not on the Atmega16U2. On my schematic I see that PD7 on the Atmega16U2 goes to Reset on the Atmega2560 via the 100 nF capacitor. I would be more doubtful of the 100 nF capacitor than the 22 pF capacitor.

Am I correct in thinking that the 100nF series capacitor is to only allow a low to high or high to low signal transition from the 16u2 to the 2560 and that a capacitor with too low or too high capacitance can adversely affect the time constant, causing the 2560 to reset before or after the data is ready to be sent?

What data? It's purpose is to allow RTS to be pulled low (and stay low) by the USB interface. Initially that will activate Reset because it will go low temporarily, but then the pull-up resistor on Reset will charge the capacitor again, taking Reset high, and allowing the chip to run. I don't think the value is particularly critical. Too low, and the Reset pulse could be too short. Too high and the bootloader data will be sent while the processor is still reset. Still, the bootloader protocol should handle anything other than an egregiously long time.

Yes the line is to control the auto reset and the RC circuit timing can adversely effect the bootloader not starting on time or ending too quickly, but yes only with a drastic difference. The data is sent over the UART lines, but the reset line lets the 2560 reset and run the bootloader, which looks for the data. If the bootloader ends too quickly the, 16u2 will spit out the ReceiveMessage timout error since no data is being received since the bootloader on the 2560 is done with its process(es)


text:
How do I read addresses on multiple DS2413 1-Wire GPIO Breakouts, using the Adafruit sketch?
I am using three DS2413 1-Wire GPIO Breakouts from Adafruit connected to an ESP8266.  I tested the DS2413
 breakouts using their example sketch and it works fine for just one DS2413.  But I cannot get it to work when 2 or more DS2413s are connected.
Adafruit DS2413 Example Sketch
https://github.com/adafruit/Adafruit_DS2413/blob/master/DS2413.pde
Adafruit DS2413 Overview
https://learn.adafruit.com/adafruit-1-wire-gpio-breakout-ds2413?view=all
When I connect 2 or more DS2413s, it only blinks the LEDs connected to the 1st breakout and doesn't read the other addresses.
I made some changes to the void setup section and now I am getting the following in the serial monitor. It sees all the addresses, but it is duplicating them and the first set have "No device found on the bus!" at the end. How can I get the sketch to read all the addresses without these errors?
Serial monitor
Looking for a DS2413 on the bus
3A B2 C2 39 00 00 00 8C No device found on the bus!
3A 8E AE 39 00 00 00 2C No device found on the bus!
3A E5 B6 39 00 00 00 55 No device found on the bus!
Found a DS2413: 3A B2 C2 39 00 00 00 8C
Found a DS2413: 3A 8E AE 39 00 00 00 2C
Found a DS2413: 3A E5 B6 39 00 00 00 55

Here is what the code with my changes.
#include <OneWire.h>

#define DS2413_ONEWIRE_PIN  (4)

#define DS2413_FAMILY_ID    0x3A
#define DS2413_ACCESS_READ  0xF5
#define DS2413_ACCESS_WRITE 0x5A
#define DS2413_ACK_SUCCESS  0xAA
#define DS2413_ACK_ERROR    0xFF

OneWire oneWire(DS2413_ONEWIRE_PIN);
uint8_t address[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };

void printBytes(uint8_t* addr, uint8_t count, bool newline=0)
{
  for (uint8_t i = 0; i < count; i++)
  {
    Serial.print(addr[i]>>4, HEX);
    Serial.print(addr[i]&0x0f, HEX);
    Serial.print(" ");
  }
  if (newline)
  {
    Serial.println();
  }
}

byte read(void)
{
  bool ok = false;
  uint8_t results;

  oneWire.reset();
  oneWire.select(address);
  oneWire.write(DS2413_ACCESS_READ);

  results = oneWire.read();                 /* Get the register results   */
  ok = (!results & 0x0F) == (results >> 4); /* Compare nibbles            */
  results &= 0x0F;                          /* Clear inverted values      */

  oneWire.reset();

  // return ok ? results : -1;
  return results;
}

bool write(uint8_t state)
{
  uint8_t ack = 0;

  /* Top six bits must '1' */
  state |= 0xFC;

  oneWire.reset();
  oneWire.select(address);
  oneWire.write(DS2413_ACCESS_WRITE);
  oneWire.write(state);
  oneWire.write(~state);                    /* Invert data and resend     */
  ack = oneWire.read();                     /* 0xAA=success, 0xFF=failure */
  if (ack == DS2413_ACK_SUCCESS)
  {
    oneWire.read();                          /* Read the status byte      */
  }
  oneWire.reset();

  return (ack == DS2413_ACK_SUCCESS ? true : false);
}

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

  Serial.println(F("Looking for a DS2413 on the bus"));

  /* Try to find a device on the bus */
  oneWire.reset_search();
  delay(250);
  while (oneWire.search(address)) {
       printBytes(address, 8);
       Serial.println(F("No device found on the bus!"));
}
  /* Check the CRC in the device address */
  if (OneWire::crc8(address, 7) != address[7])
  {
    Serial.println(F("Invalid CRC!"));
    return;
  }

  /* Make sure we have a DS2413 */
  if (address[0] != DS2413_FAMILY_ID)
  {
    printBytes(address, 8);
    Serial.println(F(" is not a DS2413!"));
    return;
  }

  while (oneWire.search(address)) {
  Serial.print(F("Found a DS2413: "));
  printBytes(address, 8);
  Serial.println(F(""));
}
}

void loop(void)
{
  /* Read */
  /*
  uint8_t state = read();
  if (state == -1)
    Serial.println(F("Failed reading the DS2413"));
  else
    Serial.println(state, BIN);
  */

  /* Write */
  bool ok = false;
  ok = write(0x3);
  if (!ok) Serial.println(F("Wire failed"));
  delay(1000);
  ok = write(0x0);
  if (!ok) Serial.println(F("Wire failed"));
  delay(1000);
}

I was able to get the ESP8266 to read all DS2413 devices without errors as well as blink each LED connected to the DS2413, individually, down the chain.
Here are animations of it working.

I owe all the credit to mortonkopf on Github. His sketch DS2413_button_array_test, was exactly what I needed to be able to read the addresses on all DS2413 devices connected and blink each LED. Here is a link to his OneWire_DS2413_array repo.
https://github.com/mortonkopf/OneWire_DS2413_array
Here is the code I am using to make this work.
// This sketch is based on mortonkopf's DS2413_button_array_test sketch and allows
// you to read multiple DS2413 devices and blink an LED connected to each DS2413,
// individually, down the chain.
// https://github.com/mortonkopf/OneWire_DS2413_array
//
// This sketch is an improvement on the write feature of the Adafruit DS2413
// sketch which only reads 1 DS2413 device.
// https://github.com/adafruit/Adafruit_DS2413
// https://learn.adafruit.com/adafruit-1-wire-gpio-breakout-ds2413/reading-writing-and-arithmatic

#include <OneWire.h>

/* reading pins
0x0 (B00000000) - Both pins LOW
0x1 (B00000001) - IOA = HIGH, IOB = LOW
0x2 (B00000010) - IOA = LOW, IOB = HIGH
0x3 (B00000011) - Both pins HIGH
0xFF (B11111111) - Read Failed!
*/
#define DS2413_ONEWIRE_PIN  (4) // GPIO 4 on Adafruit Feather HUZZAH ESP8266

#define DS2413_FAMILY_ID    0x3A
#define DS2413_ACCESS_READ  0xF5
#define DS2413_ACCESS_WRITE 0x5A
#define DS2413_ACK_SUCCESS  0xAA
#define DS2413_ACK_ERROR    0xFF

#define BUTTON_NO 3 //use this for size of array to store state values//

OneWire oneWire(DS2413_ONEWIRE_PIN);
uint8_t address[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };

byte Button_states[BUTTON_NO];//this is the array of button states//

void printBytes(uint8_t* addr, uint8_t count, bool newline=0)
{
  for (uint8_t i = 0; i < count; i++)
  {
    Serial.print(addr[i]>>4, HEX);
    Serial.print(addr[i]&0x0f, HEX);
    Serial.print(" ");
  }
  if (newline)
  {
    Serial.println();
  }
}

byte read(void)
{
  bool ok = false;
  uint8_t results;

  oneWire.reset();
  oneWire.select(address);
  oneWire.write(DS2413_ACCESS_READ);

  results = oneWire.read();                 /* Get the register results   */
  ok = (!results & 0x0F) == (results >> 4); /* Compare nibbles            */
  results &= 0x0F;                          /* Clear inverted values      */

  oneWire.reset();

  // return ok ? results : -1;
  return results;
}

bool write(uint8_t state)
{
  uint8_t ack = 0;

  /* Top six bits must '1' */
  state |= 0xFC;

  oneWire.reset();
  oneWire.select(address);
  oneWire.write(DS2413_ACCESS_WRITE);
  oneWire.write(state);
  oneWire.write(~state);                    /* Invert data and resend     */
  ack = oneWire.read();                     /* 0xAA=success, 0xFF=failure */
  if (ack == DS2413_ACK_SUCCESS)
  {
    oneWire.read();                          /* Read the status byte      */
  }
  oneWire.reset();

  return (ack == DS2413_ACK_SUCCESS ? true : false);
}

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

  Serial.println(F("Looking for a DS2413 on the bus"));
}

void loop(void) {
  byte i;
  byte present = 0;
  byte data[12];
  byte addr[8];

  if ( !oneWire.search(address)) {
    Serial.println("");
    Serial.print("No more addresses.\n");
    oneWire.reset_search();
    delay(50); //was 250
    return;
  }
  Serial.println("");
  Serial.print("R=");
  for( i = 0; i < 8; i++) {
    Serial.print(address[i], HEX);
    Serial.print(" ");
  }

  if ( OneWire::crc8( address, 7) != address[7]) {
      Serial.print("CRC is not valid!\n");
      return;
  }

  if ( address[0] != DS2413_FAMILY_ID) {
      Serial.print("Device is not a DS2413 family device.\n");
      return;
  }

// Blink each LED connected to the DS2413 one at a time
  bool ok = false;
  ok = write(0x1);
  if (!ok) Serial.println(F("Wire failed"));
  delay(200);
  ok = write(0x2);
  if (!ok) Serial.println(F("Wire failed"));
  delay(200);
  ok = write(0x0);
  if (!ok) Serial.println(F("Wire failed"));
  delay(200);
///////////////////

uint8_t state = read();
  const int IOA = 0x1;
  const int IOB = 0x2;

  if (state == -1)
  {
    Serial.println(F("Failed reading the DS2413"));
  }
  else
  {
    if (state & IOA)
    {
       Serial.print("   A");
    }
    if (state & IOB)
    { //can use this IO if needed to perfom tasks
        Serial.print("   B");
    }
  }

}

Here is a link to the Gist I created for this sketch.
https://gist.github.com/orbitrod/51eb10c1a88f5747dc79298030e4480c

You have two detection loop in your setup function.
This one can be safely deleted as for each detected device it will print the error message
while (oneWire.search(address)) {
   printBytes(address, 8);
   Serial.println(F("No device found on the bus!"));

}

source: Stack Exchange

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

sort: votes


text:
Read frequency of input in digital pins
This is a somewhat theoretical question:
Let's say I have some sensor that sends digital signals to one of Arduino's digital ports.
Now, I don't know the frequency it sends those signals in.
For example, the frequency of the sensor output could be 100Hz, so every 1/100 of a second it varies the voltage (or keeps the old voltage if the next signal is the same as the previous one), but it could just as well be 200Hz.
Would Arduino be able to faithfully read the digital signal regardless of its frequency? Or is there a conventional frequency that digital devices usually use for output?
Wouldn't it be the case that if Arduino expects 100Hz signal, but the signal is 200Hz it would miss half the inputs?
For: (1 0 1 0 0 1...) wouldn't it see: (1 1 0) - that is skip every other input because it's sampling rate would be too slow by half?
Thanks kindly for your help..

What do you mean by “digital signal”? Some kind of synchronous serial transmission protocol? SPI maybe? Or I2C? Or maybe an asynchronous one, like logic level UART? Or is it a custom protocol? Your question will start to make sense only once you specify how the data is supposed to be clocked in your protocol.

so every 1/100 of a second it varies the voltage (or keeps the old voltage if the next signal is the same as the previous one), - are you asking about measuring voltages or frequencies?

@Nick, let's assume that the 1 voltage is high enough (but not too high) for Arduino to register a 1, and the 0 voltage is also within the threshold for Arduino to register a zero (say 5V for HIGH and 0.5V for LOW). It's the frequency of the signal I'm concerned with.

@Edgar, I have in mind just a generic digital sensor - let's say one that measures temperature and sends a digital signal to Arduino at some unknown frequency.

A “generic” digital sensor doesn't mean anything. Digital sensors usually come with either SPI or I2C interfaces. Sometimes asynchronous serial. All those are well defined communication protocols. There are rules stating how the sender should notify the receiver about when precisely the data line is to be sampled. The Arduino has hardware support for these protocols, but other protocols have to be implemented in software (e.g. one wire). So forget about your meaningless “generic” and tell us what serial protocol you intend to use.

100 Hz is pretty trivial. See my page about timers.
This sketch can detect frequencies up to about 5 MHz:
// Timer and Counter example
// Author: Nick Gammon
// Date: 17th January 2012

// Input: Pin D5

// these are checked for in the main program
volatile unsigned long timerCounts;
volatile boolean counterReady;

// internal to counting routine
unsigned long overflowCount;
unsigned int timerTicks;
unsigned int timerPeriod;

void startCounting (unsigned int ms)
  {
  counterReady = false;         // time not up yet
  timerPeriod = ms;             // how many 1 ms counts to do
  timerTicks = 0;               // reset interrupt counter
  overflowCount = 0;            // no overflows yet

  // reset Timer 1 and Timer 2
  TCCR1A = 0;
  TCCR1B = 0;
  TCCR2A = 0;
  TCCR2B = 0;

  // Timer 1 - counts events on pin D5
  TIMSK1 = bit (TOIE1);   // interrupt on Timer 1 overflow

  // Timer 2 - gives us our 1 ms counting interval
  // 16 MHz clock (62.5 ns per tick) - prescaled by 128
  //  counter increments every 8 µs.
  // So we count 125 of them, giving exactly 1000 µs (1 ms)
  TCCR2A = bit (WGM21) ;   // CTC mode
  OCR2A  = 124;            // count up to 125  (zero relative!!!!)

  // Timer 2 - interrupt on match (ie. every 1 ms)
  TIMSK2 = bit (OCIE2A);   // enable Timer2 Interrupt

  TCNT1 = 0;      // Both counters to zero
  TCNT2 = 0;

  // Reset prescalers
  GTCCR = bit (PSRASY);        // reset prescaler now
  // start Timer 2
  TCCR2B =  bit (CS20) | bit (CS22) ;  // prescaler of 128
  // start Timer 1
  // External clock source on T1 pin (D5). Clock on rising edge.
  TCCR1B =  bit (CS10) | bit (CS11) | bit (CS12);
  }  // end of startCounting

ISR (TIMER1_OVF_vect)
  {
  ++overflowCount;               // count number of Counter1 overflows
  }  // end of TIMER1_OVF_vect

//******************************************************************
//  Timer2 Interrupt Service is invoked by hardware Timer 2 every 1 ms = 1000 Hz
//  16Mhz / 128 / 125 = 1000 Hz

ISR (TIMER2_COMPA_vect)
  {
  // grab counter value before it changes any more
  unsigned int timer1CounterValue;
  timer1CounterValue = TCNT1;  // see datasheet, page 117 (accessing 16-bit registers)
  unsigned long overflowCopy = overflowCount;

  // see if we have reached timing period
  if (++timerTicks < timerPeriod)
    return;  // not yet

  // if just missed an overflow
  if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
    overflowCopy++;

  // end of gate time, measurement ready

  TCCR1A = 0;    // stop timer 1
  TCCR1B = 0;

  TCCR2A = 0;    // stop timer 2
  TCCR2B = 0;

  TIMSK1 = 0;    // disable Timer1 Interrupt
  TIMSK2 = 0;    // disable Timer2 Interrupt

  // calculate total count
  timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
  counterReady = true;              // set global flag for end count period
  }  // end of TIMER2_COMPA_vect

void setup ()
  {
  Serial.begin(115200);
  Serial.println("Frequency Counter");
  } // end of setup

void loop ()
  {
  // stop Timer 0 interrupts from throwing the count out
  byte oldTCCR0A = TCCR0A;
  byte oldTCCR0B = TCCR0B;
  TCCR0A = 0;    // stop timer 0
  TCCR0B = 0;

  startCounting (500);  // how many ms to count for

  while (!counterReady)
     { }  // loop until count over

  // adjust counts by counting interval to give frequency in Hz
  float frq = (timerCounts *  1000.0) / timerPeriod;

  Serial.print ("Frequency: ");
  Serial.print ((unsigned long) frq);
  Serial.println (" Hz.");

  // restart timer 0
  TCCR0A = oldTCCR0A;
  TCCR0B = oldTCCR0B;

  // let serial stuff finish
  delay(200);
  }   // end of loop

Or is there a conventional frequency that digital devices usually use for output?

No.

Wouldn't it be the case that if Arduino expects 100Hz signal, but the signal is 200Hz it would miss half the inputs? For: (1 0 1 0 0 1...)

No.
Why would it "expect" a frequency? It isn't a person expecting a chocolate cake on its birthday.

So whatever frequency the sensor sends its data in - be it 100Hz or 5Mhz - Arduino is smart enough to read all the voltage signals faithfully?

I'm not quite sure what you mean by "read all the voltage signals" which seems to imply you want to measure the voltage.

so every 1/100 of a second it varies the voltage (or keeps the old voltage if the next signal is the same as the previous one)

But then you say:

let's assume that the 1 voltage is high enough (but not too high) for Arduino to register a 1, and the 0 voltage is also within the threshold for Arduino to register a zero (say 5V for HIGH and 0.5V for LOW). It's the frequency of the signal I'm concerned with.

The voltage levels for 0 and 1 are documented in the datasheet. For the Atmega328P for most pins they are as follows:

You can see that if Vcc is 2.4V or above then LOW is -0.5V to 0.3 * Vcc, which if Vcc is 5V then a LOW is -0.5 to 1.5V.
Similarly a HIGH is 0.6V * Vcc to Vcc + 0.5, so if Vcc is 5V then a HIGH is 3V to 5.5V.
In between 1.5V and 3V then the digital status would be undefined.
So, if your LOW and HIGH are in those voltage ranges, yes you can detect the frequency of the signal.
I'm not sure about the bit where you said "keeps the old voltage if the next signal is the same as the previous one". That seems to imply that if the signals stay the same (eg. for a second) then the voltage won't change at all, and thus the frequency will be zero.

Thanks @Nick. So whatever frequency the sensor sends its data in - be it 100Hz or 5Mhz - Arduino is smart enough to read all the voltage signals faithfully? If that's the case, that's encouraging news.. One additional question pls: can you determine the frequency of the sensor from the code - i,e. determine if the sensor is 100Hz, 200Hz etc.

See amended answer.

thanks @nick for all the info. About the last paragraph: wouldn't it be the case that if there's a stream of 1s and not 0s for a whole second, then the voltage graph would look like a horizontal line of 5V (basically like DC of 5V) for that 1 sec.)?

Yes, absolutely.

Another method if it's helpful to the world:
Using inspiration from https://forum.arduino.cc/t/how-to-read-frequency-with-arduino/528143/2
I am just measuring the seconds using micros() between each up or down portion of the waveform, multiplying the time by 2 to get the full period (assuming a duty cycle of 50%). And then inverting the full period to calculate the frequency.
I was using a Teensy 4.1 for this.
// READ FREQUENCY FROM A DIGITAL INPUT PIN SKETCH

// this cannot be used when the FreqMeasure.h toolbox is used if on teensy
// https://www.pjrc.com/teensy/td_libs_FreqMeasure.html

// define your digital input pin
#define inputPin 22

// initialize variables for the frequency reading function
boolean inputState = false; boolean lastInputState = false;
long lastTime; long period; double freq;

// the frequency reading function
double readFrequency(){
  inputState = digitalRead(inputPin);

  if (inputState != lastInputState) {
    period = micros() - lastTime; // in microseconds
    freq = 1/(2*period*pow(10,-6)); // conversion to Hz

    lastInputState = inputState;
    lastTime = micros();
  }
  return freq; // always return frequency even if it hasn't changed state...
}

// label the pin
void setup() {
  // Serial.begin(115200); // uncomment & adjust for Arduino - I was using a Teensy.
  pinMode(inputPin, INPUT);
}

// call the function and print the output at full speed
void loop() {
  Serial.print("Frequency:"); Serial.println(readFrequency());
  // works even if I put a delay in here (e.g., delay(1) millisecond)
}

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


text:
Multiple Serial Ports Stream Switch
I am trying to define multiple serial ports (multiple BMS management boards) and select via a global variable the port which one is active, this is the sketch I am trying to modify.
https://github.com/bres55/Smart-BMS-arduino-Reader/blob/master/smart_bms_reader_Mega_v11.ino
The function I want to write could be called "MySerialSwitch"
The smart_bms_reader_Mega_v11.ino has 19 calls to serial in a number of different functions. I want to be able to define the "active" MySerial in a variable that can be changed on the fly.
Something like this.
#include <SoftwareSerial.h>
SoftwareSerial MySoftSerial1(10, 11); // RX, TX
SoftwareSerial MySoftSerial2(12, 13); // RX, TX

#define MySerial1 MySoftSerial1
#define MySerial2 MySoftSerial2
#define MySerial3 Serial3

char MySerialPort[] = "MySerial1";

void setup()

{
MySoftSerial1.begin(9600);
MySoftSerial2.begin(9600);
Serial3.begin(9600);
}

This function would be modified
void call_get_cells_v()
{
  flush(); // flush first
  uint8_t data[7] = {221, 165, 4, 0, 255, 252, 119};
  MySerial.write(data, 7);
}

to read.
void call_get_cells_v()
{
  flush(); // flush first
  uint8_t data[7] = {221, 165, 4, 0, 255, 252, 119};
  MySerialSwitch.write(data, 7);
}

I have been researching this post
How to define a SoftwareSerial object inside a class?
And this post
Writing First Library - Serial Stream Object
It’s my first attempt at creating a library, I think this is kind of what I am trying to achieve, I've done the reading on stream, references and pointers. I'm not quite clear yet. I would really appreciate some assistance.
class MySerialSwitch {
    private:
        Stream *_dev;

    public:
        MySerialSwitch(Stream *dev) : _dev(dev) {}
        MySerialSwitch(Stream &dev) : _dev(&dev) {}
        (char MySerialPort);
};

    (int pos) {
    _dev->write(char MySerialPort);
}

sorry, what is the question? One problem I see is that for SotwareSerial you must select which one listens with the listen() function. and that SoftwareSerial doesn't work on many pins of Mega

I think I've worked it out, I have no idea how, this explains a little more https://forum.arduino.cc/index.php?topic=605453.0

I found this post, I don't think it will switch between hardware serial and software serial but it certainly works for just software.
#include <SoftwareSerial.h>
SoftwareSerial MySoftSerial1(10, 11); // RX, TX
SoftwareSerial MySoftSerial2(12, 13); // RX, TX
SoftwareSerial *MySerial;

void setup()
    {

   Serial.begin(115200);
   MySoftSerial1.begin(9600);
   MySoftSerial2.begin(9600);
    }

    void loop()
    {
      MySerial = &MySoftSerial1; //Query the 1st BMS
      //or change port
      MySerial = &MySoftSerial2; //Query the 2nd BMS

      // I had to all instances of MySerial.write to MySerial->write
    }

I'll keep reading to figure out what I've done but if anyone would like to explain, I'd be very appreciative.
This is the post I got the method from.
https://forum.arduino.cc/index.php?topic=605453.0
Thanks


text:
What is the best way to assign pins to an LED Cube?
I have made an LED cube that is a 3x3x3 design and was wondering if there is way to make a function in the Arduino IDE where each the layers of LEDs can be represented by a list with 1 being on and 0 being off:
{1, 0, 1, 0, 1, 0, 0, 1, 0} with the first number of the list being the first column, then the second column, etc. and the same for the rows which would be something like {0, 1, 0}. Does this make sense? If so, is there an idea for a function that could take these inputs and transform them into digitalWrite outputs? I am using an Arduino Nano for this, with pins 2, 3, 4, 5, 6, 7, 8, 9, and 11 used for the columns with A0, A1, and A2 being the rows of the cube.

Well, learning bit manipulations and using three uint16_t (as 9 bits won't fit into uint8_t) to store state for a whole cube is much better. Then you hust have to setup timer ISR and each time it fires just display one "floor". The multiplexing can be done even in loop, but it's usualy flickering as you can't do almost perfect timing as in the ISR.
And for example, I was using two 2x4x4 segments to build up 4x4x4 cube and single MAX7219 to drive it, so I don't have to handle whole multiplexing and so.
My another aproach was using individually addressable LEDs like WS2812B, so I needed only one pin to drive it all. Or by using ARM and DMA transfers, I could drive 8 or 16 lines simultaneously.


text:
Is Arduino Mega useing one buffer or multiple buffers?
So Arduino Mega has Serial, Serial1, Serial2, Serial3.
However, does those Serial lines use the same buffer? or four independent ones? i.e. are they truly receive single independently, or actually some sort of software sharing? How will that affect the coding?

what problems have you encountered?

@jsotola Not yet, but I'm trying to use UART to do a fast control system with distributive components. So there would be lots of data in ms circles in multiple ports at once. Basically, I'm trying to use over flow of data to establish fast and reliable processing... and it's kind of good to know how that buffer was working.

makes sense to be proactive .... you could run a test by feeding the same data to all three ports and read the data at varying speeds from the three ports .... you could connect the three receive pins together .... read in random sized chunks

Actually there are 2 buffers per Serial hardware interface: The hardware buffer, that is 1 byte (per direction of data transfer). The Serial library then transfers this byte in an extra buffer (64 bytes big) from an ISR. Every hardware Serial interface (Serial and Serial1 to 3 on the Mega) has it's own hardware buffer.
Then the Serial library is implemented as a class. Every hardware Serial interface get's it's own instance of this class, including the 64 byte buffer.
So the hardware and the memory is completely seperated. The only thing, what they share, is the CPU time for servicing the interrupts, which is no problem, until you are doing somehting very wrong with interrupts.

Every instance of class HardwareSerial has own buffers. Here you can see it in source code. The instances are declared/definded at the end of the HardwareSerial.h/.cpp.


text:
Why do people use 115200 instead of 9600?
So I came across lots of Arduino program setting serial speed to 115200 instead of 9600, while many people just kept using 9600 for the same purpose.
Why did people choose to use 115200 or other available speed? Why not just use 9600?

Because they want to communicate faster, or because the other end point is setup to 115200, and they don't want to change it. Or They use UART for MIDI with 31250 baud.

Because choice. 115200 is faster than 9600.

I sometimes use 460800 because it does slow down the sketch less then 115200 baud. and to communicate with esp8266 AT firmware over hardware serial on Mega I use 500 000 baud, to read the data from WiFi as fast as possible

@Juraj Do you know the reason why 460800 makes it less slowing down? related to multiplication values maybe?)

@MichelKeijzers, the TX buffer is 63 bytes long. if it fills, write/print blocks. so the baud rate is 'reflected' to the sketch. if I want to see the debug messages, but the problem is timing related, then sometimes higher baud rate helps

@Juraj Ah ok, thought it was some 'magic' number.

I didn't make a complete table on highest baud rate over different USB chips, but 921600 baud didn't work when I tried

@MichelKeijzers Exactly, why not using a faster speed like Juraj suggested? You see, you just contradicted your sentence.

@Juraj / ShoutOutAndCalculate ... I understand that higher is better, but just wonder what the value came from.

@MichelKeijzers Commonly you can't choose the serial speed to be any number. There are "standard" speeds like 9600 and 115200 that all derived from the first standard speeds like 75. BTW, the speed has the unit "steps per second", and in case of serial transmission one step is one bit. All these standard speeds are integer multiples of 75, most of them by factors of 2. For example: 9600 = 2^7 * 75, 115200 = 3 * 2^9 * 75.

@busybee thanks for the explanation.

https://www.arduino.cc/en/Reference/softwareSerial Because 115200 band was also the fastest communication enabled by the software serial.


text:
Program is executing but AT commands not showing in serial monitor
My purpose was to send SMS using GSM SIM800L coreboard  and Arduino UNO. Here is the code

    #include <SoftwareSerial.h>

//Create a software serial object to communicate with SIM800L
SoftwareSerial mySerial(3, 2); //SIM800L Tx & Rx is connected to Arduino #3 & #2

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(115200);

  //Begin serial communication with Arduino and SIM800L
  mySerial.begin(115200);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Once the handshake test is successful, it will back to OK
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  mySerial.println("AT+CMGS=\"+ZZxxxxxxxxx\"");//change ZZ with country code and xxxxxxxxxxx with phone number to sms
  updateSerial();
  mySerial.print("TEST"); //text content
  updateSerial();
  mySerial.write(26);
}

void loop()
{
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

And here is the serial monitor output
 22:31:19.430 -> Initializing...

However, when I run the code, I get the text message to my mobile phone, but I can't see any AT commands in the serial monitor. It only outputs "Initializing..." .
All the connections and baud rates are okay, checked a thousand times. Has connected 2A, 4.4v power supply to the GSM coreboard and shorten the wires, and sho No bad soldering joints. GSM module red led flash per 3 seconds. And again, I'm getting the text message to my phone. So that means the problem is with the Arduino serial monitor or code, not in the hardware. I need to see AT commands because I need to put more commands through the serial monitor, I tried typing and click send, But it's not showing anything. Any assistance you can provide would be greatly appreciated.

have tried a lower baud rate? ... that is one of the first things to try when debugging serial comm

Yes, I have tried many baud rates, 4800, 9600, also higher baud rates


text:
How to set CS pin on Beetle BLE/Bluno Beetle to Adafruit SD Card Breakout - Initialization Failed!
Hi I have a Beetle BLE (https://www.dfrobot.com/wiki/index.php/Bluno_Beetle_SKU:DFR0339) and I am trying to connect an Adafruit MicroSD card breakout board+ (https://www.adafruit.com/product/254) via SPI connections. I am trying the following code, but I am having trouble selecting the CS pin using D4 since the Beetle has no D10. Does anyone know if I am selecting D4 correctly, while keeping pin 10 as an output. I keep getting initialization failed! My setup is on the ICSP 6 pin configuration:
5V --> 5V
MISO --> DO
SCK -->CLK
GND --> GND
MOSI --> DI
D4 --> CS
RST is left out
Here is my code:
#include <SPI.h>

#include <SD.h>

File myFile;

void setup()
{
  Serial.begin(9600);
  Serial.print("Initializing SD card...");
  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  // Note that even if it's not used as the CS pin, the hardware SS pin
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output
  // or the SD library functions will not work.
//   pinMode(4, OUTPUT);
   pinMode(10, OUTPUT);
//   digitalWrite(4, HIGH); // Add this line

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.

  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
  // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop()
{
  // nothing happens after setup
}

Schematic of the Bluno beetle can be found here: https://www.dfrobot.com/product-1259.html The atmega is connected with rx and tx via 4k7 resistor to the bluetooth chip and the bluetooth chip is connected to usb. The spi bus is not used on the module, so there is no problem with other chips. Setting pin 10 as output and use pin 4 as chip select should work.

The correct ICSP was on the right, ICSP1. However, the orientation of those pins were from left to right on the TOP: SCK, 5V, MISO; left to right on the BOTTOM: MOSI, RESET, GND. In the Wiki they had the ICSP labels 1 and 2 reversed, but correct in the text below. https://www.dfrobot.com/wiki/index.php/Bluno_Beetle_SKU:DFR0339
Therefore, there was nothing wrong with the code, only the wiring to the correct pins!

The ICSP header labels on the Wiki page are wrong. In the schematic here the ICSP header has the same pinout as other Arduinos. The legend doesn't match the picture on the Wiki page but is true:

ICSP1: Atmega 328P
ICSP2: CC2540

The ICSP header is the inner one. Is right on the pictures.
At pin 1 on board the corner of the white square around pins is skewed. The pins are from left to right first row Eeset, CLK, MISO, second row Ground, MOSI, 5 V.
pdf schematic for the board

Hi Juraj, thanks for your reply. There are many links on that page link including the one I sent you. Could you please send a direct link to the correct ICSP diagram? Appreciate it.

added to the answer

Juraj and @Jot how does that correspond to the pins on the board in this picture? I'm not sure how to tell: ICSP Pin Pic

one corner is marked. it is pin 1 MISO

Sorry Juraj, I don't see it. Can you be more specific as to the order and orientation?

I edited the answer

Hi @Juraj. I soldered the wires this evening, but I'm still getting "initialization failed".   For the pins, how did you figure out that the diagram on the Wiki page was incorrect to begin with? PS - the same setup works on my Arduino Pro Mini, but I definitely want to get it working on the Beetle for my project.

I connected AVR ICSP header with dupont jumper wires so many times that I know the pinout without a diagram. And an Atmega 328 board can't have a different pinout of ICSP header because the AVR programmer connector would not match.

I'm still getting initialization failed. Any ideas as to what could be the problem? I checked my wires and they're as you said.

it is a question which of the two headers is Atmega. that with 3.3 V is not ICSP. in schema it is JP2. so it is possible that the right header is the right header

I edited the answer. https://github.com/Arduinolibrary/DFRobot_Bluno_Bettle/raw/master/Bluno%20beetle%20V1.0%20layout%20ground.pdf

Yes, I am already connecting to the correct one which is on the left (ICSP2), so that doesn't seem to be the issue here. Would the orientation and order of ICSP2 be the same as your AVR or could they be different?

Maybe the issue is something in the code which I'm not doing?

the right is right. ICSP1. ICSP2 is not ICSP.

Tested with the other pins  on ICSP1. That definitely didn't work as the sketch didn't even enter setup() because "Initializing SD card..." didn't print. Thanks for your continued help.

if the board doesn't boot, reset is connected to ground. or a short is somewhere

Hi Juraj, the correct ICSP was on the right, ICSP1. However, the orientation of those pins were from left to right on the TOP: SCK, 5V, MISO; left to right on the BOTTOM: MOSI, RESET, GND. In the Wiki they had the ICSP labels 1 and 2 reversed, but correct in the text below. https://www.dfrobot.com/wiki/index.php/Bluno_Beetle_SKU:DFR0339

then they should not call it ICSP header, because you cant use an ICSP AVR programmer with it https://www.olimex.com/Products/AVR/Programmers/AVR-ISP-MK2/open-source-hardware

I thought that ICSP is just a protocol and doesn't really have anything to do with a certain AVR programmer.

programmers have a cable with 2x3 connector

lol, I'll verify your findings on my device later, but thanks for this post. Wow, their documentation is not only useless but f'd up on top of it!

This is what I'm seeing with my multitester:

The cc2540 is the SMD chip on the same side as the ICSP pads. The atmega328p is on the opposite side of the PCB


text:
Parallel communication between multiple Arduino
Here's a post which explained the communication standard.
I need to establish communication between multiple Arduino nano board. I have used SPI bus on one of the Arduino board for wireless communication and I2C bus for another device. It appeared that both I2C bus and SPI bus support multiple device. However, since I have used both I2C and SPI for different purpose, establish parallel communication with RX TX pins seemed to be the preferable choice.
Question 1:
This post provided a nice set up for I2C bus as master and slave. However, can one adjust the code in step 2 of master device with
 Wire.begin(n);

and change all the Arduino boards as master&slave devices, thus achieve parallel communication?
Question 2: I read this post where people mentioned RS 485. However, can one achieve parallel communication with RX and TX pin like the one used in Question 1, without using RS 485?

please explain what you mean by parallel communication

@jsotola like 10 arduino nano board get together and send data to each other, the topology of the network is fully connected.

google arduino cluster and arduino node network

@jsotola That's too big. The whole point is to use the on board technology, with expanse the energy and mass of the project would be too much.

I think the term you need is "multi-drop bus", not "parallel". Parallel communication refers specifically to a completely different interfacing standard.

parallel communication is possible using arduino you need to use the ports for example port A and then a rx tx pins.
#include <Wire.h>
#include <Arduino.h>

byte i = 0;
int intpin = 44;
int rcv_ready = 45;

void setup() {
  DDRA = B11111111; // Output
  DDRC = B11111111; // Output
  pinMode(intpin, OUTPUT);
  pinMode(rcv_ready, INPUT);
}

void loop() {
  transmit();
}

void transmit() {
  PORTA = i++
  PORTC = i;
  digitalWrite(intpin, HIGH);
  while (rcv_ready == LOW) {}
  digitalWrite(intpin, LOW);

  delay(299);
}

Here we set up the two ports DDRA and DDRC to be output ports by using the   mask B11111111; We set the interrupt pin to port 44 and set it is an output and we set the receive pin to be 45 and an input.
Then we call transmit in the loop. Where we then set port A and port C to equal i++ and i respectively. And then toggle the signal to say we have transmitted a new message. This will get picked up by the Slave-input.
Slave input
#include <Arduino.h>

byte x = 0;
byte y = 0;
int rcv_ready = 45;

void setup() {
  DDRA = B00000000; // Input
  DDRC = B00000000; // Input
  Serial.begin(19200);
  attachInterrupt(5, blink, RISING);
  pinMode(rcv_ready, OUTPUT);
  digitalWrite(rcv_ready, LOW);
}

void loop() {}

void blink() {
  x = PINA;
  y = PINC;
  delay(100);
  digitalWrite(rcv_ready, HIGH);
  delay(100);
  digitalWrite(rcv_ready, LOW);
  Serial.print(x);
  Serial.print(" , ");
  Serial.println(y);
}

Here we set up the two ports DDRA and DDRC to be input ports by using the   mask B00000000;
We then set the baud rate as 19200 which matches the rate set by the master
Here we set the interrupt to be 5 which is pin 18 and tell it to call blink on an interrupt.
We then read the values from PORTA and PORTC and then we output it to the serial monitor screen. We also send back the acknowledgement of receipt to the master using pin 45

Please post your code in text format.


text:
RF24 code not working:
I watched this video and used his transmitter code and receiver code. However, it's not working. There's no response from the receiver.
The transmitter stuck at the loop:
if (!radio.write( &data, sizeof(unsigned char) )) {
Serial.println("No acknowledgement of transmission - receiving radio device connected?");
}

and the receiver never received anything and only printed:
  Serial.println("THIS IS THE RECEIVER CODE - YOU NEED THE OTHER ARDUINO TO TRANSMIT");

I've been stuck here for hours. I checked the hardware, there's no issue there. I also tried to adjust the code couple of times, and it looked decent but not helping. Could you help me to check what went wrong with the code please?

Try moving the transmitter and receiver further apart.

Check your wiring thrice, 99% of issues are there. Make sure the 3.3V bus is decoupled with at least 10mF of capacitance, noise on the 3.3V bus is an enormous no-no for nRF24L01+.

After that is done, find the RF24 examples from Arduino IDE, upload those to your boards with the right configuration and see if those work - it's a battle-tested piece of code.

@Avamander I saw your post in Arduino forum. However, it did not work for me. I went the expansive way. I tried the multiple noise filter, but it did not help. Eventually I got a special adapter with onboard regulator, it still didn't work. Turns out, it has to do with the communication device itself. The one I got had an antenna that strength singal the distance and penetration. But somehow it made the device very unreliable, possibly because it's receiving single within a mile. Once I switched to a weaker chip, it worked out immediately and the data was guaranteed.  Though less sensitive.

Even the modules with PA+LNA should work fine closer-range or in noisy environments. The most usual problem is that the power usage is underestimated, instead of the usual 14mA during transmission it could take hundreds, and that is above what onboard and could be above what small 3.3V regulators can provide. A few millifarads attached between GND and 3.3V should already improve reliability if it's the power that's the issue.

@Avamander There's nothing wrong with power. The single is very clean and I got maximum output of over 10W. I'm more and more sure it's the single receiving of that range-extended model. It's perpetuation ability was too good.  Does nRF24 library has any built in code to filter the single noise?(from the environment) I think the device is boosting every single received from the entire building. So it was not affected by the power supply, but the fact that the environment was so noise troubled actual single received.

@Avamander With weaker cheap, it's only able to receive the strongest single above certain threshold, thus a better communication quality and shorter range. i.e. it does not have the powerful LNA module.

Does nRF24 library has any built in code to filter the single noise? No, that can't be done.

The single is very clean and I got maximum output of over 10W. Are you within legal limits? The 2.4GHz band is for everyone to use.

@Avamander I set it to be min after the test.  and the channel I googled and used the channel that's not used by states providers

It's perpetuation ability was too good. [...] think the device is boosting every single received from the entire building. A nearby source will still most certainly overpower any far away noise source, receiving should work. The fact that a weaker module works still indicates a power supply issue rather than noise issue. However it's also possible that you have stumbled upon a counterfeit nRF24L01+, by any chance is it under a blob of epoxy?


text:
Can ESP 32 use the wire library exactly like that was in Arduino?
Compare the YouTube video and this webpage, the former one made programming very different in ESP32 and that was in Arduino nano, while the webpage seemed to imply that they work exactly the same.
Can we use the same code for standard Arduino library, like wire library, for ESP32 and ESP8266, or do we have to do something different?

in the video he doesn't use Arduino, but the Espressif IDF framework directly. the Arduino esp32 boards package has the Wire library for Arduino

@Juraj so does ESP 32 and ESP 8266 used exactly like Arduino for standard libraries? I heard the methods of pin labels were a little bit different.

I had no trouble to use the same sketch with Wire library on Uno and esp8266

software is the same. watch the voltages and pullups.

Code using the Arduino Wire library is generally portable between processors, but there are pitfalls to watch for.  One that I'm aware of is a difference in the Wire libraries for the ESP32 and ESP8266. The TwoWire::begin() method for the ESP32 has prototype:
bool TwoWire::begin(int sdaPin, int sclPin, uint32_t frequency);

whereas for the ESP8266 it is:
void TwoWire::begin(int sda, int scl, uint8_t address);

So, a call to begin() using the ESP#2 library will set the clock using the third parameter, whereas on the ESP8266 it will truncate the third parameter and use it as an address.
If you wish code to be portable between the ESP32 and ESP8266, then the fix for this particular issue is to call TwoWire::begin( my_SDA_pin, my_SCL_pin ) (specifying only two parameters:the SDA and SCL pins), and use a separate call to TwoWire::setClock( my_clock_speed ) to set the clock.
There may be other differences I'm not aware of...


text:
Will a pull up resistor help the UART transmission accuracy on Arduino nano?
On A post from Arduino forum , someone mentioned that a pull up resistor over RX/TX pin could help the reliably of UART communication.
Is that really the case for nano and uno board?

Nope. Did you read the question and the answer on that post? This question was about connecting multiple TX to one RX with the UART (something that it was not designed to do). The UART actively drives the RX and TX pins both low and high and does not normally need pull ups (or pull downs for that matter). If you're planning to cross larger distances, you should look at RS232, RS422 or 485.

@StarCat But they said" Master will probably need 2.2K to 4.7K pullup resistor to bring the line high reliably/quickly."

Please read the question and the answer for that post. This was not about a simple TX->RX connection but a connection of multiple TX to one RX via a diode on every TX and a pull up on the RX. This is not the way that the UART is usually used and requires bus arbitration between multiple devices.

In my experience the BIGGEST gain in reliability came from using the hardware port instead of SoftwareSerial. MASSIVE gain...

@Wendall I'm having defects in hardware port, that's why I'm looking for better ways, I've already implemented twisted wire, and capacitors, so I'm wondering if pull up resistor will help for the fast response.

What type of defect? Fried at some time or not working the way you wish? Is it distance related? Baud rate? or ???

Is the interface RS232, 485, or ? You are not getting the data you expect. What is the layout of what you are doing?

Depending on the interface, capacitors will likely do bad things.

@Wendall Capacitors stabilize the power supply.

On power yes, but on comm lines is a bad thing... they will destroy frequency response.

Please show your circuit and elaborate on your problem.

No. That is not the case. Adding a pullup resistor on a normal UART will do nothing except maybe reduce your reliability.
You only want pullup resistors on something which is "open drain" (AKA "open collector") which has no way of raising the voltage of a signal line, only lowering it - such as I2C signals, or a shared open-drain, interrupt signal.


text:
Super fast UART transimission return error
The code was based on Fahad Mirza's very helpful example here Send structure through Serial
The Sender's code now became
struct Gyro_data_structure
{
  char command_name[5];
  float gyro_X;
  float gyro_Y;
  float gyro_Z;
};

Gyro_data_structure Gyro_data;
int size_gyro = sizeof(struct Gyro_data_structure);

void setup() {
  //Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
  //Serial.begin(115200); // opens serial port, sets data rate to 9600 bps
  Serial.begin(250000);
}

void loop() {

  Gyro_data.command_name[0] = 'H';
  Gyro_data.command_name[2] = 'l';
  Gyro_data.gyro_X++;
  Gyro_data.gyro_Y=12;

  Serial.write('p');
  Serial.write('L');
  Serial.write(Gyro_data.command_name, sizeof(Gyro_data.command_name));

  Serial.write('m');
  Serial.write('x');

  send(&Gyro_data);
  delay(100); //---------------------the parameter played in this post
  //Serial.flush();
}

void send (const Gyro_data_structure* table)
{
  Serial.write((const char*)table, size_gyro);  // 2 bytes.
}

The Receiver's code
struct Gyro_data_structure
{
  char command_name[5];
  float gyro_X;
  float gyro_Y;
  float gyro_Z;
};

Gyro_data_structure  Gyro_data_received;
int size_gyro = sizeof(struct Gyro_data_structure);

void setup() {
  Serial.begin(9600);
  //Serial1.begin(9600);
  //Serial1.begin(115200);
  Serial1.begin(250000);
}

void loop() {

  //if(Serial1.available()>0)
  if(Serial1.available()>=size_gyro)//----------------worked very welll//------------------------
  {
      Serial.println(Serial1.available());

    //Serial1.findUntil('p','L');
    //Serial1.find('p');
    //Serial1.find('L');

  if ((Serial1.read() == 'p') && (Serial1.read() == 'L'))
  {
    Serial1.readBytes(Gyro_data_received.command_name, sizeof(Gyro_data_received.command_name));

    Serial.println("Received confirmation");
    Serial.println(Gyro_data_received.command_name[0]);
    Serial.println(Gyro_data_received.command_name[2]);

    if ((Serial1.read() == 'm') && (Serial1.read() == 'x')) {

      Serial.println("Gyro data received");
      receive2(&Gyro_data_received);

      Serial.println(Gyro_data_received.command_name[0]);
      Serial.println(Gyro_data_received.gyro_X);
      Serial.println(Gyro_data_received.gyro_Y);
    } else {
      Serial.println("Gyro data lost");
    }

  } else {

    Serial.println("No code confirmed");
    while(Serial1.peek()!='p'){
    Serial.print(Serial1.read()); //basically clean the receiver
    //Serial1.flush();
    }

  }

  }
}

bool receive2(Gyro_data_structure* table)
{
  return (Serial1.readBytes((char*)table, sizeof(Gyro_data_structure)) == sizeof(Gyro_data_structure));
}

What it does is for sender send a 5 byte char array and a structure to receiver. If receiver received the "code", i.e. char 'p' 'L' and 'm' 'x' it read the incoming 5byte char array and structure. If the code was not confirmed, it clear the incoming bytes.
However, I encountered the following issue.
First, at receiver's code, one pay attention to
  if(Serial1.available()>0)
  if(Serial1.available()>=size_gyro)

the condition for which the receiver start to process the read() sequence.
However, at speed(9600), I noticed that if one use
if(Serial1.available()>0)

very often it start to read when Serial1.available()=1, and return incorrect numbers which got cleared out by
Serial.println("No code confirmed");
while(Serial1.peek()!='p'){
Serial.print(Serial1.read()); //basically clean the receiver
//Serial1.flush();
}

But if one use
  if(Serial1.available()>=size_gyro)

as the condition to trigger the read(), it worked out very well. On the other hand, if one increase the serial speed to, say 115200, this does not matter, as they both return the correct result. Could you explain to me why this was the issue, please?
Second, please pay attention to
  send(&Gyro_data);
  delay(100);

At speed at or above 100, with nano board and mega board, this worked out fine. But if one wants to increase the transmission speed, change delay(100) to delay(20) in sender's code, the receiver's code returns error. This issue could not be resulted by change the wiring or increase the serial speed. Especially, the receiver's at part
  Serial.println(Serial1.available());

usually return a number of 62~63 when there's an error.
Could you explain to me where did those two questions come from? Were they because the chip set on Arduino? Especially, how to achieve a communication response under 20 ms?

what two questions are you talking about?

In my answer to your previous question, I wrote: “Binary is, however, harder to handle: [...] you may need to define a protocol of sorts in order to get the framing right. [...] I generally recommend using ASCII unless you really need the extra efficiency of a binary protocol.”. You see what I mean now?

Do you have an idea what serial speed means? Think about what your program does, and how fast bits and bytes are transfered.

First, you got some logic wrong in the receiver: you have a test for
Serial1.available()>=size_gyro and, when this is true, you read
size_gyro + 9 bytes. You should change the test in order to only start
reading when you actually have size_gyro+9 bytes available.
Then, note that command_name is transmitted twice: first as part of
the 9-byte preamble (between "pL" and "mx"), then as part of the
transmitted Gyro_data_structure. There is no point in doing so.

at speed(9600), I noticed that if one use if(Serial1.available()>0)
  very often it start to read when Serial1.available()=1, and return
  incorrect numbers

This is expected: you wait for 1 byte to be available in the input
buffer, then you attempt to read the 9-byte preamble. One of your calls
to Serial1.read() is going to find the buffer empty, and it will then
return −1.

But if one use if(Serial1.available()>=size_gyro) as the condition
  to trigger the read(), it worked out very well.

In other words, when you wait until 17 bytes are available before
reading the 9-byte preamble, you get at least the preamble right. Is
this surprising?

if one increase the serial speed to, say 115200, this does not matter,
  as they both return the correct result

Your code takes some time to do the reading. At a fast enough baud rate,
the serial port receives the incoming bytes faster than your code reads
them, so you never run into an empty buffer.

if one wants to increase the transmission speed, change delay(100) to
  delay(20) in sender's code, the receiver's code returns error

The sender is going too fast, and the receiver cannot cope with the data
rate.

Serial1.available() usually returns a number of 62~63 when there's
  an error.

This means the receive buffer is full.
Note that the receiver would be way faster if it wasn't printing so
much. Upon receiving a correct transmission, it will Serial.println()
a bunch of messages that should total at least 64 bytes. Transmitting
those bytes at 9600 b/s takes more than 66.5 ms.

Edit: proposed solution.
Your idea of prepending a “code” to the data structure in order to
identify a correct transmission is in the right track. This is a kind of
format indicator commonly known as a “magic number” or a
“signature”. It does not ensure correct transmission with 100%
confidence, as the signature could be present by accident as part of the
data structure itself. But if the signature bytes are unlikely enough to
happen by accident, you have a pretty high confidence that wherever you
find the signature in the data stream it's the start of a new packet.
You can increase this confidence by making the signature longer, at the
cost of longer transmission times.
Now, for a matter of simplicity, I would not send the signature as two
disjoint parts. Common practice is to send it as one contiguous set of
bytes, at the very beginning of the packet. For example, I would send
your packets like so:
// 5-byte signature, including the terminating '\0'.
const uint8_t Gyro_signature[] = "Gyro";

void Gyro_send(const Gyro_data_structure &gyro) {
    Serial1.write(Gyro_signature, sizeof Gyro_signature);
    Serial1.write((uint8_t *) &gyro, sizeof gyro);
}

You may want to change the signature to something less likely to happen
by accident.
On the receiver side, when you expect the signature, you read from the
port one byte at a time while counting how many correct bytes you have
so far. The algorithm goes as follows:

let i = 0 be the number of correct bytes received so far
read an incoming byte
if that incoming byte is correct, increment i
otherwise, if we just got the first signature byte, reset i = 1
otherwise reset i = 0
unless we got the full signature, go to 2

This assumes that the first signature byte doesn't appear elsewhere
within the signature. Otherwise steps 4–5 would be more complex.
Here is a receiver function that implements this algorithm, then reads
the data structure:
void Gyro_receive(Gyro_data_structure &gyro) {

    // Read until we get a complete signature.
    int discarded = 0;
    for (size_t i = 0; i < sizeof Gyro_signature; ) {
        if (Serial1.available()) {
            char c = Serial1.read();
            if (c == Gyro_signature[i]) {  // correct byte
                i++;
            } else if (c == Gyro_signature[0]) {  // first byte
                discarded += i;
                i = 1;
            } else {
                discarded += i+1;
                i = 0;
            }
        }
    }
    if (discarded) {
        Serial.print("Discarded ");
        Serial.print(discarded);
        Serial.println(" bytes.");
    }

    // Wait for the data.
    while ((size_t) Serial1.available() < sizeof gyro)
        /* wait */;

    // Read it.
    Serial1.readBytes((char *) &gyro, sizeof gyro);
}

Note that this function is blocking. If you need a non-blocking version,
you should be able to easily convert the signature-checking part into a
finite state machine where i is the state variable.


text:
How to set a time out like Serial.setTimeout() for Serial.read()?
I read a comment form here:
"Serial.setTimeout() sets the maximum milliseconds to wait for serial data when using Serial.readBytesUntil(), Serial.readBytes(), Serial.parseInt() or Serial.parseFloat(). It defaults to 1000 milliseconds."
According to the latest webpage,
"Serial functions that use the timeout value set via Serial.setTimeout():
Serial.find()

Serial.findUntil()

Serial.parseInt()

Serial.parseFloat()

Serial.readBytes()

Serial.readBytesUntil()

Serial.readString()

Serial.readStringUntil()

"
So apparently, there's no direct indication to set a timeout option for Serial.read().
How to set a time out like Serial.setTimeout() for Serial.read()?

You can't set timeout for read(), but you can use readBytes() to read one byte.
byte b;
int count = Serial.readBytes(&b, 1); // read one byte with timeout
if (count) { // 0 or 1
  Serial.write(b); //echo
}

So Serial.read() and Serial.readBytes() were like two different class of objects?

no. read() is the basic function. readBytes() is a function too and implemented with use of read().


text:
How to calibrate MPU 6050 thermometer?
I'm using MPU 6050 and there's a thermometer onboard. However, I looked through the chip set data sheets but could not find the instruction for temperature sensing.
Could you tell me how to calibrate the data string from the two address started from 0x41?

The temperature sensor is likely included to keep the gyroscope and accelerometer better calibrated over the specified temperature range.  The temperature may not be the ambient temperature should the chip warm up.
The temperature sensor specifications are in section 6.3 on page 14 of the specification sheet indirectly pointed to in the question.
TEMPERATURE SENSOR
Range -40 to +85°C
Sensitivity Untrimmed 340 LSB/ºC
Temperature Offset 35ºC -521 LSB
Linearity Best fit straight line (-40°C to +85°C) ±1°C

So, when the chip is at 35C the chip temperature register is supposed to read about -521.  To convert that into C you need to make a calculation:

chip_temperature = ((value_read + 521) + (35 * 340)) / 340

Simplified:

chip_temperature = (value_read + 12421) / 340

This looks like the right conversion above, 35C, but I get some weirdness below, it becomes 229. Also of interesting note, the well known i2cdevlib library has code for the MPU6050, and example code exists for reading temperature using mpu.readTemperature(); however, no such method seems to exist in the library (anymore?). There is something called getTemperature(); but that gives out data raw, not converted. How very strange.

I would check the math and also pay attention if the code is performing integer arithmetic and causing rounding errors.  In which case add decimal points to your numbers in an effort to force floating point math.  I'm not familiar with i2cdevlib as I've been using the drivers from the OEM.  But if no one answers your question here, I would post an issue (ask your question) over in the i2cdevlib github web pages.

Yeah, I suspected it was something like that. Re-inspired, I took another crack at casting all the variables, and I got it to behave more or less as it should. Looks like it was because I wasn't casting the uint16 returned (what would be value_read above) up to float before adding and dividing. Incidentally, I'm using a Longan nano, not an Arduino. The inbuilt screen lib for displaying text doesn't like floats, so I was trying to avoid them. Looks like I was trying too hard. Either way, the math you provide is good. +1


text:
RF24 library commands, channel, and address
I'm trying to use the RF24 library for wireless communication.
However, it appeared that this library does not have "help" option.
There was a keywords file but it did not explain what it does.
I found couple of examples online, and in the library, but id did not explain things quite in detail.
Could you explain to me how those command works, and weather there's any help file for the library?
Especially, I have a question about the channel and address used in the library.
A. Does address take character or number as input?
The official example in the library used
byte addresses[][6] = {"1Node","2Node"};

But I also say some example use
byte addresses[][6] = {"00001","00002"};

The byte command was suppose to be a 8-bit unsigned number, from 0 to 255, but why they used string " " as input?
I found a sentence in RF24.h file: Addresses are assigned via a byte array, default is 5 byte address lengths. But why they wrote byte addresses[][6] instead of byte addresses[][5]?
B. From some other video I learned that RF24 have channel and address for communication, where channel can take value from 0 to 125; pin/port take value from 0,1-5; and the address.
setChannel  KEYWORD2

The pin was explained in RF24.h. However,

Can one open multiple channel at once?
If one use the same addresses in multiple channel at once, can the address being distinguished, or were they treated as the same address?
Is channel-pin/port(while writing)-address a tree structure?

C.
Can one open up more pin/port in transmitting and writing?
  openWritingPipe   KEYWORD2
  openReadingPipe   KEYWORD2

there is a link on the page you linked. http://tmrh20.github.io/RF24

I'd suggest reading the datasheet. It's quite well written. Don't worry if you don't understand everything; just keep reading. That should give you a good idea of what this module does, and how it sort of works.

A. Does address take character or number as input?

The address is 5 bytes. In this library it is provided as an array. In C a string is merely an array of bytes. So it is possible to represent an array of bytes as a simple string. Internally the two representations:
byte address[] = "123ab";

and
byte address[] = { '1', '2', '3', 'a', 'b' };

and even:
byte address[] = { 0x49, 0x50, 0x51, 0x97, 0x98 };

are all identical, except that the first one adds an extra 0x00 to the end of it to mark the end of the string (which the library completely ignores).

B. From some other video I learned that RF24 have channel and address for communication, where channel can take value from 0 to 125; pin/port take value from 0,1-5; and the address.

It's helpful here that you have some understanding of basic radio communication terminology.
When you say that a device works at X frequency you are generally only referring to the "frequency band" that the device operates within (2.4GHz in this case). The device doesn't work at 2.4GHz - only "in the 2.4GHz band". That frequency band is then divided up into channels. Each channel is a specific frequency. Just like your television has channels you select one specific channel (and thus frequency) to tune into and communicate on.
Channel numbers are just used because it's far far easier to remember "channel 21" instead of 471.25MHz, for example.
For two devices to be able to communicate they both need to be tuned to the same frequency, and hence the same channel.
The "address" is more like the address your computer has on the network. Within the channel frequency you can have multiple devices communicating. The address identifies exactly which of the devices you want to send data to or are receiving data from.

C. Can one open up more pin/port in transmitting and writing?

The nRF24L01 internally uses pipes as a method of separating data from different devices into distinct feeds that you can read from. It is merely for convenience. You can open up to 6 pipes at once, each one receiving from a different address. All pipes are in the same channel though since you can only tune to one channel at a time.
By the way - the keywords.txt file exists solely for the IDE to do highlighting of certain words. It's not meant for a human to read when working out how to use a library.


text:
Is it "safe" to use "new" keyword to instantize several sensor objects?
I've read that it is bad practice to use dynamic memory allocations on a microcontroller and I have a pretty good grasp of why.
I am developing a custom PCB around an ATMega2560 and in my situation, I need to create 24 objects for one kind of sensor and 8 more for another.
With a small number of sensors, you might create objects like this:
Ezo_board PH = Ezo_board(99, "PH");       //create a PH circuit object, who's address is 99 and name is "PH"
Ezo_board EC = Ezo_board(100, "EC");      //create an EC circuit object who's address is 100 and name is "EC"

But since I have so many and I want to loop through them I created a pointer array
Ezo_board *EC[maxEC];
and in setup function I wrote:
for (uint8_t i = 0; i < maxEC; i++)
 {
  EC[i] = new Ezo_board(i+11) //passing the I2C address which start at 11 and increment

I never delete the Ezo_board objects in the code. Is this a safe way to use dynamic memory allocation or is there a better way to do this while still maintaining ability to loop through the sensors in subsequent code?

Why do you think you need dynamic allocation? It can be Ezo_board boards[] = {{99,"PH"}, {100,"EC"}, };, or if it has ambiguous constructors you'll need  = {Ezo_board(99, "PH"), Ezo_board(100, "EC"), }

My concern was with hard coding all the sensors in when I may wish to adjust the number of sensors used on a given board. By defining a number of sensors (maxEC), I just need to change a constant.

Well, arduino supports c++11 standard for a while, you can use range based for loop like:  for (auto & sensor : sensors)  { ...  and you don't have to know the size

I hadn't heard of range based loops before, I'll look that up!

The danger in using dynamic memory on embedded devices lies in repeated allocation & de-allocation of chunks of memory. The memory allocator splits off a piece of memory for each allocation. When one is returned the de-allocator joins it - or should join it - with an adjacent free chunk, if there is one, to create a larger free chunk instead of two adjacent smaller ones. But that is a big 'if': 1) does the particular memory-manager even try to do that? and 2) in too many instances, it won't even be possible.
The net result is that the memory pool becomes a bunch of small fragments that aren't join-able and aren't large enough to satisfy further requests.
In your scenario, dynamic allocation at the start of the run with no further returns and re-alloacation, there is very little difference between it and static allocation, other than the static allocation would have be done at load-time, just before the run begins.
Either way is fine in that case. If anyone else might ever look over your code, or if someday in the future you might come back to it and wonder whether this application might have created a fragmentation problem, then it's worth leaving a comment to make your intentions clear.
I should add here that when I need dynamic allocation in an embedded system, I write my own memory allocator that never splits free memory. Instead, it simply hands out one buffer from a statically allocated array of fixed size buffers for any request up to that size (and returns a failure code otherwise). Memory is never split or joined, so it never gets fragmented. As long as the demand for buffers is predictable and you allocate enough of them to meet the maximum demand, your system won't fail for running out of memory.

Yes, it is (in common sense) bad practise and you know why and you probabelly also know, why it is not problem in your case.
It is perfectly safe way and I do not see, why you should not do it this way.
I do similar things regularry and I have no problem with it.
I want my code working right and the readibility and maintainability are the more important steps in this way. So I structure my code in such way, that I can understand it easily even after couple of years.
There are many rules, how to make code better and there is some reason after each one. But some goes against others.
I have Arduino for fun and I use the rules as recomendations, but I am the Master of my code. So I sometime take other ways.
If it helps me to see the code better organized, I have not problem to do things my own way.
(In large corporation, where you must share code with many others, the formal rules are more important, as they helps all to be at the same platform. There you are payed to stick to rules.
In home developement I share code mainly with myself and I am not paid. So I have to care mainly only about future me)


text:
How to upload program to custom arduino board without USB FTDI and making it read only?
If I was to mass produce a microcontroller board I have designed based around the atmega328 (very similar to an arduino uno) but for one embedded task where I want one program only to be stored on it. I want to make the program read only and impossible to access and impossible to overwrite. The board will not include a USB FTDI chip in order to prevent another program being uploaded via arduino IDE. How would I upload said program to the microcontroller?
Would I have to make use of ICSP pins (I dont know much about that) and if this is an impossible task and so a USB will have to be integrated to upload programs... How would i prevent other programs overwriting the main program and also prevent this program from being viewed?
[The main program is written in the arduino IDE]

you use pins built into the 328 to program it. 2. removing the pins will help, but ultimately, you can't.

I think you cannot prevent overwriting the firmware, neither prevent viewed by others.
However, you can detect that someone overwrites it (besides you), by reading some code from e.g. EEPROM based on the content of your firmware. If you read a different code, than you can act upon it.

You can prevent reading by setting the lock fuses


text:
How to share/Reassign analog pin for two Adafruit libraries for two adafruit hardware
I'm attempting to use the Adafruit BMP180 and Adafruit 16x2 RGB LCD Display together on the same Arduino Uno R1. Both the pieces of hardware and their libraries use Analog Pin 4 and 5. Is there any way to reassign the pins for one of the libraries so I can use both of the parts together?
Here are the libraries I am using:
Adafruit BMP180/BMP085:
https://github.com/adafruit/Adafruit_BMP085_Unified and https://github.com/adafruit/Adafruit-BMP085-Library
Adafruit 16x2 RGB LCD Display:
https://github.com/adafruit/Adafruit-RGB-LCD-Shield-Library


text:
Why ESP8266 slower than Arduino nano?
I'm using the same script(and standard wire and serial library only) one uploaded to Arduino nano one uploaded to ESP8266. However, despite ESP8266 running at 160MHz, 10 times faster than nano, it's taking 3.5 ms to complete the loop, compare to 2.5 ms than that of nano.
How could that be?  why ESP8266 was slower?

It depends on what the script is doing. In practice the ESP8266 will almost always be faster. An exception might be I2C (the Wire library, like in your test). The Arduino Nano AVR processor has hardware support for I2C; the ESP8266 must use the much slower “bit banging” method.

@StarCat will the same thing (wire) happen to esp32?

It depends. Please show us the code.

@ShoutOutAndCalculate, The ESP32 has hardware support for I2C so should be able to run faster.

@StarCat Thanks! So I won't need to do the pull up resistor on ESP 32 like that of ESP 8266 right?

You can use internal pull ups, but the consensus seems to be that they are too weak for fast I2C operation and that external pullups are better (around 4.7K Ohm).

However, despite ESP8266 running at 160MHz, 10 times faster than nano, it's taking 3.5 ms to complete the loop, compare to 2.5 ms than that of nano.

There's a number of reasons for that. Chiefly:

The ESP8266 has no I2C hardware, so has to use software "bit-banging" to emulate I2C. That is slower to execute.
The ESP8266 also has to manage the WiFi hardware which takes a portion of the processing power away from the user

The result is slower execution for I2C operations and "jitter" added to timings of loops and such.

will the same thing (wire) happen to esp32?

No (or not as much). The ESP32 has hardware I2C so it doesn't need to use bit-banging to emulate it, so it will be faster. Also it is dual core and one core is used for "system management" including managing the WiFi and Bluetooth, while the second core is used to execute your sketch, so there is no (or little1) interruption by the WiFi slowing down your sketch.

1: Two cores accessing the same area of RAM causes some contention as only one core can access the same block of RAM at a time, so it's not perfect. You may still get slight delays, but they will be minuscule compared to the processing needed for the ESP8266's WiFi code.


text:
If Arduino connected to computer and opened up Serial Monitor, will Tx and Rx pin still be working?
Suppose one connected two of the Arduino Uno boards through Rx and Tx pins. Then, if one or both of the Arduino boards were connected to computer, and possibly opened up Serial Monitors, will Tx and Rx pin still be working? i.e. will Arduino still communicate through Rx and Tx pin when it's communicating to computer? If not how to make them working while connect to computer?

The USB FTDI chip is connected to the TX/RX pins. So serial may not work the way you expect.

Suppose one connected two of the Arduino Uno boards through Rx and Tx
  pins.

I assume you will connect the TX of one Arduino to the RX of the other
one and vice versa, which is the right way to connect them. As
theSealion explained in his answer, you shouldn't connect two TX Pins
together.

if one or both of the Arduino boards were connected to computer, and
  possibly opened up Serial Monitors

If you do that, the Arduino won't even notice.
Well, to be more accurate... there is a small chip on the Uno, near the
USB connector, labeled “MEGA16U2”. This chip is used as a USB/serial
converter, and it will notice when you connect the USB link and when
you open the port. However, the main chip (the big PDIP28), which is the
microcontroller that runs your sketch, will neither know nor care.

will Tx and Rx pin still be working?

Absolutely.

will Arduino still communicate through Rx and Tx pin when it's
  communicating to computer?

The RX will not communicate with the computer. What will happen is:

Whatever your Arduino writes to its serial port will be received by
both the other Arduino and the serial monitor.
Whatever you send through the serial monitor will be lost.
When you Serial.read(), you will get whatever was set by the other
Arduino.

The reason of this behavior is a 1 kΩ resistor that sits between
the Mega16U2's TX and the main microcontroller's RX. When you connect
this RX to the other Arduino's TX, which is low impedance (≈ 25 Ω),
that TX will “win”: a low impedance output overwhelms a high impedance
one.

how to make [two Arduinos communicating with each other] working while connect to computer?

There are a variety of ways for 2 Arduinos to directly communicate with each other while one or both are communicating with the Serial Monitor of a laptop computer over USB.

Use a UART for the Arduinos to communicate that is independent of the USB connection. (See https://www.arduino.cc/reference/en/language/functions/communication/serial/ )

Several Arduino-compatible boards such as the Arduino Mega 2560, Arduino Due, Arduino Uno Wifi Rev.2, etc. have 4 hardware UARTs; the pins of Serial1 (note the "1") could be used to communicate with another Arduino without interfering with the Serial (without a "1") UART communication over USB to a laptop. (Alas, the Arduino Uno has only 1 hardware UART).
The ATmega32u4-based Arduino Micro and Arduino Leonardo and ATmega32u4-based Arduino derivatives such as FLORA and many of the ARM-based Arduino derivatives such as the Teensy series have a USB interface that doesn't use any of the UART pins; so the pins of Serial1 (note the "1") could be used to communicate with another Arduino without interfering with the Serial (without a "1") non-UART communication over USB to a laptop. (Alas, the Arduino Uno has a USB interface that does use its only hardware UART pins).
Even the Arduino Uno, which has only 1 hardware UART whose pins are hard-wired to the USB interface chip, can bit-bang a slow simulation of a UART on other pins. See What's the difference between all the Software Serial Libraries? Which one is Arduino Nano compatible? .

Rather than try to simulate a UART in software (the timing is kind of tricky), it may be easier/faster to use some other less time-sensitive ways of communicating between Arduino Unos or other Arduinos, such as

SPI between 2 Arduinos (a); (b)
I2C between 2 Arduinos (a) (b)
PJON between 2 Arduinos
a few asynchronous communication protocols have no timing dependencies at all
etc.

I got exactly the same problem! I was using the Arduino Uno board with an Jtag ICE mkii for debugging which was working nice. As I begann to use the UART it was a heavy mess. The transmitting from Arduino to an external TTL-USB adapter was working but not in the other direction. I played hours before I saw this thread and that gave me the idea for looking into the shematic -> Bang! I saw the two resistors.
Lesson learned: Do not use the Arduino hardware without the rest of the tools! Thought it was a good idea to use the hardware for rapid development. Now it costs me more time that I thought...

You should't connect two TX Pins together. The Arduino has some protection resistors but even it is not recommended to connect two output pins.
The only save way to use the RX / TX pins directly is to remove the protection resistors (RN4A and RN4B in the reference design) or at least the RN4A  and use only one connection at a time. It doesn't help if you do not use the PC connection or doesn't open the Serial Monitor since the pins is still an output.
(Multiple RX Pins are no problem since they are inputs)
(And of course I know it could work with multiple TX pins together most of the time, but I would recommend it)


text:
DS3231 High Power Consumption
I plan to use my Arduino with a small battery all the time so I don't want it to use so much power. I was checking power consumption of DS3231 with a multimeter, at first it was fluttering around 1 mA and 0.4 mA with 3.3 volts. I removed the battery on DS3231 to reduce affect of charging but now it's still high, about 0.4 mA. The official paper says it should use a lot lower than that. Is it an error about my multimeter or is there something I missed like a configuration or something?

I think the data sheet talks about the current consumption from the battery. That mean, how much the module draws from the battery if it not connected to a controller. If it is connected to a controller and communicates with it, it needs more current which it draws from the controller. and not from it's own buffer battery.

Yes I connected its power to a digital pin now.


text:
L298N Motor Driver - Code issuing "expected primary-expression before '=' token"
Programming Questions / L298N Driver - Code Issuing - " expected primary-expression before '=' token"
Today at 07:20 pm
Hello Arduino Community,
Code is shown at bottom - please read below
I've been working on a little project that uses the L298N Dual Motor Driver to run a single motor.
Using this link I set up my project (disregard Using the L298N with PIC Section) :
https://www.teachmemicro.com/use-l298n-motor-driver/.

I connected my wires and checked them and their connections for any problems.
I am using 1 motor instead of two
I am using two 'C' Duracell Alkaline Batteries, connected them together in a series circuit. I've tested the batteries and they run my Small Round Electric Motor with 12000 RPM + 3 to 6V DC perfectly when I don't connect the battery and motor to the L298N Driver.
The two, 'C' batteries are 1.5 volts each (connecting them together in series give me 3 volts)
I am connecting my arduino uno to a newly purchase laptop - I've compiled codes from this computer that have worked fine.

I copied and pasted the code from the website at the link at the top. I checked device manager and chose the correct port with the correct board, so I am starting to believe there is something wrong with the code on the website.
Once I compile the program, errors pop up stating, "expected primary-expression before '=' token" for every line of code that has a #defined variable (mentioned on the top lines of the program).
It would be helpful to please comment your thoughts and solutions for this issue.
Please see link at the top for code.
Thank you.

when a sketch fails to compile, it has nothing to do with the hardware itself ... you only need to select the correct board before compiling, but it does not need to be connected for the sketch to compile ... connection to the board is only necessary during the upload phase after compilation is successful ...  that means that all of the information that you included about batteries and motors is irrelevant to your question

Definitions via #define don't use equal signs. The following is wrong
#define EN = 1

Instead it should be
#define EN 1


text:
The problem of not saving the previous value when sending it from bluetooth
Controlling Led's from Buttons and Bluetooth by same method
The problem now :
the LED light up when you send an A over Bluetooth and it will turn off after 2 sec automatically without you doing anything (this is the wrong now in video).
I Want the same char when send data the led turn on and when i want closed led send same char to turn off light .
The code: bottom this page
thank
this is the wrong now in video

 #define CLK 10
 #define CLKI 9
 #define LD 8
 #define SO 11
 #define SER 12

 byte ledstates;
 byte copy=0;
 unsigned long bt_leds_timestamp=0;
 byte bt_leds_activated=0;

 void setup(){
   Serial.begin(9600);
   pinMode(CLK,OUTPUT);
   pinMode(CLKI,OUTPUT);
   pinMode(LD,OUTPUT);
   pinMode(SO,INPUT);
   pinMode(SER,OUTPUT);
  }

 void loop(){
  if (Serial.available()>0){
  message();
 }
  shift_In();
  shift_out(ledstates);

  if(bt_leds_activated && millis()-bt_leds_timestamp > 2000){
  ledstates &= ~bt_leds_activated;
  shift_out(ledstates);
   bt_leds_activated = 0;
  }
 }

 void message(){
  if(Serial.available()){      // Send data only when you receive data:
  char data = Serial.read();        //Read   the incoming data & store into data
  Serial.print(data);          //Print Value inside data in Serial monitor

  switch (data){
  case 'A' :
    bt_leds_activated |= 1;
    break;
  case 'B' :
    bt_leds_activated |= 2;
    break;
  case 'C' :
    bt_leds_activated |= 4;
    break;
  case 'D' :
    bt_leds_activated |= 8;
    break;
  case 'E' :
    bt_leds_activated |= 16;
    break;
  case 'F' :
    bt_leds_activated |= 32 ;
    break;
  case 'G' :
    bt_leds_activated |= 64;
    break;
  case 'H' :
    bt_leds_activated |= 128;
    break;
  default   : return; }
  }
   ledstates |= bt_leds_activated;
   shift_out(ledstates);
   bt_leds_timestamp = millis();
  }

 void shift_out (byte copy){
  digitalWrite(LD, LOW);
  shiftOut(SER,CLK,MSBFIRST,copy);
  digitalWrite(LD, HIGH);
  delay(100);
 }

 void shift_In(){
  digitalWrite(CLKI,HIGH);
  digitalWrite(LD,HIGH);
  digitalWrite(LD,LOW);
  digitalWrite(LD,HIGH);
  digitalWrite(CLK,HIGH);
  digitalWrite(CLKI,LOW);
  byte buttonstates = shiftIn(SO,CLK,MSBFIRST); //read button states in a local variable
  digitalWrite(CLKI,HIGH);
  for(int i=0;i<8;i++){ // loop through all 8 bits of the buttonstates
    if(!(copy & (1<<i)) && (buttonstates & (1<<i))){ // check if old button state (in copy) is zero and new buttonstate is 1 (for the currently check bit)
        ledstates ^= 1<<i; // toggle the corresponding bit in the ledstates variable (will be shifted out later in the loop() function)
    }
  }
  copy = buttonstates;
  delay(10); // delay for debouncing
  }

C has an "Exclusive Or" operator which is ^.  You can use that instead of | so that it toggles the bit rather than always setting it:
case 'A' :
    bt_leds_activated ^= 1;
    break;

With ^ if you OR a 0 with a 1 you get a 1. If you OR a 0 with a 0 you get a 0. If you OR a 1 with a 1 you get a 0.
That means every time you send A bit one of bt_leds_activated will invert. If it's 0 it will become 1. If it's 1 it will be come 0.
Also you seem to have two sets of states - the button states, and the bluetooth states. Instead you only want one set of states, and both the buttons and the bluetooth toggle bits in that single state set.
Because of that if either of the methods of turning an LED on has turned the LED on then the other method will have no chance at all of turning the LED off.
So just drop bt_leds_activated completely and use ledstates:
case 'A':
    ledstates ^= 1;
    break;

Now both the button and the character through bluetooth will toggle the LED.

No any that change for project state after edit code. the wrong still .
hey man, please watch video to understand bug . thanks
https://youtu.be/EcpJeewE1AU

I think your problem is that you have two sets of states, when you really only want one.

What is the solution . Can you edit this bug. I think bug in this if condition

if(bt_leds_activated && millis()-bt_leds_timestamp > 2000){ ledstates &= ~bt_leds_activated; shift_out(ledstates); bt_leds_activated = 0; }

Forget bt_leds_activated completely. Just use ledstates everywhere.

Edit your answer bro, and then explain for me as example

ledstates |= bt_leds_activated; shift_out(ledstates); bt_leds_timestamp = millis();

How about these lines

I think you aren't completely clear in your own mind what you want to achieve. I have no idea what you are trying to do with those lines.

I want delay time when send char after char

I don't know what that means.

Firstly : thank for edit my code now code run perfectly . But this code is clean code or no .and then for example when send character A by Bluetooth in real The sending process requires a time delay between the sent value and the subsequent 2nd value .

Thanks for you man on your answer for may problem


text:
How to get the encoder position while the rotary motor is moving
I have a question with encoder and the rotary motor. When the motor is moving, I can't access the position of the motor.  I have run the code separately, it is perfectly fine. But when I combine, these two codes, the motor is able to move but there was no position data.
Any suggestion on how can I get the motor moving and get the encoder position at the same time.
The combined code I have drafted is there:
  #include <Stepper.h>

    const int stepsPerRevolution = 4000;  // 4000 steps for one circle with 10mm increment.
    const int motorPitchPerCircle = 10;     // 10mm per circle for the linear ball screw guide for motor.

    int val;
    int encoder0PinA = 3; // Pin 15 of the cable.
    int encoder0PinB = 4; // Pin 13 of the cable.
    int encoder0Pos = 0;
    int encoder0PinALast = LOW;
    int n = LOW;

    // initialize the stepper library on pins 8 through 11:
    Stepper myStepper(stepsPerRevolution, 9, 8, A3, A5);

    void setup() {
      // set the speed at 60 rpm:
      myStepper.setSpeed(100);
      // initialize the serial port:
      Serial.begin(9600);

      pinMode (encoder0PinA, INPUT);
      pinMode (encoder0PinB, INPUT);
      Serial.begin (9600);
    }

    void loop() {
      // step one revolution  in one direction:
      myStepper.step(6*stepsPerRevolution);
      delay(2000);

       n = digitalRead(encoder0PinA);
      if ((encoder0PinALast == LOW) && (n == HIGH)) {
        if (digitalRead(encoder0PinB) == LOW) {
          encoder0Pos--;
        } else {
          encoder0Pos++;
        }
        Serial.print (encoder0Pos);
        Serial.print ("/");
      }
      encoder0PinALast = n;

    }

You could use interrupts for the rotary encoder

https://arduino.stackexchange.com/questions/40285/problem-with-tachometer-using-attachinterrupt-and-servo/56874


text:
Sending and receiving data using 433 Mhz from Arduino to Arduino
Following this tutorial: https://tutorials-raspberrypi.com/let-raspberry-pis-communicate-with-each-other-per-433mhz-wireless-signals/ I was able to easily send code from one Raspberry Pi Zero to another using a RF 433 MHz Transmissor, Receiver pair using the Ninjablock's 433Utils library.
Now I'm trying to do the same between two Arduinos UNO. I'm following the explanations of the library itself: https://github.com/ninjablocks/433Utils, but until now without success.

Arduino_Sketches
Place the Sketches in your normal Arduino Sketches location. Install
  any required libraries:
1) Servo motor library (Should be included in the Arduino IDE)
2) Arduino rc_switch library

The Arduino rc_switch library is installed in my Arduino IDE.
What I would like to confirm is the following:
While with the Raspberry Pis I go to the folder 433Utils/RPi_utils and type the command sudo ./RFSniffer in one terminal and sudo ./codesend 1234 in another what I have to do with the Arduinos?
Upload the sketch RF_Sniffer.ino to one Arduino and the sketch Send_Demo.ino to the other and watch in the Serial Monitor the inputs/outputs appearing as magic?
That's unfortunately not working. :-(
May I install anything else? Modules and wiring is OK.

You should try the sanity check demos.  Do note that cheap 433 MHz receivers are notoriously noisy, but maybe you can see a difference in the LED.  You could also try sending from the Arduino to the pi.  Don't assume the wiring is correct until it works.

The transmitter and receiver that I use with the Arduinos are the same I used with success with RPis. By the way I've just sent from RPi (./codesend 1234) to the Arduino (using sketch RF_Sniffer.ino) with success. But not yet from Arduino to RPi. I read the code of Send_Demo.ino but I'm not sure what I should do. Just run the sketch and it will automatically transmit a code? Or similar to ./codesend 1234) should I write something (like 1234) in the Serial Monitor and hit the send button, so the sketch will transmit that way the code that would be catch by the RF_Sniffer?

Sounds like you need to study the code of whatever sketch you are trying.

That's what I'm doing and also asking for help. Maybe I find someone that could help by having experience on that.

The most important thing with making these work with a Uno is to supply enough power.  They simply will refuse to work if only powered by the USB connection.  Recommended to put 9-12 Volts into barrel connector.  How are you powering the Uno?

Hi @SDsolar With the RPis it worked connected also with the 3.3V pin! But now everything works well with the Arduinos too. As I said above I could already send from RPi and receive with the Arduino. Then I changed the send sketch to use with the Arduino and now I'm able to receive in the other Arduino.

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


text:
Do we have to calibrate LDR before using it in a project?
I am doing a project with Arduino, making a synthesizer, in which an LDR is used.
Before connecting the Arduino to a power source and use the project, do I need to calibrate the LDR like it is explained in Arduino website ?

Either pick some values and hopes if works in most cases. Or have the software keep track of the minimum and maximum values, and use that to 'scale' the light input to a normalize range. You could have the user do a "calibration" routine before using it, by putting their hand over the sensor, and removing their hand completely, and thus getting the max and min values.

An LDR is a pretty inaccurate device. It just gives you a number which relates to darkness or brightness. How do those numbers relate to darkness and brightness? Well, only in a very vague way. All you can really say with any confidence is that bigger numbers mean brighter light, and smaller numbers mean darker darkness.
Even after "calibration" the numbers are pretty meaningless in any real-world sense.
All the "calibration" does is give a rough guide to the range of the numbers produced in any given lighting situation. It's then up to you to program your sketch in such a way that it works within the ranges of those numbers.
And yes, those numbers will change depending on the current lighting situation.
You could incorporate some form of "calibration" routine in your sketch to adjust any relevant values and calculations, or you could just provide some interface for tweaking values. Or your system may just really not care. It's impossible to know until you actually start creating your system.

A good example of this is if you want a program that detects when an object is placed over the sensor and blocks the light.  In that case you wouldn't normally want to write the code such that it looks for some particular value that means darkness, because the number you get from a particular level of darkness changes.  So instead of writing code to look for some particular darkness threshold, you would write the code such that you look for large negative changes in the reading.  Maybe anytime it changes by more than a certain amount in some short time consider it covered.

My application was a little different. My illumination/light source was fixed (and exact). I compensated the sensor for temperature. The results I obtained were very exact and repeatable.
Here are my temperature compensation results.