body:
After reading the following 2 articles:

https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

I have get rid of the complete String class from my main program and went back to using character arrays.
This seems to work reliably until some extent but once I start stress testing it, quickly turns out that it is not reliable at all!

Here is the complete code, you can load it into the mega and it will produce the same results (I have removed all other unnecessary parts from the code):

    #define DEBUG

    char Command_PC[64], Command_Xbee[64], Command[64];
    int count=0;
    bool Complete_PC=false;
    bool Complete_Xbee=false;

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

    } // END void setup

    void comm() {

    /* COMM FROM PC */
    if (Serial.available()){

      #ifdef DEBUG
        Serial.println("PC: New command, collecting...");
      #endif
        count = 0;
        memset(Command_PC, 0, sizeof(Command_PC));
        while (Serial.available()){
          char character = Serial.read();
          if (character=='\n')
             {
              Complete_PC =true;
              break;
             }
          Command_PC[count] = character;
          count++;
        }
      }

    /* COMM FROM Xbee */
    if (Serial1.available()){
      #ifdef DEBUG
        Serial.println("Xbee: New command, collecting...");
      #endif
        count = 0;
        memset(Command_Xbee, 0, sizeof(Command_Xbee));
        while (Serial1.available()){
          char character = Serial1.read();
          if (character=='\n')
             {
              Complete_Xbee =true;
              break;
             }
          Command_Xbee[count] = character;
          count++;
        }
      }

       delay(500);

     if (Complete_Xbee || Complete_PC) {

      if(Complete_Xbee)
        strcpy(Command, Command_Xbee);
      else
        strcpy(Command, Command_PC);

      #ifdef DEBUG
        Serial.print("Command received: >");
        Serial.print(Command);
        Serial.println("<");
      #endif
               Complete_Xbee=false;
               Complete_PC=false;
     }

    }

    void loop()
    {
        comm();

    } // END void loop

The code is simple, all it is intended to do that whether there is a command coming from the PC (USB) or Xbee (attached to hardware uart) process it and do further things. As long as you typing in commands manually it goes reliably for a while but even then after 10-15 commands it might screws up. The automated testing with:

**`for ((;;)); do echo HELLOWORLD > /dev/ttyACM0; done`**

    Command received: >HELLOWORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOWORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOWORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOWORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOWORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOWORD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOWORL<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOWORLDELLOWORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HLOWORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELOWORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOWORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOORLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOWLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOWOD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOWOLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOWLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOWOLD<
    ERR_INVALIDCMD
    PC: New command, collecting...
    Command received: >HELLOWLD<
    ERR_INVALIDCMD
    PC: New command, collecting...

Brings out the bug right away. Is there any problem with this code? Any ideas how to make this 100% reliable even if it takes slowing the main program down?

I have noticed that by adding: `delay(500);` it makes it more stable. If this is not there it will even fail on the first manually entered command like:

    PC: New command, collecting...
    PC: New command, collecting...
    PC: New command, collecting...
    Command received: >lloworld<

By adding a delay to my test script:

**`for ((;;)); do echo HELLOWORLD > /dev/ttyACM0 && sleep 1; done`**

It runs stable for a while but after 15 mins testing it start misbehaving again:

    Command received: >HELLOWORLD<
    PC: New command, collecting...
    Command received: >HELLOWORLD<
    PC: New command, collecting...
    PC: New command, collecting...
    Command received: ><
    PC: New command, collecting...
    PC: New command, collecting...
    Command received: ><
    PC: New command, collecting...
    PC: New command, collecting...
    Command received: ><
    PC: New command, collecting...
    PC: New command, collecting...
    Command received: ><

title: Arduino Unreliable Serial communication

Answers: 3

body:
To me, your problem is because the program is reading the characters faster than they are sent by the computer. Then, some situations occur where all the characters of the buffer have been read (`Serial.available() = 0`) but the `'\n'` character has not been sent by the computer yet. The program will then exit the loop without setting the `Complete_PC` variable to true.

In that case, the program will write several times "PC: New command, collecting..." without writing any result (Complete_PC not set to true). It can also drop the first letters, as they were read during the previous loop and the `Command_PC` array and count were reset in between.

The `delay(500)` command improve the stability because it increase the chances that the whole line is received when the program is not reading it at the same time.

Try something like this:

    while ((!Complete_PC)&&(count<60))
    {
        int character = Serial.read();
        if (character=='\n')
        {
            Complete_PC =true;
        }
        else if (character!=-1)
        {
            Command_PC[count] = (char) character;
            count++;
        }
    }

body:
As @Edesign has mentioned your reception methodology is slightly flawed.  A better arrangement would be:

    static int Count_PC = 0;
    static bool Complete_PC = false;

    if (Serial.available()) {
      char character = Serial.read();
      if (character=='\n') {
        Complete_PC =true;
        Count_PC = 0;
      } else {
        if (Count_PC < 62) { // Don't overflow the array...!
          Command_PC[Count_PC++] = character;
          Command_PC[Count_PC] = 0;
        }
      }
    }

The count and complete flags are now static - that is, they retain their values between iterations of the loop. You only look at one character per iteration of the loop (you could enhance it by changing the first `if` to a `while` if you like, but this way plays better with handling multiple data sources), and add that to the string. Only when the `\n` is received do you flag it as complete. There is no clearing of the whole array, it's not needed - just ensure that you always add a `\0` to the end of the string each time you add a character.

The current character position (`Count_PC`) is reset when you receive the `\n` so that it is ready to receive the next command - be sure that you process the command that same loop (which you do anyway).

body:
@Edesign, @Majenko: thank you for your help, it turns out that the hardware DOES matter as well. It was partially a **hardware issue**. Regarding my initial code, you can get that code remove the delay(500); from it and load it into an Arduino Leonardo and it will pass my first initial stress test without any delays and it works stable even after an hour testing.

I believe that both the Mega and the Leonardo have USB2 connections:

Bus 001 Device 003: ID 2341:0042 Arduino SA Mega 2560 R3 (CDC ACM)
Bus 003 Device 013: ID 2341:8036 Arduino SA

Although this is was a *Keyestudio MEGA*, a cheap chinese counterfeit which would explain why did it have this issue. My initial code was not wrong but as you have pointed out it could have been improved, what I did.

Code1:

    static int Count_PC = 0;
    static bool Complete_PC = false;

    if (Serial.available()) {
      char character = Serial.read();
      if (character=='\n') {
        Complete_PC =true;
        Count_PC = 0;
      } else {
        if (Count_PC < 62) { // Don't overflow the array...!
          Command_PC[Count_PC++] = character;
          Command_PC[Count_PC] = 0;
        }
      }
    }

Code2:

    /* COMM FROM PC */
    if (Serial.available()){

      #ifdef DEBUG
        Serial.println("PC: New command, collecting...");
      #endif
        memset(Command_PC, 0, sizeof(Command_PC));
        while (Serial.available()){
          char character = Serial.read();
          if (character=='\n')
             {
              Complete_PC =true;
              Count_PC = 0;
              //break;
             } else {
                 if (Count_PC < 62) { // Don't overflow the array...!
                     Command_PC[Count_PC++] = character;
                     Command_PC[Count_PC] = 0;
                 }
             }
      }
    }

The difference between his code and my last code is that I do the while looping inside the function while his relies on the main loop cycles to complete the string.

Both are working but if the main program have a lot to do, his version will noticeably make the responses more sluggish. Which can be easily tested with:

     for ((;;)); do date > /dev/ttyACM0; done


body:
I have a question about capacitors in DC (digital) circuits. The picture below is an edited schematic of the Arduino Uno R3.

The DTR line is connected to the reset input of the Atmega328 by a 0.1uF capacitor.

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

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

The capacitor is needed to initiate a load to the atmega flash memory through the USB -> UART. Why is this the case, everything I have been taught says "Capacitors block DC and let AC through"

All I see is something that can let AC noise through to the Arduino reset? I know its needed, I tested it. But why its needed, how it fulfils that function I have no idea.

Please help

title: Capacitors in DC circuits

Answers: 2

body:
The capacitor C5 and resistor RN1 are used to TEMPORARILY apply RESET to the microcontroller chip during power-up.  It assumes that C5 is discharged and will conduct the "AC" (change from 0V up to 5V) until it becomes fully charged and releases the reset line so that the microcontroller can start up properly.

You can use this online calculator to see the time-constant for any given resistor and capacitor:  http://www.referencedesigner.com/rfcal/cal_05.php

When the circuit is first powered up, C5 holds the microcontroller -RESET line LOW (the active state) until C5 charges up through RN1.  At that point RN1 holds the -RESET line HIGH which releases the microcontroller to start up in an orderly manner.

It is not clear exactly what is happening between the U3 DTR pin and the junction of C5/RN2.  There is a label that says "LED3 Yellow", but there is no symbol for a LED or any other component there.  But there is typically a way for an external device to apply a reset also, so that you can re-program the microcontroller, and that is likely what is happening there.

body:
The Atmel [datasheet][1], page 305, Section 29.5 "System and Reset Characteristics" provides some useful information for the reset pulse. It says that the worst-case minimum pulse width is \$2.5\:\mu\textrm{s}\$. It then goes on to say that the ramp rate has to be contained between two boundaries; no faster than \$10\:\frac{\textrm{kV}}{\textrm{s}}\$, but also no slower than \$10\:\frac{\textrm{V}}{\textrm{s}}\$. So there are some restrictions that should be managed by any reset system.

There are some nice reset circuit ICs available which provide a manual reset input as well as a control line. I'd probably use one of those about a circuit I cared about. Okay. Actually, I'd make my own out of a PIC10LF320 in a SOT-23-6, which also includes a brown-out circuit of its own, which I'd probably also re-purpose, as well.

But let's look at this circuit. DTR is normally held HIGH (I believe) and is pulled LOW in order to initiate a reset. Assuming that the two MCUs are running on different power rails (or the same, doesn't matter), \$C_5\$ is charged up to the difference between the ATmega328's rail (via \$RN_1\$ and the DTR output line's HIGH value.) If there is no difference, the voltage will be nearly zero. But if the rails are different, then there will be a small voltage across \$C_5\$ that represents this difference.

When DTR is pulled LOW, that end of \$C_5\$ is also pulled down to that voltage (close to ground.) For the first moments, this also means that the other side of \$C_5\$ is similarly pulled downwards, too. If there was some voltage rail difference, then that's the voltage that appears at the reset pin of the ATmega328. Depending on the voltage differences between the MCUs and the reset pin requirements of the ATmega328, this could be a problem. The datasheet says that it may be required to be as low as \$600\:\textrm{mV}\$, though the typical only requires to be pulled down to \$1.3\:\textrm{V}\$. But if no difference in the rails, then hopefully near-ground appears at the reset pin of the ATmega328. I'm going to assume there is no difference, here, so that we at least have a good chance it works okay.

Now, as soon as \$C_5\$ is yanked down by DTR, \$C_5\$ begins charging up through \$RN_1\$, starting at a rate of about \$500\:\mu\textrm{A}\$. The time constant is \$1\:\textrm{ms}\$. So the voltage will rise rapidly. Assume that we only just barely achieved the required \$600\:\textrm{mV}\$ at the start (the capacitor held a slight charge.) Then we'd cross over the minimum rising threshold of \$1.1\:\textrm{V}\$ within about \$100\:\mu\textrm{s}\$. This is well more than long enough for the earlier mentioned minimum reset pulse width of \$2.5\:\mu\textrm{s}\$. So the spec is met here.

Now, let's go the other direction. Let's say that now DTR is held LOW for a long enough time that it charges up to about \$5\:\textrm{V}\$ through \$RN_1\$. Now, DTR is driven HIGH. What happens? Well, the other side of \$C_5\$ will now be at about \$10\:\textrm{V}\$ (the \$5\:\textrm{V}\$ charge on \$C_5\$ added to the DTR HIGH voltage value.) This is rapidly discharged, safely, via \$D_2\$. That's why \$D_2\$ was added. Otherwise, this voltage would be presented to the RESET pin of the ATmega328 and would have to be discharged via any internal protection diodes present there (which may themselves have additional specifications that must be met.)

What's interesting here is that the RESET pin in particular is called out in the datasheet on page 299. It says that it can support up to \$13\:\textrm{V}\$ worst case. So, technically, that might mean that \$D_2\$ isn't necessary to avoid driving protection diodes in the CPU. But it is still a good idea for an entirely different reason. This is to discharge \$C_5\$ rapidly (it would be very slow, via \$RN_1\$), so that it can be used for another reset very soon after being used.

----------

Note on the reset pin:

As Majenko added in a comment, there is a high voltage programming mode for Atmel devices like this. I frankly don't fully apprehend it, as I haven't read a datasheet on the topic. But I did find out from an Atmel video that the PC6/RESET line, which normally acts like a /RESET line, can be changed into operating like a general purpose I/O port by changing the RSTDISBL fuse, which makes the general I/O function available. The bad thing about that is that the ISP programming mode NEEDS the /RESET line to do its job. So you can't program the device anymore, if you set up that fuse. This then forces you to use the parallel programming mode that is entered using the high voltage programming mode. I would guess that entering this mode uses the /RESET pin again, but this time places a high voltage on it that is detected in order to put the device into its parallel programming mode instead of the ISP programming mode.

I can't readily find a specific programming document on the details of using this mode to program their devices. Microchip publishes them. But it appears, cursory examination only, that Atmel does not. They document how to use the mode with their tools, such as the STK500 (which I have.) But not how to design your own tool. I'm guessing, for now, that this is a matter of non-disclosure for Atmel. And given that they have it available for so many different devices, I can see why they might want to avoid having to support it.

The details on this pin are starting to get complicated-sounding. But pins cost money and silicon is cheap. So Atmel, like other companies, try to come up with methods to use their scarce pins to provide as much versatility as they can to sell devices.

That's it.

  [1]: http://www.atmel.com/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf


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

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

<!-- End schematic -->

Its a simple project. I am trying to drive 3 RGB LEDs using Arduino Nano. Since Arduino Nano does not have 9 PWM pins, the only solution I can think of by multiplexing them. I have try multiplexing 12 7-segments driven by atmega16, the results was satisfying. Is it possible to do **PWM multiplexing** on **Arduino Nano**?
So far, here is what I have done:

    const int R=9, G=10, B=11, M1=5, M2=6, M3=7;

    //I use pin 5,6,7 as selector since they are on same PORT (PORTD)

    void setup()
    {
     pinMode (R,OUTPUT);
     pinMode (G,OUTPUT);
     pinMode (B,OUTPUT);

     pinMode (M1,OUTPUT);
     pinMode (M2,OUTPUT);
     pinMode (M3,OUTPUT);
    }

    void led(int r, int g, int b)
    {
     analogWrite(R,255-r);
     analogWrite(G,255-g);
     analogWrite(B,255-b);
    }

    void loop()
    {
     for(int i=0; i<256; i++)
     {
      led(0,0,i);
      __asm__("nop\n\t");   //one clock cycle delay
      PORTD = B10000000;   //select LED-1

      led(0,i,0);
      __asm__("nop\n\t");   //one clock cycle delay
      PORTD = B01000000;   //select LED-2

      led(i,0,0);
      __asm__("nop\n\t");   //one clock cycle delay
      PORTD = B00100000;   //select LED-3
     }

     for(int i=256; i>0; i--)
     {
      led(0,0,i);
      __asm__("nop\n\t");   //one clock cycle delay
      PORTD = B10000000;   //select LED-1

      led(0,i,0);
      __asm__("nop\n\t");   //one clock cycle delay
      PORTD = B01000000;   //select LED-2

      led(i,0,0);
      __asm__("nop\n\t");   //one clock cycle delay
      PORTD = B00100000;   //select LED-3
     }

    }

But still, this does not work. The result is all the led turned on, with 'a little bit' different color, mainly white with a little addition of another color (while it supposed to be contrast, R, G and B for each LED), and its blinking. The blink is very short, but still, its annoying. One possibility I can think of my code still not optimum.
Someone had an idea?

**EDIT**
I fixed the diagram, I hope the diagram does not make any misunderstandings. As the suggestion from @jwpat7, I forget to inform that the led still error even if there is just one `for-loop`.
I am using `__asm__("nop\n\t")` as delay substitution because "theoretically", 1 clock cycle from 16mHz clock is shorter than 1 microseconds. (correct me if I am wrong, but I think its about 62.5 ns)

Thanks in advance

title: PWM multiplexing on Arduino nano

Answers: 1

body:
I've copied and slightly modified your diagram, as below.  Note the added connections of R1, R3 cathodes to that of R2, and similarly for green and blue LEDs.

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

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

<!-- End schematic -->

I'm supposing that unlike the original diagram, this one represents what you actually wired up.

A basic problem with your program is that it spends most of its time changing PWM settings, without letting PWM cycles actually occur.  To see this, do some timing analysis on the code.

The code repeatedly executes sections of code like the following:

        led(0,i,0);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B01000000;      //select LED-2

The call to `led()` results in three calls to `analogWrite()`.  As seen by perusing at [garretlab](http://garretlab.web.fc2.com/en/arduino/inside/index.html) the source code for [`analogWrite()`](http://garretlab.web.fc2.com/en/arduino/inside/arduino/wiring_analog.c/analogWrite.html), [`digitalWrite()`](http://garretlab.web.fc2.com/en/arduino/inside/arduino/wiring_digital.c/digitalWrite.html), and [`pinMode()`](http://garretlab.web.fc2.com/en/arduino/inside/arduino/wiring_digital.c/pinMode.html), each of those `analogWrite()` calls takes a few handfuls of cycles – let's say 50 at most – so the three lines of code shown above take less than a dozen microseconds to execute.  Thus each of the two `for` loops takes less than 10 milliseconds to complete, causing the `loop()` routine to run more than 50 times per second.  Persistence of vision will result in observers just seeing the average level of light, rather than any ramping up or down.

To fix the ramps-not-visible problem, determine how long you want each ramp up or down to take, and add corresponding delays in the `for` loops.  For example, suppose you want to go up in one second and down in two.  As 1000000 μs /256 passes ≈ 3906 μs per pass, you could add `delayMicroseconds(3906-36)` at the end of the first `for` loop, and `delayMicroseconds(2*3906-36)` at the end of the other, to achieve the specified rates.  (The -36 term accounts for time used by other code in each loop.  It's probably an overestimate and perhaps should be left out.)

However, the previous paragraph doesn't take multiplexing effects into account.  You may, of course, want a different PWM level for each of the nine different LED chips.  It probably is practical to just directly use as many PWM outputs as you have available, and emulate PWM in software for any remaining LEDs.

For more information about software PWM, see [some articles that google turns up](https://www.google.com/search?num=50&site=&source=hp&q=simulate+pwm+in+software+arduino&oq=simulate+pwm+in+software+arduino&gs_l=hp.3...4217.4217.0.5990.2.2.0.0.0.0.84.159.2.2.0....0...1c..64.hp..0.0.0.0.3aj_VMVB2QQ), including:
• [Arduino PWM pin vs digital pin PWM simulation](https://electronics.stackexchange.com/q/116102) on electronics.stackexchange, which presents basic ideas and some pros and cons of software-based PWM
• [AnyPWM Revisited](http://nicks-liquid-soapbox.blogspot.com/2011/02/anypwm-revisited.html), a blog article by Nick Borko about PWMing 12 LEDs using software PWM
• [PWMAllPins](http://playground.arduino.cc/Main/PWMallPins), an arduino.cc article apparently by Paul Badger or Seth Wolf about PWMing 11 LEDs using software PWM

Generally, software PWM hogs computing cycles and can be difficult to coordinate with other calculations.  But if PWM control is the only significant task a processor is handling, software PWM can be an economical way to produce extra PWM pins.


body:
I am trying to control a servo using keyboard.

    void loop() {
    if (Serial.available() > 0) {
      x = Serial.parseInt();
      while(pos < 180){
      pos = x + pos;
      Serial.println(pos);
      myservo.write(pos);
      delay(100);
     }
      }
    else if(Serial.available() > 0){
    if(pos>=180){
      pos = 0;
      delay(500);
      myservo.write(0);

      }
      }
     }

Right now the servo takes the input correctly. The only thing is that it wont change positions immediately. It will wait until it hits 180 resets to 0 and then use the input I put in. This isnt the behaviour I want. I want it to change immediately. How Do I set this up?

title: State machinese for serial input

Answers: 1

body:
I don't understand why you use 2 `Serial.available` condition.
I try to rewrote your program based on my imagination, so do not hate me if its wrong.
Why don't you try this and tell the results:

    int pos = 0,x=0;
    void loop()
    {
      while (Serial.available() > 0) x = Serial.parseInt();

      pos+=x;
      if (pos>180) pos = 0;
      myservo.write(pos);
      Serial.println (pos);
      delay(100);
    }


body:
I'm new both to this forum and to Arduino. My robot is comprised of Arduino Uno with Arduino Motor Shield, 12V DC gear motor, and two limit switches. The robot supposed to move endlessly on rails between the two walls back-and-forth. I have it all wired up and am able to switch the directions of the motor's rotation by pushing the limit switches. However, I also want to have a pause between switching of directions:

... Robot moving forward ...

If front limit switch is pushed

Stop motor

Pause 2 seconds

Run motor CCW

... Robot moving backwards ...

If rear limit switch is pushed

Stop motor

Pause 2 seconds

Run motor CW

... Robot moving forward ...

Simple `delay(2000)` doesn't work as the limit switch remains pushed against the wall. I've been trying out `millis()` approach but the fact that limit switch remains pushed (`HIGH`) I can never produce a difference in time needed to trigger an action. I learned about State Machine but not sure if and how this could help my case?

Can anyone please help me in implementing a two second pause between the switching of the motor's direction?

Below is the code that **momentarily** switches the motor's direction when robot reaches the wall and limit switch is pushed.

int switchFront_State = 0;
int switchRear_State = 0;

const int ledYellow = 6;
const int ledGreen = 5;

const int switchFront = 4;
const int switchRear = 2;

const int motorDirection = 12;
const int motorBreak = 9;
const int motorPWM = 3;

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

  pinMode(switchFront, INPUT_PULLUP); // Front switch
  pinMode(switchRear, INPUT_PULLUP); // Rear switch

  pinMode(ledYellow, OUTPUT);
  pinMode(ledGreen, OUTPUT);

  // Setup Channel A
  pinMode(motorDirection, OUTPUT); // Motor direction pin
  pinMode(motorBreak, OUTPUT); // Motor break pin
  pinMode(motorPWM, OUTPUT); // Motor PWM pin
}

void runMotorBackward(){ // Motor moving backward
  digitalWrite(motorDirection, LOW);
  digitalWrite(motorBreak, LOW);
  digitalWrite(motorPWM, 128);
}

void motorStop(){ // Stop motor
  digitalWrite(motorBreak, HIGH);
  digitalWrite(motorPWM, 0);
}

void runMotorForward(){ // Motor moving forward
  digitalWrite(motorDirection, HIGH);
  digitalWrite(motorBreak, LOW);
  digitalWrite(motorPWM, 128);
}

void loop(){
  switchFront_State = digitalRead (switchFront);
  switchRear_State = digitalRead (switchRear);

  if (switchFront_State == HIGH){ // If front switch is pressed
    digitalWrite(ledYellow, HIGH); // Yellow LED
    motorStop();
    runMotorBackward();
    } else {
    digitalWrite(ledYellow, LOW);
  }

  if (switchRear_State == HIGH){ // If rear switch is pressed
    digitalWrite(ledGreen, HIGH); // Green LED
    motorStop();
    runMotorForward();
  } else {
    digitalWrite(ledGreen, LOW);
  }
}

title: Pause between switching motor direction

Answers: 2

body:
I think the problem is because there is no delay time after your motor switch its direction, so the robot is stay on position where the switch is pressed. I don't know if this gonna work, but perhaps you can add delay after the direction changed.
But based on your code, I can't find a condition to run if no switch is pressed. For alternative, you can try this

    int direction_state = 1; //state where robot moves forward

    void loop(){

      /*notes that here I assume while robot moving forward,
       *the rear switch is impossible to pressed, so does while
       *robot moving backward, the front switch is impossible to
       *pressed.
       */

      while ((digitalRead (switchRear)==LOW) && (digitalRead (switchFront)==LOW))
      //no switch pressed, loop will break if any switch pressed
        {
          if (direction_state == 1) runMotorForward(); else
                                    runMotorBackward();
        }

      //indicator which switch is pressed and start of 2s motor stops
      if (direction_state==1) digitalWrite(ledYellow,HIGH);
      else digitalWrite(ledGreen,HIGH);

      motorStop(); //stop the motor
      delay(2000);

      //indicator 2s motor stops finished
      if (direction_state==1) digitalWrite(ledYellow,LOW); //indicator front switch is pressed
      else digitalWrite(ledGreen,LOW);

      direction_state = -direction_state //toggle the state
      if (direction_state == 1) runMotorForward(); else
                                runMotorBackward();

      delay(2000);

    }

Feel free to ask if it's not works

body:
You need to make your switch logic edge sensitive rather than state sensitive. (That's the digital electronics term for it.) That means that you need to react to the change from switch off to switch on, not to the switch being on. (Since you're using INPUT_PULLUP mode, a switch on = LOW.

So:

In your loop, don't use

    switchFront_State = digitalRead (switchFront);

instead, use code like below to detect a switch press:

    int newSwitchState = digitalRead (switchFront);
    if (newSwitchState == LOW && newSwitchState  != switchFront_State) {
        switchFront_State = newSwitchState;
        //Code to handle the limit switch being pressed
    } else if (newSwitchState == HIGH && newSwitchState  != switchFront_State) {
        switchFront_State = newSwitchState;
        //Code to handle switch changing to the off state
    }

You'll probably also need to use millis() to add some debouncing to your switch. (Ignore switch changes unless 10-20 milliseconds has passed, to avoid the switch jittering on and off when it is initially pressed or released.)


body:
With verbose upload selected the IDE provides the executed avrdude command at the top of the log.

I am interested in copy pasting that avrdude command. However at the end of the upload the command is not available anymore. The IDE only shows some last lines of the log and discard the top part.

Is that log saved anywhere? (I am on ubuntu). Any ideas how I can get that command?

title: Capturing avrdude command in IDE

Answers: 1

body: If you run the IDE from a terminal you should get the output to STDOUT in your terminal to do with what you want.


body:
I want to use a transistor to turn on and of an electric magnet, I have hooked up a transistor like this:

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

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

<!-- End schematic -->

The blue wire goes to the magnet and the white wire goes to the ground:

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

Regardless of if the arduino is on or off(I can even unplug port 12 from the arduino, the magnet is still on, the circuit never closes. What do I need to do to make the transistor turn off?

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

title: Why is my transistor always transmitting?

Answers: 1

body: Darlington transistors are *very* sensitive; even putting your hand near it can be enough to turn it on. Either tie the base to ground with a large resistor or switch to a MOSFET with its gate tied to ground through same. In either case put a diode backwards across the coil to absorb the energy from the coil when it de-energizes so that the transistor is not damaged.


body:
I am trying to create a code that has at least 6 servos attached and two buttons for a two player game. I want to be able to roll a random number and have it hold that value then when it is that players turn. The program should also take that previous number and add it to the next. It would eventually be adding up all the values of the rolls. This is what I have so far. Any advice would be helpful. Thanks!

    #include <Servo.h>

    Servo myservo;

    int pos = 0;    // variable to store the servo position
    int x;
    int button = 8;
    int BUTTON;
    int randomNumber;
    int xPrevious;

    void setup() {
        pinMode(button, INPUT);
        Serial.begin(9600);
    }

    void loop() {
      for (x = 2; x <= 7; x += 1) {
        myservo.attach(x);

        for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
          // in steps of 1 degree
          myservo.write(pos);              // tell servo to go to position in variable 'pos'
          delay(15);                       // waits 15ms for the servo to reach the position
        }
        for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
          myservo.write(pos);              // tell servo to go to position in variable 'pos'
          delay(15);                       // waits 15ms for the servo to reach the position

          BUTTON = digitalRead(button);
          if(BUTTON == LOW){
            randomNumber = random(1,7);
            delay(350);
            Serial.println(randomNumber);
          }
        }
        randomNumber += xPrevious;
      }
    }

title: Hold a random number

Answers: 2

body:
You are redefining the random number wrongly each time with

    randomNumber += xPrevious;

this is an error. You need another new variable (initialised at 0) to keep the running totals of all the random "rolls". You should be able to fix your program now you know this. Maybe something like

    TotalofTherandomNumbers += xPrevious;

to start off with.

You may also want to add in the after the line

     randomNumber = random(1,7);

a new function, of yours, that takes random value randomNumber  do the action in the game, what ever that is,  depending on if its the first or second player.

body:
Your xPrevious is declared but never given any value.

Is this what you're looking for?

        randomNumber += random(1,7);

Another thing is that you should not assume that randomNumber is initialized to 0. Better assign it a starting value.

        int randomNumber = 0;   // or whatever you want

Lastly, an Arduino int is a 2 bytes signed number. If the game goes on for a long time the variable will roll over at 32,767. Consider making it a unsigned long instead.


body:
I have the library RF24 and everything in my arduino library but for some reason it's not compiling.  I don't know why. I posted the code and also the error message that the arduin IDE keeps showing. Please help me figure out whats wrong!

    Arduino: 1.6.12 (Windows 7), Board: "Arduino/Genuino Uno"

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::read_register(unsigned char, unsigned char*, unsigned char)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::read_register(unsigned char)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::write_register(unsigned char, unsigned char const*, unsigned char)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::write_register(unsigned char, unsigned char)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::openReadingPipe(unsigned char, unsigned long long)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::setAutoAck(bool)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::setAutoAck(unsigned char, bool)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::read_payload(void*, unsigned char)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::flush_rx()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::getDynamicPayloadSize()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::flush_tx()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::get_status()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::available(unsigned char*)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::print_status(unsigned char)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::print_observe_tx(unsigned char)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::print_byte_register(char const*, unsigned char, unsigned char)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::print_address_register(char const*, unsigned char, unsigned char)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::RF24(unsigned char, unsigned char)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::RF24(unsigned char, unsigned char)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::setChannel(unsigned char)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::setPayloadSize(unsigned char)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::getPayloadSize()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::stopListening()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::powerDown()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::powerUp()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::write(void const*, unsigned char)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::available()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::read(void*, unsigned char)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::whatHappened(bool&, bool&, bool&)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::openWritingPipe(unsigned long long)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::startListening()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::toggle_features()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::enableDynamicPayloads()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::enableAckPayload()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::writeAckPayload(unsigned char, void const*, unsigned char)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::isAckPayloadAvailable()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::isPVariant()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::testCarrier()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::testRPD()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::getPALevel()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::setDataRate(rf24_datarate_e)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::getDataRate()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::setCRCLength(rf24_crclength_e)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::getCRCLength()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::printDetails()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::disableCRC()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::setRetries(unsigned char, unsigned char)'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

    (.text+0x0): multiple definition of `RF24::begin()'

    libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

    collect2.exe: error: ld returned 1 exit status

    Multiple libraries were found for "nRF24L01.h"
     Used: C:\Users\Owner\Documents\Arduino\libraries\RF24ArduinoCommunicator-master
     Not used: C:\Users\Owner\Documents\Arduino\libraries\RF24-master
     Not used: C:\Users\Owner\Documents\Arduino\libraries\RF24-master
     Not used: C:\Users\Owner\Documents\Arduino\libraries\RF24-master
     Not used: C:\Users\Owner\Documents\Arduino\libraries\RF24-master
    exit status 1
    Error compiling for board Arduino/Genuino Uno.

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

Example I tried to compile:

    /*
     Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>

     This program is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     version 2 as published by the Free Software Foundation.
     */

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

    //
    // Hardware configuration
    //

    // Set up nRF24L01 radio on SPI bus plus pins 9 & 10

    RF24 radio(9,10);

    //
    // Topology
    //

    // Radio pipe addresses for the 2 nodes to communicate.
    const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };

    //
    // Role management
    //
    // Set up role.  This sketch uses the same software for all the nodes
    // in this system.  Doing so greatly simplifies testing.
    //

    // The various roles supported by this sketch
    typedef enum { role_ping_out = 1, role_pong_back } role_e;

    // The debug-friendly names of those roles
    const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"};

    // The role of the current running sketch
    role_e role = role_pong_back;

    void setup(void)
    {
      //
      // Print preamble
      //

      Serial.begin(57600);
      printf_begin();
      printf("\n\rRF24/examples/GettingStarted/\n\r");
      printf("ROLE: %s\n\r",role_friendly_name[role]);
      printf("*** PRESS 'T' to begin transmitting to the other node\n\r");

      //
      // Setup and configure rf radio
      //

      radio.begin();

      // optionally, increase the delay between retries & # of retries
      radio.setRetries(15,15);

      // optionally, reduce the payload size.  seems to
      // improve reliability
      radio.setPayloadSize(8);

      //
      // Open pipes to other nodes for communication
      //

      // This simple sketch opens two pipes for these two nodes to communicate
      // back and forth.
      // Open 'our' pipe for writing
      // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading)

      if ( role == role_ping_out )
      {
        radio.openWritingPipe(pipes[0]);
        radio.openReadingPipe(1,pipes[1]);
      }
      else
      {
        radio.openWritingPipe(pipes[1]);
        radio.openReadingPipe(1,pipes[0]);
      }

      //
      // Start listening
      //

      radio.startListening();

      //
      // Dump the configuration of the rf unit for debugging
      //

      radio.printDetails();
    }

    void loop(void)
    {
      //
      // Ping out role.  Repeatedly send the current time
      //

      if (role == role_ping_out)
      {
        // First, stop listening so we can talk.
        radio.stopListening();

        // Take the time, and send it.  This will block until complete
        unsigned long time = millis();
        printf("Now sending %lu...",time);
        bool ok = radio.write( &time, sizeof(unsigned long) );

        if (ok)
          printf("ok...");
        else
          printf("failed.\n\r");

        // Now, continue listening
        radio.startListening();

        // Wait here until we get a response, or timeout (250ms)
        unsigned long started_waiting_at = millis();
        bool timeout = false;
        while ( ! radio.available() && ! timeout )
          if (millis() - started_waiting_at > 200 )
            timeout = true;

        // Describe the results
        if ( timeout )
        {
          printf("Failed, response timed out.\n\r");
        }
        else
        {
          // Grab the response, compare, and send to debugging spew
          unsigned long got_time;
          radio.read( &got_time, sizeof(unsigned long) );

          // Spew it
          printf("Got response %lu, round-trip delay: %lu\n\r",got_time,millis()-got_time);
        }

        // Try again 1s later
        delay(1000);
      }

      //
      // Pong back role.  Receive each packet, dump it out, and send it back
      //

      if ( role == role_pong_back )
      {
        // if there is data ready
        if ( radio.available() )
        {
          // Dump the payloads until we've gotten everything
          unsigned long got_time;
          bool done = false;
          while (!done)
          {
            // Fetch the payload, and see if this was the last one.
            done = radio.read( &got_time, sizeof(unsigned long) );

            // Spew it
            printf("Got payload %lu...",got_time);

            // Delay just a little bit to let the other unit
            // make the transition to receiver
            delay(20);
          }

          // First, stop listening so we can talk
          radio.stopListening();

          // Send the final one back.
          radio.write( &got_time, sizeof(unsigned long) );
          printf("Sent response.\n\r");

          // Now, resume listening so we catch the next packets.
          radio.startListening();
        }
      }

      //
      // Change roles
      //

      if ( Serial.available() )
      {
        char c = toupper(Serial.read());
        if ( c == 'T' && role == role_pong_back )
        {
          printf("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK\n\r");

          // Become the primary transmitter (ping out)
          role = role_ping_out;
          radio.openWritingPipe(pipes[0]);
          radio.openReadingPipe(1,pipes[1]);
        }
        else if ( c == 'R' && role == role_ping_out )
        {
          printf("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK\n\r");

          // Become the primary receiver (pong back)
          role = role_pong_back;
          radio.openWritingPipe(pipes[1]);
          radio.openReadingPipe(1,pipes[0]);
        }
      }
    }

title: Having problems compiling this code for NRF24l01 on arduino uno and arduino micro

Answers: 1

body:
You have multiple copies of the library.

Delete the folder located at:

    C:\Users\Owner\Documents\Arduino\libraries\RF24ArduinoCommunicator-master


body:
As in this [SO question][1], I use use a [RH_RF24.h][2] to control an [SI4463](https://www.silabs.com/products/wireless/EZRadioPRO/Pages/Si446x.aspx). In RH_RF24, there is not anything about the speed of communication. I need the way to control the speed of communication. Because I want to take high speed of communication when Rssi is strong and slow speed when weak (for reliability).

How should I to do it ?

  [1]: https://arduino.stackexchange.com/q/31064/28084
  [2]: http://www.airspayce.com/mikem/arduino/RadioHead/classRH__RF24.html

title: Speed of comunication by SI4463 under RH_RF24.h

Answers: 1

body:
According to [RH_RF24.h][1] `setModemRegisters` takes a `ModemConfig` struct.  `prop_2003`, `prop_2004` and `prop2005` are part of that struct and it's the value of these 3 bytes that sets the datarate.

Datarate is a **24bit unsigned value** (hence the 3 bytes in the struct). `prop_2003` is the **MSB** and `prop_2005` the **LSB**.

 - `prop_2003` default is `0x0F`
 - `prop_2004` default is `0x42`
 - `prop_2005` default is `0x40`

meaning the default data rate is `0x0F4240` ( = 1Mbps)

[This application note][2] on the API gives more details (around page 99).

  [1]: http://www.airspayce.com/mikem/arduino/RadioHead/classRH__RF24.html
  [2]: http://community.silabs.com/mgrfq63796/attachments/mgrfq63796/BluetoothandWiFi/8086/1/Si446X API DESCRIPTIONS.pdf


body:
I am using [ESP8266-12E](https://www.axman.com/content/esp8266-12e-wifi-module) with a [PCF8574](https://www.axman.com/content/esp8266-12e-wifi-module) as an I/O Pins Extender.
There are videos on youtube to use the [PCF8574](https://www.axman.com/content/esp8266-12e-wifi-module) with an ESP8266-01, but my problem is that I'm unable to analyze the pin connections with an [ESP8266-12E](https://www.axman.com/content/esp8266-12e-wifi-module).
In the youtube tutorial it is said that the _GPIO0_ AND _GPIO2_ will go to the _SDA_ and _SLC_ pins of the [PCF8574](https://www.axman.com/content/esp8266-12e-wifi-module), but then, in the case of ESP8266-12E, the pins will go to the PCF8547.

Thanks in advance.

title: How to use ESP8266-12E with PCF8574 as an I/O extender

Answers: 1

body:
Found the answer .
The data sheet of ESP8266-12E explains everything.
The pin diagram has the given tags which shows which pins we can use.


body:
Here is my code. The incoming string is "*CRB12344,Temp25,Humidity55,CC5#"

I am unable to get value of Temp which is 25 and Humidity which is 55 and CC which 5. It only display the value of CR i.e B12344 (in this case). May be issue with strtok function?

    String inputString = "";
    boolean stringComplete = false, StartCapturing = false;

    char inData[50];
    char inChar, IncomingWeight;
    char IncomingString[50];
    const int httpPort = 80;

    char *i, *k,*p;
    String CardID;
    int Temprature, Humidity, TC, CC;
    byte SendData = 0;

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

    void loop()
    {
      serialEvent();

      if (stringComplete)
      {
        inputString.toCharArray(IncomingString, 50);
        Serial.println();
        Serial.println(IncomingString);

        i = strstr(IncomingString, "CR");
        {
          if (i)
          {
            p = i+2;
            CardID = strtok(p, ",");

            Serial.print("Card Number :");
            Serial.print(CardID);
            Serial.println();
          }
        }

        i = strstr(IncomingString, "Temp");
        {
          if (i)
          {
            Temprature = strtoul(i + 4 , NULL, 10);
            Serial.print("Temprature :");
            Serial.print(Temprature);
            Serial.println();
          }
        }

        i = strstr(IncomingString, "Humidity");
        {
          if (i)
          {
            Humidity = strtoul(i + 8 , NULL, 10);
            Serial.print("Humidity :");
            Serial.print(Humidity);
            Serial.println();
          }
        }

        i = strstr(IncomingString, "TC");
        {
          if (i)
          {
            TC = strtoul(i + 2 , NULL, 10);
            Serial.print("Total Count :");
            Serial.print(TC);
            Serial.println();
          }
        }

        i = strstr(IncomingString, "CC");
        {
          if (i)
          {
            CC = strtoul(i + 2 , NULL, 10);
            Serial.print("Current Count :");
            Serial.print(CC);
            Serial.println();

          }
        }

        stringComplete = false;
        inputString = "";
        delay(10);
      }

title: strtok problem while parsing String

Answers: 1

body:
`strtok()` is a destructive function. It replaces the token with an end-of-string marker (`\0`). Thus once used the original string is irevocably lost.

Your first use of `strtok()` changes the string from:

    *CRB12344,Temp25,Humidity55,CC5#\0

to:

    *CRB12344\0Temp25,Humidity55,CC5#\0

Thus any future references to `InputString` only see up to the end-of-string marker:

    *CRB12344\0

Instead you should use `strtok()` in a `while` loop to slice the string into tokens and examine what the token is:

    char *tok = strtok(IncomingString, ",");
    while (tok) {
        if (strncmp(tok, "*CR", 3) == 0) { // tok is *CRB1234
            // ... whatever ...
        } else if (strncmp(tok, "Temp", 4) == 0) { // tok is Temp25
            // ... whatever ...
        } else if (strncmp(tok, "Humidity", 8) == 0) { // tok is Humidity55
            // ... whatever ...
        } else if (strncmp(tok, "CC", 2) == 0) { // tok is CC5#
            // ... whatever ...
        }
        tok = strtok(NULL, ","); // Note: NULL, not IncomingString
    }


body:
I am powering my Pro Mini(3.3V version) using an external battery (~6.5V 700mA) . I used to connect it to the RAW and GND pins on my pro mini and everything ran fine.

Today when I powered up my Arduino again, it didn't light up. A quick glance told me that I had connected the battery to the RST and GND pins mistakenly. Quickly pulled them out and put them into place, the Arduino worked perfectly until I discovered that the RESET button is no longer working. Without the RESET button I can't upload anything to my board.

Tried connecting the RST and GND Pins, didn't work.

The board is working fine though, I discovered a new procedure to upload as follows-
NOTE: I use the USB-to-TTL adapter by DSUN (picked up at a local electronics store).

 1. Connect the RX, TX and GND Pins from the adapter to the Pro Mini.
(The green LED on the Pro Mini lights up dimly)
 2. Upload the sketch from the IDE.
 3. As soon as the IDE shows "Uploading", connect the +5V pin from the adapter to RAW pin on Pro Mini. Upload goes fine.

The above procedure is working just fine, and the board as well. But I'd like to have my RESET button back.
So what do I do?

title: Arduino Pro Mini RESET button suddenly stopped working

Answers: 1

body:
What do you do? You replace the chip on the board.

By pumping 6.5V through the RESET pin with no power attached you have irrevocably broken the reset pin inside the chip. Way too much current will have flowed through the internals of the pin leaking its way up to the VCC pin and then back down through the rest of the chip to ground, burning out vital parts of the internal logic of the pin.

It's dead, Jim.

Your "fix" basically relies on the fact that the bootloader runs for any kind of reset - be that a RESET pin reset or a POR (Power-On Reset).


body:
I'm trying to control a few NeoPixels using a 3.3V Particle Photon.

I've got a 5V power source that I'm using to power the NeoPixels (as they require that voltage. That works fine.

Them I'm using a [74AHCT125 level shifter][1] to increase the data signal from the Photon from 3.3 to 5.

But I'm seeing sporadic response from the NeoPixels and my hunch is there's something wrong with the power output from the 74AHCT125.

Is there a way I can measure the voltage from the data output of the 74AHCT125? I tried connecting the wire from the 74AHCT125 to my multimeter but I'm not getting any measurement from it.

  [1]: https://www.adafruit.com/product/1787

title: Measure voltage of data output?

Answers: 1

body:
The reason your mulitmeter is not telling you much is probably because it reads some sort of averaged voltage, and your signal is flipping between low and high very rapidly.

If you had an oscilloscope you could easily have a look and see what the peak-to-peak voltage is, but since you don't you'll have to find another way.

If you have some basic electronic components at your disposal, you could knock up a simple peak voltage front-end for your multimeter - [this][1] looks like roughly the right thing.  You'll need to calibrate it with a known 5v level (i.e. see what reading your meter tells you for a fixed 5v supply) because you'll drop some voltage across the diode.

Otherwise perhaps you could use an analogue input of a 5v Arduino: write a simple sketch to measure (very rapidly!) and tell you the maximum reading every second, say.  I don't know off hand how fast the Uno will sample, or the clock rate of your Neopixels - you'll need the Arduino to sample at least as fast as your clock rate.

For the purpose of a quick hassle-free check, I'd probably plump for the first option.

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


body:
We are given two voltages A and B between 0 and 5V.
So how do I generate a smooth/continuous analog change in
voltage from A to B in a predefined time? The current with that varying voltage is 1 ma or less. The output voltage value is described by a simple quadratic (a*X^2)+(b*x)+c, at time x seconds.

If that not possible using an Arduino - what is the nearest  solution to it? It seems that it would require an RC circuit?

When I mean smooth/continous I mean it doesn't move in "digital steps" or to use an analogy with resistance instead of voltage - it would be like the way resistance changes when a potentiometer is turned between two places, in a given time, by hand.

A potential solution would be to make a circuit that generate arbitrary voltage between 0 and 5v, some how, at a point in time. For each subsequent small change in time, the change in time is constant, generate the desired voltage from a sketch. If the change of time is small and constant, will putting in a high pass RC filter work? Though I'm not sure of a circuit that can create an arbitrary voltage, or arbitrary voltage resolution or how good the RC filter approximates the quadratic smoothness. I don't know the answer.

title: How to create a smooth change in voltage?

Answers: 1

body: I'm not sure that there exists a perfect solution for what you want.  Generating the correct output voltage for time is easy.  Just keep track of time and use the formula you wrote to compute the correct voltage you should be at.  Then you can use a PWM output.  However, this isn't going to be perfect since it is made with pulses rather than a continuous output.  On the Uno the pulses are at 490Hz or 980Hz depending on which pin you use.  Use an RC filter and you can then make it continuous - when you tell it output 2.5V you get 2.5V rather than 0 then 5 then 0 then 5 in short bursts.  But, you're still going to get discrete steps based on the resolution of the ADC - for an Arduino Uno, it's 255 steps I believe.  You could get a separate DAC chip to increase this and can probably get enough steps that their small enough you won't notice.  Some versions of the arduino like the due have 12bit analog output and higher frequency, which should help.


body:
I am using an Arduino Mega and I have a basic webpage built using `EthernetServer` for the connection and `EthernetClient` to write the HTML to the client. I have a simple web form:

    client.println("<form method=get>");
    client.println("<input type=text name=data>");
    client.println("<input type=submit value=Submit>");
    client.println("</form>");

I'd like to receive any input from the form and check it against values in order to do stuff on the back end (e.g. reset certain data). How do I get the data from the web page?

title: Arduino Web Server: Receiving response from web form

Answers: 1

body:
Your form method is set to `GET`. In this case, when `Submit` is clicked, the client/browser sends request with values in URI:

    GET /index.html?data=user_value&default_name_of_button=Submit HTTP/1.1
    ...more lines to follow...

These HTTP header lines will be available on your `EthernetClient` instance, retrieve them line-by-line using connected(), available(), read() methods. Then parse the line, find the `user_value`.

Please note that browser retrieves your page (to display it) using `GET` method too, in that case URI will be like:

    GET /index.html HTTP/1.1
    ...more lines to follow...

It is recommended to use `POST` method to submit form values. Example content section (before content, server must send HTTP header - check [Arduino Web Server][1] example)

    <form method="POST" action="foo.php">

    First Name: <input type="text" name="first_name" />

    Last Name: <input type="text" name="last_name" />

    <input type="submit" name="action" value="Submit" />

    </form>

In this case the values are returned in content section:

    POST /foo.php HTTP/1.1
    Host: localhost
    User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Language: en-us,en;q=0.5
    Accept-Encoding: gzip,deflate
    Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
    Keep-Alive: 300
    Connection: keep-alive
    Referer: http://localhost/test.php
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 43

    first_name=John&last_name=Doe&action=Submit

Tutorial on HTTP headers:

https://code.tutsplus.com/tutorials/http-headers-for-dummies--net-8039

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


body:
I have an LCD Display HD44780 model and I was reading his [datasheets][1]

  [1]: https://www.sparkfun.com/datasheets/LCD/HD44780.pdf
I saw the it has the functionality to be switched on/off as stated:

> Display on/off control: D = 0; Display off // C = 0; Cursor off // B = 0;
> Blinking off

and by continue reading it states:

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

Then he states again:

**Display On/Off Control**

> D:  The display is on when D is 1 and off when D is 0. When off, the
> display data remains in DDRAM.

But I can't reaaly understand what I fisically need to do, can anyone help me out to better understand?

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

EDIT:
For better clarify myfinal goal is to completely (power OFF) the LCD screen, I have some NPN transistors and if this would be the best solution, how about the wiring? do I have only to stop suppying VDO?

title: How to switch on and off an HD44780 LCD Display?

Answers: 2

body:
Assuming that display is initialized in 8-bit mode: to send command such as "Turn display on/off",

 - set RS to LOW first (meaning it is command, not data)
 - set command bits on DB7-DB0 (in your case it could be 0x08 - DB2/DB1/DB0 all LOW to turn off following: display, cursor and blinking)
 - make a pulse on EN pin LOW-HIGH-LOW (take a 40uS delay before further communication)

body: At the end I manage to control the complete poweroff of the screen by connecting the pin 15 of the lcd to the Arduino and with a simple HIGH an LOW set of the arduino pin I was able to power it ON/OFF.


body:
So here are some pictures of the setup I have with an LED, 330 Ohm resistor, Arduino UNO, 2 XBee S1s, and many wires,

https://i.stack.imgur.com/QT1KF.jpg

For specifics, here is the wiring,

 - XBee Pin 1 (VCC) is connected to Arduino Uno Pin 3.3V
 - XBee Pin 2 is connected to Arduino Uno Pin 1 (TX)
 - XBee Pin 3 is connected to Arduino Uno Pin 0 (RX)
 - XBee Pin GND is connected to the minus column on the breadboard.
 - Arduino Uno Digital Pin 9 is connected to a 330 ohm resistor which is connected to an LED that is connected to the minus column on the breadboard
 - Arduino Uno Pin GND is connected to the minus column on the breadboard
 - And lastly I have another XBee connected to my laptop through a USB dongle

I'm trying to send data in the form of bits through my computer using a program called XCTU to turn the LED on and off. Here is the code for the Arduino,

    int led = 9;
    int bufferSize = 100;
    byte readBuffer[100];
    byte lastByte = 0;
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(led, OUTPUT);
      digitalWrite(led, HIGH);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      int toRead = Serial.available();
      if(toRead > 0){
        while(toRead > bufferSize){
          Serial.readBytes(readBuffer, bufferSize);
          toRead = toRead - bufferSize;
        }

        Serial.readBytes(readBuffer, toRead);
        lastByte = readBuffer[toRead - 1]; //reads last big in serial input

        if(lastByte == '1'){
          digitalWrite(led, HIGH);
        }
        else if(lastByte == '0'){
          digitalWrite(led, LOW);
        }
      }
      delay(250);
    }

However, when I send a '0' through XCTU, the LED doesn't turn off. What could be causing this? Note that I did not use a shield to connect the XBee to the Arduino Uno, I soldered the pins to the appropriate spots because I thought it was possible after watching this video,
https://www.youtube.com/watch?v=wtal7SWZek0

Also, I will be cross-posting this on arduino forums to get as much input on this as possible. I will update both topics frequently to attribute answerers for their input (https://forum.arduino.cc/index.php?topic=435027.msg2998240#msg2998240)

title: Unable to send serial data to XBee connected to Arduino Uno without a shield

Answers: 1

body:
So after experimenting with the SoftwareSerial library, it seemed that all the wiring was done correctly but the original code was replaced with,

    #include "SoftwareSerial.h"

    SoftwareSerial XBee(1, 0); //TX is 1, RX is 0 on the Arduino Uno
    int LED = 9;

    void setup()
    {
      // Baud rate MUST match XBee settings (as set in XCTU)
      XBee.begin(9600);
      pinMode(LED, OUTPUT);
    }

    void loop()
    {
      if (XBee.available())
      {
        byte c = XBee.read();
        if (c == '1')
        {
          digitalWrite(LED, HIGH);

        }
        else if (c == '0')
        {
          digitalWrite(LED, LOW);
        }
      }
      delay(150);
    }

and I am now able to turn an LED on or off with data sent from XCTU.

**Note:** I forgot to include this in my question but some configuration details were that the XBees I was working with were "XBee 1mW Wire Antenna - Series 1 (802.15.4)". Settings for each XBee configured in XCTU include,

Baud Rate: 9600

Data Bits: 8

Stop Bits: 1

no Parity nor flow control

Channel and Pan ID were identical across both XBees

For the XBee connected to the laptop,
DH = 0, DL = 2, MY = 1, and CE = Coordinator[1]

For the XBee connected to the Arduino Uno,
DH = 0, DL = 1, MY = 2, and CE = End Device[0]

*Credit to user PaulS on the arduino forum for helping me out.


body:
I found a code that turns on different RGB colors but I would like it to blink rapidly one color once called. I dont want to use void loop function to make this possible. My RGB is a cathode. Any help?

    int redPin = 8;
    int greenPin = 9;
    int bluePin = 10;

    //uncomment this line if using a Common Anode LED
    //#define COMMON_ANODE

    void setup()
    {
      pinMode(redPin, OUTPUT);
      pinMode(greenPin, OUTPUT);
      pinMode(bluePin, OUTPUT);
    }

    void loop()
    {
        for (int j = 0; j <= 10; j++) //LED simply stays on. No blinking occuring
         {
          setColor(255, 0, 0);
          delay(100);
          setColor(0, 0, 0);
            }
    }

    void setColor(int red, int green, int blue)
    {
      #ifdef COMMON_ANODE
        red = 255 - red;
        green = 255 - green;
        blue = 255 - blue;
      #endif
      analogWrite(redPin, red);
      analogWrite(greenPin, green);
      analogWrite(bluePin, blue);
    }

title: How to make RGB LED blink rapidly one color using FOR or WHILE loop

Answers: 1

body:
Simply do this:

    int redPin = 8;
    int greenPin = 9;
    int bluePin = 10;

    //uncomment this line if using a Common Anode LED
    //#define COMMON_ANODE

    void setup()
    {
      pinMode(redPin, OUTPUT);
      pinMode(greenPin, OUTPUT);
      pinMode(bluePin, OUTPUT);
    }

    void loop()
    {
      blinkLed();
    }

    void setColor(int red, int green, int blue)
    {
    #ifdef COMMON_ANODE
      red = 255 - red;
      green = 255 - green;
      blue = 255 - blue;
    #endif
      analogWrite(redPin, red);
      analogWrite(greenPin, green);
      analogWrite(bluePin, blue);
    }

    void blinkLed()
    {
      setColor(255, 0, 0);  // red
      delay(1000);
      setColor(0, 0, 0);  // off
      delay(1000);
    }

This snippet will blink your led in the red color. Put it in your void loop and you are ready to go.

NOTE: Erase the rest of the void loop before putting this in. Don't delete the function though.

**EDIT**

FULL CODE ADDED


body:
I have  written a trivial code in Arduino IDE but while verifying its returning a error displaying "i was not declared in scope 12'

      int pinMatrix[i][j]= {{2,3,4},{5,6,7},{7,8,9}};
    void setup() {
    for (i=0;i<3;i++){
      for(j=0;j<3;j++){
        pinMode(pinMatrix[i][j],OUTPUT);
      }
    }

    }

    void loop() {
    for(i=0;i<3;i++){
      for(j=0;j<3;j++){
          digitalWrite(pinMatrix[i][j],HIGH);
          delay(1000);
          digitalWrite(pinMatrix[i][j],LOW);
      }

      }

    }

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

title: 2d 3*3 LED matrix code error

Answers: 1

body:
Variable `i` & `j` are not declared. They should be declared as 3. Try this:

    const int x = 3;
    const int y = 3;

    int pinMatrix[x][y] = {{2, 3, 4}, {5, 6, 7}, {7, 8, 9}};

    void setup() {
      for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
          pinMode(pinMatrix[i][j], OUTPUT);
        }
      }
    }

    void loop() {
      for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
          digitalWrite(pinMatrix[i][j], HIGH);
          delay(1000);
          digitalWrite(pinMatrix[i][j], LOW);
        }
      }
    }


body:
I have a class with a byte (stripLength) that seems to just disappear in the middle of the frameStep() method. I'm not especially skilled with C++ (or non-VM languages in general), but I believe it's only written or modified at the initialization of the class. What am I doing wrong?

BugFinding.ino

    #define PIN 11
    #define NUM_LEDS 100
    #define WAIT 5
    #define TAIL_LENGTH 40

    #include "Libraries/Adafruit_NeoPixel.h"
    #include "LightingStrip.h"

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_RGB + NEO_KHZ800);
    LightingStrip lightStrip = LightingStrip(strip, NUM_LEDS, 20);

    void setup() {
     Serial.begin(9600);
     strip.begin();
     strip.show();
     Serial.println("BugFinding");
     lightStrip.setColors();
    }

    void loop() {
     Serial.println("loop");
     lightStrip.frameStep();
     lightStrip.write();
     delay(WAIT);
    }

LightingStrip.h

    #ifndef LIGHTINGSTRIP_H_
    #define LIGHTINGSTRIP_H_

    #include "Libraries/Adafruit_NeoPixel.h"

    class LightingStrip {
     public:
      LightingStrip(Adafruit_NeoPixel ledStrip, uint8_t stripLength, uint8_t lengthOfTail);
      void frameStep();
      void write();
      void setColors();
     protected:
      Adafruit_NeoPixel strip;
      uint8_t mode;
      uint8_t frame;
      uint8_t colorFrame;
      uint8_t stripLength;
      uint8_t tailLength;
      uint32_t buf[];
      uint32_t colors[7];
      uint8_t currentColor[3];

      void cycleStep();
    };

    #endif /* LIGHTINGSTRIP_H_ */

LightingStrip.cpp

    #include "LightingStrip.h"
    #include "Libraries/Adafruit_NeoPixel.h"

    LightingStrip::LightingStrip(Adafruit_NeoPixel ledStrip, uint8_t length, uint8_t lengthOfTail) {
     strip = ledStrip;
     stripLength = length;
     tailLength = lengthOfTail;

     buf[stripLength] = {0};
     colorFrame = 0;

     cycleStep();
    }

    void LightingStrip::setColors(){
     //colors = uint8_t[8][3];
     colors[0] = strip.Color(255, 120,   0); // Orange
     Serial.println("Color 0: " + String(colors[0]));
     Serial.println("Color 0: " + String(strip.Color(255, 120,   0)));
     Serial.println("stripLength: " + String(this->stripLength));
     colors[1] = strip.Color(  0, 255,   0); // Green
     Serial.println("setColors");
     Serial.println("stripLength: " + String(stripLength));
    }

    void LightingStrip::cycleStep(){
     frame = 0;
     colorFrame++;
    }

    void LightingStrip::frameStep(){
     Serial.println("frameStep");
     Serial.println("Color 0: " + String(colors[0]));
     int16_t j;
     Serial.println("frame: " + String(frame));
     Serial.println("colorFrame: " + String(colorFrame));
     Serial.println("stripLength 1: " + String(stripLength));
     if(frame > stripLength + tailLength)
      cycleStep();
     Serial.println("stripLength 1.2: " + String(stripLength));

     for(j=0; j<stripLength; j++){
      buf[j] = strip.Color(255,255,255);
     }
     Serial.println("stripLength 2: " + String(stripLength));
     for(j=frame; j>0 && frame-j<=stripLength; j--){
      if(j>stripLength) continue;
      buf[j] = colors[colorFrame];
      Serial.print("j: " + String(j));
      Serial.print(" color: " + String(colors[colorFrame]));
      Serial.println();
     }
     Serial.println("stripLength 3: " + String(stripLength));
     Serial.println("stripLength 4: " + String(stripLength + tailLength));
     Serial.println("stripLength 5: " + String(stripLength));

     frame++;
    }
    void LightingStrip::write(){
     Serial.println("write");
     Serial.println("stripLength: " + String(stripLength));

     int16_t j;

     for(j=0; j<stripLength; j++){
      Serial.print(" j: " + String(j));
      strip.setPixelColor(j, buf[j]);
     }
     Serial.println();
     Serial.println(String(buf[0]));
     Serial.println(String(strip.getPixelColor(0)));
     strip.show();
    }

Serial Output:

    BugFinding
    Color 0: 16742400
    Color 0: 16742400
    stripLength: 100
    setColors
    stripLength: 100
    loop
    frameStep
    Color 0: 16742400
    frame: 0
    colorFrame: 1
    stripLength 1: 100
    stripLength 1.2: 100

title: Why is my class losing a field in the middle of a method

Answers: 2

body:
I think what you mean by stripLength "disappearing" is that your `stripLength 2` trace does not appear. This is going to be because you never reach this point in the code.

Look at `buf`: it's defined as an array in the .h file, but you don't ever allocate any memory for it. `buf[stripLength] = {0}` doesn't do what you think it does. It puts a 0 into element 100, which at that point is going to trash over some memory you don't mean to write to. When you write to every element in the loop, you're going to trash over lots of memory you didn't mean to.  You want something like

    buf = (uint32_t*) malloc(stripLength*sizeof(uint32_t));

Remember to free it again in the destructor.

(Full disclosure: I'm writing this on my phone and I can't remember or test whether it's legal syntax to do this with your array defined (in the .h) as `uint32_t buf[]`. It's more common, and certainly legal, to use `uint32_t* buf`.)

body:
At first glance this looks like a sketch with typical memory (heap) issues. When using a lot of string literals, `String` variables and expressions heap memory becomes fragmented or simple exhausted.

Some programming rules to avoid this:

1. If possible use the macro `F()` with string literals. Typically `F()` should be used when printing a string.

2. If possible do not use `String` especially when there is limited amount of SRAM. Remember that ATmega328 based boards such as Arduino Uno, Nano, etc, have only 2 Kbyte SRAM.

3. Avoid `String` expressions especially in `Serial` print statements. Use several print statements instead.

Applying these programming rules to some of the statements in the code above:

    Serial.println("frameStep");
    Serial.println("Color 0: " + String(colors[0]));
    Serial.println("frame: " + String(frame));

Becomes:

    Serial.println(F("frameStep"));
    Serial.print(F("Color 0: "));
    Serial.println(colors[0]);
    Serial.print(F("frame: "));
    Serial.println(frame);

With no `String` expressions, and a lot less memory used.

Cheers!

PS: As @MarkSmith points out there is also a pure allocation error. The statement below in the `LightingStrip` constructor:

    buf[stripLength] = {0};

Does not mean allocate and assign. It means element `stripLength` is assigned the value of the pointer to an array with the single value zero. Guess that the compiler is also warning about this. The value of `buf` is random as it is not initiated. Assigning an element in the `buf` will write to a random position.


body:
The below picture is the introduction of [setModemRegisters][1] .

- First: What is the mean of **ModemConfig* config**? I mean: how to write the parameter. Maybe just give a example, and it will be better if it's suitable for this [SO question][2].
- Second: What is the mean of data rate? It is the speed of SPI between the [SI4463](https://www.silabs.com/products/wireless/EZRadioPRO/Pages/Si446x.aspx) and MCU or speed of two SI4463  ?
- Third, What is the mean of bandwidths? I never saw it...

Thanks for any help .

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

  [1]: http://www.airspayce.com/mikem/arduino/RadioHead/classRH__RF24.html#afd00202f768b4f0f893f2fbb9e650c7b
  [2]: https://arduino.stackexchange.com/q/31122/28084
  [3]: https://i.stack.imgur.com/QR3eg.jpg

title: How to use setModemRegisters in RF24

Answers: 1

body:
**ModemConfig * config** is a pointer to a `ModemConfig` struct.

You need to create a `ModemConfig` struct, populate it then pass a pointer to it in the call to the `setModemConfig()` function.

Something like this:

    // create the struct
    ModemConfig mc = ModemConfig();

    ... //populate the struct values

    // then call the function
    setModemConfig(&mc);

The **datarate** is the rate at which you are sending information over the radio channel (**not** between the MCU and the Si4463).

The **bandwidth** is the range of frequencies used in the radio transmission (e.g. in [FSK][1] if a *low/0* is 99.95MHz and a *high/1* is 100.05Mhz then the bandwidth would be 100Khz)

  [1]: https://en.wikipedia.org/wiki/Frequency-shift_keying


body:
I'm trying to connect a nRF24L01 with my Arduino Micro and Arduino Uno. The Arduino Uno works fine, but it doesn't talk with the Arduino Micro. CE is on pin 7 and CSN on pin 8. I posted the code down below into 2 Arduino IDE screens and changed one screen `bool radioNumber = 1` and `bool role = 1` and the other screen `bool radioNumber = 0` and `bool role = 0` so that they could communicate. However, the program with the Arduino Micro doesn't seem to work with pins 7 and 8. Is it code where something is wrong or do I need to change the pins and code? How do I make them both communicate with each other?

    /*
    * Getting Started example sketch for nRF24L01+ radios
    * This is a very basic example of how to send data from one node to another
    * Updated: Dec 2014 by TMRh20
    */

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

    /****************** User Config ***************************/
    /***      Set this radio as radio number 0 or 1         ***/
    bool radioNumber = 0;

    /* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8 */
    RF24 radio(7,8);
    /**********************************************************/

    byte addresses[][6] = {"1Node","2Node"};

    // Used to control whether this node is sending or receiving
    bool role = 0;

    void setup() {
      Serial.begin(115200);
      Serial.println(F("RF24/examples/GettingStarted"));
      Serial.println(F("*** PRESS 'T' to begin transmitting to the other node"));

      radio.begin();

      // Set the PA Level low to prevent power supply related issues since this is a
     // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
      radio.setPALevel(RF24_PA_LOW);

      // Open a writing and reading pipe on each radio, with opposite addresses
      if(radioNumber){
        radio.openWritingPipe(addresses[1]);
        radio.openReadingPipe(1,addresses[0]);
      }else{
        radio.openWritingPipe(addresses[0]);
        radio.openReadingPipe(1,addresses[1]);
      }

      // Start the radio listening for data
      radio.startListening();
    }

    void loop() {

    /****************** Ping Out Role ***************************/
    if (role == 1)  {

        radio.stopListening();                                    // First, stop listening so we can talk.

        Serial.println(F("Now sending"));

        unsigned long start_time = micros();                             // Take the time, and send it.  This will block until complete
         if (!radio.write( &start_time, sizeof(unsigned long) )){
           Serial.println(F("failed"));
         }

        radio.startListening();                                    // Now, continue listening

        unsigned long started_waiting_at = micros();               // Set up a timeout period, get the current microseconds
        boolean timeout = false;                                   // Set up a variable to indicate if a response was received or not

        while ( ! radio.available() ){                             // While nothing is received
          if (micros() - started_waiting_at > 200000 ){            // If waited longer than 200ms, indicate timeout and exit while loop
              timeout = true;
              break;
          }
        }

        if ( timeout ){                                             // Describe the results
            Serial.println(F("Failed, response timed out."));
        }else{
            unsigned long got_time;                                 // Grab the response, compare, and send to debugging spew
            radio.read( &got_time, sizeof(unsigned long) );
            unsigned long end_time = micros();

            // Spew it
            Serial.print(F("Sent "));
            Serial.print(start_time);
            Serial.print(F(", Got response "));
            Serial.print(got_time);
            Serial.print(F(", Round-trip delay "));
            Serial.print(end_time-start_time);
            Serial.println(F(" microseconds"));
        }

        // Try again 1s later
        delay(1000);
      }

    /****************** Pong Back Role ***************************/

      if ( role == 0 )
      {
        unsigned long got_time;

        if( radio.available()){
                                                                        // Variable for the received timestamp
          while (radio.available()) {                                   // While there is data ready
            radio.read( &got_time, sizeof(unsigned long) );             // Get the payload
          }

          radio.stopListening();                                        // First, stop listening so we can talk
          radio.write( &got_time, sizeof(unsigned long) );              // Send the final one back.
          radio.startListening();                                       // Now, resume listening so we catch the next packets.
          Serial.print(F("Sent response "));
          Serial.println(got_time);
       }
     }

    /****************** Change Roles via Serial Commands ***************************/

      if ( Serial.available() )
      {
        char c = toupper(Serial.read());
        if ( c == 'T' && role == 0 ){
          Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK"));
          role = 1;                  // Become the primary transmitter (ping out)

       }else
        if ( c == 'R' && role == 1 ){
          Serial.println(F("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK"));
           role = 0;                // Become the primary receiver (pong back)
           radio.startListening();

        }
      }

    } // Loop

title: Having trouble connect nrf24l01 to arduino micro and arduino uno!

Answers: 0


body:
I am using an [ESP8266-12E](https://www.espressif.com/en/products/hardware/esp8266ex/resources) with a PCF8547.
I have managed to turn on and turn off LEDs using these two things.
I am using these three commands to do it.

     Wire.begin(SDA_PIN,CLK_PIN);
     Wire.beginTransmission(0x20);
     Wire.write(~((uint8_t)1<<cnt));
     Wire.endTransmission();

The problem I am facing here is: I am using 4 LEDs and I am only able to turn on one LED at a time. When I turn on another, all the LEDs turn off - in short, the LEDs or the PCF8547 do not preserve the state.

I want to toggle on the LEDs without disturbing the other's state.
How can I do it?
I think, I need more knowledge about the write function, don't I?

**Update:**

I have already connected A0, A1, A2 to ground. This is the function I use now to toggle the LEDs.

    void enlight(int cnt)
    {
      if (cnt == 1)
        value = value | 1<<cnt;
        if (cnt == 2)
          value = value | 2<<cnt;
        if (cnt == 3)
          value = value | 3<<cnt;
        if (cnt == 4)
          value = value | 4<<cnt;
        value = ~value;
        Wire.begin(SDA_PIN,CLK_PIN);
        Wire.beginTransmission(0x20); Wire.write(value);
        Wire.endTransmission();
      }

but when I turn off/on any other LEDs they also toggle, which I don't want.

[![My Circuit Image][1]][1]

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

title: PCF8547 Wire.write explanations

Answers: 1

body:
(I haven't used this library, but this looks like a general C(++) question...)

The important part of what you're doing is this:

    Wire.write(~((uint8_t)1<<cnt));

Let's break it down.

It calculates a value by taking the number `1` and shifting it left `cnt` times. Then it takes the complement of that number - changes 0s to 1s and 1s to 0s.  This number is sent to Wire.write() and lights up light number `cnt`.

Example: Let's say you start with `cnt==2`, to light LED 2.  It will shift the number `1` left by two digits, giving you the binary number `00000100`.  Then it will invert this, giving you `11111011`.  This is given to Wire.write().

We can see from this that to light an LED, we need to put a '0' in the right place.

How can you make several numbers light up?  We need to put several zeros in, at the right places.

Here's an example of how you might like to do this - which isn't the prettiest code but I hope it shows you what's going on.

    // How we would like the LEDs to appear
    boolean led0 = true;    // LED 0 ON
    boolean led1 = false;   // LED 1 OFF
    boolean led2 = true;    // LED 2 ON
    boolean led3 = false;   // LED 3 OFF

    // Start with all LEDs off
    uint8_t value = 0;

    // Put a 1 in place for each LED we want to be ON
    // The | symbol means "logical OR" (Google it)
    if (led0) value = value | 1<<0;
    if (led1) value = value | 1<<0;
    if (led2) value = value | 2<<0;
    if (led3) value = value | 3<<0;

    // Invert this value
    value = ~value;

    // Write it to Wire
    Wire.begin(SDA_PIN,CLK_PIN);
    Wire.beginTransmission(0x20);
    Wire.write(value);
    Wire.endTransmission();

Since it appears you have to send values for all the lights every time, you need to remember the value you sent last time, and modify only the bits you want to change.  Here's a way you can do that:

    void setLight(int lightNum, boolean lightOn) {
      // Remember the last state of the lights.
      // Start with all lights OFF.
      static uint8_t lightsOn = 0;

      // We only have four lights (0-3).  Only respond for lights
      // we we have.
      if (lightNum<4) {
        // Get a bitmask with a single 1 in the right
        // position for this light
        uint8_t position = 1<<lightNum;

        // Clear (to 0) that bit in the state
        lightsOn &= ~position;

        // Set (to 1) the bit if we want the light on
        if(lightOn) lightsOn |= position;

        // Write out the value of all lights
        Wire.begin(SDA_PIN,CLK_PIN);
        Wire.beginTransmission(0x20);
        Wire.write(~lightsOn);
        Wire.endTransmission();
      }
    }

Call it with something like

    setLight(0, true);    // Switch the first light ON
    setLight(3, true);    // Switch the fourth light ON (first stays on)
    setLight(0, false);   // Switch the first light OFF (fourth stays on)