message:
Arduino Micro & Thin polymer lithium batteries

Is this battery:

>Polymer Lithium-ion Battery

>Model Number: PGEB014461

>https://www.powerstream.com/p/PGEB014461.pdf

Producing enough energy to power the following Arduino-micro project:

Battery (thin, flexible) to be worn. It will be safely encased (See below)

I would also be using a micro heart pulse sensor module:

>https://pulsesensor.com/

>https://cdn-shop.adafruit.com/product-files/1093/Pulse+Sensor+Data+Sheet-2018.pdf

 and a transmission module

(bluetooth, WiFi, IR, etc...  whichever is suggested or judged appropriate for an alpha project(Needs to be reliable for short range))

Edit: Clarifications about safety standards applied and "do not bend" comments...

> They do not have to be kept flat. The 0.5 mm cells can be flexed or bent into a cylinder, into a hat band, belt, etc.

As previously mentioned, the battery will be safely encased and will not go against these warnings...

>Do not immerse the battery in water or seawater, and keep the battery in a cool dry environment during stands by period.

>Do not use or leave the battery near a heat source such as fire or heater.

>When recharging, use the battery charger specifically for that purpose.

>Do not reverse the position (+) and negative (-) terminals.

>Do not connect the battery to an electrical outlet.

>Do not dispose the battery in fire or heat.

>Do not short-circuit the battery by directly connecting the positive (+) and negative (-) terminal with metal objects such as wire.

>Do not transport or store the battery together with metal objects such as necklaces, hairpins etc.

>Do not strike or throw the battery against hard surface.

>Do not directly solder the battery and pierce the battery with a nail or other sharp object.

body:
The [Arduino Micro](https://store.arduino.cc/arduino-micro) requires 5V. It runs at 16MHz, and you can't run at 16MHz at voltages below about 4V.

To run off a 3.7V battery you need an Arduino board that runs at 8Mhz, such as the ["3.3V Pro Micro" from Sparkfun](https://www.sparkfun.com/products/12587).

To know if your battery is suitable for your project you need to work out the hourly average current draw. That is the proportion of "active" and "inactive" times for each of the devices (transmission duty cycle for your transmitter, sleep times for your MCU, etc).  Until you know that you can't know the capacity (mAh) you need for your project to run for the desired amount of time between charges.

----

You can also drop the idea of an Arduino and branch out. A board that is probably tailor made for your project is the [Adafruit Feather M0 Bluefruit LE](https://www.adafruit.com/product/2995) which is designed to run from a Lithium Polymer batter (and even includes the charger) and has bluetooth built in.


sender: user

sender: assistant

body:
In a word, no. You need to provide an Arduino Micro with either > 6.5V unregulated into the barrel connector, or a regulated 5V supply directly to the 5V line.

You could use a buck/boost DC/DC converter to boost your 3.7V battery output to 5V and feed that directly into the 5V line on the Arduino (or better, feed it into the USB connector, since that will use the input switching on the Arduino.)

This one, for example:

https://www.banggood.com/DC-DC-3V-15V-to-5V-Fixed-Output-Automatic-Buck-Boost-Step-Up-Step-Down-Power-Supply-Module-p-1355829.html?gmcCountry=US&currency=USD&createTmp=1&utm_source=googleshopping&utm_medium=cpc_bgs&utm_content=frank&utm_campaign=pla-elc2-us-pc-0720&ad_id=368005069105&gclid=EAIaIQobChMI2pfb0Zj54wIVmeDICh2egQ_iEAQYAyABEgLVgvD_BwE&cur_warehouse=CN

Or this one: https://www.digikey.com/reference-designs/en/ac-dc-and-dc-dc-conversion/dc-dc-smps-single-output/1592?utm_adgroup=Converters&gclid=EAIaIQobChMIvM6-9pf54wIVxMDICh36XAxlEAAYASAAEgJsF_D_BwE

Or this one: https://www.adafruit.com/product/2190


message:
I´m trying to make a kind of videogame with Arduino UNO

it´s a school project, but I'm having some problems to create a menu selection. In the LCD, all the character are overwriting, I'm a beginer, so i dont have any idea of what i was doing wrong (ps.: sorry about my english, i'm a brazilian.
Here goes the code:
//A portable "atari" videogame project, including 3 games

    #include <LiquidCrystal.h>
    //define os pinos a ser utilizados no arduino uno,etc.
    #define btcima 9
    #define btbaixo 8
    #define bttiro 10
    #define menu 11

    LiquidCrystal lcd(7,6,5,4,3,2);

    int vel=100;
     int pxnave,pynave,pxaste,pyaste,pxtiro,pytiro;//px=posição x, py=posição y, etc
    bool game1,game2,game3,vtiro;//vtiro=variavel de tiro
    int pontos;
    int maxpontos=15;
    int vtela;
    byte nave[8]={B00000,B01100,B00110,B11111,B00110,B01100,B00000,B00000};
    byte asteroide[8]={B01110,B10111,B11111,B11101,B10111,B01110,B00000,B00000};
    byte explosao[8]={B10101,B00010,B11000,B10101,B01010,B10110,B01101,B10011};
    byte tiro3[8]={B00000,B00000,B11110,B11111,B11111,B11110,B00000,B00000};

    int      line[4] = {0,1,2,3},
             line_bk[4],
             index,
             menu_number = 0;

    boolean  menu_flag  = 0,
             enter_flag = 0,
             sub_menu = 0;

    void readButts();
    void list_menu();
    void menu_select();

    void setup()
    {
      //--configuração do menu--
     pinMode(menu,  INPUT_PULLUP);
      pinMode(bttiro, INPUT_PULLUP);

     lcd.begin (16,4);
     //lcd.setBacklight(HIGH);--apenas para lcd i2c
     lcd.clear();
     lcd.setCursor(0,0);
     lcd.print(">");

    pxnave=pynave=pyaste=pontos=pytiro=0;
    pxtiro=-1;
    pxaste=12;
    vtela=0;
    lcd.createChar(1,nave);
    lcd.createChar(2,asteroide);
    lcd.createChar(4,explosao);
    lcd.createChar(6,tiro3);
    //lcd.begin(16,2);
    //lcd.clear();
    game1=-false;
    game2=false;
    game3=false;
    vtiro=false;
    }

    void loop(){

      if(!sub_menu)
      {
       lcd.clear();
        lcd.setCursor(1,line[0]);
        lcd.print("1) NAVE: THE GaMe       ");
        lcd.setCursor(1,line[1]);
        lcd.print("2) PING PONG       ");
        lcd.setCursor(1,line[2]);
        lcd.print("3) lula & dilma      ");
        lcd.setCursor(1,line[3]);
        lcd.print("4) Creditos     ");

      }

      readButts();

      if(game1){
        lcd.clear();
        vtela=0;

      if (digitalRead(btcima)==1){
        pynave=0;

      }
      if(digitalRead(btbaixo)==1){
        pynave=1;
      }
      if(digitalRead(bttiro)==1){
        pxtiro=1;
        vtiro=true;
    pytiro=pynave;
      }
      pxaste-=1;
      desenhaNave(pxnave, pynave);
      desenhaAsteroide(pxaste, pyaste);
      if(vtiro){
        desenhaTiro3(pxtiro, pytiro);
        pxtiro+=1;
      }

      if(pxaste<0){
      pxaste=12;
      pyaste=random(0,2);
      }
      if(pxtiro>16){
        vtiro=false;
        pxtiro-=1;
      }
      if (((pxtiro==pxaste+1)&&(pytiro==pyaste))||((pxtiro==pxaste)&&(pytiro==pyaste))){
      vtiro=false;
      pxtiro=-1;
      desenhaExplosaoAsteroide(pxaste, pyaste);
      pyaste=random(0,2);
      pxaste=12;
      pontos+=5;
      if((pontos>=maxpontos)){
        game1=0;
        vtela=7;//rever
      }
    }
    if((pxnave==pxaste)&&(pynave==pyaste)){
    game1=0;
    desenhaExplosaoNave(pxnave, pynave);
    vtela=6;
    }

      delay(vel);

      }else{
        tela(vtela);
        if(digitalRead(bttiro)==1){
          reset1();
        }
      }
    }

      void readButts()
    {

       if(!digitalRead(menu))  menu_flag  = 0x01;
       if(!digitalRead(bttiro)) enter_flag = 0x01;

       if(digitalRead(menu) && menu_flag)
       {
           menu_flag = 0x00;
           list_menu();
           menu_number+=1;
           if(menu_number > 5) menu_number = 1;

       }

       if(digitalRead(bttiro) && enter_flag)
       {
          enter_flag = 0x00;
          sub_menu = !sub_menu;
          menu_select();

       }

    }

    void list_menu()
    {
      for(int i=4; i>-1; i--)
      {
         index = i-1;
         line_bk[i] = line[i];

         if(index < 1) line[i] = line_bk[i+4];

         else line[i] = line[i-1];

      }

    }

    void menu_select()
    {

        switch(menu_number)
        {
           case 1:
            vtela==0;
            game1= true;
            game2=false;
            game3=false;

                   break;
           case 2:
                vtela==4;
                  game1= false;
            game2=true;
            game3=false;
                   break;
           case 3:
               vtela==5;
               game1= false;
            game2=false;
            game3=true;
                   break;
           case 4:
                   vtela==8;
                   game1= false;
            game2=false;
            game3=false;
                   break;
           //case 5: ---pensar---

        } //end switch

    }
      void desenhaNave(int px, int py){
      lcd.setCursor(px,py);
      lcd.write(1);
    }
    void desenhaAsteroide(int px, int py){
      lcd.setCursor(px,py);
      lcd.write(2);
    }

    void desenhaTiro3(int px, int py){
      lcd.setCursor(px,py);
      lcd.write(6);
    }
    void desenhaExplosaoNave(int px, int py){
     lcd.clear();
      lcd.setCursor(px,py);
      lcd.write(4);
      delay(1000);
      lcd.clear();
    }
    void desenhaExplosaoAsteroide(int px, int py){
      lcd.setCursor(px,py);
      lcd.write(4);
      delay(1000);
      lcd.clear();
    }
    void reset1(){
      pontos=0;
      game1=true;
      vtela=0;
    }
    void reset2(){
      pontos=0;
      game2=true;
      vtela=0;
    }
    void reset3(){
      pontos=0;
      game3=true;
      vtela=0;
    }

    void tela(int cond){//0=jogo da nave 1=ganhou 2= perdeu 3= menu de seleção 4=jogo pingpong 5=jogo plataforma

    if(cond<1){
       lcd.setCursor(3,0);
         lcd.print("Nave: THE GAmE");
         lcd.setCursor(0,1);
    lcd.print("PRESSIONE START");
    }
    if(cond==6){
      lcd.setCursor(9,0);
      lcd.print("pts:");
      lcd.setCursor(13,0);
      lcd.print (pontos);
      lcd.setCursor(1,0);
      lcd.print("Perdeu");
    lcd.setCursor(0,1);
    lcd.print("PRESSIONE START");
    }
    if(cond==7){
      lcd.setCursor(9,0);
      lcd.print("pts:");
      lcd.setCursor(13,0);
      lcd.print (pontos);
      lcd.setCursor(1,0);
      lcd.print("Ganhou");
    lcd.setCursor(0,1);
    lcd.print("PRESSIONE START");
    }
    if (cond==3){
      sub_menu=true;
      lcd.clear();
    }

    if(cond==4)
    {
      lcd.setCursor(3,0);
      lcd.print ("Ping Pong");
      lcd.setCursor(0,1);
      lcd.print ("PRESSIONE START");

    }
    if (cond==5)
    {
      lcd.setCursor(3,0);
      lcd.print("Lula e Dilma");
      lcd.setCursor (0,1);
      lcd.print ("PRESSIONE START");
    }
    if (cond==8)
    {
      lcd.setCursor(3,0);
      lcd.print("Equipe LULA Livre");
      lcd.setCursor(0,1);
      lcd.print("Obrigado por Jogar");
    }
    }`enter code here`

body:
Probably since you set the cursor at a position in the middle of a line, only the new text is overwritten over the old text. But if there are some characters from the previous text, those will stay.

So the easiest way is to either clear the screen (if you can do the updating of the screen from a single place), or rewrite the entire line (and probably having to add spaces before/after the text you want to write to overwrite the old text).

Some other tips:

- Write comments and variable names in English (I know it's not your mother
language, but you can learn two languages at once, C and English).
- Align your code (make sure each { and } is aligned nicely; this will make life much easier and prevent mistakes.
- game1, game2 and game3 are booleans where only one can be true. For this the `enum` (enumeration) is invented. So make an enum `enum Game { game1, game2, game3 };` as a type, and declare a variable `Game currentGame = game1;`
- You use a switch statement for menu_number, but why not for cond?
- You use a lot of text, all text also takes up precious SRAM, where you only have 2,048 bytes of. If for each string you add F in front (thus e.g. F("MENU"); this will be stored only in Flash.


message:
Control speed of a dc motor with a 9v battery

[![enter image description here][1]][1][![enter image description here][2]][2]Problem:
I want to have a 9v battery that powers a dc motor. I want to control it with a bluetooth remote that has 3 buttons. 1st button is turn the motor with 1.5v, 2nd button is motor off and the 3rd button is full power (9v). Here is the problem normally I will change volt with my arduino using code, but it has a max voltage of 3.6v so I can't control the battery with the arduino. Also I would like the 9v battery to power the arduino and bluetooth module if that is possible, so I have only one battery that powers everything.

What I tried:
I found a lot of different things on the internet. Pwm, Tip120 transistor, L298N and it only confuses me more I have no idea where to start. Spend 8 hours looking for stuff and no step further.

Result:
I hope everything will work with a 9v battery and the bluetooth remote can switch between 3 different speeds.![enter image description here](https://i.stack.imgur.com/cIdkO.jpg)![enter image description here]

  [1]: https://i.stack.imgur.com/bYdwf.jpg
  [2]: https://i.stack.imgur.com/53jwk.png

body:
You have 3 problems here:

1. **Driver circuit the motor:** Since you only want to control the motors speed (not changing it's direction, where you would need a H-bridge like the L298N), a very simply driver circuit is sufficient. It can consist of a bipolar transistor or a MOSFET. The Arduino's digital output pin would set the transistor/MOSFET to conductive or non-conductive, which turns the motor on or off. The motor is connected (through the transistor/MOSFET) with the full supply voltage. For the needed circuit, you can google terms like "transistor as switch" or "MOSFET as switch". That should give you plenty of tutorials.

2. **Controlling the motor speed:** Normally the speed of a motor is not controlled through the voltage, since the speed behaves not linear with the voltage. Instead we use PWM (Pulse Width Modulation), where a squarewave voltage with a constant frequency is outputted at the Arduino's pin. To change the motor speed, you change the ratio between ON and OFF time of the pin (called "duty cycle"). So the motor basically get's turned on and off very fast. Since the motor is to slow, to follow the fast change, we are basically giving it small pushes very fast. If you only push half of the time (duty cycle 50%), the motor will run with about half the speed. In Arduino code you use `analogWrite(pin_number, x)` with `x` between 0 and 255 to output a PWM wave at the specified pin. Refer to the Arduino documentation for details.

3. **Powering the whole device:** First: A 9V block battery is actually like the worst choice for most cases (especially for devices with motors). It has a big series resistance, what means, that it cannot provide much current without dropping the voltage radically. They are meant for low-current devices. Better use multiple AA/AAA batteries in series.

    You didn't state, what Arduino you actually use, but from the description, it has to be one of the 3.3V boards, like the Arduino Pro Mini 3.3V version. Most Arduino boards also have a small voltage regulator on them. The input for it is mostly marked with `Vin`. Please refer to the documentation of your Arduino board, to check, which voltages are suitable for that voltage regulator. If you don't have a voltage regulator on your Arduino or your battery voltage doesn't fit, you have to provide the power through your own external voltage regulator. You should use a switching regulator (far more efficient, than linear regulators), which can provide the needed power (depending on the Arduino and the bluetooth device maybe between 50mA and 300mA, difficult to say generally) plus a bit overhead.

    You should then provide the motor with the full battery voltage, especially not through the Arduino's voltage regulator. Motors can draw quite much current. If you draw more current through a regulator, than possible, it will overheat, emergency shutdown or even burn out. If the battery voltage is not suitable, you should use a voltage regulator, that can safely provide the needed current.

---

Note: Depending on the size of the motor and it's load, you might want to add a flyback diode, that would safely let inductive reverse currents flow to ground, so that the inductive voltage is not piling up in the transistor/MOSFET.


message:
Measure revolutions per second with reed switch

I'm trying to measure speed of a fly wheel with a reed switch with one magnet (1 pulse per full rotation). I have an 100nf cap connected to switch to help with debounce.
<!-- language-all: lang-cpp -->

    #include <Arduino.h>

    int speedPin = 2; // switch is connected to pin 2
    int ledPin = 13;

    int debounceTime = 7;

    long speedPulseTime = 0;
    int speedPulseCount = 0;
    int speed = 0;
    long speedLastSample = 0;

    long serialLastReport = 0;
    int serialReportFreq = 40;

    void speedPulse()
    {
      long time = millis();
      if ((speedPulseTime + debounceTime) < time)
      {
        speedPulseCount++;
        speedPulseTime = time;
      }
    }

    void setup()
    {
      pinMode(ledPin, OUTPUT);

      pinMode(speedPin, INPUT_PULLUP);     // Set the switch pin as input
      attachInterrupt(digitalPinToInterrupt(speedPin), speedPulse, HIGH);

      Serial.begin(115200);
      Serial.println("Ready...");
    }

    void loop()
    {
      long time = micros();
      if (speedPulseCount >= 4 || (speedLastSample + 1500000) < time)
      {
        detachInterrupt(speedPin);
        int tempSpeed = 1000000 / ((time - speedLastSample) / speedPulseCount);
        if (tempSpeed < 0)
        {
          speed = 0;
        }
        else
        {
          speed = tempSpeed;
        }

        //reset sample
        speedLastSample = time;
        speedPulseCount = 0;
        attachInterrupt(digitalPinToInterrupt(speedPin), speedPulse, HIGH);
      }

      if ((serialLastReport + serialReportFreq) < millis())
      {
        Serial.print(millis());
        Serial.print(",");
        Serial.println(speed);
        serialLastReport = millis();
      }
    }

Here the code I have so far. The problem I have it jumps around a little bit. What could I change to ensure more accurate readings?

body:
It sounds like occasional "misses". Possible causes include:

 - the magnet passing far enough from the reed switch to "only just" trigger it [narrow the gap.];
 - the magnet's passage being too short for the reed switch/capacitor to respond [use a wider magnet or move closer to the center of rotation];
 - Too much capacitance [reduce it or debounce in software];

Update:

> Would it be better to debounce in software and what would be the best way to do it.

If you have an oscilloscope available, you could look at the raw switch signal (no capacitor) to find out how long it bounces. I'm guessing that it will be around 10ms for such a small switch. If the entire [make/break/make/break....] sequence takes less than 50% (being conservative) of the wheel rotation time (1/max_RPS), you can probably count the first pulse and ignore the switch for (0.5/max_RPS), or 1/2 of the fastest rotation. You appear to be doing something like this already. If you want to be a little bit more rigorous, you might do:

    see a HIGH;
    ignore switch for debounce_time;
    if still HIGH,
       count++;

Also, don't forget that variables shared between your Interrupt function and the main-line code need to be:

 1. declared as `volatile`, to tell the compiler not to expect that this variable has the value it had last time the mainline code read it; and

 2. Turn interrupts off briefly while reading or writing such a variable (if it is multi-byte) in your mainline, to prevent it being changed by the interrupt function between byte-reads/writes by the mainline.


message:
Ethernet.begin() conflicts with build-in LED on Arduino Nano

I have Arduino Nano "clone" which I would like to use with Ethernet ENC28J60 shield. I have noticed that when I include/use `UIPEthernet.h` library, build-in LED does not work properly. I have written the following sketch which I have uploaded to Arduino and run both *with* and *without* Ethernet shield with the same result: LED is not blinking. Once I comment out the line `Ethernet.begin(mac)`, LED starts blinking just fine.

Is there any way to overcome this conflict?

```
#include <UIPEthernet.h>

EthernetClient ethClient;

uint8_t mac[6] = { 0x90, 0xA2, 0xDA, 0x0D, 0xE2, 0xCD };

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

  // If this line is commented, LED starts blinking:
  Ethernet.begin(mac);

  pinMode(LED_BUILTIN, OUTPUT);

  Serial.println(F("setup() done."));
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
}
```

[![Arduino Nano + Ethernet ENC28J60 shield][1]][1]

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

body:
No, you can't.

The LED is on pin 13. Pin 13 is the clock pin for SPI. The ENC28J60 is an SPI device.

You either have control over pin 13, or you have SPI. You can't have both.


message:
Wifi module is not sending the data properly

I wrote a programm in c++ for Arduino Uno which is connected to a wifi module (ESP8266) and sends the calculated data to a server through wifi-Module with a http post request.

The problem is that the programm sends the data only 2 times throuth http and then it stops. I mean it goes to the loop but the http-send-request is not successful.

here is my program:

    #include <MySignals.h>
    #include "Wire.h"
    #include "SPI.h"

    unsigned long currentMillis;

    const unsigned long period = 10000;

    int a=1;

    void setup()  {

    Serial.begin(115200);

    MySignals.begin();
     void httpBase(int); //Enable WiFi ESP8266 Power -> bit1:1           >      bitSet(MySignals.expanderState, EXP_ESP8266_POWER);
     MySignals.expanderWrite(MySignals.expanderState);

     MySignals.initSensorUART();

     MySignals.enableSensorUART(WIFI_ESP8266);   delay(1000);

    // Checks if the WiFi module is started   int8_t answer =
    sendATcommand("AT", "OK", 6000);   if (answer == 0)   {
    MySignals.println("Error");
    // waits for an answer from the module
    while (answer == 0)
    {
      // Send AT every two seconds and wait for the answer
      answer = sendATcommand("AT", "OK", 6000);
    }   }   else if (answer == 1)   {

    MySignals.println("WiFi succesfully working!");

    if (sendATcommand("AT+CWMODE=1", "OK", 6000))
    {
      MySignals.println("CWMODE OK");
    }
    else
    {
      MySignals.println("CWMODE Error");

    }

    //Change here your WIFI_SSID and WIFI_PASSWORD
    if (sendATcommand("AT+CWJAP=\"********\",\"****\"",
    "OK", 20000))
    {
      MySignals.println("Connected!");
    }
    else
    {
      MySignals.println("Error");

    }   }

     }

    void loop()  {

    delay(10);  // wait for a second

    a=a+1;

    httpBase(a);

     }

     void httpBase(int gsr) {

     String data="value1="+String(gsr); //String
     data="a="+String(gsr);
     String postString="POST /ardu.php HTTP/1.1\r\nHost:
     192.168.178.36\r\nContent-Type: application/x-www-form-
     urlencoded\r\nContent-Length:
     "+String(data.length())+"\r\n\r\n"+data+"\r\n"; char* post = new
     char[postString.length()+1]; strcpy(post,postString.c_str());

     String inf = "AT+CIPSEND="+String(strlen(post)); char *info = new
     char[inf.length() + 1]; strcpy(info, inf.c_str());

     delay(1500); sendATcommand("AT+CIPMUX=0", "OK", 3000);

     //sendATcommand("AT+CIPSERVER=1","OK",1000);

     sendATcommand("AT+CIPSTART=\"TCP\",\"192.168.178.36\",80", "OK",
     2000);

     sendATcommand(info, "OK", 2000); sendATcommand(post, "OK", 2000);

     sendATcommand("AT+CIPCLOSE", "OK", 3000);

     delay(10000); }

    int8_t sendATcommand(char* ATcommand, char* expected_answer1,
    unsigned
    int timeout) {

    uint8_t x = 0,  answer = 0;   char response[500];   unsigned long
    previous;

    memset(response, '\0', sizeof(response));    // Initialize the
    string

    delay(100);

    while ( Serial.available() > 0) Serial.read();   // Clean the
    input
    buffer

    delay(1000);   Serial.println(ATcommand);    // Send the AT   command

     x = 0;   previous = millis();

     // this loop waits for the answer   do   {

     if (Serial.available() != 0)
     {
      response[x] = Serial.read();
      x++;
      // check if the desired answer is in the response of the module
      if (strstr(response, expected_answer1) != NULL)
      {
        answer = 1;
        //MySignals.println(response);

      }
    }
    // Waits for the asnwer with time out   }   while ((answer == 0) && ((millis() - previous) < timeout));

     return answer; }

the output is:

    AT
    WiFi succesfully working!
    AT+CWMODE=1
    CWMODE OK
    AT+CWJAP="*******","******"
    Connected!
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80
    AT+CIPSEND=127
    POST /ardu.php HTTP/1.1
    Host: 192.168.178.36
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 8

    value1=2

    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80
    AT+CIPSEND=127
    POST /ardu.php HTTP/1.1
    Host: 192.168.178.36
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 8

    value1=3

    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80
    AT+CIPSEND=127
    POST /ardu.php HTTP/1.1
    Host: 192.168.1
    ⸮⸮6⸮
    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80
    AT+CIPSEND=1
    ⸮
    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80
    AT+CIPSEND=1
    ⸮
    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80
    AT+CIPSEND=1
    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80
    AT+CIPSEND=1
    ⸮
    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80

    ⸮
    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80

    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80
    2

    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80
    2

    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80
    ⸮
    ⸮
    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80

    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80

    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80

    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80

    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80

    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80

    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80

    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80

    AT+CIPCLOSE
    AT+CIPMUX=0
    AT+CIPSTART="TCP","192.168.178.36",80

    AT+CIPCLOSE

    ....

body:
Hello Navid and welcome to the community. Buddy your code is extremely hard to read.

Now let me see if I can help you archiving your goals. First of all try not to use AT commands at all, you have an ESP8266, that's not just a Wi-Fi module but also a really good micro controller you can actually use, code for it (even using Arduino IDE). I would HIGHLY suggest you to use it if you wanna do POST and GET methods. AT commands do work, but they are not as reliable as they should be, and with your code written in that format, its going to be difficult to help you buddy.

Now if you are calling it a Wi-Fi "Module" I can presume it's a ESP01 you are talking about (those ESP8266 with no usb connection), you can find on the internet a few tutorials on how to upload code to them using your arduino uno's FTDI chip (basicly grounding the reset pin of your Arduino).

With that been said, hopefully you can split your code into those 2 micro controllers if you really need to use the Arduino uno, and do a few functions to trigger based on Serial communication on both sides. I know it sounds a lot of work, but trust me, that's by far the easiest and more reliable solution you will find.

And let me give you an bonus tip, next time you wanna work with Wi-Fi applications, get yourself a Wemos D1, they are small easy to use, reliable, have GPIO's as well as ADC and PWM pins, you can pretty much put your Arduino on a shelf for 4 dollars.

And please remember Navid, code syntax is really important.


message:
I need help programming my arduino in assembly

I am new to using an Arduino and I am trying to program my it to implement a ﬂashing pattern with two LEDs. When one LED is oﬀ, the other must be on. The program needs to be done in assembly. I have a working program in c++ but I need to convert it to assembly. I have an Arduino UNO ATmega 328p

Here is my c++ program:

     const int led = 13;
     const int led2 = 12;

     void setup() {
        pinMode(led, OUTPUT);
        pinMode(led2, OUTPUT);
     }

     void loop() {
       digitalWrite(led, HIGH);
       delay(1000);
       digitalWrite(led, LOW);
       digitalWrite(led2, HIGH);
       delay(1000);
       digitalWrite(led2, LOW);
     }

body:
Try this method to convert your sketch

https://sourceforge.net/projects/arduino-to-assembly-converter/


body:
In the case, that this is a school assignment and you actually have to program directly in assembler, you probably don't want to directly convert your C++ sketch. It will generate way more assembler code, than is really necessary for alternatively blinking two LEDs (for example `digitalWrite()` contains not only the actual writing to the corresponding pin registers, but much more code), and it will be obvious, that you didn't write it yourself.

In this case you have to go the harder way. You should start by looking into existing assembler blink programs. Via google I found [this series][1] at github gist, which also has a blink example. You can derive some of the program from there. Also there is a list of assembler command with descriptions.

In the end everything, that is done on a microcontroller, comes down to reading and writing Special Function Registers (SFR). The pins are organized in ports with 8 (or sometimes less) pins. Every port is then represented by one byte in the corresponding SFR (1 bit per pin). For changing the direction of a pin between output and input, the DDRX registers are used (where X is the character of the port used). For actually setting the output state (or enabling/disabling the internal pullup resistor) the PORTX registers are used. The current state (LOW or HIGH; while input or output) can be read from the PINX registers. For these things, the datasheet of the microcontroller (here the Atmega328P) is a must read (meaning: not completely, but enough to feel comfortable getting needed information from it).

Learn how to set single bits in a byte (in a SFR). You can learn it from the linked example, or from tutorials over the internet. Then write code to write the correct value to the corresponding DDRX bits to set the LED pins to output. Then you can use this to write a value to an output pin.

For blinking you need a timer. If you google for something like "arduino assembler blink" you will also find an example, which configures the timer for blinking. Basically it involves setting the Timers SFRs to the wanted values. If you don't want to do this, you might get away with executing a high number of "nop" operations (which does nothing). You would have to write a loop, that will execute a high number of times. ( very "nop" will need 1 clock cycle - credits to Ghanima for searching that up). The clock runs on 16MHz, so you can do the math to calculate, how long 1 "nop" needs, and then calculate, how many of them you need).

  [1]: https://gist.github.com/mhitza/8a4608f4dfdec20d3879


body:
It "needs" to be done in assembly as an assignment, right? Otherwise you would "want to learn" assembly.

What I suggest you do is change the C program to use port manipulation, for example:

```c++
 void setup() {
   DDRB |= 0b00100000;  // D13 to output mode
 }

 void loop() {
   PORTB |= 0b00100000;  // turn on D13
   delay(2000);
   PORTB &= ~0b00100000;  // turn off D13
   delay(2000);
 }
```

Now at least you are flashing D13 without using the rather complex digitalWrite and pinMode library functions. The delay is another issue I'll leave you to investigate however [my page about timers](http://www.gammon.com.au/timers) might help you.

Now you can disassemble the generated code to see what the compiler generated in assembler and use that to help you learn how to do it.

For example, when I compiled the above code and turned on "verbose compiling" I found the location of the generated .elf file.

Running avr-objdump on that file (like this):

```bash
avr-objdump -S /tmp/build436d41bc5c0da39afe99cd9c05ac272a.tmp/sketch_aug13a.ino.elf > temp.txt
```

Gives me the following code for "loop":

```none
00000094 <loop>:
  94:   2d 9a        sbi 0x05, 5 ; 5
  96: 60 ed        ldi r22, 0xD0 ; 208
  98: 77 e0        ldi r23, 0x07 ; 7
  9a: 80 e0        ldi r24, 0x00 ; 0
  9c: 90 e0        ldi r25, 0x00 ; 0
  9e: 0e 94 c5 00  call 0x18a ; 0x18a <delay>
  a2: 2d 98        cbi 0x05, 5 ; 5
  a4: 60 ed        ldi r22, 0xD0 ; 208
  a6: 77 e0        ldi r23, 0x07 ; 7
  a8: 80 e0        ldi r24, 0x00 ; 0
  aa: 90 e0        ldi r25, 0x00 ; 0
  ac: 0c 94 c5 00  jmp 0x18a ; 0x18a <delay>
```

What we basically see there is one "sbi" instruction to turn the LED on and one "cbi" instruction to turn it off.

As for the rest, well I don't want to do your homework for you. Have fun learning how to program in assembler!


body:
There are also a couple of ways of including assembler code right inside your Arduino IDE.

By including the assembler in the Arduino IDE, the assembler source is assembled and linked into your project and uploaded to your Arduino from within the IDE - just like any other program.

This makes it easy to get started with Assembler while still retaining the familiarity of the Arduino IDE. Why? Because since you can mix C / C++ code with the Assembler code this means that you do not have to write a complete assembler program that manages all of the hardware initialisation nitty gritty - you can start small and expand your assembler as and when you you feel comfortable or need to do so. Like the example below, you can start with just two lines of assembler that fit into a larger program if you wanted to.

Following are the instructions for creating a mixed C / Assembler program in Arduino. I also give an example of how to pass parameters and get a result from an Assembler function.

To create a mixed C + Assembler program create a new project in the Arduino IDE (call it whatever you like) and enter the following code into the IDE:

```C++
extern "C" {
  void myInit();
  void myLoop();
  int myAdd(int, int);
}

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

  // This is just a dummy example showing inline assembler using the asm "directive"
  // Refer to this tutorial, or similar, for details of inline assembler in Arduino:
  // https://ucexperiment.wordpress.com/2016/03/11/arduino-inline-assembly-tutorial-5-2/
  asm(
    "ldi   r26,42"
  );
}

void loop() {
  myLoop();

  int ans = myAdd(240, 25);
  delay(ans);
  Serial.print("Answer: ");
  Serial.println(ans);
  delay(1000);
}

```

Next click the little down arrow in the top right corner of the IDE as per the following diagram and select "New Tab":

[![Arduino IDE - Add New Tab][1]][1]

Enter `myFunctions.S` as the name of the new tab as shown below. Note that the name does not really matter, but, it **must end with the extension .S** and the "S" must be a capital "S" not a lowercase "s":

[![Arduino IDE - Name the New Tab][2]][2]

Paste the following code into the `myFunctions.S` tab.
```ASM
; Example assembler file that blinks an LED.
; and adds two numbers together.

#define __SFR_OFFSET 0

#include "avr/io.h"

// Declare the three function entry points as "globals"
.global myInit
.global myLoop
.global myAdd

myInit:
  sbi   DDRB,5      ; Set PB5 (the built in LED on Arduino Uno) as output
  ret

myLoop:
  ldi   r20,250     ; Set the delay duration in ms. Maximum value is 255.
  call  myDelay_ms
  sbi   PORTB,5     ; Set PB5 HIGH
  ldi   r20,250     ; Delay for another 250 ms.
  call  myDelay_ms
  cbi   PORTB,5     ; Set PB5 LOW
  ret

; These symbols are for internal to this assembler file's use only.
; They are private because they are not listed as a global symbol
; Also, they do not conform to the subroutine calling conventions used
; by the Arduino IDE's compiler. i.e. they are not compatible with
; being called directly from C. However, since we are calling them from
; our own assembler, we can (almost) make up any calling convention we like.
myDelay_ms:
  ; Delay about r20*1ms. Destroys r20, r30, and r31.
  ; One millisecond is about 16000 cycles at 16MHz.
  ; The basic loop takes about 5 cycles, so we need about 16,000,000 / 5 = 3000 loops.
  ; NB: most instructions are 8 bit, so we load the 16 bit counter using
  ;     two 8 bit loads.
  ldi   r31, 3000>>8    ; high(3000)
  ldi   r30, 3000&255   ; low(3000)
delaylp:
  sbiw    r30, 1        ; Decrement our 1 ms counter (this instruction operates on a 16 bit value in R31:R30).
  brne    delaylp       ; If R30 is non zero, loop back
  subi    r20, 1        ; Otherwise we have passed 1 ms so, decrement the high order byte of our counter.
  brne    myDelay_ms    ; If this is non zero, loop back.
  ret                   ; Otherwise, we have counted down from R20 * 3,000 - so return.

; Function to add two integers and return an integer.
; For few parameter functions, the Arduino IDE uses registers built into the
; Microcontroller (i.e. the CPU) to exchange data between subroutine caller and callee.
; Return values are as follows:
;   - single Byte (e.g. char, byte) R24 only
;   - double Byte (e.g. int)        R25:R24 (R25 is the high order byte)
;   - quad Byte   (e.g. long)       R25:R24:R23:R22 (R25 is the high order byte)
; Parameters are passed in similar ways starting with R25 and working down, but exactly
; what is where will depend upon the parameter types.
; Refer to this tutorial for more details or the AVR compiler documentation from ATMEL
;   https://ucexperiment.wordpress.com/2016/04/02/arduino-inline-assembly-tutorial-12-functions/
; In our case, a is passed in R25:R24 and b is passed in R23:R22
myAdd:
  add     r24, r22      ; Add the low order bytes
  adc     r25, r23      ; Add the high order bytes PLUS any value carried from the previous addition.
  ret                   ; The result is in R25:R24 which is where it needs to be to pass back to the C code.

```

Upload it to your Uno, start the serial monitor and you should see some sum's being ouput (well one sum continuously being output). Feel free to change the values in the main loop to see different results.

I've put loads of comments and a few references into the code to get you started on the path to finding more information.

One other reference that will be useful if you are going to mess with assembler on the UNO is the ATMega-328P reference manual/datasheet (all 662 pages of it) which you can obtain from [Microchip's ATmega328p reference page](https://www.microchip.com/wwwproducts/en/ATmega328p). There are a whole bunch more useful resources there that will likely come in handy from time to time.

  [1]: https://i.stack.imgur.com/BSEtN.png
  [2]: https://i.stack.imgur.com/uEL0b.png


message:
SparkFun BasicAHRS_I2C giving unstable readings

**SparkFun BasicAHRS_I2C giving unstable readings.**

I am using the SparkFun Arduino Sketch from [here][1].

It is giving me these results:

    X-acceleration: 91.43 mg Y-acceleration: 249.51 mg Z-acceleration: 1042.05 mg
    X-gyro rate: -0.549 degrees/sec Y-gyro rate: 0.557 degrees/sec Z-gyro rate: 1.595 degrees/sec
    X-mag field: -164.35 mG Y-mag field: -240.16 mG Z-mag field: -20.73 mG
    Temperature is 27.9 degrees C

and then the next result (when MPU9250 is still) is:

    X-acceleration: 91.49 mg Y-acceleration: 252.75 mg Z-acceleration: 1039.49 mg
    X-gyro rate: -0.076 degrees/sec Y-gyro rate: -0.130 degrees/sec Z-gyro rate: -0.008 degrees/sec
    X-mag field: -175.07 mG Y-mag field: -222.24 mG Z-mag field: -27.64 mG
    Temperature is 27.9 degrees C

Notice how the temperature has remained constant, acceleration has remained constant (although im not why there is a reading if the MPU9250 is stationary) and the mag field is fairly close. However, the Gyro values are not close.

Could I have a bad MPU9250?

I am using the Mega.

Edit: Added a complementary filter from [here][2], however they have not added a comp filter for the z value as can be seen from my screenshot of the serial monitor:

[![Serial Monitor screenshot][3]][3]

I think this is because they have the MPU6050 and not the MPU9250. I believe the MPU9250 has the magnetometer which can be used to 'help' the drift?

How could I use the magnetometer to help counter the drift?

End goal: rotate a gameobject in unity with the MPU9250 with minimal drift and maximum accuracy.

  [1]: https://github.com/sparkfun/SparkFun_MPU-9250_Breakout_Arduino_Library/blob/master/examples/MPU9250BasicAHRS_I2C/MPU9250BasicAHRS_I2C.ino
  [2]: https://www.geekmomprojects.com/gyroscopes-and-accelerometers-on-a-chip/
  [3]: https://i.stack.imgur.com/zLDYU.png

body:
If you haven’t noticed the difference in the two is minuscule.
For example, the change in degree is <1. Also the acceleration is measured in g’s which is acceleration due to gravity. The data says the measures are in mg which is 0.01g.
This is normal with accelerometers and all sensors when they pick up residual voltage from random vibrations or other sources of noise. It also could be with the error margin within SparkFun’s product since the product is more on the lower end of quality which once again is normal.
TLDR: everything is working fine.


body:
The values seem fine to me. Generally these MPU chips are really noisy, that is totally normal. Ti really use the data to the the current orientation, you have to use a filter to combine the data from accelerometer and gyroscope.

There are multiple possible filters, that can help. The easiest one to implement is a Complementary filter. It gives you pretty good results. You should be able to find corresponding tutorials on the web.

---

The code from your link does not use a complementary filter for the z axis. In the comment it says, that the accelerometer doesn't provide z angle data, and that is correct. Since gravity always goes down, you cannot distinguish the angles around that axis.

But - as you already stated - you can use the magnetometers data for this. But you will need the inclination angle of the earths magnetic field (the angle between ground and field vector).  You can google the inclination angle for your place and use it as constant. But most likely you will want to use the device inside of buildings. The magnetic field can be very disturbed there due to much steel nearby. Thus it is better to do a calibration step before use, while the device lies flat on the ground.

When you have calculated the angle around the z axis from the magnetometer data, you can use it in a complementary filter, like it was done in the linked code with the accelerometer data.

Note: Due to all the steel, the inclination angle does not have to be constant, when moving around in a building. So this is better for use inside a small space range.


message:
Possible to put the ESP8266 in bootloader mode without a FTDI?

I am trying to upload something directly to the ESP8266 using the ESP8266 IDE.
I have configured the ESP8266 to communicate at 9600 using UART_DEF and I have set the ESP8266 IDE at 9600. I see some tutorials that say to use a FTDI but I only have a [Serial to TTL cable][1] (note it even says at the bottom that it's not good for Arduinos :( ) and  am making the following connections:

 - ESP8266 RX - TTL cable TX
 - ESP8266 TX - TTL cable RX
 - ESP8266 GND - common GND
 - ESP8266 VCC - External 3.3V
 - GND from External 3.3V - common GND
 - ESP8266 GPI0 (through a 10k resistor) - common GND
 - ESP8266 GPI2 (through a 10k resistor) - External 3.3V
 - EPS8266 CH_PD - External 3.3V (sorry, that was wrong before)

However, when I upload that sketch I get an error that the board cannot be found. I have read online that the ESP has some bootloader mode that needs to be activated but haven't found great instructions on how to do that. Any advice would be appreciated.

FYI I also have an Uno if that is any help. I have communicated with the ESP8266 through the Uno before (connecting the Uno reset to ground) .

  [1]: https://www.adafruit.com/product/954

body:
The cable you point to is fine for programming the ESP8266. The only reason it's not "good" for an Arduino is the lack of a DTR signal to trigger a reset for you - which you can do manually anyway and still use it for an Arduino (if your reactions are fast enough).

You have no such problem with the ESP8266. Once you have it in bootloader mode it stays in bootloader mode until you tell it to exit bootloader mode.

First make sure that the ESP8266 is actually set up to run properly. That means:

* Connect CH_PD to 3.3V, not GND, through a pull-up resistor.
* Connect GPIO0 to 3.3V via a pull-up resistor.
* Connect RST to 3.3V via a pull-up resistor.

Then for simplicity of programming:

* Connect a button between RST and GND
* Connect a button between GPIO0 and GND

To enter bootloader mode simply hold the GPIO0 button in, tap the RST button, then release the GPIO0 button.  When you have successfully uploaded your firmware just tap the RST button to exit bootloader mode.

ESP8266 boards with a built-in USB interface usually use *both* the DTR *and* the RTS pins to control both those buttons virtually. That's somewhat complex to arrange for an external USB to TTL UART adaptor, so it's simpler to just press the buttons manually.

----

[Here's](https://www.allaboutcircuits.com/projects/breadboard-and-program-an-esp-01-circuit-with-the-arduino-ide/) a link to a website that details the circuit and operation using an ESP-01 as an example.


message:
arithmetic operation outcome differs from the expected outcome

I am writing a function
```
void Sound_Play(int frequency,int millisec)
```
A part of this function is:
```
  counting=(millisec*frequency/1000);  //counting is type int
  Serial.println((String)"millisec="+millisec+" frequency="+frequency+" (millisec*frequency/1000)="+(millisec*frequency/1000)+" counting set to="+counting);
```

But when I call the function with millisec=500 and frequency=220, the result on the Serial Monitor is:
```
millisec=500 frequency=220 (millisec*frequency/1000)=-21 counting set to=-21
```
Shouldn't counting should be 110 instead.I tried casting the result to int but in vain. What am I doing wrong and how to correct it?
Thanks!
Bhuvnesh

body:
Once again an example to `Why should I learn C/C++ first before learning Arduino`.
The main point here is: know your data types.

Your calculation `millisec*frequency/1000` would work if it was a compile time constant that is evaluated by the pre processor. In any other case this is a runtime value and so the limitations of the datatype apply.

Unless stated otherwise I assume your variables `millisec`, `frequency` and `counting` are of type `int`. `int` has a platform specific width. On Arduino this is 16-bit. (Other platforms have other widths)

It is also signed, that is why it can hold values between -32768 and 32767.
You calculation `millisec*frequency` evaluates to `500 * 220 = 110000` which is many times larger than the value that can be represented.

You can do two things:

* Use `long` which is 32-bit on Arduino. But actually I'd prefer to use a type with an obvious width. As you don't seem to need negative values I'd prefer `uint32_t`.

* If milliseconds is a constant, you can make it smarter by reducing your calculation to a division by two (or better a single right shift).


message:
I think I just bricked my Arduino. Any ideas how?

I think I have a short circuit in my Arduino Uno R3. The symptoms are:

* It does not seem to be responding as before.

* The orange "L" LED does not blink on boot-up, but just stays on continuously.

* If I plug in a 12V source, then the voltage between the 5V and GND pins starts out around 5V, but then starts dropping rapidly. In the meantime, the underside of the board heats up a lot. If I plug in the USB source, the voltage between the 5V and GND pins stabilizes at around 4.28V ... but again, nothing seems to work.

* After all this, I also checked continuity between the 5V and GND pins, and heard a beep. However, subsequent reading told me that this is not a reliable (or well-advised) test.

It seems like I have a short on my Arduino, right?  Any idea of how this could have happened?  I can only think of the following possibilities:

* I was running the Arduino off a lead-acid 12V battery. At some point, the negative terminal wire disconnected and there was some sparking at the battery when I reconnected it (the pattery was also powering other things). Could this have damaged the Arduino?

* I am using the Arduino to run 3 IR LED . To minimize wiring, I had wires these LED in series, rather than in parallel, which (at least at first) seemed to work. Is there any possibility this would have damaged it?

Thanks for any help.

body:
> If I plug in a 12V source, then the voltage between the 5V and GND pins starts out around 5V, but then starts dropping rapidly. In the meantime, the underside of the board heats up a lot. If I plug in the USB source, the voltage between the 5V and GND pins stabilizes at around 4.28V ... but again, nothing seems to work.

That sounds like the LDO is overheating and going into thermal shutdown.

> After all this, I also checked continuity between the 5V and GND pins, and heard a beep. However, subsequent reading told me that this is not a reliable (or well-advised) test.

If it's just a brief "pip" then it's just a capacitor charging or discharging. To qualify as a short it has to be a continuous "beeeeeeeeeeeeeeeeeeeeeee".

> I was running the Arduino off a lead-acid 12V battery. At some point, the negative terminal wire disconnected and there was some sparking at the battery when I reconnected it (the pattery was also powering other things). Could this have damaged the Arduino?

It sure could. If other things are connected both to the battery -ve and the Arduino then the power could have passed through the Arduino in many strange ways killing things internally.

Chances are it's dead, yes. It may just be the main MCU which (if it's a DIP version) you could pop off and replace (with one with the bootloader already installed). But there's no guarantee it's only that chip that's gone. The USB chips are also a common failure point, especially the cheap Chinese CH340G.

In the long run it's safer just to replace the entire board unless you've got plenty of spare components and the skills to diagnose and replace them as needed.


body:
See my answer [here](https://arduino.stackexchange.com/a/67491/10794). A 12V battery doesn't necessarily provide you with 12V any more than a 1.5V battery provides 1.5V.

See [here](https://www.emarineinc.com/Marine-Batteries-Maintenance-101) for example. A 12V lead-acid battery may well provide 12.7V which is *out of spec* for the Uno.

See the [page about the Uno](https://store.arduino.cc/usa/arduino-uno-rev3).

You have too much voltage going into the voltage regulator, it tries to dissipate it, it gets hot and either shuts down or fails.

I suggested in the answer above to use a buck converter to down-convert the voltage, and my answer (which was accepted) said that "it is working like butter".


message:
STM32 "Blue Pill" Serial.print freezes Serial Monitor

I am having difficulties when printing any type of variable using the Serial.print(ln) command.

The Serial Monitor becomes inactive after printing for approximately 7 - 15 times.

I currently have the STM32 Blue Pill Board, running Mac OS Mojave and Arduino IDE v 1.8.9

```
void setup() {
  Serial.begin(9600);
  pinMode(PC13, OUTPUT);

}

void loop() {
  float raw = analogRead(PA0);
  float voltage = (raw * 3.3) / 4096;
  Serial.println(voltage);
  delay(500);
}
```

body:
Printing a float should work (at least with an Arduino), but to test if it cannot handle it correctly, I suggest you convert the float to a string (e.g., with the `C` function `ftoa`, and print the characters one by one or as a string.

Since this C function is not available on Arduino, use the function implementation of [this article][1], credits to Martin Waller:

    char *ftoa(char *buffer, double d, int precision) {

     long wholePart = (long) d;

     // Deposit the whole part of the number.

     itoa(wholePart,buffer,10);

     // Now work on the faction if we need one.

     if (precision > 0) {

      // We do, so locate the end of the string and insert
      // a decimal point.

      char *endOfString = buffer;
      while (*endOfString != '\0') endOfString++;
      *endOfString++ = '.';

      // Now work on the fraction, be sure to turn any negative
      // values positive.

      if (d < 0) {
       d *= -1;
       wholePart *= -1;
      }

      double fraction = d - wholePart;
      while (precision > 0) {

       // Multipleby ten and pull out the digit.

       fraction *= 10;
       wholePart = (long) fraction;
       *endOfString++ = '0' + wholePart;

       // Update the fraction and move on to the
       // next digit.

       fraction -= wholePart;
       precision--;
      }

      // Terminate the string.

      *endOfString = '\0';
     }

       return buffer;
    }

  [1]: https://forum.arduino.cc/index.php?topic=63721.0


body:
Have you made sure to modify the board before using it?

[This page][1] mentions at least one resistor that you have to replace for the USB to "work".

> The USB standard requires a 1.5 kΩ pullup resistor on D+, but this board is known to have a wrong value (R10 on the board). It ships with either a 10 kΩ resistor or a 4.7 kΩ resistor, but it should be replaced with a 1.5 kΩ resistor, or put an appropriate resistor value (e.g 1.8 kΩ) in between PA12 and 3.3V.
>
>It is also true that some PCs are tolerant of incorrect value so, before you change the resistance, you can try if it works in your case.

I have had issues with bluepill boards myself in the past, but never had an issue like yours after fixing the resistor. (before that, I couldn't even flash the bootloader)

Try printing other things with the board, and see if there's any pattern to it cutting out. e.g. a string over and over again, or the same float over and over again.

Try different baudrates, or even SoftwareSerial to another board.

  [1]: https://stm32duinoforum.com/forum/wiki_subdomain/index_title_Blue_Pill.html


message:
ESP32 Pins won't fit in solderless breadboard

I bought an Adafrut Huzzah32 ESP32 for an IoT project. When the ESP32 arrived, I attempted to fit it into my existing breadboard, but I immediately noticed that no matter how hard I pushed, the pins wouldn't fit into the solderless breadboard.

I tried to find others with the same problem with no luck, so I went on amazon and purchased another breadboard (an Elegoo 830 tie-points Breadboard). It arrived today and I'm having the exact same problem. I don't want to use a soderable breadboard at this stage of the project as I'm just starting, but I don't know what else to do at this point.

I've Googled images of other peoples' setups and there pins are snug down in the board. What am I doing wrong? I've included photos below:

[![Level View of Breadboard][1]][1]
[![enter image description here][2]][2]

As you can see, the power module on the end fits fine but the ESP32 won't go down into the board. At this point, I've tried two different boards (one of those small Arduino ones and this one) with no luck.

Any suggestions?

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

You can see that the pins aren't even close to being down in the board.

  [2]: https://i.stack.imgur.com/VuHbC.jpg

body:
I ended up taking Gerben's suggestion from the comments and ordering the stacking headers (adafruit.com/product/2830) and plugging the ESP32 into that. The reason it works is because the stacking headers (as Gerben mentioned) are thinner and fit down into the breadboard while the female ports on top are big enough for the male pins coming out of the ESP32.

Thanks everyone!


body:
I understand. These breadboards are pretty difficult to work with. Not only fitting an ESP-32 or similar board is difficult, these breadboards are not broad enough to expose all the GPIOs on both the sides.

I had solved this problem in this video. Do have a look. It might be helpful

https://youtu.be/CQlbE1x2i2g


body:
or you can simply fit two bread boards together and mount the esp on them

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

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

(i had to twist the pins a little bit )


message:
How to connect two LED strips (APA102/SK9822) to Arduino UNO?

So what I am trying to do is to connect two SK9822 LED strips to Arduino UNO.

I am a bit confused about how to properly set this up so I can individualy control any led. So obviously 5V should go to 5V and GND to GND, but what about the CLOCK and the DATA pin.

According to the tutorials and stuff I found here, CLOCK pin needs to be connected to pin 13 and DATA to pin 10, but they only use one strip... so what I am trying to ask is can LED strips share pins? Can they be connected to the same CLOCK pin and different DATA pins or how can i set this up to use the minimum amount of pins?

I was planning on using FastLED library, where it looks like you can specify which pin is DATA and which is CLOCK,

    FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN>(leds, NUM_LEDS);

Is this because different boards have different CLK and MOSI pins or can i use any pin and set it as CLOCK or DATA? This is probably obvious but I am new to this and this is my first project.

body:
I don't know about SK9822 LED strips, however the other type of led strips can be used with every pin; this is to support multiple LED strips.

Because every LED strip has its own CLK input (wire), it would be inconvenient to share them... I'm not sure if it is possible practically, because the timing is critical and if you have just one 'master' CLK signal than the data signals for all LED strips should be sent in time. Also writing the library would be more difficult, since there is a relation between a (shared) CLK signal and other data lines.


body:
For minimum pins, daisychain them together, with the clock and data outputs on the tail end of the first strip connecting to the clock and data inputs on the second strip.

https://www.pololu.com/product/3089 says:

> Multiple LED strips can be chained together by connecting input
> connectors to output connectors. When strips are chained this way,
> they can be controlled and powered as one continuous strip.


message:
Any reason to acquire more watts than really needed?

Basic question (again):

I have a LED-strip that requires 5V, and each LED (150 in total) requires about 60 milliamps.
Calculating everything, I need 3 of these LED-strips (450 LED in total). This in turn tells me that they require 27 000 milliamps (27 amps), which is about 135W.
Which means I need an external power supply to power them.
I think about buying a 5V 40A (200 W), which should be sufficient(?).

But, is there any reason that I should not buy anything with more watts (250 or 300)?

Thanks for any help!

body:
Are you sure every led is 60 mA? Or you mean maybe each Red, green and blue led inside each led (3 x 20 mA).

You always should buy slightly more than you need (but you think about 200W instead of 135W) already which is more than enough safety overhead.

Why would you need more? If you mean to control it with an Arduino Uno, that MCU (including the LEDs etc) is high likely more than a few hundred mA. So the only reason why you need more, is if you want to control later more LED strips, or any motor or other power hungry external devices.


message:
How to power and switch on / off multiple boards at the same time?

I have many nodes.

Each node consists of an MPU9250 and ESP32.
Each node functions independently. They don't interact with each other.

How can I power all of them at the same time, and switch them all on / off at the same time easily ?

body:
You need to provide more details. How many is "many"? How far apart are they physically? Can you run wires between them? Could you use radio control?

You said in the comments that they are each powered by separate batteries.

One possibility would be to put a power MOSFET transistor on each battery, switching the power supply for a given node. Then wire the gates (and grounds) all together and control them with a switch connected to the supply from one of your batteries (or from a 5V logic line.) MOSFETs draw almost no power at idle, and draw very little gate current for switching, so you should be able to drive dozens of them from a single 5V control line. However, this would require that you have a wire running from a central switch to every node, as well as a common ground to all of them.


message:
Error Compiling sketch for Arduino Uno(ld return 1)

I have got an telnet server with esp8266 + SoftwareSerial+ UNO, and here I want to on led with command ON <type> <pin>.
<type> will be 1 or 2. It is for recive 1 or 2 numbered pins.
And I extract pin from request with indexOf and substring functions and write:
```cpp
pinMode(pin,OUTPUT);
digitalWrite(pin,HIGH);
```
I write if pin is not 0 or 1 and it is in range 2-9 for type 1 and if pin is in range 10-13. But at compile time it gives me error compiling for uno. And it gives me this error whn I use pinMode. When I write it to setup it don't give me error. Why? What happenes?

Full code:

```cpp
#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif
 String res = "";
char ssid[] = "ssid";            // your network SSID (name)
char pass[] = "passs";         // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status
int reqCount = 0;                // number of requests received

WiFiEspServer server(23);

 WiFiEspClient client;

void setup() {
  pinMode(2,OUTPUT);

  Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");
Serial.println(WiFi.localIP());

WiFi.config(IPAddress(192,168,0,165));

  // start the web server on port 80
  server.begin();
}

void loop(){
  if(!client){
    client = server.available();
    if(client){
      client.println("Welcome to telnet server!, 192.168.0.165:23");
      client.flush();
    }

  }

  if(client){
if(client.available()>0){
  res = "";
  while(client.available()>0){

char c = client.read();

res += c;

  }
  Serial.println(res);

int i = res.indexOf("ON")+3;
int j = i+1;
String hh = res.substring(i,j);
int type = hh.toInt();
Serial.println(hh);
if(type == 1)
{
  int ii = res.indexOf("ON")+5;
int jj = ii+1;
String hhh = res.substring(ii,jj);
Serial.println(hhh);
int ihhh = hhh.toInt();
if(ihhh != 0 && ihhh != 1 && (2 <=ihhh)&& ( ihhh <= 9 ))
{
  pinMode(ihhh,OUTPUT);
  digitalWrite(ihhh,HIGH);
}
else{
  client.print("Pin is TX/RX, or not 2<= pin <=9\r\n");
  client.flush();
}
}else if(type == 2){
    int iii = res.indexOf("ON")+5;
int jjj = iii+2;
String hhhh = res.substring(iii,jjj);
Serial.println(hhhh);
int ihhhh = hhhh.toInt();
if(ihhhh != 0 && ihhhh != 1 && !((2<=ihhhh)&&(ihhhh <= 9)) && (10 <= ihhhh)&&(ihhhh <= 13 ))
{
  pinMode(ihhhh,OUTPUT);
  digitalWrite(ihhhh,HIGH);
}
else{
  client.print("Pin is TX/RX, or not 2<= pin <=9\r\n");
  client.flush();
}
}

}

    if(!client.connected())
    Serial.println("Client disconnected from Telnet Server");

  }

}

```

Error is:

Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Arduino/Genuino Uno"

C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino\HardwareSerial.cpp: In member function 'availableForWrite':

C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino\HardwareSerial.cpp:203:1: internal compiler error: Segmentation fault

 }

 ^

Please submit a full bug report,

with preprocessed source if appropriate.

See <http://gcc.gnu.org/bugs.html> for instructions.

lto-wrapper.exe: fatal error: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avr-gcc returned 1 exit status

compilation terminated.

c:/program files/windowsapps/arduinollc.arduinoide_1.8.21.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/../lib/gcc/avr/5.4.0/../../../../avr/bin/ld.exe: error: lto-wrapper failed

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.

Arduino IDE version is:  1.8.9(Windows Store 1.8.21.0)

body:
This is a bug in the compiler (linker) used by the Arduino AVR Core. It's not because of a bug in your code, and there's not much you can do about it except using a different version of the AVR Core.

See this [forum post](https://forum.arduino.cc/index.php?topic=583509.0):

> Here's the traditional workaround:
>
> 1. Tools > Board > Boards Manager
> 2. Wait for downloads to finish.
> 3. When you move the mouse pointer over "Arduino AVR Boards", you will see a "Select version" dropdown menu appear. Select "1.6.21".
> 4. Click "Install".
> 5. Wait for installation to finish.
> 6. Click "Close".


message:
Problems / doubts on battery-powered Arduino Nano WiFi weather station I built

I've almost finished my first Arduino project and I'm realizing I might have gone a bit over my head - I'm a web programmer, I have a very basic electronics knowledge and started tinkering with Arduino with just a couple simple, tutorial-like small circuits.

I then started building this project of a battery-powered Weather Station that sends sensors data via WiFi to my server - I managed to have a working product but I'm bumping into issues that are starting to look a bit bigger than what they initially seemed.

The workflow (schematics follow):

On the +5V pin of the Arduino Nano (actually a cheap chinese clone) I've put an **AMS1117** to stabilize down the voltage to **3.3V** (the 3.3V ArduinoNano output wasn't powerful enough), and from there I power several modules; a **DS3232** wakes up the Arduino (pin 2) when put in deep sleep mode (every 30 mins); when woken up I read data from the **DHT11** (humidity), the **BMP085** (pressure), the **DS18B20** (temperature) and **FC-37** (rain), I connect to my WiFi using the **ESP-01**, send data to my server, and put the Arduino back to sleep until the next cycle.

[![enter image description here][1]][1]
Everything worked when on the breadboard, worked after building the circuit with a perfboard; heck, it worked even when connected to my power supply, which is something similar to this project:
[https://www.arduinolab.net/solar-li-ion-charger-and-power-supply-for-arduino/][2]

[![Image taken from the above site][3]][3]
My battery is a **3,7V 2500mA**  instead, but all components are almost the same and I use a regular USB - type B cable to connect this to my Arduino Nano

But after an hour or so it stopped working - I checked again by connecting the Arduino to my PC and it appeared to be fine, but when connected to the battery everything was powered up (all leds on!) but the ESP wasn't trasmitting (never saw the flashing blue led).

So I started some reading around and I tought it might be a problem of too much current needed, and the battery wasn't enough anymore after it got under a certain voltage (I still measured 3.80V on the battery terminals though..)...

This is what I'm thinking:

 1. to **cut/remove the LEDSs** from all the modules (dht, rtc, fc-37 has two!, AMS1117) to save power (it's 5 LEDs + the arduino power on LED). Is it safe? Will they still work with the LED circuitry interrupted?
 2. connect my power source directly to the Vin+ of the AMS1117, instead of using the **+5v Arduino output** pin (but I read it can safely outsource 500mA, which is the limit for the USB power in anyway, so it shouldn't be an issue...)
 3. for the "long run", use a transistor to power on the sensors when Arduino is awaken, keeping them off the rest of time to spare battery juice, if nothing else...But I really don't know how to start for this, I thought of an NPN transistor (I have a PN222A available) with Base to Arduino (through a 1k Ohm Resistor), Collector to +5V and Emitter to the AMS1117 Vin+, is this sensible?
 4. increase power output? but how? the power source lets 5V 600mA through a regulated DC-DC booster, it should be ideal in theory...How do I understand if it's right for me?
 5. Ditch the ESP01 in favor of the **NRF24L01** (I already have a couple of these, but any other suggestion is appreciated)...but that would require a new setup, new coding (never used those modules), a "receiver" that then sends to wifi, and btw I don't know if the signal can make it from the balcony (where I plan to put the WeatherStation) to the inside of the house (I think it will, as the WiFi does - at least I think it does)

I don't really know how to actually measure the consumption of my circuit...I've read something around but, as I said, my electronics knowledge is limited, I don't have much spare time to dedicate on this, and therefore I cannot figure out without a clear guidance, sorry...

I'm not attaching my code because I don't think it's necessary - the sleep mode I'm using is SLEEP_MODE_PWR_DOWN from the avr/sleep.h library, other than that it works fine as it is.

Can someone give me suggestions or pointers on how to analyze my problem? Am I on the right track or my reasonings are off?

Thanks for any help you could provide, if you need any more info I'll do my best (in due time though, as I said I've not that much time to work on this...if I could muster 1 or 2 hours a week it would be a dream!)

  [1]: https://i.stack.imgur.com/RoGr0.png
  [2]: https://www.arduinolab.net/solar-li-ion-charger-and-power-supply-for-arduino/
  [3]: https://i.stack.imgur.com/z0CMp.jpg

body:
You are wasting a lot of power in your system. You need to be far more efficient when running off battery.

1. Don't boost your battery voltage to 5V. Instead use a system that runs entirely at 3.3V.
2. Never use a linear voltage regulator like the AMS1117 since it just wastes power as heat. Instead use a switching "buck" regulator.
3. Turning off modules when not being used is a very good idea. Sleeping the Arduino only saves some of the power - the modules will all still consume power.

I would suggest the ideal way forward would be:

1. Remove the Arduino from the schematic completely
2. Replace the ESP-01 with an ESP8266 module with more pins, or better still an ESP32 module.
3. Connect all the sensors (optionally with P-channel MOSFETs to control the 3.3V supply to them) direct to the ESP32
4. Remove the 5V boost from the power supply
5. Connect the power supply through a 3.3V switching regulator to power the whole circuit.


message:
Using software Serial for Adafruit Thermal library and more general cpp question

I'm working on a proof of concept for using the [Adafruit_Thermal](https://github.com/adafruit/Adafruit-Thermal-Printer-Library) printer library with an ATTiny85.

The ATTiny85 does not come with hardware serial capability, so I started looking into using SoftwareSerial to create the serial port necessary. I started down this path and ran into an error in the thermal library's constructor:

```cpp
// thermal-printer.ino example file

#include "SoftwareSerial.h"
#define TX_PIN 3
#define RX_PIN 4

SoftwareSerial mySerial(RX_PIN, TX_PIN);

#include "Adafruit_Thermal.h"

Adafruit_Thermal printer(&mySerial); // Pass addr to printer constructor

```

```cpp
// Adafruit_Thermal.h

class Adafruit_Thermal : public Print
{

public:
    // IMPORTANT: constructor syntax has changed from prior versions
    // of this library.  Please see notes in the example code!

    Adafruit_Thermal(Stream *s = &Serial, uint8_t dtr = 255);
```

>Documents/Arduino/libraries/Adafruit_Thermal_Printer_Library/Adafruit_Thermal.h:125:33: error: 'Serial' was not declared in this scope
   Adafruit_Thermal(Stream *s = &Serial, uint8_t dtr = 255);

If I understand correctly, the verification process is failing because the compiler is looking for a global `Serial` value in the `Adafruit_Thermal.h`file that doesn't exist because the ATTiny85 does not have HardwareSerial.

But, going by the Adafruit_Thermal class' constructor signature the reference passing of `Serial` is just a default value (right?) so I should be able to remove it and pass in my software serial reference. [The `SoftwareSerial` class inherits from `Stream`](https://github.com/arduino/ArduinoCore-avr/blob/master/libraries/SoftwareSerial/src/SoftwareSerial.h), so it should still be a valid reference pass:

```cpp
// this:
Adafruit_Thermal(Stream *s = &Serial, uint8_t dtr = 255);

// changes to this:
Adafruit_Thermal(Stream *s, uint8_t dtr = 255);
```

But when I do that, I start getting verification errors that make it look like the thermal instance wasn't constructed, like:

> undefined reference to `Adafruit_Thermal::begin(unsigned char)'

and

> undefined reference to `Adafruit_Thermal::Adafruit_Thermal(Stream*, unsigned char)'

Does this mean the class isn't getting constructed?

I looked at the underlying constructor definition to see if something was blowing up in there, but there doesn't seem to be anything fancy at the constructor level:

```cpp
// Constructor
Adafruit_Thermal::Adafruit_Thermal(Stream *s, uint8_t dtr) :
  stream(s), dtrPin(dtr) {
  dtrEnabled = false;
}
```

This should still work with the software serial reference pass, right?

I'm a bit lost on how to debug this now. Any ideas?

# Update

After a reply from Majenko I pulled up the cpp file and looked at the header reference:

[![header reference][1]][1]

So this means the cpp file was still referring to the include path header file instead of the `lib` version?

I updated my cpp file to use:

```
#include "lib/Adafruit_Thermal.h"
```

and I still get undefined reference errors, so it may still be something else, but I wanted to share this additional info.

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

body:
:'( it's a bitter sweet solution.

After @majenko's last comment:

> Ah. So is there something you have to do in that IDE to say "Include the files in lib in the compilation`?

I remembered that this issue has bitten me before. Specifically, the issue of including subfolders into a sketch.

Normally in programming languages (at least all of the ones I work in normally), you can use relative paths or namespaces to include files from subfolders, but for some reason with Arduino if you want to include files from subfolders **you have to put the files in a directory named `src`**.

And it specifically needs to be `src`. You can't use `lib` or `libs` or `source` or `whatevernameyouwant`, it needs to be src.

I can't find a spot in the arduino reference docs or the IDE's github repository that explains that you need to use `src` for the subfolder name, but you can find various mentions in the forums. E.g.

https://arduino.stackexchange.com/a/54655/35534

So yeah, the solution to my problem was three parts.

1. Adopting the `Adafruit_Thermal` library into my codebase so that I could edit the source code without worrying about those changes polluting the orginal.
2. Removing the `&Serial` reference pass in the constructor declaration of `Adafruit_Thermal.h`
3. using the `src` directory name to include things from a subfolder.

[![solution structure][1]][1]

After doing this, the sketch passes verification.

But here's the bittersweet part. After getting past all of this and seeing the compiler get past the sketch verification the bombshell dropped; the sketch is too big for the attiny:

[![heartbreak][2]][2]

I guess it was not meant to be :'(

Well, at least I know what was causing the linker/compiler errors and I'll be able to sleep at night :P

Thanks for your help Majenko :bows:.

  [1]: https://i.stack.imgur.com/Fjlx7.png
  [2]: https://i.stack.imgur.com/9YvMt.png


message:
Motor with sinusoidal motion

I need to run a  motor to have a harmonic motion with specified amplitude and frequency ( harmonic motion mean that the angular position of the motor is a sine function of the time). I’m Looking to do a specified number of sinusoidal oscillations.
I don't know how to tell the motor that I want the speed to be a sine function of the time. Any ideas?
Also, I’m still beginning of the project?  Hence I’m pretty flexible to choose any motors (DC/servo/stepper/ brushless motor) or any controller but the system has to be precise.
If you guys know what controllers that allow that kind of motion, please let me know! Thank you :)

**EDIT**:
so what I'm trying to do is making rheometer which measures the rheological properties of a material. Basically, there are two measuring methods available: Rotational tests and oscillatory tests. With rotational measurements, the measuring bob turns in one direction. In an oscillatory test, the measuring bob "oscillates" around the axis.
[![enter image description here][1]][1]

what my focus is to with oscillatory tests with set sinusoidal oscillation.
The basic principle of an oscillatory rheometer is to induce a sinusoidal shear deformation in the sample and measure the resultant stress response; the time scale probed is determined by the frequency of oscillation, ω, of the shear deformation. In a typical experiment, the sample is placed between two plates, as shown in the below image While the top plate remains stationary, a motor rotates the bottom plate, thereby imposing a time-dependent strain γ(t)=γ ·sin(ωt) on the sample. Simultaneously, the time-dependent stress σ (t) is quantified by measuring the torque that the sample imposes on the top plate.

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

So to able to do above testing I need to run the motor with sinusoidal oscillation with exact angle.Hope you get it what im trying to say? does anyone know any  motor controllers that allow that kind of motion ? or any hints how do i wet my feet? cheers!!

  [1]: https://i.stack.imgur.com/EnLSK.jpg
  [2]: https://i.stack.imgur.com/KtNiI.jpg

body:
Your best option would be:

 - To have a DC motor with a reduction box so that it spins at lower speeds (Lets say 300 rpm) and have an encoder to count the steps. Either put the encoder before the reduction box (here it can be used a low resolution encoder, like 16 positions) or after the reduction (here you would like a more precise one, such as those 1024 positions).

 - To have a Stepper motor, which will give a good angular control as long as it doesn't misses steps (if there is too much torque it will halt its movement, and you will lose count of the angle you have already displaced).

Now, to get the motor to move in a way that its angular position is of the form theta(t) = A*sin(ωt) you would have to write some code that moves the motor to each position you want. And the difficulty of it will depend a lot on the amplitude (A) and angular speed (ω) you require.

Obs: feel free to alter/add info here


message:
MQTT PubSubClient connection problem with ESP32

I am experiencing some problems with string in Arduino application with ESP32.
I don't understand why this code works:

`mqtt.setServer ("m20.cloudmqtt.com", port);  //is OK`

and this does not work does not connect

`String strSBM = "m20.cloudmqtt.com";
mqtt.setServer (strSBM.c_str (), port);  //no OK`

I use library PubSubClient 2.7

Any of you can help me

Many thanks

body:
When you set the server from a C string it doesn't copy the string - it just retains a pointer to it:

    PubSubClient& PubSubClient::setServer(const char * domain, uint16_t port) {
        this->domain = domain;
        this->port = port;
        return *this;
    }

If the string it's pointing to goes out of scope (it's a local variable and the function finishes) the data for the string will be invalidated and lost.

It is really intended to work with string literals and global constant variables that never change.

If this is the one and only time that you ever set the server you could get away with using `strdup()` to duplicate the string data on the heap, but without direct access to the `domain` member variable of the `PubSubClient` class you have no way to `free()` the memory again should you ever wish to change the server.

    String strSBM = "m20.cloudmqtt.com";
    mqtt.setServer (strdup(strSBM.c_str()), port);

To make it so you can `free` the value you need to keep track of it separately:

    static char *temp = NULL;
    if (temp != NULL) {
        free(temp);
        temp = NULL;
    }
    temp = strdup(strSBM.c_str());
    mqtt.setServer(temp, port);


message:
Setting up I2C with HTU21D, no response after beginTransmission

I'm playing with the temperature/humidity sensor HTU21D. Datasheet: https://www.te.com/commerce/DocumentDelivery/DDEController?Action=showdoc&DocId=Data+SheetHPC199_6A6pdfEnglishENG_DS_HPC199_6_A6.pdfCAT-HSC0004

The sensor is properly wired and yields reasonable values if I use the library and example here: https://github.com/sparkfun/SparkFun_HTU21D_Breakout_Arduino_Library/blob/master/examples/SparkFun_HTU21D_Demo/SparkFun_HTU21D_Demo.ino

But I'm more interested in how I2C works, so I'm trying to write a small sketch from scratch to communicate with the sensor. Here is what I have right now:

    #include <Wire.h>

    #define SensorAddress 0x40
    #define SoftReset 0xFE
    #define TriggerTemperatureNoHold 0xF3
    #define TriggerHumidityNoHold 0xF5

    void setup(){

        Serial.begin(9600);
        Serial.println("HTU21D library");

        //delay(50);

        //Wire.beginTransmission(SensorAddress);
        //Wire.write(SoftReset);
        //Wire.endTransmission();

        //delay(50);
        Serial.println("init finished");

    }

    void loop(){

        Serial.println("entering");
        Wire.beginTransmission(0x40);
        Wire.write(0xF3);
        Wire.endTransmission();
        Serial.println("hello");

        //Hang out while measurement is taken. datasheet says 50ms, practice may call for more
        bool validResult;
        byte counter;
        for (counter = 0, validResult = 0 ; counter < 10 && !validResult ; counter++){
            delay(100);

            //Comes back in three bytes, data(MSB) / data(LSB) / Checksum
            validResult = (3 == Wire.requestFrom(0x40, 3));
            Serial.println(validResult);

        }
        Serial.println("here");
    }

I'm in the middle of debugging the sketch. When the sketch is uploaded, I'm reading on the serial connection, and all I can see is:

    HTU21D library
    init finished
    entering

It seems the program hangs on the first communication attempt, when I send the TriggerTemperatureNoHold command.

Could you give me a hand please? I don't understand why it's hanging there.

body:
You forgot `Wire.begin();`.  You should add it in `setup()`.

`Wire.begin();` will configure the IO pins for I2C usage. Without that the signals don't get in or out of the MCU, so I2C functions that wait for an ACK signal never see it and don't complete.


message:
How do you determine Lead Screw position using Absolute Encoder?

I need to control the position of a lead Screw Stepper motor using **EMS22A Absolute Encoder**? I've seen James Bruton do this in his video. can anyone help me?

James Bruton Video: https://www.youtube.com/watch?v=ngazw18f6zw

edit: What i did was to determine the "Largest Change" to count the number of cycle that has occurred. However, with fast rotation the program was not able to detect the change.

    void loop(){

    unsigned long currentMillis = millis();
    pos = encoder.ReadAngle();

      if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;
        pos2 = encoder.ReadAngle();
        }
    int change = pos2-pos;
    if (change > 200){
      cycle--;
    }
    if (change < -200){
      cycle++;
    }
    if(change > 1){
      motor.Forward();
    }
    if(change < -1){
      motor.Reverse();
    }
    if(change <= 1 && change >= -1){
      motor.Stop();
    }
    Serial.print(pos);
    Serial.print(" ");
    Serial.println(cycle);
    }

body:
The encoder attaches to the motor (or other) shaft and sends a 10-bit rotational position for a precision of 0.35 deg, and a claimed accuracy of +/- 0.7 degrees. It will be up to the application to keep track of number of rotations, detecting when the shaft has completed a rotation in either direction.

In a lead-screw application there will always be a little bit of backlash or "play". The leadscrew and nut cannot be perfect and must have a little bit of slop (technical term!) to keep the rotational friction low. This means that the nut will have some linear play, leaving that much uncertainty in the linear postion, even if the leadscrew angular position is perfectly known. Most applications manage this by turning the leadscrew back, to behind the target position, and then approaching the target in the forward direction. The leadscrew and nut position will have been calibrated for this direction. Of course it could be calibrated separately for each direction. The key is that the nut must be driven "behind" (for the particular direction) the target by more than the known linear play, to be sure the play will be entirely taken up during the approach to the target.


message:
Merge two 8 bit arrays to one 16 bit array

I am an absolute newbie to Arduino and C++ and try to go through some tutorials to gain a minimal insight. However I stuck already at some tiny Points. What I want to do? Merge two 8 bit integer Arrays in to one 16 bit Array:

    int summand_one[8] = {0,0,0,1,1,0,0,0};
    int summand_two[8] = {1,0,0,0,0,0,0,1};

    int * summand = new int[16];
    std::copy(summand_one, summand_one+8, summand);
    std::copy(summand_two, summand_two+8, summand+8);

The result should be

    {0,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1}

However it's not working at all. Constructor/destructor/type errors…

Any helpful idea how to do this?

body:
It's better to avoid dynamic memory allocation on an Arduino, with only 2 KB of SRAM memory.

Note that your arrays cost 2 (bytes/int) * (8 + 8 + 16) = 64 bytes.
And it seems you are only storing booleans, which could be stored in one bit. So consider another alternative (I will not work that out, since maybe memory consumption is not a problem).

However, an easy solution is to use uint8_t.

Also, I would use a simple memcpy. Very naively it would look like:

    uint8_t summand_one[8];
    uint8_t summand_two[8];
    uint8_t summand[16];

    void setup()
    {
    }

    void loop()
    {
      memcpy(summand, summand_one, 8);
      memcpy(summand + 8, summand_two, 8);
    }

Using some constants for the sizes, you get more flexible/readable and maintainable code:

    static const uint8_t SummandOneSize = 8;
    static const uint8_t SummandTwoSize = 8;

    uint8_t summand_one   [SummandOneSize];
    uint8_t summand_two   [SummandTwoSize];
    uint8_t summand_merged[SummandOneSize + SummandTwoSize];

    void setup()
    {
    }

    void loop()
    {
      memcpy(summand_merged                 , summand_one, SummandOneSize);
      memcpy(summand_merged + SummandOneSize, summand_two, SummandTwoSize);
    }


message:
Remote Controlled Self-Balancing Robot - how to mix control input with IMU input?

I'm building a two-wheeled, self-balancing, remote-controlled robot. I'm familiar enough with the IMU and PID to get it working to just stand up but I need to drive it via remote control.

I've got no code written yet; trying to understand the concepts before diving in.

This much I understand: `[IMU] -> [Kalman filter] -> [PID] -> [Motors]`

Where I'm getting tripped up is where to mix the RC component into that control chain?

body:
The PID get's a set point from you. For a standing still robot this a basically an angle of zero in respect to the gravity direction (which variable you use for the PID depends on your actal implementation, but it always be something derived from the angle to gravity direction). For driving forward, the robot must lean forward. So you set the new angle set point to let's say 2 degrees. The PID will try to hold that value by driving forward constantly, with a speed depending on the set angle.

So, via the remote control you simply change the angle setpoint.


message:
Error: "'lcd' does not name a type" using LiquidCrystal library

I'm following an online Arduino tutorial/course and trying to make a simple moving character on an LCD screen, but for some reason I get the following error: "error: 'lcd' does not name a type". I'm using the Tinkercad simulator because my PC's USB ports died recently.
Here's my code:

    #include <LiquidCrystal.h>

    byte character[8] {
       B01111,
       B01111,
       B01111,
       B00110,
       B01111,
       B01111,
       B01001,

    } ;

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

      lcd.createChar(0, character); //error is on this line

    const int Lbtnpin = 6;
    const int Rbtnpin = 7;
    int Lbtnprev = HIGH;
    int Rbtnprev = HIGH;
    int pos = 0;

    void setup(){
      lcd.begin(16, 2);
      lcd.clear();
      pinMode(6, INPUT_PULLUP);
      pinMode(7, INPUT_PULLUP);
    }

    void loop(){
      lcd.clear();
      int Lbtnstate;
      Lbtnstate = digitalRead(6);
      int Rbtnstate;
      Rbtnstate = digitalRead(7);

      if ((Lbtnprev == HIGH) && (Lbtnstate == LOW) && (pos > 0)) {
         pos--;
      }
      if ((Rbtnprev == HIGH) && (Rbtnstate == LOW) && (pos < 16)) {
         pos++;
      }
      lcd.setCursor(pos, 1);
      lcd.write(byte(0));
      Lbtnprev = Lbtnstate;
      Rbtnprev = Rbtnstate;
    }

body:
You cannot call methods outside of a function.
Move `lcd.createChar(0, character);` into `setup`.


message:
Use Arduino as transmitter and receiver UART

I know UART and serial communication model and data frame. But I want to ask about something else, when I searched in internet just found examples of one Arduino as (receiver) and another Arduino as (transmitter).
So my question is how can I implement two Arduino and both of arduinos can communicate each other when after transferring data from one to another
(example A->B). If the interpretation of the received data has to be forwarded to the first sender again(B->A).

body: You sure now `Serial.write()` and `Serial.read()`. That's already what you want. A hint to make it clear to you: When using the common `Serial.print()` function only the RxD line is in charge an thus only "half" of the serial interface is used. If you connect TxD of arduino A to RxD of another arduino B and RxD to TxD respectively you have full-duplex communication which is what you're asking.


message:
Waking Arduino from sleep with an ultrasonic sensor

I have a parking guide using an ultrasonic sensor (HC-SR04), based on the instructions [here][1]. I'm trying to modify the code so that the Arduino goes to sleep after a certain period of inactivity (say, 30 seconds), and wake again when the sensor 'sees' a car drive into the garage. The code [here][2] shows how to wake it with a solar panel.

However, the way I understand it, the solar panel is able to wake the Arduino because it doesn't need external power to work (because it's a solar panel). Would it be possible to do the same with an ultrasonic sensor (HC-SR04), which does need power?

It'll be running off mains power, but I don't want it to be drawing power when it's not needed.

  [1]: https://www.hackster.io/Bcjams/garage-parking-assistant-11446b
  [2]: https://holadimake.wordpress.com/2015/06/23/waking-up-an-arduino-with-input-from-a-sensor/

body:
In order to make the ultrasonic sensor work, the Arduino has to run some code to control it.  So it won't do anything while the Arduino is asleep.

What you can do is have the Arduino sleep for some reasonable amount of time, wake up and read the sensor, and then go back to sleep.  Maybe wake it up once every few seconds.  Do you really need to react to a car in the lot the millisecond it pulls in?


message:
CHSV arguments with FastLED

I'm trying to use CHSV with FastLED library and as I understand hue, value and saturation in the CHSV type are of type uint8_t, or 1 byte.

My problem is with using variables:
<!-- language-all: lang-cpp -->

    CHSV led = (hue, sat, val);

with:

    uint8_t hue;
    uint8_t sat;
    uint8_t val;

1. Is there a difference between uint8_t and byte data types? what is it and how does one use it with the context of arduino and FastLED library?

2. Am I getting the syntax wrong?
I get an error - convertion from 'uint8_t' to non scalar type 'CHSV' requasted.
I thought the library does that on its own, do I need to add more code? If yes, what code?

Thank you

body:
> Is there a difference between uint8_t and byte data types?

There is no difference in the datatype. `byte` is defined in Arduino.h:

    typedef uint8_t byte;

So, `uint8_t` and `byte` are exactly the same. The `uintX_t` types and their siblings are specifically meant for having the same size on every platform (in difference to for example `double` which is only 16 bits on Arduino Uno, but can be 32 bits on bigger chips). But `byte` will also be 8 bits on every platform, so there is really no difference.

> Am I getting the syntax wrong? I get an error - convertion from 'uint8_t' to non scalar type 'CHSV' requasted. I thought the library does that on its own, do I need to add more code? If yes, what code?

You get the error, because you use the wrong syntax here. A `CHSV` color is not just 3 byte values, it is a class with member variables and methods. So you cannot simply assign 3 byte values directly to the object. You need to actually create the object, using the values as parameters for the constructor:

    CHSV led = CHSV( hue, sat, val);

This creates a `CHSV` object, executes it's constructor, which uses the values from the parameters to set the internal values. That is the context, how this is used in the FastLED library. You can also find such lines in the examples of the library (I found such use in line 15 of the example `ColorPalette`, but there might be more). Also this is the same principle, as with the other color classes, like `CRGB`.


message:
Delay stops execution forever sometimes

I have an arduino to control an irrigation system, consisting on one pump (called "bomba" on the code) and 5 12V water valves.

Each valve controls one irrigation circuit and the idea is to open each one sequentially during one minute and then move on to the next one.

The code is this:

    const int TIEMPO_RIEGO = 64; // seconds

    const int TRIGGER = 5;

    const int BOMBA = 6;
    const int CIRCUITO_1 = 8;
    const int CIRCUITO_2 = 9;
    const int CIRCUITO_3 = 10;
    const int CIRCUITO_4 = 11;
    const int CIRCUITO_5 = 12;

    const int CIRCUITOS_ACTIVOS[] = {
      CIRCUITO_1,
      CIRCUITO_2,
      CIRCUITO_3,
      CIRCUITO_4,
      CIRCUITO_5,
    };

    void _abrirValvula(int circuito, int t) {
        digitalWrite(circuito, HIGH);
        digitalWrite(BOMBA, HIGH);
        unsigned long waitTime = t * 1000L;
        delay(waitTime);
        digitalWrite(BOMBA, LOW);
        digitalWrite(circuito, LOW);
    }

    void cicloRiegoCompleto() {
      int numeroDeCircuitos = sizeof(CIRCUITOS_ACTIVOS) / sizeof(CIRCUITOS_ACTIVOS[0]);
      for (int i=0; i<numeroDeCircuitos; i++){
        _abrirValvula(CIRCUITOS_ACTIVOS[i], TIEMPO_RIEGO);
      }
    }

    void setup() {
      pinMode(BOMBA, OUTPUT);
      pinMode(CIRCUITO_1, OUTPUT);
      pinMode(CIRCUITO_2, OUTPUT);
      pinMode(CIRCUITO_3, OUTPUT);
      pinMode(CIRCUITO_4, OUTPUT);
      pinMode(CIRCUITO_5, OUTPUT);
      pinMode(TRIGGER, INPUT);
    }

    void loop() {
      if (digitalRead(TRIGGER) == HIGH) {
       cicloRiegoCompleto();
      }
    }

On the pin 5 (TRIGGER) I have a raspberry pi connected that is connected to the internet also, so, when I send it a message from mi phone, it puts 3.3V on that pin and starts the process.

It has been working great for like a month or so but, a few days ago, the pump didn't stop when it should, and was still working hours after it started.

I pull the plug and, when I turn it on again, it worked correctly again for another 2 or 3 days.

But today it hasn't stop again. I have check that the pump has been working for around 15 minutes until I pulled the plug, and the first valve (CIRCUITO_1) has been opened the whole time, looks like the `for` loop is stuck in the first iteration.

So can it be some problem with the `delay` function?

For some reason it is waiting way more than it should?

It works sometimes and sometimes it doesn't so it makes me think: can it be some weird overflow issue?

body:
> It has been working great for like a month or so ... it makes me think: can it be some weird overflow issue?

It's hardly a software issue then. Nothing in your code would change after a month of operating. And if you turn the power off and on again then it would "forget" about the previous month.

> So can it be some problem with the delay function?

No.

---

I suggest looking at the hardware, or the code on the Pi.


body: Based on your experience with the system and the source of the Nanos, the best and quickest test I can think of is to swap in a another Nano to find out whether if the problem remains or disappears.


body: Do you have 10k resistors between gate and ground on your MOSFETs? You might be suffering from residual charge on your MOSFET gate keeping it on when it should be off.