message:
The sketch burned two H Bridges, need help to find out how to modify

This is Arduino RC control car, the sketch tested good in a small motor, but burned two 60A drivers when put into 24V,500W motors, need help to find out whats wrong?

    #include <VirtualWire.h>

    //motor A connected between A01 and A02
    //motor B connected between B01 and B02

    int STBY = 2; //standby  // mod: was 10 --2 ??

    int count;

    //Motor A
    int PWMA = 9; //Speed control   // need mod: was 3 change into 9
    int AIN1 = 8; //Direction  // was 9
    int AIN2 = 7; //Direction

    //Motor B
    int PWMB = 10; //Speed control   // need mod: was 5 change into 10
    int BIN1 = 5; //Direction   // was 6
    int BIN2 = 4; //Direction   ///was 16 put into p7 cause of Arduino uno no p16.

    const boolean FORWARD = HIGH;
    const boolean REVERSE = LOW;

    float speed_Max = 252; //pwm usually goes from was:0-255 ////0-255 changed into 0-252

    float speed_Min = 0;
    float analogInput_Max = 1023;
    float analogInput_Min = 0;
    float analogInput_Middle_X = 515;//ideally it would be analogInput_Max / 2
    float analogInput_Middle_Y = 495;//ideally it would be analogInput_Max / 2
    float deadBand = 0;
    float middleMax = (analogInput_Max / 2) + deadBand;
    float middleMin = (analogInput_Max / 2) - deadBand;
    boolean pastDirection = FORWARD;

    void setup()
    {
      // Configure Timer 2 for PWM @ 14 kHz.
      TCCR2A = 0;           // undo the configuration done by...
      TCCR2B = 0;           // ...the Arduino core library
      TCNT2  = 0;           // reset timer

      TCCR2A = _BV(COM2A1)  // non-inverted PWM on ch. A
               | _BV(COM2B1)  // same on ch; B
               | _BV(WGM20);  // mode 10: ph. correct PWM, TOP = ICR1

          TCCR2B = (TCCR2B & 0b11111000) | 0x01; //3.92116 [kHz] //** use this code got 3.9khz but joystick works not too good
        {

        Serial.begin(9600);  // Debugging only
        Serial.println("setup"); //Prints "Setup" to the serial monitor

        vw_set_rx_pin(6);       //Sets pin D12 as the RX Pin
        vw_set_ptt_inverted(true); // Required for DR3100
        vw_setup(2000);      // Bits per sec
        vw_rx_start();       // Start the receiver PLL running

        pinMode(23, OUTPUT); //Relay one ////M1 added 2 was 2 -- 4
        pinMode(25, OUTPUT); //Relay two
        pinMode(27, OUTPUT); //Relay four
        pinMode(29, OUTPUT); //Relay five
        pinMode(31, OUTPUT); //Relay sex
        pinMode(33, OUTPUT); //Relay seven
        pinMode(35, OUTPUT); //Relay eight
        pinMode(37, OUTPUT); //Relay three
        pinMode(39, OUTPUT); //Relay three
        pinMode(41, OUTPUT); //Relay eight
        pinMode(43, OUTPUT); //Relay three
        pinMode(45, OUTPUT); //Relay three

        digitalWrite(23, HIGH);
        digitalWrite(25, HIGH);
        digitalWrite(27, HIGH);
        digitalWrite(29, HIGH);
        digitalWrite(31, HIGH);
        digitalWrite(33, HIGH);
        digitalWrite(35, HIGH);
        digitalWrite(37, HIGH);
        digitalWrite(39, HIGH);
        digitalWrite(41, HIGH);
        digitalWrite(43, HIGH);
        digitalWrite(45, HIGH);
         }

      pinMode(STBY, OUTPUT); //// pin: the number of the pin whose mode you wish to set; mode: INPUT, OUTPUT, or INPUT_PULLUP.

      pinMode(PWMA, OUTPUT);
      pinMode(AIN1, OUTPUT);
      pinMode(AIN2, OUTPUT);

      pinMode(PWMB, OUTPUT);
      pinMode(BIN1, OUTPUT);
      pinMode(BIN2, OUTPUT);
    }

    void loop() {

    button(); //// disable 'button', no work. remove '//' enable, button works good
    joystick(); //// disable 'joystick', no work. remove '//' enable, joystick works good, but no motor control yet

     }

    void joystick() {

      uint8_t buf[VW_MAX_MESSAGE_LEN]; // This declares a variable array. instead of 7 variables buf1, buf2 etc...
      uint8_t buflen = VW_MAX_MESSAGE_LEN;
      if (vw_get_message(buf, &buflen)) // Non-blocking
      {
        int i;
        int column = 0;
        String message;
        int commands[30];
        // Message with a good checksum received, dump it.
        for (i = 0; i < buflen; i++)
        {
          //DEBUG:
          //Serial.print(char(buf[i]));

          if (char(buf[i]) == '|') {
            commands[column] = message.toInt();
            message = "";
            column++;
          } else {
            message += char(buf[i]);
          }
        }

        //one more time to capture the last value since the message does not end with |
        commands[column] = message.toInt();

        // DEBUG
        //    Serial.print("X: ");
        //    Serial.print(commands[0]);
        //    Serial.print(" Y: ");
        //    Serial.println(commands[1]);

         motorControl(commands[0], commands[1]);

      }

    }

    void move(int motor, int speed, boolean direction) {
      digitalWrite(STBY, HIGH); //disable standby

       if (motor == 1) {
        digitalWrite(AIN1, direction);
        digitalWrite(AIN2, !direction);
        analogWrite(PWMA, speed);
      } else {
        digitalWrite(BIN1, !direction);
        digitalWrite(BIN2, direction);
        analogWrite(PWMB, speed);
      }
    }

    void motorControl(float x, float y) {
      boolean currentDirection = y >= analogInput_Middle_Y;

        //map(value, fromLow, fromHigh, toLow, toHigh);
      if (currentDirection == REVERSE) {
        y = map(y, analogInput_Middle_Y, analogInput_Min, speed_Min, speed_Max) ;
      } else {
        y = map(y, analogInput_Middle_Y, analogInput_Max, speed_Min, speed_Max);
      }

      int subtractFromLeft = map(x, analogInput_Middle_X, analogInput_Min, speed_Min, y);
      int subtractFromRight = map(x, analogInput_Middle_X, analogInput_Max, speed_Min, y);

      if (subtractFromRight < 0) {
        subtractFromRight = 0;
      }

      if (subtractFromLeft < 0) {
        subtractFromLeft = 0;
      }

      int Throttle_RIGHT = y - subtractFromRight;
      int Throttle_LEFT = y - subtractFromLeft;

      boolean currentDirection_LEFT = currentDirection;
      boolean currentDirection_RIGHT = currentDirection;

      if (Throttle_LEFT < 1 && Throttle_RIGHT > 1) {
        currentDirection_LEFT = !currentDirection;
        Throttle_LEFT = Throttle_RIGHT;
      }

      if (Throttle_RIGHT < 1 && Throttle_LEFT > 1) {
        currentDirection_RIGHT = !currentDirection;
        Throttle_RIGHT = Throttle_LEFT;
      }

      move(1, Throttle_LEFT, currentDirection_LEFT);
      move(2, Throttle_RIGHT, currentDirection_RIGHT);

      }

    void button()
    {
      uint8_t buf[VW_MAX_MESSAGE_LEN];
      uint8_t buflen = VW_MAX_MESSAGE_LEN;
      if (vw_get_message(buf, &buflen)) // Non-blocking
      {
        int i;
        digitalWrite(13, true);  // Flash a light to show received good message
        // Message with a good checksum received, dump it.
        Serial.print("Got: ");

        for (i = 0; i < buflen; i++)
        {
          int c = (buf[i]);
          Serial.print(c);
          Serial.print(" ");
          if (c == 65 ) {
            digitalWrite(23, !digitalRead(23));  //// A--RELAY A1
          }

          if (c == 66 ) {
            digitalWrite(25, !digitalRead(25));  //// B--RELAY A2
          }

          if (c == 67 ) {
            digitalWrite(27, !digitalRead(27)); //// C--RELAY B1
          }

          if (c == 68 ) {
            digitalWrite(29, !digitalRead(29)); //// D--RELAY B2
          }
    /*
          if (c == 69 ) {
            digitalWrite(37, !digitalRead(37)); //// E--
          }

          if (c == 70 ) {
            digitalWrite(39, !digitalRead(39)); //// F--
          }
    */
          if (c == 71 ) {
            digitalWrite(31, !digitalRead(31)); //// G--RELAY C1
          }

          if (c == 72 ) {
            digitalWrite(33, !digitalRead(33));  //// H -- RELAY C2
          }

          if (c == 73 ) {
            digitalWrite(43, !digitalRead(43));  //// I --
          }

           if (c == 74 ) {
            digitalWrite(35, !digitalRead(35));  //// J --
          }

           if (c == 75 ) {
            digitalWrite(37, !digitalRead(37));  //// K --
          }

          if (c == 76 ) {
            digitalWrite(39, !digitalRead(39));  //// L --
          }
          if (c == 77 ) {
            digitalWrite(41, !digitalRead(41));  //// M --
          }
          if (c == 78 ) {
            digitalWrite(35, !digitalRead(35));  //// N --
          }

        }
        count++;
        // Serial.print(count);
        Serial.println("");
        digitalWrite(13, false);
      }
    }

My new driver is came, I just scare to use it, heard that DC motor will draw upto 300A at the start, what should I do to reduce the start current?

body:
As you wrote in comment you use this H bridge:

https://www.ebay.com/itm/60A-DC-Motor-Driver-Module-High-Power-motor-Speed-Control-Dual-Channel-H-bridge/122479397950

The description how to use it is clear:
[![h-bridge features][1]][1]

But the listing doesn't say what will happen when you set state of `A1,A2=1.1` to that H-bridge.

When you set value of `A1,A2=1.1` to a unprotected (cheap) H-Bridge you get a direct short to ground through 2 transistors burning them instantly

[![H-Bridge and electricity path for 1,1][2]][2]

Your code actually does not protect against that:

       if (motor == 1) {
        digitalWrite(AIN1, direction);
        digitalWrite(AIN2, !direction);
        analogWrite(PWMA, speed);
      } else {
        digitalWrite(BIN1, !direction);
        digitalWrite(BIN2, direction);
        analogWrite(PWMB, speed);
      }
    }

If previous value of direction is 0 (`A1,A2=0,1`) and you want to set direction to 1 (`A1,A2=1,0`) when arduino runs the line `digitalWrite(AIN1, direction);` for few cycles you actually end up with `A1,A2=1,1` and MOSFETs go bye bye.

Try setting AIN1, AIN2 (or BIN1, BIN2) to 0 before adjusting the direction

       if (motor == 1) {
        digitalWrite(AIN1, LOW);
        digitalWrite(AIN2, LOW);

        digitalWrite(AIN1, direction);
        digitalWrite(AIN2, !direction);
        analogWrite(PWMA, speed);
      } else {
        digitalWrite(BIN1, LOW);
        digitalWrite(BIN2, LOW);

        digitalWrite(BIN1, !direction);
        digitalWrite(BIN2, direction);
        analogWrite(PWMB, speed);
      }
    }

This way you are guaranteed that you always have at least one `0` there.

**EDIT:**

You wrote that the module contains IR2103s it should protect you from the problem I described above. (But my suggested fix is not dangerous so you can use it just in case)

There is another possibility. Maybe the rapidly changing of the direction induces high voltage spikes in the motor, and that burns the circuit. Do you see any power diodes there? Look at the image I pasted above it has 4 diodes that should safely discharge those spikes. Make sure your code does not change direction every few milliseconds.

  [1]: https://i.stack.imgur.com/s5fTz.png
  [2]: https://i.stack.imgur.com/YQiz5.png


sender: user

message:
DigiKeyboard - type a backslash (\)

I'm using digiKeyboard library to type to a powershell, but I need to type a backslash (a lot of them), but I can't figure it out.

I have been looking for the solution for about 3 hours and I still can't find it.
Please let me know how to make a backslash work.

The powershell command that I want to execute:

cmd /C "start /MIN powershell iwr -Uri https://tinyurl.com/WjnAU6 -OutFile c:\windows\temp\b.jpg;sp 'HKCU:Control Panel\Desktop' WallPaper 'c:\windows\temp\b.jpg';$a=1;do{RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters ,1 ,True;sleep 1}while($a++-le59)"

It just changes the wallpaper with a downloaded image, try in on your friend.

sender: assistant

body:
To include `\` in a string so it can be printed you have to escape it.  `\` is itself the escape character, so doubling it up "escapes the escape character" so it is interpreted as a normal character.

So to print `"c:\windows"` you would actually have to type `"c:\\windows"` and the `\\` gets changed by the compiler into just `\`


message:
Using ESP8266-01 via Arduino(no flash) without AT commands(using serial monitor)

I'm trying to build a smart Keychain using Arduino uno wifi(org, so Im using it like it's Arduino uno), ESP8266-01 And neo6m GPS device.

My esp8266 wasn't new, and it came without AT firmware. I flashed it so it could have AT commands but it's not completely working.

Anyway, the flash is using 115200 baud and I'd like to use serial monitor to communicate it using arduino(and blynk app).
Is there a way could I do it without flashing the esp for 9600 baud rate?

Thanks!

body:
Arduino Uno WiFi Dev Ed has the on-board esp8266 wired to additional Serial interface (I2C to Serial adapter). With [UnoWiFiDevEdSerial1][1] library you can use the on-board esp8266 and have Serial free for Serial Monitor and sketch upload. The EspProxy tool enables upload to the on-board esp8266 over the ATmega (passing bytes between Serial and Serial1).
I am the author of the UnoWiFiDevEdSerial1 library.

  [1]: https://github.com/jandrassy/UnoWiFiDevEdSerial1


message:
Memory usage: #define vs. static const for uint8_t

I'm writing an Arduino library to communicate with an I2C device, and I'm wondering what the best way is to declare all the register addresses so as to save memory.

Using `#defines`:

    #define REGISTER_MOTOR_1_MODE 0x44
    #define REGISTER_MOTOR_2_MODE 0x47

Or using `static const`:

    static const uint8_t REGISTER_MOTOR_1_MODE = 0x44;
    static const uint8_t REGISTER_MOTOR_2_MODE = 0x47;

(Obviously I have more than just two registers I need to declare, but I thought two would illustrate the point just fine)

body:
You'll find no noticeable difference memory-wise between the two.

The only real difference is that the `const` method also imposes a type to the value, which can be useful for function overloading or mathematical operations.


body:
A `#define` is a preprocessor macro. As Gerben says in his comment, it's just an automated find-and-replace.

If you use it to hold things like C string constants, e.g. `#define ERROR_STRING "You messed up, bud!"` it could actually cause your program to take more memory, since that same string literal will be duplicated every time you reference it. In that case a static const would be both type-safe AND reduce memory usage.


body:
Theoretically both approaches should consume the same amount of space and will probably result in the same code.

---

However, rather than that meaning "pick any one", what that actually means is that you should turn your attention to other factors when deciding which one to use.

As a rule of thumb you should generally avoid macros because they don't respect scoping rules due to how they work.
This can lead to some serious problems in certain cases.
See [Why are preprocessor macros evil and what are the alternatives?](https://stackoverflow.com/q/14041453).

---

However, I'd like to point out a third option: `constexpr`.
```cpp
constexpr uint8_t motorMode1Register = 0x44;
```
`constexpr` implies `const` and is a better expression of the intent that the value should be capable of being evaluated at compile time.
`constexpr` literally means "this is a constant expression and thus can be evaluated at compile time".
As a result of this, `constexpr` variables can be used in situations where other variables cannot, such as template parameters.

See [Constexpr vs Macros](https://stackoverflow.com/q/42388077).


message:
STM32 Nucleo F401RE in Arduino IDE - how to enable more than 1 Serial?

I just received a Nucleo F401RE and can't get my sketch to work on it because the compiler says Serial1 is not defined.
My sketch uses multiple serials because I need to use the usb serial monitor while also communicating to another device on a different serial port.

Here is a screenshot of the flags I selected.

[![compiling flags][1]][1]

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

According to the F401 specs it has at least 6 different serials, so the real question is: is there an easy way to use Serial1 and so on straight out of the box in the Arduino IDE?

I'm quite new and unexperienced to this field, so please excuse me if this question is too trivial.

body:
Frederic Pillon on Github has been very helpful and suggested me the solution, which is to define the serial via:

    HardwareSerial Serial1(PA10, PA9);

instead of just giving Serial1 for granted as you would do on a regular Arduino mega


message:
Serial plotter isn't displaying my supplied data

I want to use serial plotter feature of Arduino by using DHT11 as humidity sensor at a time. But I'm getting problem as plotter is not loading by the code I have. Please help me what is the problem because of which serial plotter is not loading.

Here is the Code I wrote:-

    #include <dht.h>
    #define dht_apin0 A0 // Analog Pin sensor is connected to

    dht DHT0;

    void setup() {

      Serial.begin(9600);
      delay(500);//Delay to let system boot
      Serial.println("DHT11 Humidity Sensor\n");
      delay(1000);//Wait before accessing Sensor

    }//end "setup()"

    void loop(){
      //Start of Program

        DHT0.read11(dht_apin0);

        Serial.print("Current humidity = ");
        Serial.print(DHT0.humidity);
        Serial.print("%  ");

        delay(5000);//Wait 5 seconds before accessing sensor again.

      //Fastest should be once every two seconds.

    }// end loop()

body:
You can't send arbitrary information (percent signs, text etc) to the plotter. The plotter *only* understands numeric values. You have to separate these number values from each other with commas, then do a `println` in your last value:

```
Serial.print(percent);
Serial.print(F(","));
Serial.print(tankPercent(depth));
Serial.print(F(","));
Serial.print(litres);
Serial.print(F(","));
Serial.println(tankLitres(depth));
```

In your case, it'd be simply:

    Serial.println(DHT0.humidity);

You can go a bit further if you want to switch between either serial output, or serial plotter. In one case, I just set a constant variable for graph or plain data, then have a function for each (my above `Serial` statements are actually within a function called `displayGraph()`). The data function would be something like you had originally, example:

```

void displayData(float depth, float percent, float litres){

  // water level depth (inches)

  Serial.print(F("current missing inches: "));
  Serial.println(mixtureDistance());

  // cubic inches

  Serial.print(F("total cubic inches: "));
  Serial.println(TANK_TOTAL_CUBIC_INCHES);

  Serial.print(F("current cubic inches: "));
  Serial.println(tankCurrentCubicInches(depth));

  // litres

  Serial.print(F("total litres: "));
  Serial.println(TANK_TOTAL_LITRES);

  // ... etc
}
```

I also have projects where I use a switch that if on, sets a flag to output in serial graph format, and if off, uses the serial data routine.

Then, in your sketch `loop()`, you'd do something like:

    graph
      ? displayGraph(depth, percent, litres)
      : displayData(depth, percent, litres);

...or a bit more verbose rather than using the tertiary operator:

    if (graph){
      displayGraph(...);
    }
    else {
      displayData(...);
    }

Here's a Q&D serial plotter example of my `displayGraph()` function above. In the top-right corner of the image, the four colours represent the four pieces of data I'm sending in, in order:

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

In my case, those represent the exponential moving average of the percentage of how full a liquid tank is, the second is the raw data I'm building that average on, third is the exponential moving average of how many litres are remaining in the tank, and lastly, again, the raw data for that average.

The sharp movements are simply me slapping the tank to get some variable and unstable readings for example purposes.

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


message:
How do I provide a negative current?

I'm trying to use an ATMega328 board to control a board of a broken UPS device. I replaced all the internals of the UPS by custom components, so the only things which remain are the chassis and the front board.

On this board, there are five buttons, and three LEDs.

[![][1]][1]

All those components are connected to the ground, each one through its own resistor. By connecting the different pins to the ground and to analog pins of the ATMega328 board, I can successfully detect when the buttons are pressed.

[![][2]][2]

Things, however, get tricky when I want to turn the LEDs on. They have their anode connected to the ground (through a 47Ω resistor), and their cathode connected to a dedicated pin. This means that if I apply voltage to this pin, the LED remains off.

The LED, however, turns on if I connect the ground to a 5V pin on ATMega328 board and the cathode pin to the ground of the ATMega328 board. However, connecting the ground to 5V makes it impossible to read the state of the buttons (or should I wire them somehow specifically?)

Therefore, **how do I feed negative current from the ATMega328 board?**

There is [a similar question][3] on this subject, but while the author wants to “understand the underlying electronics of the arduino and microcontrollers in general,” I, instead, just want to know how to make it work. Reading the answers from the linked question, I have an impression that this is possible, but they don't explain *how* to do it.

  [1]: https://i.stack.imgur.com/PxLIX.jpg
  [2]: https://i.stack.imgur.com/0tD2X.jpg
  [3]: https://arduino.stackexchange.com/q/4356/45493

body:
If the LEDs turn on when you apply 5V to *ground* then what you have identified as GND on the board is actually VCC.
There is no such thing as *negative current*: current is either **sourced** or **sinked**, depending if it’s exiting or entering into a node.

The diodes (LED) are one way valves, so you have a clear current direction: once that is established, identifying a button press can work either triggering when it gets LOW or when it gets HIGH, in other words that can be easily reversed.

If previously you where detecting a button press with `digitalRead(BTN_PIN) == HIGH` then just switch to `digitalRead(BTN_PIN) == LOW` and you have your solution.


body:
The answer by Roberto Lo Giacco was helpful, but I still had hard time understanding what is happening and how should I wire the boards properly. Since others may encounter similar problems, I'll explain the solution in my own words.

Note that [an answer to a similar question][1] helped me as well.

---

When a digital pin is set to high with `digitalWrite(LED_PIN, HIGH);`, it's similar (probably not in electrical terms, but at least in terms of interface) to connecting to 5V what was previously connected to the pin.

Similarly, `digitalWrite(LED_PIN, LOW);` is similar to connecting to GND what was previously connected to the pin.

This means that when the LED is connected as usual, cathode to the GND and anode (through a resistor) to a digital pin:

 - `digitalWrite(LED_PIN, HIGH);` turns the LED on, and:
 - `digitalWrite(LED_PIN, LOW);` turns it off.

Now, if the cathode is connected to the digital pin, the anode (through a resistor) can be connected to 5V. In this situation:

 - `digitalWrite(LED_PIN, HIGH);` turns the LED off.
 - `digitalWrite(LED_PIN, LOW);` turns it on.

On the photo in my question, the black wire is connected to GND. Instead, it should be connected to 5V. Other wires remain unchanged.

When it comes to the buttons, in order to determine whether the button is pressed or not, I was doing this:

    if (analogRead(ESC_PIN) == 0) {
        // The ESC button is pressed.
    }

When the button wasn't pressed, the values from `analogRead` were quite random, ranging from 50 to 250, or something like that. A zero value would indicate that the button was pressed.

With the new wiring (5V instead of GND), the new values from `analogRead` range from 350 to 900 when the button is not pressed. When the button is down, the value becomes 1023. Therefore, the new condition is simply:

    if (analogRead(ESC_PIN) == 1023) {
        // The ESC button is pressed.
    }

  [1]: https://arduino.stackexchange.com/a/46398/45493


message:
SPI Wiring Confusion

I am currently trying to learn about SPI and how it works on the Arduino. I want to wire a MAX7219 chip to it to drive an 8x8 LED matrix with. Normally, I would assume the wiring from Arduino to MAX7219 goes:

- PIN 10 SS -> CS
- PIN 11 MOSI -> DIN
- PIN 13 SCK -> CLK

And indeed, [this answer][1] confirms my assumption.
However, after going through some other resources and guides I found some confusing and conflicting information about how the pins on the two devices should be connected.

For instance, the documentation that came with my Arduino kit has this schematic.

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

[This tutorial][3] I found has the same wiring.

[![enter image description here][4]][4]

Most surprisingly, [this tutorial][5] doesn't even use the SPI pins at all.

[![enter image description here][6]][6]

What perplexes me the most is the sentence

> The VCC and GND of the module go to the 5V and GND pins of the Arduino and the three other pins, DIN, CLK and CS go to any digital pin of the Arduino board.

Is this true? If yes, then what is the point of the SPI pins at all? Why are the pins wired in so many different configurations?
I am really confused by this.

  [1]: https://arduino.stackexchange.com/questions/16348/how-do-you-use-spi-on-an-arduino
  [2]: https://i.stack.imgur.com/NoDiw.png
  [3]: https://www.brainy-bits.com/how-to-control-max7219-led-matrix/
  [4]: https://i.stack.imgur.com/gEU5b.png
  [5]: https://howtomechatronics.com/tutorials/arduino/8x8-led-matrix-max7219-tutorial-scrolling-text-android-control-via-bluetooth/
  [6]: https://i.stack.imgur.com/01fNR.png

body:
SPI is a communication protocol, you can take advantage of some hardware optimizations by using the pins where that hardware is available or you can do everything *by hand* using any pin you like, with the disadvantage of a bigger and slower firmware.
In certain situations, like in the presence of a shield or a library already using those pins, the SPI pins might be unavailable and you have to resort to a software solution (aka *bitbang*, as you manipulate bits to generate the proper signals), otherwise use of the hardware SPI pins is strongly advised.


body:
> For instance, the documentation that came with my Arduino kit has this schematic.

Pins 10 through to 13 are standard SPI pins on the Uno.

* 10 (SS)
* 11 (MOSI)
* 12 (MISO)
* 13 (SCK)

I have a tutorial [here](http://www.gammon.com.au/spi). I also have a Stack Exchange [reference question and answer](https://arduino.stackexchange.com/questions/16348/how-do-you-use-spi-on-an-arduino/16349#16349) about SPI.

---

> Most surprisingly, this tutorial doesn't even use the SPI pins at all.

It is certainly possible to "bit bang" SPI and in some cases this is desirable, for example if you have something like an SD card interface, and also want to use SPI for a display. On the page I linked, specifically at [this post](http://www.gammon.com.au/forum/?id=10892&reply=6#reply6) I describe how to bit-bang SPI.

---

> What perplexes me the most is the sentence
>
> The VCC and GND of the module go to the 5V and GND pins of the Arduino and the three other pins, DIN, CLK and CS go to any digital pin of the Arduino board.

For bit-banged SPI, yes you can use any pins.

---

> Is this true? If yes, then what is the point of the SPI pins at all?

The hardware SPI is faster and easier, and you can do other things while SPI is sending/receiving but with bit-banging it is much more timing-dependent.


body:
This video shows a project I did with a Duemilanove, 4 MAX7219s driving 4 8x8 LED matrices, and powered via 7.5V power supply.  https://www.youtube.com/watch?v=hwYqgyMc5S4

With a 9V supply, the 5V regulator overheated and shut down after some number of minutes. With 7.5V, there was no problem.

The SPI and power pins, 5V, Gnd, SCK, MOSI, go to all devices, and each chip has its own SS pin (I didn't want to deal with sending out a bunch of NOP commands to feed data thru daisy-chained chips).  Data to all 4 devices is refreshed as fast as 50mS, any faster and the display got too hard to read. I think I only used SPI at 4 MHz too, I have done other projects with SCK at 8 MHz, that can send out data really fast.


message:
ATTiny85 I2C connection with Arduino Nano

I am trying to send and receive data using I2C between an Arduino Nano and an ATTiny85.
The ATTiny is mounted on this board:
[Link][1]

I've tried to reach the slave with the simple I2C scanner, but I don't find anything.

Those are the codes:

Master (I2C scanner):

    // --------------------------------------
    // i2c_scanner
    //
    // Version 1
    //    This program (or code that looks like it)
    //    can be found in many places.
    //    For example on the Arduino.cc forum.
    //    The original author is not know.
    // Version 2, Juni 2012, Using Arduino 1.0.1
    //     Adapted to be as simple as possible by Arduino.cc user Krodal
    // Version 3, Feb 26  2013
    //    V3 by louarnold
    // Version 4, March 3, 2013, Using Arduino 1.0.3
    //    by Arduino.cc user Krodal.
    //    Changes by louarnold removed.
    //    Scanning addresses changed from 0...127 to 1...119,
    //    according to the i2c scanner by Nick Gammon
    //    http://www.gammon.com.au/forum/?id=10896
    // Version 5, March 28, 2013
    //    As version 4, but address scans now to 127.
    //    A sensor seems to use address 120.
    // Version 6, November 27, 2015.
    //    Added waiting for the Leonardo serial communication.
    //
    //
    // This sketch tests the standard 7-bit addresses
    // Devices with higher bit address might not be seen properly.
    //

    #include <Wire.h>

    void setup()
    {
      Wire.begin();

      Serial.begin(9600);
      while (!Serial);             // Leonardo: wait for serial monitor
      Serial.println("\nI2C Scanner");
    }

    void loop()
    {
      byte error, address;
      int nDevices;

      Serial.println("Scanning...");

      nDevices = 0;
      for(address = 1; address < 127; address++ )
      {
        // The i2c_scanner uses the return value of
        // the Write.endTransmisstion to see if
        // a device did acknowledge to the address.
        Wire.beginTransmission(address);
        error = Wire.endTransmission();

        if (error == 0)
        {
          Serial.print("I2C device found at address 0x");
          if (address<16)
            Serial.print("0");
          Serial.print(address,HEX);
          Serial.println("  !");

          nDevices++;
        }
        else if (error==4)
        {
          Serial.print("Unknown error at address 0x");
          if (address<16)
            Serial.print("0");
          Serial.println(address,HEX);
        }
      }
      if (nDevices == 0)
        Serial.println("No I2C devices found\n");
      else
        Serial.println("done\n");

      delay(500);           // wait 5 seconds for next scan
    }

And this is the code of the ATTiny85 (slave):

    #include <TinyWire.h>

    #define led_pin 1

    byte own_address = 10;

    void setup() {
      // config led_pin as Output for driving an LED
      pinMode(led_pin, OUTPUT);

      // config TinyWire library for I2C slave functionality
      TinyWire.begin( own_address );
      // sets callback for the event of a slave receive
      TinyWire.onReceive( onI2CReceive );
    }

    void loop() {

    }

    /*
    I2C Slave Receive Callback:
    Note that this function is called from an interrupt routine and shouldn't take long to execute
    */
    void onI2CReceive(int howMany){
      // loops, until all received bytes are read
      while(TinyWire.available()>0){
        // toggles the led everytime, when an 'a' is received
        if(TinyWire.read()=='a') digitalWrite(led_pin, !digitalRead(led_pin));
      }
    }

Once I've programmedo both the boards I've connected SCL and SCK pins of the boards together.

If i open the serial monitor of the master this is what i get:

> I2C Scanner Scanning... Unknown error at address 0x20 Unknown error at
> address 0x21 No I2C devices found
>
> Scanning... Unknown error at address 0x78 No I2C devices found
>
> Scanning... No I2C devices found
>
> Scanning... Unknown error at address 0x08 Unknown error at address
> 0x09 Unknown error at address 0x60 No I2C devices found
>
> Scanning... Unknown error at address 0x70 No I2C devices found

And so on.
Can someone explain me were I'm doing errors?

  [1]: https://www.aliexpress.com/item/GY-Attiny85-Digispark-kickstarter-Mini-USB-Development-Board-Module-Tiny85/32356300524.html?spm=2114.search0104.3.17.62253bd9WXTC3J&ws_ab_test=searchweb0_0,searchweb201602_1_10065_10068_319_317_10696_10084_453_10083_454_10618_10304_10307_10820_10821_537_10302_536_10902_10843_10059_10884_10887_321_322_10103,searchweb201603_59,ppcSwitch_0&algo_expid=7b44b0ad-ce27-4e20-b79a-b5c8487f54d5-2&algo_pvid=7b44b0ad-ce27-4e20-b79a-b5c8487f54d5&transAbTest=ae803_4

body:
Problem solved!

I've modified the code, this is the final one:

    #include <TinyWire.h>

    #define led_pin 1
    #define I2C_SLAVE_ADDR  0x11

    void setup() {
     // config led_pin as Output for driving an LED
     pinMode(led_pin, OUTPUT);

     // config TinyWire library for I2C slave functionality
     TinyWire.begin( I2C_SLAVE_ADDR );
     // sets callback for the event of a slave receive
     TinyWire.onReceive( onI2CReceive );
    }

    void loop() {

    }

    /*
    I2C Slave Receive Callback:
    Note that this function is called from an interrupt routine and shouldn't take long to execute
    */
    void onI2CReceive(int howMany){
     // loops, until all received bytes are read
     while(TinyWire.available()>0){
      // toggles the led everytime, when an 'a' is received
      if(TinyWire.read()=='a') digitalWrite(led_pin, !digitalRead(led_pin));
     }
    }

Like this the I2C scanner sees the board at the address 0x11.

The wirings are the following:

 - Arduino pin SCL to ATTiny85 pin SCL (P2)
 - Arduino pin SDA to ATTiny85 pinSDA  (P0)
 - Take care of wire to the same ground both the boards.


message:
Will a delay() function in a void SerialEvent() also stop the code that is running in the void loop() function?

This is about an Arduino Uno.

body:
This is the main function of the Arduino core:

    int main(void)
    {
     init();

     initVariant();

    #if defined(USBCON)
     USBDevice.attach();
    #endif

     setup();

     for (;;) {
      loop();
      if (serialEventRun) serialEventRun();
     }

     return 0;
    }

`serialEventRun()` runs the `serialEvent()` function, if it is assigned,
so yes, **a delay in serialEventRun will delay the loop**.


body:
In an Atmega328p, the Uno's processor, there is only 1 CPU; it can only do one thing at a time. If it is executing code in the SerialEvent() function, then by definition, it is *not* executing code in the loop() function or anywhere else.

There is a minor exception to this: interrupt service routines will run briefly when their respective interrupts occur. In fact, one way a delay() function can operate depends on timer updates that take place as interrupts. (The other way is by executing a loop whose execution time is accurately known, a specified number of times).

But interrupt service routines do one, very short, job, and return the CPU to whatever it was doing immediately before (delay() within the SerialEvent() function), so no other user code can be executed until the delay ends.


message:
Wait between UART frames

I have to reproduce a signal (of 6 UART frames) which have 950 µs delay between each of the frames. Than, a delay of 37ms at the end of those frames.

Everything going right except the delay between each frame...The baud rate is at 9600.

Here is my current code :

      Serial1.write(sw_binary_train_1);
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_2);
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_3);
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_4);
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_5);
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_6);
      delay(37);

body: set delayMicroseconds(1900) do a delay of 950µs between each frames...Strange but works !


body:
It's not strange at all.  Serial doesn't block while it sends.  When you call write that pushes the byte into the send buffer and that's all.  Then the code moves on to the next instruction, the delay(950) and during that time the serial data is actually being sent.  It takes about 1 millisecond for that to happen.

This solution works as long as the send buffer doesn't have anything else in it that's slowing you down and as long as you don't change the baud rate.  If either of those things happen then you need to recalculate that time.

A better solution would be:

      Serial1.write(sw_binary_train_1);
      Serial1.flush();
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_2);
      Serial1.flush();
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_3);
      Serial1.flush();
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_4);
      Serial1.flush();
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_5);
      Serial1.flush();
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_6);
      Serial1.flush();
      delay(37);

The flush blocks until the send buffer is empty again.  That way you don't have to account for that time and all you need the delay for is the time between transmissions.

Even better would be if those things were in an array so you didn't have to keep repeating yourself.  Anytime you catch yourself putting numbers on variable names what you really want is an array so that you can use those numbers in the program:

    for (int i=0; i<6; i++){
      Serial1.write(sw_binary_train[i]);
      Serial1.flush();
      delayMicroseconds(950);
    }
    delay(37)

looks much better.


message:
Specific formatting of floats and converting them to an array of chars

I have an oled display which can only display 4 digits + decimal point.
I need a way to format the number into 4 significant figures;
Then I need to convert that into an array of 5 chars (4 digits and one dp) before I can display them.

Not sure how to format to correct number of digits or how to convert into a char array. I searched a bit and printf seems to be the solution(?) but I've had no luck with it so far as it spits out all sorts of errors. if you know how to make it work, please can you provide a code snippet which compiles without errors? thanks.

body:
Normally `sprintf()` would be the solution - however the `sprintf()` in the AVR LIBC is a cutdown version with no floating point support.

Instead you have to use [`dtostrf()`](https://www.microchip.com/webdoc/AVRLibcReferenceManual/group__avr__stdlib_1ga060c998e77fb5fc0d3168b3ce8771d42.html) to get the job done:

    dtostrf(val, 6, 4, buffer);

The numbers there are the maximum width of the string (note: you need to take into account any minus sign in that value), and the number of decimal places (6,4 would give you room for "0.0000" but not "-0.0000"). Make sure your buffer is bigger by one byte than your text, since you have to have the trailing NULL character in there to terminate it.

Another (nasty) way would be to go via `String` (although I would never recommend using `String` for anything, ever):

    String s(val, 4);
    const char *buf = s.c_str(); // this points to the internal char buffer.


message:
How do you make a switch case run until another serial input is detected?

I am trying to create a Traffic Light Controller.
There are three modes to the controller:
Mode 1 - the traffic light operates RED-YELLOW-GREEN-YELLOW and should repeat
* (The other modes are not necessary apart from knowing the user can select the mode.)*

I want to loop the function of the mode until I receive an input from the serial monitor. If no input is detected, then it should continue with the current mode.
At the moment I am using **Serial.read()** at the start of the main loop function before my switch statement to select the mode. However, this needs an input, but I want the switch cases to loop until an input is received.

All help will be much appreciated.

body:
Use something like this (it is pseudo code so convert it to your sketch):

    enum EState { NORMAL, SPECIAL } _state; // States
    enum ENormalState { RED, YELLOW1, GREEN, YELLOW2 } _normalState; // State only valid when _state == NORMAL
    unsigned long _time; // _time only valid when _state == NORMAL

    void loop()
    {
       if ('serial input available')
       {
          if ('input == ...')
          {
             _state = NORMAL;
          }
          else if ('input == ...')
          {
             _state = SPECIAL;
          }
          ...
       }

       switch (_state)
       {
       case NORMAL:
           if (_time + ... > time())
           {
              // Change to next state
              switch (_normalState)
              {
              case RED:
                  _normalState = YELLOW1;
                  _time = time();
                  break;

              case YELLOW1:
                  _normalState = GREEN;
                  _time = time();
                  break;
              ...
              }

           setLight(_normalState); // Change the light according to the _normalState
           break;

       case SPECIAL:
           ...
           break;

       ...
       }
    }

Ideas to improve/explain:

- Try to make some specific functions for setting the light according to the current state
- You do not need a delay
- Split functions (like above, make a separate function for normal state, and specific state


body:
thankyou for your responses.
I managed to solve this myself by using a while loop to store the code inside each switch case, my working code is below, utilising **Serial.peek()** and by changing the input ending in the serial monitor to **no line ending**.
```
while ((Serial.peek() == -1)){
          regularMode(ledRed, ledYellow, ledGreen);
}
```
Serial.peek() gets the next item from the serial stack, if there is nothing there, it returns '-1' so i can check against that as shown above.


message:
GPS detecting stationary?

can someone please point me at some code snippets to detect when the GPS is stationary. I am currently using tinyGPS library and it is working fine, but my data-logger has thousands of stationary details I'd like to not bother logging. Currently I am using this,

    uint8_t speedZero() {
    uint8_t spd = gps.speed.mph();
      if (spd < 5) {
        return 0;
      } else {
        return spd;
      }
    }

But it is too granular at slow speeds, but the NEO-6M drifts a lot and 5mph standing still is not uncommon.

I have tried comparing Last Lat/Lon but not having any success as this Math is waaaay out of my skill-zone.

body:
I found this to get me started.

http://apexlogic.net/code-bank/arduino/serial-gps-find-distance-between-two-points/


message:
Normally-Open opto-coupler board

I'm looking for a Normally-Open optocoupler board for arduino. I need to control power of a device (DC 12v, 500mA).
I tried to use TLP281 board, which works, except that it inverts the output: device is powered when there is no control signal (i.e., it is Normally-Closed).

For this reason, the TLP281 board is not useful in my project.

This is picture and schematics for TLP281 board:

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

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

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

I need an optoisolator board which works analogous to normally open mechanical relay: when there is no signal, device must not be powered; and when there is signal, device must be powered.

*NOTE: workaround by inverting the control signal in microcontroller firmware is not permitted, as the device must not be powered when microcontroller is off*

  [1]: https://i.stack.imgur.com/0EZ8l.png
  [2]: https://i.stack.imgur.com/VY0Og.jpg
  [3]: https://i.stack.imgur.com/iE7wD.jpg

body:
I don't think there is a need for a specific "normally-open" opto-coupler. Same result can be easily achieved by using "normally-closed" opto-coupler and making a slightly modified "NOT" logic gate using three resistors and NPN transistor.

[![NOT gate design][1]][1]

 **1. When INPUT is LOW:**

Base of Q1 is shorted to ground through R1 so Q1 not letting the magic pixies go through. This makes OUTPUT show 5V and be in HIGH logic state.

 **2. When INPUT is HIGH:**

Base of Q1 is powered by voltage divider R/R1. R needs to be much lower than R1 to keep Q1 saturated. This makes Q1 to be passing current and setting OUTPUT to LOW state by creating a voltage divider R2/Q1(collector-emitter resistance) This means that value of R2 should be much higher then c-e resistance of Q1.

 **3. When INPUT is floating (microcontroller is turned off):**

Any voltage on INPUT caused by imperfections of the hardware, E-M noise induction, static electricity, etc. should be discharged to ground by resistors R+R1 keeping INPUT in LOW state. (This means that R+R1 cannot have to high value or the discharge speed might be to slow)

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


body:
For those, who are stumbling over this old thread and @igor-liferenko, since this board is still quite common:

This board definitely does *NOT* invert the inputs.

The comment of Igor Liferenko "tested it and I can say for sure that this board inverts the signal (on low input, there is power on output, on high input, there is no power on output)." is wrong. I don't know what he has tested, but both the schematics and tests show, that the board does not invert (or actually inverts twice -- once by the TLP281-4 itself and once by the following S8050-transistors).

So: low on input -> low on output; high on input -> high on output.


message:
Read from serial monitor and put it in a array of byte

I'm a new here and this is my first question.
I would like to read from serial monitor and stock the information in a array of bytes. then I want to print this array in serial monitor.
This is the code that I tried:

    byte A[6];

    void setup()
    {
    }

    void loop() {
      A[6] = Serial.read();
      Serial.write (A);
    }

body:
If you want to print it only, I would suggest not to store it. But if you want to do some calculations, you might store it.

The problem you make is you always store the value in the 6th element of the array A, however A only has elements A[0] to A[5], so A[6] is beyond the storage space, and results in crashes (sometimes) or at least unexpected behavior.

To fix it you have to store the value in the correct element of A, and for that you need an index variable. Since you can only store 6 values, after the 6th, start with the 0 and process it.

Like:

    byte arr[6];
    index arrIndex;

    void setup()
    {
       arrIndex = 0;
    }

    void loop() {
      // Read serial.
      arr[arrIndex] = Serial.read();

      // Increase counter
      arrIndex++;

      // If the maximum is read, print values and reset it.
      if (arrIndex == 6) {
         // Print the elements.
         for (index = 0; index < 6; index++)
         {
            Serial.write(A[index]);
         }

         // Restart counter.
         arrIndex = 0;
      }
    }

An improvement: instead of 6 everywhere, use a define:

    #define MAX_ELEMENTS 6


message:
Good quality sound using a microcontroller

I am a hobbyist. Doing some experiments with sound quality. I'll pin point my problem and requirements.

1. **Problem statement** :I want to play audio files ( recorded in human voice, not music files, just some plain human speech files)

2. **I have tried** : a project with an Arduino microcontroller and MicroSD card but audio quality was not at all good from the link below
https://www.instructables.com/id/Audio-Player-Using-Arduino-With-Micro-SD-Card/
https://circuitdigest.com/microcontroller-projects/arduino-audio-music-player
It just used an arduino UNO board, microSD using SPI, a speaker and an LM386 Audio Amplifier.

I read about the details and got to know that I need a DAC for better quality (as PWM cannot serve the purpose), and a speaker also. But there are a number of things available and I dont understand which one to buy and start a project.

Can you share the details of some micro-controller board with a DAC which suffice my purpose, memory to store audio files (or I can use a microSD card device), and a speaker project which I can follow and make one.
I am looking for a board based solution, after getting some results, I can go for separate micro-controller and DAC.

Thanks in advance.

body:
One would think that single channel for voice would be enough.  Remember the old Sprint commercials? "So quiet you can hear a pin drop", that was only single channel.  12 bits at 16 MHz for max 8 KHz bandwidth would be good.  Per Wikipedia "In telephony, the usable voice frequency band ranges from approximately 300 Hz to 3400 Hz. It is for this reason that the ultra low frequency band of the electromagnetic spectrum between 300 and 3000 Hz is also referred to as voice frequency, being the electromagnetic energy that represents acoustic energy at baseband. The bandwidth allocated for a single voice-frequency transmission channel is usually 4 kHz, including guard bands, allowing a sampling rate of 8 kHz to be used as the basis of the pulse code modulation system used for the digital PSTN. "

I think several folks, such as Adafruit.com, DFRobot.com, and others make cards with DAC outputs.  Or you could get a DAC only card from Gravitech.us

I started a project at Arduino.cc to sample 16 bits at 44.1KHz, store to SD card, then play it back later. I used external SPI ADC and DAC, and member fatlib16 there helped me to code it.  You can find it by searching "sample, record, playback later" and it should pull it up.


body:
Here is the schematic and breadboard layout I was using.
Coding can be found in this Arduino.cc thread

https://forum.arduino.cc/index.php?topic=180769.60

[![Analog Reference, ADC, DAC wiring][1]][1]

[![Layed out on breadboard before going to PCB][2]][2]

  [1]: https://i.stack.imgur.com/V4958.png
  [2]: https://i.stack.imgur.com/L7MxV.jpg


message:
How to combine two different sensor sketches to one complete sketch?

How to combine two different sensor sketches to one complete sketch for a complete circuit that attaches to one Arduino Uno?

**Sharp Dust Sensor**

    int measurePin = A0; // Connect dust sensor to Arduino A0 pin
    int ledPower = D8;   // Connect 3 led driver pins of dust sensor to Arduino D2

    int samplingTime = 280;
    int deltaTime = 40;
    int sleepTime = 9680;

    float voMeasured = 0;
    float calcVoltage = 0;
    float dustDensity = 0;

    void setup(){
      Serial.begin(9600);
      pinMode(ledPower,OUTPUT);
    }

    void loop(){
      digitalWrite(ledPower,LOW); // power on the LED
      delayMicroseconds(samplingTime);

      voMeasured = analogRead(measurePin); // read the dust value

      delayMicroseconds(deltaTime);
      digitalWrite(ledPower,HIGH); // turn the LED off
      delayMicroseconds(sleepTime);

      // 0 - 5V mapped to 0 - 1023 integer values
      // recover voltage
      calcVoltage = voMeasured * (5.0 / 1024.0);
      dustDensity = 0.17 * calcVoltage - 0.1;

      Serial.print("Raw Signal Value (0-1023): ");
      Serial.print(voMeasured);

      Serial.print(" - Voltage: ");
      Serial.print(calcVoltage);

      Serial.print(" - Dust Density: ");
      Serial.println(dustDensity); // unit: mg/m3

      delay(1000);
    }

**MQ-135 Sensor**

    int airquality = A2;
    void setup()
    {
      Serial.begin(9600);

    }
    void loop()
    {

      int sensorValue = analogRead(A2);
      Serial.print("Air Quality = ");
      Serial.print(sensorValue);

      Serial.print("*PPM");
      Serial.println();
      delay(1000);

    }

body:
There is no way of "automatically" combine two sketches into one. That's because resources of Arduino are very limited. For example UNO it has only 4 timers. If both of the sketches want to use same resource they will not work properly.

If you want to combine two sketches into one you have to write a new sketch that combines mechanisms of both sketches. It's not easy, because `delay` and `delayMicroseconds` are going to give you problems, but you should be able to do that using `micros()` and `millis()` plus some modular math.


body:
I will leave a simplified answer and I would recommend to read https://www.makeuseof.com/tag/getting-started-with-arduino-a-beginners-guide/ or similar to get a understanding of how to code.

An Arduino sketch has a structure.

1. Initialising values
2. A `void setup()` this code only run once the MCU is started
3. A `void loop()` and this code runs continuously.

So to merge two sketches you need to combine the code that is in the same sections and of course avoid duplicate code and ensure that you have unique variable names

**Sharp Dust Sensor**

    int measurePin = A0; // Connect dust sensor to Arduino A0 pin
    int ledPower = D8;   // Connect 3 led driver pins of dust sensor to Arduino D2

    void setup(){
      Serial.begin(9600);
      pinMode(ledPower,OUTPUT);
    }

**MQ-135 Sensor**

    int airquality = A2;
    void setup()
    {
      Serial.begin(9600);
    }

**Combined code**

    int measurePin = A0; // Connect dust sensor to Arduino A0 pin
    int ledPower = D8;   // Connect 3 led driver pins of dust sensor to Arduino D2
    int airquality = A2;

    void setup(){
      Serial.begin(9600);
      pinMode(ledPower,OUTPUT);
    }


message:
Sending data to UART using Atmel Studio with Attiny84

I want to send data to TFDI. It can be `hello world` or any value of variable. But I can't do. I haven't found example code on the internet. Some examples doesn't work. I am using Atmel Studio.

body:
The ATTiny84 does not have a hardware UART peripheral. Instead it has a USI (universal serial interface), which does not have all the capabilities needed for UART ("serial") interface.

You don't need to burn the Arduino bootloader to use libraries, that were written for the Arduino IDE. You only might need some of the definitions, which you can get by including the arduino.h file.

I think your best bet is to use existing libraries, like the SoftwareSerial library. There are also lots more libraries, that provide bit banged serial interfaces. You can also get them running in Atmel Studio, by including the source files. This is the easy way.

If you want to go the hard way, you might be able to program a hybrid software/hardware UART interface by utilizing some functions of the USI. In a search I found [this site](https://becomingmaker.com/usi-serial-uart-attiny85/), which is about implementing UART with the USI. They also link to Atmel's Application Note  AVR307, which is a good source for understanding this. From this starting point you might also find a ready to go implementation for the USI. If not, you will have to do the work yourself.


message:
Send files via network

I want to send a file from an Arduino to the server or another Arduino.

I wrote a code that's open the file then write the content of the text on an array and then send it.

That would work if the data is small, but when i try to send, .wav it will takes lots of time if i do it that why (storing each byte in array).
I want to send the whole file at on time.
Is there a way or a library helps ?

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

    const int push1 = 2;

    File myFile;
    char a[400];
    int c= 0;

    // network parameters
    byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0x05, 0x02 };  // ethernet interface MAC address
    IPAddress localIp(10,131,41,72);    // local ip address
    IPAddress destIp(10,131,41,74);      // destination ip address
    unsigned int port = 9631;               // destination port

    // EthernetUDP to send and receive messages.
    EthernetUDP Udp;

    // timing

    // setup the arduino and shields
    void setup() {

        pinMode(push1, INPUT);

      //Initialize serial and wait for port to open:
      Serial.begin(9600); // 19200
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

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

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

      // start ethernet and udp
      Ethernet.begin(mac, localIp);   // static ip version
      //if(Ethernet.begin(mac) == 0) {     // dhcp version
      // report failure to obtain network parameters
      // Serial.println("DHCP error");

      // no point in carrying on, loop indefinitely:
      // while(true)
      // ;
      //}

      // open UDP port
      Udp.begin(port);

      // show the local ip address (useful for dhcp)
      Serial.print("Local IP: ");
      Serial.println(Ethernet.localIP());

      // initialize previous millis variables

    }

    // do tasks
    void loop() {

    if(digitalRead(push1) == LOW){

       myFile = SD.open("R.wav" , FILE_READ);

      if (myFile) {
        // read from the file until there's nothing else in it:
        Serial.println("i will send now");
        while (myFile.available()) {
            a[i] = myFile.read();
            i++;
            }
          Udp.beginPacket(destIp, port);
         Udp.write(a);
          Udp.endPacket();
          Serial.println("Sending UDP message");
          Serial.println();
        }
        // close the file:
        myFile.close();
      } else {
       // if the file didn't open, print an error:
        Serial.println("error opening test.txt");
      }  } }

body:
You may try:

    Serial.println("Sending UDP message");
    Udp.beginPacket(destIp, port);
    while (myFile.available()) {
      Udp.write(a);
    }
    Udp.endPacket();
    Serial.println("Message sent!");

Or send the message part by part (for example 100bytes or [500bytes][1] at a time)

Though, what makes you think that Arduino would be a platform that can rapidly send large files over network?
Potentially you are better off with an Raspberry Pi.

  [1]: https://stackoverflow.com/questions/1098897/what-is-the-largest-safe-udp-packet-size-on-the-internet


message:
Having trouble with motor shield running off external power source

I apologize if I don't immediately give important info, I'm very new to arduino's/circuity of any kind.  I'll try to include as much info as possible.

Some preface:
I'm currently working on a project that generates electricity using TEG's (Thermoelectric generator). The setup I currently have is able to output upwards of 9V. The motor I'm using is able to run when directly connected to the TEG wires, sp they produce enough electricity to work. Due to the nature of the project, a stopping mechanism is being used via a photoresistor and an LED. Essentially when the light signal picked up by the photoresistor is low  enough,  power is cut to the motor.

So up until recently, the motor and the Arduino board/motor shield (Arduino UNO, Arduino Motor Shield Rev3) were being run using a 9V battery. Everything worked correctly, the motor would start when needed and stop when needed. Once I switched to the TEG's the set up stopped working (motor stopped running). What is weird is that if I connect a voltmeter to channel 1 of the motor shield, I read 6V-7V (some voltage drop but not drastic) when the LED was on and 0 when the led was off. So everything seemed to still be working, but the motor itself just won't actually run. In fact, when the LED is on, it makes a very faint noise for a second but doesn't run.

The only thing I can think of is that the current being produced by the TEG's is only enough to power the motor when directly connected, but when wired indirectly through the board thus powering the board, it no longer has enough amperage.

I included the code I wrote for it, which worked fine with a 9V battery powering the motor/board.

    const int sensorPin = A5;
    const int ledPin = 5;
    int lightLevel;

    void setup(){
      Serial.begin(9600);
      pinMode(12,OUTPUT);
      pinMode(9,OUTPUT);
      pinMode(ledPin, OUTPUT);
    }

    void loop(){
      lightLevel = analogRead(sensorPin);
      lightLevel = constrain(lightLevel, 0, 800);
      Serial.println(lightLevel);

      if(lightLevel < 200){
        digitalWrite(9,LOW);
        digitalWrite(12,HIGH);
        analogWrite(3,255);
      }
      if(lightLevel > 200){
        digitalWrite(9,HIGH);
        analogWrite(3,0);}
    }

body:
Try a decoupling capacitor acorss your TEG : 100µF/35v (+ at the +).
This will avoid micro power drops...
Verify that y hardware driving motor works below 9V.


message:
Fast data logging

I want to store noise data (basically from A0) from an Arduino Uno to an SD card with faster writing speed, preferably by using 512 data together and the write it at once. What should be the code?

body:
1. Read the values into an array big enough to store them
2. Write the array with the `write(const uint8_t *buffer, size_t size)` method.

Each `write` then gives you a block of binary data (512 values, 1024 bytes if they're 16-bit integers) written to the SD card. What you do with it then is up to you.

Note: an Arduino UNO only has 2kB of memory. If you have 512 integers that's half your memory gone. The SD card library needs another 512 bytes or more for its internal sector buffer. That's another 25% of your memory used. Already you're up to 75% of your memory gone.


message:
How to chose softserial library use on Arduino project?

I want to do a project that has multiple Arduino communication through UART, that project project one of limit is using Arduino Nano (small and cheap). I need to set 4 serial port instance on Nano to connect other nano to receive and write, I searched about serial port of nano that only have one hardware serial port, so after I found the many softserial library such as pre-bulite softserial and altsoftserial NeoSWSerial and NeoHWSerial and NeoICSerial.
Because library too libraries i don't know which one can help complete my project.

body:
I think your problem is that you need 4 serial ports.

With software serial that's just not going to happen:

* SoftwareSerial can only receive on **one** serial port at any given time.
* AltSoftSerial is limited to specific pins, and only one instance because there is only one set of pins
* NeoSWSerial is kind of between the two. More efficient than SoftwareSerial, but still (as far as I can tell) limited to one instance (it uses a timer interrupt to drive the communication, so can use any pins)

If you need communication between lots of devices over serial then you will either need devices with more hardware serial ports (Arduino Mega, for example), or implement a multi-drop bus system (like RS-485) which only needs one serial port to communicate with many devices. Extra external hardware is required though.


message:
Path relater errors on compilation in Arduino IDE 1.8.5 under Windows XP

For the XP under the Russian locale I'm getting the strange output when trying to compile Marlin project for Anycoubic 3d printer according to instruction https://3dtoday.ru/blogs/trialon/marlin119-for-anycubic-kossel-linear-plus

avr-g++: error: C:\DOCUME~1\ИЖИ: No such file or directory

avr-g++: error: Ь~1\LOCALS~1\Temp\arduino_build_153827\sketch\Marlin.ino.cpp: No such file or directory

avr-g++: error: Ь~1\LOCALS~1\Temp\arduino_build_153827\preproc\ctags_target_for_gcc_minus_e.cpp: No such file or directory

avr-g++: warning: '-x c++' after last input file has no effect

avr-g++: fatal error: no input files

compilation terminated.

exit status 1
Ошибка компиляции для платы Arduino/Genuino Mega or Mega 2560.

body: I have realized that the root cause was the windows user with the Cyrillic name. So creating a new user wiht base Latin name and running Arduino IDE from it helped


message:
RGB and Potentiometer

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

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

How do I start this program???

    int x=0;
    int P1=A5;
    int P2=A4;
    int P3=A3;
    int R1=3;
    int G1=5;
    int B1=6;
    int R2=9;
    int G2=10;
    int B2=11;
    int sValue1;
    int sValue2;
    int sValue3;
    int oValue1;
    int oValue2;
    int oValue3;
    int timer(1000);

    void setup() {
     pinMode(P1,INPUT);
     pinMode(P2,INPUT);
     pinMode(P3,INPUT);
     pinMode(R1,OUTPUT);
     pinMode(G1,OUTPUT);
     pinMode(B1,OUTPUT);
     pinMode(R2,OUTPUT);
     pinMode(G2,OUTPUT);
     pinMode(B2,OUTPUT);

    }

    void loop() {

    sValue1=analogRead(P1);
    sValue2=analogRead(P2);
    sValue3=analogRead(P3);

    oValue1=map(sValue1,0,1023,0,255);
    oValue2=map(sValue2,0,1023,0,255);
    oValue3=map(sValue3,0,1023,0,255);

    if ((sValue1=0)&&(sValue2=0)&&(sValue3=0));
    {
      setColor1(0,255,255);
      delay(timer);
      setColor2(255,0,0);
    }
    }

    void setColor1(int red1, int green1, int blue1){
      {
        analogWrite(R1,red1);
        analogWrite(G1,green1);
        analogWrite(B1,blue1);
      }
    }

    void setColor2(int red2, int green2, int blue2){
      {
        analogWrite(R2,red2);
        analogWrite(G2,green2);
        analogWrite(B2,blue2);

      }
    }

body:
1. Install [Arduino IDE](https://www.arduino.cc/en/Main/Software)
1. New sketch
1. Paste code
1. Connect the Arduino board to your PC
1. Upload sketch


body:
> Also i get Error compiling from this program

Obviously B1 is already defined as something, like your A5, A4 and A3 are.<br>
You will very likely have the same issue with B2.


body:
Arduino has created binary numbers: B1, B101, B00111, and so on.

It is documented in the reference page "[Integer Constants][1]".
The "B1" is defined in "[binary.h][2]".

They should not have done that. Not a single C++ software engineer thinks that it was a good addition. The C++ language is perfectly fine for creating binary values: 0b1, 0b101, 0b00111, and so on.

It is not your fault, you can blame Arduino. Because of this, you should **never** create variables with the name: B1, B101, B00111, and so on.

  [1]: https://www.arduino.cc/reference/en/language/variables/constants/integerconstants/
  [2]: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/binary.h#L31


message:
Can't flash ESP8266 anymore (NodeMCU)

So I've been happily making away with these nodeMCU boards now for a while but I came across a strange issue when updating some code on my board.The problem was that I couldn't flash anymore with Arduino's IDE (OR the NodeFlasher tool)

The error I was getting in Arduino's IDE was:

    warning: espcomm_send_command: didn't receive command response
    warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed

I tried flashing over all the memory with the flash tool but that didn't work, I also tried connecting D3 to 3.3v output, that did nothing. I've also tried holding the flash button down while flashing without any effect.

body:
The fix ended up being to use a 220ohm resistor between D3 and GND (It has been pointed out, though I haven't tested it, that just wiring D3 to ground on startup should have the same effect). Then unplugging the USB cable, plugging it back in, then flashing the blink program to test. That got it going. I tried a 10kohm resistor too per some documentation I read but that didn't end up working. Wanted to post in case someone else stumbled on this issue.

**Source**

[GitHub Issue][1]

**Helpful Articles:**

[ESP8266 bootloader modes][2]

[NodeMCU Pinout][3]

  [1]: https://github.com/esp8266/Arduino/issues/2428#issuecomment-413730207
  [2]: https://zoetrope.io/tech-blog/esp8266-bootloader-modes-and-gpio-state-startup
  [3]: https://pradeepsinghblog.files.wordpress.com/2016/04/nodemcu_pins.png?w=616


message:
Getting different values inside vs. outside a function while using global array

function `splitter` is designed to get a string of parameters and create a an array of parameters. If only part of parameters were given, the rest of them will get default values.

for example : input string `1,2,3,4` would fill `parameters` array with values `{"1","2","3","4"}`, but  if input string is `1,2`, `parameters={"1","2","20","0"}` while `parameters[3]` and `parameters[2]` were given its default values.

**BUT**

when assigning default values, inside `splitter` the correct values are stored in `parameters` but when using `print_output` function to show `parameters` values - different values are shown.

in output supplied, when input is `1,2`,  default values should be pasted, to `parameters[2]`, and `parameters[3]` , while input is `1,2,3,4` no need to use defaults.

**OUTPUT:**

    Running string 1,2
    param_2 was set to default value:20
    param_3 was set to default value:0
    output:
    1
    2
    0
    0
    Running string 1,2,3,4
    output:
    1
    2
    3
    4

**CODE:**

    #define PARAM_AMOUNT 4
    #define COLOR 1
    #define LED_DELAY 20
    #define BRIGHTNESS  50
    #define LED_DIRECTION 0

    char *parameters[PARAM_AMOUNT] = {"0", "0", "0", "0"};
    int param_def[] = {COLOR, BRIGHTNESS, LED_DELAY, LED_DIRECTION};

    void setup() {
      Serial.begin(9600);
      Serial.println("Running string 1,2");
      splitter("1,2");
      print_output();

      Serial.println("Running string 1,2,3,4");
      splitter("1,2,3,4");
      print_output();
    }

    void splitter(char *inputstr) {
      char * pch;
      int i = 0;

      pch = strtok (inputstr, " ,.-");
      while (pch != NULL)
      {
        parameters[i] = pch;
        pch = strtok (NULL, " ,.-");
        i++;
      }

      //  update default values
      for (int n = i ; n <= PARAM_AMOUNT - 1; n++) {
        sprintf(parameters[n], "%d", param_def[n]);
        Serial.print("param_");
        Serial.print(n);
        Serial.print(" was set to default value:");
        Serial.println(parameters[n]);
        delay(50);
      }
    }

    void print_output() {
      Serial.println("output:");
      for (int n = 0 ; n <= PARAM_AMOUNT - 1; n++) {
        Serial.println(parameters[n]);
      }
    }

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

body:
It is not a good practice to reserve memory for a string with a constant string. Allocate an array of char arrays with:
```
char parameters[PARAM_AMOUNT][PARAM_LEN];
```

Now with "0" you allocate 2 bytes for each string. The '0' and a terminating 0.

Then in `splitter` function you write 3 bytes into one of the parameters with value "20". This writes outside of the 2 bytes of memory reserved for the string.

`strcpy(parameters[i], pch);` will copy the token returned by `strtok` into your array. `pch` points into `inputstr` and the delimiters in `inputstr` are replaced by 'strtok' with zeros


message:
Dual power supply using Arduino uno and nano

I had a very vague thought. I was wondering if I could I create a dual power supply using an Arduino uno and a nano. Can the  ground terminals of both the boards be shorted and the 5 volt terminals be used as +5v and -5v . Is this possible? Would it damage the board??

body:
No, because both 5V terminals are +5V.

If both boards are powered by completely isolated power supplies then you could connect the +5V of one to GND on the other. One will then have all its signals and logic negative to your ground level, but normal compared to its own ground level. Managing it though and keeping things separate (no shared ground between two sets of peripherals, etc), would be tricky. And the moment you plug one into your computer the whole lot could go up in smoke.


message:
Stop led from blinking when running

I don't get it. I'm new to Arduino, but not to programming. I don't understand why led pin 13 keeps blinking.

here is my code..

    #include <Servo.h>

    // X servo angle will stay in [min_x, max_x] range
    // Y servo angle will stay in [min_y, max_y] range
    // to be adjusted to the size of your living room

    float min_x = 5;
    float max_x = 50;
    float min_y = 5;
    float max_y = 35;
    int min_freeze = 200;
    int max_freeze = 3000;
    float minimal_movement = 5;

    // finding center of square for starting point
    int random_delay;
    float x_position = min_x + (max_x - min_x)/2;
    float y_position = min_y + (max_y - min_y)/2;
    float x_old_position = x_position;
    float y_old_position = y_position;
    float x_new_position;
    float y_new_position;
    float x_speed;
    float y_speed;
    int movement_time;

    // Instantiating two servos
    Servo x_servo;
    Servo y_servo;
    int pos = 0;

    void setup() {
      y_servo.attach(6);  // attaches the y servo on pin 6 to the servo object
      x_servo.attach(9);  // attaches the x servo on pin 9 to the servo object
      pinMode (13, OUTPUT);
      digitalWrite (13, HIGH);  // switch on  the laser

      //Place the servos in the center at the beginning
      y_servo.write(y_position);
      x_servo.write(x_position);

    }

    void loop() {
      movement_time = random(10,40);
      random_delay = random(min_freeze, max_freeze);
      x_new_position = random(min_x+minimal_movement, max_x-minimal_movement);
      y_new_position = random(min_y+minimal_movement, max_y-minimal_movement);

      if( (y_new_position > y_old_position) && (abs(y_new_position - y_old_position) < 5 )) {
        y_new_position = y_new_position + minimal_movement;
      }  else if ( (y_new_position < y_old_position) && (abs(y_new_position - y_old_position) < 5 )) {
        y_new_position = y_new_position - minimal_movement;
      }

      if( (x_new_position > x_old_position) && (abs(x_new_position - x_old_position) < 5 )) {
        x_new_position = x_new_position + minimal_movement;
      }  else if ( (x_new_position < x_old_position) && (abs(x_new_position - x_old_position) < 5 )) {
        x_new_position = x_new_position - minimal_movement;
      }

      x_speed = (x_new_position - x_old_position)/movement_time;
      y_speed = (y_new_position - y_old_position)/movement_time;
      for (pos = 0; pos < movement_time; pos += 1) {
          x_position = x_position + x_speed;
          y_position = y_position + y_speed;
          x_servo.write(x_position);
          y_servo.write(y_position);
        delay(10);
      }
      x_old_position = x_new_position;
      y_old_position = y_new_position;
      delay(random_delay);

    }

Nowhere in this sketch, the line "digitalWrite (13, LOW);" is contained, yet I am unable to keep the LED on solid without blinking when the Arduino is looping. I've other people do it, with this code, I don't get what I'm missing!

Windows 7 64bit, Arduino Uno board, Arduino 1.8.9 program

body:
I tried your sketch on an Arduino Uno, with no servos connected, and the LED on pin 13 did not blink.

DataFiddler makes a good point in their comment. To be sure you are actually uploading the sketch, try uploading the `Blink` sketch that comes with the IDE. Change the delays from 1000ms to 200ms then upload it. The difference in flash rates should confirm or deny the ability to successful upload sketches.

You don't say which servos you are using, so I'll assume they are SG90. I'm not sure if the data sheet for every SG90 servo is the same, but if you [look at this one][1], SG90 Specifications, you'll see the "stall current" can be between 570mA and 730mA, **each**. If you are powering them from the Uno, it can't supply that much current. Another limiting factor is the computer's USB maximum current output, (if you are powering the Uno with a USB port). FWIW, my computer can only provide 500mA per USB.

I would suggest powering the servos with a separate power supply, then see what happens.

  [1]: https://arduino.stackexchange.com/questions/49727/servo-causes-disconnection/49755#49755


message:
Why Smart Plugs don't require setting port forwarding on router and how to accomplish this with NodeMCU (ESP8266)

I have a NodeMCU (ESP8266) board that I use to control some devices over the internet. To be able to access it I have to enable port forwarding on my router and set the port manually like in the image below:

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

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

But with Smart Plugs (that use a cloud based app) I don't have to set up anything on my router. I am only required to type my Wi-Fi password. So my question is how Smart Plugs are accessed over the router (why they don't need manual port forwarding setting), and how to apply this to my NodeMCU so I don't have to set port forwarding manually.

body:
Port forwarding is required to allow a device outside your router to access a device inside a router that performs NAT (Network Address Translation).

When a NodeMCU is acting as a simple server to respond to requests, it is inside your network, and so the port-forwarding is required so that your phone or computer on the Outside can access it.

However, for the cloud-based "smart" devices, it is different. The smart device opens a connection from itself to a server (the cloud) outside your network. In this case, the router understands that a new two-way connection is created between the cloud server and your smart device.

The only communication to your smart device is from the cloud server to the smart device. If you have an app on your mobile device or computer, that app or website only accesses the cloud server, when then passes the instruction on to your smart device. Reverse direction for status info from the smart device to your app, etc.

These smart devices rely on the infrastructure of their creators to continue to work. There are no LAN-to-LAN connections from the client to the device. Everything goes through the Internet to the remote cloud server, and back.

Many home routers support a protocol called uPNP, that allows a device inside the network to request port forwarding to itself. Some routers require this to be explicitly enabled, because it's a security risk to allow any device to be able to open holes in your firewall/router.

To have your NodeMCU device do this, look for libraries for ESP8266 that implement uPNP. I did a quick search and found https://github.com/ofekp/TinyUPnP though I cannot vouch for it's effectiveness or safety.


message:
RGBs and Potentiometers

I think my if statement can't be read here in my program. The RGBs should light up and change color when the potentiometer is turned but instead the RGBs just light up immediately and change color simultaneously. How do I fix this?

    int POT1=A0;
    int POT2=A1;
    int POT3=A2;
    int Red1=9;
    int Green1=10;
    int Blue1=11;
    int Red2=3;
    int Green2=5;
    int Blue2=6;
    int sValue1=0;
    int sValue2=0;
    int sValue3=0;
    int oValue1=0;
    int oValue2=0;
    int oValue3=0;
    int value1=0;
    int value2=0;
    int value3=0;
    int timer(250);

    void setup() {
     Serial.begin(9600);
     pinMode(Red1,OUTPUT);
     pinMode(Green1,OUTPUT);
     pinMode(Blue1,OUTPUT);
     pinMode(Red2,OUTPUT);
     pinMode(Green2,OUTPUT);
     pinMode(Blue2,OUTPUT);

    }

    void loop() {

    sValue1=analogRead(POT1);
    sValue2=analogRead(POT2);
    sValue3=analogRead(POT3);

    oValue1=map(sValue1,0,1023,0,255);
    oValue2=map(sValue2,0,1023,0,255);
    oValue3=map(sValue3,0,1023,0,255);

    if ((sValue1<=127)&&(sValue2<=127)&&(sValue3<=127));
    {
      setColor1(0,255,255); //red
      setColor2(255,255,0); //blue
      delay(timer);
      value1=0;
      value2=0;
      value3=0;

    }

    if ((sValue1<=127)&&(sValue2<=127)&&(sValue3>127));
    {
      setColor1(255,255,0); //blue
      delay(timer);
      setColor2(255,0,255); //green
      delay(timer);
      value1=0;
      value2=0;
      value3=1;
    }

    if ((sValue1<=127)&&(sValue2>127)&&(sValue3<=127));
    {
      setColor1(255,0,255); //green
      delay(timer);
      setColor2(0,255,255); //red
      delay(timer);
      value1=0;
      value2=1;
      value3=0;
    }

    if ((sValue1<=127)&&(sValue2>127)&&(sValue3>127));
    {
      setColor1(0,255,255); //red
      delay(timer);
      setColor2(255,0,255); //green
      delay(timer);
      value1=0;
      value2=1;
      value3=1;
    }

    Serial.print("POT 1=");
    Serial.print(value1);
    Serial.print("\t POT 2=");
    Serial.print(value2);
    Serial.print("\t POT 3=");
    Serial.print(value3);

    if ((value1==0)&&(value2==0)&&(value3==0))
    {
     Serial.print("\t RGB1=");
     Serial.print("RED");
     Serial.print("\t RGB2=");
     Serial.print("BLUE");
    }

    else if ((value1==0)&&(value2==0)&&(value3==1))
    {
      Serial.print("\t RGB1=");
      Serial.print("BLUE");
      Serial.print("\t RGB2=");
      Serial.println("GREEN");
      Serial.println(" ");
    }

    else if ((value1==0)&&(value2==1)&&(value3==0))
    {
      Serial.print("\t RGB1=");
      Serial.print("GREEN");
      Serial.print("\t RGB2=");
      Serial.println("RED");
      Serial.println(" ");
    }

    else if ((value1==0)&&(value2==1)&&(value3==1))
    {
      Serial.print("\t RGB1=");
      Serial.print("RED");
      Serial.print("\t RGB2=");
      Serial.println("GREEN");
      Serial.println(" ");
    }

    }

    void setColor1(int red1, int green1, int blue1){
      {
        analogWrite(Red1,red1);
        analogWrite(Green1,green1);
        analogWrite(Blue1,blue1);
      }
    }

    void setColor2(int red2, int green2, int blue2){
      {
        analogWrite(Red2,red2);
        analogWrite(Green2,green2);
        analogWrite(Blue2,blue2);

      }
    }

body:
I haven't traced through your if statement logic in detail to see what you are trying to do, BECAUSE I found that you have statements like this:

    //            Get rid of this semicolon in every if statement.
    //            |
    //            V
    if (condition); {
        //        ^
        //        |

        //Code that will always be executed
    }

You should **NOT** have a semicolon after an if statement like that. That says "if (condition) then do nothing" (A semicolon creates a blank "do-nothing" statement that becomes the code that is executed if the if statement is true. Then the code in the braces gets executed every time.)

It is parsed as:

    if (condition) <empty_statement;>

    {
        code that always executes
    }

That is one of the hidden "nasties" of C and it's close cousins like C++, Java, and Objective-C. Another nasty is typing:

    if (a=b)

...when you mean `if (a==b)`. (The first version puts the value of b into a, and then evaluates b as a boolean. If it's 0, the if statement is treated as false. If it's non-zero, the if statement is evaluated as true.

Another one is the fall-through cases in C `switch` statements. If you forget to add a `break` statement at the end of each case it falls through to the next case.


message:
Problems with serial communication from Arduino to ESP8266

I've been trying to get an Arduino and ESP8266 to communicate with each other over serial. The ESP8266 uses the `Serial` class for communications, while the Arduino uses `SoftwareSerial`.

The problem is that when I try to send data from the Arduino to the ESP8266,  only the first character of the string sent gets received by the ESP8266. For example, if I send a string "leather", the ESP8266 only receives an 'l'. Both devices are operating at 38400 baud, although I have tried 9600 baud with similar results (apparently `SoftwareSerial` is more reliable at lower baud rates).

Here is the relevant code that's running on both devices:

Arduino code:

    #include <stdlib.h>
    #include <SoftwareSerial.h>

    #define COMMAND_TILT                'c'
    #define SOFTWARE_SERIAL_BAUD_RATE   38400
    #define ESP_RX                      8
    #define ESP_TX                      9

    SoftwareSerial esp(ESP_RX, ESP_TX);

    void setup()
    {
        ...
        esp.begin(SOFTWARE_SERIAL_BAUD_RATE);
        ...
    }

    void loop()
    {
       if (esp.available() > 0) {
            String data;
            while (esp.available() > 0) {
                data += (char) esp.read();
            }

            char command = data.charAt(0);
            data.remove(0, 1);
            int value = data.toInt();
            char buf[STR_BUF_LEN];

            switch (command) {
                 case COMMAND_TILT:
                     ...
                     sprintf(buf, "%c%d", COMMAND_TILT, value);
                     esp.write(buf);
                     break;
                 ...
            }
        }

        delay(100);
    }

    ...

ESP8266 code:

    #define SERIAL_BAUD_RATE 38400

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

    void loop()
    {
        ...

        if (Serial.available() > 0) {
            String data;
            while (Serial.available() > 0) {
                data += (char) Serial.read();
            }

            char command = data.charAt(0);
            data.remove(0, 1);

            // problem: now, data.c_str() is blank when it should contain an integer in string format

            ...

            delay(100);
        }
    }

    ...

If it helps to know, I'm running an MQTT client on the ESP8266 and controlling some steppers and relays on the Arduino.

body: The cause of the issue was that the ESP was reading `char`s too quickly, meaning that it would give up before the next `char` could be sent from the Arduino. To fix the issue I simply added a 10 ms delay between each `Serial.read()` call on the ESP.


message:
arduino is skipping the if statement

Hi guys I am new to this language and i just tested the code to control a servo motor
Can anybody help me please ? here is the code

    void setup() {

      servo_test.attach(3);
      pinMode(9, INPUT);

    }

    void loop() {

     if ( digitalRead (9 == HIGH)) {

       for(angle = 0; angle < 180; angle += 5)    to 180 degrees
      {
        servo_test.write(angle);
        delay(5);
      }

      delay(4000);
      for(angle = 180; angle>=1; angle-=5)      to 0 degrees
      {
        servo_test.write(angle);               specified angle
        delay(5);
      }

        delay(4000);
    }

    }

It is just like the arduino completely ignore the if statement and start the loop wheter pin 9 is in high or low state  even if  i wire it directly to gnd

body:
In your code this line:

     if ( digitalRead (9 == HIGH)) {

...is likely passing the function "digitalRead()" the value zero as "9 == HIGH" is likely false.

Likely what you want to do is check if the value returned by the function "digitalRead()" is high.  Try:

     if ( digitalRead (9) == HIGH) {

...instead.


message:
I2C potentiometer mess

I bought a few MCP4651 dual 8 bit I2C pots for a project. After browsing the arduino libraries and finding nothing,"No big deal" I thought to myself ... I've already written I2C libraries for other parts that were much more complicated! (e.g: ADS1219 24 bit ADC)! so just load up the datasheet and watch the memory maps and commands! ok, there are some stuff on page 49 which seem useful! oh boy was I ever wrong! this data sheet looks like nightmare! the worst documentation for any I2C device I've seen so far. The commands I wrote based on that did absolutely nothing!

I found a code for controlling an I2C pot in one of the arduino examples which is something like this:

    #include <Wire.h>

    void setup() {
      Wire.begin(); // join i2c bus (address optional for master)
    }

    byte val = 0;

    void loop() {
      Wire.beginTransmission(44); // transmit to device #44 (0x2c)
      // device address is specified in datasheet
      Wire.write(byte(0x00));            // sends instruction byte
      Wire.write(val);             // sends potentiometer value byte
      Wire.endTransmission();     // stop transmitting

      val++;        // increment value
      if (val == 64) { // if reached 64th position (max)
        val = 0;    // start over from lowest value
      }
      delay(500);
    }

I decided to just try it and see what happens (changed the address to the correct value) and crazy enough it actually worked! so I hacked this piece of code to get the first pot to work!

    void setPot0(int n){
      if (n>256) n=256;
      if (n<0) n=0;
      Wire.beginTransmission(address);
      if (n<256){
        Wire.write(0x00);
        Wire.write(n);
      } else{
        Wire.write(0x01);
        Wire.write(0);
      }
      Wire.endTransmission();
    }
and somehow this works! I still can't find this pattern in any of the pages on datasheet, but hey! it works so I'm not gonna complain about that?
I still haven't managed to make the pot1 to work, only pot0 ... if you can make sense of how the commands and data bytes should be like, please help me. It's so much more clear in T.I datasheets; you just use the command to write to the register you want and they detail what each register does:
[![enter image description here][1]][1]
[![enter image description here][2]][2]

Edit: here is a link to the datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/22096b.pdf

  [1]: https://i.stack.imgur.com/Ss0he.jpg
  [2]: https://i.stack.imgur.com/c8GJw.jpg

body:
The registers are listed in table 4-1. Clearly enough.

The command byte format is shown in chapter 6. That command byte includes the operation and the register number, as well as upper bits for registers that expect more than 8 bits of data.

Two bytes are needed to set a register.  The first 4 bits are the register number (0000 for wiper 0, 0001 for wiper 1, and 0100 for the TCON register).  The next two bits are the operation as shown in figure 7-1. 00 for a simple write. The next two bits are the upper 2 bits of the data.  Following that are the lower 8 bits of data.

So to write a pot 0 value of 0x23 you would write:

    0x00 0x23

To write a pot 1 value of 0x65 you would write:

    0x10 0x65

To write a pot 1 value of 0x13D you would write:

    0x11 0x3D

You can make a simpler function to wrap it for you:

    void writePot(uint8_t address, uint8_t pot, uint16_t val) {
        Wire.beginTransmission(address);
        Wire.write((pot & 3) << 4 | ((val >> 8) & 3));
        Wire.write(val & 0xFF);
        Wire.endTransmission();
    }


message:
Quadcopter oscillation using PID

I am building an Arduino based flight controller for a quadcopter and have got it flying but it is not performing how I want it to. The drone is flying but when I release the sticks the drone does  not stay perfectly still. There is some random and small oscillations that occur when it is just hovering.

Right now I am using a single PID controller for each axis though functions like this.

    dt=0.005;
 error = *in - *set;

 P = (error * kp);
 I = I + (error * ki)*dt;
 D_M = ((*in - in1)*kd)/dt;
 D_E = ((error - error1)*kd)/dt;
 D=D_M*(1-jerk) + D_E*(jerk);

 I = constrain(I, LOWER_BOUND*0.75, UPPER_BOUND*0.75);
 in1 = *in;
 error1 = error;
 pid = P + I + D;

 pid = constrain(pid, LOWER_BOUND, UPPER_BOUND);
 *out = pid;

The error is the Euler angle and the setpoint is the angle I want it to go to.

I then output the PID controller values to the motors using the Arudino Servo library.

      motor1 = throttle;
      motor2 = throttle;
      motor3 = throttle;
      motor4 = throttle;

      motor1 += rollOUT;
      motor2 += rollOUT;
      motor3 -= rollOUT;
      motor4 -= rollOUT;

      motor1 -= pitchOUT;
      motor2 += pitchOUT;
      motor3 -= pitchOUT;
      motor4 += pitchOUT;

      motor1 += yawOUT;
      motor2 -= yawOUT;
      motor3 -= yawOUT;
      motor4 += yawOUT;

Is there something I am missing about quadcopter PID controllers? Thank you for the help!

body:
I'd suggest setting Kd to zero, Kp to a minimal value and letting the integral alone function as the controller. Any response to an error might be slow but the integrator alone will control a process with zero error. After observing the response of the integral for a period of time, hopefully without the problem you referenced, gradually introduce proportional control and watch for the periodic instability. If increasing the proportional gain results in oscillation, reduce the proportional back to a stable value and gradually introduce more derivative gain. I have worked with PID throughout my career and the instability you described sounds like something I'd expect to see originating from the derivative control action. No sensor is perfectly noise free and even if the noise is low amplitude, the rate of change may still be fairly large which will result in a very obvious periodic instability in the flight of your drone.

If this is the case, finding the source of the induced noise may not be easy. Perhaps reducing the derivative gain and using mostly proportional and integral control will effectively filter and attenuate the instability you're noticing. Good luck.


message:
How do I grab data from my Arduino device using a Python program?

We are currently creating a system which can log student attendance using RFIDs. Currently, we have the RFID Scanner set up (MFRC522 reader and Arduino UNO microcontroller). The database for the student's info and time-logging is also already set up. We are; however, having problems with accessing the data the Arduino is sending. We want the Arduino device to send us the Tag IDs via a USB Connection and have set it up to send the relevant data through the Serial Port. However, we cannot access this data using a Python program with this code.

    import serial

    x = 1
    while(x == 1 ):
        ser = serial.Serial("COM3", baudrate = 9600, timeout = 0)
        if(ser.is_open):
           print("Serial Port in Use")
        else:
           print("Card ID: " + ser.read)

We are attempting to read from Port COM3 (the SP the Arduino uses). If the serial port is in use, the program outputs the "Serial Port in Use" (for testing purposes only, to be removed in final code) and if not, it will output the Card ID. However, through this, we run into the problem of being unable to use the same serial port with the Arduino (we are running on Windows). We tried using a serial port splitter but replacing the "COM3" with the name of the virtual port does not work.

We would prefer not to use Processing and would be open to simply avoiding the use of a serial port completely.

body:
It isn't a good idea to open serial in a loop. It can be opened once at the start (or you can retry once per few seconds, if it fails).

Also the method `is_open` should return `true` if the serial was successfully opened so you can use it.

Maybe some working example would be a good way to start.


message:
analogWrite is not working - while trying to control DC motor speed

I'm trying to control the speed of DC Motor using

 1. Arduino R3
 2. NPN Transistor (2N2222A331)
 3. 10k potentiometer
 4. 2M ohm resistor
 5. Diode

I'm not using L298N and I'm also not using L293D.

DC motor is running, but the speed of DC motor doesn't seem to change with changes in potentiometer.
Circuit seems to be alright as DC motor is running.

The code is as follows

    int potPin = A0;
    int motorPin = 9;
    int potValue = 0;
    int motorValue = 0;

    void setup()
    {
     Serial.begin(9600);
     pinMode(motorPin,OUTPUT);
    }

    void loop()
    {
     potValue = analogRead(potPin);
     motorValue = map(potValue, 0, 1023, 0, 255);
     analogWrite(motorPin, motorValue);
     delay(2);
     Serial.print("potentiometer = " );
     Serial.print(potValue);
     Serial.print("t motor = ");
     Serial.println(motorValue);
    }

Whenever I tweak the Potentiometer, I can see the relative changes from Arduino  "Serial Monitor" (both Potentiometer values and Motor values), but the speed doesnt seem to change physically.

Things that I tried

 1. tried different combinations of resistors(100,1k,10k,1M,2M ohm) so as to vary voltage that goes to DC Motor
 2. tried to check with different Output pins like 3,5,9

Nothing works, DC motor speed isn't changing.

**this leads me - to believe that, my analogwrite isn't working.
please help me understand as to what i'm i doing wrong?**

The Circuit is as follows

[![Circuit][1]][1]

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

body:
Well, 2M resistor to the base? If the motor is running with that, the transistor must be broken (shorted). Just try to check if the motor is running with disconnected base.

You can also check PWM output by connecting LED with resistor (no, not 2M ohms, just about 330 ohms). For the transistor 1k should be sufficient maybe little less (depends on motor current and h21e amplification coeficient).

Also there are some versions 2N2222 with emitter and collector swapped. And reversed transistor has much lower current amplification coeficient.

And I hope you are using external power supply, USB is not a good idea. Starting power is usually way too much for the overcurrent protections.

Anyways, this works for me:

    void setup() {
      pinMode(9, OUTPUT);
    }

    void loop() {
      analogWrite(9, map(analogRead(A0), 0, 1023, 0, 255));
      delay(100);
    }

2N2222A + 1k + PC FAN + 12V Fan Power supply.

Connections:
E -> Gnd,
C -> FAN-,
FAN+ -> 12V,
12V GND -> Arduino GND,
Pin 9 -> 1k -> B

On the Arduino side 47k trimmer and the USB


body:
Two things to test:

 1. Have you tried to put an LED (and resistor to protect it) in the motor's place? If the brightness changes, your setup (Arduino+transistor) is working. If not, maybe you've killed your 2N2222 by giving it a wrong diode or something else is wrong.
 2. Have you tried reducing the PWM frequency? An LED can follow a fast change, but a motor can't. Also, by turning on-off the motor less frequently you dissipate less power on your transistor and diode. A quick search gave me this: [this][1].

  [1]: https://playground.arduino.cc/Code/PwmFrequency


body:
Referring to [this datasheet][1] you have connected the transistor the wrong way around. Also, 1M resistor at the base is way too high. Bipolar transistors are **current amplifiers** (amplification at about 50-100 in your case) and with 1MOhm at the base there will be no current through the base at all. I would try with 2k for a beginning.
I hope you have another transistor because this one seems to be broken and I'm pretty sure that it's not a fault in the analog output. If the output stage of the uC was broke there would be no reaction (at least in a correct circuit)

  [1]: https://www.google.com/url?sa=t&source=web&rct=j&url=http://www.next.gr/components-datasheets/2N2222.pdf&ved=2ahUKEwix_suovvDgAhUJJVAKHScsAS0QFjAMegQIBRAB&usg=AOvVaw1xklGtj-dT4MeQx-P3bZ0e "this datasheet"