body:
I've been unable to FTP anything using an Arduino and SIM800L. I have reduced the code as far as possible:

    #include <SoftwareSerial.h>

    //Create software serial object to communicate with SIM800L
    SoftwareSerial mySerial(3, 2); //SIM800L Tx & Rx is connected to Arduino #3 & #2

    String moduleAnswer = "";

    void setup()
    {
      //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
      Serial.begin(9600);

      //Begin serial communication with Arduino and SIM800L
      mySerial.begin(9600);

      Serial.println("Initializing...");
      delay(1000);

      SoftwareATCommand("AT"); //Once the handshake test is successful, it will back to OK
      SoftwareATCommand("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
      SoftwareATCommand("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
      SoftwareATCommand("AT+CREG?"); //Check whether it has registered in the network

      //APN and GRPS Setup
       SoftwareATCommand("AT+SAPBR=0,1"); //Close GPRS before connecting
       SoftwareATCommand("AT+SAPBR=3,1,\"Contype\",\"GPRS\""); //Configure bearer profile

      SoftwareATCommand("AT+SAPBR=1,1"); //Connect to GPRS

      //FTP Connection
      SoftwareATCommand("AT+FTPCID=1");
      SoftwareATCommand("AT+FTPSERV=127.189.249.205"); //Not real IP
      SoftwareATCommand("AT+FTPPORT=21");
      SoftwareATCommand("AT+FTPUN=user");
      SoftwareATCommand("AT+FTPPW=pass");

      //FTP Upload
      uploadFTP();

     }

    void loop()
    {
    }

    void uploadFTP()
    {
      SoftwareATCommand("AT+FTPPUTNAME=\"test.txt\""); //Filename
      SoftwareATCommand("AT+FTPPUTPATH=/home/arduino/SolarDataLogger/"); //Path
      SoftwareATCommand("AT+FTPPUT=1"); //Start FTP
      delay(10000);
      SoftwareATCommand("AT+FTPPUT=2,100"); //Send 100 bytes of data
      delay(10000);
      SoftwareATCommand("Hello12345"); //Send Data
      SoftwareATCommand("AT+FTPPUT=2,0"); //Close FTP

    }

    String SoftwareATCommand(String strAT)
    {

      String strNotice = "Sending: " + strAT;
      Serial.println(strNotice);
      mySerial.println(strAT);

      delay(500);
      moduleAnswer = "No Response";

      while(mySerial.available())
      {
        moduleAnswer = mySerial.readString();

        char* buf = (char*) malloc(sizeof(char)*moduleAnswer.length()+1);
        moduleAnswer.toCharArray(buf, moduleAnswer.length()+1);
        Serial.write(buf);//Forward what Software Serial received to Serial Port
         - Module answer sent to screen
        free(buf);
       }

       return moduleAnswer;
    }

The serial output where the trouble is:

[![Serial output][1]][1]

I've tried waiting longer for the `+FTPPUT: 1,1,1360` response or sending something twice, but nothing seems to work. The file gets created but no other data is ever sent.

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

title: Sim800 FTP Arduino

Answers: 2

body:
Maybe its too late to respond but the line +FTPPUT: 1,65 indicates a server error.

 https://www.elecrow.com/wiki/images/2/20/SIM800_Series_AT_Command_Manual_V1.09.pdf - page 275.

 Please check a sequence of commands , maybe something is missing ?

 I use the following sequence :

    "AT+CREG?"
    "AT+SAPBR=3,1,\"Contype\",\"GPRS\""
    "AT+SAPBR=3,1,\"APN\",\"NAME OF YOUR PROVIDER \""
    "AT+SAPBR=1,1"
    "AT+SAPBR=2,1"
    "AT+FTPCID=1"
    "AT+FTPSERV=\"SERVER ADDRESS\""
    "AT+FTPPORT=21"
    "AT+FTPTYPE=\"I\""
    "AT+FTPUN=\"USERNAME\""
    "AT+FTPPW=\"PASSWORD\""
    "AT+FTPPUTNAME=\"" + NAME OF FILE + "\""
    "AT+FTPPUT=1"
    "AT+FTPPUT=2," + STRING OF BUFFER SPACE ( Get from response of FTPPUT=1 )
    "AT+FTPPUT=2,0"

 Look on the manual for the commands above.

Sorry about my grammar

body:
what I observed in your code-I think you did not follow the proper sequence of connecting the GPRS context mentioned in the [sim800l datasheet][1].
Please follow the section 3.1. bearer configuration. I also attached the screenshot herewith. So you missed setting the Access Point Name(APN). After you query the GPRS context(last step in the image), if you get the proper IP address, then you are sure to send the data over FTP. Please follow the FTP sequence mentioned in the datasheet.
[![enter image description here][2]][2]

  [1]: https://cdn-shop.adafruit.com/datasheets/sim800_series_ip_application_note_v1.00.pdf
  [2]: https://i.stack.imgur.com/x5aln.png


body:
I am newbie and I want to build a project that contains two linear actuator that move synchronously. Two of them will lift up and down at same time. I use arduino mega and VNH5019 motor driver. I have thompson electrac ELD linear actuator. I have never tried to synchronize two linear actuator. Linear actuator have encoder output ( it is hall effect encoder -( not absolute. So it cannot keep last position in case of power cut )). Encoder type is hall effect type. Encoder output voltage levels low (logical zero), typical / max is 0.1/0.25 Vdc. Also it has output fully extented/retracted signal. I tested it with H-Bridge motor driver made of 4 SSR relays and push button switches to retract and extract. There is a synchronization problem.The system will stop when actuators extracted 500 mm ( actuators have 900 mm stroke length) How should I solve that synchronozation problem could you help me ? What should I do?

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

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

title: How to Work Two Linear Actuator Synchronously by Using Arduino and VNH5019 Motor Driver?

Answers: 1

body:
It sounds like you need to watch both encoder outputs and don't let one get ahead of the other. Naturally, they won't sync exactly (i.e., pulse simultaneously) but you can set a limit on how many counts to let them differ by, before pausing the faster actuator while the slower one catches up.

If you need to save positions across a power failure, you'll need to 1) provide enough backup power to keep the system alive past the supply failure to give you time to stop both actuators and store both of their positions in EEPROM; and 2) provide a signal to the Arduino that the supplied power (not the backup) is going down, so it can begin its orderly shutdown.


body: I have a system that uses Arduino and some modules. The system needs 5v dc power with 3A current at maximum(The system needs 3A current for some seconds every 5 minutes and after that the current will get back to 300-400mA) and on the other side i have a 5v dc charger with 400-500 mA current. So my problem is lack of amperage and i can't run correctly Arduino with 5v dc charger. For solving this problem i want to use a Lipo battery to connect to Arduino but the battery will ran out and i can't get energy from battery so i want to connect the battery to my charger while the Arduino uses the battery, How can i do that? Is there any module to do this work? Can i use TP4056 with protection version to do this work?(Note: I can't change charger)

title: Charge lipo battery while using

Answers: 1

body:
You really shouldn't charge a lithium battery whilst discharging it. The charger may either never know that it has finished charging and overcharge it, or shut off early and never charge it up properly at all.

Instead you should arrange that your MCU is powered directly from the PSU so that it always has stable power, and feed that same power into a normal charger via some form of electronic switch so it can be turned on and off. The output of the battery can then be fed through another switch into your heavy load.

When it comes time for your load to be activated you switch off the power from the charger and switch on the connection from the battery to the load.

What you use to do the switching is entirely up to you - whether you choose P-channel MOSFETs or relays entirely depends on your situation.

Here's a block diagram to better illustrate it to you:

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

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

<!-- End schematic -->


body:
I'm making a desk lamp out of 2x WS2811 strips (attached to the triple ports at top right of board below). The brightness of the strips is controlled by a potentiometer, and the colour by a switch. Each press of the switch cycles through red, blue and white:

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

Here's the code I've come up with:

    #include <FastLED.h>

    #define strip_pin     7
    #define NUM_LEDS    15

    CRGB leds[NUM_LEDS];
    int distance;
    int brightness;
    int brightnesspin = 2;
    int pin_switch = 3;

    // variables to hold the new and old switch states
    boolean oldSwitchState = LOW;
    boolean newSwitchState1 = LOW;
    boolean newSwitchState2 = LOW;
    boolean newSwitchState3 = LOW;
    byte state = 0;

    void setup()
    {
      Serial.begin(9600);
      FastLED.addLeds<WS2811, strip_pin, BRG>(leds, NUM_LEDS);
    }

    void loop()
    {
      delay(500);
    //  Colour control
    //##############################################
        newSwitchState1 = digitalRead(pin_switch);
        delay(1);
        newSwitchState2 = digitalRead(pin_switch);
        delay(1);
        newSwitchState3 = digitalRead(pin_switch);
        // if all 3 values are the same we can continue
        if (  (newSwitchState1==newSwitchState2) && (newSwitchState1==newSwitchState3) )
        {

            if ( newSwitchState1 != oldSwitchState )
            {

               // has the button switch been closed?
               if ( newSwitchState1 == HIGH )
               {
                    // increase the value of state
                    state++;
                    if (state > 3) { state = 0; }
                    for (int i = 0; i < NUM_LEDS; i++)
                    {
                    if (state==1) { leds[i].red = 100;Serial.println("Red"); }
                    if (state==2) { leds[i].blue = 100;Serial.println("Blue"); }
                    if (state==3) { leds[i].red = 100; leds[i].blue = 100; leds[i].green = 100;Serial.println("White");}
                    }
                    FastLED.show();
                }
               oldSwitchState = newSwitchState1;
            }

    //    Brightness control
    //##############################################
      brightness = analogRead(brightnesspin);  brightness = map(brightness, 0, 1024, 0, 255);
        for (int i = 0; i<NUM_LEDS; i++)
          {
            FastLED.setBrightness(brightness);
          }
      FastLED.show();
      Serial.print("Brightness: ");
      Serial.println(brightness);
        }
    }

The brightness control works fine, and the switch cycles through the colours *once*, but the strip stays white once it's there, even though the serial monitor shows the switch changing state. How can I get the strip to cycle back round to red?

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

title: Cycling through switch states

Answers: 2

body:
The problem lies in your for cycle.

 - If `(state == 1)` you are switching the red colour ON.
 - If `(state == 2)` you are switching the blue colour is ON. So at this moment, you have red AND blue colour on, not only blue. I assume the output colour is purple-ish.
 - If `(state == 3)`, you activate red (which is already ON), blue (which is also already ON) and also green (which changes state from OFF to ON) so you get white colour. At this moment you went through all three possible conditions.
 - Then you go back to `(state == 1)`. All colours are already activated, so from this moment you get only white...

Solution:

    for (int i = 0; i < NUM_LEDS; i++) {
      if (state == 1) {
        leds[i].red = 100;
        leds[i].blue = 0;
        leds[i].green = 0;
        Serial.println("Red");
      }
      if (state == 2) {
        leds[i].red = 0;
        leds[i].blue = 100;
        leds[i].green = 0;
        Serial.println("Blue");
      }
      if (state == 3) {
        leds[i].red = 100;
        leds[i].blue = 100;
        leds[i].green = 100;
        Serial.println("White");
      }
    }

body:
In your lines:

                    if (state==1) { leds[i].red = 100;Serial.println("Red"); }
                    if (state==2) { leds[i].blue = 100;Serial.println("Blue"); }
                    if (state==3) { leds[i].red = 100; leds[i].blue = 100; leds[i].green = 100;Serial.println("White");}

The LEDs are set on, but are never turned off.

Sequence is:

1: Red leds turn on; strip appears red.

2: Blue leds turn on (the leds will probably actually look purple rather than blue here as the red leds are still on)

3: Green leds turn on (red and blue leds are already on); strip appears white

back to start:

1,2,3: nothing changes as all leds are already on, strip remains white.

I'd suggest adding:

    leds[i].green = 0; leds[i].blue = 0;

to the `state == 1` condition and

    leds[i].green = 0; leds[i].red = 0

to the `state == 2` condition.


body:
My Arduino (actually an ESP32-based Adafruit HUZZAH32) is running as a wifi server. Its main job is to service GET requests from a user, and to periodically turn devices on and off based on the commands implicit in those GETs.

It needs to keep an accurate time/date - in order to turn devices on/off as directed.   My cheap real-time clock is off a couple seconds or more per day.   So I figure I'll use code such as the example at:

https://randomnerdtutorials.com/esp32-ntp-client-date-time-arduino-ide/

... in which the Arduino creates a client to get the time from an NTP server.  Once a day (e.g. checking for the RTC time to be 00:00hrs in my "loop"), I'll adjust the RTC using NTP.

Looking around, it sounds like this is ok, for the Arduino to act as a client, as long as it's not actively servicing a client (the user's GET requests).  Do I have that right ?   Need I worry that a user might be sending a GET when that happens ?

title: Arduino is running as a server, but want to occasionally act as a client to update time

Answers: 1

body:
There is no problem with running multiple servers and use multiple clients with the WiFi library of the ESP32 core for Arduino as it is not a problem with most of the WiFi libraries for Arduino (some can't run servers (TinyGsm) or can run only one server (WiFiEsp(AT)).

But you don't need a WiFiClient for NTP time. First because NTP runs on UDP and second because the ESP32 SDK provides SNTP and the ESP32 core for Arduino wraps it in functions presented in the ESP32 examples library's [SimpleTime example][1].

  [1]: https://github.com/espressif/arduino-esp32/blob/master/libraries/ESP32/examples/Time/SimpleTime/SimpleTime.ino


body:
Dears, I have an logger prototype with arduino and [ds3231 breadboard][1]. My code check periodically OSF register to check if oscillator is/was stopped, as informed in [datasheet][2]. I turn on my logger, setting up date/hour, turn of and after some time, turn it on again to check if it's ok.

After that, the logger stay tuned off for a month. When I turned it on after this time, I note that OSF bit was changed, indicating that oscillator was stopped, but the data/time wasn't lost. I don't found possible process that can change the OSF bit in datasheet and [Maxim recommendation][3]. Maybe a negative voltage on VCC that force battery go to bellow threshold can changes the OSF bit (Maxim recommendation and this [post][4]).

Then, I test my logger connecting and disconnecting voltage (VCC) and checking the OSF bit, to simulate this possible begative voltage and not have problem with it.

My question is:

- why the OSF bit changed, indicating lost of battery and consequently lost of date/time, and not lost date/time in my logger;

- what could have happened with my turned off logger to change OSF bit and not lost date;

I'm using [Adafruid RTCLib][5]. Follow the simple code to check OSF bit:

```c
#include <Wire.h>
#include <RTClib.h>

RTC_DS3231 rtc;

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

void loop()
{
  if(rtc.lostPower())
  {
     Serial.println("Date lost");
  }

  delay(1000);
}

```

Thank you!

  [1]: https://protosupplies.com/product/ds3231-rtc-with-eeprom-module/
  [2]: https://www.maximintegrated.com/en/products/analog/real-time-clocks/DS3231.html
  [3]: https://www.maximintegrated.com/en/app-notes/index.mvp/id/504
  [4]: https://electronics.stackexchange.com/questions/242169/rtc-battery-voltage-error-non-ideal-op-amp-error
  [5]: https://github.com/adafruit/RTClib

title: DS3231 OSF register changing without lost date

Answers: 0


body:
I have a nested array, but I get only the correct size of the first one.

I use this as a reference [Arduino sizeOf][1]

    int clockOn_0 [] = {19,0,0};
    int clockOn_1 [] = {20,0,0};

    int clockOff_0[] = {6,0,0};
    int clockOff_1[] = {22,0,0};

    int clock_flag_0[] = {0};
    int clock_flag_1[] = {0};

    int *dailyTO0[] = {clockOn_0,clockOff_0, clock_flag_0};
    int *dailyTO1[] = {clockOn_1,clockOff_1, clock_flag_1};
    int **test[] = {dailyTO0,dailyTO1};

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

      Serial.println("\n");

      for (int m=0; m<sizeof(test)/sizeof(test[0]);m++){
        for (int n=0; n<(sizeof(test[m])/sizeof(test[m][0]));n++){
          for (int i=0; i<(sizeof(test[m][n])/sizeof(test[m][n][0]));i++){
            Serial.println(test[m][n][i]);
          }
        }
      }

    }

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

}

This is the result:

    ⸮Hpxy⸮ $08⸮x$:⸮⸮
    23:29:40.059 ->
    23:29:40.059 -> 19
    23:29:40.059 -> 20

  [1]: https://www.arduino.cc/reference/en/language/variables/utilities/sizeof/

title: Fail to obtain Sizeof Array

Answers: 0


body:
How can I measure Voltage in Range -100mv to +100mv with Arduino ,
Is that an Arduino-shield can do that ?

title: measure very small ( negative and positve ) Voltage with Arduino

Answers: 0


body:
I want to measure very small voltage in small Range -100/+100 mv from a circuit,
can Arduino-shield ACS712 (max471) do that direkt ?

title: can I use Arduino cuurent-shield-sensor to measure very small voltage?

Answers: 0


body:
I am trying to make a ECG monitoring system using Arduino, GSM and ECG sensor which data should be sent to the private server in real time. Those data are then collected via Matlab on the remote computer and analysis should be executed in real time. When using delays in Arduino sketch GSM successfully sends data to the server but those data are sent in big delays (around 30 seconds) and the sketch doesn't send the data of the whole buffer for some reason (it should be 300 samples, but I had to try to lower that number in order to see any results). After removing delays in the loop where data should be continuously sent, GSM is not executing send data command - AT+CIPSEND. Can anybody help me fix the timer issue and explain why is not the whole buffer sent? Thanks in advance.
<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>
    #include <String.h>
    #include "DHT.h"
    int sensorPin = 0;    // set the input pin for the potentiometer
    int sensorValue = 0;
    #define DHTPIN A0
    #define DHTTYPE DHT11
    DHT dht(DHTPIN, DHTTYPE);

    #define DHT11_PIN A0

    SoftwareSerial gprsSerial(7,8);

    float t; // temperature in celcius
    float f; // temperature in fahrenheit
    float h; // humidity

      int samplesPerBuffer = 60;
      char separator = ',';
      String buffer = "";
      int currentBufferPosition = 0;
      unsigned long startSamplingTime = 0;
      const long sampleInterval = 50;

      // gsm modem config
      String gsmBuffer = "";
      int gsmSendingState = 0; // 0 not sending, 1 preparing sending, 2 sending, 3 finishing sending
    //  int gsmSendInterval = 1000;

      int gsmPreparingDelay = 200;
      int gsmSendingDelay = 1500;
      int gsmFinishingDelay = 100;
      unsigned long startRequestTime = 0;

    void setup() {
      // put your setup code here, to run once:
      gprsSerial.begin(9600);               // the GPRS baud rate
      Serial.begin(9600);    // the GPRS baud rate
      dht.begin();
      delay(1000);
      initModem();
    }

    float getSensorData() {
       t = dht.readTemperature();
      //Read humidity
      h = dht.readHumidity();

      // Compute temperature values in Celcius
      t = dht.computeHeatIndex(t,h,false);

      // Check if any reads failed and exit early (to try again).
      if (isnan(t)) {
        Serial.println("Failed to read temp from DHT sensor!");
        return 1;
      }

      return t;
    }

    void initModem() {
      // model init
      if (gprsSerial.available())
        Serial.write(gprsSerial.read());

      gprsSerial.println("AT");
      delay(1000);

      gprsSerial.println("AT+CPIN?");
      delay(1000);

      gprsSerial.println("AT+CREG?");
      delay(1000);

      gprsSerial.println("AT+CGATT?");
      delay(1000);

      gprsSerial.println("AT+CIPSHUT");
      delay(1000);

      gprsSerial.println("AT+CIPSTATUS");
      delay(2000);

      gprsSerial.println("AT+CIPMUX=0");
      delay(2000);

      ShowSerialData();

      gprsSerial.println("AT+CSTT=\"prepaidnet\"");//start task and setting the APN,
      delay(1000);

      ShowSerialData();

      gprsSerial.println("AT+CIICR");//bring up wireless connection
      delay(3000);

      ShowSerialData();

      gprsSerial.println("AT+CIFSR");//get local IP adress
      delay(2000);

      ShowSerialData();

      gprsSerial.println("AT+CIPSPRT=0");
      delay(3000);

      ShowSerialData();
    }

    void prepareSending() {
      gprsSerial.println("AT+CIPSTART=\"TCP\",\"website.com\",\"80\"");//start up the connection
      ShowSerialData();
    }

    void sendData() {
      int time = millis();
      gprsSerial.println("AT+CIPSEND");//begin send data to remote server
      String str="GET http://website.com/channel/" + gsmBuffer;
      Serial.println(str);
      gprsSerial.println(str);//begin send data to remote server
      gprsSerial.println((char)26);//sending
    }

    void finishSending() {
      gprsSerial.println("AT+CIPSHUT");//close the connection
    }

    void loop() {
     int time = millis();
     if (time - startSamplingTime >= sampleInterval) {
        if (buffer.length() == 0) {
          buffer = buffer + (String)getSensorData();
        }
        else {
          buffer = buffer + separator + (String)getSensorData();
        }
        currentBufferPosition++;
        startSamplingTime = time;
     }
     if (gsmSendingState == 0) {
       // copy buffer to gsmBuffer and triger preparing of the request
       if (currentBufferPosition == samplesPerBuffer) {
        Serial.println("GSM - Preparing sending");
        gsmBuffer = buffer;
        Serial.print("Buffer length: ");
        Serial.println(gsmBuffer.length());
        Serial.println(gsmBuffer);
        buffer = "";
        currentBufferPosition = 0;
        prepareSending();
       }

       // send data if we have something in gsmBuffer
       if (time - startRequestTime >= gsmPreparingDelay) {
        if (gsmBuffer.length() > 0) {
          Serial.println("GSM - Sending data");
          sendData();
          gsmBuffer = "";
          gsmSendingState = 1;
          startRequestTime= time;
        }
       }
     } else {
      if (gsmSendingState == 1) {
        if (time - startRequestTime >= gsmSendingDelay) {
          Serial.println("GSM - Finishing request");
          finishSending();
          gsmSendingState = 2;
          startRequestTime = time;
        }
      }
       else {
          if (gsmSendingState == 2) {
            if (time - startRequestTime >= gsmFinishingDelay) {
              Serial.println("GSM - Request finished");
              gsmSendingState = 0;
              startRequestTime = time;
            }
          }
       }
     }
    }

    void ShowSerialData()
    {
      while(gprsSerial.available()!=0)
        Serial.write(gprsSerial.read());
        Serial.print("Temperature = ");
        Serial.println(t);
        Serial.print("Humidity = ");
        Serial.println(h);
        //delay(5000);
    }

    float readTemp() {
      // Read temperature as Celsius
      t = dht.readTemperature();
      //Read humidity
      h = dht.readHumidity();

      // Compute temperature values in Celcius
      t = dht.computeHeatIndex(t,h,false);

      // Check if any reads failed and exit early (to try again).
      if (isnan(t)) {
        Serial.println("Failed to read temp from DHT sensor!");
        return 1;
      }

      return t;
    }

[![First part of serial monitor output][1]][1]

[![Second part of serial monitor output][2]][2]

[![Third part of serial monitor output][3]][3]

I tried with flush but it didn't resolve the problem. What I read yesterday after so much research is that the GSM module (I am using SIM900) cannot transmit more than 64 bytes with GET method, so I decided to try with the POST method, but no luck - code is returning HTTP 411 error - The request has an invalid header name. I tried some variants of resolving that problem but it didn't work. Does anyone have an ide how to resolve this? I haven't found some working example on the Internet, just some explanations which were unclear to me. The new code is below, along with the output.

    /**************************************************************
     *
     * This sketch connects to a website and downloads a page.
     * It can be used to perform HTTP/RESTful API calls.
     *
     * TinyGSM Getting Started guide:
     *   https://tiny.cc/tinygsm-readme
     *
     **************************************************************/

    // Select your modem:
    //#define TINY_GSM_MODEM_SIM800
    // #define TINY_GSM_MODEM_SIM808
     #define TINY_GSM_MODEM_SIM900
    // #define TINY_GSM_MODEM_UBLOX
    // #define TINY_GSM_MODEM_BG96
    // #define TINY_GSM_MODEM_A6
    // #define TINY_GSM_MODEM_A7
    // #define TINY_GSM_MODEM_M590
    // #define TINY_GSM_MODEM_ESP8266

    // Increase RX buffer if needed
    //#define TINY_GSM_RX_BUFFER 512

    #include <TinyGsmClient.h>
    #include <ArduinoHttpClient.h>
    #include <SoftwareSerial.h>
    #include <String.h>
    #include "DHT.h"
    int sensorPin = 0;    // set the input pin for the potentiometer
    int sensorValue = 0;
    #define DHTPIN A0
    #define DHTTYPE DHT11
    DHT dht(DHTPIN, DHTTYPE);

    //SoftwareSerial gprsSerial(7,8);

    float t; // temperature in celcius
    float h; // humidity
    String headerValue = "";

    int samplesPerBuffer = 60;
    char separator = ',';
    String buffer = "";
    int currentBufferPosition = 0;
    unsigned long startSamplingTime = 0;
    const long sampleInterval = 50;
    String gsmBuffer = "";
      int gsmSendingState = 0; // 0 not sending, 1 preparing sending, 2 sending, 3 finishing sending
    //  int gsmSendInterval = 1000;

      int gsmPreparingDelay = 200;
      int gsmSendingDelay = 1500;
      int gsmFinishingDelay = 100;
      unsigned long startRequestTime = 0;

    // Uncomment this if you want to see all AT commands
    //#define DUMP_AT_COMMANDS

    // Uncomment this if you want to use SSL
    //#define USE_SSL

    // Set serial for debug console (to the Serial Monitor, default speed 115200)
    #define SerialMon Serial

    // Use Hardware Serial on Mega, Leonardo, Micro
    #define SerialAT Serial1

    // or Software Serial on Uno, Nano
    //#include <SoftwareSerial.h>
    SoftwareSerial SerialAT(7, 8); // RX, TX

    // Your GPRS credentials
    // Leave empty, if missing user or pass
    const char apn[]  = "prepaidnet";
    const char user[] = "mts";
    const char pass[] = "064";

    // Server details
    const char server[] = "ekg.velizarius.com";
    const char resource[] = "/71F977B8DE73/";

    #ifdef DUMP_AT_COMMANDS
      #include <StreamDebugger.h>
      StreamDebugger debugger(SerialAT, SerialMon);
      TinyGsm modem(debugger);
    #else
      TinyGsm modem(SerialAT);
    #endif

    #ifdef USE_SSL
      TinyGsmClientSecure client(modem);
      const int  port = 443;
    #else
      TinyGsmClient client(modem);
      const int  port = 80;
    #endif

    HttpClient http(client, server, port);

    void setup() {
      // Set console baud rate
      SerialMon.begin(9600);
      delay(10);

      // Set GSM module baud rate
      SerialAT.begin(9600);
      delay(3000);

      // Restart takes quite some time
      // To skip it, call init() instead of restart()
      SerialMon.println(F("Initializing modem..."));
      modem.restart();

      String modemInfo = modem.getModemInfo();
      SerialMon.print(F("Modem: "));
      SerialMon.println(modemInfo);

      // Unlock your SIM card with a PIN
      //modem.simUnlock("1234");
    }

    void loop() {
      SerialMon.print(F("Waiting for network..."));
      if (!modem.waitForNetwork()) {
        SerialMon.println(" fail");
        delay(10000);
        return;
      }
      SerialMon.println(" OK");

      SerialMon.print(F("Connecting to "));
      SerialMon.print(apn);
      if (!modem.gprsConnect(apn, user, pass)) {
        SerialMon.println(" fail");
        delay(10000);
        return;
      }
      SerialMon.println(" OK");

      SerialMon.print(F("Connecting to "));
      SerialMon.print(server);
      if (!client.connect(server, port)) {
        SerialMon.println(" fail");
        delay(10000);
        return;
      }
      SerialMon.println(" OK");

    /*==================================================================================*/
      http.connectionKeepAlive();
      http.beginRequest();
      int codePost = http.post("/71F977B8DE73/");
    //
    //  DEBUG_MSG_LINE(F("Returned status after post = "));
    //  DEBUG_MSG(codePost);
      http.post("url");
      http.sendHeader(F("Content-Type"), F("text/html"));
      http.sendHeader(F("Content-Length"), String(t).length());
      client.println();
      http.beginBody();
      http.println(String(t));
      http.endRequest();
    /*===============================================================================*/

      // Make a HTTP POST request:
      client.print(String("POST ") + resource + " HTTP/1.0\r\n");
      client.print(String("Host: ") + server + "\r\n");
      client.print(String(F("\r\nHeader: ")) + headerValue);
      client.print(String(F("\r\n\r\n")));
      client.print(String(t));
      client.print("Connection: close\r\n\r\n");

      unsigned long timeout = millis();
      while (client.connected() && millis() - timeout < 10000L) {
        // Print available data
        while (client.available()) {
          char c = client.read();
          SerialMon.print(c);
          timeout = millis();
        }
      }
      SerialMon.println();

      // Shutdown

      client.stop();
      SerialMon.println(F("Server disconnected"));

      modem.gprsDisconnect();
      SerialMon.println(F("GPRS disconnected"));

      // Do nothing forevermore
    //  while (true) {
    //    delay(1000);
    //  }
    }

    float getSensorData() {
       t = dht.readTemperature();
      //Read humidity
      h = dht.readHumidity();

      // Compute temperature values in Celcius
      t = dht.computeHeatIndex(t,h,false);

      // Check if any reads failed and exit early (to try again).
      if (isnan(t)) {
        Serial.println("Failed to read temp from DHT sensor!");
        return 1;
      }
      return t;
    }

[![http 411][4]][4]

  [1]: https://i.stack.imgur.com/1DdV1.jpg
  [2]: https://i.stack.imgur.com/980W7.jpg
  [3]: https://i.stack.imgur.com/u0brO.jpg
  [4]: https://i.stack.imgur.com/1y8SF.jpg

title: Send ECG data using buffer in real time to the server without using delay

Answers: 0


body:
I have the following situation. <br/>
    I would like to develop a bracelet prototype that identifies when a person is on the go and also issue a question to the person for that bracelet and get an answer, depending on the status of the response by sending a notification to a mobile app. I am interested in what Arduino technologies to use.

title: Voice receiver arduino

Answers: 0


body:
My Arduino Nano can't get a reply from my new ENC28J60 Ethernet Shield - I can't get any library examples to work. Using the UIPEthernet lib, and running the EchoServer example with logging turned up, I get:

    ENC28J60::init DEBUG:csPin = 10
    ENC28J60::init DEBUG:miso = 12
    ENC28J60::init DEBUG:mosi = 11
    ENC28J60::init DEBUG:sck = 13
    ENC28J60::init DEBUG:Use Native hardware SPI
    Enc28J60Network::writeOp(uint8_t op, uint8_t address, uint8_t data) DEBUG_V3:Function started
    ENC28J60::init DEBUG_V3:Before readOp(ENC28J60_READ_CTRL_REG, ESTAT)
    Enc28J60Network::readOp(uint8_t op, uint8_t address) DEBUG_V3:Function started
    ...

so it gets nicely into the Enc28J60Network::init function. But shortly after, it does a phyWrite, tries to read a response, and then times out.

    ENC28J60::init DEBUG_V3:Before phyWrite(PHCON2, PHCON2_HDLDIS)
    Enc28J60Network::phyWrite(uint8_t address, uint16_t data) DEBUG_V3:Function started
    ... lots of attempts to read
    Enc28J60Network::phyWrite ERROR:TIMEOUT !!

And then it all starts to fail, and it never gets better. I tried the EtherCard lib, too, and it fails in a similar way.

I put the scope on the SPI pins, and I see reasonable stuff: activity on SCK and MOSI, nothing on MISO, and the SS (pin 10) switching ok - and the shield claims to use pin 10 (I briefly tried pin 8 as I flailed in confusion, but no luck there either).

So at this point, either I'm misunderstanding something, or the shield is DOA.

*Update*: Earlier, I strongly suspected the SCK line because it showed a very poor signal on my scope. But it turned out to be poor grounding on the scope probe, and the signal  was actually fine, a red herring. Thanks to @Majenko for drawing my attention to it.

*Update 2*: After getting no SPI response from the shield under any circumstances, my working hypothesis is that it was DOA. I've gone back to my UNO with W5100: all working fine. I have ordered more Nano ethernet shields, to arrive in a week or two, so I'll try with those, and provide updates/answers then.

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

title: Nano can't get reply from ENC28J60 Ethernet Shield

Answers: 2

body: The ENC28j60 shield for Nano has reset of the ENC28j60 chip on the pin 7 of the shield/Nano. Try to set the pin 7 HIGH.

body:
Thanks to @Riad, who posted this as a comment. The problem appears to be a design fault in the "DK ectronics" V1.0 Ethernet Shield.

> Perhaps this could bring some solution. https://www.mikrocontroller.net/topic/477142

The site is in German, so here's a brief translation of the key parts:

>I bought an ENC28J60 for the Arduino Nano, but it does not respond from the programmed IP.

>The shield has "NANO Ethernet Shield V1.0 DK ectronics" inscribed on the underside (spelling error in the original). There
there is a via on the bottom between pins D11 and D12,
missing from a (different) working shield. This via connects D12 line to GND from the AMS1117 on the top (easy to check D12 to GND with a multimeter). If that's the case with your shield, then this is the problem: we just have to cut out the via connection. I have
Do this with a 1mm drill by placing the top copper layer in the
via very gently (really gently!) Mill it away. If you drill too deep, you break the D12 connection completely and must possibly
solder on a new wire. Keep checking D12 and GND for continuity to see whether you've milled away enough. Work really carefully!

>After I did that, and tried the TCP Server example in the UIPEthernet
library on the Arduino, the shield was reachable.

>  -- Christoph K

I haven't yet tried to make the changes described above, because they are fiddly and I have a new batch of working shields. But my device is exactly as described by Christoph and his photos, and the fault description matches mine.


body: I have an Arduino Yun board and an Atmel ICE programmer/debugger. There are 6 pins on the Arduino Yun to connect to Atmel ICE for programming only, but I can't find the pins for debugging. Anyway to do so? Which pins on the Arduino should I connect to Atmel ICE?

title: How to debug Arduino using Atmel studio?

Answers: 1

body:
I found another very easy way to debug the arduino board with atmel studio without even using an external debugeer like the atmel ice debugger. It's an extension called vMicro which can be added within atmel studio (visual studio as well) you connect the arduino board over the micro USB to the computer and specify the parameters in the vMicro toolbar in atmel studio and that's it!
 It's ready to debug! Finally I think atmel ice is thought for other boards maybe, since debugging can be done without it easily!


body:
I am trying to create a timer that outputs the time remaining in minutes. I am using an Adafruit Circuit Playground Express.
For example, if the timer is 5 minutes, then every minute it should output the time remaining, until the time ends.

5 minutes timer started.

Delay: 5 minutes

Delay: 4 minutes

Delay: 3 minutes

Delay: 2 minutes

Delay: 1 minute

This is my attempt to implement this. I would like it to start by displaying  "Delay: 5 minutes"; however, this is not output until 1 minute has passed.

What am I doing incorrectly?

    const long interval = 1 * 60 * 1000UL;
    unsigned long previousMillis = 0;
    int minutes = 5 ;

     unsigned long currentMillis = millis();

      while (minutes >= 0){
      if (currentMillis - previousMillis >= interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

        Serial.print(F("Delay: "));
        Serial.print(minutes);
        Serial.println(F(" minute(s)"));
        minutes = minutes - 1;
      }
      }

title: 5 minute timer output time remaining

Answers: 1

body:
Try this: (I don't have an Arduino here so i can't test it)

    int minutes = 5;
    int passedminutes = 0;
    void setup() {
     Serial.begin(9600);
    }
    void loop() {
      while((millis() - minutes*60000) < 0)
      {
        if(millis()`000 == 0)
        {
          Serial.print("Remaining Time: ");
          Serial.println(minutes-passedminutes);
          Serial.println();
          passedminutes++;
          delay(1);
        }
      }
    }


body:
Firstly, I'd like to mention that I'm a beginner. This is the first time I've worked with a GPS module. The serial monitor is completely empty when I upload the following code to my circuit:
<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>

    // The serial connection to the GPS module
    SoftwareSerial ss(4, 3);

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

    void loop(){
      while (ss.available() > 0){
        // get the byte data from the GPS
        byte gpsData = ss.read();
        Serial.write(gpsData);
      }
    }

![The circuit I used](https://i.stack.imgur.com/7Ghrc.png)

Things I might've done wrong and some things I'd like to mention:

1. As you can see, I connected the module to 5V pin of Arduino but the datasheet says:
![Datasheet says that the maximum voltage that can be used is 3.6 V and the module can't stand overvoltage](https://i.stack.imgur.com/JStxq.jpg)
The reason why I think this might not be the case is that there are multiple projects on the internet that have used a circuit like mine.

2. I've placed my module on the window edge so that it can get a good line of sight. I'm yet to try it outdoors.

3. After reading the datasheet, I tried a potential divider using resistors to get 3.3V and the result is still nothing. I later realized that this was probably a really silly thing to do since I created an unstable supply which is not suitable for the module.

4. For cold-start conditions, how long can it take to lock to a satellite? I've waited several times for half an hour each time only to get no result in the end. Can it take more than that? Should I wait?

5. What can I use to supply constant 3.3V to the module? Are there any special power supplies for GPS modules?

6. Is it possible to tell if my module is damaged just by seeing?

title: Problem with powering ublox NEO-6M GPS module

Answers: 1

body:
1. The module may very well be dead now, due to giving it 5V.

But depending on which board the module is mounted on, there might be a voltage regulator that expects 5V. Check the specifications for the board you bought.

 2. A window means that at least 50% of the sky is blocked by the building. The module might not be able to get a signal from enough satellites for a cold start.

 3. A voltage divider only works if there is constant current. As you've noted, you just created an unstable power supply.

 4. The datasheet says 27 s but that is probably with a clear view of the sky.

 5. Next to the 5V pin on the Uno is a 3.3V pin. How about using that?

 6. Visually, no. But the Arduino should be able to communicate with the module if the module still works, regardless if the module has a GPS fix or not.


body:
I stored "**28328630**" in sd card but at output i getting wrong value.
on serial "**5566**" getting this value.

#include "HX711.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SPI.h>
#include <SD.h>
int data = 0;
int curr_rate = 0;  // current flow rate in L/M

File dataFile;
HX711 scale(A1, A0);
LiquidCrystal_I2C lcd(0x3F, 16, 2);  // set the LCD address to 0x27 for a 16 chars and 2 line display
const int buttonPin = 8;
int total;
int buttonState = 0;
void setup()
{
  lcd.init();
  lcd.init();
  lcd.backlight();

  lcd.setCursor(0, 0);
  lcd.print("KWALITY PVT.LTD.");
  Serial.begin(38400);

  while (!Serial)
  {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
  if (!SD.begin(4))
  {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    // return;
  }
  Serial.println("card initialized.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("datalog.txt"); //<<<<<<<<<<<<<< set the name

  // if the file is available, write to it:
  if (dataFile)
  {
    while (dataFile.available())
    {
      Serial.write(dataFile.read());      //<<<<<<<<<<<<< remove
      total = total + dataFile.parseInt();  //<<<<<<<<<<<<<<<< new
    }
    lcd.clear();
    dataFile.close();
    Serial.print("Total: ");
    lcd.setCursor(0, 1);
    lcd.print("Total:");
    Serial.println(total);
    lcd.setCursor(6, 1);
    lcd.print(total);
    Serial.print("Value in sd card 28328630....");
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening file");
  }

  scale.set_scale(2280.f);
  scale.tare();

}

void loop()
{
  buttonState = digitalRead(buttonPin);
  dataFile = SD.open("datalog.txt", FILE_WRITE);

  if (buttonState == HIGH) {

    if (scale.get_units() > 10 && scale.get_units() < 200)
    {

      //SET1
      lcd.setCursor(0, 0);
      lcd.print("LPM: ");
      lcd.setCursor(5, 0);
      data = (scale.get_units() / 10);
      lcd.print(data);
      scale.power_down();
      delay(5000);
      scale.power_up();

    //  scale.power_down();
      delay(60000);
     // scale.power_up();
      lcd.clear();

      if (dataFile) {
        Serial.print("Writing to datalog.txt...");
        dataFile.println(data);
        // close the file:
        dataFile.close();
        Serial.println("done.");
      } else {
        // if the file didn't open, print an error:
        Serial.println("error opening test.txt");
      }

      curr_rate = (data + total);
      Serial.print("Total: ");
      lcd.setCursor(0, 1);
      lcd.print("TOTAL:");
      lcd.setCursor(7, 1);
      lcd.print(curr_rate);

    }
    else
    {
      lcd.setCursor(0, 0);
      lcd.print("LPM: ");
      lcd.setCursor(5, 0);
      lcd.print("000   ");
      delay(500);
      lcd.print("        ");

      if (dataFile) {
        Serial.print("Writing to datalog.txt...");
        dataFile.println("0");
        // close the file:
        dataFile.close();
        Serial.println("done.");
      } else {
        // if the file didn't open, print an error:
        Serial.println("error opening test.txt");
      }

    }
  }
  else {
    lcd.setCursor(0, 0);
    lcd.print("     SENSOR    ");
    lcd.setCursor(0, 1);
    lcd.print("  DISCONNECTED  ");
    delay(2000);
    lcd.clear();

  }

}

title: Getting wrong value from sd card

Answers: 0


body:
I made a sketch to switch on all digital and analog pins, and found out several pins did not work as expected. Note: I manually put a jumper wire from each digital and analog pin (one at a time) to a resistor, LED and GND pin.

What I noticed was that some pins did not work (D3, D4, A4, A6 and A7) and pin A3 was only lit about half intensity. I tried two different Nanos and they performed both equally (also pin A3 at half intensity).

I also tried the jumper wires directly touching the pins (without a breadboard in between, to rule out a breadboard problem). Same behavior (so the breadboard is ok).

My questions:

1. How come pins D3, D4, A4, A6 and A7 are not output VCC (3.3V) ?
2. How can I switch pins these pins on?
3. What is the reason pin A3 is blinking at half intensity?
4. How can I switch this pin fully on?
5. Bonus question: I used numbers, why are the pin names A0..A7 and D0..D12 not defined in Arduino IDE?

---

Test sketch:

    const int NR_OF_PINS = 22;

    int pins[NR_OF_PINS]   =
    // 0  1  2  3  4  5  6   7   8   9  10 11   12  13  14  15  16  17  18  19  20  21
    //D0 D1 D2 D3 D4 D5 D6  D7  D8  D9 D10 D11 D12 D13  A0  A1  A2  A3  A4  A5  A6  A7
     { 1, 2, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25, 26 };

    void setup()
    {
      for (int n = 0; n < NR_OF_PINS; n++)
      {
        pinMode(pins[n], OUTPUT);
        digitalWrite(pins[n], HIGH);
      }
    }

    void loop()
    {
    }

title: How come some Arduino Nano pins (D3, D4, A3, A4, A6, A7) cannot be set high?

Answers: 1

body:
You don't need an array, and your "base" pin is wrong - you start at pin 1, not pin 0. Also pins A6 and A7 can only be analog inputs, not digital outputs.

It's simpler to write:

    void setup() {
        for (uint8_t i = 0; i < NUM_DIGITAL_PINS; i++) {
            pinMode(i, OUTPUT);
            digitalWrite(i, HIGH);
        }
    }

    void loop() {
    }

That will work correctly on all Arduino boards regardless of the number of pins, since the board definition defines how many pins there are, and pins are always contiguously numbered from 0.


body:
I have an ESP8266 wifi module that I want to test, to use it later. I uploaded the original Espressif AT firmware "ESP8266 AT Bin V1.7.0" from: https://www.espressif.com/en/support/download/at.

FTDI seems to be connected to the ESP all properly, since firmware upload successfully finished and prompted:

> Leaving...
> Hard resetting via RTS pin...

I use the Arduino IDE's serial monitor at 115200 baud rate set to "both NL & CR", to send the commandS "AT", "AT+GMR" e.t.c.

No response ever returns. I have no idea about what am I doing wrong, or why esptool.py can connect to the board smoothly but there is a problem with sending AT commands to it.

Thanks for all suggestions in advance. Please comment if you need any other information about the issue.

P.S: I have two modules bought at different times. Both of them wont work with AT commands.

title: ESP8266-01 Does not receive or respond to AT Commands

Answers: 0


body: I'd like to build a self-contained bicycle distancemeter similar to those now used by local police, i.e. that measure and display the distance between the bicycle handlebar's end and passing cars and beep when distance is less than 1m on 50-km/h roads. In order to avoid detecting cars when stopped at traffic lights, I need to determine whether the bicycle is moving above a minimum speed, say 10 km/h. How can I do that without having to install additional hardware on the bicyle, like a magnet on the wheel and a sensor on the fork? Accelerometers?

title: Determing approximate bicycle speed for distancemeter

Answers: 2

body:
I have built many years ago a device nearly identical to what you describe. I did not have the additional requirement of a minimum speed of 10 kph, however. As noted in the comments, that is likely best resolved with GPS as you are detecting motion, not absolute speed figures.

I used "arduino gps library" as the search terms and found many options. One of them, [TinyGPS++][1] appears to have what you require and much more:

> TinyGPS++ is a new Arduino library for parsing NMEA data streams
> provided by GPS modules.
>
> Like its predecessor, TinyGPS, this library provides compact and
> easy-to-use methods for extracting position, date, time, altitude,
> speed, and course from consumer GPS devices.
>
> However, TinyGPS++’s programmer interface is considerably simpler to
> use than TinyGPS, and the new library can extract arbitrary data from
> any of the myriad NMEA sentences out there, even proprietary ones.

I would definitely appreciate the "considerably simpler" aspect, as well as the "extract arbitrary data" portion, which seems specific to your project.

There may be other libraries that provide your objective, this was the first on the search returns.

The device I constructed used the common ultrasonic detector with a transmitter and receiver pair, coupled to a set of seven-segment LED display blocks. When the slightly-less-than-one-meter distance was presented, my device would trigger a pair of cameras. For your beep purpose, it would be straight-forward to redirect the camera trigger to a piezo speaker module or any other suitable audio device. I did not require GPS or other speed information.

  [1]: http://arduiniana.org/libraries/tinygpsplus/

body:
GPS would be simple in terms of being self-contained, but a GPS module is somewhat expensive, and is also a big power drain.

I'd recommend a wheel sensor. Some modern wireless bike-computers use accelerometer based wheel RPM sensors. You attach them to the spokes and they detect the motion with/against the force of gravity as they travel up and down. They use wireless communication like BLE (Bluetooth Low Energy.) If you added a BLE module to your Arduino you might be able to pair it with a wireless RPM sensor and measure speed that way, with no wires or magnets needed.

## EDIT:

I don't know for sure what wireless protocol these accessories use. If it's not BLE then interfacing them with an Arduino might be harder.


body:
Can Arduino handle variable variables?
<!-- language-all: lang-cpp -->

    function getLetterCode(char input) {
        int letter_a = 17;
        int letter_b = 42;
        int letter_c = 50;
        return letter_$$input$$; //pseudocode
    }

This is just a stripped down code to demonstrate my question. I am aware of arrays, the switch structure and other workarounds, but for my specific need variable variables would save tons of typing.

title: How to access variables by variable? (I.e. variable variables?)

Answers: 1

body:
No, you can't do that sort of thing. That sort of thing is only possible on interpreted languages where the name of the variables is seen at runtime.  In compiled languages you can't see the variable names (they no longer exist) so you can't access them by name like that.

Instead you need to either store your variables in a simple array and access them by index, or create an array of "key/value" pairs (simplest to use an array of a `struct`) and iterate it looking for the right key to match with your input.  Or, if there aren't too many inputs, simply use a `switch` to select different values:

    int getval(char input) {
        switch (input) {
            case 'a': return 17;
            case 'b': return 42;
            case 'c': return 50;
            default: return 0;
        }
    }


body:
I have scavenged an industrial servo with its attached ballscrew linear actuator from an old large format scanner, and I am trying to figure out how to make a 'servo drive' aka 'servo driver' aka 'servo controller'.

I'm a total novice at arduino, and am mostly a copy/paste coder - so of course this makes my goal harder.

I can find a lot of information on how to read a simple AB offset encoder that needs _**four**_ wires to work, but the encoder I have has eight wires:

A+, A-, B+, B-, Z+, Z-, +5v, 0v(aka GND)

With +5v supplied to it's wire and GND connected to 0v, rotating the motor shaft by hand, my meter reads:

 - A+: +3.97v as the 'high' and +.036v as 'low'
 - A-: same
 - B+: same
 - B-:    same
 - Z+: same - but only goes high at one location on the 360 degree
     rotation
 - Z-: same - but only goes high at one location on the 360 degree
   rotation - the same location as Z+

NOTE: Both Z pulses coincide with pulses on A+, B+, and B- ... but those are NOT coincident on A-. So maybe A- has the Z+/- trigger in it's place? I don't know. It was VERY challenging to stop rotating the shaft AT a pulse because of the tiny size of the divisions.

All voltages seen by my digital multimeter were positive voltages.

I do not understand how to properly use the encoder with so many wires. I can sort of understand that the positive and negative are probably opposite signals from each other, sort of error protection or something? I know that the Z= and Z- are roattion counters at either 90, 180, or some other offset angle to allow ticking full rotations. But am unsure about this all and am reading a lot of material that is beyond me. I'm stumped.

I can install the following code on an UNO and the UNO reads the encoder just fine off the A+ and B+ lines, with increasing count for one direction of rotation and decreasing count for the other direction. So it is reflecting the movement as it should...

BUT- I am getting 8000 pulses per shaft revolution rather than the 2000 pulses per revolution in the documentation. So something's not right here. I should see 2000 pulses per revolution... is this because of the lack of use of the other wires? Or something else?

Code i'm using for just A+ and B+:

        /*
    *Quadrature Decoder
    */
    #include "Arduino.h"
    #include <digitalWriteFast.h>

    // Quadrature encoders
    // Left encoder
    #define c_LeftEncoderInterruptA 0
    #define c_LeftEncoderInterruptB 1
    #define c_LeftEncoderPinA 2
    #define c_LeftEncoderPinB 3
    #define LeftEncoderIsReversed

    volatile bool _LeftEncoderASet;
    volatile bool _LeftEncoderBSet;
    volatile bool _LeftEncoderAPrev;
    volatile bool _LeftEncoderBPrev;
    volatile long _LeftEncoderTicks = 0;

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

      // Quadrature encoders
      // Left encoder
      pinMode(c_LeftEncoderPinA, INPUT);      // sets pin A as input
      digitalWrite(c_LeftEncoderPinA, LOW);  // turn on pullup resistors
      pinMode(c_LeftEncoderPinB, INPUT);      // sets pin B as input
      digitalWrite(c_LeftEncoderPinB, LOW);  // turn on pullup resistors
      attachInterrupt(c_LeftEncoderInterruptA, HandleLeftMotorInterruptA, CHANGE);
      attachInterrupt(c_LeftEncoderInterruptB, HandleLeftMotorInterruptB, CHANGE);
    }

    void loop()
    {
      Serial.print("Encoder Ticks: ");
      Serial.print(_LeftEncoderTicks);
      Serial.print("  Revolutions: ");
      Serial.print(_LeftEncoderTicks/2000.0); //2000 Counts Per Revolution, per the engineering manual
      Serial.print("\n");
    }

    // Interrupt service routines for the left motor's quadrature encoder
    void HandleLeftMotorInterruptA(){
      _LeftEncoderBSet = digitalReadFast(c_LeftEncoderPinB);
      _LeftEncoderASet = digitalReadFast(c_LeftEncoderPinA);

      _LeftEncoderTicks+=ParseEncoder();

      _LeftEncoderAPrev = _LeftEncoderASet;
      _LeftEncoderBPrev = _LeftEncoderBSet;
    }

    // Interrupt service routines for the right motor's quadrature encoder
    void HandleLeftMotorInterruptB(){
      // Test transition;
      _LeftEncoderBSet = digitalReadFast(c_LeftEncoderPinB);
      _LeftEncoderASet = digitalReadFast(c_LeftEncoderPinA);

      _LeftEncoderTicks+=ParseEncoder();

      _LeftEncoderAPrev = _LeftEncoderASet;
      _LeftEncoderBPrev = _LeftEncoderBSet;
    }

    int ParseEncoder(){
      if(_LeftEncoderAPrev && _LeftEncoderBPrev){
        if(!_LeftEncoderASet && _LeftEncoderBSet) return 1;
        if(_LeftEncoderASet && !_LeftEncoderBSet) return -1;
      }else if(!_LeftEncoderAPrev && _LeftEncoderBPrev){
        if(!_LeftEncoderASet && !_LeftEncoderBSet) return 1;
        if(_LeftEncoderASet && _LeftEncoderBSet) return -1;
      }else if(!_LeftEncoderAPrev && !_LeftEncoderBPrev){
        if(_LeftEncoderASet && !_LeftEncoderBSet) return 1;
        if(!_LeftEncoderASet && _LeftEncoderBSet) return -1;
      }else if(_LeftEncoderAPrev && !_LeftEncoderBPrev){
        if(_LeftEncoderASet && _LeftEncoderBSet) return 1;
        if(!_LeftEncoderASet && !_LeftEncoderBSet) return -1;
      }
    }

.
.
.
Can someone explain the function of, and how to use, all eight wires? Explain why I'm getting 4X the counts that I should with that code above? PLEASE?
.
.
.

I'm posting images of the pages from the machine's engineering handbook that have info about the servo and encoder. The info there shows that it was more or less controlled like an RC servo from the mainboard's perspective - just PWM. But it had the drive/driver/controller parts right on the mainboard of the machine.

If it will be of use I can post pictures of the encoder board itself, but at this point I did not think that necessary.

[![Piniout of connector][1]][1]
[![Servo encoder resolution][2]][2]
[![Specs part 1][3]][3]
[![Specs part 2][4]][4]

  [1]: https://i.stack.imgur.com/z5FDM.jpg
  [2]: https://i.stack.imgur.com/PsWWz.jpg
  [3]: https://i.stack.imgur.com/DnQAx.jpg
  [4]: https://i.stack.imgur.com/bVwIX.jpg

title: Undocumented industrial servo with 8-wire encoder: how to read this encoder?

Answers: 2

body:
You have already found out, how the encoder works (basically like any other rotary encoder, only with more outputs for different angle values). That is great work.

You get a value 4 times as big because of 2 little mistakes:

1. When you use `attachInterrupt()`, you set it to trigger on a `CHANGE` of the line. One pulse consists of 2 changes (for example LOW to HIGH and then HIGH to LOW). So the interrupt get's triggered twice per encoder pulse. That's a factor of 2 for the resulting value.

2. You attach an interrupt to both of the lines, but both lines output one pulse per one encoder tick. So the value get's incremented twice per tick, what means another factor of 2. You only need an interrupt on one of the lines. The other line is only there to indicate the direction of the rotation. When the interrupt for the first line triggers, you should check the value of the second line. If it is HIGH, the encoder is rotating in one direction. If it is LOW, it rotates in the oposite direction. The lines are internally connected to little buttons/switches, that are fixed to the casing with a little offset between then. They get activated by little nubs, that are connected to the axis. Depending on from which direction the nub comes during a rotation, the first or the second button/switch will get activated first. A little after that, also the second switch will activate. So you can monitor one line, and if a pulse starts on it, you check if there already is a pulse on the other line. If yes, the other line was activated first.

So all in all this results in the factor 4 in the encoder results.

---

Note, that your `ParseEncoder()` function is a little redundant and overcomplicated. In the inner if statements you check for some values, that cannot happen in there because of the outer if statement. But this function will reduce itself to simply one if statement (or less, if you use the value directly without if), since with the above, you only need to check the value of 1 line.

body:
I had some trouble figuring this out too.
I did some more googling and found this site below via an Arduino forum post:
[8 wire connection for quadrature encoder, differential wiring][1]

Here is what they say:

 > "These terms refer not to the waveforms of signals, but instead to the way the signals are wired.
 >
 > Single-ended wiring uses one signal wire per channel and all signals are referenced to a common ground.
 >
 > [TTL][2] and [Open Collector][3] are types of single-ended wiring.
 >
 > Differential wiring uses two wires per channel that are referenced to each other. The signals on these wires are always 180 electrical degrees out of phase, or exact opposites. This wiring is useful for higher noise immunity, at the cost of having more electrical connections. Differential wiring is often employed in longer wire runs as any noise picked up on the wiring is common mode rejected."

So basically we have our Power supply wire and ground, and 2 wires per signal (A+/A-, B+/B-, Z+/Z-).

2 + 6 wires = 8 wires

Now all I have to figure out is how to connect those 6 wires to an Arduino. I get how to connect the A+, B+, Z+ signals on 3 interrupt pins, now I'm just wondering if the other 3 (A-, B-, Z-) should be connected to 3 more interrupt pins.

  [1]: https://www.eeweb.com/understanding-incremental-encoder-signals/
  [2]: https://en.wikipedia.org/wiki/Transistor-transistor_logic
  [3]: https://en.wikipedia.org/wiki/Open_collector


body:
I am using a DHT11 sensor attached to a NodeMCU ESP8266 to have a web server reporting the local humidity and temperature values. I don't have a resistor attached in the circuit, the DHT11 is directly connected to the NodeMCU board. Till yesterday, the setup was giving me correct values, but from today morning, I am getting all nulls from the sensor. Does this mean that the sensor is dead? Should I have had a resistor attached to the circuit to prevent this, or does that not make any difference?

EDIT:

Please consider my question before negative voting me. I considered this question:

https://arduino.stackexchange.com/questions/47124/problem-with-a-dht11-temperature-humidity-sensor

I have followed the circuit diagram as given in the following page:

https://www.electronicwings.com/nodemcu/dht11-sensor-interfacing-with-nodemcu

It's just that I am using a NodeMCU istead of an Arduino. Does that make my question unworthy of posting here? The problem is similar.

title: DHT11 sensor reporting all null values

Answers: 0


body:
So I have a project where I send text to an Arduino, which is then printed out as a QR code on a thermal printer that can take a bitmap image with a given width and height.

Is there a way I can "scale up" the "image," making it so one pixel is scaled up to 4 or 8 pixels?

Additionally, would it be possible to add a "quiet zone" of sorts on the left side of the image, as I am not able to offset/justify it to the middle.

QR Code lib: https://github.com/ricmoo/QRCode

Thermal printer lib: https://github.com/adafruit/Adafruit-Thermal-Printer-Library

title: How to scale a bitmap (uint8_t array) in Arduino?

Answers: 1

body:
You didn't tell use the size of your QRCode, nor the type of Arduino you
are using. So I am just going to guess that your problem is that you may
have enough RAM to store the raw QRCode, but not enough to store a
scaled bitmap version.

The [Adafruit tutorial][tuto] for their thermal printer library suggests
printing bitmaps with the method:

```c++
printBitmap(width, height, tablename)
```

where `tablename` is an array holding the bitmap data. This will
obviously not work if you don't have enough RAM to store the array.
Fortunately, there is an overloaded method:

```c++
void Adafruit_Thermal::printBitmap(int w, int h, Stream *fromStream)
```

that allows you to stream the image data instead of preparing it in RAM.
You can create a stream that delivers arbitrary data by writing a class
that derives from `Stream`. Here is a tentative, untested
implementation, that delivers a scaled-up QRCode one pixel at a time:

```c++
// Stream a scaled QRCode one pixel at a time.
class QRCodeStream : public Stream
{
public:
    QRCodeStream(const QRCode &code, uint8_t scale = 1)
    : qrcode(code), scale(scale) {}

    // Output: writing to this stream is a no-op.
    size_t write(uint8_t) {}
    void flush() {}

    // Input delivers the QRCode pixels.
    int available();
    int peek();
    int read();
private:
    QRCode &qrcode;
    uint8_t scale;
    bool done = false;
    uint8_t code_x = 0;  // coordinates of the QRCode module
    uint8_t code_y = 0;
    uint8_t pix_x = 0;  // pixel coordinates within the module
    uint8_t pix_y = 0;
};

int QRCodeStream::available()
{
    // For simplicity, pretend the bytes come one at a time.
    if (done) return 0;
    else return 1;
}

int QRCodeStream::peek()
{
    if (done) return -1;
    if (qrcode_getModule(&qrcode, code_x, code_y)) {
        return 0;  // black
    } else {
        return 255;  // white
    }
}

int QRCodeStream::read()
{
    if (done) return -1;
    int data = peek();

    // Move to the next pixel.
    if (++pix_x >= scale) {
        pix_x = 0;
        if (++code_x >= qrcode.size) {
            code_x = 0;
            if (++pix_y >= scale) {
                pix_y = 0;
                if (++code_y >= qrcode.size) {
                    done = true;
                }
            }
        }
    }

    return data;
}
```

This would be used as

```c++
printer.printBitmap(width, height, QRCodeStream(qrcode, scale));
```

Note that `QRCodeStream` delivers the image data as 8-bit gray scale,
where each pixel is returned as one byte, either 0 (for black) or 255
(for white). This is likely not the format expected by the thermal
printer library, which seems to expect 1-bit black and white data, with
8 pixels packed in each byte. You will have to adapt the code for
the right format, which will likely be tedious, but not overly complex.
I leave that “as an exercise to the reader”.

[tuto]: https://learn.adafruit.com/mini-thermal-receipt-printer?view=all#bitmap-printing


body:
I did a project for IoT attendance system using ESP8266 and RDM6300. However, I can connect to wifi using WiFiMulti.addAP() function for my home WiFi.

I tried **WiFi.begin() instead of WiFiMulti.addAP()** function to connect to my mobile hotspot but the esp8266 is failing to connect. In fact, **WiFi.begin() also failed to connect to the same wifi router which was previously connected by WiFiMulti.addAP()**. Serial monitor constantly showing the below error.

    Exception (3):
    epc1=0x4020970d epc2=0x00000000 epc3=0x00000000 excvaddr=0x4003bfc9 depc=0x00000000

    >>>stack>>>

    ctx: cont
    sp: 3ffffbc0 end: 3fffffc0 offset: 01a0
    3ffffd60:  00000000 00000004 3ffffe40 3ffffef0
    3ffffd70:  4010156c 0000049c 000003fd 40209837
    3ffffd80:  0000049c 00001000 000003fd 4010156c
    3ffffd90:  40106980 3ffe85ad 3ffffe40 402354f1
    3ffffda0:  401004a5 402355db 3fff0c1c 0000049c
    3ffffdb0:  000003fd 3ffffef0 3fff0c1c 402355be
    3ffffdc0:  ffffff00 55aa55aa 00000035 00000020
    3ffffdd0:  00000020 00000048 0000004a aa55aa55
    3ffffde0:  000003ff 40235aa8 3fff0c1c 3fff0c1c
    3ffffdf0:  000000ff 3fff0c1c 0000049c 00000000
    3ffffe00:  401004a5 00000001 3fff0c2c 40235cc2
    3ffffe10:  00000008 3fff0c1c 000000ff 3ffffef0
    3ffffe20:  3fffff10 3fff0c53 00000035 00000020
    3ffffe30:  3fff0cdc 3fffff51 00000001 40235d72
    3ffffe40:  3ffffef0 40242be0 00000000 0000000c
    3ffffe50:  3fff101c 3fffff10 3fff6f54 40235d41
    3ffffe60:  3fff0c1c 40235da8 3ffe84dc 3ffe85ae
    3ffffe70:  402019ca 3ffe85ae 3ffe85b3 40201927
    3ffffe80:  61666152 00000074 3ffffe60 40204666
    3ffffe90:  4000e243 00000030 3ffffe60 402046c4
    3ffffea0:  616d7374 2e2e3730 3ffffe00 40204901
    3ffffeb0:  3ffffdf0 0693b740 000035af fffffffe
    3ffffec0:  00000090 3fffc6fc 00000003 40201dd4
    3ffffed0:  3ffee50c 000000f2 000000f2 40206bf8
    3ffffee0:  8ab9b001 00a0a64e 00000000 40206057
    3ffffef0:  78666152 3fff0c00 0000049c 00000000
    3fffff00:  00000a2e 0000007f 3fff0c1c 402356c6
    3fffff10:  61666172 66617274 32317461 40209500
    3fffff20:  00000001 3fff0c1c 00000000 402099e8
    3fffff30:  000003fd 402351a3 00000000 40101538
    3fffff40:  00000001 001ce8e7 3ffeea78 402351be
    3fffff50:  40235100 00000001 00000081 00000002
    3fffff60:  00000004 00000000 3ffee544 00000001
    3fffff70:  402083ea 000003e8 000003e8 3ffee870
    3fffff80:  3ffee544 00000000 3ffee750 40201194
    3fffff90:  00000000 00000000 ffefeffe feefeffe
    3fffffa0:  3fffdad0 00000000 3ffee840 40207830
    3fffffb0:  feefeffe feefeffe 3ffe8520 40101809
    <<<stack<<<

    ets Jan  8 2013,rst cause:2, boot mode:(3,6)

    load 0x4010f000, len 1384, room 16
    tail 8
    chksum 0x2d
    csum 0x2d
    v8b899c12
    ~ld

this is the code I uploaded to ESP8266:
<!-- language-all: lang-cpp -->

    #include <Arduino.h>

    #include <ESP8266WiFi.h>
    #include <ESP8266WiFiMulti.h>

    #include <ESP8266HTTPClient.h>

    #include <WiFiClient.h>

    #include <rdm6300.h>

    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>

    #define SCREEN_WIDTH 128 // OLED display width, in pixels
    #define SCREEN_HEIGHT 64 // OLED display height, in pixels

    // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

    #define RDM6300_RX_PIN 2
    #define READ_LED_PIN 14

    ESP8266WiFiMulti WiFiMulti;
    Rdm6300 rdm6300;

    String RFID[] = {"5958666", "5958741"};

    String SID[] = {"161-115-123", "161-115-124"};

    String NAME[] = {"Rafat", "Saney"};

    int flag[2] = {0, 0};

    void setup() {

      Serial.begin(115200);
      display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
      pinMode(READ_LED_PIN, OUTPUT);
      digitalWrite(READ_LED_PIN, LOW);
      rdm6300.begin(RDM6300_RX_PIN);

      Serial.println();
      Serial.println();
      Serial.println();
      OLED("Connecting...");
      for (uint8_t t = 4; t > 0; t--) {
        Serial.printf("[SETUP] WAIT %d...\n", t);
        Serial.flush();
        delay(1000);
      }

      WiFi.mode(WIFI_STA);
      WiFi.begin("custom", "customjack.xyz");
      Serial.print("Connecting");

      while (WiFi.status() != WL_CONNECTED) {
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("Connected");
      OLED("Connected");
      Serial.println(WiFi.localIP());

    }

    void loop() {
      // wait for WiFi connection
      if ((WiFi.status() == WL_CONNECTED)) {
    label:
        OLED("Place Your ID");
        String tag;
        int check = 0;
        if (rdm6300.update())
        {
          tag = String(rdm6300.get_tag_id());
          Serial.println(tag);
          for (int i = 0; i < 1; i++)
          {
            if (RFID[i] == tag) // checking validity of RFID
            {
              tone(READ_LED_PIN, 392);
              delay(100);
              noTone(READ_LED_PIN);
              check = 1;
              if (flag[i] == 1) // Flag=1 meaans already attendance counted
              {
                Serial.println("Attendance Already Counted");
                OLED("Already Counted");
                delay(2000);
                goto label;
              }
              OLED("Welcome "+NAME[i]);
              flag[i] = 1;
              WiFiClient client;
              HTTPClient http;

              Serial.print("[HTTP] begin...\n");
              String url = "http://metrounisas.000webhostapp.com/action.php?ID=" + SID[i];
              if (http.begin(client, url ) ) { // HTTP

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

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

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

                http.end();
              } else {
                Serial.printf("[HTTP} Unable to connect\n");
              }
            }
          }
          if (check == 0) {
            tone(READ_LED_PIN, 261);
            noTone(READ_LED_PIN);
            Serial.println("Invalid RFID");
            OLED("INVALID ID");
            delay(2000);
          }
        }
      }

      delay(1000);
    }

    void OLED(String txt){
      display.clearDisplay();
      display.setTextSize(1);
      display.setTextColor(WHITE,BLACK);
      display.setCursor(30, 30);
      display.println(txt);
      display.display();
      delay(2000);
    }

title: ESP8266 WiFi.begin() isn't working

Answers: 0


body:
    NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

    AF_DCMotor motor1(1, MOTOR12_1KHZ);
    AF_DCMotor motor2(2, MOTOR12_1KHZ);
    AF_DCMotor motor3(3, MOTOR34_1KHZ);
    AF_DCMotor motor4(4, MOTOR34_1KHZ);
    Servo myservo;

    boolean goesForward=false;
    int distance = 100;
    int speedSet = 0;

    void setup() {

      myservo.attach(10);
      myservo.write(115);
      delay(2000);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
    }

    void loop() {
     int distanceR = 0;
     int distanceL =  0;
     delay(40);

     if(distance<=15)
     {
      moveStop();
      delay(100);
      moveBackward();
      delay(300);
      moveStop();
      delay(200);
      distanceR = lookRight();
      delay(200);
      distanceL = lookLeft();
      delay(200);

      if(distanceR>=distanceL)
      {
        turnRight();
        moveStop();
      }else
      {
        turnLeft();
        moveStop();
      }
     }else
     {
      moveForward();
     }
     distance = readPing();
    }

    int lookRight()
    {
        myservo.write(50);
        delay(500);
        int distance = readPing();
        delay(100);
        myservo.write(115);
        return distance;
    }

    int lookLeft()
    {
        myservo.write(170);
        delay(500);
        int distance = readPing();
        delay(100);
        myservo.write(115);
        return distance;
        delay(100);
    }

    int readPing() {
      delay(70);
      int cm = sonar.ping_cm();
      if(cm==0)
      {
        cm = 250;
      }
      return cm;
    }

    void moveStop() {
      motor1.run(RELEASE);
      motor2.run(RELEASE);
      motor3.run(RELEASE);
      motor4.run(RELEASE);
      }

    void moveForward() {

     if(!goesForward)
      {
        goesForward=true;
        motor1.run(FORWARD);
        motor2.run(FORWARD);
        motor3.run(FORWARD);
        motor4.run(FORWARD);
       for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid loading down the batteries too quickly
       {
        motor1.setSpeed(speedSet);
        motor2.setSpeed(speedSet);
        motor3.setSpeed(speedSet);
        motor4.setSpeed(speedSet);
        delay(5);
       }
      }
    }

    void moveBackward() {
        goesForward=false;
        motor1.run(BACKWARD);
        motor2.run(BACKWARD);
        motor3.run(BACKWARD);
        motor4.run(BACKWARD);
      for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid loading down the batteries too quickly
      {
        motor1.setSpeed(speedSet);
        motor2.setSpeed(speedSet);
        motor3.setSpeed(speedSet);
        motor4.setSpeed(speedSet);
        delay(5);
      }
    }

    void turnRight() {
      motor1.run(FORWARD);
      motor2.run(FORWARD);
      motor3.run(BACKWARD);
      motor4.run(BACKWARD);
      delay(500);
      motor1.run(FORWARD);
      motor2.run(FORWARD);
      motor3.run(FORWARD);
      motor4.run(FORWARD);
    }

    void turnLeft() {
      motor1.run(BACKWARD);
      motor2.run(BACKWARD);
      motor3.run(FORWARD);
      motor4.run(FORWARD);
      delay(500);
      motor1.run(FORWARD);
      motor2.run(FORWARD);
      motor3.run(FORWARD);
      motor4.run(FORWARD);
    }

title: Why do I see error in this code

Answers: 2

body: All of the errors I got were "NewPing does not name a type", "AF_DCMOtor does not name a type" and "motor<> was not declared in this scope". I don't see library includes; at least one for NewPing is needed. I don't know where AF_DCMotor is supposed to be declared but, as it is not declared as a type, it leaves all of the motor<n> undefined. Those are the bulk (if not all) of the errors as the code stands now. Add the missing NewPing library do whatever you need to to define AF_DCMotor.

body: It probably needs a library. Looks like you have some kind of AFDC library and did not use it.


body:
I just found a lightweight library for the MPU6050 gyro. Example below.
mpu.Calibrate() never seems to end. I'm keeping it very still. When I take this out, the rest of the code works fine.

[https://github.com/gabriel-milan/TinyMPU6050/blob/master/examples/ArduinoIDE_All_Gets_Example/ArduinoIDE_All_Gets_Example.ino][1]

  [1]: https://github.com/gabriel-milan/TinyMPU6050/blob/master/examples/ArduinoIDE_All_Gets_Example/ArduinoIDE_All_Gets_Example.ino

title: How long should TinyMPU6050.h calibration run for?

Answers: 1

body:
I feel so sorry about the previous releases of TinyMPU6050. I've just released v0.5.0 that shall soon be available at the Arduino Library Manager index.

The calibration method indeed was messy, so I decided to keep it simple. I also removed dependencies of String objects and Serial stuff and it seems to work pretty fine now.

If you keep having issues with that, please let me know!

The official link to release 0.5.0 follows:
https://github.com/gabriel-milan/TinyMPU6050/releases/tag/0.5.0


body:
Can someone help me. I have this [sensor][1]

  [1]: https://nl.aliexpress.com/item/32962429148.html?spm=a2g0s.9042311.0.0.27424c4dxe6M2j

I just connected it to the 3V pin of my arduino only I read online that its better to connect it to a Arduinopin for power so you can put it off when not measuring. How do I do this? Can I just connect it to, let's say D4 and put this to HIGH and LOW or do I need something more. I googled a bit but found all kinds of different solutions. Some even talked about the need to PULLUP and PULLDOWN. whats the best way to do this.

title: Powering Moisture sensor via arduino pin

Answers: 1

body:
The entire circuit board, including the LM393, power light and it's resistor, uses 2.2 mA at 3.3 VDC (4.12 mA at 5 VDC). Once the comparator is "triggered", the "D0-LED" and it's associated resistor come in to play which bumps the current up to 3.6 mA at 3.3 VDC (7.82 mA at 5 VDC).

I think it would be OK to use `digitalWrite(pin_number, HIGH)` to power the circuit board, then use `digitalWrite(pin_number, LOW)` to turn the power off.


body: **I was wondering if it would be possible to wake an ESP8266 from a request over MQTT while it is in Light-Sleep mode?** I am planning to implement a smart switch that would receive messages from a Raspberry Pi to turn off and on, however, I don't want to have to manually hit a button to trigger an external reset (I've seen this done in many examples already). I also don't think it would be efficient for me to just set a timer and have the ESP wake up in intervals. For instance, if I want to have the smart switch turn on an appliance and the PI sends a request over MQTT when the ESP is sleeping... this will do me no good. Curious if anyone has run into this issue before and what recommendations you have.

title: Waking an ESP8266 from Light-Sleep using a signal from MQTT?

Answers: 1

body:
> I was wondering if it would be possible to wake an ESP8266 from a request over MQTT while it is in Light-Sleep mode?

No. The ESP8266 has to be awake to communicate with the MQTT server.

The best you can hope for is a periodic wakeup to connect to the server and check for any new data.  But of course that relies on the data being set to QOS 2 so it keeps trying to be delivered until the ESP8266 is awake to receive it.