body:
I have a need for a bill counter at my current job, but besides counting bills we also could use a machine to count admission cards.

The idea is to either buy a bill counter machine (like those that the Banks have), or make one from scratch by buying the parts.
Besides the bill counting feature i wanted to make it so that it also counts the certain number of cards, and check if they are either stamped or not.

My question is:

Is this possible?

If so, is it easier to just buy a arduino and use it with other parts (sensors, moving gears etc etc), or to buy a bill counter and just "crack" the OS?

Any insight would be appreciated!

PS: I am a 1st year Computer Science student, but i have 0 experience in programming in Arduino

title: Question about viability of building a Bill Counter machine

Answers: 1

body:
There are many more things to consider than just put some parts together if you try to build a counter from scratch. Automated currency handling has come a long way to today's bill counters or any vending machines. You may perfectly handle the computing part of task with an embedded system like the arduino, but paper handling is an art of itself.

If you think of this task as a challenge to acquire and hone engineering skills, go ahead. It may be one of the best training tasks one can think of. But while you may learn a lot from this conundrum, you will propably end up without an usabale device. :)

You have to consider, there are subtasks in

 - mechanics
 - electronics
 - programming

which may include

 - paper handling (separation, traction, alignment)
 - pattern recognition
 - motor control
 - high speed sensors
 - signal detection and processing
 - error and fault processing and handling
 - motor and gear connection
 - bearings and mechanical substructure
 - user interface

and many more.

To modify an existing device solves a lot of mechanical problems in advance. But it may still be difficult to change the firmware of a bill counter to your needs.

You will have to

 - break into the system (may be impossible)
 - reverse engineer the firmware
 - understand the mechanical constraints
 - find a way to adapt the system to your needs.

A third way, which in my eyes is rather intriguing, is to take an existing bill counter, rip out the controller and try to plug in your own controller, e.g. an arduino. This gives you a real chance to reach your goal while still having the opportunity to learn a lot.


body:
I am looking to utilize Pin 13 and an external LED to flicker as either the Rx or Tx LEDs do when Serial data is transferred through the Arduino. The existing code is all in real time to function with external buttons, so there can't be any delay.

I came across this link which seems useful, but I can't quite get it to read from Serial:

http://arduino.cc/en/Tutorial/BlinkWithoutDelay

Thanks in Advance

title: Serial Data through Pin 13 LED

Answers: 1

body:
If you are going to use an external LED, then using software to make the LED blink when the RX or TX line is busy is a waste of your CPU.

Instead, simply connect the LED to the RX or TX line using a transistor as a buffer to prevent the current draw from messing with the serial signal.

To borrow an image from [this answer][1] to [a similar question][2]:

![enter image description here][3]

You can try omitting the transistor buffer, but the serial waveform will be altered, possibly to the point where data becomes corrupted. The transistor prevents the current draw of the LED and resistor from loading down the RX or TX lines.

  [1]: https://electronics.stackexchange.com/a/42589
  [2]: https://electronics.stackexchange.com/questions/42581/attaching-a-led-to-pics-rx-pin
  [3]: https://i.stack.imgur.com/boiiA.gif


body:
I have a text file on an SD card, and I am trying to print the lines to the serial monitor.

This Code Works:

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

    File myFile;

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

      Serial.print("Initializing SD card...");

      pinMode(10, OUTPUT);

      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        return;
      }
      Serial.println("initialization done.");

      myFile = SD.open("c.txt");
      if (myFile) {
        Serial.println("c.txt:");

        while (myFile.available()) {
          Serial.write(myFile.read());  //THIS LINE RIGHT HERE
        }
        myFile.close();
      } else {
        // if the file didn't open, print an error:
        Serial.println("error opening c.txt");
      }
    }

    void loop()
    {
    }

However, if I replace the line `Serial.write(myFile.read());` with `Serial.println(myFile.read());`, then the code doesn't return the correct lines.

It should return numbers similar to this (albeit 3000 of them):

    564
    564
    564
    564
    564
    564
    564
    464
    564
    664
    564

If I use `Serial.println` it returns numbers like this (and it doesn't stop at 3000 lines):

    13
    10
    54
    54
    52
    13
    10
    53
    54
    52

And if I try to do `int(myFile.read())` then the integer becomes the wrong numbers (returned by `println`), not the right ones (returned by `write`).\

How do I get a number returned by `Serial.write(myFile.read());` to be an integer?

title: Serial.write and Serial.println return different values? Cannot use correct ones

Answers: 1

body:
The text file contains the sequential ascii values that spell out the data, not binary data. `println` in printing the numerical value of each byte. For example, the 10's `println` prints are '\n' characters. `write` is printing the ascii character associated with the binary value (the new line). You need to parse the ascii characters into numbers.

Luckily for you the SD library inherits from the `Stream` class, so it will have the same `parseInt` function most often used to parse ints from the serial monitor.

You probably want to set `myFile.setTimeout(0)` first because the file isn't slowly getting characters from the serial bus, so the timeout would just slow you down.

Then you should be able to parse and print out the ascii integers with something like this:

    int val = myFile.parseInt();
    Serial.println(val);


body:
I'm looking for a complete pinout of the [Arduino Ethernet R3][1].
I've found one [here][2] which is low quality, and seems not complete (where are the digital I/O pins?).

![enter image description here][3]

BTW, it was not a good idea for Arduino to name this board "Arduino Ethernet", as this is pretty useless for searching online :-(

  [1]: http://arduino.cc/en/Main/arduinoBoardEthernet
  [2]: http://f1mvp.perso.sfr.fr/Robotic/arduino.htm
  [3]: https://i.stack.imgur.com/9mk4A.jpg

title: Where can I find a better pinout diagram for "Arduino Ethernet" board?

Answers: 2

body:
The [formal Arduino.cc website][1] mentions, somewhat obscurely, that the Arduino Ethernet is pin compatible with Arduino Uno:

> The Revision 3 of the board introduces the standardized 1.0 pinout

Except for pins 10-13:

> Pins 10, 11, 12 and 13 are reserved for interfacing with the Ethernet
> module and should not be used otherwise. This reduces the number of
> available pins to 9, with 4 available as PWM outputs.

The other difference is the onboard LED is connected to pin 9 rather than the Uno's pin 13:
>On most other arduino boards, this LED is found on pin 13. It is on pin 9 on the Ethernet board because pin 13 is used as part of the SPI connection.

You can use any Arduino Uno pinout diagram as a reference, the [one you have found][2] seems to be pretty elaborated.

  [1]: http://arduino.cc/en/Main/arduinoBoardEthernet
  [2]: http://marcusjenkins.com/wp-content/uploads/2014/06/ARDUINO_V2.png

body:
That's a better one from :

https://pinoutguide.com/images/arduino/ethernet.png

This one also presents the Arduino Ethernet R3 board and
has the extra I2C pins (SCK=A5,SDA=A4) next to the AREF pin.

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

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


body:
Can I replace Atmega8 with Atmega328 in my freeduino board?
If so, let me know the steps needed.

Answers: 1

body:
Shouldn't be a problem. Some later versions already have a ATMega168 instead of the ATMega8. All three are pin-compatible.

In the arduino IDE you should however select a different board (one with a 328, like the UNO). That way the compiler knows the target MCU is the 328, and not the 8.


body:
I'm having a hard time debugging this piece of code, and i'm hoping someone can point out where i am making the mistake.

My serial output is:

    connected
    GetData()
    got data...
    next stage...

I've tested with a simple network client that loops sending a hello world, and it works fine. Every time this code halts after attempting to send a value to the `client`. I know that  `getData()` is causing the issue, but i cannot work out why, or how to best resolve it.
(apologies for the code dump, i want to be thorough)

    #include <LiquidCrystal.h>
    #include <dht11.h>
    #include <SPI.h>
    #include <Ethernet.h>
    dht11 DHT11;
    #define DHT11PIN 8

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

    IPAddress server(192,168,1,100);
    IPAddress ip(192,168,1,50);
    EthernetClient client;

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

    const int trigPin = 6;
    const int echoPinOne = 7;
    const int echoPinTwo = 8;
    const int echoPinThree = 9;
    const int echoPinFour = 10;

    void setup() {
      lcd.begin(16, 2);
      Serial.begin(9600);
      delay(1000);

      //Network
     if (Ethernet.begin(mac) == 0) {
        Serial.println("DHCP FAIL");
        Ethernet.begin(mac, ip);
      }
      delay(1000);
      Serial.println("connecting...");
      lcd.setCursor(0, 0);
      lcd.print("connecting");
      connect();
    }

    void connect(){

        if (client.connect(server, 8080)) {
        Serial.println("connected");
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("connected");

        client.println("hello server");
        client.println();
        delay(500);
        lcd.clear();
      }
      else {
        Serial.println("connection failed");
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Connection Failure");
      }
      delay(500);
    }

    void loop() {

       //network
      if(!client.available()){
        Serial.println("lost connection!-restart");
        lcd.println("Disconnection");
        client.stop();
        connect();
      }
      else {

        int inp[5];
        getData(inp);
        Serial.println("next stage...");
        char *output = (char *) &inp[0];
        client.println(output);

        client.println("first");

        Serial.println("sent first...");

        //here repeats the same process for the other sensors - omitted for clear reading

      }
       //end network

       delay(500);
    }

    void getData(){

    Serial.println("GetData()");
    long durationThree, inchesThree, cmThree = 0;
    long durationOne, inchesOne, cmOne = 0;
    long durationTwo, inchesTwo, cmTwo = 0;
    long durationFour, inchesFour, cmFour = 0;

    //SENSOR ONE
    pinMode(trigPin, OUTPUT);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    pinMode(echoPinOne, INPUT);
    durationOne = pulseIn(echoPinOne, HIGH);

    delay(100);

    //SENSOR TWO
    pinMode(trigPin, OUTPUT);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    pinMode(echoPinTwo, INPUT);
    durationTwo = pulseIn(echoPinTwo, HIGH);

    delay(100);

    //SENSOR THREE
    pinMode(trigPin, OUTPUT);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    pinMode(echoPinThree, INPUT);
    durationThree = pulseIn(echoPinThree, HIGH);

    delay(100);

    //SENSOR FOUR
    pinMode(trigPin, OUTPUT);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    pinMode(echoPinFour, INPUT);
    durationFour = pulseIn(echoPinFour, HIGH);

    //DISTANCE CALCULATION
    cmOne = microsecondsToCentimeters(durationOne);
    cmTwo = microsecondsToCentimeters(durationTwo);
    cmThree = microsecondsToCentimeters(durationThree);
    cmFour = microsecondsToCentimeters(durationFour);
    //Serial.println("sending...");
    //char *out = (char *) &cmOne;
    //Serial.println(out);
    //client.println(out);
    //Serial.println("sent!");      used this to test - same issue

    Serial.println("got data...");
    inputBuf[0] = cmOne;
    inputBuf[1] = cmTwo;
    inputBuf[2] = cmThree;
    inputBuf[3] = cmFour;

    }

    long microsecondsToCentimeters(long microseconds)
    {
    return microseconds / 29 / 2;
    }

title: data type error on sensor data to ethernet client

Answers: 1

body:
The code you posted is performing incompatible casts and by thus is sending garbage to `client.println`.

There is no automatic conversion in C/C++ from an array of integers (`int inp[]`) or longs, to a C style string `char *`. A C Style string should end with null terminator `\0`, and the one in your code doesn't. For example, in this line:

    char *output = (char *) &inp[0];

The `inp[0]` contains the first integer. The expression `&inp[0]` contains the address of that integer in memory.

Thus the cast to `(char *)` will yield a malformed C style string, since it will not end with a null terminator, and more important, will not contain the data you expect it would (this cast is saying - "hey, compiler, note that the *address* of that `int` is actually the address of a C style string").

You can, however, utilize the `String` type constructor that receives int/long, and send the duration in order, something similar to:

            void getData()
            {
                ... // rest of the code here
                client.println(String(cmOne));
                client.println(String(cmTwo));
                ... // etc.
            }


body:
I am trying to do an experiment with Arduino Uno r3 board plus a 2-channel relay shield. What I need to do is to alternatively turn on and off the relay shields. So, it requires multiple compile and upload of the program to assign values to corresponding pins. What I have seen by now is that uploading the program to Arduino is a kind of painful process and it requires nothing to be connected to pins 0 and 1 to prevent synchronization errors. So, I was wondering how I can do my experiment without having to mount/unmount relay shield each time I want to upload a new program into it.

Thanks in advance

title: Multiple upload/ Synchronization problem

Answers: 1

body:
Well, you can write a program that takes numbers out of Serial input.

    int pin1 = Serial.parseInt();
    int pin2 = Serial.parseInt();
    // etc., etc.

Simple.


body:
When I upload the code, the DC motor makes a humming noise, but doesn't turn.

    //2-Way motor control

    int motorPin1 =  5;    // One motor wire connected to digital pin 5
    int motorPin2 =  6;    // One motor wire connected to digital pin 6

    // The setup() method runs once, when the sketch starts

    void setup()   {
      // initialize the digital pins as an output:
      pinMode(motorPin1, OUTPUT);
      pinMode(motorPin2, OUTPUT);
    }

    // the loop() method runs over and over again,
    // as long as the Arduino has power
    void loop()
    {
      rotateLeft(150, 500);
      rotateRight(50, 1000);
      rotateRight(150, 1000);
      rotateRight(200, 1000);
      rotateLeft(255, 500);
      rotateRight(10, 1500);
    }

    void rotateLeft(int speedOfRotate, int length){
      analogWrite(motorPin1, speedOfRotate); //rotates motor
      digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
      delay(length); //waits
      digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
    }

    void rotateRight(int speedOfRotate, int length){
      analogWrite(motorPin2, speedOfRotate); //rotates motor
      digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
      delay(length); //waits
      digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
    }

    void rotateLeftFull(int length){
      digitalWrite(motorPin1, HIGH); //rotates motor
      digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
      delay(length); //waits
      digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
    }

    void rotateRightFull(int length){
      digitalWrite(motorPin2, HIGH); //rotates motor
      digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
      delay(length); //waits
      digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
    }

  ![][1]

Why doesn't this work?

***Update:***

I plugged it into a different port (5v) as it is a 5v motor, but now it only turns left, not right. It just hums when it goes right.

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

title: Why doesn't this motor turn?

Answers: 2

body:
The IO drivers of most common logic chips or microprocessors such as the ATmega on your Arduino are nowhere near strong enough to drive typical electromagnetic motors.

To drive a motor, you should use a higher current switching device - a standard solution for bidirectional control being an H bridge part such as a TB6612FNG, L293D, L298, etc.

These are commonly sold on "motor shields" which you can plug into your Arduino, if you want to experiment with the concept before building something (and if you do want to build something, reviewing such a working schematic first would be a good idea).

You can in theory put an L293D or its DIP-packaged work-alikes on your breadboard, but you will need some care to get it right, especially if you use one of the other parts which requires external catch diodes.

Finally, you should not be powering most motors from the Arduino's onboard regulator or a USB port, but rather should use an external power supply.

=============

Responding to your edit, by  changing connections to place the the motor between one pin and the 5v supply, you have done two things:

1) You have made it so that the voltage difference across the motor can be applied in one direction only, therefore it can only rotate in one direction.

2) You have made it so that only the N-channel MOSFET in an output driver is involved in powering the motor.  That change is *almost* a useful idea, as N-channel devices are in fact much more capable than P-channel devices of similar dimension (and practical capacitance, voltage rating, and other tradeoffs) due to the greater mobility of negative charger carriers.

But this is still not really a solution, as it is unlikely that your motor's current rating is within even the current sink rating of the N-channel side of the ATmega output.

If you want a simple, unidirectional motor control, you could pursue this idea using one external N-channel MOSFET (or even a biploar NPN power transistor, which will be less efficient but also less delicate) to connect the unpowered side of the motor to ground.

If you want bidirectional control, you will need either + and - power supplies, or four external switching devices taking the roles of the low current N-FET and P-FET totem poles inside each of the two on-chip IO pin drivers you started with.

body:
This is a huge simplification of @Chris Stratton's post, for beginners.

To put it simply, the power that runs your motor is going through your arduino. Your arduino is not made to carry that sort of power.

What you want is an H-Bridge - see https://itp.nyu.edu/physcomp/labs/motors-and-transistors/dc-motor-control-using-an-h-bridge/ - the H Bridge is specially made to carry the power needed.

Note that this page is for a 9v motor, not a 5v motor like yours - you will need to find a more appropriate power supply than a 9v battery (or, you need to find a 9v motor). If you try to power it through USB, you will be drawing the power through your computer - you may damage it!


body:
I'm new to Arduino. I'm using Arduino Mega 2560 board & MATLAB Simulink-Arduino support package and trying to integrate Maxbotix Sonar and Sharp IR sensor for my class project. When I powered single US sensor from Arduino 5V output, the readings are fine. However, when I tried to power IR sensor in parallel with US sensor, IR readings are fine but US readings fluctuate.

So, I tried powering the sensors using BEC (5V-3A). The readings for both sensors are fluctuating(extremely noisy). From the specification mentioned by manufacturers, Maxbotix US sensor draws 2mA of current, whereas IR sensor averagely draws 20mA. Is there any way to solve this problem?

Thank you.

title: Powering Infrared and Sonar sensors using BEC

Answers: 1

body:
I've managed to solve the problem. When external power supply is used to power multiple sensors, connect the GND of that supply with that of the Arduino GND input. For more details, refer to the link below.

http://www.thebox.myzen.co.uk/Tutorial/Power_Supplies.html


body:
I've been wondering for a long time what these pins, labeled `ICSP` and blank, do.

![arduino][1]

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

I can't seem to find a diagram that explains them, so I've been wondering:

 - What are they for?
 - Are they GPIO, or do they do something special?
 - How can you use them?

Thanks for the help.

title: What do these pins on the Uno do?

Answers: 1

body: They're for programming, as well as carrying the non-select signals for SPI. The right one is for programming the main MCU, the left for the USB communication MCU. You should almost never need to use them unless you need to write a bootloader to a new chip or change the fuse or lock settings on them.


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

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

Answers: 2

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

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


body:
Apologies if I have missed a relevant post somewhere, but have search for days to try figure this out...

I have written some C# code to send a Byte Array over Serial from my PC to an Arduino Nano board (Through a USB to Serial Converter)

Why would I not receive the same HEX Values (in the Arduino serial monitor) as the Values I sent?

(The Values should be the HEX for numbers 0 - 9)

C# Code:

    if(!serialPort1.IsOpen)
        {
            serialPort1.BaudRate = 9600;
            serialPort1.DataBits = 8;
            serialPort1.StopBits = System.IO.Ports.StopBits.One;
            serialPort1.Parity = System.IO.Ports.Parity.None;
            serialPort1.PortName = "COM" + cbCOMPort.Text;

            serialPort1.Open();
        }

        byte[] ByteArr = new byte[10];
        ByteArr[0] = 0x30;
        ByteArr[1] = 0x31;
        ByteArr[2] = 0x32;
        ByteArr[3] = 0x33;
        ByteArr[4] = 0x34;
        ByteArr[5] = 0x35;
        ByteArr[6] = 0x36;
        ByteArr[7] = 0x37;
        ByteArr[8] = 0x38;
        ByteArr[9] = 0x39;

        serialPort1.Write(ByteArr, 0, ByteArr.Length);
        serialPort1.Close();
Arduino Code:

    void loop()
    {
    while (Serial.available()) {
    delay(250);

    byte thisByte = Serial.read();

    Serial.print(thisByte,HEX);
    Serial.print(" | ");
    }
    }

Values received in Arduino Serial Monitor:

    D6 | B6 | 96 | 76 | 56 | 36 | 16 | F6 | 8D | 0 |

COMPLETE ARDUINO CODE WITH BLINKING LED TEST CODE

    void setup()
    {
    // start serial port at 9600 bps:
    Serial.begin(9600);
    }

    void loop()
    {
    while (Serial.available()) {
    delay(250);
    // get the new byte:
    byte thisByte = Serial.read();
    // add it to the inputString:
    //inputString += char(intChar);

    if(thisByte == 0x30 || thisByte == 0x39)
    {
    digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(50);             // wait for a second
    digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
    }
    Serial.print(thisByte,HEX);
    Serial.print(" | ");
    }
    }

title: Arduino Serial Hex Values

Answers: 0


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

title: Driving conveyor belts using Arduino Unos

Answers: 1

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.


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

title: Problem with LCD keypad shield and Arduino Uno R3

Answers: 1

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.


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

title: H-Bridge vs Motor shield for the arduino

Answers: 1

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


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

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

Answers: 2

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.


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

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

Answers: 1

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


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

title: Connect Arduino to Galaxy S2 using USB OTG

Answers: 3

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

body:
In my opinion, you have to use this shield to do this: http://arduino.cc/en/Main/ArduinoUSBHostShield

We can't plug in to use Flash Memorys into Android Phones micro USB via OTG Cable. I guess, tablets and maybe phablets can do that because these devices have *USB Host Circuits* inside. On the link, there is USB Host library for examples. This shield can attach onto your Arduino Uno.

*Edit: I have already tried to do this by doing right like you. I couldn't find any solution then I get the shield, but I still can not do to make any control from both Arduino Uno and my Android phone. Anyway, I know this is about our phones not to have USB Host Component*


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

title: OSC parsing code. Can it be optimised?

Answers: 1

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


body:
I'm Tom. I'm pretty new to electronics and programming but I've been getting better. So, recently I bought a 93lC46B EEPROM from Element 14 (It was $0.28! Why not!). I've been doing some research and reading the datasheet VERY carefully. But I still can't get the EEPROM to work right. I'm using an Arduino Uno to program the chip by using the Bit-Banging method. So what I've understood is that I need to cycle the clock, then pull the CS (Chip select) to high and then cycle the clock after each bit like this:

    digitalWrite(CLK, LOW);
    digitalWrite(DATAIN, VALUE);
    digitalWrite(CLK, High);

But so far, that method hasn't been working right. I can't seem to read or write to the device properly. I'm using this set of bits to write 1 and 2 to the first address of the ROM: 1 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0 1 1 0 0 1 0.

Here's my code so far (Sorry in advance on how bad it is):

    #define DATAOUT 11//Comes from DO on chip MISO
    #define DATAIN 13 //Goes to DI on chip    MOSI
    #define CLK 10
    #define CS 9

    int data[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    int inst1[] = {1,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,1,0,0,1,1,0,0,1,0};
    int inst2[] = {1,1,0,0,0,0,0,0,0};

    void setup(){
      Serial.begin(9600); //Start serial coms

      pinMode(CS, OUTPUT);
      pinMode(DATAOUT, OUTPUT);
      pinMode(DATAIN, INPUT);
      pinMode(CLK, OUTPUT);
      digitalWrite(CS, LOW);

      //Write 12 to address 1
      digitalWrite(CS, HIGH); //Enable device
      //Write to memory
      for(int i=0;i<25;i++){
        Write(inst1[i]);
      }
      digitalWrite(CS, LOW); //Disable device
      delay(250); //TCSL Delay
      Serial.print("Memory sucessfully written\n");

      //Read memory
      digitalWrite(CS,HIGH); //Enable device
      for(int i=0;i<9;i++){
        Write(inst2[i]);
      }
      Serial.print("Read instruction written\n");
      for(int i=0;i<16;i++){
        saveBit(i);
      }
      for(int i=0;i<16;i++){
        Serial.print(data[i]+"\n");
      }
      digitalWrite(CS,LOW);
      delay(250);
      Serial.print("Read successful!\n");
    }

    void Write(int Bit){
      digitalWrite(CLK, LOW);
      if(Bit==0){
        digitalWrite(DATAIN, LOW);
      }
      if(Bit==1){
        digitalWrite(DATAIN, HIGH);
      }
      digitalWrite(CLK, HIGH);
      delay(1);
    }

    void saveBit(int outbit){
      digitalWrite(CLK, LOW);
      if(digitalRead(DATAOUT) == HIGH){
        data[outbit] = 1;
      }
      if(digitalRead(DATAOUT) == LOW){
        data[outbit] = 0;
      }
      digitalWrite(CLK, HIGH);
      delay(1);
    }

    void loop(){

    }

title: Program/Read 93LC46B with an Arduino with bit-banging

Answers: 0


body:
Im trying to program my Arduino Due and it seems that I have to disconnect the display from it every time. Is there a work around for this?

Im using a 7" TFT with a CTE TFT LCD/SD Shield with a arduino due board.

title: How to program your Arduino Due while its connected to a display?

Answers: 0


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

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

Answers: 1

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.


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

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

Answers: 1

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;


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

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

Answers: 1

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


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

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

Answers: 5

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


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

title: Arduino cannot communicate with PC after running servo

Answers: 1

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.


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

title: Is this Bluetooth module cool for Arduino?

Answers: 3

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/


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

title: Lowest power possible in Arduino

Answers: 6

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


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

title: How to "implement" an Arduino prototype?

Answers: 3

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.


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

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

Answers: 1

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


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

title: Arduino + WizFi 210 (WiFi) HTTP POST

Answers: 1

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


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

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

Answers: 1

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.


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

title: Arduino screws up trivial program involving enum

Answers: 3

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)


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

title: Arduino PWM Frequency - Pros and Cons of Modifying

Answers: 1

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.


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

title: Replacing the Voltage regulator of a fried Arduino

Answers: 1

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


body:
I have problem to send data from processing to arduino mega.

**Processing Code :**

    import processing.serial.*;

    Serial myPort;

    void setup()
    {
    println(Serial.list());
    String arduinoPort = Serial.list()[0];
    myPort = new Serial(this, arduinoPort, 9600)
    }

    void draw()
    {
    byte a= 3;
    myPort.write(char(a));
    }

**Arduino Code :**

    #include <Servo.h>
    #include <Wire.h>

    Servo myservo1;
    Servo myservo2;

    void setup()
    {
    Serial.begin(9600);
    myservo1.attach(9);
    myservo2.attach(10);
    myservo1.write(90);
    myservo2.write(90);

    }

    void loop()
    {

    if(Serial.available()>0){
    myservo1.write(70);
    myservo2.write(70);

    }

    }

Code is really simple, processing send a value to trigger arduino mega turning 2 servo
motors.

But it doesn't response at all..
Please help if anyone has any clue.

Thanks :))

title: Sending data from processing to arduino

Answers: 0


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

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

Answers: 2

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