body:
I have a question regarding the use of [SevSegShift][1] library. I followed the example properly and tested it to see if it works. It was able to power up the seven segments and light up the whole LEDs (even the decimal) but it's not showing the output I want to show.

Based on the code below, I want to show the number 500 but it does not. Even tried `sevsegshift.setChars("abcd")`, no change.

This is my code:

    #include <SevSegShift.h>

    #define SHIFT_PIN_SHCP 6
    #define SHIFT_PIN_STCP 5
    #define SHIFT_PIN_DS   4

    SevSegShift sevseg(SHIFT_PIN_DS, SHIFT_PIN_SHCP, SHIFT_PIN_STCP, 1, true);

    void setup() {
      byte numDigits = 4;
      byte digitPins[] = {9, 10, 11, 12}; // These are the PINS of the ** Arduino **
      byte segmentPins[] = {0, 1, 2, 3, 4, 5, 6, 7}; // these are the PINs of the ** Shift register **
      bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
      byte hardwareConfig = COMMON_CATHODE; // See README.md for options
      bool updateWithDelays = false; // Default 'false' is Recommended
      bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
      bool disableDecPoint = true; // Use 'true' if your decimal point doesn't exist or isn't connected

      sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments, updateWithDelays, leadingZeros, disableDecPoint);
      sevseg.setBrightness(10);
    }

    void loop() {
      sevseg.setNumber(500);
      //delay(1000);
      sevseg.refreshDisplay(); // Must run repeatedly; don't use blocking code (ex: delay()) in the loop() function or this won't work right
    }

This is my breadboard schematic down below.

[![Breadboard][2]][2]

(220 ohm resistors on the digit pins and the segment pins are connected to the shift register)

  [1]: https://github.com/bridystone/SevSegShift
  [2]: https://i.stack.imgur.com/ug6Md.png

title: 74HC595 to 4 Digit 7 Segment using SevSegShift Library

Answers: 1

body:
Finally able to fix it with the help of @PeterPaulKiefer, I was able to find the problem. The problem is in the code itself (schematic is alright. No changes there) and this is the updated code.

    #include <SevSegShift.h>

    #define SHIFT_PIN_SHCP 6
    #define SHIFT_PIN_STCP 5
    #define SHIFT_PIN_DS   4

    SevSegShift sevseg(SHIFT_PIN_DS, SHIFT_PIN_SHCP, SHIFT_PIN_STCP, 1, true);

    void setup() {
      byte numDigits = 4;
      byte digitPins[] = {12, 11, 10, 9}; // These are the PINS of the ** Arduino **
      byte segmentPins[] = {0, 1, 2, 3, 4, 5, 6, 7}; // these are the PINs of the ** Shift register **
      bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
      byte hardwareConfig = COMMON_ANODE; // See README.md for options
      bool updateWithDelays = false; // Default 'false' is Recommended
      bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
      bool disableDecPoint = false; // Use 'true' if your decimal point doesn't exist or isn't connected

      sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments, updateWithDelays, leadingZeros, disableDecPoint);
      sevseg.setBrightness(100);
    }

    void loop() {
      sevseg.setNumber(500);
      sevseg.refreshDisplay(); // Must run repeatedly; don't use blocking code (ex: delay()) in the loop() function or this won't work right
    }

**What changed:**

 1. Turns out my 7-segment is `COMMON_ANODE` so I changed my `hardwareConfig`
 2. Set brightness to 100
 (At this point, it shows the number in reverse but with a decimal point in each digit)
 3. Set `disableDecPoint` to `false`
 (At this point, the display is showing but in reverse but no more decimal point)
 [![reverse][1]][1]
 4. To fix this, I set the `digitPins[]` in reverse and it now shows the proper format
 [![Correct Output][2]][2]

Thank you so much Peter for helping me figure out what's wrong!

Also the LED Bar I use is [4-Digit 0.36" LED, 7-segments display, common-anode][3]. (The link is to the shop I got it from)

  [1]: https://i.stack.imgur.com/sAuEM.jpg
  [2]: https://i.stack.imgur.com/Cf6tK.jpg
  [3]: https://store.createlabz.com/products/40-005?_pos=3&_sid=cf5299bd3&_ss=r


body:
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)
[![Windows command interpreter - avrdude session][1]][1]

  [1]: https://i.stack.imgur.com/TGhXX.png

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

title: Problems uploading with a new Nano

Answers: 3

body:
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

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/008ES.jpg

body: 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.

body:
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][1]

  [1]: https://arduino.stackexchange.com/questions/79909/cant-get-burn-bootloader-working-arduino-nano


body:
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][1]

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:
1. why the programmer first declare the function in source file not in header file ?
2. 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 ?
3. 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 ?

  [1]: https://github.com/jaretburkett/ILI9488

title: Is it necessary to set a function with always_inline attribution when the function would work maybe once?

Answers: 3

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

2. 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.

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

body:
> 1. 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.

> 2. 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][1]

> 3. 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][2] 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.

  [1]: https://arduino.stackexchange.com/questions/79728/when-is-spi-begintransaction-required/79737#79737
  [2]: https://arduino.github.io/arduino-cli/library-specification/#working-with-multiple-architectures

body:
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][tail],
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:

```c++
__attribute__((always_inline))
```

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

[tail]: https://en.wikipedia.org/wiki/Tail_call


body:
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?

title: Can't upload code to Arduino board on Mac

Answers: 2

body:
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.

body:
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.


body:
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

```c++
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;
    }
}
```

title: Standard deviation and variance of an array of numbers

Answers: 1

body:
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() {

}
```


body:
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?

title: Sketch skipping the OPEN Arduino inputs

Answers: 1

body: 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.


body:
I have a filter coffee machine that looks like [this one][1] 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?

  [1]: https://www.electrolux.com.tr/kitchen/small-kitchen-appliances/coffee-makers/coffee-maker/ekf5300/

title: How do I know when a filter coffee machine is finished by using any sensor?

Answers: 2

body:
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][1], 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.

  [1]: https://wiki.seeedstudio.com/Grove-Round_Force_Sensor_FSR402/

body: 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.


body: 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?

title: Is it possible to program an atmega32 via internet or remotely with Android app?

Answers: 0


body: 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.

title: How to power board plus module with one battery pack

Answers: 1

body:
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


body:
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

title: Some code only works when USB serial port connected

Answers: 1

body: 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


body:
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.

  [![Schematic][1]][1]

    #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);

    }
    }

  [1]: https://i.stack.imgur.com/bl8RW.png

title: DC motor fan speed control with Temperature Sensor

Answers: 2

body:
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.

body:
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.


body:
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())

title: Arduino serial issue

Answers: 0


body:
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$; //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

title: I2C protocol doesn't work properly

Answers: 2

body:
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?**

1. *Physical Layer*
 1. Unintentionally switched connections (SDA<>SCL)
 2. Incorrect Pins selected on Microcontroller
 3. Pull-up Resistors
  1. 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.
  2. Too big (too high resistance)
  3. Too small (too low resistance)
 4. Voltage Conversion / Mismatched  devices
 5. Spikes or noise on SDA, SCL or Vcc
 6. Parasitic Capacitance
  1. wire / trace design
  2. bus too long

2. *Protocol Layer*
 1. Bus Addresses incorrect / collisions
 2. No ACK received from slave  (ref. TI article "Troubleshooting I2C Bus Protocol" below)
  1. Timing
  2. Missing / Unexpected SCL pulses
  3. Incomplete 8 bit block
  4. Missing Bytes
  5. False slave address
  6. Unsuccessful address change
 3. NACK signal meaning ambiguity
 4. Clock speed mismatch (should be running at the speed of the slowest slave on the bus)
 5. Blocked bus (i.e., a device has reset or dropped during transmission putting the bus into an invalid state. There is no timeout.)
 6. Multimastering (too many masters on bus?) - if more than one all must support multi-master mode
 7. Clock stretching (a slave is holding the clock low)
 8. What part of the message is missing? Is the initial ACK from the slave received?

3. *Code Layer*
 1. For boards with multiple I2C ports, correctly passing the desired port to the relevant library.
 2. Use of interrupts causing timing problems
 3. 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][1]) pull-up resistance from SDA & SCL to Vcc
- Test devices like [Bus Pirate][2]
- 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][3] - 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) https://arduino.stackexchange.com/questions/22898/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/

  [1]: https://forum.digikey.com/t/what-does-open-drain-mean/716
  [2]: http://dangerousprototypes.com/docs/Bus_Pirate
  [3]: https://www.amazon.com.au/Programming-Arduino-Next-Steps-Sketches/dp/0071830251

body:
A few of my tips:

 1. 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
 2. 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


body:
```

#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 signal][1]][1]
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.

  [1]: https://i.stack.imgur.com/TQ9KF.jpg

title: Sync issue with signals

Answers: 1

body:
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);
    }


body:
this is the error code (it is new from the previous time i posted)

i am using the hourly build for this and not the Beta

    avrdude: stk500_recv(): programmer is not responding

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

    avrdude: stk500_recv(): programmer is not responding

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

    avrdude: stk500_recv(): programmer is not responding

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

    avrdude: stk500_recv(): programmer is not responding

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

    avrdude: stk500_recv(): programmer is not responding

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

    avrdude: stk500_recv(): programmer is not responding

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

    avrdude: stk500_recv(): programmer is not responding

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

    avrdude: stk500_recv(): programmer is not responding

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

    avrdude: stk500_recv(): programmer is not responding

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

    avrdude: stk500_recv(): programmer is not responding

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

[![enter image description here][1]][1]

this is the info of the loader and board i am using

  [1]: https://i.stack.imgur.com/TNEqf.png

title: i am not able to figure out the problem due to which i can't upload my sketch to nano

Answers: 2

body: I am just taking a guess as I operate on Linux. I would suggest go to tools menu and see if the correct board is selected. I would venture to guess it is not set for nano. Mine gives me two choices new and old. Try one and if it does not work try the other. Be sure your Baud is set correctly.

body: Another idea - try using Windows Filemanager to navigate down through the folder path shown in the error message and see if the avrdude.conf file exists in the specified place. this probably will not solve your problem but it might help to understand what is happening. Good luck - Bob


body:
I'm making automatic water plant system. I'm using:

Arduino Uno

3.3-6V water pump -https://www.amazon.com/Vipe-Micro-Submersible-Motor-Water/dp/B01N0X3CW4

Capacitive soil moisture sensor - https://www.amazon.com/Gikfun-Capacitive-Corrosion-Resistant-Detection/dp/B07H3P1NRM

I've noticed that when motor turns on sensor readings are much higher. First I thought that the problem is in sensor, but when I measured sensor output in both cases (when motor is on and when motor is off) there was no difference, voltage was the same. Then I measured voltage in analog pin A0 that I used, and I saw there is increase in voltage when pump is on (+0.4V), so my guess is that this voltage is added to  sensor output voltage which is giving me higher values in my serial monitor.

For powering my pump I'm using same circuit as in this example:
https://www.devacron.com/arduino-tip120-control-dc-motor/

Just except potentiometer there is my sensor, powered via 3.3V Arduino pin (its GND is connected to Arduino GND). I also tried connecting all grounds together in one point, didn't help. I powered Arduino with usb and with 9V supply, in both cases same problem. Tried powering pump and Arduino with same and with different power supplies, no luck either.

I should also add that there is no change in AREF and 5V pin when pump is working. 4.97V in both cases.

Does anyone have any idea what can be the problem and how to solve it?

Here is how I wired everything:
https://i.stack.imgur.com/8IDQR.jpg

I also tried with 0.1uF ceramic and 10nF electrolytic capacitors. as suggested, wiring it like this: https://i.stack.imgur.com/fNQnX.jpg
Didn't make much difference, problem is still there.

title: Analog input voltage rises when motor is working

Answers: 1

body:
Try adding some bypass capacitors at the two points I've added arrows to:

[![Bypass Caps][1]][1]

I suggest two in each spot, one a 0.1uF (or similar) ceramic dipped or disc and the other a 1 or 10uF electrolytic.  Keep the polarity in mind for the electrolytic.

Oh, and another thing.  Be sure your motor is not pulling your power supply voltage down.  It's possible your phone charger supply is inadequate to supply the power needs of the motor.  Use a voltmeter across the input to the Arduino and check the voltage when the motor runs.  If it's dropping much below 5V you need a better power supply.  Well, I see now that you are only powering the motor from that 5V supply.  So that's probably not it.

  [1]: https://i.stack.imgur.com/rCsDV.jpg


body:
what is the best way to init wifi communication between two devices without knowing IP of second device, let's say Raspberry Pi and ESP8266?

I want to build simple home automation system for my purpose. There will be Raspberry Pi, as heart of system and ESP8266 as controlled devices. What is best way to get them communicate? I think, the hardest think is how to get their IP address. Then it will be easy to communicate via sockets.

In next text, by RPi I mean Raspberry Pi and program in RPi will be in python (but using call of terminal commands when needed).

My idea is this: On ESP8266 will be running program, which will create WiFi Acces Point at start (on first run in network). Name (SSID) of that AP will be specific (let's say starting with ESP-AUTOMATION prefix), so Raspberry Pi will know, when new ESP device will be turned on (Raspberry Pi will repeatedly search for accesible networks). When new ESP appear, RPi will save own IP to variable and connect to newly searched network (let's say ESP-AUTOMATION-abcd). Then will RPi send to AP (ESP) it's (RPi's) IP address and local network SSID and password. Then it will disconnect, and connect back to local network (and gain it's "old" IP, which it previously saved to variable). Then ESP connect to local network with static IP and after succesfull connect, it will send to RPi it's IP address via socket (because IP addr of RPi it will already known, because RPi have send it when it served as AP). Then RPi will save that IP address. And because IP addresses (of RPi and also ESP) will be configured as static, it shouldn't change over time.

Is this good idea? Or is something of that unreal (I am at beginning of that all)?

PS: I really want completely autonomous system, so for me is not solution something like connect ESP to PC and print it's IP to serial and then it write to RPi...

Thanks for every advice/opinion.

title: What is the best way to init wifi communication between two devices (get IP address)?

Answers: 1

body:
One is a server and the other is a client.
The server do not need to know IP of the client, but the client need to know IP address of the server. See more in [communication between two Arduino][1]

  [1]: https://arduinogetstarted.com/tutorials/communication-between-two-arduino


body:
I’m dabbling in Arduino and having trouble running two sketches on my Arduino UNO simultaneously. The first is about a program that reads temperature and relative humidity and the second is a program that reads barometric pressure. Both programs work independently, but when I try to combine the two, No
help

    this is the code for temperature and relative humidity:

    #include <Adafruit_Sensor.h>
    #include <LiquidCrystal.h>
    #include <DHT.h>
    #include <DHT_U.h>

    //VARIABLES
    //Asignación de los pines digitales
    int SENSOR = 2; //Este es el pin #2
    int RS = 4;
    int E = 5;
    int D4 = 6;
    int D5 = 7;
    int D6 = 8;
    int D7 = 9;
    //Variables de lectura de tempratura y humedad
    int temp;
    int hume;
    //Creación de variables para el sensor y el display
    DHT dht(SENSOR,DHT11);                    //Formato general: DHT <var_name>(PIN, MODELO DEL SENSOR)
    LiquidCrystal lcd(RS, E, D4, D5, D6, D7); // Formato general: LiquidCrystal <var_name>(RS, RW, ENABLE, D0, D1, D2, D3, D4, D5, D6, D7)
    //Variable para salida del abanico
    int motor = 12;

    void setup(){

      //Iniciar el sensor de temp
      dht.begin();
      //Iniciar el LCD
      lcd.begin(16,2); //(tipo 16 columnas, 2 líneas)
      //Setea el Pin 12 como salida
      pinMode(motor,OUTPUT);

    }

    void loop(){ //Este es el buclé principal del programa

      //Lee valores físicos
      hume = dht.readHumidity();
      temp = dht.readTemperature();

      //Limpia el LCD
      lcd.clear(); //esta instrucción coloca el cursor en la pos 0,0 (columna, fila)
      lcd.setCursor(0,0); //(no necesaria porque la linea de arriba ya lo hace)
      //Escribe los valores leídos en el LCD
      lcd.print("TEMPERATURA: ");
      lcd.print(temp);
      lcd.print("C");
      lcd.setCursor(0,1); //esta instrucción coloca el cursor en la pos 0,1 (columna, fila)
      lcd.print("HUMEDAD: ");
      lcd.print(hume);
      lcd.print("%");

      //Activa el motor si la temperatura pasa el valor deseado
      if(temp>=30){ // Compara si la temp ya es 30 grados
        digitalWrite(motor,HIGH); //Si lo es manda un 1 lógico a teavés del pin digital #12
      }
      else{
        digitalWrite(motor,LOW);// sino, manda un 0, lo que apagaría el motor
      }

      delay(2000);//valor en milisengundos para que repita el ciclo

    }

and this is the barometric pressure code:

    #include <Wire.h>
    #include <Adafruit_BMP085.h>

    // Connect VCC of the BMP085 sensor to 3.3V (NOT 5.0V!)
    // Connect GND to Ground
    // Connect SCL to i2c clock - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 5
    // Connect SDA to i2c data - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 4
    // EOC is not used, it signifies an end of conversion
    // XCLR is a reset pin, also not used here

    Adafruit_BMP085 bmp;

    void setup() {
      Serial.begin(9600);
      if (!bmp.begin()) {
     Serial.println("Could not find a valid BMP085 sensor, check wiring!");
     while (1) {}
      }
    }

    void loop() {
        Serial.print("Temperature = ");
        Serial.print(bmp.readTemperature());
        Serial.println(" *C");

        Serial.print("Pressure = ");
        Serial.print(bmp.readPressure());
        Serial.println(" Pa");

        // Calculate altitude assuming 'standard' barometric
        // pressure of 1013.25 millibar = 101325 Pascal
        Serial.print("Altitude = ");
        Serial.print(bmp.readAltitude());
        Serial.println(" meters");

        Serial.print("Pressure at sealevel (calculated) = ");
        Serial.print(bmp.readSealevelPressure());
        Serial.println(" Pa");

      // you can get a more precise measurement of altitude
      // if you know the current sea level pressure which will
      // vary with weather and such. If it is 1015 millibars
      // that is equal to 101500 Pascals.
        Serial.print("Real altitude = ");
        Serial.print(bmp.readAltitude(101500));
        Serial.println(" meters");

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

title: Question: how to join two different codes

Answers: 1

body: You need to write one program using elements from each block of code. There is no way the Arduino will run both programs concurrently, it will only run one or the other.  You can copy and paste them together but unless done correctly it will not work. This is why it is important to understand the code you are using.


body:
I am building a weather station that contains a transmitter and a receiver and the data at the receiver's serial monitor shows either ovf, nan, 0.00 or some crazy number for the outside data (transmitter) so I'm hoping someone can take a quick look at the code and see if I missed something because I am out of ideas

The Receiver consists of an Arduino DUE, NRF24L01 transmitter, and a DHT 22 temp sensor
The Transmitter consists of an Arduino NANO, NRF24L01 transmitter, and a DHT 22 temp sensor

Thank you for any help or advice

```
// Transmitter
#include "DHT.h"
#include <SPI.h>
#include "RF24.h"

#define DHTPIN 4
#define DHTTYPE DHT22

RF24 myRadio (7, 8);
byte addresses[][6] = {"0"};

struct package
{
  float temperature ;
  float humidity ;
};
typedef struct package Package;
Package data;

DHT dht(DHTPIN, DHTTYPE);

void setup()
{
    Serial.begin(9600);
    delay(1000);
    dht.begin();
    myRadio.begin();
    myRadio.setChannel(115);
    myRadio.setPALevel(RF24_PA_MAX);
    myRadio.setDataRate( RF24_250KBPS ) ;
    myRadio.openWritingPipe( addresses[0]);
    delay(1000);
}

void loop()
{
  readSensor();
    myRadio.write(&data, sizeof(data));
  Serial.println(data.humidity);
  Serial.println(data.temperature);
  delay(1000);
}
void readSensor()
{
 data.humidity = dht.readHumidity();
 data.temperature = dht.readTemperature();
}
```

```
// Reciever
#include <SPI.h>
#include "RF24.h"
#include <DHT.h>

#define DHTPIN 53     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino

//Variables
int chk;
float hum;  //Stores humidity value
float temp; //Stores temperature value

RF24 myRadio (51,49); // CE, CSN
struct package
{
  float temperature ;
  float humidity ;
};

byte addresses[][6] = {"0"};

typedef struct package Package;
Package data;

void setup()
{
  Serial.begin(9600);
  dht.begin();
  delay(1000);
  myRadio.begin();
  myRadio.setChannel(115);
  myRadio.setPALevel(RF24_PA_MAX);
  myRadio.setDataRate( RF24_250KBPS ) ;
  myRadio.openReadingPipe(1, addresses[0]);
  myRadio.startListening();
}

void loop()
{

  if ( myRadio.available())
  {
    while (myRadio.available())
    {
    myRadio.read( &data, sizeof(data) );
    }
    Serial.print("Outside Temperature: ");
    Serial.print(data.temperature);
    Serial.print(" C |");
    Serial.print("  Outside Humidity: ");
    Serial.print(data.humidity);
    Serial.println (" %");

  //Read data and store it to variables hum and temp
    hum = dht.readHumidity();
    temp= dht.readTemperature();
    //Print temp and humidity values to serial monitor
    Serial.print("Inside Temperature: ");
    Serial.print(temp);
    Serial.print(" C |");
    Serial.print("Inside Humidity: ");
    Serial.print(hum);
    Serial.println (" %");
    Serial.println("----------------------------------------------------");
    delay(2000); //Delay 2 sec.

  }
}
```

```
Serial Monitor
----------------------------------------------------
Outside Temperature: 0.00 C |  Outside Humidity: nan %
Inside Temperature: 20.50 C |Inside Humidity: 49.70 %
----------------------------------------------------
Outside Temperature: 0.00 C |  Outside Humidity: nan %
Inside Temperature: 20.50 C |Inside Humidity: 49.70 %
----------------------------------------------------
Outside Temperature: ovf C |  Outside Humidity: -8.00 %
Inside Temperature: 20.50 C |Inside Humidity: 49.80 %
----------------------------------------------------
Outside Temperature: 0.00 C |  Outside Humidity: ovf %
Inside Temperature: 20.50 C |Inside Humidity: 49.80
```

title: Weather station project Transmitter not communicating with Receiver

Answers: 0


body:
Im trying to move a servo from one place to another while using the typical `for` loop you find in the servo's library example:

```c++
int lightON = 180;
int lightOFF = 90;

for (pos1 = lightOFF; pos1 <= lightON; pos1 += 1) {
  servo1.write(pos1);
  delay(15);
}

for (pos1 = lightON; pos1 >= lightOFF; pos1 -= 1) {
  servo1.write(pos1);
  delay(15);
}
```

The thing is that while this does work, I want to be able to move the servo a little quicker, but I can't use the `delay()` function because of some connectivity issues with another library (BLYNK).

How could I move the servo from lightOFF to lightON the quickest way possible without using the `delay()` function?

title: How to move a servo quickly and without delay function

Answers: 2

body:
The quickest way possible from `LightON` to `LightOFF` is simply `servo1.write(lightOFF);` without loops or delays, in one go; no need to do it degree by degree. For example:
```c++
int lightON = 180;
int lightOFF = 90;

for (pos1 = lightOFF; pos1 <= lightON; pos1++) {
  servo1.write(pos1);
  delay(15);
}

servo1.write(lightOFF);
```

If you want it to move a few degrees every loop and do other things in the loop while it moves, you can time it with `millis()` instead of `delay()`. The code below should move the servo 5 degrees every 0.5s:

```c++
int moveTime = 500; // Move every 0.5s
unsigned long int startMillis = 0;
int position = lightOFF;
int step = 5; // Move 5 degrees

void loop() {
  if (millis() - startMillis >= moveTime) {
    servo1.write(position);
    if (position <= lightON) {
      position = position + step;
    }
    startMillis = millis();
  }
  // Do other things
}
```

Untested and incomplete, but you get the idea.

body:
The best way is to use [map()][1] function.

    void loop() {
      unsigned long progress = millis() - startMillis;

      int angle = map(progress, 0, MOVING_PEDIOD, lightOFF , lightON);
      servo1.write(angle);
    }

The above code use the [millis()][2] function, therefore you do not need to worry about blocking other code.

Full instruction is available on [How to control speed of servo motor][3]

  [1]: https://arduinogetstarted.com/reference/arduino-map
  [2]: https://arduinogetstarted.com/reference/arduino-millis
  [3]: https://arduinogetstarted.com/faq/how-to-control-speed-of-servo-motor


body:
I have now successfully learned how to control a single 8 bit shift register 74HC595 with Arduino UNO but whenever I tried to connect another one with the first shift resistor via cascading connection just like the image shown below (well I didn't use the 10uf capacitor between positive and negative terminal), the first shift register only outputs as desired but the second shift register, connected to a cascading connection, does not seem to work...

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/3QJJw.jpg

Here is the code.

        int latchPin = 10; // Latch pin of 74HC595 is connected to Digital pin 5
    int clockPin = 11; // Clock pin of 74HC595 is connected to Digital pin 6
    int dataPin = 9; // Data pin of 74HC595 is connected to Digital pin 4

    byte leds = 0;  // Variable to hold the pattern of which LEDs are currently turned on or off

    /*
     * setup() - this function runs once when you turn your Arduino on
     * We initialize the serial connection with the computer
     */
    void setup()
    {
      // Set all the pins of 74HC595 as OUTPUT
      pinMode(latchPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      Serial.begin(9600);
    }

    /*
     * loop() - this function runs over and over again
     */
    void loop()
    {
      leds = 0; // Initially turns all the LEDs off, by giving the variable 'leds' the value 0
      updateShiftRegister();
      delay(500);
      for (int i = 0; i <= 16; i++) // Turn all the LEDs ON one by one.
      {
        bitSet(leds, i);  // Set the bit that controls that LED in the variable 'leds'
        updateShiftRegister();
        delay(500);
      }

     /* The loop above should repeated 16 times as there are 2 shift resistors, each of them containing 8 and we need to lit up all 16 LEDs*/

    }

    /*
     * updateShiftRegister() - This function sets the latchPin to low, then calls the Arduino function 'shiftOut' to shift out contents of variable 'leds' in the shift register before putting the 'latchPin' high again.
     */
    void updateShiftRegister()
    {
       digitalWrite(latchPin, LOW);
       shiftOut(dataPin, clockPin, LSBFIRST, leds);
       digitalWrite(latchPin, HIGH);
    }

so is it my code or wiring problem?

I have read many articles on internet to make myself get it understood but unfortunately, none of the articles satisfied me.

many thanks for giving me a bit of your precious time...

title: Problem connecting 2 74HC595 8 bit shift registers in cascading connection

Answers: 1

body:
I am really very sorry to say that after a long inspection , i have found that

shift register clear (pin 10) pin of the second shift register remained inactivated due to loose connection of power, after fixing it, all shift registers are working very fine.

I do really apologize to all those friends who came to help me, for wasting their time, i am really very sorry for that...

all problems are solved now.


body:
```

  #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 totalCnt;
  int CIState=B00000000;
  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(PWus);
        PORTD=PORTD^B01000000;
        delayMicroseconds(FDCSoffset);
        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 trying to generate 2 signals using the code above and this output is [![enter image description here][1]][1]

From the image, the lime green signal is called FDCS and the other is called CI. Note that the scope shows the inverted form of the signal. I want the falling edge of CI to match with the Falling edge of the 5th FDCS signal (right now rising edge is matching with the falling edge of the CI signal). But the Rising edge of the CI signal should match with the Rising edge of the first FDCS signal (which it's already doing). How do I change my code to do this?

  [1]: https://i.stack.imgur.com/GswSe.jpg

title: Bit Bang signal generation

Answers: 1

body:
If I understand correctly, you signal has a period of 8 FDCS pulses:
4 with CI high and 4 with CI low. Since the rising and falling edges of
CI do not happen at the same place relative to the FDCS pulses, you
should handle these separately.

I suggest something like the following. Note that, as I do not know what
signal(s) your setup inverted, I just try to reproduce what you show on
the scope, with non inversion:

```c++
uint8_t portState = 0;
for (int totalCnt = 0; totalCnt < 16000; totalCnt++)
{
    // On pulse 0, CI rises with FDCS.
    portState |= _BV(FDCSPIN);
    if (totalCnt % 8 == 0)
        portState |= _BV(CIPIN);
    PORTD = portState;

    delayMicroseconds(FDCSoffset);  // pulse width

    // On pulse 4, CI falls with FDCS.
    portState &= ~_BV(FDCSPIN);
    if (totalCnt % 8 == 4)
        portState &= ~_BV(CIPIN);
    PORTD = portState;

    delayMicroseconds(PWus);  // inter-pulse delay
}
```


body:
I am just starting to learn bitwise operands and here is my question. To do this:

    pinMode (13, OUTPUT);
    digitalWrite (13, HIGH);

bitwise I can do like this:

    DDRB |= B00100000;   //set PIN13 as OUTPUT
    PORTB |= B00100000;  //set PIN13 HIGH

but how I can do this:

    analogWrite(9, 200);
I know how to convert DEC numbers to BIN, but how to send this number to PWM PIN? I cannot find any good example in web..
Thank you!

title: Bitwise write to analog PIN

Answers: 1

body:
Note, you haven't specified, which Arduino you are using. I'm assuming a Atmega328p based Arduino (Uno, Nano, Mini) here, though the principle works with every AVR microcontroller, that has this hardware).

With `analogWrite()` are are not sending data bitwise out of a pin. It configures the hardware Timer for setting that pin at a specific frequency and with a specific duty cycle. So `analogWrite()` actives a totally different piece of hardware inside the microcontroller.

To do this without the Arduino function `analogWrite()`, you first need to decide, which way to go:

- You can generate an interrupt through the hardware Timer and then set the wanted pin by software inside the ISR (which gives you free choice of the pin, but also introduces some jitter in the signal)
- or you can let the hardware Timer itself toggle the pin, which does not involve any software for running (that means you can only use one of the 2 pins, that are associated with the corresponding Timer, but you will get a much more stable signal)

There are lots of tutorials on the web on how to do that. A search for "arduino timer register pwm" gave me some promising results, for example [this one][1], where they explain, how to get PWM with the Timer1 registers and a free to choose frequency. (That is a 3 part series, one part for each Timer. Part 1 for Timer 0 is [here][2], though you might want to keep Timer 0 as it is, so that functions like `delay()` and `millis()` still work as normal). There are also many such questions on this site, for example [this one][3].

Another very important source for anything hardware related is the datasheet of the corresponding microcontroller. For the Uno, Nano or Mini that is the Atmega328p, which datasheet can be found on the microchip site [here][4] (or when googling for the microcontroller name)

  [1]: https://www.eprojectszone.com/how-to-modify-the-pwm-frequency-on-the-arduino-part2timer-1-and-phase-correct-pwm-mode/
  [2]: https://www.eprojectszone.com/how-to-modify-the-pwm-frequency-on-the-arduino-part1/
  [3]: https://arduino.stackexchange.com/questions/4494/pwm-generation-using-registers
  [4]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf


body:
I have simple problem with not simple solution.

My workflow is:
 - Read CID from SD card
 - Send CID via Http to clodud
 - Download specific text from cloud
 - Write this text to file in same SD card

All is working except last step. I cannot figure out how to write to file using SDFat lib. I have to use SDFat for reading CID and other low lvl data from card. Im strugling on "open File" step. Have numerous problems with multiple declarations and none of combinations SD.h SDFat.h and FS.h not working for me. Please, help me, how to open file.

    #include <SPI.h>
    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>
    #include "SdFat.h"
    #include "sdios.h"

    SdFat sd;

    ...

    void WriteToFile(String payload) {
      fs::File myFile;

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

      myFile.println(payload);

      myFile.flush();
      myFile.close();
    }

So what is wrong: Using ESP8266 I cannot compile code due to multiple occurence of fs::File and File32.

    C:\...\Arduino\libraries\SdFat\src/SdFat.h:400:16: error: 'typedef class File32 File' conflicts with a previous declaration
     typedef File32 File;
                    ^

Now I rebuild whole code for ESP32 chip. I can compile and upload code. It can read CID send it, read incoming file and ope SD card. But when writing to file I got

    error: Cannot open file
    Check SD format.

I tried several formats, Fat16, Fat32, exFat on several SD cards from 2 to 64Gbs. All of them were unlocked, all of them were formated to 2 partitions (thats what I want) and 1 partition (for testing) withouth difference. I was also tweeking SPI speed When I set more than 16MHz, it fails (Using ESP32 Wroom)

EDIT2: When I first open volume, call chvol() on volume (not sd card) then it works and I can open file and write to it. Wtf?

      if (!volume.begin(sd.card())) {
        Serial.println("Could not find exFat partition.\nMake sure you've formatted the card");
        return;
      }

      volume.chvol();

title: Write file to SD card using SDFat.h and ESP8266

Answers: 0


body:
[My original code for BT Classic][1]

[My Work in Progress BLE Code][2]

I am trying to take all I did in BT Classic and have it working exacly the same in BLE but the Rssi keeps returning 0's in the BLE code and I don't get why, even after I do connect with my iPhone to the Esp32 the Rssi is still read as 0's.

In the BT Classic example everything works perfectly fine, but I am struggling to make my BLE code work.

What the first code does is reading Rssi signal from any device that connects to the Esp32, aproximating a distance based on the values and outputing the resulting Distance and Rssi in a list of pairs form via text that is sent to the other device, continously so that I can use that information to generate a graph and do various things with it.

I tried taking all I did in my BT Code and replicate it in BLE but it's not working at all, with rssi showing as 0 no matter what, and I've also read through the two Gatt Api's and tried replicating the same functions but there were some I didnt find an equivalent for in the BLE GATT Api:

https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/bluetooth/esp_gap_ble.html

If anyone can guide me it'd be great. To make a summary, the first 0bin link represents the BT code I need to follow and the second 0bin link represents the BLE code I need to have it working just like the BT code (have it do the same exact things).

  [1]: https://0bin.net/paste/QTptCta3#8z3gLwP4LjhgVIPqd8DtE9MNHvtXJ+vZ6x6vIWv5+u0
  [2]: https://0bin.net/paste/90Z8nTYJ#aYBZ5NZB2rorubp2Ncsvj8HuQJFnxr8f5oDJJ4bMoBR

title: How can I rewrite my Bluetooth Classic Arduino code into Bluetooth Low Energy Arduino code (and have everything working the same)

Answers: 0


body:
How can I send the string from Slave SPI to Master SPI?

I want to write code in Bare Metal.

The problem which I am facing is I can't make out what will be my blocking function in Master SPI code when receiving data from slave SPI.

As my SPIF bit is cleared in MAster code as soon as I shift out SPDR register from master to receive byte which is coming from the slave.

    #define spi_data_reg SPDR
    //Naster read byte function
        uint8_t MA_SPI0_read_byte()
        {
         spi_port &= ~(1<<SS);
         spi_data_reg = 0;
         while(!(SPSR & (1<<SPIF)));                  //Wait until transmission complete
         return(spi_data_reg);                                 //Return received data
           spi_port |= (1<<SS);
        }

        //Slave send byte function
        void SL_SPI0_send_byte(uint8_t data)
        {
         spi_data_direc=(1<<MISO);   //MISO as OUTPUT
         spi_data_reg = data;
         while(!(SPSR &(1<<SPIF)));
        }

title: SPI between Master arduino and Slave arduino

Answers: 1

body:
Feel free to take a look at my YouTube videos. They are not monetized so I'm not self-promoting. You can even skip the videos and checkout my GitHub repo with the Master and Slave sketches.
https://youtu.be/A9oSX_dwJKQ
https://youtu.be/PSUzhCtNRRQ
https://github.com/linhartr22/Arduino_SPI_Master_Slave_Demo


body:
I'm using `RF24` library to send messages between 2 MCU's : 1) ESP8266 (no Wifi, same code can be compiled to any Arduino board) 2) pro-Micro.

Message is sent in JSON format, while using `ArduinoJSON` library to `serialize` and `deserialize` messages.

Altough entire code works as expected, I get an error in "RFread" function, which `_readmsg` array loses its content after using `deserializeJson`.

 Attached below  relevant **part** of "RFread" function. Explanations in code below. Please notice "Mark [X]" in code and Serial output:

    char _readmsg[32];                                <---- Storing input in this array
        char t2[32];                                  <---- variable to clone value
        radio.read(&_readmsg, sizeof(_readmsg));      <---- getting RF input and store it in `_readmsg`
        strcpy(t2, _readmsg);                         <---- cloning, part of error seeking

        Serial.print("first: ");                      <---- printing initial value stored. OK. marked [A] in Serial output
        Serial.println(_readmsg);
        Serial.print("duplicate: ");                  <---- printing clone. OK. marked [B] in Serial output
        Serial.println(t2);

        if (key != nullptr)                           <--- check if "msg" key was sent in message
        {
          StaticJsonDocument<80> DOC;
          deserializeJson(DOC, _readmsg);             <---- **error beyond this point**
          Serial.print("second: ");
          Serial.println(_readmsg);                   <---- printing wrong value. marked [C] in Serial output

          if (DOC.containsKey(key))
          {
            const char *outmsg = DOC[key];
            if (out != nullptr)
            {
              strcpy(out, outmsg);
              return true;
            }
          }
          else
          {
            Serial.print("third: ");
            Serial.println(_readmsg);              <---- still error. marked [D] in Serial output
            Serial.print("duplicate2: ");
            Serial.println(t2);                    <---- clone variable is OK. marked [E] in Serial output
            strcpy(out, t2); // if key not present, return entire message
            return 0;
          }

and in Serial port:

    message sent OK   <---- irrelevant for debug

    15:18:14.934 -> first: {"id":"Port","msg":"fff"}       <----[A]

    15:18:14.934 -> duplicate: {"id":"Port","msg":"fff"}   <----[B]

    15:18:14.934 -> second: id                             <----[C]

    15:18:14.934 -> third: id                              <----[D]

    15:18:14.934 -> duplicate2: {"id":"Port","msg":"fff"}  <----[E]

    15:18:14.934 -> Error. no such key. got reply: {"id":"Port","msg":"fff"}

Is there a reason for that ? is it a bug ?

title: Unexplained behavior of char array after using `deserializeJson`

Answers: 2

body:
When you pass a `char*` input to [deserializeJson()](https://arduinojson.org/v6/api/json/deserializejson/), it alters the input to avoid making useless copies.
This is the "zero-copy" mode of ArduinoJson.

In this mode, the JSON parser modifies the input in-place. The following modifications are performed:

1. `'\0'` are inserted at the end of each string
2. Escaped special characters (like `\n`) are unescaped

Example:

```c++
char[] json = "{\"hello\":\"world\"}";
deserializeJson(doc, json);
```

After executing the line above, the input variable probably contains something like: `"hello\0world\0"`.

You can find more details [in the documentation](https://arduinojson.org/v6/faq/why-is-the-input-modified/)

body:
To sum up Benoit Blanchon answer:

in original code:

    deserializeJson(DOC, _readmsg);

changes to:

    deserializeJson(DOC, (const char *)_readmsg);


body:
I am trying to read multiple MPU 9250 sensors using TCA9548A multiplexer in ESP 32 and Arduino IDE. Has anyone done that successfully?

I am new to the  area of Arduino coding. I am trying to edit the code in this tutorial for MPU 9250 (https://www.bluedot.space/tutorials/connect-multiple-sensors-using-i2c-multiplexer/). I am facing issues with libraries and commands while shifting from BME 280 to MPU 9250.  Once  I am changing to MPU 9250 and trying to call instance MPU9250 IMU_0, I am getting error "no matching function for call to 'MPU9250", which I understand is because the library I've used doesn't support the call. I am unable to find alternate library or command. How can this be sorted out?

<!-- language: lang-cpp -->

    #include <Wire.h>
    #include <MPU9250.h>
    MPU9250 mpu_0;
    MPU9250 mpu_1;
    MPU9250 mpu_2;
    MPU9250 mpu_3;

    #define TCAADDR 0x70
    void tcaselect(uint8_t i) {
      if (i > 7) return;

      Wire.beginTransmission(TCAADDR);
      Wire.write(1 << i);
      Wire.endTransmission();
    }
    void setup() {
      Serial.begin(9600);
      Wire.begin();
      Serial.println(F("##############################"));
      Serial.println(F("Starting Initialization"));
      Serial.println(F("##############################"));

      //*************INITIALIZING FIRST SENSOR*******************************
      tcaselect(0);

      if (mpu_0.begin() != 0x68)
      { Serial.print(F("MPU.1 detected?\t")); Serial.println(F("No"));}
      else
      { Serial.print(F("MPU.1 detected?\t")); Serial.println(F("Yes"));}
      //**********************************************************************
      //*************INITIALIZING SECOND SENSOR*******************************
      tcaselect(1);

      if (mpu_1.begin() != 0x68)
      { Serial.print(F("MPU Nr.2 detected?\t")); Serial.println(F("No"));}
      else
      { Serial.print(F("MPU Nr.2 detected?\t")); Serial.println(F("Yes"));}
      //*********************************************************************
      //**********************************************************************
      Serial.println();
      Serial.println(F("##############################"));
      Serial.println(F("Initialization Finished"));
      Serial.println(F("##############################"));
      Serial.println();
      Serial.println();
    }

title: Reading Multiple MPU 9250 Sensors using TCA9548A Multiplexer

Answers: 1

body:
You need to adapt the example you're following to follow how the MPU library does its construction and setup.

Looking at the [documentation][1] for the MPU library you are using, you should change the definitions to:

<!-- language-all: lang-cpp -->

    MPU9250 mpu_0(Wire, 0x68);  // 0x69 if you pulled AD0 high

Then if you read further to the "Common Setup Functions" section, you'll see that this library's `setup` function has this behavior:

> This function returns a positive value on a successful initialization and returns a negative value on an unsuccesful initialization

So you need to adapt that too:

    Serial.print(F("MPU.1 detected?\t"));
    if (mpu_0.begin() < 0) { // the examples assume zero is ok too
      Serial.println(F("No"));
    } else {
      Serial.println(F("Yes"));
    }

You'll save yourself some trouble if you use an array for your sensors too.

    MPU9250 mpus[] = { MPU9250(Wire, 0x68), MPU9250(Wire, 0x68) };
    const int num_mpus = sizeof(mpus)/sizeof(mpus[0]);

Then your initialization can be done with a loop:

    for (int i = 0; i < num_mpus; ++i) {
       tcaselect(i);
       if (mpus[i].begin() < 0) {
         // ...
       }
     }

And you can do similar things for interacting with the sensor. e.g.:

    for (int i = 0; i < num_mpus; ++i) {
       tcaselect(i);
       mpus[i].readSensor();
       Serial.println(mpus[i].getAccelX_mss());
       // ...
     }

[1]: https://github.com/bolderflight/MPU9250


body:
Im practicing with an arduino UNO board (I'm a begginer) and I'm trying to turn some LED's on depending on which analog pin is connected to 5V.
Here's my code:

    int statusLed = 11;
    int out1 = 2;
    int out2 = 3;
    int out3 = 4;
    int out4 = 5;
    int in1 = A0;
    int in2 = A1;
    int in3 = A2;
    int in4 = A3;
    int statusLedBrightness = 3;
    int incBrillo = 3;
    int fadeDelay = 5;

    void blinkFade(int pin){
      analogWrite(pin, statusLedBrightness);
      statusLedBrightness = statusLedBrightness + incBrillo;
      if (statusLedBrightness <= 0 || statusLedBrightness >= 255){
        incBrillo = -incBrillo;
      }
      delay(fadeDelay);
      }

    void wait(){
      digitalWrite(out1, LOW);
      digitalWrite(out2, LOW);
      digitalWrite(out3, LOW);
      digitalWrite(out4, LOW);
      blinkFade(statusLed);
    }

    void setup() {
      // put your setup code here, to run once:
      pinMode(out1,OUTPUT);
      pinMode(out2,OUTPUT);
      pinMode(out3,OUTPUT);
      pinMode(out4,OUTPUT);
      pinMode(in1, INPUT);
      pinMode(in2, INPUT);
      pinMode(in3, INPUT);
      pinMode(in4, INPUT);
      Serial.begin(115200);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if (analogRead(in1)>=500){
        Serial.println("1: ");
        Serial.println(analogRead(in1)); //Print "1" and the read of pin A0
        turnOff();
        digitalWrite(out1,HIGH);
      }
      else if (analogRead(in2)>=500){
        Serial.println("2: ");
        Serial.println(analogRead(in2));//Print "2" and the read of pin A1
        turnOff();
        digitalWrite(out2,HIGH);
      }
      else if (analogRead(in3)>=500){
        Serial.println("3: ");
        Serial.println(analogRead(in3));//Print "3" and the read of pin A2
        turnOff();
        digitalWrite(out3,HIGH);
      }
      else if (analogRead(in4)>=500){
        Serial.println("4: ");
        Serial.println(analogRead(in4));//Print "4" and the read of pin A3
        turnOff();
        digitalWrite(out4,HIGH);
      }
      else{
        Serial.println("Stand By");
        wait();
      }

    }

The problem Im having is when I connect a wire from 5V to any analog pin (A0 to A3) it always runs this segment of code:

    Serial.println("1: ");
    Serial.println(analogRead(in1));
    turnOff();
    digitalWrite(out1,HIGH);

By my understanding it's detecting as if it always was A0 the one that is connected to 5V but i dont understand why is this happening or how to solve it.

This is a screen capture of serial monitor when 5V is connected to pin A2. It should print "3:" and the reading
[![][1]]
[1]

  [1]: https://i.stack.imgur.com/8izJq.png

title: always detects same pin as HIGH even when its not connected

Answers: 1

body:
You're not showing your schematic but I'm sure that you are simply leaving the Ax pins OPEN when you are not connecting them to your +V line.  In that case they are "floating" and as such they can float HIGH or LOW or just about anywhere.  What's happening is that when you hook up +V to any of them, that has the side-effect of pulling at least A0 HIGH along with it since you have allowed it to float.

Two things to do here:

 1. Don't allow lines to float and expect deterministic behavior.  Tie them to +V or to GROUND when you are not using them.
 2. Pull the Ax lines to +V or GND via a resistor like 10K Ohms.  This will prevent them from floating and will give you predictable results.