body:
Hi I am trying to send data(1 byte) from one arduino to another using parallel communication(a bus of 8 connections) and not using any library. However, the problem is the data gets corrupt all the time and what I am supposed to receive at receiver arduino is not what I send. The protocol that I made up is similar to uart protocol. There is ES pin and when it is low, transmission is started and when it is high, the transmission is ended. I think the problem could be related to wires that I use to connect two arduinos. There could be some noise induced that could flip bits in wires or the code is problematic. I am posting my code. Maybe you can help me get through this and help me to resolve my problem.

Sender code:

    #define ES 8 //enable sampling
    #define B0 0 //Bus 0
    #define B1 1
    #define B2 2
    #define B3 3
    #define B4 4
    #define B5 5
    #define B6 6
    #define B7 7
    const char dataToBeSent = 'C';
    bool data_bit;

    void setup() {
      pinMode(ES,OUTPUT);
      pinMode(B0,OUTPUT);
      pinMode(B1,OUTPUT);
      pinMode(B2,OUTPUT);
      pinMode(B3,OUTPUT);
      pinMode(B4,OUTPUT);
      pinMode(B5,OUTPUT);
      pinMode(B6,OUTPUT);
      pinMode(B7,OUTPUT);
      digitalWrite(ES,HIGH);
      delay(3000);
    }
    void loop() {

     digitalWrite(ES,LOW); //transmission is started
     delay(10);

     for(int i = 0 ; i<8 ; i++){
        data_bit = dataToBeSent & (0x80 >> i);
        digitalWrite(i,data_bit);
     }
      delay(10);
      digitalWrite(ES,HIGH); //end transmission
      while(true){}
    }

Receiver code:

    #define ES 8 //enable sampling
    #define B0 0 //Bus 0
    #define B1 1
    #define B2 2
    #define B3 3
    #define B4 4
    #define B5 5
    #define B6 6
    #define B7 7

    char rx_data;
    byte rx_byte= 0;
    bool rx_pin;

    void setup() {
      Serial.begin(9600);
      pinMode(ES,INPUT);
      pinMode(B0,INPUT);
      pinMode(B1,INPUT);
      pinMode(B2,INPUT);
      pinMode(B3,INPUT);
      pinMode(B4,INPUT);
      pinMode(B5,INPUT);
      pinMode(B6,INPUT);
      pinMode(B7,INPUT);
      delay(1000);

    }

    void loop() {

      byte rx_byte= 0;

      while(digitalRead(ES) == HIGH){}
      delay(15);

      for(int i = 0 ; i<8 ; i++){
        rx_pin = digitalRead(i);
        Serial.print(rx_pin);
        if(rx_pin == 1){
          rx_byte |= (0x80 >> i);
        }
      }

     rx_data = rx_byte ;

     Serial.print("Received data: ");
     Serial.println(rx_data);

     delay(15);

     while(digitalRead(ES)== HIGH){}

    }

title: parallel communication simulation problem

Answers: 1

body:
You problem is that you are only using one phase of your "ES" clock, when in fact you should be using two.

In the first phase, where ES is high, is where you set the IO pins to represent your transmitted byte. Only once that is done can you then progress to the second phase, where ES is low, to indicate to the receiver that "I have set up my outputs, it's now time for you to read them".

So your transmitted code would flow like:

1. Set ES HIGH
2. Set output pins to represent the byte
3. Set ES LOW
4. Delay
5. Set ES HIGH

If you look at any timing diagrams for any protocol there will be places where the data is being written to the bus, and places where the data is considered stable and able to be read by the receiver. It's the job of the clock signal to indicate where these points in the protocol - to *synchronise* the receiver.

For example, here is the Centronics (parallel port) protocol:

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

The data changes while nStrobe is HIGH, and only when that data is "settled" is nStrobe brought LOW to tell the receiver it can read the data. Once nStrobe is taken HIGH again the data is changed to the next byte to transmit.

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


body: Is there a way to connect a data output pin from an HT12D to an Arduino or ESP8266-12e input pin, then sense when the data pin is activated so I can have the Arduino or ESP8266-12e do something like turn on an output pin?

title: Arduino respond to input from HT12D data output

Answers: 2

body:
I am afraid I could not understand your question properly. But maybe, the answer is YES, if ...

First of all, OUTPUT pins, cannot be turned ON and turned OFF, however, you can start or stop READING that particular OUTPUT PIN based on another INPUT pin value.

If you want to connect HT12D decoder to any arduino or ESP, you must be aware to use same voltage level between IO PINS, a good approach is to use a I2C bi-directional level shifter.

    if(INPUT_PIN_VALUE >= SOME_VALUE)
    {
       digitalRead(PIN)
    }

body:
Disclaimer: In this answer I'm using ESP and Arduino interchangeably, as if they were the same. They are in context this question, but not in general.

First: According to the [datasheet of the HT12D][1], the supply voltage can be between 2.4V and 12V, so you could just provide it with the 3.3V of your ESP. That way the output pins will also run on 3.3V. Then you can simply run a wire each from an output of the chip to a digital input pin of the Arduino.

Though you then should also provide your receiver chip with 3.3V. If that is not possible, you can provide the HT12D with 5V and use simple voltage dividers on each output to break the voltage down to 3.3V. That places restrictions on the transmission speed, but I don't think, that this is relevant here, as the outputs are more meant as momentary state outputs, not data transmission outputs. In that case you connect the output of the voltage dividers to one digital input pin on the Arduino each.

**How to read the data:**

The chip will read the data from the receiver on its Din pin. When it has found a valid transmission for the used address (which is configured through the address pins), then it will pull the VT pin to HIGH and output the new data on the pins. The datasheet says:

> The HT12D, on the other hand, provides 4latch type data pins whose data remain unchanged until new data are received.

Let's imagine, that you have send the pattern `HIGH, LOW, HIGH, LOW`. The HT12D will see this as valid data and set it's outputs to this pattern. The VT pin is pulled high to show, that new valid data arrived. Now you can read this pattern into the Arduino via multiple `digitalRead()` calls, one for each output pin of the HT12D.

The surrounding code depends on your needs. For example you could just read the pins continuously again and again, every time just outputting corresponding on the data. For example like this:

    void loop(){
        if(digitalRead(HT12D_pin1)) digitalWrite(LED_pin, HIGH);
    }

Or even easier:

    void loop(){
         digitalWrite(LED_pin, digitalRead(HT12D_pin1));
    }

Or you could also read the VT pin of the HT12D and only do something, if it is HIGH. That way you only act, if there is valid data received.

---

For more info you really need to improve your question.

  [1]: https://components101.com/sites/default/files/component_datasheet/HT12D Datasheet.pdf


body:
I programmed an Arduino Uno R3 to trigger a relay once every 24 hours from the moment it is powered on.

I calculated milliseconds and used the function `delay()`.

24 hours * 60 minutes each hour * 60 second every minute * 1000 milliseconds every second

so I used :

    delay(86400000)

for 86 million and 400 thousands milliseconds.

Currently, I'm still testing it...

Will this work? If not, is there a better built-in function/library or even external library to do it?

The relay trigger doesn't have to be very accurate at the very exact time each day.

I don't need it to be very accurate, it can shift few minutes every few months or so, thats okay with me.

But how about after few months or years of use ? Will it shift the timing much?

I read somewhere about using `millis()` function
and others use an RTC (Real Time Clock) module.

I don't want to use anRTC module, I am looking for a programmatical solution.

OR will my previous method using `delay()` work for such a very high number of milliseconds?

title: Programming Arduino Uno R3 to trigger a relay once every 24 hours

Answers: 3

body:
`delay()` takes an unsigned long; I think what you do will work.

When in doubt, you could always do something like this:

    for (int hours = 0; hours < 24; hours++) {
      for (int mins = 0; mins < 60; mins++) {
        for (int secs = 0; secs < 60; secs++) {
          delay(1000);
        }
      }
    }

It will be wildly inaccurate though, because the clock is inaccurate and will also drift with temperature, made worse because a resonator is used instead of a crystal.

You will get nowhere near an accuracy of a few minutes per month this way, whatever "delaying" method you use; the hardware isn't up to it.

body:
Yes, the delay() will work, as will other methods based on the millis() counter. However, delay() will make it impossible to do something else in the meantime.

Look up [Blink without delay](https://www.arduino.cc/en/tutorial/BlinkWithoutDelay) for an example of how to accomplish such a delay while being able to do other things in your code while waiting.

**Casting**

When dealing with large numbers such as your 24-hour delay, make sure to explicitly cast those numbers as `unsigned long`, or expressing them with the "UL" extension (like for example `86400000UL`). This explicitly tells C++ to expect an "unsigned long" (which in Arduino Uno terms is a 32-bit unsigned number).

In your case (with such an obviously large number), the compiler will automatically choose the right type. In other cases (for example, if you change the expression to `24*60*60*1000`), the compiler will not automatically generate an unsigned long and you need to force it by changing the first part of the expression to an unsigned long: `24UL*60*60*1000` or, alternatively `(unsigned long) 24*60*60*1000`.

**Accuracy**

The accuracy of the timing will be dependent on the type of oscillator on your particular Arduino board. Many Arduinos or their clones use a Ceramic Oscillator that generally have an accuracy of [about 0.1 to 0.5%][1], meaning a possible deviation of 43 seconds per day and as such maybe too inaccurate for your purposes. If your Arduino has a Crystal oscillator, it will be much more accurate (to something like 150ppm, meaning a maximum deviation of about 1 second per day under normal conditions).

  [1]: https://www5.epsondevice.com/en/information/technical_info/pdf/wp_20130425_material.pdf

body: You could try enclosing the Uno in a temperature controlled "oven", say a plastic enclosure with a very low power heater (even a suitable resistor might do) and thermo sensor in with it. It should reduce some of the variation in the crystal frequency.


body:
So I'm working on a personal project using bluetooth abilities to start a BLE server and want to automatically retrieve a client's information after it's connected: ID so I can keep track of clients, but brand/make, serial.. and other information would be good as well.

My `ServerCallback` class looks like this

```cpp
class ServerCallbacks: public BLEServerCallbacks
{
  void onConnect(BLEServer* pServer)
  {
    deviceConnected = true;
    BLEDevice::startAdvertising();

    String deviceID = "XXXXX";

    Serial.print("new device ");
    Serial.print(deviceID);
    Serial.println(" connected");

  };

  void onDisconnect(BLEServer* pServer)
  {
    deviceConnected = false;

    String deviceID = "XXXXX";

    Serial.print("device ");
    Serial.print(deviceID);
    Serial.println(" disconnected");

    pServer->startAdvertising(); // restart advertising
  }
};
```

title: Get client information on BLE

Answers: 0


body:
I received the error bellow when I tried to upload any sketch on my MKR100. I uninstall/reinstall de COM drivers and the arduino IDE and nothing solve the problem. I bought another MKR1000 thinking the ahrdare was the problem , but I got the same errors.
Also If I try to open the serial monitor I got :
Error opening serial port 'ÇOM12'(Port not found)

Can someone help me?

Sketch uses 47444 bytes (18%) of program storage space. Maximum is 262144 bytes.
Forcing reset using 1200bps open/close on port COM12
processing.app.debug.RunnerException
 at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:152)
 at cc.arduino.UploaderUtils.upload(UploaderUtils.java:77)
 at processing.app.SketchController.upload(SketchController.java:732)
 at processing.app.SketchController.exportApplet(SketchController.java:703)
 at processing.app.Editor$UploadHandler.run(Editor.java:2055)
 at java.lang.Thread.run(Thread.java:748)
Caused by: processing.app.SerialException: Error touching serial port 'COM12'.
 at processing.app.Serial.touchForCDCReset(Serial.java:107)
 at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:136)
 ... 5 more
Caused by: jssc.SerialPortException: Port name - COM12; Method name - openPort(); Exception type - Port not found.
 at jssc.SerialPort.openPort(SerialPort.java:167)
 at processing.app.Serial.touchForCDCReset(Serial.java:101)
 ... 6 more

title: Uploading doesn't work on MKR1000

Answers: 0


body:
first of all I have to say that this is my first Arduino thing. I'm trying to connect a k-type termocouple to my Arduino using an LM2904 Oamp, Yes I know that this is not the best solution but is the only that I have right now due to the pandemic situation, that I can't get a dedicated module as an MAX6675

This is what I have done:

[![enter image description here][1]][1]
*note:* The Grnd symbol next to 2.6k resistor is a handwritten error, its not connected in the circuit

my problem is that with this circuit I'm having 3.7V on the arduino analog input even before connect the termocouple. After connect it, the read is about 2.6V and it starts to increase as expected when heat is applied.

My problem is if I have 2.6V for 32°C for temperatures over 200°C I will have more than 5V. Any help with this?

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

title: Connect k-type termocouple using o-amp

Answers: 0


body:
rst:0x10 (RTCWDT_RTC_RESET),boot:0x1f (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371

I am getting this error in my esp32 devkit v1
How to solve it?
I am using arduino IDE for programming the esp32

title: A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header

Answers: 0


body: I made a project based on calling with gsm module and arduino and  now i want to transmit to voice wirelessly to my bluetooth earphone which module should i use for this purpose.

title: Ardunio wireless voice transmission

Answers: 0


body:
i am working on a control Interface for serveral Components including turbo Pumps from the company Pfeiffer.

The communication will be done according to the The Pfieffer Vacuum Protocol for RS485.

Does any one have experience with this Protokoll or is there a library that can be used for this art of communication.

I will use a MAXCHIPRS485 for the communication between Arduino (SerialPorts) and the Pumps RS485 Port.

the Wiring is clear .
I want to ask if someone already has done a similar Code that sends and reads from the Pump continuously.

Thanks in advance

title: The Pfieffer Vacuum Protocol for RS485

Answers: 0


body:
I'm trying to send a SMS and read data from Firebase with my NodeMCU Amica V2. The  code works fine when I either only send a SMS or only read data from Firebase. However, when I combine this two codes SMS isn't sent. This is the error I get:

```
+ Connected.
+ Post an HTTP send SMS request.
+ Connection is closed.
+ Response:

31.0630+ Using fingerprint 'BC B0 1A 32 80 5D E6 E4 A2 29 66 2B 08 C8 E0 4C 45 29 3F D0'
+ Connecting to api.twilio.com
- Connection failed.
Last SSL error was:
Unable to allocate memory for SSL structures and buffers.
ERRCODE: -1000
```

And here is my code:
```
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <base64.h>
#include "OneWire.h"
#include "DallasTemperature.h"
#include <ArduinoJson.h>
#include <string>
using namespace std;
#include <sstream>
#include <iostream>
#include "FirebaseArduino.h"

// Your network SSID and password
const char* ssid = "*****";
const char* password = "*****";

const char* account_sid = "*****";
const char* auth_token = "*****";
String to_number    = "+*****";
String from_number = "+*****";
String message_body    = "Hello from Twilio and the ESP8266!";

// Find the api.twilio.com SHA1 fingerprint using,
//  echo | openssl s_client -connect api.twilio.com:443 | openssl x509 -fingerprint
const char fingerprint[] = "BC B0 1A 32 80 5D E6 E4 A2 29 66 2B 08 C8 E0 4C 45 29 3F D0";

#define ONE_WIRE_BUS 4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

#define FIREBASE_HOST "***.firebaseio.com"
#define FIREBASE_AUTH "*****"

float temp1 = 0;
//float temp2 = 0;
String b;
int c;

String urlencode(String str) {
  String encodedString = "";
  char c;
  char code0;
  char code1;
  char code2;
  for (int i = 0; i < str.length(); i++) {
    c = str.charAt(i);
    if (c == ' ') {
      encodedString += '+';
    } else if (isalnum(c)) {
      encodedString += c;
    } else {
      code1 = (c & 0xf) + '0';
      if ((c & 0xf) > 9) {
        code1 = (c & 0xf) - 10 + 'A';
      }
      c = (c >> 4) & 0xf;
      code0 = c + '0';
      if (c > 9) {
        code0 = c - 10 + 'A';
      }
      code2 = '\0';
      encodedString += '%';
      encodedString += code0;
      encodedString += code1;
    }
    yield();
  }
  return encodedString;
}

String get_auth_header(const String& user, const String& password) {
  size_t toencodeLen = user.length() + password.length() + 2;
  char toencode[toencodeLen];
  memset(toencode, 0, toencodeLen);
  snprintf(toencode, toencodeLen, "%s:%s", user.c_str(), password.c_str());
  String encoded = base64::encode((uint8_t*)toencode, toencodeLen - 1);
  String encoded_string = String(encoded);
  std::string::size_type i = 0;
  // Strip newlines (after every 72 characters in spec)
  while (i < encoded_string.length()) {
    i = encoded_string.indexOf('\n', i);
    if (i == -1) {
      break;
    }
    encoded_string.remove(i, 1);
  }
  return "Authorization: Basic " + encoded_string;
}

void setup() {
  Serial.begin(115200); // 115200 or 9600
  delay(1000);        // Give the serial connection time to start before the first print.
  Serial.println(""); // Newline after garbage characters.
  Serial.println(F("+++ Setup."));

  // ----------------------------------------------------
  Serial.println("+ Connect to WiFi. ");
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("+ Connected to WiFi, IP address: ");
  Serial.println(WiFi.localIP());

// ----------------------------------------------------
sensors.begin();
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
}

void loop() {
      sensors.requestTemperatures();
  temp1 = sensors.getTempCByIndex(0);
  Serial.print(temp1);
  b = Firebase.getString("002/alarm");
    c = b.toInt();
    Serial.print(c);
      if (temp1 > c) {
      // Use WiFiClientSecure to create a TLS 1.2 connection.
  //  Note, using a cert fingerprint is required.
  WiFiClientSecure client;
  client.setFingerprint(fingerprint);
  Serial.printf("+ Using fingerprint '%s'\n", fingerprint);
  const char* host = "api.twilio.com";
  const int   httpsPort = 443;
  Serial.print("+ Connecting to ");
  Serial.println(host);
  if (!client.connect(host, httpsPort)) {
    Serial.println("- Connection failed.");
    char buf[200];
                int err = client.getLastSSLError(buf, 199);

                buf[199] = '\0';

                Serial.println("Last SSL error was:");

                Serial.println(buf);

                Serial.print("ERRCODE: ");
                Serial.println(err);
///* END snippet from pushdata-io project */
//              return false;
  }
  Serial.println("+ Connected.");
    Serial.println("+ Post an HTTP send SMS request.");
  String post_data = "To=" + urlencode(to_number)
                     + "&From=" + urlencode(from_number)
                     + "&Body=" + urlencode(message_body);
  String auth_header = get_auth_header(account_sid, auth_token);
  String http_request = "POST /2010-04-01/Accounts/" + String(account_sid) + "/Messages HTTP/1.1\r\n"
                        + auth_header + "\r\n"
                        + "Host: " + host + "\r\n"
                        + "Cache-control: no-cache\r\n"
                        + "User-Agent: ESP8266 Twilio Example\r\n"
                        + "Content-Type: application/x-www-form-urlencoded\r\n"
                        + "Content-Length: " + post_data.length() + "\r\n"
                        + "Connection: close\r\n"
                        + "\r\n"
                        + post_data
                        + "\r\n";
  client.println(http_request);
  // Read the response.
  String response = "";
  while (client.connected()) {
    String line = client.readStringUntil('\n');
    response += (line);
    response += ("\r\n");
  }
  Serial.println("+ Connection is closed.");
  Serial.println("+ Response:");
  Serial.println(response);
      }
  delay(5000);
}
```

Does that mean that the NodeMCU doesn't have enough memory? I also tried changing delay() to milis(), but that didn't solve the problem.

Any help would be appreciated!

title: Unable to allocate memory

Answers: 0


body:
I have spent the better part of today trying to figure out why I can't get this to work...

I have this project where, because of previous design considerations, have implemented a singleton class that initializes a bunch of separate sensors in this system that I am running.

The system was originally built for the Particle Boron, but now I am trying to make it work with the Adafruit Feather M0, so I have had to refactor several things and omit lots of lines of Particle RTOS specific things.

However, in doing this, I find that my singleton class no longer works.

**Sensors.h:**
```
.
.
.

class Sensors{

    static Sensors *instance;

public:
    static Sensors *getInstance() {
        if (!instance) {
            instance = new Sensors;
        }
        return instance;
    }

}

private:
    Sensors();

.
.
.
```

**Sensors.cpp:**

```
.
.
.

Sensors::Sensors() : dht22(DHTPIN, DHTTYPE) {
#ifdef PLATFORM_ID
    sensorLog("app.Sensors");
#endif
}

.
.
.
```

**main.ino:**
```
.
.
.

// Sensors
Sensors *Sensors::instance = nullptr;
Sensors *allSensors = allSensors->getInstance();

void setup(){

.
.
.
```

As I try to compile this with ArduinoISP, no matter what I try, I get the following error:

```
sketch/main.ino.cpp.o: in function `Sensors::getInstance()':
sketch/lib/Sensors/src/Sensors.h:23: undefined reference to `Sensors::Sensors()'
collect2: error: ld returned 1 exit status
exit status 1
[Error] Exit with code=1
```

I have tried things like changing the line
```
instance = new Sensor;
```
to
```
instance = new Sensor();
```
making the ```instance``` public, changing the Sensor constructor, but all of this to no avail. Could this be a compiler issue? Why would this work on a Particle board, but not an Adafruit Feather M0?

title: Cannot successfully implement singleton

Answers: 2

body:
Singletons aren't a thing in Arduino. Sure, you *could* do it, but in general you'd make a class then instantiate a global object for that class. Most often that global object is instantiated in the library itself, not the sketch.

Unless you're using an advanced chip with an RTOS (such as ESP32) and making use of the threads of that RTOS heavily there is no benefit to having a singleton.

But to answer your actual question: it's probably because you are trying to use the `Sensors()` constructor at a time before the compiler knows what the `Sensors()` constructor is. You would have to add some form of forward declaration so that the compiler knows what you mean when you talk about the `Sensors()` constructor.  In general a simple:

    class Sensors;

at near the top of your header before the class is actually defined can help in these situations;

body:
I had the same problem when referencing classes from multiple files, remember to put at the top of your header file (ending in .h) `#pragma once` on files that get referenced more than once!

Edit1: Also after you declare your class you need to specify where your static variable will be stored.
After the class declaration write:

type *Class::variable;

To declare the static variable.

For example:

    #pragma once
    //#includes

    class Screen
    {
    protected:
      static void (*StateMachineStep)(int);
      static SSOLED *oled;
      static Player *player;

    public:
      Screen() {}

    };

    void (*Screen::StateMachineStep)(int);
    SSOLED *Screen::oled;
    Player *Screen::player;

Edit2: formatting


body:
In most 12v CCTV power supplies, each power cable is behind a glass fuse.  I haven't seen fuses or circuit breakers used when distributing 5v power used in IoT projects.  Is there a reason overcurrent protection is not needed in these projects?

edit:
I'm thinking specifically about fire safety.  e.g. the risk of a short circuit overheating 22awg wire run through the house?

title: circuit breaker/fuse necessary for IoT home monitor?

Answers: 1

body:
> Is there a reason overcurrent protection is not needed in these projects?

You're comparing apples and oranges.

The two systems are completely different and have different concerns.

Case in point:

* You want to burgle somewhere with CCTV installed. You can creep up on one camera unobserved.
* You know a little about electronics and figure if you cut the feed to the camera you can short out the power and blow the whole system, thus letting you wander in unobserved.

But there's fuses on each feed, so all you do is disable the *one* camera and everything else is fine, catching you red handed.

Go directly to jail. Do not pass go. Do not collect £200.

Now... do you really care that much if all your home temperature sensors lose power because of a fault in one? Probably not. And the chances of there being a fault other than from human negligence is slim. Sure, you *could* add fuses, but why add the expense? It's really not needed for such a non-critical system.

----

> edit: I'm thinking specifically about fire safety. e.g. the risk of a short circuit overheating 22awg wire run through the house?

22AWG wire has a resistance of about 53Ω per km. Say you have a loop of cable 20m long (10m there and 10m back again) and it shorted out at the far end. That's round about 1Ω.

At 5V you'd be drawing 5A of current.

If you have a really powerful power supply then it would try and supply that, and the wire would warm up - giving off about 25W of heat *over the entire length*. You might feel a bit of warmth from it.

Of course, most people would be using a smaller power supply than that for simple IoT things, so the power supply would just go "No. You're not having that!" and would die, or its internal fuse would blow. Or it would drop the voltage and get hot itself.

The chance of being able to start a fire from 5V over 22AWG from a normal power supply is pretty much zero. You're more likely going to start a fire from using a low quality power supply that itself melts and catches fire (i.e., a counterfeit Chinese phone charger).

With a very powerful power supply (tens of amps or more) and a short circuit close to the source (so low resistance) the wire will melt. Just that. It'll melt. Once melted there's no circuit, so nothing else happens. There's your fuse right there.

Once a wire has melted it doesn't continue to burn. And you don't get arcs at low voltages. It takes a lot of work to start a fire from low voltages. A lot of work and a lot of current.


body:
I need some help. I copied the heart of MEGA2560 design into a new project. I have the new PCBs with blank MCUs and now I need to get things programmed. (I have an existing project that runs on a MEGA2560)

I was able to get the MEGA16U2 programmed using the procedure here: https://www.arduino.cc/en/Hacking/DFUProgramming8U2, (I loaded "Arduino-usbserial-atmega16u2-Mega2560-Rev3.hex") and it shows up in the Arduino IDE.

I got the ATMEGA2560 bootloader loaded using the Arduino-as-ISP instructions here: https://www.arduino.cc/en/Tutorial/ArduinoISP

But, now when I try to program my board with the with Arduino IDE (through the USB connection of the MEGA16U2), I just get:

```
avrdude: stk500v2_ReceiveMessage(): timeout
```

The full output of the IDE is:

```
Sketch uses 30056 bytes (11%) of program storage space. Maximum is 253952 bytes.
Global variables use 1280 bytes (15%) of dynamic memory, leaving 6912 bytes for local variables. Maximum is 8192 bytes.
/home/xxxxx/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/bin/avrdude -C/home/xxxxx/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf -v -patmega2560 -cwiring -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/arduino_build_464802/yyyyy.ino.hex:i

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/xxxxx/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf"
         User configuration file is "/home/xxxxx/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : wiring
         Overriding Baud Rate          : 115200
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

avrdude done.  Thank you.

An error occurred while uploading the sketch
```

I can see the RX led of the MEGA16U2 flashing, and the data at the RX pin of the ATMEGA2560 IC, indicating that data is getting to the MCU from the IDE, but there is no corresponding  TX activity.

The IDE and USB cable can program an Elegoo MEGA2560 clone with no problem.

Is this a baud rate problem? A protocol problem? What should be my next debugging step?

Thanks!

---

EDIT: Per Nick Gammon's comment, I have run his chip detector script. Here is the output:

```

Atmega chip detector.
Written by Nick Gammon.
Version 1.20
Compiled on Sep  5 2020 at 07:17:55 with Arduino IDE 10812.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x98 0x01
Processor = ATmega2560
Flash memory size = 262144 bytes.
LFuse = 0xFF
HFuse = 0xD8
EFuse = 0xFD
Lock byte = 0xCF
Clock calibration = 0x88
Bootloader in use: Yes
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 8192 bytes starting at 3E000

Bootloader:

3E000: 0x0D 0x94 0x89 0xF1 0x0D 0x94 0xB2 0xF1 0x0D 0x94 0xB2 0xF1 0x0D 0x94 0xB2 0xF1

<....snipped for length....>

3FFF0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF

MD5 sum of bootloader = 0xD9 0xE6 0x6B 0x4E 0xD1 0xA6 0x11 0x2C 0x61 0x8F 0x9B 0xD5 0x5D 0x24 0xE2 0x13
Bootloader MD5 sum not known.

First 256 bytes of program memory:

00: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
10: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
20: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
30: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
40: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
50: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
60: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
70: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
80: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
90: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
A0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
B0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
C0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
D0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
E0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
F0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF

Programming mode off.

```

title: Trouble programming custom ATMEGA2560 board

Answers: 1

body:
As per the comments your output shows that the chip is working "normally" in that it reacts to the chip detector sketch. Thus the bulk of the design/implementation is OK.

Referring to [Engbedded Atmel AVR® Fuse Calculator](https://www.engbedded.com/fusecalc/) your fuse settings means the processor is expecting an external crystal oscillator. The bootloader expects (I think) a 16 MHz crystal (with appropriate capacitors). If you have not provided this then the bootloader will be running at the wrong baud rate (so to speak) — or not at all — and not react to attempts to download it by serial programming.

If you have a different frequency crystal then you may be able to work around this by adjusting the baud rate in the boards.txt file by an appropriate scaling factor.

The chip detector sketch worked because that uses ICSP programming, which provides its own clock.


body:
So I flashed the [KeyboardMessage][1] example to my [Arduino SS Micro ATmega32U4][2].

When I open an editor and push the button, I would assume the output to be

> Zou pressed the button XX times.

(The "Z" is because I use a German keyboard)

In some editors (Arduino IDE, LibreOffice) this assumption is fulfilled.

However, in several other editors (Linux Shell, gedit), **most of the times** the output is

> zou pressed the button 1 times.

starting with a lower case "z".

I use a Debian Testing computer. The only thing I changed in the sketch was the `buttonPin` as my button is soldered to pin 11.

I noticed, that this problem doesn't occur when the button is pressed a second time shortly after the first message. To investigate this, I coded a [little sketch][3] to find the threshold.

This is what I got (in gedit)

[![output][4]][4]

As line 8 shows, even after 70 millis, the upper case start is not reliable, however, somewhere after 250 millis, the error occurs every time.

My questions are:

 1. What could be the cause for this issue?
 2. How can it be fixed (if necessary, I also welcome a workaround)?

Please tell me if you need any additional information.

[edit]
After slightly altering the script, I noticed, that the problem doesn't only occur on the start of a line, but also (although less often) later in the output. See lines 24, 31 and 52 for example

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

  [1]: https://www.arduino.cc/en/Tutorial/KeyboardMessage
  [2]: https://circuit.rocks/ss-micro-atmega32u4-arduino-compatible.html
  [3]: https://gist.github.com/speendo/c4001a6bf2fdecce148a2c1094cc10fd
  [4]: https://i.stack.imgur.com/k1I8Y.png
  [5]: https://i.stack.imgur.com/YiWd3.png

title: Arduino Keyboard starts lower case (but it shouldn't)

Answers: 1

body:
I am not sure I have the answer to your problem, just a collection of
observations that hopefully steer you in the right direction.

According to your nopaste link, when you send "ON", the first four
keyboard events received by `xev` are: press(Shift\_L), press(O),
release(Shift\_L), release(o). One may notice that there is no point in
releasing the Shift key if it's going to be pressed again right away,
but let's assume that simply holding Shift is not such a useful
optimization. The detail that strikes me is that the last two events
look backwards: you usually release the letter _before_ releasing Shift.
As a result of releasing Shift first, the release event for the O key
reports lowercase "o" as a keysym. I tried this backward way of
releasing the keys on a real keyboard, but both gnome-terminal and gedit
correctly registered the uppercase letters.

Another detail apparent in the xev dump is that the two key presses
(Shit and O) happen at the exact same time. Ditto for the corresponding
key releases. Looking at the source of the Keyboard library, it appears
that both key presses are sent to the PC as a single "key report". Same
for the key releases. This is contrary to what a real keyboard does:
actuations on the Shift keys are reported immediately, irrespective of
whether other keys are actuated.

You may try to modify the Keyboard library so that the actuations on
Shift are sent in their own reports. Maybe something like this
(**warning**: completely untested):

```diff
diff --git a/src/Keyboard.cpp b/src/Keyboard.cpp
index 4a948f6..9fbf7b6 100644
--- a/src/Keyboard.cpp
+++ b/src/Keyboard.cpp
@@ -239,6 +239,7 @@ size_t Keyboard_::press(uint8_t k)
   }
   if (k & 0x80) {      // it's a capital letter or other character reached with shift
    _keyReport.modifiers |= 0x02; // the left shift modifier
+   sendReport(&_keyReport);  // send the shift key by itself
    k &= 0x7F;
   }
  }
@@ -270,6 +271,7 @@ size_t Keyboard_::press(uint8_t k)
 size_t Keyboard_::release(uint8_t k)
 {
  uint8_t i;
+ bool has_shift = false;
  if (k >= 136) {   // it's a non-printing key (not a modifier)
   k = k - 136;
  } else if (k >= 128) { // it's a modifier key
@@ -281,7 +283,7 @@ size_t Keyboard_::release(uint8_t k)
    return 0;
   }
   if (k & 0x80) {       // it's a capital letter or other character reached with shift
-   _keyReport.modifiers &= ~(0x02); // the left shift modifier
+   has_shift = true;
    k &= 0x7F;
   }
  }
@@ -295,6 +297,10 @@ size_t Keyboard_::release(uint8_t k)
  }

  sendReport(&_keyReport);
+ if (has_shift) {
+  _keyReport.modifiers &= ~(0x02); // the left shift modifier
+  sendReport(&_keyReport);   // release shift after releasing the letter
+ }
  return 1;
 }

```

Alternatively, as suggested by @jstola in a comment, you may try to
press the Shift key by itself. Maybe you don't need to care about the
key release, or about any character but the first one (as it is the only
one that seems to cause problems). A minimal workaround to try would be:

```cpp
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.println("ON");
```


body:
This is my first post here, so apologies in advance if I've done something against any forum guidelines!

I have a project where I am monitoring multiple switch states with an Arduino using multiple MCP23017 ICs. I found a fantastic [article by Nick Gammon][1] which pretty much does what I want for the first element of the project at least. There are 2 small errors in his expanderWriteBoth and expanderRead routines - swap "send" for "write", and "receive" for "read" and the code works out of the box.

However - Nick's code will only display which pin has triggered the interrupt when the input pin is grounded. If you remove the ground to return the pin to the previous state, it will not state that this pin has changed state.

Can anybody see why this is the case? I have been through the datasheet for the MCP over and over again with no clues...

Any help appreciated,
Thanks.

  [1]: http://www.gammon.com.au/forum/?id=10945&reply=1#reply1

title: Which pin triggered MCP23017 interrupt

Answers: 0


body:
I have an [esp32cam](https://www.aliexpress.com/item/32994222661.html?src=google&albch=shopping&acnt=494-037-6276&isdl=y&slnk=&plac=&mtctp=&albbt=Google_7_shopping&aff_platform=google&aff_short_key=UneMJZVf&&albagn=888888&albcp=9441019410&albag=95283287465&trgt=296904914040&crea=en32994222661&netw=u&device=c&albpg=296904914040&albpd=en32994222661&gclid=Cj0KCQjw7sz6BRDYARIsAPHzrNIBCyBnIv8PYFNA9XixKB9zNyEYuIYPcMHwMwKJoxjWxvYwV5oM4tIaAp8oEALw_wcB&gclsrc=aw.ds) that I've [programmed and powered via an FTDI connected to a computer's USB](https://dronebotworkshop.com/esp32-cam-intro/). Now that this stage is over, I'd like to run it portably, using some sort of battery.

The esp32cam has a 5V input (also a 3.3V input which word is should be avoided because it causes brownout). I'm wondering if it's possible to power it (for a short period) using a 7.3V, 9V or 12.3V battery. All the datasheets I've seen seem to specify the input range is 5V, but, for the esp32 (non-cam version), [unregulated 5V-12V seems to permissible](https://techexplorations.com/guides/esp32/begin/power/). Is this true for the esp32cam? Also, what is the right way to search for this?

title: Powering an esp32cam by a battery

Answers: 1

body:
The official ESP32-CAM has a AMS1117 voltage regulator that creates the 3.3V for the ESP.

The AMS1117 has an Absolute Maximum Input Voltage of 15V. It has a Dropout Voltage of 1.1-1.3V.

So you should stay above 4.6V to be on the safe side.

Since it's a linear voltage regulator, using a higher voltage battery has no advantage, as the "excess voltage" is converted to heat. It could even damage the regulator if too much heat is created.

You should pick the battery with the lowest voltage that still produces 4.6V when almost empty. So you could use the 7.3V battery you indicated. I'm assuming this is a 2-cell Li-ion battery, that has a voltage of 8.4V when full, and around 6V when empty. Which nicely fits your requirements.


body:
I'm having problems with my setup.

I'm trying to create a wind-speed system when you send an SMS to retrieve the correct wind speed as an SMS response.

I'm using a pro mini, connected by USB via FTDI, and a SIM808 module.

The SIM808 is connected to a mains supply and the LED status suggests it is connected to the network.

The SIM808 pins are as follows:

    TX > Pin 9
    RX > Pin 10
    VMCU V IN > Power supply +
    GND (the one under VMCU) > Power supply -
    GND (under Li-on) > GND on the Arduino

I've tried lots of source code examples but nothing much seems to happen, this is the latest code I'm testing (the top part of the loop at least). In the serial monitor, it reports back the "Sim808 init error" over and over.

    include <DFRobot_sim808.h>
    include <SoftwareSerial.h>
    define MESSAGE_LENGTH 160
    char message[MESSAGE_LENGTH];
    int messageIndex = 0;
    char MESSAGE[300];
    char lat[12];
    char lon[12];
    char wspeed[12];

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

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

    void sendSMS(); void getGPS(); void readSMS();

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

    //******** Initialize sim808 module *************
    while(!sim808.init()) {
      Serial.print("Sim808 init error\r\n");
      delay(1000);
    }
    delay(3000);

    Serial.println("SIM Init success");

I hope someone can help as I've spent ages on this and had no luck.

title: Problems using SIM808 with Pro Mini

Answers: 0


body:
I am planning a build with my own enclosure for the arduino due. As an alternative i would like to bypass the power jack and usb port that are factory soldered onto the board, in order to use jacks mounted on the enclosure, along with a power switch.

I've looked at the info regarding the boards pin configuration at https://www.arduino.cc/en/pmwiki.php?n=Main/arduinoBoardDue, and would appreciate if someone could confirm or correct this:

1. Can i use an external 9V adapter through a jack connected to the Vin and GND pins, respectively?

2. According to [This question][1], you can't connect an alternative programming USB port to Serial 0 TX/RX pins (Mega board). If this applies to the due as well, what do i need to break out the programming USB port?

Edit: Perhaps [one of these puppies][2] is the least complicated solution?

  [1]: https://arduino.stackexchange.com/questions/47480/are-pins-0-and-1-rx-and-tx-parallel-with-the-usb-jack-can-i-connect-another-u
  [2]: https://www.adafruit.com/product/3258

title: How to break out the due power supply and USB connectors?

Answers: 1

body:
so 1 - yes. the VIN pin has a common trace with the barrel jack, you can verify with a multimeter in continuity/beep mode. ive actually put power out through the barrel jack on a mega.

2- i cant find a clear schematic for the due at the moment, but on the mega the rx/tx pins are also common with the usb pins, thus they are not usable while plugged into usb


body: We designed a big piano with 15 buttons on it. Every button has a proximity sensor. Whenever users interact with the sensor a specific sound plays for that button. My code is working fine for this purpose but now I want to add background music. Our piano button sound should play on top of that background music. I am using tmrpcm library, and I already added a bg music but when I interact with the sensor, bg music stops and starts from the beginning right after the piano button sound stops. Is there a way to play a sound without interrupting a bg music. Any help will be appreciated.

title: Play sound on top of background music using arduino uno tmrpcm library

Answers: 1

body:
Assuming you are using an Arduino Uno, You didn't say. As there are many Arduino platforms these days.

As the [tmrpcm library][1] is using the [PWM  (Pulse Width Modulator) HW (Hard Ware)][2] to recreate the sound waves from the WAV file on the SDCard, the PWM is not available for creating the sounds from your piano application (you didn't say what piano application you were using).  That said, it is not impossible to re-write both applications to SUM the two wave forms together mathematically before resampling the SUM and writing that sample value to the PWM HW to simulate the SUM of the two wave forms.  However, this is likely not trivial and it is also likely the [Arduino Uno][3] processor (an [Atmel ATmega328P][4]) will not be powerful enough (perform the math fast enough) to keep up with normal sound playback.

It would likely be much simpler to use 2 Arduino Uno boards and sum the sound from the sound file application and the piano application using analog techniques external from the Arduno Uno boards.

  [1]: https://github.com/TMRh20/TMRpcm
  [2]: https://en.wikipedia.org/wiki/Pulse-width_modulation
  [3]: https://store.arduino.cc/usa/arduino-uno-rev3?gclid=Cj0KCQjw7sz6BRDYARIsAPHzrNL8aVQbqWM4sE5qDRPXdlLgkzKT1edt8cn9HgS7z7tyXz4VYCJFd_EaAnTREALw_wcB
  [4]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf


body:
So i was trying to implement a tilt compensated compass, using HMC5883L and MPU6050. The problem i am facing is, there are 2 equations for tilt compensation

**Tilt Compensated X:**   X,Y,Z are compass output (raw output)

```new_X =  X*cos(pitch) + Y*sin(roll)*sin(pitch) – Z*cos(roll)*sin(pitch)```

**Tilt Compensated Y:**

```new Y =  Y*cos(roll) + Z*sin(roll)```

**Final Heading :**
```Azimuth =  atan2(Y, X) * RAD_TO_DEG```

The angles which i am getting from the mpu are gyro-drift corrected angles which are coming through a kalman filter. Those angles are fed to these above equations and after ```atan2``` i get the tilt compensated heading. But the issue/observation here is, when i rotate the body(on which the compass and mpu are) along the Z axis (YAW axis) the heading doesn't change(sort of locked on), but changes when i tilt the body in X/Y.
I searched for thorough references, but wasn't able to find any!
Here is my code snippet (uses *compass* part form adafruit library):
```
double HEADING(double r, double p){
  sensors_event_t event;
  mag.getEvent(&event);
  r = r * (PI/180);
  p = p * (PI/180);
  double x = (event.magnetic.x)*cos(p) + (event.magnetic.y)*sin(r)*sin(p) - (event.magnetic.z)*cos(r)*sin(p);
  double y = (event.magnetic.y)*cos(r) + (event.magnetic.z)*sin(r);

  float heading = atan2(y,x);

  float declinationAngle = 0.366667 * (PI/180);// (0°22')positve declination
  heading += declinationAngle;

  if(heading < 0)
    heading += 2*PI;

  if(heading > 2*PI)
    heading -= 2*PI;

  heading = heading * 180/PI;

  return heading;
}
```
**The HMC5883L data acquisition I wrote :**
```
// i just need a direction reference not actual heading, just to keep my drone
// steady on yaw axis with reference to that direction reference but it shall be Tilt compensated
#include<Wire.h>

#define MAG 0x1E

#define R 0
#define P 1
#define Y 2

float mag_raw[3],h;
float CMP_DEC = 0.36667 * (PI/180);

void setup(){
  Serial.begin(115200);
  Wire.begin();
  Wire.setClock(400000);

  Wire.beginTransmission(MAG);
  Wire.write(0x02);
  Wire.write(0x00);
  Wire.endTransmission(true);

}

void loop(){
  Wire.beginTransmission(MAG);
  Wire.write(0x03);
  Wire.endTransmission(false);
  Wire.requestFrom(MAG,6,true);

  mag_raw[R] = Wire.read() << 8 | Wire.read();
  mag_raw[P] = Wire.read() << 8 | Wire.read();
  mag_raw[Y] = Wire.read() << 8 | Wire.read();

  h = atan2(mag_raw[P],mag_raw[R]);

//  h += CMP_DEC;

  if(h < 0) h+= (2*PI);
  if(h > (2*PI)) h -= (2*PI);
  h *= (180/PI);

//  Serial.print("X : ");
//  Serial.print(mag_raw[R]);
//  Serial.print(" Y : ");
//  Serial.print(mag_raw[P]);
//  Serial.print(" Z : ");
//  Serial.print(mag_raw[Y]);

  Serial.print(" H : ");
  Serial.println(h);

}
```
Some guidance will be very helpful!

title: How to implement a tilt compensated compass?

Answers: 1

body:
Inspecting your code, it does not appear you are [compensating the raw magnetometer values for soft and hard iron effects][1].  These terms roughly refer to adjusting the range and magnitude of each of the individual magnetometers (X, Y and Z).  Some magnetometer manufactures allow writing these compensation values into the chip.  Even then the developer and user will still need to perform some form of calibration as the magnetometer can not predict under what conditions the magnetometer will be used.  [Here is another explanation using matrices of hard and soft iron compensation][2].

Once the compass produces expected results on a flat surface parallel to the surface of the earth (in a place on earth where the magnetic lines roughly align with true north).  Consider adding tilt compensation.  Accelerometers usually do not need to be compensated as extensively as magnetometers.

This can be done using trigonometric math and [Euler angles][3].  However, as with physical [gambles][4], this can lead to a situation similar to [gimbal lock][5].  Where the trigonometric math goes to infinity.

To avoid a gimbal lock like situation, most tilt compensated compasses use [quaternions][6].  Quaternions use imaginary numbers and matrix math to describe 3 dimensional rotation.

  [1]: https://www.fierceelectronics.com/components/compensating-for-tilt-hard-iron-and-soft-iron-effects
  [2]: https://www.vectornav.com/resources/magnetometer-errors-calibration
  [3]: https://en.wikipedia.org/wiki/Euler_angles
  [4]: https://en.wikipedia.org/wiki/Gimbal
  [5]: https://en.wikipedia.org/wiki/Gimbal_lock
  [6]: https://en.wikipedia.org/wiki/Quaternion


body:
I am using BMP 280 for an altimeter to measure the altitude. Once all connected and uploaded the BMP280test code from Adafruit, the serial monitor says busy. But still, when I switch the port in tools, nothing shows on the serial monitor. How do I get the monitor to start displaying data?

Thanks

 Code:

    #include <Wire.h>
    #include <SPI.h>
    #include <Adafruit_BMP280.h>

    #define BMP_SCK  (13)
    #define BMP_MISO (12)
    #define BMP_MOSI (11)
    #define BMP_CS   (10)

    Adafruit_BMP280 bmp; // I2C
    //Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
    //Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);

    void setup() {
      Serial.begin(9600);
      Serial.println(F("BMP280 test"));

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

      /* Default settings from datasheet. */
      bmp.setSampling(Adafruit_BMP280::MODE_NORMAL,     /* Operating Mode. */
                      Adafruit_BMP280::SAMPLING_X2,     /* Temp. oversampling */
                      Adafruit_BMP280::SAMPLING_X16,    /* Pressure oversampling */
                      Adafruit_BMP280::FILTER_X16,      /* Filtering. */
                      Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */
    }

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

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

        Serial.print(F("Approx altitude = "));
        Serial.print(bmp.readAltitude(1013.25)); /* Adjusted to local forecast! */
        Serial.println(" m");

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

title: Serial Monitor Not Displaying

Answers: 0


body:
I have a WS2812b addressable RGB led ribbon that is 5m (150 RGB leds). I purchased a 5v 10amp power supply to power it; however, whenever I try to use it to power the LED strip the leds start flashing colors like crazy. Is there a reason I would be seeing this behavior or is this a sign of a bad power supply?

The setup is very simple, the data line is coming from an Arduino Uno, the voltage and ground are from the power supply. The program is just one of the sample ones with FastLED library and works "fine" when just powered by the arudino's 5V pin.

Thank you

title: WS2812B Power Supply

Answers: 1

body: The strip and the Arduino need to share the same ground connection. They are communicating through voltage and voltage is always a difference between two points. The power supply sets the supply voltage as the difference between + and ground. The chips in the strip will then try to measure the voltage on the data line relative to their ground. When the grounds are not connected, the Arduinos output pin is floating somewhere else, depending on external factors. By connecting the grounds, both devices (Arduino and strip) use the same ground value to measure voltages. Only this enables communication between the devices.


body:
[![enter image description here][1]][1]I just bought 2 Max9744 amplifiers that I wish to scan the I2C addresses, just to check against what is said in documentation. I have the amplifier powered with a 12 v supply and the Arduino powered via usb. I run an I2Cscanner it says Devices found: in the serial monitor but doesn't say the address. The wiring is correct and the 5 v supply is giving 5 V. So what gives?
Thank you
Andrew

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

title: Getting the I2C Address from a Max9744 amplifier

Answers: 0


body: I wanted to know if there is a way for my arduino to keep the last command I sent to it before I disconnected it from my computer. Thanks.

title: Arduino offline commands

Answers: 1

body: Arduino always store the last sketch you have uploaded. Even if you disconnect your board and then replug it then it follow the same commands that you gave earlier.


body: I am doing stand thrust and I have three load cells to measure the force. I would like to know if I can sum them to gather into the Arduino or I should use a junction box.

title: I have three load cells can I sum all the three into Arduino to be one output? If yes how?

Answers: 0


body:
I'm using software serial on my weather station. The way it's supposed to work is that you send an SMS to the device and it replies with the wind speed, etc.

At the moment, The wind speed is detected, waiting for an incoming SMS. The SMS arrives and it sends a response but the response SMS is sent over and over infinitely.
I'm guessing the problem is due to the:

     if (mySerial.available()>0){

As this is what I'm using to test whether the SMS has arrived and presumably, it's then always set to available.

Does anyone know how to basically reset the software serial after the message has been sent?

     #include <SoftwareSerial.h>
     #include <ADSWeather.h>

    SoftwareSerial mySerial(9, 10);

    #define ANEMOMETER_PIN 2
    #define VANE_PIN 0
    #define RAIN_PIN 3

    #define CALC_INTERVAL 1000

    unsigned long nextCalc;
    unsigned long timer;

    int windDir;
    int windSpeed;
    int rainAmmount;

    ADSWeather ws1(RAIN_PIN, VANE_PIN, ANEMOMETER_PIN); //This should configure all pins correctly

    void setup()
    {
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(RAIN_PIN), ws1.countRain, FALLING); //ws1.countRain is the ISR for the rain gauge.
      attachInterrupt(digitalPinToInterrupt(ANEMOMETER_PIN), ws1.countAnemometer, FALLING); //ws1.countAnemometer is the ISR for the anemometer.
      nextCalc = millis() + CALC_INTERVAL;

      mySerial.begin(9600);   // Setting the baud rate of GSM Module
      delay(100);
    }

    void loop()
    {
      timer = millis();

      int rainAmmount;
      long windSpeed;
      long windDirection;
      int windGust;
      int sent;

      ws1.update(); //Call this every cycle in your main loop to update all the sensor values

      if(timer > nextCalc)
      {

        nextCalc = timer + CALC_INTERVAL;
        rainAmmount = ws1.getRain();
        windSpeed = ws1.getWindSpeed();
        windDirection = ws1.getWindDirection();
        windGust = ws1.getWindGust();

    //     windSpeed / 10 will give the interger component of the wind speed
    //     windSpeed % 10 will give the fractional component of the wind speed
        Serial.print("Wind speed: ");
        Serial.print(windSpeed / 10);
        Serial.print('.');
        Serial.print(windSpeed % 10);
        Serial.print(" ");

        Serial.print("Gusting at: ");
        Serial.print(windGust / 10);
        Serial.print('.');
        Serial.print(windGust % 10);
        Serial.println("");

      }

      if (Serial.available()>0)
      {
          RecieveMessage();
      }

      //If an message comes in
     if (mySerial.available()>0){
      // Serial.write(mySerial.read());
      Serial.write("Message received");

      //Send the wind speed response.
      SendMessage();

      //At this point the SendMessage() repeats and the message is sent over and over.
    }
    }

     void SendMessage()
    {
      mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
      delay(1000);  // Delay of 1000 milli seconds or 1 second
      mySerial.println("AT+CMGS=\"NUMRemoved\"\r"); // Replace x with mobile number
      delay(1000);
      mySerial.println("I am SMS from GSM Module");// The SMS text you want to send
      delay(100);
       mySerial.println((char)26);// ASCII code of CTRL+Z
      delay(1000);
    }

     void RecieveMessage()
    {
      mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
      delay(1000);
     }

     void serialFlush(){
      while(mySerial.available() > 0) {
        char t = mySerial.read();
      }
    }

title: How to clear SoftwareSerial values?

Answers: 3

body:
For the hardware serial port, the buffer is 64 and I was reading at least 100 times. Every read will clear one byte of data from the serial buffer at a time.

For the software serial port, you do a dummy read and then check whether the buffer is empty or not using

        while(mySerial.available()>0)  {
           dummy = mySerial.read();
        }

So, in summary, you have to read the buffer until it is empty.

**Useful notes:**

1. You should be knowing when to expect actual data and when not to
2. have a way to identify the valid messages (some fixed header bytes)
3. have a way to validate the contents (checksum)

Leave a comment if you have any questions

body:
     if (mySerial.available()>0){

You are checking if any serial data has arrived. Then you **never** read it. So naturally it is always available. You have a serialFlush function which does read it, however that function is never called.

You need, however, to read more than one byte. Otherwise you will send an SMS for every byte in the input message.

body:
```c++
if (mySerial.available() > 0) {
  // Serial.write(mySerial.read());
  Serial.write("Message received");

  //Send the wind speed response.
  SendMessage();

  mySerial.begin(9600);   // Reset myserial buffer

  //At this point the SendMessage() repeats and the message is sent over and over.
}
```


body:
I need to read two values from hx711 load cells connected to strain guages. Ive found the code below that reads one guage, but being self taught and with little experience I have no idea how to adapt it to work with two, is anyone able to help?
I need two individual readings not a combined one
Thanks in advance, and credit to sparkfun who wrote this code.

```
#include "HX711.h"

#define calibration_factor -7050.0 //This value is obtained using the SparkFun_HX711_Calibration sketch

#define DOUT  3
#define CLK  2

HX711 scale;

void setup() {
  Serial.begin(9600);
  Serial.println("HX711 scale demo");

  scale.begin(DOUT, CLK);
  scale.set_scale(calibration_factor); //This value is obtained by using the SparkFun_HX711_Calibration sketch
  scale.tare(); //Assuming there is no weight on the scale at start up, reset the scale to 0

  Serial.println("Readings:");
}

void loop() {
  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 1); //scale.get_units() returns a float
  Serial.print(" lbs"); //You can change this to kg but you'll need to refactor the calibration_factor
  Serial.println();
}
```

title: Read two HX711 load cell amps

Answers: 1

body:
The line:

    HX711 scale;

is called the "instantiation of the object". It creates a new object called `scale` which is an instance of the HX711 class. It is this "object" that is your interface to the HX711 physical device.

To use two of them you first need to have two objects - one for each HX711. You can name them whatever you like.  For example:

    HX711 scale1;
    HX711 scale2;

The line:

    scale.begin(DOUT, CLK);

is where it tells the HX711 object which pins the HX711 chip is connected to. In this case `DOUT` and `CLK` which you have defined as 3 and 2 respectively.  You could just as well have written:

    scale.begin(3, 2);

Each object has to be "begun", so you would need a begin for each object you instantiate:

    scale1.begin(3, 2); // DOUT = 3, CLK = 2
    scale2.begin(5, 4); // DOUT = 5, CLK = 4

Now for every operation that you did on `scale` you would instead do on your two new objects:

    scale1.set_scale(calibration_factor);
    scale2.set_scale(calibration_factor);

etc.

And when you want to take a measurement you just select which object to read from:

    Serial.print(scale1.get_units(), 1);

or

    Serial.print(scale2.get_units(), 1);

You can add a third by creating and using `scale3` in exactly the same way as `scale1` and `scale2`.


body: So i am using adafruit io and esp-now on an esp32 to recieve voice commands from the internet and sensor values from another esp32. Independently, they both work quite fast but together the esp-now recieving speed slows down greatly with more packets lost. Any reason for that?

title: Adafruit IO + Esp-Now

Answers: 0


body:
I will be wiring a switch to the Arduino that controls the voltage. When the I turn the switch it can adjust the voltage from 0 to 5. The overall task is to print the output voltage. The print is to be a multiplication table of the voltage.

I created this code:

    void setup()

    void loop(){

      int (n,i,j,result);

      printf("enter N Value");

      scanf ("%d", &n);

      for (i=1; i<=n; i++);

      {
        for (j=1; j<=n;j++);

        {
          result= (i*j);

          printf("%d", result);

        }
        printf("\n");

      }
      return 0;

    }

But i get the error exit status 1
expected initializer before 'void' when I try to verify it. what does it mean. How do you fix it?

title: I get an error saying, "exit status 1 expected initializer before 'void'."

Answers: 1

body:
Functions must have a body. So instead of:

    void setup()

You need:

    void setup()
      {
      // do nothing
      }

---

You have other issues, for example this is not C++:

      int (n,i,j,result);

That should be:

      int n,i,j,result;

Also you are returning 0, when void functions don't return a value.

Also, here:

      printf("enter N Value");

      scanf ("%d", &n);

Where is this value coming from? There isn't a keyboard on the Arduino.

See: [scanf](https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm)

> The C library function int scanf(const char *format, ...) reads formatted input from stdin.

The Arduino is a microprocessor. It doesn't have stdin.


body: I am experimenting the `write((byte)num)` function, and I stumble upon a pre-made custom character. Usually it's on above `((byte)200)` or and below `((byte)10000)`. If anyone else know this, where could I find the list for a specific character?

title: LCD Custom Character

Answers: 1

body:
Hi Welcome to Arduino StackExchange

You can build your own LCD characters if you spend some time with the datasheet and user manuals available

Arduino has a dedicated function **[here][1]**

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    byte smiley[8] = {
      B00000,
      B10001,
      B00000,
      B00000,
      B10001,
      B01110,
      B00000,
    };

    void setup() {
      lcd.createChar(0, smiley);
      lcd.begin(16, 2);
      lcd.write(byte(0));
    }

    void loop() {}

here is one **example**:  from our tool [here][2]

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

From the **[datasheet][4]**:
[![enter image description here][5]][5]

here is one example where a Heart symbol is created using the built-in Arduino LCD library:

You can play [here][6] at our LCD1602 simulator to get a hang of it.  Please leave a message or comment if you have any questions :)
[![enter image description here][7]][7]

  [1]: https://www.arduino.cc/en/Reference/LiquidCrystalCreateChar
  [2]: https://goodarduinocode.com/projects/electronic-safe
  [3]: https://i.stack.imgur.com/fr0nB.png
  [4]: https://www.sparkfun.com/datasheets/LCD/HD44780.pdf
  [5]: https://i.stack.imgur.com/t2G5f.png
  [6]: https://wokwi.com/playground/lcd1602-i2c
  [7]: https://i.stack.imgur.com/zWZFQ.png


body:
what is the maximum length for matrix can be used for matrix inversion on atmega32,for example,can we implement matrix inversion for 15x15 matrix on atmega32? And if  it can be done on atmega32..does this will make the atmega32 to be slower?
I want to implement kalamn filter 15 states for euler angles estimation...the data of the matrix will be floating point..

title: About maximum length of matrix can be use for matrix invertsion on atmega32

Answers: 1

body:
Floats in the Arduino IDE are normally 4 bytes. So you can work out with a calculator that your matrix will take at least 15 x 15 x 4 bytes (900 bytes). That is out of a total of 2048 bytes of RAM on the Atmega32.

That may seem to be enough RAM, but other things, like the libraries, will also take RAM. I did [an answer to a question about RAM](https://arduino.stackexchange.com/a/13210/10794) a while back. Even a very simple sketch (in this case) took 346 bytes.

Also, your library, or whatever-it-is you are using for matrix inversion, may require RAM for variables, etc.

My suggestion would be to make your code invert a very small matrix (eg. 1 x 1) and see how much RAM that uses. Then you can extrapolate out fairly simply to how much would be needed for a larger matrix.


body:
There is a library  [davetcc / IoAbstraction][1]. The only library working as expected with my rotary encoder. The problem that on rotation I can only see serial output with position data, but I cannot get these data as some variable value.

There is the swithch initialization and function definition in main.cpp
`switches.addSwitch(spinwheelClickPin, onSpinwheelClicked);`

    void onSpinwheelClicked(uint8_t pin, bool heldDown) {
      Serial.print("Button pressed ");
      Serial.println(heldDown ? "Held" : "Pressed");
    }

The definition from `SwitchInput.cpp`

    bool SwitchInput::addSwitch(pinid_t pin, KeyCallbackFn callback,uint8_t repeat, bool invertLogic) {
     if(internalAddSwitch(pin, invertLogic)) {
            KeyboardItem item(pin, callback, repeat, invertLogic);
            return keys.add(item);
        }

        return false;
    }

There is the callback function type definition from `SwitchInput.h`

    typedef void(*KeyCallbackFn)(pinid_t key, bool heldDown);

I canon just change void to bool. So how can I get this `heldDown` variable value?

Sorry if the question is stupid.

  [1]: https://github.com/davetcc/IoAbstraction

title: How to get variable from callback function?

Answers: 1

body:
Callback functions are usually `void` and don't return real data, because they are called by some type of event handling system, like the mentioned library. As this is calling the callback function, not you, it does not make much sense to return data from it. To get that return value, you would need to change the library for every bit of data, that you want. Thus return values of callback functions are either `void` or some message to the event handling system (for example to make the event system send down the event to the next possible handler).

But you can use global variables to get the data from the callback. Define a global variable for the value, that you want to extract, and inside the callback function set that variable. Then at other places in your code you can use that global variable.

The library, that you linked, seems to handle the event in the main code and not in interrupts. So you are safe to just use the global variables as you like.

Though to be complete: When interrupts are involved and you change global variables inside an interrupt service routine, you need to be very careful. Single byte variables are not problem, but with multi-byte variables you can get scrambled data, as the interrupt might occur in the middle of processing that variable. Then you need to introduce a critical section, where interrupts are disabled for a very short time.


body:
I bought a 9 DOF IMU from [AliExpress][1] (pictures below), asking because this seems to be somewhat of a common issue (and I'm a bleeding noob). I tried setting up this board using example codes from Adafruit - presuming this would work and it's a compatible board (and it just looked exactly the same). However, surprise - several errors.

 1. Using this [guide][2] I attempted to run the [pitchrollheading][3] example - it reports LSM303 not found. The wiring is according to this guide, A4 (SDA) and A5 (SCL) are connected, 5V in, Ground of IMU to Ground of Arduino (Arduino uno, like in the guide)
 2. Next I debugged the lines on the board using the multimeter: 5V on line in vs ground, 5V on the SDA/SDC lines (seemed fine)
 3. Then I debugged using the [i2cdetect][4] library, however it reported empty.

         0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
         00:          -- -- -- -- -- -- -- -- -- -- -- -- --
         10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
         20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
         30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
         40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
         50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
         60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
         70: -- -- -- -- -- -- -- --

 4. Using analog read I can get values that seem to change with board movement, that would confirm that - in theory - the board works.

Questions

 1. Making sense from debugging: What could be somre reasons the board not listed using the i2cdetect library (also tried a script)?
 2. Is there an easy way (or would you recommend spending time to investigate) to use the rawdata from the arduino's analog in lines to compute pitch,roll and heading?
 3. Would a project like this be typically orders of magnitude easier to set up with a raspberry pi (I have one setup and ready)? (more libraries?)
 4. Are IMU's usually easy to setup, and is it likely this would be easier with a more expensive IMU (e.g. [MPU9250/6500][5])?

Thank you in advance, and please remember: I'm a noob, I ask for your patience and advice.

[![enter image description here][6]][6]
[![enter image description here][7]][7]

  [1]: https://www.aliexpress.com/item/32903832768.html
  [2]: https://learn.adafruit.com/adafruit-9-dof-imu-breakout/software
  [3]: https://github.com/adafruit/Adafruit_9DOF/blob/master/examples/pitchrollheading/pitchrollheading.ino
  [4]: https://www.arduinolibraries.info/libraries/i2cdetect
  [5]: https://www.amazon.com/HiLetgo-Gyroscope-Acceleration-Accelerator-Magnetometer/dp/B01I1J0Z7Y
  [6]: https://i.stack.imgur.com/91nJt.jpg
  [7]: https://i.stack.imgur.com/wltVX.jpg

title: Setup/Debug affordable 9DOF IMU

Answers: 1

body: I re-soldered all connections and used new wires. Now the board is recognized by the i2cdetect library. Upon multimetering all connections using the continuous mode (*the one that looks like a loudspeaker*), I noticed my breadboard sometimes does not conduct properly. Cheap breadboards and/or cables are at fault here, as far as I can tell - a rookie mistake. I'm guessing the ground connection is the only one I have not measured before


body:
I'm using SoftwareSerial with a SIM808 GSM modulde to detect incoming SMS messages.
The problem I'm currently having is that I need to access the phone number from the received SMS so I can send a reply back to that number.

I'm trying to access the contents of the SoftwareSerial and print it to the serial monitor, just so I can see its contents but for some reason, nothing at all is being output. The "Message received" string is being output to the monitor, along with everything else that's needed. It's just the mySerial.read() that won't show.

How can I access the incoming SMS message and get the phone number from it?

Excuse the messy code. It's a work in progress.

     #include <SoftwareSerial.h>
     #include <ADSWeather.h>

    SoftwareSerial mySerial(9, 10);

    #define ANEMOMETER_PIN 2
    #define VANE_PIN 0
    #define RAIN_PIN 3

    #define CALC_INTERVAL 1000

    unsigned long nextCalc;
    unsigned long timer;

    int windDir;
    int windSpeed;
    int rainAmmount;
    const int switchpin =  7;

    ADSWeather ws1(RAIN_PIN, VANE_PIN, ANEMOMETER_PIN); //This should configure all pins correctly

    void setup()
    {
      pinMode(switchpin, OUTPUT);
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(ANEMOMETER_PIN), ws1.countAnemometer, FALLING); //ws1.countAnemometer is the ISR for the anemometer.
      nextCalc = millis() + CALC_INTERVAL;

      mySerial.begin(9600);   // Setting the baud rate of GSM Module
      delay(100);

      digitalWrite(switchpin, HIGH);
      delay(3000);
      digitalWrite(switchpin, LOW);
            RecieveMessage();
          Serial.write("SMS set to recieve messages");
    }

    void loop()
    {

      timer = millis();

      int rainAmmount;
      long windSpeed;
      long windDirection;
      int windGust;
      int sent;

      ws1.update(); //Call this every cycle in your main loop to update all the sensor values

      if(timer > nextCalc)
      {

        nextCalc = timer + CALC_INTERVAL;
        rainAmmount = ws1.getRain();
        windSpeed = ws1.getWindSpeed();
        windDirection = ws1.getWindDirection();
        windGust = ws1.getWindGust();

    //     windSpeed / 10 will give the interger component of the wind speed
    //     windSpeed % 10 will give the fractional component of the wind speed
        Serial.print("Wind speed: ");
        Serial.print(windSpeed);
        //Serial.print('.');
        //Serial.print(windSpeed % 10);
        //Serial.print(" ");

        Serial.print(" Gusting at: ");
        Serial.print(windGust);
        //Serial.print('.');
        //Serial.print(windGust % 10);
        Serial.println("");

      }

      //if (Serial.available()>0)
      //{
          //RecieveMessage();
         // Serial.write("SMS set to recieve messages");
      //}

    //  mySerial.flush();
     // serialFlush();

      //If an message comes in
     if (mySerial.available()>0){

      Serial.write("Message received");
      Serial.write(mySerial.read());

      String stringSMSMessage;
      stringSMSMessage = String("Wind speed near St. John's lock: ");
      stringSMSMessage += windSpeed;
      stringSMSMessage += "MPH";
      //stringSMSMessage += '.';
     // stringSMSMessage += windSpeed & 10;
      stringSMSMessage += " Gusting at: ";
      stringSMSMessage += windGust;
        stringSMSMessage += "MPH";
     // stringSMSMessage += '.';
      //stringSMSMessage += windGust % 10;
      stringSMSMessage += ' ';

      //Send the wind speed response.
        mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
      delay(1000);  // Delay of 1000 milli seconds or 1 second
      mySerial.println("AT+CMGS=\"07769218312\"\r"); // Replace x with mobile number
      delay(1000);
      mySerial.println(stringSMSMessage);// The SMS text you want to send
      delay(100);
       mySerial.println((char)26);// ASCII code of CTRL+Z
      delay(10000);
      mySerial.flush();
      serialFlush();

    }
    }

     void SendMessage()
    {
      mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
      delay(1000);  // Delay of 1000 milli seconds or 1 second
      mySerial.println("AT+CMGS=\"Phone Number Goes Here\"\r"); // Replace x with mobile number
      delay(1000);
      mySerial.println("I am SMS from GSM Module");// The SMS text you want to send
      delay(100);
       mySerial.println((char)26);// ASCII code of CTRL+Z
      delay(10000);
      mySerial.flush();
      serialFlush();

    }

     void RecieveMessage()
    {
      mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
      delay(1000);
     }

     void serialFlush(){
      while(mySerial.available()>0)  {
         mySerial.read();
        }
    }

title: How to access Software Serial contents/value and extract some details?

Answers: 0


body:
I am having some trouble using my gps (on Serial1) with my other sensors.

They both work great independently but when I use them in the same code, it's either the gps or the sensors that get to write on the Serial monitor.

For my gps I am using [TinyGPS++][1], but I have a feeling that's not what's causing this problem here.

To simplify the code I'll be replacing what the sensors are supposed to write with this:

```
Serial.println("Hello there");
```

Here is the code

```
  if (Serial1.available() > 0) {
    gps.encode(Serial1.read());
    if (gps.location.isUpdated()){
      Serial.println("Satellite Count:");
      Serial.println(gps.satellites.value());
      Serial.println("Latitude:");
      Serial.println(gps.location.lat(), 6);
      Serial.println("Longitude:");
      Serial.println(gps.location.lng(), 6);
      Serial.println("Speed KT:");
      Serial.println(gps.speed.knots());
      Serial.println("Altitude Feet:");
      Serial.println(gps.altitude.feet());
      Serial.println("");
    }
  }
  Serial.println("Hello there");
```

I get this

```
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there
Hello there

```

If the line is removed, I get this

```
Satellite Count:
5
Latitude:
xx.xxxxx
Longitude:
-xx.xxxxxx
Speed KT:
0.19
Altitude Feet:
331.69

```

  [1]: https://github.com/mikalhart/TinyGPSPlus
Thank you

title: printing data from gps on Serial1 and sensors into Serial

Answers: 1

body:
This looks like another case of serial spam.  I recommend changing to a frame-based approach and controlling that rate with checks to millis.

That limits the spam.  Alternative is to limit it outright to 1:

~~~
//a static global:
static int isaidHELLO = 0;

//later in the loop
if (Serial1.available() > 0) {
    gps.encode(Serial1.read());
    if (gps.location.isUpdated()){
      Serial.println("Satellite Count:");
      Serial.println(gps.satellites.value());
      Serial.println("Latitude:");
      Serial.println(gps.location.lat(), 6);
      Serial.println("Longitude:");
      Serial.println(gps.location.lng(), 6);
      Serial.println("Speed KT:");
      Serial.println(gps.speed.knots());
      Serial.println("Altitude Feet:");
      Serial.println(gps.altitude.feet());
      Serial.println("");
      isaidHELLO = 0;
    }
  }
  if(isaidHELLO == 0)
  {
      Serial.println("Hello there");
      isaidHELLO = 1;
  }

~~~


body:
I built a button box, everything is wired up and all of the push buttons work using the code below, but for some reason my rotary encoders are not working, well 3 out of the 4 are not working. Is there something in my code that I messed up? Should rotary encoders not be linked to analog pins? Any guidance would be appreciated.

EDIT - Correct code replacing incorrect code.

```#include <Keypad.h>
#include <Keyboard.h>
#include <SimpleRotary.h>

#define NUMROWS 6
#define NUMCOLS 4

const int ModPin = A0;
int ModState = 0;

//define the symbols on the buttons of the keypads
char buttons[NUMROWS][NUMCOLS] = {
  {'7','5','3','1'},
  {'6','4','2','0'},
  {'r','e','w','q'},
  {'i','u','y','t'},
  {'f','d','s','a'},
  {'p','j','h','g'},
};

char buttonsMod[NUMROWS][NUMCOLS] = {
  {'7','5','3','1'},
  {'6','4','2','0'},
  {0xC9,0xC7,0xC5,0xC3},
  {0xC8,0xC6,0xC4,0xC2},
  {'f','d','s','a'},
  {'p','j','h','g'},
};

byte rowPins[NUMROWS] = {13,12,11,10,9,8}; //connect to the row pinouts of the keypad
byte colPins[NUMCOLS] = {7,6,5,4}; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad
Keypad buttbx = Keypad( makeKeymap(buttons), rowPins, colPins, NUMROWS, NUMCOLS);
Keypad buttbxMod = Keypad( makeKeymap(buttonsMod), rowPins, colPins, NUMROWS, NUMCOLS);

SimpleRotary RotaryA(1,2,3);
SimpleRotary RotaryB(0,A5,3);
SimpleRotary RotaryC(A4,A3,3);
SimpleRotary RotaryD(A2,A1,3);

void setup() {
  Keyboard.begin();
  pinMode(ModPin, INPUT_PULLUP);
}

void loop() {
ModState = digitalRead(ModPin);
  if (ModState == HIGH) {
    CheckAllButtons();
  } else {
  CheckAllButtonsMod();
  }

byte i;

  // 0 = not turning, 1 = CW, 2 = CCW

  i = RotaryA.rotate();

  if ( i == 1 ) {
    Keyboard.press(KEY_LEFT_ARROW);
    delay(150);
    Keyboard.releaseAll();
  }
  if ( i == 2 ) {
    Keyboard.press(KEY_RIGHT_ARROW);
    delay(150);
    Keyboard.releaseAll();
  }

  i = RotaryB.rotate();

  if ( i == 1 ) {
    Keyboard.press(KEY_LEFT_ARROW);
    delay(150);
    Keyboard.releaseAll();
  }
  if ( i == 2 ) {
    Keyboard.press(KEY_RIGHT_ARROW);
    delay(150);
    Keyboard.releaseAll();
  }

  i = RotaryC.rotate();

  if ( i == 1 ) {
    Keyboard.press(KEY_LEFT_ARROW);
    delay(150);
    Keyboard.releaseAll();
  }
  if ( i == 2 ) {
    Keyboard.press(KEY_RIGHT_ARROW);
    delay(150);
    Keyboard.releaseAll();
  }

  i = RotaryD.rotate();

  if ( i == 1 ) {
    Keyboard.press(KEY_LEFT_ARROW);
    delay(150);
    Keyboard.releaseAll();
  }
  if ( i == 2 ) {
    Keyboard.press(KEY_RIGHT_ARROW);
    delay(150);
    Keyboard.releaseAll();
  }
}

void CheckAllButtons(void) {
  char key = buttbx.getKey();
  if (key != NO_KEY)  {
    Keyboard.press(key);
    delay(150);
    Keyboard.releaseAll();
  }//Keyboard.write(key);
}

void CheckAllButtonsMod(void) {
  char key = buttbxMod.getKey();
  if (key != NO_KEY)  {
    Keyboard.press(key);
    delay(150);
    Keyboard.releaseAll();
  }//Keyboard.write(key);
}
```

title: Help with code not working

Answers: 0


body:
Well I am trying make language page with Nextion display and Arduino Mega. If user enter the language page Nextion display is sending page name with this commend to Arduino for which is current page.

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

While page preinitializing moment.

    print "dil"

If user choice a language and then press the Next button, Nextion sending this comment to Arduino.

    if(r0.val==1)
    {
      va0.txt="en"
    }else if(r1.val==1)
    {
      va0.txt="tr"
    }else
    {
      va0.txt="de"
    }
    print va0.txt
    page 2

Everyting is normal until here. If user press back button at page 2 in a short time. Serial print not only send "tr" or "de" or "en" but also sending "dil" comment all together. Because of that ```Serial2.readString();``` commend return such as "trdil" or "endil" or "dedil". So that program not working properly. Just I want to receive language's 2 letter short code.

There is a comment which is useful if I send data Arduino to Nextion to understand last of the commend line.

      Serial2.write(0xff);
      Serial2.write(0xff);
      Serial2.write(0xff);

How can tell the Arduino there is a line break after sending "tr" or "en" or "de".

Assume that I am using simple Serial receiver commend.

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

    void loop() {
      if (Serial2.available() > 0)
      {
        String Received  = Serial2.readString();
        Serial.println(Received);
      }
    }

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

title: How to tell if there is a line break from Nextion display to Arduino at Serial

Answers: 0


body:
I have a Duinopeak shield that lets you plug on an ESP-01 and provides a 5V-3.3V regulator and level shifting for the Tx and Rx pins. I cannot get it to work with a setup that has worked with every ESP-01 or Wifi Shield I have used before.

Between the Arduino and the shield I connect Tx/Tx and Rx/Rx. I either load a blank sketch or jumper RST to ground on the Arduino. I use pins 0 and 1 through the shield. When I plug in the USB cable and type AT and "send". Nothing. No light blinks on the ESP sitting on the board. This is the board:

https://alexnld.com/product/duinopeak-esp8266-esp-01-wifi-expansion-board-shield-without-esp8266-module-for-arduino/

I know the ESP and the board works, because if I connect it to a Mega and use Seria1 instead of the main serial(0), rewire Tx/Rx and Rx/Tx, and upload a sketch to echo the USB Serial to Serial1 and back, using Serial Monitor, I can send AT commands and see responses. But when connected to pins 0 and 1, it acts like it isn't connected.

What I have tried:
- Tried an Uno and Mega
- Tried removing the plastic jumpers and running wires from the rows of Rx and Tx pins to the header directly
- Tried different pins on the row (there are 8 Tx pins and 8 Rx pins so you can jumper to D0-D7)
- Tested the continuity of each pin with a meter

I thought it must be the level shifter, but then why would it work when using Serial1? I thought the pins might have a cold solder joint, but then I used jumper wires from the pins in both tests and the same pins work (in reverse) when I connect them to Serial1 on the Mega. I thought it might be because of the 2 resistors on the USB path to pins 0 and 1 on an Arduino, but they prefer the pins over the USB. And why would another very similar board work? Tracing and finding an identical looking board shows this schematic. Odd thing is this is identical to a different board that works
:

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

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

title: Help using an Arduino as as an FTDI with a ESP8266 carrier shield to see an AT response

Answers: 0


body:
I have an ESP8266 which I wish to place in deep sleep until a reed switch senses a door being opened. The ESP8266 is woken from deep sleep by briefly raising the RESET pin high.

In my original design, I thought that raising the RESET pin would wake the device instantly. Instead raising the pin holds the device in a reset state until it goes low again. This means that the 8266 currently wakes after the door is opened and closed again.

I'm looking for a way to briefly trigger the RESET pin after the reed switch connection is broken with minimal additional hardware, and minimal power drain while in deep sleep. I can use either NC or NO Reed switches.

Any suggestions?

title: Trigger ESP8266 reset pin on broken connection

Answers: 0


body:
How can I stop the loop when I enroll a fingerprint to the module?

The loop is stuck in enrolling fingerprint even it was already done. The result I want was after the enrollment of fingerprint, it will exit the loop of enrollment and start the default switch command. Thank you in advance.

Here is my loop code.

        void loop() {
    //
        if (Serial.available() > 0) {
          // read the incoming byte:
          command = Serial.read();

          // say what you got:
          Serial.print("I received: ");
          Serial.println(command);
        }
        switch (command) {
        case 'A':
        {
          Serial.println("Ready to enroll a fingerprint!");
          Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");
          id = readnumber();
          if (id == 0) {// ID #0 not allowed, try again!
             return;
          }
          Serial.print("Enrolling ID #");
          Serial.println(id);

          while (!  getFingerprintEnroll() );
        }
          break;
        case 'B':
        {
          Serial.println("Case 2");
        }
          break;
        default:
        {
            getFingerprintDoorLoob();
            delay(50);
        }
          break;
      }
    }

Here is the enroll fingerprint code:

     uint8_t getFingerprintEnroll() {

      int p = -1;
      Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
      while (p != FINGERPRINT_OK) {
        p = finger1.getImage();
        switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
          Serial.println(".");
          break;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          break;
        case FINGERPRINT_IMAGEFAIL:
          Serial.println("Imaging error");
          break;
        default:
          Serial.println("Unknown error");
          break;
        }
      }

      // OK success!

      p = finger1.image2Tz(1);
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      Serial.println("Remove finger");
      delay(2000);
      p = 0;
      while (p != FINGERPRINT_NOFINGER) {
        p = finger1.getImage();
      }
      Serial.print("ID "); Serial.println(id);
      p = -1;
      Serial.println("Place same finger again");
      while (p != FINGERPRINT_OK) {
        p = finger1.getImage();
        switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
          Serial.print(".");
          break;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          break;
        case FINGERPRINT_IMAGEFAIL:
          Serial.println("Imaging error");
          break;
        default:
          Serial.println("Unknown error");
          break;
        }
      }

      // OK success!

      p = finger1.image2Tz(2);
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      // OK converted!
      Serial.print("Creating model for #");  Serial.println(id);

      p = finger1.createModel();
      if (p == FINGERPRINT_OK) {
        Serial.println("Prints matched!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_ENROLLMISMATCH) {
        Serial.println("Fingerprints did not match");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }

      Serial.print("ID "); Serial.println(id);
      p = finger1.storeModel(id);
      if (p == FINGERPRINT_OK) {
        Serial.println("Stored!");

      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_BADLOCATION) {
        Serial.println("Could not store in that location");
        return p;
      } else if (p == FINGERPRINT_FLASHERR) {
        Serial.println("Error writing to flash");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }
    }

This was the current result, what I expect was after it was stored the loop will break. please help thank you
[![enter image description here][1]][1]

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

title: Arduino fingerprint Scanner stop loop after enroll or delete

Answers: 1

body:
I see the problem here. Now observe the

`if(Serial.available>0)`

`{`

`//Block of Statements`

`}`

Your closing bracket for **that** if statement must be after the `switch()` statement.

For every iteration (`void loop()`) your `command` variable runs your switch and calls the enrolling function.

So it should be:

`if (Serial.available>0){`

`//Block of statements`

`Switch(command){`

`//Block of statements}`

`}`

`}`

Hope this helped


body:
I have recovered an old sketch (2 years ago) in which I used 2 DHT22 sensors and sent the values to an web app to store in database. The sketch works fine with a ES8266 module connected to an arduino uno. In my new project I am trying to do the same action, but sending GPS coordinates obtained with GPS NEO-6m module.

I have write a function that returns a string with the parameters as lat, lng, altitude, and others.

```
void loop(){
  gps_data = get_gps_data();

  // all code for wifi client sending
  ..........
  client.print("GET /reads/store?"+gps_data);
  .......
  .......
}
String get_gps_data(){
  // GPS capture function
  ...........
}
```
The function takes 5 second in get GPS information but I always get....
TIMEOUT>>>
Disconecting 3
and none call arrives to to web server
but if I change (for example..)
```
gps_data = "gps=1&lat=36.125471&lng=-4.478658.....";
```

the system works fine and send continuously the data, and if I put a delay before and after the gps the system works. If I take a value from DHT22, the code works too, but with the GPS the URL is not sent to the server.

Any idea?

Thank you in advance...

title: ESP8266 WiFiEspClient Disconnect 3 with GPS

Answers: 0


body:
I'm fairly new to working and programming with arduinos. The project I am working on is a digital clock which uses a string of ```WS2812``` leds to light up the correct numbers. Each digit consists of 7 leds and there are two 'colon' leds between the second and third digits. I am using the ```FastLED``` library to try to program the code. I am able to make the leds light up such that all four digits are the same number (four consecutive 5's). However, the second I try to have it display multiple different numbers, everything goes south quickly. Here are some pictures of my current results:

[![55:55. I can create this with any number 0-9.][1]][1]

55:55. I can create this with any number 0-9.

[![Should be 12:34.][2]][2]

Should be 12:34.

Here is the code that I'm working with so far:

```#include <FastLED.h>
#include <RTClib.h>

RTC_DS3231 rtc;
DateTime now;

#define NUM_LEDS 30
#define LED_PIN 6

CRGB leds[NUM_LEDS];

void setup() {
  // put your setup code here, to run once:

  Serial.begin(57600);

  FastLED.addLeds<WS2812, LED_PIN>(leds, NUM_LEDS);

  FastLED.clear();
}

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

  const int ZERO[]={0,1,2,4,5,6};
  const int ONE[]={2,6};
  const int TWO[]={0,1,3,5,6};
  const int THREE[]={1,2,3,5,6};
  const int FOUR[]={2,3,4,6};
  const int FIVE[]={1,2,3,4,5};
  const int SIX[]={0,1,2,3,4,5};
  const int SEVEN[]={2,5,6};
  const int EIGHT[]={0,1,2,3,4,5,6};
  const int NINE[]={2,3,4,5,6};

  for(int i=0; i<sizeof(ONE);i++){
        leds[ONE[i]]=CRGB::Red;
        FastLED.show();
      }

  for(int i=0; i<sizeof(TWO);i++){
        leds[TWO[i]+7]=CRGB::Red;
        FastLED.show();
     }

  for(int i=0; i<sizeof(THREE);i++){
        leds[THREE[i]+16]=CRGB::Red;
        FastLED.show();
      }

  for(int i=0; i<sizeof(FOUR);i++){
        leds[FOUR[i]+23]=CRGB::Red;
        FastLED.show();
      }
```

Can anyone explain what's going wrong? Any help would be greatly appreciated. Let me know if you need clarification!

  [1]: https://i.stack.imgur.com/6nmFx.jpg
  [2]: https://i.stack.imgur.com/WLIHZ.jpg

title: FastLED not performing as expected

Answers: 1

body:
Your problem is your usage of `sizeof()`. It doesn't do what you think it does.

`sizeof()` gives you the *amount of memory* a variable takes up. It does *not* give you the number of elements in an array.

For example:

    const int ONE[]={2,6};

`sizeof(ONE)` will not give you 2. It will give you 4. An `int` is two bytes in size (16 bits). An array of 2 ints is, therefore, 2x2 = 4 bytes.

So when you're iterating over a 2 byte array but counting 0-3 you're overflowing your array and reading from the next bits of memory - which happen to be the first two entries of the `TWO` array in this case.

To get the number of entries in an array you must divide the `sizeof()` by the size of the variable type the array is made up of.  The most common way of doing that is:

    sizeof(ONE) / sizeof(ONE[0])

It's common to set up some macros at the time of array creation so you can easily refer to it later:

```
const int ONE[]={2,6};
#define ONE_SIZE (sizeof(ONE) / sizeof(ONE[0]))
```

You should also consider using an array of `byte` (or better, the standard `uint8_t`) where the size of one element will be 1 not 2, since you don't need to store any number > 255. It's still good to do the division of the `sizeof()` even with a 1 byte size in case you should ever need to change the variable type in the future. It's also a good habit to get into.