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

void setup() {}

void loop() {}

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

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

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

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

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

so select Every and compile if you know which library

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

void loop() {

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

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

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

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

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

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

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

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

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

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

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

const int LED = 13;

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

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

#define FREQUENCY     RF69_915MHZ

#define RFM69_RST     4

RFM69 radio;

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

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

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

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

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

  pinMode(RFM69_INT, INPUT);

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

  Serial.println("Starting up");
}

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

  delay(5000);
}

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


text:
How do I convert Arduino to an ATmega328P-based project?
I have an Arduino board where I am using some of the peripherals like LCD with I2C.
Now I want to convert this Arduino-based circuit to an atmega328p based circuit, i.e. atmega328p with LCD and I2C.
Here is my actual question: Can I use the same sketch (binary) that I have compiled and uploaded for the Arduino board for the atmega328p and does it work? Or do I need to write atmega328p based C++ code?

A compiled sketch will run just fine on a bare ATmega328p, if all the necessary surrounding components are there, and if you have a way to program it.
This could be as simple as putting the chip on the Uno and programming it there. Don't do that too often; the socket isn't intended for that. You could get a 28-pin ZIF socket, though.
There are a few things to consider:

The bare chip needs external components like a crystal, etc. to function; you can check the Uno's schematic to see what you want to copy to your PCB/breadboard;
You may want to include a way to program the ATmega328p in-circuit using an ISP or a USB-to-serial chip;
The pin numbers will be different, a minor annoyance;
Possibly things I forgot.

There is a how-to on the Arduino site, and also a description of how to build a "whole" Arduino on a breadboard.

Thank you so much!

You are most welcome. Please accept the answer (if you accept it) so the question doesn't stay open.

I've built PCBs with a standalone ATMega328p chip on them before for situations where I wanted all my electronics embedded onto a single board. It can be a great learning experience imo.
I would suggest first creating a schematic and implementing it on a breadboard with DIP packages as seen on the photo. You will need a crystal, loading caps (22 pF), as well as bypass caps (100nF) and pull-up resistors. Plus any other components your application requires.

After that typically you would burn a boot loader onto the chip so it can be programmed with the Arduino IDE.
Nick Gammon has provided an excellent tutorial on all of this. His article was my main resource when I made my PCBs: http://www.gammon.com.au/breadboard
Once you get everything working on a breadboard, you may want to look into laying out a PCB for a more permanent solution. Best of luck!

Unable to write in the comments. If you are looking at using just a raw atmega328p, you can use the Arduino as ISP sketch and then upload your existing sketch to the new chip. I use it for programming ATTiny 85 chips for small stand alone projects. Here is a Link  to the Arduino site which explains this in detail.

Yes, you can use the same sketch and also the same HEX file. Though the uploading depends on your actual setup. If you include a UART USB bridge, like the Arduino has, then you can upload over USB (assuming you have burned the bootloader to the Atmega328p). Otherwise you can use your Arduino as an ISP programmer and burn your sketch onto the Atmega through it. Google for Arduino as ISP for more information

The Arduino has already a 328p chip on the board, but with a bootloader and a 16MHz crystal.
If you use only the chip, you need to create a board like the arduino.
Or you can extend the IDE with this board library:
https://github.com/MCUdude/MiniCore
So you can still use the same sketch but remove the crystal for example.

source: Stack Exchange

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

sort: votes


text:
Code Optimization: Interrupt when a value reaches 0
I have a working program and I wish to improve its efficiency as much as possible.
It will blink slow, then faster and faster  until it restarts.
It works, but my main concern is, currently, I am using a if statement in the void loop(), and I am certain that, using an interrupt when a specific variable has reached 0, would improve efficiency.
byte amp = 0;

void setup() {
  pinMode(13, OUTPUT);
  reset();
}

void loop() {            // The following
  digitalWrite(13,HIGH); // code is for the sake of example
  delay(amp*100);        // Simplified to focus on the loop
  digitalWrite(13, LOW);
  delay(amp*100);
  amp--;
  if (!amp) {reset();}     // <-This right here
}

void reset() {amp = 10;}

My understanding is, the if statement is called every time the loop restarts.

Is it possible to set up an interrupt for when a certain variable reaches 0?
Which option would require less computing power, a continually called if loop, or an interrupt?

For what are you trying to save computing time? The first step would be to ditch all the delay() calls (since with them you have up to 2s, where the Arduino is just twiddling its thumbs) and use millis() like in the BlinkWithoutDelay example for a non-blocking coding style. The if statement only takes so little time, that it doesn't matter for 99,9% of cases. What do you want to do in your code besides the blinking, that you need this optimization?

Thanks for your answer @chrisl, actually this is not my regular code and only for the sake of simplified example.

you can't really use an interrupt to replace an if statement ... the proper way to service an interrupt is to only set a flag in the ISR ... then test the flag in loop(), usually by using an if statement

look at the assembly code created from the sketch if you want to understand advanced things.

@B7th I already thought so, but you still didn't write about what your regular code does besides blinking. I think, that you might look into a totally unnecessary direction for optimizing your code out of missing knowledge. To actually know that, we would need to know, for what you are trying to save "computation power". Only then we can give you an answer, that really gets you further.

You did not specify the kind of Arduino you are using but, based on another recent question of yours, I will assume it is an AVR-based Arduino.
You cannot have an interrupt automatically triggered by a variable reaching zero. What you can do, instead, is trigger an interrupt by software, by toggling a pin that is configured both as an output and as an interrupt source:
const uint8_t int_pin = 2;  // pin used for interrupt

void setup() {
    digitalWrite(int_pin, LOW);
    pinMode(int_pin, OUTPUT);
    attachInterrupt(digitalPinToInterrupt(int_pin, reset, RISING));
}

static inline void trigger_interrupt() {
    digitalWrite(int_pin, HIGH);
    digitalWrite(int_pin, LOW);
}

// Within loop():
if (!amp) trigger_interrupt();

However, if you do that, you will discover that interrupts are slow; awfully slow compared with a simple if test:

digitalWrite() itself is awfully slow. This can be overcome by using direct port access, but that is still two cycles for toggling the pin in each direction.

You will lose an extra cycle in the pin synchronizer.

Once the IRQ is raised, the CPU needs four cycles to prepare itself for servicing it.

The interrupt vector is a jmp instruction, which takes 3 cycles.

The ISR then has to save every single register it is going to use, including the status register. That takes two cycles per register. And there are quite a lot of registers to save...

This ISR, which is provided by the Arduino core, will then look for the interrupt handler you provided with attachInterrupt(). This also involves checking that the pointer to the handler is not zero (the kind of test you seem to be worried about). It then has to call (4 cycles) your handler, which will have to return (4 cycles) to the ISR. You could avoid this indirection by defining the ISR yourself instead of relying on attachInterrupt().

Once the job is done, all the saved registers have to be restored (2 cycles times many register), and the reti instruction (4 cycles) is issued in order to restore control to the interrupted program.

Last but not least, since amp will be modified in interrupt context, you will have to qualify it as volatile. This keyword prevents the compiler from perform optimizations that are unsafe in this situation, and you will loose a lot of time to these missed optimization opportunities.

In contrast, this line:
if (--amp == 0) amp = 10;

would be translated by the compiler into something like this:
   dec  amp     ; --amp, as amp is likely already in a register
   brne 1f      ; if (amp != 0) skip the following
   ldi  amp, 10 ; amp = 10
1:

The whole sequence takes 3 cycles, irrespective of whether the if condition was true or false. That is at least one order of magnitude faster than the interrupt-based solution.

Very complete explanation of how and why. Thank you Edgar this helps make a lot of sense of how the assembly works!

Simple if statements are very fast and won't affect performance much even when used in every looping of the loop.
Using an interrupt to implement something simple like if (!amp) amp = 10; will probably make things slower:

something will have to keep track of the counter to generate an interrupt, and this "something" takes MCU time, unless it is a peripheral;
interrupts have overhead;
on single-thread MCUs, interrupts stop regular code execution until they are done;
amp = 10; will still have to be executed, in the regular code, or, if you must, in the interrupt.

You would gain more by getting rid of the function call to reset(), but the compiler probably does that for you.
Also, I wouldn't know how to replace a regular if with an interrupt, unless the counter is kept by a (timer) peripheral.

Re “amp = 10; will still have to be executed, in the regular code“: Why would you do that in the regular code? This statement would not take longer that setting a boolean.

@Edgar-Bonet: Yes, in this simple example it is just one statement, so it doesn't matter here.. I'm not of the school that says you should always only set a flag in an interrupt and must do everything else in the loop, in case you were worried

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


text:
How to add two assembly arrays in arduino
Hey guys what I'm trying to do is to sum two arrays and return a new array; for example if given
  uint8_t a[] = {2, 4, 6};
  uint8_t b[] = {1, 2, 3};

I should get { 3, 6, 9} What I'm trying to do is have a .ino file call on an assembly file that will do this in assembly and not in C and this is what I currently have in assembly:
// mimics void sumArrays(uint8_t *a, uint8_t *b, uint8_t *c, byte length){} method
    .global sumArrays
    sumArrays:
      //r18 is the byte length
      //r24 and r25 first  array 31,30
      //r23 and r22 second array 29,28
      //r21 and r20 third  array 27,26

      mov r30, r24
      mov r31, r25
      mov r28, r22
      mov r29, r23
      mov r26, r20
      mov r27, r21
      ldi r17, 0 //counter variable
      ldi r19, 1
      call printRegs
      //jmp sumLoop

      ret

    sumLoop:
      cp r17, r18
      brge endSumLoop
      ldi r16, 0
      add r16, Z+
      add r16, Y+
      st X+, r16
      add r17, r23
      jmp sumLoop:

    endSumLoop:
      ret

However, I get sketch/assignment13.S:65: Error: constant value required which is most likely from the
add r16, Z+
add r16, Y+

Lines but otherwise, how would I add it to a temporary variable while progressing the pointer?

Why are you using assembly for this instead of C?

add r16, Z+

You probably meant something like
add r16, memory[Z+]

However, the AVR is a RISC processor. It has instructions to address the
memory, and instructions to do arithmetics, but it has no “complex”
instructions that both address the memory and do arithmetics with the
addressed data. So you have to use separate instructions to:

Load (ld) the data from RAM

do the arithmetics

store (st) the result in RAM

Now, looking at your assemble code, I have a few comments:

If you are mixing assembly and C/C++, you should pay attention to the
ABI conventions. Specifically, some registers, like r28 and
r29, “belong” to the caller. If your function needs to use them, it
should save their contents (typically by pushing them to the
stack) before clobbering them, and restore them (pop) before
returning.

For adding two 8-bit numbers (a + b), a single addition is enough.
There is no point in starting the addition with zero (i.e. computing
0 + a + b).

For managing the counter, it can be more convenient to decrement the
initial count you where given (like in C: if (--length) return;)
rather than using an extra variable that is incremented.

There is no need to split such a simple function into smaller
functions.


text:
Connect 4 HC-12 transmitters to 1 HC-12 receiver
I am currently receiving data from HC-12 modules via USB-TTL that are working in pair . But I want to receive data simultaneously from 4 Hc-12 modules to a single HC-12 module via USB-TTL.

so, what is your question?

how can i connect 4 HC-12 transmitting modules to 1HC-12 receiving module

I don't really understand. Those are wireless modules, they're already "connected" as long as they are in range. What problems are you having receiving the signals ?

yes i am having problem receiving the signals. even though both the receiving and transmitting module have same channel FU and baud rate

Well show a schematic of how you have things wired up, and show the relevant pieces of code for the receiver and transmitter. (Please [edit] your question for that.) There's not enough information here.

there isn't coding for this . check data sheet for HC-12

https://www.elecrow.com/download/HC-12.pdf

When a HC-12 is transmiting all other HC-12 in his range (using same frequency) are receiving. So if you want your transmiter to talk to one specific HC-12 then to an other and so on, you have to create a kind of "message protocol".
Let's say you have an Arduino with a HC-12 and 4 buttons and want to turn on-off 4 lights, each connected to a HC-12. You can use a binary representation, so a byte, on which each bit as a meaning.
Bit 0 -> at 1 -> turn on the light at 0 turn off
Bit 1-2 -> give the number of the HC-12
So 00000111 -> message for HC12 number 4, tell it to turn on the light.
ALL HC-12 will receive the message. So each has to check the incoming byte to see if "it's for me" or nor.
If you want one HC-12 to receive from many HC-12, that's the same: the message must contain the "id" of "who is sending".

The problem with multiple transmitter mostly resides in the collision risks. On networking contexts like Ethernet, There is a collision detection protocol making transceiver know that a problem arises, but that doesn't exist with HC-12, so you need something else.
In air contexts like this one, another solutions might to minimize chances of collisions restraining onself to a low bandwidth percentage (e.g.: not more that 10% of the total time) and just ignore lost packets.
However, if you cannot ignore lost packets, you need to implement a synchronisation protocol between receiver and transmitters. A solution would be to make some kind of token bus, where your receiver would poll each transmitter each on his turn to see if it has something to send.
However, since it is not recommended (and sometimes not even legal) to use to much time slices, you should avoid continuously polling all the transmitters.
In this case, what I suggest is that each transmitter can "wake up" the receiver by sending an unattended message. If this doesn't not cause reaction, this is interpreted as a collision detection. Then the transmitter wait for a specific delay (each one having a different delay value) - or a random delay.
When the receiver receives this packet it processes it, Then polls all the other transmitters, and then goes back to sleep mode, until the next time.
If the packets are long it might be better to have a short wake-up packet and to send the real data during the polling phase, and if the packets are short, you can just use the collision avoidance mechanisme alone.


text:
i am not able to figure out the problem due to which i can't upload my sketch to nano
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

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

the code has no problems but idk what is avrdude

Looks like your installation is incomplete. Make sure your core is up to date in the boards manager. Try reinstalling the core.

it is up to date i even checked it even the conf file it there but it shows can't open config file and then path name then shows no such directory or file

Them maybe you have a permissions problem. Are you using the app store version on Windows 10 s?

yes i am using the store version

Don't. It's broken. Download the version form the Arduino website.

k thx for the solution

Uninstall the IDE. Delete all the support files. Download the IDE. Update the core.

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

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.


text:
Analog input voltage rises when motor is working
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.

Nothing coming to mind immediately, at least nothing I have good reason to think is actually the problem.  Even with the reference diagram and understanding how you've effectively replaced the potentiometer with the sensor, it would be good to have a picture of the actual wiring.  Sometimes it just reveals things you didn't think to mention.

My first thought is that you have a noise problem with either the sensor itself picking up noise and misinterpreting it as input or noise being picked up by the analog pin and interfering with your readings.  You might try it without the pump motor hooked up so that you can isolate the problem.

@jwh20 without the motor, sensor reading are stable when connected to analog pin. Can there be a problem with Arduino? I do not have other just this one, but I don't know what are the chances that something is wrong...I bought it just for this project and I must also add that in this project I had a lot more components connected (I removed everything except pump and sensor to try to isolate the problem, just as you said) and everything else works great, even bme280 sensor and oled display, which are connected to A4 and A5 pins. Maybe is noice from the pump...But I can't remove it completely...

Why don't you show how you have things hooked up?  I suspect you have either a power supply issue or a noise issue caused by the motor.  You either need to beef up the supply to your motor and/or filter the noise being produced by it.

@timemage  I will draw what I've done, no problem and edit my main post

That may help.  But clear actual pictures of real wiring won't hurt.

@timemage jwh20 I added link in my first post hope it's clear enough

Try adding some bypass capacitors across the motor leads and also from Vcc to GND at the moisture sensor.

I have only one thought beyond what jwh20 has said, but it's dependent on your 2.2k resistor not really being 2.2k.

@timemage  Yes, It is actually a 2k resistor on the picture, not 2.2 you are right, I made I mistake. I'm pretty sure though it's not a current problem. I also tried with higher value resistors, even tried just turning the motor on all the time directly from power source, without that transistor circuit and signal from Arduino, just motor, diode, sensor and Uno, with only grounds connected together and same thing happened. So I hope that  capacitors will solve my problem.

The diode on your schematic drawing is in the wrong configuration. It supposed to connect across the motor with cathode to 5V and anode to the join of motor and the collector pin of TIP120. See what is a protection diode for explanation. You get it wrong because the link that you provided has a wrong connection too.

@hcheung, compare with the image of the actual wiring.  They probably just got it backwards trying to make the diagram quickly.

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

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.

Thank you very much for suggestion. Unfortunately, I don't have them right know at my place, but I could get them tomorrow when shops are open, so I will post results then :)

ok I tried with capacitors, one 0.1uF ceramic, and one 10uF electrolytic where I put longer lead to + side and shorter to -. I can get a picture of my circuit if it's needed if you think I maybe wired it bad. Didn't help. Sensor value in water is 250 and when motor is on, in a few seconds value goes up to 450, then it goes down to 400 in about 30 seconds and that's it...

Please update your question with a photo of what you've tried.

ok I added and put a photo hope it's clear enough

It's clear there is some sort of interference caused by the motor or your motor control circuit that is causing the reading from what I suspect is a very sensitive "antenna" moisture sensor and the caps are just not enough.  How about a different approach?  You might try pumping water for a few seconds and then stopping the pump and taking a series of readings over a few minutes until the values stabilize.  Then repeat as needed until you get to the moisture reading you want.

I already did that in my code, before even asking this question. I'm reading from sensor every two minutes which is more then enough from values to stabilize, so it's not affecting functionality of my project at all. However, I asked this question because I was pissed that I couldn't find solution. I googled, read many forums, solutions, and nothing worked so I decided to ask here in case that maybe someone would have any new idea. Is it possible that Arduino is faulty? I'm not planning to buy a new one, but I would like to know where the problem is :) Thank you anyways :)

I doubt the Arduino is defective. These types of issues can be difficult to track down but it's also exacerbated by the way you have constructed this so far, specifically with wires going all over the place being quite long, no shielding, etc.  Since we addressed, to some degree at least, the power, the next is noise being introduced into the analog input line from your sensor.  Don't feel bad about this, you're at the interface between theory and real-world issues.  Noise problems keep engineers up at night!

This particular sensor just generated an analog signal and the ADC in the Arduino just reads that voltage.  You might also try putting a capacitor, try a smaller one like your 0.1 uF, from that signal line to GND.  That will help to "slow down" the signals on that line.  You not really needing to take readings quickly in this application since you really are not ever changing the moisture content quickly.

Thank you for suggestions :))


text:
What is the best way to init wifi communication between two devices (get IP address)?
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.

That seems very overcomplicated to me. While not knowing, how exactly you would implement this on the ESP and Pi, you could let the Pi broadcast a special message over the network, which identifies it as your automation application server. All clients in the network will get this special message. Non-automation devices won't know, what to do with this message, thus they will ignore it. The ESP can wait for this message and when it arrives, it can save the IP, that the message came from (source IP). Then the ESP can contact the Pi by IP.

@chrisl Oh, seems very good and "simple" at the same time (y). Probably I will do it this way. THANKS!

One mechanism you could use for this is called "multicast DNS (mDNS)". This is supported by both the Raspberry Pi and the ESP8266. See also resolving Raspberry Pi address through mDNS with NodeMCU

you give the rpi a fixed IP, and on boot have the ESPs send that IP a check-in http request, which will reveal their IP to the pi.

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

But when server (RPi) will need to control clients? (For example switch lamp...)

@RozonaZoro The server will automatically get to know the client IP, when the first request from the client comes in. It would just have to save it. But the question seems to focus on the step before that. When the client doesn't know the IP of the server, how could it acquire the IP automatically?

Yes, the biggest problem is your last question. Probably I will solve it with sending broadcast message from RPi, as have suggested @chrisl.

It can be possible if the server support mDNS (Multicast DNS)


text:
Question: how to join two different codes
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);
}

If the problem is with your joint code, show that code, not the individual sketch that works. You also need to elaborate more on the meaning of "no help", what does it means? Got error? can't compile? etc..

write a new sketch that does everything that the two sketches do ... replace some of the serial.print with lcd.print ... for example, in setup() do dht.begin, lcd.begin, clear lcd, display start message on lcd, if bmp.begin fails then display error message ..... etc

you can refer to how to combine two Arduino code

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.


text:
Weather station project Transmitter not communicating with Receiver
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

Nothing wrong with your code. nRF24L01 consumed quite some power during transmission, the 3.3v regulators on your Due and Nano might not be able provide the surge current it needs, try to add a large cap (10uF or above) to both of nRF24L01 3.3v pins to see if it help, or use a 3.3v that can delivery 200mA+ current.

Thank you!! It worked like a charm.


text:
How to move a servo quickly and without delay function
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:
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?

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

The best way is to use map() 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() function, therefore you do not need to worry about blocking other code.
Full instruction is available on How to control speed of servo motor

Nice idea! It should be combined with constrain() in order to avoid overshooting (map() does not implicitly constrain()).


text:
Problem connecting 2 74HC595 8 bit shift registers in cascading connection
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...

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

connect the microcontroller output to the second 74HC595 to test it

add a second shiftOut. one sends only 8 bits. https://www.arduino.cc/reference/en/language/functions/advanced-io/shiftout/

someone please post a code, I really am unable to understand what to do, even after reading the article link by @Juraj, i have got a new mess inside my brain

add leds2 and send it before leds

You're (still) only shifting one byte (8 bits) of data out, so your second HC595 never receives any data. You should do what @Juraj wrote: add a leds2  variable to your code and insert a second ShiftOut(dataPin, clockPin, LSBFIRST, leds2); before the first shiftOut() in the updateShiftRegister() function. You should also set the appropriate bits in leds2 to control which LED is on and which is off.

As Juraj wrote add another line shiftOut(dataPin, clockPin, LSBFIRST, leds); to the updateShiftRegister() function, right above or beneath the other one. Currently you are only sending data for the first shift register. A second register would also need data, so you need to shift out another byte of data.

Oh, getting to understand it a little, i have to create another byte data type named 'led2' for the second shift register then repeat the same process? Right?

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.


text:
Bit Bang signal generation

  #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
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?

What should the behaviour of "CI" be when it is "low", after the falling edge of the fifth "FDCS" pulse? For how many "FDCS" pulses should it remain low? The code is easy to adapt but you've not yet specified the complete "CI" cycle.

@StarCat To summarise, CI should go HIGH when FDCS goes HIGH, then stay HIGH for 4 complete cycles of FDCS, then go LOW on the FALLING edge of the 5th Cycle. Now the CI pin should stay LOW until the RISING edge of the 10th cycle of FDCS after which the pattern repeats. The pattern should repeat 2000 times.

Alread asked and answered here: Sync issue with signals

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

Could you let me know what the postState variable is?

@Redlion11: It's a typo. ;-) Fixed!

Thanks for the clarificationn!!


text:
Bitwise write to analog PIN
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!

AnalogWrite is a wrapper that hides complexity from you. You will have to configure on of those Timer/Counter to do PWM and set multiple registers accordingly.

Thank you! Have you got any material where to read more about it and how to do it?

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, 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, 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.
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 (or when googling for the microcontroller name)

I am sorry - I am using Nano..

@wotesi Then all the links, that I've included, apply to your Arduino. The Nano also uses the Atmega328p

Great! Thank you very much!


text:
Write file to SD card using SDFat.h and ESP8266
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();

If you don't describe us the problems more detailed, we can not say what went wrong. Does the code not compile? Is there an error message, when you run the prog? Perhaps you locked the SD card, so writing is impossible, or you have to change the FAT Vlolume with sd.chvol(). Does open for read work? Have you tried that?.... Just saying "it doesn't work" is not enough!  ;-).

I edited question with some news and updates


text:
How can I rewrite my Bluetooth Classic Arduino code into Bluetooth Low Energy Arduino code (and have everything working the same)
My original code for BT Classic
My Work in Progress BLE Code
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).


text:
SPI between Master arduino and Slave arduino
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)));
    }

At first: spi_port |= (1<<SS); after the return wil not work. You'll never reach the line. Why do you initialize spi_data_reg = 0;? Have you set the master to input like spi_data_direc=(1<<MISO); elsewhere? I did not yet programmed SPI communications with the low level api, so I do not know if one of these could be the problem. But as no one else repsonded ... Just some ideas; better than nothing.

As far as I understand SPI communication, Slave cannot send data to Master without Master initiating the communication. Typically, Master sends a dummy data so that it can receive a response from Slave. So Master needs to know how many bytes to receive and send dummy data to Slave as many times to get the response.


text:
Unexplained behavior of char array after using `deserializeJson`
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 ?

Please see: Why is the input modified?

Also, please check the error code returned by deserializeJson()

@BenoitBlanchon Error gets "OK"

When you pass a char* input to 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:

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

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

Thank you for your reply - I don't understand why _readmsg changes ( as a concept ). Whould you recommend to clone that variable as I did using t2 ?

To sum up Benoit Blanchon answer:
in original code:
deserializeJson(DOC, _readmsg);

changes to:
deserializeJson(DOC, (const char *)_readmsg);


text:
Reading Multiple MPU 9250 Sensors using TCA9548A Multiplexer
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?
#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();
}

"I am facing issues".  What issues?

Your code is nearly impossible to read.  You might consider editing your question and using the code formatting facilities on the page.

Which MPU9250 library are you using? Did you look at its examples to fix your code?

I see no question being asked

I am using MPU 9250 library from bolder-flights system. In the tutorial about multiplexer, they have used BME280 and BlueDot_BME280library. 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. What alternatives can I use or how can I achieve taking readings from Multiple MPU9250 simultaneously using a multiplexer?
Thanks

You need to adapt the example you're following to follow how the MPU library does its construction and setup.
Looking at the documentation for the MPU library you are using, you should change the definitions to:
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());
   // ...
 }

Thankyou very much... I would try implementing these..


text:
always detects same pin as HIGH even when its not connected
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

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:

Don't allow lines to float and expect deterministic behavior.  Tie them to +V or to GROUND when you are not using them.
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.

that was it, adding resistors to pull Ax lines to GND did it. Thanks!


text:
Native USB port on custom ATSAM3x8e board not recognised in windows
I have been designing my own PCB using the atsam3x8e chip, the same as the Arduino due which I used to prototype with. So far I've managed to get my boards up and running by programming them via the serial TX & RX pins using a USB to serial converter, but I can't seem to get the "Native" USB port to work in windows.
When the boards are plugged in, they show up in the windows device manager as "Unknown USB Device (Device Descriptor Request Failed)" but do not show up in BOSSA or Atmel Studio 7.0. My understanding was that when the chip is reset and erased, it should just show up as a "BOSSA programming port" the same as the Arduino DUE does when it is put through the same procedure.
I'm not sure whether this is an issue with the hardware design of the board or not. I have used a USB C connector instead of a Micro USB so have not connected the UOTGID pin and instead added two pulldown resistors to the CC pins on the new connector.
If anyone has any suggestions on this please let me know.

"do not show up in BOSSA or Atmel Studio 7.0" is a consequence of "Unknown USB Device (Device Descriptor Request Failed)", not so much additional information.  Your understanding about it showing up as USB when erased is correct.  Show the hardware design.

added @timemage

I'm not terribly familiar with USB-C pinout, and it's hard to read just the PCB layout, but if I take it for granted that your two parallel traces are the D+ and D-, they go to only the high speed pins and not the full speed pins.  The due design does both.

@timemage this USB port is fairly simple, its 2.0 spec with VBUS, GND, DATA +, DATA- and CC pins instead of the ID pins. You're correct about the parallel traces being the data lines but they're connected to the high-speed pins directly and the full speed pins with 30k ohm resistors R22and R23.

Trying a different USB C cable and programming the boards over serial with an Arduino sketch makes the boards appear as Arduino DUE, but when reset and erased after this, the boards are still coming up as Unknown USB Device, is this normal behaviour since the vendor ID and Product ID are different?

Due has 39 ohms there.  Wild guess, USB interface fails or succeeds depending on the speed configured in the due/sam3x8e because of how you have it (not really) connected.

Sorry, that was just a typo... meant 39ohm, thanks for your help though


text:
Finding Relatively Accurate Velocity Using an IMU
I am currently working on a project where I am trying to accurately find velocity in a handheld device using an IMU for about 30 seconds.
I have been having major issues doing this because of large amounts of drift from poor calculations due to inaccurate sensor readings.
I have tried tuning offsets for my sensor and using other sensor fusion libraries to find my linear acceleration.
At this point I don't know if I am doing something wrong, going about the process wrong, or if my sensors are just to inaccurate to accomplish this.
I am hoping if anyone may have recommendations on how to accomplish this from the ground up. I currently have two 9DOF IMUS listed below. The first one I tried to use the predefined linear acceleration function to find velocity in ndof mode, using bosch calibration steps. The second i spent hours tuning the offsets on to get linear acceleration and it came out much worse than the first sensor. For the second I can include code but I used the madgwick from the Adafruit_AHRS library for the sensor fusion for sake of time.
Any help is appreciated.

https://www.adafruit.com/product/4646 (BNo055 first board)
https://www.adafruit.com/product/3463 (FXOS8700 + FXAS21002 second board)

Integration of acceleration to derive velocity is a difficult task.  This is the first step in dead reckoning.  Consider some of the following options to improve accuracy:

Some IMUs can be adjusted to increase sample speed. If the
acceleration is sudden, more samples my improve the accuracy of the
calculated velocity.
Try aligning just 1 of the axes of the IMU chip in the direction of
acceleration. Do this to simplify the problem.  Depending on the
Arduino you are using, the processor may not have the power to
perform the trig functions necessary for anything except
acceleration only along 1 of the IMU's axes.
Take care of loosing significant digits.  If using integers, try
multiplying everything up.  For example instead of 1 equaling 1
meter multiply the value up such that 1000 equals 1.000 meters.  Now
integer math can be used to calculate down to the mm.

I do have it at the highest rate I can sample. Also unfortunately for my current project the imu is in a handheld device and therefore cannot be aligned in a easier fashion.

Hand held?  Then you need get data from all 3 accelerometers.  And do the math to add up the contribution of each to find the overall acceleration vector.  Then integrate that vector over time in to a velocity vector.  Maybe you can do this if you are clever on an Arduino Uno.  But it my be worth looking at the specific processor used on different Arduinos and picking the fastest most powerful one.  I think you should really start simple and then try to add complexity.  Hand held is really really hard.  A car would be easier as one can assume the car is always up right.

I actually have been doing the vector math. I believe the main issue is because of bad readings from the accelerometer or bad orientation algorithm, I am not able to subtract the gravity vector out without large error

This is 1 of several reasons I think it best to start simple and add complexity 1 step at a time.  Thinking, maybe it's time for a trick.  Warning, this will likely not work well over longer periods of time.  But for 30 seconds, why not try subtracting the long term average from the reading.  So at rest the device eventually zeros out.  The long term average will not be able to respond to sudden acceleration so such acceleration will be seen by the velocity calculation code.

Okay thank you I'll give this a shot and let you know how it goes

Checkout my post above as well i added more detail

For more context I did ask BOSCH directly about this issue and explained my setup in more detail.
https://community.bosch-sensortec.com/t5/MEMS-sensors-forum/BNO055-Outputting-Bad-Linear-Accel-Data/m-p/18976#M5212

Please edit this into your question and then remove it. "This space is for answers only".


text:
Is this a feasible circuit?
The last couple months I’ve been working on this project, I’m nearing its end and I’m getting really excited!  However, this is still pretty new to me and so I was hoping my electrical diagram/accumulated knowledge could be verified before I go and start spending money on parts.  All criticism is welcome as are any additional resources.
Thank you in advance!

Logic:
Arduino setup:
Arduino pins (aside from the power section) at the bottom are capable of outputting up to 40mA at most and when using multiple pins, no more than 200 mA should ever be drawn at once
Piezo buzzers are the only electrical component that do not need resistors
This was taken directly from How To Mechatronics, attaching a 330 Ohm resistor to the LED strip lowers its electrical noise
The other resistor attached to the LED strip should be 25 ohms, seeing as I don’t have one though I will be using a 27-ohm resistor instead.  Where 5 LED’s on the strip should take up 300mA (each GRB uses 20mA and I’m using 5 in total, therefore 20 x 3 x 5 = 300).  Using Ohms law R = V/I, therefore R = 7.5/0.3, therefore R = 25.
**I would like to add that I also looked at Watt’s law and was a big confused as I got a current of 200 mA instead (as the LED’s each use between 0.1 – 0.3 Watts, therefore I = W/V, therefore I = 1.5/7.5, therefore I = 0.2)  I went with the 27 ohms instead of the 37.5 ohms watts law gave me instead because How To Mechatronics really seemed to know what was up
I chose to power the board via the 7.5V, 1A adapter mostly because I wanted its voltage-in to be regulated and seeing as it won’t be plugged into a computer, I thought USB was a bit sketch and it made more sense to use the power port as opposed to the Vin pin.
Motor setup:
The motor was chosen based off of my need for high torque – the door handle I am trying to push requires 5 pounds (raised to 6 pounds for extra breathing room) and the entire handle is 4.5 inches (lowered to 3 inches for breathing room) in length (the measurements were provided by a friend as I wont be home for a little bit, might seem a bit overkill but its just cause I don’t think they are entirely accurate in the first place).  Using these measurements and the equation Torque = length x Force I got the required torque had to be greater than 0.3572kg/cm to open my door.  Knowing this I took a look at a bunch of Nema stepper motors and chose one capable of producing that torque (based off of its holding torque) that was the lightest and smallest.  I wanted something light as I am still unsure how I will be mounting this to my door…
Originally, I was going to use the L298N but seeing as how using the 5V pin off the Arduino is not recommended for powering it and that they generally don’t dissipate heat that well for their motors I decided not to
Lastly, the 12V 4A power supply was chosen because I needed something stronger than 9V and I wanted to save money.  Seeing as I would have the 0.5A - 0.7A current option selected (to my knowledge anything more could cause damage unlike with the Arduino, extra current is not necessarily a bad thing in this case) it’s a bit overkill.  I’m thinking it shouldn’t cause any thermal limiting though seeing as it is rated to 4A and its not as if my motor will be going that often anyways :)
Links (all links except for the motor which goes to pololu redirect to amazon):
7.5V 1A Power supply:
https://www.amazon.ca/Belker-Adjustable-Universal-Household-Electronics/dp/B07NKZCWT1/ref=cm_cr_arp_d_product_top?ie=UTF8
12V 4A power supply:
https://www.amazon.ca/COOLM-Adapter-100-240V-Doorbell-5-5X2-5MM/dp/B07H2T31JJ/ref=sr_1_6?dchild=1&keywords=10V+4A+POWER+SUPPLY&qid=1606959202&s=hi&sr=1-6
KEYESTUDIO W5500 Ethernet Arduino (Uno):
https://www.amazon.ca/gp/product/B079G4WDGW/ref=ppx_yo_dt_b_asin_title_o03_s00?ie=UTF8&th=1
NEMA 14 stepper motor (2.7V, 1 A/Phase):
https://www.pololu.com/product/1209
TB6600 stepper motor driver:
https://www.amazon.ca/TB6600-Stepper-Driver-Controller-tb6600/dp/B07B9ZQF5D/ref=asc_df_B07B9ZQF5D/?tag=googleshopc0c-20&linkCode=df0&hvadid=292963865944&hvpos=&hvnetw=g&hvrand=11283888445696292979&hvpone=&hvptwo=&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9001232&hvtargid=pla-524548131497&psc=1
LED strip (WS2812B):
https://www.amazon.ca/gp/product/B01CDTED80/ref=ppx_yo_dt_b_asin_title_o06_s00?ie=UTF8&psc=1

what is the purpose of the device?

its a door unlocker :) gona set it up inside my apartment, the LEDs creates a colour code to be entered on a website I built, the speaker is to give me a minute heads up and the motor will pull a string to unlock the door

interesting ... the color code authentication is very clever

The 330 Ohms resistor does not lower any noise. It is not necessary. 2. The LED strip (WS2812B) can be powered by the Arduinos power pin. I would prefer an external power source, avoiding an overload of the Arduinos power regulator. It has no cooling and if you draw 500 mA it has to dissipate (7.5-5)*0.5 = 1.25 Watts. (It'll get really hot ;-) ) You could build an external regulator with an 7805 or LM317 or use a 5 Volt Power Supply. 3. If the color code is entered into Website, how does the Website communicate with the Arduino to control the motor? Have I misunderstood the setup?

Get a 5V power supply instead of the 7.5V. Get one with a  micro-USB plug. They are probably cheaper than the one you picked. Secondly; ohms law doesn't apply to WS2812 leds, as the regulate the current themselves. Thirdly, some buzzers require a transistor to drive, as some exceed the maximum current of an Arduino pin. Fourthly; it seems like a stepper motor is a bit of overkill for the application you're describing. I was thinking about maybe using a solenoid or one of the beefier hobby servos. But it kind of depends on how much force is required to unlock the door.

@Gerben Thank you so much as well :)  I really appreciate your help!  I dont know why I didnt think about getting a micro USB plug haha I'll definately go with that :) I have a lot of projects in mind  after this one so 2 & 3 will really help with those :)

Wow, that's a lot of work. I'm impressed. I can not help myself, but: ;-) In the Arduino code line 141 you increment the posi variable. Is this really necessary? You did inc. it already in the last line of the while loop. I'm really busy at the moment, so perhaps I'll have a look at it during the weekend.

@PeterPaulKiefer omg... thank you!  I haven't tested it yet but I'm sure that would've taken so long to debug!  I totally see what you mean :)  sounds good hoping to branch off of it too later in the future its been a big project and I've learned a lot since starting :)

Let's take a look at the LEDs.  Different kinds of LEDs have different forward voltage requirements. Non-bright LEDs tend to require less voltage than bright LEDs, since bright LEDs need more power to work. Typical VLED values are 1.7V for non-high-brightness red, 1.9V for high-brightness high-efficiency low-current red, 2V for orange and yellow, 2.1V for green, and 3.4 to 3.6V for bright white and most blue types.
In order to make sure that this voltage gets dropped across the LED, you should use a voltage greater than the LED's forward voltage. Use at least 3V supply voltage for lower-voltage LEDs and 4.5V for 3.4V types. Also add a resistor in series with the LED to limit excess current from burning out the LED, usually so that the current flowing through the LED is about 10mA. Make sure that the current doesn't exceed the maximum current specified on the LED's datasheet. You have 5 LEDs in series with (assuming keeps the math simple) a Vf of 2 Volts, therefore you need 5*2 (they add) or 10 volts to get them to light then a little more (2 volts) so you can control the current with a resistor. At this point you have 5 volts trying to push current through a 10V device circuit, nothing will happen. Using 12 volts and Ohm's law a 200 Ohm resistor will give you about 10 mA, a safe current for most LEDS. If you want them light replace the 27 Ohm with a 200 Ohm and connect to the +12V inplace of the 5V pin. Note LEDs do not work well in parallel unless the current is controlled in each LED or LED string. This is based on your schematic showing 5 LEDs powered by a 5V source.

The LEDs in the question are addressable LEDs that take care of their own current regulation. Your answer is not relevant to those.

An led's forward voltage does not depend on the power rating, all leds (of certain color) have the same forward drop (more or less, slight differences between manufacturers/materials). Power leds instead are driven at higher currents.

Take a look at a LUXEON 5050 It needs about 22V at 25mA and about 25V at 200mA.  Then there is the Violet Indium gallium which has a Vf range of 2.8 to 4 volts or Green which is 1.9 to 4 volts, over 200% Delta. Try this link: https://www.circuitbread.com/ee-faq/the-forward-voltages-of-different-leds The Vf is determined by the chemestry used and the process. LEDs also make great substitutes for low voltage zeners, just keep the current down, try it.


text:
LM35 temperature decreases when heated
I have a question regarding the LM35. The sensor is supposed to have values that are to be directly proportional. But instead of the temperature increasing, the sensor values decrease.
This is my setup below. It seems to be a standard setup in different LM35 tutorial pages.

const int sensor= A0; // Assigning analog pin A0 to variable 'sensor'

void setup() {
  pinMode(sensor,INPUT); // Configuring sensor pin as input
  Serial.begin(9600);
}

void loop() {

  float reading=analogRead(sensor); //Reading the value from sensor
  float vout= (reading*5000)/1024;
  float temp= vout/10;

  Serial.print("in DegreeC= ");
  Serial.print(temp);
  Serial.println("");

  delay(500); //Delay of 1 second for ease of viewing

}

These are the results. From room temperature, I applied heat through the use of a lighter and it went lower instead of higher.

I read somewhere that it has something to do with the power supplied by the Arduino. However, when I used a 12V supply to power the Arduino, the readings became very erratic and unstable.
UPDATE:
I have finally returned from the city (Took a long time because of Quarantine Restrictions) and I brought 3 LM35 from another shop. All 3 of the new LM35 worked as intended and didn't lower its temp reading when exposed to heat (With the same configuration). I could rule out these possibilities as to the reason why the LM35 didn't work.
1. Manufacturing Defect - all three of the LM35 didn't work as intended. They all had their temperature lowered when exposed to heat. There could be a defect in the manufacturing process because it doesn't work as advertised. (Leaning towards this)
2. Static Electricity - I remember receiving the LM35 in a plastic bag as packaged by the shop. It could have been affected by static electricity and damaged the circuit inside (on all three though?). The LM35s I received recently had been packaged in those electrostatic discharge protection packaging so it could have probably contributed to it? I need more insight on this I apologize for not being able to properly word it out.
There could be more but these are the most I could come up with as a conclusion.

Do not configure the analog pin as an digitial input pin. If you want to use it as an analog pin.you don't need any setup. An lm35 is like a complicated zener diode. Perhaps it help to put a resistor (say 10 kOhms)  from Vout to GND to stabilize the output voltage of the LM35. Just two guesses.

@PeterPaulKiefer I added the 10kOhms however the temperature reading became 0 celsius. Changed the resistor to 1k Ohms, still 0 celsius reading. Changed to 100kOhms, still 0 celsius reading. I had also set my code and removed the pinMode however still the same output. The temperature always scales down when exposed to heat (even with my 3 other spare LM35 but they are from the same shop tho). I will go and buy a capacitor tomorrow to do more testing on the sensor.

If the GND with a 10k resistor leads to zero Volt, then the LM35 does not output any voltage. It might be broken. (All three are broken?; perhaps from a fake parts store ;-( ).  There is a (really low) probabillity that the arduino analog ports are broken. If you have two simple resistors (>= 1000Ohms) you can put them in series, add VCC and GND each at an end and connect the middle (where the resistors are put together) to the analog port. If both resistors are the same value, it should result in about 512 +- 20.

You are reading A5 but in your diagram you show it hooked up to A0:

Change your code to this and I believe it will work:
const int sensor= A0; // Assigning analog pin A0 to variable 'sensor'

void setup() {
  pinMode(sensor,INPUT); // Configuring sensor pin as input
  Serial.begin(9600);
}

void loop() {

  float reading=analogRead(sensor); //Reading the value from sensor
  float vout= (reading*5000)/1024;
  float temp= vout/10;

  Serial.print("in DegreeC= ");
  Serial.print(temp);
  Serial.println("");

  delay(500); //Delay of 1 second for ease of viewing

}

The data you are reading from A5 is indeterminate and just happens to decrease as A0 increases.
================================================================================
UPDATE:
Ok, so you corrected yourself and are reading the correct pin in spite of what your schematic shows.  Please explain this:
float vout= (reading*5000)/1024;
float temp= vout/10;

I think you want:
float vout = (reading/1024.0) * 5000.0;
float temp = vout/10.0;

You are carelessly mixing floating point and integer math.

I'm so sorry I forgot to change the code to A0 but the output is still the same. Temperature goes down when exposed to heat :(

Do you have a voltmeter?  Your next step is to determine what the voltage on pin 2 of the LM35 is doing when you apply heat.  If it actually goes down then you probably have a bad LM35.  If it goes up as it should, then you have an issue with your Arduino or the code.

I will update once I go out tomorrow to get myself a multimeter. The thing is, I have 3 other spare LM35 and all of them have the same behavior. They are however from the same shop so I think I'll find another LM35 from a local shop tomorrow and compare.


text:
Testing of voltage level converter with arduino
I am having a problem I am testing logic level shifter https://ewall.com.pk/product_view/IIC-I2C-Logic-Level-Converter-Bi-Directional-Module-5V-to-3.3V/910. I have followed the procedure as given in this post Test level shifter with Arduino and some data. But I am getting opposite result when I connect LV1 to LV2 arduino stop uploading and give error and nothing displays on serail monitor. Kindly help me.

Please post your circuit schematic.  It's not at all clear what you are doing.

Apparently you did not completely follow the description at Test level shifter with Arduino as that states that you need to upload a blank sketch before connecting the Arduino serial port to the level shifter, not after (that will not work but that's as expected). Did you also add pullups as described in the answer? Also, a schematic would really help.

i have not added pullups. Sorry but i don't know how to add pull ups and their purpose. I just followed the edited solution of post.

In electronic logic circuits, a pull-up resistor or pull-down resistor is a resistor used to ensure a known state of a signal. They are a very fundamental building block in electronics. I would recommend reading this article on pull-up resistors: https://www.electronics-tutorials.ws/logic/pull-up-resistor.html This will help you understand some of the above comments.

so that means without adding pullups my circuit is incomplete

Someone please guide me .