body:
I made a super simple arduino uno sketch to send a serial byte once every second:

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

    void loop(){
       Serial.write(12); // send a byte with the value 12
       delay(1000);
    }

My arduino is hooked up to com 3.

On the other end of the line, I have a C++ program with the following read function:

    int Serial::ReadData(char *buffer, unsigned int nbChar)
    {
        //Number of bytes we'll have read
        DWORD bytesRead;
        //Number of bytes we'll really ask to read
        unsigned int toRead;

        //Use the ClearCommError function to get status info on the Serial port
        ClearCommError(this->hSerial, &this->errors, &this->status);

        //Check if there is something to read
        if(this->status.cbInQue>0)
        {
            //If there is we check if there is enough data to read the required number
            //of characters, if not we'll read only the available characters to prevent
            //locking of the application.
            if(this->status.cbInQue>nbChar)
            {
                toRead = nbChar;
            }
            else
            {
                toRead = this->status.cbInQue;
            }

            //Try to read the require number of chars, and return the number of read bytes on success
            if(ReadFile(this->hSerial, buffer, toRead, &bytesRead, NULL) && bytesRead != 0)
            {
                return bytesRead;
            }

        }

        //If nothing has been read, or that an error was detected return -1
        return -1;

    }

This seems to check only one time if data is available, so obviously I have to loop through it until data comes in.  I did that in my main program:

    #include "Serial.h"
    #include <iostream>

    using namespace std;

    int main(void)
    {
     Serial serial("COM3");

     char* c = "";
     int len = strlen(c);
     while(c == "")
     {
      serial.ReadData(c, len);
     }

     cout << "\n\n";
     system("PAUSE");
    }

When I do this, my C++ program gets stuck in an infinite loop waiting for data from the arduino, and I cannot figure out why this is happening.  My program never sees the data the arduino is sending.

This Serial class works and is configured properly because I can SEND all the data I want to the arduino without any problems.  My issues are only with reading back from the arduino.

Can someone please help me figure out why this is not working?

title: Why can't this C++ program read my arduino's Serial.write()?

Answers: 2

body:
The problem is in your C++ program at the other end of the line (not the Arduino side):

    char* c = "";
    int len = strlen(c);
    while(c == "")
    {
        serial.ReadData(c, len);
    }

Here, `len` is zero because that is the length of "" , the empty string! Thus, in your loop, you ask `ReadData` to read 0 bytes. Hence, the condition of your `while` loop is always true as, `c` never changes.

Also, the `while` condition seems incorrect as it is not recommended in C++ to compare 2 strings (defines as `char *` or `char [...]`) with `==`. In your situation, what is important is the number of characters read by `ReadData`:

    char c[LEN + 1];
    int numBytes = 0;
    while(true)
    {
        numBytes = serial.ReadData(c, LEN);
        if (numBytes != -1)
        {
            // Terminate the string if we want to use c variable as a string
            c[numBytes] = 0;
            break;
        }
    }

in the code above, `LEN` is the number of characters you want to read at one time, in you example it should be set to 1, either as a `#define` or as a `const` variable:

    // either:
    #define LEN 1
    // or:
    const int LEN = 1;

The code above also ensures that `c` can be used as a normal string, by adding a `0` at the end. This is mandatory only if you want to use string functions on `c` such as `strlen`, `strcpy`, `strchr`... otherwise `numBytes` is enough to manage the number of characters read into `c`.

body:
    char* c = "";
    while(c == "")

The variable named c is a misnomer, because it is a pointer to a string, not a character.
For example c = 0x123456.

You should use a more explicit name for your variable.

This first line assigns a pointer to an empty string to the c pointer.
So, the value stored at address 0x123456 == whatever pointer to a static memory address containing '\0'

Note that no memory has been allocated to hold characters. Only a pointer to char has been allocated. Thus you cannot store anything in your string!!

You could write something like:
`char data[2] = "";`
That would allocate a pointer, and a string to hold 2 characters

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

The second line, `while(c == "")` compares a real memory pointer (e.g. 0x123456) with a compiler pointer.
`""` is not a real application pointer, you should not manipulate it.

So that second line relies on a compiler behavior.

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

If I were you I would wrap the multi-char routine into a single-char routine. For example:

    int ReadChar(char *c)
    {
      return ReadData(c, 1);
    }

Then:

    main()
    {
      char c;
      ReadChar(&c);
    }

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

On a different note, I think the compiler should catch such error.
The line `c == ""` would never do anything useful and should be caught.


body:
I have a program where the Arduino acts as an Ethernet Server.

The client continuously sends packets which is of the following format

    Start Byte=0x7E;
    Some Data/Command Bytes;      //Can be of varying length
    End Byte=0x7A;

Some packets take more time to process than others.

So my question is what is the best way to read the bytes of the memory so that we always work on one packet at a time.I can read in data from the buffer one at a time and loop through till the `END BYTE` is reached but it doesn't seem a very efficient way to get the packets.

I would be interested if someone has better ideas on how to read in packets one at a time from the buffer in the most efficient way possible.

title: Best way to process data received by EthernetServer

Answers: 0


body:
In [this post](https://arduino.stackexchange.com/questions/3489/arduino-boot-loader-problem), it was mentioned that to get the Arduino IDE to support an ATmega328 (only the ATmega328P is supported):

> I should mention the Arduino way of doing this, is to create a new
> boards.txt file with this chip and add (not change) the avrdude.conf
> file. This will allow programing either from selecting the correct
> board. but that is another subject.

After a great deal of research in the past, and attempted modifications to boards.txt and avrdude.conf, I arrived at the conclusion that the Toolchain doesn't support the ATmega328 therefore the changes will have no effect.

Can anyone confirm that they have successfully found a way to make these changes, so we can avoid the need for a work-around?

title: How to modify Arduino boards.txt to support new MCUs

Answers: 1

body:
Please, Note that the Arduino IDE is behind on many of the tools. In this case avrdude and its conf file, along with avr-gcc

**First:**

    .\arduino-1.5.6-r2\hardware\tools\avr\etc\avrdude.conf

needs to support the m328 in addition to m328p. This can be done by either updating

    .\arduino-1.5.6-r2\hardware\tools\avr\bin\avrdude.exe

to something like [avrdude-6.1-svn-20131205-mingw32](http://download.savannah.gnu.org/releases/avrdude/). along with replacing the conf file with the new one

    .\arduino-1.5.6-r2\hardware\tools\avr\etc\avrdude.conf

file that has both m328 along with the m328p. Note 6.1 supports a parent method, making it easy to duplicate chips with different signatures. Or use existing 5.11 and add to its

    .\arduino-1.5.6-r2\hardware\tools\avr\etc\avrdude.conf

file by duplicating the entire m328p section and renaming the new entry to "m328" along with the correct signature.

**Second:**

avr-gcc need to be updated to support compiling both the m328p and m328. Yes, it just a semantic thing. But the next part will send either ATmega328p or ATmega328 to both gcc and dude. which both need to support it. One can simply copy over

    .\arduino-1.5.6-r2\hardware\tools\avr\

with the new tool chain. I used [avr-gcc-4.8_2013-03-06_mingw32](http://sourceforge.net/projects/mobilechessboar/files/avr-gcc snapshots (Win32)/)

**Third:**

replace the following line in boards.txt

    uno.build.mcu=atmega328p

with

    ## Arduino ATmega328P
    ## ---------------------------------------------
    uno.menu.cpu.atmega328p=ATmega328P
    uno.menu.cpu.atmega328p.build.mcu=atmega328p

    ## Arduino ATmega328
    ## ---------------------------------------------
    uno.menu.cpu.atmega328=ATmega328
    uno.menu.cpu.atmega328.build.mcu=atmega328

This will add an option to the IDE when UNO is selected for either chip. And subsequently send the correct MCU to both the compiler and avrdude.

----------

**Proof:**

Below are the verbose output of the IDE with the above changes. Note the -mmcu and -p for both options. As a real unit is was not connected it yielded the "not in sync" error. Where this shows it all works.

    C:\projects\Arduino\arduino-1.5.6-r2\hardware\tools\avr\bin\avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\cores\arduino -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\variants\standard C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp -o C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp.o
    ...
    C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex

    Sketch uses 444 bytes (1%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
    C:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/bin/avrdude -CC:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex:i

    avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
    ...
    avrdude: stk500_getsync(): not in sync: resp=0x00

    avrdude done.  Thank you.

----------

    C:\projects\Arduino\arduino-1.5.6-r2\hardware\tools\avr\bin\avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -MMD -mmcu=atmega328 -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\cores\arduino -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\variants\standard C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp -o C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp.o
    ...
    C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex

    Sketch uses 444 bytes (1%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
    C:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/bin/avrdude -CC:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328 -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex:i

    avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
    ...
    avrdude: stk500_getsync(): not in sync: resp=0x00
    avrdude done.  Thank you.


body:
I tried this code:

    #include <Adafruit_CC3000.h>
    #include <ccspi.h>
    #include <SPI.h>
    #include <string.h>
    #include "utility/debug.h"
    #include "DHT.h"
    #include<stdlib.h>

    // These are the interrupt and control pins
    #define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
    // These can be any two pins
    #define ADAFRUIT_CC3000_VBAT  5
    #define ADAFRUIT_CC3000_CS    10
    // Use hardware SPI for the remaining pins
    // On an UNO, SCK = 13, MISO = 12, and MOSI = 11
    Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIVIDER); // you can change this clock speed

    // WLAN parameters
    #define WLAN_SSID       "ID"
    #define WLAN_PASS       "PASS"
    #define WLAN_SECURITY   WLAN_SEC_WPA

    #define IDLE_TIMEOUT_MS  3000      // Amount of time to wait (in milliseconds) with no data
                                       // received before closing the connection.  If you know the server
                                       // you're accessing is quick to respond, you can reduce this value.
    #define DHTPIN 7
    #define DHTTYPE DHT11

    // What page to grab!
    #define WEBSITE      "myapp.herokuapp.com" //your website

    uint32_t ip;
    DHT dht(DHTPIN, DHTTYPE);

    const unsigned long connectTimeout  = 15L * 1000L;
    void setup(void)
    {
        Serial.begin(115200);
        //Serial.begin(9600);
        Serial.println(F("\nInitializing..."));
        if (!cc3000.begin())
      {
        Serial.println(F("Couldn't begin()! Check your wiring?"));
        while(1);
      }
        Serial.print(F("\nAttempting to connect to ")); Serial.println(WLAN_SSID);
        if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
        Serial.println(F("Failed!"));
        while(1);
      }
        Serial.println(F("Connected!"));

        Serial.println(F("Request DHCP"));
      while (!cc3000.checkDHCP())
      {
        delay(100); // ToDo: Insert a DHCP timeout!
      }
      ///if he login and he can show info/ mean he login and only then continue
        while (! displayConnectionDetails()) {
        delay(1000);
      }
    }

    void loop(void)
    {
     float h = dht.readHumidity();
      float t = dht.readTemperature();

      int temperature = (int) t;
      int humidity = (int) h;

      String temperatures=String(temperature);
      String humiditys=String(humidity);

      Serial.print("Temperature: ");
      Serial.print(temperatures);
      Serial.print(" F /");
      Serial.print("Humidity: ");
      Serial.print(humiditys);
      Serial.print("%");
      Serial.println("");

       // Create the request.
      String request = "GET /plants/0003/create_measurement?capsules=1&humidity=" + humiditys + "&soil_moisture=40&temperature=" + temperatures + " &water_tank=10&light=20&battery=4 HTTP/1.1\r\n";
      // Print and Send the request
      Serial.println("About to send: ");
      Serial.print(request);
      Serial.print(F("Host: "));
      Serial.print(WEBSITE);
      Serial.print(F("\r\n"));
      Serial.print(F("User-Agent: Compost Monitor/1.0\r\n"));
      Serial.println();
      send_request(request);

    }

    void send_request (String request)
    {
      Serial.println("Enter Request");
      ip = 0;
      // Try looking up the website's IP address
      Serial.print(WEBSITE); Serial.print(F(" -> "));
      while (ip == 0) {
        if (cc3000.getHostByName(WEBSITE, &ip)<0) {
          Serial.println(F("Couldn't resolve!"));
        }
        delay(500);
      }

      cc3000.printIPdotsRev(ip);
        Serial.println();
    Serial.println("after Ip");

      Adafruit_CC3000_Client www ;
       unsigned long t = millis();

    do {
        Serial.println("Into do");
       www = cc3000.connectTCP(ip, 80);
    } while((!www.connected()) &&
        ((millis() - t) < connectTimeout));

      String b="0";
      if(www.connected())
      {
      b="1";
      }
      Serial.println("! Out Do" + b);
      if (www.connected()) {
        www.print(request);
        www.print(F("Host: "));
        www.print(WEBSITE);
        www.print(F("\r\n"));
        www.print(F("User-Agent: Compost Monitor/1.0\r\n"));
        www.print(F("\r\n"));
        www.println();
      } else {
        Serial.println(F("Connection failed"));
        return;
      }

      Serial.println(F("-------------------------------------"));
    Serial.println("time to reed");
      /* Read data until either the connection is closed, or the idle timeout is reached. */
      unsigned long lastRead = millis();
      while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
        while (www.available()) {
          char c = www.read();
          Serial.print(c);
          lastRead = millis();
        }
      }
      www.close();
      Serial.println(F("-------------------------------------"));
    Serial.println("no time to reed");

    }

    bool displayConnectionDetails(void)
    {
      uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

      if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
      {
        Serial.println(F("Unable to retrieve the IP Address!\r\n"));
        return false;
      }
      else
      {
        Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
        Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
        Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
        Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
        Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
        Serial.println();
        return true;
      }
    }

This sends data to my server. However, no entries are appearing on my server.

title: How to send data from cc3000 to herokuapp server

Answers: 0


body:
I am relatively new to Arduino platform and not know much. I am working on a Bicycle speedometer with turn and stop indicators.

I am planning on connecting an inductor magnet to calculate the rotation of my front wheel while providing the following services from the same arduino board:

 1. Input horn and turn indicator switches.
 2. Output to turn indicators.
 3. Stop light when one of the brakes is
    applied.

While I am sure of how to connect all the sensors, except the magnet, I am not sure how to handle the various inputs and the outputs at once.

I must be able to horn and stuff while the indicator blinks at a regular interval all the while the monitor keeps displaying my speed and distance covered.

Any reference or help would be greatly appreciated.
Thanks in advance.

Bharath. S.

title: How to handle multiple input pins at once?

Answers: 4

body:
Since your post mentioned that you are relatively new to Arduino, in case you have not done below, you may start by

a) get a printed book, ebook or 'well structured' tutorial, says, systematically covering 10 to 20 topics instead of short tutorial on just one topic

b) this will get you covered for your task 1 to 3, but, only as individual tasks.

c) after mastering (b), try to combine them, instead of stand alone in tutorial

d) interrupt is advance topic and not be cover in many starting books. You can see http://arduino.cc/en/Reference/attachInterrupt   Interrupt works only on certain pins, depending on which Arduino board model.

body:
Since I apparently can't comment yet, here's an incomplete but I think useful answer; this is a perspective on how I would go about it:
For the brake lights it's pretty easy to just put it in a loop that 'if brakes, brake light on'. I would say keep everything in one loop, no interrupts or anything. If an indicator switch is on, the loop gets the current time with millis(), sets a flag to on, and turns on the light. It then loops like normal, checks the flag and if sufficient time has passed turns off the light, gets a new time, and unchecks the flag. If i understand your needs correctly, the rest is just 'if input high, output high' that you can check every time through the loop. Can't help with the magnet though, no experience there.

body:
How fast do we need to read the magnetic switch to not miss any pulses? I'll make some working assumptions:

 - Using 700c wheel and 28mm tire [assumed; adjust as necessary]
 - Rolling radius 2.1m [[from here][1]; there are other ways to arrive at this]
 - Max speed 22 m/sec (50mph), [working assumption; adjust as you see fit]
 - Magnet and switch interact for at most 3% of a rotation, [WAGuess]

The wheel will have to turn at ~10RPS at max speed giving a pulse period of 100ms. The pulse width will be at most 3% of that, or 3ms.

Your service loop would have to execute in somewhat less than 3ms, every time, in order to not miss any wheel pulses and that's if I haven't been too optimistic about the pulse width. I'd personally assume a 1ms maximum loop time, then test it on the road by sampling & logging wheel-pulse level with an Arduino at at least 10x that rate or 10+KHz.

Or I'd go with an interrupt-driven wheel pulse period timer not width) to ease the constraints on the main loop.

The main loop need only poll your turn, brake, and horn switches and a timer for blinking the turn signals. Even if the timing is a little erratic for some reason, no harm is done, and nothing is likely to be apparent to the rider or other road users.

  [1]: http://www.bikecalc.com/wheel_size_math

body:
You need a finite state machine. Then you can have code that would typically require `delay()` but without blocking the `loop()` while it waits.

 Here is a crude class I wrote to do it

**stateMachine.h**

    /*
     StateMachine

     Class to perform some state machine logic on the Arduino
    */

    #if (ARDUINO >= 100)
     #include <Arduino.h>
    #else
     #include <WProgram.h>
     #include <pins_arduino.h>
    #endif

    class StateMachine
    {
      public:
      // Constructor
      StateMachine(void (*)(void));
      // Functions
      void update(void);
      void nextState(uint16_t, uint32_t);
      uint16_t currentState(void);
      void stop(void);

      private:
      void (*callback)(void);   // Callback to state machine code
      uint16_t state;      // Current state of the machine
      uint32_t delay;      // Delay until state change. Delay of -1 is stopped
      uint32_t timer;      // Timer to keep track of last run time
      uint8_t isRunning;   // Are we running?
      int16_t counter[2];  // Two counters for general use
    };

**stateMachine.cpp**

    /*
     StateMachine

     Class to perform some state machine logic on the Arduino
    */

    #include "StateMachine.h"

    //
    // Constructor
    //
    StateMachine::StateMachine(void (*callbackFunction) (void)) {
      state = 0;
      delay = 0;
      timer = 0;
      isRunning = 0;
      callback = callbackFunction;
      counter[0] = 0;
      counter[1] = 0;
    }

    //
    // Update the state machine
    //
    // Use in loop()
    // Will keep running over and over unless stop()ed
    //
    void StateMachine::update(void) {
      if (isRunning) {
        if(millis() - timer >= delay) {
          timer = millis();
          //Call the state machine
          callback();
        }
      }
    }

    //
    // Current state
    //
    uint16_t StateMachine::currentState() {
      return state;
    }

    //
    // Next state
    //
    void StateMachine::nextState(uint16_t nextState, uint32_t nextDelay) {
      state = nextState;
      delay = nextDelay;
      isRunning = 1;
      //Restart timer
      timer = millis();
    }

    //
    // Stop
    //
    void StateMachine::stop()
    {
      isRunning = 0;
    }

Then you need a function with the logic:

    void exampleStateMachineCallback()
    {
      switch (exampleStateMachine.currentState()) {
        case 0:
          //initialise everything and then got to state 1 immediately
          exampleStateMachine.nextState(1,0);
          break;

        case 1:
          //do something then do state 2 500ms later
          exampleStateMachine.nextState(2,500);
          break;

        case 2:
          //do something then do state 1 500ms later
          exampleStateMachine.nextState(1,500);
          break;
      }
    }

Finally in the global variables we join them up

    StateMachine exampleStateMachine = StateMachine(exampleStateMachineCallback);

And in `loop()` we call update all the time

   exampleStateMachine.update();

The states implement your logic. For example, state 1 in the above code could be turn on the led, and state 2 could be turn it off. State 0 might prepare some variables. If you wanted the led to start flashing with a button press it might look like

    if(digitalRead(LEFT_BUTTON) == HIGH) exampleStateMachine.nextState(0,0);

And if you wanted to stop it:

    exampleStateMachine.stop();

In the StateMachine class I put two counters, you could use these to do other timers. For example, to flash a led for 30 seconds it might look like

    void exampleStateMachineCallback()
    {
      switch (exampleStateMachine.currentState()) {
        case 0:
          exampleStateMachine.counter[0] = 0;
          exampleStateMachine.nextState(1,0);
          break;

        case 1:
          digitalWrite(13,HIGH);
          exampleStateMachine.nextState(2,500);
          break;

        case 2:
          digitalWrite(13,LOW);
          exampleStateMachine.counter[0]++;
          if (exampleStateMachine.counter[0] >= 30) exampleStateMachine.stop();
          else exampleStateMachine.nextState(1,500);
          break;
      }
    }


body: I'm having trouble figuring out how to start my project. The objective is to control a robot with four servo motors and six DC motors through bluetooth. I have a bluetooth shield from Adafruit and I'm using the Arduino UNO. Ideally, I want to control this robot by sending it packets through Processing. The problem is I don't know how to create a packet with a header, payload, and checksum. I can't find any examples; can anyone help me find something to help me get started?

title: Arduino Packet for Bluetooth

Answers: 2

body:
First, depending on the degree of reliability you need, you may not actually have to do this yourself, as the bluetooth implementation will already invisibly-to-you add, verify, and remove a packet and checksum framing around your data.  But let's assume you want to add your own as well.

A packet is a batch of data to be transmitted as a contained unit.  It may or may not contain exactly one useful message, but it is quite convenient if it does, and since you will be doing your own packetization (at this level) you can make sure that it does.  So basically you will transmit something that has a structure, for example:

 1. Hi, I'm a packet
 2. attention HAL
 3. "Open the pod bay doors"
 4. The bytes in this message should add up to xx if you ignore the overflow
 5. That was a packet

There are countless ways you could implement this, but your life will be a lot easier if you make both the messages and the packet structure human readable, so that you can watch on the serial monitor, and perhaps even type manually.  So let's say you did something like

    M1=200/BF\n

For simplicity sake, instead of having a "Hi I'm a packet" header, we just use the newline character '\n' to mark the end of a packet, and *assume* that whatever comes next is the start of a new packet.  Further, since bluetooth is already creating a one-to-one link, you don't need to address who you are talking to.

Now we have a message, for example "M1=200" meaning "drive motor 1 at PWM level 200" (out of 255).

I'm somewhat randomly choosing the '/' character to mark the division between the message body and it's checksum.

"BF" might be the low two hex digits of adding up all the previous bytes in this message (it's not, I just picked something random).

And finally you have your newline to mark the end of a message **and** the end of a packet, since in this scheme we've decided that 1 packet = 1 message.

*For extra fun, if the robot itself is not dangerous, you can make a test mode where the receiver will accept messages with no '/' and checksum, and only check the checksum on those where it is present.  This would allow you to manually type messages into a terminal when you are experimenting.  Or you can make your own specialized terminal program which calculates and appends a checksum each time you press return*

body:
Start simple.

1. send serial data from PC. either use Arduino USB port or on real hardware serial port, needs USB to serial adaptor and a terminal software. (see diagram in below web)

2. for starting, no need for header. Just use simple text as defined yourself

3. on Arduino side, read serial input. For example, type letter 'a' on PC will blink LED, 'b' to move servo 30 degree

4. Replace serial communication (like RS-232 or a UART) with Bluetooth. Bluetooth supports many 'profiles', like headset, keyboard, etc. that are not suitable in your case.

See below video. You need to use the SPP profile. see https://learn.sparkfun.com/tutorials/bluetooth-basics/bluetooth-profiles

Make sure your purchased bluetooth device supports SPP. Some bluetooth device are permanently setup to do one fix action. However, many bluetooth need to be 'programmed' (told what to do) before doing the task via AT command. Set speed, pairing, etc.

https://learn.sparkfun.com/tutorials/using-the-bluesmirf/example-code-using-command-mode

http://www.instructables.com/id/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/


body:
I need to access distance data using a LV-EZ0 Maxtronix ultrasonic sensor: [MB1000
LV-MaxSonar®-EZ0™High Performance Ultrasonic Rangefinder][1]

Can anyone suggest what particular arduino libraries or code would be most useful?

I noticed this new ping library, [NewPing][2]

Would this work for my purposes with this particular sensor?

  [1]: http://www.maxbotix.com/Ultrasonic_Sensors/MB1000.htm
  [2]: http://playground.arduino.cc/Code/NewPing

title: Coding and libraries for Maxtronix Ultrasonic sensors

Answers: 1

body:
Likely work in pulse mode (library you mentioned) and sure work in RS232 serial mode (spec. in data sheet page 2, top, read data number as text).

How many sensors do you need and how fast update rate? Serial mode is easier if you application need small number of sensor at 'nominal' update rate (Arduino has limited number of hardware serial port, although softserial library may help).

Essentially, in pulse mode, the RX and PW pin is similar to Trig and Echo pin on many widely available sensor (several models number, basically following similar principle). Need care about the high and low relationship as may differ from the default value in library.

Taken from the [data sheet of LV-MaxSonar®-EZ0][1]

> R X – If held low, the EZ0™ will stop ranging. Bring high for 20uS or
> more to command a range reading.
>
> P W – This pin outputs a pulse width representation of range

Specifically you may want to first try the simple (old) ping: [Ping Ultrasonic Range Finder][2]

Changes needed:

1. Your sensor data sheet requires 20 μs trigger pulse while the above is 2 μs;
2. The library read a high pulse. Your sensor data sheet 'send pulse' which likely imply a HIGH pulse, may not need change;
3. The library use one pin for both in and out. your is one pin in (in for sensor, out for Arduino) for trigger and one put out for measurement.

Also, another library. Note the author states that many sensor from the factory differs (may need small change in code): [Distance Detection
with MaxSonar ultrasonic rangefinder][3].

  [1]: http://www.maxbotix.com/documents/MB1000_Datasheet.pdf
  [2]: http://arduino.cc/en/Tutorial/Ping?from=Tutorial.UltrasoundSensor
  [3]: http://playground.arduino.cc/Main/MaxSonar


body:
I have this sketch:

    #include <TimerOne.h>
    #include <IRremote.h>
    #include <RGBMood.h>

    int RECV_PIN = 2;  // IR-Receiver PIN
    int led = 13;       // Satus-LED PIN
    int modus;          // Modus for Interrupt-Querry
    int ledr = 11;       // RGB LED red PIN
    int ledg = 12;       // RGB LED green PIN
    int ledb = 13;       // RGB LED blue PIN
    int SerialBuffer = 0;

    RGBMood m(ledr, ledg, ledb);

    int timerwert = 20;   // Timer time for Interrupt in ms

    String readString;

    // Color arrays
    int black[3]  = { 0, 0, 0 };
    int white[3]  = { 100, 100, 100 };
    int red[3]    = { 100, 0, 0 };
    int green[3]  = { 0, 100, 0 };
    int blue[3]   = { 0, 0, 100 };
    int yellow[3] = { 40, 95, 0 };
    int dimWhite[3] = { 30, 30, 30 };

    int brightness = 0;    // how bright the LED is
    int fadeAmount = 5;    // how many points to fade the LED by
    // etc.

    // Set initial color
    int redVal = black[0];
    int grnVal = black[1];
    int bluVal = black[2];

    int wait = 10;      // 10ms internal crossFade delay; increase for slower fades
    int hold = 0;       // Optional hold when a color is complete, before the next crossFade
    int DEBUG = 1;      // DEBUG counter; if set to 1, will write values back via serial
    int loopCount = 60; // How often should DEBUG report?
    int repeat = 3;     // How many times should we loop before stopping? (0 for no stop)
    int j = 0;          // Loop counter for repeat

    // Initialize color variables
    int prevR = redVal;
    int prevG = grnVal;
    int prevB = bluVal;

    #define ON                0xF4F37A66
    #define OFF               0x1363ADB4
    #define BRIGHTNESS_UP     0xE6721691
    #define BRIGHTNESS_DOWN   0xE9721B48
    #define FLASH             0xFFF00F
    #define STROBE            0xFFE817
    #define FADE              0x39ED1255
    #define SMOOTH            0xFFC837

    #define RED               0x9D561314
    #define GREEN             0XCB8E93A5
    #define BLUE              0xC88E8EEC
    #define WHITE             0x16DBBEE3

    #define ORANGE            0xFFB04F
    #define YELLOW_DARK       0xFFA857
    #define YELLOW_MEDIUM     0xFF9867
    #define YELLOW_LIGHT      0xFF8877

    #define GREEN_LIGHT       0XFF30CF
    #define GREEN_BLUE1       0XFF28D7
    #define GREEN_BLUE2       0XFF18E7
    #define GREEN_BLUE3       0XFF08F7

    #define BLUE_RED          0XFF708F
    #define PURPLE_DARK       0XFF6897
    #define PURPLE_LIGHT      0XFF58A7
    #define PINK              0XFF48B7

    IRrecv irrecv(RECV_PIN);
    decode_results results;

    void setup()
    {
      pinMode(ledr, OUTPUT); // Set RGB LED Pins as Output
      pinMode(ledg, OUTPUT); // Set RGB LED Pins as Output
      pinMode(ledb, OUTPUT); // Set RGB LED Pins as Output
      pinMode(led, OUTPUT); // set Status-LED as Output
      m.setMode(RGBMood::RANDOM_HUE_MODE);  // Automatic random fade.
      m.setHoldingTime(4000);  // Keep the same color for 4 seconds before fading again.
      m.setFadingSteps(150);   // Fade with 150 steps.
      m.setFadingSpeed(50);    // Each step last 50ms. A complete fade takes 50*150 = 7.5 seconds
      m.setHSB(random(359), 255, 255);

    Serial.begin(9600);

      irrecv.enableIRIn(); // Start of IR-Recive

      Timer1.initialize(timerwert); // Initialisation of Timer-Interrupts
      Timer1.attachInterrupt(leseIR); // IR-Read from Interrupt
    }

    void leseIR(){
      if (irrecv.decode(&results)){
         irrecv.resume();  // Receive the next value
        switch (results.value)  {

          case FADE: // Modus Fade (DIY 4)
            modus = 1;
          break;

          case 0xFF906F: // Modus pcambi (DIY 5)
            modus = 2;
          break;

          case ON:  //Power
           modus = 0;
            crossFade(white);         // RGB LEDs Off
          break;
                case OFF:  //Power
           modus = 0;
            crossFade(black);         // RGB LEDs Off
          break;

          case BLUE:  //Blau 0,0,255
            modus = 0;
          crossFade(blue);
          break;

          case RED: //Rot
            modus = 0;
            crossFade(red);
          break;

          case GREEN://Grün
            modus = 0;
            crossFade(green);
          break;

          case WHITE: //Weiss
            modus = 0;
            crossFade(white);
          break;

          case BRIGHTNESS_UP: //DIMMING
            modus = 0;
            // fade in from min to max in increments of 5 points:
      for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
        // sets the value (range from 0 to 255):
        analogWrite(ledg, fadeValue);

      }

          break;

           case BRIGHTNESS_DOWN: //orange
            modus = 0;
          for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) {
        // sets the value (range from 0 to 255):
        analogWrite(ledg, fadeValue);
          }

          break;

          case 0xFFAA55://Grün mitrtel
            modus = 0;

          break;

          case 0xFF926D: //blau mittel
            modus = 0;

          break;

          case 0xFF12ED: //rosa
            modus = 0;

          break;

         }             // Switch END

      }

    }

    void loop() {
    if(modus==1){    // Querry pb Modus:1
    m.tick();
    }

          Serial.println(results.value, HEX);
          Serial.println(DEC);
          Serial.println(DEC);
          Serial.println(DEC);

      }

      int calculateStep(int prevValue, int endValue) {
      int step = endValue - prevValue; // What's the overall gap?
      if (step) {                      // If its non-zero,
        step = 1020/step;              //   divide by 1020
      }
      return step;
    }

    /* The next function is calculateVal. When the loop value, i,
    *  reaches the step size appropriate for one of the
    *  colors, it increases or decreases the value of that color by 1.
    *  (R, G, and B are each calculated separately.)
    */

    int calculateVal(int step, int val, int i) {

      if ((step) && i % step == 0) { // If step is non-zero and its time to change a value,
        if (step > 0) {              //   increment the value if step is positive...
          val += 1;
        }
        else if (step < 0) {         //   ...or decrement it if step is negative
          val -= 1;
        }
      }
      // Defensive driving: make sure val stays in the range 0-255
      if (val > 255) {
        val = 255;
      }
      else if (val < 0) {
        val = 0;
      }
      return val;
    }

    /* crossFade() converts the percentage colors to a
    *  0-255 range, then loops 1020 times, checking to see if
    *  the value needs to be updated each time, then writing
    *  the color values to the correct pins.
    */

    void crossFade(int color[3]) {
      // Convert to 0-255
      int R = (color[0] * 255) / 100;
      int G = (color[1] * 255) / 100;
      int B = (color[2] * 255) / 100;

      int stepR = calculateStep(prevR, R);
      int stepG = calculateStep(prevG, G);
      int stepB = calculateStep(prevB, B);

      for (int i = 0; i <= 1020; i++) {
        redVal = calculateVal(stepR, redVal, i);
        grnVal = calculateVal(stepG, grnVal, i);
        bluVal = calculateVal(stepB, bluVal, i);

        analogWrite(ledr, redVal);   // Write current values to LED pins
        analogWrite(ledg, grnVal);
        analogWrite(ledb, bluVal);

        delay(wait); // Pause for 'wait' milliseconds before resuming the loop

      }
      // Update current values for next loop
      prevR = redVal;
      prevG = grnVal;
      prevB = bluVal;
      delay(hold); // Pause for optional 'wait' milliseconds before resuming the loop
    }

It's working like a charm, the fade operates smoothly using `timer1`, the colors appear correct on led, but I can't fix the brightness part. **Can  someone provide sample code to do this?**

If anyone else wants to use the code, I'm using an Arduino Mega 2560, please use the same PINs as mine since timers works only on 11,12,13 on this Arduino. ([link with pin info regarding several Arduino boards][1])

 - [RGB mood library][2]
 - [TimerOne library][3]
 - [IR Library][4]

I'm using a small Xbox 360 IR control (no numbers keypad), some HEX codes are left intact from the original sketch found on internet.

[original topic][5]

  [1]: http://www.pjrc.com/teensy/td_libs_TimerOne.html
  [2]: http://forum.arduino.cc/index.php/topic,90160.0.html
  [3]: http://github.com/PaulStoffregen/TimerOne
  [4]: http://github.com/shirriff/Arduino-IRremote
  [5]: http://forum.arduino.cc/index.php?topic=256671

title: Arduino Remote controlled RGB LED strip, having issues with brightness/dimming

Answers: 2

body:
You don't have a delay in the fade loop, this goes from 0 to 255 almost instantly:

    for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
        // sets the value (range from 0 to 255):
        analogWrite(ledg, fadeValue);
    }

But I'm not sure you want to fade from off to on in one go. If you want to just increment and decrement the brightness:

First notice that `prevR, prevG, prevB` hold the current led values. So we shall use them.

Change the switch case to:

    case BRIGHTNESS_UP:
        modus = 0;
        int c[3];
        // decrease by 0.9*value but also take off 2 so we get to zero
        c[0] = (prevR-2) * 90 / 100;
        c[1] = (prevG-2) * 90 / 100;
        c[2] = (prevB-2) * 90 / 100;
        for( int j = 0; j < 3; j++ ) {
            if (c[j] < 0) c[j] = 0;
        }
        crossFade(c);
        break;

    case BRIGHTNESS_DOWN:
        modus = 0;
        int c[3];
        // increase value by 1/0.9 but also add 2 so we get off zero
        c[0] = (prevR+2) * 100 / 90 + 2;
        c[1] = (prevG+2) * 100 / 90 + 2;
        c[2] = (prevB+2) * 100 / 90 + 2;
        for( int j = 0; j < 3; j++ ) {
            if (c[j] > 100) c[j] = 100;
        }
        crossFade(c);
        break;

I can't check this to see if it works see please test and see.

**Edit**

Different approach:

Global variable for brightness:

    int brightness = 100;
    int c[3];

Change this value each time:

    case BRIGHTNESS_UP:
        modus = 0;
        brightness += 5;
        if (brightness > 255) brightness = 255;
        c[0] = prevR; c[1] = prevG; c[2] = prevB;
        crossFade(c);
        break;

    case BRIGHTNESS_DOWN:
        modus = 0;
        brightness -= 5;
        if (brightness < 0) brightness = 0;
        c[0] = prevR; c[1] = prevG; c[2] = prevB;
        crossFade(c);
        break;

Then in `crossFade` we change the last few lines:

    analogWrite(ledr, redVal * brightness / 255);   // Write current values to LED pins
    analogWrite(ledg, grnVal * brightness / 255);
    analogWrite(ledb, bluVal * brightness / 255);

**Edit 2:**

I think that what might be happening is that the color is reduced by brightness, then that reduced value is saved in prevR/G/B when actually it should just be the full brightness value. Try changing last bit of `crossFade` to :

    prevR = color[0];
    prevG = color[1];
    prevB = color[2];

body:
I've moved the `analogWrite` part of the code inside the `switch case` `BRIGHTNESS_UP` & `BRIGHTNESS_DOWN` and it's working. I also removed the `crossFade(c);` line.

Here's the working code:

    #include <TimerOne.h>
    #include <IRremote.h>
    #include <RGBMood.h>

    int RECV_PIN = 2;  // IR-Receiver PIN
    int led = 13;       // Satus-LED PIN
    int modus;          // Modus for Interrupt-Querry
    int ledr = 11;       // RGB LED red PIN
    int ledg = 12;       // RGB LED green PIN
    int ledb = 13;       // RGB LED blue PIN
    int SerialBuffer = 0;
    int c[3];

    //RGB Pins Array
    int CH[3] = {11, 12, 13};
    int val[3] = {0, 0, 0}; // led brightness 0-255

    RGBMood m(ledr, ledg, ledb);

    int timerwert = 20;   // Timer time for Interrupt in ms

    String readString;

    // Color arrays
    int black[3]  = { 0, 0, 0 };
    int white[3]  = { 100, 100, 100 };
    int red[3]    = { 100, 0, 0 };
    int green[3]  = { 0, 100, 0 };
    int blue[3]   = { 0, 0, 100 };
    int yellow[3] = { 40, 95, 0 };
    int dimWhite[3] = { 30, 30, 30 };

    int brightness = 100;    // how bright the LED is
    int fadeAmount = 5;    // how many points to fade the LED by
    // etc.

    // Set initial color
    int redVal = black[0];
    int grnVal = black[1];
    int bluVal = black[2];

    int wait = 10;      // 10ms internal crossFade delay; increase for slower fades
    int hold = 0;       // Optional hold when a color is complete, before the next crossFade
    int DEBUG = 1;      // DEBUG counter; if set to 1, will write values back via serial
    int loopCount = 60; // How often should DEBUG report?
    int repeat = 3;     // How many times should we loop before stopping? (0 for no stop)
    int j = 0;          // Loop counter for repeat

    // Initialize color variables
    int prevR = redVal;
    int prevG = grnVal;
    int prevB = bluVal;

    #define ON                0xF4F37A66
    #define OFF               0x1363ADB4
    #define BRIGHTNESS_UP     0xE6721691
    #define BRIGHTNESS_DOWN   0xE9721B48
    #define FLASH             0xFFF00F
    #define STROBE            0xFFE817
    #define FADE              0x39ED1255
    #define SMOOTH            0xFFC837

    #define RED               0x9D561314
    #define GREEN             0XCB8E93A5
    #define BLUE              0xC88E8EEC
    #define WHITE             0x16DBBEE3

    #define ORANGE            0xFFB04F
    #define YELLOW_DARK       0xFFA857
    #define YELLOW_MEDIUM     0xFF9867
    #define YELLOW_LIGHT      0xFF8877

    #define GREEN_LIGHT       0XFF30CF
    #define GREEN_BLUE1       0XFF28D7
    #define GREEN_BLUE2       0XFF18E7
    #define GREEN_BLUE3       0XFF08F7

    #define BLUE_RED          0XFF708F
    #define PURPLE_DARK       0XFF6897
    #define PURPLE_LIGHT      0XFF58A7
    #define PINK              0XFF48B7
    #define MAX 255

    IRrecv irrecv(RECV_PIN);
    decode_results results;

    void setup()
    {
      pinMode(ledr, OUTPUT); // Set RGB LED Pins as Output
      pinMode(ledg, OUTPUT); // Set RGB LED Pins as Output
      pinMode(ledb, OUTPUT); // Set RGB LED Pins as Output
      pinMode(led, OUTPUT); // set Status-LED as Output
     //initiate rgb pins output
        for (int i=0; i<3; i++)
      {
        pinMode(CH[i], OUTPUT);
      }

      m.setMode(RGBMood::RANDOM_HUE_MODE);  // Automatic random fade.
      m.setHoldingTime(4000);  // Keep the same color for 4 seconds before fading again.
      m.setFadingSteps(150);   // Fade with 150 steps.
      m.setFadingSpeed(50);    // Each step last 50ms. A complete fade takes 50*150 = 7.5 seconds
      m.setHSB(random(359), 255, 255);

    Serial.begin(9600);

      irrecv.enableIRIn(); // Start of IR-Recive

      Timer1.initialize(timerwert); // Initialisation of Timer-Interrupts
      Timer1.attachInterrupt(leseIR); // IR-Read from Interrupt
    }

    void leseIR(){
      if (irrecv.decode(&results)){
         irrecv.resume();  // Receive the next value
        switch (results.value)  {

          case FADE: // Modus Fade (DIY 4)
            modus = 1;
          break;

          case 0xFF906F: // Modus pcambi (DIY 5)
            modus = 2;
          break;

          case ON:  //Power
           modus = 0;
            crossFade(white);         // RGB LEDs Off
          break;
                case OFF:  //Power
           modus = 0;
            crossFade(black);         // RGB LEDs Off
          break;

          case BLUE:  //Blau 0,0,255
            modus = 0;
          crossFade(blue);
          break;

          case RED: //Rot
            modus = 0;
            crossFade(red);
          break;

          case GREEN://Grün
            modus = 0;
            crossFade(green);
          break;

          case WHITE: //Weiss
            modus = 0;
            crossFade(white);
          break;

          case BRIGHTNESS_UP: //DIMMING UP
            modus = 0;
        brightness += 5;
        if (brightness > 255) brightness = 255;
        c[0] = prevR; c[1] = prevG; c[2] = prevB;
        analogWrite(ledr, redVal * brightness / 255);   // Write current values to LED pins
        analogWrite(ledg, grnVal * brightness / 255);
        analogWrite(ledb, bluVal * brightness / 255);

          break;

           case BRIGHTNESS_DOWN: //DIMMING DOWN
             modus = 0;
        brightness -= 5;
        if (brightness < 0) brightness = 0;
        c[0] = prevR; c[1] = prevG; c[2] = prevB;
        analogWrite(ledr, redVal * brightness / 255);   // Write current values to LED pins
        analogWrite(ledg, grnVal * brightness / 255);
        analogWrite(ledb, bluVal * brightness / 255);

          break;

          case 0xFFAA55://Grün mitrtel
            modus = 0;
          break;

          case 0xFF926D: //blau mittel
            modus = 0;

          break;

          case 0xFF12ED: //rosa
            modus = 0;

          break;

         }             // Switch END

      }
    }

    void loop() {
    if(modus==1){    // Querry pb Modus:1
    m.tick();
    }
    if(modus==2){    // Querry pb Modus:1

    }
            Serial.println(prevR);
            Serial.println(prevG);
            Serial.println(prevB);
    //      Serial.println(results.value, HEX);
    //      Serial.println(DEC);
    //      Serial.println(DEC);
    //      Serial.println(DEC);
    //      Serial.print("channel 1,2,3 values:");              // sends  brightness values to the serial monitor
        //  for(int i=0; i<3; i++){                             // every time the remote is pressed
        //  Serial.print(CH[i]);
    //      Serial.print("   ");
        // }
      }

      int calculateStep(int prevValue, int endValue) {
      int step = endValue - prevValue; // What's the overall gap?
      if (step) {                      // If its non-zero,
        step = 1020/step;              //   divide by 1020
      }
      return step;
    }

    /* The next function is calculateVal. When the loop value, i,
    *  reaches the step size appropriate for one of the
    *  colors, it increases or decreases the value of that color by 1.
    *  (R, G, and B are each calculated separately.)
    */

    int calculateVal(int step, int val, int i) {

      if ((step) && i % step == 0) { // If step is non-zero and its time to change a value,
        if (step > 0) {              //   increment the value if step is positive...
          val += 1;
        }
        else if (step < 0) {         //   ...or decrement it if step is negative
          val -= 1;
        }
      }
      // Defensive driving: make sure val stays in the range 0-255
      if (val > 255) {
        val = 255;
      }
      else if (val < 0) {
        val = 0;
      }
      return val;
    }

    /* crossFade() converts the percentage colors to a
    *  0-255 range, then loops 1020 times, checking to see if
    *  the value needs to be updated each time, then writing
    *  the color values to the correct pins.
    */

    void crossFade(int color[3]) {
      // Convert to 0-255
      int R = (color[0] * 255) / 100;
      int G = (color[1] * 255) / 100;
      int B = (color[2] * 255) / 100;

      int stepR = calculateStep(prevR, R);
      int stepG = calculateStep(prevG, G);
      int stepB = calculateStep(prevB, B);

      for (int i = 0; i <= 1020; i++) {
        redVal = calculateVal(stepR, redVal, i);
        grnVal = calculateVal(stepG, grnVal, i);
        bluVal = calculateVal(stepB, bluVal, i);

        analogWrite(ledr, redVal);   // Write current values to LED pins
        analogWrite(ledg, grnVal);
        analogWrite(ledb, bluVal);

        delay(wait); // Pause for 'wait' milliseconds before resuming the loop

      }
      // Update current values for next loop
      prevR = redVal;
      prevG = grnVal;
      prevB = bluVal;
      delay(hold); // Pause for optional 'wait' milliseconds before resuming the loop
    }

thanks geometrikal for your support! You believe it's possible to manipulate the dimming of the fade effect too? It's using the RGBMood class to create a HSB color mix.


body:
I am new to Arduino and SIM300/900 world. But I see that there is a possibility of building a vehicle tracker (approximate locality since I will use GPRS network location) using just these 2 boards.

My question is, is my assumption correct ? Can I build a vehicle tracker using just Arduino **Nano** and SIM300 mobule ? Is there a board that has both of them on one board so that I dont have to buy them separately ? Cost is a major factor on the decision.

title: Arduino Nano and SIM300 module for http calls for location

Answers: 1

body:
Not really.

Module can read the cell ID by below command. However, only phone company has the list of cell ID and their location. This information is only accurate to serving range of a cell, mostly in range of, 0.1 to 15km, from very dense city to country

Module can also read network ID and know, from public information, the country and network operator name.

Example taken from web:

    AT+CREG?

This should give you a result like:

    +CREG: 2,1,"1030","639E"

Working through the 4 returned values, the "2" reflects the
current "+CREG" setting (2 means "Enables unexpected network
registration and location information messages"), "1" indicates
that the phone is registered with the network, "1030" is the
Location Area Code (LAC) in hex (4144 decimal), and "639E" is the
CellID (CI) in hex (25502 decimal).


body: I have looked through the AT command set of Arduino GSM Shield boards. I dont find any AT command that provides network GPS. I wonder what I am missing. Why isn't it possible for GSM module to provide NetworkGPS (the one that is not really accurate) ?

title: Arduino GSM Module with network GPS

Answers: 2

body:
Simple answer is that it is function of cellular network (phone company) instead of the module.

More informative answer is, Position is calculated by network via

  1. serving cell base station ID and location
  2. when phone on standby, it monitors signal strength from multiple base stations and signal strength is roughly related to distance
  3. when phone on transmitting, base station has one more piece of information. It calculates distance through time taken for signal to travel to multiple base stations (called 'time advance' in original GSM)

US E911 utilizes these to locate the phone.

Good technical paper with diagrams
https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=6&cad=rja&uact=8&ved=0CEUQFjAF&url=https://www.fig.net/pub/costarica_1/papers/ts08/ts08_01_schwieger_2407.pdf&ei=Ms3bU8-DItfr8AXT7oLQCg&usg=AFQjCNHImn4G34WC0Naw8IH6g1gfLzykuQ&bvm=bv.72197243,d.dGc

http://en.wikipedia.org/wiki/Positioning_(telecommunications)

body:
This is a very complicated situation.  In short, the module itself does not provide Assisted GPS without both the handset's help, and the help of the carrier.

Since the module is sold as an OEM or embeddable object, the manufacturer either hasn't included such functionality, or hasn't enabled it, or hasn't documented it.

Even if it were included, enabled, and documented, it has to work with the carrier, and each carrier provides different services for different modules.  Some locate solely based on triangulation using cell towers and the module's command channel.  Others depend on the module capturing a short sequence of RF from the GPS network, sending it to the carrier's AGPS server to be processed, which then reports back a very accurate position.

At any rate, this is not a standardized function for embedded cellular modules because cellular networks and carriers vary in how they've chosen to implement AGPS.

If you want to use AGPS in an embedded cellular module, you'll need to work with both the module manufacturer and the cellular carrier to enable that functionality.  It usually involves additional charges - renting an AGPS server, for instance.  These often involve a monthly fee in addition to a per-request fee.  Some companies set up their own AGPS servers to do the processing, but the cellular company still has to provide gross location information based on the tower signal reception.

Suffice to say, this is not something that is common or cheap enough for low volume projects.  Unless you're going to be working with thousands of these devices it's typically cheaper to integrate a standalone GPS chipset in your device.


body: I'm trying to get audio data from an ADC connected to an Arduino into a host PC.  I've done some digging and found LUFA, which I think Arduino uses under the hood. Is it possible to use the Arduino as a USB device, and if so, are there any examples?  Thanks!

title: Using Arduino as USB Device?

Answers: 2

body:
I am confused on what your end purpose is.  do you want something that works or you want to make a project for self-learning purpose.

For ready-made products that you can buy, if you want the PC to be able to input and output sound, there are hundreds models of a) sound card plug into PC  b) external sound card link to PC via USB cable    They ranges from a few USD to 50 to 200 with huge range of performance in terms of sampling rate and number of bits (low noise).

Ardu build-in ADC is 10 to 12 bits. These card are 16 to 24 bits.

See
http://www.bestbuy.com/site/computer-cards-components/sound-cards/abcat0507003.c?id=abcat0507003

24 bits 116 dB SNR very low noise
http://us.creative.com/p/sound-blaster/sound-blaster-z

I used them as test instrument for commercial/university projects with success.

I saw on TV news that same setup (high bit card, at -110dB or lower noise level) used in the underwater signal search for MH370 down plane months ago.

body:
LUFA is used for the USB to serial firmware on the separate USB-serial bridge AVR found on Uno and newer Megas. The firmware is compiled using a supplied makefile. Otherwise LUFA isn't used by Arduino.

But LUFA is probably the right choice if you want to make a USB audio device. It comes with examples of both input and output audio devices. But you will have to compile using the supplied makefile, unless you are really ninja. On a Linux distro it's easy - don't know about other OS'es.

The demo "Audio Input Device Demo" comes with LUFA and is ompatible with the atmega32u4 used on Leonardo. It can be set up to sample analog input and send it to the pc. From the documentation:

> On start-up the system will automatically enumerate and function as a USB microphone. By default, the demo will produce a square wave test tone when the board button is pressed. If USE_TEST_TONE is not defined in the project makefile, incoming audio from the ADC channel 1 will be sampled and sent to the host computer instead.


body:
I am a true beginner here. Trying to build a "slot machine" type game and am in the beginning stages. Found a RNG for LCD code and tweaked it a bit to get three digits to display randomly. Worked just fine. But what I'm trying to accomplish is getting a red LED to blink when none of the RN match, blue when 2 RN match, and green when 3 RN match. What is happening now, is that the LCD will no longer generate random numbers when I press my button UNless I hold the button in for a couple of seconds. As soon as the random numbers appear my green led flashes briefly then the red and blue blink opposite of each other (red on 1 sec, off 1 sec, blue on 1 sec, off 1 sec, repeat......green only briefly when random numbers change). So after hours and hours of searching goggle and trying to figure this out on my own I am turning the folks who know what they are doing :)Please tell me what I am doing wrong.... Any help would be greatly appreciated. So why did the RNG stop working with a single press of my button, and where is my code wrong that gets the correct lighting operation? Here is my code so far

    #include <WProgram.h>
     #include<Arduino.h>
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

    /* pin laayout of the LCD with the arduino:
    arduino pin = LCD pins
    7=RS
    8=E
    9=D4
    10=D5
    11=D6
    12=D7
    RW=ground
    */

    int inpin=2; //switchpin
    int reading; // stocks switchpin

    int inpin2=4; //switchpin
    int reading2; //stocks switchpin

    int inpin3=6; //switchpin
    int reading3; //stocks switchpin

    int ran; //stocks random number for dice roll 1
    int ran2; //stocks random number for dice roll 2
    int ran3; //stocks random number for dice roll 3

    int outpin=LOW;
    int LED1=0; // red LED

    int outpin2=LOW;
    int LED2=1; // Blue LED

    int outpin3=LOW;
    int LED3=3; // Green LED

    void setup()

     {
     lcd.begin(16,2);
       pinMode(LED1,OUTPUT);
       pinMode(LED2,OUTPUT);
       pinMode(LED3,OUTPUT);
     }

      void loop()
      {

        //reading of switch

        reading=digitalRead(inpin);
        reading2=digitalRead(inpin2);
        reading3=digitalRead(inpin3);

        //random numbers generation

        ran3=random(6);
        ran2=random(6);
        ran=random(6);

        {
        if (reading != reading2 != reading3);
          digitalWrite(LED1, HIGH);   // turn the LED on (HIGH is the voltage level)
          delay(1000);               // wait for a second
          digitalWrite(LED1, LOW);    // turn the LED off by making the voltage LOW
          delay(1000);               // wait for a second
      }

      {
        if (reading3 == reading2 || reading);
          digitalWrite(LED2, HIGH);   // turn the LED on (HIGH is the voltage level)
          delay(500);               // wait for a second
          digitalWrite(LED2, LOW);    // turn the LED off by making the voltage LOW
          delay(500);               // wait for a second
      }

      {
        if (reading==reading2==reading3)
          digitalWrite(LED3, HIGH);   // turn the LED on (HIGH is the voltage level)
          delay(250);               // wait for a second
          digitalWrite(LED3, LOW);    // turn the LED off by making the voltage LOW
          delay(250);               // wait for a second
      }

        // Set the screen for the PL1 and PL2 label on the top.

        lcd.setCursor(0,0);
        lcd.print("RL 1");

        lcd.setCursor(6,0);
        lcd.print("RL 2");

        lcd.setCursor(12,0);
        lcd.print("RL 3");

        //display of random number.

        if (reading==HIGH){
            lcd.setCursor(2,1);
            lcd.print(ran);
           delay(250);} // not really clean but used as a debouche founction. That way the µC can read only once the inpin within 250ms. i'll try to improve that.

       if(reading2==HIGH){ //same as the player , only the location of the result on the screen is different
           lcd.setCursor(6,0);
           lcd.print("RL 2");
           lcd.setCursor(8,1);
           lcd.print(ran2);
          delay(250);}

          if(reading3==HIGH){ //same as the player , only the location of the result on the screen is different
           lcd.setCursor(12,0);
           lcd.print("RL 3");
           lcd.setCursor(14,1);
           lcd.print(ran3);
          delay(250);}

And here is the original code I found: http://www.desiquintans.com/articles.php?page=randuino (which also shows how it is wired up).

Tweaked to get the 3 random numbers and not just the two that it was set to:

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

    /* pin laayout of the LCD with the arduino:
    arduino pin = LCD pins
    7=RS
    8=E
    9=D4
    10=D5
    11=D6
    12=D7
    RW=ground
    */

    int inpin=2; //switchpin
    int reading; // stocks switchpin

    int inpin2=4; //switchpin
    int reading2; //stocks switchpin

    int inpin3=6;
    int reading3;

    int ran; //stocks randoms for player 1
    int ran2; //stocks random for player 2
    int ran3;

    void setup(){
      lcd.begin(16,2);
    }

    void loop(){

        //reading of switch

        reading=digitalRead(inpin);
        reading2=digitalRead(inpin2);
        reading3=digitalRead(inpin3);

        //random numbers generation

        ran3=random(6);
        ran2=random(6);
        ran=random(6);

        // Set the screen for the PL1 and PL2 label on the top.

        lcd.setCursor(0,0);
        lcd.print("RL 1");

        lcd.setCursor(6,0);
        lcd.print("RL 2");

        lcd.setCursor(12,0);
        lcd.print("RL 3");

        //display of random number.

        if (reading==HIGH){
          lcd.setCursor(2,1);
          lcd.print(ran);
          delay(250);} // not really clean but used as a debouche founction. That way the µC can read only once the inpin within 250ms. i'll try to improve that.

       if(reading2==HIGH){ //same as the player , only the location of the result on the screen is different
           lcd.setCursor(6,0);
           lcd.print("RL 2");
            lcd.setCursor(8,1);
            lcd.print(ran2);
          delay(250);}

          if(reading3==HIGH){ //same as the player , only the location of the result on the screen is different
           lcd.setCursor(12,0);
           lcd.print("RL 3");
            lcd.setCursor(14,1);
            lcd.print(ran3);
          delay(250);}
    }

title: LED's won't light up when LCD/RNG hits 2 || 3 of a kind

Answers: 1

body:
So after a ton more research I figured out what I was doing wrong. For anyone who reads these answers, I found two web sites to be an enormous help. They are http://playground.arduino.cc/uploads/Main/arduino_notebook_v1-1.pdf  and  http://mikrohw.wz.cz/HakDuino/Arduino_Cookbook.pdf   Good luck to you and have fun with your project. Thank you Gerben & Doowybbob for responding and trying to get me to look in the right direction. Turns out that a lot of my code was correctly heading in the right direction. But in my if statements, I wasn't addressing all the possible states. So now the LEDs light up at the appropriate time and I also added a buzzer. Here is my final code...... Thanks and Cheers, SWTORguy

    #define PIEZO 5 // pin 5 is capable of PWM (Pulse width modulation) output to drive tones
    #include <WProgram.h>
    #include<Arduino.h>
    #include <LiquidCrystal.h>
      LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

    /* pin laayout of the LCD with the arduino:
    arduino pin = LCD pins
    7=RS
    8=E
    9=D4
    10=D5
    11=D6
    12=D7
    RW=ground
    */

    const int button = A5;  // changes 2 to an integer from a constant
    int buttonState;
    int prevButtonState;

    int inpin=2; //switchpin (rolling of dice1)
    int reading; // stocks switchpin

    int inpin2=4; //switchpin (rolling of dice2)
    int reading2; //stocks switchpin

    int inpin3=6; //switchpin (rolling of dice3)
    int reading3; //stocks switchpin

    int ran; //stocks randoms for dice 1
    int ran2; //stocks random for dice 2
    int ran3; // stocks random for dice 3

    int outpin=LOW;
    int LED1=13; //red LED

    int outpin2=LOW;
    int LED2=1; //blue LED

    int outpin3=LOW;
    int LED3=3; //green LED

    int outpin4=LOW;
    int BUZ=5; //piezio Buzzer

    int del = 500; //buzzers delay time for inbetween LED flashes

    void setup(){
       lcd.begin(16,2);
       pinMode (PIEZO, OUTPUT); //pin mapping
       pinMode(LED1,OUTPUT); //pin mapping
       pinMode(LED2,OUTPUT); //pin mapping
       pinMode(LED3,OUTPUT); //pin mapping
       pinMode (button, INPUT); //pin mapping
       pinMode (reading, INPUT); //pin mapping
       pinMode (reading2, INPUT); //pin mapping
       pinMode (reading3, INPUT); //pin mapping
    }

    void loop(){
        buttonState = digitalRead (button);
        if (buttonState != prevButtonState && buttonState == HIGH) //pushing the button
        {
        //reading of switch
        reading=digitalRead(inpin);
        reading2=digitalRead(inpin2);
        reading3=digitalRead(inpin3);

        //random numbers generation
        ran3=random(1,7); // #'s 1 through 6
        ran2=random(1,7); // #'s 1 through 6
        ran=random(1,7); // #'s 1 through 6

        // Set the LCD screen for dice 1-3 label on the top.
        lcd.setCursor(0,0);
        lcd.print("die");

        lcd.setCursor(5,0);
        lcd.print("die2");

        lcd.setCursor(11,0);
        lcd.print("die3");

        //display of random number.
        if (reading==HIGH){
            lcd.setCursor(2,1);
            lcd.print(ran);
            delay(250); // not really clean but used as a debounce function.
        }

        if(reading2==HIGH){
           lcd.setCursor(5,0);
           lcd.print("die2");
           lcd.setCursor(8,1);
           lcd.print(ran2);
          delay(250);
        }

        if(reading3==HIGH){
           lcd.setCursor(11,0);
           lcd.print("die3");
           lcd.setCursor(14,1);
           lcd.print(ran3);
           delay(250);
        }

        /*the logic that tells which LED to blink and when to sound the buzzer
          dependent upon which state the random numbers dispayed are in*/
        if (ran == ran2 && ran2 == ran3) // random number state (3 of a kind)
        {
          for (int c=0; c <= 2; c++) // variable defining how many times the green LED will blink and buzzer sound
          {
              digitalWrite(PIEZO, LOW); // buzzer off
              delay(del); // wait for .5 second
              digitalWrite(LED3, HIGH);   // Green - turn the LED on (HIGH is the voltage level)
              delay(100);               // wait for a second
              digitalWrite(LED3, LOW);    // turn the LED off by making the voltage LOW
              delay(100);               // wait for a second
              analogWrite(PIEZO, 128); //Buzzer on
              delay(del); // wait for .5 second
          }
          digitalWrite(PIEZO, LOW); //buzzer off
        }else{
            if(ran == ran2 || ran2 == ran3 || ran == ran3) // random number state (2 of a kind)
            {
                for (int b=0; b <= 2; b++) // variable defining how many times the blue LED will blink and buzzer sound
                {
                    digitalWrite(PIEZO, LOW); // buzzer off
                    delay(del); // wait for .5 second
                    digitalWrite(LED2, HIGH);  //Blue - turn the LED on (HIGH is the voltage level)
                    delay(100);   // wait for a second
                    digitalWrite(LED2, LOW);  // turn the LED off by making the voltage LOw
                    delay(100);   // wait for a second
                    analogWrite(PIEZO, 128); //Buzzer on
                    delay(del); // wait for .5 second
                }
                digitalWrite(PIEZO, LOW); //buzzer off
            }else{
                for (int a=0; a <= 10; a++) // variable defining how many times the red LED will blink.
                {
                    digitalWrite(LED1, HIGH);   // Red - turn the LED on (HIGH is the voltage level)
                    delay(100);               // wait for a second
                    digitalWrite(LED1, LOW);    // turn the LED off by making the voltage LOW
                    delay(100);               // wait for a second
                }
            }
        }

      }
    }


body:
I've been going through my program again and again, and I can't figure out what is causing it not to work as intended.  First, the story: I'm trying to use an Arduino to control a bunch of relays which are controlling sockets (8 of them). I want to use an Adafruit Trellis LED panel/switches to do this. Basically, when the button is pressed, the LED lights up and the relay gets tripped.  Pressing it again does the reverse.

I will provide my code for inspection.

    #include <Wire.h>
    #include "Adafruit_Trellis.h"

    /***************************************************
    This example shows reading buttons and setting/clearing buttons in a loop
    "momentary" mode has the LED light up only when a button is pressed
    "latching" mode lets you turn the LED on/off when pressed

    Up to 8 matrices can be used but this example will show 4 or 1
    ****************************************************/

    #define MOMENTARY 0
    #define LATCHING 1
    // set the mode here
    #define MODE LATCHING

    Adafruit_Trellis matrix0 = Adafruit_Trellis();

    // uncomment the below to add 3 more matrices
    /*
    Adafruit_Trellis matrix1 = Adafruit_Trellis();
    Adafruit_Trellis matrix2 = Adafruit_Trellis();
    Adafruit_Trellis matrix3 = Adafruit_Trellis();
    // you can add another 4, up to 8
    */

    // Just one
    Adafruit_TrellisSet trellis = Adafruit_TrellisSet(&matrix0);
    // or use the below to select 4, up to 8 can be passed in
    //Adafruit_TrellisSet trellis =  Adafruit_TrellisSet(&matrix0, &matrix1, &matrix2, &matrix3);

    // set to however many you're working with here, up to 8
    #define NUMTRELLIS 1

    #define numKeys (NUMTRELLIS * 16)

    // Connect Trellis Vin to 5V and Ground to ground.
    // Connect the INT wire to pin #A2 (can change later!)
    #define INTPIN A2
    // relay pins
    #define relay1 2
    #define relay2 3
    #define relay3 4
    #define relay4 5
    #define relay5 6
    #define relay6 7
    #define relay7 8
    #define relay8 9
    int i = 0;

    // Connect I2C SDA pin to your Arduino SDA line
    // Connect I2C SCL pin to your Arduino SCL line
    // All Trellises share the SDA, SCL and INT pin!
    // Even 8 tiles use only 3 wires max

    void setup() {
     Serial.begin(115200);
     Serial.println("Trellis on");

     // INT pin requires a pullup
     pinMode(INTPIN, INPUT);
     //relay pins
     pinMode(relay1, OUTPUT);
     pinMode(relay2, OUTPUT);
     pinMode(relay3, OUTPUT);
     pinMode(relay4, OUTPUT);
     pinMode(relay5, OUTPUT);
     pinMode(relay6, OUTPUT);
     pinMode(relay7, OUTPUT);
     pinMode(relay8, OUTPUT);

     digitalWrite(INTPIN, HIGH);

     // begin() with the addresses of each panel in order
     // I find it easiest if the addresses are in order
     trellis.begin(0x70);  // only one
     // trellis.begin(0x70, 0x71, 0x72, 0x73);  // or four!

     // light up all the LEDs in order
     for (uint8_t i = 0; i < numKeys; i++) {
      trellis.setLED(i);
      trellis.writeDisplay();
      delay(50);
     }
     // then turn them off
     for (uint8_t i = 0; i < numKeys; i++) {
      trellis.clrLED(i);
      trellis.writeDisplay();
      delay(50);
     }
    }

    void toggleLight(int i){
     if (trellis.isLED(i))
      trellis.clrLED(i);
     else
      trellis.setLED(i);

    }

    void loop() {
     delay(30); // 30ms delay is required, dont remove me!
     //init relay states
     static int relay1state = 0;
     static int relay2state = 0;
     static int relay3state = 0;
     static int relay4state = 0;
     static int relay5state = 0;
     static int relay6state = 0;
     static int relay7state = 0;
     static int relay8state = 0;

     if (MODE == MOMENTARY) {
      // If a button was just pressed or released...
      if (trellis.readSwitches()) {
       // go through every button
       for (uint8_t i = 0; i < numKeys; i++) {
        // if it was pressed, turn it on
        if (trellis.justPressed(i)) {
         Serial.print("v"); Serial.println(i);
         trellis.setLED(i);
        }
        // if it was released, turn it off
        if (trellis.justReleased(i)) {
         Serial.print("^"); Serial.println(i);
         trellis.clrLED(i);
        }
       }
       // tell the trellis to set the LEDs we requested
       trellis.writeDisplay();
      }
     }

     if (MODE == LATCHING) {
      // If a button was just pressed or released...
      if (trellis.readSwitches()) {
       // go through every button
       for (i; i < numKeys; i++) {
        // if it was pressed...
        if (trellis.justPressed(i)) {

         switch (i)
         {
         case '0':
          relay1state ^= 1; // xor current value with 1 (causes value to toggle)
          if (relay1state) {
           delay(100);
           digitalWrite(relay1, HIGH);
              toggleLight(i);
           Serial.println("Outlet 1 on");
           break;
          }
          else {
           delay(100);
           digitalWrite(relay1, LOW);
           toggleLight(i);
             Serial.println("Outlet 1 off");
           break;
          }

         case '1':
          relay2state ^= 1; // xor current value with 1 (causes value to toggle)
          if (relay2state) {
           delay(100);
           digitalWrite(relay2, HIGH);
           toggleLight(i);
           Serial.println("Outlet 2 on");
           break;
          }
          else {
           delay(100);
           digitalWrite(relay2, LOW);
           toggleLight(i);
           Serial.println("Outlet 2 off");

           break;
          }
          //...add case 3-8 & 9-15
         }
         trellis.writeDisplay();
        }
       }
      }

     }
    }

title: Using an Adafruit Trellis to control a set of relays

Answers: 2

body:
There's an issue with your switch case statement. You switch on ` int i` but your cases use chars like `'1'`. This is comparing the value of `i` to the integer value of the character 0 or 1 which are actually 48 and 49 respectively. Check out an ASCII table for more info on this.

Try removing the single quotes and just have something like this:

    switch(i) {
        case 0:
            //case 0 stuff
            break;
        case 1:
            //case 1 stuff
            break;
    }

This will compare the value of `i` to the number that you expect.

I suppose another way to fix this would be to add 48 to `i` every time you check it. I would change the case statements though.

**UPDATE**

You should be declaring the ready state variables outside of your `loop()` function and then initializing them in `setup()`.
Something like this:

    int ready1state;
    void setup() {
        //setup stuff
        ready1state = 0;
    }

    void loop() {
        //loop stuff
        ready1state ^= 1;
        //use ready1state
    }

body:
Stepping back from your code problems, why are you using relays? Do you mean electromechanical relays? Those draw a lot of current and you need to wire them with a protection diode so they don't destroy the control circuit when you disconnect the power and the inductive field on the relay coil collapses.

If you're switching AC power, mechanical relays are a reasonable way to go, but for DC like motors/LEDs, etc, it's usually better to use electronic switches of some kind (e.g. transistors).


body:
I'm building a small library that will be used and production and released open source. I'm paying a lot of attention to the "best practices" to make sure this code is reliable and easy to use. I also would also like to make this easy to edit. I'm having an issue with the naming scheme of the whole project.

There are a few Arduino naming quirks. If I have a sketch called `mylib`:

 - ...I can't create a tab called `mylib.cpp`. However, I *can* create a file called `mylib.h`...
 - ...The folder and main sketch file **must** be the same name as the folder it is in
 - ...The sketch name (and folder) cannot contain any spaces.

*Well, why are you creating a sketch for a library?* The Arduino IDE won't open a `.cpp` file unless there's a sketch in that folder (and you have to open the `.ino`/`.pde` file in that folder). I'm trying to get this to work with the Arduino IDE so, if users need to edit the library, then can just open the file and go to the correct tab. If they use an external editor, they won't be able to compile it to see if there are any errors.

I'd ideally just do this structure:

    my_lib
       |- my_lib.ino
       |- mylib.cpp
       |- mylib.h

However, a user might see that the folder is called `my_lib` and try including the file `my_lib.h`.

I think this is a major oversight in the Arduino IDE, but I need to have this work with the Arduino IDE. If it was just me working on this code, I might consider making the library directly in a project directory, but that isn't ideal. Is there anything that I can do to bypass this/make it easy for users to edit? Is there any "standard"/"convention" that defines how to do this?

title: How to avoid odd naming rules for Arduino when writing a library?

Answers: 3

body:
Yep, the Arduino IDE kinda sucks eventually. There is no best practise really, as Arduino `*.ino` files aren't proper c / c++ anyway. I would hope that people who know how to write C++ classes (as opposed to Arduino) would be able to do it outside the IDE.

My suggestion would be to make the *.ino file a test file. That is, it runs a set of functions to check that the library behaves as desired. It could also include example code, so people who use the library know how to include it in their programs.

All that being said, time to fly Penguin...  Ditch the Arduino IDE and go with embedXcode or some other third party IDE template :P

![enter image description here][1]

(I just wanted to put a pic of a penguin)

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

body:
For anyone curious what I did, I ended up doing a naming convention like this:

    my_lib_v1_2
       |- my_lib_v1_2.ino
       |- mylib.cpp
       |- mylib.h

Then, the user could include `mylib.h` still, and people with the Arduino IDE could edit it.

body:
The Arduino IDE's restriction of not allowing you to create a .cpp tab with the same name as the sketch has been removed since the 1.6.12 release.

In fact, older IDE versions would happily open and save sketches that contained, e.g., mylib.ino and mylib.cpp. You just needed to create the .cpp file outside of the Arduino IDE.

The reason for this restriction in previous IDE versions was that the file in the temporary build folder generated from the preprocessed sketch was named {build.project_name}.cpp, which would be overwritten by the other .cpp "tab" file of the same name. Of course that is not an issue for your desired usage of the Arduino IDE simply to edit library source files. Later, the Arduino developers changed to the much more sensible system of naming the preprocessed file {build.project_name}.ino.cpp. Thus the restriction was no longer necessary.


body:
I want to make a system that always have the same current (about 1ma) in a water with silver electrode. At start it will be purified water so conductivity will be really low.

But with time silver particle will be released in water, raising his conductivity so if I don't lower the voltage the current will raise too (meaning that bigger particle will be released which I don't want too).

So, is there any way I can measure low current and adapt voltage with the result (since deducting resistance wouldn't be hard).

I know about ASC712 but It seem that he can't be precise enough (steps of 13ma max) to my use.

I precise it's not that long I'm trying to get back in electronics with arduino so many school things have been forgotten.

title: Measure low current with variable voltage

Answers: 2

body:
Alternatively, you can buy ready made unit. Random search from web give example like this has 3 models for, 1.5, 3 and 6kV 1mA constant current.  http://www.matsusada.com/high-voltage/sc/

Safety first if self make (do you need a unit for use or you want to do exercise trying to make it). **May not be a easy project.**

Your post stated 'purified water', resistance will be really high, in many mega ohm range, if it is really pure.

First measure resistance with multitester to get realistic ohm reading in pure and later stage when "with time silver particle will be released in water".

The hi and then lower ohm will get you voltage needed. to drive 1mA through multiple mega ohm need kilo volt and need special circuit and suitable experience for hi volt safety.

body:
What you want is called a constant current source. You can actually build a simple one using [one transistor][1] ; but a better one uses two transistors - as in the left example below - see [this page][2] for explanations.

![Transistor based current source][3]

Here the leds would be your load, R=680 Ohm would give you about 1mA - and you would need to increase the value of the 2k2 resistor to somewhere around 22k.

The problem is that, as John Williams noted, forcing 1mA through a high resistance requires high voltage : 1MOhm would need 1kV, 10MOhm needs 10kV etc. That's very dangerous voltages! and quite some power as well : 10kV at 1mA means 10W.

I think you need to define your needs first :

 - What is a tolerable error on the absolute value of current? (Would constant 1.1mA be OK?)
 - What is a tolerable error on the current variations? (Would current varying between 1.19mA and 1.21mA be OK?)
 - Do you absolutely need 1mA right from start? Or can you accept a lower current at start, growing with increased conductivity until 1mA is reached and then being held nicely constant?

If the above examples are fine, a current source as described above would do the job nicely for less than 1USD.

If you really need a constant current source right from the start, then be prepared to work with expensive and dangerous pieces of equipment.

  [1]: http://en.wikipedia.org/wiki/Current_source#mediaviewer/File:Const_cur_src_113.svg
  [2]: http://www.talkingelectronics.com/projects/TheTransistorAmplifier/TheTransistorAmplifier-P2.html
  [3]: https://i.stack.imgur.com/E01sN.gif


body: I want to write a lipoly powered arduino device that can be launched from sleep mode by pressing a certain key that is connected to ground. Usually, when no in sleep mode I enable the internal pull-up resistor for a definite level. But when in sleep mode, I assume this would drain to much power and hence I want to avoid it. Is it sufficient to just wait for a pin-change interrupt on the same port pin without the internal or an additional external pull-up resistor?

title: External (pin change) interrupt and power consumption

Answers: 2

body: You **must not** leave CMOS inputs floating. This will *increase* power consumption, and as a worst result may damage the device. Use an external pull-up if you feel that the internal pull-up passes too much current.

body:
Tutorial from University of South Florida
https://www.youtube.com/watch?v=HiAbxSO_9nU

Internal pull-up resistor does not drain too much current. Only leakage in nA range. It is correct to use pull up, in your case, as this is what it is designed to do. As Ignacio Vazquez-Abrams, do not leave input pin open.

MCU are designed to do the precise action you mentioned, to wake up on pin change as in mass produced wrist watch and TV remote controller. On remote, MCU sleeps until key pressed. On watch, it wake on timer 1 second) and key change.


body:
As the title, I'd like to reset the Arduino sketch from the linux machine. Is it possible? how?

One solution could be to save the hex file inside the sd card and then upload it via the lua sketch but I think there is a smarter solution.

title: YUN. How to reset the micro controller from linux?

Answers: 2

body: According to the Yun schematic, GPIO18 of the SoC is connected to the MCU reset circuitry. Toggling it should allow you to reset the MCU.

body: Use command `reset-mcu`: it's a linux script that resets the 32u4 via GPIO


body:
I'd like to use an H-Bridge  AND send PWM signal.

I've used this schematics: http://itp.nyu.edu/physcomp/Labs/DCMotorControl
and use the PWM signal inside the *enablePin*. But the H_Bridge is getting very hot.

Am I wrong?

### EDIT:
I'm using and H-Bridge but not for driving a motor, instead I'm driving a peltier cell (like this one: https://www.sparkfun.com/products/10080). What I'm trying to achieve is to have a fixed peltier cell and to have in the same side sometimes hot, sometimes cold. This behaviour is done by switching the positive and negative with the H-Bridge. To control how much cold and how much hot I'm using PWM.

title: H_Bridge with PWM gets too hot

Answers: 4

body:
Short answer: You're drawing too much current through the H-bridge.

Longer answer: The H-bridge is most efficient when fully on and that's when the chip gets rated for the maximum current. The rating also, probably, states that a heat sink is attached to the chip. Using PWM to slow down the motor decreases the current going through the bridge, but also incurs inefficiencies because the transistors / MOSFETs are partially on, and thus acting somewhat as resistors. This inefficiency manifests as heat.

So you have several options.
1. Choose a smaller motor.  This reduces the overall current needed.  Only feasible if this is a learning project.
2. Choose a beefier H-bridge.  This increases the ratings of the bridge to handle current for this motor.
3. Add a heat-sink to the existing bridge.  This will help dissipate the heat generated.

Generally I'd recommend both 2 and 3, but it depends on your ultimate goal of the project.

body:
This L298N board with heat sink is widely available, low cost, used in many successful project with 2 amperes capacity to support reasonably large motors.

Video, tutorial, code example in:

http://www.youtube.com/watch?v=qwNvYYqBy7I

http://www.icstation.com/product_info.php?products_id=2540#.U90l_kBbIlh

http://arduino-info.wikispaces.com/MotorDrivers

http://arduino-info.wikispaces.com/ArduinoShieldL298N

body:
Are you using the `L293NE` or the `SN754410`?

My guess it the `L293NE`. With this one, if you set the enable to low, it will go into "Fast motor stop". What this does is short the two pins of the motor. This will make the motor turn into a dynamo, will all the current that is being generated going through the IC. This will make the IC hot.

This also means you motors are running very inefficiently.

body:
According to data sheet from factory, L293 and L298 do not go into fast stop mode if you connect and program them as below.

They have two inputs to control direction and one ENABLE for PWM.

When PWM signal is zero, both transistors are high impedance according to page 2 of factory data in http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=0CDUQFjAB&url=http://www.ti.com/lit/ds/symlink/l293d.pdf&ei=0z7dU-G4OZPf8AX-loDQCA&usg=AFQjCNEHiZAPaBUP_j8kV3BBPstAKiFDyw&bvm=bv.72197243,d.dGc

Data sheet Page 6 of L298, PWM connects to enable. CD is 10 and 01 for direction. fast stop is CD 00 or 11
http://www.st.com/st-web-ui/static/active/en/resource/technical/document/datasheet/CD00000240.pdf

Hope it helps


body:
I've got 2 int16_t numbers, say 388 and 10288, which are sensor readings from an accelerometer. I want to estimate the angle of the device on that, but seemingly there are some type overflow issues:

My final goal is this:

    theta =  atan(-ax/sqrt((float)ay*ay+az*az));

The problem occurs in the bracket: ay^2 and az^2 are the 2 power of the given numbers. I recalculated with matlab and for the above example I get `a^2+b^2 = 388^2+10288^2 = 105993488` what I get from the arduino however is `152848`.
To be short: I don't know much about fixed point math or thelike and I couldn't find a sufficient answer to this: How do I calculate the square root term?

title: square root of large number

Answers: 1

body:
You need 2 typecasts. So

    atan(-ax/sqrt((float)ay*ay+(float)az*az));

Otherwise it will use int16_t for the right side of the addition and overflow.

Though for speed you might want to typecast them as `long` (`int32_t`), as floats calculations on the arduino are really slow. The `sqrt` function will covert this double into a float for you.


body:
What does the [MQ-2][1] sensor detect?

I know it detects concentrations of flammable gas. But does it detect smoke from fires too?
What about smoke from cigarettes, and other things?

  [1]: http://linksprite.com/wiki/index.php5?title=MQ2_Smoke_Detector_Shield_for_Arduino

title: What is exactly MQ-2 sensor?

Answers: 1

body:
Simple answer is no.

There are about 10 similar sensors, each detect specific kind of chemicals


body:
    int i, j;
    char data;
    int flag=0;

    void loop()
    {
    if(Serial.available() > 0){
        data  = Serial.read();
        flag=0;
      }

      if (data == 'd' && 'b') {
        digitalWrite(cONOF, HIGH);
      } else if (data == 't' && 'w') {
        digitalWrite(cONOF, LOW);
      }

      if (data == 'y' && 'w') {
        digitalWrite(start, HIGH);
        delay(2000);
        digitalWrite(start, LOW);
      }

      if (data == 'e' && 'r' && 'h' && 'i') {
        for (i=0;i<10;i++) {
          digitalWrite(horn, HIGH);
          delay(100);
          digitalWrite(horn, LOW);
          delay(100);
        }
        for (j=0;j<10;j++) {
          digitalWrite(horn, HIGH);
          delay(500);
          digitalWrite(horn, LOW);
          delay(500);
        }
        digitalWrite(horn, LOW);
      }

    }

I want to read data from the USART where the messages have more than one character. I tried the code above but it doesn't work well. For example, I want to send the message 'db' to turn the output on, but just sending 'd' also turns it on, how do I fix this?

title: Read multiple char from USART

Answers: 1

body:
You need split the reading into two processes - storing the characters and checking if they are the right message.

To store the characters for example:

    String message = "";

    void loop()
    {
    while(Serial.available()) {
        char b = Serial.read();

        if (b == '\r') {
            processMessage();
            message = "";
        }
        else {
            message += b;
        }
    }
    }

The process might look like

    void processMessage() {

        if (message == "fb") {
             foo();
        }
        else if (message == "bf") {
             bar();
        }
    }

I just use the [Messenger library][1] usually. But note you have to change `WProgram.h` to `Arduino.h` in `Messenger.cpp` to get it to work.

  [1]: http://playground.arduino.cc/code/messenger


body: Is there a delay function available that does not use `millis()` which itself makes use of a timer? Does not need to be hyper-exact.

title: Delay function without using a timer

Answers: 1

body:
    delayMicroseconds(1000);// maximum delay is 65535 uS

or

    #include <util/delay.h>
    _delay_ms(1);


body:
Why is a toroidal inductor being used in the RFID reader described in *[DIY FSK RFID Reader][1]*?

I feel that a toroidal inductor wouldn't be very effective in grasping the changes in electromagnetic field changes.

  [1]: http://playground.arduino.cc/Main/DIYRFIDReader

title: 125 kHz RFID reader with Arduino

Answers: 1

body:
Yes, Chris Stratton is right. A toroidal inductor keeps flux within the core, reduces the external flux to near zero and have near zero ability to grasp/convert external flux/magnetic field into electrical signal. Apparently, the word 'toroidal' was used in loose sense referring to a circularly shaped coil.

In an real-life commercial product, a 125 kHz coil typically has many turns on a very thin wire on an open-air core (no core).

An example profession factory made a 125 kHz RFID with a [GitHub][1] Arduino library and photos of an antenna coil:

 * *[125 kHz RFID module - UART][2]*

 * *[Seeed-Studio/RFID_Library][3]*

 * *[125Khz RFID module - UART][4]* (wiki)

Also, see *[Building RFID Card Reader using PIC Microcontroller][5]*.

Note, for higher frequency RFID, not shown in above examples, coils have fewer turns than for 125 kHz.

  [1]: http://en.wikipedia.org/wiki/GitHub
  [2]: http://www.seeedstudio.com/depot/125Khz-RFID-module-UART-p-171.html
  [3]: https://github.com/Seeed-Studio/RFID_Library
  [4]: http://www.seeedstudio.com/wiki/index.php?title=125Khz_RFID_module_-_UART
  [5]: http://www.8051projects.net/news-i140-5-building-rfid-card-reader-using-pic-microcontroller.html


body:
I want to power down my Olimexino as much as possible and only wakeup on a pin-change interrupt. I removed the 3.3V/5V jumper (so the processor does not get power) and 3µA were displayed, so the voltage regulator is really a low power variant. What I have done:

    #include <avr/power.h>

    power_all_disable();
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    sleep_enable();
    sleep_cpu();

This resulted in still using 220µA. Now I disable the ADC, too:

    ADCSRA = 0;

which reduces it to 100µA. I've tried to disable further ADC-stuff using

    ACSR = 0;
    ADMUX = 0;

and tried to disable (?) the Watchdog Timer using

    WDTCSR = 1 << WDP3;

but without any further improvements. The datasheet for the 32u4 suggests to disable the Brown-Out-Detector, too, but I don't seem to be able to do that using code, but only by setting some fuses which is not possible directly using the Arduino IDE. Any further ideas?

title: Olimexino (32u4): power down

Answers: 0


body:
I wanted to use both [TMRpcm][1] and [VirtualWire][2] with ATmega328 in an Arduino-like board I'm making, but both libraries use TIMER1. I wanted to use each lib for the following purposes:

* TMRpcm: play a WAV sound from an SD Card;
* VirtualWire: to receive commands from an RF remote control.

[TMRpcm Advanced Features Wiki][5] has a section on [how to use TIMER2 instead][6], but I couldn't get it to work. They also say:

> Notes:
>
> 1. This is usually not the best solution.

So, before I spend any more time on this, I would like to hear what you guys have to say.

So, my question is: **is there a workaround to solve this conflict on the use of TIMER1, so I can use both libs in my project?**

If not, **what other alternatives do I have?**

My circuits for reading the SD card and driving the speaker are similar to the schematic in this Instructable: [Playing Wave file using Arduino][3]. And I'm using one of those
[433MHz Receiver modules][4] for the RF part (standard, working circuit).

Both features, the RF receiver and SD card WAV playing, work correctly, when run separately (with separate sketches).

   [1]: https://github.com/TMRh20/TMRpcm
   [2]: http://www.airspayce.com/mikem/arduino/VirtualWire/
   [3]: http://www.instructables.com/id/Playing-Wave-file-using-arduino/
   [4]: http://www.soldafria.com.br/datasheet/RWS-375-6(433_92mhz).pdf
   [5]: https://github.com/TMRh20/TMRpcm/wiki/Advanced-Features
   [6]: https://github.com/TMRh20/TMRpcm/wiki/Advanced-Features#timer2-usage

title: Using both TMRpcm and VirtualWire libs with ATmega328, despite the conflict on TIMER1

Answers: 3

body:
You could edit the VirtualWire.cpp source to use Timer2 instead of Timer1. For VirtualWire 1.18 the relevant section starts on line 512 with `#else // ARDUINO`.

On line 515 change `(uint16_t)-1` to `(uint8_t)-1` since Timer2 is only 8 bit. Then change all the TCCR1A, TCCR1B, OCR1A, TIMSK1 and OCIE1A to their Timer2 equivalent (hint: swap the 1's for 2's). Line 533 should be the last. On line 778 you also need to make a change to use TIMER2_COMPA_vect for VW_TIMER_VECTOR.

I hope that it helps.

body:
I ended up working around the issue by building a board with two ATmegas in it. One MCU handles the sound while the other handles the RF receiver, each using its own TIMER1, both communicating via I2C.

It's kind of a low tech dual core controller board. Not the most efficient solution, but it worked great for me.

body:
the virtual wire library has been obsoleted, and you should now use the [RadioHead][1] library. In this RadioHead Library, you can edit the RH_ASK.cpp file, and uncomment the #define RH_ASK_ARDUINO_USE_TIMER2 near the top.

  [1]: http://www.airspayce.com/mikem/arduino/RadioHead/