message:
Creation of multiple power cells to be controlled by Arduino

I'm fairly new to the Arduino world, but have a history of good working knowledge of computers and software (I'm a software engineer), but I've only had the opportunity so far to create a few simple successful play-around projects.

I've decided to embark on a fairly ambitious project to build my son a ride on battery powered car for Christmas and trying to put all the pieces together.

An integral part of this plan is to develop what I call a couple of 'Power cells', which is simply a battery enclosure that has:

**Updated:**

1. An input from the Arduino to control the motor speed/voltage.
2. An input from either the Arduino or forward reverse switch to control the direction of polarity (make motor spin forwards or backwards)
3. Has a output to power the motor: 20V, drawing about 1-1.5 Amps
4. Has a output to power the 9x 12V LED lights on it, about upto 50W total (the LED lights will be controlled by the Arduino outside of the power bank, seeing there are a few of them).

I've drawn up a schematic that works with the components I've bought to help put the system together and was wondering if I am missing anything, critical or not?

Info about the battery I'm using can be found here: [Aldi Xfinity 20V Li-Ion Battery teardown.][1]

**More Specifically:**

- Are there any errors with the cabling, I'm assuming no additional earth is required in a DC Circuit.
- What size cables will i need to adequately service my power requirements?
- Would I be able to control the reverse polarity switch directly from the Arduino? As I would like to also trigger a beeper when it is switched in reverse mode. Keep in mind the arduino would need to control 2-4 power cells.
- I assume the controlling the potentiometer from the arduino I would need to use junction boxes between the arduino and the power cells to distribute the signal across each power cell, would this be the best way to do this?
- The Li-Ion Battery also seems to have T output pin, i assume this is temperature monitoring, is there a way to utilize this input into the arduino for safety monitoring?
- I was thinking of splitting the lighting power load between 2 power banks, would this be recommended / possible? (left power cell would power left side leds and right power bank would power right cell leds, with the exception of them both powering the center led).
- Are there any additional safety precautions I should be following, especially working with a Li-Ion battery, ie. Fuse etc ?

I'm planning to make 2x of these Power cells to put in the car (each powers its own motor) (with the ability to add another 2 down the track).

Would really appreciate your feedback (please let me know if this is not the right place to ask this sort of question).

[![Power Cell Schematic][2]][2]

  [1]: http://robotsaregodless.blogspot.com/2017/05/aldi-xfinity-plus-20v-rechargeable-li.html
  [2]: https://i.stack.imgur.com/VttZl.jpg

body:
OK. Looks much better now. And I see one problem. It seems that the normal way to do the speed control is with a pot. A variable voltage at the input depending on the rotation. The Arduino low end designs have an analog out capability but it really is not analog. It is a pulse width variable signal that produces an on percentage between 0 volts and the CPU positive supply voltage. The boards do not have a real digital to analog converter. (maybe some higher end boards but not boards based on the Uno CPU.

It may still work but you need to integrate the pulse output and produce a real analog output voltage. A resistor on the output connected to a capacitor to ground will do the integration and filter out the pulses.

[![][1]][1]

See http://www.ontrak.net/pwm.htm for more details.

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

The problem you might encounter is to much loading on the capacitor by the pot input circuit. Without more details about the module I couldn't say. The signal can be buffered with an amplifier but that adds to the complexity. Still would be doable though.

Or you can add a real digital to analog converter to the Arduino board. That would be my preference rather than having to add a buffer amplifier if a simple RC circuit wasn't good enough.

Do you have a link for that board?

From the picture of the linked speed module. It uses a LM324 opamp to generate the PWM signal. I did a quick look and found a typical circuit.

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

http://www.pcsilencioso.com/cpemma/graphics/erg_pwm_sch.gif

Typical but not the exact one. It is much as I expected. And if you did the RC only filtering then it may just work. The opamp input would not be too much loading on the capacitor. The concern that I have is that the 5 volt maximum from the Arduino may not be high enough to turn the motor on at its maximum value.

  [1]: https://i.stack.imgur.com/Xlx4X.gif
  [2]: https://i.stack.imgur.com/g9lvC.jpg
  [3]: https://i.stack.imgur.com/bG8u3.gif


sender: user

message:
Connect Arduino Uno to server using oneM2M platform

I have an Arduino Uno that doesn't have any Wi-Fi. After putting the sensor there, I've found out that it is quiet impossible to connect to localhost for oneM2M platform.

Is there any possibility that I can connect to localhost using just the blue cable below which will also being used for uploading the code? Any help will be much appreciated!

[![Sensor on breadboard and Uno][1]][1]

  [1]: https://i.stack.imgur.com/tHsxj.jpg "Sensor on breadboard and Uno"

sender: assistant

body:
You can not do it without a special software running on the computer. I mean special as in someone will need to write it since there likely isn't something available that you can find.

The most practical solution is to either use an ethernet shield on the Uno. Or use a board like the Wemos D1 Mini (an ESP8266 based board) that can do Wifi. It can run under the Arduino platform. And they are dirt cheap.

https://wiki.wemos.cc/products:d1:d1_mini

https://wiki.wemos.cc/doku.php

https://wiki.wemos.cc/products:d1_mini_shields:dht_shield


message:
How to build a wireless pump controller using arduino and esps?

I want to have automatic control for my pump, wirelessly.

A transmitter unit fitted in the water tank would sense the water level and transmit the data to a receiver unit attached to the pump starter to turn it off/on.

Also an override unit would allow me to turn the pump on/off according to my will and will also display the water level.

How do I write the code for the wireless transmission part ?

body:
First of all I would recommend to play around with Web Server example to understand how the server hosting works. Also, the ip adders is assigned randomly to the ESP so you definitely need to write a rule in your WiFi router in order to assign a static ip to the ESP. But you can try to use mDNS to assign a name to your esp. For example http://pump.local/path. You can find some instructions [here][1]. If you are looking for simplicity you can use Blynk. It is a fully automated and free service that allows you to control you ESP from anywhere where there is a internet connection. And it also can display different variables such as the water level in your case.

  [1]: https://techtutorialsx.com/2016/11/20/esp8266-webserver-resolving-an-address-with-mdns/


message:
Triggering a soft reset (Arduino Leonardo)

I want to trigger a soft reset on my Arduino Leonardo, and after some searching settled on using the watchdog timer, as it seemed to be the easiest and cleanest way to do it.

However, I don't think it works as it should. It seems to work fine on the following example:

    #include <avr/wdt.h>

    int outputPin = LED_BUILTIN;

    void setup() {
      MCUSR = 0;
      wdt_disable();
      pinMode(outputPin, OUTPUT);
      digitalWrite(outputPin, HIGH);
      delay(500);
      digitalWrite(outputPin, LOW);
      delay(500);
      digitalWrite(outputPin, HIGH);
      delay(500);
      digitalWrite(outputPin, LOW);
      delay(1000);
    }

    void loop() {
      wdt_enable(WDTO_15MS);
      while (true) {}
    }

The LED blinks continuously,.

But for the following example:

    #include <avr/wdt.h>

    void setup() {
      MCUSR = 0;
      wdt_disable();
      Serial.begin(9600);
      while (!Serial);
      Serial.println("Hello");
    }

    void loop() {
      wdt_enable(WDTO_15MS);
      while (true) {}
    }

"Hello" only gets printed once (where I would expect it to arrive continuously).

I tried increasing the watchdog timeout to 2 seconds, but that didn't solve the issue.

body: So it turns out my code was working correctly, the watchdog performed the reset as it should, the problem was only that I needed to relaunch the serial monitor after each reset.


message:
expected unqualified id before token

here is the code.

PROBLEM:- if I use for the loop the error comes "expected unqualified-id before for .......but if I use the void loop instead of for loop...the code is run without any error. Meanwhile, I needed for loop .

    long int Distance = 0;  // Record the number of steps we've taken
    //LOW LOGIC MOVEMENT BACKWARD and GEARS MOVE clocwise
    // PIN 18 FOR DIRECTIRON
    // PIN 19 FOR STEP  INPUT
    int y= 10^-6;
    long int k;
    long int h= 1600;
    void setup() {
    Serial.begin(9600);
      pinMode(18, OUTPUT);
      pinMode(19, OUTPUT);
      pinMode(14, OUTPUT);
      pinMode(15, OUTPUT);
      digitalWrite(18,LOW);
      digitalWrite(19, LOW);
     digitalWrite(14, LOW);
     digitalWrite(15, LOW);
    }
    for ( k=0; k<=h; k++)
    {
      //if we are at the end of our move
      digitalWrite(19, HIGH);
      delayMicroseconds(100);
      digitalWrite(19, LOW);
      delayMicroseconds(100);
      Distance = Distance + 1;   // record this step
      //k=Distance;
    //   Check to see
      if (Distance ==h)
     {
       // We are! Reverse direction (invert DIR signal)
       if (digitalRead(18) == LOW)
        {
         digitalWrite(18, HIGH);
       }
       else
       {
         digitalWrite(18, LOW);
       }
    //    Reset our distance back to zero since we're
     //   starting a new move
       Distance = 0;
      //   Now pause for half a second
        delay(1000);
      }
      }
    }

body:
You need the `void loop()` function on your sketch. This function gets called directly after the setup. If it's not there, then the program cannot compile. You cannot put any execution code (means code other than declarations and such) outside of a function.

Depending on what exactly you want to achieve, you have 2 options:

 1. If you want the program to only run once and then stop until the next reset, you can put your code inside the `setup()` function and leave the `void loop()` function empty ( with this: `void loop(){ }` ).
 2. If you want the program to repeat itself indefinitely after the for loop, you can put the code inside the `void loop()` function.

Whatever you choose, you need the `void loop()` function.

Note: The `void loop()` function is part of the Arduino world. In general all programs for microcontroller in C/C++ have a function called `main()`. It is the function, that starts the execution of the program. Without it no program would actually run. The Arduino framework wraps this `main()` function up and gives you directly one function to execute the initialization code (`void setup()`) and one function, that runs after that and loops indefinitely (`void loop()`). This infinite loop is an important thing, because the microcontroller has no OS or such that he can return to. If you don't have an infinite loop there, the execution can go on to the next address in the program, where you don't know what it contains.

---

Also the line `int y= 10^-6;` does not, what you might think it does. In C/C++ the `^` is not the power function, but will do a bitwise OR operation. You will have to use a function for this, for example the `pow(value1, value2)` function. You can use google to find one of the many examples, how to use it.

And in the same line, (I assume as above) you want to tell Arduino to put a value much smaller than 1 (a value between 0 and 1) into an integer variable. It will contain `0`. `int` means integer and cannot hold decimal numbers (number with something after the decimal point). It can hold numbers like -1,0,1,2,3 in the range from -32768 to 32767 (because it is 16 bits wide on the Arduino UNO and Mega). You will have to use the `float` type for this.


body:
It looks like you intended the for-loop to run to completion once. If that is correct, just include it and its entire block of code within and at the end of the setup() function. You will still need to provide a loop() function but it can be empty:

    void loop(){
       ;
    }

If, instead, you wanted the for() loop to be run repeatedly, enclose it in the loop() function:

    void loop(){
       for ( k=0; k<=h; k++ )
       {
       ...
       }
    }

The setup() function runs once after a power up or reset. The loop function then gets called repeatedly, forever. Put your functional code in whichever one fits your purpose.

The reason for the error message is that, as you've written the for-loop, it is outside of a function, but executable code (as opposed to defining global variables) is only valid within a function.


message:
How to package a 16 bit integer to send it with serial.write?

I am trying to display the values i get from reading a potentiometer (0-1023) in the program called 'processing'.

when I just use Serial.write(integer) and display the value on a line graph in 'processing' the line will max out at 256 and loop back around to 0 as i vary the potentiometer.

I understand that this is because the serial.write can only write in bytes(8 bits) so I would need to package the 16 bit integer into 2 bytes.

i was considering using a union but as you can probably guess i am very new to arduino so i haven't been able to make that work.

here is the code i have tried:

    union Data{  uint16_t now; } data;

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

    }

    void loop() {   // put your main code here, to run repeatedly:
        uint16_t sensorVal = analogRead(A1);
         union Data data;

        data.now = sensorVal;

        Serial.println(data.now);

        //Serial.write(sensorVal);
        delay(10); }

body:
You need to send the uint16_t as the two the individual bytes it is composed of, one at a time, in whatever order your Arduino code and the code on the PC agree on: (MSB first, aka, big-endian; or LSB first, aka little-endian).

Since it would be possible for the two devices to get out of sync, you may also want to package up the two bytes with a third, or "start-byte". Pick some fixed value (such as 0xCC) that has a couple of its MSbits set, then the MSB, then the LSB. Your receiver can know to look for that fixed value, then the MSB (which it knows can't have those high bits set because the analog data is only 10-bits), then the LSB (which could have any value).

The PC should only accept a three-byte packet when it has received one that fits that scheme. Otherwise it waits for another 0xCC (or whatever value you choose), collects two more bytes, and tries again.


body:
Send the 16-bit value as two 8-bit values (with a start byte as per **JRobert**'s answer):

    Serial.write(0xCC); // Send the start byte
    Serial.write((sensorVal >> 8) & 0xFF); // Send the upper byte first
    Serial.write((sensorVal & 0xFF); // Send the lower byte


body:
I was checking out the documentation for [Serial.write()][1]

  [1]: https://www.arduino.cc/en/Serial/Write

You can sent out an array of 2 8Bits in the form of Serial.write(buf, len)

Simply create an int buffer, and then use your original integer and do bit shifting. Notice the `& 255` used to make sure there are no values beyond 8 bits.

    int data = 1000;
    short int buf[2];
    buf[0] = data & 255;
    buf[1] = (data >> 8)  & 255;
    Serial.write(buf, 4);

Also, in C, the name of an array is used as the pointer for the first element. So if you look at the documentation for `Serial.write(buf,len)` again, you will find that you can probably get the pointer for your int value, and write 2 bytes itself!

    Serial.write(*data, 2);
  or `Serial.write(&data, 2)`


body:
This may help
Transmisor

    int valor;
    byte val;

    void setup() {

    Serial.begin(9600);
    }

    void loop() {

    valor=analogRead(A0);
    val=map(valor,0,1023,0,179);
    Serial.println(val);
    Serial.write(val);
    delay(100);
    }

Receptor

    byte mensaje;
    int valor;
    void setup() {

    Serial.begin(9600);
    }

    void loop() {

    if (Serial.available()){
      mensaje=Serial.read();
      valor=mensaje;
      Serial.print(valor);
      Serial.println(" ");
    }
    }


message:
Sanity check for dual IR LED circuit

If the intent is to drive the two LED's with 200-400mA (using PWM @ 38Hz), is there anything wrong with this solution?

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

Perhaps this is a better solution, as it ensures the current is exactly the same for the two LED's (so that they are not out of phase with each other):

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

  [1]: https://i.stack.imgur.com/uzYzH.png
  [2]: https://i.stack.imgur.com/plVWU.png

body:
I would use a single transistor rated at minimum 1A continuous (a MOSFET by choice), and have both LEDs switched in parallel with their own resistor.  By having them in series as in your second schematic you are limiting the input voltage to a minimum of *2×Vf* which could be as high as 5.2V, and thus more than your power source can provide.

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

This gives the same result as your first circuit, but only uses one transistor for the switching. You can add more LED+Resistor pairs in parallel as you like as long as the total current is below that which the chosen MOSFET can handle.

You should rate the MOSFET to handle the maximum continuous current, not the pulse current, in case the output of the Arduino should be set continuously HIGH instead of sending PWM.

You should also note that the *pulse* current of an LED is usually rated at 1% duty cycle.

Also note that as the voltage of your power source drops, so will the voltage across the resistors, and thus the current flowing through them (and your LEDs) making the LEDs dim.  It may be beneficial to first pass your battery power through a high-efficiency 3.3V switch-mode regulator to keep the voltage stable whilst wasting the minimum amount of power in the regulation.


message:
Controlling LED and Button with single pin

I am trying to use an ATTINY85/Ardunio Uno to turn an LED on and listen to a button input. I don't mind if the LED turns on when the button is used.

I am have found [this thread][1] from a couple of years ago however it doesn't seem to work at low voltage (3V) due ending up with floating pins due to the forward voltage of the LED. I was wondering if anyone had a soltion or if they could check to see if my solution would be suitable.

Many Thanks

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

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

<!-- End schematic -->

  [1]: https://electronics.stackexchange.com/questions/264178/pin-as-both-input-for-a-switch-and-output-for-led-with-atmega32u4

body:
I think this is what you want...

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

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

<!-- End schematic -->

To check for button, set pin to INPUT and enable pullup. If pin is LOW, then the button is pushed.

To light LED, set pin to OUTPUT and LOW.


message:
How to avoid Multiple definition of 'Blynk' error?

By including

     #include <BlynkSimpleEsp8266.h>
Blynk library (https://github.com/blynkkk/blynk-library) from more than 1 module/cpp file, "Multiple definition of `Blynk’" error is thrown at compile time. The header file contains following:

    static WiFiClient _blynkWifiClient;
    static BlynkArduinoClient _blynkTransport(_blynkWifiClient);
    BlynkWifi Blynk(_blynkTransport);

How can I get the Blynk declarations into a second or third module, without multiple definitions error? Editing the header/library file/s is not an option!

By the question in https://stackoverflow.com/questions/48392571 it is still not clear what a working solution is...

body:
The Blynk "simple" header files are not ready to be included into multiple cpp files. They are meant to be included only in the main ino file. The reason is that the variable allocations are in headers file, which is bad practice for  C and C++. The h files should contain only declarations. The right way would have

    extern BlynkWifi Blynk;

and the lines which are now in the h file should go in a cpp file. Then every cpp file that includes the .h will know about the variables but the variables would be allocated only once.

The fix is to change the library or to copy the BlynkSimpleEsp8266.h include to your project as for example MyBlynk.h and change the Blynk variable in MyBlynk.h to `extern` and add a MyBlynk.cpp file with variables allocation

    #include "MyBlynk.h"

    WiFiClient _blynkWifiClient;
    BlynkArduinoClient _blynkTransport(_blynkWifiClient);
    BlynkWifi Blynk(_blynkTransport);


message:
Why do I get “ stray '#' in program ” error?

I am making an Arduino program with SIM800L module and would like to check credit status of the SIM card.
When I manually enter the command: AT+CUSD=1,"*123#" into Serial Monitor, it works fine.

But in the Arduino (1.8.7) I am receiving an error
      ` stray  "#" in program `

when compiling this line of sketch:
      ` SIM800.print("AT+CUSD=1,"*123#"\r"); `

I am not experienced enough to fix this problem.
Could somebody help me, please?

Thank you.
Marko

body:
Use the escape backslash to get a double quote in a text. See: https://en.cppreference.com/w/cpp/language/escape

Is the `*123$` between double quotes?

    Serial.println("Hello");
    Serial.println("I said: Hello to you");
    Serial.println("I said: \"Hello\" to you");
    Serial.println("AT+CUSD=1,\"*123#\"\r");
    Serial.println("AT+CUSD=1,\"*123#\"");

I think the carriage return `\r` at the end is not needed when the `println` is used. The `println` adds a linefeed `\n` by the way.


message:
Make a float using integers

I want to make a floating point number that has only one decimal point.
I have separate integers for both side.
Ex:

`int n1 = 8;`

`int n2 = 2;`

I want to make 8.2 as float value using separate integers.
Please give me a solution.

body:
Seems too simple:

    float x = n1 + n2 * 0.1;

Is there a trick?

**Edit**: The method proposed by Michel Keijzers, namely

    float x = n1 + n2 / 10.0;

(I removed the redundant casts) can be slightly more accurate, but takes
longer to compute, because division is significantly slower than
multiplication on the Uno. Computing `n2/10.0` always yields the
correctly rounded result, namely the float that best approximates the
exact mathematical result. On the other hand, `n2*0.1` involves _two_
rounding operations: one at compile time, in the representation of 0.1
(which is not an exact float), another at run time, which rounds the
result of the multiplication. If `n2` is between 0 and 8, you end up
getting the correctly rounded result anyway, just as with `n2/10.0`.
However, if `n2` is 9, then

* `n2*0.1` yields 0.900000035762786865234375 (error ≈ 3.6e-8)
* `n2/10.0` yields 0.89999997615814208984375 (error ≈ -2.4e-8)

The former carries a rounding error 1.5 larger than the latter.


body:
    float x = (float) n1 + (float) (n2 / 10.0);

This works only if the value of n2 has 1 digit. Otherwise the following make it smaller until n2 gets below 1.0:

    float x = (float) n1;

    float f2 = (float) n2;
    while (f2 >= 1.0)
    {
       f2 /= 10.0;
    }
    x = n1 + f2;


message:
Getting incorrect output from ADC over SPI in Arduino Uno

I am trying to read data from an ADC ADCS7476 [(datasheet)][1] using SPI on Arduino Uno. I am using the following code to read the data from the ADC and printing it on serial monitor. However, the code is always printing 0. I never used SPI before and I am not able to debug the issue, does anyone know where I am going wrong.

I am using the following connections:

1. ADC's SCLK to Pin 13 on Ardunio
2. ADC's SDATA to Pin 12 on Arduino
3. ADC's CS to Pin 10 on Arduino

Code:

    #include <SPI.h>
    #define cs 10

    SPISettings settingsA(250000, MSBFIRST, SPI_MODE0);
    byte highbyte,lowbyte;
    unsigned int data;

    void setup() {
      Serial.begin(9600);
      pinMode(cs, OUTPUT);
      digitalWrite(cs, HIGH);
      delay(1000);
      SPI.begin();
    }

    void loop() {
      SPI.beginTransaction(settingsA);
      digitalWrite(cs, LOW);
      delayMicroseconds(1);
      highbyte = SPI.transfer(0xFF);
      lowbyte = SPI.transfer(0xFF);
      digitalWrite(cs, HIGH);
      delayMicroseconds(1);
      SPI.endTransaction();
      data= ((unsigned int)highbyte << 8 ) + lowbyte;
      Serial.println(data);
      delay(100);
    }

  [1]: https://www.ti.com/lit/ds/symlink/adcs7476.pdf

body:
*I am leaving this answer in case anyone stumbles across this question in the future*

In a super frustrating, anti-climactic end, it turns out that the ADC chip itself was not working properly. I tested the (faulty) chip using the code above and observed the output of data pin on the oscilloscope and the output was the same square wave irrespective of the input. I managed to find a new ADC and I tested it and it was working correctly. But this raises a new issue for me, this is the third ADC chip I tested that was working correctly, the first two were faulty. It is very unlikely that it is a manufacturing issue and I used the same connections and the same code to test all three of them. Maybe it has to something to do with soldering, because AFAIK that's the only thing that's different.  If anyone knows anything else that might have gone wrong, I'm all ears.


message:
How to retain the on state of the LED and buzzer if the sensor is triggered?

I'm working on a project which is likely an earthquake alarm. The sketch that I got from the internet does not retain the "on" state of the indicators(LED and buzzer)when it is triggered. I want to modify the sketch that it makes the LED and buzzer retains their "on" state when the sensor(accelerometer) is triggered. Could someone help me ?

Here is the code:

    #include <Wire.h>
    #include <MPU6050.h>

    #define minval -5
    #define maxval 3

    MPU6050 mpu;

    void setup()
    {
      Serial.begin(115200);
      pinMode(7,OUTPUT);
      pinMode(8,OUTPUT);

      delay (2000);

      // Initialize MPU6050
      Serial.println("Initialize MPU6050");

      while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
      {
        Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
        delay(500);
      }

      mpu.setThreshold(3);
      // Check settings
      checkSettings();
    }

    void checkSettings()
    {
      Serial.println();
      Serial.print(" * Sleep Mode:        ");
      Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");
      Serial.print(" * Clock Source:      ");
      switch(mpu.getClockSource())
      {
        case MPU6050_CLOCK_KEEP_RESET:
          Serial.println("Stops the clock and keeps the timing generator in reset");
          break;
        case MPU6050_CLOCK_EXTERNAL_19MHZ:
          Serial.println("PLL with external 19.2MHz reference");
          break;
        case MPU6050_CLOCK_EXTERNAL_32KHZ:
          Serial.println("PLL with external 32.768kHz reference");
          break;
        case MPU6050_CLOCK_PLL_ZGYRO:
          Serial.println("PLL with Z axis gyroscope reference");
          break;
        case MPU6050_CLOCK_PLL_YGYRO:
          Serial.println("PLL with Y axis gyroscope reference");
          break;
        case MPU6050_CLOCK_PLL_XGYRO:
          Serial.println("PLL with X axis gyroscope reference");
          break;
        case MPU6050_CLOCK_INTERNAL_8MHZ:
          Serial.println("Internal 8MHz oscillator");
          break;
      }

      Serial.print(" * Gyroscope:         ");
      switch(mpu.getScale())
      {
        case MPU6050_SCALE_2000DPS:
          Serial.println("2000 dps");
          break;
        case MPU6050_SCALE_1000DPS:
          Serial.println("1000 dps");
          break;
        case MPU6050_SCALE_500DPS:
           Serial.println("500 dps");
           break;
        case MPU6050_SCALE_250DPS:
           Serial.println("250 dps");
           break;
      }

      Serial.print(" * Gyroscope offsets: ");
      Serial.print(mpu.getGyroOffsetX());
      Serial.print(" / ");
      Serial.print(mpu.getGyroOffsetY());
      Serial.print(" / ");
      Serial.println(mpu.getGyroOffsetZ());
      Serial.println();
    }

    void loop()
    {
      Vector rawGyro = mpu.readRawGyro();
      Vector normGyro = mpu.readNormalizeGyro();
      Serial.print(" Xraw = ");
      Serial.print(rawGyro.XAxis);
      Serial.print(" Yraw = ");
      Serial.print(rawGyro.YAxis);
      Serial.print(" Zraw = ");
      Serial.println(rawGyro.ZAxis);

      if (normGyro.XAxis > maxval ||
          normGyro.XAxis < minval &&
          normGyro.YAxis > maxval ||
          normGyro.YAxis  < minval &&
          normGyro.ZAxis > maxval ||
          normGyro.ZAxis  < minval)
      {
        digitalWrite(7,HIGH);
        digitalWrite(8,HIGH);
        delay(300);
        digitalWrite(7,HIGH);
        digitalWrite(8,HIGH);
        delay(300);
        delay (1000);
      }
      else
      {
        digitalWrite(7,LOW);
        digitalWrite(8,LOW);
      }
      Serial.print(" Xnorm = ");
      Serial.print(normGyro.XAxis);
      Serial.print(" Ynorm = ");
      Serial.print(normGyro.YAxis);
      Serial.print(" Znorm = ");
      Serial.println(normGyro.ZAxis);
      delay(10);
    }

body:
- Define a (boolean: bool) variable, set it to false initially.

- When the sensor is activated, set the variable to true.

- Define something that should be able to disactivate the buzzer/LEDs. And if that happens, set the variable to FALSE. Maybe this is a reset button ?

- Than based on this variable set the buzzer and LEDs on or off.

So you get something like a global variable

    bool alarmTriggered;

In setup:

    alarmTriggered = false;

In loop:

    if (AreSensorsTriggered(...)) // Create your own function
    {
       alarmTriggered = true;
    }
    else if (IsResetButtonPressed(...)) // Create your own function
    {
       alarmTriggered = false;
    }

    SetBuzzer(alarmTriggered); // Create a function that enables/disables buzzer
    SetLEDs(alarmTriggered); // Create a function that enabled/disables LEDs


message:
How to manage variable I2C read lengths requiring address incrementation (Wire/I2C/EEPROM IC emulation)

The question is about how to have information/control of a variable length read for an Arduino acting as a slave device.

The concrete context is that I want to emulate an EEPROM IC.
A byte write to the EEPROM's address sets the internal EEPROM address to start reading from.
The subsequent read from the EEPROM's address, will start returning bytes from that internal address which is incremented for each byte read.

"Wire.onRequest(requestEvent);" allows us to set up a handler, but it seems to be called only once on the start of the read.

In the handler it is possible to provide a reply of multiple bytes.
However I did not find the documentation allowing to know how many bytes were effectively sent to the master.

I got the initial code from [the arduino forum][1] .  I've adapted it to this:

    #include <Wire.h>
    //#define DEBUG
    byte XEEPROM[256] = {
      0x5D, 0x26, 0x31, 0x91, 0x3e, 0x12, 0x8e, 0x70, 0xa5, 0x57, 0x3d, 0xed, 0x91, 0x99, 0xb4, 0x11,
      0x38, 0xde, 0x1b, 0xd6, 0x4c, 0xd9, 0xf5, 0x13, 0x23, 0x94, 0xb8, 0x3d, 0x9c, 0xb0, 0xc4, 0x54,
      0xf0, 0x69, 0xca, 0xb3, 0x28, 0x84, 0xa5, 0xc1, 0x80, 0x53, 0x69, 0x0c, 0x38, 0x4f, 0x0c, 0x74,
      0xa1, 0x5b, 0x8c, 0x71, 0x34, 0x30, 0x38, 0x30, 0x30, 0x38, 0x31, 0x35, 0x33, 0x31, 0x30, 0x35,
      0x00, 0x12, 0x5a, 0x1e, 0xbd, 0x9e, 0x00, 0x00, 0x02, 0x82, 0x30, 0xaa, 0x10, 0xb7, 0x7f, 0x8d,
      0x0a, 0xcb, 0x2e, 0xc1, 0xeb, 0x52, 0x20, 0xdc, 0x00, 0x03, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x97, 0x55, 0x57, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x47, 0x4d, 0x54, 0x00, 0x42, 0x53, 0x54, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x05, 0x00, 0x02, 0x03, 0x05, 0x00, 0x01,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc4, 0xff, 0xff, 0xff,
      0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
      0x68, 0xaa, 0xdd, 0x02, 0x46, 0x45, 0x8f, 0x8f, 0x78, 0x56, 0xbb, 0x69, 0x01, 0x04, 0x46, 0x45,
      0x8f, 0x8f, 0x78, 0x56, 0xbb, 0x69, 0x01, 0x04, 0x46, 0x45, 0x8f, 0x8f, 0x78, 0x56, 0xbb, 0x69,
      0x12, 0x03, 0x46, 0x45, 0x8f, 0x8f, 0x78, 0x56, 0xbb, 0x69, 0x02, 0x02, 0x46, 0x45, 0x8f, 0x8f,
      0x78, 0x56, 0xbb, 0x69, 0x12, 0x02, 0x84, 0x79, 0x80, 0x00, 0x00, 0x00, 0x16, 0x01, 0x00, 0x00
    };
    static volatile byte rQ;

    void setup()
    {
     Wire.begin(0x50);
     Wire.onReceive(receiveEvent);
     Wire.onRequest(requestEvent);
     Serial.begin(115200);
     Serial.println("I2C EEPROM EMULATION\n");
    }

    void loop()
    {
    }

    void requestEvent(){
      //Wire.write(XEEPROM[rQ]); // Just 1
      Wire.write(XEEPROM+rQ,6); /// More than 1
      #ifdef DEBUG
      Serial.print("ADR:");
      Serial.print(rQ,HEX);
      Serial.print("R:");
      Serial.print(XEEPROM[rQ],HEX);  // print the character
      Serial.println();
      #endif
      rQ++; // Increment should depend on number of reads - not sure how to detect that.
    }

    void receiveEvent(int iData){
        rQ = Wire.read();
        Serial.print("ADR:");
        Serial.print(rQ,HEX);
        bool dwHeader=false;
        // loop through all but the last
        while(1 < Wire.available())
        {
          if(!dwHeader) {
              dwHeader=true;
              Serial.print("DATAW:");
          }
          XEEPROM[rQ]=Wire.read();;
          Serial.print(XEEPROM[rQ],HEX);  // print the character
        }
        Serial.println(); // new line
    }

The question is about requestEvent and specifically:

    void requestEvent(){
      //Wire.write(XEEPROM[rQ]); // Just 1
      Wire.write(XEEPROM+rQ,6); /// More than 1
      rQ++; // Increment should depend on number of reads - not sure how to
    }

I would like to send one at a time, or at least be able to increment rQ according to the number of bytes effectively sent.

If you want to look at a datasheet, you can look at the [AT24C02 datasheet][2].
With regards to the incrementing internal EEPROM address, the EEPROM specification says:

> **CURRENT ADDRESS READ**: The internal data word address counter maintains
> the last address accessed during the last read or write operation,
> incremented by one. This address stays valid between operations as
> long as the chip power is maintained. The address “roll over” during
> read is from the last byte of the last memory page to the first byte
> of the first page. The address “roll over” during write is from the
> last byte of the current page to the first byte of the same page.

This is why the Arduino code emulating the EEPROM should know exactly how many bytes were read.

Thanks.

  [1]: http://forum.arduino.cc/index.php?topic=17897.0
  [2]: http://ww1.microchip.com/downloads/en/devicedoc/doc0180.pdf

body:
This is exactly what I stumbled upon when trying to create a I2C slave with a memory-based interface.

You are right, the `requestEvent` callback is called only once. So you have to prepare it beforehand. What is positive, however, is that the `write` function will discard all the unused bytes.

So, what can you do? Well, first of all a sum up of the I2C "messages". You, as a master, can

- Send a "write" command, with a payload
- Send a "read" command, with no payload, and the slave will reply with bytes as long as you continue to send ACKs

In my mind there were two different approaches:

 - The "write" command should contain the initial register and the number of registers to read; this approach, however, complicates distinguishing between a "read from EEPROM" and "write to EEPROM" commands
 - The write command should send only the initial register for reading from EEPROM, and the initial register + content to be written for writing to EEPROM.

In my project I chose the second approach. For this reason, when the master writes something on the I2C bus, the first byte of the payload is the register number, and then if there is no other data the slave prepares for sending the contents of the register and the next ones, while if there is any data this is treated as a write command.

The only problem with this approach is that the slave has to prepare a buffer, and the buffer size limits the maximum number of registers returned. I set this limit to 8 in my code; if the master asks for more than only 0s are returned.

Here is the library I wrote for this project.

File I2CInterface.h:

    #ifndef I2CINTERFACE_H
    #define I2CINTERFACE_H

    #include <stdint.h>

    class I2CInterface
    {
      public:
        static I2CInterface instance;

      public:
        void start();

      private:
        I2CInterface();

        static void requestEvent();
        static void receiveEvent(int howMany);
        void resetSendingBuffer();

      private:
        static const uint8_t Address = 0x46;

        static const uint8_t MaxBufferLength = 8; // (max) 8 byte
        uint8_t sendingBuffer[MaxBufferLength];
    };

    #endif // I2CINTERFACE_H

File I2CInterface.cpp

    #include <Arduino.h>
    #include <Wire.h>
    #include "I2CInterface.h"

    I2CInterface I2CInterface::instance;

    I2CInterface::I2CInterface()
    {

    }

    void I2CInterface::start()
    {
      Wire.begin(Address);
      Wire.onRequest(requestEvent);
      Wire.onReceive(receiveEvent);
      resetSendingBuffer();
    }

    void I2CInterface::requestEvent()
    {
      Wire.write(instance.sendingBuffer, MaxBufferLength);
      instance.resetSendingBuffer();
    }

    void I2CInterface::receiveEvent(int howMany)
    {
      if (howMany <= 0)
        return;
      else if (howMany == 1)
      { // Reading request
        uint8_t regist = Wire.read();
        for (uint8_t i = 0; i < MaxBufferLength; i++)
          instance.sendingBuffer[i] = Configuration.getRegister(regist++);
      }
      else
      { // Writing request
        uint8_t regist = Wire.read();
        while (Wire.available())
        {
          Configuration.setRegister(regist++, Wire.read());
        }
        instance.resetSendingBuffer();
      }
    }

    void I2CInterface::resetSendingBuffer()
    {
      for (uint8_t i = 0; i < MaxBufferLength; i++)
        sendingBuffer[i] = 0x00;
    }

Please note that the `Configuration.getRegister` and `Configuration.setRegister` are the functions I used to get and set some registers; you can substitute them with a direct EEPROM access or your own functions.

You just need to add, in your main file,

    #include "I2CInterface.h"
    ...

    void setup()
    {
      ...
      I2CInterface::instance.start();
      ...
    }


body:
Note, that I haven't tested the code below, since I currently don't have enough time for it. But it may help you to get, what you want to do.

The way the I2C interface works is, that after each byte read from the slave, the master will answer with ACK or NACK, depending on if he wants to read more data or not. So the slave doesn't know beforehand, how many bytes the master wants to read.

But you can change the `Wire` library, to call the `onRequest` callback for every single byte, instead of every request. The important code lies in the path of your Arduino installation at `hardware/arduino/avr/libraries/Wire/src/utility/twi.c` at line 575 (I refer to my installation of version 1.8.5; might be slightly different for you):

    case TW_ST_SLA_ACK:          // addressed, returned ack
    case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack
          // enter slave transmitter mode
          twi_state = TWI_STX;
          // ready the tx buffer index for iteration
          twi_txBufferIndex = 0;
          // set tx buffer length to be zero, to verify if user changes it
          twi_txBufferLength = 0;
          // request for txBuffer to be filled and length to be set
          // note: user must call twi_transmit(bytes, length) to do this
          twi_onSlaveTransmit();
          // if they didn't change buffer & length, initialize it
          if(0 == twi_txBufferLength){
            twi_txBufferLength = 1;
            twi_txBuffer[0] = 0x00;
          }
          // transmit first byte from buffer, fall
    case TW_ST_DATA_ACK: // byte sent, ack returned
          // copy data to output register
          TWDR = twi_txBuffer[twi_txBufferIndex++];
          // if there is more to send, ack, otherwise nack
          if(twi_txBufferIndex < twi_txBufferLength){
            twi_reply(1);
          }else{
            twi_reply(0);
          }
          break;

When receiving a request with correct address, the first `case` will be executed (of course after other stuff with receiving address and sending ACK). The `twi_onSlaveTransmit()` function will execute the `onRequest` callback. When that is done, the code falls directly into the next `case` statement, which sends the first byte. When the slave receives an ACK after that byte, it should come back to this `case` and send another byte.

We can now put the buffer filling code into the second `case` statement, so that the callback will be executed for every requested byte. In this case we also need to change the `if` statement after that, so that it only triggers and sends NACK, if the user didn't write a byte in the callback. The original library seems to write at minimum 1 byte (even it nothing is in the buffer; it is set to zero). So we will also do this by setting a flag in the first `case` statement. The code now looks like this:

    case TW_ST_SLA_ACK:          // addressed, returned ack
    case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack
          // enter slave transmitter mode
          twi_state = TWI_STX;
          twi_slave_transmit_first_byte = 1;
          // transmit first byte from buffer, fall
    case TW_ST_DATA_ACK: // byte sent, ack returned
          // ready the tx buffer index for iteration
          twi_txBufferIndex = 0;
          // set tx buffer length to be zero, to verify if user changes it
          twi_txBufferLength = 0;
          // request for txBuffer to be filled and length to be set
          // note: user must call twi_transmit(bytes, length) to do this
          twi_onSlaveTransmit();
          if(twi_slave_transmit_first_byte == 1){
              twi_slave_transmit_first_byte = 0;
              // if they didn't change buffer & length, initialize it
              if(0 == twi_txBufferLength){
                twi_txBufferLength = 1;
                twi_txBuffer[0] = 0x00;
              }
          }
          // copy data to output register
          TWDR = twi_txBuffer[twi_txBufferIndex++];
          // if there is more to send, ack, otherwise nack
          if(twi_txBufferIndex < twi_txBufferLength){
            twi_reply(1);
          }else{
            twi_reply(0);
          }
          break;

And we have to add the flag declaration at the top of the file (where all the other static volatile variables are defined) as static volatile:

    static volatile uint8_t twi_slave_transmit_first_byte = 0;

In the `onRequest` callback you can now write a single byte to the buffer and incrementing your counter.

---

I think, that should work. If someone knows better, please correct me.


message:
How to define and use a list/array of chars using `Serial.print`

I wish to define a list of months names and access it when printing a report.

Array was defined as follows:

`const char months []=
{'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'};`

    for (int i=0; i<=11; i++) {

                                     Serial.print(months[i]);
                            }

**Tries:**

I was looking for help under `Arrays` in Arduino documentation didn't give, as far as I found, any explanation for such case, but arrays of `int`

Appreciate any help.

body:
You are almost there:

- Use a char* instead of char, a char can only contain one character
- Use " instead of ' (Thanks Juraj)

Then you get:

    const char* months[] =
     {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};


message:
LED intensity on digital pins

I am using an Arduino UNO.

On any digital/analog pin, if an LED (with resistor) is connected and we use digitalWrite(pin,HIGH) the LED lights up rather dimly.

On the other hand, if we use pinMode(pin,OUTPUT) and then use digitalWrite, the LED lights up to maximum intensity.

I checked that in both cases, the voltage on the pin is 5V. Any explanation for this ? Thanks.

body:
This is due to a specific feature of the AVR microcontrollers, where the
same register (`PORTB`, `PORTC` or `PORTD`) is used for controlling both
the output value of the pin and its optional internal pullup resistor.
The command `digitalWrite(pin,HIGH)` sets to 1 the bit of this register
corresponding to the selected pin.

- If the pin is set to `INPUT` (which is the default), the effect of
  `digitalWrite(pin,HIGH)` is to turn on the internal pullup.

- If the pin is set to `OUTPUT`, the same command sets the output to
  `HIGH`.

The internal pullup is about 30 kΩ, which lets flow a very small
current through the LED. You may notice that the voltage at the pin is
5 V if nothing is connected to it, but significantly less when the
LED is connected. Notice also that the preferred way of enabling the
pullup is `pinMode(pin,INPUT_PULLUP)`.


message:
Can I operate an arduino that has a file uploaded on it, without having the file myself?

I've been a massive idiot and accidentally deleted the sketch I need for a project at university, and I didn't create any backups. The sketch is already uploaded into the arduino, which operates using the serial monitor; when "1" is entered it does one thing, when "2" is entered it does another thing and so on. My question is: can I still use the serial monitor to operate the arduino without having the original sketch?

Any help would be appreciated, thank you.

body:
Of course you can. The serial monitor has nothing to do with the sketch - it's just a very primitive serial interface program.

You don't even need the serial monitor. You can use any serial interface program ("terminal emulator") such as Teraterm, Putty, Hyperterminal, etc.


message:
Is there something wrong in my sketch?

I've been working on a project that need two sensors(mq2 and mpu6050), I got each sketches from the internet and I managed to work the mq2 but for the mpu6050, I'm still not sure if its working. The thing is I want the two sensors to work on their own but in one sketch. When the mq2 senses some gas, I want the LED and BUZZER turned on and the only way to turn it off is by resetting the arduino. For the MPU6050, it's the same with the mq2, when the MP6050 is triggered, I want the other LED and the same buzzer turn on, again the only way to turn it off is by resetting the arduino. I want to combine the se two skectches in one. But when I combined it, the circuit won't work. Could someone help me ?

Here is the code that I modified and combined:

    #include <Wire.h>
    #include <MPU6050.h>

    #define minval -5
    #define maxval 3

    MPU6050 mpu;
    //////////////////////////////////////////////////////////////////

    //for mq2

    int redLed = 12;
    int greenLed = 11;
    int buzzer = 10;
    int smokeA0 = A5;
    // Your threshold value
    int sensorThres = 100;

    //////////////////////////////////////////////////////////////////

    void setup(){
      pinMode(redLed, OUTPUT);
      pinMode(greenLed, OUTPUT);
      pinMode(buzzer, OUTPUT);
      pinMode(smokeA0, INPUT);
      pinMode(7,OUTPUT);
      pinMode(8,OUTPUT);
      mpu.setThreshold(3);
    }

    //////////////////////////////////////////////////////////////////

    void loop(){
      // for mq2

      int analogSensor = analogRead(smokeA0);

      // Checks if it has reached the threshold value
      if (analogSensor > sensorThres)
      {
        digitalWrite(redLed, HIGH);
        digitalWrite(greenLed, LOW);
        tone(buzzer, 1000);
      }
      else{
      digitalWrite(greenLed, HIGH);
      }
      // for MPU6050

      Vector rawGyro = mpu.readRawGyro();
      Vector normGyro = mpu.readNormalizeGyro();
      if (normGyro.XAxis > maxval ||
          normGyro.XAxis < minval &&
          normGyro.YAxis > maxval ||
          normGyro.YAxis  < minval &&
          normGyro.ZAxis > maxval ||
          normGyro.ZAxis  < minval)
      {
        digitalWrite(7,HIGH);
        digitalWrite(8,HIGH);
      }
      else
      {
        digitalWrite(7,LOW);
        digitalWrite(8,LOW);
      }

    }

Here is the code for the mq2:

    int redLed = 12;
    int greenLed = 11;
    int buzzer = 10;
    int smokeA0 = A5;
    // Your threshold value
    int sensorThres = 150;

    void setup() {
      pinMode(redLed, OUTPUT);
      pinMode(greenLed, OUTPUT);
      pinMode(buzzer, OUTPUT);
      pinMode(smokeA0, INPUT);
    }

    void loop() {
      int analogSensor = analogRead(smokeA0);

      // Checks if it has reached the threshold value
      if (analogSensor > sensorThres)
      {
        digitalWrite(redLed, HIGH);
        digitalWrite(greenLed, LOW);
        tone(buzzer, 1000);
      }
      else{
      digitalWrite(greenLed, HIGH);
      delay(100);
      }
    }

Here is the code for the MPU6050(I removed some lines when I put it at the combined sketch because I dont need the LCD code, dunno if I did it correct):

    #include <Wire.h>
    #include <MPU6050.h>

    #define minval -5
    #define maxval 3

    MPU6050 mpu;

    void setup()
    {
      Serial.begin(115200);
      pinMode(7,OUTPUT);
      pinMode(8,OUTPUT);

      delay (2000);

      // Initialize MPU6050
      Serial.println("Initialize MPU6050");

      while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
      {
        Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
        delay(500);
      }

      mpu.setThreshold(3);
      // Check settings
      checkSettings();
    }

    void checkSettings()
    {
      Serial.println();
      Serial.print(" * Sleep Mode:        ");
      Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");
      Serial.print(" * Clock Source:      ");
      switch(mpu.getClockSource())
      {
        case MPU6050_CLOCK_KEEP_RESET:
          Serial.println("Stops the clock and keeps the timing generator in reset");
          break;
        case MPU6050_CLOCK_EXTERNAL_19MHZ:
          Serial.println("PLL with external 19.2MHz reference");
          break;
        case MPU6050_CLOCK_EXTERNAL_32KHZ:
          Serial.println("PLL with external 32.768kHz reference");
          break;
        case MPU6050_CLOCK_PLL_ZGYRO:
          Serial.println("PLL with Z axis gyroscope reference");
          break;
        case MPU6050_CLOCK_PLL_YGYRO:
          Serial.println("PLL with Y axis gyroscope reference");
          break;
        case MPU6050_CLOCK_PLL_XGYRO:
          Serial.println("PLL with X axis gyroscope reference");
          break;
        case MPU6050_CLOCK_INTERNAL_8MHZ:
          Serial.println("Internal 8MHz oscillator");
          break;
      }

      Serial.print(" * Gyroscope:         ");
      switch(mpu.getScale())
      {
        case MPU6050_SCALE_2000DPS:
          Serial.println("2000 dps");
          break;
        case MPU6050_SCALE_1000DPS:
          Serial.println("1000 dps");
          break;
        case MPU6050_SCALE_500DPS:
           Serial.println("500 dps");
           break;
        case MPU6050_SCALE_250DPS:
           Serial.println("250 dps");
           break;
      }

      Serial.print(" * Gyroscope offsets: ");
      Serial.print(mpu.getGyroOffsetX());
      Serial.print(" / ");
      Serial.print(mpu.getGyroOffsetY());
      Serial.print(" / ");
      Serial.println(mpu.getGyroOffsetZ());
      Serial.println();
    }

    void loop()
    {
      Vector rawGyro = mpu.readRawGyro();
      Vector normGyro = mpu.readNormalizeGyro();
      Serial.print(" Xraw = ");
      Serial.print(rawGyro.XAxis);
      Serial.print(" Yraw = ");
      Serial.print(rawGyro.YAxis);
      Serial.print(" Zraw = ");
      Serial.println(rawGyro.ZAxis);

      if (normGyro.XAxis > maxval ||
          normGyro.XAxis < minval &&
          normGyro.YAxis > maxval ||
          normGyro.YAxis  < minval &&
          normGyro.ZAxis > maxval ||
          normGyro.ZAxis  < minval)
      {
        digitalWrite(7,HIGH);
        digitalWrite(8,HIGH);
        delay(300);
        digitalWrite(7,HIGH);
        digitalWrite(8,HIGH);
        delay(300);
        delay (1000);
      }
      else
      {
        digitalWrite(7,LOW);
        digitalWrite(8,LOW);
      }
      Serial.print(" Xnorm = ");
      Serial.print(normGyro.XAxis);
      Serial.print(" Ynorm = ");
      Serial.print(normGyro.YAxis);
      Serial.print(" Znorm = ");
      Serial.println(normGyro.ZAxis);
      delay(10);
    }

body:
The Arduino Uno has the special functions on fixed pins.
The I2C bus, for example, uses pin A4 and A5.

In the [Arduino Wire reference page][1] is a table of the pin numbers for the Arduino boards.

The pins called "SDA" and "SCL" near the USB connector are connected to the pins "A4" and "A5" (for an Arduino Uno).
That means that if you use the I2C bus, you may not use pin "A4" and "A5" for something else.

Connect the MQ2 gas sensor to pin A0, A1, A2 or A3, and it should work.

The MPU-6050 is an old sensor, there are newer and better sensors with less noise.
The MPU-6050 is a 3.3V sensor, that means its power should be 3.3V and the I2C bus should have 3.3V levels.
The Arduino Uno has a microcontroller that runs at 5V, and therefor it has a I2C bus with 5V levels.
A I2C level shifter can be used to connect the Arduino Uno with the MPU-6050. You can also use 4k7 pullup resistors from SDA to 3.3V and from SCL to 3.3V. Those pullup resistors are often already on the MPU-6050 module.

The MPU-6050 will work (for some time) with a I2C bus that has 5V levels, it might even work when the MPU-6050 is powered with 5V directly to the chip. That will influence the data, and the sensor might get damaged. Newer 3.3V sensor chips are often faster damaged with 5V, but don't push your luck with the MPU-6050.

  [1]: https://www.arduino.cc/en/Reference/Wire


message:
How to stop a linear actuator?

I wrote code but the motor does not stop, it keeps moving.
Can anyone send code so that I can stop the motor after my code shown below?

    const int forwards = 7;
    const int backwards = 6;//assign relay INx pin to arduino pin

    void setup() {
      pinMode(forwards, OUTPUT);//set relay as an output
      pinMode(backwards, OUTPUT);//set relay as an output
    }

    void loop() {
     digitalWrite(forwards, LOW);
     digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
     delay(20000); // wait 2 seconds

     digitalWrite(forwards, HIGH);
     digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
     delay(2000);// wait 2 seconds

     digitalWrite(forwards, HIGH);
     digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
     delay(20000);// wait 2 seconds

     digitalWrite(forwards, HIGH);
     digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
     delay(2000);// wait 2 seconds
    }

body:
There's multiple things you can do.  Here's some examples.

1: Move code out of `loop()` and into` setup()`:

    const int forwards = 7;
    const int backwards = 6;//assign relay INx pin to arduino pin

    void setup() {
        pinMode(forwards, OUTPUT);//set relay as an output
        pinMode(backwards, OUTPUT);//set relay as an output

        digitalWrite(forwards, LOW);
        digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
        delay(20000); // wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
        delay(2000);// wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
        delay(20000);// wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
        delay(2000);// wait 2 seconds
    }

    void loop() {
    }

2: Stop `loop()` from looping:

    const int forwards = 7;
    const int backwards = 6;//assign relay INx pin to arduino pin

    void setup() {
        pinMode(forwards, OUTPUT);//set relay as an output
        pinMode(backwards, OUTPUT);//set relay as an output
    }

    void loop() {

        digitalWrite(forwards, LOW);
        digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
        delay(20000); // wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
        delay(2000);// wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
        delay(20000);// wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
        delay(2000);// wait 2 seconds

        while (1); // Stop here and do nothing forever
    }

3: Set a "I have done it" flag:

    const int forwards = 7;
    const int backwards = 6;//assign relay INx pin to arduino pin
    bool complete = false;

    void setup() {
        pinMode(forwards, OUTPUT);//set relay as an output
        pinMode(backwards, OUTPUT);//set relay as an output
    }

    void loop() {
        if (!complete) {
            digitalWrite(forwards, LOW);
            digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
            delay(20000); // wait 2 seconds

            digitalWrite(forwards, HIGH);
            digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
            delay(2000);// wait 2 seconds

            digitalWrite(forwards, HIGH);
            digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
            delay(20000);// wait 2 seconds

            digitalWrite(forwards, HIGH);
            digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
            delay(2000);// wait 2 seconds

            complete = true;
        }
    }

Each has benefits and drawbacks. Which is right for you depends on what you are actually trying to achieve.


message:
ESP32 stops looping after 2 loops

My code: https://pastebin.com/UmdK33U2

I made a menu so I can send commands. First I connect to the wifi and then I send the command to send a request.

Then when it detects the key datos(); goes true, so the loop detects that and it starts sending requests.
After 2 requests it just doesnt continue.

What I can do?

Btw im using a ESP32.

Thank you!

    boolean datos = false;

    #include <WiFi.h>
    #include <HTTPClient.h>

    const char* ssid = "ssid";
    const char* password = "pass";

    //removed the password and ssid for security, it was there before.
    void setup() {
      pinMode(2, OUTPUT);
      Serial.begin(115200);

      while (!Serial)
        ;
      Serial.println("===================================================");
      Serial.println("Welcome to the menu, choose what do you want to do:");
      Serial.println("1º Connect to the Wifi | W");
      Serial.println("2º Scan Wifi | S");
      Serial.println("3º Send data to Website | D");
      Serial.println("===================================================");
      Serial.println("Made by Francine and Javi.");
      Serial.println("===================================================");
    }

    void scanwifi() {
      int n = WiFi.scanNetworks();
      Serial.println("===================================================");
      Serial.println("Scan have been finished.");
      Serial.println("===================================================");
      if (n == 0) {
        Serial.println("===================================================");
        Serial.println("No networks have been found.");
        Serial.println("===================================================");
      } else {
        Serial.print(n); // imprimir en el puerto serial el # de redes encontradas
        Serial.println(" networks have been found.");
        for (int i = 0; i < n; ++i) {
          // SSID: Nombre de la red; RSSI: Potencia de la red en dBm
          Serial.print(i + 1); //iniciamos en la red # 1...
          Serial.print(": ");
          Serial.print(WiFi.SSID(i)); //Imprime el nombre de la red
          Serial.print(" (");
          Serial.print(WiFi.RSSI(i)); //Imprime la potencia de la señal en dBm
          Serial.print(")");
          byte encryption = WiFi.encryptionType(i); // en la variable encryption, guardamos el tipo de encriptación de la red
          Serial.print(" Encryption Type: ");
          Serial.println(encryption, HEX); // imprimimos el tipo de encriptación: 2: WPA, 5: WEP, etc.
          delay(10);
        }
      }
    }

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

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);

        Serial.println("Connecting to WiFi..");
      }

      Serial.println("Connected to the WiFi network");
      delay(1000);
      setup();
    }

    void loop() {
      if (Serial.available()) {
        char ch = Serial.read();
        if (ch == 'w' || ch == 'W') {
          conectarsealwifi();
        }
        if (ch == 'S' || ch == 's') {
          scanwifi();
        }
        if (ch == 'd' || ch == 'D') {
          datos = true;
          Serial.println(datos);
        }
        if (datos == true) { // si esta habilitado el sending de datos haz
          //randomN = random(200);
          if (WiFi.status() == WL_CONNECTED) {
            digitalWrite(2, HIGH);
            HTTPClient http;

            http.begin("removedtheurl"); //Specify the URL
            int httpCode = http.GET();                            //Make the request

            if (httpCode > 0) { //Check for the returning code

              String payload = http.getString();
              Serial.println(httpCode);
              Serial.println(payload);
              Serial.println("===================================================");

            } else {
              Serial.println(
                  "Error on HTTP request, reminder maybe its cloudflare shit.");
            }
            http.end(); //Free the resources
            digitalWrite(2, LOW);
          }
          delay(2000);

        } else {

        }
      }
    }

body: You send from Serial Monitor a character followed by a new line character. This two characters are available. Nothing more to enter the `if (Serial.available()) {` block.


message:
Ultrasonic sensor showing weird reading

When i run a test code in Newping library for ultrasonic sensor SR04 then in works properly but when i run the actual code for obstacle avoiding robot then it shows 0 cm everytime. This means that wiring is correct but there is something wrong in my code below

    #include <NewPing.h>
    #include <AFMotor.h> //import your motor shield library

    #define TRIGGER_PIN  12
    #define ECHO_PIN     11
    #define MAX_DISTANCE 200

    NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

    AF_DCMotor motor1(1, MOTOR12_64KHZ); // set up motors.
    AF_DCMotor motor2(2, MOTOR12_8KHZ);

    int distance;

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

    void loop() {
      delay(50);
      distance = sonar.ping_cm(); // start the scan
      delay(20);
      if (distance < 2) {
       Serial.println("Close Obstacle detected!" );
       Serial.println("Obstacle Details:");
       Serial.print("Distance From Robot is " );
       Serial.print(distance);
       Serial.print( " CM!");// print out the distance in centimeters.
       delay(10);
       Serial.println (" The obstacle is declared a threat due to close distance. ");
       Serial.println (" Turning !");
       motor1.run(FORWARD);  // Turn as long as there's an obstacle ahead.
       motor2.run(BACKWARD);

    }
      else {
       Serial.println("No obstacle detected. going forward");
       delay(15);
       motor1.run(FORWARD); //if there's no obstacle ahead, Go Forward!
       motor2.run(FORWARD);
      }
    }

Test code for sensor which worked:-

    #include <NewPing.h>

    #define TRIGGER_PIN  12
    #define ECHO_PIN     11
    #define MAX_DISTANCE 200

    NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

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

    void loop() {
      delay(50);
      Serial.print("Ping: ");
      Serial.print(sonar.ping_cm());
      Serial.println("cm");
    }

Tell me whats wrong here

[![motor shield used is from dk electronics][2]][2]

Motor Shield used below
  [1]: https://i.stack.imgur.com/58p5A.jpg
  [2]: https://i.stack.imgur.com/dYXiE.jpg

Wiring of sensor is connected to Arduino below the shield

body:
Try with

    unsigned int distance;

Instead of

    int distance;

It could also be the motor shield that is using the same pins as your ultrasonic sensor.


message:
SD Card Read/Write Arduino Mega Fail

I have an Arduino Mega 2560 where I have used a MicroSD Card Module to Read/Write Data on the Micro SD Card.
I have tried using the Example in the Arduino IDE but the data is not being written or read by Arduino to the SD Card Module. The connections with the module is exactly how it is described in the Sketch.
I have attached pictures of the Connection and the module I use for the same.

The Example sketch for the SD Card Read/Write is also attached.

If there is a problem that you can notice, please let me know what the problem is and if it can be solved.

Thank you in advance.

    /*
    SD card read/write

    This example shows how to read and write data to and from an SD card file
    The circuit:
    * SD card attached to SPI bus as follows:
    ** MOSI - pin 11
    ** MISO - pin 12
    ** CLK - pin 13
    ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN)

    created   Nov 2010
    by David A. Mellis
    modified 9 Apr 2012
    by Tom Igoe

    This example code is in the public domain.

    */

    #include <SPI.h>
    #include <SD.h>

     File myFile;

     void setup() {
     // Open serial communications and wait for port to open:
      Serial.begin(9600);
         while (!Serial) {
            ; // wait for serial port to connect. Needed for native USB port only
          }

     Serial.print("Initializing SD card...");

     if (!SD.begin(4)) {
     Serial.println("initialization failed!");
     return;
      }

      Serial.println("initialization done.");

      // open the file. note that only one file can be open at a time,
      // so you have to close this one before opening another.
       myFile = SD.open("test.txt", FILE_WRITE);

      // if the file opened okay, write to it:
        if (myFile) {
        Serial.print("Writing to test.txt...");
        myFile.println("testing 1, 2, 3.");
        // close the file:
        myFile.close();
        Serial.println("done.");
         } else {
         // if the file didn't open, print an error:
         Serial.println("error opening test.txt");
       }

        // re-open the file for reading:
      myFile = SD.open("test.txt");
      if (myFile) {
       Serial.println("test.txt:");

        // read from the file until there's nothing else in it:
         while (myFile.available()) {
         Serial.write(myFile.read());
         }
        // close the file:
        myFile.close();
         } else {
        // if the file didn't open, print an error:
        Serial.println("error opening test.txt");
         }
        }

        void loop() {
       // nothing happens after setup
         }

[Connection with Arduino][1]
[SD Card Module][2]

  [1]: https://i.stack.imgur.com/KGxBb.jpg
  [2]: https://i.stack.imgur.com/pdxIo.jpg

body: The SPI wiring described in the SD card example sketch is for Uno. On Mega the SPI pins are 50 MISO, 51 MOSI and 52 CLK.


message:
strtok keep original char

I want to make a vocab program for an arduino. The vocabs are saved in a char array seperated with an '/'. Now I want to split a random picked char and split it at the '/' so I can save it into two variables. But if I do it with strtok the original string gets sacrificed. If now the same vocab comes again...

I hope you can help me, but if you think a other way to do it would be better I'm open for suggestions.
Here's my code

    long random1, random2, random3, random4;
    int lengtharray = 5;
    char* vocab1;
    char* vocab2;
    char* vocab3;
    char* vocab4;
    char* german1;
    char* english1;
    char vocabs[5][16] = {"Apfel/apple","er/he","Zoo/zoo","sie/she","Hallo/hello"};

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

    void loop() {
    randomSeed(analogRead(0));
    random1 = random(0,lengtharray);
    randomSeed(analogRead(0));
    random2 = random(0,lengtharray);
    while(random2 == random1){
        randomSeed(analogRead(0));
        random2 = random(0,lengtharray);
    }
    randomSeed(analogRead(0));
    random3 = random(0,lengtharray);
    while(random3 == random1 || random3 == random2){
        randomSeed(analogRead(0));
        random3 = random(0,lengtharray);
    }
    randomSeed(analogRead(0));
    random4 = random(0,lengtharray);
    while(random4 == random1 || random4 == random2 || random4 == random3){
        randomSeed(analogRead(0));
        random4 = random(0,lengtharray);
    }

    vocab1 = vocabs[random1];
    vocab2 = vocabs[random2];
    vocab3 = vocabs[random3];
    vocab4 = vocabs[random4];

    Serial.println(vocab1);
    Serial.println(vocab2);
    Serial.println(vocab3);
    Serial.println(vocab4);
    Serial.println("//");
    delay(1000);

    german1 = strtok(vocab1,"/");
    english1 = strtok(NULL,"/");
    Serial.println(german1);
    Serial.println(english1);
    }

body: Make a buffer large enough to hold the largest of the word-pairs. Copy the selected pair into the buffer and run strtok() in that buffer. Strtok will damage the buffer contents but that is a throw-away; the original word-pair string is still unchanged.


body:
Personally I would take a completely different tack. I'd store the word pairs as separate items within a struct:

    struct wordpair {
        const char *german;
        const char *english;
    };

    struct wordpair pairs[] = {
        { "Apfel", "apple" },
        { "er", "he" },
        { "Zoo", "zoo" },
        { "sie", "she" },
        { "Hallo", "hello" },
    };

    #define NWORDS (sizeof(pairs) / sizeof(pairs[0]))

Now you have instant access to the words.  For example:

    pairs[3].german

is `"sie"`, and

    pairs[3].english

is `"she"`.

You don't need to waste time splitting words up, since they are already split up.  You don't need to worry about words getting corrupted, because you're never writing anything to the words.  Indeed, if you tried to, because they are tagged as `const`, the compiler should complain.

So:

    struct wordpair *vocab1 = &pairs[random1];

    Serial.println(vocab1->german);

The macro `NWORDS` gives you the size of the array for easy reference.


message:
Initialize and read from a PROGMEM array of pointers to PROGMEM arrays

I'm working on a project for the arduino uno for which I need multiple constant arrays of bytes. Such an array is initialized like so:

    const byte charR[] PROGMEM = {
      B01111111,//top half
      B01111111,
      B01000100,
      B01000110,
      B01101111,
      B00111001,
      B00000000,
      B01111000,//bottom half
      B01111000,
      B00000000,
      B00000000,
      B01111000,
      B01111000,
      B00000000
    };
This array represents the capital letter R. I read the nth byte of this array like so:

    nth_byte = pgm_read_word(charR+n);
This is all fine and good so far, but now I need to take it a step further. I need to create the array message[]. I need to use message[] to read byte arrays in a certain sequence. For instance:

    message[] = {
      charR,
      chare,
      charp,
      charl,
      chary,
      charspace,
      charp,
      charl,
      chare,
      chara,
      chars,
      chare
    };
Each entry in message[] refers to a byte array that represents a character. Notice how multiples appear. This is kind of like a 2-D array, but I want to save progmem by only defining each character once.

How do I properly initialize message[]? Will I need to use pointers for this? How do I properly get the array size or yth byte of the xth entry in message[]?

body:
`const byte* const message[] PROGMEM =`

to use an item, load it in RAM

`strcpy_P(buffer, (byte*)pgm_read_word(&(message[i])));`

source [Arduino reference - PROGMEM][1]

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


message:
LB1847 stepper controller :how to connect to grbl atmega based board with step ,direction,enable , limit?

I like to use an LB1847 chip with stepper motor "both salvaged from old copier". I made a GRBL AtMega board, this board gives step, direction, enable and limit leads.

So I tried to find the corresponding pins on the LB1847, but the data sheet only shows enable1 and enable2 pins and phase1 and phase2 pins?

So how can I connect the step and direction and enable pins of AtMega to these pins of LB1847?

There are other logic pins on LB1847 chip to control current and decay.
If the data sheet is required i can upload it.

Thanks in advance

body: It seems that most people use an Arduino CNC Shield to connect their Arduino Uno (running GRBL software) to the drivers of the stepper-motors. Via Google you find plenty of them, for example: here and here. The schematics of the latter example are published here. You could use the information from this schematic to make your own 'interface' between the Arduino and the LB1847 driver chips.


message:
Look for Master and Slave code with error for a Arduino Mege

I am building a a-10c Sim. So I need lots of input and outputs. Each Arduino has 54 digital i/o and 16 analog inputs in each. As I need more I just add another arduino mega 2560.

I want to thank in advance Im am very new at his, and would welcome any help.

Regards,

Gary
Im am a dyslexic so pls excuse the spelling or bed sentences

body:
I am not sure that I understand what you are planning to build. From the Internet I see that a "10c Sim" is a flight simulation program. Therefore I assume you plan to build some hardware, like flight stick and throttle, to provide the necessary input to the PC on which this sim program runs.

The number of digital i/o and analog inputs you mention is not true for "each Arduino" but only for an Arduino Mega.

To expand the number of i/o pins you could add another Arduino, but this makes the programming (much) more complicated. You could set them up as master and slave, where the master tells the slave which output to perform and the slave tells the master which input came in. Or you can split-up the total system into two subsystems where each Arduino has his own responsibilities to handle it's part of the system. In order not to lose many i/o pins to the connection between both Arduino's, the connection between the two Arduino's has to be serial.

But there are better possibilities to extend the number of i/o-pins. IC's (chips) exist wit a serial input and a number of (parallel) i/o pins. A special case of this are the IC's working with I2C as the serial connection. Look at Google for "i2c port expander".


message:
problem related to arduino

first of all, I am not very good at English. if I have done a mistake during describe the problem apologize me. I want to combine both ultrasonic sensor code and mpu6050 sensor. can anyone tell me how to combine both codes in one code?

    #include <Wire.h>
    //I2C communication library for MPU6050
    #include <I2Cdev.h>
    //MPU6050 interfacing library
    #include <MPU6050_6Axis_MotionApps20.h>
    //Processing incoming serial data
    #include <CmdMessenger.h>
    //Contain definition of maximum limits of various data type
    #include <limits.h>

    //Creating MPU6050 Object
    MPU6050 mpu(0x68);
    //Messenger object
    CmdMessenger Messenger_Handler = CmdMessenger(Serial);

    ///////////////////////////////////////////////////////////////////////////////////////
    //DMP options
    //Set true if DMP init was successful
    bool dmpReady = false;
    //Holds actual interrupt status byte from MPU
    uint8_t mpuIntStatus;
    //return status after each device operation
    uint8_t devStatus;
    //Expected DMP paclet size
    uint16_t packetSize;
    //count of all bytes currently in FIFO
    uint16_t fifoCount;
    //FIFO storate buffer
    uint8_t fifoBuffer[64];

    #define OUTPUT_READABLE_QUATERNION
    ////////////////////////////////////////////////////////////////////////////////////////////////

    //orientation/motion vars
    Quaternion q;
    VectorInt16 aa;
    VectorInt16 aaReal;
    VectorInt16 aaWorld;
    VectorFloat gravity;

    //Euler angle container
    float euler[3];

    //yaw/pitch/roll container and gravity vector
    float ypr[3];

    // ================================================================
    // ===               INTERRUPT DETECTION ROUTINE                ===
    // ================================================================

    volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
    void dmpDataReady() {
        mpuInterrupt = true;
    }

    /////////////////////////////////////////////////////////////////
    //Motor Pin definition
    //Left Motor pins

    #define A_1 3
    #define B_1 4

    //PWM 1 pin number
    #define PWM_1 6

    //Right Motor
    #define A_2 4
    #define B_2 5

    //PWM 2 pin number
    #define PWM_2 5

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //Ultrasonic pins definition
    const int echo = 24, Trig = 23;
    long duration, cm;

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////////////////
    //Motor speed from PC
    //Motor left and right speed
    float motor_left_speed = 0;
    float motor_right_speed = 0;
    /////////////////////////////////////////////////////////////////

    //Setup serial, encoders, ultrasonic, MPU6050 and Reset functions
    void setup()
    {

      //Init Serial port with 115200 baud rate
      Serial.begin(115200);

      //Setup Motors
      SetupMotors();
      //Setup Ultrasonic
      SetupUltrasonic();
      //Setup MPU 6050
      Setup_MPU6050();

      //Set up Messenger
    //  Messenger_Handler.attach(OnMssageCompleted);

    }

    void SetupMotors()
    {

     //Left motor
     pinMode(A_1,OUTPUT);
     pinMode(B_1,OUTPUT);

     //Right Motor
     pinMode(A_2,OUTPUT);
     pinMode(B_2,OUTPUT);

    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //Setup UltrasonicsSensor() function
    void SetupUltrasonic()
    {
     pinMode(Trig, OUTPUT);
     pinMode(echo, INPUT);

    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //Setup MPU6050 function

    void Setup_MPU6050()
    {

        Wire.begin();
       // initialize device
        Serial.println("Initializing I2C devices...");
        mpu.initialize();

        // verify connection
        Serial.println("Testing device connections...");
        Serial.println(mpu.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");

        //Initialize DMP in MPU 6050
        Setup_MPU6050_DMP();

    }
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //Setup MPU 6050 DMP
    void Setup_MPU6050_DMP()
    {

         //DMP Initialization

       devStatus = mpu.dmpInitialize();

       mpu.setXGyroOffset(220);
       mpu.setXGyroOffset(76);
       mpu.setXGyroOffset(-85);
       mpu.setXGyroOffset(1788);

       if(devStatus == 0){
             Serial.println(F("Enabling DMP..."));
            mpu.setDMPEnabled(true);
        //mpu.setDMPEnabled(true);

    //    pinMode(PUSH2,INPUT_PULLUP);
    //    attachInterrupt(PUSH2, dmpDataReady, RISING);

        mpuIntStatus = mpu.getIntStatus();

        dmpReady = true;

        packetSize = mpu.dmpGetFIFOPacketSize();

       }else{

         ;
         }
    }

    void loop() {

     //Read from Serial port
        Read_From_Serial();

        //Send ultrasonic values through serial port
        Update_Ultra_Sonic();

        //Send MPU 6050 values through serial port
        Update_MPU6050();

    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //Read from Serial Function

    void Read_From_Serial()

    {
       while(Serial.available() > 0)
        {

           int data = Serial.read();
    //       Messenger_Handler.process(data);

        }

    }

    void Update_Ultra_Sonic()
    {
      digitalWrite(Trig, LOW);
      delayMicroseconds(2);
      digitalWrite(Trig, HIGH);
      delayMicroseconds(10);
      digitalWrite(Trig, LOW);
      // The echo pin is used to read the signal from the PING))): a HIGH
      // pulse whose duration is the time (in microseconds) from the sending
      // of the ping to the reception of its echo off of an object.
      duration = pulseIn(echo, HIGH);

      //Sending through serial port
      Serial.print("u");
      Serial.print("\t");
      Serial.print(cm);
      Serial.print("\n");

    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //Update MPU6050

    void Update_MPU6050()
    {

      int16_t ax, ay, az;
      int16_t gx, gy, gz;

        ///Update values from DMP for getting rotation vector
        Update_MPU6050_DMP();

    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //Update MPU6050 DMP functions

    void Update_MPU6050_DMP()
    {

     //DMP Processing
     // if programming failed, don't try to do anything
        if (!dmpReady) return;

         // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt && fifoCount < packetSize) {

            ;

              }

    // reset interrupt flag and get INT_STATUS byte
        mpuInterrupt = false;
        mpuIntStatus = mpu.getIntStatus();

        //get current FIFO count
        fifoCount = mpu.getFIFOCount();

        // check for overflow (this should never happen unless our code is too inefficient)
        if ((mpuIntStatus & 0x10) || fifoCount > 512) {
            // reset so we can continue cleanly
            mpu.resetFIFO();
        }

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    else if (mpuIntStatus & 0x02) {
            // wait for correct available data length, should be a VERY short wait
            while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

            // read a packet from FIFO
            mpu.getFIFOBytes(fifoBuffer, packetSize);

            // track FIFO count here in case there is > 1 packet available
            // (this lets us immediately read more without waiting for an interrupt)
            fifoCount -= packetSize;

            #ifdef OUTPUT_READABLE_QUATERNION
                // display quaternion values in easy matrix form: w x y z
                mpu.dmpGetQuaternion(&q, fifoBuffer);

                Serial.print("i");Serial.print("\t");
                Serial.print(q.x); Serial.print("\t");
                Serial.print(q.y); Serial.print("\t");
                Serial.print(q.z); Serial.print("\t");
                Serial.print(q.w);
                Serial.print("\n");

            #endif

            #ifdef OUTPUT_READABLE_EULER
                // display Euler angles in degrees
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetEuler(euler, &q);
                Serial.print("euler\t");
                Serial.print(euler[0] * 180/M_PI);
                Serial.print("\t");
                Serial.print(euler[1] * 180/M_PI);
                Serial.print("\t");
                Serial.println(euler[2] * 180/M_PI);
            #endif

            #ifdef OUTPUT_READABLE_YAWPITCHROLL
                // display Euler angles in degrees
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
                Serial.print("ypr\t");
                Serial.print(ypr[0] * 180/M_PI);
                Serial.print("\t");
                Serial.print(ypr[1] * 180/M_PI);
                Serial.print("\t");
                Serial.println(ypr[2] * 180/M_PI);
            #endif

            #ifdef OUTPUT_READABLE_REALACCEL
                // display real acceleration, adjusted to remove gravity
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetAccel(&aa, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
                Serial.print("areal\t");
                Serial.print(aaReal.x);
                Serial.print("\t");
                Serial.print(aaReal.y);
                Serial.print("\t");
                Serial.println(aaReal.z);
            #endif

            #ifdef OUTPUT_READABLE_WORLDACCEL
                // display initial world-frame acceleration, adjusted to remove gravity
                // and rotated based on known orientation from quaternion
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetAccel(&aa, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
                mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
                Serial.print("aworld\t");
                Serial.print(aaWorld.x);
                Serial.print("\t");
                Serial.print(aaWorld.y);
                Serial.print("\t");
                Serial.println(aaWorld.z);
            #endif

            #ifdef OUTPUT_TEAPOT
                // display quaternion values in InvenSense Teapot demo format:
                teapotPacket[2] = fifoBuffer[0];
                teapotPacket[3] = fifoBuffer[1];
                teapotPacket[4] = fifoBuffer[4];
                teapotPacket[5] = fifoBuffer[5];
                teapotPacket[6] = fifoBuffer[8];
                teapotPacket[7] = fifoBuffer[9];
                teapotPacket[8] = fifoBuffer[12];
                teapotPacket[9] = fifoBuffer[13];
                Serial.write(teapotPacket, 14);
                teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
            #endif

        }

    }

body: In the function `Update_Ultra_Sonic()` you do the measurement and save the result in the variable `duration`. Then you print the variable `cm`, but you haven't calculated the value for this variable yet. You have to calculate the number of cm from the echos `duration` and save the result in `cm`. When you don't do this, the variable stays at zero.


message:
How can I call the constructor of a Class after it called once?

I have a problem with Classes.
I have a bunch of code, that code is uses Adafruit MQTT FONA library. I call the Class for make new Instance and Connect to specified server with this code;

    Adafruit_MQTT_FONA mqtt(&fona, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

When I want to connect to another server, I call this Instance's constructor after it called once. But it don't let me to construct it again. How can I construct the same instance again after it constructed once?

    void connectMqtt()
    {
        Adafruit_MQTT_FONA mqtt(&fona, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
    }

    connectMqtt();

Thanks for helps! Have a good day!

body:
You can't. Once constructed, an object remains constructed until you delete it.

You could either use dynamic allocation and `new` and `delete` to create and destroy objects at will, or you could create multiple objects with different settings and use different objects at different times.

Another option would be to modify the library to create a new function that accepts and assigns new server settings. All the constructor does is store the settings in variables - there's no reason why you couldn't just change those variables.


message:
How to build an µC controlled power regulator?

The idea: Use an Arduino-like µC to control a set of CPU fans by control the voltage the CPU fans receive. My question: How can I do this in an easy way?

Yes, I know, there is PWM but this is not very suitable for this purpose: I did some tests with it but it turns out that the characteristics of PWM fans don't suite my purpose: PWM fans are designed to be controlled between not audible and full speed, not between nearly not rotating and full speed. Even very special fans with a wide range of PWM speed control don't work as well as powering a regular 12V fan with just 5 or 6V.

Which brings me to an alternative idea: It should be possible to send an I2C or SPI signal to some kind of IC that then provides a voltage as required.

Alternatively to that there seem to be PWM controlled voltage regulators available. But that doesn't seem to be a very elegant solution, isn't it?

Or is there an even better way of controlling the voltage output to the fans I'm not aware of?

I'm aiming for a solution that works well and can be build with little effort. Unfortunately I don't know how to do that: I can't find any breakouts I could use right away for that purpose. Probably there are some and I just have not been able to find them? Any help is appreciated!

body:
It's actually very simple, and it indeed does involve using PWM.

PWM is just a signal being on for a percentage of a predefined period.  That percentage is also, when the PWM signal is averaged out, equivalent to a percentage of the peak voltage of the PWM signal.

So if you take a PWM signal and use it to switch a higher power source (say, through a P-channel MOSFET that's being itself switched by an N-channel MOSFET), then add smoothing to that switched output, and you have a variable voltage.

If you want to know what that voltage is you can add a resistor network to the output (assuming it's higher than the voltage the MCU can handle) and read the divided voltage using an ADC.  You can then use that as a feedback loop to adjust the PWM duty cycle to get your desired voltage.

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

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

<!-- End schematic -->

That is precisely* how switch-mode power supplies work. Use PWM to switch a FET that controls an incoming voltage, then smooth it out, adding a feedback network for control.

----

<sub>*Apart from the PWM bit: they often use other methods of switching the signal to get better efficiency at different loads, such as PFM.</sub>