body:
I have an extrange Problem...
I have written this short code:

    ////////////// BOARD SETTINGS \\\\\\\\\\\\\\
    #define BAUD_RATE 9600

    // Board type selection
    // Uncomment the wanted
    //#define WAND 0
    //#define GUN 0
    #define RIFLE 0

    ////////////// WAND SETTINGS \\\\\\\\\\\\\\
    #ifdef WAND
    //#define USE_CHARGER 0

    #endif

    ////////////// GUN SETTINGS \\\\\\\\\\\\\\
    #if GUN
    //#define USE_CHARGER 0

    #endif

    ////////////// RIFLE SETTINGS \\\\\\\\\\\\\\
    #ifdef RIFLE
      #define USE_CHARGER 0

    #endif
It's in a file called `Settings.h`, that I use in the main code:

    #include "Settings.h"

    void setup(){
      Serial.begin(BAUD_RATE);
      #ifdef WAND
        Serial.println("Initializing Wand...");
      #endif
      #ifdef GUN
        Serial.println("Initializing Gun...");
      #endif
      #ifdef RIFLE
        Serial.println("Initializing Rifle...");
      #endif
    }

    void loop(){
      #ifdef WAND

      #endif
      #ifdef GUN

      #endif
      #ifdef RIFLE

      #endif
    }
But for an extrange reason, it gives me this error: `error: #endif without #if`
Full error is:

    In file included from D:\MEGA\Winsoft\Projects\Hardware\MWands\Arduino_5\Arduino_5.ino:1:0:

    Settings.h:15: error: #endif without #if

     #endif

      ^

    Settings.h:21: error: #endif without #if

     #endif

      ^

    Settings.h:27: error: #endif without #if

     #endif

      ^

    exit status 1
    #endif without #if
Any idea in where am I wrong?

And taking advantage that I'm asking, is necessary the 0 after `#define RIFLE 0`, next to each definition?

title: #endif without #if

Answers: 2

body:
If you remove backslashes at the end of comments on lines before `#ifdefs`, it will work just fine.

The gvim editor was much more helpful in that:
[![enter image description here][1]][1]

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

body:
It looks like your comment style is causing the problem.

Remove the `////////////// BOARD SETTINGS \\\\\\\\\\\\\\` style comments, or change them to something like: `/*----------- BOARD SETTINGS -----------*/`


body:
I am making an LED circuit for a Lobot (from star wars) costume headset that will not be on a PCB or stripboard. It will all be running inside the walls of the plastic shell I am making. Please see Gif of what I am hoping to do:

[![Gif of Lobot from the star wars in action][1]][1]

EDIT:
-----
The LEDs will run through 4 different programs. Here is one program as an example:

-Far left and right led pairs will alternate on/off
-Single LEDs will blink twice then off for a cycle
-The (4) pairs on the left and right will rise and fall like a soundboard
-The (3) pairs of white(blue in the demo) will chase bottom to top and back down again

I am new to electronics so I am a little nervous about running the ground wire for it. Here is my circuit:
## EDIT 2: ##

Here is a reworked diagram based on the suggestions i received below:
[![Circuit with resistors][2]][2]

The reds were switched to blue for the simulation but will actually be white. So they are 3v each but running in parallel will need 100ohm.

Now that we have that out of the way, is the ground wire run correctly?

The simulation runs perfectly, but I want to make sure that I am not overlooking something important before I try it on my arduino IRL. Is there a neater way to do this? Google searches availed me not. What is the accepted method for this type of circuit?

  [1]: https://i.stack.imgur.com/1FHVv.gif
  [2]: https://i.stack.imgur.com/ktXVY.jpg
  [3]: https://i.stack.imgur.com/9LJWI.gif

title: Arduino Nano Circuit grounding

Answers: 2

body:
The schematics is unfortunately somewhat complicated to read as one has to look at the pinout to understand it. When comparing it to the [pinout](http://www.keywild.com/arduino/gallery/Nano_PinOut.png) however I find a few things that are odd, e.g. one of the green wires (top, fourth pin from the right) is connected to GND.

Note that the sum of the forward voltages of the LEDs connected in series need to be (significantly) lower than the supply voltage of the Arduino. This forward voltage is different for differing LEDs (depending on the colour). Blue LEDs have a higher voltage (typically 3.0 - 3.5 volts). Connecting two blue LEDs or some more red LEDs in series leads to a necessary forward voltage higher than what the Arduino can provide.

Be sure to add the current limiting resistor for the LEDs in the appropriate places. Due to the non-linear current-voltage characteristic of (light emitting) diodes those resistors are a must-have (unless driving them with a current source, which the Arduinos GPIO pins are not). Do use one resistor per LED or if LEDs are connected in series. Do not use only one resistor for LEDs wired in parallel. For more details on this topic see [here](https://electronics.stackexchange.com/q/32990/52154).

**Edit to add** ([revision of question](https://arduino.stackexchange.com/revisions/37893/4)):

Given 3 V forward voltage and 100 Ohm series resistor one LED presumably leads to a current of about 20 mA. But since you intent to drive two LEDs in parallel (so 40 mA) from each pin, you're well out of spec and hitting Absolute Maximum Ratings:

DC current rating, [source](https://www.arduino.cc/en/Main/arduinoBoardMicro#techspecs):

> DC Current per I/O Pin . . . . . . . . . . . . . . . . . .  20 mA

Absolute Maximum Rating, [source](http://www.atmel.com/Images/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf)

> DC Current per I/O Pin . . . . . . . . . . . . . . . . . .  40.0mA

Furthermore you intend to connect 18 pairs of LEDs (give or take the red LEDs). This would be a total current of 720 mA which is significantly above the limits of the microcontroller. Consider that all the current flowing through the LEDs into the GPIO pins also needs to flow to VCC through the controllers power supply lines (just two pins!). Those have limits too:

Absolute Maximum Rating, [source](http://www.atmel.com/Images/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf)

> DC Current VCC and GND Pins  . . . . . . . . . .  200.0mA

You need an external driver (such as the ULN2803, as presented in [this answer](https://arduino.stackexchange.com/a/37899/17196)) or transistors.

body:
I am putting all comments here as answer.
Micro, Macro, Nano, Uno, Mega... It doesn't matter, all run at 5V. Your schematics won't work.Ghanima is giving you basic, but MUST components. Also i would suggest to use ULN2803 chips. Easy to use transistors. You won't need to calculate resistors for transistors :D

Additional, your arduino will burn in first few seconds, because the current will be to big. you should not drive LEDs from Arduino.

To make it SUPER COOL i would suggest [WS2812B][1] LEDs. They need 5V, GND, and Data in. And you can make it any color you want and control all LEDs separately.

[Some video about WS2812B][2]

I would strongly recommend it.

  [1]: http://www.seeedstudio.com/document/pdf/WS2812B Datasheet.pdf
  [2]: https://www.youtube.com/watch?v=KaClIgAVuI8


body:
I have a 4*4 keypad and I want to use it to enter a number.  I will then use this number as a delay to a LED or a motor to run for the specified time.
This is my sample code:

    #include<Keypad.h>
    #include<LiquidCrystal.h>
    const byte numRows = 4; //number of rows on keypad
    const byte numCols = 4; //number of columns on keypad

    char keymap[numRows][numCols]=
    {
    {'1', '2', '3', 'A'},
    {'4', '5', '6', 'B'},
    {'7', '8', '9', 'C'},
    {'X', '0', 'Y', 'D'}
    };

    char value[4]="";
    int index = 0;

    byte rowPins[numRows] = {22,23,24,25}; //Rows 0 to 3
    byte colPins[numCols]= {26,27,28,29}; //Columns 0 to 3

    Keypad key= Keypad(makeKeymap(keymap), rowPins, colPins, numRows,numCols);

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    void setup() {
    Serial.begin(9600);
    pinMode(13,OUTPUT);
    lcd.begin(20,4);

    lcd.print("       WELCOME      ");
    delay(100);
    }

    void loop() {
    char keypress = key.getKey();
    while (keypress != NO_KEY){
      if (keypress == 'X'){
          lcd.clear();
          for(int j=0;j<=4;j++){
            value[j]=0;
          }
          index=0;
          }
       else if (keypress == 'Y'){
          int amt = atoi(value);
          digitalWrite(13, HIGH);
          delay(amt);
          }
       else
          value[index]=keypress;
          index++;
        }
    }

How do I read the value returned by the keypad as an integer?  (When I press 3 I want to read 3 not "3").

title: Using a 4*4 keypad to enter an integer value

Answers: 2

body: Your problem is that you have your keypress matching inside a while loop. That means it will, once matched once, continue matching over and over again as infinitum. You need to replace your while with an if so it only runs once for each keypress.

body:
You can easily read by this line of code

    value = anyDigitFromKeypad - 48

e.g value = "3"-48 = 3


body:
I'm completely new to Arduino or even micro-controllers, I'm not even good in physics.

First of all, I'll explain what I am trying to build:

I have an Arduino Nano, for a university project (computer science) I'm trying to make an alternative controller(HID). This controller will be a simple glove, which contains conductive yarn from the Arduino to each finger. If two fingers connect their conductive yarn, I know which fingers are connected and I map this to an input for the computer, which I connected to the Arduino.

For example, if the thumb touches the index finger, it means an `X` on the computer.

To get the code done is not the problem I guess.

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

Since I'm completely new, I have some pretty basic questions:

1) Can I use the circuit diagram I created or won't it work? Imagine the switches are my hand, which works like a switch.

2) Does my circuit need a connection to 5V and ground, or can one of the pins be a GROUND / 5V?

3) To know if a switch is active, do I have to watch for changes on the pin? For example, the pin is LOW, is it HIGH after the circuit is "closed"?

If you guys can provide me further information for my project or nice tutorials to get in touch with micro-controllers, I would really appreciate it.

Thank you in advance!

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

title: Basic questions on Inputs

Answers: 2

body:
>1) Can i use the circuit diagram i created or wont it work?

It won't work. The reason is when the switches are open the input pins are floating and that means they could be `HIGH`or `LOW` or flipping back and forth. You want the pins to be always in a specific state whether the switch is open or closed. To do this a pull-up or pull-down resistor is used. This resistor sets the pin to `HIGH` or `LOW` respectively when the switch is open but the value of the resistor is chosen so that when the switch is closed it overpowers the resistor and the pin reads the opposite state. Since you have your switches connected between the input pin and 5 V you would need to add a pull-down resistor to every pin. That's easy enough but there is an even easier way. The microcontroller on your Nano has internal pull-up resistors you can turn on by doing this:

    pinMode(inputPin, INPUT_PULLUP);

See: https://www.arduino.cc/en/Reference/PinMode

So using the internal pull-ups meas you wouldn't need to add any extra components. But a pull-up isn't helpful if you have your switches connected to 5 V because that would make the pin read `HIGH` whether the switch is opened or closed. So you would need to connect the switches to GND instead. This would mean that the input pin will read `HIGH` when the switch is open and `LOW` when the switch is closed.

>3) To know if a switch is active do i have to watch for changes on the Pin?

Of course. The easiest way to do this is with `digitalRead()`.

See: https://www.arduino.cc/en/Reference/DigitalRead

You need to make sure your code is non-blocking. When blocking code like `delay()` is used the microcontroller will not be able to check the state of the input pins and so you could miss touches or have the controller not be responsive enough.

body:
When you're dealing with switches, you need to watch out for 'bounce'. This means that a switch is never perfect and when it changes state from ON to OFF or vice versa, usually there are several fluctuations that take place before the switch settles on a final ON/OFF value.

You could debounce your switches by either hardware or software. If you're debouncing your switches by software basically you run a check on each switch to see if it's digital value has stabilised over some finite time period (usually a few milliseconds) and take action on the switch value only AFTER its value has stabilised.

Hardware debouncing makes use of capacitors in your circuit that prevent high frequency fluctuations in the line from reaching your digital pin. Put simply, the capacitor acts like a channel to 'drain' away variations in voltage. If you are implementing hardware debouncing, you can just do a digitalRead() to read your pin.

http://dduino.blogspot.in/2012/03/arduino-button-debouncing.html


body:
I was actually thinking to buy a cheap HC-05 module while I was searching I found a similar (think so) [module](https://m.aliexpress.com/s/item/32616503772.html) It say it is a replace for HC modules.

Is it compatible with Arduino Nano and will it work same as the HC-05 module ????

title: SPP-C and HC-05 are they the same thing or something else?

Answers: 2

body: Yes, both the SPP-C and HC-05 are compatible with the Arduino range, and they do work in pretty much the same manner!

body:
In theory they are the same and have the same capabilities. Practically they are not. With SPP-C you get twice the headache for half the price as for HC-05. In had to find it out the hard way [Sending data using Bluetooth SPP-C Module without a Breakout-Board][1]. I tried both SPP-C and HC-05 with and without breakout boards finding the same issues. So if you are willing to spend time, risk your project and save some money then use SPP-C. Otherwise use the well known HC-05.

  [1]: https://arduino.stackexchange.com/questions/26873/sending-data-using-bluetooth-spp-c-module-without-a-breakout-board


body:
Can I connect an Arduino Uno Wifi to Arduino Cloud? If yes, how? If no, what cloud is compatible?

I have tried to look online but I could not find anything that raises this question.

Answers: 1

body:
If you sign in to Arduino Cloud the very first thing it asks you is which board you are using. One of the options is the Arduino WiFi Shield 101. That is a shield that you can attach to any Uno-footprint board (including the Uno) to give it encrypted WiFi.

Another option is the Yun shield which turns your Uno into a kind-of Yun.

There are many many other "clouds*" that support Arduino, and many that if you are a reasonable programmer should be simple enough to make work with Arduino, since 99.99% of them all work through some form of HTML-based interface.

----

* Cloud: *n.* An idiotic buzzword used to describe pretty much any website these days.


body:
I got given a Fio V3 but unfortunately the MicroUSB port is missing, not sure why.  Is there any other way to program it?  I'm thinking perhaps those 6 pins under the microcontroller?

[![fiov3][1]][1]

Also can I still power the board?  I notice it doesn't have a VCC or RAW pin like the Pro Micro version.  I'm not to worried about using a battery, can I plug any matching voltage into the battery plug?

I tried looking through the schematics and tutorials on Sparkfun but don't really know what I'm looking at.  Here are some relevant links anyhow:

* [Product page][2]
* [Schematics][3]
* [Datasheet][4]

  [1]: https://i.stack.imgur.com/e32KL.jpg
  [2]: https://www.sparkfun.com/products/11520
  [3]: https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/Arduino-Fio_v31.pdf
  [4]: https://cdn.sparkfun.com/datasheets/Components/General IC/33244_SPCN.pdf "Datasheet"

title: How to program Fio v3 without MicroUSB port

Answers: 2

body:
The board runs at 3.3V, so you can provide 3.3V directly into the 3.3V pin on the side. Also the black connector next to the USB socket is a battery connection for a Li-Ion battery or similar. It will take any voltage between 3.6V and 5V. Any higher and, according to the schematics, you need to remove the solder link that's just below the battery connector (silver blob). With that link removed you can theoretically go up to 20V on the battery input.

Yes, you can program through the 6-pin header below the main chip if you have a suitable hardware programmer (e.g., USBASP). That is a normal ICSP header like most Arduino boards have.

body:
Looking at the hook up guide might help.  https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide

The "best" solution might be to try and get the connector replaced, if the pads are still OK.  But soldering those connectors is not an easy task.

The datasheet you linked to is the Lion charger, forget about that PDF.


body:
I've not used my Arduino for about 2 months. Before this time it worked fine, but now when I want to upload my program I get this error:

> Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.

I reset immediately after uploading but it doesn't work.What else should I do?
I'm using Ubuntu and the Arduino IDE.

title: I can't upload my program to Arduino Uno

Answers: 2

body:
Checks:

- Check if the board has power (probably it will).
- Check if the board is shown at the ports in the IDE (i.e. COM3: Arduino Uno).
- Check if you put the correct board in the IDE (e.g. Uno, Mega etc.).
- Check if you have multiple versions of the IDE running.
- Check if you have multiple IDEs installed.
- Check if you don't have the RX pin used while uploading a sketch.

Try the following:

- Use a different USB port on your computer
- Use a different USB cable
- Reinstall the Arduino IDE

body:
I struggled with a failure to upload the `Blink` program, with LED between #13 pin (+) and GND lead.

My solution was found by choosing other serial ports by stepping through the Serial Port options under the **Tools** menu

Selecting the correct port brought my new board to life!


body:
How can I program in Arduino Uno a `serial.available` that will detect some chars that aren't supposed to belong in a list of options, like this:

    void lerRespostaUtilizador(){
      if(Serial.available('s' && 'v' && 'r'){
        Serial.println("Podes visualizar: (s)inais de controlo, (v)ariaveis do sistema e conteudo de (r)egistos.")
      }
      switch(Serial.read()){
        case 's': // Mostrar sinais de controlo
          mostrarSinais();
          Serial.println("Podes visualizar ainda: (v)ariaveis do sistema e conteudo de (r)egistos.");
          Serial.println("");
          break;
        case 'v': // Mostrar variáveis do sistema
          mostrarVariaveis();
          Serial.println("Podes visualizar ainda: (s)inais de controlo e conteudo de (r)egistos.");
          Serial.println("");
          break;
        case 'r': // Mostrar conteúdo de registos
          mostrarRegistos();
          Serial.println("Podes visualizar ainda: (s)inais de controlo e (v)ariaveis do sistema.");
          Serial.println("");
          break;
        }
    }

What I want is if the user inserts some chars that aren't 's', 'v' or 'r', a message will appear saying what they can insert to obtain certain results.

title: Detect certain characters and if not a consequence

Answers: 1

body:
I would rewrite that as something like this:

    void lerRespostaUtilizador(){
      while (!Serial.available());
      switch(Serial.read()){
        case 's': // Mostrar sinais de controlo
          mostrarSinais();
          break;
        case 'v': // Mostrar variáveis do sistema
          mostrarVariaveis();
          break;
        case 'r': // Mostrar conteúdo de registos
          mostrarRegistos();
          break;
        default:
          Serial.println(F("Podes visualizar: (s)inais de controlo, (v)ariaveis do sistema e conteudo de (r)egistos."));
        }
    }


body:
I've just started with the I2C protocol. I read about it in the datasheet, other documents, blogs and videos.

So, I started to develop my code and I think I did my first success, I succeeded to send start and check TWST for sending start signal.

I get started OK, but I can't proceed to send data. What I'm missing? I'm thinking I didn't send the correct address.

    void I2C_init(void);
    void I2C_start(void);
    void I2C_stop(void);
    void I2C_tx(uint8_t data);
    void I2C_TWSR_Check(void);

    void setup() {
      Serial.begin(9600);
      I2C_init();
      //  I2C_TWSR_Check();
      I2C_start();
      I2C_TWSR_Check();
      I2C_tx(0x40);           // sending the address
      I2C_TWSR_Check();       // waiting for response
    }

    void loop() {
      uint8_t i;
      // simple loop to blink an LED on the I/O expander pin
      for (i=0;i<5;i++) {
        I2C_tx(0xff);
        I2C_TWSR_Check();
        _delay_ms(500);
        I2C_tx(0x00);
        I2C_TWSR_Check();
        _delay_ms(500);
      }
    }

    void I2C_init(void) {
      //set SCL to 100kHz
      TWSR = 0x00;
      TWBR = 0x48;
      //enable TWI
      TWCR = (1<<TWEN);
    }

    void I2C_start(void) {
      TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
      while (!(TWCR & (1<<TWINT)));
    }

    void I2C_stop(void) {
      TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
    }

    void I2C_tx(uint8_t u8data) {
      TWDR = u8data;
      while (!(TWCR & (1<<TWINT)));
    }

    void I2C_TWSR_Check(void) {
      uint8_t Status;
      Status = TWSR & 0xF8;
      switch(Status) {
        case 0x08: // start OK
        Serial.println("Start is OK");
         break;
        case 0x10: // Re start
        Serial.println("Re start");
         break;
        case 0x18: // SLA+W OK ACK
        Serial.println("SLA+W OK ACK");
         break;
        case 0x20: // SLA+W no ACK
        Serial.println("SLA+W no ACK");
         break;
        case 0x28: // data OK ACK
        Serial.println("data OK ACK");
         break;
        case 0x30: // data OK no ACK
        Serial.println("data OK no ACK");
         break;
        case 0x38: // arbitration lost in SLA+W or data TX
        Serial.println("arbitration lost in SLA+W or data TX");
         break;
         default:
         Serial.println("Error");
        break;
      }
    }

title: I2C begginer with I/O expander with mega328p C code

Answers: 1

body:
OK the answer is that I didn't send the correct address!

Because if the I2C starting command with the slave is successful, then you should get successful sending ACK according reading the value of transmission status from the status register TWSR and ANDing this value with 0xF8. Then by reading the datasheet you know the value of transmission status. I developed a function to determine the status of transmission with Arduino Serial library which is I2C_TWSR_Check();.

I did this code for Master transmitter and receiver only.

So the trick is that you have to fix the address according to the AVR's TW address command format, which is the first bit is for read/write command and the remaining 7-bits are for the address, so you have to shift the real address which I got by "I2C address scanner" I got from one of AVRfreaks members.

For example, if the address is 0x20, then after shifting it 1-bit to the left, the new address is 0x40 for write operation and 0x41 for read operation.

    void I2C_init(void);
    void I2C_start(uint8_t address);
    void I2C_stop(void);
    void I2C_tx(uint8_t data);
    uint8_t I2C_rx(void);
    void I2C_TWSR_Check(void);

    uint8_t bitmask;

    /////////// I2C modules addresses ////////////
    // 8-bit I/O expander 0x20
    #define IOEXP_WR  0x40    // I/O 8-bits expander address
    #define IOEXP_RD  0x41

    // LCD1602 adapter
    #define LCD1602_WR  0x4E  // LCD1602 I2C adapter address
    #define LCD1602_RD  0x4F

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

    void loop() {

      I2C_start(LCD1602_WR);
      I2C_TWSR_Check();
      I2C_tx(0xff);
      I2C_TWSR_Check();
      I2C_stop();
      _delay_ms(500);

      I2C_start(LCD1602_WR);
      I2C_tx(0x00);
      I2C_stop();
      _delay_ms(500);
    }

    void I2C_init(void)
    {
      //set SCL to 100kHz
      TWSR = 0x00;
      TWBR = 0x48;
      //enable TWI
      TWCR = (1<<TWEN);
    }

    void I2C_start(uint8_t address)
    {
      TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
      while (!(TWCR & (1<<TWINT)));
      //I2C_TWSR_Check();
      TWDR = address;
      TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
      while (!(TWCR & (1<<TWINT)));
      //I2C_TWSR_Check();
    }

    void I2C_stop(void)
    {
      TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
    }

    void I2C_tx(uint8_t data)
    {
      TWDR = data;
      TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
      while (!(TWCR & (1<<TWINT)));
      //I2C_TWSR_Check();
    }

    uint8_t I2C_rx(void)
    {
      TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
      while (!(TWCR & (1<<TWINT)));
      return TWDR;
    }

    void I2C_TWSR_Check(void)
    {
      uint8_t Status;
      Status = TWSR & 0xF8;
      switch(Status)
      {
        /////////////// MASTER TRANSMITTER //////////////
        case 0x08:
        Serial.println("Start is OK");
         break;
        case 0x10:
        Serial.println("Re start");
         break;
        case 0x18:
        Serial.println("SLA+W OK ACK");
         break;
        case 0x20:
        Serial.println("SLA+W no ACK");
         break;
        case 0x28:
        Serial.println("data TX OK ACK");
         break;
        case 0x30:
        Serial.println("data TX OK no ACK");
         break;
        case 0x38:        // arbitration lost in SLA+W or data TX
        Serial.println("arbitration lost in SLA+W or data TX");
         break;

        /////////////// MASTER RECEIVER //////////////
        case 0x40:
        Serial.println("SLA+R OK ACK");
         break;
        case 0x48:
        Serial.println("SLA+R OK NO ACK");
         break;
        case 0x50:
        Serial.println("data RX OK ACK");
         break;
        case 0x58:
        Serial.println("data RX OK NO ACK");
         break;

         default:
         Serial.println("Error");
        break;
      }
    }


body:
Can someone please explain to me, like I'm 5, why this circuit does not work?

[![Led no resistor][1]][1]

Every resistance calculator I use says that there is not enough voltage to calculate a resistance. If I understand correctly, wouldn't the LEDs light but just at a lower brightness?

Using R = V/I, The source voltage is 5v, the LED voltage is 6 divided by the current of 20mA equals -50ohms. All of the charge is used up by the time it reaches the arduino right?

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

title: LED series Resistor- Noob question

Answers: 4

body:
LEDs won't necessarily light at lower brightness (or conform to Ohm's law at all), it's explained [here][1]. If an appliance apparently does provide a "dim" LED mode, it's usually using a clocked signal (and blinking rapidly).

  [1]: https://electronics.stackexchange.com/questions/256336/does-led-brightness-change-with-voltage

body:
The two LEDs in series have a forward voltage of 6v which is more than the Arduino's supply voltage.

Forward voltage is the bare minimum amount of voltage required for the LEDs to start conducting electricity (ie: to allow the current to pass through)

Read this: https://www.baldengineer.com/led-basics.html :

> Forward Voltage
>
> The Forward Voltage defines the amount of voltage
> required in order to conduct electricity. Any voltages below this
> amount will cause the LED to remain “Open” and non-conductive. This
> also means any components in-series with the LED will not have current
> flowing through them either! Once the voltage dropped across the LED
> reaches the Forward Voltage, it will begin to conduct electricity. Not
> only that, but the LED will only drop its Forward Voltage at any given
> time.
>
> For example, consider a LED with a Forward Voltage rated at 3.0V. Now
> what happens if you attach the Anode to the Positive (+) Terminal of a
> AA (LR-6) Battery and the Cathode to the Negative (-) Terminal? Will
> the LED do anything? No! The AA (LR-6) Battery only has a nominal
> voltage of 1.5V. Until you add a second battery, the LED will not
> light up.

body:
The simple reason is that LEDs are not light bulbs. An LED is not a passive device and does not follow Ohms law.

To a first approximation if the voltage across an LED is below the forward voltage then no current will flow. In that situation the voltage across the LED pins is whatever the supply voltage is.<br>
If the voltage across an LED is over the forward voltage then an unlimited current can flow and the voltage between the pins is fixed at the forward voltage.

This approximation isn't perfect but 90% of the time it's good enough.

So with 1 LED and no resistor you get 3V over the LED and then 2V left over with zero resistance, I=V/R = 2/0 = infinite current flow. The LED is dissipating 3*infinity watts of energy and instantly vaporizes. Clearly this isn't exactly what happens in the real world but the result is enough to tell you that bad things will happen.

With 1 LED and a 200 ohm resistor you get 3V over the LED and then 2V extra with 200 ohms resistance, I=V/R = 2/200 = 10mA. The LED is within its operating current and will light up.

With 2 LEDs and no resistor you get 3V on one LED and 2 V on the second (or 2.5 on both if you prefer). Either one or both LEDs are below their forward voltage and so no current flows. The LEDs remain off.

body:
 > Can someone please explain to

With the right leds, the circuit can work.

Where it may fail:

1. Two less with combined forward voltage greater than the one applied to them. The meds wouldnt light up or wouldn't light up brightly, depending on the leds used.

2. The two leds with combined forward voltage much less than the supply which has low output resistance. The two leds may light up very brightly, or so briefly ending up in led heaven permanently. If you can capture them in high frame rate code on the glow before their death is quite pretty.


body: I am a long time participant in a competition called [Robocup Rescue Line](http://rcj.robocup.org/rcj2016/rescue_line_2016.pdf). For next year's competition, I am building a robot (and the code for the robot) from the ground up. The tasks that the robot has to do are complex enough for the code to be a fairly complex thing. I have some experience with classes and OOP so I thought I could try to organize the code in a OOP fashion. I thought I could have a class for each type of Sensor (e.g: LineSensor(), RGBSensor UltraSound()...) and another for the Motors (e.g: Motor()) that would have two instances on the code. Basically, all the code has to do is take sensor readings and produce a motor response. With this class structure, where would I do this correspondence? Is this not appropriate for this kind of project? Is there a better way to do this, that is still OOP?

title: Should I use OOP?

Answers: 1

body:
I have a lot of experience with OOP, but mostly in embedded/pure software designs. However, I'm sure you can use it in a robot project too.

Avoid creating lots of objects dynamically, this results in gap in the very small memory available for the Uno. Try to create the object instances beforehand (this will also benefit performance hits during execution, by placing it into the initialization).

About the Sensors: you can make a baseclass if needed (Sensor) and let other classes derive from it (there is a small performance hit when calling methods though).

For the controlling:

- Put sensor readings in the sensor classes
- Put motor responses in the motor classes
- Put the control in a special class (Control?) that couples the sensor response to the motor response.


body:
Specifically, I want to add multiple relays (approximately 36 to 40) to an Arduino Uno board (using only a few pins). I found a solution using ShiftOut. You can take a look [here][1]. But here the example is for testing small LEDs bulbs.

I will control high-voltage electricity like fans, tube lights, washing machine with those relays, so what will be a proper graph or image diagram for that? And if you have any more suggestions for me then you can tell me :) And yes please tell me what I should use for it.

Right now am thinking to use an Arduino, relays, 74HC595 IC only. My diagram for controlling LED is like this:

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

You can edit it. I just need proper guidance for it and a few good suggestions.

  [1]: https://www.arduino.cc/en/tutorial/ShiftOut
  [2]: https://i.stack.imgur.com/QQgZZ.gif

title: Need a proper diagram to connect my multiple relays (more than 8) with only a few pins on Arduino Uno Board

Answers: 2

body:
If you want to drive a normal magnetic relay you will need to add a transistor / resistor to the output of the 74HC595 as the current is too high across the magnet of the relay to be driven directly by the 74HC595. If you don't want to use a transistor for every relay, you could you an 8 channel driver chip like the ULN2803A. You should be able to connect your relay coil directly from 12v and to the ULN2803A.

Have a look at this page for an example. http://www.mcmajan.com/mcmajanwpr/blog/2014/04/18/arduino-how-to-connect-many-12v-relays-en/

body:
What about using an I2C I/O expander like MAX7328 or equal and a ULN28XX as relay driver. and you can connect several I/O expanders to the same I2C buss with different addresses.

This will use minimal amount of pins and minimal amount of components.


body:
I had a code that implements Kalman noise filtering on Arduino, and there is a use of malloc() and free(). I'm wondering if this will affect the Arduino or not (for example, the program will not function as I wanted, ...).

This is because when I got all raw (unfiltered) data and wrote the same Kalman Noise Filter function on Matlab, the filtering works well. However, when I write this FKalman function directly in Arduino, it doesn't work like it did on Matlab.

The Kalman Noise Filter is based on this article: http://www.bzarg.com/p/how-a-kalman-filter-works-in-pictures/

Here is the code (just have a look at the function Fkalman and the tick, ignore the other parts):

    #define START_MSG

    #define NBDATASEND 6
    #define NBBYTE2SEND (2*NBDATASEND)

    char StartMessage[] = "START";
    char StopMessage[] = "STOP";
    uint8_t byteRead;
    uint8_t StartAsked = 0;
    uint8_t StopAsked = 0;
    unsigned long previous = 0;
    int mod_11k = 12;
    int mod_17k = 13;
    uint8_t Header = 174;
    uint8_t tab_1[NBBYTE2SEND]={0,0,0,0,0,0,0,0,0,0,0,0};
    uint16_t data_toSend[NBDATASEND]={0,0,0,0,0,0};

    float P1[4];float P2[4];float P3[4]; float P4[4];float P5[4];float P6[4];
    float xprec1[2];float xprec2[2];float xprec3[2];float xprec4[2];float xprec5[2];float xprec6[2];
    float *sol1;float *sol2;float *sol3; float *sol4;float *sol5;float *sol6;
    float Te;
    float Tbeg;

    void setup() {
      pinMode(mod_11k,OUTPUT);
      pinMode(mod_17k,OUTPUT);
      digitalWrite(mod_11k,LOW);
      digitalWrite(mod_17k,LOW);
      //Start serial port with Gumstix
      Serial1.begin(115200);

    //Initialize KF
     P1[0] = 0.05; P1[1] =0; P1[2] =0; P1[3] = 0.05;
     P2[0] = 0.05; P2[1] =0; P2[2] =0; P2[3] = 0.05;
     P3[0] = 0.05; P3[1] =0; P3[2] =0; P3[3] = 0.05;
     P4[0] = 0.05; P4[1] =0; P4[2] =0; P4[3] = 0.05;
     P5[0] = 0.05; P5[1] =0; P5[2] =0; P5[3] = 0.05;
     P6[0] = 0.05; P6[1] =0; P6[2] =0; P6[3] = 0.05;
     xprec1[0] =0; xprec1[1] =0;
     xprec2[0] =0; xprec2[1] =0;
     xprec3[0] =0; xprec3[1] =0;
     xprec4[0] =0; xprec4[1] =0;
     xprec5[0] =0; xprec5[1] =0;
     xprec6[0] =0; xprec6[1] =0;

      //Wait for start message
    #ifdef START_MSG
      //Waiting START message to begin
      StartAsked = 0;
      while (StartAsked == 0)
      {
        if (Serial1.available() >= strlen(StartMessage))        //?????
        {
          //Serial.write("Bytes available");
          // verifiy that the received stream is well the start stream
          for (i = 0; i < strlen(StartMessage); i++)
          {
            byteRead = Serial1.read();
            if ((uint8_t)StartMessage[i] == byteRead)
            {
              StartAsked = 1;
            }
           // Serial.println(byteRead);
          }
        }
        delay(1);
      }
      Serial1.write("START");
      //Serial.write("START");
    #endif

    //KF first time
        Tbeg = millis();
        digitalWrite(mod_11k,HIGH);
        delayMicroseconds(2000);
        data_toSend[0] = analogRead(0);   //phi1 11k
        data_toSend[1] = analogRead(1); //phi2 11k
        data_toSend[2] = analogRead(2);
        digitalWrite(mod_11k,LOW);
        delayMicroseconds(200);
        digitalWrite(mod_17k,HIGH);
        delayMicroseconds(2000);
        data_toSend[3] = analogRead(0);
        data_toSend[4] = analogRead(1);
        data_toSend[5] = analogRead(2);
        digitalWrite(mod_17k,LOW);
        delayMicroseconds(200);
        xprec1[0] = data_toSend[0];
        xprec2[0] = data_toSend[1];
        xprec3[0] = data_toSend[2];
        xprec4[0] = data_toSend[3];
        xprec5[0] = data_toSend[4];
        xprec6[0] = data_toSend[5];
        Te = (millis() - Tbeg)/1000;
        sol1 = Fkalman(xprec1,data_toSend[0],P1,Te);
        sol2 = Fkalman(xprec2,data_toSend[1],P2,Te);
        sol3 = Fkalman(xprec3,data_toSend[2],P3,Te);
        sol4 = Fkalman(xprec4,data_toSend[3],P4,Te);
        sol5 = Fkalman(xprec5,data_toSend[4],P5,Te);
        sol6 = Fkalman(xprec6,data_toSend[5],P6,Te);
        Tbeg= millis();
    }

    void loop()
    {
        tick();
    }

    void tick() {
        //Previous value for filtering
        P1[0] =sol1[2]; P1[1] =sol1[3]; P1[2] =sol1[4]; P1[3] =sol1[5];
        P2[0] =sol2[2]; P2[1] =sol2[3]; P2[2] =sol2[4]; P2[3] =sol2[5];
        P3[0] =sol3[2]; P3[1] =sol3[3]; P3[2] =sol3[4]; P3[3] =sol3[5];
        P4[0] =sol4[2]; P4[1] =sol4[3]; P4[2] =sol4[4]; P4[3] =sol4[5];
        P5[0] =sol5[2]; P5[1] =sol5[3]; P5[2] =sol5[4]; P5[3] =sol5[5];
        P6[0] =sol6[2]; P6[1] =sol6[3]; P6[2] =sol6[4]; P6[3] =sol6[5];
        xprec1[0] =sol1[0]; xprec1[1] =sol1[1];
        xprec2[0] =sol2[0]; xprec2[1] =sol2[1];
        xprec3[0] =sol3[0]; xprec3[1] =sol3[1];
        xprec4[0] =sol4[0]; xprec4[1] =sol4[1];
        xprec5[0] =sol5[0]; xprec5[1] =sol5[1];
        xprec6[0] =sol6[0]; xprec6[1] =sol6[1];

        free(sol1);
        free(sol2);
        free(sol3);
        free(sol4);
        free(sol5);
        free(sol6);

        //Get data
        digitalWrite(mod_11k,HIGH);
        delayMicroseconds(2000);
        data_toSend[0] = analogRead(0);   //phi1 11k
        data_toSend[1] = analogRead(1); //phi2 11k
        data_toSend[2] = analogRead(2);
        digitalWrite(mod_11k,LOW);
        delayMicroseconds(200);
        digitalWrite(mod_17k,HIGH);
        delayMicroseconds(2000);
        data_toSend[3] = analogRead(0);
        data_toSend[4] = analogRead(1);
        data_toSend[5] = analogRead(2);
        digitalWrite(mod_17k,LOW);
        delayMicroseconds(200);
        Te = (millis() - Tbeg)/1000;

        //Filter
        sol1 = Fkalman(xprec1,data_toSend[0],P1,Te);
        sol2 = Fkalman(xprec2,data_toSend[1],P2,Te);
        sol3 = Fkalman(xprec3,data_toSend[2],P3,Te);
        sol4 = Fkalman(xprec4,data_toSend[3],P4,Te);
        sol5 = Fkalman(xprec5,data_toSend[4],P5,Te);
        sol6 = Fkalman(xprec6,data_toSend[5],P6,Te);
        Tbeg= millis();

        data_toSend[0] = sol1[0];
        data_toSend[1] = sol2[0];
        data_toSend[2] = sol3[0];
        data_toSend[3] = sol4[0];
        data_toSend[4] = sol5[0];
        data_toSend[5] = sol6[0];

        //Send data
        Codage(data_toSend,tab_1);
        HeaderSendnUInt8_RS232(tab_1,NBBYTE2SEND,Header);
    }

    void Codage(int16_t *d_send, uint8_t *tab_Send)
    {
        int i;
        for(i=0; i<NBDATASEND ;i++)
        {
           d_send[i]=d_send[i]+8192;
           tab_Send[2*i]= (uint8_t) ((d_send[i] & 127));              //lấy 7 bit đầu
           tab_Send[2*i+1]= (uint8_t) ((d_send[i] & 16256)>>7);       //lấy 7 bit sau
        }
    }

    uint8_t HeaderSendnUInt8_RS232(uint8_t *ToSend, uint8_t NbToSend, uint8_t Header)
    {
        Serial1.write(&Header,1);         //Header đâu phải pointer??
        return(Serial1.write((const uint8_t*)ToSend, NbToSend));
    }

    float *Fkalman(float xprec[2],float ymes,float P[4],float Te){
                         // Filtre proprement dit
        float *sol = NULL ;
        sol = (float*) malloc (sizeof(float) * 6);
        float xpred[2];
        float Ppred[4] ;
        float Kf[2] ;
        int q = 0.05;
        int r = 100;

        //x prediction
        xpred[0] = xprec[0] + Te*xprec[1];
        xpred[1] = xprec[1];

        //P_pred = F.P.F'+Q
        Ppred[0] = q + P[0]+ Te*(P[2] +P[1]+Te*P[3]);
        Ppred[1] = P[1] + Te*P[3];
        Ppred[2] = P[2] + Te*P[3] ;
        Ppred[3] = q+ P[3];

        //Kf = (P_pred.C').inv(C.P_pred.C'+R)
        Kf[0]  = (Ppred[0]/(r+Ppred[0]));
        Kf[1]  = (Ppred[2]/(r+Ppred[0]));

        //X_est
        sol[0] = xpred[0] + Kf[0]*(ymes-xpred[0]);
        sol[1] = xprec[1] + Kf[1]*(ymes-xprec[0]);

        //P_est = (I-Kf*C)*P_pred
        sol[2] = Ppred[0]*(1-Kf[0]);
        sol[3] = Ppred[1]*(1-Kf[0]);
        sol[4] = -Kf[1]*Ppred[0]+Ppred[2];
        sol[5] = -Kf[1]*Ppred[1]+Ppred[3];
        return sol;
      }

If you find any problem related to the Fkalman function or my loop function, please tell me. Thank you!!

title: Is the use of malloc() and free() necessary in my Kalman noise Filter function?

Answers: 2

body:
It's not recommended, however you're only working with small amounts, and the same amount each time (6 floats per "sol" and 6 "sols", so 36 floats, or 144 bytes). Since it's always the same amount I would expect the same block of memory to be allocated each time.

Personally I would use local array variables in the calling function and pass them as a parameter to the function(s) that manipulate them, rather than returning a pointer to an allocated array.

    float sol1[6];
    Fkalman(xprec1,data_toSend[0],P1,Te,sol1);

    ....

    void Fkalman(float xprec[2],float ymes,float P[4],float Te, float *sol){

etc.

However I can't see it causing an issue, so if you would clarify "doesn't work as well" we may be able to point you in a better direction.

body:
As Majenko already explained it is only 144 bytes. You can use local variables as he proposes.

If you need to keep the values over multiple calls to the Fkalman function, create the space as a variable of an array for each of the calls (if the function is called a fixed number of times).

Besides this, malloc cost some time and for performance reasons it is better to do this during start up once, so the loop function is not hindered by mallocs and free.


body:
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

title: Multiple SPI reads slows down read time dramatically

Answers: 2

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.

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:)


body:
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?

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

Answers: 1

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.)


body:
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

title: Problems adding ESP8266 wifi board

Answers: 1

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.


body:
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?

title: Two devices on one UART/Serial

Answers: 3

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.


body:
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

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

Answers: 3

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.


body:
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

title: Simple Ground circuit layout

Answers: 1

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


body:
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

title: Error on sending AT+CWJAP_DEF commands to ESP8266

Answers: 3

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/


body:
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?

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

Answers: 1

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.


body:
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?

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

Answers: 1

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.


body:
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!

title: Arduino nano Serial port not recognized

Answers: 1

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.


body:
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?

title: POWER_MODE_IDLE wake on any input change?

Answers: 2

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.


body: 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

title: Using ALL the analog pins on Mega for Servo

Answers: 2

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


body:
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

title: Programming Arduino Micro via RX/TX

Answers: 2

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.


body:
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?

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

Answers: 2

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.


body:
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

title: Connecting a 5v dc fan to ultrasonic sensor

Answers: 1

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.


body:
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. :)

title: Trying to send .wav files between NodeMCU

Answers: 1

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.


body:
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.

title: Arduino Nano and ESP8266

Answers: 1

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.


body:
I want to make RFID Tag as a variable, and push it to the web server. But I struggle to do the `Serial.read` function.

Any solutions?

Here is my code
<!-- language-all: lang-cpp -->

    #include <ESP8266WiFi.h>
    #include <SPI.h>
    #include <MFRC522.h>

    /* wiring the MFRC522 to ESP8266 (ESP-12)
    SDA(SS) - D4 (GPIO2)
    SCK - D5 (GPIO14) (hw spi)
    MOSI - D7 (GPIO13) (hw spi)
    MISO - D6 (GPIO12) (hw spi)
    IRQ -
    GND - G
    RST - D3 (GPIO0) (FLASH)
    3.3V - 3V
    */

    #define RST_PIN D3 // RST-PIN für RC522 - RFID - SPI - Modul GPIO5
    #define SS_PIN D4 // SDA-PIN für RC522 - RFID - SPI - Modul GPIO4

    const char *ssid = "Keluarga"; // change according to your Network -
    cannot be longer than 32 characters!
    const char *pass = "batikpekalongan11"; // change according to your
    Network

    String a;

    MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
    WiFiServer server(80);

    void setup() {
    Serial.begin(115200); // Initialize serial communications
    delay(10);
    Serial.print(F("Booting...."));

    SPI.begin(); // Init SPI bus
    mfrc522.PCD_Init(); // Init MFRC522

    WiFi.begin(ssid, pass);

    int retries = 0;
    while ((WiFi.status() != WL_CONNECTED) && (retries < 10)) {
    retries++;
    delay(500);
    Serial.print(".");
     }
    if (WiFi.status() == WL_CONNECTED) {
    Serial.println(F("WiFi connected"));
    }

    Serial.println(F("Ready!"));
    Serial.println(F("Scan for Card and print UID:"));
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

    // Start the server
    server.begin();
    Serial.println("Server started");
      }

    void loop() {
     // Check if a client has connected
     WiFiClient client = server.available();
     if (!client) {
     return;
     }

     // Look for new cards
       if ( ! mfrc522.PICC_IsNewCardPresent()) {
    delay(50);
    return;
    }
    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
    delay(50);
    return;
    }
    // Show some details of the PICC (that is: the tag/card)
      Serial.print(F("Card UID:"));
      dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
      a = Serial.readString();
      Serial.println("kakak");
      Serial.println(a);

    // Wait until the client sends some data
    Serial.println("new client");
     while(!client.available()){
     delay(1);
     }

    // Read the first line of the request
    String request = client.readStringUntil('\r');
    Serial.println(request);
    client.flush();

    // Return the response
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println(""); //  do not forget this one
    client.println("<!DOCTYPE HTML>");
    client.println("<html>");

    client.print("Card UID:");
    client.print(a);
    client.println("</html>");
    //delay(1);
    //Serial.println("Client disonnected");
    //Serial.println("");
    }

title: Make RFID Tag as a variable

Answers: 0


body:
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\

title: NRF24L01 only receiving zeros

Answers: 1

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.


body:
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 ?

title: Major difference between DTR signal and RTS signal?

Answers: 3

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


body: 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.

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

Answers: 2

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.