# Question
Title: How to modify Arduino boards.txt to support new MCUs
In this post, 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?

# Answer
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. 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

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

```
> 4 votes

---
Tags: avrdude, atmega328
---


title: Arduino Packet for Bluetooth

text:
# Question
Title: Arduino Packet for Bluetooth
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?

# Answer
> 2 votes
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*

# Answer
> 1 votes
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/

---
Tags: motor, bluetooth, servo
---


# Question
Title: Coding and libraries for Maxtronix Ultrasonic sensors
I need to access distance data using a LV-EZ0 Maxtronix ultrasonic sensor: MB1000 LV-MaxSonar®-EZ0™High Performance Ultrasonic Rangefinder

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

I noticed this new ping library, NewPing

Would this work for my purposes with this particular sensor?

# Answer
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

> 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

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.
> 1 votes

---
Tags: arduino-uno, sensors
---


# Question
Title: Arduino Nano and SIM300 module for http calls for location
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.

# Answer
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).
> 1 votes

---
Tags: arduino-nano
---


# Question
Title: Using an Adafruit Trellis to control a set of relays
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();
                }
            }
        }

    }
}

```

# Answer
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).
> 1 votes

# Answer
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
}

```
> 0 votes

---
Tags: led, i2c, relay
---


# Question
Title: Arduino Remote controlled RGB LED strip, having issues with brightness/dimming
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)

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

# Answer
> 2 votes
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];

```

# Answer
> 1 votes
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.

---
Tags: programming, led
---


# Question
Title: Measure low current with variable voltage
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.

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

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.
> 3 votes

# Answer
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.
> 1 votes

---
Tags: current
---


# Question
Title: External (pin change) interrupt and power consumption
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?

# Answer
> 3 votes
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.

# Answer
> 0 votes
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.

---
Tags: power, interrupt
---


# Question
Title: How to handle multiple input pins at once?
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.

# Answer
> 1 votes
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; 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.

# Answer
> 1 votes
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;
  }
}

```

# Answer
> 0 votes
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.

# Answer
> -1 votes
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.

---
Tags: programming, sketch
---


title: square root of large number

text:
# Question
Title: square root of large number
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?

# Answer
> 5 votes
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.

---
Tags: accelerometer, data-type
---


title: Using Arduino as USB Device?

text:
# Question
Title: Using Arduino as USB Device?
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!

# Answer
> 2 votes
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.

# Answer
> 0 votes
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.

---
Tags: avr, audio
---


title: H_Bridge with PWM gets too hot

text:
# Question
Title: H_Bridge with PWM gets too hot
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.

# Answer
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.
> 3 votes

# Answer
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
> 2 votes

# Answer
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.
> 2 votes

# Answer
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%3A%2F%2Fwww.ti.com%2Flit%2Fds%2Fsymlink%2Fl293d.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
> 2 votes

---
Tags: arduino-uno, pwm
---


title: What is exactly MQ-2 sensor?

text:
# Question
Title: What is exactly MQ-2 sensor?
What does the MQ-2 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?

# Answer
Simple answer is no.

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

---
Tags: sensors
---


title: Read multiple char from USART

text:
# Question
Title: Read multiple char from USART
```
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?

# Answer
> 1 votes
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 usually. But note you have to change `WProgram.h` to `Arduino.h` in `Messenger.cpp` to get it to work.

---
Tags: arduino-uno
---


title: Delay function without using a timer

text:
# Question
Title: Delay function without using a timer
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.

# Answer
```
delayMicroseconds(1000);// maximum delay is 65535 uS

```

or

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

```
> 4 votes

---
Tags: time
---


title: Parsing JSON on the Arduino

text:
# Question
Title: Parsing JSON on the Arduino
I'm using the ArduinoJson library. There is a great example for parsing a single JSON object in the source code. I am attempting to iterate over an array of JSON objects:

```
#include <JsonParser.h>

using namespace ArduinoJson::Parser;

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

  char json[] = "[{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}, \
    {\"sensor\":\"gps\",\"time\":1351824140,\"data\":[50.756080,21.302038]}]";

  JsonParser<32> parser;
  JsonArray root = parser.parse(json);

  if (!root.success()) {
    Serial.println("JsonParser.parse() failed");
    return;
  }

  for (JsonArrayIterator item = root.begin(); item != root.end(); ++item) {
    // unsure of what to do here.

    Serial.println((*item)["data"]);
    // results in:
    // ParseJsonArray:21: error: call of overloaded
    //   'println(ArduinoJson::Parser::JsonValue)' is ambiguous

    JsonObject something = JsonObject(*item);
    Serial.println(something["sensor"]);
    // results in :
    // ParseJsonArray:26: error: call of overloaded
    //   'println(ArduinoJson::Parser::JsonValue)' is ambiguous
  }
}

void loop() {}

```

item is of type JsonValue. I would like to treat it as a JsonObject and pull some data out of it.

# Answer
> 3 votes
This is how I would write this loop:

```
for (JsonArrayIterator it = root.begin(); it != root.end(); ++it)
{
  JsonObject row = *it;

  char*  sensor    = row["sensor"];
  long   time      = row["time"];
  double latitude  = row["data"][0];
  double longitude = row["data"][1];

  Serial.println(sensor);
  Serial.println(time);
  Serial.println(latitude, 6);
  Serial.println(longitude, 6);
}

```

And, if C++11 is available (which is not the case with Arduino IDE 1.0.5):

```
for (auto row : root)
{
  char*  sensor    = row["sensor"];
  long   time      = row["time"];
  double latitude  = row["data"][0];
  double longitude = row["data"][1];

  Serial.println(sensor);
  Serial.println(time);
  Serial.println(latitude, 6);
  Serial.println(longitude, 6);
}

```

# Answer
> 2 votes
Got it! Initially, casting the retrieval of the item from the JsonObject before printing was enough.

```
JsonObject something = JsonObject(*item);
Serial.println((char*)something["sensor"]);

```

Although, I think this looks better.

```
char* sensor = (*item)["sensor"];
Serial.println(sensor);

```

---
Tags: arduino-uno, c++
---


title: 125 kHz RFID reader with Arduino

text:
# Question
Title: 125 kHz RFID reader with Arduino
Why is a toroidal inductor being used in the RFID reader described in *DIY FSK RFID Reader*?

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

# Answer
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 Arduino library and photos of an antenna coil:

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

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

---
Tags: rfid
---


# Question
Title: Shortest time interval that Arduino Uno R3 can read
I am doing a light speed determination experimsmt. Lightspeed is around 3\*10^8 m/s. For this, I need to measure time interval between 2 light sensors in nanoseconds, Somewhere about 50ns. Is this possible using the Uno R3? I know the clock is 16MHz only but is the clock irrelevantto the topic? If it is not possible, Some tips would be helpful. Thank you.

Sorry for irrelevant tags. No suitable tags found.

# Answer
> 2 votes
At 16MHz, the quickest operation that the cpu can do (a one cycle operation) will take 62.5 nanoseconds (1/(16\*10^6) seconds). That means the best resolution you could conceivably have is 62.5 ns chunks. It will take considerably longer than one clock to respond to an outside event though, so making an experiment will be really tough even then.

Maybe you could build an experiment like the Fizeau apparatus where the arduino measured pulses of light that make it back through the slit? Those would be measured in microseconds. The arduino could change the speed of the grooved wheel and maximize the returning pulse width, reading the rpm then gives you the speed of light.

I'll note that since the meter is defined by the speed of light, and the foot defined by the meter, You would not be measuring the speed of light in feet or meters per second; you would be measuring the length of a meter given how long a second is, or vice versa.

---
Tags: time
---


title: Knowing the Arduino memory capacity

text:
# Question
Title: Knowing the Arduino memory capacity
I am using Arduino uno. My data is storing into EEPROM whenever i run my program, it will store multiple data depend on the loop. For my program it calculate 10 sample in 0.1 sec, so 100 sample in 1 sec. How can i know how much memory i can run?

I have added this code to my program it display 895.

```
#include <Arduino.h>
int freeRam () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
void setup(){
Serial.begin(9600);
Serial.println(freeRam());}
void loop(){}

```

# Answer
> 5 votes
The `freeRam()` method you are suggesting calculates the "space" between the `heap` and the `stack`, thus it returns the free `SRAM`.

There is no way to calculate free remaining `EEPROM` (if that is what you are asking), since it just contains some arbitrary data at arbitrary locations. Get the `EEPROM` capacity from the device data sheet and make sure to write within its boundaries.

---
Tags: c
---


# Question
Title: LCD showing weird characters when using two 1-wire temperature sensors
I have a sketch to display a temperature obtained from 1-wire DS18B20 sensors. The sketch works fine, however when I connect two sensors to my board, the text on the LCD displays gets corrupted (### and other symbols shown instead of a temperature).

I have tried plugging each of the two DS18B20 sensors individually and it works with both of them, the problem shows only when I use both at the same time. I am connecting them both with black to ground, red to 5V and white to Dx and to 5V via a 4.7 kOhm pull-up resistor.

I have little idea how to check what is wrong - is it some kind of interference, insufficient voltage, or a SW problem?

# Answer
> 0 votes
After some more searching I have found Arduino forum topic LCD text corrupts after Arduino runs for length of time. I have followed this advice:

> In particular, try running the LCD ground wire directly to a ground pin on the Arduino (not to the breadboard) and keep it short.

This seemed to solve the issue, therefore it was likely some kind of interference on the ground wiring. (Before this, the ground to the LCD went trought the breadboard power bus).

---
Tags: lcd, 1-wire
---


# Question
Title: LED's won't light up when LCD/RNG hits 2 || 3 of a kind
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);}
}

```

# Answer
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
            }
        }
    }

  }
}

```
> 2 votes

---
Tags: arduino-uno, sketch, lcd
---


# Question
Title: Is it possible to program an Attiny85 with a USB-to-TTL converter?
I currently use my Arduino to program Attiny85. As I have one of these USB-to-TTL adapters I am wondering if it is possible to program Attiny85 with it, to free up my Arduino. I know it is possible to program Atmega's with such a thing.

If it is in fact possible to use the converter as a simple programmer for Attiny's, how should I connect the converter to the Attiny?

# Answer
> 5 votes
Yes, it is possible.

Note that the FTDI chip (assuming that is what you have) can be accessed as either Virtual Com Port VCP or D2XX. Where VCP is the traditional method of using them as Serial Ports with avrdude calling "-c arduino -P COM3 -b115200". However the later D2XX method allows for the pins to be Bit Bang'ed.

One can see in this tutorial it is possible to call avrdude with a programmer of "-c ftdi". Assuming that the D2XX drivers are installed.

Where I see in the current releases 1.0.5r2 and 1.5.7's avrdude's config files that a programmer of type "avrftdi" is supported, as opposed to the article "ftdi"

However, that is not to say the IDE natively supports its. You will have to either call avdude manually. Or add the "avrftdi" to "\arduino-1.5.7\hardware\arduino\avr\programmers.txt" so that the IDE will be aware of it.

---

That all said I see "Tiny AVR Programmer" that are very in-expensive.

---
Tags: avr, attiny
---


# Question
Title: My counting function is not working with the text on my lcd
I want the bottom row of my LCD to display the counting function and include text:

```
lcd.setCursor(0, 1);
lcd.print("Launch in"millis()/1000);

```

But it comes out with an error, what part is wrong?

# Answer
The last line in the code you provided won't compile.

The `lcd.print()` function expects a char, byte, int, long or string (taken from the LiquidCrystal docs) and you're trying to combine a string and an int which the compiler isn't going to understand.

The easiest way to print both would be to have two lcd.print statements:

```
lcd.print("launch in ");
lcd.print(millis()/1000);

```

Most of this is taken from quickly googling displaying time on an lcd screen. Check out this forum post, it seems similar to what you want to do: click me!
> 1 votes

# Answer
Change the last line to:

```
lcd.print("Launch in " + (millis() / 1000));

```

The `+` *concatenates* the string `Launch in` with the number that results from `millis() / 1000`.
> 1 votes

# Answer
```
lcd.setCursor(0, 1);
lcd.print("Launch in ");
lcd.print(millis()/1000);

```
> 1 votes

---
Tags: programming, lcd
---


title: question about progmem

text:
# Question
Title: question about progmem
I have a problem understanding the following code:

```
PROGMEM  prog_uint16_t x={1232,3232,43343};
rawlen = pgm_read_word_near(x);
memcpy_P(uSendBuff, pfSendBuff+1, rawlen * sizeof(uint16_t));

```

Why do we need this? -

```
rawlen * sizeof(uint16_t));

```

Why not this? -

```
memcpy_P(uSendBuff, pfSendBuff+1, sizeof(rawlen));

```

# Answer
Probably because x is an **array** of integers (although in the code you posted you miss the '\[\]'), thus memcpy\_p should run over `rawlen` integers, each integer occupies `sizeof(uint16_t)` bytes, hence `rawlen * sizeof(uint16_t)` bytes in program memory space.
> 2 votes

---
Tags: flash, progmem
---


# Question
Title: Arduino Servo won't move when using classes
I'm trying to make a class work with Arduino, however it doesn't seem to trigger properly. The **code is compiling** perfectly, and it's supposed to control the **leg of an hexapod**. Also, the example sweep works on this servo, so no problem here. However, the servo is not actually moving. I'm thinking it has something to do with the order of declaring the variables:

```
#include <Servo.h>

// Abstract each leg, so only those functions can be accessed
class Leg {
  // Actions that can be triggered from outside
  public:
    Leg(int hipPin, int kneePin);
    void up();

  // These should be only available for the leg
  private:
    Servo hip;
    Servo knee;
  };

Leg::Leg(int hipPin, int kneePin) {
  hip.attach(hipPin);
  knee.attach(kneePin);
  }

// Testing the leg: move it up
void Leg::up() {
  for(int pos = 0; pos < 180; pos += 1) {
    hip.write(pos);
    delay(15);
    }
  }

// Initialize the leg
Leg topLeft(9, 10);

void setup() {
  }

// Test the function up()
void loop() {
  topLeft.up();
  }

```

I'm testing only the pin 9 (leaving the 10 empty). It *seems in pain*, meaning, you can see the servo trembling but not moving really at 0 degrees.

# Answer
It looks this problem may be due to bad order of initializers calls for global variables.

In C++, the order of global variable initialization is unpredictable across different compilation units (i.e. C++ source files, not header files). Initialization order is only respected **inside** one compilation unit.

In your program, there are several global variables that, if initialized in the wrong order, will fail your program:

* `Leg topLeft;` this is your class instance
* `servo_t servos[MAX_SERVOS];`, `int8_t Channel[_Nbr_16timers ];` and `uint8_t ServoCount = 0;` all defined in `Servo.cpp`

Calling `Servo.attach()` requires that the 3 variables above have already been initialized, which you cannot be sure of.

How can you fix that?

By not performing the `attach()` in `Leg` constructor but delegating it to some kind of `init()` method that you can call from `setup()`:

```
class Leg {
    // Actions that can be triggered from outside
    public:
    void init(int hipPin, int kneePin);
    void up();

    // These should be only available for the leg
    private:
    Servo hip;
    Servo knee;
};

Leg::init(int hipPin, int kneePin) {
    hip.attach(hipPin);
    knee.attach(kneePin);
}

// Testing the leg: move it up
void Leg::up() {
    for(int pos = 0; pos < 180; pos += 1) {
        hip.write(pos);
        delay(15);
    }
}

// Declare the leg
Leg topLeft;

void setup() {
    // Initialize the leg
    topLeft.init(9, 10);
}

// Test the function up()
void loop() {
    topLeft.up();
}

```
> 5 votes

---
Tags: arduino-uno, c++, class
---


# Question
Title: On my lcd my characters collide, how can i remove one(because of the programming)
My code means that when i press a button it displays a word, but by default words are already there and i need to get rid of those default words.

```
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7,8,9,10,11,12);

int buttonApin = 4;

void setup() {
 pinMode(buttonApin, INPUT_PULLUP);
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("Mission Control ");
}

void loop()
{
  if (digitalRead(buttonApin) == LOW)
  {
    lcd.setCursor(0, 1);
    lcd.print("Test");
  }

  lcd.setCursor(0, 1);

lcd.print("launch in ");
lcd.print(millis()/1000);

```

# Answer
The HD44780 controller has a 80 bytes (characters) memory, in order to support up to 2x40 character displays. Since you use a 2x16 display, there is an empty space in the memory you can use on your benefit. It's like having two desktops, you are able to show one or the other.

Refer to LCD Addressing for a visualization of the the memory locations and detailed explanation.

Anything you write in locations `setCursor(16, 0)` to `setCursor(39, 0)` and `setCursor(16, 1)` to `setCursor(39, 1)` will not be visible until you scroll to the left. Consequently you can have some text already written in the hidden area and then alternate the shown text just by scrolling left and right.

Here is an example

```
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7,8,9,10,11,12);

int buttonApin = 4;

void setup() {
   // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
}

void loop()
{
  if (digitalRead(buttonApin) == LOW)
  {
    // write text to the visible area
    lcd.setCursor(0, 0);
    lcd.print("showing 0,0-15,0");
    lcd.setCursor(0, 1);
    lcd.print("showing 1,0-15,1");

    // write text to the hidden area
    lcd.setCursor(16, 0);
    lcd.print("now  16,0-31,0");
    lcd.setCursor(16, 1);
    lcd.print("now  16,1-31,1");

    while (1) {  // scroll to the left and back to show different text without writing a single character
    delay(2000);
    for(uint8_t i=0;i<16;i++) lcd.scrollDisplayLeft();
    delay(2000);
    for(uint8_t i=0;i<16;i++) lcd.scrollDisplayRight();
    }

  }

}

```

The code changes the visible text just by scrolling
> 3 votes

# Answer
Either clear the display first, or print enough spaces after to overwrite the existing text.
> 3 votes

---
Tags: arduino-uno, programming, pins, lcd, sketch
---


title: Arduino as USB HID

text:
# Question
Title: Arduino as USB HID
Is it possible to build a HID device (like a keyboard) using an Arduino uno?

At the time being, I have button inputs on the Arduino giving outputs on the serial line. So, how can I transform my current firmware into something that can behave like a HID keyboard?

* Shall I write a new window device driver?
* Shall I create a software layer that could take my serial data and have windows read it as HID input?
* Is there any better way to achieve this, if it is possible at all?

# Answer
> 16 votes
> Is it possible to build a HID device (like a keyboard) using an Arduino uno?

yes it is! And there's a great tutorial on how to do that over here

> At the time being, I have button inputs on the Arduino giving outputs on the serial line. So, how can I transform my current firmware into something that can behave like a HID keyboard?

As the tutorial shows you, you need to transform your firmware code so instead of printing the events, you actually trigger events. What you need to do, is add to your code:

```
void triggerKey(uint8_t mod, uint8_t chr) {
    uint8_t buf[8] = {mod, chr, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
    // press key
    Serial.write(buf, 8);
    // emulate key press delay
    delay(10);
    buf[1] = 0x00;
    // release key
    Serial.write(buf, 8);
}

```

What you're doing here, is send from your main Arduino microcontroller events over the serial line to the smaller microcontroller that handles USB communication. That microcontroller will take those key "buffers" and transfer them as USB HID Keyboard key presses over USB.

Beware that the key character (`chr` in the code here), is actually a keycode sent over USB that gets interpreted by your USB HID driver, which then translates it into a real character using the current layout you've setup for your keyboard.

The `mod` character is one of the modifier keys you have on the keyboard (`shift`, `control`, `alt`...), `0x00` being no modifier.

> * Shall I write a new window device driver?

No, you don't need! With the DFU upgrade, your arduino will be seen as a USB keyboard by windows.

> * Shall I create a software layer that could take my serial data and have windows read it as HID input?

You neither need to do that, and it's actually a very bad idea for many reasons:

* your solution would not be portable, and thus you'd need to hack something for every platform you may use,
* your solution would imply a lot of new code ; the more code one write, the more bugs is likely to be in your system,
* your solution would be really hackish, as it would behave as a device driver (i.e. *kernel land*) taking input from a user program (i.e. *user land*) and is likely to not work, be a hell to debug, and prone for security issues... If that's even possible to do!

> I'm using an Uno, but I'll look at what you posted because last time we considered the DFU update but we're kinda scared of bricking stuff

Finally you're having concerns, in a comment, about bricking your arduino. Please believe me and the author of the article that you **cannot** brick your arduino doing a firmware flash:

*NOTE: There is no chance of ‘bricking’ the device using this method. The Arduino bootloader firmware can always be updated using the DFU protocol!*

In case something gets really badly wrong, and you get a bootloader corruption in the little AVR (atmega8u2), you still can reflash it using another arduino or an atmel programmer using the 6 pins next to the USB plug.

In the end, know that the **only** way to brick an AVR, thus an Arduino as well, is to play with the fuses and reset the programming fuses. And even then, you may use HVSP to save your device, though it's often less trouble to just take a new chip.

# Answer
> 10 votes
I created a project that fully replaces the Arduino Bootloader. You are able to upload sketches and use it as HID. See Project HID on Github: https://github.com/NicoHood/HID

---
Tags: arduino-uno, serial
---


# Question
Title: Arduino Yun's sample "Bridge" code not working
I'm new to the Arduino world (or the electronics world for that matter).

I have the Arduino Yun and the WifiStatus code works fine (so does the HttpClient). But every time I try to run the bridge sample code, all I see is the pin 13 led light up, and the browser commands don't work.

PS: I have updated the open-wrt to ver. 1.3.

Any thoughts on why this would be happening?

Edit 1:

I have tried to reboot arduino using the hardware switches as well as from the web console. The blink sketch works fine, so does the WifiStatus code and the HttpClient code.

The other problem I face after every few uploads is that the IDE is stuck at "Uploading...". I have tried to give it more time (even an hour). But then I had to unplug it from the Mac and restarted. Then it worked but only for a few times.

But this problem is not specific to the Bridge code. The uploading issue has occurred with other sample code as well. But at least the code worked.

Edit 2:

This is the result from the command `ls /dev/tty.*`

```
/dev/tty.Bluetooth-Incoming-Port    /dev/tty.usbmodem1431
/dev/tty.Bluetooth-Modem

```

# Answer
I ended up doing two things. First I got a replacement hardware. That made the bridge code start working.

And I also changed the port from `/dev/tty.usbmodem1431` to `/dev/cu.usbmodem1431`. As shown in the picture below. That fixed the issue with IDE getting stuck at "Uploading...".

Not sure if this fix will last.
> 1 votes

---
Tags: arduino-yun
---


title: Adapt program to suit Arduino UNO

text:
# Question
Title: Adapt program to suit Arduino UNO
I am trying to use a program that has been written for STM32 microprocessor for interfacing with a Time to Digital Converter TDC GP22 via SPI interface. I would like to use the same program and adapt it to suit Arduino Uno for interfacing with TDC GP22. This would really help save a lot of time.

Can someone please suggest me the most effective way to do this ?

# Answer
You'll be wasting your time tring to convert the code on a procedure by procedure basis. Arduino has different libraries, different clocks, different pins, etc.

I suggest you flowchart the code, and then work out which of the Arduino libraries (SPI, LCD, etc.) you can use to achieve the flow. You'll be able to drop some of the initialisation code probably as Arduino is easier to run "out the box".

There's no quick-and-easy solution here - it's a re-write... as you'll find is often the case migrating code from one MCU to another.
> 1 votes

---
Tags: arduino-uno, programming
---


# Question
Title: What transparent casings are commonly used for smaller devices with a display
Not exactly Arduino-specific, but if you want to get a daily usable device (instead of a floating wire connection on your table) you eventually want to put your (Arduino-based) device into a nice casing. What are the different types of cases that people use?

I found soap cases as well as kitchen boxes (used one large cheese box from Mepal Rosti).

# Answer
So far we have used:

ABS cases (pic camdenboss.com):

Small pelicases (convenient to open, pic pelican-case.com):

3D printed cases with a clear perspex window (pic instructables.com):

I've seen other people use laser cut perspex (pic spikenzielabs.com):
> 4 votes

# Answer
If you have affordable access to a laser cutter, then you could laser cut a box to exactly match your project.

Laser cutters typically come with software that reads SVG or DXF files. Find out what file types are used, then search the web for something like "laser cut box design tool SVG", and you'll find a bunch of ways to make the box outline.

For example, this laser cut box web site generates a pdf file, which you can 'print'. You fill in a few parameters, and it does the rest, generating all the profiles for interlocking edges. Even though the edges are interlocking, you might want to add some glue to make it more robust.

An advantage of laser cutting is you can choose the materials. Maybe you'd like wood, with a transparent red acrylic lid.

A further advantage, if your laser can read things like SVG or DXF, is you could use a CAD or drawing program to modify the box. So, for example, you could 'etch' labels onto a control panel, or cut extra holes to mount LEDs. Or just decorate the outside of the box.
> 3 votes

---
Tags: arduino-uno
---


title: little pump isn't working

text:
# Question
Title: little pump isn't working
I'm trying to use a little pump with my arduino nano:

```
void setup ()
{
  pinMode(waterPump, OUTPUT);
}
...
  while (val < valueWater)
  {
    Serial.println ("in while"); // testing purpose
    digitalWrite(waterPump, HIGH);
    delay(1000); // 1 second
    digitalWrite(waterPump, LOW);
    val = analogRead(sondeEau);
  }

```

When I try this one, pump isn't working. When I unplug the waterPump pin, I see "LED3" that run, and when I plut it, LED3 is not running, why?

I tried to plug pump directly on 5V on arduino, pump works well...

This is the pump I bought: http://www.dx.com/p/hsyy01-water-pump-motor-w-hose-white-silver-236808

Thanks in advance to help me!

# Answer
*You plugged this directly into your Arduino?* You might as well have dropped your Arduino in the water you are pumping...

The Arduino can only supply **40mA** per pin. However, you pump requires **800 mA**!!! Often, when overloading a pin, the Arduino chip is fried. Even worse, a typical USB port can only supply 500 mA, so you could have fried your computer if using USB.

You'll need a motor driver. Like mentioned in the comments, the Arduino motor shield is a great place to start. If you don't to spend all that money, you have a few options:

* A *relay* is an easy way that works with almost all voltages and any reasonable amount of current.
* If you want something a little more professional, a *transistor,* like a *MOSFET* would be the way to go. They're fairly cheap, but you have to know which to pick (that's hard to do in practice).
* You can also get a half H-bridge which I think would work well for your situation.

> When I unplug the waterPump pin, I see "LED3" that run, and when I plut it, LED3 is not running, why?

The motor is likely taking up all the current.

**tl;dr:** get an external power source and get a proper motor driver.
> 3 votes

# Answer
As Chris says, you should never plug a high current device like a motor directly into a pin on your Arduino. That motor is rated at 800 mA, which is more than you can draw from the entire 5V supply on the Arduino!

The digital pins are rated for 40 mA max, if I remember correctly. You tried to draw 20 times that much. There is a decent chance that you burned out the driver for that digital pin. I would try hooking an LED through a 220 ohm resistor and to ground and see if it still lights up when you send it a HIGH logic signal.

For a simple DC motor you should be able to use a high current transistor and an external power supply to drive it.

Edit: If I were doing this I would use a logic-level MOSFET to drive the pump directly, plus a flyback diode. To use a relay, you will still need a transistor to power the relay coil, AND a flyback diode. Your circuit might look like this:

(Note that I made no attempt to pick the RIGHT kind of diode and transistor. Ignore the part numbers shown in the schematic. I just used the defaults.)
> 4 votes

---
Tags: motor, arduino-nano
---