message:
Multiple SPI reads slows down read time dramatically

I have a two channel 24bit ADC(LTC2402- http://cds.linear.com/docs/en/datasheet/24012f.pdf) that I am communicating with via Arduino Leonardo(Leonardo because it was free!). If I attempt to do multiple reads the SPI becomes very slow while if I do a single read the time to send is what is expected. I have have integrated with python and timed the different transactions. A single read takes around 170ms( this is for both channels and the datasheet of the ADC indicates about 65ms per conversion(table 3 arduino as external sck etc.)) BUT if I do 5 reads the time taken is about 1.5s(expected about 0.65s) 10 reads take about 3s and 20 about 6.5s. Doing no ADC conversions and just serial comm to python is less than 2ms.

The relevant python code is as follows:

    def getdata(ser,code):#ser is the arduino that has been connected, code is for writting to arduino
        ser.write(code)
        ch0=float(ser.readline().decode()[:-2])
        ch1=float(ser.readline().decode()[:-2])
        return ch0,ch1

    code='1'
    code=code.encode()

    a=datetime.datetime.now()
    ch0,ch1=getdata(ser,code)
    b=datetime.datetime.now()
    print(b-a)

The arduino code is as follows. The code has been simplified to just the necessary byte reads from the ADC, all other code has been removed to ensure the delays are coming from the SPI.transfer(0x00). The full code retrieves 4 bytes per channel and converts this to voltage and returns these values.

    #include <SPI.h>

    const int ltcs = 3; //active low ADC enable

    float ch0=0.0;
    float ch1=0.0;
    byte b0;

    void setup() {
    SPI.begin();
    SPI.beginTransaction(SPISettings(200000, MSBFIRST, SPI_MODE0));

    Serial.begin(9600); // set the baud rate

    pinMode(ltcs, OUTPUT);
    digitalWrite(ltcs, LOW);
    }

    void loop() {
    if(Serial.available()){

       int data = Serial.read() - '0';
       if(data>0){

       getdata2(ch0,ch1);
        //getdata2(ch0,ch1); //run multiple getdata2 to test multiple conversions
       //getdata2(ch0,ch1);
        //getdata2(ch0,ch1);
       //getdata2(ch0,ch1);

        Serial.println(0.2);
        Serial.println(0.4);

      }
      }
      }

     void getdata2(float &ch0, float &ch1) {
       ch0 = 0.0;
       ch1 = 0.0;

       for (int i = 0; i < 2; i++) { //Do twice to retrieve both Channels
         while (digitalRead(MISO) == HIGH) {
         }

           b0 = SPI.transfer(0x00);
           b0 = SPI.transfer(0x00);
           b0 = SPI.transfer(0x00);
           b0 = SPI.transfer(0x00);
       }
       }

Can anyone help me? I have tried different SPISettings with no change. Interestingly I also find that the Baud rate does not change either.

Thanks for the help if any

body:
You probably want to take a look at the datasheet and work on one routine that returns adc results from a channel selected by the user. The typical process is to read the register until EOC is asserted (_EOC is low).

and you would go from there.


sender: user

sender: assistant

body: I found the error. Unfortunately I was so busy blaming the code and assuming it was my lack of arduino knowledge that I forgot to check the hardware specs. I thought I was using the maximum external oscillator frequency(f_EOSC) of 300KHz, but in fact was using the 50Hz internal oscillator frequency with an external f_sck from the arduino. This means that the conversions where in fact running at expected times. The thing that threw me off was that the first reading was much faster than the rest. This was most likely because at first read I only had to wait for one channel conversion as the other was already done before I request the data and so the first readings wait time is only as long as a single channels conversion. I would need to implement a 300KHz external clk if I want faster conversion speeds. Thanks for the help for those who tried:)


message:
Do I need to run an expand drive sketch if I update the Yun Firmware subsequent to expanding?

I have a Geeetech Iduino Yun shield, that initially had Geetech's System image (v2.02, 2015) on it. I then ran a USB storage expander sketch to take advantage of the space on a flash drive. I then installed a number of packages (such as `vim`). I subsequently flashed/updated the firmware with Dragino v2 yun-4.1.2 sysupgrade firmware, only to find that `vim` and other packages have disappeared, as well as my Python code.

Has the update undone the expansion and is the Linux system now confined to what's provided by the firmware? Do I need to run an expansion sketch and install packages again?

body:
After upgrading the firmware and rebooting:

1. Log in to your Yun through your browser and use the LuCI interface.
2. Navigate to "System" > "Software" and observe the "Free space" meter. You will see that the total space shown is between 800KB and 1MB, instead of the size of your flash drive. This indicates that the system is that of the memory available on the board.

Yes, you will need to run the expander sketch again and reinstall software that was previously there. (You might want to back up the contents of the drive beforehand, using a PC running GNU/Linux.)


message:
Problems adding ESP8266 wifi board

I just received an ESP8266 wifi module and I am trying to add the board. However I am having an issue. All websites/tutorials say to use [http://arduino.esp8266.com/stable/package_esp8266com_index.json][1], however nothing is there. Can it be found somewhere else?

  [1]: http://arduino.esp8266.com/stable/package_esp8266com_index.json

body:
It looks like the server is down.  Isitdownrightnow reports that it's been down for almost 4 days: http://www.isitdownrightnow.com/arduino.esp8266.com.html

There is a discussion about it over on the ESP8266 forums: http://www.esp8266.com/viewtopic.php?f=26&t=3134&start=8

Let's hope it will be back again soon.


message:
Two devices on one UART/Serial

I'm using an Arduino Mega which has 4 RX/TX UARTS/serials.
3 RX's of them I use for MIDI In
2 TX's of them I use for MIDI Out (maybe later a DMX out too)

One I use currently for debugging. On the other hand, in the future I want:

- Using an ESP8266 WIFI which also seems to use an UART (both RX/TX)

Of course I can remove the debugging RX/TX, but maybe some more additions are needed and for the first RX/TX I need to remove the RX each time I upload (so I rather leave it for debugging).

I was wondering, is it possible to share an UART if I don't use the WIFI module and MIDI port at the same time?

body:
It's certainly possible to multiplex a UART port, yes, though you will need extra hardware to do it. You will need:

* A multiplexer to select between the two RX lines and feed the right one to the Arduino's RX pin
* A demultiplexer to select which of the devices to send the Arduino's TX pin to.

"Analog" (de)multiplexers (e.g., CD4052) may be the simplest option since they can work in both directions. Another alternative would be combinations of tri-state buffers and glue logic to control them.


body:
If your application can tolerate the limitations of [SoftwareSerial][1], it's the easiest way to add a port. The terminal may be the better candidate for it.

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


body:
Consider running the RX and TX of the first UART to the common terminals of an On-Off-On DPDT switch or relay.  Calling the On positions A and B, connect the A terminals to RX and TX of one device, and the B terminals to RX and TX of another device.  Use position A for the first device,  position B for the second device, and the Off position for program loading.

It isn't clear to me whether your debugging is via USB serial or via a separate device. In the former case, a DPST switch would be adequate.  Also, two SPDT's could be used in place of a DPDT if you wish to switch RX and TX separately, or four SPST switches can be used if you have nothing better.

This is premised on the idea that during development you need to be able to send/receive debugging IO.  I don't know how to interpret your
“don't want to be rely on a user having to remove the cable”  phrase, but suppose a user-cabled setup won't need debug-channel switching.


message:
Make Sure \n is the last character in serial string

I have an Arduino that I've put between a computer and an RS485 device. The job of the Arduino now is just to transmit data but will eventually do data logging and have a small user interface as time goes by.

So far, this serial read code has worked for me to communicate to the Arduino from the computer:

     void serialEvent()
     {
      while(Serial.available())
      {
        // get new byte
        char inChar = (char)Serial.read();
        if (inChar == '\n')
        {
          stringComplete = true;
        }
        else
        {
          inputstring += inChar;
        }
      }
     }

The downside here is that I cannot send the '\n' char to my RS485 unit. Is there a way I can refine the code so I can send an arbitrary string of chars while still having a termination [thing] to turn on the stringComplete flag?

EDIT To clarify this the process by how my message string is being created:

    Input: U16 Address, U16 Data, U8 Function Code
    U16 Address -> U8 Address Split High, U8 Address Split Low
    U16 Data -> U8 Data Split High, U8 Data Split Low

    U8 Array of [U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]

    U8 Array -> Message String

    Output: Write Message String

body:
Normally strings end with a '/0' item ... than /n is part of the string and can be handled as normally.

So you have to change the check to

    if (inchar == '\0')

Also consider not adding a character every time to the string, since it will cause the string to be replaced/copied every time, which is not good for both performance and memory gaps resulting.

Instead make a predefined buffer if possible (if you know the maximum string length, don't forget to add +1 for the ending '0' character). In that case you can add the '\0' yourself or even better:

    char inputString[101];
    uint8_t inputStringLength = 0;

    while(Serial.available())
    {
        // get new byte
        char inChar = (char) Serial.read();
        inputString[inputStringLength++] = inChar;

        stringComplete = (inChar == '\0')
    }


body:
`Serial.avilable()` returns the number of bytes available in the buffer. One solution could be to try reading that many bytes at a time. This assumes that the buffer contains only entire strings.

Note: If your RS485 device sends multiple, non-delimited strings between buffer reads then this may not work as desired.

    void serialEvent()
    {
      int bytes = Serial.available();

      if ( bytes == 0 ) // empty buffer, bail
        return;

      for (; bytes > 0; bytes-- )
      {
        // get new byte
        char inChar = (char)Serial.read();
        inputstring += inChar;
      }
      stringComplete = true;
    }


body:
Since you are using all 8 bits of the serial data for your data there is nothing "in band" that you can use for a delimiter.

Instead you will have to think outside the box somewhat and create some form of "out of band" data that can signal the end of a packte.

One option (probably the simplest) would be to include the concept of time into your protocol.  If you go more than X milliseconds (X is to be determined by you) without receiving a byte then you are at the end of your packet. This has the disadvantage that it slows down your maximum packet rate, since each packet has to have a suitable delay between them.

Another option may be to use a serial *break* character between packets. This is a special event where the UART output is held low for at least 10 symbol lengths, which results in an framing error (the STOP bit is wrong) and a flag being set. It would mean though that you have to implement all the UART code yourself since the Arduino's UART code doesn't support breaks.

A third option, which also would require you to write your own UART code, or alter the Arduino UART code, would be to operate the UART in 9-bit mode. You then have 0-511 instead of 0-255, so you can send your 8-bit data as per normal (with the 9th bit set to 0) and any control and protocol characters with the 9th bit set, so between 256 and 511.

Finally, you could halve your overall transmission speed by sending the data as ASCII-encoded HEX digits. That would be two characters (0-9,A-F) for each byte sent, leaving all the other characters (including `\n`) available for you to use as you wish.


message:
Simple Ground circuit layout

I am making a circuit without using a PCB or perfboard and i am unsure if i am running the ground wire correctly.
[![Grounding layout][1]][1]

I usually prototype on a breadboard with the ground all joining on the far right, is this the same concept? I wanted to know if this is the accepted  convention for running the ground back to the board.

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

body: Yes, based on basic electrical theory, you have the ground connected correctly.


message:
Error on sending AT+CWJAP_DEF commands to ESP8266

I am trying to send `AT` commands to `ESP8266` to get connected with internet with the Wifi.

When I am sending `AT` and `AT+RST` command on serial monitor then I am getting OK and ready response which seems perfect.

Then I am sending `AT+CWLAP` to get list of available wifi networks which is also executing correctly.

    AT+CWLAP

    +CWLAP:(3,"Moto",-42,"a4:70:d6:7a:fa:6c",1,25,0)
    +CWLAP:(4,"PRANJAL",-95,"1c:a5:32:3d:f5:c4",1,-16,0)
    +CWLAP:(2,"VIHAN",-94,"c8:3a:35:2f:1d:81",1,-21,0)
    +CWLAP:(3,"Tenda",-93,"c8:3a:35:20:a9:b1",9,-4,0)

    OK

Then I sent `AT+CWMODE?` which is also perfect.

    AT+CWMODE?

    +CWMODE:1

    OK

Now I am trying to connect `ESP8266` with above listed Wifi with this command, it is sending an ERROR on serial monitor.

> AT+CWJAP_DEF="Moto","reset1234"

**Error**

    ⸮=IRe"Moto","reset1234"

    ERROR

Can anyone suggest me what could be the reason of this issue ?at

body:
Based on the gibberish echo, the possible causes are:

 - Insufficient power. You need a source that can supply up to 300mA which is about the max consumption for the module. A good-sized capacitor across the ESP power rails (10uF maybe) wouldn't hurt.
 - Baud rate is too high. If you're using an Arduino as 'middle-man' and talking to the ESP8266 through a SoftwareSerial port, you're likely to face this sort of issue if the baud rate is as high as 115200; SoftwareSerial is unreliable at such rates.


body: Alright! I just tried to connect with different wifi and it got connected with it. It was some kinda issue with mobile hotspot.


body:
The source of such problems are mostly as under

- Bad / loose wiring (power and communication)
- software serial is not much reliable
- Arduino serial monitor is not a user friendly way of testing out ESP modue

To solve wiring related problems for good check out [this design][1].

To solve communication monitoring problems check out [this solution][2]

Use USB to TTL interface to connect ESP module directly to your PC without using an Arduino ([find details here][3])

  [1]: http://absaransari.com/2018/01/25/how-to-power-esp8266-from-5v-supply/
  [2]: http://absaransari.com/2018/01/27/esp8266-wifi-module-configuration-utility/
  [3]: http://absaransari.com/2018/01/26/connecting-esp8266-wifi-mobile-with-computer-using-pl2303/


message:
How to logically tell than an UNO is being, or about to be programmed

I have an MIDI application that uses the RX and TX serial interface.  When I program the UNO there is a collision between the on board programmer and the MIDI application RX serial port.  The MIDI shield provides a jumper to disconnect to prevent the collision during programming.

I would like to add a FET switch to open and close if I am programming, but it's not clear to me that there is a signal I can tap into on the UNO that indicates programming is about to start or that it has just finished.

I was thinking about using a pull up on a digital pin on the UNO that drives low when the program starts up. That might be the way to go, but I assumed that this must be a common issue with a common solution that I am just not finding on stack exchange.
Is there a standard logical way to tell that UNO is about to be programmed via the onboard USB port?

body: Your proposed solution is the normal method. A GPIO pin which is an "Activate Device" signal. It's pulled in one direction, the "inactive" direction, and you actively drive it in the other "active" direction in your program.


message:
OSX upload error: avrdude: ser_open(): can't open device "/dev/cu.mydev" : Resource Busy

I'm trying to upload the blink script to my unnamed Arduino-like board. However, the USB port appears to be busy.

This is all the output I get:

<!-- language: none -->

    Archiving built core (caching) in: /var/folders/43/7_h5zwcs1csdr2dc635m1yq40000gp/T/arduino_cache_942504/core/core_arduino_avr_uno_51f02b7210b938436b779d1c032618e1.a
    De schets gebruikt 928 bytes (2%)  programma-opslagruimte. Maximum is 32256 bytes.
    Globale variabelen gebruiken 9 bytes (0%) van het dynamisch geheugen. Resteren 2039 bytes voor lokale variabelen. Maximum is 2048 bytes.
    avrdude: ser_open(): can't open device "/dev/cu.mydev": Resource busy

I've tried all solutions I could find on internet, but they haven't solved my issue. The main difference with my error and online solutions/errors is that I only have this error. Other people experienced extra errors which enabled the debugging of the problem.

Can anyone help me please?

body:
I think my available serial ports were insufficient or something. I installed the ch34* driver which allowed an additional device showing up. Here's the download: http://www.wch.cn/download/CH341SER_MAC_ZIP.html

Then I selected this port and I finally could upload.


message:
Arduino nano Serial port not recognized

First sorry for my bad english, not my native lenguage.

Today I started working on my Arduino nano (first time used). When plugged for the first time the "L" led started blinking, after that I tried to write a simple program but I noticed that the "Port" option on the Arduino IDE was Gray. So I couldn't choose the port. After that I searched A LOT but nothing seems to work.

While trying to test if the problem was the Arduino and not the PC, I make a simple circuit with 1 LED, 1 resistor of 1Kohm, and a breadboard. I connected the 5V pin to the LED and GNG to the other point, And when I did this the "L" LED stopped blinking forever. I am 100%  sure that I did not make a short circuit. ¿Maybe the breadboard is in a bad state?

Additional info:

-Windows 10.
-The port doesn't appear at Device manager (tried every port of my notebook).
-The "POW" led is ON when I plug the USB.
- The Arduino is a clone (chip CH340G).

So now I don't know if the problem is the port or if the Arduino Nano is dead because of a possible short circuit between 5V and GND pins.

thanks in advance!

body: I think your Arduino got short or the transmitter-receiver in it is damaged so the device manager cannot recognize the COM port.It once happened with my Arduino Uno. Try changing the USB cable.If it does not help your Arduino is damaged.


message:
POWER_MODE_IDLE wake on any input change?

I want to be able to put an Arduino to "sleep" but I want it to immediately resume if any panel tactile buttons are pressed.

The purpose is to try to minimize any digital noise in an nearby high gain analog circuit.

My guess at this point is that I want to put the Arduino into POWER_MODE_IDLE but it is less clear to me the best way to wake up.

How can I instantly wake up from POWER_MODE_ILDE if any input changes? I don't want to have to hold down a button or even use a specific input. Is there a "catch-all" interrupt that will react immedately to a change on any or on a large set of inputs?

body:
The Arduino can only be woken from sleep by a change on pins 2 and/or 3.

> On the hardware front, the Arduino is equipped with two interrupt
> ports: digital pin 2 and 3. So the Arduino can sense those pins for an
> event to wake up and resume execution of code.

http://playground.arduino.cc/Learning/ArduinoSleepCode

However, the datasheet indicates that any pin can be used:

http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf Section 17. EXINT - External Interrupts

> The External Interrupts are triggered by the INT pins or any of the PCINT pins.
> [...]
> The Pin Change Interrupt Request 2 (PCI2) will trigger if any enabled
> PCINT[23:16] pin toggles. The Pin Change Interrupt Request 1 (PCI1)
> will trigger if any enabled PCINT[14:8] pin toggles. The Pin Change
> Interrupt Request 0 (PCI0) will trigger if any enabled PCINT[7:0] pin
> toggles. The PCMSK2, PCMSK1 and
> PCMSK0 Registers control which pins contribute to the pin change
> interrupts.


body:
As I mention on my [page about interrupts](http://www.gammon.com.au/interrupts) you can use pin-change interrupts on the Atmega328P to wake from the deepest sleep mode (SLEEP_MODE_PWR_DOWN).

Example code:

<!-- language-all: lang-C++ -->

    #include <avr/sleep.h>

    const byte LEDLOOP = 8;
    const byte LEDWAKE = 9;

    ISR (PCINT1_vect)
     {
     // handle pin change interrupt for A0 to A5 here

     // toggle LED
     digitalWrite (LEDWAKE, !digitalRead (LEDWAKE));
     }  // end of PCINT1_vect

    void setup ()
      {
      pinMode (LEDWAKE, OUTPUT);
      pinMode (LEDLOOP, OUTPUT);
      digitalWrite (A0, HIGH);  // enable pull-up

      // pin change interrupt
      PCMSK1 |= bit (PCINT8);  // want pin A0
      PCIFR  |= bit (PCIF1);   // clear any outstanding interrupts
      PCICR  |= bit (PCIE1);   // enable pin change interrupts for A0 to A5

      }  // end of setup

    void loop ()
    {

      set_sleep_mode (SLEEP_MODE_PWR_DOWN);
      sleep_mode ();

      // flash to indicate we got out of sleep
      digitalWrite (LEDLOOP, HIGH);
      delay (100);
      digitalWrite (LEDLOOP, LOW);
      delay (100);

      } // end of loop

This has the advantage of consuming very little power while asleep, and also waking on any pin (of an Atmega328P).

Running on 5V at 25°C you should only consume around 150 nA of current while asleep (on a "bare bones" board without USB chip, voltage regulator or power LEDs).

Other sleep modes may use more power but wake more quickly.


message:
Using ALL the analog pins on Mega for Servo

I wish to use ALL the Analog pins on a Mega2560 R3 to control Servo's, all is well up to and including A9, but from there on nothing. {sound familiar} this is apparently not a new problem. I have tried Servo.h and MegaServo.h but still no luck, does anyone have info on a library that will do this or a method to get around it........all the pins on the end buss are used for other purposes and are not available. I can post the code, but first just asking the general questions. Thanks Doug

body:
OK..Solved...tried a library I had previously discarded for another project but it works with this situation..SoftwareServo ....(had also tried versions of Servo and MegaServo with no luck) I have attached a proven sketch that shows the method using arrays (as i have 16 servos to control) hope this is of use to others.

        /*This sketch will enable you to use ALL of the Analog pins on a Mega2560 to control a Servo
     * it uses the Arrays and the Softwareservo.h as the other Servo libraries do not support
     * Mega Analog above A9
     * this is the only method i have found that works
     * hope this is of use to others.
     */
    #include <SoftwareServo.h>

    SoftwareServo servos[16];  // create servo object to control a servo

    int pos=0;
    int servoPins[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,A13,A14,A15};                    //servo pin numbers
    int servoPosMin[] = {80,80,80,80,80,80,80,80,80,89,80,81,80,70,80,45};                        //servo lower setting to suit individual servo
    int servoPosMax[] = {100,100,100,100,100,100,100,100,100,100,100,100,100,110,100,160};        //servo upper setting to suit individual servo
    boolean refresh = false;  // toggle refresh on/off
    int m = 0;
    int p = 0;
    void setup()
    {
      Serial.begin(115200);
      for (m=0;m < 16;m++) {
          // attaches the servo on pin to the servo object
        servos[m].attach(servoPins[m]);
          // init angle of servo inbetween two limitations
        servos[m].write(((servoPosMax[m]+servoPosMin[m])/2));
        Serial.println(m);
        delay(10);
          SoftwareServo::refresh();
      }
    }
    void loop()
    {
      for (p=0;p < 16;p++) {

        for (pos = servoPosMin[p]; pos <= servoPosMax[p]; pos += 1) { // goes from 0 degrees to 180 degrees
          servos[p].write(pos);                                       // tell servo to go to position in variable 'pos'
          delay(15);                                                  // waits 15ms for the servo to reach the position
          Refresh();
      }
        for (pos = servoPosMax[p]; pos >= servoPosMin[p]; pos -= 1) { // goes from 180 degrees to 0 degrees
          servos[p].write(pos);                                       // tell servo to go to position in variable 'pos'
          delay(15);                                                  // waits 15ms for the servo to reach the position
          Refresh();
        }
      }
    }
    void Refresh() {
      refresh = refresh ? false : true;                             // set refresh one time / 2
      if (refresh) SoftwareServo::refresh();
      Serial.print("Servo Number = ");
      Serial.println(p);
      Serial.print("  Angle =  ");
      Serial.println(pos);
    }


body:
There is a relatively easy fix, you need to change one symbol in the library code, in `Servo.h`:

Change

    typedef struct  {
       uint8_t nbr        :6 ;
       uint8_t isActive   :1 ;
     } ServoPin_t   ;

To

    typedef struct  {
       uint8_t nbr        :7 ;
       uint8_t isActive   :1 ;
     } ServoPin_t   ;

Pull request here: https://github.com/arduino-libraries/Servo/pull/11


message:
Programming Arduino Micro via RX/TX

I can't access my Arduino Micro's USB programming port when it's in my project. I want to reroute the RX and TX pins outside to a serial-to-usb adapter.

I have [this][1] on hand from a while ago. I found the RX and TX pins in the serial connector and I connected them to the RX and TX pins of the Arduino as well as GND but when I try and program the device nothing happens. I usually get an open port error or something like that but the programming LED on the adapter doesn't light up. Conversely if I try using the Basic Stamp software I at least get a programming LED to light up on the adapter.

Do I need an FTDI breakout instead? Or am I wiring something wrong?

  [1]: https://www.parallax.com/product/28030

body:
RS-232 logic uses a negative voltage typically from -3 to -25V to represent a logical high and a positive +3 to +25V to represent a low. On the flip side TTL used on the AtMega uses +5V or +3.3V as a high (or VCC) and 0V as a low. [Read more][1]

Other than that the signals are the same logically so all that is needed is to invert the RS232 from -/+ ~12V to 0-5V using a [simple converter.][2]

Possibly the easiest approach is to use another Arduino Uno as a programmer, which needs 3 pins, TX, RX, and RESET. This tutorial seems to have some success. Check out "programming an Arduino with another".

  [1]: https://www.sparkfun.com/tutorials/215
  [2]: https://www.sparkfun.com/products/449


body:
yes you can, use a FTDI 232 USB TO SERIAL  then set the Arduino IDE to the board you will be programing, and the serial port the FTDI RS232 Programmer is on.

connect the two rx to tx, and tx to rx, also the vcc of programmer to Arduino 5v pin.

then press and hold the reset button, and upload "regular".

The trick is to let go of RESET just after it finishes compiling, and it will get programed.

i think between 1-2 seconds after it finishes compiling and the compiling line just turned all green.

This is also how wireless programmer work using a Bluetooth module. I tried using the DTR pin to reset, but that did not work for me.


message:
Make lights come on and off depending on which button is pressed

Imagine a strip of LEDs with O being HIGH and X being LOW.

X O X O X

Now if I pressed the button below the second O and wanted it to switch the last two LEDs (4th one to LOW and 5th to HIGH or any opposite value of what it was), but if I pressed the first X wanted it to switch that one HIGH, the second one LOW, and the third HIGH.

I want to continue this type of pattern where each button press will result in two or three of the LEDs changing their effective state.

How might I achieve this? I have researched using the modulo function and can only get it to work every other click of a button. I have also tried using a pullup function and couldn't get it to work at all.

Can someone please just point me in the right direction?

body:
>I want to continue this type of pattern where each button press will result in two or three of the LEDs changing their effective state.

I'll assume there are *nLED* LEDs and buttons, and that the buttons are momentary buttons and need debouncing.  I presume you have one button beneath each LED, numbered say 0 to *nLED-1*, and that the two or three LEDs that will change when button *k* is pressed have numbers  *k, k+1,* and possibly *k+2*.

To simplify the coding, create an array (or a bit map), say *Lsts*, with *nLED* entries, to represent the current state of LEDs, and a similar array, say *Bsts* for button statuses, and an array of bytes *bounce* to track debouncing status.

On each pass through `loop()`, use a `for` loop to read each eligible switch.  A switch with a nonzero *bounce* entry is debouncing and doesn't get read.  If a switch is read and it changes, update the LED statuses in  *Lsts* and at ports.  For example:

    enum { nLED=5, debouncePasses=50 };
    byte Lsts[nLED]={0}, Bsts[nLED]={1,1,1,1,1}, bounce[nLED]={0};
    const byte Lpins[nLED] = { 3,4,5,6,7 };
    const byte Bpins[nLED] = { 8,9,10,11,12 };
    //... etc

    void setup() {
      for (byte i=0; i<nLED; ++i) {
        pinMode(Lpins[i], OUTPUT);
        // Buttons will have negative logic, hi for open, lo for pressed
        pinMode(Bpins[i], INPUT_PULLUP);
      }
      // ... any other initialization ...
    }
    void loop() {
      for (byte i=0; i<nLED; ++i) {
        // See if button is eligible for reading, and if it changed
        if (bounce[i]) {
          --bounce[i]; // Decrease bounce pass counter
        } else {
          if (digitalRead(Bpins[i]) != Bsts[i]){
            // Yes,  it's eligible and it changed
            bounce[i] = debouncePasses; // Set button's debounce counter
            if (Bsts[i]) { // Test if switch was pressed vs released
           // Toggle the button's light and the next one or two lights
           for (int j=i; j<nLED && j<i+3; ++j) {
             Lsts[j] = !Lsts[j];
             digitalWrite(Lpins[j], Lsts[j]);
           }
            }
            Bsts[i] = !Bsts[i]; // Toggle button state
          }
        }
      }
      // ... any other stuff
      delayMicroseconds(500); // Delay for bounce-pass timing
      // alternately, instead of delayMicroseconds, sleep until timer tick
    }

---

*Edit 1:*  If there are more LEDs than buttons, then use separate constants for the counts, adjust the initializations, etc.  For example:

    enum { nButton=5, nLED=6, debouncePasses=50 };
    byte Lsts[nLED] ={1,0,1,0,1,0};
    byte Bsts[nButton]={1,1,1,1,1}, bounce[nLED]={0};

    //... etc

    void setup() {
      for (byte i=0; i<nLED; ++i) {
        pinMode(Lpins[i], OUTPUT);
        digitalWrite(Lpins[i], Lsts[i]);
      }
      // Buttons will have negative logic, hi for open, lo for pressed
      for (byte i=0; i<nButton; ++i) {
        pinMode(Bpins[i], INPUT_PULLUP);
      }
      // ... any other initialization ...
    }

In `loop()`, change the initial `for` from `for (byte i=0; i<nLED; ++i)` to `for (byte i=0; i<nButton; ++i)`.  This will work ok if there is an extra LEDs after the LEDs that line up with buttons.

---

*Edit 2:*
>Why when using an array doesn't the arduino recognize the HIGH or LOW state of an led? I tried adding this simple code:
 `if (42 && 44 && 46 && 48 && 50 == HIGH){`
 `digitalWrite (ledWin, LOW); } else {digitalWrite (ledWin, HIGH);}`

Evidently you want to test if all the LEDs are on, and apparently the numbers 42, 44, ... 50 are supposed to somehow represent LED states.

However, numbers like 42, 44, ... are constant values and cannot properly represent the value of something that varies.  The condition in that `if` statement will always evaluate to the same value, false, as follows.

According to the C/C++ standard, a condition like `42 && 44 && 46 && 48 && 50 == HIGH` consisting of a series of terms separated by `&&` operators will be evaluated left to right until either one is false (making the whole expression false) or all are true (making it true).  (For example, see the *Remarks* section of [Logical AND Operator: &&](https://msdn.microsoft.com/en-us/library/c6s3h5a7.aspx).)

In this case, 42 is non-zero, hence true.  Next, 44 is true, 46 is true, and 48 is true.  But `50 == HIGH` is false – the value of `HIGH` is 1, and 50 is not equal to 1.  Therefore the whole expression is false.

A better approach to finding out if all the LEDs are on or off is to test the values of `Lsts[]` entries.  For example, you could add them up, and then see if the sum is equal to 0 (all off) or equal to `nLED` (all on):

    byte nOn = 0;
    for (byte i=0; i<nLED; ++i) nOn += Lsts[i];
    digitalWrite (ledWin, nOn < nLED);

That will set the `ledWin` pin if not all of the LEDs are on, else will clear it.


body:
> Can someone please just point me in the right direction?

what is "right" is highly subjective. I would consider a good solution to be one where the functionalities desired is broken down into natural modules that are then integrated to perform the desired functions. By that (highly subjective) standard, the solution posted earlier would be a poor one -> due to its tightly coupled / inter-mingled approach.

if I were to take a shot at this, I would consider the implementation below:

      key_state = read_keys(); //read keys / buttons, with or without debouncing
      led_process(key_state);  //process the key_state, and light up / off leds based on key_state

Essentially, you scan the keys / buttons, and based on that, turn on / off the leds.

All you need to do after that is to implement the individual functions based on your particular hardware design, or even software approaches: for example, read_keys() can be implemented in the isr, as can led_process().

A solution like this is highly portable: it works on pretty much anything that supports a C compiler, and is implementation-independent: the logic holds true, and all you do is to change the two functions to perform different kinds of lighting.

To me, modulizing your code is a huge advantage for a high-level language like C, and vital in taking on a real life project of moderate complexity.


message:
Connecting a 5v dc fan to ultrasonic sensor

I am currently doing a simple uni project where i want the distance read by an ultrasonic sensor to control the speed of a dc 5v fan. I have attached a schematic of how i think i can link the ultrasonic sensor and fan components in order to achieve my main goal. Please tell me if this circuit is right or wrong and give some helpful feedback, thank you!

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

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

body:
It's wrong.

A fan is a motor. A motor is a power hungry inductive device.

Just like any other motor or similar device (such as a relay or solenoid) you cannot drive it directly from the Arduino. Instead you need (at the very least) a transistor to switch a higher current and a diode to absorb back EMF.


message:
Trying to send .wav files between NodeMCU

Im trying yo send wav files between two nodeMCU. My setup is like this
uSD Card Module -> Arduino Mega -> Node MCU

So this is my setup, where I have 4 devices like this. One will serve as the central network(where I called it "server") where it will create an access point for the 3 other devices("modules") to connect to. The server will send data by using UDP so it can broadcast to the three modules simultaneously.
I'm able to send .txt files which is stored on the uSD module. Pass the .txt file contents to the nodeMCU through serial port, then recieve it on the other NodeMCU which will then send the data to the Arduino Mega also through serial port and will store it on its uSD Shield.

When I would try .wav files. It is able to send the whole .wav file to the NodeMCU from Arduino Mega (since .wav files are too big, I divide the .wav files into sets since the serial port can't handle too large data being sent/recieved. But when it would send the data from the nodeMCU to the other nodeMCU there are parts which are not being sent. When I try to observe what are not being sent, its part of the WAV Header Format, so it needs to be sent. Ill be posting the codes Im using to send and recieve and also a screenshot/example of the wav file as it is being sent.

Server's Arduino Mega Sending data to NodeMCU Serially:

    void sendFiletoSerial(char fileSend[12]){
      Serial.println();
      Serial1.println();
      if (!myFile.open(fileSend, O_READ)) {
        sdf.errorHalt("opening test.txt for read failed");
      }
      Serial.print(fileSend);
      Serial.print(" Size:");
      Serial.println(myFile.fileSize());

      Serial1.print(fileSend);
      Serial1.print(" Size:");
      Serial1.println(myFile.fileSize());
      delay(1500);
      fileofSize = myFile.fileSize();
      myFile.close();
      // read from the file until there's nothing else in it:
      char data;
      long int index=0;
        for(int i =0; i<(fileofSize/tempSize);i++){
        if (!myFile.open(fileSend, O_READ)) {
        sdf.errorHalt("opening test.txt for read failed");
      }
        //Serial.println(i);
        myFile.seekSet(index);
      for(int j =0; j<tempSize;j++){
      int temp = myFile.read();
     intTempFile[j]=temp;
      index++;

      }
      for(int k =0;k<tempSize;k++){
      Serial1.write(intTempFile[k]);
      }
        myFile.close();
        delay(1500);
      }
      Serial.println("LAST SET OF DATA");
        if (!myFile.open(fileSend, O_READ)) {
        sdf.errorHalt("opening test.txt for read failed");
      }
        myFile.seekSet(index);
        int lastSetSize=fileofSize-((fileofSize/tempSize)*tempSize);
        Serial.println(fileofSize-((fileofSize/tempSize)*tempSize));
      for(int j =0; j<lastSetSize;j++){
     int temp = myFile.read();

     intTempFile[j]=temp;
      index++;

      }
      Serial.println();
      Serial.println("tempFile");
      for(int k =0;k<lastSetSize;k++){
      Serial1.write(intTempFile[k]);
      }
        myFile.close();

    }
Server's code for Sending from NodeMCU to other Node MCU:

        if (Serial.available()) {
              byte readStr[100];
            Serial.readBytes(readStr,100);
           // Serial.write(readStr[i]);
            }

             port.beginPacket("192.168.4.255",2390);
             for(int i =0; i <100; i++){
            port.write(readStr[i]);
             }
             port.endPacket();
          }

Module's Code for NodeMCU to recieve data from other NodeMCU:

    void dumpMode(){
      while(1){
        int packetSize = port.parsePacket();
          if (packetSize) {
            port.read(packetBuffer, fileSentSize);
            Serial.write(packetBuffer);

      }
      if(Serial.available()){
        String reply = Serial.readString();
        if(reply == "STOP"){
          break;
        }

        }
      }
    }

Server's NodeMCU Sent Data:

    RIFFäN  WAVEfmt      À]  À]    dataÀN  €€€€€€€€€€€€€€€€€€€€€€€€

Module's NodeMCU Recieved Data:

    RIFFäN€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€

Is there something im doing wrong thats why NodeMCU is not either sending or recieving every content of the wav file?

Thank you for those who will help out. :)

body:
You *could* just program the NodeMCUs and skip the Megas; they have sufficient pins to drive an SD card. There's so much wrong with your code: opening and closing the same file so many times and *then* having to seek for every chunk because of the previous nastiness, writing and reading bytes singly instead of just passing in a buffer, among others. I also hope you know that you didn't send only the WAV data to the transmitting NodeMCU; there's a bunch of stuff (CRLF, file size, etc) before that.

Your particular problem's most likely the fact that your Mega "server" is just sending chunks continuously to the NodeMCU, never minding if the latter is reading them quickly enough that its serial buffer doesn't overflow, especially considering you're sending data over the network between chunks. You should also note that UDP isn't exactly the most reliable protocol; it's connection-less and so packets will be lost. It's generally used if packet loss isn't a big deal (in your case, it is) or if upper layers implement error control.

What you need to implement is a way for each party to confirm that they've received the next chunk before the their sender transmits the next. The Mega needs to wait for a 'go-ahead' from the NodeMCU before sending the next chunk; for instance, the NodeMCU can reply each chunk with the number of bytes it actually read, so you can know if you should reduce your chunk size to not overwhelm the NodeMCU buffer.

The packets sent over the network also need to be tagged with a sequence number (because of aforementioned error control). The NodeMCU at the receiver needs to acknowledge the packet it received each packet, perhaps by sending that packet's number to the transmitting NodeMCU. This will help ensure all packets are received and in order. Or you could just use TCP which already implements these and more.


message:
Arduino Nano and ESP8266

I am trying to use Arduino Nano with ESP8266 (01). I tried to follow a lot of online tutorial with no result.

In particular this one http://www.martyncurrey.com/arduino-to-esp8266-serial-commincation/.
I think connections between Arduino Nano and ESP8266 are fine, when I upload the code on Arduino the red led on the ESP8266 turns on, I set the Arduino Monitor to 9600 BAUD and try to send command like "AT" but I got not reply from ESP8266. I also tried to switch to 115200 BAUD with no result too.

I don't if is something wrong or ESP8266 is damaged. Is there any tutorial that you may suggest?

Thank you.

body:
The Serial Monitor's baud rate must match what you have in

    Serial.begin(9600);

The EDP8266's baud rate is specified in the line

    ESPserial.begin(9600);

and that is the one you need to change to try different baud rates with the ESP8266. The newer AIThinker firmwares default to 115200 baud, not 9600 baud.

Be warned, though, that SoftwareSerial isn't that great at 115200 baud - you tend to get some data corruption. It is best to change the baud rate to 9600 baud with

    AT+CIOBAUD=9600

I'd also recommend investing in one of the ESP-01 programming boards from eBay. Make sure you get one of the ones with a switch on it that switches between programming and UART mode. Something like [this one](http://www.ebay.co.uk/itm/322466871464). It makes working with the ESP-01 much simpler - you can directly use your PC to set it up right for your system, and even upgrade the firmware (or program it directly with a sketch from the Arduino IDE if you install the right core) with minimum hassle.


message:
NRF24L01 only receiving zeros

I'm attempting to transmit very simple data across some NRF24l01 modules for testing purposes, and I've been following a [YouTube guide][1].

Here is my code:

Trasmitter:

    #include "RF24.h"
    #include <SPI.h>

    RF24 Radio (7, 8);
    byte address[][6] = {"0"};
    struct package{
       int on = 1;
    };

    typedef struct package Package;
    Package data;

    void setup() {
      Serial.begin(9600);
      delay(1000);
      Radio.begin();
      Radio.setChannel(118);
      Radio.setPALevel(RF24_PA_LOW);
      Radio.setDataRate(RF24_250KBPS);
      Radio.openWritingPipe(address[0]);
      delay(1000);
    }

    void loop() {
      Radio.write(&data, sizeof(data));

      Serial.println("Data sent:");
      Serial.println(data.on);
      delay(1000);
      }
    }

Receiver:

     #include "RF24.h"
     #include <SPI.h>

     RF24 Radio (7, 8);
     byte address[][6] = {"0"};
     struct package{
        int on = 1;
     };

     typedef struct package Package;
     Package data;

     void setup() {
       Serial.begin(9600);
       pinMode(2, OUTPUT);
       delay(1000);
       Radio.begin();
       Radio.setChannel(118);
       Radio.setPALevel(RF24_PA_LOW);
       Radio.setDataRate(RF24_250KBPS);
       Radio.openReadingPipe(1, address[0]);
       Radio.startListening();
       delay(1000);
     }

     void loop() {
       while(Radio.available()){
         Radio.read(&data, sizeof(data));
         if(data.on == 1){
           digitalWrite(2, HIGH);
         }
         else if(data.on == 0){
           digitalWrite(2, HIGH);
         }
         else{
           digitalWrite(2, LOW);
         }
         Serial.println(data.on);
       }
       while(!Radio.available()){
         Serial.println("Error");
       }
       delay(1000);
     }

When I run the code on each respective unit, I receive only zeros on the receiver. Since I don't see where data.on could get set to zero in my code, I'm assuming there is a communication issue somehow between the two modules, even though `Radio.available()` is functioning properly.

Am I missing something obvious?

  [1]: https://www.youtube.com/watch?v=D40cgHyBLL4\

body:
The OP wrote:

The issue turned out to be that the SPI pins on the MEGA are assigned differently than the UNO, and the code was actually working the whole time. I cant thank you enough for helping me, even if it turned out to be in vain.


message:
Major difference between DTR signal and RTS signal?

I actually had a doubt about what is the difference between the RTS signal and DTR signal ?
I already know this that the DTR signal is used to auto reset when we use Arduino and similar MCUs. Can anyone say what is the major difference between these signals and what is their active state ?

body:
Electrically they are both the same. The difference is what they are used for.

DTR means Data Terminal Ready and indicates that the connected device is ready to receive data.

> Data Terminal Ready (DTR) is a control signal in RS-232 serial communications, transmitted from data terminal equipment (DTE), such as a computer, to data communications equipment (DCE), for example a modem, to indicate that the terminal is ready for communications and the modem may initiate a communications channel.

RTS means Request To Send and indicates to the connected device that it wants to send data.

> The DTE asserts RTS to indicate a desire to transmit to the DCE, and in response the DCE asserts CTS to grant permission, once synchronization with the DCE at the far end is achieved.

Basically DTR is used to indicate the presence of some equipment, and RTS is one half of hardware flow control (along with CTS) to start and stop communication.

On USB communication (e.g., using FT232 USB to UART adaptor, etc) the meaning is less clear. DTR is asserted when the port is opened (usually) and RTS is most likely not asserted at all. It's at the whim of the operating system and/or the driver whether DTR is automatically asserted or not, and whether RTS is even implemented.


body: As a counter point, industrial systems utilize the UART protocol at much higher rates - 10 Mbits for example.   RTS/CTS can prove very useful when a large data set is being received at a higher rate.  We have clients using LVDS and RS-485 IO types for the higher speeds. DTR/DSR is occasionally used to see if the other equipment is on-line but this signal pair is in the rare to use category.


body:
DTS and RTS are used on esp8266 boards with USB (Wemos, NodeMcu) to reset the board and to set io 0 low for bootloader mode. You can see it in source code of esptool.py. Sometimes you want a reset without going to bootloader mode.

    RTS = either CH_PD/EN or nRESET (both active low = chip in reset
    DTR = GPIO0 (active low = boot to flasher)

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

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


message:
l293d is not able to drive two 300 rpm motors simultaneously

I am using l293d in a line follower but recently I am facing a problem. my l293d motor driver is not able to power 2 300 rpm motors simultaneously while with one of the motors at a time it works perfectly fine. Earlier it used to drive both the motors at optimal desired speed but recently its posing the above mentioned problems. I have tried replacing the Motor driver and Arduino itself but nothing worked and I am still facing the problem.

body:
 1. Check if both channels are working in either direction individually.
 2. Check the current draw under the load per motor using an Digital Multimeter as an Ammeter function.

**The L293 is designed to provide bidirectional drive currents of up to 1A at voltages from 4.5V to 36V.
600mA per channel for L293D**

 3. As long as your motors at drawing more than 600mA per motor, it should work fine.


body:
Check your power supply with a multimeter. Look out for voltage drops under load, or similar problems.

Also, make some tests with another power supply in order to find out if the one you're currently using is faulty or not. You say you've tried replacing the motor driver and the arduino, but not the power supply.


message:
RFID+Fingerprint sensor code

I'm trying to create a security door system that uses an RFID and fingerprint sensor (Adafruit) to allow/deny access to a door. I have the fingerprint sensor and RFID hooked up to an LED, but the code isn't working very well. I want the LED to light only and only when both fingerprints and RFID are verified. Here is my preliminary code.

    //HEADERFILES
    #include <SPI.h> //rfid
    #include <MFRC522.h>//rfid
    #include <Adafruit_Fingerprint.h> //FINGERPRINT
    #include <SoftwareSerial.h> //FINGERPRINT
    #include<stdint.h> //FINGERPRINT

    //rfid settings
    #define RST_PIN         9          // rfid pin 9 RST_pin
    #define SS_PIN          10         // rfid pin 10 SS_pin
    MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
    String read_rfid;
    String ok_rfid_1 = "cbb427b2"; //white card
    String ok_rfid_2 = "0ebb14f39"; //blue key chain

    //fingerprint settings
    int getFingerprintIDez();
    // pin #2 is IN from sensor (GREEN wire)
    // pin #3 is OUT from arduino  (YELLOW wire)
    SoftwareSerial mySerial(2, 3);
    //activates serial communication on pin 2 & 3
    Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

    //output garage door pin
    int door = 7; //motor to door

    void dump_byte_array(byte * buffer , byte bufferSize) { //why so important
      read_rfid = "";
      for (byte i = 0; i < bufferSize; i++) {
        read_rfid = read_rfid + String(buffer[i], HEX);
      }
    }

    void setup() {
      //RFID setup
      Serial.begin(9600);
      // Initialize serial communications with the PC
      while (!Serial);
      // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
      finger.begin(57600);
      SPI.begin(); // Init SPI bus
      mfrc522.PCD_Init(); // Init MFRC522 RFID
      pinMode (door, OUTPUT);
      //FINGERPRINT setup
      {
        while (!Serial);  // For Yun/Leo/Micro/Zero/...
        if (finger.verifyPassword()) {
          Serial.println("Found fingerprint sensor!");
        } else {
          Serial.println("Did not find fingerprint sensor :(");
          while (1);
        }
        Serial.println("Waiting for valid finger...");
      }

    }

    // OK success!

    p = finger.image2Tz();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
    }
    }

    //DOOR/OUTPUT PIN PROPERTIES CHANGE TO REFLECT HOW FAST AND HOW LONG MOTOR     PULLS DOOR USING DIGITALWRITE; BREAK..   //USING LED FOR NOW

    void open_door() {
      digitalWrite (door, HIGH);
      delay (2000);
      digitalWrite (door, LOW);
    }

    void loop() {
      // RFID LOOP SETTINGS                                                   `
      if ( ! mfrc522.PICC_IsNewCardPresent()) {     // Look for new cards
        return;
      }
      if ( ! mfrc522.PICC_ReadCardSerial()) {       // Select one of the c ards
        return;
      }
      dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
      Serial.println(read_rfid);
      // FINGERPRINT LOOP SETTINGS

      getFingerprintID();  // start fingerprint sensor
      delay(100);

      uint8_t getFingerprintID() {
        uint8_t p = finger.getImage();
        switch (p) {
          case FINGERPRINT_OK:
            Serial.println("Image taken");
            break;
          case FINGERPRINT_NOFINGER:
            Serial.println("No finger detected");
            return p;
          case FINGERPRINT_PACKETRECIEVEERR:
            Serial.println("Communication error");
            return p;
          case FINGERPRINT_IMAGEFAIL:
            Serial.println("Imaging error");
            return p;
          default:
            Serial.println("Unknown error");
            return p;
        }

        p = finger.fingerFastSearch();
        if (p == FINGERPRINT_OK && read_rfid == ok_rfid_1) {
          Serial.println(ok_rfid_1);
          open_door();
        }

      }

**And this is the error I am getting**

    Arduino: 1.8.1 (Windows 10), Board: "Arduino/Genuino Uno"

    fingerprint:127: error: expected unqualified-id before '{' token

     {

     ^

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

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

I am new to this so please bear with me and explain in childish manner if possible.

body:
Can't say I have read what you posted here or what you're trying to do, however nonetheless I have fixed the errors in your post. This will compile no problem. Good luck with your project.

    #include <Adafruit_Fingerprint.h>
    #include <SoftwareSerial.h>
    int getFingerprintIDez();
    SoftwareSerial mySerial(2, 3);
    Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

    //HEADERFILES
    #include <SPI.h> //rfid
    #include <MFRC522.h>//rfid
    #include<stdint.h> //FINGERPRINT

    //RFID settings
    #define RST_PIN         9          // RFID pin 9 RST_pin
    #define SS_PIN          10         // RFID pin 10 SS_pin
    MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
    String read_rfid;
    String ok_rfid_1 = "cbb427b2"; //white card
    String ok_rfid_2 = "0ebb14f39"; //blue key chain

    int door = 7; //motor to door

    void dump_byte_array(byte * buffer , byte bufferSize) {
      //why so important
      read_rfid = "";
      for (byte i = 0; i < bufferSize; i++) {
        read_rfid = read_rfid + String(buffer[i], HEX);
      }
    }

    void setup() {
      //RFID setup
      finger.begin(57600);
      Serial.begin(9600);
      // Initialize serial communications with the PC
      while (!Serial);
      // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
      SPI.begin(); // Init SPI bus
      mfrc522.PCD_Init(); // Init MFRC522 RFID
      pinMode (door, OUTPUT);
      //FINGERPRINT setup
      {
        while (!Serial);  // For Yun/Leo/Micro/Zero/...
        if (finger.verifyPassword()) {
          Serial.println("Found fingerprint sensor!");
        } else {
          Serial.println("Did not find fingerprint sensor :(");
          while (1);
        }
        Serial.println("Waiting for valid finger...");
      }
    }

    // OK success!

    void open_door() {
      digitalWrite (door, HIGH);
      delay (2000);
      digitalWrite (door, LOW);
    }

    void loop() {
      // RFID LOOP SETTINGS
      if (! mfrc522.PICC_IsNewCardPresent()) {
        // Look for new cards
        return;
      }
      if (!mfrc522.PICC_ReadCardSerial()) {
        // Select one of the cards
        return;
      }
      dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
      Serial.println(read_rfid);
      // FINGERPRINT LOOP SETTINGS
      getFingerprintID();  // start fingerprint sensor
      delay(100);
    }

    uint8_t getFingerprintID() {
      uint8_t p = finger.getImage();
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
          Serial.println("No finger detected");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_IMAGEFAIL:
          Serial.println("Imaging error");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      // OK success!
      p = finger.image2Tz();
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      // OK converted!
      p = finger.fingerFastSearch();
      if (p == FINGERPRINT_OK) {
        Serial.println("Found a print match!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_NOTFOUND) {
        Serial.println("Did not find a match");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }
      // found a match!
      Serial.print("Found ID #"); Serial.print(finger.fingerID);
      Serial.print(" with confidence of "); Serial.println(finger.confidence);
    }


body:
    default:
      Serial.println("Unknown error");
      return p;
    }
    } <-- Why?

Proper indentation shows that you have an extraneous closing curly brace.


message:
Arduino MPU6050 not working due to LED PWM

I'm having some problem with the [MPU6050 example sketch][1]. I added a few bits of code of my own, so that my LEDs change color based on the yaw-pitch-roll. However when I try to run it, the values of the yaw-pitch-roll get all distorted, like this:

    ypr -38.68  -30.05  41.34
    ypr -55.42  -35.25  -31.68
    ypr -101.02 23.53   -65.01
    ypr 101.29  -19.63  12.81
    ypr -51.97  -37.49  44.85
    ypr 37.89   38.20   -37.95
    ypr 72.15   -13.70  22.68
    ypr 0.00    0.00    90.00
    ypr -45.73  74.52   -11.89
    ypr 134.36  31.89   -31.08
    ypr -13.86  -21.51  3.54

And when I disable `analogWrite` on the LED lights the yaw-pitch-roll gives normal output again.

Below is the code for changing the LED colors.

    void setColor (float red, float blue){
      int redColor = (int)255 - red;
      int blueColor = (int)255 - blue;
      analogWrite(redPin, redColor);
      analogWrite(bluePin, blueColor);
    }

Does anyone know what is going wrong here?

EDIT:

The wiring:

[![Wiring of my project][2]][2]

The code:

    // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
    // for both classes must be in the include path of your project
    #include "I2Cdev.h"

    #include "MPU6050_6Axis_MotionApps20.h"
    //#include "MPU6050.h" // not necessary if using MotionApps include file

    // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation is used in I2Cdev.h
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        #include "Wire.h"
    #endif

    // class default I2C address is 0x68
    // specific I2C addresses may be passed as a parameter here
    // AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
    // AD0 high = 0x69
    MPU6050 mpu;
    //MPU6050 mpu(0x69); // <-- use for AD0 high

    // uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
    // quaternion components in a [w, x, y, z] format (not best for parsing
    // on a remote host such as Processing or something though)
    //#define OUTPUT_READABLE_QUATERNION

    // uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
    // (in degrees) calculated from the quaternions coming from the FIFO.
    // Note that Euler angles suffer from gimbal lock (for more info, see
    // http://en.wikipedia.org/wiki/Gimbal_lock)
    //#define OUTPUT_READABLE_EULER

    // uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
    // pitch/roll angles (in degrees) calculated from the quaternions coming
    // from the FIFO. Note this also requires gravity vector calculations.
    // Also note that yaw/pitch/roll angles suffer from gimbal lock (for
    // more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
    #define OUTPUT_READABLE_YAWPITCHROLL

    // uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
    // components with gravity removed. This acceleration reference frame is
    // not compensated for orientation, so +X is always +X according to the
    // sensor, just without the effects of gravity. If you want acceleration
    // compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
    //#define OUTPUT_READABLE_REALACCEL

    // uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
    // components with gravity removed and adjusted for the world frame of
    // reference (yaw is relative to initial orientation, since no magnetometer
    // is present in this case). Could be quite handy in some cases.
    //#define OUTPUT_READABLE_WORLDACCEL

    // uncomment "OUTPUT_TEAPOT" if you want output that matches the
    // format used for the InvenSense teapot demo
    //#define OUTPUT_TEAPOT

    #define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
    bool blinkState = false;

    // MPU control/status vars
    bool dmpReady = false;  // set true if DMP init was successful
    uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
    uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
    uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;     // count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO storage buffer

    // orientation/motion vars
    Quaternion q;           // [w, x, y, z]         quaternion container
    VectorInt16 aa;         // [x, y, z]            accel sensor measurements
    VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
    VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float euler[3];         // [psi, theta, phi]    Euler angle container
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

    // packet structure for InvenSense teapot demo
    uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

    int redPin = 11;
    int bluePin = 9;

    int startR = 100;
    int startB = 10;

    int eindR = 255;
    int eindB = 255;

    int gyroMin = 0;
    int gyroMax = 80;
    int gyroRange = 0;
    float rangeR = 0;
    float rangeB = 0;

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

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

    void setup() {
        // join I2C bus (I2Cdev library doesn't do this automatically)
        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
            TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif

        gyroRange = (gyroMax - 10) - (gyroMin + 10);
        rangeR = (float)(eindR - startR)/gyroRange;
        rangeB = (float)(eindB - startB)/gyroRange;

        Serial.begin(115200);
        while (!Serial);

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

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

        // wait for ready
        Serial.println(F("\nSend any character to begin DMP programming and demo: "));
        /*while (Serial.available() && Serial.read()); // empty buffer
        while (!Serial.available());                 // wait for data
        while (Serial.available() && Serial.read()); // empty buffer again*/

        // load and configure the DMP
        Serial.println(F("Initializing DMP..."));
        devStatus = mpu.dmpInitialize();

        // supply your own gyro offsets here, scaled for min sensitivity
        mpu.setXGyroOffset(220);
        mpu.setYGyroOffset(76);
        mpu.setZGyroOffset(-85);
        mpu.setZAccelOffset(1); // 1688 factory default for my test chip

        // make sure it worked (returns 0 if so)
        if (devStatus == 0) {
            // turn on the DMP, now that it's ready
            Serial.println(F("Enabling DMP..."));
            mpu.setDMPEnabled(true);

            // enable Arduino interrupt detection
            Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
            attachInterrupt(0, dmpDataReady, RISING);
            mpuIntStatus = mpu.getIntStatus();

            // set our DMP Ready flag so the main loop() function knows it's okay to use it
            Serial.println(F("DMP ready! Waiting for first interrupt..."));
            dmpReady = true;

            // get expected DMP packet size for later comparison
            packetSize = mpu.dmpGetFIFOPacketSize();
        } else {
            // ERROR!
            // 1 = initial memory load failed
            // 2 = DMP configuration updates failed
            // (if it's going to break, usually the code will be 1)
            Serial.print(F("DMP Initialization failed (code "));
            Serial.print(devStatus);
            Serial.println(F(")"));
        }

        // configure LED for output
        pinMode(LED_PIN, OUTPUT);
        pinMode(redPin, OUTPUT);
        pinMode(bluePin, OUTPUT);
        //digitalWrite(redPin, LOW);
        //digitalWrite(bluePin, LOW);
        setColor(100.0,100.0);
    }

    void loop() {
        // if programming failed, don't try to do anything
        if (!dmpReady) return;

        // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt && fifoCount < packetSize) {
            // other program behavior stuff here
        }

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

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

        // check for overflow (this should never happen unless our code is too inefficient)
        if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
            // reset so we can continue cleanly
            mpu.resetFIFO();
            Serial.println(F("FIFO overflow!"));
            } else if (mpuIntStatus & 0x02) {
              // otherwise, check for DMP data ready interrupt (this should happen frequently)
             // wait for correct available data length, should be a VERY short wait
            while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

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

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

            #ifdef OUTPUT_READABLE_QUATERNION
                // display quaternion values in easy matrix form: w x y z
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                Serial.print("quat\t");
                Serial.print(q.w);
                Serial.print("\t");
                Serial.print(q.x);
                Serial.print("\t");
                Serial.print(q.y);
                Serial.print("\t");
                Serial.println(q.z);
            #endif

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

            #ifdef OUTPUT_READABLE_YAWPITCHROLL
                // display Euler angles in degrees
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
                Serial.print("ypr\t");
                Serial.print(ypr[0] * 180/M_PI);
                Serial.print("\t");
                Serial.print(ypr[1] * 180/M_PI);
                Serial.print("\t");
                Serial.println(ypr[2] * 180/M_PI);
                int degree = ypr[1] * 180/M_PI;
                if (degree <= (gyroMin + 10)){
                  setColor(startR, startB);
                }
                if ((degree > (gyroMin + 10)) && (degree < (gyroMax - 10))){
                  float calcR = (startR + ((degree-10) * rangeR));
                  float calcB = (startB + ((degree-10) * rangeB));
                  setColor(calcR,calcB);
                }
                if (degree >= (gyroMax - 10)){
                  setColor(eindR, eindB);
                }
            #endif

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

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

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

            // blink LED to indicate activity
            blinkState = !blinkState;
            digitalWrite(LED_PIN, blinkState);
        }
    }
    void setColor (float red, float blue){
      int redColor = (int)255 - red;
      int blueColor = (int)255 - blue;
      analogWrite(redPin, redColor);
      analogWrite(bluePin, blueColor);
    }

EDIT 2:
After a lot of testing with and without resistors and new cables (I thought there might be some sort of cable damage), it still isn't working fully. The weird thing is that when every component is hooked up via a breadboard it works (without resistors). But as soon as I try to solder everything it works randomly.

Is there a chance that the type of cable (copper vs aluminium) has any effect on this? The breadboard cables are aluminium and the soldered cables are copper.

  [1]: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050/examples/MPU6050_DMP6
  [2]: https://i.stack.imgur.com/mbojC.png

body:
You have no resistors on your LEDs. The PWM signals are causing huge amounts of noise in the MCU corrupting all your data and communications.

Add resistors (say 330Ω) to each LED cathode pin (so 9 resistors).


message:
Testing ID and Serial Communication (Update)

Here is my challenge: I have to create a sketch where I would have a prompt asking the user to enter an ID. If it is successful, it would turn on the green LED and response with "Hello, your name is so-so."  If it failed, it would turn on the red LED and response with "Invalid username! Try again."

The code is here:

    //Establish myID as CHAR data type
     char myID = 'tg123';
     //Establish testID to receive data to be tested against myID
     char testID;

     //Establish green and red LEDs to PWM pins
     const int gLED = 10;
     const int rLED = 5;

     void setup()
     {
      //Establishing baud rate at 9600
      Serial.begin(9600);
      pinMode(gLED, OUTPUT);
      pinMode(rLED, OUTPUT);
     }

     void loop()
     {
      //Act when there are data in the buffer
      while (Serial.available())
      {
        testID = Serial.read();
        //If data = myID, turn on green LED and acknowledge
        if (testID == myID)
        {
          digitalWrite(gLED, HIGH);
          digitalWrite(rLED, LOW);
          Serial.println("Hello! Your name is Trevor.");
          delay(5000);
        }
        else
        {
          digitalWrite(rLED, HIGH);
          digitalWrite(gLED, LOW);
          Serial.println("Invalid ID! Try again.");
          delay(2000);
        }
      }
     }

Two problems I have had with this:

1. The damn thing would print the line "Please enter your ID:" infinitely if it was inside the loop, so I got fed up and moved it to the set up, and
2. no matter what I enter in the serial monitor, it does not do anything.

Update: After reading Arduino's website, I found I can predefine the char data type by adding `char myID = 'tg123';`.  It is getting closer to achieving what I want, but it's exhibiting some strange behavior.  When I type in exactly tg123 in the serial monitor, it would report the error message as defined in the sketch before passing.

body:
When you use the Arduino IDE to compile your code for an Uno, it will tell you

>Sketch uses 2106 bytes (6%) of program storage space. Maximum is 32256 bytes.
Global variables use 237 bytes (11%) of dynamic memory, leaving 1811 bytes for local variables. Maximum is 2048 bytes.

as if there had been a clean and correct compilation.  However, if you compile it via `make` and a makefile (see, eg, [sudar's Arduino Makefile](https://github.com/sudar/Arduino-Makefile)) you will see a warning like the following:

>stringInit1.ino:2:14: warning: character constant too long for its type [enabled by default]
  char myID = 'tg123';

where `stringInit1` stands for whatever you call your sketch.

The `char` data type stands for a single character.  To represent a text string, use either an array of characters (for example, `char *myID = "tg123"` or `char myID[] = "tg123"`) or a `String` type (which, in general, is problematic on small-RAM embedded processors).

Then, to make the comparison, keep track of how many characters have been input so far, and as you input each character, compare it to the current character of `myID`, clearing a match-flag if characters don't match.  Eg, `if (testChar != myID[currentCount]) matchFlag = false;`.  Note, initialize `currentCount` to zero and `matchFlag` to true in `setup()` and before each retry.


body:
You are assigning a string to a single character here.

>char myID = 'tg123';

Instead you should make it a String variable. And compare it after all the characters are recieved.

>String myID = "tg123";

And Here is the modified code you should test with. In this case I have assumed you simply write the ID (string) in serial terminal and hit enter.

N.B. If you want to enter each character one by one, then it will not be able to catch the whole string. For this case you have to add some time-out to wait for next character to arrive.

    String recvData = "";
    void loop()
    {
      while (!Serial.available());
      while (Serial.available())
      {
        char ch = Serial.read();
        recvData += ch;
      }
      if (myID == recvData)
      {
        digitalWrite(gLED, HIGH);
        digitalWrite(rLED, LOW);
        Serial.println("Hello! Your name is Trevor.");
        delay(5000);
      }
      else
      {
        digitalWrite(rLED, HIGH);
        digitalWrite(gLED, LOW);
        Serial.println("Invalid ID! Try again.");
        delay(2000);
      }
      recvData = "";
     }


message:
Accelerometer MPU-6050 marks timeout in Unity

I've been having this problem, that I am trying to use an accelerometer MPU-6050 to get the rotation and pass that information to Unity.

I also have some buttons in the same Arduino. I'm using an Arduino Uno. With those buttons, everything works well, but the moment I put something related to the accelerometer in the Arduino code, Unity marks a time out. When I run it on Arduino it sends me all the info I'm asking, so I don't really know what's the problem. I really appreciate if someone could help me.

Here is code on Arduino:

    #include<Wire.h>
    #define A_R 16384.0
    #define G_R 131.0
     #define RAD_A_DEG = 57.295779
    const int MPU_addr=0x68;  // I2C address of the MPU-6050
    int AcX,AcY,AcZ,GyX,GyY;

    float Acc[2];
    float Gy[2];
    float Angle[2];
    int button = 0;
    int button2 = 0;
    int button3 = 0;

    float arriba=0, abajo=0,mouse=0;

    void setup(){
      Wire.begin();
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x6B);  // PWR_MGMT_1 register
      Wire.write(0);     // set to zero (wakes up the MPU-6050)
      Wire.endTransmission(true);
      pinMode(7, INPUT); // declare pushbutton as input
    pinMode(6, INPUT);
    pinMode(5,INPUT);
      Serial.begin(9600);
    }

    void loop(){
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
      Wire.endTransmission(false);
      //Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers

      AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
      AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
     AcZ=Wire.read()<<8|Wire.read();

      Acc[1] = atan(-1*(AcX/A_R)/sqrt(pow((AcY/A_R),2) + pow((AcZ/A_R),2)))*RAD_TO_DEG;
       Acc[0] = atan((AcY/A_R)/sqrt(pow((AcX/A_R),2) + pow((AcZ/A_R),2)))*RAD_TO_DEG;

      GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
      GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)

      Angle[0] = 0.98 *(Angle[0]+Gy[0]*0.010) + 0.02*Acc[0];
       Angle[1] = 0.98 *(Angle[1]+Gy[1]*0.010) + 0.02*Acc[1];

            button = digitalRead(7);
      button2 = digitalRead(6);
      button3 = digitalRead (5);

       //Mostrar los valores por consola
       if(button == HIGH){
     arriba=1;
      }else if(button==LOW){
      arriba=0;
      }

      if(button2 == HIGH){
        abajo=1;
      }else if(button2==LOW){
        abajo=0;
      }

      if(button3 == HIGH){  //boton 3
        mouse=1;
      }else if(button3==LOW){
        mouse=0;
      }
      Serial.print(arriba);
      Serial.print(",");
      Serial.print(abajo);
      Serial.print(",");
      Serial.print(mouse);
       Serial.print(",");

       Serial.print(Angle[0]);
       Serial.print(",");
       Serial.println(Angle[1]);

      delay(200);
    }

I know this isn't an Unity forum, but here is the code in Unity. The only thing it does, is read it and put the results in an array.

<!-- language: c# -->

    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.IO.Ports;
    using System.Globalization;
    using System;

    using UnityEngine;

    public class ConectarArduino: MonoBehaviour
    {
        string Recibidos;
        public string Linea, Linea1,Linea2;
        public int Arrib, Abajo,Boton;
        SerialPort stream;
        // Use this for initialization

        void Start()
        {
            stream = new SerialPort("COM3", 9600);
            //  stream.
            stream.Open();
            stream.ReadTimeout = 300;

        }

        // Update is called once per frame
        void Update()
        {
            try
            {
                Recibidos = stream.ReadLine();
                Debug.Log(Recibidos);
            }
            catch (System.Exception e)
            {
                Debug.Log(e.Message);
                throw;
            }

            string[] Values = Recibidos.Split(',').Select(str => str.Trim()).ToArray();
            Linea = Values[0];
            Linea1 = Values[1];
            Linea2 = Values[2];

body:
Running MPU-6050 at 57600bps seemed to be the good rate for me:

      pinMode(5,INPUT);
      Serial.begin(57600);
    }

It worked for me and I found these guys for whom it was the good rate :

From [MPU-6050-simple-library][1], specifically [MPU6050_test.ino][2]:

>     void setup() {
>       Serial.begin(57600);
>       MPU6050mgr.begin(); // Initializes IMU module
>     }

From [Another Arduino as external i2c device for MPU6050][3]:

>     void setup() {
>       Wire.begin(0x1E);                // join i2c bus with address #8
>       Wire.onReceive(receiveEvent); // register event
>       Serial.begin(57600);           // start serial for output
>     }

From [Library for Arduino and MPU-6050 communication][4]:

>     void setup() {
>       Serial.begin(57600);
>       MPU6050mgr.begin(); // Initializes IMU module
>     }

You may also find this link useful: [MPU-6050 Redux: DMP Data Fusion vs. Complementary Filter][5].

  [1]: https://github.com/dadez87/MPU-6050-simple-library
  [2]: https://github.com/dadez87/MPU-6050-simple-library/blob/master/MPU6050_test/MPU6050_test.ino
  [3]: https://www.i2cdevlib.com/forums/topic/538-another-arduino-as-external-i2c-device-for-mpu6050/
  [4]: https://www.monocilindro.com/2017/02/25/library-arduino-mpu-6050-communication/
  [5]: http://www.geekmomprojects.com/mpu-6050-redux-dmp-data-fusion-vs-complementary-filter/


message:
Attiny85 not recognized at windows startup

I'm using an Attiny85 to interact with a computer using an USB connection, and everything works fine except when I restart my computer and the Attiny85 is connected. When Windows end to boot up the Attiny85 isnt't recognized, and on Device Manager it's listed like this:

[![Unknown USB Device (Device Descriptor Request Failed)][1]][1]

If I unplug the Attiny85 and then plug it back in, everything works just fine.

Is there any to make it detectable at boot time without having to always unplug/plug it?

**EDIT:**

More details:

I'm using this board
[![ATtiny85 USB Mini Dev Board][2]][2]

and **libusb-win32** as the USB driver

  [1]: https://i.stack.imgur.com/bSScC.png
  [2]: https://i.stack.imgur.com/IAxPj.png

body:
I don't have enough reputations to make a comment so I will drop my 2 cents here.

There should be more elegant way to do this but as a fast solution I would recommend two things:

1. If it is possible, add a push button to your board to reset the MCU manually when the PC is booted up.

2. You can make a software reset after powering up the board by a certain time (e.g. 10 sec) by using watchdog timer.


message:
How many WS2811 LED strips can I control with Arduino?

Is there any limitation to connecting more strips?

I plan to create for my temple [Ganpati Street Lighting LED Decoration - Full HD Ahmednagar Mh India][1]

Watch this video and give me some ideas and suggestions.

  [1]: https://www.youtube.com/watch?v=VeGUrpI-5oQ

body:
There are three factors to consider when driving strings of these LEDs from an Arduino:

1. How much memory the Arduino has - each LED takes at least 3 bytes of RAM (possibly more depending on the library implementation). (An Uno could probably just manage 500 at most)
2. How long it takes to send the data over the wire - the more LEDs you have in a chain the longer each update takes and the slower your animations run.
3. How you power such a huge number of LEDs efficiently. You won't just plug them into the 5V pin of the Arduino that's for sure.

Note that the arrangement you link to most likely isn't a single small microcontroller controlling the whole lot. Instead it is much more likely each individual strip has a single controller and those controllers are all networked together (probably through RS-485 or CAN) to a master controller (probably a PC) to send instructions to them all.


body:
Majenko is totally right (as always).

But as an alternative solution, you could opt for SPI-based LEDstrips. They're not bound to specific timings and thus:

 1. You can "generate"/stream colors. You can let your Arduino calculate the next color and send it directly. In this way, you'll only need RAM for one pixel at the time. For the length, you're now only limited to the time it takes to update a strip.
 2. Sending of data in SPI is done in hardware and can thus be done by hardware, while your software focusses on the next job/pixel. (So you also don't need to calculate the whole strip at once, before sending)
 3. Often, you can send "pixels" much faster, by simply increasing your SPI clock. I'm not sure what the limit will be here, check the ledstrip datasheets.

Also, if you're going to push the limit of Arduino, why not use better hardware? The Teensy 3.2 is often used for ledstrip projects, since it has 64K ram and 256K flash and can run at 96Mhz  (not sure about the SPI speed). Have a look at fastled and octows as well.

You should split up this project, to make it scalable. Try to make one "row" of it and start adding more rows (with individual controllers and power).

I agree with Majenko on using RS485 or CAN to connect/command/sync these different rows.


body:
I have worked with setups similar to this. Arduino is limited as mentioned by Majenko.

If you like the Arduino platform I recommend you look into the Teensy based controllers.  They are 32 bit based and have more memory and are optimized to handle LED projects like this. Best of all, it uses the Arduino IDE with numerous libraries.  The Teensy would need to be paired with a Network adapter, so you could use sACN E1.31 and use software like Jinx to create the effects you're wanting to do.


message:
Yun UBoot Prompt Not Showing

I have a Geeetech Iduino Yun Shield. I accidentally flashed [the wrong firmware image](https://www.arduino.cc/en/Tutorial/YunSysupgrade) (not the sysupgrade) to the board. I then tried using the [Yun UBoot Reflash](https://www.arduino.cc/en/Tutorial/YunUBootReflash) method. However, when I open the console monitor from the IDE and restart/reboot the board, I do not get the UBoot prompt. I have attempted to run it at least ten times without receiving any console/serial output.

*EDIT*: The shield is running on a Leonardo base board.

Is there anything I can do to load the correct firmware onto the board and get it operational or is the board truly bricked? If so, is it possible to obtain a new Atheros AR9331 board to replace the existing one or should I buy a new Yun?

**Update**: I have tried to get the shield to do an FTP boot, [as detailed here by Majenko](https://hackingmajenkoblog.wordpress.com/2016/02/24/fixing-the-dragino-yun-board/). I get to the stage where I get the `dr_boot>` prompt. However, when I type in `tftpboot 0x81000000 dragino2-yun-common-v2.0.6-kernel.bin`, I get no feedback; it just sits there indefinitely (unless I interupt the process). I can't figure out what I'm doing wrong.

body:
The shield is very different to the real Yun when it comes to serial communication.

Typically the Atheros's UART is mapped to pins 0/1 of the shield for communication with the board it is plugged in to. Those pins are also the pins you use to communicate with the PC, so the normal YunSerialTerminal sketch can't be used.

Instead you will have to lift those pins out of the socket they go into (depending on the shield you may just be able to bend them slightly) and then manually connect them (along with ground) to an external USB to UART adaptor (e.g., FT232) to use for the communication.  Nothing needs to be installed into the Arduino board since that is now just being used as a power supply.

See [this answer](https://arduino.stackexchange.com/a/38448/25757) for which pins to use to run the shield stand-alone.


message:
Makeblock Arduino keeps stopping from motor overpower protection

I got a makeblock Arduino. Sometimes when I make it go forward at full speed, all motors stop for 3 seconds and it beeps shortly. I think it is that the motors are a little hard to turn for a moment and it stops to prevent damage to the motors. It is getting very annoying. Is there any way to disable it or make it less sensitive?

body:
It is unlikely the pause in operation is because of the motors.  It is more likely the [Makeblock][1] is stopping because the  motor controllers are too hot.  Next time try to identify which chips on the board are controlling the motors and test if they are getting hot to the touch.  If so, consider adding heat sinks to these chips to mitigate any heat dissipation problems.

An alternative explanation involves a limited power supply.  It could be that when the motors are demanding high current, the voltage drops and the processor resets.  Consider a power supply that can offer more amperage.  Or larger capacity batteries.

  [1]: http://wiki.makeblock.cc/index.php?title=Getting_Started_with_Makeblock


message:
HC-SR04 pulse at multiple angles

I have a HC-SR04 sensor mounted on a stepper motor, mounted on a car.
The idea is this:

 - The car moves forward with the ultrasonic sensor facing the front
 - If the sensor reads a small distance the car do the following:
       - Stop
       - Turn the sensor to the left and get a new distance
       - Turn the sensor to the Right and get a new distance
       - Drive slightly backward
       - The car turns the to direction the distance was the highest
       - Drive forward again

I think I must have wrongly understood how the echo/ultrasonic sensor works. Because when I read values to the left and right, it will always return zero, but reading values when driving forward works very well.

Below is the relevant code

    //Trigger
    void triggerEcho(){
      digitalWrite(echoTrigPin,LOW);
      delayMicroseconds(5);
      digitalWrite(echoTrigPin,HIGH);
      delayMicroseconds(10);
      digitalWrite(echoTrigPin,LOW);
    }

    //Trigger, receive and calculate distance (cm)
    long getEchoDistance(){
      triggerEcho();
      pinMode(echoRecPin, INPUT);
      long echoDuration = pulseIn(echoRecPin, HIGH);

      return echoDuration / 58;
    }

    void loop(){

      long distance = getEchoDistance();

      //If front obstacle is encountered
      if((distance < 5) && (distance != 0)){
          carStop();
          servo.write(180);                     //turn echo sensor left
          delay(250);
          long distanceL = getEchoDistance();   //trigger and read sensor value
          servo.write(0);                       //turn echo sensor right
          delay(250);
          long distanceR = getEchoDistance();   //trigger and read sensor value

          //this will always show distance as 0
          Serial.print("  LEFT :"); Serial.print(distanceL); Serial.print("\n");
          Serial.print("  RIGHT:"); Serial.print(distanceR); Serial.print("\n");

          carDriveBackward(135, 1.185, 1.0);     //drive backwards
          delay(250);
          if(distanceR>distanceL)                //turn in the direction that was furthest
            carTurnRight(100,1250);
          else
            carTurnLeft(100,1250);
          carStop();
          servo.write(90);                        //face sensor forward
          delay(250);
        }
        else
          carDriveForward(135, 1.185, 1.0); //R - L
    }

I bet something is wrong with how I'm implementing the `triggerEcho()` and `getEchoDistance()`. I excluded anything on the wiring and pins, as the reading of the distance is very correct when reading the facing the front.

body:
I doubt you have misunderstood the way ultra sound works.  You send a pulse and then go quiet waiting for a reply.  The time it takes to send the pulse is the minimum distance you can detect things at.

If you are not getting returns left and right then it could be there is nothing there or turning the head is breaking a connection.

Firstly jack the vehicle up off the floor so it doesn't go anywhere.
Place a solid object (book) in front of the vehicle and make sure it detects it.
Now place the same object to the right of the vehicle, do it detect it?
Stop the US sensor when it is looking right (by killing the power) and check that it is looking horizontally.  Check the connections, are they being pulled loose?

Your code looks fine, you US works forwards so I think it is a mechanical issue with your car.


message:
NodeMCU with RFID RC522 and I2C interface LCD module together

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

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

I'm newbie in Arduino programming so I hope to get a clear answer.

I have NodeMCU v1 12-E, I connected it with RFID RC522 as in attachment picture.

Now my question:
I need to connect I2C interface LCD module with it to print some words in.
The RFID use the default SDA and SCL pins on NodeMCU V1.0 "D1 and D2" also when I see wiring for the LCD I2C it use same D1 and D2 pins.
So now if I change the RFID instance creation code to

    MFRC522 mfrc522(0,2);

    //SS_PIN 3 RST_PIN 4

Is the RFID will work as previous pins and the LCD will work also?

body: You can have multiple devices on the I2C bus so long as they all have different addresses.  This means you should be able to connect D1 and D2 to the RFID and LCD.  HOWEVER I'm not sure that you are using I2C to talk to the RFID board, if you aren't then you may need to move the RFID boards pins and leave I2C on D1&2.