body:
I have been trying for a long time how to use a word declared as `const string* word = "xxx"` as name of void function declared somewhere below in my code.

Here is example with `ssid`:

```c++
const char* ssid = "name_of_ssid";

void (*name of ssid*) () {

⠀//some code

}
```

I want to use word declared in `const char*` in quotation marks as name of function.
It can not be written just `void ssid()`.
Yes, I can set a name of void function manually, when `const char* ssid = "CoffeeWifi"` I can type `void CaffeeWifi()` but I want to do that by this way because my code is specific for this option and explaining this code here would be very difficult. When I change array of `const char*` word from `"xxx"` to `"yyy"` I want to  change the name of void from `void xxx()` to `void yyy()` as well.

How to do that? What function should I use?

Thank you!

title: Use chars in quotes in const char* as name of function

Answers: 2

body:
Such a thing is impossible (unless you keep striving; neither have I tried it yet). Judging from your intention, one thing you can do is to create an array of the names of the functions you'd like to use, another array carrying the pointers to the functions and a programme to call the function according to the input text. I haven't tried it myself, so perhaps I may not sound sensible, but that is the only thing that came to my mind.

An example:
```
String function_names[3] = {"foo", "bar", "quux"}; /* I am not sure of this syntax;
                                                corrections are welcome */
int *functions[3] = {&foo, &bar, &quux};

String input;

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

void loop(){
        while(Serial.available()){
              String temp_input = Serial.readString()
              input = (temp_input == "")? String("Nothing here") : temp_input;
              execute(input);
        }
        delay(1000);
}

void execute(String func_name){
        for(int i = 0; i < 3; i++){
              if(function_names[i] == func_name){
                     *functions[i]();
              }
         }
}

int foo(){
    Serial.println("foo");
    return(0);
}

int bar(){
    Serial.println("bar");
    return(0);
}

int quux(){
    Serial.println("quux");
    return(0);
}
```

body:
Being a const char, you can set it at compile time with a define and then use it.

    #define fstring(x) #x

    const char* ssid = fstring(SSID_NAME) ;

    void setup() {
      Serial.println("Start");
      Serial.println(ssid);
      SSID_NAME();

    }

    void loop() {}

    void SSID_NAME (){
      Serial.println(ssid);
    }

Instead of using quotes, this uses the stringize operator.


body:
I am designing an automation system for my research project and planning on using Arduino Uno to do the same. The program is to execute simple instructions based on few input parameters and does not need large computational powers. It is estimated it would take 26 minutes to run the program (26-minute cycle*) and it is expected that it would take anywhere from 3 weeks to 2 months to complete the project (1160 - 3300 cycles before reboot)

My question is as follows:
 1. Is the Arduino Uno capable of surviving the extended service expectancy and execute the program correctly?
 2. What is the influence of small voltage fluctuations on the endurance of electronics on the board?
 3. Is a heat sink needed for this application? How to determine the power draw to choose heat sink size?
4. Is there any fatigue rating for the cyclic running of the program?

I am planning to power the entire system via a regulated 12V 600-watt battery bank and this bank would be periodically recharged.

*By cycle duration I mean the real word time required for completion of one batch. It is estimated that it's required to complete 1160-3300 cycles/batches for the research

title: Endurance of Arduino UNO during 24/7 operations and mild power fluctuations

Answers: 3

body:
I see no problems in that. Given the program you write is stable and correct, the Arduino UNO will certainly work without any problems for months. It has an integrated voltage regulator, so you can attach a 12V battery directly and it automatically regulates voltage changes. The CPU and/or flash do not have any "fatigue" problems as long as the program is only read or executed. The program flash has a limited number of write cycles, but that also is far beyond where you'll get problems.

Where I do see a problem is in your use case. You seem to be doing quite complex mathematics with quite a lot of data, when one cycle takes 26 Minutes. You might not have enough RAM on the UNO to do this. It has only 2.5k (that is around 2500 bytes) of RAM. Where do you store the results?

body:
> Is the Arduino Uno capable of surviving the extended service expectancy and execute the program correctly?

Yes, it is. Though your program and wiring needs to be stable and correct.

> What is the influence of small voltage fluctuations on the endurance of electronics on the board?

Depends on what you call small. As long as you don't enter the brown-out region (where the voltage is so low, that the Arduino goes into reset for safety) or giving a too high voltage to it (See the specifications for that), you should be fine.

> Is a heat sink needed for this application? How to determine the power draw to choose heat sink size?

The power draw of the Arduino depends on what you are doing with it. The best way would be to just measure the current of your application. Then you get the power by multiplying current and voltage. Normally you don't need a heatsink with an Arduino. The only part, that can get hot, is the linear voltage regulator. Depending on what you are interfacing with the Arduino, you might need to put a small heat sink on that (12V is a bit on the high side of input voltage for the regulator. It will dissipate the excess 7V as heat, so 7V multiplied by the used current). The microcontroller on the Arduino will not get hot (unless you are doing something terribly wrong).

And you should make sure, that the current for extra peripherals in your project doesn't flow through the Arduino, since that will place an extra burden on the voltage regulator. It should flow past it (means you connect them in parallel to the voltage source).

> Is there any fatigue rating for the cyclic running of the program?

No, not really. I think the flash memory (where the program is stored) has a data retention failure rate of less then 1ppm (parts per million) over 20 years. So the program will not be lost, until you plan to run your application a hundret years. Also there is no read limit on the flash memory, only a write limit.

body: I have Arduino here powered over year long, still working (running the same loop() again and again) without a glitch and it is not even hand-temperature hot in my living room - I expect it to run flawlessly for lot more years, until I will switch it off :)


body:
I want to open notepad by my Digispark. I use this code:

```c++
/*  * Generated with <3 by Dckuino.js, an open source project !  */

#include <avr/pgmspace.h>
#include "DigiKeyboard.h"

const char line1[] PROGMEM = "notepad.exe";
const char line2[] PROGMEM = "Hello World!";

char buffer[256];

#define GetPsz(x) (strncpy_P(buffer, (char*)x, 256))
#define KEY_UP_ARROW      0x52
#define KEY_DOWN_ARROW    0x51
#define KEY_LEFT_ARROW        0x50
#define KEY_RIGHT_ARROW       0x4F
#define KEY_LEFT_GUI          0xE3
#define KEY_ESC               0x29
#define KEY_TAB               0x2B

void digiBegin() {
  DigiKeyboard.sendKeyStroke(0,0);
  DigiKeyboard.delay(50);
}

void digiEnd() {
  const int led=1;
  pinMode(led, OUTPUT);
  while (1) {
    digitalWrite(led, !digitalRead(led));
    DigiKeyboard.delay(1000);
  }
}

void printText(char *txt) {
  DigiKeyboard.print(txt);
  DigiKeyboard.update();
}

void setup() {
  digiBegin();

  DigiKeyboard.sendKeyStroke(KEY_R,MOD_GUI_LEFT);

  DigiKeyboard.delay(50);

  // notepad.exe   printText(GetPsz(line1));

  DigiKeyboard.sendKeyStroke(KEY_ENTER);

  DigiKeyboard.delay(100);

  // Hello World!   printText(GetPsz(line2));

  digiEnd();
} /* Unused endless loop */ void loop() {}
```

My program opened RUN Windows, but instead of typing "notepad.exe" it types "fgl]hY&]p]" and I don't know where am I am making mistakes. Please help me.

I have to write my code similar this:

```c++
#include "DigiKeyboard.h"

int pinled = 1;

void setup()
{
    pinMode(3, INPUT);

    digitalWrite(3, HIGH);
}

void loop()
{
    DigiKeyboard.sendKeyStroke(0);

    if(digitalRead(3) == LOW)
    {
        DigiKeyboard.sendKeyPress(KEY_R, MOD_GUI_LEFT);
        DigiKeyboard.delay(10);

        DigiKeyboard.sendKeyStroke(0, 0);

        DigiKeyboard.sendKeyStroke(KEY_C);
        DigiKeyboard.sendKeyStroke(KEY_M);
        DigiKeyboard.sendKeyStroke(KEY_D);
        DigiKeyboard.sendKeyStroke(KEY_ENTER);

        DigiKeyboard.delay(500);

        DigiKeyboard.sendKeyStroke(KEY_I);
        DigiKeyboard.sendKeyStroke(KEY_P);
        DigiKeyboard.sendKeyStroke(KEY_C);
        DigiKeyboard.sendKeyStroke(KEY_O);
        DigiKeyboard.sendKeyStroke(KEY_N);
        DigiKeyboard.sendKeyStroke(KEY_F);
        DigiKeyboard.sendKeyStroke(KEY_I);
        DigiKeyboard.sendKeyStroke(KEY_G);
        DigiKeyboard.sendKeyStroke(KEY_ENTER);
    }
}
```

title: Mistake in keyboard typing by Digispark

Answers: 0


body:
For a project I am working on, I need to connect my ESP32 board to another server via MQTT protocol. I am using the Mosquitto MQTT Broker and it is presently on my laptop. Following is the test code I am using, which I'll build around this program.
```

#include <WiFi.h>
#include <PubSubClient.h>

const char* ssid = "*****";              //WiFi Name
const char* password = "********";      //WiFi Password
const char* server= "***.***.**.***";    //RPi or Machine IP on which the broker is

WiFiClient espClient;
PubSubClient client(espClient);

int setup_WiFi(){
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.print("Attempting MQTT connection...");
  client.connect("esp32");
  if (client.connect("esp32")){
      Serial.println("connected");
    }
    else {
      Serial.print("failed, rc=");
      Serial.println(client.state());
    }
    return 0;
}

int reconnect() {
  unsigned long startAttemptTime = millis();
  while (!client.connected())
  {
    Serial.println("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("esp32")){                 //if (client.connect("esp32", MQTT_USER, MQTT_PASS)) {
      Serial.println("connected");
    }
    else {
      Serial.print("failed, rc=");
      Serial.println(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
  return 0;
}

int send_mqtt(){
  setup_WiFi();
  char sss[15]="Hello World";
   if (!client.connected()){
    reconnect();
  }
  client.publish("esp32/test", sss);    //send message
  WiFi.disconnect(true);
  Serial.println("Sent");
  return 0;
}
void setup() {
  Serial.begin(115200);
  client.setServer(server, 1883);   //mqtt server details
  setup_WiFi();
  reconnect();
  send_mqtt();
}

void loop() {
  send_mqtt();
  delay(10000);     //Wait 10 secs before next transmission
}
```
I tried connection but got this error
>Attempting MQTT connection...failed, rc= -2

What am I doing wrong? Any changes I need to make to the .conf file about which I don't know?
Guide me.
Thank You in advance

title: Connect ESP32 via MQTT

Answers: 1

body:
The code in your sketch is unlikely to be the problem. It works fine for me after I enter the IP addresses and password for my network.

According to the [pubSubClient API documentation](https://pubsubclient.knolleary.net/api#state), the `rc = -2` code returned by `client.state()` is due to the network connection having failed. As your code has already checked that it is connected to WiFi before trying to contact the MQTT broker, it is probably the communication between the two devices that is the issue, not the WiFi connection itself.  Things to check:

1. Are both devices are on the same network, and do they have a route to contact each other? From the laptop running the MQTT broker, try running `ping XXX.XXX.XXX.XXX` (replacing the XXXs with the IP address reported by the ESP32), and check you get a response. You might wish to comment out line 67 of your code so it doesn't disconnect from WiFi after every attempt at sending a message, otherwise you will see lots of lost packets.
2. Have you got the right IP address for the MQTT broker in your sketch? It should be the IP address for your laptop, not the loopback address, `127.0.0.1`.
3. Can you use another device on the same network to connect to the MQTT server? (e.g. a cellphone running a MQTT dashboard app, or [MQTT Explorer](http://mqtt-explorer.com/) in Windows)
3. Is Mosquitto configured to listen out for remote connections? If you are running v2 of Mosquitto, you have to deliberately [configure it](https://mosquitto.org/documentation/migrating-to-2-0/#listener-behaviour-changes) to accept incoming connections, otherwise it will only listen to the `localhost` interface. You would also have to either set up an authentication mechanism or explicitly configure it to allow anonymous connections. This might be why you can connect from the laptop running the broker, but not from other devices.
4. On the MQTT server, can you see any connection attempts in Mosquitto's log file (`/var/log/mosquitto/mosquitto.log`)? There might be some error messages that give you further clues.


body:
I am intending to use the Arduino Due processors into my own designs. We have a very extensive (dozen of thousands of lines in .c code) sets of Arduino Due functional codes, and now I intend to move into a more solid form shape.

I have the following questions. What i need is some sort of feedback in order to answer those by myself and realize how to proceed.

 1. I understand some of the Fast Speed Serial options in the Microchip IC cannot be tried in the Arduino Due (such as USBOTG?)?. What I actually need is some Serial Speed close to 2Mbps and a USB Programming Port.

 2. Which are the main differences between the [Microchip ATSAM3X8E][1] and the Atmel ATSAM3X8E? R: No, they are the same.

 3. I notice there are some functionalities in the Microchip ATSAM3X8E or even in the Atmel ATSAM3X8E not able to be reproduced in the Arduino Due Board?

 4. Do The Microchip ATSAM3X8E IC have its own functionalities not present in the Atmel ATSAM3X8E? R: No, they are the same.

 5. As note, there is a [Keil ARM SAM3X-EK Evaluation Kit][4] (also also [here][2] with its [brochure][3]), with a ATSAM3X8H, which is not the same IC series, but somehow exposes my concern (if real).

 6. If my concern about High Speed Serial is real, how should I evaluate it?

  [1]: https://www.microchip.com/wwwproducts/en/ATSAM3X8E
  [2]: https://www.keil.com/boards2/atmel/sam3x_ek/
  [3]: https://keilpack.azureedge.net/content/Keil.SAM3_DFP.1.2.2/Boards/Atmel/SAM3X-EK/Documents/doc_11156.pdf
  [4]: https://www.element14.com/community/docs/DOC-47133/l/atmel-atsam3x-ek-evaluation-kit

title: Do I need an Microchip ATSAM3X8E Evaluation Kit?

Answers: 1

body:
> I understand some of the Fast Speed Serial options in the Microchip IC cannot be tried in the Arduino Due (such as USBOTG?)?. What I actually need is some Serial Speed close to 2Mbps and a USB Programming Port.

What would make you think that? The chip is the chip regardless of what board it's soldered to. You have the native USB and you have all the UART connections direct to the chip. The board has no effect on that at all.  2Mbps is nothing. You can go *much* faster than that.

> Which are the main differences between the Microchip ATSAM3X8E and the Atmel ATSAM3X8E?

The label. When Microchip bought Atmel a few years back they bought *everything*. That includes the Malaysian factories where the Atmel chips are made (a friend of mine had the job of inventory combining and spent quite some time in Malaysia sorting it all out). Microchip ATSAM3X8E chips are made in the same factory by the same people to the same designs on the same machines. It's just they are now labelled "Microchip" instead of "Atmel".

> I notice there are some functionalities in the Microchip ATSAM3X8E or even in the Atmel ATSAM3X8E not able to be reproduced in the Arduino Due Board?

Is that a question or a statement. Or aren't you sure? The Due is just a chip on a board with some support circuitry. Everything that is in the chip is there, you can't remove it. There may be the case that a specific pin may not be brought out to a header, but you will have to compare the datasheet with the schematic in that case. The chip is not at fault here.

> Do The Microchip ATSAM3X8E IC have its own functionalities not present in the Atmel ATSAM3X8E?

No. The two are 100% identical.

> As note, there is a Keil ARM SAM3X-EK Evaluation Kit (also also here with its brochure), with a ATSAM3X8H, which is not the same IC series, but somehow exposes my concern (if real).

The ATSAMA3X8H is not commercially available. It was a specific custom chip made only for the SAM3X-EK kit. It is, essentially, a SAM3X8E with more IO pins and the ability to connect to SDRAM.

> If my concern about High Speed Serial is real, how should I evaluate it?

Your concern is not real. Only imagined. The only possibility is that the UART to USB chip used on the Due may not be able to keep up at high baud rates. That has nothing to do with what the SAM3X8E can do, just what the interface to your PC is capable of. You can replace that with an external USB to UART interface if you want, such as an FT232R based interface. That is if it's communication with your PC that you're concerned about, in which case you would be better with the native USB interface as it's not restricted by whatever external hardware is added.


body:
I wish to connect an Arduino ( any of 328P family ) which its 5v, with ESP8266 (ESP-01, or even NodeMCU or Wemos D1 mini ) which is 3v3 logic. My goal is that ESP8266 will be in-charge of MQTT messages and other remote abilities, while Arduino board will be in charge of UP/Off/Down rocker switch and 2 relays ( For reliability I rather have this setup ). **Both MCU's code is written by me using Arduino**

I Know of 2 main ways: voltage divider and level shifter ( and 3rd will be to use a 3v3 logic as pro-mini - but let's leave for now ).

My questions are:

A) Does `Rx` `Tx` need a voltage to be the same ( some on-line tutorial ignore this at all )? if so, is it needed both ways ?

B) Some Tutorial mention that using a voltage divider create some communication interference. It is true and/ relevant for use as explained ?

C) Does `SofwareSerial` library is recommended (again - reliability ).

title: Serial Communication between ESP8266 and Arduino ( Sofware and Hardware )

Answers: 2

body:
> A) Does Rx Tx need a voltage to be the same ( some on-line tutorial ignore this at all )? if so, is it needed both ways ?

The point is, that often 3.3V MCUs cannot tolerate voltages significantly above that. So connecting 5V can hurt it. I've seen quite a bit of discussion online, if ESP boards are 5V tolerant or not, but I haven't seen a real investigation in this. Often you can very well get away with connecting them directly, but nobody will give you any guarantees about this. If you want to be safe, you need to add some kind of voltage transition from Arduino TX to ESP RX. The other line (ESP TX to arduino RX) is driven by the ESP with 3.3V, which is ok for the Arduino (3.3V is enough for the Arduino to see it as HIGH), so you don't need anything on this line.

> B) Some Tutorial mention that using a voltage divider create some communication interference. It is true and/ relevant for use as explained ?

Since a voltage divider is passive, you get extra effects (parasitic capacitance and inductance), which limits the baudrate. Though I still got communication without errors with baudrates up to 115200 (I did not do a thorough investigation, this is just subjective experience). Electronically better would be proper level shifting (which uses transistors), but in most cases a voltage divider also works well. So I would say unless you want to use really high baudrates you are good with a voltage divider. Others can of course also provide their experience on this site.

> Does SofwareSerial library is recommended (again - reliability ).

Generally a Hardware Serial interface is always better, since the communication protocol is completely handled in hardware. The code just needs to read and write the individual bytes from/to hardware registers. `SoftwareSerial` is used, when there is no free to use Hardware Serial interface. And it imposes some extra limits: You can only listen to one `SoftwareSerial` interface at any give time and you cannot use high baudrates with it (I think 115200 is already too high for it, depending on the used Arduino). Also it depends on the rest of your code (depends on your use of ISRs). So, if you have an unused hardware Serial interface on your Arduino board, you should use that. Otherwise you can use `SoftwareSerial`.

body:
Just adding a little flesh to @chrisl's excellent answer with some added technical detail:

>B) Some Tutorial mention that using a voltage divider create some communication interference. It is true and/ relevant for use as explained ?

The problem here is that the resistors and the input pin's capacitance form a low-pass filter. Too high a resistance and you deform the nice clean square wave of the serial data. This limits the baud rate you can reliably use. Reduce the resistor values and you increase the frequency of the filtering, thus allowing higher baud rates, but at the cost of increased current draw from the TX pin.

> Does SofwareSerial library is recommended (again - reliability ).

The problem of SoftwareSerial is twofold: it's very much a "blocking" system, whereby the MCU can't be doing anything else when a byte is being either received or transmitted, and it's very picky about timing, partly because of that blocking.  There are two factors that affect the maximum speed you can use: how fast the MCU can process the incoming signal to work out what it is, and how fast the MCU can process that decoded signal to get it stored in the buffer.

While it's possible to receive reliably a byte at 115200 baud the problem comes when receiving multiple bytes rapidly. The Arduino is not always able to take that received byte and store it in the RX ringbuffer fast enough before the start bit of the next byte arrives, so it misses it. This causes corruption in the data stream.

For this reason I never recommend more than 9600 baud (or maybe 38400 at a pinch) to give the Arduino more time to process the bytes as they arrive. However that then means that more time is spent doing the sending or receiving, which blocks the rest of your program during that time for longer.

Also SoftwareSerial is strictly half duplex: when you're receiving you can't send, and when you're sending you can't receive. It's only really of any use in a "call-response" style protocol where switching between sending and receiving is predictable.


body:
I am trying to put BLE and WiFi web server on the same ESP32 board, using Arduino IDE.
However, BLE library is too heavy. It spends about 73% of program size and there no room for WiFi.

    Program too big. The size is 1328706 bytes (of a 1310720 byte maximum

These are libraries I am trying to use in the same solution:

    #include <BLEDevice.h>
    #include <BLEUtils.h>
    #include <BLEScan.h>
    #include <BLEAdvertisedDevice.h>
    #include <EEPROM.h>
    #include <WiFi.h>

Is there anything I can try to spare program size?
Is there any alternative?

title: BLE scanner and WiFi web server on the ESP32 board

Answers: 0


body:
I am using the SIM900A gsm module and trying to connect with my site using a GET request. My issue is that when submitting AT+HTTPACTION=0, I receive a status the response as +HTTPACTION:0,600,0. In this case, the GET request is raised successfully but the response size is 0. In this case, I am not able to fetch a response from the server. The datasheet says the 600 code means "Not HTTP PDU" but I am not aware of how I need to address this. I also sometimes receive code 200, but it is very rare.
following is the response of the AT commands:

```
AT

OK
AT+COPS?

+COPS: 0,0,"Vi India"

OK
AT+CGDCONT=1,"IP","internet"

OK
AT+CGDCONT=?

+CGDCONT: (1-3),"IP",,,(0),(0)

OK
AT+SAPBR=3,1,"CONTYPE","GPRS"

OK
AT+SAPBR=3,1,"APN","internet"

OK
AT+SAPBR=1,1

OK
AT+SAPBR=2,1

+SAPBR: 1,1,"100.103.109.188"

OK
AT+HTTPINIT

OK
AT+HTTPPARA="CID",1

OK
AT+HTTPPARA="URL","mysite.co.in/newlist.php?K=THS&a=35.97&b=18.84"

OK
AT+HTTPACTION=0

OK

+HTTPACTION:0,600,0
AT+HTTPTERM

OK
```
Thanks in advance for the support.

**Edit** I have tried further, I have observed that still, the status code still remains the same 0,600,0 status code. However, when I changed the URL to www.google.com, it returns the expected +HTTPACTION:0,200, xxx status code. Please provide some guidance to get the issue resolve.

title: How to address +HTTPACTION:0,600,0 Not HTTP PDU response

Answers: 0


body:
I just got started with Arduino, and found out that I need the IDE to compile and upload codes, which works perfectly fine. This is my code:

```
# pragma GCC optimize ("Ofast")

char i = 0 ;
unsigned long time, lastTime ;

void setup() {
 pinMode(LED_BUILTIN, OUTPUT) ;
}

void loop() {
 time = millis() ;

 if (time > lastTime) {
  lastTime = time + 100 ;
  i = ~i ;
  digitalWrite(LED_BUILTIN, i  ? HIGH : LOW) ;
 }
}
```

But the biggest problem is that the IDE is written in Java and it uses 1 GB of system's memory, and it's very heavy.

So is there a way I can use the Linux command line to compile and upload the code to the Arduino UNO?

title: Is it possible to compile and upload code witout the IDE?

Answers: 1

body:
Yes, I haven't used it but on the official page it is mentioned, called Arduino CLI (command line interface), available for Mac and Linux.

https://www.arduino.cc/pro/cli

Excerpt:

> Arduino CLI is a command line tool that contains all you need to
> easily build applications around the Arduino ecosystem. Parse the JSON
> output of the CLI or implement it as an always-on service that accepts
> commands via a gRPC interface using your language of choice.
>
> Arduino CLI is the backbone of the Arduino Create Web Editor serving
> over a million users.

Also, it's open source and can be found on GitHub at https://github.com/arduino/arduino-cli/releases


body:
Rosserial Arduino custom msg publisher. I am publishing custom msg (6 float64 values and header) and subscribe Vector3Stamped msg from Arduino mega2560. But is not working!

The error I get is the following (the custom publisher is publishing correctly but the usual subscriber is not working):

> Creation of subscriber failed: need
> more than 1 value to unpack

 When I have the following in Arduino/libraries/Rosserial_Arduino_Library/src/ros.h

     #elif defined(__AVR_ATmega2560__)
           typedef NodeHandle_ <ArduinoHardware, 15, 15, 512, 512> NodeHandle

while the error is different when changing Arduino/libraries/Rosserial_Arduino_Library/src/ros.h to the following:

    #elif defined(__AVR_ATmega2560__)
       typedef NodeHandle_<ArduinoHardware, 15, 15, 512, 512,FlashReadOutBuffer_> NodeHandle;

The error I get in this case is the folowing (the custom publisher is not working but the usual subscriber is working)

> Creation of publisher failed: need
> more than 1 value to unpack

Tried to
> publish before configured, topic id
> 115

My arduino code is the following:

    #include <HardwareSerial.h>
    #include <ODriveArduino.h>
    #include <Wire.h>
    #include <ros.h>
    #include <std_msgs/String.h>
    #include <geometry_msgs/Vector3Stamped.h>
    #include <geometry_msgs/Twist.h>
    #include <ros/time.h>
    #include <mybot/encoderMsgStamped.h>

    #define ROBOT_WIDTH (480) //MILLI METER
    #define WHEEL_DIAMETER (165.1)  // MILLI METER
    #define WHEEL_CIRC (518.676947108) //circumference OF THE WHEEL
    #define CPR_ENCODER (90)

    HardwareSerial& odrive_serial1 = Serial1;
    HardwareSerial& odrive_serial2 = Serial2;
    HardwareSerial& odrive_serial3 = Serial3;
    //axis0(M0)-left
    //axis1(M1)-right
    ODriveArduino odrive1(odrive_serial1);
    ODriveArduino odrive2(odrive_serial2);
    ODriveArduino odrive3(odrive_serial3);

    // cmd_vel variables to be received to drive with
    float demandx;
    float demandz;

    // timers for the sub-main loop
    unsigned long currentMillis;
    long previousMillis = 0;    // set up timers
    float loopTime = 100;  //100ms
    long forward0;
    long forward1;
    long turn0;
    long turn1;

    // position and velocity variables read from the ODrive
    long posfl,posfr,posml,posmr,posrl,posrr;

    long posfl_old,posfr_old,posml_old,posmr_old,posrl_old,posrr_old;
    long posfl_diff,posfr_diff,posml_diff,posmr_diff,posrl_diff,posrr_diff;
    float posfl_mm_diff,posfr_mm_diff,posml_mm_diff,posmr_mm_diff,posrl_mm_diff,posrr_mm_diff;

    ros::NodeHandle nh;

    //function that will be called when receiving command from host
    void handle_cmd (const geometry_msgs::Twist& cmd_vel) {

         demandx = cmd_vel.linear.x;
         demandz = cmd_vel.angular.z;
    }

    ros::Subscriber<geometry_msgs::Twist> cmd_vel("/cmd_vel", handle_cmd);   //create a subscriber to ROS topic for velocity commands (will execute "handle_cmd" function when receiving data)
    mybot::encoderMsgStamped pos_msg;                                //create a "pos_msg" ROS message
    ros::Publisher pos_pub("encoderPos", &pos_msg);                          //create a publisher to ROS topic "encoderPos" using the "pos_msg" type

    void setup() {
      nh.initNode();                            //init ROS node
      nh.getHardware()->setBaud(115200);         //set baud for ROS serial communication
      nh.subscribe(cmd_vel);                    //suscribe to ROS topic for velocity commands
      nh.advertise(pos_pub);                  //prepare to publish speed in ROS topic
      odrive_serial1.begin(115200);
      odrive_serial2.begin(115200);
      odrive_serial3.begin(115200);
      odrive1.SetVelocity(0,0);
      odrive1.SetVelocity(1,0);
      odrive2.SetVelocity(0,0);
      odrive2.SetVelocity(1,0);
      odrive3.SetVelocity(0,0);
      odrive3.SetVelocity(1,0);
      odrive1.SetPosition(0,0.0);
      odrive1.SetPosition(1,0.0);
      odrive2.SetPosition(0,0.0);
      odrive2.SetPosition(1,0.0);
      odrive3.SetPosition(0,0.0);
      odrive3.SetPosition(1,0.0);
      Serial.begin(115200);
      while (!Serial) ;

    }

    //_________________________________________________________________________

    void loop() {
      nh.spinOnce();
      currentMillis = millis();
      if (currentMillis - previousMillis >= loopTime) {  // run a loop every 100ms
         previousMillis = currentMillis;          // reset the clock to time it
         float modifier_lin = 1.03;        // scaling factor because the wheels are squashy / there is wheel slip etc.
         float modifier_ang = 0.92;        // scaling factor because the wheels are squashy / there is wheel slip etc.

         forward0 = demandx * 1.927982351202 * modifier_lin ; // convert m/s into counts/s
         forward1 = demandx * 1.927982351202 * modifier_lin; // convert m/s into counts/s
         turn0 = demandz * 0.46271576428  * modifier_ang;    // convert rads/s into counts/s
         turn1 = demandz * 0.46271576428 * modifier_ang;    // convert rads/s into counts/s

         forward1 = forward1*-1;      // one motor and encoder is mounted facing the other way
         odrive1.SetVelocity(1, forward0 + turn0); //-1 the motors are on opposite direction
         odrive1.SetVelocity(0, forward1 + turn1);
         odrive2.SetVelocity(1, forward0 + turn0); //-1 the motors are on opposite direction
         odrive2.SetVelocity(0, forward1 + turn1);
         odrive3.SetVelocity(1, forward0 + turn0); //-1 the motors are on opposite direction
         odrive3.SetVelocity(0, forward1 + turn1);

        // get positions from ODrive
        posfr = odrive3.GetPosition(1) *-1;
        posfl = odrive3.GetPosition(0);

        posmr = odrive2.GetPosition(1) *-1;
        posml = odrive2.GetPosition(0);

        posrr = odrive1.GetPosition(1) *-1;
        posrl = odrive1.GetPosition(0);

        // work out the difference on each loop, and bookmark the old value
        posfl_diff = posfl - posfl_old;
        posfr_diff = posfr - posfr_old;
        posfl_old = posfl;
        posfr_old = posfr;

        posml_diff = posml - posml_old;
        posmr_diff = posmr - posmr_old;
        posml_old = posml;
        posmr_old = posmr;

        posrl_diff = posrl - posrl_old;
        posrr_diff = posrr - posrr_old;
        posrl_old = posrl;
        posrr_old = posrr;

        // calc mm from encoder counts
        posfl_mm_diff = posfl_diff /0.1735184116;
        posfr_mm_diff = posfr_diff /0.1735184116;

        posml_mm_diff = posml_diff /0.1735184116;
        posmr_mm_diff = posmr_diff /0.1735184116;

        posrl_mm_diff = posrl_diff /0.1735184116;
        posrr_mm_diff = posrr_diff /0.1735184116;

         publishPos();
      }
     }

    void publishPos() {
      pos_msg.header.stamp = nh.now();      //timestamp for odometry data
      pos_msg.fl = posfl_mm_diff;
      pos_msg.ml = posml_mm_diff;
      pos_msg.rl = posrl_mm_diff;
      pos_msg.fr = posfr_mm_diff;
      pos_msg.mr = posmr_mm_diff;
      pos_msg.rr = posrr_mm_diff;
      pos_pub.publish(&pos_msg);

    }

**Note:** With usual publish and subscribe msgs and the following Arduino/libraries/Rosserial_Arduino_Library/src/ros.h everything works fine for both publishing and subscribing:

     #elif defined(__AVR_ATmega2560__)
     typedef NodeHandle_<ArduinoHardware, 15, 15, 512, 512,FlashReadOutBuffer_>  NodeHandle;

title: Rosserial. Arduino Publishing custom msg (6 float64 values and header) and subscribe Vector3Stamped msg from Arduino mega2560 is not working!

Answers: 0


body:
I'm trying to set my temperature measurements to two decimal places. Currently what I get are six decimal places.
Here is my code:
```
#include "math.h"

...

(in loop)
temp1 = sensors.getTempCByIndex(0);
     temp1 = roundf(temp1*100)/100;
```
Once I push temp1 to Firebase realtime database there are sic decimals, such as 26.059999. I'm using dsb20 sensor for temperature measurements.
What could be wrong?

Thanks for your help in advance!

title: Setting float to two decimal places

Answers: 3

body:
`float` variables don't have a number of decimal places: that's how they get their name: "floating point" - the decimal point floats around as needed.

It's only when you *output* the value that it's rendered with a fixed (or limited) number of decimal places.  Using `Serial.print()` the second digit is the number of decimal points:

```c++
Serial.println(temp1, 6); // 26.059999
Serial.println(temp1, 2); // 26.06
```

body:
In addition to Majenkos answer:

A `float` cannot take any decimal number. It has a limited change and a limited resolution in that range you could say. So if often happens, that the flat (rounded) value is not a valid `float`. This is the case for `26.05`. There is no valid `float` value, that is exactly `26.05`. So the nearest valid `float` value is chosen. The following code would always print `26.059999`:

    float i = 26.05;
    Serial.println(i);

since the variable `i` contains the `float` number `26.059999` (nearest valid `float` value to `26.06`). That is the reason, why mostly the rounding of `float`s is only done directly with the outputting/printing. In that stage the number is not longer bound to the limitations of the `float` type (since it is internally not again saved in that type).

body:
one can convert to n decimals with the String Class

    float num = 3.14159
    String str1 = String(num, 1) // 3.1
    String str2 = String(num, 2) // 3.14
    String str3 = String(num, 3) // 3.141


body:
When i run the code on the Arduino the Stepper only does a small turn every cycle. How can i make that constantly turning?
``` //Servo Teil
 #include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position
//Servo Teil
#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  // set the speed at 60 rpm:
  myStepper.setSpeed(105);
  // initialize the serial port:
  Serial.begin(9600);
  //Servo
    myservo.attach(3);  // attaches the servo on pin 9 to the servo object
    //Servo

}

void loop() {
  // step one revolution  in one direction:
  Serial.println("clockwise");
  myStepper.step(stepsPerRevolution);
  //Servo
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  //Servo

}
 ```

title: How to let Stepper motor spin constantly?

Answers: 0


body:
I am experimenting with the following program I found online (with slight modifications):

```
int x;
void setup() {
 Serial.begin(9600);
 Serial.setTimeout(1);
}
void loop() {
 while (!Serial.available());
 x = Serial.readString().toInt();
 int y = x + 1;
 Serial.print(y);
}
```

I am encountering an error in Serial monitor output; if I input `1`, I get `21` printed. I think what's happening is that every digit in a number gets incremented by 1, and then `1` is put at the end for some reason. For example, if I input `234`, my output is `3451`. I think the error lies with the line ` x = Serial.readString().toInt();`, but am unsure how to fix this. Thank you!

title: Error Outputting Values Arduino Serial.print

Answers: 1

body:
There's two problems here.

First, you don't enter "234", you enter "2" followed by "3" and finally "4". Your really small timeout doesn't give the digits enough time to arrive.

Second, your line ending is being received and interpreted as "not a number" which is returned as 0 by `.toInt()`.

What you need to do is:

1. Don't set a short timeout - you can remove that line entirely.
2. Use `.readStringUntil('\n')` to read up until your line ending in one go.


body:
I got an Arduino UNO today, and I am just writing a basic blink program. I have 3 LEDS on the arduino. Those LEDS are connected to Pin 1, 2, and 3.

Now I can control those LED by writing octal values 0 to 7 to the `/dev/ttyUSB0`.

The code I have written so far is:
```
# pragma GCC optimize ("Ofast")

# define LED1 1
# define LED2 2
# define LED3 3

char buf[4] ;
unsigned char inp, len ;

void setup() {
 pinMode(LED1, OUTPUT) ;
 pinMode(LED2, OUTPUT) ;
 pinMode(LED3, OUTPUT) ;

 Serial.begin(9600) ;
}

void loop() {
 len = Serial.readBytes(buf, 3) ;

 if (len) {
  buf[3] = '\0' ;
  inp = atoi(buf) ;

  // Illuminate LEDs
  digitalWrite(LED1, 1 & inp ? HIGH : LOW) ;
  digitalWrite(LED2, 2 & inp ? HIGH : LOW) ;
  digitalWrite(LED3, 4 & inp ? HIGH : LOW) ;
 }
}
```

So when I write:
 + 0 turns off all the LEDS
 + 1 turns on LED on pin 1
 + 2 turns on LED on pin 2
 + 3 turns on LED on pin 1 and 2
 + 4 turns on LED on pin 3
 + 5 turns on LED on pin 1 and 3
 + 6 turns on LED on pin 2 and 3
 + 7 turns on all the LEDS.

The problem is that, when I write 7 for example, it takes up to 1 second to turn on the LEDS. If I write 0, it takes another second to turn off the LEDS.

Is there way to control the LEDS in close to real-time?

title: Slow USB reading operation

Answers: 3

body:
When sending multiple bytes which together form a single message it is best to use a delimiter character and read the data until there. That way you don't run into timeouts and you can be sure, that the received data represents a full message.

In the cases where the LEDs need 1s to react you are most likely sending less than 3 bytes, which causes the `Serial.readBytes()` function to time out after the default 1s. I guess you are currently always sending only 1 byte (though you are trying to read 3 byte in your code).

To use a delimiter character there are multiple ways. The easiest fix would be using `Serial.readStringUntil('\n')`. The newline character (which I used as a parameter here) is a common delimiter character. You would then need to aways send the newline character at the end of a full message.

Just setting the timeout very low is not a very good solution. With a low baudrate as 9600 that can easily mean, that the message is chopped up into multiple parts, because the transmission takes longer than the timeout.

---

Besides that: I don't really understand, why you need to receive 3 bytes for turning on or off 3 LEDs. One byte (even, when you are just using single digits) has a big enough data space for more than these 3 LEDs. Also you are not really using octal numbers. `atoi()` is expecting a string representation of a decimal number. There is nothing octal in your code. And then you are using the first 3 bits of the resulting number for controlling the LEDs.

All in all this seems quite complicated for a very basic task. Maybe there is some reason for that, which you didn't write about.

body:
You're calling `Serial.readBytes()` when there may or may not be 3 bytes available. If there aren't 3, the call waits for them to arrive or for a timeout. That's the delay you are seeing.

If you really want 3 bytes at a time, check whether there are 3 before you try to read them:

    if( Serial.available >= 3 )
       len = Serial.readBytes(buf, 3);

When the `if` fails - because there aren't three bytes available - you won't waste any time waiting for them.

body: On the Arduino UNO pins 0 and 1 are used for serial communications.  That might not make a difference here, but it's probably a good idea to avoid them unless really needed.


body:
I'm working on a project using TTGO TS wich communicate wih arduino via I²C protocole
How can I find the adress of TTGO TS board used in I²C communication ?

title: TTGO TS I²C adress

Answers: 2

body:
Like @romkey said, use a I²C scanner to find the address of the device, for example [this][1] one from the Arduino website. Connect the device to the Arduino board, upload the code and look up the I²C address of your device.

  [1]: https://playground.arduino.cc/Main/I2cScanner/

body:
The TTGO TS uses an ST7735 display. This is *not* an I2C device. Instead it uses its own custom serial protocol. Since the DC pin is broken out for you it uses the 4-wire serial interface which is simplest to use with SPI.

It's confusing that they use the terms SCL and SDA, which makes you think it's I2C, but it's not.


body:
A zero detector crossover sends a pulse to the Arduino, it must start counting x time and then a pulse is sent from the Arduino, once the timer reaches time x, it must stop counting and only start counting again when it receives the new pulse of the zero crossing detector, the idea is to do something like this:
[![enter image description here][1]][1]
What I don't know is how to keep the timer off all the time toff that appears in the image.

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

title: Turn off Timer1 / Timer1 One-shot

Answers: 2

body:
the way to turn off the Timer is to set the CS12, CS11 and CS10 prescale bits to 0, in this way the CLK signal is disconnected and the timer stops counting, when you want the timer to continue counting, they are set back to 1 the CS12, CS11 and CS10 bits according to the selected prescale.

    byte savePrescale

    savePrescale = TCCR1B & (0b111<<CS10);
    ...
    TCCR1B &= ~(0b111<<CS10); // Stop Timer1 Clock
    ...
    TCCR1B |= savePrescale;  // Restart Timer1 clock.
    ...

body:
You can initiate a "One shot" timer at each zero-crossing.

The trick @Gerben mentioned in https://arduino.stackexchange.com/questions/83616/turn-off-timer1#comment187112_83616 eventually links to code at https://github.com/bigjosh/TimerShot which does the one-shot functionality on Timer2 by idling the timer at TCNT2=0 with OCR2A=0, and using the TCNT2 space above 0 to operate an adjustable oneshot on OC2B.

This trick can be adapted to Timer1:

    // The one shot pulses are output on Digital pin OC1B (Arduino Uno D10, Mega D12, Nano D3)
    // Modified by Dave Forrest 2020-01-11 for Timer 1
    // Based on Josh Levine's Nov 23, 2015 work at https://github.com/bigjosh/TimerShot/blob/master/TimerShot.ino

    #define OSP_SET_WIDTH(cycles) (OCR1B = 0xffff-(cycles-1))

    // Setup the one-shot pulse generator and initialize with a pulse width that is (cycles) clock counts long

    void osp_setup(uint16_t cycles) {

      TCCR1B =  0;      // Halt counter by setting clock select bits to 0 (No clock source).
                  // This keeps anything from happeneing while we get set up

      TCNT1 = 0x00;     // Start counting at bottom.
      OCR1A = 0;      // Set TOP to 0. This effectively keeps us from counting because the counter just keeps reseting back to 0.
              // We break out of this by manually setting the TCNT higher than 0, in which case it will count all the way up to MAX and then overflow back to 0 and get locked up again.
      OSP_SET_WIDTH(cycles);    // This also makes new OCR values get loaded from the buffer on every clock cycle.

      TCCR1A = 0b11<<COM1B0  | 0b11<<WGM10;  // OC1B=Set on Match, clear on BOTTOM. Mode 15 Fast PWM.
      TCCR1B = (0b11<<WGM12)| (0b001<<CS10); // Start counting now. WGM 15=0b1111  to select Fast PWM mode

      //DDRB |= _BV(2);     // Set pin to output (Note that OC1B = GPIO port PB2 = Arduino Uno Digital Pin 10)
      DDRB |= _BV(6);     // Set pin to output (Note that OC1B = GPIO port PB6 = Arduino Mega Digital Pin 12)
      //DDRD |= _BV(3);     // Set pin to output (Note that OC1B = GPIO port PD3 = Arduino Nano Digital Pin 3)
    }

    // Setup the one-shot pulse generator

    void osp_setup() {
      osp_setup(1);
    }

    // Fire a one-shot pulse. Use the most recently set width.

    #define OSP_FIRE() (TCNT1 = OCR1B - 1)

    // Test there is currently a pulse still in progress

    #define OSP_INPROGRESS() (TCNT1>0)

    // Fire a one-shot pulse with the specified width.
    // Order of operations in calculating m must avoid overflow of the uint16_t.
    // TCNT2 starts one count lower than the match value becuase the chip will block any compare on the cycle after setting a TCNT.

    #define OSP_SET_AND_FIRE(cycles) {uint16_t m=0xffff-(cycles-1); OCR1B=m;TCNT1 =m-1;}

    void setup()
    {
      osp_setup();

    }

    void loop()
    {
      // Step though 0-11 cycle long pulses for demo purposes
      for (uint8_t o = 0; o < 101; o++) {
        OSP_SET_AND_FIRE(o);
        while (OSP_INPROGRESS());         // This just shows how you would wait if necessary - not necessary in this application.
        //_delay_us(1);      // Wait to let the audience clap
      }
    }

This code produced pulses with a resolution of 62.5ns, which is on the edge of what my test equipment can measure.  Here's a 6.25us, 100 cycle pulse next to a 1 cycle pulse:

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

With Timer1's 16 bit range and the /1 prescaler you can do pulses from 62.5ns to 4us.  With the /1024 prescaler, (`TCCR1B|=(0b101 <<CS10);`) it can do 64us up to 4.194sec.  With /256 prescaler, (`TCCR1B|=(0b100 <<CS10);`) it can do 16us up to 1.05sec.

For a one shot triggered on a zero-crossing, you might try something like this with the above

    void loop()
    {
      ...
      int t1_us = 1000000UL/60 /8 ; // 1/8th of a 60Hz cycle

      if(needOneShot){  // Set needOneShot with an interrupt or sensor or something
        OSP_SET_AND_FIRE(t1_us/16);  // 16us ticks with the /256 prescaler
         needOneShot = false;
      }
      ...
    }

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


body:
[![enter image description here][1]][1]I am working on a brushed motor quadcopter using Arduino pro mini.

Every time I try to throttle, the Arduino gets reset by itself (motors start to spin but they will be turned off in 2 sec). I have added a `1000uf` capacitor (tried up to `3300uf`) to the input of Arduino `VCC` and `GND`. But still having the same issue.

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

title: Arduino pro mini resetting itself

Answers: 0


body:
I've got 3 AJ-SR04M sensors working on an Arduino MKR Wifi 1010, but I was curious what the purpose of this screw on the sensor boards is. It seems to somehow impact the accuracy/performance, but I can't seem to find any info on it. Anyone know what this is called/what it does exactly?

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

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

title: AJ-SR04M Screw Purpose

Answers: 0


body:
I'm running UNV SIM808 Shield with Arduino Uno using [DFRobot_SIM808][1]. The shield has no issues detecting incoming SMS while **powered on**. I just found out if the shield is **off** while sending the SMS, it won't detect it when it becomes online again.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    #include <DFRobot_sim808.h>
    #include <SoftwareSerial.h>

    #define MESSAGE_LENGTH 160
    char message[MESSAGE_LENGTH];
    int messageIndex = 0;

    char phone[16];
    char datetime[24];

    #define PIN_TX    3
    #define PIN_RX    2

    SoftwareSerial mySerial(PIN_TX,PIN_RX);
    DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

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

      //******** Initialize sim808 module *************
       while(!sim808.init())  { Serial.println("Starting Sim808...");   sim808.powerUpDown(9); }

      delay(3000);
      Serial.println("Init Success, please send SMS message to me!");
    }

    void loop() {
      //*********** Detecting unread SMS ************************
       messageIndex = sim808.isSMSunread();
        Serial.print("messageIndex: ");
        Serial.println(messageIndex);

       //*********** At least, there is one UNREAD SMS ***********
       if (messageIndex > 0) {
          sim808.readSMS(messageIndex, message, MESSAGE_LENGTH, phone, datetime);

          //***********In order not to full SIM Memory, is better to delete it**********
          sim808.deleteSMS(messageIndex);
          Serial.print("From number: ");
          Serial.println(phone);
          Serial.print("Datetime: ");
          Serial.println(datetime);
          Serial.print("Recieved Message: ");
          Serial.println(message);
       }
    }

<!-- end snippet -->

I'm sharing the serial monitor data after powering off the shield. I sent a this message (**2:24**) at 2:24 AM local time. **10 mins** later, I powered the shield **on** and waited for the message to be detected but with no luck for **15 mins**. I sent another message (**2:49**) local time while the shield is **on** and it was detected right away along with the previous message.

> It runs every 3 seconds but I cleaned the data

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    02:34:56.342 -> Starting Sim808...
    02:35:06.958 -> Init Success, please send SMS message to me!
    02:35:09.602 -> messageIndex: -1
    02:40:00.686 -> messageIndex: 0
    02:45:02.311 -> messageIndex: 0
    02:49:26.940 -> messageIndex: 0
    02:49:29.560 -> messageIndex: 0
    02:49:32.216 -> messageIndex: 0
    02:49:33.565 -> messageIndex: 7
    02:49:36.269 -> From number: +***********
    02:49:36.322 -> Datetime: 21/04/21,02:24:20+12
    02:49:36.369 -> Recieved Message: 2:24
    02:49:37.624 -> messageIndex: 8
    02:49:40.373 -> From number: +***********
    02:49:40.373 -> Datetime: 21/04/21,02:49:28+12
    02:49:40.426 -> Recieved Message: 2:49
    02:49:43.029 -> messageIndex: 0
    02:49:45.691 -> messageIndex: 0
    02:49:48.314 -> messageIndex: 0

<!-- end snippet -->

Here is code for **sim808.isSMSunread();** function. Maybe there is something can be tweaked within the code can mitigate this issue:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    char DFRobot_SIM808::isSMSunread(){
        char gprsBuffer[48];  //48 is enough to see +CMGL:
        char *s;

     sim808_check_with_cmd("AT+CMGF=1\r\n","OK\r\n",CMD);    delay(1000);
        sim808_send_cmd(F("AT+CMGL=\"REC UNREAD\",1\r\n"));
        sim808_clean_buffer(gprsBuffer,31);
        sim808_read_buffer(gprsBuffer,30,DEFAULT_TIMEOUT);

        if(NULL != ( s = strstr(gprsBuffer,"OK"))) {
            delay(50);
            return 0;
        } else {
            sim808_wait_for_resp("OK\r\n", CMD);
            sim808_send_cmd("AT+CMGL=\"REC UNREAD\",1\r\n");
            sim808_clean_buffer(gprsBuffer,48);
            sim808_read_buffer(gprsBuffer,47,DEFAULT_TIMEOUT);
            if(NULL != ( s = strstr(gprsBuffer,"+CMGL:"))) {
                s = strstr(gprsBuffer,":");
                if (s != NULL) {
                    sim808_wait_for_resp("OK\r\n", CMD);
                    return atoi(s+1);
                }
            } else {
                return -1;
            }
        }
        return -1;
    }

<!-- end snippet -->

***What i'm looking for is to make the shield detect any unread messages if it was sent while off?***

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

  [1]: https://github.com/DFRobot/DFRobot_SIM808
  [2]: https://i.stack.imgur.com/HQK6z.png

title: SIM808 Doesn't detect SMS if sent while offline

Answers: 0


body:
trying to create this simple circuit where a rectangular voltage input is transferred to a sine wave output.

the process is quite simple, but I couldn't see the actual sine wave when connecting an oscilloscope.

I'm currently working on a simulator online, so I thought it would be best to share the circuit with the c++ code, and perhaps you would have any insights on why I keep seeing rectangular output voltage rather than sine when the data is indeed a sine wave:

here's an image of the circuit for some specific time:

[![circuit simulator][1]][1]

and the code that generates the sine wave is

    #include <math.h>

    const int numSamples = 500;
    const float pi = 3.1415;
    int f = 2; // signal frequency
    float sf = 500.0; // sample frequency > 2*f (Nyquist)
    int sineSignal[numSamples];

    void setup(){
     pinMode(13, OUTPUT);
     // creating sine signal:
     for (int i = 0; i < numSamples; i++){
      float t = i / sf;
      // +1 shift to get values from 0 to 2
      sineSignal[i] = (int) (127 * (sin(2 * pi * f * t) + 1.0));
     }
    }

    void loop(){
     int pinToConnect = 9;
     for (int i = 0; i < numSamples; i++){
      analogWrite(pinToConnect, sineSignal[i]);
      delay(2);
     }
    }
ps. this is all based on this video: [How to Generate Sine Wave using Arduino?][2]

  [1]: https://i.stack.imgur.com/DfxFK.png
  [2]: https://www.youtube.com/watch?v=ojkUaCSFM30

title: Arduino simulator - generating sine wave from PWD (Oscilloscope read is rectangular)

Answers: 1

body:
It's working as intened.

The arduino UNO has no DAC (digital to analog converter) onboard, so all it can produce are digital signals, either 0 or 5v. The analogWrite function uses [Pulse Width Modulation](https://www.arduino.cc/en/Tutorial/Foundations/PWM) to produce an output that, *on average*, has the requested voltage, by quickly alternating between logic low and high with different durations.

This is done at the hardware level using the Atmega's timers, and it's very useful in driving LEDs, servos, steppers and more, but it doesn't produce a steady analog output.

I would suggest either moving to a chip that has an onboard DAC, using an external DAC chip [such as this one](https://www.adafruit.com/product/935), or [building a simple DAC yourself](https://create.arduino.cc/projecthub/Arduino_Scuola/build-a-simple-dac-for-your-arduino-4c00bd).

An even simpler solution would be building a RC lowpass filter on the output pin, which would provide a simple, but probably imprecise, way to smooth out the signal and make it look like an analog one


body:
I'm using ezbutton to make a pushbutton act like a toggle switch, first press doing permanent on, second press doing permanent off. I'm just trying to understand the basic coding. This project is just a testbed for what I'm planning to do later - wiring vehicle toggle switches to Arduino and feeding the output signal to mosfet that will control the load state. So I'm trying to get the code as nice and tidy as I possible can. In the code below, I would like to know if ledState will be applicable when this sketch will control a mosfet instead of a test led, and I've seen comments saying "ledState = !ledState;" is not optimal - but being a beginner I'm not sure what this means, and is there a better more sound way to address it. Thanks!

    #include <ezButton.h>

    // ---
    // Declaration
    // ---

    const int button1  = 9;
    const int led1     = 4;
    int ledState = LOW;

    ezButton button(button1);

    // ---
    // Setup
    // ---

    void setup()
    {

      pinMode(led1, OUTPUT);
      pinMode(button1, INPUT_PULLUP);
      button.setDebounceTime(50);

    }

    // ***
    // Main Loop
    // ***
    void loop()
    {

      button.loop();

      if (button.isPressed()) {
        ledState = !ledState;
        digitalWrite(led1, ledState);
      }

    }

title: Making pushbutton behave as a toggle switch with ezButton - do I have to use ledstate with =! operator

Answers: 1

body:
I've been looking through the [source code for ezButton.c][1]

The function `isPressed()` is something of a misnomer and is only meaningful for a push-to-make button on the low side of a pull-up resistor. It actually detects falling edges of the signal, so it should be called `isFallingEdge()`, but the code itself is good.

Similarly for `isReleased()` which detects rising edges of the signal, so should be called `isRisingEdge()`.

The constructor defaults to `INPUT_PULLUP` which may (or may not) be what you want for your buttons and toggle switches, so it's something to bear in mind especially for low-side push-to-break buttons or high-side push-to-make buttons which will generate rising edges when pressed and falling edges when released thus reversing the meanings of `isPressed()` and `isReleased()`, hence why they really should be called `isFallingEdge()` and `isRisingEdge()`.

The algorithm in `ezButton::loop()` could be optimised a bit by getting rid of `previousSteadyState` and nesting the final `if` statement within the second `if` statement.

Other than that, it's quite a good algorithm that makes use of hysteresis to reset the debounce timer.

For comparison you could take a look at my algorithm in this [simple debouncer for Arduino][2] that simply detects rising edges, falling edges or both edges without regard to whether a button was pressed or released, and can be used in a polling loop or with interrupts. Here's the essence of the algorithm:

```c++
    bool input_state = digitalRead(INPUT_PIN);
    unsigned long current_ms = millis();

    edge = rise = fall = false;

    // Hysteresis:
    //   If there is no change, reset the debounce timer.
    //   Else, compare the time difference with the debounce delay.
    if (input_state == output_state)
    {
      last_ms = current_ms;
    }
    else if ((current_ms - last_ms) >= DEBOUNCE_DELAY_ms)
    {
      // Successfully debounced, so update the outputs.
      rise = input_state && !output_state;
      fall = !input_state && output_state;
      edge = rise || fall;
      output_state = input_state;
    }
```

And `ledState = !ledState;` simple toggles the value of `ledState` which is what you write to your LED with `digitalWrite(led1, ledState);` each time a falling edge is detected in the input signal.

  [1]: https://github.com/ArduinoGetStarted/button/blob/master/src/ezButton.cpp
  [2]: https://github.com/TimMathias/Arduino-Debouncer


body:
I modify this code from my friend and it look strange.

    void setup() {
        Serial.begin(115200);
        Serial.println("reset");
    }
    void loop() {
        for (int d; d <= 32767; d++) {
          Serial.println(d);
          delay (1000);
        }
    }

for some reason when you press reset, the variable will keep counting from last value as shown.

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

this not gonna happen when you put these block in setup()

I know that not good idea to use varible in for loop without assigned the value, but I belived it must have a interesting reason for this.
For my hypothesis, the variable value just allocate with same address in memory. when this code run in setup() some how the complier detect this situation and assign 0 as initial value. but when in the loop() some how the compiler don't assign new value to the memory address and it get old value from last time the program was run before resetted. I still need further explanation.

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

title: non asssign variable using by for in loop() can remeber last value. what happen here?

Answers: 1

body:
I think you missed a compiler warning (I did, too!) - notice that you are using 'd' uninitialized. On each re-entry to the loop() function, loop()'s stack will be in the same place in memory. The for-loop doesn't initialize 'd', but the boot loader did zero RAM for your first run. 'd' happens to occupy the same memory location on each entry to loop(), so the old value (just before reset) is still in place. Since the for-loop didn't re-initialize it... :)

The fix is:

    for (int d=0; d <= 32767; d++) {

Update:

That begs the question: Why did your run fail as expected, while my run appeared to execute normally? My guess is different bootloaders, one that does, and one that doesn't, initialize SRAM on a reset that doesn't result in an upload.


body:
I'm measuring voltage between button's ground and input pole on the following sketch. When button is on `off` state, there's `5V` there, when it's switched on and led turs on, there's `0`. Is this a correct way, and also how do I make it easier to write code and have `LOW` represent led being off. In this sketch, `digitalWrite(led1, LOW);` means the LED is actually turned on, so how do I tweak this to be representative of actual state, `high=led on`.
```cpp
#include <ezButton.h>

// -----
// Declaration
// -----

const int button1  = 9;
const int led1     = 4;
int ledState = LOW;

ezButton button(button1);

// -----
// Setup
// -----

void setup()
{

  pinMode(led1, OUTPUT);
  pinMode(button1, INPUT_PULLUP);
  button.setDebounceTime(50);

}

// *****
// Main Loop
// *****

void loop()
{

  if( digitalRead(button1) == LOW ) {
    digitalWrite(led1, HIGH);
  }
  else  {
    digitalWrite(led1, LOW);
  }

}

// *****
```

title: Arduino button voltage versus HIGH/LOW state

Answers: 0


body:
I am using ESP32 CAM for one project and I have a sensor that is I2C connected to pins 21 and 22 (default I2C). The sensor is working fine until I turn on the camera. The camera uses this pins (21,22) as input output, not for I2C communication. When I try to read the sensor data in the loop I can't reach the sensor. I want to check the sensor data mainly and if there is some indication from the sensor to turn on the camera.

 How I can make this redefinition of the pins in the main loop?

I did try to declare the pins with  `Wire.begin(21,22, 100000);` in the loop but is not working.

title: How to use pins for I2C that is used from other hardware?

Answers: 0


body:
After asking [How to connect Arduino & ESP8266][1], I tried to build such circuit.

First I tried the code one 2 Nano's - to verify 2 MCU sending and receiving messages. After that, I started to build the following circuit:

**Take1:** MCU A: Arduino Micro 5V, MCU B: WEMOS mini. `R1`=10K, `R2`=20K. **FAIL**

**Take2:** MCU A: Arduino Micro 5V, MCU B: WEMOS mini. `R1`=1K, `R2`=2K. **FAIL**

**Take3:** MCU A: Arduino NANO ,MCU B: WEMOS mini. `R1`=1K, `R2`=2K. **FAIL**

**Take4:** MCU A: Arduino NANO 5V, MCU B: WEMOS mini. `Tx` to `Rx` (no vdiv ). **OK**

[![Updated diagram][2]][2]

**Edit1:** LCD display is connected to MCU B ( as it was tested using 2 Nano ) via I2C. Messages received are sent to LCD. PLEASE IGNORE LCD shown in not I2C

**Edit2**:

1) Diagram updated - GND was missing and POWER IN clarification.

2) LCD display is an I2C one. It shows properly WEMOS is booting up properly ( shows a boot msg ), and spits every incoming `Serial` message from other MCU. When TAKE4 and TAKE1 were taken, setup and code worked PROPERLY.

What is done wrong?

  [1]: https://arduino.stackexchange.com/questions/83585/serial-communication-between-esp8266-and-arduino-sofware-and-hardware/83588#83588
  [2]: https://i.stack.imgur.com/bvP4u.jpg

title: Serial Connection - 3.3v to 5V MCU's

Answers: 0


body:
I'm trying to send data from sensor to ThingSpeak, but the AT commands always return Fail. They work sometimes and send data.  But, most of the time they return fail.

My Connections:

| ESP          | Arduino|
|--------------|--------|
| Gnd          | Gnd    |
| Vcc, ChPD/En | 3.3v   |
| Rx           | 2      |
| Tx           | 3      |

My code:

```
#include <SoftwareSerial.h>

#include "DHT.h"

#define DHTPIN 10
#define DHTTYPE DHT11

#define RX 2
#define TX 3

#include <OneWire.h>
#include <DallasTemperature.h>
#include <LiquidCrystal_I2C.h>

#define SensorPin 0          // the pH meter Analog output is connected with the Arduino’s Analog

#define ONE_WIRE_BUS 8

LiquidCrystal_I2C lcd(0x27, 16, 2);
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
DHT dht(DHTPIN, DHTTYPE);
float phValue;

String AP = "Mukadam";       // AP NAME
String PASS = "28oct1997"; // AP PASSWORD
String API = "ZIGGVWBPU0BJ9A0I";   // Write API KEY
String HOST = "api.thingspeak.com";
String PORT = "80";

String f1 = "field1";
String f2 = "field2";
String f3 = "field3";
String f4 = "field4";

int countTrueCommand;
int countTimeCommand;

boolean found = false;

int valSensor = 1;

SoftwareSerial esp8266(RX,TX);

float Celcius=0;
float Fahrenheit=0;

float b;

int buf[10],temp;

unsigned long int avgValue;

void setup()
{
  lcd.begin();
  lcd.backlight();
  Serial.begin(9600);
  dht.begin();
  pinMode(13,OUTPUT);

  sensors.begin();

  lcd.print("WT:");

  esp8266.begin(115200);

  sendCommand("AT",3,"OK\r\n\r\n");
  sendCommand("AT+CWMODE=1",5,"OK");
  sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK");
}

void loop()
{
  sensors.requestTemperatures();
  Celcius=sensors.getTempCByIndex(0);
  Fahrenheit=sensors.toFahrenheit(Celcius);

  Serial.print("C:");
  Serial.print(Celcius);

  lcd.setCursor(3,0);

  lcd.print(Celcius);

  String getData = "GET /update?api_key="+ API +"&"+ f1 +"="+String(Celcius);

  sendCommand("AT+CIPMUX=1",5,"OK");
  sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK");
  sendCommand("AT+CIPSEND=0," +String(getData.length()+4),4,">");

  esp8266.println(getData);

  delay(1500);countTrueCommand++;

  sendCommand("AT+CIPCLOSE=0",5,"OK");

  for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
  {
    buf[i]=analogRead(SensorPin);
    delay(100);
  }

  for(int i=0;i<9;i++)        //sort the analog from small to large
  {
    for(int j=i+1;j<10;j++)
    {
      if(buf[i]>buf[j])
      {
        temp=buf[i];
        buf[i]=buf[j];
        buf[j]=temp;
      }
    }
  }

  avgValue=0;

  for(int i=2;i<8;i++)                      //take the average value of 6 center sample
    avgValue+=buf[i];

  float phValue=(float)avgValue*5.0/1024/6; //convert the analog into millivolt
  phValue=3.5*phValue;                      //convert the millivolt into pH value

  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);

  lcd.setCursor(9,0);
  lcd.print("pH:");
  lcd.setCursor(12,0);
  lcd.print(phValue);

  getData = "GET /update?api_key="+ API +"&"+ f2 +"="+String(phValue);
  sendCommand("AT+CIPMUX=1",5,"OK");
  sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK");
  sendCommand("AT+CIPSEND=0," +String(getData.length()+4),4,">");

  esp8266.println(getData);delay(1500);countTrueCommand++;

  sendCommand("AT+CIPCLOSE=0",5,"OK");

  lcd.setCursor(12,0);
  lcd.print(phValue);

  float h = dht.readHumidity();

  lcd.setCursor(0,1);
  lcd.print("H:");
  lcd.setCursor(2,1);
  lcd.print(h);

  float t = dht.readTemperature();

  lcd.setCursor(8,1);
  lcd.print("AT:");
  lcd.setCursor(11,1);
  lcd.print(t);
  lcd.setCursor(12,0);
  lcd.print(phValue);
}

void sendCommand(String command, int maxTime, char readReplay[]) {
  Serial.print(countTrueCommand);
  Serial.print(". at command => ");
  Serial.print(command);
  Serial.print(" ");

  while(countTimeCommand < (maxTime*1))
  {
    esp8266.println(command);//at+cipsend

    if(esp8266.find(readReplay))//ok
    {
      found = true;
      break;
    }

    countTimeCommand++;
  }

  if(found == true)
  {
    Serial.println("OYI");
    countTrueCommand++;
    countTimeCommand = 0;
  }

  if(found == false)
  {
    Serial.println("Fail");

    countTrueCommand = 0;
    countTimeCommand = 0;
  }

  found = false;
}
```
And here is serial monitor output:

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

title: All AT commands return Fail

Answers: 0


body:
I want to get some JSON data from a HTTPS secured Webserver using a ESP8266.
For some reason I'm getting an empty response, I believe there's an error parsing the GET request.
In Chrome I get the JSON response without problems.

GET Request:

    httpsClient.print(String("GET ") + path + " HTTP/1.1\r\n" +
                   "Host: " + host + "\r\n" +
                   "Connection: close\r\n\r\n");
Host and Path:

    const char *host = "www.adler-mannheim.de";
    const char *path = "/jsonapi/game/current";

**UPDATE:**

I tried fetching some JSON from another Server and it worked finde, so i can rule out my code.
Fiddling around with the host and path I observe this:

 - Hostname without "www" results in a 301

 - Hostname with "https://www" results in no HTTPS connection at all

So it seems that a "www" is required although it unfortunately leads into a empty response.

The output is as follows:

    headers received
    reply was:
    ==========
    ==========
    closing connection

In the first case, without using "www" in ahead of host there's some 301 HTML in between the two lines of "=".

Whole function:

    void connect() {
      WiFiClientSecure httpsClient;    //Declare object of class WiFiClient

      Serial.println(host);
      httpsClient.setInsecure();

      Serial.print("HTTPS Connecting");
      int r=0; //retry counter
      while((!httpsClient.connect(host, httpsPort)) && (r < 30)){
          delay(100);
          Serial.print(".");
          r++;
      }
      if(r==30) {
        Serial.println("Connection failed");
      }
      else {
        Serial.println("Connected to web");
      }

      String getData, Link;

      //GET Data

      Serial.print("requesting URL: ");
      Serial.println(host+Link);

      httpsClient.print(String("GET ") + path + " HTTP/1.1\r\n" +
                   "Host: " + host + "\r\n" +
                   "Connection: close\r\n\r\n");

      Serial.println("request sent: ");
      Serial.println(String("GET ") + path + " HTTP/1.1\r\n" +
                   "Host: " + host + "\r\n" +
                   "Connection: close\r\n\r\n");
      while (httpsClient.connected()) {
        String line = httpsClient.readStringUntil('\n');
        if (line == "\r") {
          Serial.println("headers received");
          break;
        }
      }

      Serial.println("reply was:");
      Serial.println("==========");
      String line;
      while(httpsClient.available()){
        line = httpsClient.readStringUntil('\n');  //Read Line by Line
        Serial.println(line); //Print response
      }
      Serial.println("==========");
      Serial.println("closing connection");

      delay(2000);  //GET Data at every 2 seconds
    }

**UPDATE 2:**

I tried the following code from the ESP8266HTTPClient Library examples:

    void connect2() {

      WiFiClientSecure client;

      //client.setFingerprint(fingerprint);
      client.setInsecure();

      HTTPClient https;

      Serial.print("[HTTPS] begin...\n");
      if (https.begin(client, "https://github.com/esp8266/Arduino/issues/3417")) {  // HTTPS

        Serial.print("[HTTPS] GET...\n");
        // start connection and send HTTP header
        int httpCode = https.GET();

        // httpCode will be negative on error
        if (httpCode > 0) {
          // HTTP header has been send and Server response header has been handled
          Serial.printf("[HTTPS] GET... code: %d\n", httpCode);

          // file found at server
          if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
            String payload = https.getString();
            Serial.println(payload);
          }
        } else {
          Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str());
        }

        https.end();
      } else {
        Serial.printf("[HTTPS] Unable to connect\n");
      }

      Serial.println("Wait 10s before next round...");
      delay(10000);
    }

This one gives me a 200 but no payload. Other sites work

**UPDATE 3:**

I had a look on the headers.

    https.headers()
This gives me 0 headers on every page, even when there's a payload.

I also had a closer look at the payload that returns from my desired api and its filled with NULL.
In a weird way this is only the case with my desired page and only my desired subpages.
Requesting something more at top level e.g "https://www.adler-mannheim.de/jsonapi" which is basically a SilverStripe Welcome page, I get a fully fetched beautiful HTML payload.

I got literally no Idea why. Do I have to set a specific User Agent or something so that the Server responds?

title: Arduino ESP8266 HTTPS Request returning empty response

Answers: 2

body:
Okay I have no Idea what I changed apart from deleting some imports which might have collided, but now it works. Regular call with "https://www" does the thing.

Thanks anyways

body: I had this same problem and I realized it was because I was using an `WiFiClientSecure` to try to an endpoint over HTTP instead of HTTPS. If anyone else is having this same problem, I would check that.


body:
I am using an arduino mega clone called the Funduino.

I am developing a python based, tkinter application that will receive the serial data that arduino sends.

However, i am witnessing some behavior that i cannot explain and i am trying to debug. I won't say anything more, because this is an arduino forum, not a python forum.

But, in the arduino, there are some leds. One of them is power, which is constantly ON, when the arduino is powered.

There is another led that is named 'L'. When i open a serial connection this is lighted up and it stays ON.

However sometimes, when i send a string to the arduino, in order to trigger some data exchange, this button is switched off.

So what does this 'L' led is, and what it means when it is turned off?

title: Purpose of LED indicator

Answers: 2

body:
This buildin LED is connected to an IO pin of the microcontroller on the Mega (most commonly pin 13, but might be different depending on the board). So the meaning depends on what the code on the Mega does with it.

When the board is reset (which happens on opening of serial connection), first the bootloader will run. It gives you a short blink on the buildin LED. After the bootloader finishes, your own code is in charge. Whatever you do in your code with pin 13 will be reflected on the LED. Here the meaning depends on you.

body:
If you do not configure the pins, they are initialized as `pinMode(xx,INPUT)` which is a floating high impedance state.  Per the Arduino Uno R3 schematic, that pin is on PB5/SCK/13 which is run through the op-amp (top center in the schematic) to drive the LED. Per the Arduino Mega schematic, that pin is on PB7/OC0A/OC1C/13 which isn't run through the op amp.  I left mine unconfigured on a Mega clone and measured a 1.5V on 13 and had the LED on.  On an Uno clone, the light was on while unconfigured, and I measured 0.9v (but my DMM seemed to draw down the voltage).

If the pin is left floating in an unknown state, it could drive the LED into an unknown state.

[![Arduino Uno Schematic][1]][1] [![Arduino Mega2560 R3 Schematic detail][2]][2]

You can control it's state with:

    pinMode(LED_BUILTIN,OUTPUT);  // LED is forced off (0.01V)
    digitalWrite(LED_BUILTIN,1);  // force LED on (4.97)

or

    pinMode(LED_BUILTIN,INPUT_PULLUP); // On, but with the internal pullup resistor, not logic gates.  Pin 13 can be shorted to ground.

or set it back to the default tri-state:

    pinMode(LED_BUILTIN,INPUT); // Tri-state, undefined.
    // You could control the LED from an external signal on the pin.

Measure the voltage at pin 13 and see what you get.

Personally, I purpose it as a status indicator light.  E.g.  https://github.com/drf5n/foxyPulseInduction_Discrimination/blob/discrimination/StatusCodeLED/StatusCodeLED.ino

Because of the tri-state/op-amp LED driver on "L", you can use the light as as a logic probe--you could leave it unconfigured and jumper it to other inputs or outputs for troubleshooting and diagnostics.  If you have a project monitoring one important input, rather than putting it on a different input pin and explicitly echoing it to the LED like `digitalWrite(LED_BUILTIN,digitalRead(sensorPin));` you could hook it to pin 13 to visually see the input status and just `digitalRead(sensorPin)`.

====

Note that there are two revisions of the Arduino Mega schematic.

* https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf -- A top search hit
* https://content.arduino.cc/assets/MEGA2560_Rev3e_sch.pdf from https://store-usa.arduino.cc/products/arduino-mega-2560-rev3

After testing this behavior, I noticed that the my Mega clone did not match the Arduino Mega schematic at https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf . Tracing it out, it does use the op-amp like the Uno. (Pin 1&2 of the opamp attach to the "L" LED through the third resistor in the resistor array next to the LED.)

  [1]: https://i.stack.imgur.com/ugHED.png
  [2]: https://i.stack.imgur.com/I5SJJ.png
  [3]: https://i.stack.imgur.com/BEd6S.png


body: I have an SD card have a very big file (1M character). i try to load it into memory in terms of 4K character array ( The maximum I could do using Arduino Mega). but this take almost 250 call to the server. And this is too much. Is there any way better to do it. I am using firebase as my server and i am touching the limit and this is inacceptable to the stability of the program

title: Sending data to server

Answers: 0


body:
My program only works when the following line is added:

    Serial.begin(9600);

When this is disabled/removed the program no longer switches output state regular

I'm using an Arduino Mega 2560.

When the line is **added**:
- The output is switched ON or OFF regular around every 1sec.

When the line is **removed**:
- The output is switched after 1 sec (as expected) but then switched multiple times after around 3 sec.
- I tried with another Arduino Mega 2560: This time, the output is switched after 1sec (as expected) but then switched multiple times right after (and not after around 3 sec).

What could be the problem?

My code:

    byte inputPin2 = 2;
    byte inputPin3 = 3;
    byte outputPin = 13;
    boolean outputPin_HIGH = false;
    volatile short angle = -18;

    void setup() {
      Serial.begin(9600);      //<----------------------
      pinMode(hallSensorPin, OUTPUT);

      pinMode(inputPin2, INPUT_PULLUP);
      pinMode(inputPin3, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(inputPin2), ISR_addAngle, CHANGE);
      attachInterrupt(digitalPinToInterrupt(inputPin3), ISR_addAngle, CHANGE);
    }

    void ISR_addAngle() {
      angle = angle + 18;
    }

    void loop() {
      if (angle == 900) {
        if (outputPin_HIGH) {
          digitalWrite(outputPin, LOW);
          outputPin_HIGH = false;
        } else {
          digitalWrite(outputPin, HIGH);
          outputPin_HIGH = true;
        }
        angle = angle - 900;
      }
    }

title: Program only works with Serial.begin

Answers: 0


body:
I have built a simple scale using 4 so called 50kg load cells.

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

They are connected in a bridge and mounted on wooden feet of a square shaped box. All as a proof of concept which worked quite ok. The readings are all OK and deviation of +/- 2kg is totally acceptable for my project. I followed this discussion which also explains how the connection should be made properly using 4 cells.

https://arduino.stackexchange.com/questions/11946/how-to-get-weight-data-from-glass-electronic-bathroom-scale-sensors/18698?newreg=dfc67e294d934ae28fd067724558f894

Now I want to keep the load cells on the feet but change the shape of the scale and instead of a square use a rectangle with the following sides.

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

In such a form a weight distribution will not be centered all the time. The object to be weighed can shift to the right or to the left.

 - Will this affect the measurements in a negative way or will the HX711 controller still take care of it and show the correct results?
 - Will the measurements still be correct using 4 cells? If not what would be the proper way of weighing a rectangular shaped load?
 - Would it more appropriate to measure the load with 2 cells on the right and two cells on the left and then sum it up?

  [1]: https://i.stack.imgur.com/LfGgC.jpg
  [2]: https://i.stack.imgur.com/qhQXO.png

title: Load cell weight distribution on rectangular shape instead of square

Answers: 1

body:
Newton's second law says that if a force acts on a mass, that mass will accelerate at a rate proportional to the force and inversely proportional to the mass.

All that means for your scale is that if you are not being accelerated up or down, the net vertical force on your body must be 0. Since your body has weight, and the net vertical force on your body is 0 (you aren't accelerating, are you? :) then the downward force must be balanced by an exactly equal upward force. That upward force is the sum of the upward forces exerted by each load cell. Their contributions may individually change depending on where you stand, but *their sum must exactly equal your weight*.

Note that we have said nothing about the placement of the cells! If your platform allows it, you could move one of the cells 6 (or 60 or 600) feet away from the the others, for instance. The total upward force must still be the same.

So the bottom line is:

   `F_lc1 + F_lc2 + F_lc3 + F_lc4 == your weight`

no matter where you place the cells.


body:
My Arduino controller reads data coming from four different sensors. After the data is read, I individually compute four input average values. I understood that I am having the same lines of code repeated four times. Instead, I want to define a function with an analog pin as input and compute the average. My code is working fine. The question I have is, will this function improve the speed, reduce memory?

My code:

    // Samples average
    sample_cnt = 1000;

    //// Input the pin number and compute average value
    float Average_input_value(int analog_pin){
      float avg_val = 0;
      for(int i=0;i<sample_cnt;i++){
        avg_val += analogRead(analog_pin);
      }
      // Divide by Sample count to get the average value
      avg_val = avg_val/sample_cnt;
      return avg_val;
      }

title: Is defining a function improves speed rather computing average for each analog input separately

Answers: 2

body:
Writing the code out four times, in line, is a little bit faster than calling a function because the function call and return take some time, and the loop instructions take some time, and neither of those contribute to the average calculation.

Writing a function that you use four times, however, is much more readable, is much easier to fix if you've made a mistake because you can fix it once instead of four times, and is much easier to change or replace for the same reason, if that ever becomes necessary. Besides, a good optimizing compiler can often decide when to rewrite your loop as inline several repetitions of the loop contents (called "unrolling the loop"), so hand optimizing is probably not worthwhile.

Where your function will win over 4 repetitions of the calculation code is in the code-space needed. The function is more compact, but slightly slower.

body:
Just adding some numbers to complement JRobert's answer.

On the Uno, the cost of calling a function and returning from it is
about 0.5 µs. In contrast, calling `analogRead()` within a loop
costs _at least_ 112 µs per iteration. Given that you are computing
the sum as a `float` (where a suitably sized integer would suffice), it
may well be more that 112 µs in your case.

I do not know how many readings you want to average, but even if it is
only a handful, the calls to `analogRead()` will completely dwarf the
cost of using a function.


body:
I downloaded a water flow sketch and got it working on a bread board using an Uno, and a LCD shield.  I what to make it on perf board using a Nano, and an NOT I2C LCD.

I soldered it all up, got "Hello World" to run ok.  But because my water flow sketch originally uses D2 for the sensor, and the new sketch uses D2 for the LCD I obviously need to change the sensor pin.  I have the sensor hooked up to D8, but I can't figure out how to tell the sketch that....

I believe it is this line of code:

        byte sensorInterrupt = 0;  // 0 = digital pin 2
        byte sensorPin       = 2;
But I have tried changing the values based on the nano pin out diagram, but I just can't get it to read.  I don't think it is a hardware problem, but if i can get confirmation that i have the pin declared correctly I can go back a de-solder stuff and check....

```cpp
    /*
Liquid flow rate sensor -DIYhacking.com Arvind Sanjeev

Measure the liquid/water flow rate using this code.
Connect Vcc and Gnd of sensor to arduino, and the
signal line to arduino digital pin 2.

 */
// include the library code:
#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

byte statusLed    = 13;

byte sensorInterrupt = 0;  // 0 = digital pin 2
byte sensorPin       = 2;

// The hall-effect flow sensor outputs approximately 4.5 pulses per second per
// litre/minute of flow.
float calibrationFactor = 7.55;  //biger more / min

volatile byte pulseCount;

float flowRate;
unsigned int flowMilliLitres;
unsigned long totalMilliLitres;

unsigned long oldTime;

void setup()
{

  // Initialize a serial connection for reporting values to the host
  Serial.begin(9600);

     lcd.begin(16, 2);
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("S.V. SAVANNAH");
   lcd.setCursor(0,1);
   lcd.print("DAY TANK");

  // Set up the status LED line as an output
  pinMode(statusLed, OUTPUT);
  digitalWrite(statusLed, HIGH);  // We have an active-low LED attached

  pinMode(sensorPin, INPUT);
  digitalWrite(sensorPin, HIGH);

  pulseCount        = 0;
  flowRate          = 0.0;
  flowMilliLitres   = 0;
  totalMilliLitres  = 0;
  oldTime           = 0;

  // The Hall-effect sensor is connected to pin 2 which uses interrupt 0.
  // Configured to trigger on a FALLING state change (transition from HIGH
  // state to LOW state)
  attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
}

/**
 * Main program loop
 */
void loop()
{

   if((millis() - oldTime) > 1000)    // Only process counters once per second
  {
    // Disable the interrupt while calculating flow rate and sending the value to
    // the host
    detachInterrupt(sensorInterrupt);

    // Because this loop may not complete in exactly 1 second intervals we calculate
    // the number of milliseconds that have passed since the last execution and use
    // that to scale the output. We also apply the calibrationFactor to scale the output
    // based on the number of pulses per second per units of measure (litres/minute in
    // this case) coming from the sensor.
    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;

    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.
    oldTime = millis();

    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.
    flowMilliLitres = (flowRate / 60) * 1000;

    // Add the millilitres passed in this second to the cumulative total
    totalMilliLitres += flowMilliLitres;

    unsigned int frac;

    // Print the flow rate for this second in litres / minute
    Serial.print("Flow rate: ");
    Serial.print(int(flowRate));  // Print the integer part of the variable
    Serial.print("L/min");
    Serial.print("\t");       // Print tab space

    // Print the cumulative total of litres flowed since starting
    Serial.print("Output Liquid Quantity: ");
    Serial.print(totalMilliLitres);
    Serial.println("mL");
    Serial.print("\t");       // Print tab space
  Serial.print(totalMilliLitres/1000);
  Serial.print("L");

      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print(int(flowRate));  // Print the integer part of the variable
      lcd.print("L/min ");

    // Print the cumulative total of litres flowed since starting
    lcd.print("Total ");
  lcd.print(totalMilliLitres/1000.00);
  lcd.print("L");

    // Reset the pulse counter so we can start incrementing again
    pulseCount = 0;

    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
  }
}

/*
Insterrupt Service Routine
 */
void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

 ```

title: How do you know what to call the digital pin your using? changing the sensor pin your using

Answers: 0


body:
Recently, I have been working on a project involving 8 Tower Pro sg90 servos and an Arduino Uno. The issue I am running into is that the servos will randomly move when connected, without even receiving a signal from the Arduino.

Specifically, sometimes the servos will work perfectly and the input moves the servos fine, but then all of a sudden the servos will start twitching and moving erratically back and forth. Then I disconnect the power and plug it back in and I will sometimes work again or sometimes not.

I don't think power is the problem because I am powering the servos externally with a 5.5v power supply which can provide 2.5 amps. I also made sure to have a common ground between the Arduino and the power supply. Additionally, I don't think this is an issue of a broken servo because I have this problem with all eight. In my code, I have input pins to control the servos which are just buttons. These buttons also have pull-down resistors, so I don't think the input is the problem either. I am using the Arduino servo library.

The only other thing I can think of is external frequency interference because some of the circuitry and wiring are close together, but none of the wires are very long and I even tried putting a ferrite bead on the servo cables but to no avail.

If anyone has any ideas about a solution to my problem which I have not tried yet that would be amazing!

~~~c++
#include <Servo.h>

Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;
Servo servo5;
Servo servo6;
Servo servo7;
Servo servo8;

void setup(){
  pinMode(5, INPUT);
  pinMode(4, INPUT);
  pinMode(3, INPUT);
  pinMode(2, INPUT);
  pinMode(1, INPUT);
  pinMode(A0, INPUT);
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);
  servo1.attach(13);
  servo2.attach(12);
  servo3.attach(11);
  servo4.attach(10);
  servo5.attach(9);
  servo6.attach(8);
  servo7.attach(7);
  servo8.attach(6);
}

void loop(){
  if(digitalRead(5)==LOW){
    servo1.write(120);
    delay(20);
  }
  else{
    servo1.write(50);
    delay(20);
  }
  if(digitalRead(4)==LOW){
    servo2.write(110);
    delay(20);
  }
  else{
    servo2.write(200);
    delay(20);
  }
  if(digitalRead(3)==LOW){
    servo3.write(120);
    delay(20);
  }
  else{
    servo3.write(50);
    delay(20);
  }
  if(digitalRead(2)==LOW){
    servo4.write(110);
    delay(20);
  }
  else{
    servo4.write(200);
    delay(20);
  }
  if(digitalRead(1)==LOW){
    servo5.write(120);
    delay(20);
  }
  else{
    servo5.write(50);
    delay(20);
  }
  if(digitalRead(A3)==LOW){
    servo6.write(110);
    delay(20);
  }
  else{
    servo6.write(200);
    delay(20);
  }
  if(digitalRead(A2)==LOW){
    servo7.write(120);
    delay(20);
  }
  else{
    servo7.write(50);
    delay(20);
  }
  if(digitalRead(A1)==LOW){
    servo8.write(110);
    delay(20);
  }
  else{
    servo8.write(200);
    delay(20);
  }
}
~~~

title: Random Servo Movement with Arduino Uno

Answers: 1

body:
You call servoX.write() repeatedly, even when no button has changed. Each call turns off interrupts briefly while the servo value is being updated. This happens, maybe 40 times/sec and may be messing up the servo timing in some non-constant way. Try only calling the servoX.write() functions once, only when its button-state has settled into a new state.

Update:

> could you provide an example please

      bool prevButton5 = LOW;            // one of these for each button
        :                                // outside of the loop() func.
        :

      if(digitalRead(5) != prevButton5){  // button changed?
        prevButton5 = !prevButton5;       // save new button state
        if(preButton5 == LOW){            // (your same code from here down)
          servo1.write(120);
          delay(20);
        }
        else{
          servo1.write(50);
          delay(20);
        }
      }

 - Make a boolean for each button.
 - Wrap each of your button segments as I did for button5. Notice that your code is now executed only if the associated button has changed, so you will have many fewer servoX.write() calls.

That isn't the totally best way to do it. I made it as straightforward as I could, even though the additional code gets replicated for every button. I'd probably write a single function that manages one button and one motor, and call that function for each button / motor pair.

I also ignored the concept of switch-bounce to keep the number of changes low, but you should look it up and consider it. Switch-bounce is *apparent* bouncing of the switch contacts for a few milli-seconds during the change from open to closed or vice-versa, which leads to several make-break-make.....-make cycles (or the reverse) when you push or release the button. I'd probably make (or search for) a button debounce function and call it for the particular button I'm testing if I see that button has changed.

First try the "rude and crude" fix I suggested and get that working. Then if you're interested, try making one or more of the refinements.

Update:

    the servos still jitter and twitch esspecailly when
    I move the whole arduino and wires around.

That suggests either or both of
 - cross-talk;
 - the plug wires' connections being less than solid, especially when the wires move.

Try:
 - laying out the servo cables to keep them away from each other as much as possible;
 - wiring only a few of the servos, and in different combinations;
 - also try commenting out the code - or not - for those servos you disconnected in the previous step.

If it turns out to be the plug-in wires and if this project is intended to actually be used for something, I'd suggest using a screw-terminal shield on your Uno to attach the servo wires more securely.