message:
PWM multiplexing on Arduino nano

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

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.


sender: user

message:
State machinese for serial input

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?

sender: assistant

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);
    }


message:
Pause between switching motor direction

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);
  }
}

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


message:
Capturing avrdude command in IDE

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?

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.


message:
Why is my transistor always transmitting?

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

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.


message:
Hold a random number

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;
      }
    }

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.


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

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]);
        }
      }
    }

body:
You have multiple copies of the library.

Delete the folder located at:

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


message:
Speed of comunication by SI4463 under RH_RF24.h

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

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


message:
strtok problem while parsing String

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);
      }

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
    }


message:
Arduino Pro Mini RESET button suddenly stopped working

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?

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


message:
How to create a smooth change in voltage?

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.

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.


message:
Arduino Web Server: Receiving response from web form

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?

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


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

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?

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.


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

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)

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.


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

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);
    }

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


message:
2d 3*3 LED matrix code error

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

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);
        }
      }
    }


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

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

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.


message:
How to use setModemRegisters in RF24

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

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


message:
PCF8547 Wire.write explanations

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

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)


message:
Arduino Uno Reading Fuses

I am trying to read the fuse values for the Arduino Uno, but keep getting the following results returned back to me:

    enter code hereavrdude: Version 6.0.1, compiled on Dec 16 2013 at 17:26:24
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/usr/local/CrossPack-AVR-20131216/etc/avrdude.conf"
         User configuration file is "/Users/hd334/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/cu.usbmodem1421
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 4.4
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0x1e950f
    avrdude: safemode: lfuse reads as 0
    avrdude: safemode: hfuse reads as 0
    avrdude: safemode: efuse reads as 0

    avrdude: safemode: lfuse reads as 0
    avrdude: safemode: hfuse reads as 0
    avrdude: safemode: efuse reads as 0
    avrdude: safemode: Fuses OK (H:00, E:00, L:00)

    avrdude done.  Thank you.

I have tried using avrisp as the programmer too, but this reports an invalid device signature. If I override the device signature check with -F I get the same results as above.

I am using an Uno as the ISP to another uno and have connected the two together as detailed in
https://www.arduino.cc/en/Tutorial/ArduinoISP

I have boot loaded the Arduino Atmega328P boot loader and from the fuse settings given in the boards.txt file expect to see:
lfuse reads 0xff
hfuse reads 0xde
efuse reads 0x05

Another question is with the low fuse set to 0xff the CKDIV8 is programmed so won't the clock be set to 2MHz?

Please help

body:
I'm using a stk500 (USB <> ISP programmer) to read atmega328p fuses. I use this cmd:

    C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\avrdude.exe -CC:"\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega328p -cstk500 -PCOM9 -e -Ulfuse:r:-:i -Uhfuse:r:-:i -Uefuse:r:-:i

Sometime ago I had some issues with device signatures because I missed the "p" in atmega328p definition.

As a tip, you can check the Arduino verbose to help you with more information:

FILE >> PREFERENCES

SHOW VERBOSE OUTPUT DURING: [x] COMPILATION [x] UPLOAD


body:
Concerning your questions about clock division settings: have a look at [this pretty tool][1], it gives you a avrdude query for setting fuses (take care!). The CKDIV8 bit of the low fuse is set by default, so an AT328p will run at 1MHz, clearing this bit will result in 8 MHz.

When flashing you should never override any checks as this may damage/lock your chip.

I see that avrdudes states the supply voltage to be 0.3 volts which is far to low for communication. Any received bits would be low level and therefore any information read will be 0. ISPs usually provide a supply voltage which often can be selected by switches on the programmer. If you are sure your programmer is allright, check your circuit in general.

Btw, which ISP-model do you use?
Is your mcu assembled on a custom pcb (setup?)? If yes, do you have an arduino(like) board to verify this behaviour?

  [1]: http://www.engbedded.com/fusecalc/


message:
Problem with sending a POST request using the WiFiEsp library

I'm using an ESP8266 version 1 with the [WiFiEsp library](https://github.com/bportaluri/WiFiEsp) to connect to WiFi, and that works just fine.

I'm setting up the device using the same code as in the example [`WebClientRepeating`](https://github.com/bportaluri/WiFiEsp/blob/master/examples/WebClientRepeating/WebClientRepeating.ino).

I need to send a POST request instead of a GET request, but I can't get it to work as I want. If I create my POST request like this, it works just fine:

    if (client.connect(server, 3005)) {
      Serial.println("Connecting...");

      // send the HTTP POST request
      client.println("POST /open/peripherals HTTP/1.1");
      client.println("Host: 192.168.10.137:3005");
      client.println("User-Agent: Arduino/1.0");
      client.println("Connection: close");
      client.println();

      // note the time that the connection was made
      lastConnectionTime = millis();
    }
    else {
      // if you couldn't make a connection
      Serial.println("Connection failed");
    }

I get the response like this:

    [WiFiEsp] Connecting to 192.168.10.137
    Connecting...
    HTTP/1.1 200 OK
    X-Powered-By: Express
    Content-Type: application/json; charset=utf-8
    Content-Length: 19
    ETag: W/"13-jSAaqMh5E3R94/b2aONzvg"
    Date: Sun, 13 Nov 2016 10:20:58 GMT
    Connection: close

    {"temp":"Testdata"}

However, if I try to send some body data in the request it fails:

    if (client.connect(server, 3005)) {
      Serial.println("Connecting...");

      // send the HTTP POST request
      client.println("POST /open/peripherals HTTP/1.1");
      client.println("Host: 192.168.10.137:3005");
      client.println("User-Agent: Arduino/1.0");
      client.println("Connection: close");
      client.println("Content-Type: application/x-www-form-urlencoded");
      client.println("Content-Length: 16");
      client.println();
      client.println("temperature=22.7");

      // note the time that the connection was made
      lastConnectionTime = millis();
    }
    else {
      // if you couldn't make a connection
      Serial.println("Connection failed");
    }

Then the response from serial output is:

    [WiFiEsp] Connecting to 192.168.10.137
    Connecting...
    [WiFiEsp] >>> TIMEOUT >>>
    [WiFiEsp] Data packet send error (1)
    [WiFiEsp] Failed to write to socket 0
    [WiFiEsp] Disconnecting  0

However, the POST request including the body is received by the Web server just fine, but the response sent to the Arduino I can't read because it shows me an error instead of a proper response. From my webserver the response for the POST call that works and the POST call that fails is the same.

Does anyone knows why this fails when I add `Content-Type`, `Content-Length` and some body data?

Thanks in advance!

body:
Your problem is the content you are sending. While this format works well e. g. in Python libraries, this library seems to have a problem with it.
I solved it this way, when I happened to face this problem:

    //all your other code, including the remaining HTTP-Request
    String content = "{\"temperature\":\""+String(value)+"\"}";
    client.println("Content-Length: 16"); //insert, well, your content length
    client.println(content);


body:
One major problem seems to exists within the AT firmware of most ESP's. By default, the http headers it sends include **"Connection: close"**. However, the firmware seems to be buggy and unable to cope with the server closing the connection after it sends the response. Thus, in order to be able to get a response back from the target server you need to have **"Connection: keep-alive"** instead. This means you must explicitly add this to your header since **"Connection: close"** will be added if nothing else is said.
Also to make life easier for the WifiEsp library you could make sure your server returns an already well-known status string for the library like fx **"SEND OK"**… I'm doing this on a barometer logger that sends data to a MVC Web Api written in C# and it works perfect...

Here's my code:

    String PostHeader = "POST http://" + server + ":" + String(port) + "/api/values HTTP/1.1\r\n";
    PostHeader += "Connection: keep-alive\r\n";
    PostHeader += "Content-Type: application/json; charset=utf-8\r\n";
    PostHeader += "Host: " + server + ":" + String(port) + "\r\n";
    PostHeader += "Content-Length: " + String(jsonString.length()) + "\r\n\r\n";
    PostHeader += jsonString;
    Serial.println(PostHeader);
    client.connect(server.c_str(), port);
    client.println(PostHeader);
    client.stop();

And the full log looks like this:

    POST http://192.168.10.197:8001/api/values HTTP/1.1
    Connection: keep-alive
    Content-Type: application/json; charset=utf-8
    Host: 192.168.10.197:8001
    Content-Length: 144

    {"IpAddress":"192.168.10.230","MacAddress":"5c:cf:7f:d9:2f:c8","Temperature":34.6,"Pressure":1007,"Altitude":48.48573,"PressureAtSeaLevel":1007}

    [WiFiEsp] Connecting to 192.168.10.197
    [WiFiEsp] Disconnecting  3

In the file debug.h located in the WifiEsp library source code you could alter a define and get more output to your serial console. Open the file and change

    #define _ESPLOGLEVEL_ 3
to

    #define _ESPLOGLEVEL_ 4
Save the file and recompile/deploy your source code to your Arduino and you will get extensive information about all AT commands the library sends and what the library receives in return.


message:
Compiling sketch vi command line

Since I don't like the text editor of the Arduino IDE, I decided to write a python script that I can invoke from my text editor to compile and upload my source. I program the popular esp8266 chip. So far I found that there is a python builder [here][1]. This did not work for me. So is there any way to compile my source (e.g. main.ino) via a terminal command?

  [1]: https://github.com/esp8266/Arduino/blob/master/tools/build.py

body: In the Arduino IDE  preferences, select  external editor. Then you can write/ edit your sketches with any editor you choose. When you click compile or upload on the IDE toolbar, it will load your changes each time you compile.


body:
I found a [makefile][1] created to compile ESP8266 sketches. You can use this makefile from command line:

    cd /path/to/sketch
    make -f /path/to/makefile/makeEspArduino.mk upload

  [1]: https://github.com/plerup/makeEspArduino


message:
Atmega328P 8MHz External Clock

Has anyone experience configuring the Atmega328P to work with an 8Mhz external clock?

I want to reduce the power consumption of the device. If I just connect an 8MHz external quartz oscillator then simple programs like LED blink still work (With the time delays doubled), but if I try to use communication like UART, then I am unable to. So no programming new sketches.

body:
If you reduce the main clock speed by 50% then everything else is reduced by 50% as well.

The whole chip runs at half the speed. That includes things like the UART.

For example, the bootloader is set to run at 115200 baud on a 16MHz chip. If you run that same chip, with the same bootloader, at 8MHz then the bootloader will actually be running at half the baud rate, so 115200 / 2 = 57600 baud.

Unless you tell the IDE that your board is now running at 8MHz (by creating or using the correct board configuration information to set F_CPU to 8000000) then time runs at half the speed in your sketches too. So a delay of one second will last two seconds. Every two milliseconds a single millisecond will pass. And again baud rates will be wrong. If you use:

    Serial.begin(9600);

you will actually be running at half that speed (4800 baud) and so you would have to set your serial terminal program to that speed instead of the one you requested.

To to do things properly you will have to:

1. Replace the crystal
2. Edit, compile, and install a new version of the bootloader that runs at 8MHz
3. Create (or edit) a suitable board definition (in boards.txt) to compile sketches that expect to run at 8MHz.


body:
Firstly, you can buy 8MHz Atmega328P Pro-Minis from China. They are cheap and run at 3.3V. Look at eBay.

If you want to reduce the power consumption of Arduino boards, you have three primary attack vectors:

- Removing the power LED
- Removing the voltage regulator
- A Low-Power library

All of these have different impacts on the power consumption of your respective board.

An extensive comparison can be found [here in this blog-post](https://andreasrohner.at/posts/Electronics/How-to-modify-an-Arduino-Pro-Mini-clone-for-low-power-consumption/).


body:
The easiest way is to use the settings:

**Tools > Board > Arduino Pro or Pro Mini**

**Tools > Processor > ATmega328 (3.3V, 8MHz)**

The problem with that is the Pro Mini bootloader is 2kB and has a [bug](https://github.com/arduino/Arduino/issues/4492) that causes an endless reset loop if you do a watchdog reset.

The better option is to use https://github.com/MCUdude/MiniCore, which includes the Optiboot bootloader, saving 1.5kB of flash memory vs using the Pro Mini bootloader and doesn't have the watchdog bug.

After selecting the correct configuration for your hardware from the **Tools** menu, do **Tools > Burn Bootloader**, which will set the fuses on your ATmega328P and upload the correct bootloader.


message:
Debugging library - Error- expected unqualified id before '.' token

I'm writing a library for my project, which interfaces sensors used and structures them in different systems.

But I'm such a noob at C++. The compiler is throwing this error:

    libraries/cec-core/cec-core.cpp: In member function 'void Habitaculo::Update()':
    libraries/cec-core/cec-core.cpp:15:8: error: expected unqualified-id before '.' token
    _Sluz.Update();

This is the header of that class:

    class Habitaculo
    {
     public:
     Habitaculo(int refrate, int luzpin, int dhtpin);
     //Values from Indoor Sensors
     int temp;
     int hum;
     int luz;
     //Update Methods
     void Update();  //Updates sensors value
     void UpdateReg(); //writes to SD or enabled output method
     private:
     //Clock Managing
     long _PreviousMillis;
     unsigned long _CurrentMillis;
     int _RefreshRate;
     //Sensor instances
     class _Sluz;
     class _SDHT;
    };

This are the member functions affected:

    Habitaculo::Habitaculo(int refrate, int luzpin, int dhtpin){
     //Clock management
     _RefreshRate = refrate;
     _PreviousMillis = 0;
     //Systems to initialize
     LDR _Sluz(luzpin);   //analogpin
     DHT11 _SDHT(dhtpin); //buspin
    }
    void Habitaculo::Update(){
     _CurrentMillis = millis();
     if (_CurrentMillis-_PreviousMillis > _RefreshRate){
      _Sluz.Update();  //unqualified-id before '.' token
      _SDHT.Update();  //unqualified-id before '.' token
      temp = _SDHT.temp;  //expected primary-expression before '.'
      hum = _SDHT.hum;  //expected primary-expression before '.'
      luz = _Sluz.value;  //expected primary-expression before '.'
      _PreviousMillis = _CurrentMillis;
     }
    }

The error is thrown in every step of the `Update` method. But I can copy that piece of code right in the `Habitaculo` constructor and it works well. So I assume I'm missing something basic about language syntax, because I'm really new to all this scene.

Every class involved in this (LDR, DHT11) works fine. It's when I try to put all this together into a new class - inside an unified Update method - that everything crashes.

body:
    class _Sluz;
    class _SDHT;

You're forward declared two classes but I see nothing about what those classes are. You then to and use those class declarations as if they were class instances.

I think you are lacking a bit of basic syntax knowledge there. You may have meant:

    Sluz _Sluz;
    SDHT _SDHT;

Though not knowing what those classes are meant to be or how they are even defined I cannot know really what you think you're meaning.


body:
From what I guess in your code, here is how you want your class declared:

    class Habitaculo
    {
        public:
        Habitaculo(int refrate, int luzpin, int dhtpin);
        //Values from Indoor Sensors
        int temp;
        int hum;
        int luz;
        //Update Methods
        void Update();      //Updates sensors value
        void UpdateReg();   //writes to SD or enabled output method
        private:
        //Clock Managing
        long _PreviousMillis;
        unsigned long _CurrentMillis;
        int _RefreshRate;
        //Sensor instances
        LDR _Sluz;
        DHT11 _SDHT;
    };

Of course, in your header file, you will have to `#include` the proper header files for `DHT11` and `LDR` classes.

Then you will need to change your constructor as follows:

    Habitaculo::Habitaculo(int refrate, int luzpin, int dhtpin)
    :_Sluz(luzpin), _SDHT(dhtpin)
    {
        //Clock management
        _RefreshRate = refrate;
        _PreviousMillis = 0;
    }

Note the `:_Sluz(luzpin), _SDHT(dhtpin)` line before the constructor body, in C++, this is how members of your class that are instances of another class must be instantiated.

Actually, you could even empty the whole cosntructor body by also initializing `_RefreshRate` and `_PreviousMillis` in the same manner:

    Habitaculo::Habitaculo(int refrate, int luzpin, int dhtpin)
    :_PreviousMillis(0), _RefreshRate(refrate), _Sluz(luzpin), _SDHT(dhtpin) {}

which is a bit more idiomatic C++.


message:
Read signal from co-ax cable with ADC

I have an Arduino Uno and I'd like to read a signal from a co-ax cable with it. The cable carries 12VDC (power for other components) along with a signal (of about 1 Ghz frequency). How do I go about recording this signal with my Uno? I'm new to this field so I don't know the full capabilities of the ADC. Also, the Uno can't handle >5 VDC, so what should I do to make the signal readable?

body:
It's not possible. To sample a 1GHz signal you need to sample at least 2 billion times per second (a sample rate of 2Gsps). You can maybe get a couple of hundred KILO samples (thousand) per second on an Arduino.

Also the 1GHz signal itself is of no interest to you. What is of interest is what is *modulated* on the 1GHz signal.

What is normally done is:

1. Down-mix (filter) the carrier signal to an IF (Intermediate Frequency) usually in the order of a few kilohertz
2. Demodulate the signal using whatever modulation scheme was used to encode it.
3. Extract the encoded information from the demodulated signal.

To do that you'd need

1. the precise carrier frequency (1GHz is not the same as 1.029GHz)
2. the modulation scheme used (there's loads to choose from)
3. knowledge about any data formats and encodings used in the signal

As well as the hardware to do all that.

So no, you're never going to come even anywhere close with an Uno. You need specialised RF hardware just to prepare the signal for working with.


message:
Atmega32u4 external 8MHz clock

Does anyone know how to configure the Atmega32u4 to run using an external 8MHz oscillator ?

I needs to still be responsive to the Arduino IDE

Thanks

body:
See §28.2 in [Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf](http://www.atmel.com/Images/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf), which explains usage of various fuse bits.

Also see [engbedded.com/fusecalc](http://www.engbedded.com/fusecalc/), which lets you easily figure out fuse settings.  Fusecalc also tells you the strings to use as part of avrdude command strings.

Once you know the fuse settings, send them to your device via a command like

    avrdude -p m32u4 -c usbasp -u -U lfuse:w:0xEF:m -U hfuse:w:0xD5:m -U efuse:w:0x07:m

or like

    avrdude -p m32u4 -P $port -c arduino -u -U lfuse:w:0xEF:m -U hfuse:w:0xD5:m -U efuse:w:0x07:m

where `$port` represents a port name like `/dev/ttyUSB0`.

Note, it makes sense to read the fuses first, and put the readings into Fusecalc to see what they correspond to.  You can read the fuses via a command like

    avrdude -p m32u4 -P $port -c arduino -U hfuse:r:-:i


message:
Which sensor i can use to transmit some values from Arduino Uno to phone using bluetooth?

I want to transmit some values from arduino uno to my phone using bluetooth.
Which sensor i can use?I want to see some options because i'm a little bit uncertain.Thanks to all which can give me an advice !  :)

body:
It's not a sensor, its a module. A quite popular module is the [HC-05][1]. It's a very simple to use module with a lot of support by the community. Cheap and great for projects.

  [1]: https://www.amazon.com/Wireless-Bluetooth-Serial-Transceiver-Module/dp/B00INWZRNC/ref=sr_1_1?ie=UTF8&qid=1479068592&sr=8-1&keywords=hc05


message:
Can anybody advise what type of connector this is?

I recently purchased an LiPower shield from SparkFun.

I also bought a Lithium Polymer battery off eBay and it appears to have a JST male connector (i could be wrong)?

I expected it to slot right into the board however the fit is slightly too large. Can any advise me of the name of the connector for the board battery supply, or have I mistaken the battery output connector?

Please see pictures below, thanks!

[![Iso view][2]][2]

[![Battery connection lead][4]][4]

  [2]: https://i.stack.imgur.com/aP0P7.jpg
  [4]: https://i.stack.imgur.com/MotH2.jpg

body: The board uses a JST PH connector, with 2.0mm spacing. The battery has a JST XH connector, with 2.5mm spacing. You will need to replace the battery connector or put a XH socket on the board.


body:
That is generically a "JST" connector.  Named from the company that originally designed and made them.  But I believe there are many "second-source" (and likely counterfeit) sources of similar or identical connectors.

They are avaiable in a variety of mechanical configurations (horizontal, vertical, PC board mount, wire-end, etc. etc.)  And there are several variations with different pin sizes and pin-pitch (distance between the pins). They all look very similar, especially in photographs, but as you demonstrate, the different pitch families are NOT inter-connectable.

If you had bought the battery from SparkFun, it is quite likely that it would have the mating connector.  But since there is no standardization here, you will end up dealing with these kinds of mismatches.


body:
header on the board IS jst XHA connector,but wirinhg harness is XH,[![enter image description here][1]][1]

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


message:
IRRemote send and receive same Arduino

I am an Arduino (and C/C++) newbie so apologies if I am missing something obvious.

I am using [IRremote (github link)][1] as my IR library.

I can get the simple send and receive demos working  individually.

However, I cannot get send AND receive working in the same Arduino at the same time.

I do not wish to do something like the "IRrecord" example but what I do want to do is have Arduino send and receive at all times and then trigger alarm/LED once the "beam" is broken.

I am using a TSOP 22 series as my IR receiver. I have tried to use protothreads but no luck. Any tips appreciated.

My current code snippet:

    #include <IRremote.h>

    int RECV_PIN = 11;

    IRrecv irrecv(RECV_PIN);
    IRsend irsend;

    decode_results results;

    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
      Serial.println("IR Receiver... Started");
    }

    void loop() {
      //single threaded nature seems to break below

      // i want to start receiver here
      if (irrecv.decode(&results)) {
        Serial.println(results.value, HEX);
        irrecv.resume(); // Receive the next value
      }
      //delay(5000);

      //trying to send here
      for (int i = 0; i < 3; i++) {
        irsend.sendSony(0xa90, 12);
        Serial.println("Sent Sony......");
        delay(40);
      }
      //delay(5000); //5 second delay between each signal burst
    }

  [1]: https://github.com/z3t0/Arduino-IRremote /"IRremote"

body:
I **THINK** the problem is that the Arduino takes some time (very minimal) to send the signal, but when it comes to receive it, the signal has already dissipated though your room.

---

>send and receive at all times and then trigger alarm/LED once the "beam" is broken.

Use a laser, it's cheaper, more acurate, and more "James Bond'ish'" :)


body:
I managed to do this using solution from [Ken Sheriff's Blog][1]. Ken provides a simple example and documents it perfectly. Due to the nature of my IR Receiver (rejecting continuous beam) I used the sample code provided by Stephane Deniaud in the comments section. Thanks to both...

    #include <IRremote.h>

    #define PIN_DETECT 2
    IRsend irsend;

    void setup()
    {
        pinMode(PIN_DETECT, INPUT);

        Serial.begin(115200);
        Serial.println("READY");

        attachInterrupt(digitalPinToInterrupt(PIN_DETECT), checkIRBeamBreak, RISING);

        // Note : the IR emitter is on PIN #3
        irsend.enableIROut(38);
        IREmitterOn();
    }

    // Use this function instead of delay() as delay() does not work in interrupt callbacks
    void pause(int ms) {
        // We need a loop as the largest value for delayMicroseconds that will produce an accurate delay is 16383
        for (int i = 0; i < ms; i++) {
            delayMicroseconds(1000);
        }
    }

    void IREmitterOff() {
        irsend.space(0);
        pause(60); // 60 ms is OK for my TSOP but should be tuned
    }

    void IREmitterOn() {
        irsend.mark(0);
        pause(10);
    }

    void switchOffOnIREmitter() {
        IREmitterOff();
        IREmitterOn();
    }

    void checkIRBeamBreak() {
        int val = digitalRead(PIN_DETECT);
        // LOW : no beam break
        // HIGH : beam break
        if (val == LOW)
            return;

        detachInterrupt(digitalPinToInterrupt(PIN_DETECT));
        switchOffOnIREmitter();
        if (digitalRead(PIN_DETECT) == HIGH) {
            Serial.println("IR BEAM BREAK !!!!");
        }
        attachInterrupt(digitalPinToInterrupt(PIN_DETECT), checkIRBeamBreak, RISING);
    }

    void loop() {

    }

  [1]: http://www.righto.com/2010/03/detecting-ir-beam-break-with-arduino-ir.html
  [2]: http://Stephane Deniaud