body:
The MCP42100 does not appear to be an appropriate digital pot for this application.

Without a schematic of the motor controller it is hard to tell, but a good guess would be that the digital pot is seeing voltages higher than the supply voltage you are feeding it, and higher than the **maximum supply voltage** of the digital pot (5.5V; 7.0V abs max). I don't see a voltage regulator on the motor controller board, nor would one be necessary for a low-end design. Probably just a PWM using a 555, as you say.

To make this work you probably need a different type of digital pot - one that can accept logic level inputs and has a higher supply voltage (12V + some margin). You also typically actually have to feed it the higher supply voltage (and be careful that nothing shorts and ruins the micro board).

Otherwise the input protection networks on the digital pot conducts more current than you would expect.


sender: user

message:
Arduino Due for camera control?

Could one use the Arduino Due to control camera module like OV5642 and send the data to spi device? My project is to capture image with OV5642 and then to send the image data(RGB565) to other device via spi. For this STM32 must be enough, but I'd be happy if I can use the arduino IDE. Because it is much easier to program.

Could you please let me know, if you can use the Due for this task?

sender: assistant

body:
You are still not giving the full picture, pun intended.

I'll give you an example of what sort of info is missing.

For example, what's the frame rate? What's the color depth of the sensor?
If you look at the SAM3x TRM, it says that the SPI is clocked at max 65MHz.

So, the (simplified) math would say:

24bit/pixel * 5Mpixel / 65MHz =  1.846 seconds

And that doesn't even account for acquisition time, so if you do not have fully working DMA on both sides, it's probably even worse.
And it will be worse, because you cannot stuff in RAM in one go the entire image.

But maybe that's good enough for you, however it's not possible to say because of the missing info.


message:
Doesn't work radio transmission from Arduino Uno to Arduino Pro Micro

I have Arduino Uno, Arduino Pro Micro, XY-MK-5V and FS1000A.
I need transmit data from Pro Micro to Uno.

Transmitter:

        #include <VirtualWire.h>

        void setup() {

          Serial.begin(9600);

          vw_setup(2000);
          vw_set_tx_pin(14);
        }

        void loop() {

          send("Test message!");
          delay(2000);
        }

        void send (char *message)
        {
          vw_send((uint8_t *)message, strlen(message));
          vw_wait_tx();
        }

Receiver:

    #include <VirtualWire.h>

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

        vw_set_rx_pin(12);
        vw_setup(2000);

        vw_rx_start();
    }

    void loop()
    {
        uint8_t buf[VW_MAX_MESSAGE_LEN];
        uint8_t buflen = VW_MAX_MESSAGE_LEN;

        if(vw_get_message(buf, &buflen))
        {
            for(int i = 0; i < buflen; i++)
            {
                Serial.print(buf[i]);
            }

            Serial.println();
        }
    }

I dont know why it's doesn't works. When I changed Uno with Micro and Micro with Uno, it's worked.

But I need: Micro + transmitter FS1000A & Uno + receiver XY-MK-5V.

Please help me. I'm using [this Pro Micro][1].

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

body: Thanks for your answers. I solved this problem, my Chinese copy has problems with power.


message:
LiPo battery charger

Is it possible to build a battery charger with just an arduino UNO board (and perharps some passive components)?. It's a 3.7V 550 mAh LiPo Battery. I understand I need to monitor the charge and the current flowing into the battery to properly (as in *safely*) charge it.

body: Yes, it is. AVR146 describes how to charge a battery using a ATmega16U4/32U4 (Leonardo), but there is nothing specific to that chip regarding the actual charging, and the serial communication can easily enough be ported to the ATmega328P.


body:
I'll assume that you are trying to charge from a 5V "USB" source.

If you only want to use a UNO + passive components then the hardware intensive method of application note [AVR146: Lithium-Ion Battery Charging via USB with ATmega16/32U4](http://www.atmel.com/Images/doc7801.pdf) which Ignacio suggests does not meet your need. This is a capable charger but the UNO would not be the major part of it.

**"Normal" charger**

The use of any of the available LiIon charger ICs is an easy and low cost way of adding a charger. These ICs and all related components can cost as little as a few dollars. But ...

**UNO + one resistor very low current charger:**

If using a UNO with no external active parts the current drive rating of the UNO pins limits the maximum current able to be provided. If you **really** want to meet your specification you can achieve a few ten's of mA charge using with a UNO and a few resistors (possibly just one.)

**Super simple good capability charger**

But, a good compromise can be achieved using a UNO (or similar) + one transistor plus a few resistors and capacitors. This can achieve all the usual basic capabilities

 - Low current "trickle up" for very low voltage cells

 - Constant current charge until Vmax is reached

 - Constant voltage charge until I_cutoff is reached.

 - Terminate and stay active until recharge needed.

I will only outline the basic system here. More can be said as and if required.
The main point of note s that in its simplest form the charger uses a linear charging mode so a modest amount of heat needs to be dissipated in the control transistor. Max power dissipation for a A max charge rate would be 2 Watts when the battery was at 3V and full charge was wanted from 5V in.
Power dissipation = (Vin - Vbattery) x Icharge
Worst case here = (5V - 3V) x 1A = 2 watts.
A buck converter could be used (UNO controlled) if desired.

A transistor Q1 connects Vin to battery

Q1 can be PWM controlled by the Uno.

Battery current is monitored by a small resistor Rcur from B- to ground (or in B+ lead)

Vbattery is monitored with an ADC channel (ADC1 or ADC_V)

Current is measured by measuring voltage across Rcur with an ADC (ADC2 or ADC_I).

If Rcur is from B- to ground then V Rcur = V ADC2. If Rcur is in B+ lead V across Icur = V_ADC2 - V_ADC1.

Q1 on state can be varied by PWM from Uno to control battery current. PWM voltage is smoothed by an RC low pass filter to allow smooth DC control.

**Charging:**

The following steps constitute the standard LiIon charging algorithm implemented by most charger ICs. Variations can be made.

 - If Vbat < 3V set Ichg to Itrickle by PWMing Q1 and reading battery current.

 While 3V <= Vbat <= 4.2V chg at Imax for battery.

 When Vbattery = V-max = 4.2V adjust Ichg with PWM to hold Vbat at 4.2V until   Ichg falls to desired fraction of Imax.

 Turn off chg voltage fully and monitor Vbat to restart charge at Vbat = Vrestart - maybe 4.0V or as desired.


message:
Multi-threaded Robot

I am working on a small robot project, the code which i made for this has a sequential execution in a single thread. There are a lot of Delay() function needed. Due to which the accuracy is extremely bad.
i want to to implement the movements in one thread and the sensor detection in another thread.

    #define M1 3
    #define M2 5
    #define M3 6
    #define M4 9
    #define L_trig 2
    #define L_echo 4
    #define R_trig 7
    #define R_echo 8
    #define servo 10
    #define solenoid_pin 11
    #define LDR_pin1 12
    #define LDR_pin2 13
    void setup()
    {
    // Motors Initilization
    pinMode(M1,OUTPUT);
    pinMode(M2,OUTPUT);
    pinMode(M3,OUTPUT);
    pinMode(M4,OUTPUT);
    // Ultrasonic  Initilization
    pinMode(L_trig, OUTPUT);
    pinMode(L_echo, INPUT);
    pinMode(R_trig, OUTPUT);
    pinMode(R_echo, INPUT);
    S.attach(servo);
    }

    void loop()
    {

     Runmotor(M1);
     Runmotor(M2);
     Runmotor(M3);
     Runmotor(M4);
     servo_rotation();
     Ultrasonic_value(L_trig,L_echo);
     Ultrasonic_value(R_trig,R_echo);

     if(Ultrasonic_value(L_trig,L_echo)<5 || Ultrasonic_value(R_trig,R_echo)<5)

       {
         turnLeft();
         //Serial.println("Working");
       }

    }

    // Run Motor
    void Runmotor(int which)
    {
      for(int i=0;i<1023;i++)
      {
     analogWrite(which, i);
      }
    }
    // Stop Motor
    void stopmotor(int which)
    {
      digitalWrite(which,LOW);
    }
    // To turn the robot left side
    void turnLeft()
    {
      stopmotor(M2);
      stopmotor(M3);
      delay(5000);
      Runmotor(M2);
      Runmotor(M3);
    }
    // To turn the robot Rightside
    void turnRight()
    {
      stopmotor(M1);
      stopmotor(M4);
      delay(5000);
      Runmotor(M1);
      Runmotor(M4);
    }
    // Servo Rotation
    void servo_rotation()
    {
     for(angle=0;angle<=180;angle++)
    {
     S.write(angle);
     if(angle==90)
     {
       delay(2000);
     }
    }
    delay(2000);
    for(angle=180;angle>=0;angle--)
    {
      S.write(angle);
      Serial.println(angle);
      if(angle==90)
     {
       delay(2000);
     }
    }
     delay(2000);
    }

    // Calculation of distance
    long Ultrasonic_value(int which_trig,int which_echo)
    {
      long duration, distance;
      digitalWrite(which_trig, LOW);
      delayMicroseconds(2);
      digitalWrite(which_trig, HIGH);
      delayMicroseconds(10);
      digitalWrite(which_trig, LOW);
      duration = pulseIn(which_echo, HIGH);
      // distance = duration*343*100/2;
      distance = (duration/2) / 29.1;
      delay(100);
      return distance;
    }

    void Solenoid_Fire()
    {
      digitalWrite(solenoid_pin,LOW);
    }

    void Solenoid_Reload()
    {
      digitalWrite(solenoid_pin,HIGH);
    }
    /*
    bool LDR_reading(int LDR_pin1 , int LDR_pin2)
    {

    }
    */

Please help me. I want to implement this code in a Multi-thread fashion. Thanks in Advance

body:
I am looking at [this][1], for a similar project.
It seems light and simple enough that you could have a quick trial.
Converting those functions to threads shouldn't be too time consuming.

Once every activity is implemented as thread, you could use semaphores to hold them blocked and then create a state machine which controls them through the semaphores.

  [1]: http://file:///home/igor/dev/eclipse-workspace/NilRTOS-Arduino/html/examples.html


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

I think this needs a major rework. First here:

      for(int i=0;i<1023;i++)
      {
      analogWrite(which, i);
      }

The maximum you can analogWrite is 255, so change 1023 to 255.

Next, get rid of the delay() calls.

---

Let's look at `turnLeft` :

    // To turn the robot left side
    void turnLeft()
    {
      stopmotor(M2);
      stopmotor(M3);
      delay(5000);
      Runmotor(M2);
      Runmotor(M3);
    }

Why stop the motor and then start it again? Do you mean:

    // To turn the robot left side
    void turnLeft()
    {
      stopmotor(M1);
      stopmotor(M4);
      delay(5000);
      Runmotor(M2);
      Runmotor(M3);
    }

I don't see what the delay achieves anyway. Get rid of it:

    // To turn the robot left side
    void turnLeft()
    {
      stopmotor(M1);
      stopmotor(M4);
      Runmotor(M2);
      Runmotor(M3);
    }

In fact, I don't see what any of the delay() calls achieve. Try removing them.

---

See my post [How to do multiple things at once ... like cook bacon and eggs](http://www.gammon.com.au/blink) for tips on doing multiple things without using delay().

---

Also consider using arrays. Instead of M1, M2, M3, M4, make an array:

    const int NUMBER_OF_MOTORS = 4;
    const int motorPins [NUMBER_OF_MOTORS] = { 3, 4, 6, 9 };

Now it is easier to set them all to output:

    // Motors Initilization

    for (int i = 0; i < NUMBER_OF_MOTORS; i++)
      pinMode (motorPins [i], OUTPUT);

It is also easier to start or stop all of them:

    for (int i = 0; i < NUMBER_OF_MOTORS; i++)
      stopmotor (i);

Where stopmotor is now:

    // Stop Motor
    void stopmotor(int which)
    {
      digitalWrite(motorPins [which],LOW);
    }

---

*(Edited to add)*

I also don't see what this achieves:

    void Runmotor(int which)
    {
      for(int i=0;i<1023;i++)
      {
     analogWrite(which, i);
      }
    }

Apart from the fact that you can't go up to 1023, if you stop at 255, the time taken to do all those analogWrite is just over 2 ms. Why bother? Why not just do this:

    void Runmotor(int which)
    {
      digitalWrite (which, HIGH);
    }


body:
You may want to take a look at LMX by David Anderson [A Light-Weight Multi-Tasking Executive][1].

He has a very good set of videos on the code that he did for [Dallas Personal Robotics Group (DPRG)][2].

The specific videos for LMX are:

 - [David Anderson on Robotics Software - part 1][3]
 - [David Anderson on Robotics Software - part 2][4]

  [1]: http://www.geology.smu.edu/dpa-www/robo/LMX
  [2]: https://www.youtube.com/channel/UCsGzeeBTraAts7lMQdfhqtA
  [3]: https://www.youtube.com/watch?v=nRaosdrDrdA
  [4]: https://www.youtube.com/watch?v=Jnrg4WAtxGQ


body:
You could use a [scheduler][1] and simply start tasks with:

    #include <Scheduler.h>
    ...
    void setup()
    {
      ...
      Scheduler.start(servoSetup, servoLoop);
      Scheduler.start(sensorSetup, sensorLoop);
      ...
    }

    void servoSetup()
    {
      S.attach(servo);
    }

    void servoLoop()
    {
      int angle;
      for(angle = 0;angle <= 180; angle++) {
        S.write(angle);
        if (angle == 90) {
          delay(2000);
        }
      }
      delay(2000);
      ...
    }
    ...

The tasks must call *yield()* or *delay()* to context switch. The *taskSetup* function is called first and once by the task. The *taskLoop* function is repeatedly called by the task. This can be viewed as running an additional sketch.

For more details see the [example sketches][2].

  [1]: https://github.com/mikaelpatel/Arduino-Scheduler
  [2]: https://github.com/mikaelpatel/Arduino-Scheduler/tree/master/examples


body:
You could also give my ThreadHandler library a try

https://bitbucket.org/adamb3_14/threadhandler/src/master/

It uses an interrupting scheduler to allow context switching without relaying on yield() or delay().

I created the library because I needed three threads and I needed two of them to run at a precise time no matter what the others were doing. The first thread handled serial communication. The second was running a Kalman filter using float matrix multiplication with the Eigen library. And the third was a fast current control loop thread which had to be able to interrupt the matrix calculations.

How it works
------------
Each cyclic thread has a priority and a period. If a thread, with higher priority than the current executing thread, reaches its next execution time the scheduler will pause the current thread and switch to the higher priority one. Once the high priority thread completes its execution the scheduler switches back to the previous thread.

### Scheduling rules

The scheduling scheme of the ThreadHandler library is as follows:

1. Highest priority first.
2. If the priority is the same then the thread with the earliest deadline is executed first.
3. If two threads have the same deadline then the first created thread will execute first.
4. A thread can only be interrupted by threads with higher priority.
5. Once a thread is executing it will block execution for all threads with lower priority until the run function returns.
6. The loop function has priority -128 compared to ThreadHandler threads.

How to use
----------
Threads can be created via c++ inheritance

```c++
class MyThread : public Thread
{
public:
    MyThread() : Thread(priority, period, offset){}

    virtual ~MyThread(){}

    virtual void run()
    {
        //code to run
    }
};

MyThread* threadObj = new MyThread();
```
Or via createThread and a lambda function
```c++
Thread* myThread = createThread(priority, period, offset,
    []()
    {
        //code to run
    });
```
Thread objects automatically connect to the ThreadHandler when they are created.

To start execution of created thread objects call:
```c++
ThreadHandler::getInstance()->enableThreadExecution();
```


message:
I have an 'error' with my code

The following code gives me an error:

    // RFIDunio.h is from http://learn.robotgeek.com/getting-started-guides/39-robot-kits/151-rfiduino.html
    #include <RFIDuino.h>

    byte    keyTag[5] = {0,0,0,0,0};
    boolean noise = false;
    byte    masterTag[5] = {37,0,0,127,24};
    byte    tagData[5];
    byte    tagDatas[5];
    boolean verifyKey = false;
    boolean mastaKey = false;

    void setup()
    {
      Serial.begin(9600);
      Serial.println("Welcome to my system!");
    }

    RFIDuino myRFIDuino(1.2);

    void loop()
    {
      if(myRFIDunio.scanForTag(tagData == true)
      {
        verifyKey = myRFIDunio.compareTagData(tagData, keyTag);
        mastaKey = myRFIDunio.compareTagData(tagData, masterTag);
        if(verifyKey == true)
        {
          digitalWrite(myRFIDunio.led2,HIGH);
          if(noise == true)
          {
            myRFIDunio.successSound();
          }
          Serial.println("Correct Key!" + " UID = " + tagData[5]);
          delay(250);
          digitalWrite(myRFIDunio.led2,LOW);
        }
        else if(mastaKey == true)
        {
          Serial.println("Programming mode activated!");
          delay(500);
          Serial.println("Please scan a card.");
          myRFIDunio.scanForTag(tagDatas == true)
          delay(1000);
          tagDatas[5] = tagData[5];
          Serial.println("Card has been programmed!");
        }
        else
        {
          digitalWrite(myRFIDuno.led1,HIGH);
          if(noise == true)
             {
                myRFIDuino.errorSound();
             }
          Serial.println("Wrong! " + "UID = " + tagData[5]);
          delay(250);
          digitalWrite(myRFIDunio.led1,LOW);
        }
      }

The error is:

    C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106 -IC:\Program Files (x86)\Arduino\hardware\arduino\cores\arduino -IC:\Program Files (x86)\Arduino\hardware\arduino\variants\standard -IC:\Users\*****\Documents\Arduino\libraries\RFIDuino C:\Users\*****\AppData\Local\Temp\build6101268048586666869.tmp\sketch_jul24a.cpp -o C:\Users\*****\AppData\Local\Temp\build6101268048586666869.tmp\sketch_jul24a.cpp.o
    sketch_jul24a.ino: In function 'void loop()':
    sketch_jul24a:20: error: 'myRFIDunio' was not declared in this scope
    sketch_jul24a:20: error: ISO C++ forbids comparison between pointer and integer
    sketch_jul24a:21: error: expected `)' before '{' token
    sketch_jul24a:55: error: expected statement at end of input
    sketch_jul24a:55: error: expected `}' at end of input

body: C++ is spelling-sensitive; identifiers need to be spelled the same way each time they are used.


body:
    if(myRFIDunio.scanForTag(tagData == true)

I think you have a bracket missing there.

    if(myRFIDunio.scanForTag(tagData) == true)

Also I think you have spelled myRFIDuino wrong.  ni <-> in

    if(myRFIDuino.scanForTag(tagData) == true)

And you need a } at the end of your program.

As well, you can't add strings together like you are doing in your Serial prints.  Break them up into multiple prints:

    Serial.print("Correct Key!  UID = ");
    Serial.println(tagData[5]);

You also have other bits that make no sense at all, such as:

    myRFIDuino.scanForTag(tagDatas == true)

One further thing - that library will never work on Linux, or on MAC OS/X where case sensitivity is enabled on the filesystem.  The .cpp file is including a badly named .h file.


message:
Is the SIM900 3G? Or is the SIM900A able to connect to 3G?

I would like to state that I am not familiar with the whole cellular connection thing. But I was wondering if the SIM900/or/SIM900A is 3G and will work with [PTel Mobile][1].

I need this Arduino to be able to travel and needs to connect to every PTel's tower. Will I be able to connect to 3G or only the 2G and the 1G networks?

  [1]: http://www.ptel.com

body:
First of all if you are in USA you cannot use SIM 900A since it supports only Dual frequency bands.(900,1800 MHz)it supports only Asian region countries.

According to [Wikipedia, PTel Mobile][1] supports only GSM 850/1900 frequencies.
so SIM 900 supports( 850,900,1800,1900 MHz ) you must use SIM900

Considering about the speed you cannot obtain 3g, 4g speed since GSM Shield(SIM900) provides maximum of [GPRS class 10: max. 85.6 kbps (downlink)][2] so,

It will able to connect but cannot get such speed in 3g and 4g.

  [1]: https://en.wikipedia.org/wiki/List_of_United_States_mobile_virtual_network_operators
  [2]: http://www.simcom.eu/index.php?m=termekek&prime=1&sub=40&id=0000000147&page=1


body: It will not be able to connect to a 3G or 4G network. There has to be a 2G network / support and that support is getting less.


message:
Which bluetooth module should I buy?

I am doing a wireless rover using arduino mega 2560 that can be controlled by a smartphone and a PC. Which bluetooth module would fit me? Again I want to control it both by my Laptop(Built-in Bluetooth) and my smartphone. Thanks in advance.

body:
A little late but in case someone like me ran into this:

**HC-05** seems to be the DIY choice. Can work in slave or master mode and works with Android but not iOS.

**HC-06** is the same as HC-05 except that you can only use it in slave mode.

**HM-10** seems to be the option for iOS users.


message:
reversing a micro motor by reversing two pins - one Source and one sink?

can I use this configuration of two pins to run a micro motor ,so I be able to change the polarity of the current (by the code itself-one time out pin1-high out pin2 - low , while next time one low two high!) every time I would like ?(and by changing the polarity OF THE CURRENT to the motor it will revers it) !

Thank's !

body:
    **Required:**

    Drive micro-motor directly from two processor pins.

     - Pin 1 high / Pin 2 low for one direction.
     - Pin 1 low / Pin 2 high for other direction.**

This is not a very good idea if it can be avoided but yes, you can operate a motor that way,  providing that the motor current is low enough to meet the pin current ratings. It would have to be a very small motor to achieve this.

Take careful note of the current versus voltage drive capabilities of the processor concerned. While a pin may be shown as being able to source or sing 5 or 10 or 20 mA, this is accompanied by a voltage rise for a sink and voltage drop for a source, so at higher currents lower voltages will be available.

A danger is that motor noise may affect the processor.
Placing a small capacitor across the motor will help, and driving the motor through a small resistor from each pin will also help keep noise away from the processor. But depending on the motor used this may not be enough.
The series resistors will drop some voltage and so are limited in maximum allowable size.
The parallel capacitor will slow the direction transition - the larger the capacitor the slower the change.

Using drivers or "buffers" which are higher current rated would allow a larger motor to be driven and would help isolate the processor from the motor noise.

Ask further if any idea here sounds useful.

__________

Added: Had a discussion with Gerben (below).
I'd avoided mentioning "catch diodes" but this is an add on that can help.
From each pin add a small Schottky diode* from pin to Vcc and pin to ground so that all 4 diodes are reverse biased.
(ie Cathode goes to Vcc = line on diode on upper diodes.
Anode goes to ground on "lower" diodes. )
These diodes are usually non conducting. If motor operation or switching causes spikes that rise above Vcc or below ground these diodes will conduct (slightly) before  the internal protection diodes do. This is not ideal but can help.
As Gerben notes, when reversing the motor, driving BOTH pins to ground until the motor has stopped and then applying reversing polarity can help. Also driving both high will do the same. There are pros and cons with either method.

* eg [**BAT54** surface mount](http://www.diodes.com/datasheets/ds11005.pdf),   [**BAT48 through hole**](http://www.st.com/web/en/resource/technical/document/datasheet/CD00000768.pdf), [1N581x](http://www.digikey.com/product-search/en?k=schottky+diode+1n581&mnonly=0&newproducts=0&ColumnSort=1000011&page=1&stock=0&pbfree=0&rohs=0&quantity=1&ptm=0&fid=0&pageSize=25)  or similar.


message:
Measuring KWh connecting to the mains

I need to measure KWh of the mains, connecting something like a sensor to the mains and reading its value into analog. I already know to measure KWh from a KWh meter but I need to make my own.

body:
If i understand your question correctly, what you want to do is measure the current consumed from the mains by whatever load is connected to it (Fan, AC, computer etc).

What you need is basically a current sensor, have a look at https://www.sparkfun.com/products/8883 and https://www.sparkfun.com/products/11005

**Please understand that you are playing with the mains and unless you take the required precautions, you can get seriously injured**


message:
Arduino IDE on Fedora

I'm using [Fedora_21_MATE.img][1] on a Raspberry Pi. Installing the Arduino IDE 1.0.6 using these commands, taken from [Arduino On Pi][2]. Those instructions are for Raspbian, I assume, so changing for Fedora, `apt-get` to `yum`:

    sudo yum install arduino

One waits and `arduino` installs. One can then run the Arduino IDE from the Fedora GUI menu, and it loads - after moaning about the user has to be a member of the `dialout` and `lock` groups. This is easily resolved by adding the user to the required groups, using the control panel.

However, trying to compile anything, i.e. `blink`, in the IDE, gives me the following error:

    avr-g++: error trying to exec cc1plus: execvp: No such file or directory

In verbose mode, little additional information is offered.

    Arduino: 1.0.6 (Linux), Board: "Arduino Uno"
    avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /tmp/build6314348775898760987.tmp/Blink.cpp -o /tmp/build6314348775898760987.tmp/Blink.cpp.o
    avr-g++: error trying to exec 'cc1plus': execvp: No such file or directory

The file in question, `cc1plus`, is actually present in the filesystem:

    [piebody@berrybody ~]$ locate cc1plus
    /usr/libexec/gcc/armv7hl-redhat-linux-gnueabi/4.9.2/cc1plus
    /usr/libexec/gcc/avr/4.9.2/cc1plus
    [piebody@berrybody ~]$

Does anyone know why it doesn't run "out of the box"? Do I need to modify any environment variables, and if so, which ones and with what exactly? I assume my `PATH` environment variable needs fixing, but is there any environment variable specific to `avr-g++` that needs changing?

I appreciate that this is probably a simple UNIX paths issue, and that the question may be more suited to SE: Unix & Linux.

  [1]: http://sourceforge.net/projects/berryboot/files/os_images/Fedora_21_MATE.img/download
  [2]: http://www.instructables.com/id/Arduino-On-Pi/

body:
There seem to be two issues:

 - Getting the IDE to fully function when launched from the command
   line, and;
 - Getting the IDE to fully function (i.e. compile) when launched from
   the Fedora GUI menu.

I have found a solution if I run the Arduino IDE from the command line, by adding the path to  one of the `cc1plus` binaries to the `PATH` environment variable:

    [piebody@berrybody ~]$ PATH=${PATH}:/usr/libexec/gcc/avr/4.9.2
    [piebody@berrybody ~]$ export PATH
    [piebody@berrybody ~]$ arduino&

However, if I launch the Arduino IDE from the Fedora application menu, and then try to compile a sketch, it still can't locate `cc1plus`. Maybe the `PATH` needs to be added in my `.profile`, or some other mechanism, to get an application launched from the Fedora menu to see the path?1

Yet, even with the command line launch, it still does not finish compiling.  I now get the following error when the IDE attempts to compile:

    In file included from Blink.ino:18:0:
    /usr/share/arduino/hardware/arduino/cores/arduino/Arduino.h:23:20: fatal error: stdlib.h: No such file or directory
     #include <stdlib.h>
                        ^
    compilation terminated.

In verbose mode

    Arduino: 1.0.6 (Linux), Board: "Arduino Uno"
    avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /tmp/build1210300884764677972.tmp/Blink.cpp -o /tmp/build1210300884764677972.tmp/Blink.cpp.o
    In file included from Blink.ino:18:0:
    /usr/share/arduino/hardware/arduino/cores/arduino/Arduino.h:23:20: fatal error: stdlib.h: No such file or directory
     #include <stdlib.h>
                        ^
    compilation terminated.

I assume that this is another `PATH` issue. One that relates to the path to the Arduino libraries, or [`libc`][1] libraries.

After reading [can't locate avr libraries][2]2, I can't see why `avr-g++` is not picking up the `avr` directory in the `/usr` directory.

The actual path to `stdlib.h` is `/usr/avr/include/stdlib.h`

The output of `avr-gcc` (and `avr-g++`) shows `--prefix=/usr`

The Arduino IDE preference file (`~/.arduino/preference.txt`) shows the line

    last.ide.1.0.6.hardwarepath=/usr/share/arduino/hardware

**Linking the includes**

If I manually link some header files to where the compiler actually is looking, then it works (until `avr-gcc` needs a header that I have not linked to):

    cd /usr/share/arduino/hardware/arduino/cores/arduino
    sudo ln -s /usr/avr/include/stdlib.h stdlib.h
    sudo ln -s /usr/avr/include/string.h string.h
    sudo ln -s /usr/avr/include/math.h math.h

but I can not do this for *every* header file, it is ridiculous. There must be a way of linking to `/usr/avr` from `/usr/share/arduino/hardware/arduino/cores/arduino`. I have tried linking the parent directories `/usr/avr` and `/usr/avr/include`, at various points along the directory hierarchy of `/usr/share/arduino/hardware/arduino/cores/arduino`, but none of those seem to work.

**Copying the include directory**

After reading [default include file path?][3], and running `avr-cpp -v` I saw that the default `#include` search path was

    #include <...> search starts here:
     /bin/../lib/gcc/avr/4.9.2/include
     /bin/../lib/gcc/avr/4.9.2/include-fixed
    End of search list.

From this, I could see that `avr-cpp` was searching in `/lib/gcc/avr/4.9.2/include`. I examined, and compared, the contents of `/lib/gcc/avr/4.9.2/include` with `/usr/avr/include` and they held similar (the same) files, except `/lib/gcc/avr/4.9.2/include` was a subset, that is to say that it was missing the required files.

I ended up copying the `/usr/avr/include` directory, which contains the required header files (`stdlid.h` etc., to which I had linked previously), and replacing the original `include` directory, in the directory where `avr-gcc` seemed to be looking, which was in its own directory location `/lib/gcc/avr/4.9.2/`.

    cd /lib/gcc/avr/4.9.2/
    mv include include.old
    cp -r /usr/avr/include .

Then the Arduino compiler seemed to work, until it then gave an assembler error:

    Assembler messages
    Error: unrecognized option -mmcu=avr5

This is an issue with `avr-as`.

I will update as I resolve these issues.

------

1 I eventually resolved this by creating a script in `/usr/bin` (where the `arduino` binary was located) called `arduino.launch` which contains the `PATH` settings and a call to `arduino`:

    #!/bin/sh
    PATH=${PATH}:/usr/libexec/gcc/avr/4.9.2
    export PATH
    arduino

setting it to be executable with `chmod +x arduino.launch`. Then I edited the properties of the Fedora Arduino launch icon, by right-clicking on the icon and selecting **Properties**, and changed the **Command** entry from `arduino` to `arduino.launch`.

However, there must be a better way of doing this, as this seems to be a bit of a hack.

2 Other posts [1][4], [2][5] and [3][6]) that I have read, apart from providing useful paths to investigate, merely suggest reinstalling. However, as bone headed as I may seem, there must be a way of linking up what is already on the file system (everything is there - just in the "wrong" place), such that compiles work as they should.

  [1]: http://ubuntuforums.org/showthread.php?t=441404
  [2]: http://forum.arduino.cc/index.php?topic=48232.0
  [3]: http://www.avrfreaks.net/forum/default-include-file-path
  [4]: http://forum.arduino.cc/index.php?topic=49652.0
  [5]: http://forum.arduino.cc/index.php?topic=86852.0
  [6]: http://forum.arduino.cc/index.php?topic=52129.0


message:
Use LED on pin 13 again after using the SD library

*The question in short:*
On an Arduino UNO or Nano using the [SD library](https://www.arduino.cc/en/Reference/SD), is it somehow possible to use the LED on pin 13 (or any other pin that is used by the library) again after finishing all SD operations?

*Detailed explanation:*
In my sketch, during setup() I need to read some data from a file on the SD card, which is being closed again before leaving setup().

Now, I wanted to use the LED on pin 13 during loop() as a status indicator for the user, but it seems that after SD.begin(), pin 13 (and its LED) cannot be used as an OUTPUT anymore.

Here is a minimum sketch to show the behavior. It doesn't matter if I try to turn on the LED right after the call to SD.begin() in setup() or in loop():

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

    #define SD_CS  4
    #define LED    13

    void setup() {
      pinMode(LED, OUTPUT);

      // This still works:
      digitalWrite(LED, HIGH);
      delay(1000);
      digitalWrite(LED, LOW);

      SD.begin(SD_CS);

      // This does not work anymore:
      digitalWrite(LED, HIGH);
      delay(1000);
      digitalWrite(LED, LOW);
    }

    void loop() {}

body: It is possible to use the LED on pin 13 again by disabling the SPI bus that is used by the SD library to read/write data to/from the SD card. To disable the SPI bus, simply call `SPI.end()` after closing the file on the SD card.


message:
UNO Timer 1 CTC mode not resetting TCNT1

I'm trying to set up timer 1 to run an isr in CTC mode. no matter what i set OCR1A to it always executes at the same frequency and if i print out TCNT1 I get values higher than OCR1A.

here is my Code

        void timer1_init()
        {
        // set up timer with prescaler = 8 and CTC mode
        TCCR1B |= (1 << WGM12)|(0 << CS12)|(1 << CS11)|(0 << CS10);

        // initialize counter
        TCNT1 = 0;

        // initialize compare value
        OCR1A = 100;

        // enable compare interrupt
        TIMSK1 |= (1 << OCIE1A);

          // enable global interrupts
            sei();
        }

    ISR(TIMER1_COMPA_vect){
        SET(MOTOR_PORT,LEFT_MOTOR_STEP); //set the pin high
        delayMicroseconds(3); //keep high for a bit
        CLR(MOTOR_PORT,LEFT_MOTOR_STEP); //set it low
    }

I'm using this to drive a stepper motor so using PWM mode wont work.

body:
It sounds as though timer 1 has not in fact been set to wavegen mode 4. You can ensure that it is by also clearing the other bits of WGM1:

    TCCR1A &= ~(_BV(WGM10) | _BV(WGM11));
    TCCR1B &= ~_BV(WGM13);


message:
Can PWM break a DC motor?

I want to know if controlling the speed of a DC motor with PWM could break (burn out the DC motor. Sorry my English isn't that good.

body: Provided that the voltage specs of the motor are not violated, no. However, the inductance of the motor stands a very good chance of destroying the *switch* unless an appropriately-rated flyback diode is used.


body:
Providing that you send the appropriate voltage this shouldn't break your motor. The creator of Arduino suggest this way of driving motor on his book.
Source: Massimo Banzi's book : "getting started with arduino" : chapter 5 Advanced Input and Output.


message:
LIght bulb to light up

I'd like to write a JavaScript function that lights up an led light for X milliseconds depending on the response from the JavaScript function.

    function HowManySeconds() {
       setTimeout(HowManySeconds,5000)
       return 1000
    }

The JavaScript function will come from a website, so I suppose I would need an Internet enabled device that connects to my router and can 'browse' to my website.

Q: What do I need to buy? A [tessel][1]? An [Espruino][2]?

  [1]: https://tessel.io/
  [2]: http://www.espruino.com/

body:
You could try the intel galileo or the intel edison with arduino shield. They can be programmed with a variant of the arduino ide, but it is possible to call also programs from the native linux os. Or you could have a look at the esp826.
At least on the edison it is possible to run node.js, while the esp supports lua.


message:
Servo motors won't work with motor controller

I have a motor controller controlling two motors, which works perfectly fine when I comment out the two servos in the below code. These two servos are not connected to the motor controller but simply being operated using other Arduino Uno pins, as seen in the code.

When the servo `attach()` functions are included in the code the motor controller only works with one of the motors and the other completely stops working.

I don't understand why the servos are interfering with the motor controller. What's going on here?

    #include <Servo.h>
    Servo myServo1;
    Servo myServo2;

    int m1_ALI = 10;
    int m1_BLI = 9;
    int m2_ALI = 3;
    int m2_BLI = 11;

    int m1_AHI = 12;
    int m1_BHI = 4;
    int m2_AHI = 6;
    int m2_BHI = 5;

    void setup() {

      //myServo1.attach(7);
      //myServo2.attach(8);

      pinMode(m1_AHI, OUTPUT);
      pinMode(m1_ALI, OUTPUT);
      pinMode(m1_BLI, OUTPUT);
      pinMode(m1_BHI, OUTPUT);
      pinMode(m2_AHI, OUTPUT);
      pinMode(m2_ALI, OUTPUT);
      pinMode(m2_BLI, OUTPUT);
      pinMode(m2_BHI, OUTPUT);
    }

    void loop() {

    moveForward(30);

    }//end loop

    void moveForward(int x){

        digitalWrite(m1_AHI, LOW);
        digitalWrite(m1_BLI, LOW);
        digitalWrite(m1_BHI, HIGH);

        digitalWrite(m2_AHI, LOW);
        digitalWrite(m2_BLI, LOW);
        digitalWrite(m2_BHI, HIGH);

        analogWrite(m2_ALI, x);
        analogWrite(m1_ALI, x);
    }//end moveForward

body:
See Servo.cpp:

> Note that analogWrite of PWM on pins associated with the timer are disabled when the first servo is attached.
 Timers are seized as needed in groups of 12 servos - 24 servos use two timers, 48 servos will use four.

Also [Servo Library reference](https://www.arduino.cc/en/Reference/Servo)

> On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

You are using pins 9 and 10 for your motors.

---

analogWrite uses PWM, the servo library uses PWM, you have a conflict of resources here.


message:
What is Arduino?

Actually I don't know about Arduino, but seeing my fellow classmates, I want to start learning it. Could anybody tell what actually Arduino is about?

body:
* [What is Arduino?](https://www.arduino.cc/)
* [Arduino video tutorials](https://www.youtube.com/playlist?list=PLT6rF_I5kknPf2qlVFlvH47qHvqvzkknd)
* [Official boards](https://www.arduino.cc/en/Main/Products)
* [Wikipedia - Arduino](https://en.wikipedia.org/wiki/Arduino)
* [Arduino forum](http://forum.arduino.cc/)

---

A popular Arduino - The Arduino Uno:

[![Arduino Uno][1]][1]

---

In case I get accused of writing a "link-only" answer ...

The Arduino is a hobbyist prototyping platform, where users can develop projects for microprocessors. Typically the boards have one or two processors on them, can connect to a PC/Mac/Linux by a USB interface, be programmed in C++, and operate external devices (eg. motors, lights, MIDI, LCD screens, LEDs) and take readings (eg. temperature, time, location, voltage).

Different boards have different capabilities, such as the number of I/O ports, the amount of memory, and the size of the program that can be uploaded.

You can connect them to the major operating systems:

* Linux
* Macintosh
* Windows

The hardware and software are open-source, making development for them easy.

---

Image attribution: [Sparkfun Electronics](http://www.flickr.com/people/41898857@N04)

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


message:
How to Publish to MQTT with retain option

I don't understand how to publish to mqtt with retain option (The fourth parameters)

I know that I need length in an byte array but I've try allot to determine how to calculate my payload message to an byte var.

here is my code to publish once I am connected.

    String str;
    char chBright[4];
    str = String(ledBrightness); //converting integer into a string
    str = str + '%';
    str.toCharArray(chBright, 4);
    MQTTClient.publish("/maison/GF/Escalier/stairLight/b", chBright);

document ask the third parameter to be an byte

>topic – the topic to publish to `char*`

>payload – the message to publish `byte array`

>length – the length of the message `byte`

>retained – whether the message should be retained `byte`

>>`0` – not retained

>>`1` – retained

[mqtt client for Arduino][1]

**How in c++ to get bytes from the message I want to publish?**

Tank you to clarify my knowledge

  [1]: http://knolleary.net/arduino-client-for-mqtt/api/#publish3 "Arduino client for mQTT info doc"

body:
> How in c++ to get bytes length from the message I want to publish?

For a String object, the method `length()` tells you the length.

eg.

    int len = str.length ();

For a null-terminated C-type string, you can use `strlen`, eg.

    char foo [20] = "bar";
    int len = strlen (foo);


body:
> How to Publish to MQTT with retain option?

The quick answer is add payload length, and retained as true as the last parameters to publish().

    const int BUF_MAX = 8;
    char buf[BUF_MAX];
    itoa(ledBrightness, buf, 10);
    strcat(buf, "%");
    int len = strlen(buf) + 1;
    MQTTClient.publish("/maison/GF/Escalier/stairLight/b", buf, len, true);

Above is a rewrite with the extra parameter for "retained", payload length, and payload as a null-terminated string.

Cheers!


message:
Remote temperature and humidity sensor with long battery life

I want to build a remote sensor which will measure temperature (range 5-30°C) and humidity (range 20-90%) and provide regularly (in the range of one measurement every minute or tenth of minutes) the measurement via wireless. This sensor will be used indoor, mostly in dark areas.

*Note: measurement could be done every minutes and sending them could be done immediately or in batch of 10 measurements or more).*

I was looking to build this solution using an Arduino, DHT22 sensor and a radio transmitter using ZigBee or Z-Wave protocol, and power it via AA rechargeable batteries. But after studying this solution, I found that it would be challenging to even get **a week of battery life**, this would require using the radio sparingly and to try to use as much as possible the power modes of the Arduino ATmel controller.

That's **not enough**, I want a battery life in the range of several months, 1 month would be "acceptable", **6 months would be the target**, breakthrough would be > 1 year.

*Note: I don't want wifi, this seems to suck even more power than the other mentioned radio protocol*

Questions
=========

Is there another more power efficient way to wireless-ly transmit the data?

Or shall I reconsider Arduino all together and look for another more power efficient controller?

Or is there another way?

body:
Sleep mode of a Zigbee is around 5uA. Power-down mode of an arduino is about the same. You can power the DHT22 via one of the digital pins, so it only uses power if you need it (though I thing you need to give it some time to "warm up"). So I don't see much of a problem. You just need to get the software working right.

Also, don't use an Uno, but one of the more bare-bones boards (e.g. Pro Mini) that don't have an usb-to-serial chip on board. Remove the power-led. Maybe remove the voltage regulator, and use 3 AAs for 4.5V.

I use blank ATMega328 chips, and build my own "arduinos" without all the unnecessary parts. I'm currently working on something similar, and plan on using an CR2032 coincell for power. >1 Year should be possible as far as I can see. If not I'll switch to AAs (11 times more power).


body:
I made a [Temperature and humidity sensor - battery powered](http://www.gammon.com.au/forum/?id=12106) in 2013. It is powered from 3 x AA batteries, and lasted, as I recall, until a couple of months ago before I changed the batteries. That is, almost two years.

It logs to an SD card every 15 minutes. You could change that interval of course, it would probably not last as long logging every minute.

[![Temperature and humidity sensor][1]][1]

I certainly wouldn't attempt it with a pre-made board, because of the drain by the power LEDs, the USB chip, the voltage regulator, etc.

I measured 6 µA consumption when asleep.

---

### Schematic

[![Temperature logger schematic][2]][2]

*(RH-click and "View Image" to see a larger version)*

The schematic is deliberately presented as "blocks" of parts of the circuit. To understand it from scratch, make up individual parts, test them and get the code working to your satisfaction. For example, the clock or the temperature sensor.

Some of the parts (like the clock) are already available as pre-assembled boards, if you prefer to reduce soldering.

You could manage without the 7-segment LED readout, however I found it useful for confirming it is working "in the field". The readout LEDs can be purchased cheaply from eBay for around $US 3. Search for `MAX7219 8-Digit LED Display Module 7-Segment` or similar.

---

### Example output

Example of measuring temperature and humidity every minute:

[![Spreadsheet of temperatures][3]][3]

[![Graph of temperatures][4]][4]

You can see from the graph that I left the room at 9:30 pm, and the temperature slowly dropped until 6:30 am the next morning. The zig-zag effect is the central heating turning on and off.

---

### Construction details

See the [linked page](http://www.gammon.com.au/forum/?id=12106) for construction notes, schematic, and code.

Power saving details at [Power saving techniques for microprocessors](http://www.gammon.com.au/power).

---

### Estimated life at logging once a minute

If my calculations are correct, logging every minute might reduce battery life to 7 months (these things are best tested of course), but that is because the consumption is much higher when you power up the SD card. It would probably be best to take 15 readings, and then write to the card every 15 minutes. The extra time writing would be minimal, and that would keep the need to power up the card low.

---

### The 7-segment LEDs

To clarify, those 8 LEDs are not normally on. The battery wouldn't last long if they were! If you press the switch it gives an immediate reading through the LEDs, and also tells you how many writes to disk it has done, and how many write errors it has had. This confirms all is operating properly.

The "busy" LED is there to warn you to not remove the SD card while it is writing to it.

---

### Radio communication

To transmit information you could use a NRF24L01 transceiver module. You get those for a couple of dollars on eBay. Example:

[![NRF24L01 top][5]][5]

Underneath:

[![NRF24L01 bottom][6]][6]

You would need another one at the other end to receive (you would need two of whatever radio you chose).

I did a [solar powered project](http://www.gammon.com.au/forum/?id=12821) using a couple of those. The NRF24L01 uses about 0.9 µA in power-down mode, so that is pretty minimal.

It also uses SPI, so the connections would be very similar to the SD card connector.

I suggest if you are going to attempt this to first get confident with a normal Uno, get the code tested, make sure you have the sleeping/waking going OK, then move it to a low-power board. There are places like [Evil Mad Scientist](http://shop.evilmadscientist.com/directory) that make "bare" boards, with a prototyping area, which you can use to put things like your temperature sensor on.

[![Bare bones board][7]][7]

  [1]: https://i.stack.imgur.com/uWSdG.png
  [2]: https://i.stack.imgur.com/f1AFf.png
  [3]: https://i.stack.imgur.com/sl9ep.png
  [4]: https://i.stack.imgur.com/fg5fZ.png
  [5]: https://i.stack.imgur.com/qdss4.jpg
  [6]: https://i.stack.imgur.com/qYYS6.jpg
  [7]: https://i.stack.imgur.com/iUkhM.jpg


body:
There is an excellent article on power reduction at http://www.gammon.com.au/power , but it's definitely worth looking at the parts of your project OTHER than the arduino - that is, your sensor, and your radio. These tend to use much more than your Arduino.

There is some persistent storage on the Arduino - EEPROM - write all your data to that as you read it, then send it all in bulk. Most of the time your radio will spend will be start/end communication.

Making your board is not as daunting as it seems. Use a breadboard to develop & test your project, then use stripboard (aka veroboard) to build your project. You can cut the tracks with a sharp utility knife, or with a specialized stripboard cutting tool (accurate & easier than a knife).

If you are still nervous, find your local makerspace or hackerspace - there are people there that would be happy to teach you to solder, and help you work out your ideas.


message:
Teensy: SPI and Pressure Sensor

I'm first time working with a Teensy 3.1. I have to connect this (MS5803-01BA: http://www.amsys.de/products/ms5803.htm) pressure sensor via SPI to my Teensy.

My problem is, that I don't have any reliable knowledge on SPI. I read the Wikipedia for it and also the Teensy-Manual.

For the pressure sensor I already got a C-Code but it is only working with the ATMEL ATmega644p microcontroller. I tried to get the code to work with my Teensy, but it seems like I don't get either any input nor any output.

I hope that one of you can help me with the following code and tell me what I'm missing out on. Thank you.

Code:

http://pastebin.com/xaWXfRUR

Datasheet of the pressure sensor:

http://www.amsys.de/sheets/amsys.de.ms5803_01b.pdf

C-Code for the pressure sensor for the ATMEL ATmega644p microcontroller:
http://www.amsys.de/sheets/amsys.de.an520_e.pdf

---

PS: Please excuse my not perfect English for it's not my native language.

body:
Details about SPI at [SPI - Serial Peripheral Interface - for Arduino](http://www.gammon.com.au/spi)

This isn't right:

      SPI.transfer(CMD_ADC_READ); // send ADC read command
      SPDR = SPI.transfer(0x00); // send 0 to read 1st byte (MSB)
      ret = SPDR;
      temp = 65536 * ret;
      SPDR = SPI.transfer(0x00); // send 0 to read 2nd byte
      ret = SPDR;
      temp = temp + 256 * ret;
      SPDR = SPI.transfer(0x00); // send 0 to read 3rd byte (LSB)

The SPI library handles SPDR for you. Writing to it yourself will corrupt its behaviour.

It should be more like:

      SPI.transfer(CMD_ADC_READ); // send ADC read command
      ret = SPI.transfer(0x00); // send 0 to read 1st byte (MSB)
      temp = 65536 * ret;
      ret = SPI.transfer(0x00); // send 0 to read 2nd byte
      temp = temp + 256 * ret;
      ret = SPI.transfer(0x00); // send 0 to read 3rd byte (LSB)

Ditto for elsewhere.


message:
Background processes - Arduino Mega and SeeedStudio CAN shield

I am attempting to interface an Arduino Mega 2560 with a system of four Black Jaguar motor controllers connected in CAN. I'm using the CAN shield from SeeedStudios to accomplish this.

The way Jaguars in CAN mode are configured, you must send a message every 100 ms to the network to keep the link active. However, I'm also getting input from Serial to another Arduino as well as sending other commands to the Jaguars, but not regularly enough to specifically time it out.

Is it possible to have the link message sent asynchronously in the background while I perform other code? I have looked into timers and interrupts, however I am unsure if this would truly solve the issue considering I have other processes that take more than 100 ms to complete.

Here's my loop statement:

    loop() {
      CAN.sendMsgBuf(HEARTBEAT,1,0,volModeEnable); //HEARTBEAT keeps CAN link active
      setVoltage(3,.5); //Sets voltage of Motor by percent
      setVoltage(4,.5);
      setVoltage(6,.5);
      setVoltage(8,.5);
      //GrabFromSerial(); Takes longer than 100ms
      //Control Statement for Additional Commands goes here... (also necessary to be > 100ms)
    }

body:
I see several options:

 1. Change your code to achieve lower delays on the other functions
 2. Use interrupts at a set frequency to trigger the sending (and maybe the automatic transmission trigger pins, see MCP2515 datasheet, depending on pin use & schematic of your specific shield)
 3. Use a basic scheduler/rtos

It is hard to tell what is going on without the rest of your code, if it is a good idea to try to achieve faster functions.

I am not 100% sure the CAN-lib would will work well in the context of an interrupt.


message:
Can't upload sketches to breadboard Arduino

* I have an ATmega328 chip with the boot-loader installed.

* I also have an Arduino Uno with the ATmega328 chip removed.

* I hooked this chip up to a breadboard with the proper 22pF caps, 16MHz crystal, and 10kΩ pull-up resistor.

* The LED flasher was loaded prior, and this works fine when I hook an LED and resistor up to pin 19. I have confirmed my external crystal works by disconnecting it, and the flashing stops, when I reconnect the crystal, the flashing continues.

* Power is fed from my Arduino Uno 5 V out to the DIY Arduino

* I connected the reset wire, and data wires, ensuring pin 2 went to RX and pin 3 to TX.

**In the software**

First to confirm everything works, I removed the chip from the breadboard and placed it in the Arduino. The sketch uploaded successfully using the settings:  Arduino Uno as board and AVRISP mkll as programmer.

Now I move the chip to the breadboard, and ensure all the wires are connected. The LED starts to blink again, but when I try to upload the sketch, I get an error:

`avrdude: stk500_recv(): programmer is not responding`

I ensure continuity between the reset, TX, RX, and power connections and try different settings like Arduino as ISP and different boards under settings including the Duemilanove and nano but nothing seems to be working.

Any suggestions on what to try next?

[![Photo of circuit on breadboard][1]][1]

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

body:
Answered by Skyler440:

> Never mind, found the problem. My software switched to the bluetooth for some reason after I changed some other settings.

*Converted to answer to reduce unanswered questions.*


body:
There are two AVR ICs present on the Arduino board, one is used for the USB to ICSP interface and the other one is the μC which you're using.

As I've noticed that you've tried to connect `Tx` and `Rx` pins including reset for programming the IC. Those pins are used for communication on serial protocol, where as the AVR in Arduino is programmed using SPI Protocol, so you should be using MISO, MOSI, SCK, SS (they're pins 13-10 respectively) and Reset pins on the Arduino, then the AVR which is used as USB-SPI bridge for programming can communicate with the μC and program it.


message:
that no matter what the inputs are Motor1 always moves

int motor_forward1 = 7;
    int motor_reverse1 = 6;
    int motor_forward2 = 5;
    int motor_reverse2 = 4;
    int motor_forward3 = 3;
    int motor_reverse3 = 2;
    int sensor1 = A0;
    int sensor2 = A1;

     void setup()
    {

       pinMode(motor_forward1, OUTPUT);
       pinMode(motor_reverse1, OUTPUT);
       pinMode(motor_forward2, OUTPUT);
       pinMode(motor_reverse2, OUTPUT);
       pinMode(motor_forward3, OUTPUT);
       pinMode(motor_reverse3, OUTPUT);
       pinMode(sensor1, INPUT);
       pinMode(sensor2, INPUT);
     }

     void loop()
     {
       if (digitalRead(A0) == HIGH)
       {
         digitalWrite(motor_forward1,1);
         digitalWrite(motor_reverse1,0);
         delay(5000);
         digitalWrite(motor_forward1,0);
         digitalWrite(motor_reverse1,1);
         delay(5000);
         digitalWrite(motor_forward1,0);
         digitalWrite(motor_reverse1,0);
         delay(1000);
       }
       else if (digitalRead(A1) == HIGH)
       {
         digitalWrite(motor_forward2,1);
         digitalWrite(motor_reverse2,0);
         delay(5000);
         digitalWrite(motor_forward2,0);
         digitalWrite(motor_reverse2,1);
         delay(5000);
         digitalWrite(motor_forward2,0);
         digitalWrite(motor_reverse2,0);
         delay(1000);
       }
       else
       {
         digitalWrite(motor_forward3,1);
         digitalWrite(motor_reverse3,0);
         delay(5000);
         digitalWrite(motor_forward3,0);
         digitalWrite(motor_reverse3,1);
         delay(5000);
         digitalWrite(motor_forward3,0);
         digitalWrite(motor_reverse3,0);
         delay(1000);
       }
       delay(5000);
     }

Schematic [**here**][1].

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

body:
The code isn't wrong, it's far too simple to be at fault.

The error is from within Proteus. Those 'pushbutton' switches (and the other switch simulations) are not quite as straightforward as one would like. They have an OFF resistance, usually 100 Megaohms, but that's enough to trick the simulation into not behaving like it should do. You MUST pull the inputs to ground with a resistor - any sensible value will do as it's only required for the *simulation*. As they are, they're in some odd floating/magic/unknown state; common sense does not apply here!

An alternative is to swap the pushbutton for a SPDT switch; connect the common to the Arduino and the other contacts to the 7805 output and ground. You won't need the resistor in this case.


message:
Self-diagnose components in the circuit

How can I tackle self-diagnosis problem within my Arduino project?
For example, I have a temperature sensor and humidity sensor. How can I know if they work or not on Arduino start or inside the sketch loop?

body:
You could get your program to output messages to the serial pin on your board, Tx. For example:

    Serial.begin(9600) //baud rate of 9600

    Serial.print("Debug Message");

You can use this to print out string and integers. Here is the link to further information on the Arduino website - https://www.arduino.cc/en/reference/serial

If you are already using the Serial pins then you could use the SoftwareSerial Library - https://www.arduino.cc/en/Reference/softwareSerial

This library allows you to make two other pins on your board Tx and Rx. For example:

    SoftwareSerial mySerial(12,13) //Makes pin 12 Rx and pin 13 Tx

    mySerial.begin(9600) //baud rate of 9600

    mySerial.println("Debug Message");

To read the output from any of the pins on your arduino - use a USB to TTL serial cable. Plug it into your computer and use a program like PuTTY to connect to the serial cable and read the messages coming from the Arduino.


body:
If you can define "it works" in code (e.g. the temperature is between X and Y degrees, and changes no faster than 2 degrees per second), and all you need is a "Yes" or a "No", then you can write this into code, then the easiest way is to use an LED. Make sure you blink it, rather than having it on steadily, so you can tell if it's frozen.

Make sure you try unplugging your sensor, to understand what it does when it fails; this is one thing you specifically want to test for.

If you specifically do not want to do this in your main loop, you can do an interrupt-driven version, but that adds a lot of complexity. I suggest you do it in your main loop if you can.

You can use the current time to blink the light regularly:

    if (everything_is_working()) {
      if (millis()000<1000) {
         <turn led on>
      } else {
         <turn led off>
      }
    }

The two numbers let you control the flashes. I've used 10,000 and 1,000; this means that out of every 10,000 millis (10 seconds), the led is on 1,000 millis (1 second). Depending on your preference, you can adjust these to your liking. You can also add an else clause which blinks a different pattern depending on what is wrong - 9 seconds on out of 10 for a problem with the humidity sensor, and 5 seconds out of 10 for the temperature sensor having issues.

If your sketch isn't running, the led will stay in it's current state - either on, or off, indefinitely. If your project has no power, the light will obviously be off.

If you want more data, you can either make more complex blink codes - short-long-short-long, for example - or add multiple lights, or even a three-colour LED, with different colours indicating different problems.


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

Another approach can be handy if you want to do detailed debugging (like outputting numbers) but your serial port is already in use for something, like a GPS. You can use a second Arduino as a "debugging interface" using SPI or I2C. For example, using SPI:

[![Debug via SPI][1]][1]

Or via I2C:

[![Debug via I2C][2]][2]

In these examples the "debugging" Uno also supplies power to the "main" Uno via the 5 V / Gnd pins.

I have a description about this method on [Debugging using SPI/I2C and a second processor](http://www.gammon.com.au/forum/?id=11329). Code is available at: [http://gammon.com.au/Arduino/SPI_Debugging.zip](http://gammon.com.au/Arduino/SPI_Debugging.zip) and [http://gammon.com.au/Arduino/I2C_Debugging.zip](http://gammon.com.au/Arduino/I2C_Debugging.zip) .

To demonstrate the idea, on the "main" Uno this is an example of sending debugging info via SPI:

    // make true to debug, false to not
    #define DEBUG true

    #include <SPI.h>

    // conditional debugging
    #if DEBUG

      #define beginDebug()  do { SPI.begin (); SPI.setClockDivider(SPI_CLOCK_DIV8); } while (0)
      #define Trace(x)      SPIdebug.print   (x)
      #define Trace2(x,y)   SPIdebug.print   (x,y)
      #define Traceln(x)    SPIdebug.println (x)
      #define Traceln2(x,y) SPIdebug.println (x,y)
      #define TraceFunc()   do { SPIdebug.print (F("In function: ")); SPIdebug.println (__PRETTY_FUNCTION__); } while (0)

      class tSPIdebug : public Print
      {
      public:
        virtual size_t write (const byte c)
          {
          digitalWrite(SS, LOW);
          SPI.transfer (c);
          digitalWrite(SS, HIGH);
          return 1;
          }  // end of tSPIdebug::write
      }; // end of tSPIdebug

      // an instance of the SPIdebug object
      tSPIdebug SPIdebug;

    #else
      #define beginDebug()  ((void) 0)
      #define Trace(x)      ((void) 0)
      #define Trace2(x,y)   ((void) 0)
      #define Traceln(x)    ((void) 0)
      #define Traceln2(x,y) ((void) 0)
      #define TraceFunc()   ((void) 0)
    #endif // DEBUG

    long counter;
    unsigned long start;

    void setup() {
      start = micros ();

      beginDebug ();
      Traceln (F("Commenced device-under-test debugging!"));
      TraceFunc ();  // show current function name

    }  // end of setup

    void foo ()
      {
      TraceFunc (); // show current function name
      }

    void loop()
    {

      counter++;
      if (counter == 100000)
      {
        Traceln (F("100000 reached."));
        Trace (F("took "));
        Traceln (micros () - start);
        counter = 0;
        foo ();
      }  // end of if

    }  // end of loop

If DEBUG is true then the debugging prints are activated. Otherwise they turn into "no code".

The receiving end looks like this:

    volatile char buf [1000];
    volatile int inpoint, outpoint;

    void setup (void)
    {
      Serial.begin (115200);   // debugging

      Serial.println ();
      Serial.println (F("Commencing debugging session ..."));
      Serial.println ();

      // have to send on master in, *slave out*
      pinMode(MISO, OUTPUT);

      // turn on SPI in slave mode
      SPCR |= bit (SPE);

      // now turn on interrupts
      SPCR |= bit (SPIE);

    }  // end of setup

    // SPI interrupt routine
    ISR (SPI_STC_vect)
    {
    byte c = SPDR;  // grab byte from SPI Data Register
    int next = inpoint + 1;  // next insert point

      // wrap-around at end of buffer
      if (next >= sizeof buf)
        next = 0;

      if (next == outpoint)  // caught up with removal point?
        return;  // give up

      // insert at insertion point
      buf [inpoint] = c;
      inpoint = next;  // advance to next

    }  // end of interrupt routine SPI_STC_vect

    void loop (void)
    {
      // insertion and removal point the same, nothing there
      noInterrupts ();  // atomic test of a 16-bit variable
      if (outpoint == inpoint)
        {
        interrupts ();
        return;
        }
      interrupts ();

      // display anything found in the circular buffer
      Serial.print (buf [outpoint]);

      noInterrupts ();
      if (++outpoint >= sizeof buf)
        outpoint = 0;  // wrap around
      interrupts ();

    }  // end of loop

There is a 1000 byte buffer which will cope with bursts of incoming data, which is then sent out the serial port on the debugging Uno (that is, to your serial monitor).

The linked library above includes code for SPI and I2C debugging interfaces.

---

Having said that, the simplest thing is just to do serial debugging prints inside your code on the main device, if that is practical.

Remember to use the `F()` macro, or your debugging code might take up so much RAM it causes a crash.

eg.

    Serial.println (F("Temperature sensor working."));

  [1]: https://i.stack.imgur.com/V0aI6.jpg
  [2]: https://i.stack.imgur.com/SLwei.jpg


message:
Printing SD card file contents on LCD

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

This is a part of my program which reads data from file stored in SD card and displays that on an LCD screen.

      File dataFile = SD.open("1165.txt");

      if (dataFile) {
        Serial.println("File Opened");
        lcd.clear();
           delay( 5 );  //LCD-specific M
           lcd.setCursor( 0,0 );

      while (dataFile.available()) {
          Serial.write(dataFile.read());
          lcd.write(dataFile.read());
          lcd.print(dataFile.read());
        }
      dataFile.close();
      } else {
        // if the file didn't open, print an error:
        Serial.println("error");
      }

When I look at the serial monitor it prints the contents of that file but none of these commands print what is printed in the serial monitor,

    lcd.write(dataFile.read());
    lcd.print(dataFile.read());

Any ideas?

body:
When you call `dataFile.read()`, the file pointer is advanced, so you always read different bytes in each `read` call. Imagine the file like a book with many lines: Each time you read, you advance the current line, so with multiple calls, you never get the same data. The solution is to currently store the last read byte:

    while (dataFile.available()) {
      char readByte = dataFile.read();
      Serial.write(readByte);
      lcd.write(readByte);
      lcd.print(readByte);
    }

You have two calls for displaying data in the LCD, but be careful that the second call (`print`) might interpret your data as a number, so just remove the `lcd.print(readByte)` call altogether to be sure it's printing the raw character.


body:
You could also implement a readLine routine, similar to:

    void _readLine(File f, char *line)
    {
     boolean cr_found = false;
     int p = 0;
     while (f.available()) {
      char b = f.read();
      if(b!='\r' && b!='\n')
       line[p++] = b;

      if(b == '\r') cr_found = true;
      if((b == '\n') && cr_found) break;
     }
     line[p] = '\0';
    }

And read the SD file line by line, processing each one of them by its own.

    char buffer[32];

    while(dataFile.available()) {
        _readLine(dataFile, buffer);
        // do something with buffer
    }


message:
nRF2401 communication (extended vs normal)

Communicating to the antenna-less version from an extended range nRF2401 seems to produce some strange results...

At a distance, the receiver seems to receive a number of values instead of one. For example, if I send a 1, I will receive a 1, but 30 times.

Has anyone had experience communicating across the two models, or is it just best practice to stick to communicating across same models? (Short range <-> short range, long range <-> long range)?

body:
I've run both version fine together

Your symptom of receiving the same value 30 times would be related to a failed ACK, so the sender thinks it hasn't been received and resends it.

I've had potentially similar problems with the power amplified version running at full power causing interference in nearby circuity, try dialling down the power setting on it.


message:
Want to add an LCD display screen for the output motor

I want add an LCD display screen at output motor. When the motor runs the LCD display show like "motor 1 run forward" and "motor 1 run reverse". I want it display for all motor but I don't know how code using arduino using 16x2 LCD display screen.

    int motor_forward1 = 7;
    int motor_reverse1 = 6;
    int motor_forward2 = 5;
    int motor_reverse2 = 4;
    int motor_forward3 = 3;
    int motor_reverse3 = 2;
    int sensor1 = 13;
    int sensor2 = 12;

     void setup()
    {

       pinMode(motor_forward1, OUTPUT);
       pinMode(motor_reverse1, OUTPUT);
       pinMode(motor_forward2, OUTPUT);
       pinMode(motor_reverse2, OUTPUT);
       pinMode(motor_forward3, OUTPUT);
       pinMode(motor_reverse3, OUTPUT);
       pinMode(sensor1, INPUT);
       pinMode(sensor2, INPUT);
     }

     void loop()
     {
       if (digitalRead(13) == HIGH)
       {
         print
         digitalWrite(motor_forward1,1);
         digitalWrite(motor_reverse1,0);
         delay(5000);
         digitalWrite(motor_forward1,0);
         digitalWrite(motor_reverse1,1);
         delay(5000);
         digitalWrite(motor_forward1,0);
         digitalWrite(motor_reverse1,0);
         delay(1000);
       }
       else if (digitalRead(12) == HIGH)
       {
         digitalWrite(motor_forward2,1);
         digitalWrite(motor_reverse2,0);
         delay(5000);
         digitalWrite(motor_forward2,0);
         digitalWrite(motor_reverse2,1);
         delay(5000);
         digitalWrite(motor_forward2,0);
         digitalWrite(motor_reverse2,0);
         delay(1000);
       }
       else
       {
         digitalWrite(motor_forward3,1);
         digitalWrite(motor_reverse3,0);
         delay(5000);
         digitalWrite(motor_forward3,0);
         digitalWrite(motor_reverse3,1);
         delay(5000);
         digitalWrite(motor_forward3,0);
         digitalWrite(motor_reverse3,0);
         delay(1000);
       }
       delay(5000);
     }

body:
From this [instructable][1]:

    // include the library code:
    #include <LiquidCrystal.h>

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    void setup() {
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // Print a message to the LCD.
      lcd.print(" **Text for line 1 of LCD**");
      lcd.setCursor(0, 1);
      lcd.print(" **Text for line 2 of LCD**");
      // THE REST OF YOUR SETUP
    }

    void loop() {
        if (digitalRead(13) == HIGH) {
            // I assume this is the motor going forward
            lcd.print("motor 1 run forward");
        }
    }

  [1]: http://www.instructables.com/id/Connect-A-16x2-LCD-Display-To-An-Arduino/?ALLSTEPS
  [2]: https://www.arduino.cc/en/Tutorial/LiquidCrystal


message:
Suggest me an Arduino development board, with a removable ATmega chip?

I want to buy an arduino development board which has facility to remove its chip and insert a new one anytime. I want to use multiple chips in a single board for different purposes.

If it is not possible, Please suggest me any alternative.

body:
It is possible, you could probably do it on most of the Arduino boards too.

This page on the Arduino website may help you - https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard

I have personally never attempted it but I know quite a few people who have and they have never had too many big issues.


body: Only the Arduino Uno has a socketed IC chip. All the rest are using soldered SMD ICs.


body:
You could get an [ATmegaXX8 target board](http://shop.evilmadscientist.com/productsmenu/tinykitlist/74-atmegaxx8) from Evil Mad Scientist. That has (or can have) a ZIF socket so you can easily remove the chip without bending its legs.

[![AtmegaXX8 target board][1]][1]

That's around $US 3 for the board, $2 for the ZIF socket, $1 for the crystal, 45 cents for the ICSP header.

You can put an Atmega328P into the socket (same chip as on the Uno). Note that *some soldering is required*. You would need to solder on the ZIF socket, the ISP header, and make up an FTDI header if you wanted to easily program it from the IDE.

You would also need (or it would be helpful to have) a 16 MHz crystal along with 2 x 18 pF capacitors. They have them for sale at that site.

You would also need a 10 k pull-up resistor for Reset, a couple of 0.1 µF decoupling capacitors, and another 0.1 µF capacitor for handling reset via the FTDI interface - if you use it.

If you want to program serially (and do serial debugging) you need some sort of USB interface, such as an FTDI cable or board.

Example [FTDI Serial TTL-232 USB Cable](http://www.adafruit.com/products/70).

[![FTDI cable][2]][2]

That is around $US 18. (Of course, you only need to buy the cable once, so this is a one-time cost).

You would need to solder in 6 header pins in a line to plug that into (on the prototyping area) and then run appropriate wires to Tx/Rx/Gnd/5V and Reset via the 0.1 µF capacitor I mentioned.

Adafruit have an [Arduino bootloader-programmed chip (Atmega328P)](http://www.adafruit.com/products/123) for $US 6.

All-up it would probably cost you around $US 30 to put it together. (The FTDI cable is a once-off cost, as you can use that on multiple projects).

---

Other vendors will probably have similar products.

  [1]: https://i.stack.imgur.com/NaC8r.jpg
  [2]: https://i.stack.imgur.com/9KNFw.jpg


body:
If the question is driven by need of minimizing the overall cost, well, on ebay you can find plenty of Arduino Mini Pro at about $2, shipment included. Add an USBASP programmer at the cost of $5 and you get a solution which is still pretty cheap and allows each board to be used, rather than having just one with multiple chips to insert/remove.
At a fraction of the cost of the other solutions described here.


body:
The ultimate solution would be to build it yourself!

[![Standalone Arduino][1]][1]

Arduino has an excellent step by step guide on how to build a [standalone Arduino][2], using a ATMega328, on a breadboard. Now everything is removable, not just the chip.

Note that there is one slight error in the guide, which I have highlighted here, [Arduino Standalone - photo shows incorrect pin wired to MOSI][3].

There is a video on how to achieve, more or less, the same thing, [1-Day Project: Build Your Own Arduino Uno for $5][4].

  [1]: https://i.stack.imgur.com/EYXT3.jpg
  [2]: https://www.arduino.cc/en/main/standalone
  [3]: https://arduino.stackexchange.com/questions/10392/arduino-standalone-photo-shows-incorrect-pin-wired-to-mosi
  [4]: https://www.youtube.com/watch?v=sNIMCdVOHOM


message:
nRF24L01 module using Mirf library was working and then stopped

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

I have two nRF24L01 modules, they are both attached to a sensor shield that has special ports for this type of module, on Arduino Unos.

[![Sensor shield, with nRF24LO1 in it][1]][1]

I have this code on the Arduino that is sending the signal:

    #include <MirfHardwareSpiDriver.h>
    #include <MirfSpiDriver.h>
    #include <Mirf.h>
    #include <nRF24L01.h>
    #include <SPI.h>
    #include <Wire.h>

    //0 = stop, 1 = left, 2 = right, 3 = forward, 4 = backwards
    long command;
    long last_command;

    long Joystick_1_X;
    long Joystick_1_Y;
    long Joystick_1;

    void setup() {
      // put your setup code here, to run once:
      Mirf.spi = &MirfHardwareSpi;
      Mirf.init();
      Mirf.setTADDR((byte *)"serv1");
      Mirf.payload = sizeof(long);
      Mirf.config();
      Serial.begin(115200);
    }

    void loop() {
      Joystick_1_X = analogRead(A0);
      Joystick_1_Y = analogRead(A1);

      if(Joystick_1_X < 450){
         command = 1;
      }else if(Joystick_1_X > 600){
        command = 2;
      }else if(Joystick_1_Y > 600){
        command = 3;
      }else if(Joystick_1_Y < 400){
        command = 4;
      }else{
        command = 0;
      }
      if(command == last_command){
      }else{
        Mirf.send((byte *)&command);
        last_command = command;
       }
      }

and this code on the Arduino that is receiving

    #include "SPI.h"
    #include "Mirf.h"
    #include "nRF24L01.h"
    #include "MirfHardwareSpiDriver.h"

    int TN1= 3;
    int TN2 = 4;
    int ENA = 9;

    int TN4 = 5;
    int TN3 = 6;
    int ENB = 10;

    long data;

    void setup() {
     pinMode(TN1, OUTPUT);
     pinMode(TN2, OUTPUT);
     pinMode(TN3, OUTPUT);
     pinMode(TN4, OUTPUT);
     pinMode(ENA, OUTPUT);
     pinMode(ENB, OUTPUT);

     Mirf.spi = &MirfHardwareSpi;
     Mirf.init();
     Mirf.setRADDR((byte *)"serv1");
     Mirf.payload = sizeof(long);
     Mirf.config();
     Serial.begin(115200);
     Serial.print("begin");

    }

    void loop() {

      // put your main code here, to run repeatedly:
      receiveCommand();
      if(data == 1){
        left();
      }else if(data == 2){
        right();
      }else if(data == 3){
        forward();
      }else if(data == 4){
        backwards();
      }else if(data == 0){
        stop_rover();
      }
    }

    void receiveCommand(){
      if(!Mirf.isSending() && Mirf.dataReady()){
        Mirf.getData((byte *)&data);
        Mirf.rxFifoEmpty();
        Serial.print(data);
      }else{
        Serial.println("No data to be recieved");
      }
    }

    void forward(){
      digitalWrite(ENB, HIGH);
      digitalWrite(ENA, HIGH);
      digitalWrite(TN4, HIGH);
      digitalWrite(TN3, LOW);
      digitalWrite(TN1, HIGH);
      digitalWrite(TN2, LOW);
    }

    void backwards(){
      digitalWrite(ENB, HIGH);
      digitalWrite(ENA, HIGH);
      digitalWrite(TN4, LOW);
      digitalWrite(TN3, HIGH);
      digitalWrite(TN1, LOW);
      digitalWrite(TN2, HIGH);
    }

    void left(){
       digitalWrite(ENA, HIGH);
       digitalWrite(TN1, HIGH);
       digitalWrite(TN2, LOW);
    }

    void right(){
      digitalWrite(ENB, HIGH);
      digitalWrite(TN4, HIGH);
      digitalWrite(TN3, LOW);
    }

    void stop_rover(){
      digitalWrite(ENB, LOW);
      digitalWrite(ENA, LOW);
      digitalWrite(TN4, LOW);
      digitalWrite(TN3, LOW);
      digitalWrite(TN1, LOW);
      digitalWrite(TN2, LOW);
    }

This was working, and the rover did spin its wheels when the remote broadcasted a signal, but then it just stopped. The sensor shield says that they are plugged into the 3V port, I tried using the RF24 library and that did not work either.

Any help would be greatly appreciated.

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

body:
Using the MIRF Library that I got from [here][1], and then using this code to send

     Mirf.send((byte *)&command);
        while(Mirf.isSending()){
            }

and this code to receive

     if(!Mirf.isSending() && Mirf.dataReady()){
        Mirf.getData((byte *)&data);
        Mirf.rxFifoEmpty();
    else(){
    }

I was able to get it to work

  [1]: http://www.sainsmart.com/zen/documents/20-011-401/Codes_for_Self-balancing_robot.zip


message:
Arduino can't find my custom library: fatal error, Motor.h not found etc

I have been working on a project building a robot and using my own custom-built libraries to control it. However after converting all my old code into libraries Arduino can't find them.

Everything thing I have seen says to save them in the 'libraries' folder in with the sketches in MyDocuments and to reboot the Arduino Environment so it will recognize them.

Did that.

It even recognizes them in the sketch menu as libraries that can be imported. However, when I click on them to be included, a new blank line is entered into the sketch instead of an include statement. Perhaps this is some clue? I am really out of ideas at this point as to what I have done wrong.

body:
I had the same symptom described here. In my case, there was a broken link in my libraries directory. Removing that link made the problem go away. It seems that you need to be careful that there is nothing in that directory that could cause the IDE to have difficulty parsing it.

I saw this on a Linux environment (the original poster didn't specify the OS but the reference to "MyDocuments" sounds like Windows). The link I referenced was a symbolic link I had created to a custom library that I subsequently moved, breaking the link.


body:
I wanted to vote for the answer from trpropst, but I don't seem to be authorised to do so.

I had the same problem as Caleb. It turned out that the problem was that the user library directory /Arduino/libraries/ contained a library with a missing ".h" file. The Arduino IDE stopped loading the user libraries when it reached the library with the missing ".h" file.

i.e.

the folder "/Arduino/libraries/libraryA" existed

the file "/Arduino/libraries/libraryA/libraryA.h" existed

but the file "/Arduino/libraries/libraryA/libraryA.h" had an include

"#include <libraryB>" for which the folder "/Arduino/libraries/libraryB" existed but it did not contain a file "/Arduino/libraries/libraryB/libraryB.h"

I was trying to compile a program using libraryC, but not using libraryA or libraryB. I guess the lesson is do not develop libraries using the production tool chain.

edited to print < and > correctly


message:
Using union to return a range of bits from a data frame: wrong approach?

I'm working on an adaptation of Jason Leyrer's [Guitar Hero Library][1] for Arduino.  My version is for a DJ Hero controller, and I've also borrowed some code from this Arduino forum thread: topic=120527 (sorry can't post links yet).

The protocol is i2c and I am successfully reading data from it, however I'm not 100% sure what to do with the data.

The buttons are fine, as they are mapped to just one bit in a given byte.  However the other controls are a combination of 4, 5 and 6 bit longs.

The format according to Wiibrew is like so:

[![Table of DJ Hero dataframe format][2]][2]

 - `BE` is for Euphoria button
 - `CS` : Crossfade Slider, lower is left and upper is right
 - `SX` and `SY` are the black analog stick.
 - `ED` is the Effect Dial
 - `RTT` is the turntable on the right as a 6-bit signed integer (positive = CW; negative = CCW)
 - `RBG`,`RBR`,`RBB` are the Green, Red and Blue buttons on the right
 - LTT is the turntable on the left as a 6-bit signed integer (positive = CW; negative = CCW)
 - `LBG`,`LBR`,`LBB` are the Green, Red and Blue buttons on the left

I'm trying to do this:

<!-- language: c -->

     signed long DJ_ED()
    {
      pack5 ED;
      ED[0] = (DJ_buf[3] >> 5) & 1;
      ED[1] = (DJ_buf[3] >> 6) & 1;
      ED[2] = (DJ_buf[3] >> 7) & 1;
      ED[3] = (DJ_buf[2] >> 5) & 1;
      ED[4] = (DJ_buf[2] >> 6) & 1;

      return ED;
    }

Where pack5 is the following:

<!-- language: c -->

    #define packet5
    union pack5
    {
       signed long value;
       int ints[5];
    };

but I'm getting the following error:

`no match for 'operator[]' (operand types are 'pack5' and 'int')`

What am I doing wrong?

  [1]: http://www.jleyrer.net/blog/2008/03/wii-guitarduino/
  [2]: https://i.stack.imgur.com/RVhDH.png

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

You are using a union so you have to specify which part of the union you want. Your function should read:

     signed long DJ_ED()
    {
      pack5 ED;
      ED.ints[0] = (DJ_buf[3] >> 5) & 1;
      ED.ints[1] = (DJ_buf[3] >> 6) & 1;
      ED.ints[2] = (DJ_buf[3] >> 7) & 1;
      ED.ints[3] = (DJ_buf[2] >> 5) & 1;
      ED.ints[4] = (DJ_buf[2] >> 6) & 1;

      return ED.value;
    }

It still looks wrong because you are only putting a single bit into those 5 bytes (because of the & 1). And 5 x int will be a lot longer than one signed long.

---

The code below seems to match the data structure you posted an image of:

    struct packedFields
    {
      // byte 0
      unsigned int sx      : 5;
      unsigned int rtt_4_3 : 3;

      // byte 1
      unsigned int sy      : 5;
      unsigned int rtt_2_1 : 3;

      // byte 2
      unsigned int rtt_5   : 1;
      unsigned int cs      : 4;
      unsigned int ed_4_3  : 2;
      unsigned int rtt_0   : 1;

      // byte 3
      unsigned int ltt_4_0  : 5;
      unsigned int ed       : 3;

      // byte 4
      unsigned int ltt_5    : 1;
      unsigned int rbr      : 1;
      unsigned int b_plus   : 1;
      unsigned int filler_2 : 1;
      unsigned int b_minus  : 1;
      unsigned int lbr      : 1;
      unsigned int filler_1 : 2;

      // byte 5
      unsigned int filler_4 : 2;
      unsigned int rbb      : 1;
      unsigned int lbg      : 1;
      unsigned int be       : 1;
      unsigned int rbg      : 1;
      unsigned int filler_3 : 1;
      unsigned int lbb      : 1;

    };

    union packedFieldsUnion
      {
      packedFields a;
      byte b [6];
      };

    void doSomethingWithTheFields (packedFieldsUnion & theFields);  // prototype
    void doSomethingWithTheFields (packedFieldsUnion & theFields)
      {
      theFields.a.rtt_4_3 = 3;
      theFields.a.ltt_4_0 = 2;
      }  // end of doSomethingWithTheFields

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      Serial.print (F("packedFields sized = "));
      Serial.println (sizeof (packedFields));

      packedFieldsUnion foo;
      memset (&foo, 0, sizeof foo);

      doSomethingWithTheFields (foo);

      Serial.println (F("-- packedFields bytes --"));
      for (int i = 0; i < sizeof foo; i++)
        Serial.println ((int) foo.b [i], HEX);

      }  // end of setup

    void loop ()
      {
      }  // end of loop

I have a bitwise struct, as Ignacio Vazquez-Abrams suggested. Testing indicates you put the low-order bits first. Then I made a union of this struct and 6 bytes. You can't fit the whole thing into a signed long anyway (a long is 4 bytes) so that part of your code was doomed to fail.

A small bit of test code proves that the bits are being accessed in the correct way. You still need to fiddle around with things like RTT which has individual bits scattered in different places.

---

If you look at the data format you posted there are 6 bytes, not 5. They are numbered 0, 1, 2, 3, 4, 5. A total of six of them.


message:
Good tips for how to connect cables into Mux Shield II?

I just got a Mux Shield 2 and got it working as I expected. Now I started to find out how to actually connect the I/O cables to the board. Doesn't seem to be as simple as I thought. I don't want to solder cables into the board for maintenance reasons. So, does anyone have any good tips on how to do this?

[![Photo of shield][1]][1]

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

body:
Solder 100-mil male headers onto the board, then use 100-mil crimp terminals to connect the wires.

[![100-mil male headers][1]][1]
[![Female crimp terminals][2]][2]
[![Connected][3]][3]

  [1]: https://i.stack.imgur.com/edU2P.jpg
  [2]: https://i.stack.imgur.com/DRMxf.jpg
  [3]: https://i.stack.imgur.com/L50td.jpg


message:
I2Cdev #include weirdness

I am using [Jeff Rowberg's MPU6050 library](https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050), and I simply don't understand what is going on in the following lines of the first example (MPU6050_raw.ino):

    #include "I2Cdev.h"
    #include "MPU6050.h"

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

So, what I got from that is, if I2Cdev is using Wire instead of some alternative I2C library, I should include Wire.h. I really don't see why that's necessary, so I removed the line in which Wire.h is included, and got this error:

    C:\Users\Franco2500k\Documents\Arduino\libraries\I2Cdev/I2Cdev.h:80:26: fatal error: Wire.h: No such file or directory
         #include <Wire.h>

So, apparently, I2Cdev.h already tries to include Wire.h, but somehow fails? And another #include a few lines later goes back in time and fixes everything? Can someone explain what is going on?

body:
The Arduino IDE means well, really it does. It copies your source, the device core, and any libraries used by your source all to a separate directory so that it doesn't poison any of their original locations unintentionally.

But of course, there's something missing from that list. The IDE *doesn't copy libraries used by other libraries*. Therefore if you don't include Wire.h in your .ino file then Wire will be missing from the build and you get the error observed. Cracktastic.


message:
How can I turn this into an (Ableton) controller?

I found this lovely decade box in a demolished house recently and want to turn it into an Ableton controller. As you see, there are 18 knobs, each with 12 individual states.

I'd like to have a program which can access the states of all the knobs at any time, and I have an arduino which I can use. Is this possible to do without a shield?

My first thought is that, since many of the leads on the back already have resistors on them, I could use a sort of total-resistance-across-the-connection approach which would suit itself to the analog inputs. But I'm not sure that's the way to go, especially if I want very low latency.

How can I wire up a board that has digital access to all the pins here? How does a multiplexer play into this? How many inputs would I need? I am super new to this kind of stuff, so I imagine this must be a pretty simple answer.

Thanks for your help.

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

  [1]: https://i.stack.imgur.com/fUlgW.jpg
  [2]: https://i.stack.imgur.com/64SC2.jpg

body:
The hard part here is that you essentially have 216 inputs you need to read.

You could multiplex the analog pins using two [74HC4051](http://playground.arduino.cc/Learning/4051). Analogread takes around 0.1ms, so around 2ms for all 18 knobs. Debouncing would however be pretty hard.

I'd probably go with input shift registers, and remove all the resistors. You would however need 27 8-bit shift register (3 registers per 2 knobs).

To reduce this you could encode the rotary position into 4-bit using a [diode network](http://www.allaboutcircuits.com/worksheets/encoders-and-decoders/). That way you can use only 1 shift register per 2 knobs. So 9 in total.


body:
You can use the analog route by using a [CD74HC4067][2], then you can hook it up to a analog demultiplexer, such as the [CD74HC4067][2](breakout from SFE) which has 16 analog/digital inputs. You would use one of these and two analog pins, one from the breakout and one from the panel, as there are 17 dials from what I can see.

An example of a resistor ladder:
![enter image description here][3]

The 4067 is addressed using 4 digital pins to make up a binary address relating to each input. You would put this into a for loop and read from each address and put in an array of values each time you loop. And when leaving the loop read the last analog value.
I would use port manipulation to write the address as it would speed up the operation.

Once you have the values in the array you can then do the math require to get where the dial is or you can do that as you read the analog pin the the for loop, kind of keep it all in one function. You can find the calculation for converting in the Wikipedia article, the R-2R style.

[Bildr][4] have a nice write up with some code, an image of the basic setup:

![enter image description here][5]

  [1]: https://www.sparkfun.com/products/9056
  [2]: https://www.sparkfun.com/products/9056
  [3]: https://i.stack.imgur.com/kdWa3.png
  [4]: http://bildr.org/2011/02/cd74hc4067-arduino/
  [5]: https://i.stack.imgur.com/KCi3R.png


body:
The other answers are excellent, however I want to address this question:

>  How does a multiplexer play into this?

Just as an example of how multiplexing helps, I opened up a [scrolling LED sign](http://www.gammon.com.au/forum/?id=12298) which has 504 individual LEDs which "appear" to be all on at once (if wanted).

Internally were 10 x [74HC595](http://www.gammon.com.au/forum/?id=11518) serial shift registers. 9 of them were hooked up to the individual columns (giving 72 columns), and the last one was connected to the 7 rows.

     9 * 8 =  72    columns
    72 * 7 = 504    LEDs

Thus we could turn on 504 LEDs. However to have individual LEDs appear to come on the code has to turn on one row (out of the 7) and then output the pattern for that row to the 72 columns. Then it switches to another row, does the next pattern, and so on.

I have a [video of this effect](https://vimeo.com/80312101) on Vimeo.

If you do it fast enough, all the LEDs appear to be one at once.

---

Now you can do this for switches too, just connect all the individual positions together, and then apply "power" to each switch in sequence, and read the results. This time you want an **input** shift register, eg. the [74HC165](http://www.gammon.com.au/forum/?id=11979) for the reading, and an output register for powering each switch.

The problem is with switches though, that you would get "phantom" reads because switches aren't diodes (or, worse, the inactive switches would short the power to ground). So you would need a **diode** in series with each switch to prevent that. Ah well, diodes are cheap.

This is exactly the same concept as the way keypads work. Say, a 16-key keypad will have 8 wires: 4 rows and 4 columns.

---

Having said all that, you will still need quite a few chips unless you set up quite a complex "simulated" keypad array. Maybe it wouldn't be too bad.

You have 17 switches so that would be 2 x 74HC595 for activating each switch, plus one spare pin on the Arduino. And the switches seem to have around 12 positions, so that would be 2 x 74HC165 to read which position it was at.

So, for each switch, you make that one HIGH and the others LOW. Current will flow through the diodes and the rotary switch, presenting a HIGH on one of the 12 "reading" pins. The diodes stop the current from shorting the HIGH to the LOW through other switches.

You take a reading, and move onto the next switch. This can be done quickly, in the same way the LED sign scrolls so fast you can't spot any flickering.

This schematic illustrates the idea:

[![Rotary switch example][1]][1]

In this example we apply a HIGH to the common part (rotor) of the left switch. It goes through the diode, and the selected position, to make input "read 1" high. The diode on the other switch prevents the HIGH from being shorted to the LOW, even though both switches are in the same position.

You would need a pull-down resistor for each of the 12 "reading" lines, so that if they weren't being forced HIGH, they would read LOW. And one diode per rotary switch. So, not too many extra parts. And the wiring is simple, just connect each corresponding switch pin together (except for the common one, of course).

I think this will work, unless anyone can see a major flaw. :)

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


message:
ATtiny461 PWM CTC mode help

I am a beginner at AVR and programming. I am using ATtiny461 and asked to make code to use timer in PWM and CTC mode and use interrupts and pin toggle, this code worked for me with normal timer and toggle but I don't know how to make it work with CTC and PWM:

    #include <avr/io.h>
    #include <avr/interrupt.h>

    //Init PD6 pin as output
    void InitPort(void)
    {
     PORTB&=~(1<<PB1);//initial value 0
     DDRB|=(1<<PB1);
    }
    //Initialize Timer0
    void InitTimer0(void)
    {
     //Enable Timer0 overflow Interrupt
     TIMSK|=(1<<TOIE0);
     //Set Initial Timer value
     TCNT1=5;
    }
    void StartTimer0(void)
    {
     //Set prescaller 64 and start timer
     TCCR0B|=(1<<CS01)|(1<<CS00);
     //Enable global interrupts
     sei();
    }
    //Timer0 Overflow ISR
    ISR(TIMER0_OVF_vect)
    {
     //Reset Initial Timer value
     TCNT1=5;
     //toggle PD6 pin
     PINB=(1<<PB1);
    }

    int main(void)
    {
     InitPort();
     InitTimer0();
     StartTimer0();
     while(1)
     {
      //doing nothing
     }
    }

and I know those commands for setting fast PWM and CTC:

    TCCR1D |= (0<<WGM10)|(0<<WGM11);
    TCCR1A |= (1<<PWM1A)|(1<<COM1A0)|(0<<COM1A1);

body:
PWM is only supported for timer1 on the ATTiny461. Not in timer0.

Look at [TCCR1A](http://www.atmel.com/images/atmel-2588-8-bit-avr-microcontrollers-tinyavr-attiny261-attiny461-attiny861_datasheet.pdf#page=112); specifically the COM1xn bits.