message:
Controlling output frequency of 3 Phase SPWM Inverter

I am now on a 3 Phase SPWM inverter project, and i got this code from this [article][1]. It works perfectly on simulation. But the problem is, i can't make the output frequency variable. I intend to vary the frequency at range 0 to 100 Hz and use it to control the speed of 3 phase induction motor. Could anyone help me, please? Any advice or maybe you got a code that works perfectly in controlling spwm inverter frequency. Here is the code of 3 phase spwm inverter. Oh, i am using Arduino Mega by the way.

                int i=0;
                int j=0;
                int k=0;
                int x=0;
                int y=0;
                int z=0;
                int OK=0;
                int OK1=0;
                int OK2=0
                int OK3=0;
                int OK4=0;
                int sinPWM[]={1,2,5,7,10,12,15,17,19,22,24,27,30,32,34,37,39,42,
                44,47,49,52,54,57,59,61,64,66,69,71,73,76,78,80,83,85,88,90,92,94,97,99,
                101,103,106,108,110,113,115,117,119,121,124,126,128,130,132,134,136,138,140,142,144,146,
                148,150,152,154,156,158,160,162,164,166,168,169,171,173,175,177,178,180,182,184,185,187,188,190,192,193,
                195,196,198,199,201,202,204,205,207,208,209,211,212,213,215,216,217,219,220,221,222,223,224,225,226,227,
                228,229,230,231,232,233,234,235,236,237,237,238,239,240,240,241,242,242,243,243,244,244,245,245,246,246,
                247,247,247,248,248,248,248,249,249,249,249,249,255,255,255,255,249,249,249,249,249,248,
                248,248,248,247,247,247,246,246,245,245,244,244,243,243,242,242,241,240,240,239,238,237,237,236,235,234,
                233,232,231,230,229,228,227,226,225,224,223,222,221,220,219,217,216,215,213,212,211,209,208,207,205,204,
                202,201,199,198,196,195,193,192,190,188,187,185,184,182,180,178,177,175,173,171,169,168,166,164,162,160,
                158,156,154,152,150,148,146,144,142,140,138,136,134,132,130,128,126,124,121,119,117,115,113,110,108,106,
                103,101,99,97,94,92,90,88,85,83,80,78,76,73,71,69,66,64,61,59,57,54,52,49,47,44,42,39,37,34,32,30,
                27,24,22,19,17,15,12,10,7,5,2,1};

                int potinput = A1;
                int potfreq = A2;
                float potinputval;
                float potfreqval;
                float A;
                float F;

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

                pinMode(4, OUTPUT);
                pinMode(13,OUTPUT);
                pinMode(9,OUTPUT);
                pinMode(10,OUTPUT);
                pinMode(2,OUTPUT);
                pinMode(5,OUTPUT);

                cli();// stop interrupts
                TCCR0A=0;//reset the value
                TCCR0B=0;//reset the value
                TCNT0=0;//reset the value
                //0b allow me to write bits in binary
                TCCR0A=0b10100001;//phase correct pwm mode
                TCCR0B=0b00000001; //no prescaler

                TCCR2A=0;//reset the value
                TCCR2B=0;//reset the value
                TCNT2=0;//reset the value
                //0b allow me to write bits in binary
                TCCR2A=0b10100001;//phase correct pwm mode
                TCCR2B=0b00000001; //no prescaler

                TCCR3A=0;//reset the value
                TCCR3B=0;//reset the value
                TCNT3=0;//reset the value
                //0b allow me to write bits in binary
                TCCR3A=0b10100001;//phase correct pwm mode
                TCCR3B=0b00000001; //no prescaler
                TCCR1A=0;//reset the value
                TCCR1B=0;//reset the value
                TCNT1=0;//reset the value
                OCR1A=509;// compare match value
                TCCR1B=0b00001001; //WGM12 bit is 1 for CTC mode and no prescaler

                TIMSK1 |=(1 << OCIE1A);// enable interrupts

                sei();//stop interrupts
                }
                ISR(TIMER1_COMPA_vect){// interrupt when timer 1 match with OCR1A value
                if(i>313 && OK==0){// final value from vector for pin 13
                i=0;// go to first value of vector
                OK=1;//enable pin 4
                }
                if(i>313 && OK==1){// final value from vector for pin 4
                i=0;//go to firs value of vector
                OK=0;//enable pin 13
                }
                x = round(A*sinPWM[i]); // x take the value from vector corresponding to position i(i is zero indexed)
                i=i+1;// go to the next position
                if(OK==0){
                OCR0B=0;//make pin 4 0
                OCR0A=x;//enable pin 13 to corresponding duty cycle
                }
                if(OK==1){
                OCR0A=0;//make pin 13 0
                OCR0B=x;//enable pin 4 to corresponding duty cycle
                }

                if ((i==209) || OK1==1){//if i equal with 209 enable second signal
                OK1=1;//mantain if function
                if(j>313 && OK2==0){// final value from vector for pin 10
                j=0;// go to first value of vector
                OK2=1;//enable pin 9
                }
                if(j>313 && OK2==1){// final value from vector for pin 9
                j=0;//go to firs value of vector
                OK2=0;//enable pin 10
                }
                y = round(A*sinPWM[j]);// y take the value from vector corresponding to position j(j is zero indexed)
                j=j+1;// go to the next position
                if(OK2==0){
                OCR2B=0;//make pin 9 0
                OCR2A=y;//enable pin 10 to corresponding duty cycle
                }
                if(OK2==1){
                OCR2A=0;//make pin 10 0
                OCR2B=y;//enable pin 9 to corresponding duty cycle
                }
                }
                if ((j==209) || OK3==1){//if j equal with 209 enable third signal
                OK3=1;//mantain if function
                if(k>313 && OK4==0){// final value from vector for pin 5
                k=0;// go to first value of vector
                OK4=1;//enable pin 2
                }
                if(k>313 && OK4==1){// final value from vector for pin 2
                k=0;//go to firs value of vector
                OK4=0;//enable pin 5
                }
                z=round(A*sinPWM[k]);// z take the value from vector corresponding to position k(k is zero indexed)
                k=k+1;// go to the next position
                if(OK4==0){
                OCR3B=0;//make pin 2 0
                OCR3A=z;//enable pin 5 to corresponding duty cycle
                }
                if(OK4==1){
                OCR3A=0;//make pin 5 0
                OCR3B=z;//enable pin 2 to corresponding duty cycle
            }
            }
            }
            void loop() {

              potinputval = analogRead(potinput);
              A = potinputval/1023;

              potfreqval = analogRead(potfreq);
              F = map(potfreqval,1023,0,0,50);}

  [1]: http://www.eprojectszone.com/how-to-generate-three-phase-spwm-signal-with-arduino/
  [2]: https://github.com/tardate/LittleArduinoProjects/blob/master/Electronics101/SwitchModePowerSupplies/BasicInvertingBuckBoostAvrControl/BasicInvertingBuckBoostAvrControl.ino
  [3]: https://pastebin.com/G7N6tFbM

body:
In this sketch the PWM values, matching a sampled sine curve, are stored in integer array sinPWM[]. The values from sinPWM (1 - 255) are used unmodified (via intermediate variables x, y and z) to set the various timing registers (OCR0A/B, OCR2A/B and OCR3A/B) which control the pulse width modulation. In this way the amplitude(s) of the generated sine wave(s) will be constant.

If you want to control the speed of the motor you have to multiply the values from sinPWM with a factor between 0 and 1. The most logical place is to do that when the values from sinPWM are transferred to the intermediate variables x, y and z. Example: x=round(0.8 * sinPWM[i]). The factor, 0.8 in this example, you can of course replace by a variable which value is derived from an analogRead() of a pin connected to a potmeter or some sensor. But make sure to convert it to a value in the range 0-1 before you use it in the calculation.


sender: user

message:
ESP8266 like WiFi modules

I am trying to make a circuit using [Nodemcu ESP8266][1] to control the speed and direction of 3 DC servo motors, however I am short of analog pins.
So are there any ways to increase the number of analog pins?
Or are there other WiFi modules like the ESP8266, but with more number of analog pins?

  [1]: http://www.nodemcu.com/index_en.html

sender: assistant

body:
How many PWMs do you need?

[Here][1] you can find a useful description about PWMs on ESP8266 NodeMCU.

According to image, ESP8266 NodeMcu has 9 PWMs pin.

[![ESP8266 PWM Pinout][2]][2]

  [1]: https://www.electronicwings.com/nodemcu/nodemcu-pwm-with-arduino-ide
  [2]: https://i.stack.imgur.com/hdiUX.png


message:
Can't replace SoftwareSerial by Serial1 on Mega board

This sketch runs well with SoftwareSerial define and the monitor displays device modbus values. But now, i want to replace SoftwareSerial by Serial1
and i have no data.

This is the sketch with SoftwareSerial:

    #include <SoftwareSerial.h>
    #define SSerialRX        10  //Serial Receive pin
    #define SSerialTX        11  //Serial Transmit pin
    #define SSerialTxControl 40   //RS485 Direction control
    #define RS485Transmit    HIGH
    #define RS485Receive     LOW

    SoftwareSerial RS485Serial(SSerialRX, SSerialTX); // RX, TX
    byte byteSend;

    void setup()
    {
      Serial.begin(9600);
      pinMode(SSerialTxControl, OUTPUT);
      digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
      RS485Serial.begin(9600);
    }
    void loop()
    {
      delay(500);
      if (RS485Serial.available())
      { for(int i=0; i<7; i++)
        {
        byteSend = RS485Serial.read();   // Read the byte

        Serial.print(byteSend, HEX);
        Serial.print(" ");
        }
      }
      digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
      byte request[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x01, 0x84, 0x0A};
      RS485Serial.write(request, sizeof(request));

      digitalWrite(SSerialTxControl, RS485Receive);
      Serial.println(" ");
    }

And the sketch i tried with Serial1 (pin 19(Rx) and 18(Tx)):

    #define SSerialTxControl 40   //RS485 Direction control
    #define RS485Transmit    HIGH
    #define RS485Receive     LOW

    byte byteSend;

    void setup()
    {
      Serial.begin(9600);
      pinMode(SSerialTxControl, OUTPUT);
      digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
      Serial1.begin(9600);
    }
    void loop()
    {
      delay(500);
      if (Serial1.available())
      { for(int i=0; i<7; i++)
        {
        byteSend = Serial1.read();   // Read the byte

        Serial.print(byteSend, HEX);
        Serial.print(" ");
        }
      }
      digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
      byte request[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x01, 0x84, 0x0A};
      Serial1.write(request, sizeof(request));

      digitalWrite(SSerialTxControl, RS485Receive);
      Serial.println(" ");
    }

Can you help me to find my mistake ?

body:
>  what is the best way to solve it, using Serial1?

With either serial device, you need to collect characters until you have an entire message. If every message will be a fixed number of bytes, you can wait until the return value of the Serial::available() call indicates it has that many characters, then collect them into a buffer and process them. But this assumes you'll never get a badly-formed message. If you do, the incoming bytes will get out of sync with your program.
A better way is to collect bytes into your buffer (but do nothing with them) until you have a complete message (by byte-count, newline character, or however you need to recognize that it is complete) or your buffer is about to overflow, and then either process them, or if your buffer filled and the contents doesn't look like a valid message, discard it and try to re-synchronize with the source. That may mean reading and ignoring bytes until you get a newline, and dealing with the fact you got a garbled message, or telling your source to restart or reset. The exact method (or whether you even want to bother detecting bad messages) depends on the particular situation. Will someone die if you fail? Will something catch fire, burn parts, lose weeks worth of good data, ... ? Or is this an experiment whose consequence of failure are zero or at least not worth any effort to detect it?


message:
Digital Input using a button doesn't work properly when using it to control a relay

I'm trying to control a relay both via Bluetooth and using a switch. The problem is that, when the LED is off, I can turn it on with the switch but then if I turn off the switch the relay will stay on. Is there something wrong with my code? Thanks in advance. The switch is installed as follows:
[![Switch][1]][1]

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

Here is my code: Switch is connected to pin 3 and the relay is connected to pin 2.
<!-- language-all: lang-cpp -->

    //bluetooth hc-06
    int ledPin = 2; // usamos un pin de salida al LED
    int state = 0; // Variable lectrura serial
    int interruptor=3;

    void setup() {
        pinMode(ledPin, OUTPUT);   //Declara pin de Salida
        pinMode(interruptor, INPUT);
        digitalWrite(ledPin, LOW); //Normalmente Apagado
        Serial1.begin(9600);
        }

    void loop() {
      int valor=digitalRead(interruptor);

      if(Serial1.available() > 0){
           state = Serial1.read();
      } // esta parte del código es para solo 1 Carácter o Unidad.

     if (state == '0'&& valor== LOW) {
        digitalWrite(ledPin, LOW);
        Serial1.println("LED: off");
     }

     else
     if (state == '1' || valor== HIGH) {
         digitalWrite(ledPin, HIGH);
         Serial1.println("LED: on");
     }

    }

New code:

    //bluetooth hc-06
    int ledPin = 2; // usamos un pin de salida al LED
    int state = 1; // Variable lectrura serial
    int interruptor=3;

    void setup() {
        pinMode(ledPin, OUTPUT);   //Declara pin de Salida
        pinMode(interruptor, INPUT);
        digitalWrite(ledPin, LOW); //Normalmente Apagado
        Serial1.begin(9600);
        }

    void loop() {
      int valor=digitalRead(interruptor);
     //si el modulo ha mandado dato, guardarlo en estado.

      if(Serial1.available() > 0){
           state = Serial1.read();
      } // esta parte del código es para solo 1 Carácter o Unidad.

     // si el estado es 0 ese sería Apagado “OFF”
     if (valor== LOW) {
        digitalWrite(ledPin, LOW);
        Serial1.println("LED: off");
     }

     // de lo contrario si el estado es 1 ese sería Encendido “ON”
     else
     if (valor== HIGH) {
         if (state== 1){
         digitalWrite(ledPin, HIGH);
         Serial1.println("LED: on");
         }
         else if (state== 0){
         digitalWrite(ledPin, LOW);
         Serial1.println("LED: off");

         }
     }

    }

body:
You have to invalidate the `state` variable when `Serial` is not available, otherwise you will produce strange behaviours.

```cpp
if (Serial1.available() > 0) {
    state = Serial1.read();
} else {
    state = -1; // not valid
}
```

Also, serial values will be characters, not integers, so compare with character values, e.g.,

```cpp
if (state == '1')
```


body:
Well, there are a couple of problems.

In the original SW, you are checking for `state = '0'` and `state = '1'`, but the initial value of state is `0` (not `'0'`). For this reason both tests always return false.

In addition, avoid setting conditions when not necessary. `else` already mean "all the other options", so if you have one variable that can be only A or B, don't write `if A ... else if B ...`; the second condition is necessary (and meaningful) only if the condition is actually something you care of (so you want to exclude condition C).

I started modifying your sketch from the new version, and here are the things I modified:

 - Variables were set to type `uint8_t`; `int` is not efficient on 8-bit platforms, so use 8-bit variables whenever you can
 - Instead of using multiple triggers, I used a single variable (`ledState`) to calculate the state in each loop. This way it is much easier to track the modifications
 - simplified the input management: now it turns on the led when the input is high, and does nothing (leaves it off) when it is low
 - simplified the bluetooth management. With a `'1'` it turns on the led, and all the other chars set it off; if you need only a '0' to turn it off you can easily modify the parentheses to ignore other chars

This is the code I wrote. NOTE: I did not test it, so there may be residual bugs. Let me know if it works as you expect or want some additional clarifications:

    uint8_t ledPin = 2;
    uint8_t interruptor = 3;
    uint8_t bluetoothState = '0';

    void setup() {
        pinMode(ledPin, OUTPUT);
        pinMode(interruptor, INPUT);
        digitalWrite(ledPin, LOW);
        Serial1.begin(9600);
    }

    void loop() {
     uint8_t ledState = LOW;

     if (digitalRead(interruptor)) {
      ledState = HIGH;
      Serial1.println("LED: on (switch)");
     }

     if(Serial1.available() > 0){
      bluetoothState = Serial1.read();
     }

     if (bluetoothState == '1') {
      ledState = HIGH;
      Serial1.println("LED: on (BT)");
     }

     digitalWrite(ledPin, ledState);
     if (ledState == LOW) {
      Serial1.println("LED: off");
     }
    }

Things still to do (IMHO):
 - make a robust button handler (for instance using the debounce library)
 - get rid of the serial debug outputs
 - make a better serial protocol


message:
Dynamically create functions for AccelStepper that use Adafrut_StepperMotor.oneStep methods?

In the [Adafruit_MotorShieldV2Library>Accel_MultiStepper](https://github.com/adafruit/Adafruit_Motor_Shield_V2_Library/blob/master/examples/Accel_MultiStepper/Accel_MultiStepper.ino) example, [AccelSteppers](https://www.airspayce.com/mikem/arduino/AccelStepper/classAccelStepper.html#afa3061ce813303a8f2fa206ee8d012bd) are initialized using the following *static* forwardstep1 and backwardstep1:

    #include <Wire.h>
    #include <AccelStepper.h>
    #include <Adafruit_MotorShield.h>

    //First, get an Adafruit_MotorShield
    Adafruit_MotorShield AFMStop(0x60); // Default address, no jumpers

    //Then, get a stepper motor from it
    Adafruit_StepperMotor *myStepper1 = AFMStop.getStepper(200, 1);

    //Then, create callbacks for the AccelStepper's constructor
    void forwardstep1() {
        myStepper1->onestep(FORWARD, SINGLE);
    }
    void backwardstep1() {
        myStepper1->onestep(BACKWARD, SINGLE);
    }

    //Finally, create the stepper motor
    AccelStepper stepper1(forwardstep1, backwardstep1);

I intend to then use these AccelSteppers as members in a [MultiStepper](http://www.airspayce.com/mikem/arduino/AccelStepper/MultiStepper_8pde-example.html), which I'm skipping here because it shouldn't be relevant.

I want to make a function that automates this process. Ideally it would work something like this:

    typedef void(*mover)();
    AccelStepper makeStepper(Adafruit_StepperMotor myStepper){
        // create functions of type mover
        mover forward = []{myStepper->onestep(FORWARD, DOUBLE);};
        mover back = []{myStep->onestep(BACKWARD, DOUBLE);};
        return AccelStepper step(forward, back);
    }

- What I've tried:
  - Obviously the above solution. This doesn't work because myStepper isn't captured, but if you capture it it's not a mover object and can't be passed to AccelStepper.
  - Using an object's function. This doesn't work because object functions have the implicit first parameter this. [See this for more info](https://stackoverflow.com/questions/8865766/get-a-pointer-to-objects-member-function)
  - Making the parameter myStepper static after it's passed in. This doesn't work because it gets over-written on every call to the function.
  - Using std::forward. This would probably work, but I don't think std::forward is defined in ArduinoSTL because I keep getting the error `'forward' is not a member of 'std'`. See the code below:
      - Note, In an attempt to make this work, I upgraded the following folders to `-std=gnu++17` on my ubuntu machine, resulting in `__cplusplus == 201500`:
          - ~/.local/share/umake/ide/arduino/hardware/arduino/avr/platform.txt
          - ~/.local/share/umake/ide/arduino/hardware/hardware/platform.txt

### std::forward attempt

    #include <ArduinoSTL.h>
    using namespace std;
    #include <iostream>
    #include <functional>
    #include <utility>

    typedef void(*mover)();

    template <classF>
    mover lambda_to_ptr(F&& f){
        static F fn = std::forward<F>(f);
        return []{ return fn();};
    }
    AccelStepper makeStepper(Adafruit_StepperMotor myStepper){
        // create functions of type mover
        mover forward = []{myStepper->onestep(FORWARD, DOUBLE);};
        mover back = []{myStep->onestep(BACKWARD, DOUBLE);};
        return AccelStepper step(lambda_to_prt(forward), lambda_to_ptr(back));
    }

p.s. Of course, I could always change the functions in the library, but this is (almost) always a bad idea.

body:
I ended up just inheriting AccelStepper, and extending the [
AccelStepper::AccelStepper ( uint8_t interface = AccelStepper::FULL4WIRE,uint8_t pin1 = 2,uint8_t pin2 = 3, uint8_t pin3 = 4, uint8_t pin4 = 5, bool enable = true )](https://www.airspayce.com/mikem/arduino/AccelStepper/classAccelStepper.html#a3bc75bd6571b98a6177838ca81ac39ab) constructor to add my own Adafruit_StepperMotor instance variable and using it in an overridden step0 (which is the only function those callbacks were used in).

    class MyAccelStepper: public AccelStepper
    {
       public:
           MyAccelStepper(Adafruit_StepperMotor *myStepper):AccelStepper(0,0,0,0,0,false)
           {
             //MyStepper(0, 0, 0, 0, 0, false);
             _myStepper = myStepper;
           }
       protected:
           void step0(long step){
              (void)(step);
              if(speed() > 0){
                _myStepper->onestep(FORWARD, DOUBLE);
              }else{
                _myStepper->onestep(BACKWARD, DOUBLE);
              }
           }
        private:
           Adafruit_StepperMotor *_myStepper;
    };


message:
Problem sending SMS from a GSM SIM900

I have a laser security system project with a GSM SIM900 and a few sensors. I'm using an Arduino Mega 2560, and everything is working normally, except the GSM is not sending an SMS to the phone and I don't know why!

this is  my code:

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include <Keypad.h>
    #include <SoftwareSerial.h>

    SoftwareSerial sim900(0,1);
    String  TextForSMS;

    int dataldr =0;
    int sensorldr = A0;
    int ldrState = LOW;
    int ldrthres = 900;

    int pir = A1;
    int pirState = LOW;
    int val = 0;

    int gas = A8;
    int sensorgasThres = 400;

    #define Password_Length 8
    #define PINNUMBER ""

    int signalPin = 2;
    int led1 = 12;
    int led2 = 11;
    int led3 = 10;
    int led4 = 9;
    int led5 = 8;
    int led6 = 7;
    int laser =6;

    char Data[Password_Length];
    char Master[Password_Length] = "123A456";
    byte data_count = 0, master_count = 0;
    bool Pass_is_good;
    char customKey;

    const byte ROWS = 4;
    const byte COLS = 4;

    char hexaKeys[ROWS][COLS] = {
      {'1', '2', '3', 'A'},
      {'4', '5', '6', 'B'},
      {'7', '8', '9', 'C'},
      {'*', '0', '#', 'D'}
    };

    byte rowPins[ROWS] = {30,31,32, 33};
    byte colPins[COLS] = {34, 35, 36, 37};

    Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

    LiquidCrystal_I2C lcd(0x3F, 20, 4);

    void setup(){

      lcd.init();
      lcd.backlight();

      pinMode(signalPin, OUTPUT);
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(led5, OUTPUT);
      pinMode(led6, OUTPUT);
      pinMode(laser, OUTPUT);

      pinMode(gas, INPUT);
      pinMode(pir, INPUT);
      pinMode(sensorldr,INPUT);

     randomSeed(analogRead(0));
      Serial.begin(9600);
      sim900.begin (9600);
      Serial.println(" loggin time completed");
    delay(5000);

    }

    void loop(){

         digitalWrite(laser, HIGH);
         digitalWrite(led1, HIGH);

         lcd.setCursor(0,0);
         lcd.print("Enter Password:");

       char customKey = customKeypad.getKey();

      if (customKey){

        Data[data_count] = customKey;
        lcd.setCursor(data_count,1);
        lcd.print(Data[data_count]);
        data_count++;
        }

      if(data_count == Password_Length-1){
        lcd.clear();

        if(!strcmp(Data, Master)){

          lcd.print("Correct");
          digitalWrite(led3, HIGH);
          tone(signalPin, 150,200);
          delay(5000);
          digitalWrite(signalPin, LOW);
          digitalWrite(led3, LOW);
          digitalWrite(laser, LOW);
          ldrState = LOW;
          delay(5000);
          digitalWrite(laser, HIGH);
          ldrState = HIGH;

          }
        else{
                lcd.print("Incorrect");
                digitalWrite(led4, HIGH);
                digitalWrite(signalPin, HIGH);

          delay(2000);

                digitalWrite(led4, LOW);
               digitalWrite(signalPin, LOW);
     TextForSMS="\nIntruder password wrong";
      sendSMS(TextForSMS);
     lcd.setCursor(10,2);
      lcd.print("sms2sent");      }

        lcd.clear();
        clearData();
      }

      int   dataldr =analogRead(sensorldr);
         lcd.setCursor(0,3);
         lcd.print("Laser:");
         lcd.setCursor(7,3);
         lcd.print(dataldr);

      if(dataldr<ldrthres){
        digitalWrite(signalPin, HIGH);
        digitalWrite(led2, HIGH);
      TextForSMS="\nIntruder detected";
      sendSMS(TextForSMS);
      lcd.setCursor(10,2);
      lcd.print("sms1sent");

      }
      else
      {
        digitalWrite(led2, LOW);
        noTone(signalPin);

      }
      delay(100);

     int analogSensor = analogRead(gas);
      lcd.setCursor(0,2);
      lcd.print("Gas:");
      lcd.setCursor(4,2);
      lcd.print(analogSensor);
      // Checks if it has reached the threshold value
      if (analogSensor > sensorgasThres)
      {
                digitalWrite(led5, HIGH);
                digitalWrite(signalPin, HIGH);

         TextForSMS="\nIntruder GAS";
      sendSMS(TextForSMS);
      lcd.setCursor(10,2);
      lcd.print("sms3sent");
      }
      else
      {
        digitalWrite(led5, LOW);
        noTone(signalPin);
      }
      delay(100);

      val = digitalRead(pir);
      if (val == HIGH) {
        digitalWrite(led6, HIGH);

        if (pirState == LOW) {
               Serial.println("Motion detected!");
               pirState = HIGH;
        }
      } else {
        digitalWrite(led6, HIGH);
     delay (5000);
        if (pirState == LOW){
               Serial.println("Motion ended!");
          pirState = LOW;
        }
      }

    }

    void clearData(){
      while(data_count !=0){
        Data[data_count--] = 0;
      }
      return;
    }

    void sendSMS (String message){
        sim900.print("AT+CMGF=1");
        delay(1000);

      sim900.println("AT+CMGS=\"+380633965886\"\r ");
          delay(1000);
    sim900.println(message);
        delay(1000);
    sim900.println((char)26);
        delay(1000);
    sim900.println();
        delay(1000);

      }

Also on Github:

https://github.com/shiyaroo/gsm-sim900/blob/master/laser_security_system__gsm.ino

body:
It’s *not* a good approach to put delay function between AT commands.

You have to parse SIM900 responses and check if module replies with OK.

If you don’t receive responses from module, could be different problems:

1. wrong baudrate
2. connection or power supply problem
3. SIM card problem (out of cash, sim lock with pin, etc..)

here you can find a useful guide:
https://randomnerdtutorials.com/sim900-gsm-gprs-shield-arduino/


message:
Invalid conversion from 'const char' to 'uint8_t*'

I am just a newbie, don't know how to solve this issue

    void loop()
    {
      UdpSend("Test", "192.168.0.240", 4210);
    }

    void UdpSend(const char* message, uint8_t * ipaddress, int port){
          Serial.println("Send message: ");
          Udp.beginPacket(ipaddress, port);
          Udp.write(message);
          Udp.endPacket();
    }

Arduino IDE can't compile.

The error message:  ***invalid conversion from 'const char*' to 'uint8_t* {aka unsigned char*}' [-fpermissive]***

Trying to change with this code:

    void UdpSend(uint8_t * message, uint8_t * ipaddress, int port){
          Serial.println("Send message: ");
          Udp.beginPacket(ipaddress, port);
          Udp.write(message);
          Udp.endPacket();
    }

Also doesn't work, the error message: ***invalid conversion from 'const char*' to 'uint8_t* {aka unsigned char*}' [-fpermissive]***

Please help...

body:
Not sure why you're using `uint8_t` at all

The Udp.beginPacket function signature is

    int WiFiUDP::beginPacket(const char *host, uint16_t port)

No hint of uint8_t there

and .write is either

    WiFiUDP::write(uint8_t byte)
    WiFiUDP::write(const uint8_t *buffer, size_t size)
    WiFiUDP::write(const char *str)
    WiFiUDP::write(const char *buffer, size_t size)

So, your other attempt to use `write((uint8_t *))` is also wrong

Try this:

    void loop()
    {
      UdpSend("Test", "192.168.0.240", 4210);
    }

    void UdpSend(const char* message, const char * ipaddress, int port){
          Serial.println("Send message: ");
          Udp.beginPacket(ipaddress, port);
          Udp.write(message);
          Udp.endPacket();
    }


body:
In ESP32 Arduino package the WiFiUdp.h doesn't pull in all Print class `write` functions. As consequence the WiFiUdp class doesn't know `write(const char *str)`.

Use `Udp.print(message);` if message is a zero-terminated char array

or `Udp.write(message, size);` if message is a byte array


message:
Is there a relationship between RSSI and Power? If so, how are they connected and does it have a formula to extract one from the other?

I have searched on Google but to no avail. Perhaps you guys can help.

-Aj

body:
> Is there a relationship between RSSI and Power?

Yes

> If so, how are they connected and does it have a formula to extract one from the other?

RSSI is in relation to the square-root of the power. See below references for the actual formula.

Holiday extra: RSSI for an RF433 module can be estimated by the time from end of transmission and noise. This is the time for the AGC circuit to increase gain from the received signal to the noise level. Please see Cosa RF433 library for an example.

References:

 1. https://en.wikipedia.org/wiki/Received_signal_strength_indication
 2. https://en.wikipedia.org/wiki/Signal_strength_in_telecommunications


message:
Generating and reading a PWM signal at the same time on Arduino Uno R3?

The code below should generate a PWM signal on digital pin 3. But know I want to see if it is even working. I was thinking about a Event triggering method like ISR. But somehow it does not work. I guess a ISR needs to a Input Pin, e.g. it would work, when I would've a PWM signal coming from somewhere.

Is it even possible to generate a PWM signal and read it to see some results on the serial monitor?

edited code:

    byte const PWM_PIN = 3;

    volatile unsigned long pwm_value = 0;
    volatile unsigned long prev_time = 0;

    void setup() {
      pinMode(PWM_PIN, OUTPUT);
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(PWM_PIN), rising, RISING);
    }

    void loop() {
      digitalWrite(PWM_PIN, HIGH);
      delay(400);
      digitalWrite(PWM_PIN, LOW);
      delay(1600);
    }

    void rising() {
      attachInterrupt(digitalPinToInterrupt(PWM_PIN), falling, FALLING);
      prev_time = millis();
    }

    void falling() {
      attachInterrupt(digitalPinToInterrupt(PWM_PIN), rising, RISING);
      pwm_value = millis()-prev_time;
      Serial.println(pwm_value);
    }

body:
1. You aren’t generating a correct PWM, because Serial.println introduces a delay. The right way for generating PWM is to use **analogWrite** function.

2. You **can’t** use attachInterrupt function for detecting rising and falling edge of an **output pin**.

3. In order to detect the rising and falling edge of a PWM signal, you have to use the **timer interrupt** of PWM module. For doing this, You have to write/read directly ATmega registers without using Arduino libraries. What version of Arduino are you using?


body:
You are declaring the variables `prev_time` and `pwm_value` as `int`, which has (on a standard Arduino) 16 bits. Since you use the signed variant, you get a range of values from -32768 to 32767. But `micros()` is returning an `unsigned long`, which has 4 bytes (32 bits) and is not signed. With `int` there are only 32.767 ms (since it represents microseconds here), without letting the variable overflow. Even the full range would give you only about 65 ms. It simply cannot hold a value like 1000000. If you assign this value to an `int`, it will directly overflow (which - I think - would give you the value modulo 2^16), effectively loosing big parts of the information. You cannot get meaningful results with this in such a high time scale.

When measuring time (with `millis()` or `micros()`) you should always be sure to use `unsigned long` as type to prevent these problems.

---

Apart from the variable type, why do you use `micros()` here? You are measuring times in the hundreds of milliseconds, so why not use `millis()`? This would keep the values lower.


message:
Can't extract basic data using ThingspeakHTTP

I don't know anything about HTML, but I want to extract the % probability of the Northern lights being visible from this webpage
[http://aurorawatch.ca/][1].
  [1]: http://www.aurorawatch.ca/

I entered this into the URL field, and selected HTML version 1.

When I inspect the text element I want and copy the Xpath I get the following:

"/html/body/div[1]/div[5]/table/tbody/tr[1]/td/div[1]/table[2]/tbody/tr[2]/td/div/table/tbody/tr/td[2]/span"

and enter this into the "parse string" field of the ThingSpeak API app, but get the following error:

"Error parsing document, try a different parse string."

Most people who get this error seem to be getting data that doesn't load with the original page, so I think I must be missing something.

If there is a better solution for pulling this number to my ESP8266 than creating a thingspeak API, I would love to hear it too!

body:
You should use this page, since the other is the front page of the site and more likely to be dynamic:

* http://www.aurorawatch.ca/index.php?option=com_content&task=view&id=28&Itemid=47

The XPath is also slightly different. The first `tbody` in the reported path doesn't actually exist. You should also add `/text()` to the end of the path to just return the textual content of the node:

* `/html/body/div[1]/div[5]/table[2]/tr[3]/td/table/tbody/tr/td[2]/span/text()`


message:
How can I distinguish values sent from Arduino

Having in my visual basic app something like:

    private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            *whatever* value = serialPort1.Read*whatever*();
        }

Suppose my Arduino sends in every loop, the value read by a photoresistor. Suppose my Arduino also sends a 0 if certain led is LOW or a 1 if certain led is HIGH. Finally suppose my Arduino also sends a value that is equal to the number of times the loop has been executed.

In the 25th execution, lets suppose my Arduino sends something like:

    Serial.write(LED_state) // 0 or 1 for LOW or HIGH
    Serial.write(photoresistor_value) //lets suppose 25
    Serial.write(loop_number) //25

Question: if all the values are sent using Serial.write or Serial.print, and all values are ints, how can I distinguish in my app if the value 25 received belongs to the photoresistor or to the loop? Is there any way to send something like (key, value) from Arduino so I can distinguish between the ints received so I can assign them correctly to my app variables?

body:
> Is there any way to send something like (key, value)

Sure:

    Serial.print("LED state: ");
    Serial.println(LED_state);

You will have to modify your VB code to parse that.


message:
Sending file from PC to Arduino

How can i send a (file) from PC to Arduino Yun at running time ?

There's a way to send some commands via Serial.
But how would a whole file goes ? Assuming the file can take place at RAM without any problems.

Thanks

body:
You can send a file, byte after byte, using Serial.
On the Arduino side, you parse serial communication and put bytes inside an array. At the end, you reconstruct the file.


body:
The first question is what do you want to do with your image : Arduino Yun has a Linux chip & an Arduino chip.
And I don't think that image treatment must happen in the Arduino side...
So you can send your image with scp to Linux side, then do what you want with it and perhaps, eventually, send the result for action to the Arduino part.


body:
Back in the mists of time (late 1990s, if anyone's counting), there existed a file transfer protocol called [XMODEM][1] that was used to send a file across a link normally used for a terminal, on small, publicly available systems known as Bulletin Board Systems, or BBSes.
XMODEM divided a file into packets of 129 bytes, sent and acknowledged one packet at a time. It had a simple 8-bit checksum to verify the file contents which was just "ok" over a reasonably reliable line, line and inadequate on a noisy one. But it was one of the first experimenter-built and widely used protocols.

As it was pushed harder and harder (larger file sizes, higher line speeds intolerant of the small, single-packet handshake) and its weaknesses became more problematic,a number of derivatives were developed to address the weaknesses.

[ZMODEM][2] was one of those, which allowed the sender a "sliding window" of packets, so it could keep sending packets (up to the window maximum) without stopping to wait for each acknowledgement, and could use larger packet sizes, among other improvements.

They are relatively easy to implement, XMODEM more-so, and source code or specs can be found by looking around.

If your files aren't horrendously large and the lines are fairly reliable, even XMODEM may be adequate.

  [1]: https://en.wikipedia.org/wiki/XMODEM
  [2]: https://en.wikipedia.org/wiki/ZMODEM


message:
Arduino Uno will not connect to MAC computer running Sierra

I purchased an Arduino Uno. I am trying to set it up, but when I got to the "port" on my MAC, there is no option to select anything related to my board. The only connections the port tab allows me to connect to is the bluetooth incoming port, which is not correct because it gives me errors when I try to set up the UNO to block on and off for 1 second. I know this is the legit Arduino Uno, so why is the bluetooth not connecting?

body: I assume you have installed Arduino IDE on your mac and connecting board to mac using USB cable. Many time it happens due to driver or OS reason. Just plug the Arduino to another USB port and it should work.


message:
Doubt in choosing the right DC motor?

Take this motor as an example - https://www.robotshop.com/en/12v-100rpm-583-oz-in-brushed-dc-motor.html

it has torque of 42kg.cm

I know all the calculation to find the payload of dc motor from here - https://www.quora.com/How-do-I-calculate-how-much-weight-can-DC-motor-carry

My main concern is the output power. Power formula is:-

power = voltage x Stall Current
      = 12 x 2A = 24W

But the specification says that the power is 5W. Which value should I use in my calculation?

body:
With a current rating of `0.68 A` at `12 V` you get the *normal* power requirement of `8.6 W` for a `7Kg.cm` torque.

If, for any reason, you stall the motor, your driver must be capable to output `2.2 A` or `26.5 W` to avoid a permanent damage.


message:
Unable to set LCD contrast using DAC pin on ESP32

I have followed the instructions at https://www.arduino.cc/en/Tutorial/HelloWorld and have my LCD displaying some text. I've also connected the LED back light (LCD pins 15&16).

I wanted to replace the potentiometer used to set the contrast, with a connection to the DAC pin. It needs to be about 0.8V.

When I connect the contrast pin from the LCD to my DAC pin on my ESP32 board, it doesn't work, the contrast is too high. Using a volt meter, it measures about 2.5V.

If I disconnect the LCD contrast pin from my DAC pin, the voltage measured is 0.8V.

Any ideas or examples on how to control the LCD contrast using a DAC pin?

I wondered if I need to add a resistor or something.

body:
The DAC in the ESP32 is ok for sourcing current but not so good at sinking current, and that is what you need.

A amplifier set up as a voltage follower would work.

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

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


message:
Arduino Uno unable to detect serial port on MAC os Mojave 10.14.2

Ive upgraded to Mojave.  I've never used Arduino before.  I was given Arduino Uno.
Arduino Uno does not find any serial ports... can't load Blink example (the first step)

In blind frustration, I tried the three ports available... None of work.

I've loaded the
CH34x_Install_V1.4.pkg
to no avail.

How do I get a serial port package that will enable serial ports in general (and more importantly for arduino)

thx,
Bruce
On a related Note: the list of things that Mojave broke is long!  To solve many problems, re-install xcode FIRST!!! and read articles on apache, there is a "new and improve" apache server embedded in mojave.

body:
If you are using a genuino or genuine Arduino, the most common cause of this is using a USB *power only* cable to connect rather than a data cable. (You only need the CH34x_Install_V1.4.pkg if you are running an Arduino clone based on that chipset)

If I ran the world, the USB standard would include some way to distinguish whether it's power only or power and data without having to [test it with a multimeter][1]. I know, I know, that's crazy talk.

  [1]: https://electronics.stackexchange.com/a/140229/171525


message:
esp32 spi library, how read a mcp23s08 register

thanks for any help
I need to read a gpio expander mcp23s08 set as 8 bits input.
my code write correctly (I believe) the setup register using SPI library, with the enclosed example modified.
But I do not understand how read a gpio register (0x09)
code (with the read out routine wrong:

    #define GPIO_SEL_pin 14                         // D14 = MCP23S08 GPIO SPI select pin
    #define SCLK 18                                 // D18 SPI SCLK
    #define MISO 19                                 // D19 SPI MISO
    #define MOSI 23                                 // D23 SPI MOSI

    #include <SPI.h>

    uint8_t keyboard;

    static const int spiClk = 1000000; // 1 MHz

    //uninitalised pointers to SPI objects
    SPIClass * mcp23s08 = NULL;

    void setup() {
      Serial.begin(115200);
      pinMode(GPIO_SEL_pin, OUTPUT);                     //MCP23S08 SPI select pin
      digitalWrite(GPIO_SEL_pin, HIGH);                  //pull ss high to disable data transfer
      mcp23s08 = new SPIClass(VSPI);
      mcp23s08->begin(SCLK, MISO, MOSI, GPIO_SEL_pin);   //SCLK, MISO, MOSI, SS
      mcp23s08SetUp();
      delay(1);

    }

    void loop() {
      keyboard = mcp23s08Read();
      Serial.println (keyboard);
      delay(100);
    }

    // ================================== routines =================================
    void mcp23s08SetUp( void ) {
      uint8_t dev_adr  = 0x40;                          // MCP23S08 address 0; R/W = write
      uint8_t reg_adr  = 0x00;                          // MCP23S08 IODIR register
      uint8_t reg_data = 0xFF;                          // pin configured as input

      digitalWrite(GPIO_SEL_pin, LOW);                 //pull SS slow to prep other end for transfer
    // ============================= MCP3S08 pin as input ==============================
      mcp23s08->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
      mcp23s08->transfer(dev_adr);
      mcp23s08->transfer(reg_adr);
      mcp23s08->transfer(reg_data);
      mcp23s08->endTransaction();

      reg_adr  = 0x01;                                 // MCP23S08 IPOL register
      reg_data = 0xFF;                                 // invert input polarity
    // ============================= MCP3S08 invert input ==============================
      mcp23s08->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
      mcp23s08->transfer(dev_adr);
      mcp23s08->transfer(reg_adr);
      mcp23s08->transfer(reg_data);
      mcp23s08->endTransaction();

      reg_adr  = 0x06;                                 // MCP23S08 GPPU pull-up register
      reg_data = 0xFF;                                 // set pull-up register
    // ============================= MCP3S08 pullup resistor ==============================
      mcp23s08->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
      mcp23s08->transfer(dev_adr);
      mcp23s08->transfer(reg_adr);
      mcp23s08->transfer(reg_data);
      mcp23s08->endTransaction();

      digitalWrite(GPIO_SEL_pin, HIGH);                //pull ss high to signify end of data transfer
    }

    uint8_t mcp23s08Read ( void ) {
      uint8_t dev_adr  = 0x41;                          // MCP23S08 address 0; R/W = read
      uint8_t reg_adr  = 0x09;                          // MCP23S08 GPIO register
      uint8_t reg_data;                                 // GPIO register
      mcp23s08->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
      mcp23s08->transfer(dev_adr);
      mcp23s08->transfer(reg_adr);
      reg_data = mcp23s08->transfer(0x00);
      mcp23s08->endTransaction();
      return reg_data;
    }

body:
You forgot to toggle SS pin in `mcp23s08Read()` function.

     uint8_t mcp23s08Read ( void ) {
          ----> digitalWrite(GPIO_SEL_pin, LOW);                 //pull SS slow to prep other end for transfer
          uint8_t dev_adr  = 0x41;                          // MCP23S08 address 0; R/W = read
          uint8_t reg_adr  = 0x09;                          // MCP23S08 GPIO register
          uint8_t reg_data;                                 // GPIO register
          mcp23s08->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
          mcp23s08->transfer(dev_adr);
          mcp23s08->transfer(reg_adr);
          reg_data = mcp23s08->transfer(0x00);
          mcp23s08->endTransaction();
          ----> digitalWrite(GPIO_SEL_pin, HIGH);                //pull ss high to signify end of data transfer
          return reg_data;
        }


message:
Error with Sparkfun MP3 Shield and Arduino Due playing music files

The code worked on my Ardino Uno. I plugged it up the exact same way and am now getting an error.

Here is the error I get when I try to upload my code to the due:

    Arduino: 1.8.5 (Windows 10), Board: "Arduino Due (Programming Port)"

    C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp: In static member function 'static void SFEMP3Shield::refill()':

    C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:1984:7: error: 'sei' was not declared in this scope

       sei();

           ^

    C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:2006:9: error: 'cli' was not declared in this scope

         cli(); // allow transfer to occur with out interruption.

             ^

    C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp: In member function 'void SFEMP3Shield::SendSingleMIDInote()':

    C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:2053:7: error: 'cli' was not declared in this scope

       cli(); // allow transfer to occur with out interruption.

           ^

    C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:2067:7: error: 'sei' was not declared in this scope

       sei();  // renable interrupts for other processes

           ^

    exit status 1
    Error compiling for board Arduino Due (Programming Port).

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

Here is my code:

    #include <SPI.h>
    #include <SdFat.h>
    #include <SdFatUtil.h>
    #include <SFEMP3Shield.h>

    SdFat sd;
    SFEMP3Shield MP3player;

    const uint8_t volume = 10; // MP3 Player volume 0=max, 255=lowest (off)
    //10 for normal 50 for testing

    const uint16_t monoMode = 1;

    void setup() {
      initSD();
      initMP3Player();
    }

    void loop() {
      if(!MP3player.isPlaying()){
        MP3player.playTrack(1);
      }
    }

    void initSD() {
      if(!sd.begin(SD_SEL, SPI_HALF_SPEED))
        sd.initErrorHalt();
      if(!sd.chdir("/"))
        sd.errorHalt("sd.chdir");
    }

    void initMP3Player() {
      uint8_t result = MP3player.begin();
      MP3player.setVolume(volume, volume);
      MP3player.setMonoMode(monoMode);
    }

body:
The library is written for the Uno, not the Due. It relies on two instructions that are only available in the AVR compiler.

Newer versions of the core provide a pair of macros, `interrupts()` and `noInterrupts()` that should be used in place of `sei()` and `cli()` respectively, which should be provided by the Due's core as well to make it cross-platform. However that library has never been updated to work with those macros.

You *could* replace the `sei()` and `cli()` calls in the library with `interrupts()` and `noInterrupts()`, however that may not make it work, since it was written with the Uno and other AVR based chips in mind.


message:
How to assign two or more variables incoming from app

I'm really new to Arduino and have some doubts about how Arduino reads data. Lets suppose I have 3 variables `a,b,c`. I need these variables in my Arduino to make whatever. Since all variables are read using `Serial.read()` how can I distinguish between them in my Arduino?

Example:

`Variable a: 2`
`Variable b: 3`
`Variable c: 4`

Arduino example code:

    void loop() {
    int a = Serial.read();
    int b = Serial.read();
    int c = Serial.read();

    if(a == '0'){
    digitalWrite(yellowLed, HIGH);
    }

    if(b == '0'){
    digitalWrite(blueLed, HIGH);
    }

    if(c == '0'){
    digitalWrite(redLed, HIGH);
    }

In every loop, my Arduino does `serial.read()` 3 times, if I only send value b from my app, since `int a = Serial.read()` executes first, will my b value be assigned to a? If yes, how can I avoid that problem and force the correct assignment? Aditionally, in every loop, if `Serial.read()` doesnt read anything, will my values be changed to null or zero?

body:
This is a classic problem that is solved either by uniquely identifying each value or by agreeing on a pre-defined sequence of data.  However, it can be said that many solutions exist for this problem & that these are only 2 examples.

In the first case, the sender and receiver need to agree that all data will be sent in pairs.  A pair of bytes, for example, where the first identifies the data and the second is the data.  In this case the order of data does not matter.  And much more of one type of data can be sent than another.  This is good to use when the data rate is irregular and does not need to be fast.  Stock prices for example.

In the second case, the sender and receiver need to agree that all data will be sent in the same sequence even if there is no data to be sent.  Such a scheme may employ a special synchronizing bit to identify the beginning of a sequence of data.  Usually, when there is no data to be sent, a zero is sent.  But if zeros are significant, then special null characters will have to be agreed upon.  This is good when the data rate is regular and needs to be fast.  Digitized audio for example.


message:
Using a toggle switch to run part of a sketch

First, I am a beginner for this.  I just ordered my first book on coding Arduino and I'm working through some simple applications using a DS3231 (that has a temperature reading), LCD, MicroSD card module, etc.  My board is a Uno R3.  Currently, I need a sketch to run part of a program which contains a loop to collect data and have this run when a toggle switch is turned on.  So, toggle goes on and part of program runs, toggle goes off and this part exits.
The reason I need a toggle with constant on/off is the problem with G forces and vibration.  I momentary push button input will not be reliable.  Ultimately, all the components will be in a amateur high-power rocket to run a roll control program.
If you can help, I greatly appreciate your assistance.

body:
There are different ways to accomplish the same thing.

The condition is a flag, or a read port.

    if(digitalRead(inPin))
         {
         // Your first code here.
         }
    else
         {
         // second code
         }

Switch contacts will bounce when opening or closing. You may want to consider that. Usually it is stable within 10 milliseconds. Depending on what you are doing it may or may not be relevant.


body:
You need a few things.
At the top of your sketch, before setup()

    byte togglePin = x; // from 2 to 19 with an Uno. Wire to connect pin to Gnd when closed.

In setup()

     pinMode (togglePin, INPUT_PULLUP);

In loop()

    if (digitalRead(togglePin) == LOW){
    // switch closed, do something - or stop doing something
    // maybe set a flag too, like
    toggleState = 0;
    }
    else {
    // switch, stop doing something - or start doing something
    toggleState = 1;
    }

The flag can be used elsewhere in your code

    if (someOtherCondition && toggleState == 0){
    // run a timer or motor or something
    }
    if (someOtherCondition && toggleState == 1){
    // turn off timer or motor or something
    }


message:
Creating a library for arduino

I found a really nice 24 bit I2C adc which was fairly cheap as well (ADS1219) but as far as I could tell there are no libraries for it so I decided to make my own. I have managed to write functions and get everything working on the arduino itself but I've been having massive issues with converting it into a library.
So I tried a very basic sketch to see if I can do something as simple as printing hello world using the library.
Here is my ADS1219.h file:

    #ifndef ADS1219
    #define ADS1219

    #if ARDUINO >= 100
     #include "Arduino.h"
    #else
     #include "WProgram.h"
    #endif

    class ADS1219{
    public:
     ADS1219();
     void begin();
     void printHello();
    };

    #endif

And the ADS1219.cpp:

    #if ARDUINO >= 100
     #include "Arduino.h"
    #else
     #include "WProgram.h"
    #endif

    #include

    ADS1219::ADS1219{
     Serial.println("New object created!");
    }

    void ADS1219::begin(){
     Serial.begin(9600);
    }

    void ADS1219::printHello(){
     Serial.println("Hello World");
    }

and my main sketch:

    #include

    ads = new ADS1219;

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

    void loop() {
      ads.printHello();
      delay(2000);
    }

but I get this really long error which basically says I've failed with creating the ads object.
I tried ADS1219 ads; as well but same error ... not sure what's wrong tbh.

    Arduino: 1.8.8 (Windows 10), Board: "Arduino Nano, ATmega328P (Old Bootloader)"

    In file included from sketchADS1219.cpp:7:0:

    ADS1219.h:14:11: error: expected unqualified-id before ')' token

       ADS1219();

               ^

    ADS1219.h:12:14: error: an anonymous struct cannot have function members

     class ADS1219{

                  ^

    ADS1219.h:18:1: error: abstract declarator '' used as declaration

     };

     ^

    ADS1219.cpp:9:17: error: expected id-expression before '{' token

     ADS1219::ADS1219{

                     ^

    ADS1219.cpp:13:21: error: explicit qualification in declaration of 'void begin()'

     void ADS1219::begin(){

                         ^

    ADS1219.cpp:17:26: error: explicit qualification in declaration of 'void printHello()'

     void ADS1219::printHello(){

                              ^

    In file included from C:UsersOM222ODesktopadslibadslib.ino:1:0:

    ADS1219.h:14:11: error: expected unqualified-id before ')' token

       ADS1219();

               ^

    ADS1219.h:12:14: error: an anonymous struct cannot have function members

     class ADS1219{

                  ^

    ADS1219.h:18:1: error: abstract declarator '' used as declaration

     };

     ^

    adslib:3:1: error: 'ads' does not name a type

     ads = new ADS1219;

     ^

    C:UsersOM222ODesktopadslibadslib.ino: In function 'void setup()':

    adslib:7:3: error: 'ads' was not declared in this scope

       ads.begin();

       ^

    C:UsersOM222ODesktopadslibadslib.ino: In function 'void loop()':

    adslib:11:3: error: 'ads' was not declared in this scope

       ads.printHello();

       ^

    exit status 1
    expected unqualified-id before ')' token

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

body:
Your problem stems from this line:

    #define ADS1219

You define the macro ADS1219 as empty. From that point on all references to ADS1219 get replaced with nothing. For example:

    class ADS1219{
    public:
     ADS1219();
     void begin();
     void printHello();
    };

becomes:

    class {
    public:
     ();
     void begin();
     void printHello();
    };

And

    void ADS1219::begin(){
     Serial.begin(9600);
    }

becomes:

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

By using the same name in your header guard as your class name you screw everything else up.

I always use strict rules for header guard macros to ensure that they never conflict with anything else.  You should change yours to read something else.  I would use:

    #ifndef _ADS1219_H
    #define _ADS1219_H

    // ... content

    #endif

----

You are also lacking the parenthesis in the constructor implementation:

    ADS1219::ADS1219{
     Serial.println("New object created!");
    }

should read:

    ADS1219::ADS1219(){
     Serial.println("New object created!");
    }

And you don't give your `ads` variable a type and you don't want to use new:

    ads = new ADS1219;

should read:

    ADS1219 ads;


body:
Are you sure you're compiling this for C++ and not C?

In any case, you're defining

    #define ADS1219

I'm not sure what that does to your class name. Have you tried to

    #define ADS1219_H  // <- Standard include guard

instead? Does this yield different results.


body:
I have made a lot of progress and almost everything works fine ... except I initially used strings in switch case for setting up the voltage reference and conversion modes ... it did not like it at all. I instead aimed to use enums for the same purpose but I'm getting this error now:

    Arduino: 1.8.8 (Windows 10), Board: "Arduino Nano, ATmega328P (Old Bootloader)"

    In file included from sketch\LibraryExample1.ino.cpp:1:0:

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:81:18: error: expected identifier before numeric constant

     #define INTERNAL 3

                      ^

    C:\Users\OM222O\Documents\Arduino\libraries\ADS1219/ADS1219.h:49:3: note: in expansion of macro 'INTERNAL'

       INTERNAL = VREF_INTERNAL,

       ^

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:81:18: error: expected '}' before numeric constant

     #define INTERNAL 3

                      ^

    C:\Users\OM222O\Documents\Arduino\libraries\ADS1219/ADS1219.h:49:3: note: in expansion of macro 'INTERNAL'

       INTERNAL = VREF_INTERNAL,

       ^

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:81:18: error: expected unqualified-id before numeric constant

     #define INTERNAL 3

                      ^

    C:\Users\OM222O\Documents\Arduino\libraries\ADS1219/ADS1219.h:49:3: note: in expansion of macro 'INTERNAL'

       INTERNAL = VREF_INTERNAL,

       ^

    In file included from C:\Users\OM222O\Desktop\LibraryExample1\LibraryExample1.ino:2:0:

    C:\Users\OM222O\Documents\Arduino\libraries\ADS1219/ADS1219.h:51:1: error: expected declaration before '}' token

     }adsRef_t;

     ^

    exit status 1
    Error compiling for board Arduino Nano.

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

my ADS1219.h file is:

    #ifndef ADS1219_H
    #define ADS1219_H

    #if (ARDUINO >=100)
      #include "Arduino.h"
    #else
      #include "WProgram.h"
    #endif

    #include <Wire.h>

    #define CONFIG_REGISTER_ADDRESS 0x20
    #define STATUS_REGISTER_ADDRESS 0x24

    #define MUX_MASK     0x1F
    #define MUX_DIFF_0_1   0x00
    #define MUX_DIFF_2_3   0x20
    #define MUX_DIFF_1_2   0x40
    #define MUX_SINGLE_0   0x60
    #define MUX_SINGLE_1   0x80
    #define MUX_SINGLE_2   0xA0
    #define MUX_SINGLE_3   0xC0
    #define MUX_SHORTED    0xE0

    #define GAIN_MASK     0xEF
    #define GAIN_ONE    0x00
    #define GAIN_FOUR    0x10

    #define DATA_RATE_MASK   0xF3
    #define DATA_RATE_20   0x00
    #define DATA_RATE_90   0x04
    #define DATA_RATE_330   0x08
    #define DATA_RATE_1000   0x0c

    #define MODE_MASK    0xFD
    #define MODE_SINGLE_SHOT  0x00
    #define MODE_CONTINUOUS   0x02

    #define VREF_MASK    0xFE
    #define VREF_INTERNAL   0x00
    #define VREF_EXTERNAL   0x01

    typedef enum{
      ONE = GAIN_ONE,
      FOUR = GAIN_FOUR
    }adsGain_t;

    typedef enum{
      INTERNAL = VREF_INTERNAL,
      EXTERNAL = VREF_EXTERNAL
    }adsRef_t;

    typedef enum{
      SINGLE_SHOT = MODE_SINGLE_SHOT,
      CONTINUOUS = MODE_CONTINUOUS
    }adsMode_t;

    class ADS1219  {
      protected:
     uint8_t address;
      public:
        // Constructor
        ADS1219(int drdy, uint8_t addr = 0x40);

        // Methods
        void begin();
     void resetConfig();
     long readSingleEnded(int channel);
     long readDifferential_0_1();
     long readDifferential_2_3();
     long readDifferential_1_2();
     long readShorted();
     void setGain(adsGain_t gain);
     void setDataRate(int rate);
     void setConversionMode(adsMode_t mode);
     void setVoltageReference(adsRef_t vref);

      private:
     void writeRegister(uint8_t data);
     uint8_t readRegister(uint8_t reg);
     long readConversionResult();
     uint8_t config;
     int data_ready;
    };
    #endif

and my cpp file is:

    #if ARDUINO >= 100
     #include "Arduino.h"
    #else
     #include "WProgram.h"
    #endif

    #include <Wire.h>
    #include "ADS1219.h"

    static uint8_t i2cRead(void) {
      #if ARDUINO >= 100
      return Wire.read();
      #else
      return Wire.receive();
      #endif
    }

    static void i2cWrite(uint8_t x) {
      #if ARDUINO >= 100
      Wire.write(x);
      #else
      Wire.send(x);
      #endif
    }

    ADS1219::ADS1219(int drdy, uint8_t addr) {
      data_ready = drdy;
      address = addr;
      config = 0x00;
    }

    void ADS1219::begin() {
      Wire.begin();
    }

    uint8_t ADS1219::readRegister(uint8_t reg){
      Wire.beginTransmission(address);
      i2cWrite(reg);
      Wire.endTransmission();
      Wire.requestFrom((uint8_t)address,(uint8_t)1);
      return i2cRead();
    }

    void ADS1219::writeRegister(uint8_t data){
      Wire.beginTransmission(address);
      i2cWrite(CONFIG_REGISTER_ADDRESS);
      i2cWrite(data);
      Wire.endTransmission();
    }

    long ADS1219::readConversionResult(){
      Wire.beginTransmission(address);
      i2cWrite(0x10);
      Wire.endTransmission();
      Wire.requestFrom((uint8_t)address,(uint8_t)3);
      byte dataMSB = i2cRead();
      byte data = i2cRead();
      byte dataLSB = i2cRead();
      long data32 = dataMSB;
      data32 <<= 8;
      data32 |= data;
      data32 <<= 8;
      data32 |= dataLSB;
      return (data32 << 8) >> 8;
    }

    void ADS1219::resetConfig(){
     writeRegister(0x00);
    }

    long ADS1219::readSingleEnded(int channel){
     if (channel > 3) return 0;
     config &= MUX_MASK;
     switch (channel){
        case (0):
          config |= MUX_SINGLE_0;
          break;
        case (1):
          config |= MUX_SINGLE_1;
          break;
        case (2):
          config |= MUX_SINGLE_2;
          break;
        case (3):
          config |= MUX_SINGLE_3;
          break;
     default:
       break;
      }
      writeRegister(config);
      while(digitalRead(data_ready)==1);
      return readConversionResult();
    }

    long ADS1219::readDifferential_0_1(){
      config &= MUX_MASK;
      config |= MUX_DIFF_0_1;
      writeRegister(config);
      while(digitalRead(data_ready)==1);
      return readConversionResult();
    }

    long ADS1219::readDifferential_2_3(){
      config &= MUX_MASK;
      config |= MUX_DIFF_2_3;
      writeRegister(config);
      while(digitalRead(data_ready)==1);
      return readConversionResult();
    }

    long ADS1219::readDifferential_1_2(){
      config &= MUX_MASK;
      config |= MUX_DIFF_1_2;
      writeRegister(config);
      while(digitalRead(data_ready)==1);
      return readConversionResult();
    }

    long ADS1219::readShorted(){
      config &= MUX_MASK;
      config |= MUX_SHORTED;
      writeRegister(config);
      while(digitalRead(data_ready)==1);
      return readConversionResult();
    }

    void ADS1219::setGain(adsGain_t gain){
     config &= GAIN_MASK;
     config |= gain;
      writeRegister(config);
    }

    void ADS1219::setDataRate(int rate){
     config &= DATA_RATE_MASK;
     switch (rate){
        case (20):
          config |= DATA_RATE_20;
          break;
        case (90):
          config |= DATA_RATE_90;
          break;
        case (330):
          config |= DATA_RATE_330;
          break;
        case (1000):
          config |= DATA_RATE_1000;
          break;
     default:
       break;
      }
      writeRegister(config);
    }

    void ADS1219::setConversionMode(adsMode_t mode){
     config &= MODE_MASK;
     config |= mode;
      writeRegister(config);
    }

    void ADS1219::setVoltageReference(adsRef_t vref){
     config &= VREF_MASK;
     config |= vref;
      writeRegister(config);
    }

it seems to be passing Gain (or maybe hasn't compiled that yet) but failing on the reference selection ... I don't know what I should change in order to fix the issue.

Edit: I'm really hoping it's not another naming convention thing ... if it is, I'm sorry but C++ seems to waaaaayyyy too picky about names in general


message:
Which LCD Pins, if any, require PWM?

In the Arduino [Tutorial Page][1] named "Hello World" aimed to help people connect a 16x2 LCD Display compatible with Hitachi HD44780 driver to an Arduino Uno. The pins used to connect the Arduino Uno and LCD Module are as follows:

 - LCD RS pin to digital pin 12
 - LCD Enable pin to digital pin 11
 - LCD D4 pin to digital pin 5
 - LCD D5 pin to digital pin 4
 - LCD D6 pin to digital pin 3
 - LCD D7 pin to digital pin 2

Pins 3,5 and 11 are connected to PWM Pins, however, I'm wondering if they actually need these PWM capabilities or does this tutorial just pick random pins and the LCD's D6, D4 and Enable pins doesn't actually need the PWM capabilities available of these pins.

I'm asking this as I'm considering on using an Arduino Mega for my next project and it would be much easier and neater for all the pins of the LCD to go onto the digital pins instead of some being on the digital and others on the PWM pins.

  [1]: https://www.arduino.cc/en/Tutorial/HelloWorld

body:
Likely all programmable pins on modern embedded processors are able to perform digital I/O.  In addition, many can also perform other tasks such as PWM, or Analog to Digital Conversion (ADC).  This is true for many of the different processors used on different Arduino boards.

Often, the nice people who write the C++ driver class of programs or Arduino Libraries offer the user the ability to change pin assignments used by the Arduino Libraries when instantiating an instance of the driver.  This is true for the [LiquidCrystal driver][1] in the [tutorial][2] in the question.  This can be an advantage as processor's resources are limited.  For example, if you need PWM controlled pin to dim LEDs, you can move LCD controlling pins to other non-PWM pins.

The LCD specified in the tutorial linked to in the above question uses a common [Hitachi HD44780][3] interface.  Such assemblies only need embedded processor Digital I/O pins for control.  Had the LCD no electronic driver, the segments need to be directly driven by very low alternating current (AC).  This is difficult for embedded processors.  However, it may be possible using enough PWM pins and some clever software & hardware.

  [1]: https://www.arduino.cc/en/Reference/LiquidCrystal
  [2]: https://www.arduino.cc/en/Tutorial/HelloWorld
  [3]: https://en.wikipedia.org/wiki/Hitachi_HD44780_LCD_controller


body:
PWM is not used on those pins for the LCD operation. You can choose more convenient pins as long as they are general purpose pins. For example, not A/D input only.

(I thought you might appreciate a short clear answer)


message:
Trying to save .wav files with new name every loop

I have built a set up with an Arduino UNO hooked up to a switch, so that whenever the switch goes from HIGH to LOW it saves audio to an SD card. I am using the TMRpcm Library. The problem is the current code will only be able to record 1 audio file; I want to the Arduino to run for a long period of time collecting multiple audio files as the switch is turned on and off. I need a way that will allow it so everytime the switch is pushed back down the next file saved will have a different name than the one previously saved (preferably by an increased numeric value eg "1.wav" & "2.wav"). I have tried **audio.startRecording(audiofile+".wav", 16000, A0);** and it makes it so no files save to the SD card accept an empty file simple titled 'WAV'. I have tried using a switch case but it will not allow me to reach a case over 10, without running out of RAM. Currently, my code can save 1 audio file but I want it to reach a point where it can save as many as the SD card can hold, without having to restart the software.

My current code is here. Any help would be greatly appreciated

    //////////////////////////////////////// SD CARD
    #include <SD.h>
    #include <SPI.h>
    #include <TMRpcm.h>
    #define SD_ChipSelectPin 10
    TMRpcm audio;
    //////////////////////////////////////// SWITCH CASE
    int audiofile = 0;     // # of recording
    unsigned long i = 0;
    bool recmode = 0;      // recording state
    //////////////////////////////////////// SWITCH
    int inPin = 2;         // input Switch Pin
    int state = HIGH;      // the current state switch
    int reading;           // the current reading from the switch

    void setup() {
      Serial.begin(9600);
      pinMode(A0, INPUT);  // Microphone
      pinMode(inPin, INPUT_PULLUP); // Switch
      //////////////////////////////////////// SD CARD
      SD.begin(SD_ChipSelectPin);
      audio.CSPin = SD_ChipSelectPin;
    }

    void loop() {

      reading = digitalRead(inPin);
      ////////////////////////////////////////
      while (i < 300000) {
        i++;
      }
      i = 0;
      ////////////////////////////////////////
      if (reading == LOW) {
        if (recmode == 0) {
          recmode = 1;

          Serial.println("Recording");

          audiofile++; // To move case
          audio.startRecording("1.wav", 16000, A0);
        }
      }
      ////////////////////////////////////////
      else if (reading == HIGH) {
        recmode = 0;

        Serial.println("Hung-Up");
        audio.stopRecording("1.wav");
      }
    }

body:
I would (and do) use `snprintf` to format a string as a filename:

    // Global scope, or local static
    uint32_t myFileNumber = 1;
    char filename[12];

    // in your function - results in 00000001.WAV
    snprintf(filename, 12, "d.WAV", myFileNumber);

d will allow between 00000000.WAV and 99999999.WAV and always with 8 digits. Any more and it will get truncated and corrupted (100000000.WA) but won't cause a buffer overrun. You will have to take precautions that you never have more than 100 million files ;)


message:
Code getting stuck waiting for GPS Output

I'm basically trying to make a device that pulls the GPS information from a SIM808 and pushes it to a server online via GPRS.

I am sorry as I am not good at programming so ive spent days trying to debug this but i have not been able to figure out whats wrong.

Ill get the basics out of the way.

Board: Mega2560 (I know its overkill but its what i had in hand)
SIM+GPS sensor: SIM808 Module  TinyGPS v13
RTC: DS1307
Arduino IDE v1.8.8

Down to the specifics,
I started with SoftwareSerial Library but i heard it was inefficient so i switched to AltSoftSerial.
The serial library is working as I do get output using AT commands.
The problem is that when i load up the stock TinyGPS example sketch sometimes it works sometimes it gives me error saying the GPS module wasn't detected.

i tried using AT commands directly or a different GPS library but i cant figure out how to pass on data to a database over GPRS.

but basically I am sure the wiring isn't faulty nor is the GPS module (i hope) as it gives an output at ATCommands, even the RTC module is confirmed working. I know the URL in the ATCommand is fake but that is for demonstration purposes.

Coming to the code below. If i change the bool newData = false; to bool newData = true; the the code works just once with wrong GPS information.

any help would be greatly appreciated. Thank You

Edit 1: The problem has been solved, it wasn't working when i used both GPS and GPRS on SIM808 i switched to NeoGPS 6m module and GPRS from SIM800/808 it worked. Thank You.

    #include <AltSoftSerial.h>
    #include <TinyGPS.h>

    #include <Wire.h>
    #include <DS1307new.h>

    TinyGPS gps;

    SoftwareSerial sGPS (46,48);

    uint16_t startAddr = 0x0000;  //Start address to store in NVRam
    uint16_t lastAddr;        //New address to store in NVRam
    uint16_t TimeIsSet = 0xaa55;  //Helper that time must not be set again

    int currentDay = 0;
    int currentMonth = 0;
    int currentYear = 0;
    int currentHour = 0;
    int currentMinute = 0;

    float flat, flon;
    float previousFLat = 0.0;
    float previousFLon = 0.0;

    void setup()
    {

      Serial.begin(9600);
      sGPS.begin(9600);

      /*
      Control the clock.
      Clock will only be set if NV-RAM Address does not contain 0xaa.
      DS1307 should have a battery backup.
      */

      RTC.getRAM(54, (uint8_t *)&TimeIsSet, sizeof(uint16_t));
      if (TimeIsSet != 0xaa55)
      {
        RTC.stopClock();

        RTC.fillByYMD(2011,4,8);
        RTC.fillByHMS(22,7,0);

        RTC.setTime();
        TimeIsSet = 0xaa55;
        RTC.setRAM(54, (uint8_t *)&TimeIsSet, sizeof(uint16_t));
        RTC.startClock();
      }
      else
      {
        RTC.getTime();
      }

      /*
       Control Register for SQW pin which can be used as an interrupt.
    */
      RTC.ctrl = 0x00;                      // 0x00=disable SQW pin, 0x10=1Hz,
                                            // 0x11=4096Hz, 0x12=8192Hz, 0x13=32768Hz
      RTC.setCTRL();
      delay(5000);
      }

      void loop()
    {
        RTC.getTime();

        currentDay = RTC.day;
        currentMonth = RTC.month;
        currentYear = RTC.year;
        currentHour = RTC.hour;
        currentMinute = RTC.minute;

      bool newData = false;

      //For one second we parse GPS data and report some key values

      for (unsigned long start = millis(); millis() - start < 1000;)

      {
      while (sGPS.available())
        {
          char c = sGPS.read();
          Serial.write(c); // uncomment this line if you want to see the GPS data flowing
          if (gps.encode(c)) // Did a new valid sentence come in?
          newData = true;
        }

      }

      if (newData)
      {
        unsigned long age;
        gps.f_get_position(&flat, &flon, &age);

        if ((flat !=previousFLat)||(flon !=previousFLon))
        {
          previousFLat = flat;
          previousFLon = flon;
          Serial.print (previousFLat,6);
          Serial.println(previousFLon,6);
          SendSQL();
        }
      }

    }

      void SendSQL()
      {

        //Serial.println("Start Send");
        Serial.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
        delay(500);
        Serial.println("AT+SAPBR=3,1,\"APN\",\"airtelgprs.com\"");
        delay(500);
        Serial.println("AT+SAPBR=1,1");
        delay(500);
        Serial.println("AT+SAPBR=2,1");
        delay(3000);
        Serial.println("AT+HTTPINIT");
        delay(500);
        Serial.println("AT+HTTPARA=\"CID\",1");
        delay(500);
        Serial.print("AT+HTTPARA=\"URL\",\"www.google.com/add_data.php?");
        Serial.print("addDay=");

          if (currentDay <10)
            {
            Serial.print("0");
            Serial.print(currentDay);
            }

          else
            {
            Serial.print(currentDay);
            }

          Serial.print("/");

          if (currentMonth < 10)
            {
              Serial.print("0");
              Serial.print(currentMonth);
            }

          else
            {
              Serial.print(currentMonth);
            }

          Serial.print("/");
          Serial.print(currentYear);
          Serial.print("&addHour=");

          if (currentHour <10)
            {
              Serial.print("0");
              Serial.print(currentHour);
            }

            else

            {
              Serial.print(currentHour);
            }

            Serial.print(":");

            if (currentMinute <10)

            {
              Serial.print("0");
              Serial.print(currentMinute);
            }

            else

            {
              Serial.print (currentMinute);
            }

              Serial.print ("&addLati=");
              Serial.print(previousFLat, 6);
              Serial.print("&addLongti=");
              Serial.print(previousFLon, 6);
              Serial.println("\"");
              delay(3000);
              Serial.println("AT+HTTPACTION=0");
              delay(15000);
              Serial.println("AT+HTTPTERM");
              delay(500);
              Serial.println("AT+SAPBR=0,1");
              delay(500);
              Serial.println("Finish");
            }

body:
You have a Mega with 4 hardware serial ports. Use of those - Serial1, Serial2, Serial 3 - to talk to the GPS.

I did a project with a SIM808 module from DF Robotics.  I spent some time just powering the GPS part of it up and watching what came out.  Do the same with some simple serial print statements.

    if (Serial1.available() >0){
    Serial.print(Serial1.read());
    }

Then when you understand what comes out, you can watch in setup() for the end of messages that indicate you have good GPS data, or just send AT commands until you get a good reply back. My module took I think 7-8 seconds before it would talk, so I just waited in setup() until I started getting messages. I knew what to expect from the above testing, it was always a fixed amount, so I grabbed all that, looked at the last few to make sure it was as expected, then started the GPS commands to see if it had good data from the satellites before continuing. I suspect the TinyGPS library does similar, but the SIM808 module added some extra characters, or you had to add extra characters, to identify GPS commands from the text message commands the SIM808 expected.


body:
I agree with above answer use the Serial ports available and do something in your setup to probe the sim808 until you get some feedback I am using SIM868 in one of my projects and had the same problem of not getting any feedback until i set a while loop up in the setup that was probing by only sending 'AT' to the module (I did not use tinyGPS i only used Serial and sent it AT commands)

[Here the application notes with the AT commands for the GPS side of SIM808][1]

  [1]: https://cdn-shop.adafruit.com/datasheets/SIM808_GPS_Application_Note_V1.00.pdf

This approach will give you a better idea of what is happening and where you are going wrong


body: The problem has been solved, it wasn't working when i used both GPS and GPRS on SIM808 i switched to NeoGPS 6m module and GPRS from SIM800/808 it worked. Thank You.


message:
toggling Rx, Tx pins after Serial.begin

What should one expect when the following program runs on Arduino Uno?

    void setup()
    {
        Serial.begin(9600);
        DDRD |= 0b11;
    }

    void loop()
    {
        PORTD |= 0b11;
        delay(100);
        Serial.print("ABCD");
        PORTD &= ~0b11;
        delay(100);
        Serial.print("DEFG\n");
    }

When Serial.begin() is used, the pins PD0, PD1 might be configured as UART pins. After that if DDR is used, are the pins configured as GPIO, or are they still UART Rx, Tx pins?

body:
As always, the answer is in the datasheet:

> * TXD/PCINT17 – Port D, Bit 1
>
> TXD, Transmit Data (Data output pin for the USART). When the USART Transmitter is enabled, this pin is configured as an output **regardless of the value of DDD1.**
PCINT17: Pin Change Interrupt source 17. The PD1 pin can serve as an external interrupt source.
>
> * RXD/PCINT16 – Port D, Bit 0
>
> RXD, Receive Data (Data input pin for the USART). When the USART Receiver is enabled this pin is configured as an input **regardless of the value of DDD0.** When the USART forces this pin to be an input, the pull-up can still be controlled by the PORTD0 bit.

As to what trying to set the output level on the TX pin would have, only experimentation can show.  It's not defined in the datasheet (because who would do it?)


message:
Nano damaged. Power LED OK. USB Detected. No Sketch upload. No Program running

seems i damaged one of my Nanos. i have to say i am new to Arduino and have basic electronik skills and i realized after shopping via amazon that the Nanos i have are clones with CH340G.
never the less they are working. i was building a light driven open/close circuit for my chickens. using L293D motordriver, LCD, photocell. my sketch was just reading the photocell and outputting it on the LCD. not yet using the L293D in the sketch but assembled it already (without Motors and MV+).
The program was running for ~ 2 minutes. i was testing the reading for the photocell and was wondering why at low light the reading was still quite high ~ 600+. then all disappeared from the LCD apart of the background light.
as i couldnt get it running i tried to upload Blink again -> not working

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x96 code here
    ...
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x96
    Problem beim Hochladen auf das Board. Hilfestellung dazu unter http://www.arduino.cc/en/Guide/Troubleshooting#upload.

after a while i was reading about programmers so i turned another Nano into a ArduinoISP trying to write either Booloader or Sketch via ISP bypassing USB (as i understood the different articles)
which gave

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

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x14

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x01
    avrdude: stk500_initialize(): (a) protocol error, expect=0x14, resp=0x10
    avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

    avrdude: stk500_disable(): unknown response=0x12
    Der ausgewählte serielle Port avrdude: stk500_disable(): unknown response=0x12
     ist nicht vorhanden oder das Board ist nicht angeschlossen

then i used Atmega_Board_Detector and Atmega_Board_Programmer which both seem to work.
output of Boarddetector:

  Atmega chip detector.
  Written by Nick Gammon.
  Version 1.20
  Compiled on Dec 27 2018 at 15:13:27 with Arduino IDE 10808.
  Attempting to enter ICSP programming mode ...
  Entered programming mode OK.
  Signature = 0x1E 0x95 0x0F
  Processor = ATmega328P
  Flash memory size = 32768 bytes.
  LFuse = 0xFF
  HFuse = 0xDE
  EFuse = 0xFD
  Lock byte = 0xEF
  Clock calibration = 0x9E
  Bootloader in use: Yes
  EEPROM preserved through erase: No
  Watchdog timer always on: No
  Bootloader is 512 bytes starting at 7E00

  Bootloader:

  7E00: 0x11 0x24 0x84 0xB7 0x14 0xBE 0x81 0xFF 0xF0 0xD0 0x85 0xE0 0x80 0x93 0x81 0x00
  7E10: 0x82 0xE0 0x80 0x93 0xC0 0x00 0x88 0xE1 0x80 0x93 0xC1 0x00 0x86 0xE0 0x80 0x93
  7E20: 0xC2 0x00 0x80 0xE1 0x80 0x93 0xC4 0x00 0x8E 0xE0 0xC9 0xD0 0x25 0x9A 0x86 0xE0
  7E30: 0x20 0xE3 0x3C 0xEF 0x91 0xE0 0x30 0x93 0x85 0x00 0x20 0x93 0x84 0x00 0x96 0xBB
  7E40: 0xB0 0x9B 0xFE 0xCF 0x1D 0x9A 0xA8 0x95 0x81 0x50 0xA9 0xF7 0xCC 0x24 0xDD 0x24
  7E50: 0x88 0x24 0x83 0x94 0xB5 0xE0 0xAB 0x2E 0xA1 0xE1 0x9A 0x2E 0xF3 0xE0 0xBF 0x2E
  7E60: 0xA2 0xD0 0x81 0x34 0x61 0xF4 0x9F 0xD0 0x08 0x2F 0xAF 0xD0 0x02 0x38 0x11 0xF0
  7E70: 0x01 0x38 0x11 0xF4 0x84 0xE0 0x01 0xC0 0x83 0xE0 0x8D 0xD0 0x89 0xC0 0x82 0x34
  7E80: 0x11 0xF4 0x84 0xE1 0x03 0xC0 0x85 0x34 0x19 0xF4 0x85 0xE0 0xA6 0xD0 0x80 0xC0
  7E90: 0x85 0x35 0x79 0xF4 0x88 0xD0 0xE8 0x2E 0xFF 0x24 0x85 0xD0 0x08 0x2F 0x10 0xE0
  7EA0: 0x10 0x2F 0x00 0x27 0x0E 0x29 0x1F 0x29 0x00 0x0F 0x11 0x1F 0x8E 0xD0 0x68 0x01
  7EB0: 0x6F 0xC0 0x86 0x35 0x21 0xF4 0x84 0xE0 0x90 0xD0 0x80 0xE0 0xDE 0xCF 0x84 0x36
  7EC0: 0x09 0xF0 0x40 0xC0 0x70 0xD0 0x6F 0xD0 0x08 0x2F 0x6D 0xD0 0x80 0xE0 0xC8 0x16
  7ED0: 0x80 0xE7 0xD8 0x06 0x18 0xF4 0xF6 0x01 0xB7 0xBE 0xE8 0x95 0xC0 0xE0 0xD1 0xE0
  7EE0: 0x62 0xD0 0x89 0x93 0x0C 0x17 0xE1 0xF7 0xF0 0xE0 0xCF 0x16 0xF0 0xE7 0xDF 0x06
  7EF0: 0x18 0xF0 0xF6 0x01 0xB7 0xBE 0xE8 0x95 0x68 0xD0 0x07 0xB6 0x00 0xFC 0xFD 0xCF
  7F00: 0xA6 0x01 0xA0 0xE0 0xB1 0xE0 0x2C 0x91 0x30 0xE0 0x11 0x96 0x8C 0x91 0x11 0x97
  7F10: 0x90 0xE0 0x98 0x2F 0x88 0x27 0x82 0x2B 0x93 0x2B 0x12 0x96 0xFA 0x01 0x0C 0x01
  7F20: 0x87 0xBE 0xE8 0x95 0x11 0x24 0x4E 0x5F 0x5F 0x4F 0xF1 0xE0 0xA0 0x38 0xBF 0x07
  7F30: 0x51 0xF7 0xF6 0x01 0xA7 0xBE 0xE8 0x95 0x07 0xB6 0x00 0xFC 0xFD 0xCF 0x97 0xBE
  7F40: 0xE8 0x95 0x26 0xC0 0x84 0x37 0xB1 0xF4 0x2E 0xD0 0x2D 0xD0 0xF8 0x2E 0x2B 0xD0
  7F50: 0x3C 0xD0 0xF6 0x01 0xEF 0x2C 0x8F 0x01 0x0F 0x5F 0x1F 0x4F 0x84 0x91 0x1B 0xD0
  7F60: 0xEA 0x94 0xF8 0x01 0xC1 0xF7 0x08 0x94 0xC1 0x1C 0xD1 0x1C 0xFA 0x94 0xCF 0x0C
  7F70: 0xD1 0x1C 0x0E 0xC0 0x85 0x37 0x39 0xF4 0x28 0xD0 0x8E 0xE1 0x0C 0xD0 0x85 0xE9
  7F80: 0x0A 0xD0 0x8F 0xE0 0x7A 0xCF 0x81 0x35 0x11 0xF4 0x88 0xE0 0x18 0xD0 0x1D 0xD0
  7F90: 0x80 0xE1 0x01 0xD0 0x65 0xCF 0x98 0x2F 0x80 0x91 0xC0 0x00 0x85 0xFF 0xFC 0xCF
  7FA0: 0x90 0x93 0xC6 0x00 0x08 0x95 0x80 0x91 0xC0 0x00 0x87 0xFF 0xFC 0xCF 0x80 0x91
  7FB0: 0xC0 0x00 0x84 0xFD 0x01 0xC0 0xA8 0x95 0x80 0x91 0xC6 0x00 0x08 0x95 0xE0 0xE6
  7FC0: 0xF0 0xE0 0x98 0xE1 0x90 0x83 0x80 0x83 0x08 0x95 0xED 0xDF 0x80 0x32 0x19 0xF0
  7FD0: 0x88 0xE0 0xF5 0xDF 0xFF 0xCF 0x84 0xE1 0xDE 0xCF 0x1F 0x93 0x18 0x2F 0xE3 0xDF
  7FE0: 0x11 0x50 0xE9 0xF7 0xF2 0xDF 0x1F 0x91 0x08 0x95 0x80 0xE0 0xE8 0xDF 0xEE 0x27
  7FF0: 0xFF 0x27 0x09 0x94 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0x04 0x04

  MD5 sum of bootloader = 0xFB 0xF4 0x9B 0x7B 0x59 0x73 0x7F 0x65 0xE8 0xD0 0xF8 0xA5 0x08 0x12 0xE7 0x9F
  Bootloader name: optiboot_atmega328

  First 256 bytes of program memory:

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

  Programming mode off.
Output of Board Programmer:

  Atmega chip programmer.
  Written by Nick Gammon.
  Version 1.38
  Compiled on Dec 27 2018 at 15:15:38 with Arduino IDE 10808.
  Attempting to enter ICSP programming mode ...
  Entered programming mode OK.
  Signature = 0x1E 0x95 0x0F
  Processor = ATmega328P
  Flash memory size = 32768 bytes.
  LFuse = 0xFF
  HFuse = 0xDE
  EFuse = 0xFD
  Lock byte = 0xEF
  Clock calibration = 0x9E
  Type 'L' to use Lilypad (8 MHz) loader, or 'U' for Uno (16 MHz) loader ...
  Using Uno Optiboot 16 MHz loader.
  Bootloader address = 0x7E00
  Bootloader length = 512 bytes.
  Type 'Q' to quit, 'V' to verify, or 'G' to program the chip with the bootloader ...
  Erasing chip ...
  Writing bootloader ...
  Committing page starting at 0x7E00
  Committing page starting at 0x7E80
  Committing page starting at 0x7F00
  Committing page starting at 0x7F80
  Written.
  Verifying ...
  No errors found.
  Writing fuses ...
  LFuse = 0xFF
  HFuse = 0xDE
  EFuse = 0xFD
  Lock byte = 0xEF
  Clock calibration = 0x9E
  Done.
  Programming mode off.
  Type 'C' when ready to continue with another chip ...

other observations:
when trying to upload a sketch the rx LED blinks where thin a few times but not bright and at the speed it usually does. the L LED blinks at power on a few times.

i have 2 questions:

1. can you see anything in my circuit that could have damaged the NANO?

2. any idea to recover the NANO?

i am more curious on the first question as i don't want to take out another one. the second is more curiosity what can be done on a Nano.
and i am clueless why it died as i run all the experiments individually on an UNO

attached pictures and my fight with Fritzing for the schematics.
[![enter image description here][1]][1]
[![enter image description here][2]][2]
[![enter image description here][3]][3]
[![enter image description here][4]][4]
Many Thanks already

  [1]: https://i.stack.imgur.com/aNv8K.jpg
  [2]: https://i.stack.imgur.com/LrWQY.jpg
  [3]: https://i.stack.imgur.com/1R3Xu.jpg
  [4]: https://i.stack.imgur.com/hJgt1.jpg

UPDATE:
just recognized that also my working NANOs can not be programmed via ArduinoISP Sketch using a Programmer NANO. so as the tools from Nick Gammon.
are working https://github.com/nickgammon/arduino_sketches. i assume my chip is working and it is up to the USB Chip or connection.

UPDATE2:
my NANO is fully back in live. what ever happened seems to have corrupted my flash. so after the TIPs from @Majenko with the 10uF Cap between Reset and GND i was able to programm via a "Programmernano". but here is another catch
when you first flash bootloader and then right away flash a sketch via programmer as well, this erases again the bootloader. you can check this with the
Atmega chip detector.
Written by Nick Gammon.

  Bootloader is 2048 bytes starting at 7800

  Bootloader:

  7800: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
  7810: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
  7820: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
  7830: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF

So i just flash the Bootloader via ArduinoISP and then connect the NANO directly to USB to flash a sketch

body:
Try replacing the diode as in this link, it worked for me: [https://forum.arduino.cc/index.php?topic=166089.0][1]

 A short on VCC might damage the diode.

As for the answer to the first question, yes there is a flaw in the design, if the external power is lost the LCD and the L293D will be powered from USB through the above diode.

"Small change" , see Juraj's comment below.

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


body:
Based on the output from my sketches that you have posted, the CPU chip is fine (Atmega328P). Since you cannot program via the USB port is looks likely that the CH340G is damaged.

A fall-back position is to use another one of the sketches (Atmega_Hex_Uploader) in the link you posted, and upload code via the SPI interface. To make this work you need to purchase a micro-SD card interface as described [here](http://www.gammon.com.au/forum/?id=11638) for around $US 15.

As for why it failed, this should be investigated promptly. Possibly [the answer by Dorian](https://arduino.stackexchange.com/a/60064/10794) will help.


message:
20 m LED WS2811 Pixel Stripe 12 V

i need some help for my masterthesis.
I plan an Light and Sound installation and for this I decided to use the shape of an Dodecahedron and I want to put LED RGB Pixel Stripes on the surfaces to light the space. Imagine it like a huge ceiling light in shape of a half Dodecahedron.

What I have:

 - 1 x Arduino Starter Kit
 - 4 x RGB LED Pixel Stripe: BTF-LIGHTING WS2811, 5M, 60 LEDs/m, 300LEDs RGB, DC12V
  - (0,3W/LED = 90W/5 M (1 LED Stripe) = 360 W/20 M an in total 40A (4 LED Stripes))
 - 2 x LED Stripe: Minger SMD 2835, 5m, 300 LEDs, Dimmable, 6000K Kaltweiß, DC12V
(?)

The half of the Dodecahedron has 6 surfaces. Each surface gets like 300 to 350 cm RGB LEDs and 150 cm of Cold White.

My plan is to program the RGB LEDs with Strobe-Light (10 Hz) and changing colours and at the End of the installation the Cold White ("Daylight") is lighten up the space. (But this is another challenge for me ;))

How to connect all of them with my Arduino Uno? Any ideas?
Thank you very much!

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

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

body: So, addressable RGB LED strips.  You can drive each string from an Arduino output, or daisy chain the signal thru all of them and just pump out the needed data using Adafruit Neopixel library, or the FastLED library. Make multiple power connections to keep the amount of 12V current going thru any one strip to a reasonable level.


body:
Your big challenge is going to be power. Sum up the current requirements of ALL of your LED strips. Find a power supply that puts out ≈20% more than that. Read up on the max power you can pass through each strip, You can daisy-chain the power on multiple strips up to the current handling ability of the strips. Say the docs say a strip can pass max 5A through it, and each draws 1A. So you could chain the power connections of 5 of them one to the next, but no more than that. Also make sure you use power wire that's rated for your current needs. Remember your ground wires need to be heavy enough for your current needs as well. (The signal wires can be much lighter gauge.)

The signal lines don't need to follow the same topology as the power connections, but it's simpler to wire up if they do. (You could make the control lines of ALL of the LED strips in one long "snake" but run the power wires in a star pattern so the power wires don't exceed the current carrying limits of the strips or of your power wires. You could also wire both the power and the signal lines in a star pattern, and drive each point of the star with a separate Arduino pin.) You should be able to find a [**chart online that gives you the current carrying ability of different gauges of wire**][1]. There, too, use wire that's rated a little over the current need, just to be safe. (That chart also talks about maximum length of wire to keep the voltage drop below 2%, which is a good idea.)

  [1]: http://info.waytekwire.com/blog/automotive-wire-gauge-guide/


message:
Do the libraries of the Arduino Uno work with the Arduino Mega?

I did a project with the Arduino Due and the libraries for the VS1053 MP3 Shield were not compatable with the Due. Are the libraries that work with the Uno compatable with the Arduino Mega?

body:
> Are the libraries that work with the Uno compatable with the Arduino Mega?

Sometimes.

They have a higher chance of being compatible, due to them both using the same AVR core, but since internal peripherals differ slightly there is a chance that, depending on what the library does, it won't work right.

You just have to try it and see.


message:
SIlly PID question using the PID library

I'm new to PID.
My goal: control the motor to get it to run a given RPM by a potmeter (which is setpoint).
Sensor is optical (detects white line, reflections), counts 100 round in x amount of time. Small calculation gives detected RPM.
I'm using an Arduino and the PID library.

Now my question.
Let's say I've implemented the PID lib on the arduino. It all calculates and so on, but it gives a PID_value which I don't understand.

Ex:
setpoint = 5000
detected = 4999
received PID value = 40

It's my guess that this (or rather: all) PID-lib I'm using always gives a value between 0 and 255 and I have to map/scale that value to my AC trigger.
Could someone point me in the right direction? Thanks!

body:
See [PID Library - SetOutputLimits()](https://playground.arduino.cc/Code/PIDLibrarySetOutputLimits) - you can change the limits.

For a meaningful result you need to make the output do something reasonable to the speed. Since your detected speed is lower than the desired speed, you have found it outputs a positive value, which is good, as far as it goes. But you have to interpret that in the context of what you are currently sending to the motor. If you are using PWM to control the motor you could feed the output (40 in this case) to the motor. If that makes it go even slower hopefully the PID library will compensate.

It's hard to make more suggestions without seeing the code.