text:
Problems uploading with a new Nano
My first post - I am a relative newbie.
I want to make a smartcontroller for my boat - I have built the electronics and written and tested a sketch for the Nano, all working totally fine. I then decided that I would  like to keep my existing Nano (Nano-A) as a development system and buy another one (Nano-B) to actually deploy. Both of these are cheap chinese clones (from different suppliers).
However I cannot upload anything to Nano-B. It seems to be basically working (LEDs flash) but not wishing to accept any sketch uploads. The COM port seems to be working OK and I have tried all the various options available in the Arduino IDE (boards, programmers etc.) without success.
So I came to the conclusion that possibly the bootloader on Nano-B needs to be re-flashed.
So I setup Nano-A as a programmer, loaded up "ArduinoISP", connected up the ISP pins and hit "burn bootloader".
It seems as if this is "nearly working". I have turned on the -v (verbose) option for avrdude and pasted the log below. It looks to me as if the IDE is invoking avrdude twice; (1) To set the Fuses etc, and (2) to upload the actual bootloader. I seems that (1) is working OK but (2) is failing.
I've been tearing my hair out for about 3 weeks with this and would be really keen to get some ideas.
Thanks in advance.
Arduino "burn bootloader" IDE Log - follows;
Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Nano, ATmega328P"

C:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM8 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xFF:m

avrdude: Version 6.3-20190619

         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/

         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM8

         Using Programmer              : stk500v1

         Overriding Baud Rate          : 19200

         AVR Part                      : ATmega328P

         Chip Erase delay              : 9000 us

         PAGEL                         : PD7

         BS2                           : PC2

         RESET disposition             : dedicated

         RETRY pulse                   : SCK

         serial program mode           : yes

         parallel program mode         : yes

         Timeout                       : 200

         StabDelay                     : 100

         CmdexeDelay                   : 25

         SyncLoops                     : 32

         ByteDelay                     : 0

         PollIndex                     : 3

         PollValue                     : 0x53

         Memory Detail                 :

                                  Block Poll               Page                       Polled

           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack

           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------

           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff

           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff

           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500

         Description     : Atmel STK500 Version 1.x firmware

         Hardware Version: 2

         Firmware Version: 1.18

         Topcard         : Unknown

         Vtarget         : 0.0 V

         Varef           : 0.0 V

         Oscillator      : Off

         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.11s

avrdude: Device signature = 0x1e950f (probably m328p)

avrdude: erasing chip

avrdude: reading input file "0x3F"

avrdude: writing lock (1 bytes):

Writing | ################################################## | 100% 0.04s

avrdude: 1 bytes of lock written

avrdude: verifying lock memory against 0x3F:

avrdude: load data lock data from input file 0x3F:

avrdude: input file 0x3F contains 1 bytes

avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...

avrdude: 1 bytes of lock verified

avrdude: reading input file "0xFD"

avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.04s

avrdude: 1 bytes of efuse written

avrdude: verifying efuse memory against 0xFD:

avrdude: load data efuse data from input file 0xFD:

avrdude: input file 0xFD contains 1 bytes

avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...

avrdude: 1 bytes of efuse verified

avrdude: reading input file "0xDA"

avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.04s

avrdude: 1 bytes of hfuse written

avrdude: verifying hfuse memory against 0xDA:

avrdude: load data hfuse data from input file 0xDA:

avrdude: input file 0xDA contains 1 bytes

avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...

avrdude: 1 bytes of hfuse verified

avrdude: reading input file "0xFF"

avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.04s

avrdude: 1 bytes of lfuse written

avrdude: verifying lfuse memory against 0xFF:

avrdude: load data lfuse data from input file 0xFF:

avrdude: input file 0xFF contains 1 bytes

avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...

avrdude: 1 bytes of lfuse verified

avrdude done.  Thank you.

C:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM8 -b19200 -Uflash:w:C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:i -Ulock:w:0x0F:m

avrdude: Version 6.3-20190619

         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/

         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM8

         Using Programmer              : stk500v1

         Overriding Baud Rate          : 19200

         AVR Part                      : ATmega328P

         Chip Erase delay              : 9000 us

         PAGEL                         : PD7

         BS2                           : PC2

         RESET disposition             : dedicated

         RETRY pulse                   : SCK

         serial program mode           : yes

         parallel program mode         : yes

         Timeout                       : 200

         StabDelay                     : 100

         CmdexeDelay                   : 25

         SyncLoops                     : 32

         ByteDelay                     : 0

         PollIndex                     : 3

         PollValue                     : 0x53

         Memory Detail                 :

                                  Block Poll               Page                       Polled

           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack

           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------

           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff

           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff

           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500

         Description     : Atmel STK500 Version 1.x firmware

         Hardware Version: 2

         Firmware Version: 1.18

         Topcard         : Unknown

         Vtarget         : 0.0 V

         Varef           : 0.0 V

         Oscillator      : Off

         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.11s

avrdude: Device signature = 0x1e950f (probably m328p)

avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed

         To disable this feature, specify the -D option.

avrdude: erasing chip

avrdude: reading input file "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex"

avrdude: writing flash (32768 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_cmd(): programmer is out of sync

avrdude: stk500_cmd(): programmer is out of sync

avrdude: stk500_cmd(): programmer is out of sync

avrdude: 32768 bytes of flash written

avrdude: verifying flash memory against C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:

avrdude: load data flash data from input file C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:

avrdude: input file C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex contains 32768 bytes

avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.00s

avrdude: loadaddr(): (b) protocol error, expect=0x14, resp=0x3f

avrdude: stk500_paged_load(): (a) protocol error, expect=0x14, resp=0x10

avrdude: stk500_cmd(): protocol error

avr_read(): error reading address 0x7e01

    read operation not supported for memory "flash"

avrdude: failed to read all of flash memory, rc=-2

avrdude: stk500_disable(): protocol error, expect=0x14, resp=0xff

avrdude done.  Thank you.

Error while burning bootloader.

Edit ... Connections between the Arduinos. Nano A is the programmer. Nano B is the target

Nano A    Nano B
ISP 1  --     ISP 1 (MISO)
ISP 2  --     ISP 2 (VCC - 5v)
ISP 3  --     ISP 3 (SCK)
ISP 4  --     ISP 4 (MOSI)
ISP 6  --     ISP 6 (GND)
D10    --     ISP 5 (RESET)

I have also now added a 60ohm resistor between RESET and +5V on Nano A
I have also tried connecting a capacitor between RESET and GND. (2uF and 100uF - I didn't have a 10uF) - but it made no difference
Further investigations.
I have tried running avrdude in "terminal" mode and can confirm that I can do all of the usual read/write operations except writing to anywhere in flash memory. This seems to be the only operation that does not work. I will now try breaking down the flash write operation into the individual SPI programming instructions to see if I can work out where it is failing. I suspect that my MCU is a "brick" but I have learned loads!
Another edit;
I have now been using the avrdude terminal mode "send" command to step throuh the individual SPI operations one at a time to write flash memory and hey! it works! (see below)

So, if this works, why does ArduinoISP fail to load the bootloader?
I will set this up as another/new question

What, if anything, did you do with the reset signal on the nano that runs the arduinoisp.ino sketch?

Could you show how you've connected both Nano's?

I have connected the two nanos using the 6 pin ISP headers. as follows;

@RobW: please [edit] your question to add details, don't add them as comments

I have now fixed this problem, but still do not fully understand what the original problem was.
Please see my other post on this qusetion to see what I did
Link to other post

There is more then one bootloader in the Nano's, a new one and the old one. I had the same problem so I simply went to tools in the IDE and switched from the new  to the old, it solved my problems.

Thanks Gil - This is one of the first things that I tried - without success.

Sorry I am out of ideas. I hope somebody can help you.

Perhaps this isn't the answer to the bootloader issue but I went through the same thing recently, I realized a little late about what was exactly the problem, so I checked the uC on the Nano Board and it has an ATMega168 instead of the normal ATMega328p.
So if you are using ArduinoIDE you need to check the ATMega168 option while you are selecting your uC chip (as in the picture above)... Sometimes (as it happened to me, just going for the basics solve all the problems)
Hope this could help you mate

Thanks Cyborg. I had a look at the uC and it is an ATMega328p. Interestingly (perhaps) it is a lot bigger that the uC that is on the other Nano - also a 328p

Yeah mate, this link may help you to learn something new about ATMega328p packages: https://www.eeweb.com/the-different-atmega328-packages/


text:
Is it necessary to set a function with always_inline attribution when the function would work maybe once?
I'm going through a library for the ILI9488 running by SPI and want to copy this library in my version.
In the beginning of the source file, there's a guard for the SPI_HAS_TRANSACTION that if the library would run in Arduino compiler then it would use the SPI functions, otherwise it should run from another platform SPI libraries.
Library link:
jaretburkett / ILI9488
This is the part of code I have questions about:
// If the SPI library has transaction support, these functions
// establish settings and protect from interference from other
// libraries.  Otherwise, they simply do nothing.
#ifdef SPI_HAS_TRANSACTION
static inline void spi_begin(void) __attribute__((always_inline));
static inline void spi_begin(void) {
#if defined (ARDUINO_ARCH_ARC32)
  // max speed!
  SPI.beginTransaction(SPISettings(16000000, MSBFIRST, SPI_MODE0));
#else
    // max speed!
  SPI.beginTransaction(SPISettings(24000000, MSBFIRST, SPI_MODE0));
#endif
}
static inline void spi_end(void) __attribute__((always_inline));
static inline void spi_end(void) {
  SPI.endTransaction();
}
#else
#define spi_begin()
#define spi_end()
#endif

My questions:

why the programmer first declare the function in source file not in header file ?
why to use always_inline attribution for a function that's is most the time used once in program file and it's not likely to be used many times during operating time ?
what does this define means ARDUINO_ARCH_ARC32 and where to find it ? I searched in all files in arduino folders and didn't find it. Is it dedicated for fast boards or the usual 16MHz arduino boards ?

Edit:
I want to add another question for the same library.
This function content:
void ILI9488::spiwrite(uint8_t c) {

  //Serial.print("0x"); Serial.print(c, HEX); Serial.print(", ");

  if (hwSPI) {
#if defined (__AVR__)
  #ifndef SPI_HAS_TRANSACTION
    uint8_t backupSPCR = SPCR;
    SPCR = mySPCR;
  #endif
    SPDR = c;
    while(!(SPSR & _BV(SPIF)));
  #ifndef SPI_HAS_TRANSACTION
    SPCR = backupSPCR;
  #endif
#else
    SPI.transfer(c);
#endif
  } else {
#if defined(ESP8266) || defined (ARDUINO_ARCH_ARC32)
    for(uint8_t bit = 0x80; bit; bit >>= 1) {
      if(c & bit) {
    digitalWrite(_mosi, HIGH);
      } else {
    digitalWrite(_mosi, LOW);
      }
      digitalWrite(_sclk, HIGH);
      digitalWrite(_sclk, LOW);
    }
#else
    // Fast SPI bitbang swiped from LPD8806 library
    for(uint8_t bit = 0x80; bit; bit >>= 1) {
      if(c & bit) {
    //digitalWrite(_mosi, HIGH);
    *mosiport |=  mosipinmask;
      } else {
    //digitalWrite(_mosi, LOW);
    *mosiport &= ~mosipinmask;
      }
      //digitalWrite(_sclk, HIGH);
      *clkport |=  clkpinmask;
      //digitalWrite(_sclk, LOW);
      *clkport &= ~clkpinmask;
    }
#endif
  }
}

what I understood from this is that the programmer wants the library to be more versatile to support AVR chips programmer by another IDE than Arduino, also supports ESP8266 and anything else should be handled by softSPI, actually pretty smart coding I guess.
My question here, is does #if defined (__AVR__) checks for either AVR/Arduino in general and when specifies SPI_HAS_TRANSACTION means Arduino SPI library specifically ? right ?

why the programmer first declare the function in source file not in header file ?

the declarion is for the inline attribute. the function should be used only in this cpp.

why to use always_inline attribution for a function that's is most the time used once in program file and it's not likely to be used many
times during operating time ?

there are 14 occurrences of transaction start and it is called before every SPI communication commands set in the library. see my answer about beginTransaction

what does this define means ARDUINO_ARCH_ARC32 and where to find it ? I searched in all files in arduino folders and didn't find it. Is it
dedicated for fast boards or the usual 16MHz arduino boards ?

the architecture define is generated by the builder from selected board's boards package folder name. ARC32 architecture is the Intel Arduino 101 boards package.
EDIT (answer to edited part of the question):

My question here, is does #if defined (__AVR__) checks for either
AVR/Arduino in general and when specifies SPI_HAS_TRANSACTION means
Arduino SPI library specifically ? right ?

__AVR__ is defined in avrlibc, the toolchain for AVR microcontrolers. Arduino uses avrlibc for AVR MCUs. It is not recommended to check __AVR__. The AVR family of MCU is now large with different peripherals so checking __AVR__ should be really restricted to CPU matters.
Every Arduino 'architecture' has its own SPI library. The transactions support was added later so not all implementations of the SPI library support transactions. To declare transactions availability in SPI library Arduino defined the SPI_HAS_TRANSACTION define.

Thank you for the links ! Really helpful. But I have a question, where the defines are located ? Also what speeds are related to ? like ARC32 has 16MHz so which other chips have 24MHz ?

other SPI libraries use max SPI speed of the architecture if higher is requested. the architecture (and board) defines are specified as -D option on compiler command line created by the arduino builder based on platform.txt entries as -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch}

first where to find platform.txt ? second, I understood that the defines are saved in platform.txt file and passed with -D option during compilation, so the compiler put things together in linker stage, right ?

I want to add another question in the main post, hope you check it.

I enhanced the answer. platform.txt is in boards package folder as it is installed by Arduino IDE (please don't ask a follow up question for this. it is a different topic).  you can read the Arduino platform documentation here https://arduino.github.io/arduino-cli/platform-specification/

thanks for the support

The function is only used in the library, and not part of the "API" of that library. Kind of like a private function.

Both functions are both being called 14 times inside the source code of this library. But in the larger scheme of things, it doesn't add a lot. But why not add it and maybe save a few bytes, and a few clock cycles.

The ARDUINO_ARCH_ARC32 is for the Arduino 101 board (Intel Curie processor).

I'm replying to your answer points.

Yes, the programmer defined a guard with two functions; static inline void spi_begin(void) and static inline void spi_end(void) which include a call for SPI library.

How to save few bytes with inline ? I learned that it saves clock cycles but not space.

So actually, I don't have to use ARDUINO_ARCH_ARC32 when I'm using nano or uno boards ? right ?

It's been more than two months. I don't remember what this is about.

It's about the use of SPI begin function that is used in a library and put in inline mode.

I don't have time to dive into you question again, at the moment. So I'm not able to answer your followup. Sorry.

Thank you so much for your kind reply, you're right, it's been a lot of time for anyone other than me to remember what this topic is about, I'm sorry for my unbalanced follow-up question, I really should open a new thread.

Here I am only addressing question number 2. The others have already
complete answers.
The choice to whether a function should be inlined or not is a
speed/size trade-off. There is a cost to calling a function. On AVR, for
example, the call instruction takes 4 CPU cycles, and ret takes
another 4. Inlining the function removes this cost. On the other hand,
you end up with as many copies of the function as places where it is
inlined, and this in turn costs flash memory.
The compiler is usually smart enough to make wise decision regarding
function inlining. In this case, it is not obvious what decision it
would make on its own. On the one hand, the function is used multiple
times in the code, which makes a good case against inlining it. On the
other hand, the body of the function is tiny: only setting up some
registers (the two parameters of SPIClass::beginTransaction(),
including the implicit this) and jumping to another function,
so the cost of inlining is small.
For this library, the programmer happened to have a strong opinion on
this matter, and he though inlining was really the best option. Also, he
did not thrust the compiler to make the good decision. This is the
reason why he used the gcc extension:
__attribute__((always_inline))

And no, it is not necessary, it is just an optimization choice.

Thank you so much for your answer, after some time; just now, I opened this thread and read your answer with more deep attention, and got your answer understood at a very good level. I learned that if I didn't use __attribute__((always_inline)) then the compiler would decide if the function is inlined or not. That's an important information I learned about inlining. Also, the inlined function should be small enough not to take a lot of flash space, big functions should be called normally.

source: Stack Exchange

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

sort: votes


text:
Can't upload code to Arduino board on Mac
I'm using a MacBook Pro with 10.13.6, an Official Arduino Uno Board and Arduino 1.8.13 IDE.
I'm having troubles uploading code to the Arduino Board.
I have 5 ports available:

dev/cu.-AvnetaSPPPort
dev/cu.Bluetooth-Incoming-Port
dev/cu.SRS-BTX300-DataInteract
dev/cu.RS-XB41-BluetoothSeria-1
dev/cu.UEMEGABOOM-LWACP-2

I'm not sure if any oh these ports is the correct one but I've already tried all of them and I keep getting errors like: "avrdude: ser_open(): can't open device "/dev/cu.-AvneraSPPPort": Resource busy"
Some weeks ago I was trying Arduino on the same computer and all went good but right now I can't get it to work, however I don't remember wich port was selected.
In the IDE the board I have selected is "Arduino Uno" and as Programmer option I have "AVRISP mkll".
Does anyone know how to solve this?

@timemage the board is an official UNO

@timemage done!

From what little I can tell, on a Mac it should show up with usbmodem in the name.  For my part unless you want me to "it's not on that list" as an answer, you're going to have to add some extra detail.  What exactly I'm not sure.  I guess whatever you can say about what if anything appears in the mac device manager and what your usb connection from the mac to the uno usb port looks like.

which sketch did you load last time it worked? ... that sketch runs when you plug the UNO into a USB port and may be interfering somehow

There's not much the sketch can do, short of activating some external circuitry that causes the board to brown out, that will drop an UNO off USB.

@timemage the OP may have modified the ATmega16u2

I finally solved the problem.
Although the Board has no information about being a clone (it only says "Uno" and was provided by the faculty so I think it is official), I was looking on the web for similar problems and found out that installing CH340 Driver was working for a lot of users.
So that was what I did and now it works like a charm.

List the ports again, with- and without the Arduino plugged in: open the built-in Terminal app (usually in Applications/Utilities) and type 'ls /dev/tty.*'. The difference will tell you the Arduino's device name.
"Resource Busy" generally means something else has already connected to that port.  Is a terminal-emulator program running and connected to that port? If you're using a terminal-emulator other than the one built in to the IDE, you have tell it to disconnect before you can upload to the Arduino.

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


text:
Standard deviation and variance of an array of numbers
Looking for a simple way to get the variance of an array of numbers,
that will compile with the Arduino compiler.
Something like this c#:
static float variance(double []a, int n)
{
    // Compute mean (average of elements)
    double sum = 0;

    for (int i = 0; i < n; i++) sum += a[i];
    double mean = (double)sum / (double)n;
    // Compute sum squared differences with mean.
    double sqDiff = 0;
    for (int i = 0; i < n; i++)
        sqDiff += (a[i] - mean) * (a[i] - mean);
    return (float)sqDiff / n;
}

// Driver Code
public static void Main ()
{
    double []arr = {10, 11, 12, 13};
    int n = arr.Length;
    Console.WriteLine( "Variance: " + variance(arr, n));
}

To keep it simple, and thanks for all your help....
it is a platform with actuators in each corner to raise and lower
the platform....
Each actuator sends a feed back via modbus to the main micro processor at its request
Which is stored to a array, which is processed and then sent via modbus
Back to control (simple on/off) each actuator to keep platform in somewhat of a level position +/- a set number....
I already use the min/max  (max – min =  ) in the my code to limit a set, simple differential between the
Actuators....  I am thinking that using the variance differential would work better for the application....
Thinking it would also detect a jammed or faulty actuator faster than the max/min difference with
Less platform twisting....
(Response to Edgar), You could look at it as XYZ,…  X= position.. Y= actuator.. Z=sample rate
This is my code snip it for the max/min
example 1  —  adj_str =  actuators position = (10,11,10,9) run level flag 1
example 2  —  adj_str =  actuators position = (10,14,10,9) run level flag 0
void min_max()
{
    int max = adj_str[0];
    int min = adj_str[0];
    for (int i = 0; i <= 3; i++)
    {
        const int value = adj_str[i];
        if (value > max) max = value ;
        if (value < min) min = value ;
    }
    //-
    adj_str_dif = max - min;
    //-
    if (adj_str_dif < 1) level_flag = 1;
    //-
    if ((level_flag == 1)&&(adj_str_dif > 4))  // 4 = the differential
    { level_flag = 0;}
    //-
    if (level_flag == 0)           // Level Till Max or Min (re-level)
    {
        // -- Lower --
        if (adj_str_dif > 0 && (digitalRead(but_pin[1]) == LOW))
            base = (max);
        // -- Raise --
        if (adj_str_dif > 0 && (digitalRead(but_pin[2]) == LOW))
            base = (min);
    }
    //-
    if (level_flag == 1)       // Run Till full retract or full extend
    {
        // -- Lower --
        if (adj_str_dif < 1 && (digitalRead(but_pin[1]) == LOW))
            base = 1023;
        // -- Raise --
        if (adj_str_dif < 1 && (digitalRead(but_pin[2]) == LOW))
            base = 0;
    }
}

general programming question ... not an arduino related question ... off topic here ... please post at https://stackoverflow.com/questions instead

Your example code takes an array of doubles; do you really want to take your input from a string? From a single string containing all of the data? Perhaps comma separated? Perhaps with white-space permitted but ignored (only between values, not within any), .... So your question, not only not Arduino-specific, is also not sufficiently specified to be able to answer it. Assuming I guessed right, you'd need to read the string, collect each value, convert it to double, and stash it in an array to be passed as 'a' to your function 'variance()'.

the example code is from https://www.geeksforgeeks.org/program-for-variance-and-standard-deviation-of-an-array/

JRoberts..... the example code is from                                 [link] https://www.geeksforgeeks.org/program-for-variance-and-standard-deviation-of-an-array/)  ..... i was hoping to change this a bit to run some tests on the Arduino IDE.... i  already have a string setup that contains multiple ADC readings, and if i am correct in my assumption i can use the variance result to flag an execution.. i do like the bell curve it creates and thinking it may work for my project

This looks very much like an XY Problem. You seem to be asking the wrong question, for several reasons: 1. If your data comes from the Arduino's ADC, converting the numbers to a string, only to convert them back to numbers, is both useless and incredibly wasteful. 2. This algorithm for the variance requires you to read the array twice. Not the method you want to use on a microcontroller. You want to do it in a single pass, as you read the ADC, so you do not have to ever store the measurements. Please, tell us what you actually want to achieve.

Eric, where you write string you meant array?

@Juraj: As evidenced by his example code (mostly the type adj_str), he indeed means “array of numbers”. I edited the question to avoid confusion.

Please note that calculating an average by adding all the numbers and dividing by count is not a good method when using floating point arithmetic. To then use that average in variance calculations risks bigger errors. The online algorithm performs much better as well as being memory friendly. The numerical stability and correctness of the algorithm starts mattering a lot of you using calculations to control external devices.

I miss a description of your problem regarding "doesn't compile with the Arduino compiler" (Besides c# to arduino c++ changes)

The ( int adj_str [4]; )  is updated every polling of the slave's, to clarify... i have been treating this as the entire dataset for that point in time of travel.... i will cheek out further the Welford's online algorithm, may work better than the standard deviation variance that was posted and like the single pass ! ..... i may seem a bit Dyslexia but i like the term ambidextrous....have not had a chance yet to test Juraj updated version

C++ and C# (or Java) basic language constructs are very similar. Here is the Arduino version of your C# code with minimal required modifications. There is no change in the function implementation.

float variance(double a[], int n)
{
    // Compute mean (average of elements)
    double sum = 0;

    for (int i = 0; i < n; i++) sum += a[i];
    double mean = (double)sum / (double)n;
    // Compute sum squared differences with mean.
    double sqDiff = 0;
    for (int i = 0; i < n; i++)
        sqDiff += (a[i] - mean) * (a[i] - mean);
    return (float)sqDiff / n;
}

void setup() {
    Serial.begin(115200);
    double arr[] = {10, 11, 12, 13};
    int n = sizeof(arr) / sizeof(double);
    Serial.print( "Variance: ");
    Serial.println(variance(arr, n));
}

void loop() {

}

Thanks ... will try running this later tonite

Works as posted


text:
Sketch skipping the OPEN Arduino inputs
Folks,
I am a beginner to Arduino. I have a sketch that tests a set of INPUTS for HIGH or LOW by using a 'for' loop. When the for loop reaches an INPUT which is kept OPEN (no wires connected to it), the for loop apparently 'skips' that INPUT and move on to the next. However, if I have +5V connected to any INPUTS within the range of the for loop, it works correctly. Any thoughts what's is happening here?

probably bad programming ... the arduino will do exactly what you tell it to do, so you are giving it incorrect instructions

You can edit your code into the question if you want to try for a more a specific answer.

You should always connect something to an input to pull it high or low when no signal is present.  The simplest thing is to activate the built-in pullup resistor, which will result in the input returning HIGH when there is nothing connected.  If that's not compatible with your particular use, add a resistor from the input to ground (10k-100k is fine) so that it will return LOW when nothing else is connected.  If the input is just floating, it is susceptible to noise causing random state changes. The input impedance is very high (100 Meg) so it can pick up static and other mischief.

Thanks a lot. I'll avoid floating inputs.


text:
How do I know when a filter coffee machine is finished by using any sensor?
I have a filter coffee machine that looks like this one and I would like to send a message to the machine users by using any development board (like Arduino or NodeMcu) when the machine is finished.
I haven't found a way to detect when the machine is finished. (I also don't want to do any physical change on the machine, like adding any cable or opening in the machine. I can use any sensor or so on.)
How can I do that? Any advice?

Maybe a capacitive level sensor at the side of the pot? That might work. Or maybe a reflective light sensor on the pot (LED plus phototransistor, which senses the change in reflected light, when the coffee reaches a specific level)

measure the power consumption

Ultrasonic: measure the height of the water. Will be hard to fix inside the machine and probably hard to get a water proof version.

Easiest and cheapest: measure the maximum time it takes to make coffee and then use a timer. The coffee will be kept warm anyways, so just come back after x minutes.

weight sensor under the cup? are there some LEDs to indicate status?

(Just a note...) This was done many, many years ago: Trojan Room coffee pot -- However, a camera might be a bit exaggerated.

The normal method is by temperature. When you heat the water you can never get above 100C as the water boiling takes the extra energy away in the phase change to steam. But once all the water has been removed from the heating tank the heater can get higher that 100C. So when that happens the heater shuts off as it's got no more water to heat up.  Basic physics.  So monitor the temperature of the heater then allow a certain amount of extra time for the last bit to filter (determined by experimentation).

Just two ideas, both non-invasive:
The machine moves water from the reservoir at the back to the coffeepot at the front of the machine, so its weight distribution will change while making coffee.
If you put a thin pressure pad (like this one, or something similar) under the whole machine at the back you should see the pressure at that point become smaller while coffee is being made.
If the effect isn't pronounced enough, you could make the whole machine tilt forward while making coffee by putting a narrow and thin strip of plastic under its centre from left to right so it can swivel forward and back just a little depending on the location of the bulk of the water.
If the pressure on the pressure pad at the back stops dropping, the coffee is ready. You can also detect when the coffee can is empty again this way, or maybe even how many cups of coffee are still available in the coffee can.
Or maybe you could detect with a contact microphone when the machine goes silent, assuming it makes sufficient noise when making coffee. Mine does.

I'd use two load cells instead of those pressure pads. But other than that, this is a nice solution.

Added benefit it that it can notify you when there is less that a cup of coffee left in the pot, and thuse requiring a refill.

Even easier would be to only measure the entire weight of the machine. A sudden increase of weight, indicates it's just filled up. Start a timer for, say, 2 minutes, plus 1 minute for every 100ml (i.e. 100gr). You'd have to do some test runs to measure the amount of time needed for different amounts of water. (You could even make it help you measuring out the right amount of ground coffee.)

If the machine has a Brewing- or a Done Brewing LED, a light sensor can detect this without no changes or connections to the machine. This would also have the advantage of working for a short or full pot.


text:
Is it possible to program an atmega32 via internet or remotely with Android app?
There is a board with atmega32 microcontroller, sim card and Bluetooth modules. I used to program this microcontroller using a serial port cable. As long as the circuit is able to connect to internet, is it possible to program atmega32 via internet remotely?

if you can use a SD bootloader and SD card, it could download the update binary to SD card and reset. but it is very possible that you don't have enough memory left for the SD library

@Juraj Could you please explain it a bit more, if you had the same experience?

I enhanced the Arduino OTA library for SAMD to support classic ATmega Arduinos with at least 64 kB of flash. there are two ways: storing the uploaded update in upper half of the flash or on SD card. with less then 64 kB of flash there is no space for networking library + flash space or networking library + SD library. but maybe you can fit it with download over cellular network or bluetooth. https://github.com/jandrassy/ArduinoOTA/blob/master/examples/Advanced/OTASketchDownload_SD/OTASketchDownload_SD.ino


text:
How to power board plus module with one battery pack
I'm someone who's very new to robotics and the physical side of computers (software guy) so apologies if this is a stupid question. I'm purchasing an Arduino Nano 33 IoT that I'll be using in conjunction with an Adafruit FONA 3G Cellular Breakout (https://www.adafruit.com/product/2687). I'd like to be able to power the entire unit off of one battery pack but my problem is that both the Arduino and the Adafruit 3G unit have separate power inputs. Adafruit's website says that a Lipoly battery is required to run the unit. Is there any way to "pass through" or "split" power between the two units? This way I was thinking I could run everything off of one external battery pack. Optimally I don't have to use a Lipoly battery and I could use a large external battery pack connected to jumpers or a barrel jack.

https://learn.adafruit.com/adafruit-fona-3g-cellular-gps-breakout/arduino-wiring

Note that the SIM4320 has a supply voltage range: 3.4~ 4.2V. So you can't just use any odd battery pack. It also, at times, uses a lot of power, so your battery has to be able to provide these short bursts of current.

you can use a breadboard and jumper cable. connect the VCC and GND of battery to a breadboard, do this for your Arduino and sim card module too. just remember they should be in a one row. GND with GND row, and VCC with VCC row
note: this way is okay just for debugging


text:
Some code only works when USB serial port connected
I'm using Arduino Uno as my microcontroller, but I got a strange behavior. I need to run several function at the same time. One to get GPS and temperature value then send every value to user's phone number when a request received by SIM800L GSM module, and another to display those value on I2C LCD. Everything works fine when my USB port connected to my computer. But when I tried to unplug the USB and using external power source from Li-Po battery I can't get a response from SIM800L module whenever I send a request message.
When I tried to create a separate program (just received a request message and then sent a response by SIM800L) it works fine even though using external power supply (Li-Po battery) without USB port plugged in. Another strange behavior is when I was using both of Li-Po battery and USB port connected then unplugged the USB port it works fine again. But when I unplugged my battery and then plugged it again without USB port connected, SIM800L couldn't send a response. What is wrong ?
This is my full code:

#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include <LiquidCrystal_I2C.h>
#include <SoftwareSerial.h>
#include "DHT.h"

//sms
char ReceivedSms;
short DHT_OK=-1, GPS_OK=-1;
String DataSms;
int _timeout;
String _buffer;
String number = "+62811XXXXXX";

//dht
#define DHTPIN 5
#define DHTTYPE DHT11

LiquidCrystal_I2C lcd(0x27,20,4);
SoftwareSerial sim800l(2,3);
DHT dht(DHTPIN, DHTTYPE);

// The TinyGPS++ object
TinyGPSPlus gps;

void setup()
{
  Serial.begin(9600);
  sim800l.begin(9600);
  dht.begin();
  lcd.init();                      // initialize the lcd
  // Print a message to the LCD.
  lcd.backlight();
  _buffer.reserve(50);
  ReceiveMode();
}

void loop()
{
   displayInfo();

}

void displayInfo()
{
  String RSMS;

  while(sim800l.available() > 0) {
      ReceivedSms = sim800l.read();
      RSMS.concat(ReceivedSms);
      GPS_OK = RSMS.indexOf("All");
   }

  if (gps.location.isValid())
  {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Latitude  : ");
    lcd.println(gps.location.lat(), 6);
    lcd.setCursor(0,1);
    lcd.print("Longitude : ");
    lcd.println(gps.location.lng(), 6);
    delay(5000);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Suhu       : ");
    lcd.println(dht.readTemperature());
    lcd.setCursor(0,1);
    lcd.print("Kelembaban : ");
    lcd.println(dht.readHumidity());
    delay(2000);

    if(GPS_OK!=-1)
        {
        String link = "http://www.google.com/maps/place/" + String(gps.location.lat(),6) + "," + String(gps.location.lng(),6);
        DataSms = "ALL\nSuhu = "+String(dht.readTemperature(),1)+" C"+" \nKelembaban ="+String(dht.readHumidity(),1)+" %"+" \nMaps = "+link;
        SendMessage();
        ReceiveMode();
        GPS_OK = -1;
        }
  }
  else
  {

    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("GPS not found");
    delay(2000);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Suhu      :");
    lcd.println(dht.readTemperature());
    lcd.setCursor(0,1);
    lcd.print("Kelembaban:");
    lcd.println(dht.readHumidity());
    delay(2000);

    if(GPS_OK!=-1)
       {
        DataSms = "ALL\nSuhu = "+String(dht.readTemperature(),1)+" C"+" \nKelembaban ="+String(dht.readHumidity(),1)+" %"+" \nMaps = Lokasi Tidak Ditemukan";
        SendMessage();
        ReceiveMode();
        GPS_OK = -1;
       }
  }

}

String _readSerial() {
  _timeout = 0;
  while  (!sim800l.available() && _timeout < 12000  )
  {
    delay(13);
    _timeout++;
  }
  if (sim800l.available()) {
    return sim800l.readString();
  }
}

void ReceiveMode() {
  sim800l.println("AT");
  delay(100);
  sim800l.println("AT+CMGF=1");
  delay(100);
  sim800l.println("AT+CNMI=2,2,0,0,0");
  delay(100);
}

void SendMessage()
{
  //Serial.println ("Sending Message");
  sim800l.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);
  //Serial.println ("Set SMS Number");
  sim800l.println("AT+CMGS=\"" + number + "\"\r"); //Mobile phone number to send message
  delay(1000);
  String SMS = "Hello from 800L...";
  sim800l.println(DataSms);
  delay(100);
  sim800l.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  _buffer = _readSerial();
}

Just for your information I'm using Li-Po battery 7.4V 2200mAh

I suspect that you have power supply issues when you are not connected to the USB.  Using your voltmeter, please measure the Uno's supply voltage when not connected to USB.  Also check the supply voltage for the SIM800 when disconnected.

You never call gps.encode(...) - and anyway, where is your GPS connected? I see no SoftwareSerial for it (which by the way can only listen on ONE interface at a time).

It sounds like but I am only guessing you have a grounding problem. Be sure all the grounds are connected together.  I assume you are connecting the lipo battery to Vin and not the 5V pin. The battery voltage swings to much for stable operation. Be sure to follow jwh20's suggestions and you should be operational.

@Majenko I'm using digital pin 0 and 1 for my GPS.. that's work fine although I have to disconnected GPS VCC pin first during uploading my program

@Gil I'm connecting the Li-Po battery to my 5v stepdown then I'm connecting the output of this stepdown to 5v Arduino pin, is this okay to directly connecting 7.4V Li-Po battery to 5v Arduino pin?

Here I attach my simple schematic wiring of how do I power up my Arduino and another part: https://github.com/Proxcentaur/track-gps-sim/blob/main/wiring.PNG

@Majenko I have tried using 2 software serial in Arduino Uno but it doesn't work. Then I have decided to use digital pin 0 and 1

@jwh20 I have measured it, Uno supply voltage when not connected to USB and just connected to battery is 8.04V

Pins 0 and 1 conflict with the usb serial. You can't j use both.

I have solved my problem by click on Arduino reset button pin after all of my components got a power supply. Somehow I can't explain why does it work after doing that simple thing

Good to hear! It always helps to feed them good electrons:-)


text:
DC motor fan speed control with Temperature Sensor
I used this circuit schematic for the project however, when DC Motor starts to work, temperature value is increasing abnormally high. How can I solve this problem? It shows abnormal high values like 70, 85 ,101 etc.

#define TEMPERATURE A0
#define fan 3
void setup(){
Serial.begin(9600);
pinMode(fan, OUTPUT);
}

void loop(){
float temp = analogRead(TEMPERATURE);    //Read the analog pin
temp = temp * 0.48828125;   // convert output (mv) to readable celcius

Serial.print(temp);
//print the temperature status
Serial.print('\n');
delay(1000);

 if (temp<=24){
  analogWrite(fan, 51);

  delay(1000);

}
else if (temp<=26 && temp>24){
  analogWrite(fan,122);

  delay(1000);

}
 else if (temp<=30 && temp>26){
  analogWrite(fan,223);

  delay(1000);

}
else if (temp>30){
  analogWrite(fan,255);

  delay(2000);

}
}

Hello Raul, please edit your original question instead of asking a new one. Duplicate: DC Motor fan control with Temperature sensor

I think the problem lies in the fact, that you did not calibrate the sensor. You just take the analog reading and multiply it with 0.48828125. Where did you get this value from? And what kind of sensor do you use. The schematic shows a sensor with 3 pins. Is it perhaps a digital sensor like the 18B20? You can not use the analog port to read a digitial sensor.

I am assuming that whatever temperature you are measuring is not rising when the motor is on.
I see that you are sharing the power/ground between your temperature sensor IC and the motor.  Motors are extremely noisy from an electrical viewpoint and it's almost certainly causing your temperature sensor to malfunction.
It would be best to separate the temp sensor power/ground connections from the motor power/ground connections completely.  Power the motor from an external supply instead of sourcing it from the Arduino.
Another thing that might help is to add some bypass capacitors as close as possible to the motor and to the temperature IC across the Vcc and GND lines.  This will help to smooth out the power in spite of the noise that the motor itself generates.  Generally you want at least one of two types, an electrolytic capacitor and a ceramic capacitor.  These are both inexpensive if you don't already have some on hand.  I'll suggest a 10 uF electrolytic and a 0.1 uF ceramic capacitor near both the motor and the temp sensor.

Besides all the good advice from jwh20, you should start with a general strategy to find out where the problem lies.  You should hang a DVM directly between the sensor output and ground and see if the voltage also shows the rising problem.  If not, the trouble is in your code.
A drifting value is often due a wiring issue, like a bad sensor ground.  It wouldn't hurt to go over all the wiring very carefully.


text:
Arduino serial issue
My arduino mega should be communicating with another card (ANET8) and also with a DC resistance meter (with python code) using 2 serial ports, one using the USB(resistance meter) and the other one with RX and TX.
The Anet8 is sending a signal to trigger the MeasGo part in the code, and therefore with the Serial.print(A8flag) it triggers a measurment part in python, that measurement part in python sends in the Serial port a command that the arduino should read through Serial.readString and thus execute a function called "MuxRelayChoicee".
My problem is that, the part with " if Serial.available()>0 ... " is not working. I know it because my debug_pin1 is not made to HIGH.
Did i miss something ?
#include "pins.h"

#include <SoftwareSerial.h>

String flag, A8flag, sys;
int i;
int POW_RELAY_PIN=12;
int debug_pin = 38;
int debug_pin1 = 39;
SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // set the digital pin as output:
  pinMode(10, INPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);

  pinMode(debug_pin, OUTPUT);
  pinMode(debug_pin1, OUTPUT);

  Set_Pins(); //to activate mux pins

    // Open serial communications and wait for port to open:
  Serial.begin(9600);
//  Serial.setTimeout(500);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  mySerial.begin(9600);
//  mySerial.setTimeout(500);
  while (!mySerial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
}

void loop() {

  if (mySerial.available()>0)
  {
     delay(50);
     String A8flag ="";
     A8flag=mySerial.readString();
     delay(50);

 if(A8flag.equals("MeasGO\n")){
     Serial.print(A8flag);
     delay(100);
     Serial.flush();
     digitalWrite(debug_pin, HIGH);

     if (Serial.available()>0)
     {

        String sys ="";
        sys=Serial.readString();
        delay(50);
        digitalWrite(debug_pin1, HIGH);
        MuxRelayChoice(sys);
 }
 }

Here is a part of the code i send with python :
if flag=="MeasGO":
      for n in range(4):
        ser.write(("sys"+str(n)+"\n").encode()) #Writing to the Serial port of Arduino
        time.sleep(1)
        data=mybk.query('FETCh?')
        time.sleep(1)
        t.append(time.time()-t0)
        print("sys"+str(n)+ '\n')
        res[n]=float(data[:13])*1000
        print(str(res[n])+'\t mOhm')
      with open(path+'csvfile.csv','a') as f:
          f.write(str(time.time()-t0)[:7]+'\t'+str(res[0])+'\t'+str(res[1])+'\t'+str(res[2])+'\t'+str(res[3])+'\n') #Give your csv text here.
      time.sleep(0.5)
      ser.write("MeasOK\n".encode())

Why are you using software serial, the Mega has 4 serial ports that work very nicely. Also to my knowledge the Softwareserial can only service 1 operating software serial channel at a time.

It seems likely that this code can be edited down to show the same problem using the Serial Monitor rather than python for send data and making no reference to AVET8 or MeaGo, whatever those are.  If the problem is principally about everything leading up to enter a conditional statement the first time, the body of the conditional statement is unimportant to the problem. If you don't find the problem yourself in this process, you'll have code that most anyone here can test themselves.

If you're unable to completely remove the python code from the troubleshooting process (you likely can), you may be able to at least shorten it and remove all of the unnecessary dependencies yielding complete and short python source that can be run by anyone wanting to help you with your arduino code.

This has nothing to do with anything, but SoftwareSerial::begin() sets the correct pin modes for the RX and TX pin numbers given in the constructor.  You needn't call pinMode for them yourself.  Ignoring the constructor bit, the same is true for your available HardwareSerial objects.  That can be removed from the code.


text:
I2C protocol doesn't work properly
I am trying to make I2C Communication between NodeMCU and arduino Uno boards. However it is not working properly. It makes communication for once time when i uploaded code.
Master Device Code(NodeMCU 1.0)
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <Wire.h>

HTTPClient client;

StaticJsonDocument <200> doc;

const char* ssid = "MY_SSID";
const char* pass = "MY_PASSWORD";

void setup() {
  Serial.begin(9600);
  Wire.begin(D1,D2);
  WiFi.begin(ssid,pass);
  while(WiFi.status() != WL_CONNECTED) {;}
}

void loop() {

  const char* cd = getCode();
  if(cd==nullptr) {
    Serial.println("Problem Occurred.");
    delay(10000);
    return;
  }
  //Bad code is starting...
  //Basically, sending 24 bytes of data for a Wire Transmission

  int n = strlen(cd);
  int rem = n%24; //remainder
  int quo = (n-rem)/24; //quotient

  while(quo!=0) {
    char sel[24];

    for(int i =0;i<24;i++) {
      sel[i] = cd[((((n-rem)/24)-quo)*24)+i];
    }

    Wire.beginTransmission(8);
    Wire.write(sel);
    Wire.endTransmission();
    quo-=1;
  }

  char sel[rem];

  for(int i =0;i<rem;i++) {
    sel[i] = cd[n-rem+i];
  }

  if(rem>0) {
     Wire.beginTransmission(8);
     Wire.write(sel);
     Wire.endTransmission();
  }
  //Bad code finished!

  //this is also not working.
  Wire.requestFrom(8,3);

  while(Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }

  delay(15000);
}

//get code from server.
const char* getCode() {
  client.begin("http://...");

  int res = client.GET();

  if(res<0) {
    return 0;
  }

  String root = client.getString();
  deserializeJson(doc,root);
  const char* code = doc["Liste"][0]["code"];
  return code;
}

Slave Device Code(Arduino Uno)
#include <Wire.h>

void setup() {
  Serial.begin(9600);
  Wire.begin(8);
  Wire.onReceive(received);
  Wire.onRequest(requested);
}

void loop() {delay(200);}

void received(int bytes) {

  while (Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }

}

void requested() {
  Wire.write("abc");
}

Circuit:
D1-SDA
D2-SCL
GND-GND

To which voltage 3.3V or 5V do you pull up the SCL and SDA line? Is the MCU a 3.3V  controller? Just connecting D1-SDA D2-SCL is not enough. If the electrical setup is OK, you could remove all the Wifi and JSON code from the MCU prog and try I2S alone. Another strange thing: you call client.begin("http://..."); each time you call the getCode() method without client.end(). Perhaps this crashes the connection to the server. I don't know if the client.begin is safely callable twice without calling close before..

You may need to do some additional research. I'm debugging some I2C problems myself at the moment. Happy to share what my research has turned up:
Guiding Ideas - What could break?

Physical Layer

Unintentionally switched connections (SDA<>SCL)
Incorrect Pins selected on Microcontroller
Pull-up Resistors

Too many

Devices often have pull-ups installed by default. Only one set is needed per bus. Rule of parallel resistors applies to calculate effective resistance.

Too big (too high resistance)
Too small (too low resistance)

Voltage Conversion / Mismatched  devices
Spikes or noise on SDA, SCL or Vcc
Parasitic Capacitance

wire / trace design
bus too long

Protocol Layer

Bus Addresses incorrect / collisions
No ACK received from slave  (ref. TI article "Troubleshooting I2C Bus Protocol" below)

Timing
Missing / Unexpected SCL pulses
Incomplete 8 bit block
Missing Bytes
False slave address
Unsuccessful address change

NACK signal meaning ambiguity
Clock speed mismatch (should be running at the speed of the slowest slave on the bus)
Blocked bus (i.e., a device has reset or dropped during transmission putting the bus into an invalid state. There is no timeout.)
Multimastering (too many masters on bus?) - if more than one all must support multi-master mode
Clock stretching (a slave is holding the clock low)
What part of the message is missing? Is the initial ACK from the slave received?

Code Layer

For boards with multiple I2C ports, correctly passing the desired port to the relevant library.
Use of interrupts causing timing problems
Use of blocking code structures causing timing problems

Testing Methods

Bus Pinging / Bus Scan (like Arduino Multi-speed scanner https://forum.arduino.cc/index.php?topic=197360)
Connect additional devices to the bus and see which combinations work to identify the failing item
Multimeter checks

Stable Vcc?
Common Ground?
(Open Drain) pull-up resistance from SDA & SCL to Vcc

Test devices like Bus Pirate
Oscilloscope Analysis / Decode (references below)
Sifting out which device is causing the problem. (See Hackaday article) Put different-value resistors on the output of all chips on the bus. The low voltage values will be slightly different for each chip, allowing you to see on a scope which chip is talking at any given time, and diagnose when they’re talking over each other.
install I2C multiplexor to seperate bus into a single connector for each device (i.e., from bus to star topology) (e.g., PCA9544A)

References
I2C General

For Arduino Programming Arduino Next Steps - Going Further with
Sketches Chapter 7
For ESP32
https://randomnerdtutorials.com/esp32-i2c-communication-arduino-ide/

I2C Debug Advice

I2C Primer (I2C-bus.org) - a good reference for everything discussed here https://www.i2c-bus.org/i2c-primer/

Common Problems https://www.i2c-bus.org/i2c-primer/common-problems/
Obscure Problems https://www.i2c-bus.org/i2c-primer/obscure-problems/ Analysing Obscure Problems https://www.i2c-bus.org/i2c-primer/analysing-obscure-problems/

WHAT COULD GO WRONG? I2C EDITION (Hackaday) https://hackaday.com/2016/07/19/what-could-go-wrong-i2c-edition/
How to design and debug a custom I2C master-slave system? (Stack Exchange) How to design and debug a custom I2C master-slave system?
Troubleshooting I2C Bus Protocol  https://www.ti.com/lit/an/scaa106/scaa106.pdf

Oscilloscope Analysis of I2C

How to debug I2C through waveform analysis (Texas Instruments) https://www.ti.com/lit/an/slyt770/slyt770.pdf
Using an oscilloscope to debug the I2C protocol https://www.electronicproducts.com/using-an-oscilloscope-to-debug-the-i2c-protocol/

I will get reference this answer for my future projects. I found solution but unfortunately can't remember, however i guess it was related with code layer.

A few of my tips:

if Arduino is powered using VIN port, the battery must STRICTLY between 7 to 12 volts, otherwise the Arduino board is unstable. Serial communication typically require good board stability
A capacitor (100 to 500uF) across the 5V (or 3.3V) and GND port helps to give I2C device a consistent voltage level, which is essential


text:
Sync issue with signals

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "digitalWriteFast.h"

#define BUTTONPIN 2
#define FDCSPIN 6
#define CIPIN 5
#define SPEAKERPIN 4

float RPM=1000.0;
int PWus=1.5*1000.0;
int FDCSoffset=(1000.0/RPM/60.0/4.0) - (PWus/1000.0);
int CiCnt;
int totalCnt;
int CIState=B01100000;
bool Buttonstate=0;
LiquidCrystal_I2C lcd(0x27, 20, 4);

void setup()
{
  Serial.begin(9600);
  lcd.begin();
  lcd.backlight();
  lcd.clear();
  lcd.print("READY TO TEST"); // Waiting for button press
  pinMode(BUTTONPIN, INPUT);// Setting button as Input
  pinMode(FDCSPIN, OUTPUT); // Fuel Delivery Control Signal
  pinMode(CIPIN, OUTPUT); // Cylinder Identification
  digitalWriteFast(FDCSPIN, LOW);
  digitalWriteFast(CIPIN, LOW);
}

void loop()
{
 Buttonstate=digitalReadFast(BUTTONPIN);
 if(Buttonstate==1)
 {
  delay(5);
  if(Buttonstate==1)
  {
    runInjectorTest();
  }
 }
}
void runInjectorTest()
{
  lcd.print("Test Run");
  playtesttone();

    for(totalCnt=0;totalCnt<8000;totalCnt++)
    {

      PORTD=CIState;
      delayMicroseconds(FDCSoffset);
      PORTD=PORTD^B01000000;
      delayMicroseconds(PWus);
      if(totalCnt%4==0)
      {
        CIState=CIState^B00100000;
      }
    }
  totalCnt=0;
  playfinishtone();
}
void playtesttone()
{
  tone(SPEAKERPIN, 500, 500);
  delay(700);
  tone(SPEAKERPIN, 500, 500);
  delay(700);
  tone(SPEAKERPIN, 500, 500);
  delay(700);
  tone(SPEAKERPIN, 2000, 500);
}
void playfinishtone()
{

  tone(SPEAKERPIN, 2000, 500);
  delay(700);
  tone(SPEAKERPIN, 2000, 500);
  delay(700);
  tone(SPEAKERPIN, 2000, 500);
  delay(700);
  tone(SPEAKERPIN, 500, 500);

}

I am using this code to generate 2 signals, called CI and FDCS. CI stays on until the 5th FDCS pulse. I checked the output which is connected to a driver using the scope and I got this.
The rising edge and falling edge of the longer signal (CI, dark green) are supposed to sync with the rising edge of the FDCS signal (Lime green),but they are inline with the falling edge. Note that the output is inverted (when compared to the code) hence the signal generated by the Arduino pins is according to the code.

so, what is your question?

@jsotola Why is the signal not turning on at the exact same time? according to the code, I am writing the PORTD register at the same time for both pin 6 and 5, so they should sync up right?

which code line writes both bits to PORTD?

@jsotola PORTD=CIState, under runInjectortest(), in the for loop. CIState=B01100000

If the output is inverted, and you turn the higher frequent signal on it is displayed on the scope as a falling edge. (because it is inverted: rising edge becomes a falling edge.) You got what you programmed. ;-)

@PeterPaulKiefer Oh god thanks, now are there any way to change the code to work on the falling edge?

You change both signals separately with a delay between. I added an answer to show you my idea.

I did not tried it out. But something like this might help to synchronize the inverted signals to the rising edge of the high frequent signal.
I removed the FDCSoffset delay, because it is negative according to the variables at the top.
// initialize CIState with 00
int CIState=B00000000;

// lines not shown .....

for( totalCnt=0; totalCnt<8000; totalCnt++ )
{
  CIState=CIState^B01000000;
  if(totalCnt%4==0)
  {
    CIState=CIState^B00100000;
  }
  // both signals are set at the same time
  PORTD=CIState;
  delayMicroseconds(PWus);
}


text:
GET/POST request via AT Commands
I am trying to send a simple GET/POST request to a dummy end point on https://requestbin.com/. I am using an ESP8266 module. I am using the arduino serial monitor to send these AT commands. I connect to wifi and then use the following AT commands
AT+CIPSTART="TCP","54.166.71.140 ",443  (the IP address from requestbin)

I then do
AT+CIPSEND=80

followed by
GET / HTTP/1.0\r\nHost: fc35001f8ec49962d182320446070d.m.pipedream.net\r\n\r\n

I get the output as follows
Recv 80 bytes

SEND OK

+IPD,272:HTTP/1.1 400 Bad Request
Server: awselb/2.0
Date: Mon, 07 Dec 2020 13:28:01 GMT
Content-Type: text/html
Content-Length: 122
Connection: close

<title>400 Bad Request</title>

400 Bad Request

CLOSED

Is there problem with the length of CIPSEND or the format of the request itself.

the \r\n are send as \r\n, not as new line characters

how should the At command look like in that case ?

send first GET / HTTP/1.0, then Host: fc35001f8ec49962d182320446070d.m.pipedream.net and then an empty line. do it fast before the connection times out

what would be the value for CIPSEND in this case ?

the count should include the new line charcaters. \r as 1 and \n as 1 character

Is there an easier way to calculate how long the AT+CIPSEND value should be ? i still get bad request.

bad request is a response from the server, so it can connect and receive the response. that is a good test. now write the code

Let us continue this discussion in chat.


text:
Interfacing unusual 4 digits 7 segments display
There is a common anode and common cathode of 7 segments display. But I got an unusual one.
There are 7 pins controlling 4 digits 7 segments.

I find the pinout by a multimeter. Basically, each pin can be anode or cathode.

My questions:

What is the exact name of this 7 segments display?
How to drive this display by Arduino, any website/sample code?
If I am using the 5V tolerant board, which resistor I need to use? And how is the schematic?

It appears to be some sort of proprietary 7-segment display, possibly from a clock or clock radio.  I doubt you are going to find any Arduino library that supports this directly and you may be better off just getting a standard display that can work with existing libraries.  Otherwise you will certainly learn a lot by figuring out how to make this one work and writing your own library.  As far as resistors, it's difficult to say since we don't know what's inside the thing.  Start with something conservative, say 1K, and work down from there.

Looks like a Charlieplexed matrix. You may try a Web search for “Arduino Charlieplexing”.

This display seems to have 32 addressable LEDs controlled by only
7 pins. Judging from this fact, and from the provided pinout table, it
looks like a Charlieplexed matrix.
A typical way to drive this kind of matrix is by looping over the
cathodes. You pull one cathode pin LOW, and then pull HIGH all the
anodes of the LEDs you want to shine which are connected to this
particular cathode. Wait a few milliseconds, then move to the next
cathode. It is important that all pins that are not involved in lighting
an LED remain in INPUT mode.
For example, let's say you want to light all the segments of the first
digit (display an “8”) while keeping everything else off. You first pull
pin 1 LOW (first cathode) and pull HIGH pins 2–5 (segments F, G, C
and D). Let that shine for a few milliseconds, then put everything to
high impedance (pins to INPUT) and move to the next cathode: pin 2
goes LOW and pin 1 (segment A) goes HIGH. And so on until you have
done all the cathodes.
For the coding part, I would suggest using a 7×7 matrix of booleans
telling whether a particular segment is meant to be lit. The indices of
the array would be row = cathode number and column = anode number. The
array would have the same structure as the pinout table you posted,
except for the fact that the lines and columns would have indices
ranging 0–6 instead of 1–7. This should make it easy to handle
refreshing the display.
Drawing the digits is a bit trickier than with traditional 7-segment
displays, as for each segment you will have to find its coordinates in
the matrix (cathode number and anode number). For this, I would use a
“mapping matrix” that stores the mapping (digit number, segment number)
→ (cathode number, anode number).
Below is a tentative, and untested, implementation of these strategies.
Note that I did not write a function to output a digit, but that should
be easy to implement on top of the set_segment() function defined
here. Besides, the question of how to draw a digit once you know how to
control individual segments is the standard 7-segment problem, for which
you should be able to find many tutorials.
Note that this code assumes you drive the display directly, using no
iterface other than current-limiting resistors. This carries the risk of
either overloading the cathode outputs or having the display be too dim,
depending on the current-limiting resistors. You may want to use
transistors for the cathodes, in which case you would have a set of
cathode pins different from the set of anode pins.
// Arduino pins connected to the display.
const uint8_t display_pins[7] = {2, 3, 4, 5, 6, 7, 8};

// Which segments are lit. Each segment is located in this matrix at
// the coordinates [cathode][anode].
bool segment_lit[7][7];

// Coordinates in the matrix above where a segment can be found.
struct SegmentCoordinates {
    uint8_t cathode;
    uint8_t anode;
};

// segments[digit][segment] gives the coordinates of
// any segment (0 = A) of any digit (0 = 1st digit).
const SegmentCoordinates segments[4][7] = {
// seg: A      B        C       D      E        F       G
    {{1, 0}, {2, 0}, {0, 3}, {0, 4}, {3, 0}, {0, 1}, {0, 2}},
    {{2, 1}, {3, 1}, {1, 4}, {5, 1}, {4, 1}, {1, 2}, {1, 3}},
    {{3, 4}, {4, 2}, {4, 3}, {0, 5}, {2, 5}, {2, 3}, {2, 4}},
    {{5, 6}, {6, 5}, {5, 4}, {3, 5}, {5, 3}, {4, 5}, {6, 4}}
};

// Turn a segment OFF (lit = false) or ON (lit = true).
void set_segment(uint8_t digit, uint8_t segment, bool lit) {
    SegmentCoordinates coordinates = segments[digit][segment];
    segment_lit[coordinates.cathode][coordinates.anode] = lit;
}

void setup(){}

void loop() {
    static uint8_t cathode;  // currently used cathode

    // Set the current cathode to OUTPUT LOW.
    digitalWrite(display_pins[cathode], LOW);
    pinMode(display_pins[cathode], OUTPUT);

    // Set the relevant anodes to OUTPUT HIGH.
    for (int anode = 0; anode < 7; anode++) {
        if (segment_lit[cathode][anode]) {
            digitalWrite(display_pins[anode], HIGH);
            pinMode(display_pins[anode], OUTPUT);
        }
    }

    // Let that shine for a while.
    delay(10);

    // Turn off everything.
    for (int pin = 0; pin < 7; pin++) {
        pinMode(display_pins[pin], INPUT);
    }

    // Move to the next cathode.
    if (++cathode >= 7) cathode = 0;
}

I used delay() here for simplicity. In production code you would
handdle the timings with millis() in a non-blocking fashion, in the
spirit of the “Blink without delay” tutorial.

Thanks, it works. I just modify the delay(10) to delay(1), and add the set_segment() into setup()

I don't know. If I had to talk about it, I would say a LED segment display with a matrix layout with a complementary drive.

If a pin is used as a cathode, a LOW signal must be applied. If it is used as an anode, a HIGH signal must be applied.

You could define constants for each segments anode and cathode that define a pin number. e.g :
#define CAT_1A = 2
#define AN_1A  = 1

and so on. Then if you whant to show segment 1A set CAT_1A to LOW and AN_1A to HIGH.
Of course the whole process is more complicated. You have to define which segments must be light up to show a specific digit. You must show all four digits one by one in a fast loop and so on. But that's the same as you would do for an ordinary LED segment bar. The difference is that you have to configure pin pairs and not single pins.

Use your Multimeter to measure the Forward voltage of the segments. If they are red, it should be around 1.8 to 2.4 Volts. Substract this Voltage from 5 Volts. Then devide by 0.02 (20 mA) and you get the Resistor in Ohms. A standard LED is bright enough with about 20 mA.

Example:
(5V - 1.8V) / 0.02A) = 160 Ohm

Use a resistor of say 100 Ohms at each pin. It is common available and as the current flows always through 2 pins, you have 200 Ohms together.
It is also possible that the LED bar has internal resistors. Try to meassure the resistance beetween to pins.
Edit
When I said, "each digit must be shown in a fast loop", I forgot to clearify that, for each digit, the segments must be switched sequentially.
You can do it even more complicated and show all Segments with a common cathode or a common annode at once.   Then you need fewer cycles, but as you use resistors for all pins (see point 3.) this could dim the LEDs remarkably. Also, becaus technically, the forward voltage of different LED may differ, so the some could be brighter the others.
There is also another thing, I did not think of, when I wrote the answer. If you power a segment, say from pin A (+5V) to pin B (GND), you have a resistor (100 Ohms), an LED (minus 1.8 Volts) and a second resitor (100 Ohms) in series. So in an ideal situation the voltage on pin B (also on the second resitor) would by around 1.6 Volts. Pin B is the cathode of the LED segment, but can also be the anode of another segment (S2).  If the cathode of S2 is connected to GND there is a very small chance, that the segment lights up. If you don't see (ghost) lights, all is fine. But if some segments light up (but much darker than the right ones) you have to find a better solution.

Re “You must schow all four digits one by one in a fast loop”: That won't work. At any given time, you can only light segments that all share either the same anode or the same cathode. So, instead of looping over the digits, you will have to loop over the anodes (or over the cathodes).

@EdgarBonet Showing Digit one by one is meant in addition to show each segment one by one. It seams that I did not express myself clearly. I'll edit the answer.

Re “show all Segments with a common cathode [...] could dim the LEDs remarkably”: no more than showing the segments one by one. If you want a brighter display, you have to drive the cathodes with transistors. Re “If the cathode of S2 is connected to GND there is a very small chance, that the segment lights up”: that's why that cathode should not be pulled LOW (connected to GND): it should be left floating (INPUT mode, a.k.a. “high impedance”).

@EdgarBonnet As multiple LEDs with a common cathode or a common anode have a single source or drain with a resistor. The current through all LEDs together is the same as the current through that single resistor. So each LED sees only a part of the current. Say you have 5 LEDs with a common cathode then the current through the common resistor is 5V / (100Ohm+20Ohm) ~~ 41mA. The current through each LED is 1/5 of this ~ 8,3 mA. I think you would see the difference. Using high impedance state for unused pins is one of the better solutions I mentioned.

You are right, of course, the display will be dim. But that's not my point. My point is that it will also be dim if you handle the segments one by one. Think duty cycle, and average the brightness over a full scan cycle.

@EdgarBonnet That's a good point. I did not expect the LED to dim much because of the duty cycle, but now I'm not sure anymore. I'll have to get such a LED Display and try it. Thank you for the comment.

You answered my last question, and give me an idea for the resistor, but I have no idea how to implement your code.


text:
Nextion won't update text using data passed in Arduino Uno serial print
Q: Is it possible to send data in variables from Arduino to Nextion through SerialPrint? If so, what is the correct syntax?
I have an Arduino Uno connected to a Nextion NX4024T032 and a Sunfounder RC522, with a USB run from my PC into the Uno. I want the Nextion to show the name associated with an RFID card from simple if/then statements in the .ino file.
I created what I thought was a simple set of .ino and .tft files to test the Nextion updating from data sent from the Arduino by serial print. I have confirmed in Serial Monitor on the PC that the RFID reader is functioning and that the Uno is sending out the information I am asking it to print. But the Nextion is not changing text to match what I am trying to send it. It just displays the value entered for .txt in the HMI editor.
I am trying to do this without nextion libraries.
Pinout for the RC522 is as in the .ino below (9-13); plus GND and 3.3V on the Uno.
Pinout for the Nextion is Nextion TX to Uno 1, Nextion RX to Uno 0, plus GND and 5V on the Uno.
Here's the .ino:
/*
 *-----------------------------------------------------
 * Aggiunti pin per arduino Mega
 * add pin configuration for arduino mega
 * http://mac86project.altervista.org/
 ---------------------------------------------------Nicola Coppola
 * Pin layout should be as follows:
 * Signal     Pin              Pin               Pin
 *            Arduino Uno      Arduino Mega      MFRC522 board
 * ------------------------------------------------------------
 * Reset      9                5                 RST
 * SPI SS     10               53                SDA
 * SPI MOSI   11               51                MOSI
 * SPI MISO   12               50                MISO
 * SPI SCK    13               52                SCK
 */

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

#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

void setup() {
    Serial.begin(9600); // Initialize serial communications with the PC
    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init(); // Init MFRC522 card
    Serial.println("Scan PICC to see UID and type...");
}

void loop() {

//condensed to remove RFID code
  if (UID_string == "4294935680")
  {
    Serial.println("va0.txt=\"Maia\"");
  }

  if (UID_string == "31615")
  {
    Serial.println("va0.txt=\"Claire\"");
  }

  if (UID_string == "24498")
  {
    Serial.println("va0.txt=\"Jack\"");
  }
}

The .tft I loaded to the Nextion using an SD card is just a text box (t0) on page0, a timer event and a value. The timer should update t0.txt on the display to equal most recent va0.txt in the serial print every 400 ms.

UPDATE:
While trying to understand syntax for commands to send from Arduino Uno to Nextion, I came across directions for sending data a character at a time. So, a very new version below, with all RFID parts removed.
 * Pin layout should be as follows:
 * Signal     Pin              Pin               Pin
 *            Arduino Uno      Arduino Mega      MFRC522 board
 * ------------------------------------------------------------
 * Reset      9                5                 RST
 * SPI SS     10               53                SDA
 * SPI MOSI   11               51                MOSI
 * SPI MISO   12               50                MISO
 * SPI SCK    13               52                SCK
 */

#include <SPI.h>
#include <SoftwareSerial.h>
#define SS_PIN 10
#define RST_PIN 9
SoftwareSerial mySerial(0,1);

void setup() {
    Serial.begin(9600); // Initialize serial communications with the PC
    SPI.begin();            // Init SPI bus

  while (!Serial) { // wait for serial port to connect. Needed for native USB port only
    ;
  }

  Serial.println("Serial On"); //Print this messages when the serial port is connected
  mySerial.begin(9600); // set the data rate for the SoftwareSerial port

}

//NOTE:Credit to RamjetX : http://forum.arduino.cc/index.php?topic=89143.0

void writeString(String stringData) { // Used to serially push out a String with Serial.write()

  for (int i = 0; i < stringData.length(); i++)
  {
    mySerial.write(stringData[i]);   // Push each char 1 by 1 on each loop pass
  }

  mySerial.write(0xff); //We need to write the 3 ending bits to the Nextion as well
  mySerial.write(0xff); //it will tell the Nextion that this is the end of what we want to send.
  mySerial.write(0xff);

} // end writeString function

void loop() {
  String sendThis = "";
  sendThis = "t0.txt=\"working\""; //Declare and initialise the string we will send

  delay(300); //

  writeString(sendThis); // Use a function to write the message character by character to the Nextion because
  mySerial.write(sendThis) gives you an error due to a datatype mismatch*/
}

Conclusion: The SerialPrintln() statements still send text to the serial monitor, but mySerial.write does not show in the serial monitor and the Nextion screen still does not update to show "working" as passed in t0.txt .

I have condensed the RFID code and added explicit questions at the top of the post. Please clarify what 'fixed text' would look like?

Thank you for the direction and replies. I am pretty sure I want to use variables if possible, because later I want to use the Nextion to show multiple buttons showing text strings coming from a MySQL cloud-based db. My understanding is that Nextion is useful for storing much of what will be displayed on screen (.e.g, graphics), and so my plan is to send variables to Nextion and change only the .txt values of the buttons. At the moment, I am simply trying to get started with Arduino directing Nextion at all, while keeping in mind the pins that will be used by the RFID module.

I see your point - well said. I will take another run at it and post an update. Thanks again.

use software serial for the Nextion ... see software serial example sketch that passes input from serial monitor to the device ... type the Nextion comnands into serial monitor

read the instruction set info at the Nextion website ... you missed something

I've tried to send data a character at a time (see new code below UPDATE) but Nextion is still not updating.

you cannot use pins 0 and 1 for software serial ... those are hardware serial ... use the software serial example at the arduino website


text:
Unable to control fan with IR circuit despite capturing and reproducing the IR transmissions
I'm trying to use an Arduino to control my Bionaire window fan. I followed several guides to build an IR receiver circuit to record the patterns sent by the remote for its five buttons . From there, I've tried both an IR transmitter circuit with IRSendRaw and a separate Raspberry Pi circuit using an IR transceiver hat and LIRC , but the fan does not seem to pick up either. I've verified that the Pi receiver recognizes the commands from the Arduino transmitter circuit just as it does from the fan's actual remote and vice-versa, but even if I put the fan directly against the IR LED, it does not respond to any of the commands from the circuit.
What else might I need to do to make this work properly? As an alternative, what would be the best way to go about directly activating the 'buttons' on the remote circuit board pictured above?
Thanks in advance for your help
For future refernece, these are the signals I recorded for the remote, which match up with this post on electronics stackexchange.
power: 4E87E0AB
1300 -400 1300 -350 450 -1200 1300 -400 1300 -350 1300 -400 450 -1200 500 -1200 450 -1200 1300 -400 1300 -350 450
temp_up: 4EA240AE
1300 -400 1300 -350 450 -1200 1300 -400 1300 -350 1300 -400 450 -1200 450 -1250 450 -1200 450 -1250 1300 -350 1300
temp_down: 1D2FEFF6
1300 -400 1300 -350 450 -1250 1300 -350 1300 -350 500 -1200 1300 -350 500 -1200 450 -1200 500 -1200 450 -1200 450
mode: 39D41DC6
1300 -350 1300 -400 450 -1200 1300 -350 1300 -400 450 -1200 500 -1200 1300 -350 500 -1200 450 -1200 450 -1250 450
air_flow: E0984BB6
1300 -400 1300 -350 500 -1200 1300 -350 1300 -400 450 -1200 450 -1250 450 -1200 1300 -350 500 -1200 450 -1200 500

This is the sketch I'm trying to use to transmit data (just a modified version of the send raw demo from the library). Note that I also tried with only 23 items in the array (as originally recorded), but that made no difference:
#include <IRremote.h>

IRsend irsend;

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

}

void loop() {
  int khz = 38; // 38kHz carrier frequency for the NEC protocol
  Serial.println("Sending power");
  unsigned int irSignal[] = {1300,350, 1300,350, 500,1200, 1300,350, 1300,400, 1300,350, 450,1250, 450,1200, 450,1200, 1300,400, 1300,350, 500, 1200};
  irsend.sendRaw(irSignal, 24, khz); //Note the approach used to automatically calculate the size of the array.

  delay(1000); //In this example, the signal will be repeated every 5 seconds, approximately.
}

EDIT to show that I seem to be able to replicate the real signal.
In the following output from the IRecvDump2 example, the top two signal dumps are from the real remote and the bottom two are from my RPi sending the recorded signal. They're very slightly different, but seem (to me) to be within the variation of the recording of the true signal anyway.
What else could I be missing? Could there be some brightness threshold such that even holding the Pi directly up to (i.e. touching) the fan receiver wouldn't work? Some other sort of wake-up signal that for whatever reason the Arduino isn't recording/receiving?
Encoding  : UNKNOWN
Code      : 4E87E0AB (32 bits)
Timing[23]:
     +1300, - 400     +1300, - 350     + 450, -1200     +1350, - 350
     +1300, - 350     +1300, - 400     + 450, -1200     + 500, -1200
     + 450, -1200     +1300, - 400     +1250, - 400     + 450
unsigned int  rawData[23] = {1300,400, 1300,350, 450,1200, 1350,350, 1300,350, 1300,400, 450,1200, 500,1200, 450,1200, 1300,400, 1250,400, 450};  // UNKNOWN 4E87E0AB

Encoding  : UNKNOWN
Code      : 4E87E0AB (32 bits)
Timing[23]:
     +1300, - 400     +1300, - 350     + 450, -1250     +1300, - 350
     +1300, - 400     +1300, - 350     + 450, -1200     + 500, -1200
     + 450, -1200     +1300, - 400     +1300, - 350     + 450
unsigned int  rawData[23] = {1300,400, 1300,350, 450,1250, 1300,350, 1300,400, 1300,350, 450,1200, 500,1200, 450,1200, 1300,400, 1300,350, 450};  // UNKNOWN 4E87E0AB

Encoding  : UNKNOWN
Code      : 4E87E0AB (32 bits)
Timing[23]:
     +1350, - 350     +1300, - 350     + 450, -1200     +1300, - 350
     +1300, - 350     +1300, - 400     + 450, -1200     + 450, -1200
     + 450, -1200     +1350, - 350     +1300, - 350     + 450
unsigned int  rawData[23] = {1350,350, 1300,350, 450,1200, 1300,350, 1300,350, 1300,400, 450,1200, 450,1200, 450,1200, 1350,350, 1300,350, 450};  // UNKNOWN 4E87E0AB

Encoding  : UNKNOWN
Code      : 4E87E0AB (32 bits)
Timing[23]:
     +1350, - 300     +1350, - 350     + 450, -1200     +1300, - 350
     +1300, - 350     +1350, - 350     + 450, -1200     + 450, -1200
     + 450, -1200     +1300, - 350     +1350, - 350     + 450
unsigned int  rawData[23] = {1350,300, 1350,350, 450,1200, 1300,350, 1300,350, 1350,350, 450,1200, 450,1200, 450,1200, 1300,350, 1350,350, 450};  // UNKNOWN 4E87E0AB

Those codes look way to short to me. They also don't seem to include a preamble. Could you tell how you got those signals codes?

I got the signals from the IRRecvDump2 example in the Arduino-IRremote library.
I thought the signals looked odd as well, but I found one other post in the EE stack exchange where someone had recorded the same signals.
I am using the IRSendRaw example from the same library to send from the Arduino and lirc's irsend when sending from the Pi

Updated the main post with my sketch @jsotola

there is another thing to try ... if you have access to a learning IR remote ... use it to learn one of the fan remote control buttons and confirm that it can control the fan ... next use it to learn the arduino non-working signal .... then use the arduino to record the learned code .... compare it to the original recorded values

one other thing you could try .... set all the timing values to what the controller IC datasheet shows   ... the two values are 1266 μs and 422 μs   .... the trailing gap should be 6752 μs ... so 1300,350, 1300,350, 500,1200 ... should be 1266, 422, 1266, 422, 422, 1266 ... and the very last 1200 should be 6752

Thanks for the suggestion. I don't have a learning IR remote at the moment, but I can get one at some point.
And ah, I didn't think of that for the last gap. I guess I figured that since it was 'off' that just having no signal afterwards would be sufficient (and why the signal got recorded the way it did).

Your code assumed that C1 and C2 bits are set to 1, but according to the EE stack exchange link, those pins are float, and therefore should be consider as '0' instead of '1' as shown in your irSignal data.

@jsotola Unfortunately, changing the intervals to align exactly with the spec didn't seem to help.

@hcheung I saw that, but if that's what my arduino recorded being sent by the remote, then shouldn't that be what I send to the fan?

is your device actually outputting IR? ... check with your phone camera

Yes. I checked with my camera and, as I said, also tried using one of pi/arduino to transmit and the other to read and both directions recognize the signal.

is there a difference between a signal captured from the remote control and a signal captured from the second arduino?

The IRecvDump2 output is the same when I send the recorded signal from my Raspberry Pi

Interesting question with a lot of paths. I know nothing about your controller but in working with IR remotes in the past I found almost all IR remotes use the infrared frequency range (300 GHz - 400 GHz). This range should not be confused with the modulation rate (carrier frequency) of the remote control. The remote control codes are sent to the receiver using the modulation rate. The modulation rate for the remotes and set top boxes is between 36 kHz and 60 kHz, typically 36 kHz to 39kHz. Try this link it may be a bit redundant but it may help. http://www.pehratek.com/documents/FAQ-Infrared-Light-Control.pdf

I think you meant 300Ghz - 400Ghz.

@Gil There is no link in your answer. Maybe you forgot it

Sorry, I should have clarified: I'm using IRSendRaw example from the Arduino-IRremote library to send, so the 38 KHz modulation should be handled.

Sorry I am not familiar with that example or library.  Sorry Gerben I hit a K instead of a G, thanks, I changed it.

@Gil  gHz is gram hertz   ... it should be GHz