message:
object with multiple instances with internal data store separate for each instance

I'm trying to keep track of a timer, and the internal variables seem to be overrun by one another.

I just want two instances of the Output class, which can keep track of the _elapsed_time so I can check if the time elapsed. It's a poor-man's real-time for a game. I know there are libraries available and I'm planning to use them, but I would really appreciate knowing what's going on here: I want a buzzer pin, and status led pin to 'blink' at different intervals. They both work individually, but when I have them both uncommented they work somewhat serially...

    #include "Arduino.h"

    #include "MTC.h"

    #include <SoftwareSerial.h>   //Software Serial Port

    //HARDWARE SETTINGS
    #define PIN_STATUS     13
    #define PIN_BUZZER     A2

    Output *STATUS(0);
    Output *BUZZER;

    void setup()
    {
     Serial.begin(9600);
     STATUS = new Output();
     STATUS->Begin(PIN_STATUS, STATE_OFF);
     BUZZER = new (Output) Output(3);
     BUZZER->Begin(PIN_BUZZER, STATE_OFF);
    }

    void loop()
    {
     static bool run_once = true;

     if (run_once == true)
     {
      run_once = false;
      Serial.print("Running");
      Serial.flush();
     }
     delay(250);

     //Serial.println("still running");

     STATUS->SetStrobe(3000);

     //BUZZER->SetStrobe(4000);

    }

and class:

    #ifndef MTC_h
    #define MTC_H

    typedef int OUTPUT_STATE;
    OUTPUT_STATE STATE_OFF = 0;
    OUTPUT_STATE STATE_ON = 1;
    OUTPUT_STATE STATE_STROBE = 2;

    class Output
    {
    private:
     int _pin;
     OUTPUT_STATE _last_state;
     unsigned long _cycle_duration;
            unsigned long _last_elapsed;

    public:
     Output();           //constructor: set pin data store
     void Begin(int pin, OUTPUT_STATE state);        //set hardware to output and defaul state
     void Set(OUTPUT_STATE state);        //toggle operability
     void SetStrobe(unsigned long duration);      //strobe operability
    };

    Output::Output()         //constructor: set pin data store
    {

    }

    void Output::Begin(int pin, OUTPUT_STATE state)
    {
     _pin = pin;
            _last_elapsed = millis();
     pinMode(_pin, OUTPUT);
     digitalWrite(_pin, state);
     _last_state = state;
    }

    void Output::Set(OUTPUT_STATE state)
    {
     if (_last_state != state)
     {
      digitalWrite(_pin, state);
      _last_state = state;
     }
    }

    void Output::SetStrobe(unsigned long duration)
    {
     static OUTPUT_STATE _last_strobe_state = STATE_OFF;

     unsigned long elapsed = millis() - _last_elapsed;
     if (elapsed >= duration)
     {
      if (_last_strobe_state == STATE_OFF)
      {
       digitalWrite(_pin, STATE_ON);
       _last_strobe_state = STATE_ON;
      }
      else
      {
       digitalWrite(_pin, STATE_OFF);
       _last_strobe_state = STATE_OFF;
      }
      _last_state = STATE_STROBE;
      _last_elapsed = millis();
     }
    }
    #endif

body:
Your `Output::SetStrobe()` is wrong, it uses a `static` variable (`_lasr_strobe_state`) that is thus shared between all instances of `OUTPUT`, which is NOT what you want.

You have to change it into a non-static member of class Output instead:

    class Output
    {
    private:
        int _pin;
        OUTPUT_STATE _last_state;
        // NEW member here!!!
        OUTPUT_STATE _last_strobe_state;
        unsigned long _cycle_duration;
            unsigned long _last_elapsed;

    public:
        Output();     //constructor: set pin data store
        void Begin(int pin, OUTPUT_STATE state);//set hardware to output and defaul state
        void Set(OUTPUT_STATE state);            //toggle operability
        void SetStrobe(unsigned long duration);  //strobe operability
    };

Then you initialize it in the constructor:

    Output::Output():_last_strobe_state(STATE_OFF)
    {

    }

And you remove it (static declaration) from method `SetProbe` (the rest of the method does not change):

    void Output::SetStrobe(unsigned long duration)
    {
        unsigned long elapsed = millis() - _last_elapsed;
        if (elapsed >= duration)
        {
            if (_last_strobe_state == STATE_OFF)
            {
                digitalWrite(_pin, STATE_ON);
                _last_strobe_state = STATE_ON;
            }
            else
            {
                digitalWrite(_pin, STATE_OFF);
                _last_strobe_state = STATE_OFF;
            }
            _last_state = STATE_STROBE;
            _last_elapsed = millis();
        }
    }


sender: user

sender: assistant

body:
This is not a real answer, as @jfpoilpret already gave a perfectly valid
one. Just a few observations and suggestions from looking at your code.
I write is as an answer only because it is too long to fit in a comment.

1. The member variable `_cycle_duration` is not used. You could remove
   it and save a couple of bytes per Output instance.
2. `if (run_once == true)` is equivalent to `if ((run_once == true) ==
   true)`. They are both considered bad style. Preferred style is to
   just write `if (run_once)`.
3. On the Arduino, it is generally good practice to avoid dynamic
   allocation whenever possible. Of course, it is not always possible,
   but in this instance it is quite easy: declare STATUS and BUZZER as
   objects instead of pointers (as in `Output STATUS;`), then replace
   `->` by a single dot (`.`).


message:
Driving conveyor belts using Arduino Unos

We are planning to drive conveyor belts with Arduino Unos using stepper motors. We are planning to use easy drivers, so that we control at least 3 motors with one Uno. Currently we are still at an initial stage, we are designing and planning the setup of conveyor belts. But what I wanted to ask was, regarding the coding.

How would I code so that say the belt moves forward for `x` seconds, and then after time it moves backwards for `y` seconds. Any basic idea on the code would be great thank you. I could do the basic code, but I just need help with timers part.

body:
In regards to time control use the mills() function.  You start by creating an:

    unsigned long lastTime = millis();

Then later in the program create another variable:

    unsigned long currentTime = millis();

Next Compare the two:

    unsigned long elapsedTime = currentTime - lastTime;

For the most part I normally just shorten the last two lines into one:

    unsigned long elapsedTime = millis() - lastTime;

Stepper motors are not needed if you are just doing timed control, but the advantage of stepper motors are you can move them with pin point accuracy based on the number of steps per rotation.  If there are 60 steps per rotation then 360 degrees per rotation/ 60 steps per rotation and you get that each step is 6 degrees.  So in order to turn the motor 6 degrees you would turn it 6 steps.  This also allows you to keep track of angular velocity.

When I control motors I normally create an array of the different parts of the cycle then loop through the array.


message:
Problem with LCD keypad shield and Arduino Uno R3

I have a problem with powering my LCD Keypad Shield from a DC cable (4 AA batteries or 9V battery). Everything looks good, but the LCD screen doesn't display anything. When I used a USB cable, the screen works as it should.

What is the problem?

body: I do not have an answer... but it might be power consumption problem, ou voltage stability problem. I use a LCD shield with an RFID card reader (contactless card reader like you can find in the subway). When I plug the thing to a 9v battery the contrast is higher than when I connect it to an USB cable.


message:
H-Bridge vs Motor shield for the arduino

Assuming we wish to control a small toy car with an arduino - meaning spinning the right and left wheels forward and backward and being able to break and control the speed, where each wheel has it's own engine (but of course two engines on the same side will run on the same speed and direction).

We saw we have two main options - Buying and wiring up a H-Bridge or buying a motor shield (which is based on one).

Are there any advantages for using a motor shield?

Thanks in advance.

body:
If I were a beginner, I'd go with the Motor shield.

I'm even personaly using the one from DfRobot, which as @Gerben said, is just plug and play.

It also allows you to select the input power for the motors, which can be either from the 5V Arduino pin or from an external battery. This is pretty convenient if you need more than 5V to power up your motors. It can also support 2A of current draw, which is more than enough for small arduino toy cards.

Here is the shield: https://www.dfrobot.com/index.php?route=product/product&product_id=1180&search=2A&description=true


message:
where to syphon off voltage from a 25 pin serial?

I have a mircocontroller that's looking to be powered by a 5v source.

I am trying to 'cypher off' some of this power from a 25 pin serial port, which is being powered by a constant power source.

Are there any pins that could give me that sort of voltage, or enough to power the board?

![enter image description here][1]

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

Please note, I'm **not an electrical person** at all, and so hope this is actually possible (otherwise my 3 months + program's work doesn't really add to anything).

I've tried a 9v battery, but it didn't seem to hold its charge?

I'm reading these labels going "what the ..." so you can probably tell coding the board wasn't the easiest, either.

**Edit History**

 - *I would like to clarify this is an **existing serial lead***
 - *I understand this may be deemed verging off topic,* *but due to the need to 'power' a* *microcontroller, I thought this could be answered here*
 - *If this isn't possible, (as an alternative, possibly) would a 9V/battery be able to power this board reliably for around 2-3 weeks?*

body:
You should be able to use pin 7 for negative, 9 as positive, this gives you 12 volts.

YOU MUST NOT HOOK THIS UP DIRECTLY to the arduino, connect it to a plug for the power jack (right of the USB connection).

If you are using a USB -> serial adapter, then the voltage may be 5v, but don't count on it.

Of course, USB is always going to be better!

PS - if you draw more power than the serial port is rated for, you will probably destroy the card. In most cases, this will be the motherboard. You are unlikely to be able to find out what it is rated for (look for Amps or A, or milliAmps  mA, or microAmps uA). The Arduino (with NO inputs or outputs, and idle) running from a 9v battery will draw about 50 milliAmps.


body:
In a lot of further research, I have discovered that 'It doesn't really matter' what the serial port diagram says, since in 25 pin serials (and 9 pin D-subs), it all depends on the circuit at the other end, showing which wires are actually '*connected*', or '*used*'.

***********

I managed to get *some* current from +pin 6 -pin 5 in which allowed me to draw *some* current, but have chosen to go with a (PP3?) 9v battery instead due to its reliability.

**************

So, in conclusion to this question, there isn't a specific answer, since it all depends on how the serial at the other end is wired.

It seems to me that in my case, there were minimal wires actually connected, so I was forced to look for other means of connecting to a 'reliable' power source.


message:
Arduino Uno synthesizer - Line Level (audio) output to mixer/amplifier

Is using PWM tones from Arduino amplified by a HiFi amplifier safe? Can I damage the amplifier or speakers because the PWM signal is not a "real" audio signal? Taken in consideration that I do not clip the signal and using a RC Low Pass Filter to filter out inaudible frequencies and using a LM386 amplifier chip to amplify and control the volume?

I am developing a synth/sampler project based on the Arduino Uno r3. This is my first electronics project ever and because of that reason I have some questions which I can't find a definite answer for on internet.

The synth has two function. It has a tone generator using the ToneAC library. With code I have mimicked LFO and VCO functions, using potentiometers I can adjust the frequency and LFO speed realtime. The other function is that I can trigger samples stored on a SD card using the TMRpcm library. The lowest frequency which can be played is 100hz and the highest 3100hz.

The device will be used in nightclubs on high end sound-systems and PA. I am afraid I will damage the equipment with my device because I do not send a pure audio (AC?) signal.

Currently the flow is like this:

PWM output (pin 9, 10) -> voltage divider to 2.5v -> RC Low Pass Filter 15Khz -> LM386 amp with volume control -> mono jack output -> mixing desk -> amplifier -> speakers

*(the TMRpcm and ToneAC library share the same pin (9), I have fixed this by disabling the TMRpcm when the ToneAC is playing and vice versa. The mono jack is wired as follow. pin 9 goes to plus side of mono jack output, pin 10 to negative side. The TMRpcm pin 9 also needs to go to plus side of mono jack output, and mono jack negative needs to go to ground. Because I disable the ToneAC at that time I consider port 10 grounded because it not generating any sound so there is no signal/voltage running out of it, aka the IO pin is set to LOW)*

I am hoping that using the voltage divider I am within range of the Audio Line levels of a default mixers Line-IN (like Pioneer, Behringer, etc). The RC Low Pass Filter is used to filter of inaudible frequencies and clean up the sound a bit, the LM386 audio amp is used to amplify the signal and (hopefully) make it a real audio signal.

Because I lack a lot of knowledge in this field and because I do not own a oscilloscope I can't say for sure if my output signal is harmful for the equipment and was hoping to get some guidance on my project on this forum.

body:
In theory, the peak signal accepted from your amplifier should be 0.894V p2p if you want to rescpect the common -10dB signal strength/level. I don't know why you would want to have a 5V to 2.5V "voltage divider" in the first place, but in any case if you use that you already limit the current probably enough, it all depends on the resistor values used.

Using the LM386 amplifier is also simply not required at all, since the Arduino is already providing more than enough power. If you want to tune the volume at that stage, simply combine all functions (volume, low pass and current limit) by connecting the 5V PWM output thru a resistor (eg. 4k7) to a POT (eg. 1k) in parallel with the capacitor (eg.2n2) would give you approximately what you want. Then to remove de DC component, add a series capacitor (eg. 1uF) and you're all set. You may still hear a "click" when you connect it to the amplifier though, so keep the faders low when connecting.

Of course you can adapt the values quite liberally, but these values are both safe and should be close to what is needed (cutoff 15kHz, Vpp 0.88V max).


message:
Connect Arduino to Galaxy S2 using USB OTG

I want to connect an Android Galaxy S2 phone to my UNO Arduino using USB OTG functionality.
I can upgrade/root the android to any version I want. My goal is to be able to communicate between the devices (send/receive data).

I've tried to search for whether that's possible but found conflicting answers whether Galaxy S2 and the Arduino UNO would be able to be connected this way.

Anyone knows whether this is possible? If yes - Do I need to do anything special - such as rooting the device, flashing it to a certain rom or something like that?

Thanks in advance!

body: If you use a bluetooth serial module - e.g. google hc 06 - you can do it wirelessly. I have a had good results with this - you can hook it up to pins 0 & 1, then use the stock arduino serial code. Probably not a good idea to hook up to both the bluetooth module and the USB (e.g. for programming) at the same time, they may interfere with each other.


body:
**Method 1.** Basically you do not need root permission to communicate over USB. I am making app for Android for my project and using this [FTDriver][1]

**Method 2.** If you are not programming in JAVA then you can try third party apps like:

 - [Arduino Uno Communicator][2]

Uno doesn't have FT232 chip so I found it a bit harder. So instead I have FT232 chip and use `SoftwareSerial`.

**Method 3.** To communicate with Arduino you can use Bluetooth with HC-06 module. There are lots of third party apps to connect and send/receive data. [Bluetooth Terminal][3]

  [1]: https://github.com/ksksue/FTDriver
  [2]: https://play.google.com/store/apps/details?id=com.primavera.arduino.listener&hl=en
  [3]: https://play.google.com/store/apps/details?id=Qwerty.BluetoothTerminal&hl=en


message:
OSC parsing code. Can it be optimised?

I'm using this [OSC library][1] and [TouchOSC][2] to controls some motors.
Right now I'm receiving those two kind of messages:

    /u/1       // move motor 1 of default steps
    /u/2       // move motor 2 of default steps

    /u/1/5     // move motor 1 of 5 steps
    /u/3/25    // move motor 1 of 25 steps

and so on.

Right now I have this piece of code:

    void loop() {
      OSCMsgReceive();
    }

    void OSCMsgReceive() {

      OSCMessage msgIN;
      int size;
      if ((size = Udp.parsePacket()) > 0) {
        //Serial.println("incoming message.. ");
        while (size--) {
          byte n = Udp.read();
          msgIN.fill(n);
          Serial.print((char)n);
        }
        Serial.println();
        if (!msgIN.hasError()) {
          msgIN.route("/u", up);
        }
      }
    }

    void upValueExtraction(char *ca, int &num_motor, int &num_step) {
        String s = String(ca);
        String num_motor_s = "";
        String num_step_s = "-1";
        int n = 0;
        for(int i=0; i<s.length(); i++) {
          char c = s[i];
          if(c=='\\') {
            n++;
          }
          if(n==0) num_motor_s += c;
          if(n==1) num_step_s += c;
        }
        Serial.print("num motor: "); Serial.println(num_motor_s.toInt());
        Serial.print("num step: "); Serial.println(num_step_s.toInt());

        num_motor = num_motor_s.toInt();
        num_step = num_step_s.toInt();
    }

    void up(OSCMessage &msg, int addrOffset) {
      static boolean flag = false;
      if (!flag) {
        Serial.print("route: up "); Serial.println(addrOffset);

        char ca[200];
        msg.getAddress(ca, addrOffset+1);

        int num_motor, num_step;
        upValueExtraction(ca, num_motor, num_step);

        if(num_step==-1) {
          num_step = defaul_steps;
        }

        Serial.print("Have to move motor n ");
        Serial.print(num_motor);
        Serial.print(" of step ");
        Serial.println(num_step);
      }
      flag = !flag;
    }

Even if it is working and even if I'm using an Arduino DUE (much more memory then the UNO) I think it can be optimised.

Does it contains some leeks? How can I better use the OSC matching part of the library? Any kind of "embedded c++" guidelines? Can I do everything inline without a `ca` char array and `s` String variables? Is better to use Arduino Lib `String` class or plain old C str* functions? Any kind of comment?

Thanks in advance.

  [1]: https://github.com/CNMAT/OSC
  [2]: http://hexler.net/software/touchosc

body:
OSC is such a simple format that I ended up ditching libraries entirely, and just parsing the UDP packets directly with a state machine.  Just learn the wire format of the bytes and parse the state machine explicitly.

It's just a trivial function calling format.  The message starts with a 32-bit padded zero terminated string (important!) for the method name.  I am not sure if the type tag is mandatory but it was always being sent (ie: ",iff"), then the binary values corresponding to what type tag says - like bigendian int32,float32,float32.

This was related to OSC generated by ChucK, SuperCollider, and CSound.

Real optimizations would come just from the design of the protocol itself.  You will need to assume that any UDP packet can be dropped.

You are sending motor changes as diffs from current position, so you need to handle packet drops somehow.  (ie: Do you have a TCP-like mechanism?  Do you change the design to send absolute motor positions so that position reports are idempotent and subject to re-broadcast?  Do you ack message receipt individually, or do you periodically poll the device for its current state?)


message:
how to know which pin is being used, change pin?

i am having an issue where i am unsure how my device knows what pins its using. Version #1 is a timeclock which is simply declared with no pin numbers. Version #2 is a simple loop with a device on pin A0;

So how can i set / change the pins for the clock to use. Currently it is on A4 & A5.

If i wanted to move the clock to say pins.. A1 and A2, how would i do that?

Thanks

Version #1-------------------------------------------------

    // Date and time functions using a DS1307 RTC connected via I2C and Wire lib
    #include <Wire.h>
    #include "RTClib.h"

    RTC_DS1307 RTC;

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

      if (! RTC.isrunning()) {
        Serial.println("RTC is NOT running!");
        // following line sets the RTC to the date & time this sketch was compiled
     //   RTC.adjust(DateTime(__DATE__, __TIME__));
      }

    }

    void loop () {

        DateTime now = RTC.now();

        Serial.print(now.year(), DEC);
        Serial.print('/');
        Serial.print(now.month(), DEC);
        Serial.print('/');
        Serial.print(now.day(), DEC);
        Serial.print(' ');
        Serial.print(now.hour(), DEC);
        Serial.print(':');
        Serial.print(now.minute(), DEC);
        Serial.print(':');
        Serial.print(now.second(), DEC);
        Serial.println();
        delay(3000);
    }

Version #2---------------------------------------------------------

    int powerswitch1 = A0;
    void setup()
    {
    pinMode(powerswitch1, OUTPUT);
    }

    void loop ()
    {

    digitalWrite(powerswitch1, HIGH);
    delay(500);
    digitalWrite(powerswitch1, LOW);
    delay(500);
    digitalWrite(powerswitch1, HIGH);
    delay(500);
    }

body:
Your confusion is over the multiple functions of analog pins A4 and A5.

In addition to being analog pins, they are also the pins configured internally for I2C/TWI serial, which is interfaced with using the Wire library on arduino. Since those are the only two pins Wire can use, there is no need to specify them, the sketch just calls `Wire.begin()` to set everything up.

If you need a second I2C device you can simply connect them both up to A4 and A5 at the same time, the protocol is designed to support that kind of thing. If you need to use A4 and A5 for something else besides I2C, you can't continue to use the hardware I2C library.

It is possible to use a software implementation of I2C/TWI serial on other pins, but usually soft-serial implementation have some drawbacks compared to the hardware version. There is an implementation on the arduino playground here: http://playground.arduino.cc/Main/SoftwareI2CLibrary

That said, the RTC library you are using seems to internally use the Wire library, so it would take some hacking to switch it to a different I2C implementation.


message:
Can't store temperature in variable ( for further processing)

I am trying to store temperature data in a variable, so that I can use it for making a JSON object, but the problem is, that when I try to store the temperature in a variable, it prints out the wrong value. I'm using a DHT11 temperature/humidity sensor and a library for calculating the temperature.

    Serial.print("Temperature (°C): ");
    Serial.println((float)DHT11.temperature, DEC);
    int temp1 = ((float)DHT11.temperature, DEC);
    Serial.println(temp1);

These 4 lines is printing out this:

    Temperature (Â°C): 23.0000000000
    10

The first one is correct, but the second line should also be saying "23".
I have tried only loading the data in once with the library, as in outcommenting one line, but that does not work.
It's like I have some syntax wrong, but I can't figure out what.

body:
This line:

>     int temp1 = ((float)DHT11.temperature, DEC);

casts `DHT11.temperature` to an `float`, throws away the value, then assigns `DEC` to `temp1`. That is not what you want.

>     int temp1 = DHT11.temperature;


message:
Throughput and BER test with nRF24L01+ radio and Teensy microcontroller

I am trying to modify the example given in the [this page](http://shanes.net/another-nrf24l01-sketch-string-sendreceive/) to a basic throughput and BER test with two nRF24L01+ and Teensy 3.0 modules.

I want to modify the nrf24l01_send_string example in a way that I can remove the powerUp powerDown and delay and transmit the next packet purely based on the ACK received from the receiver. The problem is [RF24 class](http://maniacbug.github.io/RF24/classRF24.html) does not seem to have a method to transmit ACK (not ACK+Payload) and the datasheet does give any information on the structure of the ACK message. The example works when powerUp and powerDown are removed, but I need to modify it to measure throughput by removing the delay.

body:
@Gerben remarked:

> You can't send the ACK manually. The module itself sends the ACK
> automatically (if enabled that is), once it receives the package. This
> way the sending module only need to be listening for the ACK for the
> shortest amount of time, reducing power usage. To attach data to the
> ACK package you need the writeAckPayload function. But you have to
> prepare this before any package is received


message:
Arduino RF24 library Delay after write function causes no byte availability

It's about the RF24 library you can find here. http://maniacbug.github.io/RF24/index.html

I transmit data from one Arduino to another using NRF24L01 radios.
When I use the write-function on the transmitter arduino (joystick is an array) and after that I put in a delay higher then 10, the available function returns false.

Transmitter

    radio.write( joystick, sizeof(joystick) );
    delay(20);

Receiver

    if(!available())
      print('No data'); // delay > 10 --> No data will be printed

Why is it working with a delay of 10 but not above? Has it something to do with timeouts which is mentioned in the docs of the library?: http://maniacbug.github.io/RF24/classRF24.html#a4cd4c198a47704db20b6b5cf0731cd58

Thank you for your answers.

body:
Please read this: https://arduino.stackexchange.com/questions/4509/arduino-nrf24l01-arduino-to-netmf-transmit-issue?rq=1
Although you are not using NETMF, @PhilVallone uses the library and chip together successfully, points out the samples are not asynchronous, and addresses time-out. The OP for that question is using delay(1000) and no answer has been accepted.


body:
Try updating your library to the new TMRh20 fork. That improves the old maniacbug's version a lot (possibly also fixing the bug). tmrh20.github.io/RF24

It's also worth noting that after you've read the message, it will print out "no data" until you receive new message.


body:
I had the same problem. My solution is:

First make `.stopListening()`

then `.write(&data, sizeof(data))`

and behind the `write` command an `.startListening()`.

Now you can delay for longer times.


body:
In my situation the issue was with the Transmitter not continuing to transmit after a delay. I was able to resolve the issue using the powerDown (http://maniacbug.github.io/RF24/classRF24.html#aa0a51923a09ba4f3478aba9be0f8a6a1) and powerUp (http://maniacbug.github.io/RF24/classRF24.html#a5cdaf47aa0edd6dca1b9a8bb7972a1a3) functions. Here is a snipet of my code. "radioTx" is the name assigned to my transmitter.

    //standard code setup for arduino uno board examples
    radioTx.begin();
    radioTx.setChannel(108);
    radioTx.openWritingPipe(pipe);

    }

    void loop() {

      int dist_cm = sonar.ping_cm();

      Serial.println(dist_cm);
      radioTx.write(&dist_cm,sizeof(dist_cm));
      radioTx.powerDown();
      delay(5000);
      radioTx.powerUp();

      }


body:
Try using

    unsigned long t = millis();
    while(millis() - t < DELAY);
instead of "delay(DELAY)"


message:
Arduino cannot communicate with PC after running servo

I was messing around with my arduino uno r3 and servo today. The book I got said to run the servo through the arduino. Everything was fine. I started changing the code, and then things started to get bad. I noticed that if I did not put a delay in between the servo movements, the board would freeze, and I would have to get lucky. Well now I just can't communicate with the board. I plug the board in to my pc, windows 7 makes the connection sound, the board turns on the ON light, the L light flashes, then goes steady. In the arduino software, the COM3 port, which is where I'm plugging it in, is not coming up. Only COM1 is there. I'm not sure what to do. The board is still functioning, the servo moves. I tried to plug it in with a different port and with the servo disconnected but it still doesn't want to communicate with my pc. The code I'm using is below

    #include <Servo.h>

    Servo servo1;

    void setup()
    {
      servo1.attach(9);
    }

    void loop()
    {
      servo1.write(50);
      delay(500);
      servo1.write(90);
      delay(500);
      servo1.write(140);
      delay(1000);

      for(int i = 50;i<140;i+=10){
        servo1.write(i);
        delay(10);
      }
    }

I would also like to add that I understand that you shouldn't run the servos through an arduino. I was following the book, and began researching when things went down hill.

body:
I've had some problems in the past reprogramming my Arduino Uno if it writes to the serial port - I don't know if the problem is the same, but here's how I got around it:

Option 1: Hold down the reset switch, then plug your Arduino into the USB port. Select the right COM port (if needed), compile your code (something ultra simple, e.g. blink led), and then, JUST BEFORE IT STARTS UPLOADING, release the reset switch. Wash, rinse, repeat, until you get it to work, through blind luck.

Option 2: Get hold of a ICSP (such as the one I got, USBASP made by FreeTronics  http://www.freetronics.com.au/products/usbasp-icsp-programmer-for-avr-arduino#.VL8Vv3WjlIc which I am v. happy with), plug it into the serial port, plug the other end onto your Arduino UNO ICSP header (6 pins, opposite end of the board from USB), then select Tools -> Burn Bootloader. Overwrites any program, works 100% of the time. Now you can unplug your USBASP, and plug your Uno back in and program it normally. This is also a great tool if you end up using AtMega (or AtTiny) chips directly (AtMega is the chip used to do all the work on the Arduino).

To avoid this, I have gotten into the habit of putting a 5 second delay as the first thing in the startup code.

FOR FUTURE GENERATIONS: I got mine here in New Zealand, so that will probably not help most people. FreeTronics makes them, and I am very happy I got their one (they have a "slow clock" jumper that is very convenient when programming Atmel chips not on an Arduino board), I expect that any USBASP would do the trick too - in response to the question, Amazon has a couple under $4, and I expect that the price will not go up.

Search for "USBASP". Make sure you get a ribbon cable. For Arduino Uno, you need a 6-pin ribbon cable. It is also possible to use these cables to communicated directly with a running Arduino over these same pins.


message:
Is this Bluetooth module cool for Arduino?

I am making a basic project that will have 4 or 5 arduino nodes. Each arduino will have a bluetooth module attached. The thing I want is, I want to be able for each one of these arduinos to know the other is present in the room (let's say, 5 meters). For my experience in the cellphone, I don't even have to pair bluetooth devices to know about their presence, as long as they are in visible mode. Since I just need to know their presence, and no exchange of information will ever happen, I probably will never have to pair them right?

For this project I need a bluetooth (BT) module that:

1) Enables me to change the ID of each arduino, so that, even if I use my cellphone to scan for BT devices I will see (Arduino1, Arduino2, etc...) instead of default-factory-names.

2) Enables me to scan around for existing devices every time each X seconds, because I want each arduino to know if the others are in the room.

Will this module do the trick? http://www.ebay.co.uk/itm/Interface-Base-Board-Serial-Transceiver-Bluetooth-Module-For-Arduino-UNO-R3-/111482008102?pt=UK_BOI_Electrical_Components_Supplies_ET&hash=item19f4d87226

Later I will probably hang around with batteries so I will want a low power BT module, having the same 2 capabilities mentioned. Will NRF8001 do the trick for me? http://www.nordicsemi.com/eng/Products/Bluetooth-Smart-Bluetooth-low-energy/nRF8001

Thanks!

body:
From skimming that post, I believe that your linked pcb is not a full bluetooth module (note how there is no bluetooth chip or antenna of any kind). This is simply a "base board," which is why it is so cheap1.

You will need [something like this](http://www.ebay.com/itm/Wireless-Serial-4-Pin-Bluetooth-RF-Transceiver-Module-Backplane-RS232-F-Arduino-/261024370087?pt=LH_DefaultDomain_0&hash=item3cc643cda7) that actually has the components you want.

To answer your questions:

1. The bluetooth library for arduino sets the discoverale name to ARDUINOBT by default, but that can be changed in the setup() method.
2. "scan around" is a little ambiguous—AFAIK, bluetooth can only connect to one device at a time, but I'm not sure if that's totally true. You may want to look into using radios instead of BT, as they can communicate more freely with one another, are extremely cheap, and have extensive arduino libraries availible. I'm currently working on a project that uses the [nRF24L01](http://www.ebay.com/itm/2PCS-Arduino-NRF24L01-2-4GHz-Wireless-Transceiver-Module-New-/170819064718?pt=LH_DefaultDomain_0&hash=item27c59c138e), and I'd be happy to answer any questions you have about it.

1: It also has a draw of 6v VCC, which is more than the Uno can output.


body:
The first link is for a **breakout board only** - it has a **placeholder** for a BT module, similar to the [HC Bluetooth models series][1], but it is n*ot a complete Bluetooth board* (hence the "Interface Base Board" in the product's title). Please do not do that mistake - I did it already :)

For your purposes, it seems that something similar to the cheap [HC-05][2] can satisfy both requirements: You can change the device name, and perform inquiry to scan other Bluetooth devices' MAC address, both using AT commands.

It has low operation voltage (1.8v-3.6v), but it operates as the good-old 2.1 Bluetooth standard, which waste a LOT of energy while running. If power consumption is a prime requirement, you might want to consider the more expensive Bluetooth low energy, such as a breakout board for the chip you suggested (the NRF8001).

  [1]: http://www.rcscomponents.kiev.ua/datasheets/hc_hc-05-user-instructions-bluetooth.pdf
  [2]: ftp://imall.iteadstudio.com/BLOG/2010_07/More_Powerful_Serial_Port_Bluetooth_Module_MasterSlave.pdf


body:
Should've been a comment, but...

First of all, your questions 1 and 2: yes, that can be done.

I'd go for a HC-05 just like Omer suggests. And if you want to pair them, it is perfectly possible to pair one master with several slaves. Depending on implementation, a slave can connect to several masters too. The HC-05 can switch between these modes.

You can't do it with a NRF8001, as this is a BLE slave device only, it won't do scanning. Try to find a device that can do both, like [BLE mini][1].

You can't mix BLE and Bluetooth devices for this, it's either or.

  [1]: http://redbearlab.com/blemini/


message:
Lowest power possible in Arduino

I have googled all around and I know about some tricks to make ATmega328 not being a power hog. I am using **Arduino Nano V3.0**.

However, I didn't find out what is the minimal consumption possible with it?

My project consists of an Arduino that will wake up each 10 seconds and, by bluetooth (BT) will scan for existing devices, and if one specific device is not listed, it will lit a LED for 5 seconds and then go to sleep again.

In sum:

1. Sleep for 10 secs

2. Wake up

3. Scan for BT devices

4. If device ABC is in the list go to 1.

5. Lit LED

6. Delay 5 secs

7. Go to 1.

For bluetooth I will use **NRF8001**, because it is the most efficient BT module I know so far.

Can you give me some ideas of what tricks should I use to make this ATmega328 and BT module last like one year with a **500mAh battery**? Has anyone tried this that can share his experience? Is ATmega328 the right uC for this? I am using it just because I already have code/libraries for it.

---------------

> Creating the new tag 'nrf8001' requires at least 150 reputation. Try something from the existing tags list instead.

body:
Lowest possible power consumption for an Arduino is 0mA - just disconnect it's Vcc :)

And seriously, when there are many factors involved, it is hard to include all of them into the proper equations, considering different factors that affect the current consumption such as temperature, humidity, quality and distance of the wires etc. Best would be to perform measurements of the power consumption for, say, several cycles of steps 1 to 7, and do the average.

Remember that the ATmega chip will draw more current depending on the voltage, so you might want to keep voltage as low as possible.

[Here is a nice project][1] of an ATtiny (Arduino alike) that runs on a coin CR2032 battery (~200mAh) for **220 days** until it died, while wirelessly broadcasting the results and the measurements of the battery discharge rate, so you could actually achieve pretty good results working with a 500mAh battery.

  [1]: http://harizanov.com/2012/10/funky-as-remote-temperature-sensing-node-with-ds18b20/
  [2]: https://i.stack.imgur.com/tjDfZ.png


body:
The issues regarding efficiency of power are:

 1. The CPU speed
 2. The Voltage
 3. The Power Regulator (not supply)
 4. The Peripherals

Address each one of these and don't over look any of them. Or any sub component. But note that some are more impacting than others.

 1. while it is possible to lower the speed, It is more practical to just sleep. As you have indicated you are going to do.

 2. Running at 3V instead of 5V is a big savings. Note that the 328 can run as low as 1.8V

 3. DON'T use Linear Regulators. Most all Arduino's have a 7-12V to 5V(or 3.3V) Linear Regulator. This just burns the difference between the supply (aka battery) and the VCC, used.

 4. pay attention to the peripherals. Likely this means getting rid of not needed devices. Example the USB to Serial chip that exists on the Nano. What is the lowest voltage can the radio run at? Must it run at a regulated voltage. Use the largest possible resistor values. Such as on pull ups. A 500K pull up will draw less current than a 10K. Where if too big any capacitance may slow it down. Which is likely acceptable.

One of the biggest savings is running directly off of the Battery without a Linear Regulator. Where the ATmega328P can run from 3V down to 1.6V. It would be recommend to use the Brown Out detector.

Also note that ALL batteries have a self discharge rate.  This will determine the maximum possible life of the battery, then minus your devices consumption.


body:
Read the link in @j-g-faustus 's comment - very thorough. http://www.gammon.com.au/power - it starts with a stock board running at 50milliAmps and ends up at 0.002 milliAmps.

You will also need to find out the power consumption for your BT module - this may dwarf the power arduino's power consumption. The same goes for the LED.

Normal LEDs run at about (ballpark!) 20 milliamps - this means that on the coin battery mentioned by @Omer, 200milliAmp-hours/20 milliAmps = 10 hours of led light.

You can measure the power draw with a multimeter; stick your probes between the + of the battery and whatever the battery would normally connect to (you will have to disconnect the battery of course) - if using a 9v battery, plug in the negative, disconnect the positive, turning the snap connector 90 degrees; then you can put one probe on the battery, the other on the (open) snap connector. Measure Arduino awake + led on + BT connected and sending data. Measure again with everything off/idle/sleeping. Work out how much time it will spend in each state; this will give you an average number of milliamp-hours.


body:
These are essentially notes in support of other answers:

One year = 8765 hours.

So average drain for 1 year life from 500 mAh
= 500 mAh/8765h
= 57 uA average.
To get one year on a 500 mAh battery you need to have average drain under say 50 uA

An efficient modern LED
is usefully bright at 1 mA and
probably very acceptable at 0.1 mA.

Best LEDs are 30 Cd+ at 20 mA
so 150 mCd mean at 0.1 mA
and your eye-brain sees more like the peak.

0.1 mA at 1% duty cycle for one year
= 8765 x 0.1 x 1/100
= 8.765 mAh
or about 2% of your battery capacity.


body:
For simple applications like this, you might find it more convenient to use a smaller board/MCU from the Arduino system. For example the [Digispark] uses an [ATtiny85] rather than the standard [ATmega328P]. It's not clear that the MCU itself would use much less power (it's pretty much the same CPU core, after all, though you are powering less RAM) but the board has only the one MCU and the regulator on it. You can still power it from and program it via USB (at 5 V) for development, but for production use you can (as others have mentioned) provide 1.8 V power on the VCC line, ignoring the regulator, and you will not have to worry about the power usage of things like the USB interface (an FT232 on the Nano, but a whole second microcontroller on some other boards!) and other parts on the Nano.

[Digispark]: http://digistump.com/wiki/digispark
[ATtiny85]: http://www.atmel.com/Images/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf
[ATmega328P]: http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf


body:
[Easy Very Low Power BLE in Arduino][1] covers using Arduino IDE and nRF52832 chips to code very low power projects, i.e. <100uA continuously, waiting for connection or while connected and sending data.

The <100uA current is at max tx power and can be further reduced by reducing Tx power and increasing the advertising and connection intervals.  Ignoring the LED, you should be able to get close to the 1year on a 500mAH battery.

Currently working on adding two small solar cells (50mm x 30mm) to extend battery life.  These cheap cells ($0.60) don't need full sun and work well in the shade or out of the sun near a window or under a desk lamp.

  [1]: https://www.forward.com.au/pfod/BLE/LowPower/index.html


message:
How to "implement" an Arduino prototype?

I am starting with Arduinos, coming from the world of Linux (with the RPi as a bridge) and after having tested some setups I now wonder where to go next in implementation.

What I am trying to understand is whether it is recommended (time and cost-wise)

  - to create a standalone, circuit-board based version of whatever I prototyped on the breadboard, with a micro-controller with connections trimmed down to what is needed for that specific setup?
  - or rather just look at neatly packaging the Arduiono with the breadboard and wires in a case?

I expect to build 5 or 6 of the same simple setups (to put in various places in my house).

Note: there is a [similar question][1] (with almost the same title) but it deals with the legal aspects of commercializing a setup.

  [1]: https://electronics.stackexchange.com/questions/64280/what-make-now-that-i-have-implemented-a-working-prototype-of-my-system

body:
> with the breadboard

That phrase right there makes the solution a non-starter. Solderless breadboards are good for prototyping, but are too fragile for use in a final project.

As for whether or not you should use an actual Arduino or reduce the circuit to a minimum, that is between you and your wallet. It is possible to make a basic AVR board (including MCU) for under $6 in parts, but the time investment is not entirely trivial.


body:
I started using an Arduino (Uno), and a solderless breadboard, to do my prototyping.

After the 2nd project, I started programming the Arduino, then pulling the AtMega chip off the board (if you have a through-hole chip rather than a surface mount one) and plugging that into my breadboard (you will need some supporting circuitry for this - a clock and a powersupply e.g. batteries). The AtMega has a larger range of voltages than the Arduino, and can be run up to 20mhz. You will need to jiggle some constants for this, or be ready for your delays to run quicker too.

I have since bought an USBISP (see Google), which can be hooked up to the Arduino board (there is a 6 pin header made for this, on the opposite side to the USB), or can be hooked up to specific pins. With this, I have started programming AtTiny chips - smaller, easier to set up, fewer pins to interface with, and really, really cheap!

All my long-term projects are on veroboard (see Google) - solder everything on, then cut it to the size you need. It's worth spending time before you solder working out your layout.

If you want to produce these in bulk, I would suggest getting some prototypes on veroboard first (you will, invariably, make changes once you start testing!), then when you're happy, you can copy the veroboard design (possibly tweaking it to optimize for greater flexibility), and order PCBs from a company that does this sort of thing.

Good luck!


body:
> What I am trying to understand is whether it is recommended (time and cost-wise) to create a standalone, circuit-board based version of whatever I prototyped on the breadboard, with a micro-controller with connections trimmed down to what is needed for that specific setup? or rather just look at neatly packaging the Arduiono with the breadboard and wires in a case?

Given what is available in assembled form, using a complete commercial product per project would make most sense except where you are building in substantial volume.

Because ...

I am using [Arduino Nano 3s from China](http://www.aliexpress.com/store/product/Freeshipping-10PCS-LOT-Nano-3-0-controller-compatible-with-arduino-nano-NO-CABLE/213957_1511622386.html) which cost me $US3 each in quantities of 10 with free postage (takes 2 to 3 weeks to arrive here at the bottom of the world) and I see that the same people are now charging $2.85 each in 10's. There are numerous suppliers of similar products and I am only mentioning these as I have had good results from them and the quality is acceptable.

You would probably have trouble buying just the parts for the cost of a $3 assembled working Nano and you'd need to cost your time at $0/hour. Building your own for the experience, or if you are using many and you want a cut down subset and really must get the price well under $3 MAY make sense.

The same people also sell an [**Arduino Pro mini**](http://www.aliexpress.com/store/product/10Pcs-Lot-Pro-Mini-Module-Atmega328-5V-16M-For-Arduino-Compatible-With-Nano/213957_1432639609.html) for $US1.85 in 10s free postage (ie $18.50 for TEN). You need to use a plug in USB module to program these via USB. I bought some of these as well - also good, but the convenience of the always available USB makes the Nano preferable (to me).

Note: USB cables cost extra !!! :-)
_________________

**Related:**

Some people have expressed reservations about buying Asian source Arduinos and suggest people should support either US fronted companies or the Arduino's originators.

I appreciate the merit of supporting the people who have put the effort into the system, but the system is very very consciously open source in all respects - and in fact code samples that come with the IDE are expressly Public Domain. (Documentation is CC by SA ...). If open source is to be truly meaningful it needs to be able to survive being truly so. Unlike many other products where Asian copies may have suspect IP legacies, the Arduino products are wholly legitimate (as far as I know).

 I have not pored over them in detail (yet) but I note that the 5V voltage regulator on the Chinese ones is an LM1117 (LDO LM317-like) as opposed to the original LM2940. The USB bridge ICs are, as is well known, not "genuine" FTDI parts but Asian semi-equivalents which, with their own drivers, work well enough in this context.

You can certainly buy low cost rubbish versions from Asian sources, and part of the open source tradeoff is deciding where you do and don't get value for money overall.


message:
Does the map() function works on an ATtiny85?

I have a working project on Arduino Uno.Now I want to shrink my project using an ATtiny85. Before purchasing an waiting for the shipment to arrive, I want to make sure that my whole code will run on ATtiny85.

specialy, will the map() function which is working on  an Arduino Uno ( ATMEGA328P-PU ),  work with a ATtiny85 Microcontroller?

body:
The `map` function uses integer arithmetic, and since the ATmega series and the ATtiny series use the same 8-bit AVR instruction set, there should be no difference when using it, and you are good to go from that aspect.

Consider that there are many other differences regarding I/O pins, storage etc. - that you might want to consider. [Here is a good source][1] for a basic comparison between the ATmega based Arduino to ATtiny85.

  [1]: https://goddess-gate.com/projects/en/arduino/attiny85vsatmega328


message:
Arduino + WizFi 210 (WiFi) HTTP POST

I would like to do an HTTP POST to Carriots. I saw a few tutorials.

Both of them are using ethernet instead of WiFi. I realize the ways of using Arduino WiFi shield and WizFi Shield are a bit different. What do I need to do to run a basic server using the WizFi Shield?

Code:

<!-- language: c -->

    /******************************************************************
     WizFiShield Web Client Test Example
    *****************************************************************/

    // WizFiShield communicates using SPI, so include the SPI library:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <SPI.h>
    #include <WizFi2x0.h>
    #include <WizFiClient.h>
    #include <TimerOne.h>

    #define SSID    "EricLeong3"        // SSID of your AP
    #define Key     "ericChoong91"  // Key or Passphrase
    // Wi-Fi security option (NO_SECURITY, WEP_SECURITY, WPA_SECURITY, WPA2PSK_SECURITY)
    #define Security        WPA2PSK_SECURITY
    #define APIKEY  "xxxxxxxxx" // Replace with your Carriots apikey
    #define DEVICE  "fypSensors@eric3231559.eric3231559"

    WizFi2x0Class myWizFi;
    WizFiClient myClient;
    TimeoutClass ConnectInterval;
    boolean Wifi_setup = false;

    ///////////////////////////////
    // 1msec Timer
    void Timer1_ISR() {
      myWizFi.ReplyCheckTimer.CheckIsTimeout();
    }
    //
    //////////////////////////////

    void setup() {
      byte retval;
      Serial.begin(9600);
      Serial.println("\r\nSerial Init");
      // initalize WizFi2x0 module:
      myWizFi.begin();
      ConnectInterval.init();
      // Socket Creation with Server IP address and Server Port num
      myClient =  WizFiClient("82,223,244,60", 80);
      // Timer1 Initialize
      Timer1.initialize(1000); // 1msec
      Timer1.attachInterrupt(Timer1_ISR);
      myWizFi.SendSync();
      myWizFi.ReplyCheckTimer.TimerStart(3000);
      Serial.println("Send Sync data");
      while(1) {
        if(myWizFi.CheckSyncReply()) {
          myWizFi.ReplyCheckTimer.TimerStop();
          Serial.println("Rcvd Sync data");
          break;
        }
        if(myWizFi.ReplyCheckTimer.GetIsTimeout()) {
          Serial.println("Rcving Sync Timeout!!");
          // Nothing to do forever;
          for(;;)
          ;
        }
      }
      ////////////////////////////////////////////////////////////////////////////
      // AP association
      while(1) {
        retval = myWizFi.associate(SSID, Key, Security, true);
        if(retval == 1) {
          Serial.println("AP association Success");
          Wifi_setup = true;
          break;
        } else {
          Serial.println("AP association Failed");
        }
      }
    }

    void loop() {
      Serial.println("apleleee ");
      uint8_t retval;
      retval = myClient.connect();
      if(retval == 1) {
        String json = "{\"protocol\":\"v2\",\"device\":\""+String(DEVICE)+"\",\"at\":\"now\",\"data\":{\"Air Temperature\":\"58\",\"Humidity\":\"59\"}}";
        Serial.println("Connected! ");
        //myClient.write((byte *)"GET /search?q=WizFi210 HTTP/1.0\r\n\r\n");
        myClient.write((byte *)"POST /streams HTTP/1.1");
        myClient.write((byte *)"Host: api.carriots.com");
        myClient.write((byte *)"Accept: application/json");
        myClient.write((byte *)"User-Agent: Arduino-Carriots");
        myClient.write((byte *)"Content-Type: application/json");
        myClient.write((byte *)"carriots.apikey: ");
        myClient.write((byte *)APIKEY);
        myClient.write((byte *)"Content-Length: ");
        byte thisLength = json.length();
        myClient.write(thisLength);
        myClient.write((byte *)"Connection: close");
        myClient.write((byte *)"");
        myClient.write((byte *)"{\"protocol\":\"v2\",\"device\":\"");
        myClient.write((byte *)DEVICE);
        myClient.write((byte *)"\",\"at\":\"now\",\"data\":{\"Air Temperature\":");
        myClient.write((byte *)"58");
        myClient.write((byte *)",\"Humidity\":");
        myClient.write((byte *)"59");
        myClient.write((byte *)"}}");
      } else
        Serial.println("Connection Failed");
      }

The response I get on the serial monitor

    Serial Init
    Send Sync data
    Rcvd Sync data
    AT

    Rcvd Reply: [ERROR]
    [ERROR]
    Timeout  with ERROR reply
    AP association Failed
    AT

    Rcvd Reply: õAT
    õAT
    -1

    Rcvd Reply: [ERROR: INVALID INPUT]
    [ERROR
    INVALID
    INPUT]
    -1

    Rcvd Reply: AT
    AT
    -1

    Rcvd Reply: [OK]
    [OK]
    ATE0

    Rcvd Reply: ATE0
    ATE0
    -1

    Rcvd Reply: [OK]
    [OK]
    AT+XDUM=0

    Rcvd Reply: [OK]
    [OK]
    AT+BDATA=1

    Rcvd Reply: [OK]
    [OK]
    AT+WD

    Rcvd Reply: [OK]
    [OK]
    AT+WM=0

    Rcvd Reply: [OK]
    [OK]
    AT+WPAPSK=EricLeong3,ericChoong91

    Rcvd Reply: Computing PSK from SSID and PassPhrase...
    Computing
    PSK
    from
    SSID
    and
    PassPhrase...
    -1

    Rcvd Reply: [OK]
    [OK]
    AT+NDHCP=1

    Rcvd Reply: [OK]
    [OK]
    AT+WA=EricLeong3

    Rcvd Reply:     IP              SubNet         Gateway
        IP              SubNet         Gateway
    IP
    SubNet
    Gateway

    Rcvd Reply:  192.168.1.42: 255.255.255.0: 192.168.1.1
     192.168.1.42: 255.255.255.0: 192.168.1.1
    192.168.1.42
    192.168.1.42
    255.255.255.0
    255.255.255.0
    192.168.1.1
    192.168.1.1

    Rcvd Reply: [OK]
    [OK]
    AP association Success
    apleleee
    AT+DNSLOOKUP=82,223,244,60,3,5

    Rcvd Reply: [ERROR: INVALID INPUT]
    Token: [ERROR

May I know what's wrong with the code? Why does it show a token error instead of success? What I am trying to do is posting an HTTP POST request to Carriots, which is a place to do my m2m things. I am still wondering which part I am missing. I referred to few sources such as

http://forum.carriots.com/index.php/topic/61-wireless-gardening-with-arduino-cc3000-wifi-modules/page-2

https://github.com/Wiznet/WizFiShield

body:
[The library provides an example for a server.][1]

Here's what it looks like:

    /******************************************************************
     WizFiShield Web Server Test Example

     A simple web server that shows "Hello World" string

     Circuit:
     WizFi2x0 connected to Arduino via SPI

     RST: pin 2  // Output
     DRDY: pin 3  // Input
     CSB: pin 4  // output
     MOSI: pin 11  // output
     MISO: pin 12  // input
     SCK: pin 13  // out

     Created 27 Sep. 2012
     by James YS Kim  (jameskim@wiznet.co.kr, javakys@gmail.com)

     Modified 27 May. 2013
     by Jinbuhm Kim  (jbkim@wiznet.co.kr, jinbuhm.kim@gmail.com)
    *****************************************************************/

    // WizFi210 communicates using SPI, so include the SPI library:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <SPI.h>
    #include <WizFi2x0.h>
    #include <WizFiClient.h>
    #include <WizFiServer.h>
    #include <TimerOne.h>

    #define SSID    ""        // SSID of your AP
    #define Key     ""  // Key or Passphrase
    // Wi-Fi security option (NO_SECURITY, WEP_SECURITY, WPA_SECURITY, WPA2PSK_SECURITY)
    //#define Security        WPA_SECURITY

    #define MAX_SOCK_NUM    4

    unsigned int SrcPort = 80;

    WizFi2x0Class myWizFi;
    WizFiClient myClient[MAX_SOCK_NUM];//(SIP, ServerPort);
    WizFiServer myServer(SrcPort);

    boolean Wifi_setup = false;

    ///////////////////////////////
    // 1msec Timer
    void Timer1_ISR()
    {
      myWizFi.ReplyCheckTimer.CheckIsTimeout();
    }
    //
    //////////////////////////////
    void setup() {
      byte retval, i;

      Serial.begin(9600);
      Serial.println("\r\nSerial Init");

      for(i=0; i<MAX_SOCK_NUM; i++)
        myClient[i] =  WizFiClient();

      myWizFi.begin();

      // Timer1 Initialize
      Timer1.initialize(1000); // 1msec
      Timer1.attachInterrupt(Timer1_ISR);

      myWizFi.SendSync();
      myWizFi.ReplyCheckTimer.TimerStart(3000);

      Serial.println("Send Sync data");

      while(1)
      {
        if(myWizFi.CheckSyncReply())
        {
          myWizFi.ReplyCheckTimer.TimerStop();
          Serial.println("Rcvd Sync data");
          break;
        }
        if(myWizFi.ReplyCheckTimer.GetIsTimeout())
        {
          Serial.println("Rcving Sync Timeout!!");
          return;
        }
      }

      ////////////////////////////////////////////////////////////////////////////
      // AP association
      while(1)
      {
        byte tmpstr[32];

        retval = myWizFi.associate(SSID, Key, Security, true);

        if(retval == 1){
          myWizFi.GetSrcIPAddr(tmpstr);
          Serial.println("WizFi2xo AP Associated");
          Serial.print("MY IPAddress: ");
          Serial.println((char *)tmpstr);
          Wifi_setup = true;
          break;
        }else{
          Serial.println("AP association Failed");
        }
      }

      if(myServer.begin())
        Serial.println("Server Listen OK");
      else
        Serial.println("Server Listen Failed");
    }

    void loop()
    {
      uint8_t retval, i;
      byte rcvdBuf[129];

      memset(rcvdBuf, 0, 129);

      if(Wifi_setup)
      {
        myWizFi.RcvPacket();
        for(i=0; i<MAX_SOCK_NUM; i++)
        {
          if(myClient[i].available()){
             retval = myClient[i].read(rcvdBuf);
             if(retval > 0)
             {
               Serial.print("CID[");
               Serial.print((char)myClient[i].GetCID());
               Serial.print("]");
               Serial.println((char *)rcvdBuf);

               if((rcvdBuf[retval - 1] == 0x0A) && (rcvdBuf[retval - 2] == 0x0D) && (rcvdBuf[retval - 3] == 0x0A) && (rcvdBuf[retval - 4] == 0x0D))
               {
                 Serial.print("Receiving Completed");
                 myClient[i].write((byte *)"HTTP/1.1 200 OK\r\n");
                 myClient[i].write((byte *)"Content-Type: text/html\r\n");
                 myClient[i].write((byte *)"\r\n");
                 myClient[i].write((byte *)"Hello World !\r\n");

                 delay(100);
                 myClient[i].disconnect();
               }
             }
           }
        }
      }
    }

Using the `WizFiServer` class, it seems to assign a `WizFiClient` instance to each HTTP socket connection. It can then call `clientName.write( /* Data to be sent to client */ );` and `clientName.read();` to get values.

Once it is done with the client, it can free up resources by calling `clientName.disconnect();`.

  [1]: https://github.com/Wiznet/WizFiShield/blob/master/Software/WizFiShield/examples/WizFiWebServerTest/WizFiWebServerTest.ino


message:
SIM900 GRPS Shield Power down over issue AT+CIICR cmd(Bring Wireless Coms)

I'm trying to get the TinySine SIM900 GPRS Shield working to get data over the GPRS network, using Arduino MEGA.

I'm Able to register my SIM with this Shield and even , but as soon as I sent the command AT+CIICR to Bring up the Wireless Coms, the Shiled powers down, all LEDs are OFF except the Red one.

What is the source of the Problem?

Thanks

body:
The SIM9000 shield requires up to 2 Amperes to operate its wireless functions. Thus it must be powered from an external 9 Volt power supply, and the supply should be able to supply at least 2 Amperes, preferably more.

The shield will thus not work if powered through the Arduino, or using a low current external supply. The current draw for initial setup is low, hence registration of the SIM might be fine. Enabling wireless pushes the current draw beyond what your supply can cope with. This is shutting your setup down.

Replace (or use) a 2 Amperes or better 9 Volt DC power supply, feed this power to the shield, not the Arduino, and attempt your code again.

Note that there are some changes required in using an Arduino Mega instead of the Uno with the TinySine GPRS shield, which are described in the help files and on some example videos on YouTube.


message:
Arduino screws up trivial program involving enum

Behold this insanity:

    enum WhatArduinoIs {
      Easy, But, Insane, Obsolete, And, Far, Worse, Than, mBed
    };

    void TellMe(WhatArduinoIs pls) { }

    void setup() { }
    void loop() { }

I'm pretty good at C++, so I'm fairly sure that should compile. However I get this error:

    sketch_jan21b.ino:3:13: error: variable or field 'TellMe' declared void
    sketch_jan21b.ino:3:13: error: 'WhatArduinoIs' was not declared in this scope
    Error compiling.

I've encountered the Arduino "IDE"'s propensity for insane and totally unrobust modification of programs before. Specifically when you `#include` libraries Arduino only magically adds the relevant C++ files if the `#include` is in your main sketch. `#include <LiquidCrystal.h>` in another C++ file? Link errors.

I suspect in this case it is Arduino magically trying to add function declarations to the start of the file so their order doesn't matter. I.e. it turns the file into this:

    void TellMe(WhatArduinoIs pls);

    enum WhatArduinoIs {
      Easy, But, Insane, Obsolete, And, Far, Worse, Than, mBed
    };

    void TellMe(WhatArduinoIs pls) { }

    void setup() { }
    void loop() { }

That obviously doesn't work. How can I tell Arduino to leave my damn program alone?

body:
You seem to be correct about what the arduino IDE is doing to your sketch.

Arduino will not preprocess any .h or .cpp files, so you could use a second file. you could also break the IDE's function locating regex with a dummy `throw()` statement like this:

    void TellMe(WhatArduinoIs pls) throw() { }

The dummy throw allows it to compile for me on 1.5.8


body:
You can workaround the issue by putting your `enum` and function into a namespace. You can even take advantage of C++ unnamed namespaces if you like:

    namespace
    {
      enum WhatArduinoIs {
        Easy, But, Insane, Obsolete, And, Far, Worse, Than, mBed
      };

      void TellMe(WhatArduinoIs pls) { }
    }

    void setup() { }
    void loop() { }

It's annoying (as are many things in the Arduino IDE), but it seems to work.

If you're more experienced with programming then you might want to consider using a 3rd party IDE with an Arduino plugin, such as Eclipse. The Arduino IDE is really only designed for beginners.


body:
**All** you need is a function prototype. I have a detailed explanation at [Classes and objects: how many and which file types I actually need to use them?](https://arduino.stackexchange.com/questions/13178/classes-and-objects-how-many-and-which-file-types-i-actually-need-to-use-them)

So, this compiles:

    enum WhatArduinoIs {
      Easy, But, Insane, Obsolete, And, Far, Worse, Than, mBed
    };

    void TellMe(WhatArduinoIs pls);  // prototype
    void TellMe(WhatArduinoIs pls)
      {
      }
    void setup() { }
    void loop() { }

Off-site reference: [How to avoid the quirks of the IDE sketch file pre-preprocessing](http://www.gammon.com.au/forum/?id=12625)


message:
Arduino PWM Frequency - Pros and Cons of Modifying

I am interested in using an Arduino Uno to produce an analog signal by running PWM through an RC low-pass filter.

I'll be controlling a highly dynamic object and need a clean voltage signal to avoid instabilities.  Per [this calculator on RC designs](http://sim.okawa-denshi.jp/en/PWMtool.php), it's suggested that one strategy to reducing voltage ripple is to increase the PWM frequency.

With PWM configured to a default of [980Hz for pins 5 and 6, and PWM of 490Hz for the remaining pins](https://arduino.stackexchange.com/questions/210/why-do-some-pins-have-a-different-pwm-frequency), I've decided that this will create too much voltage ripple for my filter.  I've found [resources](http://arduino-info.wikispaces.com/Arduino-PWM-Frequency) that describe how to configure the registers to increase the PWM frequency rather drastically.

My question is very simple: Are there any disadvantages to using a higher frequency PWM?  Why is the default set to be so slow?

Thank you!

body:
A PWM frequency of 490Hz means a period of approximately 2.041ms. This allows a high period of 2ms, which is the maximum pulse length required by a large number of inexpensive servos. Obviously if your design uses no servos then this is not a consideration.

Timer 0 itself is used for the various Arduino timing functions (`delay()`, `millis()`, etc.), so if you change the frequency used for timer 0 then those functions will no longer have accurate results.


message:
Replacing the Voltage regulator of a fried Arduino

I accidentally fried my Arduino. I found [this][1] Instructable. The symptoms are the same. The board not powering on connecting USB source and the over current protector was heating up. So I removed the voltage regulator as mentioned in the Instructable. But the problem is the pins 1 and 2 of where the regulator used to be are still shorted out. That is even after removing the regulator, the pins seem to be somehow internally shorted. I tried checking the continuity on another working Arduino and found it to be not shorted. What seems to be the problem?

  [1]: http://www.instructables.com/id/Fix-a-fried-Arduino-Mega/?ALLSTEPS

body:
I know it's an old thread, but others are likely to have this problem.  If you check [the open source schematics][1], there are a couple of nearby capacitors that connect pin 1 (GND) to pin 2 (+5V) of the regulator.

I would check C2 and PC2 (top right of the diagram) as well as C1 (top left of schematic diagram), and any other components you can find that bridge the rails between +5V and ground.  Capacitors are more likely to fail shorted than many other components.  You will have to remove at least one pin of each capacitor to test it since you don't know where the short is, or you can simply remove capacitors until the short goes away.

  [1]: https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf


message:
How do I connect two slaves of same type in I2C?

I am not experienced about I2C communications, but I do happen to have two HMC5883L magnetometer modules that I wish to connect to a single arduino. It uses I2C protocol, and hence the slave device will have a fixed address. Now Can I change the address of one of my sensors so that the Arduino can differentiate between the two? (I seem to find no way out by reading the datasheet)
Thanks in Advance
Siddharth Jha

P.S. Can an MPU 6050 module be used to find angle of rotation in X-Y plane (Parallel to the ground)?

body:
You can't change the address. You could connect it to some other pins, and bit-bang the I2C protocol.

Or connect the vcc of the unit to an arduino pin, so you can turn it on and off.


body:
The problem is with the magnetometer:
"The HMC5883L has a fixed I2C address, you can only connect one sensor per microcontroller!"
[Wiring and Test][1]

Also, it says it in the specs on page 2:
 I2C Address
8-bit read address 0x3D
8-bit write address 0x3C
[3-Axis Digital Compass IC HMC5883L][2]

Low cost magnetometers appear to have fixed I2C addresses. One solution would be to get a different one in addition to yours. For example, the MAG3110 has I2C address 0x0E and the FXMS3110CDR1 has I2C address 0x0F.
[Xtrinsic MAG3110 Three-Axis, Digital
Magnetometer][3]

More information on this page:

[How to connect multiple of the same device to an Arduino using I2C?][4]

P.S. You are more likely to get an answer to your second question by posting it separately (and help others in the process).

  [1]: https://learn.adafruit.com/adafruit-hmc5883l-breakout-triple-axis-magnetometer-compass-sensor/wiring-and-test
  [2]: https://cdn.sparkfun.com/datasheets/Sensors/Magneto/HMC5883L-FDS.pdf
  [3]: https://cdn.sparkfun.com/datasheets/Sensors/Magneto/MAG3110_v9.2.pdf
  [4]: https://electronics.stackexchange.com/questions/130235/how-to-connect-multiple-of-the-same-device-to-an-arduino-using-i2c


message:
Are Arduino's truly OSH?

I keep reading how Arduinos are "open source", but my understanding of OSH is that all its components must be open source.

Arduino uses an Atmel 8-bit CPU - but Googling this shows the Atmel is proprietary!?

So I ask: how can Arduino be OSH if it's chief component - its Atmel CPU - is proprietary?!?

body:
I just scanned over the [TAPR][1] and [CERN][2] open hardware licenses and I didn't see such a provision. My quick take on OHLs is that they are specifications for building the hardware - and therefore, information - not the hardware itself. And it only makes sense when we consider the incredibly expensive and complicated (from an experimenter's point of view) infrastructure that is a chip foundry necessary to create the kinds of hardware we take for granted and have reduced to commodity parts, CPUs, & MCUs being a prime example.

Thus "Arduino" is an open source specification for building microcontroller boards or board-sets based on ATMEL MCU chips, as well as the products of the Italian company SmartProjects. That is why there are so-called Arduino clones, otherwise, why wouldn't any clone of an Arduino *be* an Arduino?

  [1]: http://en.wikipedia.org/wiki/TAPR_Open_Hardware_License#Conditions
  [2]: http://www.ohwr.org/documents/294


message:
Using NodeJS, socket.io and Adafruit HUZZAH CC3000 breakout board to control Arduino wirelessly?

I'm looking to build my a wirelessly controlled lamp and have a few questions. Would I be able to use the Adafruit HUZZAH CC3000 breakout board to receive commands from a website and control a connected lamp?

I just set up a NodeJS server with webpage on my PC and using socket.io and Firmata I was able to communicate with the Arduino using the webpage over a serial connection. Could I set up similar implementation except instead of communicating over serial I'd communicate using Wifi? Would I need to host a web server on the Wifi board itself to communicate with the Arduino or is there some way to just use the wifi board as a communication between external site and Firmata?

body:
I happen to have received the CC3000 shield yesterday and have been playing with it today...

**What do you mean by "receive commands from a website"?**

If you mean "can it serve a simple website and act upon HTTP requests" (e.g. requests to http://arduino.local/on would turn a lamp off and http://arduino.local/off would turn if off), then yes it can. You make the HTTP requests using javascript's XMLHTTPRequest if you want to be able to communicate from within a web page without having to re-render a page.

There is an example sketch of an HTTP server included in the CC3000 library that would get you started. Note that the example HTTP server sketch can only handle one HTTP request/response at a time.

You will obviously also need some way of controlling a relay of you want to control a lamp.

**Update:** Since you updated your question to include how you are currently communicating:

I'm not familiar with socket.io or Firmata, but I'm guessing socket.io is a way of getting your web client (browser) to talk directly Firmata which talks to your Arduino over the USB-Serial connection? If so, then I'm not sure if it's possible to use the Firmata protocol over wireless, but it is possible for the CC3000 to act as a generic TCP server and act on data that it receives wirelessly, so it might be possible to communicate between socket.io and the TCP server. The EchoServer sketch shows how to set up a TCP server to receive raw data.

If you're only turning a lamp on/off you basically only need to control 1 pin. Isn't Firmata a bit overkill for that? Be careful about sketch size. I'm not sure how big Firmata compiles to, but the wireless library with some kind or server is over 22,000 byes (of a possible 32,000) on an Uno, so you might struggle to fit both on.


body: Have you heard of aREST.io? There is a wifi library that supports the CC3000 (http://arest.io/wifi/) that sounds like it might do a similar thing to Firmata


message:
How are Arduino's OSH if Atmel AVR is proprietary?

I keep reading how Arduinos are "open source", but my understanding of OSH is that all its components must be open source.

Arduino uses an [Atmel AVR](http://en.wikipedia.org/wiki/Atmel_AVR) CPU - but Googling this shows the Atmel is proprietary!?

So I ask: **how can Arduino be truly OSH if it's chief component - its Atmel CPU - is proprietary?!?**

body:
The components are necessarily going to be proprietary.  There is no feasible way around this.  If you wanted to design a new open source microcontroller from scratch with no proprietary components, it would set you back several billion dollars.  The software used to design integrated circuits costs hundreds of thousands of dollars to license and represents billions of dollars of investment.  Production of the chips themselves takes place in wafer fabs that cost billions of dollars to build, and represent billions of dollars of investment in process technology and semiconductor physics research.  The equipment and process technologies are very closely held trade secrets.  If you are OK with proprietary production, then you can submit GDSII design files (developed with your own open source IC design software) to fabs such as TSMC for production, but the line setup costs will run in the hundreds of thousands of dollars.

Bottom line: you have to draw the line somewhere as to what is acceptable to be 'open' and what is not.  Open source hardware generally means the board-level design files and firmware sources are available, and generally nothing more.

Interestingly, there are many open source CPU designs available.  Sun's OpenSPARC is an open design, you can download the RTL description of the CPU core and modify it.  However, convering RTL to a chip requires IC design software or implementation on a proprietary FPGA with a proprietary development environment.


body:
An 'Arduino' is open source in that you can see the schematics, go out and buy any required components (including the AVR), and change the design however you like.

The AVR is not part of what Arduino owns, it is a simply a component which they have built their design around. You could if you so choose replace that component with something else like a PIC for example, or any other programmable microcontroller for that matter. Granted if you made such a change you would also have to change the software, but then if you change the hardware even to another AVR you would have to change the software so in that sense it isn't really a limiting factor.


body:
There is a good practical question and interesting issues raised here, but this part:

"my understanding of OSH is that all its components must be open source."

I would say your understanding is wrong, where did you get that from?

The design (i.e. how to arrange components) must be open source. Ideally the components would be Open Source too, but practicality dictates that components must be bought "off the shelf". IOW, overall the design should aim for "as Open Source as much as possible".

The thing about hardware is that to realize a design components must be bought, and those components often contain proprietary IP. Of course, the same problem applies to Open Source Software, to run it I need to buy a CPU from Intel, AMD, etc.

So while all open source designs must rely on some proprietary IP as a base platform, the practical question is how easily can the design be moved to another platform (portability), and how easily a component can be substituted (fungibility).

There is only one source of AVR chips and that is Atmel. Other components, like a 3.3V regulator can be easily substituted with other.

The Arduino core software does not rely solely on AVR architecture, in principle it is portable to any CPU platform, in practice any platform that is targeted by GCC. The fact that some Arduinos are not AVR e.g. Due, shows that.


body:
Open-source hardware is fundamentally different from open-source software in that you cannot make a copy of OSH for free. If you want to build an Arduino, you will need all the components it's made of, and even the simplest components like diodes are proprietary, just like the AVR chip. Neither can be home-made and both are proprietary designs.

The important thing about OSH is not that it's made of free components, but the fact that **information about how it's made is freely available**. The abundance of Arduino shields and addons is not due to availability of free AVR cores, but to the fact that anyone has access to the information needed to make their board Arduino-compatible. BTW, that's how personal computers gained the dominant position on the market: IBM has published detailed specifications [including schematics](https://en.wikipedia.org/wiki/IBM_Personal_Computer#Third-party_products) of their IBM PC (albeit not under a free license), enabling other companies to make compatible hardware, and later on, PC clones.

Last but not least, the open-source aspect of Arduino is by no means limited to the hardware. The core library was written in portable way, which made it possible to run it on a [wide range](https://en.wikipedia.org/wiki/List_of_Arduino_boards_and_compatible_systems) of hardware cores. There are even FPGA boards featuring Arduino connectors ([1](https://www.eevblog.com/forum/microcontrollers/cyclone-v-gx-starter-kit-the-ultimate-arduino/), [2](http://www.aloriumtech.com/xlr8/), [3](http://papilio.cc/)), which can run Arduino software on soft-cores such as [F32C](http://www.nxlab.fer.hr/fpgarduino/) or [NIOS](https://github.com/dimag0g/nios_duino).


message:
Where Can I Find a 12v Solder-less Breadboard Power Supply?

I am trying to find a 12 V input and 12 V output breadboard power supply but I can't find one. I am making an Arduino-controlled lock but the Arduino cannot power the lock strike by itself so I need to use a separate power supply. The link to make things clearer:
http://www.instructables.com/id/Arduino-RFID-Door-Lock/#step0

body: They sell 5V/3.3V breadboard supplies on eBay for $3-$5 shipped from China. Buy one and rewire/modify it to bypass the voltage regulator


body: There is nothing special about a "breadboard power adapter" that isn't served by a normal regulated supply. Simply use wires or a barrel jack or some other connector to connect any regulated supply to the breadboard as desired.


message:
Can Arduino's open design be "scaled" to 64-bit CPUs?

If Arduino is OSH that simply uses 8-bit Atmel AVR MCU as a design component, then can Arduino somehow be tweaked to work with a 64-bit CPU/MCU? If so, what might this entail?

body:
It has already been ported to a 32-bit Arm - the Arduino Due - 84mhz, Cortex M3.

To port it to a 64-bit CPU, someone would need to create a design for the PCB, and set up an appropriate build/compile system for it.

Having said that, a 32-bit CPU is an awful lot of power for this sort of thing - I suspect that if a 32-bit Arm isn't enough, then what you're really looking for is a full-blown PC. A Cortex M3 can handle 4GB of memory, and can run a version of Linux (uCLinux, since the M3 does not have a memory management unit, MMU, and the standard Linux kernel needs this). The Due would be unable to run even uCLinux, due to limited memory.

In fact, the Raspberry Pi is also a (700mhz Cortex A8) 32-bit CPU; I imagine that a little bit of tweaking could make the Arduino IDE compile & upload for the Raspberry Pi. This would fall into the category of "Because I can".

Note: The Raspberry Pi is not opensource, I know. Neither is the Arm in the Arduino Due, nor the AtMega that is at the heart of the Arduino Uno.


message:
connection issues with 3 arduinos any suggestions?

I have 3 arduinos that I want to program on, all of them with their own cable and I have tried to connect them to my laptop on several different usb ports, my usb ports work with mouses so that's unlikely to be the problem. However I just cannot connect to them they just don't appear under /dev/ttyACM* and the arduino IDE cannot find them either. I'm running ubuntu 14.04 any suggestions for finding out what is likely to be wrong with my system or the arduinos?

For some odd reason they now all appear to be seen as /dev/ttyACM* but they now all give me a

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

error

Anybody have any idea how to fix? The arduino's do not have any wires in them except usb (nothing in reset or any other pin), I'm on ubuntu so the drivers shouldn't be an issue? And pin 13 flashes when I reset the arduino.

body: it's been a while but a long time later I found that the cable I was using was broken. A different cable worked.


message:
Send one bit out per clock pulse received using direct port manipulation?

I want to send one bit of a byte out per 'rising edge' received to an Arduino digital input. I am addressing the outputs using direct port manipulation (to achieve maximum speed), and I would like to do the same for input.

So I'm calling a function called bitBang in my main loop, sending the ready line high before moving into the function:

    //Send control
 PORTB |= _BV(PORTB2);
 bitBang(controlByte);
 PORTB &= ~_BV(PORTB2);

What I would like to do upon entering the function is listen for a rising edge to appear on the digital input port using the direct port syntax and iterate through the byte setting the data line high or low depending on the bit's value.

**How can I achieve this in the most efficient way possible?**

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

Example bit-banged SPI using port manipulation:

---

**bitBangedSPIfast.h** :

    #include <Arduino.h>

    class bitBangedSPIfast
      {
      // addresses of output ports - NULL if not applicable
      volatile byte * const mosiPort_;
      volatile byte * const misoPin_;
      volatile byte * const sckPort_;

      // bit masks for above
      const byte mosiBit_;
      const byte misoBit_;
      const byte sckBit_;

      // addresses of data direction register ports
      volatile byte * const mosiDDR_;
      volatile byte * const misoDDR_;
      volatile byte * const sckDDR_;

      // bit masks for above
      const byte mosiDDRBit_;
      const byte misoDDRBit_;
      const byte sckDDRBit_;

      // delay for clock being high
      unsigned long delayUs_;

      public:
        // constructor
        bitBangedSPIfast (
              // output ports
              volatile byte & mosiPort,
              const    byte mosiBit,
              volatile byte & misoPin,
              const    byte misoBit,
              volatile byte & sckPort,
              const    byte sckBit,

              // data direction register ports
              volatile byte & mosiDDR,
              const    byte mosiDDRBit,
              volatile byte & misoDDR,
              const    byte misoDDRBit,
              volatile byte & sckDDR,
              const    byte sckDDRBit,

              const unsigned long delayUs = 1)
           :
             mosiPort_ (&mosiPort),
             mosiBit_  (1 << mosiBit),
             misoPin_  (&misoPin),
             misoBit_  (1 << misoBit),
             sckPort_  (&sckPort),
             sckBit_   (1 << sckBit),

             mosiDDR_     (&mosiDDR),
             mosiDDRBit_  (1 << mosiDDRBit),
             misoDDR_     (&misoDDR),
             misoDDRBit_  (1 << misoDDRBit),
             sckDDR_      (&sckDDR),
             sckDDRBit_   (1 << sckDDRBit),

            delayUs_ (delayUs) { }

        void begin ();
        byte transfer (byte input);

      };  // end of bitBangedSPIfast

---

**bitBangedSPIfast.cpp** :

    #include <bitBangedSPIfast.h>

    void bitBangedSPIfast::begin ()
      {
      if (mosiPort_)
        *mosiDDR_ |= mosiDDRBit_;    // output
      if (misoPin_)
        *misoDDR_ &= ~misoDDRBit_;   // input
      *sckDDR_ |= sckDDRBit_;        // output
      }   // end of bitBangedSPIfast::begin

    // Bit Banged SPI transfer
    byte bitBangedSPIfast::transfer (byte c)
    {
      // loop for each bit
      for (byte bit = 0; bit < 8; bit++)
        {
        // set up MOSI on falling edge of previous SCK (sampled on rising edge)
        if (mosiPort_)
          {
          if (c & 0x80)
            *mosiPort_ |= mosiBit_;
          else
            *mosiPort_ &= ~mosiBit_;
          }

        // finished with MS bit, get read to receive next bit
        c <<= 1;

        // read MISO
        if (misoPin_)
          c |= (*misoPin_ & misoBit_) != 0;

        // clock high
        *sckPort_ |= sckBit_;

        // delay between rise and fall of clock
        delayMicroseconds (delayUs_);

        // clock low
        *sckPort_ &= ~sckBit_;

        // delay between rise and fall of clock
        delayMicroseconds (delayUs_);
        }  // end of for loop, for each bit

      return c;
      }  // end of bitBangedSPIfast::transfer

---

**Example usage**:

    #include <bitBangedSPIfast.h>

    bitBangedSPIfast bbSPI (PORTD,  5, PIND,  6, PORTD, 7,    // MOSI port (D5), MISO pin (D6), SCK port (D7)
                            DDRD,   5, DDRD,  6, DDRD,  7);   // MOSI ddr  (D5), MISO ddr (D6), SCK ddr  (D7)
    const byte mySS =  8;  // slave select

    void setup (void)
      {
      bbSPI.begin ();
      pinMode (mySS, OUTPUT);
      }  // end of setup

    void loop (void)
      {
      char c;

      // enable Slave Select
      digitalWrite(mySS, LOW);

      // send test string
      for (const char * p = "Hello, world!" ; c = *p; p++)
        bbSPI.transfer (c);

      // disable Slave Select
      digitalWrite(mySS, HIGH);

      delay (100);
      }  // end of loop

---

### Reference

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


message:
Arduino Uno R3 not recognized by computer, TX and RX not blinking, neither are lit. Is it dead?

I was trying to make my arduino uno r3 to work on my Linux machine (including the IDE), but it wouldn't. At first I thought it was a software problem. Added myself to different groups and did everything, people discussed on the forums. It didn't work. It wasn't recognized by the computer at all. I reinstalled. Nothing again. Thought it was a hardware problem of my computer. Tried with dad's (Windows 7 machine). Didn't work. Then I saw that the two leds (TX and RX) are not blinking, neither are lit. I started doing a research on the internet but everybody suggests doing the loopback test from the IDE. My Arduino Uno R3 is not recognized by the computer, therefore the IDE. Is there any way to check if it's dead or if it's a minor problem?

Edit: I read a lot on the case last night and I reach to the conclusion that my ATmega16u2 (the usb-serial chip, I'm sure it is 16u2 and not 8u2, it's written on the chip itself) might be dead. Tried to reflash the firmware but cannot get it in DFU mode (as it says in this article click here). dfu-programmer (the Linux application) throws the following error: `dfu-programmer: no device present`. What to do?

body:
Before you can access serial TX/RX on Arduino make sure USB to serial converter on the board is working. To check it (on Linux) do the following:

1. Open the terminal, type 'dmesg' and press 'enter'. You will see some output with timestamps (number in square brackets). Note the timestamp of the last line. Run dmesg several times to make sure nothing writes to it and you still see the last timestamp.

2. Plug your board into USB port and run dmesg once again. You should see something like the output below. The first line is the last line of dmesg prior to plugging in the Arduino, the second line is actual detection. The board I used in this example is 2560, UNO will give you similar output. If you can see this output your board is recognized just fine. If you can't see it then either the USB to serial chip (just another AVR MCU) on the Arduino or USB host in your PC or both are defective.

<pre>
    [279152.351690] systemd-logind[867]: New session c51 of user lightdm.
    [280362.732094] usb 3-2: new full-speed USB device number 3 using uhci_hcd
    [280362.931266] usb 3-2: New USB device found, idVendor=2341, idProduct=0010
    [280362.931275] usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=220
    [280362.931282] usb 3-2: Product: Arduino Mega 2560
    [280362.931288] usb 3-2: Manufacturer: Arduino (www.arduino.cc)
    [280362.931293] usb 3-2: SerialNumber: 64938323331351213172
    [280362.986579] cdc_acm 3-2:1.0: ttyACM0: USB ACM device
    [280362.988470] usbcore: registered new interface driver cdc_acm
    [280362.988473] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters
    [280362.732094] usb 3-2: new full-speed USB device number 3 using uhci_hcd
    [280362.931266] usb 3-2: New USB device found, idVendor=2341, idProduct=0010
    [280362.931275] usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=220
    [280362.931282] usb 3-2: Product: Arduino Mega 2560
    [280362.931288] usb 3-2: Manufacturer: Arduino (www.arduino.cc)
    [280362.931293] usb 3-2: SerialNumber: 64938323331351213172
    [280362.986579] cdc_acm 3-2:1.0: ttyACM0: USB ACM device
    [280362.988470] usbcore: registered new interface driver cdc_acm
    [280362.988473] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters
</pre>


body:
1. Delete your Arduino IDE, but store your libraries if you need in future.
2. Download Arduino ERW 1.0.5 from here: http://forum.arduino.cc/index.php?topic=118440
3. Try your steps again with your connections belong to your schematic.


body:
There is a chance that your bootloader is not working anymore. You can burn a new bootloader to the device with another Uno, there are nice [guides on the Arduino-Website][1].

  [1]: http://arduino.cc/en/Tutorial/ArduinoToBreadboard


message:
Increasing payload size above 32 bytes using nRF24L01+

I tried to modify the example in the following page, by replacing the given string with a 56 bytes one after making all the suitable changes to read(), write() and max_payload_size(increased to 64 bytes), payload_size() parameters/methods in the RF24 library.

http://shanes.net/another-nrf24l01-sketch-string-sendreceive/

The problem is the receiver truncates the string to 32 characters. Is 32 bytes a hard limitation for payload with the nrf24l01+ radio? If so how to I modify the receiver in above example problem to receive the entire string?

body:
If you look at the [specification or datasheet](https://www.nordicsemi.com/eng/Products/2.4GHz-RF/nRF24L01P) for the nRF24l01+, you will see that the 32 byte payload is the maximum that the device can handle.

For example:

![spec][1]

If you need to transmit anything larger than 32 bytes, you will need to develop a protocol that splits up your data into chunks of 32 bytes or less and sends the data in several packets.

The actual protocol you design is up to you, but a simple technique might be using the first packet to send a count of the number of data packets to expect and then simply send those packets, each with a part of your data and reassemble it at the receiving end.

You may need to design something more robust so you don't get confused by lost packets or bad data. The larger your payload, the more chance of transmission errors, so it might be an idea to experiemnt with the payload size to get the best throughput for your particular application.

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


message:
Increasing analogread speed on the Arduino Uno

I want to transfer data from my smartphon to the Arduino by using the audio jack of my smartphone. For this I need verry high reading frequencys.

I have used

    bitClear(ADCSRA,ADPS0);
    bitSet(ADCSRA,ADPS1);
    bitClear(ADCSRA,ADPS2);

to boost analogread to ~10microseconds, which would be enough. But somehow I am still wasting 5.4 ms at the beginning of the transmission.

The only thing between signal start and first analogread is a start of a for loop:

    while(analogRead(A0)<50) (true); //wait for start of transmission
    for(i = 0; i<500;i++){
    data[i]=analogRead(A0);
    }

But does starting a for loop take 5.4 ms?
Do you have any ideas?

body:
It sounds like you could benefit from interrupt handled free running sampling, doing that should get you sampling rates up to the maximum listed on the 328's datasheet, 76.9 kSPs. Although, that's at a reduced resolution. [This site][1] explains better, under the section "Free running sampling".

  [1]: http://meettechniek.info/embedded/arduino-analog.html


body:
I did some further analysis on the signal and the problem was not the Arduino. It did everything quick and correct.
The problem was my smartphone. I used androids AudioTrack class and somehow it did cut off parts of the signal. This could be "fixed" by increasing the length of the signal. I just added 0's at the beginning and end.


message:
Does Leonardo need a separate power supply?

I'm currently using an Arduino Uno (R3), but want to switch to Leonardo for the USB-ability. The Uno can work from the USB's 5V. Looking at the Leonardo's schematic it seems the only input to the voltage regulator is from the power connector. This makes sense as it's a 5V regulator which needs > 5V in. But I don't see the MOSFET which connects the USB's 5V to the board's 5V, like there's one on the UNO.

So, does the Leonardo need the separate power input connected?

body: Power steering is performed by the assembly labelled "+5V AUTO SELECTOR" at the bottom of the page. The voltage at VIN is halved and then compared with the board's 3.3V output in order to determine whether or not to enable USB power via T1.


message:
Connecting multiple DHT 11 sensors

I want to collect data (both Humidity & Temperature) from 80 sensors. let's say I have 80 "DHT 11 Humidity & Temperature" sensors (for ex. in a warehouse) and one Arduino Uno R3 pack. It's clear that arduino has no so many pins to connect. I'm sorry that I don't know if it's possible. If so, what can I use to achieve this?
Thank you all for your suggestions.

body:
Analog multiplexers are one way, but they tend to have a significant resistance when on, and this could cause the protocol not to work.
For 80 channels you need 7 bits addressing. Say you have an 8-input multiplexer, then a 3-bit address indicates which of the 8 inputs is selected. Use 10 of these, all with the three address lines connected, and you have 10 outputs from 80 inputs.
Next, use a 16-input multiplexer to select which of the 10 inputs you want to use. For this multiplexer you need 4 address lines. Together with the other 3 address lines you have 7 address lines, enough to select 1 of up to 128 sensors. But I repeat, this approach may not work if the multiplexer's resistance is too high.

A more robust (albeit more expensive) is to use analog switches to connect/disconnect each sensor. Analog switches (Analog Devices has a lot of them) have on-resistances down to < 1 ohm, so the sure should be OK for the application.
To control the long series of switches you could use a daisy chain of 74HC595 shift registers, which only requires a couple of I/Os on your controller, but gives you virtually unlimited outputs.