body:
I want to communicate two (2) ESP32's via Json commands using ESPAsyncWeb.h. The master should have specific operations to execute and respond to the client, and the client should be able to send specific Json commands to ask questions and receive responses. I have tried the method below but is throwing me weird errors such as

> cannot bind non-const lvalue reference of type 'ArduinoJson::JsonObject&' {aka 'ArduinoJson6185_91::OBjectRef&'} to an rvalue of type 'ArduinoJson6185_91::enable_if<true, ArduinJson6185_91::ObjectRef>::type' {aka 'ArduinoJson6185_91::ObjectRef'}

I am not sure how to implement the operations for sending Json and receiving response from the Server using ArduinoJson 6. If anyone could enligthen me on how to conduct such transactions I'd appreciate it.

```
 void setup(){

//start serial comm
//Broadcast as WiFi SoftAP

 server.on("/command", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &json)
          {JsonObject& jsonObj = json.as<JsonObject>();
           uint8_t command = jsonObj["C"];
           String response;
           switch(command){
                           case 0: response = "{\"SCAN\":\"received_scan\"}";
                           request -> send(200, "application/json", response);
                           return;
                           case 1: /*...similar stuff */

                           case 2: /*...*/
}});
server.begin();
}

title: Use of ESPAsyncWebServer.h with ArduinoJson version 6 for Master-Client transactions

Answers: 1

body:
> cannot bind non-const lvalue reference of type 'ArduinoJson::JsonObject&' {aka 'ArduinoJson6185_91::ObjectRef&'} to an rvalue of type 'ArduinoJson6185_91::enable_if<true, ArduinJson6185_91::ObjectRef>::type' {aka 'ArduinoJson6185_91::ObjectRef'}

In other words, "cannot assign `JsonObject` to `JsonObject&`".
The compiler refuses to save a reference to a temporary variable because the reference would inevitably dangle.

To fix this issue, you must remove the ampersand (`&`) after `JsonObject`, like so:

```c++
JsonObject jsonObj = json.as<JsonObject>();
```

And it would be best if you also did the same for `JsonVariant`.

BTW, the cast from [`JsonVariant`](https://arduinojson.org/v6/api/jsonvariant/) to [`JsonObject`](https://arduinojson.org/v6/api/jsonobject/) isn't necessary in your case, so you could simplify your program to:

```c++
server.on("/command", HTTP_POST,
          [](AsyncWebServerRequest* request, JsonVariant json) {
            switch (json["C"].as<uint8_t>()) {
              case 0:
                request->send(200, "application/json",
                              "{\"SCAN\":\"received_scan\"}");
                return;

              case 1: /*...similar stuff */

              case 2: /*...*/
            }
          });
```

I recommend that you have a look at [ArduinoJson's documentation](https://arduinojson.org/v6/doc/); I heard it's pretty good ;-)


body:
> I bough Sim7020_mini module. I put IOT Sim card, and plug-in antenna,
> connect Rx,Tx into USB-TTL, then put supply into VIN (5 volt), LED
> power was lid on. Arduino Serial Monitor set into 115200, but no
> character appear, also I enter AT, no answer. I already making sure my
> wiring. Measuring STATUS pin 42 showing 1.8 volt, means not active.
>
> Schematic look like wrong, according to sim7020 Hardware design v1.02,
> to put SIM7020 to On we should give LOW pulse 1 second into PWRKEY.
> But STATUS pin still 1.8 volt.
>
> May anyone has successful using this such module? Any clue?

[First question about using SIM7020_mini Module][1]

Thank you @hcheung for clue about 1.8 volt.

The SIM7020_mini module already equipped with logic level shifter between 1.8v and 3.3v.

I know SIM 7020C already Up, pin `STATUS` (42) is HIGH, pin `NETLIGHT` (41) blinking.

Here is my schematic, I just want to enter AT Command first. But on my Serial Monitor (Arduino) doesn't show any character received.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/CADEM.png)

<!-- End schematic -->

When I type 'AT' it's echoed back to screen Serial Monitor. When I reverse Tx/Rx between SIM7020_mini module and USB-TTL, no character echoed. When I restart SIM7020_mini module, there is no character received by Serial Monitor.

  [1]: https://stackoverflow.com/questions/72073576

title: How to use Sim7020_mini NB-IOT module

Answers: 1

body:
My fault, AT command on Serial Monitor (Arduino IDE) should be ending with `Carriage Return`, while my Serial Monitor using `New Line`

Thank you for responses.


body:
I am trying to build a simple motor test sketch, currently, to test a NEMA 23 stepper motor and the DM542T stepper driver.

Here is the code, and I am having trouble figuring out how to properly wire the 5-lead button (+, -, Common, NO, NC)

Here is the code

    // Pin numbers
    const int buttonPin = 2;
    const int directionPin = 8;
    const int stepPin = 9;

    // Other constants
    const int NumSteps = 5000; // steps
    const int Speed = 500;

    void setup() {
      pinMode(buttonPin, INPUT_PULLUP);
      pinMode(directionPin, OUTPUT);
      pinMode(stepPin, OUTPUT);
      digitalWrite(directionPin, LOW);
      digitalWrite(stepPin, LOW);
    }

    void loop() {
      if (digitalRead(buttonPin)) {
        // Move in one direction
        for (int distance = 0; distance < NumSteps; distance++) {
          digitalWrite(stepPin, HIGH);
          delayMicroseconds(Speed);
          digitalWrite(stepPin, LOW);
          delayMicroseconds(Speed);
        }
       // Reverse direction
       digitalWrite(directionPin, !digitalRead(directionPin));
     }
      delay(5);
    }

The button is a momentary button, so I am holding it in to simulate a latching button.

I have the buttons Common and Neg leads wired together, and connected to the Gnd pin on the Arduino (mega rev3)
I have the buttons Positive and the NC wired together and connected to pin 2.

Wiring that button in that manner, works fine in the button-controlled blink sketch, but is not working here (LED on the button doesn't light up and the motor test doesn't run).

Note: I am using a 5 lead momentary button as that what the project these motors will be for will be using.

Any help appreciated.

title: Using a 5 pin button with Arduino Correctly

Answers: 1

body:
The button's pins are as follows:

* +: The LED's anode
* -: The LED's cathode
* C: The common pin of the switch
* NC: Normally Closed - is normally connected to the C pin until the button is pressed
* NO: Normally Open - is connected to the C pin when you press the button

So to use the button as a button the two pins you care about are C and NO. Use those pins (in any order) as you would any normal button with a pullup resistor (or the internal `INPUT_PULLUP` resistor).

To use the LED can be a little more tricky. Most of this style of button have the LED set up for 12V usage. While you *may* get a slight glow from it from 5V you would probably need to switch it with a transistor and power it from 12V to get it to light up properly. However your button may be rated differently and need a different voltage.


body:
I found the following Github Repo that makes it possible to build your own Yubikey with an Arduino Leonardo device.

https://github.com/pagong/arduino-yksim

Pretty cool. However I am wondering if using this is legal at all?

YubiCo is a company and they sell sticks with the YubiKey OTP feature. The verification process happens through their servers. Somehow I can't quite imagine that the company YubiCo tolerates that their processes and products could be easily replaced by open source products? Maybe they have any patents or utility models? And I was not able to find any licensing information which makes sense since official firmware seems to be closed source. So I guess it makes sense that no licensing information is available since the yksim project is a reverse engineered thing?! But I'll admit quite frankly: I have no idea of all this.

I would also like to use this library and possibly also for my customer projects, but I need to know whether this is really allowed.

Hope someone can help me here and I know that the internet is no source for a 100% sure legal advice. But maybe someone has a clue or a hint for me.

title: Is it legal to "simulate" Yubikey OTP autentication with an Arduino in own product?

Answers: 1

body:
According to <https://www.yubico.com/blog/secure-hardware-vs-open-source/>

> The YubiKey hardware with its integral firmware has never been open sourced, whereas almost all of the supporting applications are open source.

I am not a lawyer, however it would seem that providing you aren't copying their (non open source) hardware, but are merely replicating the functionality, then this would appear to be OK. **Disclaimer**: I may be wrong.

Having said that, I agree with the comment under the question, you should probably ask at https://law.stackexchange.com/

Questions about the legality of an Arduino application really are legal questions, not technical ones.


body:
I'm using a SAMD21G18A based board - the arduino zero, for a battery-powered wearable project (a type of computer mouse). I'm trying to figure out how to put the device to sleep, when it hasn't been moved for a period of time. I'm using data from a connected gyroscope, which is stored into an array. If the sum of the data in the array is less than some threshold, then I put the device into sleep using the sleep function from the [arduino low-power library](https://www.arduino.cc/reference/en/libraries/arduino-low-power/lowpower.sleep/). I'm waking the device with an interrupt from the sensor.

```
void nomotion_sleep(float x_value) {
  static float sleep_threshold = 15;
  static float sleep_array[15];
  static byte sa_size = 15;
  static float asum; // array sum
  static byte i = 0;
  static uint32_t array_timer;

  if (timer1(array_timer, 60000)) { // a timer f, checks every min
    sleep_array[i] = abs(x_value); //x_value is from the gyro
    asum += sleep_array[i];
    i += 1;
    if (i == sa_size - 1) {
      if (asum < sleep_threshold) {
        //sleep
        LowPower.sleep();
      }
      for (byte ii = 0; ii < sa_size; ii += 1) {
        sleep_array[i] = 0;
      }
      asum = 0;
      i = 0;
    }
  }
}

```

The issue is if the device goes into sleep the array sum value is not = 0 for the next iteration. Not sure how to fix this. Should I make it a `volatile` global variable and change upon wake up in the ISR?

Is there a better way to do this? Thank you for trying to help.

title: Putting samd-based board into sleep mode

Answers: 0


body:
When trying to flash my genuine arduino micro with avrdude from cmd on a Manjaro system I get the infamous error

`avrdude: stk500_getsync() attempt x of 10 ...`

Im adding this post to the many other that ask about this error because all of them are trying to use the IDE to flash the arduino, whereas I can use it no problem on both Linux and Windows, but when using avrdude from cmd on Linux I get this error. This confirms that the board is fine and there are no shorts on the reset pin or any other possible physical cause of this issue, something appears to be wrong in the avrdude configuration.

This is my Makefile:
```
default: build

build:
 avr-gcc -mmcu=atmega32u4 main.c -o main

flash:
 avr-objcopy -O ihex -R .eeprom main main.hex
 avrdude -F -V -c arduino -p m32u4 -P /dev/ttyACM0 -b 115200 -U flash:w:main.hex
```

Can you suggest anyway to fix this?

EDIT:
Problem Solved!

The error was in the `-c` parameter, for the atmega 32u4 it's supposed to be `avr109` and not `arduino`.

title: Linux avrdude: stk500_getsync()

Answers: 1

body:
There are two common ways of resetting an Arduino into the bootloader:

1. For UART based boards (Uno, Mega2560 etc) just opening the port resets the board
2. For USB based boards (Micro, etc with the 32u4 chip) you have to manually tell it to reset

Yours is option 2 - unless you tell it to reset the board it won't do anything. The IDE normally handles that for you.

But it's simple: just cause the CDC/ACM port to be opened at 1200 baud and closed again. The simplest method is to use `stty` to do it for you:

```bash
stty -F /dev/ttyACM0 speed 1200
```

You should find that it then resets the board. Adding a short delay to allow the USB to reset would be good too. So your whole programming routine could look something like:

```bash
flash:
    avr-objcopy -O ihex -R .eeprom main main.hex
    stty -F /dev/ttyACM0 speed 1200
    sleep 1
    avrdude -F -V -c arduino -p m32u4 -P /dev/ttyACM0 -b 115200 -U flash:w:main.hex
```

In Makefiles I find it useful to set the port as an overridable variable:

```bash
PORT?=/dev/ttyACM0
```

Then use `${PORT}` everywhere instead of `/dev/ttyACM0` - then you can use `make PORT=/dev/ttyACM1` if you need to without having to edit the Makefile. Great if you have multiple boards.


body:
Consider:

```c++
#include <EEPROM.h>

byte guifactor1 = 1;
byte guifactor2 = 2;
byte guifactor3 = 3;
byte guifactor4 = 4;
byte guifactorgas = 5;
byte guifactorwater = 6;

volatile unsigned long count1factor;
volatile unsigned long count2factor;
volatile unsigned long count3factor;
volatile unsigned long count4factor;
volatile unsigned long countgasfactor;
volatile unsigned long countwaterfactor;

void loop(){
if (guifactor1 > -1){
    EEPROM.write(1, guifactor1);
    EEPROM.commit();
    count1factor = EEPROM.read(1);
    Serial.println(count1factor);
  }

  if (guifactor2 > -1){
    EEPROM.write(2, guifactor2);
    EEPROM.commit();
    count2factor = EEPROM.read(2);
    Serial.println(count2factor);
  }

  if (guifactor3 > -1){
    EEPROM.write(3, guifactor3);
    EEPROM.commit();
    count3factor = EEPROM.read(3);
    Serial.println(count3factor);
  }

  if (guifactor4 > -1){
    EEPROM.write(4, guifactor4);
    EEPROM.commit();
    count4factor = EEPROM.read(4);
    Serial.println(count4factor);
  }

  if (guifactorgas > -1){
    EEPROM.write(5, guifactorgas);
    EEPROM.commit();
    countgasfactor = EEPROM.read(5);
    Serial.println(countgasfactor);
  }

  if (guifactor1 > -1){
    EEPROM.write(6, guifactorwater);
    EEPROM.commit();
    countwaterfactor = EEPROM.read(6);
    Serial.println(countwaterfactor);
  }
}

void setup(){

}
```

The problem I have with my code is that it either doesn’t write the value to the EEPROM or it doesn’t read the value as it doesn’t print anything to the monitor.

I expected to read 1 2 3 4 5 6 from the monitor as I write the bytes to the EEPROM and then transfer the value to the *unsigned long* and print the variable.

title: What is wrong with the way I write and or read the EEPROM adresses?

Answers: 1

body:
You forgot to call `Serial.begin()` in `setup()`.

As a side note, your `if` tests are useless. The compiler warns me that:

```text
comparison is always true due to limited range of data type
```

**For reference**: the previous answer, valid for the initial question
where `guifactor1` and co. were all `unsigned long`.

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

The program does nothing because all the actions are conditioned on
tests such as

```c++
if (guifactor1 > -1)
```

and these tests are always false. The reason they are false is because
arithmetic comparison operators such as `<` [perform _usual arithmetic
conversions_][uac] on their operands prior to doing the actual
comparison. Since `guifactor1` is `unsigned long`, and this type has a
higher conversion rank than `int` (the type of `-1`), the second operand
is implicitly converted to `unsigned long`, yielding `ULONG_MAX`.

[uac]: https://en.cppreference.com/w/cpp/language/operator_comparison#Arithmetic_comparison_operators


body:
I need to send an array of floating-point numbers from python to Arduino Mega. For that, I read many sources[ \[this][1] [this][2] [this][3] [this][4] [this\]][5] [this][6]] and many more links for the same I referred. But unable to solve the problem.

I tried to send the angles to Arduino through python and return these values to python to print.

Below is the Python code in which I try to send the array named angle and tries to print the values received from Arduino.

    import cv2
    import numpy as np
    import serial
    import struct
    import time

    ser = serial.Serial('COM3', 9600, timeout = 1)
    time.sleep(2)
    if(ser.isOpen() == False):
        ser.open()
    print('com3 is open', ser.isOpen())

    angle = [120.2,154.2,14.25]
    ser.write(struct.pack('>fff', 10.5,11.9,48.2)) # B for interger and f for float
    #ser.write(struct.pack('>f', angle)) # B for interger and f for float

    time.sleep(2)
    ser.flush()

    data = ser.readline()
    data = str(data.decode("utf"))
    print(data)

    ser.close()

Below is the Arduino code:

    float f1; float f2; float f3;

    void setup() {
      // put your setup code here, to run once:
    Serial.begin(9600);

    Serial.println("Arduino is in parseFloat!");
    }

    void loop() {

      if (Serial.available() > 0)
      {
        d1 = Serial.parseFloat(); d2 = Serial.parseFloat(); d3 = Serial.parseFloat();

        ad = d1 +2.5;
        Serial.println(ad)
      }
    delay(2000);
    }

The error I got is:
I got no error or warnings but there is no output also for the print commands as shown in below Figure.
[![enter image description here][7]][7]

I need help to send the values to Arduino using python.

  [1]: https://arduino.stackexchange.com/questions/49682/sending-float-values-from-python-to-arduino-via-serial-communication
  [2]: https://arduino.stackexchange.com/questions/5090/sending-a-floating-point-number-from-python-to-arduino
  [3]: https://arduino.stackexchange.com/questions/45874/arduino-serial-communication-with-python-sending-an-array
  [4]: https://stackoverflow.com/questions/27639605/send-a-list-of-data-from-python-to-arduino-using-pyserial
  [5]: https://arduino.stackexchange.com/questions/9627/send-multiple-int-values-from-python-to-arduino-using-pyserial
  [6]: https://forum.arduino.cc/t/sending-float-values-from-python-to-arduino-via-serial-stumped/455736
  [7]: https://i.stack.imgur.com/eKuND.png

title: Sending float values from Python to Arduino using Serial communication

Answers: 1

body:
There are two things going on here.

**First** of all, if you look up the [*readline()* method in Python][1] that is referenced in the [PySerial manual][2], you'll see the following:

    readline(size=- 1, /)

    Read and return one line from the stream. If size is specified, at most size bytes will be read.
    The line terminator is always b'\n' for binary files; for text files, the newline argument to open() can be used to select the line terminator(s) recognized.

In your program, you are actually sending more than one line back to serial port from the Arduino. The first line is the ASCII-encoded "Arduino is in ParseFloat!". The second one is the test float calculation. If you don't account for the fact you are expecting multiple "lines" from the serial port,  you wouldn't see the test calculation, because you are not actually reading it. For encoded data, it states that the line ends at the '\n' char/digit (10).

**Try it out** change the "println" to "print" in your Arduino program and add another message either in the setup or the loop. Run your Python program. What do you see? Now change the "print" back to println". Run your Python program again. What do you see now?

**Secondly**, Edgar Bonet points out the second issue. The *write()* method in the PySerial API requires data to be a bytes array, but it's the way you are encoding it. It seems that the Arduino Serial class expects a ASCII-encoded byte-array, rather than a float byte-array (the floats encoded as a single-precision floating point number), which is what you are sending.

If you change your code to something like this (for example):

    angle = [120.2,154.2,14.25]
    ser.write(str(angle).encode('utf-8'))

you should be able to see your test calculation come back, granted that you read what I wrote in the first part of this answer.

  [1]: https://docs.python.org/3/library/io.html#io.IOBase.readline
  [2]: https://pyserial.readthedocs.io/en/latest/pyserial_api.html


body:
I am using a NodeMcu with Arduino IDE on Ubuntu.
I have managed to upload the blink script and it work.
Now, when i plug the nodemcu, the serial port /dev/ttyUSB0 is briefly available in the IDE.
After 2 seconds, the port menu is grayed out again and I can't use it.

Same with `ls /dev/tty*` `/dev/ttyUSB0` is briefly available.
```bash
/dev/tty    /dev/tty23  /dev/tty39  /dev/tty54      /dev/ttyS10  /dev/ttyS26
/dev/tty0   /dev/tty24  /dev/tty4   /dev/tty55      /dev/ttyS11  /dev/ttyS27
/dev/tty1   /dev/tty25  /dev/tty40  /dev/tty56      /dev/ttyS12  /dev/ttyS28
/dev/tty10  /dev/tty26  /dev/tty41  /dev/tty57      /dev/ttyS13  /dev/ttyS29
/dev/tty11  /dev/tty27  /dev/tty42  /dev/tty58      /dev/ttyS14  /dev/ttyS3
/dev/tty12  /dev/tty28  /dev/tty43  /dev/tty59      /dev/ttyS15  /dev/ttyS30
/dev/tty13  /dev/tty29  /dev/tty44  /dev/tty6       /dev/ttyS16  /dev/ttyS31
/dev/tty14  /dev/tty3   /dev/tty45  /dev/tty60      /dev/ttyS17  /dev/ttyS4
/dev/tty15  /dev/tty30  /dev/tty46  /dev/tty61      /dev/ttyS18  /dev/ttyS5
/dev/tty16  /dev/tty31  /dev/tty47  /dev/tty62      /dev/ttyS19  /dev/ttyS6
/dev/tty17  /dev/tty32  /dev/tty48  /dev/tty63      /dev/ttyS2   /dev/ttyS7
/dev/tty18  /dev/tty33  /dev/tty49  /dev/tty7       /dev/ttyS20  /dev/ttyS8
/dev/tty19  /dev/tty34  /dev/tty5   /dev/tty8       /dev/ttyS21  /dev/ttyS9
/dev/tty2   /dev/tty35  /dev/tty50  /dev/tty9       /dev/ttyS22  /dev/ttyUSB0
/dev/tty20  /dev/tty36  /dev/tty51  /dev/ttyprintk  /dev/ttyS23
/dev/tty21  /dev/tty37  /dev/tty52  /dev/ttyS0      /dev/ttyS24
/dev/tty22  /dev/tty38  /dev/tty53  /dev/ttyS1      /dev/ttyS25
```
After 2 seconds:
```bash
/dev/tty    /dev/tty23  /dev/tty39  /dev/tty54      /dev/ttyS10  /dev/ttyS26
/dev/tty0   /dev/tty24  /dev/tty4   /dev/tty55      /dev/ttyS11  /dev/ttyS27
/dev/tty1   /dev/tty25  /dev/tty40  /dev/tty56      /dev/ttyS12  /dev/ttyS28
/dev/tty10  /dev/tty26  /dev/tty41  /dev/tty57      /dev/ttyS13  /dev/ttyS29
/dev/tty11  /dev/tty27  /dev/tty42  /dev/tty58      /dev/ttyS14  /dev/ttyS3
/dev/tty12  /dev/tty28  /dev/tty43  /dev/tty59      /dev/ttyS15  /dev/ttyS30
/dev/tty13  /dev/tty29  /dev/tty44  /dev/tty6       /dev/ttyS16  /dev/ttyS31
/dev/tty14  /dev/tty3   /dev/tty45  /dev/tty60      /dev/ttyS17  /dev/ttyS4
/dev/tty15  /dev/tty30  /dev/tty46  /dev/tty61      /dev/ttyS18  /dev/ttyS5
/dev/tty16  /dev/tty31  /dev/tty47  /dev/tty62      /dev/ttyS19  /dev/ttyS6
/dev/tty17  /dev/tty32  /dev/tty48  /dev/tty63      /dev/ttyS2   /dev/ttyS7
/dev/tty18  /dev/tty33  /dev/tty49  /dev/tty7       /dev/ttyS20  /dev/ttyS8
/dev/tty19  /dev/tty34  /dev/tty5   /dev/tty8       /dev/ttyS21  /dev/ttyS9
/dev/tty2   /dev/tty35  /dev/tty50  /dev/tty9       /dev/ttyS22
/dev/tty20  /dev/tty36  /dev/tty51  /dev/ttyprintk  /dev/ttyS23
/dev/tty21  /dev/tty37  /dev/tty52  /dev/ttyS0      /dev/ttyS24
/dev/tty22  /dev/tty38  /dev/tty53  /dev/ttyS1      /dev/ttyS25
```
How can I fix that? I have try all the usb ports.
The NodeMCU settings:
[![enter image description here][1]][1]

Actually Using Ubuntu 22.04 LTS

EDIT:
While running `sudo dmesg -w` and connecting the mcu I get:
```
[ 3726.038486] usb 1-1: new full-speed USB device number 13 using xhci_hcd
[ 3726.220532] usb 1-1: New USB device found, idVendor=10c4, idProduct=ea60, bcdDevice= 1.00
[ 3726.220536] usb 1-1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[ 3726.220537] usb 1-1: Product: CP2102 USB to UART Bridge Controller
[ 3726.220538] usb 1-1: Manufacturer: Silicon Labs
[ 3726.220539] usb 1-1: SerialNumber: 0001
[ 3726.229998] cp210x 1-1:1.0: cp210x converter detected
[ 3726.231005] usb 1-1: cp210x converter now attached to ttyUSB0
[ 3727.565688] usb 1-1: usbfs: interface 0 claimed by cp210x while 'brltty' sets config #1
[ 3727.566375] cp210x ttyUSB0: cp210x converter now disconnected from ttyUSB0
[ 3727.566391] cp210x 1-1:1.0: device disconnected
```

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

title: Ubuntu Serial Port Briefly showing on arduino IDE

Answers: 1

body:
This could be happening because `Brltty` application. Remove it and try again.

    sudo apt remove brltty
    sudo apt autoclean && sudo apt autoremove


body:
I am simulating a circuit with arduino, which determine if there is current at input, then turn the led on at the output. The problem is the light is always on even when the button is open at the input.

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

This is my code:

    void setup() {
      pinMode(7, OUTPUT);
      pinMode(8, INPUT);
      digitalWrite(7, LOW);
    }

    void loop() {
      int on = digitalRead(8);
      digitalWrite(7, on);
    }

Why does this happen and how do I solve it?

Any help would be appreciated.

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

title: Why the led is always on in proteus?

Answers: 1

body:
Microcontroller inputs don't detect the presence of current. They compare a voltage to a threshold.

In reality the input pin is closest to a capacitor. You press your button and it charges that capacitor to above the threshold voltage for "HIGH". Then you release the button but that capacitor remains charged and still reading "HIGH". You need something to reduce the charge on that capacitor to below the "LOW" threshold voltage.

This is most normally done with a resistor between the GPIO pin and GND which will "bleed off" that charge and give you a LOW reading when the button is released.

This is a "pull down" resistor (you can also reverse it and have a "pull up" resistor and the button connected to GND) and is an essential part of any input that doesn't itself generate both the HIGH and LOW voltages required (any switch or button).

Also 10V on a GPIO pin **will** destroy your Arduino.


body:
first of all I would like to apologize for the, probably very basic and stupid questions for you, but I'm not an electronic expert..

I'm implementing my project using an Arduino Mega 2560 (I need more pins.. this is the most important reason that it drives the Arduino choice)
I'll put my project in an external environment without the electricity source. For this reason my idea is to use a battery with a solar panel as power input to charge the battery.
I also applied some low-power techniques in order to reduce energy consumption as much as possible.
Regarding the solar panel and battery connections I purchased this Arduino Solar Shield.

[Solar Charger Shield V2.2 - Seeed Wiki][1]

And here I'm a bit (a lot) confused about the choice of the battery and the solar panel(s) to be purchased.
First of all, my idea is to use multiple (2 or 4) solar panels in order to exploit as much as possible the solar light (multiple positions) but I'm not able (I'm not sure) about the solar panel selection to purchase.
Considering that the maximum current that the solar shield could be delivered is 700mA can I use 4 solar panels like this
https://www.seeedstudio.com/1W-Solar-Panel-80X100.html
(applying also 4 applying 4 diodes to avoid reverse current)?

About this the possible number or size of the solar panels Do I need to consider the amount of th Current at Peak Power?
For example, using 4 solar panels with 170mA as Current at Peak Power, 4*170 = 680 that it's > of the current of the solar shield.
So, is this wrong? Do I reduce the amount of the panels or do I use a different panel?

About the Solar input voltage it's 4.8~6V.
These are the specifications about the solar panel:

Dimensions: 100x80x2.5(±0.2) mm
Typical voltage: 5.5V
Typical current: 170mA
Open-circuit voltage: 8.2 V
Maximum load voltage: 6.4V
Maximum load voltage, Open-circuit voltage are > Solar input voltage. Is it a risk?
About the lipo battery, can I use a battery 3.7v and about the mAh value as high as possible (for example this https://www.amazon.it/2100mAh-Lithium-Polymer-Replacement-Bluetooth/dp/B095BTSMYH/?th=1 ?)
What about the maximum current value (in this case 5A)? Is it ok?
In case, can you suggest me something else?

** *********** EDIT *********** **

As suggested I'm updating my question in order to give additional info about my scenario.

My project will be installed in an external environment (with some atmospheric protections IP67).
The location, from solar irradiation point of view, it's a good place: https://globalsolaratlas.info/detail?m=site&c=40.283716,17.586365,9&a=18.056138,39.997805,18.056138,40.420456,18.535172,40.420456,18.535172,39.997805,18.056138,39.997805&s=40.11799,18.382874

About my project:
- I'll have to take the measurements from more sensors:
- starting from 1 to 10/15 humidity/temperature (DHT22) sensor;
- starting from 1 to 10/15 load cells (4 load cells for each HX711);
- I'll send the data using some transmissions using a LORA Shield.

I don't need to retrieve the measurements continuously or in very short periods.

The idea is to sleep my Arduino (in low power with all power sensors disconnected) and, using a RTC DS3231 module, to wake-up it on regular intervals, read the data, send it via LORA and go to sleep again.

The idea is to wake-up every 15 minutes. The time that I imagine about the measurements and the send will take a few seconds (around 30s in case I can approximate it to 1 minute).

And at the moment I don't have the exact measurements about the used current (because I can connect all here.. but I need to purchase the solar panels and the battery in order to make a real test also)..So, the idea now is to approximate.. In case I can adjust something later.

At the moment, measuring the current I have.

around 0.35mA when the Arduino is sleeping.

I probably can reduce it again because I have to remove 2 power led indicators (1 on my DS3231, one on my LORA shield... and, in case, also the power led on my Arduino).

When the Arduino works (live mode) probably I can consider around 90/100mA (probably this is too much) for 30s).

I'm not expert but, using this values I calculated the average about the used current in 1 hour:

((100mA * 4 minutes) + (0,35mA * 56 minutes)) /60 = 7mA/m
420 mA/h

I'll need 5v about the voltage.

I don't have any limitation about the size or the space.

I think that considering 7days without solar power supply or bad water conditions could be enough (in my opinion it's too much)

  [1]: https://wiki.seeedstudio.com/Solar_Charger_Shield_V2.2/

title: Arduino + Solar Charger Shield V2.2: Battery and Solar panels selection

Answers: 1

body:
This is a question that's better suited for the electrical engineering SO, but I can give you some pointers to reword and re-post your question so it's not as broad.

Right now you have a few unknown variables to juggle, so you should be jotting down your thoughts on all of the following:

 - Where will the unit be placed and/or located? How long do you expect it to go without needing to have its battery recharged?
 - What is the continuous power consumption? You should know your approximate continuous current consumption and at which voltage you will be running the Arduino and the sensors that you connect to it
 - What environmental conditions do you expect the unit to experience? Do you have a limiting factor on size or space?
 - How much are you willing to pay?

You can definitely use multiple solar panels, but you'd have to connect them in parallel (so they maintain the same voltage), and even then, the linked charger shield can only go up to 900 mA of charging current. The 600-700 mA is the supported power output of the battery, or the max current that the shield can provide to your system thru the shield. It can be larger if you lower the system's voltage and stay within the maximum limits of the charger shield.

With regards to your second question, yes, current at peak power is a good metric for your approximations. If you go thru my questions, you will know how much your systems consumes in a day and choose a battery that can discharge no more than X amount of percent per day (depending on the type of battery). Your goal is to be able to charge that battery back at least close to its full capacity--your solar panels or the amount of thereof, as well as your charger, will be dictated by that.

For the Voc of the solar panel - ideally, it would be less than the solar input voltage. It's the voltage of the panel without a load connected to it. Of course, you will have a load connected to the solar panel and thus the typical voltage will be around what's stated, but if you don't want to damage your charger, you have to make sure your SP will be properly loaded under most conditions! It will be safer to connect multiple smaller SPs to get the current that will keep the system up and charge your battery.

With regards to the battery current - you have to check which current it is. Is it the charging current? Output current? Be mindful that you are limited by your charger in this case (3W output, 900 mA charging current).

Hope this gives you a start! It's a good question, but you need to do some more reading and you need to have a better idea of the design for your system before we can be more helpful.

Edit:

Per the updated information...

I will use your estimates, but do consider that for sensors that require power, you can add them and make your calculations more accurate. Also, while LoRA is low-power, it will consume some power too, and you can factor that in.

Let's assume your numbers are correct and the average current consumption averages out to ~ 420 mA/h. Then, if you want to  keep the system alive for 7 days, you'll need a battery with a capacity of 420 mA/h * 24 hours/day * 7 days -> 70,560 mAh or 70.560 Ah. At 5 volts, your system effectively requires 0.420 A/h * 5 V -> 2.1 Watts/hour  (finicky units here, eh?). That would translate to ~353 Watts/week. Also, 5V means you will need a battery that can provide that voltage - a lower voltage battery will not support your system.

The next thing you have to consider then is the battery type - [there are a few][1], but the ones I'd go for are either Li-ion or VRLA (valve-regulated lead acid). There is a tradeoff between cost - Li-ion batteries cost more, but they are typically better in the majority of factors rather than SLA (sealed lead acid) batteries. Doing some googling, you could get a 70-100 Ah SLA/VRLA for ~$200-300 and a Li-ion for ~$400-500. Do note, however, that you can discharge Li-ion batteries more deeply than VRLA ones - it's recommended to keep the charge on the VRLA batteries around ~50% and preferably around ~75% to extend its life. You can discharge Li-ion batteries up to 80% or a bit more and that's fine, they don't suffer as extensive reduction in their lifetime like SLAs.

To put that into perspective, if you have an application that requires ~8 Ah, then ideally for a VRLA you'd need to size a battery such that it doesn't go below 50% for your worst-case application scenario. That is, if you think you'll need the device to run for 7 days without any sun, then you'll need a battery of a 16 Ah capacity or more. Even bigger if you want to extend its lifetime. For Li-ion, aiming at a bit higher than 8 Ah should be fine. For your application, that means getting a SLA battery that's > 140 Ah (unless it's a deep discharge SLA battery) or a Li-ion battery that's close to 70 Ah.

Now, it must be noted that most batteries that provide those capacities typically come in 12V, so you would have to add a buck-converter to convert from 12V to the battery voltage your charger needs (3-4.5V). The charger you linked states that it can provide up to 3W out, which is 600 mA max at 5V. That would support your application as your average current draw is less than 600 mA.

For charging, however, you have to keep in mind that your system, on average, draws 420 mA/hour. So the charger's charging capabilities would actually be 900 - 420 -> 480 mA/hour. That means that based on worst-case considered direct solar irradiation hourly data in the link you provided, you'd get ~ 8 hours of direct sunlight (again, worst case!). So 8 hours you can charge -> 480 * 8 = 3840 mAh and you'll lose 6720 (420 * 16) mAh. That is not good, because you're losing the charge on the battery each day.

That means 2 things -  you have to get a charger that permits a larger charging current within the maximum charging current of the battery rating AND you have to get enough panels (OR a big enough panel) to be able to provide that current. With the panels that you linked, the max current per panel is ~170 mA for the typical voltage of 5.5V. To provide a charging current of ~ 900 mA, you'd need 5 panels, but as mentioned above, that still wouldn't be enough. So, back to the drawing board...

I hope this is enough to help you make more progress on your design.

  [1]: https://batterysolutions.com/learning-center/battery-types/


body:
While testing the [CustomCharacter.ino][1] example for the Grove LCD RGB Backlight from Seeed Studio on an Arduino 101 card, there is an extra pixel that appears above an eye of the smiley and the smiley gets shifted one row down also. (see attached picture just below, with some manual changes in the library, while trying to fix the problem)

[![Example of the problem][2]][2]

Actually, depending on the order of the characters assignments, the smiley is finally displayed correctly, such as in the following minimal working example, where the two `createChar()` assignments have been swapped (`1` is before `0`) and both smileys are displayed correctly:
```
#include <Wire.h>
#include "rgb_lcd.h"

rgb_lcd lcd;

byte smiley[8] = {
    0b00000,
    0b00000,
    0b01010,
    0b00000,
    0b00000,
    0b10001,
    0b01110,
    0b00000
};

void setup()
{
    lcd.begin(16, 2);
    lcd.createChar(1, smiley);
    lcd.createChar(0, smiley);
    lcd.setCursor(0, 0);
    lcd.write((unsigned char)0);
    lcd.write(1);
}

void loop() {}
```

If I happen to put `lcd.createChar(0, smiley);` back before `lcd.createChar(1, smiley);`, the error (the shift in the pixels rows + the extra activated pixel) occurs again for the second smiley.

Could anybody explain why this actually happens and, hopefully, give some way to fix the display?

  [1]: https://github.com/Seeed-Studio/Grove_LCD_RGB_Backlight/blob/master/examples/CustomCharacter/CustomCharacter.ino
  [2]: https://i.stack.imgur.com/YMIgf.jpg

title: Why is there an extra pixel in the smiley for the Grove LCD RGB Backlight from Seeed Studio?

Answers: 0


body:
I'm using an ESP32 which I connected to a MAX31329 RTC through I2C.

Unfortunately I can't read any register from the RTC. After modifying the MAX31328 library didn't work, I tried reading single registers directly. Here is the code:

    #include "Wire.h"

    int seconds = 0;
    int ret = 0;

    void setup() {

    Serial.begin(115200);
    delay(500);

    Wire.begin(33,32,100000);

    delay(500);
    Wire.beginTransmission(0x68);
      Wire.write(0x06);
      Wire.write(13);
      ret = Wire.endTransmission();
      if(ret != 0)
        Serial.println("i2c Setup failed");

      delay(500);
    }

    void loop() {

      Wire.beginTransmission(0x68);
      Wire.write(0x06);

      Wire.requestFrom(0x68,1);
      seconds = Wire.read();
      ret = Wire.endTransmission();
      if(ret != 0)
        Serial.println("Read failed");

      Serial.println(seconds);

    delay(1000);
    }

The register always returns 0.

Do you see the error in my code?
The datasheet of the MAX31329 can be found [here](https://datasheets.maximintegrated.com/en/ds/MAX31329.pdf).

I'm trying for days now and have no clue what the problem is.
Thanks a lot for your support in advance.

Best regards,

Martin

title: Can't read through I2C from RTC

Answers: 3

body:
You are doing things in the wrong order.

>      Wire.beginTransmission(0x68);
>      Wire.write(0x06);
>      Wire.requestFrom(0x68,1);
>      seconds = Wire.read();
>      ret = Wire.endTransmission();

The request is sent on the endTransmission call, so you need to do that before trying to get a response. In other words:

      Wire.beginTransmission(0x68);
      Wire.write(0x06);
      ret = Wire.endTransmission();

      Wire.requestFrom(0x68,1);
      seconds = Wire.read();

body:
To read the max31329 you do need to do the following as Nick Said

    Wire.beginTransmission(0x68);
    Wire.write(0x06);
    ret = Wire.endTransmission(false); //No Stop, so the request is a restart

    Wire.requestFrom(0x68,1);
    seconds = Wire.read();

But it needs to be a repeated restart following the write to register 0x06, hence the false in Wire.endTransmission(false). It took me ages to figure out as the DS3231 and MAX31328 don't required this, I actually found this writen in the data sheet for the MAX31343 which has a similar set of registers with seconds starting at 0x06 unlike the previous clocks that start at 0x00. Interestingly with these ones, reading the status register 0x00 will return to you any flags for interupts and automatically reset them after reading the register, which I think is new and better.

body:
I have been using the ESP32 for about 10 years now and it can be finicky

I2C is an Open Collector interface requiring Pull-up resistors to work.

If you are using a board module it likely has the pull-ups if not make sure you have them (around 1.5K OHMS) from SDA and SCL to 3.3 Vcc.

I suggest starting with Arduino's i2cdetect.ino and debug if it is being seen.
If not you have a wiring issue.

while both other answers are fairly good, you show no schematic or mention if you are using a RTC board.


body:
I cannot find the answer from [official document](https://www.arduino.cc/reference/en/language/functions/communication/serial/begin/) and also surprised no one asked the same question.

What is the default baud rates if I didn't call `Serial.begin`?

title: What is the default baud rate without calling Serial.begin?

Answers: 1

body:
There is no default baud rate. When the sketch starts, the serial port
is disabled (thus non-functional). Calling `Serial.begin()` enables the
port.


body:
I am using an Arduino Pro Micro (basically a Leonardo in a smaller form factor) in a mobile application where power consumption is really important.

To reduce power consumption, I put the Arduino to sleep, but that disconnects USB. That's not really acceptable in this application, since reconnecting USB after the Arduino wakes takes pretty long (a second or two).

Is there some way to keep the USB connection alive while still conserving energy? E.g. by waking the ATMega32u4 frequently to keep the connection alive? Or is there some not-as-deep sleep moden where the USB connection stays alive?

Edits for clarification:

The device is an USB HID device. If the device goes to sleep after a few minutes of inactivity, having to reconnect after the user pressed a button causes quite a long delay between pressing the button and a reaction on the device.

I am using the ATMega32u4's native USB implementation, so no V-USB or anything similar.

I am putting the device to sleep like so:

```
Keyboard.end();
USBCON = 0;
LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_OFF);
```

This is how I wake it up again:

```
USBDevice.attach();
delay(50);
Keyboard.begin(KeyboardLayout_en_US);
```

title: Arduino Leonardo/Pro Micro sleep and USB

Answers: 2

body:
This would better serve as a comment, but I can't post comments (yet)...

 - What is your application doing? Is it supposed to be asynchronous? Why are 1-2 seconds too long?
 - By the "USB" connection, you mean the UART/Serial peripheral?
 - How are you putting the board to sleep? Are you using the Arduino Sleep Modes? If so, which one are you using?

I'll speculate a bit: if you are using the ASP, then you might have to change the source code for the functions you are using to accommodate for keeping that peripheral awake. Do note that it might make the application more power-hungry than you want it to be.

Waking up more often could be done, but ideally you would need a synchronization mechanism, because at least eventually you'll run into an issue where you might miss the data or you'll wake up the device so often, you'll lose your power savings.

body:
The Arduino has several sleep modes. They differ mainly by the clocks
that are kept running, the peripherals that are enabled, and the
possible wake-up sources. All these modes are described in the
[datasheet of the ATmega32U4 microcontroller][datasheet], section 7:
_Power Management and Sleep Modes_.

You may see here that “Power-down” is one of the deepest sleep modes:
all clocks are disabled, the main oscillator is turned off, and only
asynchronous wake-up sources are available. As you have experienced, the
USB port is not functional in this mode.

In contrast, “Idle” is a somewhat shallow sleep: the CPU is halted but
the peripherals remain clocked. Any enabled interrupt can be used as a
wake-up source. This is a good option if you want the USB link to remain
connected while sleeping, and you can get it with the `LowPower.idle()`
function.

If you are worried about the sleep mode to be too “shallow” and not save
enough energy, note that the parameters if `LowPower.idle()` let you
specify which peripherals you want to keep running during sleep. If you
keep running only those that are needed, this should limit the power
consumption to what is strictly needed.

[datasheet]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf#G5.998200


body:
I recently got a Microchip Fubarino, contains a PIC32MX250F128D and I'm totally new to the Arduino IDE, i uploaded the blink sketch all fine and well.
Schematic: [FubarinoMini_v15_sch][1]

```
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
//pinMode(LED_BUILTIN, OUTPUT);

//asm ("BSF PORTA,10");
//pinMode(RA10, OUTPUT);
//TRISA10 = 0;
TRISAbits.RA10 = 0;
//PORTAbits.RA10 = 1;
//PORTAbits.RA10 = 0; // set to output
//mapPps(20, PPS_OUT_SDO2)
}

// the loop function runs over and over again forever
void loop() {
//digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
PORTAbits.RA10 = 1;
delay(500); // wait for a second
//digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
PORTAbits.RA10 = 0;
delay(500); // wait for a second
}
```
restults in:
```
 Blink:45:12: error: 'volatile union __LATAbits_t' has no member named 'RA10'
LATAbits.RA10 = 0;
```
changing:
```
void loop() {
  //digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  PORTAbits.RA10 = 1;
  delay(500);                       // wait for a second
  //digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  PORTAbits.RA10 = 0;
  delay(500);                       // wait for a second
}
```
doesn't work either.

I also tried this example code:
https://github.com/fubarino/fubarino.github.com/wiki/Fubarino-Mini-pps
It does work.
```
#define LED 1
#define SCK2 4
#define SDI2 18
#define SDO2 20
```
The led on the Fubarino board is not connected to pin 1, but to RA10.
Pin 18 is the MCLR on the device, reviewing the datasheet you can't even set SDI2 & SDO2 to the above defined numbers.

Normally on a PIC16F84 or so, you would do something like this.
```
bank1
movlw b'00000001'
movwf TRISA

movlw b'11110000'
movwf TRISB
bank0
```

the Arduino "code" seems a bit abstract.
I Would like to experiment with the button.
The Chipkit pps example shows you can use the Microchip keywords from the devices datasheet.

Can the Fubarino be setup like a classic PIC device in the Arduino IDE?
Configuring all the pins before going in to loop, using the Keywords from the datasheet.

  [1]: https://ww1.microchip.com/downloads/en/DeviceDoc/FubarinoMini_v15_sch.pdf

title: Using a Microchip Fubarino with the Arduino IDE, how to acces and configure all pins

Answers: 1

body:
The entries in the "bits" structures are named after the bits.

It's not

    TRISAbits.RA10

but

    TRISAbits.TRISA10

The same goes for

    LATAbits.LATA10

The only exception is the "port" one

    PORTAbits.RA10

Which is a hangover from the old PIC16 chips that didn't have a LATx register.

----

> The led on the Fubarino board is not connected to pin 1, but to RA10.

Pin 1 is RA10. If you look in the file `Board_Data.c` for the Fubarino_Mini variant (`packages/chipKIT/hardware/pic32/2.1.0/variants/Fubarino_Mini/Board_Data.c`) you can see all the pin mappings. There's a bunch of arrays there that define how everything fits together.

The second entry in most of those arrays (pin 1, starts counting at 0) is for RA10.  As for

> Pin 18 is the MCLR on the device, reviewing the datasheet you can't even set SDI2 & SDO2 to the above defined numbers.

the PPS is a whole other mess on those chips. Pin 18 is not the 18th pin on the board, but digital IO pin number 18, which is the 19th entry in those pin array tables - RA4.  Mapping RA4 is done through the file `packages/chipKIT/hardware/pic32/2.1.0/cores/pic32/pps/pingroups_1xx2xx.h` which contains an entry:

    #define _PPS_RPA4       (2 + _PPS_SET_C)

and the file `packages/chipKIT/hardware/pic32/2.1.0/cores/pic32/pps/peripherals_1xx2xx.h` which has:

    PPS_IN_SDI2     = (35 + _PPS_SET_C + _PPS_INPUT_BIT),

Those are then used by the mapPps() function to map RA4 to SDI2. Something which is perfectly possible.

Yes, it's convoluted and a bit of a mess, but the best we could come up with given how limited the PIC32MX2xx IO multiplexer is.


body:
I need to print data on the Arduino serial monitor received from the Xbee in AT mode. I have searched on most forums and have not found anything on how to do this.

I have my Xbee tx connected to Arduino nano Rx and rx connected to tx.

title: How to receive data from Xbee in AT mode on Arduino Nano

Answers: 1

body:
You connected the Xbee to the single hardware serial interface that the Nano has. Is is also used by the USB to Serial chip, which connects to the Serial Monitor. So what you are sending to the Xbee is also sent to the Serial Monitor. What the Xbee sends is only sent to the Arduino (since the Xbee TX pin is connected to RX of Arduino and also TX of the Arduino's USB to Serial chip).

But you can separate then by using a `SoftwareSerial` interface on any other pins of your liking. Then you can connect the Xbee to it. Then forward the output of the `SoftwareSerial` interface to the `Serial` interface. To see how this works have a look the [first example of the `SoftwareSerial` library][1]. It's basically checking both interfaces, reads available data from one interface and writes it to the other (note the `write()` in contrast to `print()` since when forwarding you don't want to interpret the data again to another format like `print()` does).

Also there are plenty examples and tutorials about `SoftwareSerial` on the web. An important restriction is that only one `SoftwareSerial` interface can listen to data at any time. The Hardware `Serial` interface doesn't have such a problem.

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/master/libraries/SoftwareSerial/examples/SoftwareSerialExample/SoftwareSerialExample.ino


body:
so i recently got an arduino micro for a project needing the control of two stepper motors with the A4988 driver. previously i was prototyping on an arduino uno and everything was working fine, but on the switch to the micro the motors started behaving erratically such as random step direction and a random number of steps being taken. i've pretty confidently narrowed it down to the output pins floating, i've recorded the direction pin on the micro floating with ~2v being "off" and ~3v being "on" with a multimeter.
the thing is is that i can't find anything about fixing this other than doing.
```c++
pinMode(DIR, OUTPUT);
digitalWrite(DIR, HIGH);
```
or external pull resistors and i've tried both pull up and down resistors at 100k and 330 ohm with no luck.

right now i have one motor connected to uno and one to the micro, the motor on the uno still runs fine with no external pull resistors. the below schematic shows a simplified version of how both the uno and the micro are wired.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/V4Vts.png)

<!-- End schematic -->

and here is the code both arduinos are running.
```c++
#include "A4988.h"

#define MOTOR_STEPS 200
#define DIR 10
#define STEP 9

A4988 stepper(MOTOR_STEPS, DIR, STEP);

void setup() {
    pinMode(DIR, OUTPUT);
    digitalWrite(DIR, HIGH);

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

    stepper.setRPM(100);
}

void loop() {
    stepper.rotate(360);
    delay(1000);

    stepper.rotate(-360);
    delay(1000);
}
```

here are some links to other related post
<https://stackoverflow.com/questions/14174162/arduino-micro-triggering-with-no-contact>
<https://forum.arduino.cc/t/high-impedance-output-pin/655236>

title: Arduino Micro digital output pins floating / high Z

Answers: 0


body:
I am using schematic of Arduino Pro mini 3.3v/8 MHz version. Please see below circuit diagram I built.
[![enter image description here][1]][1]

Power supply to circuit is 3.3V.

I have a USB ASP programmer which I used in previous version of same circuit running at 5V/16MHz. It was working fine.
It is connected to board like this.
[![enter image description here][2]][2]

I want to burn bootloader in this controller so that I can use with arduino IDE. I have done following settings.
[![enter image description here][3]][3]

When I connect USBASP to PC (Windows 10), in device manager, I see the USBASP. Driver installed through Zadig.

[![enter image description here][4]][4]

When I click Tools -->  Burn Bootloader in arduino IDE , I get this error

avrdude: error: program enable: target doesn't answer. 1

avrdude: initialization failed, rc=-1

         Double check connections and try again, or use -F to override
         this check.

Error while burning bootloader.

[![enter image description here][5]][5]

  [1]: https://i.stack.imgur.com/yoxKc.png
  [2]: https://i.stack.imgur.com/jq6qT.jpg
  [3]: https://i.stack.imgur.com/8lt5I.png
  [4]: https://i.stack.imgur.com/Q2wnu.png
  [5]: https://i.stack.imgur.com/EyYOm.png

What I have tried:
1 - Changed firmware of USBASP to official fishl.de website.

2 - Put JP3 on USBASP.

3 - Changed driver of USBASP from libusb-k to libusb-win32 from Zadig. Error changes to

Arduino: 1.8.15 (Windows 10), Board: "Arduino Pro or Pro Mini, ATmega328P (3.3V, 8 MHz)"

avrdude: warning: cannot set sck period. please check for usbasp firmware update.

avrdude: error: program enable: target doesn't answer. 1

avrdude: initialization failed, rc=-1

         Double check connections and try again, or use -F to override

         this check.

4 - Replaced microcontroller from some other board to this board.

5 - Checked voltage on 8 MHz crsytal pins of controller. 3.12V and 3.28V. Cant see wave on oscilloscope.

Nothing works. Same error. I was hopeful that maybe atemga328 is faulty but even after changing it, it doesnt work and I cant burn bootloader and get same error.

Can this be due to crystal capacitor values of 10 pF instead of 20pF? (I chose 10nF after reading datasheet carefully).

Any ideas why this problem?

title: Can not burn arduino pro mini 8 MHz bootloader with usbasp

Answers: 1

body: The problem was related to crystal. When I changed to another crystal (different part number), it worked.


body:
I am trying to use the stepper library and the stepper object is documented like this

> This function creates a new instance of the Stepper class that represents a particular stepper motor attached to your Arduino board.
Use it at the top of your sketch, above setup() and loop(). The number of parameters depends on how you’ve wired your motor, either using two or four pins of the Arduino board.
Syntax
Stepper(steps, pin1, pin2)
Stepper(steps, pin1, pin2, pin3, pin4)
Parameters
steps: the number of steps in one revolution of your motor.
If your motor gives the number of degrees per step, divide that number into 360 to get the number of steps (e.g. 360 / 3.6 gives 100 steps).
pin1, pin2: two pins that are attached to the motor.
pin3, pin4: the last two pins attached to the motor, if it’s connected to four pins.
Returns
A new instance of the Stepper motor class.
Example
Stepper myStepper = Stepper(100, 5, 6);
"""

The problem is that "two pins" and "last two pins" do not tell me anything about which pins go where on the motor driver. I am using a DM320T stepper driver

Can anybody tell me what "pin1 pin2 pin3 pin4" actually correspond to?

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

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

title: Please help me navigate the stepper motor object definition in the documentation

Answers: 1

body:
The standard `Stepper` library does not support stepper drivers, which only have a step (in this case labels "PUL" for pulse) and a direction pin (labeled "DIR"). So you need to use a different library. I suggest using the [`Accelstepper` library][1], which is also more capable than the standard `Stepper` library. Then you can define the `AccelStepper` object like this:

    AccelStepper stepper(AccelStepper::DRIVER, STEPPER_DIR_PIN, STEPPER_STEP_PIN);

About the connections: The shown driver is meant to be connected with twisted wire pairs, so in this case one wire for signal and the other for ground or 5V. Look at the documentation for your stepper driver. There you should be able to find a wiring diagram.

  [1]: https://www.arduino.cc/reference/en/libraries/accelstepper/


body:
I have set up a single pulse (width of ~400 ms) using the burst feature on the Tektronix AFG3102 function generator and I want to transfer this signal to the digital pin of Arduino UNO. Essentially I want to continuously (in a loop) perform reading on pin 7 using the built-in digitalread() function. So I'm expecting to see 0 when I did not trigger the signal and 1 when I trigger the signal for a duration of 400 ms and then back to 0. However, this is not the case here as I'm just reading 0s even though I trigger my signal. Interestingly when I change the width of the pulse to 1ms I can see the signal coming through, but It does seem to work with 400 ms.

I have placed my code here for your review. I would highly appreciate some help on this.

    void setup() {
        Serial.begin(9600); // start serial for output
        pinMode(7,INPUT);
    }
    void loop() {
          Serial.println(digitalRead(7));
          Serial.print('\n');
    }

Thank you,

Nikan

title: Transfer a single pulse from Tektronix function generator to Arduino UNO

Answers: 0


body:
I am trying to convert

this project <https://maker.pro/arduino/projects/simple-fm-radio-receiver-with-arduino-uno-and-rda5807m>

to  3 touch sensors TTP223.

But so far  my new code don't work.

Please can you have a look at these changes?

Update:

The code goes in loop and the serial monitor show:
push 3
push 4
push 2
push 3
push 4
push 2

and so on

I can also see in the oled, the 3 menu options change cyclically.

TTP223 sensor linked to pin 4 stay always with his red light on.

If I touch the sensor connected to pin 3,  menu does not change (Manual tune,  Volume, Auto tune).

(I have checked Touch sensors if they work alone).

```
|
|
//TTP223
#define Pin_DOWN 4   //  destra
#define Pin_UP 2     // sinistra
#define Pin_SET 3    // menù
#define FIX_BAND 1

int menu;
#define MAXmenu  3
int menux;
#define MAXmenux  3

|
|
void setup()
{
  Wire.begin();
  //Serial.begin(9600);
  Serial.begin(57600);

//TTP223
pinMode(Pin_DOWN,INPUT_PULLUP );
pinMode(Pin_UP,INPUT_PULLUP);
pinMode(Pin_SET,INPUT_PULLUP);
boolean SET=digitalRead(Pin_SET);
boolean UP=digitalRead(Pin_UP);
boolean DOWN=digitalRead(Pin_DOWN);

|
|
void loop() {
  int newPos;
  unsigned long now = millis();
 // static unsigned long nextFreqTime = 0;
  static unsigned long nextRadioInfoTime = 0;
  char c;
  /*entradaV = analogRead(entrada);

   #if DEBUG
      Serial.print("sensor = " );  Serial.println(entradaV);delay(50);
   #endif
   */
// Boton menu   d
/* if(entradaV>500 && entradaV<524)
   { */
//TTP223
if(digitalRead(3) == HIGH) {
    delay(150);
    Serial.println("push 3");
    menu++;
    if(menu>MAXmenu)menu=1;
    Visualizar();

    #if DEBUG
      Serial.print("menu = " );  Serial.println(menu);
    #endif
    //while(1020>analogRead(entrada))delay(5);

   }

// Boton derecho
/* if( entradaV<50)
   { */
//TTP223
if(digitalRead(4) == HIGH) {
    Serial.println("push 4");
    menux++;
    if(menux>MAXmenux)menux=MAXmenux;
    #if DEBUG
      Serial.print("menux = " );  Serial.println(menux);
    #endif
    switch(menu)
      {
        case 1:
          frecuencia++;
          if(frecuencia>210)frecuencia=210;
          delay(130);
        break;
        case 2:
           volumen++;
           if(volumen>15)volumen=15;
           // while(1020>analogRead(entrada))delay(5);
        break;
        case 3:
           busqueda(0);
           // while(1020>analogRead(entrada))delay(5);
        break;
        case 4:
           // LcdClear();
            tft.clearDisplay();
           // visualPI();
            delay(3000);
           // LcdClear();
            tft.clearDisplay();
            frecuenciaOld=-1;
        break;
      }
   }

// Boton izquierdo
/* if( entradaV<700 && entradaV>660)
    { */
//TTP223
if(digitalRead(2) == HIGH) {
    Serial.println("push 2");
    menux--;
    if(menux<1)menux=1;
    #if DEBUG
      Serial.print("menux = " );  Serial.println(menux);
    #endif
    switch(menu)
      {
        case 1:
            frecuencia--;
            if(frecuencia<0)frecuencia=0;
            delay(130);
        break;
        case 2:
            volumen--;
            if(volumen<0)volumen=0;
            // while(1020>analogRead(entrada))delay(5);
        break;
        case 3:
            busqueda(1);
            // while(1020>analogRead(entrada))delay(5);
        break;
        case 4:
           // LcdClear();
          tft.clearDisplay();
            //tft.print(frecuencia);
            //visualPTY();
            delay(3000);
           // LcdClear();
            tft.clearDisplay();
            frecuenciaOld=-1;
        break;
      }

   }
|
|
```

title: HOW convert momentary button to touch sensor TTP223?

Answers: 0


body:
I'm almost successfully able to GET a json blob and print it to the console. It seems to be failing on *some* string fields I am guessing because of the length. Any thoughts/ideas/suggestions to make this work?

The requested json blob (I can see this entire string from the console, it is spaced out here for readability). The entire length of the original string happens to be 597 characters.

```
{
 "expand":"schema,names"
 ,"startAt":0
 ,"maxResults":50
 ,"total":2
 ,"issues":[{
   "expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields"
  ,"id":"94245"
  ,"self":"https://myServer.atlassian.net/rest/api/3/issue/9425"
  ,"key":"BP-4349"
  ,"fields":{
   "summary":"QM: API Timeout Error on Checkout "
  }
 }
 ,{"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields"
  ,"id":"93129"
  ,"self":"https://myServer.atlassian.net/rest/api/3/issue/9319"
  ,"key":"BP-4078"
  ,"fields":{
   "summary":"Search \"term\" options - broken in loader see sproc"
  }
 }]
}
```

The code I'm using to fetch this json object reduced as much as possible:

```
JsonRequest request(2048);
//...snip...// (inside JsonRequest object)
WiFiClientSecure *client = new WiFiClientSecure;
HTTPCliernt download_client;
download_client.begin(*client, url);
download_client.collectHeaders(headerKeys, 5);
download_client.setAuthorizationHeader(authValue);
download_client.setUserAgent( HARDWARE_NAME );
int httpCode = download_client.GET();
if(httpCode == HTTP_CODE_OK)
{
 String result = download_client.getString();
 download_client.end();
 client->stop();
 dsError = deserializeJson(*this, (uint8_t*) (result.c_str()) );  //this refers to this object which is the JsonRequest
 if(!dsError)
 {
  ...
  return true;
    .....
(outside JsonRequest object, request is a deseralized `SpiRamJsonDocument` )
//...snip...//

int total = request["total"].as<int>();       //working: 2
int startAt = request["startAt"].as<int>();      //working: 0
int maxResults = request["maxResults"].as<int>();    //working: 50
int totalRecords = total + startAt;
for(; startAt < totalRecords && maxResults > 0; startAt++, maxResults--)
{
 log_i("%s: %s - %s"
  ,request["issues"][startAt]["key"].as<String>()     //working: BP-4349
  ,request["issues"][startAt]["fields"]["summary"].as<String>() //broken? (garbage string)
  ,request["issues"][startAt]["self"].as<String>()    //broken? (garbage string)
 );

}
```

I don't know why some strings worked and some did not. I assume that the length of the string is the problem ?
How would you suggest I retrieve the longer strings ?
How do I know when the length dictates the use of `.as<String>()` vs something else?

title: Problem deseralizing some fields in JsonRequest

Answers: 1

body:
Turns out there is a arduino json troubleshooter specifically for this type of issue here: https://arduinojson.org/v6/troubleshooter/  wow awesome. If you are having an similar issue I would start there.

This didn't fix my problem, for myself if I cast the types to `const char *` meaning

```
...snip...
const char* x = request["issues"][startAt]["self"].as<const char *>()
log_i("%s", x);
...snip...
```

this worked every time for every string


body:
I need to write and read the measurements received by a sensor on an SD card. The card reading would be to display the data on a TFT screen. Specifically, I am using the 1.8-inch ST7735 screen. To use the card with Arduino I am using an SD card reader module (ANGEEK brand). Both devices work with SPI protocol.

To verify that this would be possible I make a test code. In it, two functions (measure_V and measure_I) simulate the voltage and current measurements. So what I do is call those two functions to get 10 measurements and save all of them to SD. Then I read them and display them on the screen. I show them both on the serial monitor and on the TFT screen. In order to map the values of V_data and I_data I use two functions that give me the maximum value in each measure. However, nothing appears either on the serial monitor or on the screen. The two devices share the MISO, MOSI, and SCK pins. Could someone help me with this? It is the first time that I use the SPI protocol with more than one device.

```
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <SD.h>
#include <SPI.h>

#define TFT_CS 10
#define A0_pin 8
#define RST_pin 9

#define SD_CS 7                                              // CS pin of SD card connected to pin 7 of Arduino

Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, A0_pin, RST_pin);

const uint8_t rotation=2;                                    // Origin of coordinates top left

float V_data[10], I_data[10];                                // Store voltage and current measurements

File V_points;
File I_points;

const uint16_t  Display_Color_Green = 0x07E0;                // Green color

int measure_V(int x){
  int voltage;
  voltage = x;
  return voltage;
}

int measure_I(int x){
  int current;
  current = pow(x, 2);
  return current;
}

int max_V(){
  int maxVal = 0;
  for (int i=0; i<sizeof(V_data)/sizeof(float); i++) {
    if (maxVal < V_data[i]) {
      maxVal= V_data[i];
    }
  }
  return maxVal;
}

int max_I(){
  int maxVal = 0;
  for (int i=0; i<sizeof(I_data)/sizeof(float); i++) {
    if (maxVal < I_data[i]) {
      maxVal= I_data[i];
    }
  }
  return maxVal;
}

void setup() {

  Serial.begin(9600);
  tft.initR(INITR_GREENTAB);                                                // Initialize a ST7735R chip, green tab
  tft.setSPISpeed(40000000);
  tft.setRotation(rotation);                                                // We set type of rotation
  tft.fillScreen(ST7735_BLACK);

  Serial.print("Initializing SD card...");

  if (!SD.begin(SD_CS))
  {
    Serial.println("SD initialization failed!");
    while (1) ;
  }
  Serial.println("SD initialization done.");
}

void loop() {

  int static n = 0;                                                              // Measurement number (initial measurement = 0)
  uint16_t pixelV, pixelI;

  // We perform and save on the memory card 10 measurements
  for(int i=0; i<=9; i++){
    V_points.print(measure_V(i));                                                // New voltage value
    I_points.print(measure_I(i));                                                // New current value
    }

  // We read the 10 measures of the card
  while (V_points.available() && I_points.available()){
    V_data[n] = V_points.parseFloat();                                           // Read voltage value from file
    I_data[n] = I_points.parseFloat();                                           // Read current value from file
    Serial.print("Voltage= ");
    Serial.print(V_data[n]);
    Serial.print(", ");
    Serial.print("Current= ");
    Serial.println(I_data[n]);
    pixelV = map(V_data[n], 0, max_V(), 0, 128);                                 // We map tension
    pixelI = map(I_data[n], 0, max_I(), 0, 160);                                 // We map current
    tft.drawPixel(pixelV, pixelI, Display_Color_Green);
    n++;
    }

}

```

title: SPI protocol with multiple devices

Answers: 0


body:
Under normal operation, the value of a joystick's ADC range on my board is from 0 to 1023 (10-bits). However, my graph for either axis is not continuous. Rather, there is more than one min and maximum for both axis. I am running this thread on a MSP432P401R however the code isn't any different than an Arduino.
```
int jumpFlag;
int backwardsFlag;
int forwardsFlag;
int selPin = P5_1; //Select digital pin location
int xOutPin = A14;
int yOutPin = A13;

void setupPlayerActions() {
  pinMode(selPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(selPin),jumpISR,RISING);
  //pinMode(xOutPin, ); //Analog X pin setup
  //pinMode(xOutPin, ); //Analog Y pin setup
}

void jumpISR() {
  Serial.println("Jump Detected!");
  jumpFlag = 1;
}

void loopPlayerActions() {
  int x_adc_val, y_adc_val;
  int leftThreshold=50,rightThreshold=900;
  float x_volt, y_volt;
  x_adc_val = analogRead(xOutPin);
  y_adc_val = analogRead(yOutPin);
  x_volt = ( ( x_adc_val ));  /*Convert digital value to voltage */
  y_volt = ( ( y_adc_val));  /*Convert digital value to voltage */
  if (x_volt < leftThreshold){
    Serial.println("Move Backwards");
  }
  else if (x_volt < rightThreshold){
    Serial.println("Move Forwards");
  }
  Serial.println("X_Voltage = ");
  Serial.print(x_volt);
  Serial.print("\t");
  //Serial.print("Y_Voltage = ");
  //Serial.println(y_volt);
  delay(100);

  //delay(250);
}
```
The graph goes to zero for all positive x and y integers however it briefly reaches a maximum past a small value on the -x and -y axis then sinks to about ~420. What could be causing this?

title: Joystick reading erroneous values

Answers: 1

body:
A 10 bit ADC may not have 10 bits of resolution for a given sample.  It might only have 5 or 6 bits due to random noise and other factors.  Consult the chip manufactures specifications / recommendations if you need a specific number.

What can be done?

 * If response time is not an issue, consider averaging the ADC reading.  A common coding practice is to use an [exponential moving average][1].
 * Consider a better ADC.  Many times a dedicated ADC chip (not integrated into a processor) will have better specifications.

For more in depth reading [this NXP (aka: Motorola, Freescale) application note][2] discusses "How to Increase the Analog-to-Digital
Converter Accuracy in an Application".

  [1]: https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  [2]: https://www.nxp.com/docs/en/application-note/AN5250.pdf


body: I have noticed that the parseFloat() function returns decimal numbers, but only up to 2 decimal places. Would it be possible for it to return the numbers with more decimal places? In case we need more precision

title: parseFloat() function

Answers: 1

body:
> the `parseFloat()` function returns decimal numbers

No, it doesn't. It returns a **binary** (not decimal) floating point
number.

> only up to 2 decimal places

The number returned by `parseFloat()` has 24 significant digits.
Binary digits, that is, also called “bits”. This is roughly equivalent
to 7 decimal digits.

That being said, beware of `Serial.print()`. This function converts
binary floating point numbers to decimal, and defaults to showing only
two digits after the radix point. You can ask for more:

```c++
Serial.println(x, 6);  // display x with 6 digits after the radix point.
```

If you want to gain some basic understanding of how floating point
numbers work, I recommend reading [The Floating-Point Guide - What Every
Programmer Should Know About Floating-Point Arithmetic][fp-guide].

[fp-guide]: https://floating-point-gui.de/


body:
So I have an adafruit feather M0 LoRa 900 MHz and try to connect it to a helium hotspot (add to my helium console). For that I use the [official helium documentation][1] provided by helium and I get to the point of uploading the sketch to the board, but (as stated guide) if I open the serial monitor afterwards I only get an error message called: EV_JOIN_FAILED with a seemingly random number behind the error message. The output of the serial monitor looks like this:

22924969: EV_JOIN_FAILED

24125790: EV_JOIN_FAILED

25510651: EV_JOIN_FAILED

26731900: EV_JOIN_FAILED

28546725: EV_JOIN_FAILED

29506788: EV_JOIN_FAILED

30549623: EV_JOIN_FAILED

31955928: EV_JOIN_FAILED

33169043: EV_JOIN_FAILED

34528464: EV_JOIN_FAILED

36263160: EV_JOIN_FAILED

37424536: EV_JOIN_FAILED

38958548: EV_JOIN_FAILED

40127470: EV_JOIN_FAILED

40996827: EV_JOIN_FAILED

----------

I made sure to edit the config file of LMIC and also triple checked that I entered the correct AppKey, Device EUI and App EUI into the test program.

My goal is to connect my adafruit feathe M0 to the helium console and send a Hello World packet and get developing.

Help would be apreciated.

Edit: Here is a screenshots of the adafruit feather M0 itself[![adfruit M0][2]][2]

  [1]: https://docs.helium.com/use-the-network/devices/development/adafruit/adafruit-feather-m0-rfm95/arduino/
  [2]: https://i.stack.imgur.com/P7luU.png

title: Adafruit feather helium integration

Answers: 0


body:
I have an Arduino UNO R3 where I’ve set Pin 13 to “HIGH” (as shown here) and I’ve connected an LED to Pin 13 and GND which glows brightly using a USB attached to my MacBook Air providing (I think) 5V.

Now, I’m powering the Arduino externally using a 3V (1.5+1.5) battery and the 5V/GND connection. The green light blinks showing the Arduino is being powered and the bulb glows since it’s the same circuit.

Now, I wish to connect the USB to the Arduino and basically read the voltage of the LED via Pin 13 and the GND connection. Of course, I could accomplish this by simply attaching a multimeter but that’s not the problem since it’s not the true aim of the project (which I can state if required but it’s more complicated and not too different).
But when I connect the USB the LED glows brighter and the voltage across it is around 3.5V (higher than what the battery is supplying). I want the computer to read the voltage of the battery and not supply the arduino with it’s own power. How do I accomplish this (note: I’m allowed to break certain circuitry on the Arduino but I’d prefer to do this as last resort)?

Basically, how do I read voltage readings on a computer off an arduino without powering the arduino i.e. How do I convert the USB port and my computer into a multimeter with the arduino?

(I'm very new to experimenting with this so may have made crushing mistakes. Any help is appreciated)

title: Externally powering Arduino while reading voltage off it via USB

Answers: 1

body: Pin 13 is a digital pin, it does not have the capability to read voltage. You need to use one of the analog pins to read voltage, they are prefixed with the letter "A" (A0 for example). You also need to note the Analog reference (maximum voltage reference point for the A/D) is the Arduino's +5 volt supply so if that changes so will the readings. You will get 0 with zero input and 1023 when the voltage matches the reference voltage. Note this voltage cannot exceed VCC by more than a very small amount (0.6V)or you will damage the Arduino. The USB supplies about 4.5 volts, depending on the protection circuit. If you power it via Vin with the appropriate voltage it will have nominally 5 volts and of course the ever changing battery voltage. All of these change your reference voltage changing your voltage measurement. The best solution is to power it externally and then connect the battery - to ground and the battery + to one of the A/D inputs. With a little math in your code you will have a voltmeter. There are many fine examples on line complete with code for the Arduino.


body:
I was trying to upload the source code of a project to the Arduino UNO and this is the error that I keep on receiving.

After I closed and reopened it again, the Port option is gray. I tried everything (installing new drivers, uninstalling it) but nothing works. This board works on my PC (Win 10) but doesn't work on my laptop (Win 11).

```
avrdude: ser_open(): can't set com-state for "\\.\com3" an error occurred while uploading the sketch.
```

title: Unable To Upload Source Code on Arduino UNO(Windows 11)

Answers: 0


body:
I'm sorry for this stupid question...
I'm not an electronic/electric expert..
In order to select the battery capacity as well as the solar panel I'm measuring the Arduino current consumption.
So, I connected my multimeter (in line) (I rotated the selector on 200mA) and I'm able to see the values that are:

- around 85mA for  few seconds (around 8seconds) when the system works;
- around 0.38 mA during the remaining 52 seconds when the system is in sleep mode.
I'll enable my system around 8s for each 15minutes (basically 4 times for hour)

In order to have a general idea, I would like to use a site like this https://www.digikey.it/en/resources/conversion-calculators/conversion-calculator-battery-life

Now, It's not clear for me how can I use the retrieved values:
Do I calculate the current consuming in 1h?

The values that I obtained are related to the current consumed for a second?

What I have to punt into the field "Device Consumption" on the linked web-site?

title: Arduino battery capacity selection based on the current measurements

Answers: 1

body:
You have two current values and the approximate time those currents run for.  From that you can calculate the *average* current.

If you have 8 seconds "on" and (15*60-8) 892 seconds "off" that gives you:

    (85 * 8) + (0.38 * 892)
    ------------------------
             900

Which comes out as 1.13mA on average at any point in time (that's a simple ratio calculation - the times don't matter, only the ratio between them).

Over the course of 1 hour you will consume around 1.13mA on average, which is 1.13mAh.

To run for 24 hours you will need 1.13*24 = 27.2mAh. To run for a week it's 27.2*7 = 190mAh.

The calculations, as you can see, once you have the average current are pretty simple.

Of course you need to "derate" the results since batteries *never* hold the stated amount - that is both a "theoretical maximum" under ideal conditions, which degrades over time (as you will know when your phone battery starts dying too soon), plus you *never* run a battery completely flat.  Personally I like to double the capacity to err on the safe side.

You also know that you need to charge the batteries with at least an average of 1.13mA from your solar cells. That means working out what ratio of the time will be available for actual charging (daylight with good sun brightness) and calculating how much current you will need to generate during that time to allow the system to run in the dark.


body:
I need to connect the following devices to an Arduino UNO board. The problem is that I run out of pins to be able to connect them all. Is there any way to do it?

- ultrasonic sensor
- yellow led
- green led
- red led
- buzzer
- keypad 4x4

I'm doing the project in Tinkercad

In the picture below I tried to do it, but I am missing 2 pins for the ultrasonic sensor trig and echo

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

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

title: Connecting various devices to Arduino

Answers: 1

body:
As cguck70 already stated in the comments: The pins A0 to A5 can be analog input pins, but they can also be normal digital input/output pins. You can use them to your liking, just like any other digital input/output.

So just connect two of these pins to your ultrasonic sensor and use the pin names `A0`, `A1` and so on in your code.


body:
I'd like to make some basic calculator. Currently, I'm struggling with inputs. I wanted to get from user some numerical input, then, I'd like to have an information, which type of calculation he is about to do. I'm not sure why, but I can't get any numerical input from user, because the program "jumps" ahead to the operation type. Here's some code:

    void loop(){
    int a = getNumber();

    if(a != NO_KEY){
        do{
        operationType = getOperationType();
        }while(!operationType);
      }
  }

**getNumber**

      int getNumber(){
      char userInput = customKeypad.getKey();
      int value;

      if (userInput == '0' || userInput == '1' || userInput == '2' || userInput == '3' || userInput == '4' || userInput == '5' ||
      userInput == '6' || userInput == '7' || userInput == '8' || userInput == '9'){
          value = userInput - '0';
          Serial.println("value");
          Serial.println(value);

        }
      return value;
      }

**getOperationType**

    char getOperationType(){
    char userInput = customKeypad.getKey();

      switch (userInput){

          case '+':
    //      add(a , b);
            Serial.println("add");
            break;
          case '-':
    //      subtract(a , b);
            Serial.println("subtract");
            break;
          case '*':
    //      multiply(a , b);
            Serial.println("multiply");
            break;
          case '/':
    //      divide(a , b);
            Serial.println("Divide");
            break;
          case 'C':
    //      TODO
            break;
        }
        return userInput;
      }

Can I have any hint, why I can't just get simple inputs from the keyboard?

title: Can't get input from 4x4 keyboard

Answers: 1

body:
You need to watch out for what you return and if your variables are initialized. So, what happens here:

In `loop()` you call `getNumber()`. There you declare two variables:

- `userInput`, which you initialize to the return value of `customKeypad.getKey()`. So this variable will have the value `NO_KEY` if no key is pressed.
- `value`, which you don't initialize. Thus its value is whatever was there in the variables memory space before it was allocated. This can be anything, but it is not random in most cases. It depends on what your program does prior to this, but you don't have any control over it.

Then you check for `userInput` being an ASCI digit. As you didn't press a key this obviously is false, so the variable `value` gets never written. And then you return that variable.

In `loop()` you check if the return value of `getNumber()` is unequal to `NO_KEY`. And since you didn't initialize `value`, it probably is. Thus the program goes directly to the operation type part.

---

**What to do now?**

First: Always initialize every variable that you declare in a function. Global variables get initialized implicitly, but not local variables. To be sure that I don't make an error, I just always initialize ALL my variables when declaring them.

Second: Currently `value` will not be `NO_KEY` since you don't assign that value to the variable. But doing so wouldn't fit with your program logic. `value` is the real numeric value, not the ASCI representation of it. And `NO_KEY` is defined in the `Keypad` library as `\0` (the null character, with numeric value zero). So `NO_KEY` is actually equal to `0`. And zero is also a valid input to your calculator.

Instead I would suggest returning `-1` if no key was pressed and then in `loop()` checking for that. So something like this:

    int getNumber(){
      char userInput = customKeypad.getKey();
      int value;

      if (userInput == '0' || userInput == '1' || userInput == '2' || userInput == '3' || userInput == '4' || userInput == '5' || userInput == '6' || userInput == '7' || userInput == '8' || userInput == '9'){
        value = userInput - '0';
        Serial.println("value");
        Serial.println(value);
      } else {
        return -1;
      }
      return value;
    }

    void loop(){
      int a = getNumber();

      if(a != -1){
        do{
          operationType = getOperationType();
        }while(!operationType);
      }
    }

---

That said, I have some suggestions for you for going further:

- For checking if the returned key is an ASCII digit there is actually a simple function for that: `isDigit()`. So instead of your chained equal conditions you can just use

        if(isDigit(userInput))

- If you go on in this style you will find yourself wrapping multiple loops in one another as you need to loop for waiting on a keypress. That can get rather messy and it gets difficult to add additional functionality. Instead you could implement a Finite State Machine (FSM). Here the code in `loop()` consists mainly out of a switch case structure, where every case is one state of your program. For example you could have the states NUMBER1_INPUT, OPERATION_INPUT, NUMBER2_INPUT, DISPLAY_RESULT. The switch structure uses a single int variable as a state marker. For example when you set that state variable to NUMBER1_INPUT it will stay there and loop. When the user as done the number input you can change the state variable to OPERATION_INPUT and let it continue there. It is an important concept and it will change your way of Arduino coding for the better.

    There are many resource for learning how to program a FSM. I've once written [a longer answer about this][1], but you can search for something like "Finite State Machine" on this site or the web to find out more.

  [1]: https://arduino.stackexchange.com/questions/63488/wanted-to-control-2-servos-with-serial-read/63491#63491


body:
Hi I want to connect arduino NANO to my laptop with Type-C (USB-C) ports (on below image left side [4] and other side [3]). Now I bought a USB-C to USB-C cable, because it appeared to be the right tool, but the Arduino is not even powered by this cable. if I use regular USB 3.2 Gen 2 Port (on below image [5]) everythings for fine. but this usb-c ports not recognize the Arduino NANO even NANO's power LED is not switching ON.

On the other hand If I plug in my phone to this usb-c cable it works both ports. It means that cable is working good. I have changed 2 times cable stil not responding.

On the [docs][1], it look usb-c and regular usb 3.2 ports works same. But why usb-c ports not working with Arduino. also my laptop is MSI GS66

[![enter image description here][2]][2]

[![enter image description here][3]][3]

I'd appreciate if anyone has a solution or an idea to fix it. Thanks!

  [1]: https://www.manua.ls/msi/gs66-stealth/manual?p=18
  [2]: https://i.stack.imgur.com/1fQPQ.jpg
  [3]: https://i.stack.imgur.com/J0Okp.jpg

title: USB-C to USB-C cable Arduino is not responding even not powered by this cable

Answers: 1

body:
That Nano is not USB-C compliant. Yes, it has the connector, but it doesn't do all the required handshaking to put the USB-C port on the laptop into host (and provide power) mode. This is needed because those ports are also power inputs and have to be told to output power - otherwise plug in power to them and bang horrible things happen.

You have to use the larger USB 3.2 ports which are always power providers and never power consumers.


body:
I am working on a simple data acquisition system based on an Arduino Uno. Each run would ideally collect up to 10k data points (all doubles). Obviously, the Arduino doesn't have the capacity to hold all that at once. However, as one would expect, printing out the data as its being acquired significantly slows the process down (by about a factor of 7). I have looked around to find if there's a standard way to deal with this issue in the world of Arduinos, but have come up short. I come from a background where memory is never an issue, so I'm not as well versed in this side of things.

Obviously I don't expect perfection, but any insight or sources would be helpful.

title: How do you deal with balancing the limited storage of Arduino with the decrease in speed if you just print everything as it gets measured?

Answers: 3

body: Don't use `String` and others dynamic allocated object in your code. There is not any reason for slow down serial output, only inefficient memory management.

body:
This is all about choosing the right tool for the job.

At the moment you're trying to fit 50 clowns into a mini. While there are ways of doing it (by extending the "mini" outwards with extra "room") it's not what you'd normally do.

Instead you'd hire a coach.

If you have a scenario whereby you need to store more data than an Uno can store then you would typically *use a different board with a more powerful chip*.

There's plenty out there, many that are cheaper than the Uno...

If you desperately do want to use the Uno then:

* Reduce your data size: consider using smaller variables, such as 16 bit integers and fixed point arithmetic instead of floating point values.
* Improve your data transmission: send binary data instead of ASCII data, and increase your baud rate to the highest that can be reliably achieved
* Consider adding external storage, such as an SPI SRAM chip or an SD card.

body: My solution is to use FRAM, it is much faster then printing and has almost unlimited read and write cycles. It is also non volatile so if power fails the data does not. They can be gotten I2C or SPI your preference. I purchased 32K x 8 devices for well under $6.00 last year from my favorite china supplier. You can treat it as one big ring buffer and print from it while you load data into it.


body:
I'm working on the sound reactive led lamp as my first project and have slightly different materials to start with. First I'd like to simply learn to power the LED strip.

from https://www.youtube.com/watch?v=5oRir4dck_w

I'm attaching pictures so it's as simple as possible, but I'd like to confirm where to attach the wires on the uno and the basic logic behind how to get from the attempt I have now, to actually turning on the LEDs. Thanks so much!

(I think the images show up but please let me know if not)

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

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/NGsTO.jpg
  [2]: https://i.stack.imgur.com/nCenK.jpg

title: Powering LEDs with Arduino uno 5v

Answers: 1

body: A good question, best asked as you did before frying something. My Arduino rule #1 A power supply the Arduino is NOT! Connect the ground of the LED power supply to the ground of the arduino. Then connect the data line, as you have it in your picture. If you try to operate as it is in the picture the odds are high that you will fry the regulator on the Arduino depending on the output of the wall wart. You have a 5V power supply connected to the Vin connector, that does not work as it goes through the regulator and protection circuitry before getting to the processor. You need to power via the 5V pin with a 5V power supply. This can also be used to power your LEDs assuming they do not pull much over 1 amp. If you want to power by the connector, my preference, you need about 7.5 to 12 VDC. The additional filtering does not hurt and can only help. It also helps to protect from transients.


body:
How i can create a Json Array with double values and 2 decimal point using the ArduinoJson Library?

https://arduinojson.org/v6/how-to/configure-the-serialization-of-floats/

In the folowing small example it is possible to write to the Json file a double value with 2 decimal point.

```
#include <ArduinoJson.h>

double round2(double value) {
  return (int)(value * 100 + 0.5) / 100.0;
}

double round3(double value) {
  return (int)(value * 1000 + 0.5) / 1000.0;
}

double var1 = 1.23456789;
double var2 = 5.05599991;

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

  StaticJsonDocument<200> doc;
  doc["hello"] = "world";
  doc["var1"] = round2(var1);
  doc["var2"] = round3(var2);

  serializeJsonPretty(doc, Serial);

}
```
In my sketch right now i am able to create the Json Array with the values read from a Analog input. Only the created Json Array have 9 decimal points. I do not know how to implement in my sketch, folowing the aboth example that the values inside the Json array have only two decimal points.

Follow my sketch.

```
#include <ArduinoJson.h>

#define ADC_Range_Pin  35  // Pin Range Sensor

unsigned long scale_previousMillis = 0;
const long scale_interval = 100; // Interval
const byte NUM_SAMPLES = 20;
double buffer_range [NUM_SAMPLES];

// Range Sensor Instanzen-----------------------------
double Current_range = 0; //4-20 mA
double rawADCValue_range = 0;
double ADCVoltage_range = 0; //0-3,3 V
double range = 0; //0-50mm
unsigned long range_t;

double mapfloat(double x, double in_min, double in_max, double out_min, double out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

double round_range(double value) {
  return (int)(value * 100 + 0.5) / 100.0;
}

void Read_Scale() {

  StaticJsonDocument<1000> doc;

  static int scale_counter = 0;

  if (millis() - scale_previousMillis >= scale_interval) {
    scale_previousMillis = millis();

    rawADCValue_range = 0;
    for (int i = 0; i < 100; ) {
      if (millis() - range_t  >= 1) {
        rawADCValue_range += analogRead(ADC_Range_Pin);
        i++;
        range_t = millis();
      }
    }

    ADCVoltage_range = (double)(rawADCValue_range / 100.0) * (3.3 / 4095.0);
    Current_range = mapfloat(ADCVoltage_range, 0.8, 3.3, 4, 20);
    range = mapfloat(Current_range, 4, 20, 0, 50);

    buffer_range[scale_counter] = range ;

    scale_counter ++;

    JsonArray rangeValues = doc.createNestedArray("Range");

    if (scale_counter >= NUM_SAMPLES)
    {
      for (int i = 0; i < NUM_SAMPLES; i++) {
        rangeValues.add (buffer_range[i]);
      }

      serializeJson(doc, Serial);
      Serial.println();
      scale_counter = 0;
      Serial.println();

    }
  }
}

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

void loop() {
  Read_Scale();
}
```

title: Arduino create Json Array with double values and 2 decimal point

Answers: 1

body:
You defined the rounding function `round_range()`, but never used it.
You want to round the numbers that you are putting into the array within
the JSON document:

```c++
rangeValues.add(round_range(buffer_range[i]));
```