message:
How do I know when a filter coffee machine is finished by using any sensor?

I have a filter coffee machine that looks like [this one][1] and I would like to send a message to the machine users by using any development board (like Arduino or NodeMcu) when the machine is finished.

I haven't found a way to detect when the machine is finished. (I also don't want to do any physical change on the machine, like adding any cable or opening in the machine. I can use any sensor or so on.)

How can I do that? Any advice?

  [1]: https://www.electrolux.com.tr/kitchen/small-kitchen-appliances/coffee-makers/coffee-maker/ekf5300/

body:
Just two ideas, both non-invasive:

The machine moves water from the reservoir at the back to the coffeepot at the front of the machine, so its weight distribution will change while making coffee.

If you put a thin pressure pad (like [this one][1], or something similar) under the whole machine at the back you should see the pressure at that point become smaller while coffee is being made.

If the effect isn't pronounced enough, you could make the whole machine tilt forward while making coffee by putting a narrow and thin strip of plastic under its centre from left to right so it can swivel forward and back just a little depending on the location of the bulk of the water.

If the pressure on the pressure pad at the back stops dropping, the coffee is ready. You can also detect when the coffee can is empty again this way, or maybe even how many cups of coffee are still available in the coffee can.

Or maybe you could detect with a contact microphone when the machine goes silent, assuming it makes sufficient noise when making coffee. Mine does.

  [1]: https://wiki.seeedstudio.com/Grove-Round_Force_Sensor_FSR402/


sender: user

sender: assistant

body: If the machine has a Brewing- or a Done Brewing LED, a light sensor can detect this without no changes or connections to the machine. This would also have the advantage of working for a short or full pot.


message:
How to power board plus module with one battery pack

I'm someone who's very new to robotics and the physical side of computers (software guy) so apologies if this is a stupid question. I'm purchasing an Arduino Nano 33 IoT that I'll be using in conjunction with an Adafruit FONA 3G Cellular Breakout (https://www.adafruit.com/product/2687). I'd like to be able to power the entire unit off of one battery pack but my problem is that both the Arduino and the Adafruit 3G unit have separate power inputs. Adafruit's website says that a Lipoly battery is required to run the unit. Is there any way to "pass through" or "split" power between the two units? This way I was thinking I could run everything off of one external battery pack. Optimally I don't have to use a Lipoly battery and I could use a large external battery pack connected to jumpers or a barrel jack.

body:
you can use a breadboard and jumper cable. connect the VCC and GND of battery to a breadboard, do this for your Arduino and sim card module too. just remember they should be in a one row. GND with GND row, and VCC with VCC row
note: this way is okay just for debugging


message:
Some code only works when USB serial port connected

I'm using Arduino Uno as my microcontroller, but I got a strange behavior. I need to run several function at the same time. One to get GPS and temperature value then send every value to user's phone number when a request received by SIM800L GSM module, and another to display those value on I2C LCD. Everything works fine when my USB port connected to my computer. But when I tried to unplug the USB and using external power source from Li-Po battery I can't get a response from SIM800L module whenever I send a request message.

When I tried to create a separate program (just received a request message and then sent a response by SIM800L) it works fine even though using external power supply (Li-Po battery) without USB port plugged in. Another strange behavior is when I was using both of Li-Po battery and USB port connected then unplugged the USB port it works fine again. But when I unplugged my battery and then plugged it again without USB port connected, SIM800L couldn't send a response. What is wrong ?

This is my full code:
```

#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include <LiquidCrystal_I2C.h>
#include <SoftwareSerial.h>
#include "DHT.h"

//sms
char ReceivedSms;
short DHT_OK=-1, GPS_OK=-1;
String DataSms;
int _timeout;
String _buffer;
String number = "+62811XXXXXX";

//dht
#define DHTPIN 5
#define DHTTYPE DHT11

LiquidCrystal_I2C lcd(0x27,20,4);
SoftwareSerial sim800l(2,3);
DHT dht(DHTPIN, DHTTYPE);

// The TinyGPS++ object
TinyGPSPlus gps;

void setup()
{
  Serial.begin(9600);
  sim800l.begin(9600);
  dht.begin();
  lcd.init();                      // initialize the lcd
  // Print a message to the LCD.
  lcd.backlight();
  _buffer.reserve(50);
  ReceiveMode();
}

void loop()
{
   displayInfo();

}

void displayInfo()
{
  String RSMS;

  while(sim800l.available() > 0) {
      ReceivedSms = sim800l.read();
      RSMS.concat(ReceivedSms);
      GPS_OK = RSMS.indexOf("All");
   }

  if (gps.location.isValid())
  {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Latitude  : ");
    lcd.println(gps.location.lat(), 6);
    lcd.setCursor(0,1);
    lcd.print("Longitude : ");
    lcd.println(gps.location.lng(), 6);
    delay(5000);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Suhu       : ");
    lcd.println(dht.readTemperature());
    lcd.setCursor(0,1);
    lcd.print("Kelembaban : ");
    lcd.println(dht.readHumidity());
    delay(2000);

    if(GPS_OK!=-1)
        {
        String link = "http://www.google.com/maps/place/" + String(gps.location.lat(),6) + "," + String(gps.location.lng(),6);
        DataSms = "ALL\nSuhu = "+String(dht.readTemperature(),1)+" C"+" \nKelembaban ="+String(dht.readHumidity(),1)+" %"+" \nMaps = "+link;
        SendMessage();
        ReceiveMode();
        GPS_OK = -1;
        }
  }
  else
  {

    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("GPS not found");
    delay(2000);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Suhu      :");
    lcd.println(dht.readTemperature());
    lcd.setCursor(0,1);
    lcd.print("Kelembaban:");
    lcd.println(dht.readHumidity());
    delay(2000);

    if(GPS_OK!=-1)
       {
        DataSms = "ALL\nSuhu = "+String(dht.readTemperature(),1)+" C"+" \nKelembaban ="+String(dht.readHumidity(),1)+" %"+" \nMaps = Lokasi Tidak Ditemukan";
        SendMessage();
        ReceiveMode();
        GPS_OK = -1;
       }
  }

}

String _readSerial() {
  _timeout = 0;
  while  (!sim800l.available() && _timeout < 12000  )
  {
    delay(13);
    _timeout++;
  }
  if (sim800l.available()) {
    return sim800l.readString();
  }
}

void ReceiveMode() {
  sim800l.println("AT");
  delay(100);
  sim800l.println("AT+CMGF=1");
  delay(100);
  sim800l.println("AT+CNMI=2,2,0,0,0");
  delay(100);
}

void SendMessage()
{
  //Serial.println ("Sending Message");
  sim800l.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);
  //Serial.println ("Set SMS Number");
  sim800l.println("AT+CMGS=\"" + number + "\"\r"); //Mobile phone number to send message
  delay(1000);
  String SMS = "Hello from 800L...";
  sim800l.println(DataSms);
  delay(100);
  sim800l.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  _buffer = _readSerial();
}
```
Just for your information I'm using Li-Po battery 7.4V 2200mAh

body: I have solved my problem by click on Arduino reset button pin after all of my components got a power supply. Somehow I can't explain why does it work after doing that simple thing


message:
DC motor fan speed control with Temperature Sensor

I used this circuit schematic for the project however, when DC Motor starts to work, temperature value is increasing abnormally high. How can I solve this problem? It shows abnormal high values like 70, 85 ,101 etc.

  [![Schematic][1]][1]

    #define TEMPERATURE A0
    #define fan 3
    void setup(){
    Serial.begin(9600);
    pinMode(fan, OUTPUT);
    }

    void loop(){
    float temp = analogRead(TEMPERATURE);    //Read the analog pin
    temp = temp * 0.48828125;   // convert output (mv) to readable celcius

    Serial.print(temp);
    //print the temperature status
    Serial.print('\n');
    delay(1000);

     if (temp<=24){
      analogWrite(fan, 51);

      delay(1000);

    }
    else if (temp<=26 && temp>24){
      analogWrite(fan,122);

      delay(1000);

    }
     else if (temp<=30 && temp>26){
      analogWrite(fan,223);

      delay(1000);

    }
    else if (temp>30){
      analogWrite(fan,255);

      delay(2000);

    }
    }

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

body:
I am assuming that whatever temperature you are measuring is not rising when the motor is on.

I see that you are sharing the power/ground between your temperature sensor IC and the motor.  Motors are extremely noisy from an electrical viewpoint and it's almost certainly causing your temperature sensor to malfunction.

It would be best to separate the temp sensor power/ground connections from the motor power/ground connections completely.  Power the motor from an external supply instead of sourcing it from the Arduino.

Another thing that might help is to add some bypass capacitors as close as possible to the motor and to the temperature IC across the Vcc and GND lines.  This will help to smooth out the power in spite of the noise that the motor itself generates.  Generally you want at least one of two types, an electrolytic capacitor and a ceramic capacitor.  These are both inexpensive if you don't already have some on hand.  I'll suggest a 10 uF electrolytic and a 0.1 uF ceramic capacitor near both the motor and the temp sensor.


body:
Besides all the good advice from jwh20, you should start with a general strategy to find out where the problem lies.  You should hang a DVM directly between the sensor output and ground and see if the voltage also shows the rising problem.  If not, the trouble is in your code.

A drifting value is often due a wiring issue, like a bad sensor ground.  It wouldn't hurt to go over all the wiring very carefully.


message:
I2C protocol doesn't work properly

I am trying to make I2C Communication between NodeMCU and arduino Uno boards. However it is not working properly. It makes communication for once time when i uploaded code.

**Master Device Code(NodeMCU 1.0)**

    #include <ArduinoJson.h>
    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>
    #include <Wire.h>

    HTTPClient client;

    StaticJsonDocument <200> doc;

    const char* ssid = "MY_SSID";
    const char* pass = "MY_PASSWORD";

    void setup() {
      Serial.begin(9600);
      Wire.begin(D1,D2);
      WiFi.begin(ssid,pass);
      while(WiFi.status() != WL_CONNECTED) {;}
    }

    void loop() {

      const char* cd = getCode();
      if(cd==nullptr) {
        Serial.println("Problem Occurred.");
        delay(10000);
        return;
      }
      //Bad code is starting...
      //Basically, sending 24 bytes of data for a Wire Transmission

      int n = strlen(cd);
      int rem = n$; //remainder
      int quo = (n-rem)/24; //quotient

      while(quo!=0) {
        char sel[24];

        for(int i =0;i<24;i++) {
          sel[i] = cd[((((n-rem)/24)-quo)*24)+i];
        }

        Wire.beginTransmission(8);
        Wire.write(sel);
        Wire.endTransmission();
        quo-=1;
      }

      char sel[rem];

      for(int i =0;i<rem;i++) {
        sel[i] = cd[n-rem+i];
      }

      if(rem>0) {
         Wire.beginTransmission(8);
         Wire.write(sel);
         Wire.endTransmission();
      }
      //Bad code finished!

      //this is also not working.
      Wire.requestFrom(8,3);

      while(Wire.available()) {
        char c = Wire.read();
        Serial.print(c);
      }

      delay(15000);
    }

    //get code from server.
    const char* getCode() {
      client.begin("http://...");

      int res = client.GET();

      if(res<0) {
        return 0;
      }

      String root = client.getString();
      deserializeJson(doc,root);
      const char* code = doc["Liste"][0]["code"];
      return code;
    }

**Slave Device Code(Arduino Uno)**

    #include <Wire.h>

    void setup() {
      Serial.begin(9600);
      Wire.begin(8);
      Wire.onReceive(received);
      Wire.onRequest(requested);
    }

    void loop() {delay(200);}

    void received(int bytes) {

      while (Wire.available()) {
        char c = Wire.read();
        Serial.print(c);
      }

    }

    void requested() {
      Wire.write("abc");
    }

**Circuit:**

D1-SDA

D2-SCL

GND-GND

body:
You may need to do some additional research. I'm debugging some I2C problems myself at the moment. Happy to share what my research has turned up:

**Guiding Ideas - What could break?**

1. *Physical Layer*
 1. Unintentionally switched connections (SDA<>SCL)
 2. Incorrect Pins selected on Microcontroller
 3. Pull-up Resistors
  1. Too many
   - Devices often have pull-ups installed by default. Only one set is needed per bus. Rule of parallel resistors applies to calculate effective resistance.
  2. Too big (too high resistance)
  3. Too small (too low resistance)
 4. Voltage Conversion / Mismatched  devices
 5. Spikes or noise on SDA, SCL or Vcc
 6. Parasitic Capacitance
  1. wire / trace design
  2. bus too long

2. *Protocol Layer*
 1. Bus Addresses incorrect / collisions
 2. No ACK received from slave  (ref. TI article "Troubleshooting I2C Bus Protocol" below)
  1. Timing
  2. Missing / Unexpected SCL pulses
  3. Incomplete 8 bit block
  4. Missing Bytes
  5. False slave address
  6. Unsuccessful address change
 3. NACK signal meaning ambiguity
 4. Clock speed mismatch (should be running at the speed of the slowest slave on the bus)
 5. Blocked bus (i.e., a device has reset or dropped during transmission putting the bus into an invalid state. There is no timeout.)
 6. Multimastering (too many masters on bus?) - if more than one all must support multi-master mode
 7. Clock stretching (a slave is holding the clock low)
 8. What part of the message is missing? Is the initial ACK from the slave received?

3. *Code Layer*
 1. For boards with multiple I2C ports, correctly passing the desired port to the relevant library.
 2. Use of interrupts causing timing problems
 3. Use of blocking code structures causing timing problems

**Testing Methods**

- Bus Pinging / Bus Scan (like Arduino Multi-speed scanner https://forum.arduino.cc/index.php?topic=197360)
- Connect additional devices to the bus and see which combinations work to identify the failing item
- Multimeter checks
 - Stable Vcc?
 - Common Ground?
 - ([Open Drain][1]) pull-up resistance from SDA & SCL to Vcc
- Test devices like [Bus Pirate][2]
- Oscilloscope Analysis / Decode (references below)
- Sifting out which device is causing the problem. (See Hackaday article) Put different-value resistors on the output of all chips on the bus. The low voltage values will be slightly different for each chip, allowing you to see on a scope which chip is talking at any given time, and diagnose when they’re talking over each other.
- install I2C multiplexor to seperate bus into a single connector for each device (i.e., from bus to star topology) (e.g., PCA9544A)

**References**

*I2C General*

 - For Arduino [Programming Arduino Next Steps][3] - Going Further with
   Sketches Chapter 7
 - For ESP32
   https://randomnerdtutorials.com/esp32-i2c-communication-arduino-ide/

*I2C Debug Advice*

 - I2C Primer (I2C-bus.org) - a good reference for everything discussed here https://www.i2c-bus.org/i2c-primer/
 * Common Problems https://www.i2c-bus.org/i2c-primer/common-problems/
 * Obscure Problems https://www.i2c-bus.org/i2c-primer/obscure-problems/ Analysing Obscure Problems https://www.i2c-bus.org/i2c-primer/analysing-obscure-problems/
- WHAT COULD GO WRONG? I2C EDITION (Hackaday) https://hackaday.com/2016/07/19/what-could-go-wrong-i2c-edition/
- How to design and debug a custom I2C master-slave system? (Stack Exchange) https://arduino.stackexchange.com/questions/22898/how-to-design-and-debug-a-custom-i2c-master-slave-system
- Troubleshooting I2C Bus Protocol  https://www.ti.com/lit/an/scaa106/scaa106.pdf

*Oscilloscope Analysis of I2C*

- How to debug I2C through waveform analysis (Texas Instruments) https://www.ti.com/lit/an/slyt770/slyt770.pdf
- Using an oscilloscope to debug the I2C protocol https://www.electronicproducts.com/using-an-oscilloscope-to-debug-the-i2c-protocol/

  [1]: https://forum.digikey.com/t/what-does-open-drain-mean/716
  [2]: http://dangerousprototypes.com/docs/Bus_Pirate
  [3]: https://www.amazon.com.au/Programming-Arduino-Next-Steps-Sketches/dp/0071830251


body:
A few of my tips:

 1. if Arduino is powered using VIN port, the battery must STRICTLY between 7 to 12 volts, otherwise the Arduino board is unstable. Serial communication typically require good board stability
 2. A capacitor (100 to 500uF) across the 5V (or 3.3V) and GND port helps to give I2C device a consistent voltage level, which is essential


message:
Sync issue with signals

```

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "digitalWriteFast.h"

#define BUTTONPIN 2
#define FDCSPIN 6
#define CIPIN 5
#define SPEAKERPIN 4

float RPM=1000.0;
int PWus=1.5*1000.0;
int FDCSoffset=(1000.0/RPM/60.0/4.0) - (PWus/1000.0);
int CiCnt;
int totalCnt;
int CIState=B01100000;
bool Buttonstate=0;
LiquidCrystal_I2C lcd(0x27, 20, 4);

void setup()
{
  Serial.begin(9600);
  lcd.begin();
  lcd.backlight();
  lcd.clear();
  lcd.print("READY TO TEST"); // Waiting for button press
  pinMode(BUTTONPIN, INPUT);// Setting button as Input
  pinMode(FDCSPIN, OUTPUT); // Fuel Delivery Control Signal
  pinMode(CIPIN, OUTPUT); // Cylinder Identification
  digitalWriteFast(FDCSPIN, LOW);
  digitalWriteFast(CIPIN, LOW);
}

void loop()
{
 Buttonstate=digitalReadFast(BUTTONPIN);
 if(Buttonstate==1)
 {
  delay(5);
  if(Buttonstate==1)
  {
    runInjectorTest();
  }
 }
}
void runInjectorTest()
{
  lcd.print("Test Run");
  playtesttone();

    for(totalCnt=0;totalCnt<8000;totalCnt++)
    {

      PORTD=CIState;
      delayMicroseconds(FDCSoffset);
      PORTD=PORTD^B01000000;
      delayMicroseconds(PWus);
      if(totalCnt%4==0)
      {
        CIState=CIState^B00100000;
      }
    }
  totalCnt=0;
  playfinishtone();
}
void playtesttone()
{
  tone(SPEAKERPIN, 500, 500);
  delay(700);
  tone(SPEAKERPIN, 500, 500);
  delay(700);
  tone(SPEAKERPIN, 500, 500);
  delay(700);
  tone(SPEAKERPIN, 2000, 500);
}
void playfinishtone()
{

  tone(SPEAKERPIN, 2000, 500);
  delay(700);
  tone(SPEAKERPIN, 2000, 500);
  delay(700);
  tone(SPEAKERPIN, 2000, 500);
  delay(700);
  tone(SPEAKERPIN, 500, 500);

}
```

I am using this code to generate 2 signals, called CI and FDCS. CI stays on until the 5th FDCS pulse. I checked the output which is connected to a driver using the scope and I got this.[![The signal][1]][1]
The rising edge and falling edge of the longer signal (CI, dark green) are supposed to sync with the rising edge of the FDCS signal (Lime green),but they are inline with the falling edge. Note that the output is inverted (when compared to the code) hence the signal generated by the Arduino pins is according to the code.

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

body:
I did not tried it out. But something like this might help to synchronize the inverted signals to the rising edge of the high frequent signal.

I removed the FDCSoffset delay, because it is negative according to the variables at the top.

    // initialize CIState with 00
    int CIState=B00000000;

    // lines not shown .....

    for( totalCnt=0; totalCnt<8000; totalCnt++ )
    {
      CIState=CIState^B01000000;
      if(totalCnt%4==0)
      {
        CIState=CIState^B00100000;
      }
      // both signals are set at the same time
      PORTD=CIState;
      delayMicroseconds(PWus);
    }


message:
i am not able to figure out the problem due to which i can't upload my sketch to nano

this is the error code (it is new from the previous time i posted)

i am using the hourly build for this and not the Beta

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x6e

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x6e

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x6e

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x6e

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x6e

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x6e

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x6e

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x6e

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x6e

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x6e

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

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

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

body: I am just taking a guess as I operate on Linux. I would suggest go to tools menu and see if the correct board is selected. I would venture to guess it is not set for nano. Mine gives me two choices new and old. Try one and if it does not work try the other. Be sure your Baud is set correctly.


body: Another idea - try using Windows Filemanager to navigate down through the folder path shown in the error message and see if the avrdude.conf file exists in the specified place. this probably will not solve your problem but it might help to understand what is happening. Good luck - Bob


message:
Analog input voltage rises when motor is working

I'm making automatic water plant system. I'm using:

Arduino Uno

3.3-6V water pump -https://www.amazon.com/Vipe-Micro-Submersible-Motor-Water/dp/B01N0X3CW4

Capacitive soil moisture sensor - https://www.amazon.com/Gikfun-Capacitive-Corrosion-Resistant-Detection/dp/B07H3P1NRM

I've noticed that when motor turns on sensor readings are much higher. First I thought that the problem is in sensor, but when I measured sensor output in both cases (when motor is on and when motor is off) there was no difference, voltage was the same. Then I measured voltage in analog pin A0 that I used, and I saw there is increase in voltage when pump is on (+0.4V), so my guess is that this voltage is added to  sensor output voltage which is giving me higher values in my serial monitor.

For powering my pump I'm using same circuit as in this example:
https://www.devacron.com/arduino-tip120-control-dc-motor/

Just except potentiometer there is my sensor, powered via 3.3V Arduino pin (its GND is connected to Arduino GND). I also tried connecting all grounds together in one point, didn't help. I powered Arduino with usb and with 9V supply, in both cases same problem. Tried powering pump and Arduino with same and with different power supplies, no luck either.

I should also add that there is no change in AREF and 5V pin when pump is working. 4.97V in both cases.

Does anyone have any idea what can be the problem and how to solve it?

Here is how I wired everything:
https://i.stack.imgur.com/8IDQR.jpg

I also tried with 0.1uF ceramic and 10nF electrolytic capacitors. as suggested, wiring it like this: https://i.stack.imgur.com/fNQnX.jpg
Didn't make much difference, problem is still there.

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

[![Bypass Caps][1]][1]

I suggest two in each spot, one a 0.1uF (or similar) ceramic dipped or disc and the other a 1 or 10uF electrolytic.  Keep the polarity in mind for the electrolytic.

Oh, and another thing.  Be sure your motor is not pulling your power supply voltage down.  It's possible your phone charger supply is inadequate to supply the power needs of the motor.  Use a voltmeter across the input to the Arduino and check the voltage when the motor runs.  If it's dropping much below 5V you need a better power supply.  Well, I see now that you are only powering the motor from that 5V supply.  So that's probably not it.

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


message:
What is the best way to init wifi communication between two devices (get IP address)?

what is the best way to init wifi communication between two devices without knowing IP of second device, let's say Raspberry Pi and ESP8266?

I want to build simple home automation system for my purpose. There will be Raspberry Pi, as heart of system and ESP8266 as controlled devices. What is best way to get them communicate? I think, the hardest think is how to get their IP address. Then it will be easy to communicate via sockets.

In next text, by RPi I mean Raspberry Pi and program in RPi will be in python (but using call of terminal commands when needed).

My idea is this: On ESP8266 will be running program, which will create WiFi Acces Point at start (on first run in network). Name (SSID) of that AP will be specific (let's say starting with ESP-AUTOMATION prefix), so Raspberry Pi will know, when new ESP device will be turned on (Raspberry Pi will repeatedly search for accesible networks). When new ESP appear, RPi will save own IP to variable and connect to newly searched network (let's say ESP-AUTOMATION-abcd). Then will RPi send to AP (ESP) it's (RPi's) IP address and local network SSID and password. Then it will disconnect, and connect back to local network (and gain it's "old" IP, which it previously saved to variable). Then ESP connect to local network with static IP and after succesfull connect, it will send to RPi it's IP address via socket (because IP addr of RPi it will already known, because RPi have send it when it served as AP). Then RPi will save that IP address. And because IP addresses (of RPi and also ESP) will be configured as static, it shouldn't change over time.

Is this good idea? Or is something of that unreal (I am at beginning of that all)?

PS: I really want completely autonomous system, so for me is not solution something like connect ESP to PC and print it's IP to serial and then it write to RPi...

Thanks for every advice/opinion.

body:
One is a server and the other is a client.
The server do not need to know IP of the client, but the client need to know IP address of the server. See more in [communication between two Arduino][1]

  [1]: https://arduinogetstarted.com/tutorials/communication-between-two-arduino


message:
How to move a servo quickly and without delay function

Im trying to move a servo from one place to another while using the typical `for` loop you find in the servo's library example:

```c++
int lightON = 180;
int lightOFF = 90;

for (pos1 = lightOFF; pos1 <= lightON; pos1 += 1) {
  servo1.write(pos1);
  delay(15);
}

for (pos1 = lightON; pos1 >= lightOFF; pos1 -= 1) {
  servo1.write(pos1);
  delay(15);
}
```

The thing is that while this does work, I want to be able to move the servo a little quicker, but I can't use the `delay()` function because of some connectivity issues with another library (BLYNK).

How could I move the servo from lightOFF to lightON the quickest way possible without using the `delay()` function?

body:
The quickest way possible from `LightON` to `LightOFF` is simply `servo1.write(lightOFF);` without loops or delays, in one go; no need to do it degree by degree. For example:
```c++
int lightON = 180;
int lightOFF = 90;

for (pos1 = lightOFF; pos1 <= lightON; pos1++) {
  servo1.write(pos1);
  delay(15);
}

servo1.write(lightOFF);
```

If you want it to move a few degrees every loop and do other things in the loop while it moves, you can time it with `millis()` instead of `delay()`. The code below should move the servo 5 degrees every 0.5s:

```c++
int moveTime = 500; // Move every 0.5s
unsigned long int startMillis = 0;
int position = lightOFF;
int step = 5; // Move 5 degrees

void loop() {
  if (millis() - startMillis >= moveTime) {
    servo1.write(position);
    if (position <= lightON) {
      position = position + step;
    }
    startMillis = millis();
  }
  // Do other things
}
```

Untested and incomplete, but you get the idea.


body:
The best way is to use [map()][1] function.

    void loop() {
      unsigned long progress = millis() - startMillis;

      int angle = map(progress, 0, MOVING_PEDIOD, lightOFF , lightON);
      servo1.write(angle);
    }

The above code use the [millis()][2] function, therefore you do not need to worry about blocking other code.

Full instruction is available on [How to control speed of servo motor][3]

  [1]: https://arduinogetstarted.com/reference/arduino-map
  [2]: https://arduinogetstarted.com/reference/arduino-millis
  [3]: https://arduinogetstarted.com/faq/how-to-control-speed-of-servo-motor


message:
Problem connecting 2 74HC595 8 bit shift registers in cascading connection

I have now successfully learned how to control a single 8 bit shift register 74HC595 with Arduino UNO but whenever I tried to connect another one with the first shift resistor via cascading connection just like the image shown below (well I didn't use the 10uf capacitor between positive and negative terminal), the first shift register only outputs as desired but the second shift register, connected to a cascading connection, does not seem to work...

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

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

Here is the code.

        int latchPin = 10; // Latch pin of 74HC595 is connected to Digital pin 5
    int clockPin = 11; // Clock pin of 74HC595 is connected to Digital pin 6
    int dataPin = 9; // Data pin of 74HC595 is connected to Digital pin 4

    byte leds = 0;  // Variable to hold the pattern of which LEDs are currently turned on or off

    /*
     * setup() - this function runs once when you turn your Arduino on
     * We initialize the serial connection with the computer
     */
    void setup()
    {
      // Set all the pins of 74HC595 as OUTPUT
      pinMode(latchPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      Serial.begin(9600);
    }

    /*
     * loop() - this function runs over and over again
     */
    void loop()
    {
      leds = 0; // Initially turns all the LEDs off, by giving the variable 'leds' the value 0
      updateShiftRegister();
      delay(500);
      for (int i = 0; i <= 16; i++) // Turn all the LEDs ON one by one.
      {
        bitSet(leds, i);  // Set the bit that controls that LED in the variable 'leds'
        updateShiftRegister();
        delay(500);
      }

     /* The loop above should repeated 16 times as there are 2 shift resistors, each of them containing 8 and we need to lit up all 16 LEDs*/

    }

    /*
     * updateShiftRegister() - This function sets the latchPin to low, then calls the Arduino function 'shiftOut' to shift out contents of variable 'leds' in the shift register before putting the 'latchPin' high again.
     */
    void updateShiftRegister()
    {
       digitalWrite(latchPin, LOW);
       shiftOut(dataPin, clockPin, LSBFIRST, leds);
       digitalWrite(latchPin, HIGH);
    }

so is it my code or wiring problem?

I have read many articles on internet to make myself get it understood but unfortunately, none of the articles satisfied me.

many thanks for giving me a bit of your precious time...

body:
I am really very sorry to say that after a long inspection , i have found that

shift register clear (pin 10) pin of the second shift register remained inactivated due to loose connection of power, after fixing it, all shift registers are working very fine.

I do really apologize to all those friends who came to help me, for wasting their time, i am really very sorry for that...

all problems are solved now.


message:
Bit Bang signal generation

```

  #include <Wire.h>
  #include <LiquidCrystal_I2C.h>
  #include "digitalWriteFast.h"

  #define BUTTONPIN 2
  #define FDCSPIN 6
  #define CIPIN 5
  #define SPEAKERPIN 4

  float RPM=1000.0;
  int PWus=1.5*1000.0;
  int FDCSoffset=(1000.0/RPM/60.0/4.0) - (PWus/1000.0);
  int totalCnt;
  int CIState=B00000000;
  bool Buttonstate=0;
  LiquidCrystal_I2C lcd(0x27, 20, 4);

  void setup()
  {
    Serial.begin(9600);
    lcd.begin();
    lcd.backlight();
    lcd.clear();
    lcd.print("READY TO TEST"); // Waiting for button press
    pinMode(BUTTONPIN, INPUT);// Setting button as Input
    pinMode(FDCSPIN, OUTPUT); // Fuel Delivery Control Signal
    pinMode(CIPIN, OUTPUT); // Cylinder Identification
    digitalWriteFast(FDCSPIN, LOW);
    digitalWriteFast(CIPIN, LOW);
  }

  void loop()
  {
   Buttonstate=digitalReadFast(BUTTONPIN);
   if(Buttonstate==1)
   {
    delay(5);
    if(Buttonstate==1)
    {
      runInjectorTest();
    }
   }
  }
  void runInjectorTest()
  {
    lcd.print("Test Run");
    playtesttone();

      for(totalCnt=0;totalCnt<8000;totalCnt++)
      {

        PORTD=CIState;
        delayMicroseconds(PWus);
        PORTD=PORTD^B01000000;
        delayMicroseconds(FDCSoffset);
        if(totalCnt%4==0)
        {
          CIState=CIState^B00100000;
        }
      }
    totalCnt=0;
    playfinishtone();
  }
  void playtesttone()
  {
    tone(SPEAKERPIN, 500, 500);
    delay(700);
    tone(SPEAKERPIN, 500, 500);
    delay(700);
    tone(SPEAKERPIN, 500, 500);
    delay(700);
    tone(SPEAKERPIN, 2000, 500);
  }
  void playfinishtone()
  {

    tone(SPEAKERPIN, 2000, 500);
    delay(700);
    tone(SPEAKERPIN, 2000, 500);
    delay(700);
    tone(SPEAKERPIN, 2000, 500);
    delay(700);
    tone(SPEAKERPIN, 500, 500);

  }
```
I am trying to generate 2 signals using the code above and this output is [![enter image description here][1]][1]

From the image, the lime green signal is called FDCS and the other is called CI. Note that the scope shows the inverted form of the signal. I want the falling edge of CI to match with the Falling edge of the 5th FDCS signal (right now rising edge is matching with the falling edge of the CI signal). But the Rising edge of the CI signal should match with the Rising edge of the first FDCS signal (which it's already doing). How do I change my code to do this?

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

body:
If I understand correctly, you signal has a period of 8 FDCS pulses:
4 with CI high and 4 with CI low. Since the rising and falling edges of
CI do not happen at the same place relative to the FDCS pulses, you
should handle these separately.

I suggest something like the following. Note that, as I do not know what
signal(s) your setup inverted, I just try to reproduce what you show on
the scope, with non inversion:

```c++
uint8_t portState = 0;
for (int totalCnt = 0; totalCnt < 16000; totalCnt++)
{
    // On pulse 0, CI rises with FDCS.
    portState |= _BV(FDCSPIN);
    if (totalCnt % 8 == 0)
        portState |= _BV(CIPIN);
    PORTD = portState;

    delayMicroseconds(FDCSoffset);  // pulse width

    // On pulse 4, CI falls with FDCS.
    portState &= ~_BV(FDCSPIN);
    if (totalCnt % 8 == 4)
        portState &= ~_BV(CIPIN);
    PORTD = portState;

    delayMicroseconds(PWus);  // inter-pulse delay
}
```


message:
Bitwise write to analog PIN

I am just starting to learn bitwise operands and here is my question. To do this:

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

bitwise I can do like this:

    DDRB |= B00100000;   //set PIN13 as OUTPUT
    PORTB |= B00100000;  //set PIN13 HIGH

but how I can do this:

    analogWrite(9, 200);
I know how to convert DEC numbers to BIN, but how to send this number to PWM PIN? I cannot find any good example in web..
Thank you!

body:
Note, you haven't specified, which Arduino you are using. I'm assuming a Atmega328p based Arduino (Uno, Nano, Mini) here, though the principle works with every AVR microcontroller, that has this hardware).

With `analogWrite()` are are not sending data bitwise out of a pin. It configures the hardware Timer for setting that pin at a specific frequency and with a specific duty cycle. So `analogWrite()` actives a totally different piece of hardware inside the microcontroller.

To do this without the Arduino function `analogWrite()`, you first need to decide, which way to go:

- You can generate an interrupt through the hardware Timer and then set the wanted pin by software inside the ISR (which gives you free choice of the pin, but also introduces some jitter in the signal)
- or you can let the hardware Timer itself toggle the pin, which does not involve any software for running (that means you can only use one of the 2 pins, that are associated with the corresponding Timer, but you will get a much more stable signal)

There are lots of tutorials on the web on how to do that. A search for "arduino timer register pwm" gave me some promising results, for example [this one][1], where they explain, how to get PWM with the Timer1 registers and a free to choose frequency. (That is a 3 part series, one part for each Timer. Part 1 for Timer 0 is [here][2], though you might want to keep Timer 0 as it is, so that functions like `delay()` and `millis()` still work as normal). There are also many such questions on this site, for example [this one][3].

Another very important source for anything hardware related is the datasheet of the corresponding microcontroller. For the Uno, Nano or Mini that is the Atmega328p, which datasheet can be found on the microchip site [here][4] (or when googling for the microcontroller name)

  [1]: https://www.eprojectszone.com/how-to-modify-the-pwm-frequency-on-the-arduino-part2timer-1-and-phase-correct-pwm-mode/
  [2]: https://www.eprojectszone.com/how-to-modify-the-pwm-frequency-on-the-arduino-part1/
  [3]: https://arduino.stackexchange.com/questions/4494/pwm-generation-using-registers
  [4]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf


message:
Unexplained behavior of char array after using `deserializeJson`

I'm using `RF24` library to send messages between 2 MCU's : 1) ESP8266 (no Wifi, same code can be compiled to any Arduino board) 2) pro-Micro.

Message is sent in JSON format, while using `ArduinoJSON` library to `serialize` and `deserialize` messages.

Altough entire code works as expected, I get an error in "RFread" function, which `_readmsg` array loses its content after using `deserializeJson`.

 Attached below  relevant **part** of "RFread" function. Explanations in code below. Please notice "Mark [X]" in code and Serial output:

    char _readmsg[32];                                <---- Storing input in this array
        char t2[32];                                  <---- variable to clone value
        radio.read(&_readmsg, sizeof(_readmsg));      <---- getting RF input and store it in `_readmsg`
        strcpy(t2, _readmsg);                         <---- cloning, part of error seeking

        Serial.print("first: ");                      <---- printing initial value stored. OK. marked [A] in Serial output
        Serial.println(_readmsg);
        Serial.print("duplicate: ");                  <---- printing clone. OK. marked [B] in Serial output
        Serial.println(t2);

        if (key != nullptr)                           <--- check if "msg" key was sent in message
        {
          StaticJsonDocument<80> DOC;
          deserializeJson(DOC, _readmsg);             <---- **error beyond this point**
          Serial.print("second: ");
          Serial.println(_readmsg);                   <---- printing wrong value. marked [C] in Serial output

          if (DOC.containsKey(key))
          {
            const char *outmsg = DOC[key];
            if (out != nullptr)
            {
              strcpy(out, outmsg);
              return true;
            }
          }
          else
          {
            Serial.print("third: ");
            Serial.println(_readmsg);              <---- still error. marked [D] in Serial output
            Serial.print("duplicate2: ");
            Serial.println(t2);                    <---- clone variable is OK. marked [E] in Serial output
            strcpy(out, t2); // if key not present, return entire message
            return 0;
          }

and in Serial port:

    message sent OK   <---- irrelevant for debug

    15:18:14.934 -> first: {"id":"Port","msg":"fff"}       <----[A]

    15:18:14.934 -> duplicate: {"id":"Port","msg":"fff"}   <----[B]

    15:18:14.934 -> second: id                             <----[C]

    15:18:14.934 -> third: id                              <----[D]

    15:18:14.934 -> duplicate2: {"id":"Port","msg":"fff"}  <----[E]

    15:18:14.934 -> Error. no such key. got reply: {"id":"Port","msg":"fff"}

Is there a reason for that ? is it a bug ?

body:
When you pass a `char*` input to [deserializeJson()](https://arduinojson.org/v6/api/json/deserializejson/), it alters the input to avoid making useless copies.
This is the "zero-copy" mode of ArduinoJson.

In this mode, the JSON parser modifies the input in-place. The following modifications are performed:

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

Example:

```c++
char[] json = "{\"hello\":\"world\"}";
deserializeJson(doc, json);
```

After executing the line above, the input variable probably contains something like: `"hello\0world\0"`.

You can find more details [in the documentation](https://arduinojson.org/v6/faq/why-is-the-input-modified/)


body:
To sum up Benoit Blanchon answer:

in original code:

    deserializeJson(DOC, _readmsg);

changes to:

    deserializeJson(DOC, (const char *)_readmsg);


message:
Reading Multiple MPU 9250 Sensors using TCA9548A Multiplexer

I am trying to read multiple MPU 9250 sensors using TCA9548A multiplexer in ESP 32 and Arduino IDE. Has anyone done that successfully?

I am new to the  area of Arduino coding. I am trying to edit the code in this tutorial for MPU 9250 (https://www.bluedot.space/tutorials/connect-multiple-sensors-using-i2c-multiplexer/). I am facing issues with libraries and commands while shifting from BME 280 to MPU 9250.  Once  I am changing to MPU 9250 and trying to call instance MPU9250 IMU_0, I am getting error "no matching function for call to 'MPU9250", which I understand is because the library I've used doesn't support the call. I am unable to find alternate library or command. How can this be sorted out?

<!-- language: lang-cpp -->

    #include <Wire.h>
    #include <MPU9250.h>
    MPU9250 mpu_0;
    MPU9250 mpu_1;
    MPU9250 mpu_2;
    MPU9250 mpu_3;

    #define TCAADDR 0x70
    void tcaselect(uint8_t i) {
      if (i > 7) return;

      Wire.beginTransmission(TCAADDR);
      Wire.write(1 << i);
      Wire.endTransmission();
    }
    void setup() {
      Serial.begin(9600);
      Wire.begin();
      Serial.println(F("##############################"));
      Serial.println(F("Starting Initialization"));
      Serial.println(F("##############################"));

      //*************INITIALIZING FIRST SENSOR*******************************
      tcaselect(0);

      if (mpu_0.begin() != 0x68)
      { Serial.print(F("MPU.1 detected?\t")); Serial.println(F("No"));}
      else
      { Serial.print(F("MPU.1 detected?\t")); Serial.println(F("Yes"));}
      //**********************************************************************
      //*************INITIALIZING SECOND SENSOR*******************************
      tcaselect(1);

      if (mpu_1.begin() != 0x68)
      { Serial.print(F("MPU Nr.2 detected?\t")); Serial.println(F("No"));}
      else
      { Serial.print(F("MPU Nr.2 detected?\t")); Serial.println(F("Yes"));}
      //*********************************************************************
      //**********************************************************************
      Serial.println();
      Serial.println(F("##############################"));
      Serial.println(F("Initialization Finished"));
      Serial.println(F("##############################"));
      Serial.println();
      Serial.println();
    }

body:
You need to adapt the example you're following to follow how the MPU library does its construction and setup.

Looking at the [documentation][1] for the MPU library you are using, you should change the definitions to:

<!-- language-all: lang-cpp -->

    MPU9250 mpu_0(Wire, 0x68);  // 0x69 if you pulled AD0 high

Then if you read further to the "Common Setup Functions" section, you'll see that this library's `setup` function has this behavior:

> This function returns a positive value on a successful initialization and returns a negative value on an unsuccesful initialization

So you need to adapt that too:

    Serial.print(F("MPU.1 detected?\t"));
    if (mpu_0.begin() < 0) { // the examples assume zero is ok too
      Serial.println(F("No"));
    } else {
      Serial.println(F("Yes"));
    }

You'll save yourself some trouble if you use an array for your sensors too.

    MPU9250 mpus[] = { MPU9250(Wire, 0x68), MPU9250(Wire, 0x68) };
    const int num_mpus = sizeof(mpus)/sizeof(mpus[0]);

Then your initialization can be done with a loop:

    for (int i = 0; i < num_mpus; ++i) {
       tcaselect(i);
       if (mpus[i].begin() < 0) {
         // ...
       }
     }

And you can do similar things for interacting with the sensor. e.g.:

    for (int i = 0; i < num_mpus; ++i) {
       tcaselect(i);
       mpus[i].readSensor();
       Serial.println(mpus[i].getAccelX_mss());
       // ...
     }

[1]: https://github.com/bolderflight/MPU9250


message:
always detects same pin as HIGH even when its not connected

Im practicing with an arduino UNO board (I'm a begginer) and I'm trying to turn some LED's on depending on which analog pin is connected to 5V.
Here's my code:

    int statusLed = 11;
    int out1 = 2;
    int out2 = 3;
    int out3 = 4;
    int out4 = 5;
    int in1 = A0;
    int in2 = A1;
    int in3 = A2;
    int in4 = A3;
    int statusLedBrightness = 3;
    int incBrillo = 3;
    int fadeDelay = 5;

    void blinkFade(int pin){
      analogWrite(pin, statusLedBrightness);
      statusLedBrightness = statusLedBrightness + incBrillo;
      if (statusLedBrightness <= 0 || statusLedBrightness >= 255){
        incBrillo = -incBrillo;
      }
      delay(fadeDelay);
      }

    void wait(){
      digitalWrite(out1, LOW);
      digitalWrite(out2, LOW);
      digitalWrite(out3, LOW);
      digitalWrite(out4, LOW);
      blinkFade(statusLed);
    }

    void setup() {
      // put your setup code here, to run once:
      pinMode(out1,OUTPUT);
      pinMode(out2,OUTPUT);
      pinMode(out3,OUTPUT);
      pinMode(out4,OUTPUT);
      pinMode(in1, INPUT);
      pinMode(in2, INPUT);
      pinMode(in3, INPUT);
      pinMode(in4, INPUT);
      Serial.begin(115200);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if (analogRead(in1)>=500){
        Serial.println("1: ");
        Serial.println(analogRead(in1)); //Print "1" and the read of pin A0
        turnOff();
        digitalWrite(out1,HIGH);
      }
      else if (analogRead(in2)>=500){
        Serial.println("2: ");
        Serial.println(analogRead(in2));//Print "2" and the read of pin A1
        turnOff();
        digitalWrite(out2,HIGH);
      }
      else if (analogRead(in3)>=500){
        Serial.println("3: ");
        Serial.println(analogRead(in3));//Print "3" and the read of pin A2
        turnOff();
        digitalWrite(out3,HIGH);
      }
      else if (analogRead(in4)>=500){
        Serial.println("4: ");
        Serial.println(analogRead(in4));//Print "4" and the read of pin A3
        turnOff();
        digitalWrite(out4,HIGH);
      }
      else{
        Serial.println("Stand By");
        wait();
      }

    }

The problem Im having is when I connect a wire from 5V to any analog pin (A0 to A3) it always runs this segment of code:

    Serial.println("1: ");
    Serial.println(analogRead(in1));
    turnOff();
    digitalWrite(out1,HIGH);

By my understanding it's detecting as if it always was A0 the one that is connected to 5V but i dont understand why is this happening or how to solve it.

This is a screen capture of serial monitor when 5V is connected to pin A2. It should print "3:" and the reading
[![][1]]
[1]

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

body:
You're not showing your schematic but I'm sure that you are simply leaving the Ax pins OPEN when you are not connecting them to your +V line.  In that case they are "floating" and as such they can float HIGH or LOW or just about anywhere.  What's happening is that when you hook up +V to any of them, that has the side-effect of pulling at least A0 HIGH along with it since you have allowed it to float.

Two things to do here:

 1. Don't allow lines to float and expect deterministic behavior.  Tie them to +V or to GROUND when you are not using them.
 2. Pull the Ax lines to +V or GND via a resistor like 10K Ohms.  This will prevent them from floating and will give you predictable results.


message:
Finding Relatively Accurate Velocity Using an IMU

I am currently working on a project where I am trying to accurately find velocity in a handheld device using an IMU for about 30 seconds.
I have been having major issues doing this because of large amounts of drift from poor calculations due to inaccurate sensor readings.
I have tried tuning offsets for my sensor and using other sensor fusion libraries to find my linear acceleration.

At this point I don't know if I am doing something wrong, going about the process wrong, or if my sensors are just to inaccurate to accomplish this.

I am hoping if anyone may have recommendations on how to accomplish this from the ground up. I currently have two 9DOF IMUS listed below. The first one I tried to use the predefined linear acceleration function to find velocity in ndof mode, using bosch calibration steps. The second i spent hours tuning the offsets on to get linear acceleration and it came out much worse than the first sensor. For the second I can include code but I used the madgwick from the Adafruit_AHRS library for the sensor fusion for sake of time.

Any help is appreciated.

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

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

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

  [1]: https://phys.libretexts.org/Bookshelves/University_Physics/Book:_University_Physics_(OpenStax)/Map:_University_Physics_I_-_Mechanics_Sound_Oscillations_and_Waves_(OpenStax)/03:_Motion_Along_a_Straight_Line/3.08:_Finding_Velocity_and_Displacement_from_Acceleration
  [2]: https://en.wikipedia.org/wiki/Dead_reckoning


body:
For more context I did ask BOSCH directly about this issue and explained my setup in more detail.

[https://community.bosch-sensortec.com/t5/MEMS-sensors-forum/BNO055-Outputting-Bad-Linear-Accel-Data/m-p/18976#M5212][1]

  [1]: https://community.bosch-sensortec.com/t5/MEMS-sensors-forum/BNO055-Outputting-Bad-Linear-Accel-Data/m-p/18976#M5212


message:
LM35 temperature decreases when heated

I have a question regarding the LM35. The sensor is supposed to have values that are to be directly proportional. But instead of the temperature increasing, the sensor values decrease.

This is my setup below. It seems to be a standard setup in different LM35 tutorial pages.

[![LM35 Breadboard configuration][1]][1]

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

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

    void loop() {

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

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

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

    }

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

[![Heat up results][2]][2]

I read somewhere that it has something to do with the power supplied by the Arduino. However, when I used a 12V supply to power the Arduino, the readings became very erratic and unstable.

## **UPDATE:** ##

I have finally returned from the city (Took a long time because of Quarantine Restrictions) and I brought 3 LM35 from another shop. All 3 of the new LM35 worked as intended and didn't lower its temp reading when exposed to heat (With the same configuration). I could rule out these possibilities as to the reason why the LM35 didn't work.

 **1. Manufacturing Defect** - all **three** of the LM35 didn't work as intended. They all had their temperature lowered when exposed to heat. There could be a defect in the manufacturing process because it doesn't work as advertised. (Leaning towards this)

 **2. Static Electricity** - I remember receiving the LM35 in a plastic bag as packaged by the shop. It could have been affected by static electricity and damaged the circuit inside (on all three though?). The LM35s I received recently had been packaged in those electrostatic discharge protection packaging so it could have probably contributed to it? I need more insight on this I apologize for not being able to properly word it out.

There could be more but these are the most I could come up with as a conclusion.

  [1]: https://i.stack.imgur.com/igZQQ.png
  [2]: https://i.stack.imgur.com/SOYHX.png

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

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

Change your code to this and I believe it will work:

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

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

    void loop() {

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

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

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

    }

The data you are reading from A5 is indeterminate and just happens to decrease as A0 increases.

================================================================================
UPDATE:

Ok, so you corrected yourself and are reading the correct pin in spite of what your schematic shows.  Please explain this:

    float vout= (reading*5000)/1024;
    float temp= vout/10;

I think you want:

    float vout = (reading/1024.0) * 5000.0;
    float temp = vout/10.0;

You are carelessly mixing floating point and integer math.

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


message:
Can I safely connect my A6 GPRS module to this 5V 2A phone adapter

I have an A6 GPRS module, and my Samsung phone power adapter has output of 5V and 2A. But it also says 9V and 1.6A

[![My Samsung Mobile Power Adapter][1]][1]
My Phone's Adapter

So would it damage my A6 GPRS Module if I plug this to it via the micro usb power port? (especially because it also says 9V)?

[![My A6 GPRS module][2]][2]

My A6 GPRS module

  [1]: https://i.stack.imgur.com/t2nMp.png
  [2]: https://i.stack.imgur.com/HhhAW.png

body:
The standard output for USB is 5V but there are some such chargers that will output more for enhanced charging output on devices that support it.

In this case the adapter will default to 5V and will only upgrade to 9V if the device requests it.  The GPRS module will not request 9V and so the adapter will continue to provide only 5V which is what you want.


message:
Datasheet of arduino power jack

Can we find out about the parts that the arduino uses?

I want to make a shield, and i bought the same power jacks.

And i thought that there would be two pins, one for power, one for GND.
However, it has three pins.

The supplier did not have a datasheet, and right now i do not have a continuity beeper either, so could i see its datasheet somewhere, or does anyone know why it has three pins?

body:
This is an image from a typical power jack:

[![From here https://www.we-online.de/katalog/datasheet/6941xx301002.pdf][1]][1]

The specific ones you bought may differ.  The vendor should be able to supply you with a manufacturer and P/N or an actual data sheet.

Image copied from: https://www.we-online.de/katalog/datasheet/6941xx301002.pdf

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


message:
Module that can both detect Voltage (12V) and Control current

I need a module for ARDUINO that can both detect Voltage (12V) **and** Control current between 2 pins (12V), like a relay on another device

I have found relay modules to control pins and another module for 4-channel Voltage detection, but it seems like a lot of components and wiring.

Is there any module that can do both?

body:
You don't need another module to detect voltage on an Arduino.  The UNO, which I assume you are using, has 6 analog inputs (A0-A5) that can directly read voltage.  The only problem is that you want to measure a voltage up to 12V and the Arduino can only handle 5V.  So the solution is to DIVIDE that using two resistors in a voltage-divider configuration so that you only see 5V at the Arduino when there is 12V on the signal.

From here: https://www.electroniclinic.com/what-is-a-voltage-divider-or-potential-divider-formula-and-practical-uses/

you can see how to make one:

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

As far as controlling a "current" that is usually done with a relay.  There are no on-board relays but there are the digital outputs that can drive a small relay or can be connected via some other circuitry like a couple of transistors to drive just about any size relay.

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


body:
I would suggest opto-isolators for both directions.

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

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

<!-- End schematic -->

For the Ardiuno sending control signal you have to know which way round to connect to the inputs of your controller. Chances are one will be ground - that's "CTL Low".


message:
Attiny85 Clone Cannot set P1 to input

Everything i read about the chinese Digispark attiny85 clones says you can use p0-5 as digitlal I\O (p5 as after fuse reset)

Simple test code for a button will not let me use P1 as an input tied to a simple button.

The code below works on p0,p2,p5 but will only interrupt the LED that is set to on, on P1.

    #include "DigiKeyboard.h"

    //pins 3 & 4 used for usb connection
    bool buttonState1 = 0;

    void setup() {
      pinMode(1, INPUT);
      digitalWrite(1, HIGH); //turn on pull-up resistor
    }

    void loop() {

        if (digitalRead(1)!= buttonState1){
          buttonState1 = digitalRead(1);
          if (buttonState1 == LOW)DigiKeyboard.print("test1");
        }

    }

body:
I had a quick look into the Schematics of a digisparc board. P1 is hardwired over an LED and a resistor to GND. If you turn on the PULL UP resistor for P1 the LED should light up and the voltage at P1 would be very low (it depends on the voltage divider that is built from the PULL UP resistor and the LED resistor); so the P1 reading should be LOW. If you connected the Button to GND and press it, the voltage at P1 drops to 0. But, that does not affect the LOW state. The program does not react. The LED turns off, because it is not powered anymore.

You could try to connect the button to +5V and do not setup a PULL UP resistor for P1. If you press the button the LED should light up and +5V should be at P1. It should change its state from high to low. (I did not tried that; but I see no reason, why it would not work).


message:
arduino parking lot

I want to make a project where there is a parking lot and a ir sensor which senses when a car comes and displays a message on lcd saying to insert a rfid card and then it opens a gate and there are many ir sensors in the slots to detect where there are cars and sends a message saying which slot is free.but the problem is many parts need the 5v pin but there is only one on the arduino board so i wanted to ask if any problem will occur if we connect multiple parts to one 5v pin if there will be a problem what is the work around.

body: You can connect multiple devices or modules to the same 5v pin, as long as it does not exceed the maximum current that the on-board 5v regulator can handled. If you are using a genuine [Arduino Uno](https://content.arduino.cc/assets/UNO-TH_Rev3e_sch.pdf), it has a [NCP1117](https://www.onsemi.com/pub/Collateral/NCP1117-D.PDF) which has a maximum current of 1A. If you don't have a genuine Arduino Uno, check the part number and find the datasheet to find out the maximum current.


message:
RF24- Splitting and sending a longer than 32 byte payload

In order to send a long payload I've created the following function:

    void splitMSG(const char *msg, const int arraySize, const int len)
    {
      Serial.print("Array size: ");
      Serial.println(arraySize);
      byte numPackets = (int)(arraySize / len);
      byte P_iterator = 0;
      if (arraySize % len > 0)
      {
        numPackets++;
      }
      Serial.print("num_Packets: ");
      Serial.println(numPackets);

      while (P_iterator < numPackets)
      {
        char t[len + 1];
        char *ptr1 = msg + P_iterator * (len);
        strncpy(t, ptr1, len);
        t[len + 1] = '\0';
        Serial.println(t);
        radio.write(&t, sizeof(t));
        P_iterator++;
      }
    }

The split message is sent to the serial monitor to verify it is as expected.

**On the sending device :

    void loop()
    {
      radio.stopListening();

      char send_msg[] = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";  // <----- input msg
      splitMSG(send_msg, sizeof(send_msg), 10);                  // <----- split to 10 bytes a packet
      delay(1000);
      // Serial.println("±±±±±±±±");
    }

On the serial monitor I get:

    08:06:17.569 -> Array size: 37
    08:06:17.569 -> num_Packets: 4
    08:06:17.569 -> 1234567890
    08:06:17.569 -> ABCDEFGHIJ
    08:06:17.569 -> KLMNOPQRST
    08:06:17.569 -> UVWXYZ

**On the receiving device:

    void loop()
    {
      if (radio.available())
      {
        while (radio.available())
        {
          char buf[32];
          radio.read(&buf, sizeof(buf));
          Serial.print("got msg: ");
          Serial.println(buf);
          radio.flush_rx();
        }
      }

      delay(100);
    }

On the serial monitor I get:

    08:08:18.462 -> got msg: 1234567890⸮⸮⸮⸮
    08:08:18.561 -> got msg: ABCDEFGHIJKLMNOPQRSTUVWXYZ
    08:08:19.555 -> got msg: 1234567890ABCDEFGHIJKLMNOPQRST⸮⸮⸮⸮
    08:08:20.549 -> got msg: 1234567890ABCDEFGHIJKLMNOPQRST⸮⸮⸮⸮
    08:08:21.576 -> got msg: 1234567890ABCDEFGHIJKLMNOPQRST⸮⸮⸮⸮
    08:08:22.570 -> got msg: 1234567890ABCDEFGHIJKLMNOPQRST⸮⸮⸮⸮
    08:08:22.669 -> got msg: UVWXYZ

Does the problem with `radio.write` ' buffer , or the way I split the message ?

body:
    t[len + 1] = '\0';

Your array is declared as having `len+1` bytes of storage. So the last index is `len`, not `len+1`. You're writing the zero one past the end of the array, thus you're not transmitting it (and sending one byte of "garbage" instead).


message:
Most precise way to measure linear distance travelled by a wheel

Suppose a bot with wheels is traveling in a a straight line, and we want to measure this linear distance traversed by it as accurately as possible.

One of the ways is to use an optical encoder to measure the angle of rotation of the wheels and get the linear distance traveled.

Another way could be to use the data from accelerometer and get the linear distance traveled.

Which of these two methods would be better? Is there a third method which is more precise than the previous two?

body:
If you measure  one of the free running wheels (with no motor connect to it), it depends on the traction of the wheel, but that could be fairly accurate.

If you move horizontally a simple accellerometer (1 axis) would be great. But if you have a vertical component, then you can not distinct between accelleration and weight force (Einstein). If you use a 3 axes accellerometer, you can compute/extract the robots moving speed (subtract the G component = 9.81 m/s²) and thus the distance. You have to use vector arithmetic in this case.

If the ground has enough "structure" you could use an optical sensor (like optical mice have).

If you have a reference object (e.g. a wall, a book) you could use a LIDAR sensor (https://en.wikipedia.org/wiki/Lidar) to measure the absolute distances at time points and compute the relative distance between these time points.


body:
If you use an accelerometer, you have to integrate twice to arrive at distance travelled. These two integrations will also compound errors and noise, so the result won't be very accurate without many corrections.

If a wheel doesn't slip and is undriven, the results of counting wheel rotations should be fairly accurate when the robot is moving in a straight line.

Dragging a cheap computer mouse behind the robot and reading its output could also work, but I haven't tried that one yet.

The most accurate, if you can set up a flat object that reflects well enough at the destination of the robot, is probably LIDAR. Not cheap, but easy enough to do as long as the robot moves in a straight line.

Another option would be to count wheel rotations, and calibrate with LIDAR (or GPS for very long distances) and use the calibrated wheel rotations in the final version, or use two or more methods and do sensor fusion.


message:
Problems with inputting into serial monitor

I am currently working on a project where i take a frequency, and i want the code to take that value and use a formula to work out its mmh2O level. I use the Serial Monitor to input the values, but i have a problem. When writing the values e.g. "44.62352548","44.49151522". The value that is sent is wrong and displayed wrong.
[![enter image description here][1]][1]

I know the code i have written does not support this many signigicant figures from a float. And i have tried a few things to try and solve it but i cannot crack it.

I have tried using dtostrf() command, but i have never used this before and dont understand. Somebody from the arduino Forums had helped me out but it didnt seem to work.
I have also tried formatting aswell, and that did not seem to work.

If anyone has any help and advice it would be much appreciated.
```
float level;
float myValue;

String msg1 = "Enter Frequency (type 0 to exit): ";
String msg2 = "Your Frequency is: ";

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

void loop()
{
  Serial.print(msg1);

  while (Serial.available() == 0);
  {

  }
  myValue = Serial.parseFloat();
  if (myValue == 0.0)
  {
    Serial.end();
  }
  else
  {
    freqConversion();
  }
}

 void freqConversion()
{
  level = (myValue-44.712)/-0.0285493333;
  Serial.println(myValue);
  Serial.print(msg2);
  Serial.println(level);
}
```

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

body:
You have hit a bug in the implementation of `parseFloat()`.

This function [reads the number you send as an integer][parse], ignoring
the decimal point, and stores it in a `long`. It then multiplies it by a
scaling factor (a power of 0.1) in order to get the correct value. The
problem is, if you provide too many significant digits, the integer
overflows, and you get garbage. For example "44.64978683" is interpreted
as

```c++
(long) 4464978683 * 0.00000001
```

but `(long) 4464978683` overflows and rolls over to 170011387, hence the
result you get.

Simple workaround: do not provide so many significant digits. They are
irrelevant anyway given the resolution of a `float`.

**Edit**: I did not find any bug report for this issue, so [I submitted my own][issue] to the Arduino dev team.

[parse]: https://github.com/arduino/ArduinoCore-API/blob/1.1.0/api/Stream.cpp#L182
[issue]: https://github.com/arduino/ArduinoCore-API/issues/129

**Update**: Per request of a maintainer, I submitted [a pull
request][pr] with a failing unit test revealing this bug. We then worked
on a fix, which has now been merged to master. It should be published on
the next release of ArduinoCore-API.

Note, however, that the AVR core does not yet use the common API
repository. In the meantime, it may be worth submitting a pull request
to ArduinoCore-avr that cherry-picks the fix from ArduinoCore-API.

[pr]: https://github.com/arduino/ArduinoCore-API/pull/133


message:
How safely write to SD or Eeprom on Arduino power off

I want to constantly store data to sd. But how I make sure data is not corrupted on moment of power off? I think I could add small capacitor on 5V and check when voltage drops, so I would stop data write. Or is there better solution for safe data write?

body:
I think a "small" capacitor here is not going to do the job as you need to keep power stable until the write is completed.  You need to determine:

 1. How much power am I using?
 2. How quickly can I detect a power outage?
 3. How much time do I need to keep power on the Arduino to complete the write operation(s) I want to complete.

Then you will be in a position to calculate how much capacity you need and whether a capacitor or battery is more appropriate.


body:
You're probably going to want to look to [various forms of NVRAM (Non-volatile RAM)][1].  SRAM with an automatic save to EEPROM function on power loss, e.g. [47L16][2].  Or battery backed RAM; if you have a real-time clock in your project you may have some limited storage in it.  E.g., the [DS1307][3] has 56 bytes, although you can probably find a more accurate RTC that has storage in it.  Or FRAM, though it's as bit expensive, e.g. [cy15b064q-sxet][4]

In any case you'd probably want to write your data out in blocks with CRC so that you can make a determination on whether or not a partial write was done when reading back later.

  [1]: https://en.wikipedia.org/wiki/Non-volatile_random-access_memory
  [2]: https://www.microchip.com/wwwproducts/en/47L16
  [3]: https://datasheets.maximintegrated.com/en/ds/DS1307.pdf
  [4]: https://www.cypress.com/part/cy15b064q-sxet


message:
File.read() always returns -1

I'm trying to print a txt file from an SD card to a SSD1306 using the u8x8 library.
Here's the current code:

    #include <SD.h>

    #include <Arduino.h>
    #include <U8x8lib.h>

    #ifdef U8X8_HAVE_HW_SPI
    #include <SPI.h>
    #endif
    #ifdef U8X8_HAVE_HW_I2C
    #include <Wire.h>
    #endif

      U8X8_SSD1306_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);

    /*
      This example will probably not work with the SSD1606, because of the
      internal buffer swapping
    */
    #define maxChar  128
    #define rows 8
    #define cols 16

    File myFile;
    int x = 0;
    int y = 0;
    char c;

    void setup()
    {
      /*Serial.begin(9600);
      Serial.print("Initializing SD... ");
      if (!SD.begin(10)) {
        Serial.println("initialization failed!");
        while (1);
      }
      Serial.println("initialization done.");*/

      u8x8.begin();
      delay(500);
      u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);

      myFile = SD.open("target.txt", FILE_READ);
      u8x8.clear();
      u8x8.print("ciao");
      u8x8.print(myFile.read());
      delay(2000);
      printNewSet();
    }
    void loop()
    {

    }

    void printNewSet()
    {
      u8x8.clear();
      x = 0;
      y = 0;
      while (myFile.available() && y<rows)
      {
        c = (char) myFile.read();
        if (c == '\n') c = 'a';
        u8x8.print(c);
        stepCoords();
      }
    }

    void stepCoords()
    {
      x++;
      if (x >= cols) newLine();
    }
    void newLine()
    {
      u8x8.print('\n');
      x = 0;
      y++;
    }

The function `printNewSet()` is supposed to print a batch of characters until either the file ends or the display limit is reached.

The file displayed correctly until i switched from `while(myFile.available()) u8x8.print( (char) myFile.read());` to `printNewSet()`, at which point `myFile.read()` only returns -1 and `myFile.available()` is always false.

What is going wrong?

EDIT: While debugging i discovered that myFile fails to be initialized. Am I running out of memory?

body: I had accidentally commented out the SD initialization along with the serial initialization. After uncommenting it it works correctly


message:
NRF24 and usb digispark

I want to connect NRf24 module with digispark and use USB capabilities at same time.
currently, i use this conexion diagram:

                   NC      PB5  1|o   |8  Vcc --- nRF24L01  VCC, pin2 --- LED --- 5V
    nRF24L01  CE, pin3 --- PB3  2|    |7  PB2 --- nRF24L01  SCK, pin5
    nRF24L01 CSN, pin4 --- PB4  3|    |6  PB1 --- nRF24L01 MOSI, pin6
    nRF24L01 GND, pin1 --- GND  4|    |5  PB0 --- nRF24L01 MISO, pin7

Bu my problem is that as you see in this diagram CE and CSN are in the USB + and - pins:
[![enter image description here][1]][1]
I just want that my module receive data so, i think that if i power up every time CE pin and i change CSN pin to PB5 this may work but, in fact this don't
I can't use 3 pin connexion because i don't have capacitor and my project is for Wednesday
Thanks in advance for your help

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

body: it is possible to use digispark with NRF24 and USB keyboard without use system that need capacitors as the tree cable solution? I just want to use the digispark as RX


body:
As per https://digistump.com/wiki/digispark/tutorials/basics:

*Pin 3 and Pin 4 (P3 and P4) are used for USB communication and programming, while you can use them in your circuit if you are not using USB communication, you may have to unplug your circuit during programming if the circuit would impede the pin states or dramatically affect the voltage levels on these pins.*


message:
nRF24l01+ Problems. Data is being recieved as 0

I am trying to transmit the values of three potentiometers via the nRF24L01+ (w/antenna). I am using the regulator designed for the nRF24L01+, so I don't think I need to add a decoupling capacitor. I am using a data structure to send the POT outputs as bytes. On the transmitter end, the values of the data structure are correct. On the receiver, however, each value of the data structure is being received as 0. I have an if statement to verify if radio.available() and apparently the radio is available. If I change the wiring of either the receiver or the transmitter, the radio is not available, so I am assuming it is wired correctly. Plus, the regulator makes it pretty simple.

I have :
- CE = D7
- CSN = D8
- (and all the other mandatory pins 11, 12, 13 connected correctly) and D10 set to output with nothing connected. (I read on another post that D10 must be set to output to make it the SPI master, or something like that)...

I have been trying for days and can't seem to figure out what I'm doing wrong. Let me know if you need anymore information.

```C++
//Transmitter//
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

// Define the digital inputs
#define liftPOT A2  // Joystick button 1
#define thrustPOT A0  // Joystick button 2
#define rudderPOT A1   // Toggle switch 1

RF24 radio(7, 8);   // nRF24L01 (CE, CSN)
const byte address[6] = "00001"; // Address
// Max size of this struct is 32 bytes - NRF24L01 buffer limit
struct Data_Package {
  byte thrustPOT;
  byte liftPOT;
  byte rudderPOT;
};
Data_Package data; //Create a variable with the above structure
void setup() {
  Serial.begin(9600);
  // Define the radio communication
  radio.begin();
  radio.openWritingPipe(address);
  radio.setAutoAck(false);
  radio.setDataRate(RF24_250KBPS);
  radio.setPALevel(RF24_PA_LOW);

  // Set initial default values
  data.thrustPOT = 127; // Values from 0 to 255. When Joystick is in resting position, the value is in the middle, or 127. We actually map the pot value from 0 to 1023 to 0 to 255 because that's one BYTE value
  data.rudderPOT = 127;
  data.liftPOT = 1;
}
void loop() {
  // Read all analog inputs and map them to one Byte value
  data.thrustPOT = map(analogRead(A1), 0, 1023, 0, 255); // Convert the analog read value from 0 to 1023 into a BYTE value from 0 to 255
  data.rudderPOT = map(analogRead(A0), 0, 1023, 0, 255);
  data.liftPOT = map(analogRead(A2), 0, 1023, 0, 255);
  radio.write(&data, sizeof(Data_Package));

  int liftVal, thrustVal, rudderPOS;
  liftVal = map(analogRead(A2), 0, 1023, 0, 255);
  thrustVal = map(analogRead(A0), 0, 1023, 0, 255);
  rudderPOS = map(analogRead(A1), 0, 1023, 0, 255);
  Serial.print("Lift : ");
  Serial.print(data.liftPOT);
  Serial.print(" Thrust : ");
  Serial.print(data.thrustPOT);
  Serial.print(" Rudder : ");
  Serial.println(data.rudderPOT);
```
```C++
//Receiver//
    #include <RF24Network.h>
#include <RF24Network_config.h>
#include <Sync.h>

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

RF24 radio(7, 8);   // nRF24L01 (CE, CSN)
const byte address[6] = "00001";
unsigned long lastReceiveTime = 0;
unsigned long currentTime = 0;
Servo thrustESC;  // create servo object to control the ESC
Servo liftESC;
Servo rudder;
int thrustVal, liftVal, rudderVal;
// Max size of this struct is 32 bytes - NRF24L01 buffer limit
struct Data_Package {
  byte thrustPOT;
  byte liftPOT;
  byte rudderPOT;
};
Data_Package data; //Create a variable with the above structure
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setAutoAck(false);
  radio.setDataRate(RF24_250KBPS);
  radio.setPALevel(RF24_PA_LOW);
  radio.startListening(); //  Set the module as receiver
  resetData();
  thrustESC.attach(6);
  liftESC.attach(5);
  rudder.attach(3);
  pinMode(10, OUTPUT);

}
void loop() {
  // Check whether we keep receving data, or we have a connection between the two modules
  currentTime = millis();
  if ( currentTime - lastReceiveTime > 1000 ) { // If current time is more then 1 second since we have recived the last data, that means we have lost connection
    resetData(); // If connection is lost, reset the data. It prevents unwanted behavior, for example if a drone jas a throttle up, if we lose connection it can keep flying away if we dont reset the function
  }
  // Check whether there is data to be received
  if (radio.available()) {
    radio.read(&data, sizeof(Data_Package)); // Read the whole data and store it into the 'data' structure
    lastReceiveTime = millis(); // At this moment we have received the data
    Serial.print("recieving");
  }
  // Controlling servos
  rudderVal = map(data.rudderPOT, 0, 255, 0, 50);
  rudder.write(rudderVal);
  // Controlling brushless motor with ESC
  // Lift propeller
  liftVal = map(data.liftPOT, 0, 255, 1000, 2000); // Map the receiving value form 0 to 255 to 0 1000 to 2000, values used for controlling ESCs
  liftESC.writeMicroseconds(liftVal); // Send the PWM control singal to the ESC

  // Thrust propeller
  thrustVal = constrain(data.thrustPOT, 130, 255); // Joysticks stays in middle. So we only need values the upper values from 130 to 255
  thrustVal = map(thrustVal, 130, 255, 1000, 2000);
  thrustESC.writeMicroseconds(thrustVal);
  Serial.print("Lift : ");
  Serial.print(data.thrustPOT);
  Serial.print(" Thrust : ");
  Serial.print(thrustVal);
  Serial.print(" Rudder : ");
  Serial.println(rudderVal);
}
void resetData() {
  // Reset the values when there is no radio connection - Set initial default values
  data.thrustPOT = 127;
  data.liftPOT = 1;
    data.rudderPOT = 127;
    Serial.println("reset");

}
```

body: In order to diagnose my proplem, I used the radio.isChipConnected() function. When the function returns 0, you have a wiring problem. If you are getting consistent high or low values, run the above function. If you return a 1, that means that the nRF24L01 is connected correctly and there is likely a software error. Simplify everything in the code to where only one simple thing is being transmitted and received. I would recommend starting small with nothing attached to the arduino other than the radio module. Once that is behaving properly, build up to your goal step by step, checking along the way. My mistake was soldering my entire set up directly to the arduino and then trying to troubleshoot.


message:
Can't get "Burn Bootloader" working - Arduino Nano

This is a follow up from a previous question. I have one Nano working perfectly (I think) (Nano A) and another one (Nano B) which seems to be working but has no bootloader. So I am trying to use Nano-A as an ISP programmer to burn the bootloader into Nano-B. I am pretty confident with my hardware and Arduino IDE setup. See previous question for the details; <https://arduino.stackexchange.com/questions/79743/problems-uploading-with-a-new-nano>

I have pasted below two screen sessions. The first shows the Arduino IDE Log when I (unsuccesfully) try to run "Burn Bootloader" - IT *almost* works! (but not quite). - So I beleive that there is not too much wrong with my setup.

The second session is me using running avrdude in "terminal" mode from a Windows command prompt. I have used individual "send" commands to send the ISP instructions required to programme a single word into bootloader flash memory and this all seems to work OK. So I don't understand why avrdude is not working when invoked by the IDE.

**Arduino IDE Log (lengthy)**

```
C:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM8 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xFF:m

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 "C:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM8
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.11s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: erasing chip
avrdude: reading input file "0x3F"
avrdude: writing lock (1 bytes):

Writing | ################################################## | 100% 0.04s

avrdude: 1 bytes of lock written
avrdude: verifying lock memory against 0x3F:
avrdude: load data lock data from input file 0x3F:
avrdude: input file 0x3F contains 1 bytes
avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...
avrdude: 1 bytes of lock verified
avrdude: reading input file "0xFD"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.04s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0xFD:
avrdude: load data efuse data from input file 0xFD:
avrdude: input file 0xFD contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...
avrdude: 1 bytes of efuse verified
avrdude: reading input file "0xDA"
avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.04s

avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xDA:
avrdude: load data hfuse data from input file 0xDA:
avrdude: input file 0xDA contains 1 bytes
avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...
avrdude: 1 bytes of hfuse verified
avrdude: reading input file "0xFF"
avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.04s

avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xFF:
avrdude: load data lfuse data from input file 0xFF:
avrdude: input file 0xFF contains 1 bytes
avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...
avrdude: 1 bytes of lfuse verified

avrdude done.  Thank you.

C:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM8 -b19200 -Uflash:w:C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:i -Ulock:w:0x0F:m

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 "C:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM8
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.11s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex"
avrdude: writing flash (32768 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_cmd(): programmer is out of sync
avrdude: stk500_cmd(): programmer is out of sync
avrdude: 32768 bytes of flash written
avrdude: verifying flash memory against C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:
avrdude: load data flash data from input file C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:
avrdude: input file C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex contains 32768 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.00s

avrdude: loadaddr(): (b) protocol error, expect=0x14, resp=0xc0

avrdude: stk500_paged_load(): (a) protocol error, expect=0x14, resp=0x10
avrdude: stk500_cmd(): protocol error
avr_read(): error reading address 0x7e00
    read operation not supported for memory "flash"
avrdude: failed to read all of flash memory, rc=-2
avrdude: stk500_disable(): protocol error, expect=0x14, resp=0xd1

avrdude done.  Thank you.

Error while burning bootloader.
```

**avrdude session (short)**

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

Note that when writing to the bootloader flash, using the "send" instruction, you have to supply the address as a "word" - i.e. 16bit address - hence 0x3C00. When usning the "read" instruction, the address is a "byte" (8 bit) address, hence 0x7800 - this is the same address.

Update: I have now managed to upload my original sketch to the application area of flash on this Nano using the "Sketch->upload using programmer" menu option of the Arduino IDE. So I do now have a useable Nano but I have still not solved my original problem i.e. this  Nano still does not have a bootloader. I would like to fix this problem becaue I am sure that I will want to update/modify my app int the future. So there is now an ancilliary question - i.e. is it possible to burn a  bootloader without erasing a pre-existing application? - Answer, I think is no because maybe you have to do a chip erase before writing to the bootloader area?

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

body:
Yay! - I now have a fully working Nano with new bootloader and application loaded using this.

I have done so much that I'm not sure what the original problem was but the final change was modifying the "programmers.txt" file such that "Arduino as ISP" entry was changed as follows;

    Original line;
    arduinoasisp.protocol=stk500v1

    Changed to;
    arduinoasisp.protocol=arduino

I did this because I noticed that the menu option "Upload using programmer" (which worked) invoked avrdude with the parameter "-c arduino" whereas the "burn bootloader" option used "-c stk500v1" (which was not working).

I can't pretened that I fully understand but I'm happy that this now works and that I have now learnt enough to know where to start looking if I get similar problems in the future.

I should also add that I would never have got here without the help of @timemage - who has helped a lot - many many thanks


message:
I am looking into putting sound files onto an Arduino Nano without a microSD card

I figured out how to install the sound onto the card from this site

<https://github.com/charliegerard/dev-notes/blob/master/arduino/wavFilesWithoutSdCard.md>

It says I need to use pin 11 on the Uno but would pin 11 on the nano work or not? I am getting these boards.

<https://www.amazon.com/gp/product/B0713XK923/ref=ox_sc_act_title_3?smid=A2WWHQ25ENKVJ1&psc=1>

Also, does anyone have good speaker suggestions, I'm going with these right now(<https://www.amazon.com/CQRobot-JST-PH2-0-Interface-Electronic-Projects/dp/B0738NLFTG/ref=sr_1_6?dchild=1&keywords=speakers+arduino]\&qid=1607285501&sr=8-6>)

I'm not sure if I'm giving enough information so just tell me if I need to provide you with more information.

body:
Uno and Nano uses the same Atmel MCU, so pin 11 is the same on both.

And a for the speakers, Arduino CAN'T driver 8ohms load! You need a amplifier.


message:
Connect RGB LED board to Arduino?

I'm trying to repurpose an RGB LED (pictured) and use an Arduino board I've just gotten to reprogram the lights. I'm very new to electronics engineering and I don't really know how to get started. How would I connect it to the Arduino? What kind of wire(s) would be best for soldering this to as well as connecting to the Arduino? Can this be programmed like any other LED?

Images:
 https://i.stack.imgur.com/u14Bd.jpg
 https://i.stack.imgur.com/2inQB.jpg

body:
Connect each of the 3 "L" wires to 3 separate digital IO pins of an arduino e.g. D8, D9, D10 via a resistor say 470 ohms but the value is not too critical. Connect VDD to the arduino +5v.

Use the arduino IDE write a sketch that configures pins 8 9 and 10 as outputs and then see what happens when you send these pins HIGH or LOW. Theres lots more you can do. Good luck.


body:
Given that the pin is labeled VDD, it's likely that the LEDs are common anode. (You'd hook the VDD pin to a positive voltage, and then connect the other pins to ground in order to light them.)

You really need to know the specs of the LEDs in order to calculate the size of the current limiting resistors.

Say your LEDs have a 1.2v forward voltage and can take 20 mA of current (.02 amps)

You'd use the formula R = (supply_voltage - LED_voltage)/current

so R = (5-1.2)/.020  = 190 Ω. Use the next higher value. (220 Ω for 20% resistors, the cheapest/most common kind you're likely to have access to.)

Try hooking each of the LEDs through a 220 Ω resistor to ground and seeing what you get. (Note that different colors of LEDs can have different forward voltages, so the forward voltage you use in the above calculation might be different for each LED.) If it barely lights, move down to the next-lower resistor value and try again. (150 Ω for 20% resistors.) If it's crazy-bright, or gets warm to the touch, use the next higher resistor value.

You'd then control the LEDs using PWM pins on your Arduino, and vary the duty cycle on 3 different output pins to vary the apparent brightness of the different colored LEDs. Note that since these LEDS appear to be common **anode** (Common power connection, and you switch the grounds to turn them on and off) the PWM values will be reversed. Setting a PWM pin to 0 will make that LED burn the brightest, and setting it to 255 will turn it off. That's because at 0, the pin is at 5V 0% of the time and connected to ground (which lights it) 100% of the time.