text:
Modbus rtu data decimal to float conversion

Hi,am trying to communicate with power-factor controller [Selec APFC 148-312] using modbus RTU,am following example sketch from modbusmaster library. am able to get the raw data from the instrument but data structure seems to be in decimal format, can someone help me to convert this into float.thank you
#include <ModbusMaster.h>

#define MAX485_DE      3
#define MAX485_RE_NEG  2

// instantiate ModbusMaster object
ModbusMaster node;

void preTransmission()
{
  digitalWrite(MAX485_RE_NEG, 1);
  digitalWrite(MAX485_DE, 1);
}

void postTransmission()
{
  digitalWrite(MAX485_RE_NEG, 0);
  digitalWrite(MAX485_DE, 0);
}

void setup()
{
  pinMode(MAX485_RE_NEG, OUTPUT);
  pinMode(MAX485_DE, OUTPUT);
  // Init in receive mode

  digitalWrite(MAX485_RE_NEG, 0);
  digitalWrite(MAX485_DE, 0);

  // Modbus communication runs at 9600 baud
  Serial.begin(9600);

  // Modbus slave ID 1
  node.begin(1, Serial);
  // Callbacks allow us to configure the RS485 transceiver correctly
  node.preTransmission(preTransmission);
  node.postTransmission(postTransmission);
}

void loop()
{
  float result;

  result = node.readInputRegisters(0x30000, 10);
  if (result == node.ku8MBSuccess)
  {

    Serial.print("V1N: ");
    Serial.println(node.getResponseBuffer(0x01));

    Serial.print("V2N: ");
    Serial.println(node.getResponseBuffer(0x02));

    Serial.print("V3N: ");
    Serial.println(node.getResponseBuffer(0x03));

    Serial.print("Vavg: ");
    Serial.println(node.getResponseBuffer(0x04));

    Serial.print("V12: ");
    Serial.println(node.getResponseBuffer(0x05));

    Serial.print("V23: ");
    Serial.println(node.getResponseBuffer(0x06));

    Serial.print("V31: ");
    Serial.println(node.getResponseBuffer(0x07));

    Serial.print("L-L avg: ");
    Serial.println(node.getResponseBuffer(0x08));
  }
  delay(1000);
}

C++ programming question ... not Arduino specific really

decimal format and floating point format are two different things ... what do you actually need?

@jsotola i just need the output displayed in the serial monitor to be in voltage and other parameter readings as given on the data sheet.

Re “data structure seems to be in decimal format”: It's not. It's binary. The reason you see decimal on the serial console is because Serial.println() converts its argument to decimal, for the purpose of printing it as text. The authors of this method assumed that most humans prefer reading decimal rather than binary. Note that Serial.println() can be told (by a second argument) to use a different base.

I'm not sure this can really be considered topical, but someone wanting to read floating point numbers over MODBUS with an Arduino might get something out of it.  Also I have no way to test this really.  But here goes:
Your MODBUS map shows V2N at 30002, and you notice 30003 is not mentioned in the map.  Your voltage from phase two to neutral appears to be encoded into two consecutive 16-bit registers, which is a somewhat normal scheme for conveying 32bit floats via MODBUS, from what I can tell.  So, your values of 17280 and 9830 are two halves of a 32-bit floating point number.  In hex, 0x4380 and 0x2666.  These seem to be taken together as 0x43802666 as the bit pattern for 32-bit float.
A function like this would allow you to extract your 32-bit float data from your separate 16-bit MODBUS register reads:
float modbus_16bit_register_pair_to_float(uint16_t a, uint16_t b) {
    uint32_t combined = ((uint32_t)a << 16) | b;
    float f;
    memcpy(&f, &combined, sizeof f);
    return f;
}

There are lots of ways you could do this.  This code assumes that the float type's endian matches the uint32_t type's endian, and that float is 32-bit, which is common but not strictly standard.
Running this on 17280 and 9830 gives 256.3 (rounded), which doesn't perfectly match other output, but I suspect that's just because the reading is varying.

Thank You Sir. it worked.


text:
How to gradually increase and decrease the speed of a motor using IR remote
I am making an IR controlled helicopter and I have the very basic part of the code done, but I don't know how to make the motor gradually increase speed. I want the motor to gradually increase speed when you hold the button on the IR remote and hold its speed when you stop pushing the button. And the same for when the helicopter goes down.
Here is the code:
   #include <IRremote.h>
   #include <Servo.h>
   #define enA 9
   #define enB 11
   #define in1 6
   #define in2 7
   #define in3 4
   #define in4 5

   Servo ball1;

   int IR_RECEIVE_PIN = 2;
   IRrecv IrReceiver(IR_RECEIVE_PIN);
   decode_results results;

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

     ball1.attach(10);

     pinMode(in1, OUTPUT);
     pinMode(in2, OUTPUT);
     pinMode(in3, OUTPUT);
     pinMode(in4, OUTPUT);
   }
   void loop() {
     if (IrReceiver.decode(&results)) {
       switch (results.value) {

         case 0xFFA857:
           Serial.println("case: UP");
           digitalWrite(enA, 255);
           digitalWrite(in1, HIGH);
           digitalWrite(in2, LOW);
           break;

         case 0xFFE01F:
           Serial.println("case: DOWN");
           digitalWrite(enA, 120);
           digitalWrite(in1, LOW);
           digitalWrite(in2, LOW);
           break;

         case 0xFF18E7:
           Serial.println("case: FORWARD");
           ball1.write(90);
           break;

         case 0xFF10EF:
           Serial.println("case: LEFT");
           digitalWrite(in3, LOW);
           digitalWrite(in4, LOW);
           break;

         case 0xFF5AA5:
           Serial.println("case: RIGHT");
           digitalWrite(in3, HIGH);
           digitalWrite(in4, LOW);
           break;

         case 0xFF48B5:
           Serial.println("case: BACKWARD");
           ball1.write( ? ); // I need help on the direction of the linear servo
           break;
       }

       Serial.println(results.value, HEX);
       IrReceiver.resume();
     }
   }

It is the same code I used to control a RGB LED (But modified). Would it be possible to upload this code to an IC? I already programmed my UNO as an ISP, but there seems to be a problem. Also, I am using a linear servo for the pitch of the helicopter, can someone please show me how to change the direction of a linear servo? I have one that is similar to the Pico linear servo.

Should each case statement have a matching break statement?

Yes, I removed them when I was trying something, but I added them back now... Thanks!

Properly indenting your code would make it much easier to follow.

Okay, I indented it...

Every time you receive an "up" code increase the speed. Every time you receive a "down" code decrease the speed. IR doesn't (usually) have a concept of "press" and "release", only "press" and it sends the code repeatedly while it's pressed.

Mhh, normally you don't see IR controlled flight models, because it is too unreliable and it won't work in direct sunlight (because the IR light from the sun already saturates the sensor, so that it cannot see the signal from the sender). Are you sure, that you want to use IR? A good RF sender and receiver (like in other flight models) are nornally way better

Hi chrisl, thank you! I will see if I can get an RF sender and receiver... I used IR because it is all I have now, but I will look into your idea. Thanks again!

You could separate reading the controls and taking actions and there are several ways of doing that, one example shown below where the switch() can be used to read all commands and according to the value call one or more atomic functions. For instance, one function to change speed and another one to change direction, and perhaps calling several functions in a row for more complex tasks like take off and land (I have no idea how those helicopter projects works).
On each case you do the validation, min and max allowed values, dependencies on other factors and alike.
void loop() {

  if (IrReceiver.decode(&results)) {

    switch (results.value) {

      case 0xFFA857: // up
        verticalSpeed = verticalSpeed + verticalSpeedStep;
        if (verticalSpeed > maxVerticalSpeed) verticalSpeed = maxVerticalSpeed;
        setVericalMotor();
        break;

      case 0xFFE01F: //down
        verticalSpeed = verticalSpeed - verticalSpeedStep;
        if (verticalSpeed < 0) verticalSpeed = 0;
        setVericalMotor();
        break;

    }
  }
}

void setVericalMotor() {
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(enA, verticalSpeed);
}

As for your question regarding the servo, they usually run from 0 to 180 degrees, so tey anything in that range as the "reverse" for 90 degrees for Forward (normally that should be 0 or 180).

Thank you for the help!!

I have not worked with verticalSpeed before, and the compiler says it is not declared in a scope along with verticalSpeedStep, and maxVerticalSpeed... Could you please help me?

The code I showed you is not a complete program, just an idea how to design your program and as part of it you have to declare the variables.  As you are new to programming I suggest you follow one of the many getting started with Arduino tutorials you can find on arduino.cc and many other websites.

Okay, thank you!

source: Stack Exchange

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

sort: votes


text:
How to convert a String to Hex array
I am trying use a HMI display. If I want to send a data, for example I want to write "TOPWAY" to 0x00000080 address it should like that:
    Serial.write(0xaa); // packet head
    Serial.write(0x42); // VP_N16 string write command
    Serial.write(0x00); // VP_N16 address
    Serial.write(0x00);
    Serial.write(0x00);
    Serial.write(0x80);
    Serial.write(0x54); //T
    Serial.write(0x4f); //O
    Serial.write(0x50); //P
    Serial.write(0x57); //W
    Serial.write(0x41); //A
    Serial.write(0x59); //Y
    Serial.write(0x00); //string end with "\0"
    Serial.write(0xcc); // packet tail
    Serial.write(0x33); // packet tail
    Serial.write(0xc3); // packet tail
    Serial.write(0x3c); // packet tail

I want to make a method like SendString(String abc) to send that like above. I need convert string a hex array and call in Serial.write(array[i]). Can you hep me?

There is no such thing as a hex array. Everything is all just numbers. Even letters are numbers. Your string is already an array.

Serial.print("TOPWAY"); should do it

@Juraj you mean like that for total query like above: Serial.write(0xaa);
Serial.write(0x42);
Serial.write(0x00);     Serial.write(0x00);
Serial.write(0x00);
Serial.write(0x80); Serial.print("TOPWAY"); Serial.write(0x00); //string end with "\0"
Serial.write(0xcc);
Serial.write(0x33);
Serial.write(0xc3);
Serial.write(0x3c); . if Not? please show me as answer not in comment.

the answer is below

I don't know anything about the particular display, but based on the information provided I hope this is at least shows the foundation of one way you could approach a final solution.
Update:

Incorporated great improvements and a fix from Edgar in the comments.
String overload.
Display baud rate suggested by mehmet

#define DISPLAY_DEVICE Serial
#define DISPLAY_DEVICE_BAUD 9600

static uint8_t displayPktStart[] = {
    0xaa, // packet headchar
    0x42, // VP_N16 string write command
    0x00, // VP_N16 address
    0x00, // ...Fill
    0x00,
    0x80
  };

static uint8_t displayPktEnd[] = {
    0x00, // End of text
    0xcc, // packet tail
    0x33, // packet tail
    0xc3, // packet tail
    0x3c // packet tail
  };

void writeDisplay(const char* text)
{
  // Write packet headers
  DISPLAY_DEVICE.write(displayPktStart, sizeof displayPktStart);

  // Send text
  DISPLAY_DEVICE.print(text);

  // Write packet tail
  DISPLAY_DEVICE.write(displayPktEnd, sizeof displayPktEnd);
}

void writeDisplay(const String& text)
{
  writeDisplay(text.c_str());
}

void setup()
{
  DISPLAY_DEVICE.begin(DISPLAY_DEVICE_BAUD);
}

void loop()
{
  String msg = "TOPWAY";
  writeDisplay(msg);

  delay(2000);
  writeDisplay("Peanuts taste like chicken");
  delay(500);
  writeDisplay("");
  delay(1000);
  writeDisplay("No. Seriously");
  delay(2000);
}

Instead of writing a loop, you can DISPLAY_DEVICE.write(displayPktStart, sizeof displayPktStart);, and likewise for displayPktEnd. 2. You mean DISPLAY_DEVICE.print(text);, not println(). 3. Serial.print() will not send the terminating \0, you may want to add that to displayPktEnd.

@EdgarBonet Thanks. Updated.

Thanks A lot. I've added DISPLAY_DEVICE.begin(9600); in setup

@mehmet I hope my update matches your expectations.

@voidPointer well, I don't want to bother you too much, but I have one more question. if I want to use dynamic address, such as "000080" instead of     Serial.write(0x00);
Serial.write(0x00);
Serial.write(0x80); how to add this method, like writeDisplay(msg, "000080");

@mehmet Remove the address from displayPktStart, add uint32_t parameter to both writeDisplay and send it after directly after DISPLAY_DEVICE.write(displayPktStart,...

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


text:
How to Burn Bootloader with custom Fuses
I have a Atmega328p IC without external Crystal (My target).
When I use a arduino to burn the bootloader to my target, the Arduino as ISP sketch changes the fuses of my target, so it tries to use its external crystal, which is not connected, So it cannot proceed the bootloader burn.

How can I modify the Fuse settings while Burning bootloader with arduino?

You need to either adjust the current board fuse settings in boards.txt or create a new board variant that matches your settings.
For example the Uno is set up with:
uno.bootloader.tool=avrdude
uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0xFD
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F
uno.bootloader.file=optiboot/optiboot_atmega328.hex

and after changing this file, I needed to re-start the arduino.exe, thank you!

You can use MiniCore boards support package for Arduino IDE to work with nonstandard AVR boards or breadboard setups. This core has many settings in Tools menu to set different parameters of the board.


text:
L298N motor controller board EN pins

For this device are the enable pins meant to be connected to PWM pins?
If so then how am I able to use this device with an arduino uno?
The uno does not have any pwm pins right?

the pins with ~. https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

The uno pins are 3, 5, 6, 9, 10, 11.
See https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/
Usage:
analogWrite(pin, value);

The people over at How to Mechatronics have a great introduction to this board and using it with an Arduino Uno.
The enable pins are for turning the motors on and off. See the table for the different settings.  But the EN pin is also used for controlling the motor speed.
PWM is used to adjust the speed the motors turn at. Rather than simply turning the enable pin fully “on” (i.e, full speed), PWM is used to adjust the voltage and thereby control the speed the motors turn.
So the short answer is yes, you can connect a PWM signal to the EN pins.  Yes a UNO can produce PWM (as answered by others)


text:
L298 motor controller board

Hello I have 2 questions:
A) do I have to remove any of the plastic casings that I have highlighted in order to make the motors move.
B) What is the purpose of the black plastic casing that I have pointed out?

Remove black casings? The jumper by the Vin and M1 headers is to control the on-board circuitry power—when enabled the on-board circuitry uses the 12V max Vin through a voltage regulator to run the 5V components, when disabled you need to supply a 5V source. The “black cases" on the left and right are protection diodes; if they’re removed bad things happen.

A) do I have to remove any of the plastic casings that I have highlighted in order to make the motors move.

Those aren't "casings", those are diodes. They are part of the circuit and must be left alone.

B) What is the purpose of the black plastic casing that I have pointed out?

That is a "jumper" and is used to connect the +5V pin to the internal 5V regulator so the board can be run from just the 12V input power supply. Remove that if, and only if, you want to supply 5V to the board separately from elsewhere.


text:
AW9523B I2C on Arduino Nano
I'm testing the AW9523B IO expander with an Arduino Nano. I can't get the device to be recognized.
Using I2C scanner to find all attached I2C devices.
I've connected AW9523B to the correct pins to the SDA/SCL pints of the Arduino, with 5K pullups. INTN is connected to GND.
An EEPROM is also connected on the bus. The EEPROM is recognized on the bus. I swapped the SDA/SCL pins just to make sure, and still AW9523B was not found on bus.
I've tried changing the AD0 and AD1 pins to no avail.
I have a 22uf capacitor on the VCC.
Changing the AD0 pin does change the default state of a connected LED, so I'm fairly confident the chip is not dead.
I've also tried the two example sketches from:

https://github.com/mrmx/AW9523B

Curious if anyone has gotten their AW9523B to work.

Updated Working Schematic

It sounds like you got to many resistors connected maybe where they should not. The chip works fine if installed properly. Post a schematic of how you have it wired, including links to the technical information on the parts you are using. I looked up the part and is is straightforward, Look at the data sheet, Typical Application 1: Drive 16 function LED, including 6 ports feasible for LED backlight your circuit should look like that. Examine that application.

Tried removing all the resistors other than the I2C pullups, no help. Updated with schematic.

How did they connect the LED on the data sheet?

The device can be either open-drain or push-pull, depending on configuration register, and/or the AD1 and AD0 settings. Either way, it shouldn't impact if the device is found on the I2S bus.

Connect RSTN to +5V with a 10K pullup resistor.

Thanks @Majenko I had not read the datasheet carefully enough! I saw it had a pull down resistor, figured that would be default non-reset state. Upon further reading, yes, low = reset. Why they put it in a default reset state is strange to me, but I'm not engineer.  None of the datasheet schematics have that pin pulled or set high...

Transcribing and adding to the answer from the comments.
The AW9523B has a reset (RSTN) pin 23 which is internally pulled low by a 100K ohm resistor (i.e., default = reset). @Majenko suggests attaching a pull-up 10K ohm resistor to +5V (i.e., not reset) to enable the chip.
The data sheet schematics and section describing the reset function (pg14) seem to anticipate the RSTN pin being connected to an MCU GPO pin used to dynamically control the reset function.


text:
Programming ATTiny1614; Unexpected Signature
Trying to program an ATTTYIN1614 with jtag2updi.
https://github.com/ElTangas/jtag2updi

I was able to use this tool to program an ATTINY1626-XFR and ATTINY807-MNR, but I'm getting an error with ATTINY1614-SSFR.
avrdude: Expected signature for ATtiny1614 is 1E 94 22
         Double check chip, or use -F to override this check.

If you want to make the answer follow more from the question, the part of the avrdude output listing that shows the signature that was actual read would be helpful.

@EdHayes3 if you do not indent the URL, then it becomes clickable ... indented lines are formatted as code

I had the wrong ATTiny1614 selected. Needed to select the non-optiboot option.


text:
How do you get 2 PWM pins to inversely bitbang at 25 KHz on a Nano?
I need 2 PWM pins to oscillate at 25 KHz but they need to oscillate inverse to each other.  When one is high, the other must be low and vise-versa.
I want to do this with a Nano.

use one pin and invert it using hardware

Use two timers with the same settings, started simulaneously.

@towe: How do you start them simultaneously?

@EdgarBonet Set their Clock Select right after each other, that should only be a couple clock cycles of difference.

There are various solutions. I suggest using two PWM channels driven by
a single timer. This way you do not have to worry about synchronizing
two timers. You can configure the channels identically, except that one
of them would be in “non-inverting” PWM mode, while the other one would
be in “inverting” mode.
Here is how I would do it: use Timer 1 to drive pins 9 (PB1, OC1A) and
10 (PB2, OC1B) in fast PWM.
void setup() {
    // Configure Timer 1 for complementary PWM @ 25 kHz.
    DDRB  |= _BV(PB1);    // set pin 9 = PB1 = OC1A as output
    DDRB  |= _BV(PB2);    // set pin 10 = PB2 = OC1B as output
    TCCR1A = 0;           // undo the Arduino timer initialization
    TCCR1B = 0;           // ditto
    ICR1   = 640 - 1;     // period = 640 CPU cycles = 40 us
    OCR1A  = 320 - 1;     // OC1A HIGH for 320 CPU cycles = 20 us
    OCR1B  = 320 - 1;     // OC1B LOW for 320 CPU cycles = 20 us
    TCCR1A = _BV(COM1A1)  // non-inverting PWM on OC1A
           | _BV(COM1B0)  // inverting PWM on OC1B
           | _BV(COM1B1)  // ditto
           | _BV(WGM11);  // fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS10);   // clock at F_CPU
}

Ah, that's what I had in mind first, but I was irritated by the second Compare Output Mode behaving different for OC1A and OC1B and thought they were fixed to each other. +1

This works perfectly.  I could not have asked for a more simple and precise solution !!!


text:
Using the touchscreen.getpoint causes program to instantly crash
this code runs fine until I add in the if statement surrounding the draw screen() method. upon clicking the screen, the program instantly crashes, turning the screen white. any help would be appreciated.
"
// IMPORTANT: Adafruit_TFTLCD LIBRARY MUST BE SPECIFICALLY
// CONFIGURED FOR EITHER THE TFT SHIELD OR THE BREAKOUT BOARD.
// SEE RELEVANT COMMENTS IN Adafruit_TFTLCD.h FOR SETUP.

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_TFTLCD.h> // Hardware-specific library

#include <stdint.h>
#include "TouchScreen.h"
#define YP A2  // must be an analog pin, use "An" notation!
#define XM A3  // must be an analog pin, use "An" notation!
#define YM 8   // can be a digital pin
#define XP 9   // can be a digital pin

// The control pins for the LCD can be assigned to any digital or
// analog pins...but we'll use the analog pins as this allows us to
// double up the pins with the touch screen (see the TFT paint example).
#define LCD_CS A3 // Chip Select goes to Analog 3
#define LCD_CD A2 // Command/Data goes to Analog 2
#define LCD_WR A1 // LCD Write goes to Analog 1
#define LCD_RD A0 // LCD Read goes to Analog 0

#define LCD_RESET A4 // Can alternately just connect to Arduino's reset pin

// When using the BREAKOUT BOARD only, use these 8 data lines to the LCD:
// For the Arduino Uno, Duemilanove, Diecimila, etc.:
//   D0 connects to digital pin 8  (Notice these are
//   D1 connects to digital pin 9   NOT in order!)
//   D2 connects to digital pin 2
//   D3 connects to digital pin 3
//   D4 connects to digital pin 4
//   D5 connects to digital pin 5
//   D6 connects to digital pin 6
//   D7 connects to digital pin 7
// For the Arduino Mega, use digital pins 22 through 29
// (on the 2-row header at the end of the board).

// Assign human-readable names to some common 16-bit color values:
#define  BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);
// If using the shield, all control and data lines are fixed, and
// a simpler declaration can optionally be used:
// Adafruit_TFTLCD tft;
int six;
int hundred;
int twenty;
int ten;
int four;
int eight;
int two;
int twelve;
TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);
void setup()
{
  Serial.begin(9600);
  Serial.println(F("TFT LCD test"));
  tft.reset();
  uint16_t identifier = tft.readID();

  tft.begin(identifier);
  tft.fillScreen(BLACK);

  six = random(1, 6);
  eight = random(1, 8);
  twenty = random(1, 20);
  hundred = random(1, 100);
  four = random(1, 4);
  ten = random(1, 10);
  two = random(1, 2);
  twelve = random(1, 12);

  tft.setTextColor(WHITE);  tft.setTextSize(4);
  drawNumbers();

}

void loop() {

  six = random(1, 6);
  eight = random(1, 8);
  twenty = random(1, 20);
  hundred = random(1, 100);
  four = random(1, 4);
  ten = random(1, 10);
  two = random(1, 2);
  twelve = random(1, 12);
  if (ts.getPoint().z != 0) {
    drawNumbers();
  }

}

void drawNumbers() {
  tft.setCursor(0, 0);
  tft.fillScreen(BLACK);
  tft.println("D2: " + String(two));
  tft.println("D4: " + String(four));
  tft.println("D6: " + String(six));
  tft.println("D8: " + String(eight));
  tft.println("D10: " + String(ten));
  tft.println("D12: " + String(twelve));
  tft.println("D20: " + String(twenty));
  tft.println("D100: " + String(hundred));

}"

this library seems largely ill documented, but this seems egreigous if its not on my end.

how can you possibly know that the program crashed?

Welcome to SE/Arduino! Please take the [tour] to learn how this site works. -- Check what ts.getpoint() returns. -- As it seems, the "Touchscreen" module is some local library. Would you mind to provide a link, please? [Edit] your question, don't add a comment.

Updated:

Provided info not revelant.

I would approach the problem like this. What if anything is returned by getPoint.
  if (ts.getPoint().z != 0) {
    drawNumbers();
  }

To
  auto pt = ts.getPoint().z;
  Serial.print("Point: ");
  Serial.println(pt);

  if (pt != 0) {
    drawNumbers();
  }

This would tell me if I am getting a value back or if it is a problem elsewhere.
Hope this helps.

hi, first of all, thanks for replying.
That method itself doesn't seem to be the issue, it'll run fine on its own. The issue is when the if statement and the touchscreen getpoint method is invoked the program crashes. I am able to print using that method without issue.

Ignore my original answer. After some extra testing the String class now now supports your use. I shall instead add a tip.

@cptcrabcakes Sorry, I think my original answer was not upto date. I have amended.

The serial monitor is reporting point data back, which makes me think this isnt a true crash, just the graphics library freaking out.

@cptcrabcakes You may get better quaility help if you can provide info such as the platform you are using like Uno, Nano etc, and details of the screen in the question.

Someone marked the answer down as not useful despite the fact it helped diagnose the error was elewhere? Ok.

Figured it out
the TFT screen im using forces the sharing of pins being used for analog and digital together. By starting my draw method with pinMode() i set the pins to be treated as the touchscreen's
void drawNumbers() {
    pinMode (XM, OUTPUT);
  pinMode (YP, OUTPUT);
  tft.setCursor(0, 0);
  tft.fillScreen(BLACK);
  tft.println("D2: " + String(two));
  tft.println("D4: " + String(four));
  tft.println("D6: " + String(six));
  tft.println("D8: " + String(eight));
  tft.println("D10: " + String(ten));
  tft.println("D12: " + String(twelve));
  tft.println("D20: " + String(twenty));
  tft.println("D100: " + String(hundred));

}


text:
NodeMCU ESP32 as a replacement for my arduino project
I would just like to ask if this microcontroller can power or can manage 2 servos, 2 motors, and 2 hc-sr04 ultrasonic distance sensor combined? Also, does this board come with a bluetooth module?

Thanks for the answer @StarCat but how would I do the "logic level translation"?

Easiest would be to use the little 4-channel bidirectional level converters. Sometimes a simple voltage divider made out of two resistors would be enough (5V output to 3.3V input) and some 5V peripherals are 3.3V tolerant.

thank you so much @StarCat

The ESP32 has more than enough free GPIOs to manage those peripherals. Also, the ESP32 does indeed come with a bluetooth module.
Your question about powering these peripherals very much depends on their power requirements. I would not count on being able to run motors or servos from the internal power supply of a NodeMCU board, so you would need an external supply.
Also, note that the ESP32 is a 3.3V device and might require logic level translation if you’re using 5V peripherals.


text:
MC33926 Brushed Motor Driver (Shield/Carrier)
How can I use a MC33926 Motor Driver like it is offered for Arduino to drive forwards, backwards with a PWM and a direction control.
The problem is that the MC33926 has Inputs IN1 and IN2 and not PWM and DIR as usual. How can IN1 and IN2 be directly used with a Arduino. Such as it is done in the ArduMower project.
I'm also wondering under which conditions this is controller is energy efficient? If the load has a flywheel effect (e.g. high RPM mower disk) reducing RPM would waste energy?
I know there are different shields that have logic to drive the inputs with PWM and DIR, but the ArduMower PCB 1.4 decided to hook it up directly. Here is a hardware solution by pololu (I wish i would understand these two NAND gates and the Q2, but that's another problem):

https://www.pololu.com/product/1213/pictures

I have figured this so far:

If the PWM frequency is too low, the load-free power consumption (100% PWM 200mA) of the
motors increases(!) rapidly when driving slowly, e.g. 33% to 1A.
From a certain PWM frequency (>2kHz), the power consumption normalizes and driving more slowly requires less power.
MC33936 has IN1 and IN2, which are normally connected with IN1 = LOW and
IN2 = PWM or IN1 = PWM and IN2 = LOW (not good for most MCs)
Alternatively you can use IN1 = PWM and IN2 = LOW / HIGH BUT you must INVERT the PWM SIGNAL when running reverse, i.e. IN1 = PWM and IN2 = LOW or reverse IN1 = ~PWM (inverted PWM) and IN2 = HIGH. Otherwise you start driving at 0 PWM with 100% motor power. This is quite tricky, too.
MC33936 has no freewheel (except if ENABLE = LOW) and brakes the
motor to 0 when IN1 = IN2
MC33936 is a braking motor controller that actively sets the output RPM.
of the motor according to PWM.


text:
Printing the array using print and serial write function in Arduino Uno
I have, one program with only using printing array and other with serial write and print function for the array, while using serial write and print function I get these extra characters between the data as shown below, can anyone help me with this
Printing the array with print function
uint8_t a[13] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0X77, 0x88,
                 0x01, 0x02, 0x03, 0x04, 0x05};
int i;

void Print_Hexa(uint8_t num) {
  char Hex_Array[2];

  sprintf(Hex_Array, "%02X", num);
  Serial.print(Hex_Array);
}

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

void loop() {
  for (i = 0; i <= 12; i++) {
    //Serial.write(a[i]);
    Print_Hexa(a[i]);
  }
  Serial.println();
  delay(100);
}

Using with serial write and print function for array
uint8_t a[13] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0X77, 0x88,
                 0x01, 0x02, 0x03, 0x04, 0x05};
int i;

void Print_Hexa(uint8_t num) {
  char Hex_Array[2];

  sprintf(Hex_Array, "%02X", num);
  Serial.print(Hex_Array);
}

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

void loop() {
  for (i = 0; i <= 12; i++) {
    Serial.write(a[i]);
    Print_Hexa(a[i]);
  }
  Serial.println();
  delay(100);
}

Serial.write(a[i]); sends a character but not all values are readable characters

To prevent buffer overruns, use snprintf(Hex_Array, sizeof(Hex_Array), "%02X", num);. More info here and here. Also be aware that the Arduino versions don't support the %f format specifier.

Serial.write(some_byte) writes a byte on the serial output. The
Arduino serial monitor tries to interpret the bytes it receives as text:

0x11 is a control character, displayed as “□”
0x22 is the ASCII code for the double quote (")
0x33 is the ASCII code for the digit 3.
0x44 is the ASCII code for the uppercase letter “D”
etc.

Is it possible to remove them or mask them if possible

@voticoy: Sure! Remove the Serial.write() statement.

To store a 2 character string you need a 3 byte array, not a 2 byte array. This is because in C a string consists of the actual string data and a zero ("NULL") byte at the end to indicate where the end of the string is.
So you would need:
char Hex_Array[3];

so it can store, for the number 0x69: 69\0. Otherwise you overrun the array and corrupt other data that follows in the stack, and changing that other data corrupts your string by changing the "end of string" marker to some other random ASCII character.

Thank you for the response, I changed the array size to 3 as mentioned, still in the serial monitor output remains the same.


text:
Nikon IR remote trigger (ML-L3) emulator not working
I have tried to follow along/reproduce the results from several sources for emulating the Nikon infrared remote trigger:

Adafruit Guide
DIY Nikon ML-L3 IR Wireless Remote Hack with Arduino UNO
Teardown and Project: Clone Nikon ML-L3 IR Remote and Emulation
Teach you how to DIY Nikon ML-L3 infrared remote control did not read yet
Arduino wireless remote for Nikon DSLR
Arduino Nikon Infrared command code
Arduino – IR remote/ intervalometer for Nikon D80 DSLR

I can read the signal from my remote trigger, but I cannot reproduce it with my Arduino setup. The signal I can receive (w/ TSOP38238 receiver diode) matches all of the signals given by the links above (there is some expected variance in pulse durations).
I don't think my hardware is at fault:

TSOP38238 receives @ 950 nm
my IR LED is 940-950 nm per datasheet
my IR LED works (I can see it emitting when I point it at my phone camera)

simulate this circuit – Schematic created using CircuitLab
My Code:
I have tried the code given in the links above, most don't use Port Manipulation and instead trial-and-error the delay durations to account for the overhead in Arduino functions. I have experimented with different values of the wait variable (8-13 microseconds) but have not gotten it working so far. I prefer to have my code versatile like this (no hard coded durations) so I can use it with other remotes in the future.
uint16_t Signal[] = [2050, 27800, 430, 1650, 430, 3650, 430, 65000]; // ON & OFF pulse durations (microseconds)
uint8_t wait = 13; // duration (microseconds) between pin state changes

// the setup function runs once when you press reset or power the board
void setup() {
    DDRB = B00000001; // set digital pin 8 to output
    PORTB = B00000000; // set digital pin 8 LOW
    Serial.begin(9600); // start serial monitor
}

// the loop function runs over and over again forever
void loop() {
    delay(1500); // wait a bit between sending signal
    sendSignal();
    sendSignal();
    // send signal twice, this is what the actual remote does
    Serial.println("Signal sent"); // message saying signal was sent
}

// function that sends the signal
void sendSignal(void) {
    for (int i = 0; i < sizeof(Signal)/sizeof(Signal[0]); i++) { // for each element in Signal array
        if (i%2 > 0) { // odd numbered index, is an OFF pulse
            PORTB = B00000000; // set digital pin 8 LOW
            delayMicroseconds(Signal[i]); // delay for OFF pulse duration
        } else { // even numbered index (including i=0), is an ON pulse, 38 kHz (26.3 usec period), 50% duty cycle
            unsigned long currentTime = micros(); // get current time
            while (micros() - currentTime < (unsigned long)Signal[i]) { // while still in ON pulse duration
                PORTB = B00000001; // set digital pin 8 HIGH
                delayMicroseconds(wait); // leave ON for time
                PORTB = B00000000; // set digital pin 8 LOW
                delayMicroseconds(wait); // leave OFF for time
            }
        }
    }
}

I hold my camera in direct line of sight of the LED (not blocking the receiver on the camera) from distances of ~2in to ~3ft away without success.
Has anyone tried this before? Is there a mistake in my approach or code?

generating an 38kHz signal with delayMicroseconds doesn't result in a very accurate frequency. It's probably lower due to the while loop taking some time to execute. The code provided in you second to last link actually uses 7µs of delay, and uses a simpler for-loop. It also uses a 810µs delay after the first pulse, where your code uses 27800µs

@Gerben That link uses delay(27) and delayMicroseconds(810) for a total delay of 27810 microseconds. It also uses digitalWrite instead of port manipulation which is slower.

But the delayMicroseconds documentation does say "the largest value that will produce an accurate delay is 16383" so I will try to combine delay w/ delayMicroseconds like that link does.

one if the links you posted includes code ... why are you not using it?

@jsotola none of the provided code worked for me

Got it working. The problems were the delayMicroseconds input being too large (see comments) and the frequency mismatches.
I set up a script to time the code segments of interest and that allowed me to select the best wait duration. It looks like this:
while (i < 256) {
    /* your code to time here */
    i++;
}
i = 0;
unsigned long time = 10000000 + micros();
Serial.println(time);

Make sure to time the empty loop and subtract that from your readings w/ code. Take the difference between time read outs, subtract the printing statement overhead (which is dependent on how many digits it is printing, hence the 10000000 + micros() to keep # of digits constant) and divide by 256.
I measured 4 different combinations to find the closest frequency match:

Command Type:
Wait duration (micro seconds):
Frequency (Hz):
% difference from 38 kHz

Port Manipulation
14
36990
-2.7 %

Port Manipulation
13
39960
5.2 %

digitalWrite
11
35980
-5.3 %

digitalWrite
10
38790
2.1 %

The final code ended up looking a lot like the one from this link; counting off cycles of the on-off 38 kHz pulse.


text:
Error using `NtpClientLib.h`
Since Core of ESP8266 upgraded to v.3.0 (now it is 3.0.2), I encounter errors using this library.
First, the deprecation of byte to uint8 (hoped that an upgrade of NTP lib to 3.0.2 beta will solve it ), but now even using library's built in example file fails, show the same message regarding byte error.
Is there a workaround ?
In file included from /home/guy/Documents/git/Arduino/libraries/NtpClientLib/examples/NTPClientESP8266/NTPClientESP8266.ino:38:
/home/guy/Documents/git/Arduino/libraries/NtpClientLib/src/NtpClientLib.h:501:32: error: reference to 'byte' is ambiguous
  501 |     bool summertime (int year, byte month, byte day, byte hour, byte weekday, byte tzHours);
      |                                ^~~~
In file included from /home/guy/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/xtensa-lx106-elf/include/c++/10.3.0/cmath:42,
                 from /home/guy/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/xtensa-lx106-elf/include/c++/10.3.0/math.h:36,
                 from /home/guy/.arduino15/packages/esp8266/hardware/esp8266/3.0.2/cores/esp8266/Arduino.h:34,
                 from sketch/NTPClientESP8266.ino.cpp:1:

EDIT 1 :: VERSIONS

I just compiled that example fine no problem with 3.0.2. Maybe there's something broken about your Arduino / ESP8266 installation.

Or maybe your libraries are out of date...?

@Majenko - see installed version, IDE, and Example sktech fails

Don't use the library manager to install libraries. Download it direct from Github. You can pretty much guarantee that whatever is in the library manager will be out of date.

@Majenko - Amazing!! You were right. I delted all NTPClient libraries, and reinstalled only from github... and its OK now. Thnk you

The esp8266 Arduino 3 has breaking changes so library authors need to adjust their libraries to this changes. Check the repository of the library for the fixes.
The NtpClient library was marked as deprecated by the author. The reason was that there is a better way to work with NTP on ESP. Now the library was 'restarted' as an alternative to SDK functions because the author solved microseconds accuracy.
If you don't need microseconds accuracy, you don't need to use Arduino NtpClient library on esp8266 or esp32. The Espressif SDK have support to get the NTP time to internal RTC.
Both ESP Arduino cores have examples for NTP. For esp8266 it is the esp8266/NTP-TZ-DST example.
The NTP part should be in setup()
configTime(TIME_ZONE, "pool.ntp.org");

TIME_ZONE should be value from TZ_ constants from TZ.h, for example I have
#include <TZ.h>
#define TIME_ZONE TZ_Europe_Bratislava

The SDK will keep the time with the internal RTC of the ESP and adjust it periodically from NTP server.
You can get the esp8266 RTC time time with
time_t t = time(nullptr); // epoch
struct tm *tm = localtime(&t);
uint8_t minute = tm->tm_min;
uint8_t hour = tm->tm_hour;

if you want to wait in setup() until the time is retrieved you can use
  time_t now = time(nullptr);
  while (now < SECS_YR_2000) {
    delay(100);
    now = time(nullptr);
  }

Firstly, thank you very much. Second, is there a way to update daylight saving automatically ?

@Guy.D, it adjusts for day light saving time automatically. I built an alarm clock with esp8266 and these functions. https://github.com/jandrassy/SunriseClock

Tough your answer avoids the use of the library asked, but to mark it as an Answer, I need you to reff to Majenko's answer, that actually solved it.

@Guy.D, I updated the answer


text:
What is the correct way to externally power a MKR 1010 WiFi
I'm a little confused by the powering arrangements of the MKR 1010 WiFi. I need to power it on a breadboard from an external power supply. I will not be using a LiPo battery and I need it to work when the USB is disconnected.
Assuming there is no battery or USB connected, I think I need to apply power on the Vin pin (the pinout diagram on arduino.cc shows this as an input pin and 5V as an output pin). However, the 5V pin has a resettable fuse inline whereas Vin does not, which to me is counterintuitive.
So my questions are twofold:

What is the correct pin for supplying external power, and
What is the correct voltage to apply

https://store.arduino.cc/arduino-mkr-wifi-1010 see the FAQ section

@Juraj While that does at least in part answer the question, it might have been more in the spirit of Stack Exchange to copy that FAQ section into an answer. External links tend to rot over time and are not especially helpful.

What is the correct pin for supplying external power, and

VIN

What is the correct voltage to apply

The bq24195 can accept between 3.9V and 17V according to the datasheet. However the power LED on the board may blow if you apply more than about 12v since it only has a 330Ω resistor with it.

The polyfuse on 5V is there to protect the USB's power connection incase the user makes a mistake and short circuits it. It's more for the protection of your computer's USB port than the MKR board itself.


text:
Low Power, SD Card module and SCK
in order to minimise power consumption in a project using the Arduino Nano, I need to set pin D13 to HIGH after using it as SCK for transferring data to an SD card module (I use the SD.h module. I already read that there are issues, but trying SdFat.h somehow made the issue worse). The board is powered by 4*1.3 V batteries, which is within specifications of the chip. The onboard voltage regulator, the power LED and the built-in LED (connected to D13) are torn off the board.
So I power up the module via a MOSFET switch circuit, start the communication with SD.begin(SDChipSelect) and write something to the SD card. All of this works just fine. Afterwards, I call pinMode(SDCLK,OUTPUT); digitalWrite(SDCLK,HIGH); (where SDCLK == 13) before powering off the whole module by closing the MOSFET switch and going to deep sleep forever.
The switch setup (using an n-channel MOSFET) is such that the SD module's VCC is always HIGH, but no current can flow to ground, if the switch is off. Hence I need to turn D13 HIGH, not LOW, in order to turn off the module completely. Changing MISO, MOSI pins didn't affect anything, so I don't change them.
But... instead of drawing something like 0.1 mA without anything attached, the Arduino draws around 1 mA, which I can't afford. Apparently, the reason is that D13 doesn't care that I want it to go to HIGH. I can confirm this directly by measuring its voltage as well as by measuring the current drop if I pull off the connection between the SD module's SCK and the D13 pin on the Arduino. If I pull off the wires connecting MISO, MOSI or even the MOSFET itself, power consumption doesn't change.
That being said, power consumption is low, if I never write to the card (i.e. if I turn D13 high at in the setup, never power on anything, do not initialise the module via SD.begin(...), but go to deep sleep immediately).
What am I doing wrong? Do I somehow need to "end" the communication with the SD module, so I can turn D13 high or is there something special going on with this particular pin?
Here are the relevant parts of my code:
#include <LowPower.h>
#include <SD.h>

static const int GPSPower = 5;
static const int MP3Power = 2;
static const int SDPower  = 8;
static const int SDCLK    = 13;

void blink(int n) {
  for (int i=0; i<n; i++) {
    digitalWrite(9,HIGH);
    delay(50);
    digitalWrite(9,LOW);
    delay(200);
  }
  return;
}

void setup() {
  // this pin is used in 'blink' to power an LED for debugging
  pinMode(9,OUTPUT); digitalWrite(9,LOW);
  // Set all pins connected to MOSFET gates as low outputs.
  pinMode(MP3Power,OUTPUT); digitalWrite(MP3Power,LOW);
  pinMode(GPSPower,OUTPUT); digitalWrite(GPSPower,LOW);
  pinMode(SDPower,OUTPUT);  digitalWrite(SDPower,LOW);
  // this is D13
  pinMode(SDCLK,OUTPUT); digitalWrite(SDCLK,HIGH);

  // if false, power consumption stays at ~0.1 mA
  // if true, two strings are written and power consumption stays ~1.0 mA
  if (false) {
    String filename = "test.txt";
    write2sd("firststring",filename);
    write2sd("anotherstring",filename);
    blink(3); // feedback for debugging
  }

  // never go into loop
  while (true) {
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
  }
}

void loop() {
}

int write2sd(String data, String filename) {
  // power SD module
  digitalWrite(SDPower,HIGH);

  // check availability
  if (!SD.begin(SDChipSelect)) {
    // return early but power off the module first
    pinMode(SDCLK,OUTPUT); digitalWrite(SDCLK,HIGH);
    digitalWrite(SDPower,LOW);
    blink(10); // indicates an error
    return 1;
  }
  // SD Card should be initialised now
  File file = SD.open(filename, FILE_WRITE);

  // write to file
  if (file) {
    file.println(data);
    file.close();
  }

  // CLK still runs at this point and causes power consumption of ~1mA
  // power it off
  pinMode(SDCLK,OUTPUT); digitalWrite(SDCLK,HIGH);

  // turn off module power
  digitalWrite(SDPower,LOW);
  return 0;
}

You can't change the SPI pins, as long as SPI is enabled. In other words; digitalWrite(SDCLK,HIGH);   doesn't do anything.

Well I guess that explains it. Is it possible to disable SPI every time after writing?

Check out this article: https://thecavepearlproject.org/2017/05/21/switching-off-sd-cards-for-low-power-data-logging/

@Gerben, do you want to write a proper answer, which I can accept? Calling SPI.end() at the end of the routine before setting CLK, MISO and MOSI to HIGH afterwards actually works and my power consumption is down to 0.1 mA again :)


text:
ATTINY13A, Servo only makes half a sweep
I have been trying to get a servo to sweep using an attiny13A. And i managed to get the servo to (kindoff) work by the help of a previous thread. But i'm now getting an issue. The servo only goes to 180 degrees and does not return to 0 degrees, instead it just keeps trying to go further then 180 degrees eventhough its not mechanicly capabel of doing so. Anyone have any idea how i can solve this? ( I need it for a small animatronic part) (also the servo is a generic 9gram servo and i have tested it on multiple servos, its the same result) thanks in advance
#define F_CPU 9600000
int servo = PB1;  //connect servo to PB1
long angle;
int pwm;
int counter = 0;
int LED = PB3;
#include <avr/io.h>
void adc_setup (void)
{
    // Set the ADC input to PB2/ADC1
  ADMUX |= (1 << MUX0);
  ADMUX |= (1 << ADLAR);
  // Set the prescaler to clock/128 & enable ADC
  // At 9.6 MHz this is 75 kHz.
  ADCSRA |= (1 << ADPS1) | (1 << ADPS0) | (1 << ADEN);
}
int adc_read (void)
{
  // Start the conversion
  ADCSRA |= (1 << ADSC);
  // Wait for it to finish
  while (ADCSRA & (1 << ADSC));
  return ADCH; // return the value
}
void setup()
{
  pinMode(LED, OUTPUT);
  pinMode(servo, OUTPUT);  // set servo as output pin
  digitalWrite(LED, HIGH);
  delay(3000);
  pinMode(LED, LOW); //blink LED

}
void loop ()
{
 for(counter = 0; counter < 180; counter++)  //scan fril 0 degrees to 180 degrees
  {
    servoPulse(servo, counter);  // call the servoPulse function.
    delay(15);
  }

delay(1000);

 for(counter = 180; counter > 0; counter--)  // now scan back from 180 to 0 degrees
  {
    servoPulse(servo, counter);  // call the servoPulse function.
    delay(15);
 }
}
void servoPulse (int servo, int counter)
{
  pwm = (angle * 11) + 500;    // Convert angle to microseconds
  digitalWrite(servo, HIGH);
  delayMicroseconds(pwm);
  digitalWrite(servo, LOW);
  delay(50); // Refresh cycle of servo
}

I’m a little confused; servos require a pulse every 20ms (this depends on the servo; there’s a fair amount of variability) but you’re pulsing with a 65ms delay (delay in loop + delay in servoPulse) so my first guess would be the PWM signal is bogus—your overall pulse width is > 65ms, with the HIGHS signal a tiny fraction of that. I don’t see angle changed anywhere in the code, or initialized, and servoPulse ignores what I think you meant to use, counter.


text:
Arduino voltage misunderstanding
For arduino nano.
I set digital pins 1,2,3,4,5 to HIGH (I do this using digitalWrite(pin,HIGH) for each pin). Does this mean that 5V is being sent through each of the pins so in total there is 25V going out from the arduino?
How is this possible?

think about this ... connect five wires to the positive terminal of a 9 V battery ... is there 45 V on the wires?

i think that you are confusing voltage and current  ... voltage is like the pressure in the water pipes in your house ... it is the same at all of the water taps ... if you open taps in the kitchen and in the bathroom, the pressure at the taps is the same, it does not increase, but the amount of water flowing is double ... the water flow is like electric current

Voltage is a potential difference, like height. If you have five hills that are all 5m tall, you don't have a single 25m hill, you just have five places that are 5m tall.

Every pin gives you 5V on HIGH, yes, but these voltages don't add up.
Voltages are always measured between two points. In electronics we are defining one point in our circuit, that we use for all measurements, and call it ground. This is normally the negative pin of the power source.
Each pin has 5V in reference to the same ground, so they cannot add up (because that would mean the second 5V would be in reference to the 5V of the other pin, not in reference to ground). In the end they are connected in parallel to Vcc (where the power for the microcontroller is connected, in this case the 5V pin) of the Arduino (through the output drivers of the respective pin).
In the end this boils down to kirchoff's laws (if you want to research more about it). At a junction of connections, the voltage stays the same, but the current will be divided up between the connections.

Imagine that I have 5 flagpoles. I go to each of those flagpoles and raise a flag to a height of 2 meters. Since I have 5 flags, each at a height of 2 meters, does that mean that my flags have a total height of 10 meters?
Well, that question doesn't make a whole lot of sense, because "total height of the flags" isn't really a meaningful quantity. It's true that if you add up all the heights, you get 10 meters, but that number doesn't have any real meaning. Nothing in the system is 10 meters high.
Likewise, suppose you set 5 output pins all HIGH. Those output pins are just like flags on flagpoles, and you're raising each pin to a "height" of 5 volts. Nothing in the system is at a voltage of 25 volts; it doesn't make any sense to talk about a "total voltage."

If a private were tasked with climbing or polishing every flagpole, then yes, he would have to climb or polish a total of 10 meters of flagpole. But that's just a nuance of the analogy, your comment about voltage is correct.

It's a fascinating question. The Nano has 22 pins, all potentially set to output. D0 to D13, and A0 to A7.
So we have a total of 22 outputs. Now if they did add up then we could connect up a 5V battery and get 110V out of it! That might kill you! So clearly something is amiss here.
It's like when an employee has "20 years experience". Do they really have 20 times the experience they had in the first year, or do they have the same experience 20 times over?
The fact is that all 22 pins are all referenced to the same ground pin, so we really have 22 x 5V but all from the same starting point. So we really have 5V but with maybe a bit more current.
If you look at the datasheet, you don't even have 22 x the current you might have from one pin. The Atmega328P is specified to have a total of 200 mA current output.
Don't worry, setting all pins to output won't kill you. :)


text:
Arduino powered with 12v and interrupt noise
Hi i've a big problem with my project.
I realized a simple project with Arduino Uno: i've attached interrupt to pin 2 to read water flow.
If I power on Arduino from 5v usb all works as expected: my water counter (showed on an lcd) increase only if water pass trough the sensor flow.
But if poweron arduino with external 12v, the interrupt start immediately, also in no water passing trough sensor and also if i remove phisically the sensor from the circuit!!
Any suggest?
Flow sensor has 3 pins: vcc, gnd, data.
Data pin goes to pin 2 (interrupt), vcc to arduino 5v, and gnd with arduino gnd.

What flow sensor do you have exactly? And what 12V power supply?

@chrisl the flow meter is a yf-s201. But the sensor is not the problem, because the noise appear also if remove the sensor from my circuit. I use a power supply with output 12v/2.0A

Did you enable the internal pull-up on the Arduino? Are you using an external pull-up instead?

I ask because the sensor might need a pullup or pulldown resistor, which you don't currently use. A floating input pin (like when you disconnect the sensor without enabling the internal pullup) can change its state to whatever noise floats by, for example the noise from the 12V power supply. The example code that I found here enables the internal pullup resistor. Please do this via pinMode(pin, INPUT_PULLUP); , then report back if it worked

@itajackass you said that the interrupts occur when the sensor is not connected, so why are you even talking about the sensor?

@chrisl no luck. Setting it as INPUT_PULLUP instead INPUT, the problem of "noise" as gone.....but also the correct working is gone! The counter not increment, stay at 0, if I flow water inside sensor....

@itajackass Can you upload your code?

correct behavior disappearing from pullup could indicate bad sensor wiring as well.


text:
Arduino ESPTelnet.h library read data from cmd screen
I am new to Arduino. I used Arduino IDE for upload code to ESP8266 module. I wrote an ATM application on the tiva-tm4c123 board. I am trying to connect to the application from the internet using telnet and ip address. I uploaded the example code of the ESPtelnet library to the ESP8266 module and connected the esp wifi module to the tm4c123 card by using uart. The ESP8266 module sends the data from the tiva card to the putty screen that I connect via telnet. But it does not transfer what I write from the putty screen to the tiva card. I couldn't find a function like telnet.read(). Is there a telnet function that will read the data from the Putty screen? I searched a lot but couldn't find it. If I find this function, I know that I can send the read data to the tiva card with Serial.write(telnet.read).ESP's RX and TX are connected to the tiva card. I created a wireless connection to the Putty screen.  When a char or string is entered on the telnet screen, it will send it to the tiva card with Serial write from the TX of the ESP8266.I want to write a code that will run in the following logic.
 if (telnet.available()) {
    Serial.print(telnet.read());
  }

Here is the example code

#include "ESPTelnet.h"

/* ------------------------------------------------- */

#define SERIAL_SPEED    115200
#define WIFI_SSID       "****"
#define WIFI_PASSWORD   "****"

/* ------------------------------------------------- */

ESPTelnet telnet;
IPAddress ip;

/* ------------------------------------------------- */

void setupSerial(long speed, String msg = "") {
  Serial.begin(speed);
  while (!Serial) {
  }
  delay(200);
  Serial.println();
  Serial.println();
  if (msg != "") Serial.println(msg);
}

/* ------------------------------------------------- */

bool isConnected() {
  return (WiFi.status() == WL_CONNECTED);
}

/* ------------------------------------------------- */

bool connectToWiFi(const char* ssid, const char* password, int max_tries = 20, int pause = 500) {
  int i = 0;
  WiFi.mode(WIFI_STA);
  #if defined(ARDUINO_ARCH_ESP8266)
    WiFi.forceSleepWake();
    delay(200);
  #endif
  WiFi.begin(ssid, password);
  do {
    delay(pause);
    Serial.print(".");
  } while (!isConnected() || i++ < max_tries);
  WiFi.setAutoReconnect(true);
  WiFi.persistent(true);
  return isConnected();
}

/* ------------------------------------------------- */

void errorMsg(String error, bool restart = true) {
  Serial.println(error);
  if (restart) {
    Serial.println("Rebooting now...");
    delay(2000);
    ESP.restart();
    delay(2000);
  }
}

/* ------------------------------------------------- */

void setupTelnet() {
  // passing on functions for various telnet events
  telnet.onConnect(onTelnetConnect);
  telnet.onConnectionAttempt(onTelnetConnectionAttempt);
  telnet.onReconnect(onTelnetReconnect);
  telnet.onDisconnect(onTelnetDisconnect);

  // passing a lambda function
  telnet.onInputReceived([](String str) {
    // checks for a certain command
    if (str == "ping") {
      telnet.println("> pong");
      Serial.println("- Telnet: pong");
    }
  });

  Serial.print("- Telnet: ");
  if (telnet.begin()) {
    Serial.println("running");
  } else {
    Serial.println("error.");
    errorMsg("Will reboot...");
  }
}

/* ------------------------------------------------- */

// (optional) callback functions for telnet events
void onTelnetConnect(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" connected");
}

void onTelnetDisconnect(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" disconnected");
}

void onTelnetReconnect(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" reconnected");
}

void onTelnetConnectionAttempt(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" tried to connected");
}

/* ------------------------------------------------- */

void setup() {
  setupSerial(SERIAL_SPEED, "Telnet Test");

  Serial.print("- Wifi: ");
  connectToWiFi(WIFI_SSID, WIFI_PASSWORD);

  if (isConnected()) {
    ip = WiFi.localIP();
    Serial.print(" ");
    Serial.println(ip);
    setupTelnet();
  } else {
    Serial.println();
    errorMsg("Error connecting to WiFi");
  }
}

/* ------------------------------------------------- */

void loop() {
  telnet.loop();

  // send serial input to telnet as output
  // this part read tiva and transmit to ESP
  if (Serial.available()) {
    telnet.print(Serial.read());
  }
}
//* ------------------------------------------------- */

i think that you can only send data from the keyboard ... PuTTY does not have a screen read function

try Serial.write(telnet.read());. it is better to use while than if here: while (telnet.available())

@Juraj Problem is that there is no telnet.read() or telnet.avaible() function.

ok. sorry I don't know the library. I wrote a simpler telnet server library TelneStream, but it is really only a Server class wrapped in a thin layer. Arduino esp8266 3.0 has my ArduinoWiFiServer demonstrated by the PagerServer telnet example

It appears to me that the library has been written to accept input terminated by a newline character.
    char c = client.read();
    if (c != '\n') {
      if (c >= 32) {
        input += c;
      }
    // EOL -> send input
    } else {
      if (on_input != NULL) on_input(input);
      input = "";
      }

It will keep adding characters to the input buffer until a newline character is detected, and then pass the contents to the .onInputReceived recieved handler.
If my understanding is correct, the best you can do without making alterations to the library itself is:-

  telnet.onInputReceived([](String str) {
      Serial.println(str);
  });

Again, if I'm right then the newline character will always need to be present to push the data through.
Hope this is useful.

@Juraj Precisely.

so why do you write about altering the library

@voidPointer yes, when I use this, there is data exchange, but I need to debug it to confirm that it is correct. I will get back to you.

sorry. now I see what you mean. it is a lambda

@Juraj Because it is not simply a matter of if data is available.  The newline must also be present for delivery, rather than transmitting anything received. Without that understanding it would may be consuing why data isn't pushed through.

telnet clients usually send the newline. it can be configured. the library author knows it


text:
Arduino Uno won't connect when using USB-C to USB adapter
So I just got my first Arduino which is an Arduino Uno. I have a newer MacBook Air which doesn't have any USB ports so I thought I'd just use one of those USB-C to USB adapters.
I plugged it in and then searched for the Board in the Tools > Port menu. It was nowhere to be seen, only the /dev/cu.Bluetooth-Incoming-Port showed up.
To be clear, the Arduino did show signs of connectivity, it just didn't show up under the Port list. I'm also not 100% sure if it's an Arduino Uno since the company I bought it from said I should select Arduino/Genuino Uno in the Board menu which isn't an option anymore.
Is it a problem with my Arduino, my Laptop or my adapter?

Maybe it is not original, and it uses different usb-serial chip than the original one. Popular converters for Arduino Uno clones are CH340 and CP2104. You may try to install the driver for these 2 chips.

It now shows up in the Ports tab after installing the CH340 driver. Thanks a lot!


text:
How do you handle sensor drift?
I have a pair of potentiometers, on the Arduino, the output seems to drift, by one or 2 digits, back and forth. I would prefer they were read as one fixed value, without variation when their knobs are not turning. You can see in the image, the first and second values are shifting back and forth slightly. How should I address this?
I'm thinking of making a standard deviation function, but then I thought that might be unnecessarily complex.

My code is that the 2 sensor values are setting points in an SVG polyline. Variance means extra points will get plotted, while the device waits for valid input.
How should I deal with the variance in potentiometer readings to avoid outputting noise?
Here's my source:
/**Fucntion Defs**/
void svgHeader();
void svgFooter();
void polyLineBegin();
void polyLineEnd();

int Reset = 4;     //programmatically reset the arduino
int potX = A0;
int potY = A1;

int sensorValX = 0;
int sensorValY = 0;
int oldX = 0;
int oldY = 0;

int del = 2;       //a button on pin 2 for deleting drawn content
int delbutton = 0;
void setup() {
  Serial.begin(9600);
  pinMode(del, INPUT);
  svgHeader();
  polyLineBegin();
  delay(1000);
}

void loop() {
  // close the svg and start over
  if (digitalRead(del) == LOW ) {
    delbutton = 1;
    polyLineEnd();
    svgFooter();
    delay(5000);
    digitalWrite(Reset, LOW);
    digitalWrite(Reset, HIGH);
    svgHeader();
    polyLineBegin();
  } else {
    delbutton = 0;
    //Serial.println(delbutton);

  }

  //dont draw if its not changing
  sensorValX = analogRead(potX);
  sensorValY = analogRead(potY);
  if (sensorValX == oldX && sensorValY == oldY) {
    ; //dont do shi.
  } else {
    Serial.print(sensorValX);
    Serial.print(",");
    Serial.print(sensorValY);
    Serial.print(",");
    oldX = sensorValX;
    oldY = sensorValY;
    // Serial.println(delbutton);
    delay(1000);
  }
}
/**Functions**/

void polyLineBegin() {
  Serial.println ("<polyline points=\""); //x,y points go here

}

void polyLineEnd() {
  Serial.println ("0, 0\" stroke=\"red\" fill=\"transparent\" stroke-width=\"5\"/>");  //a dirty hack to avoid dealing with 1 last trailing comma.

}

void svgHeader() {
  Serial.println("<svg width=\"1023\" height=\"1023\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">");
};

void svgFooter() {
  Serial.println ("</svg>");
};

That's quantisation noise and is normal. You can't get rid of it, only deal with it. You could take an average, or you could discard some resolution, or you could write your code to work in a range of values not one single value.

Thats not drifting, just electrical noise in the analog input. You cannot really avoid that. But since your code isn't time critical, why not measuring multiple times, a erafing the values and then using the result. That would drastically reduce the noise in the used values

so Ill have to write some code to deal with it. I'm currently looking at calculating variance, standard deviation, normalization, and some other math terms I'm not exactly familiar with. I think I can make a simple statement to ignore values +/-1 of the read values,  but im not sure what to do if the variance where any more than that.

Before you do a analogRead(potX) ... do a "calibration" of your Vcc supply (through internal reference) if it is used as "reference" voltage with some "mean". This can help.

ok, once I got the idea I would need to do it in code, it became simpler to solve. In looking around the terms of quantization, the term thresh-holding came up, and I realized how to solve the problem.
I created a threshold value, and compared the difference between old and new variables.
int threshold =3;
int xVariance = abs(sensorValX-oldX);
int yVariance = abs(sensorValY-oldY);
if (xVariance >=threshold && yVariance >= threshold ||xVariance >=threshold || yVariance >=threshold){
  Serial.print(sensorValX);
  Serial.print(",");
  Serial.print(sensorValY);
  Serial.print(",");
 oldX=sensorValX;
 oldY=sensorValY;

}else{
; //dont do shi.
 // Serial.println(delbutton);
delay(1000);
    }

now, when I turn either potentiometer, I get a response, and output I desire, but not while the device is just sitting there.

Note, that you can leave out the xVariance >=threshold && yVariance >= threshold part in your if statement. It is redundant. The OR operator || will also evaluate to true, if both conditions are met.

This approach introduces hysteresis, which is indeed a common and effective approach against this kind of problems.

@chrisl, is it redundant? in the event one or both potentiometers are +/- threshold value? one value may change, while the other is constant, or both may change.

Yes, it is redundant. The OR operator || also evaluates to true, if both operants are true. You can refer to the truth table of that operator. What you were thinking of is called exclusive OR, or shortly XOR.

Remove the analog component from your device.
Use a rotary encoder.
It will sense the knob rotation digitally.
One huge advantage is that you can easily select the sensitivity of the input. One click can advance the counter by .001 just as easily as advancing by a 1000.
https://duckduckgo.com/?q=rotary+encoder&iar=images&iax=images&ia=images

you're not wrong, once I get this project functionally operable, its going to a children's museum, and you cant have knobs with limits, they break when you get 1000 kids a week cramming them all the way to one side or the other. but I still have some work to do, and I don't have the encoders yet.

@j0h then you may be interested in this ... uses a stepping motor as an encoder ... it makes a tough encoder ... https://create.arduino.cc/projecthub/andrewf1/using-stepper-motor-as-rotary-encoder-3f5de4

Right on! @jsotola I saw some things like this while working in a paper mill, but forgot all about it. I'm definitely going to look into this more, as steeper motors are harder to break than tiny little knobs.

Some methods for "dealing" with the noise:

Take multiple samples. Calculate the average ("mean"). Discard the decimal. This is "oversampling" along with resolution reduction (but reduction of the now increased oversampled resolution).
Take multiple samples. Find the most common value ("mode").
Divide the value by 2 (or 4 if needed). This reduces the range of values and the sampled resolution but discards the noise portion.

The problem you are suffering from is "quantisation noise". This is because an analog signal and a digital signal are not completely compatible. The ADC converts the analog signal into a digital value by successively comparing it to smaller and smaller voltages in steps ("quanta"). There is a limit to how small the steps can get (the resolution), but an analog voltage doesn't adhere to those steps, it will always be somewhere between the final two steps. Sometimes it will be detected as the lower step, sometimes the upper step. By taking multiple samples and averaging them you are estimating how close to one step or the other the value is and "refining" the result. This is "oversampling" and is used to increase the resolution of the ADC at the cost of sample speed.
With those extra samples you can either say "It's this much closer to the upper step" (take the "mean"), or say "It's more likely to be nearer the upper step" (take the "mode") to try and "fix" the value to one of the steps.

I appreciate the new words, and concepts, I will look into these methods further. I was concerned that calculating standard deviation on the Arduino may reduce performance, by being computationally intensive.

I think you should handle the trailing comma within the Arduino by using leading commas instead, but omit the first leading comma using a flag to indicate the first coordinate:
bool firstCoordinate;

void loop()
{
    . . .
    if (xVariance >= threshold || yVariance >= threshold)
    {
        if (!firstCoordinate)
        {
            Serial.print(",");
            firstCoordinate = false;
        }
        Serial.print(sensorValX);
        Serial.print(",");
        Serial.print(sensorValY);
        oldX = sensorValX;
        oldY = sensorValY;
    }
    . . .
}

void polyLineBegin()
{
    Serial.println("<polyline points=\""); //x,y points go here
    firstCoordinate = true;
}

void polyLineEnd()
{
    // Clean line ending.
    Serial.println("\" stroke=\"red\" fill=\"transparent\" stroke-width=\"5\"/>");
}

Alternatively, the first coordinate could be added to the line when it begins, then there is no need for a flag:
void polyLineBegin()
{
    Serial.println("<polyline points=\""); //x,y points go here
    Serial.println(sensorValX);
    Serial.println(",");
    Serial.println(sensorValY);
}

void loop()
{
    . . .
    if (xVariance >= threshold || yVariance >= threshold)
    {
        Serial.print(",");
        Serial.print(sensorValX);
        Serial.print(",");
        Serial.print(sensorValY);
        oldX = sensorValX;
        oldY = sensorValY;
    }
    . . .
}

The thresholding technique is great, but, as an aside, I recently discovered this excellent statistics library by Majenko while working on a non-blocking averaging function for Arduino and looking at converting it into a class. I found that that library already does what I want.

thanks @tim, this is valid, constructive criticism, related to the code. It might not address the question, but it does represent meaningful feedback.


text:
Using a level converter to adjust the voltage levels
we are currently working on a device that needs us to connect an sd card reader to 2 Arduino’s ( Uno and zero) , however, we just found that it is not possible to do so without a level converter , may we have some help about how to do the proper connection from the sd ( that is already connected to arduino zero) to the level converter and then to the Uno. We want to make sure that both microcontrollers work at the same voltage of 3.3V. The Arduino Uno works at 5V whereas the Zero works at 3.3V which is why we need the level converter

You want to have two devices talking to the same SD card? At the same time? You can't.

Actually they have to talk to the sd card one after another, one should get the data first and then the other one should transfer it.

if one after another can be avoided with one device telling the other to write for it, it might simplify things.

Could you please explain your idea clearly..

A circuit diagram and a better description of the objective would help in providing answers. It sounds like you have one MCU with an SD card, and a second one without. You want to connect the second MCU and have them both access the SD card? I suggest splitting up all the work and designing a modular approach to who is doing what. In hardware I’ve found devices like Pololu 2595 Logic level shifters useful and easy to connect. I suggest avoiding attempting to have two devices sequentially writing directly to one SD card, rather having one MCU coordinate the SD I/O for all of them.

Two devices writing to one SD card like they have exclusive access, without very strict arbitration to control which device is writing or reading which part of the card, will corrupt the file system on the card very quickly. It’s much simpler and safer to have one “master” like @RowanP suggested.

Think of it like a network. You have one USB hard drive, but two computers. You plug the hard drive in to one computer and share the filesystem across the network to the other computer. You don't plug the hard drive into both computers. That is what you need to do with your SD card. You connect it to one MCU then "share" it with the other one through some other communication medium (network, serial, I2C, whatever is most suitable for your usage).

That’s what we exactly thinking about and what led us to the idea of using a level converter or shifter, the level converter has Tx and Rx pins , through these pins we’re planning to take data from the Arduino zero and send them to the Uno using the Rx, what do you think about the idea?

The level converter we currently planning to use is sparkfun 2 Channel 5V 3.3V I2C TTL Logic Level Converter Module

https://www.fruugo.eg/2-channel-5v-33v-i2c-ttl-logic-level-converter-module/p-52178967-105041923?language=en&ac=google&gclid=CjwKCAjwr56IBhAvEiwA1fuqGhTPCLet8h74pZrUWV_CKpYDl20vlOBIhPEua3GKtN1ljVWm-dfoZxoCtisQAvD_BwE


text:
Why I cant get sizeof a pointer Array
well I am trying to get array size  to convert hex value to int value. but if I try to get size of array it returns every time 2. Actually .I dont understand. how to get array size, can you help me?
this is my code
unsigned long w;

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

  uint8_t * packet = read_packet();
  Serial.println(sizeof(packet)); // PROMLEM IS HERE, IT RETURNS EVERYTIME "2"

  for (int i = 0; i < 4; i++)
  {
    Serial.println(packet[i]); //if i print the packet array all elements are here
  }

  /*
    for (byte i = 0; i < sizeof packet; i++) {
      w = w + ((long)(packet[sizeof packet - (i + 1)]) << (i * 8));
    }

  */
}

void loop() {
  // put your main code here, to run repeatedly:

}

uint8_t *read_packet() {
  static uint8_t buffer[4];

  buffer[0] = 0x00;
  buffer[1] = 0x32;
  buffer[2] = 0x32;
  buffer[3] = 0x32;

  Serial.println(sizeof buffer);
  return buffer;
}

if I print the packet array, all 4 elements are there 0,50,50,50. but size of array returns every time "2". even if I increase the array size.
maybe you can think why am I using pointers? because of my previous question answer is using this method. Read serial with header and end marker

sizeof is a compile-time item reporting the bytes something takes.  In this case that means the bytes that the numeric value of pointer itself uses.  If you allocate memory yourself, you'll have to store that separately.  Consider using a c++ vector.

@Abel There's no such thing as a C++ vector on Arduino - the STL is lacking.

there are implementations that should work well enough.
https://www.arduino.cc/reference/en/libraries/vector/

@mehmet Please see my answer to a previous question: http://arduino.stackexchange.com/a/25317/22924

A pointer is just a pointer. It's not an array. On 8 bit Arduinos the memory address range is a 16 bit value, so a pointer will always be 2 bytes.
You need to return two values from your function - the buffer pointer and the length of the buffer. This is usually done by passing an extra integer pointer parameter:
unsigned long w;

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

  uint8_t plen;
  uint8_t * packet = read_packet(&plen); // Pass the pointer to the plen variable to store the length in

  Serial.println(plen); // This now prints "4"

  for (int i = 0; i < plen; i++) // You can now use `plen` here
  {
    Serial.println(packet[i]); //if i print the packet array all elements are here
  }
}

void loop() {
  // put your main code here, to run repeatedly:

}

uint8_t *read_packet(uint8_t *len) {

  static uint8_t buffer[4];

  buffer[0] = 0x00;
  buffer[1] = 0x32;
  buffer[2] = 0x32;
  buffer[3] = 0x32;

  if (len != NULL) *len = 4; // Store 4 in the length variable if provided

  return buffer;
}

just a quick add: since arduino uses C++, it is possible to use reference to array uint8_t (&buffer)[4] to pass actual array and have sizeof working properly, and template to automatically have non-fixed size array, and maintain compile-time check for size and sizeof-like functions working properly, even with static_assert. Extremely powerful to control what size of array a function can process all at compile time

@Lesto Sure. But that implies some level of knowledge on the part of the programmer to even know what a reference or a template is... And this is Arduino...

Majenko's answer explains things and shows how to fix your code, but the solution with static buffer inside the function is not common.
Common is to have int readBuffer(unit8_t* buffer, size_t size).
The parameters are the buffer provided by the caller and the size of that buffer. The return value is the count of bytes written by the function into the buffer.
Real example:
int WiFiEspAtBuffStream::read(uint8_t* data, size_t size) {
  if (size == 0 || !available())
    return 0;

  size_t l = rxBufferLength - rxBufferIndex;
  if (l == 0 && size > rxBufferSize) // internal buffer is empty and provided buffer is large
    return EspAtDrv.recvData(linkId, data, size); // fill the large provided buffer directly

  // copy from internal buffer
  fillRXbuffer();
  for (size_t i = 0; i < l && i < size; i++) {
    data[i] = rxBuffer[rxBufferIndex++];
  }
  if (size <= l) // provided buffer was filled
    return size;
  return l + read(data + l, size - l); // handle the rest of provided buffer
}


text:
NRF24L01 receiver flooded with data packets
Following this tutorial I attempted making an NRF transmitter and receiver using an Arduino Nano. On the transmitter side I used the following code:
// SimpleTx - the master or the transmitter

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

const byte slaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

char dataToSend[10] = "Message 0";
char txNum = '0';

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000; // send once per second

void setup() {

    Serial.begin(9600);

    Serial.println("SimpleTx Starting");

    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.setRetries(3,5); // delay, count
    radio.openWritingPipe(slaveAddress);
}

//====================

void loop() {
    currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {
        send();
        prevMillis = millis();
    }
}

//====================

void send() {

    bool rslt;
    rslt = radio.write( &dataToSend, sizeof(dataToSend) );
        // Always use sizeof() as it gives the size as the number of bytes.
        // For example if dataToSend was an int sizeof() would correctly return 2

    Serial.print("Data Sent ");
    Serial.print(dataToSend);
    if (rslt) {
        Serial.println("  Acknowledge received");
        updateMessage();
    }
    else {
        Serial.println("  Tx failed");
    }
}

//================

void updateMessage() {
        // so you can see that new data is being sent
    txNum += 1;
    if (txNum > '9') {
        txNum = '0';
    }
    dataToSend[8] = txNum;
}

The serial monitor prints
13:05:22.966 -> Data Sent Message 3  SimpleTx Starting
13:05:25.437 -> Data Sent Message 0  Acknowledge received
13:05:26.436 -> Data Sent Message 1  Acknowledge received
13:05:27.434 -> Data Sent Message 2  Acknowledge received
13:05:28.432 -> Data Sent Message 3  Acknowledge received
13:05:29.432 -> Data Sent Message 4  Acknowledge received
13:05:30.432 -> Data Sent Message 5  Acknowledge received
13:05:31.427 -> Data Sent Message 6  Acknowledge received

at 1 second intervals. I assume this points to an 'okay' transmitter. On the receiver side, I used the code
// SimpleRx - the slave or the receiver

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

const byte thisSlaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN);

char dataReceived[10]; // this must match dataToSend in the TX
bool newData = false;

//===========

void setup() {

    Serial.begin(9600);

    Serial.println("SimpleRx Starting");
    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.openReadingPipe(1, thisSlaveAddress);
    radio.startListening();
}

//=============

void loop() {
    getData();
    showData();
}

//==============

void getData() {
    if ( radio.available() ) {
        radio.read( &dataReceived, sizeof(dataReceived) );
        newData = true;
    }
}

void showData() {
    if (newData == true) {
        Serial.print("Data received ");
        Serial.println(dataReceived);
        newData = false;
    }
}

And the receiver gets flooded with data packets
13:06:20.318 -> Data received⸮SimpleRx Starting
13:06:21.798 -> Data received
13:06:21.831 -> Data received
13:06:21.831 -> Data received
13:06:21.864 -> Data received

The post also mentions that this is due to "most likely the Arduino is not communicating properly with its nRF24." Following the recommendations of post #30, later in the thread, the output of radio.printDetails() for the transmitter is
19:43:56.897 -> CheckConnection Starting
19:43:56.897 ->
19:43:56.897 -> FIRST WITH THE DEFAULT ADDRESSES aftCheckConnection Starting
19:43:58.355 ->
19:43:58.355 -> FIRST WITH THE DEFAULT ADDRESSES after power on
19:43:58.422 ->   Note that RF24 does NOT reset when Arduino resets - only when power is removed
19:43:58.488 ->   If the numbers are mostly 0x00 or 0xff it means that the Arduino is not
19:43:58.574 ->      communicating with the nRF24
19:43:58.621 ->
19:43:58.621 -> SPI Speedz  = 10 Mhz
19:43:58.654 -> STATUS      = 0x7f RX_DR=1 TX_DS=1 MAX_RT=1 RX_P_NO=7 TX_FULL=1
19:43:58.721 -> RX_ADDR_P0-1    = 0xffffffffff 0xffffffffff
19:43:58.754 -> RX_ADDR_P2-5    = 0xff 0xff 0x7f 0xff
19:43:58.788 -> TX_ADDR     = 0xffffffff7f
19:43:58.821 -> RX_PW_P0-6  = 0x00 0x00 0x00 0x00 0x00 0x00
19:43:58.854 -> EN_AA       = 0x00
19:43:58.887 -> EN_RXADDR   = 0x7f
19:43:58.887 -> RF_CH       = 0x00
19:43:58.920 -> RF_SETUP    = 0x00
19:43:58.920 -> CONFIG      = 0x00
19:43:58.954 -> DYNPD/FEATURE   = 0x00 0x00
19:43:58.954 -> Data Rate   = 1 MBPS
19:43:58.987 -> Model       = nRF24L01+
19:43:59.020 -> CRC Length  = Disabled
19:43:59.020 -> PA Power    = PA_MIN
19:43:59.053 -> ARC     = 0
19:43:59.053 ->
19:43:59.053 ->
19:43:59.053 -> AND NOW WITH ADDRESS AAAxR  0x41 41 41 78 52   ON P1
19:43:59.120 ->  and 250KBPS data rate
19:43:59.154 ->
19:43:59.154 -> SPI Speedz  = 10 Mhz
19:43:59.186 -> STATUS      = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
19:43:59.253 -> RX_ADDR_P0-1    = 0x0000000000 0x0000000000
19:43:59.286 -> RX_ADDR_P2-5    = 0x00 0x00 0x00 0x00
19:43:59.320 -> TX_ADDR     = 0x0000000000
19:43:59.353 -> RX_PW_P0-6  = 0x00 0x00 0x00 0x00 0x00 0x00
19:43:59.386 -> EN_AA       = 0x00
19:43:59.419 -> EN_RXADDR   = 0x00
19:43:59.419 -> RF_CH       = 0x00
19:43:59.452 -> RF_SETUP    = 0x00
19:43:59.452 -> CONFIG      = 0x00
19:43:59.486 -> DYNPD/FEATURE   = 0x00 0x00
19:43:59.486 -> Data Rate   = 1 MBPS
19:43:59.519 -> Model       = nRF24L01+
19:43:59.552 -> CRC Length  = Disabled
19:43:59.552 -> PA Power    = PA_MIN
19:43:59.585 -> ARC     = 0
19:43:59.585 ->
19:43:59.585 ->

The same sketch when uploaded on the receiver gives,
19:48:38.260 -> CheckConnection Starting
19:48:38.260 ->
19:48:38.260 ->
19:48:38.260 ->
19:48:38.260 -> FIRST WITH THE DEFAULT ADDRESSES aftCheckConnection Starting
19:48:39.708 ->
19:48:39.708 -> FIRST WITH THE DEFAULT ADDRESSES after power on
19:48:39.774 ->   Note that RF24 does NOT reset when Arduino resets - only when power is removed
19:48:39.841 ->   If the numbers are mostly 0x00 or 0xff it means that the Arduino is not
19:48:39.941 ->      communicating with the nRF24
19:48:39.974 ->
19:48:39.974 -> SPI Speedz  = 10 Mhz
19:48:40.008 -> STATUS      = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
19:48:40.075 -> RX_ADDR_P0-1    = 0x0000000000 0x0000000000
19:48:40.109 -> RX_ADDR_P2-5    = 0x00 0x00 0x00 0x00
19:48:40.141 -> TX_ADDR     = 0x0000000000
19:48:40.175 -> RX_PW_P0-6  = 0x00 0x00 0x00 0x00 0x00 0x00
19:48:40.208 -> EN_AA       = 0x00
19:48:40.242 -> EN_RXADDR   = 0x00
19:48:40.242 -> RF_CH       = 0x00
19:48:40.274 -> RF_SETUP    = 0x00
19:48:40.274 -> CONFIG      = 0x00
19:48:40.308 -> DYNPD/FEATURE   = 0x00 0x00
19:48:40.308 -> Data Rate   = 1 MBPS
19:48:40.341 -> Model       = nRF24L01+
19:48:40.374 -> CRC Length  = Disabled
19:48:40.374 -> PA Power    = PA_MIN
19:48:40.407 -> ARC     = 0
19:48:40.407 ->
19:48:40.407 ->
19:48:40.407 -> AND NOW WITH ADDRESS AAAxR  0x41 41 41 78 52   ON P1
19:48:40.474 ->  and 250KBPS data rate
19:48:40.508 ->
19:48:40.508 -> SPI Speedz  = 10 Mhz
19:48:40.541 -> STATUS      = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
19:48:40.607 -> RX_ADDR_P0-1    = 0x0000000000 0x0000000000
19:48:40.640 -> RX_ADDR_P2-5    = 0x00 0x00 0x00 0x00
19:48:40.674 -> TX_ADDR     = 0x0000000000
19:48:40.707 -> RX_PW_P0-6  = 0x00 0x00 0x00 0x00 0x00 0x00
19:48:40.740 -> EN_AA       = 0x00
19:48:40.773 -> EN_RXADDR   = 0x00
19:48:40.773 -> RF_CH       = 0x00
19:48:40.806 -> RF_SETUP    = 0x00
19:48:40.806 -> CONFIG      = 0x00
19:48:40.840 -> DYNPD/FEATURE   = 0x00 0x00
19:48:40.840 -> Data Rate   = 1 MBPS
19:48:40.873 -> Model       = nRF24L01+
19:48:40.906 -> CRC Length  = Disabled
19:48:40.906 -> PA Power    = PA_MIN
19:48:40.939 -> ARC     = 0
19:48:40.939 ->
19:48:40.939 ->

There is some miscommunication as claimed by that post. I tried changing the pins of CE, CSN to 7,8 but the problem persisted for the receiver. I changed the power supply to the NRF using two alkaline AA batteries, but that didn't solve the problem either. I also connected a 10 μF capacitor between the power supply pins of the NRF, but no luck.
Next, I tried changing the NRF module. I used an NRF module which was working correctly as a transmitter(printing "Data Sent Message X  Acknowledge received") at 1 second, as intervals as a receiver in place, still the same problem.
Any help would oblige.
P.S: I am using Arduino clones, but they work for other purposes. The NRF's have "NRF24L01" stamped on the chip, and seem to be fine.

The radio.printDetails() information are coming from the sender or the receiver ?

According to reply #30 on the Arduino Forum thread "Simple nRF24L01+ 2.4GHz transceiver demo", radio.printDetails() is run twice: once for unintialised and a second time for initialised. This should give you two sets of results, but you've only posted one set in your question. Are both sets of results identical?

@Vincent, sorry for the incomplete information. I have updated the question. What strikes me, is that #reply #30 sets radio.setDataRate( RF24_250KBPS ); but radio.printDetails(); report Data Rate   = 1 MBPS.

@tim, sorry for the incomplete details too. I have posted both sets now. They are identical for the receiver, but STATUS, RX_ADDR_P0-1, RX_ADDR_P2-5, TX_ADDR and EN_RXADDR differ for the transmitter.

@RanjitPal About DataRate, nRF24L01 can transmit only with 1MBPS or 2MBPS, while nRF24L01+ (upgraded version) can also transmit with 250KBPS (which is useful for polluted environment or longer distance communication). This is why you can not set your nRF24L01 to a 250KBPS datarate. But it surprises me that the printDetails() command indicates the upgraded version to be honest. The pipe1 address also remains the same even if you execute openReadingPipe(1, thisSlaveAddress) which is another problem.

@RanjitPal To me, the problem might come from setRetries(3,5) (5 retries with 1ms interval) while AutoAcknowledgment (= AA) is disabled. When AA is disabled, the transmitter module automaticaly return true even if the receiver hasn't received anything. In your case, the receiver seems to receive something, but not the message Message x you have sent, since nothing is displayed on the serial monitor. Try to enabled AA, or change to setRetries(1,1).

@Vincent, I funny thing I notice is that the serial prints "Data Received" even when I dont have a transmitter connected. I mean if I just power the Arduino and the NRF for the receiver, "Data Received" is printed in the serial.

Following the Getting Started Example, it prints "radio hardware is not responding!!". Well radio.begin() returns a false.


text:
What should I do with stackOverflow in compile error?
I don't have port, but when I want to compile my code (even empty files),
I encounter this error:
Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

The code is:
int LED_red=4;
int LED_yellow =2;
int green =0;

void setup() {
  // put your setup code here, to run once:
  pinMode(LED_red,OUTPUT);
  pinMode(LED_yellow,OUTPUT);
  pinMode(green,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(LED_red,HIGH);
  digitalWrite(LED_yellow,LOW);
  digitalWrite(green ,LOW);
  delay(5000);
  digitalWrite(LED_yellow,HIGH);
  digitalWrite(LED_red,LOW);
  digitalWrite(green,LOW);
  delay(5000);
  digitalWrite(green,HIGH);
  digitalWrite(LED_yellow,LOW);
  digitalWrite(LED_red,LOW);
  delay(5000);
}

Sketch uses 998 bytes (3%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

I want a hex address for cordinate this code with Proteus, but it doesn't compile and dosn't give me hex address.

I don't think that's an error.  It looks like the report regarding how much of the target processors resources you are using.  From the looks of it, you program is very small and will most certainly fit the target processor you have chosen.

Where is the Stack Overflow you mention in your question title? As others noted, your “error” is just a summary generated after successfully compiling your code and not an actual error.

What is the exact issue? As has been mentioned many times, your code compiles fine according to the output you’ve shown. You are not showing us any evidence of a problem. What does “I want hex address for cordinate this code with Proteus” mean? What hex address? Are you trying this with Proteus or with the Arduino IDE?

Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

This is not an error message. Rather, it's a message that results from a successful compile of your empty programme.

Sketch uses 998 bytes (3%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

Neither is this an error message. Rather, it's a message that results from a successful compile of your more substantial programme.
To export the HEX file from the Arduino IDE for Proteus, go to:

Menu bar -> Sketch -> Export compiled Binary

The short-cut is Ctrl+Alt+S.
You will find the .hex file in the same directory as your sketch.

Tanks a lot , your answer was so useful for me!

@dorsa, thanks. If it answers your question, be sure to accept it by clicking on the tick to left of it.

There is nothing to do.
What you are seeing is not an error. It is merely an informational message telling you how much of the available resources your sketch is using. Since it is using far less than the maximum available (as you would expect from an empty sketch) you have no problem.
You only need to worry about those figures when the "amount left" gets too small.

tanks a lot , but I want a hxe address for زcordinate this code with Proteus but it doesnt compile and dosent gove me hxe address ; can you tell me what should I do please?

@dorsa What code? What exactly are you trying to do?

int LED_red=4;   int LED_yellow =2; int green =0;
void setup() {
pinMode(LED_red,OUTPUT);
pinMode(LED_yellow,OUTPUT);
pinMode(green,OUTPUT);
}
void loop() {
digitalWrite(LED_red,HIGH);
digitalWrite(LED_yellow,LOW);
digitalWrite(green ,LOW);
delay(5000);
digitalWrite(LED_yellow,HIGH);
digitalWrite(LED_red,LOW);
digitalWrite(green,LOW);
delay(5000);
digitalWrite(green,HIGH);
digitalWrite(LED_yellow,LOW);
digitalWrite(LED_red,LOW);
delay(5000);
}

@dorsa Please, don't post code in comments. Edit your question and provide all the information. Including what actual error you get when you try and compile.

Ok ,I do it ; do you have any idea about this ?

@dorsa There still is no error. What is your actual problem?

What you are seeing is not an error.
Although your sketch is empty, there is Arduino framework code that gets created with it. This code actually calls your setup() and loop() functions so things operate as you would expect. It was designed this way to make it eaiser to get started.

thanks but I do not know what to do , can you help me again please and told me what to fo

@dorsa, you don’t have to do anything except upload your code to Arduino. Please follow a tutorial that explains the basics of how the Arduino IDE works, such as this one.

You can change the processor settings from Tools-->Processor-->Atmega328P(Bootloader). It solved my problem.

Please explain how this solves the "problem". What was your error message?


text:
Pulsein not working when share ground
I have 3rd party device that create PWM output which I want to measure it with Arduino, the problem I have is when I shared ground between the two boards which cause the Pulsein output to become zero. (why this is happening, and how to fix it)
The reason I am connecting the ground since I need measure other signals on that board. (All other signals are responding fine)

simulate this circuit – Schematic created using CircuitLab
code:
#define pulse_ip 3
unsigned long duration;
int ontime,offtime,duty;
float freq,period;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(pulse_ip, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

  ontime = pulseIn(pulse_ip, HIGH);
  offtime = pulseIn(pulse_ip, LOW);
  period = ontime + offtime;
  freq = 1000000.0 / period;
  duty = (ontime / period) * 100;
  Serial.print(offtime);
  Serial.print("-");
  Serial.print(ontime);
  Serial.print("-");
  Serial.print(period);
  Serial.print("-");
  Serial.print(freq);
  Serial.print("-");
  Serial.print((duty * 255) / 100);
  Serial.print("-");
  Serial.println(duty);
  delay(1000);

}

what is your question?

why I am getting zero when I share the ground

are you sure you don't get only random pulses without common ground?

@Juraj that is good point maybe I am getting random, let me double check

@Juraj Yes I believe you are correct I am getting random numbers and as soon as I share ground become zero

does calling pulseIn twice make sense? check the reference https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/

The reason I am connecting the ground since I need measure other signals on that board. -- no, the reason you connect the grounds is because you have to. https://majenko.co.uk/blog/our-blog-1/the-importance-of-sharing-grounds-12

@Majenko you are of course correct, that was reason I was getting random number

What (approximate) frequency is the PWM signal? And what voltage levels?

@Majenko 3.3V is the voltage,  14.56k freq  of pwm

you should provide a timeout argument so that it runs faster. even then, it's pushing the limits of hardware and CPU speed and will likely be fuzzy/noisy if it works at all. It would be better to use an RC filter to convert the PWM into an analog voltage, then divide that down to 0-5v, then sample the resulting signal. Since you only seem to need 1 sample a second, you can easily use a large capacitor and sample averaging to get a very smooth analog voltage.

Without connected grounds the signal on the input pin you read with pulseIn must be random noise.
Two pulseIn one waiting for HIGH change and second waiting for LOW don't make sense because for parameter HIGH, pulseIn waits for the pin to go from LOW to HIGH, starts timing, then waits for the pin to go LOW and stops timing. Then it returns the length of the pulse in microseconds.


text:
Why do I get this error when uploading a sketch on my arduino uno?
I have two Arduino Unos. On the first I can upload my sketch wittout any error, but with my second Arduino I always get this error, altough Im using the same settings:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xbf

What I tried:

different Usb Port
different Usb Cable
swapped the MCU on the board
restarted VSCODE

I also have this error sometimes, especially when I'm switching boards or usb port and forget to reselect  the device at Tools > Port.