title: Changing how a longpress is executed

text:
# Question
Title: Changing how a longpress is executed
I have an RGB LED common Anode attached to my Uno and this code detects a long press to turn the LED on and off. Short presses cycle through colors, then off.

The problem is that a longpress is 2+sec, but it doesn't register until I release the button. How would I set this up to execute the code at 2sec regardless of whether the button is released?

It's probably not worth my time if it requres too much modification. I have a working item, it's just not... ideal.

```
Xhunsigned long keyPrevMillis = 0;
const unsigned long keySampleIntervalMs = 25;

int redPin = 11;
int greenPin = 10;
int bluePin = 9;
int LEDcolor=0; // 0=White, 1=Red, 2=Green, 3-Blue, 4=Yellow, 5=Purple, 6=Pink, 7=Orange, 8=Off
int LEDstatus =0; //0=Off, 1=On
int changed =0; //has the LEDstatus just changed?
byte longKeyPressCountMax = 80;    // 80 * 25 = 2000 ms
byte longKeyPressCount = 0;

byte prevKeyState = HIGH;         // button is active low
const byte keyPin = 2;            // button is connected to pin 2 and GND

// called when button is kept pressed for less than 2 seconds
void shortKeyPress()
{
   Serial.println("short");
   if (LEDstatus==1)
   {
      LEDcolor = LEDcolor +1;
      if (LEDcolor==0) {analogWrite(redPin, 0);analogWrite(greenPin, 0);analogWrite(bluePin, 0);Serial.println("White");}
      if (LEDcolor==1) {analogWrite(redPin, 0);analogWrite(greenPin, 255);analogWrite(bluePin, 255);Serial.println("Red");}
      if (LEDcolor==2) {analogWrite(redPin, 255);analogWrite(greenPin, 0);analogWrite(bluePin, 255);Serial.println("Green");}
      if (LEDcolor==3) {analogWrite(redPin, 255);analogWrite(greenPin, 255);analogWrite(bluePin, 0);Serial.println("Blue");}
      if (LEDcolor==4) {analogWrite(redPin, 0);analogWrite(greenPin, 0);analogWrite(bluePin, 255);Serial.println("Yellow");}
      if (LEDcolor==5) {analogWrite(redPin, 175);analogWrite(greenPin, 255);analogWrite(bluePin, 175);Serial.println("Purple");}
      if (LEDcolor==6) {analogWrite(redPin, 0);analogWrite(greenPin, 255);analogWrite(bluePin, 155);Serial.println("Pink");}
      if (LEDcolor==7) {analogWrite(redPin, 5);analogWrite(greenPin, 215);analogWrite(bluePin, 255);Serial.println("Orange");}
      if (LEDcolor==8) {analogWrite(redPin, 255);analogWrite(greenPin, 255);analogWrite(bluePin, 255);Serial.println("Off");LEDstatus=0;}
   }
}

// called when button is kept pressed for more than 2 seconds
void longKeyPress()
{
   Serial.println("long");
   if (LEDstatus==0 && changed==0)
   {
      analogWrite(redPin, 0);
      analogWrite(greenPin, 0);
      analogWrite(bluePin, 0);
      LEDcolor=0;
      changed=1;
      LEDstatus=1;Serial.println("On");
   }
   if (LEDstatus==1 && changed==0)
   {
      analogWrite(redPin, 255);
      analogWrite(greenPin, 255);
      analogWrite(bluePin, 255);
      LEDcolor=0;
      changed=1;
      LEDstatus=0;Serial.println("Off");
   }
   changed=0;
}

// called when key goes from not pressed to pressed
void keyPress() {
   Serial.println("key press");
   longKeyPressCount = 0;
}

// called when key goes from pressed to not pressed
void keyRelease() {
   Serial.println("key release");

   if (longKeyPressCount >= longKeyPressCountMax) {
      longKeyPress();
   }
   else {
      shortKeyPress();
   }
}

void setup()
{
   Serial.begin(9600);
   pinMode(keyPin, INPUT);
   digitalWrite(keyPin, HIGH);
   pinMode(redPin, OUTPUT);
   pinMode(greenPin, OUTPUT);
   pinMode(bluePin, OUTPUT);
   analogWrite(redPin, 255);
   analogWrite(greenPin, 255);
   analogWrite(bluePin, 255);
}

void loop() {
// key management section
   if (millis() - keyPrevMillis >= keySampleIntervalMs) {
      keyPrevMillis = millis();

      byte currKeyState = digitalRead(keyPin);

      if ((prevKeyState == HIGH) && (currKeyState == LOW)) {
         keyPress();
      }
      else if ((prevKeyState == LOW) && (currKeyState == HIGH)) {
         keyRelease();
      }
      else if (currKeyState == LOW) {
         longKeyPressCount++;
      }

      prevKeyState = currKeyState;
   }
}

```

# Answer
I've rewritten the code entirely. Not that yours was terrible, it was just easier for me to start from scratch. You are left with a very empty `loop()`, which I always prefer.

The code contains three 'colours' and an OFF state. You can add as many other colours as you wish: add an enumeration to `_LED_STATE` and then add a corresponding `case(<NEW_COLOUR>)` statement in `LEDcontrol()`. I haven't included any `analogWrite()` functions - or in fact any declarations for the LED pins at all - because I'm a little too lazy but it should be obvious where to put them within the case statement.

Note that in the final `case()` statement, the LED state is changed from green to off. This means that a short press will turn the LED off after it has cycled through all the other colours, but will stay off until a long press. If you only want long pressed to switch off/on, change line 103 to `eLED_STATE = _LED_STATE_RED;`, or whichever the first colour is.

```
#define btn 3   // button pin

#define SHORT_PRESS 100     // useful for debouncing, can be changed
#define LONG_PRESS  2000    // defines how long a 'long press' is
#define CYCLE       false
#define SHOW        true

//--// You can add new colours in this enum block
enum _LED_STATE
{
    _LED_STATE_OFF,
    _LED_STATE_RED,
    _LED_STATE_BLUE,
    _LED_STATE_GREEN
};

_LED_STATE eLED_STATE = _LED_STATE_OFF;

void setup()
{
    pinMode(btn, OUTPUT);
    LEDcontrol(SHOW);
}

void loop()
{

    if (digitalRead(btn))
        btnPressed();
}

void btnPressed()
{
    unsigned long tStart = millis();

    //--// Loop continuously while button is pressed
    while (digitalRead(btn))
    {
        //--// If LONG_PRESS is exceeded...
        if (millis() > tStart + LONG_PRESS)
        {
            //--// If LED is off, turn it on
            if (eLED_STATE == _LED_STATE_OFF)
                eLED_STATE = _LED_STATE_RED;        // Choose 'starting' colour
            //--// If LED is on, turn if off
            else
                eLED_STATE = _LED_STATE_OFF;
            //--// Update LED to display new eLED_STATE
            LEDcontrol(SHOW);
            //--// Now loop here until button is released
            while (digitalRead(btn));
        }
    }

    //--// If button is released in between the two press times
    if ((millis() > tStart + SHORT_PRESS) && (millis() < tStart + LONG_PRESS))
    {
        //--// Ignore if LED is off         ////// REMOVE ////////////////////
        if (eLED_STATE == _LED_STATE_OFF)   ////////// IF ////////////////////
            return;                         ///////////// NECESSARY //////////

        //--// Change the LED colour
        LEDcontrol(CYCLE);
        //--// Update LED to display new eLED_STATE
        LEDcontrol(SHOW);
    }

    //--// This helps to debounce; experiment with it
    delay(10);
}

void LEDcontrol(bool SHOW_OR_CYCLE)
{
    switch (eLED_STATE)
    {
        case(_LED_STATE_RED) :
        {
            if (SHOW_OR_CYCLE)
            {
                // paint it red
                return;
            }
            eLED_STATE = _LED_STATE_GREEN;
            return;
        }
        case(_LED_STATE_GREEN) :
        {
            if (SHOW_OR_CYCLE)
            {
                // paint it green
                return;
            }
            eLED_STATE = _LED_STATE_BLUE;
            return;
        }
        case(_LED_STATE_BLUE) :
        {
            if (SHOW_OR_CYCLE)
            {
                // paint it blue
                return;
            }
            //--// What happens after last colour? Next colour or OFF?
            eLED_STATE = _LED_STATE_OFF;
            return;
        }
        case(_LED_STATE_OFF) :
        {
            if (SHOW_OR_CYCLE)
            {
                // paint it black
                return;
            }
            eLED_STATE = _LED_STATE_RED;
            return;
        }
    }
}

```
> 1 votes

---
Tags: led, button, rgb-led
---


title: How to read bitmap image on Arduino

text:
# Question
Title: How to read bitmap image on Arduino
I want to convert a bitmap into binary array. My bitmap image is 272\*208 pixel monochromatic 1bpp image. I'm confused when the width I get from my image is 16 instead of 272, the height is corrected. And when I skip the bitmap header to get bitmap infomation, I got string of meaningless number in my text file.

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

File bmpImage;
File textFile;

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

Serial.print("Initializing SD card...");
if (!SD.begin(53)) {
  Serial.println("initialization failed!");
  return;
}
Serial.println("initialization done.");
int height = 0;
int width = 0;

// Open
bmpImage = SD.open("Circle.bmp", FILE_READ);
textFile = SD.open("test.txt", FILE_WRITE);

bmpImage.seek(0x12);// width in pixel = 16
width = bmpImage.read();
bmpImage.seek(0x16);// height in pixel = 208
height = bmpImage.read();
Serial.println(width);
Serial.println(height);

int imageSize = height*width;

bmpImage.seek(0x36);//skip bitmap header

for(int i = 0; i < height; i ++) {
  for (int j = 0; j < width; j ++) {
    textFile.write(bmpImage.read());
    textFile.write(" ");
  }
  textFile.write("\n");
}

bmpImage.close();
textFile.close();

Serial.println("done write");
}

void loop()
{
  // nothing happens after setup
}

```

# Answer
> 5 votes
That was a very raw way of trying to read a BMP file. There are a lot of assumptions that might give errors.

1. The file is a BMP file. The header signature is not checked.
2. The image offset is assumed to be directly after the file header. It is not read.
3. The image width is less than 256. Only the lowest byte of the 32-bit image width is read. As 272\>256 the low byte is 16.
4. The image height is less than 256. Only the lowest byte of the 32-bit image height is read.

It is a small bitmap but it will take a very long time to read when reading a single byte at a time. There are methods to improve performance but that is an answer to another question.

A more robust method to read the BMP header and image information is to define them as a struct and read.

```
struct bmp_file_header_t {
  uint16_t signature;
  uint32_t file_size;
  uint16_t reserved[2];
  uint32_t image_offset;
};

struct bmp_image_header_t {
  uint32_t header_size;
  uint32_t image_width;
  uint32_t image_height;
  uint16_t color_planes;
  uint16_t bits_per_pixel;
  uint32_t compression_method;
  uint32_t image_size;
  uint32_t horizontal_resolution;
  uint32_t vertical_resolution;
  uint32_t colors_in_palette;
  uint32_t important_colors;
};

bmpImage = SD.open("Circle.bmp", FILE_READ);
...
// Read the file header
bmp_file_header_t fileHeader;
bmpImage.read(&fileHeader, sizeof(fileHeader));
...
// Check signature
...
// Read the image header
bmp_image_header_t imageHeader;
bmpImage.read(&imageHeader, sizeof(imageHeader));
...
// Check image size and format
...
// Locate the pixels
bmpImage.seek(fileHeader.image_offset);

```

The file and image information are stored in little-endian so that works just fine on an AVR.

# Answer
> 3 votes
First of all I suggest you to read the full specification of the bmp file header (for instance on wikipedia).

Particularly see that

1. You can have a color table (palette): consequently the starting address of the bitmap data CAN not be 0x36
2. The pixels are not stored one per byte, but can be packed (see Pixel storage)
3. There are different type of headers
4. Width and Height are 4 byte integers, so your width is fine (272 = 256 + 16)

This said, *if* your bitmap has a standard `BITMAPINFOHEADER` header, and *if* your bitmap has a 24 bit standard coding (16 millions of colors) you can do something like this:

```
int32_t readNbytesInt(File *p_file, int position, byte nBytes)
{
    if (nBytes > 4)
        return 0;

    p_file->seek(position);

    int32_t weight = 1;
    int32_t result = 0;
    for (; nBytes; nBytes--)
    {
        result += weight * p_file->read();
        weight <<= 8;
    }
    return result;
}

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

    Serial.print("Initializing SD card...");
    if (!SD.begin(53)) {
        Serial.println("initialization failed!");
        while (1); // <- this is how you should block execution, not with returns
    }
    Serial.println("initialization done.");

    // Open
    File bmpImage = SD.open("Circle.bmp", FILE_READ);
    File textFile = SD.open("test.txt", FILE_WRITE);

    int32_t dataStartingOffset = readNbytesInt(&bmpImage, 0x0A, 4);

    // Change their types to int32_t (4byte)
    int32_t width = readNbytesInt(&bmpImage, 0x12, 4);
    int32_t height = readNbytesInt(&bmpImage, 0x16, 4);
    Serial.println(width);
    Serial.println(height);

    int16_t pixelsize = readNbytesInt(&bmpImage, 0x1C, 2);

    if (pixelsize != 24)
    {
        Serial.println("Image is not 24 bpp");
        while (1);
    }

    bmpImage.seek(dataStartingOffset);//skip bitmap header

    // 24bpp means you have three bytes per pixel, usually B G R

    byte R, G, B;

    for(int32_t i = 0; i < height; i ++) {
        for (int32_t j = 0; j < width; j ++) {
            B = bmpImage.read();
            G = bmpImage.read();
            R = bmpImage.read();
            textFile.print("R");
            textFile.print(R);
            textFile.print("G");
            textFile.print(G);
            textFile.print("B");
            textFile.print(B);
            textFile.print(" ");
        }
        textFile.print("\n");
    }

    bmpImage.close();
    textFile.close();

    Serial.println("done write");
}

```

The text output of this should be a file with an array of strings like `R10G100B25`, where R is the red component of the pixel, G is the green component and B the blue one.

Now, this is only compatible with the 24bpp format. If you want to support more formats you will need to read the specs and code them.

Let me know if this works for you

# Answer
> 2 votes
Or you could keep your old code with some adjustments, if you just want to read your image without bothering with too many checks.

Change the type of imageSize to `unsigned long`.

The height and width are 4-byte fields, so a single read() wont cut it. You have to declare the height and width as *long* or *int32\_t* variables and then read 4 bytes at each offset, while using bit shifting to assemble the bytes into one number and remembering that it's little endian. Something like this:

```
long width |= bmpImage.read();
width |= (long)(bmpImage.read()) << 8;
width |= (long)(bmpImage.read()) << 16;
width |= (long)(bmpImage.read()) << 24;

```

Repeat this to get the height but use *abs()* to get the absolute value since its usually negative. You can also check for a colour table; usually the ColorDepth field is a good indicator (offset 28); if its less than 16, then you should expect a colour table. But if you know this already, you can skip it and get to the start offset, usually 0x36. Your current code doesnt take the padding into account (even though your image doesn't have any padding) and it also isnt using the actual image width in bytes. To get this width, assuming the BMP uses RGB888 24 bits per pixel:

```
width = ((width * 24) + 31) / 32;
width *= 4;

```

With this, you can now read each row, though its usually arranged bottom-up. However, you arent writing properly to the file. You should use `textfile.print()` and not `write()`; the former will write the decimal value of each byte to your file while the latter will write the exact un-encoded byte to the text file, which would result in a lot of gibberish when you try to display the file's contents, say on Notepad, since the range of printable characters (under default ASCII encoding) is between 32 - 127 and your image probably has lots of bytes outside that range.

---
Tags: arduino-mega
---


# Question
Title: Use potentiometer to control motor's speed
Following the arduino starter kit, one of the projects uses a push button to on/off a motor.

In the end they suggest to try to use a potentiometer to control the speed of the motor. I already did it, but I am not sure how I should use the capacitors(I placed one with the pot).

In one of the previous examples they used 2 100uF capacitors(one for the pot. and another for a servo motor) and I was wondering if this would be the same case.

This is my circuit:

The code:

```
const int POT_PIN = A0;
const int MOTOR_PIN = 9;
int motorSpeed = 0;
int potVal = 0;

void setup()
{
  pinMode(MOTOR_PIN, OUTPUT);
}

void loop()
{
  potVal = analogRead(POT_PIN);

  motorSpeed = map(potVal, 0, 1023, 0, 255);

  analogWrite(MOTOR_PIN, motorSpeed);
}

```

*Previous example with capacitors:*

Code:

```
#include <Servo.h>

Servo myServo;

int const POT_PIN = A0;
int potVal;
int angle;

int alpha = 0.8;
int rawReading;

void setup()
{
  myServo.attach(9);

  Serial.begin(9600);
}

void loop()
{
  rawReading = analogRead(POT_PIN);
  potVal = alpha*potVal + (1-alpha)*rawReading;
  Serial.print("potVal: ");
  Serial.print(potVal);

  angle = map(potVal, 0, 1023, 0, 179);
  Serial.print(", angle: ");
  Serial.println(angle);

  myServo.write(angle);
  delay(15);
}

```

# Answer
> 4 votes
Ah, now I see. Your confusion in this case is perfectly understandable. They threw a couple of capacitors into the circuit without explaining *why they were added in the first place*. In order to understand why capacitors were added you need to go a little deeper into electronics theory, specifically **capacitance** and **inductance**, what they are and how they work.

Inductance is, to put it succinctly, resistance (*not* related to the resistance in resistors, measured in ohms) to change in current by sacrificing or absorbing voltage. If current is 0, then inductance will try to keep it at 0, if at 1A then it will try to keep it at 1A, and so on. Inductance is caused by the magnetic fields generated by electricity flowing through a conductor, and hence **every conductor exhibits some measure of inductance**. (Coils have much higher inductance though, since the magnetic fields of the loops reinforce each other. And a "core" material such as ferrite or iron intensifies the magnetic field.)

Now, this isn't a large problem if your conductors are short, but as they get longer their inductance can cause power issues. Sudden power demand increases are unable to be accommodated because the supply can't put the increased current through the inductance quickly enough. This is where capacitance comes in.

Capacitance is resistance to change in *voltage* by sacrificing or absorbing *current*. When something tries to reduce the voltage either through power consumption or because of high-speed switching, capacitance holds the voltage as close to constant as it can by pulling or dumping electricity out of or into the circuit. Capacitance is caused by charges between two conductors attracting each other through a non-conductive material.

So what happens is that a circuit needs bursts of power to work, and if the wires connecting the supply to the circuit have too much inductance then the circuit will be starved of power. We balance this by placing a capacitance close to the circuit so that it can supply power to the circuit for the short time while the supply is busy overcoming the inductance of the wires.

The servo, being a mechanical device, needs a decent amount of power. We put a **bulk capacitor** near it on the supply lines to help provide this power. The analog input connected to the potentiometer needs much, *much* less power, so the inductance there isn't a problem and we forgo the capacitor there.

# Answer
> 0 votes
Do you want to use a pushbutton to control the speed of the motor?

Then one way to go would be to increment a variable by say 10 every time the switch is pressed.

In pseudocode:

```
// In the setup section:
speed =0

// In the main loop:
Read pushbutton
if different from previous state then speed = speed + 5
if speed > 255 then speed = 0 // Go back to zero if over 255

analogWrite(pin x, speed)  // This sets the PWM value

```

If you want to have a more fancy control then you could increment speed every second by 5 while the pushbutton remains pressed, and also go back to zero speed in small decrement instead of in a single step.

---
Tags: motor, system-design, potentiometer
---


title: How to capture good sound with Arduino?

text:
# Question
Title: How to capture good sound with Arduino?
Is it possible to capture good sound with Aduino? I need to record street / birds / nature sounds.

As I found, maximal sample rate, achievable with built-in ADC is 9kHz, which is to low.

So, I require to use some external hardware. But wave shields I saw are to expensive (comparable by price with Arduino itself), probably, because of excess functions (including not only ADC but also DAC and so on).

Simultaneously, there are ICs, providing ADC functionality and even MP3 encoding functionality for relatively low price. But here a schematic design required.

So, how to find appropriate solution here?

# Answer
> 1 votes
Yes but you want something much faster then the Arduino, normally it is in the 96k~48k bps range. Try this link, they make a lot of great parts and the bulk of what you have to do is control software. You can let the chip do the grunt work (analog) and transfer thee data to where ever you want. Some of the chips will record for 300 seconds plus.

http://www.aplusinc.com.tw/exec/product.php?lg=E&mod=show&cid=43&pid=aPR33A3

I have used there parts they work great.

Have fun, Gil

# Answer
> 1 votes
> Is it possible to capture good sound with Aduino? I need to record street / birds / nature sounds.

The answer is "no" for AVR based Arduino boards. They have simply too low sampling rate, ADC resolution, limited buffering memory and processing speed.

The ADC sample rate is at most 9 K samples per second (112 us per sample) at highest resolution (10 bits). The resolution can be improved (e.g. 12 bits) by using oversampling but this is at the cost of sampling frequency.

The Arduino Uno has only 2K byte memory. Using all that for buffering would give at most 1 K samples. That is little over a second sound data. A SD file could be used but requires a lot of smart programming to not drop samples at max sampling rate.

Low quality, 8-bit samples, then "yes". See here.

Now an Arduino Due is much more powerful, has much more memory, etc. See here.

---
Tags: sound, adc
---


title: arduino and gsm module receive

text:
# Question
Title: arduino and gsm module receive
Can you help me with the codes? I have gizduino(arduino clone), i used the codes in receiving sms from the internet but what i receive is a symbol "y" with two dots at the top. Whats wrong?

My gsm is set to suart.

```
// Example 55.4

#include <SoftwareSerial.h>
SoftwareSerial SIM900(2,3);

char incoming_char=0;

void setup()
{
  Serial.begin(19200); // for serial monitor
  SIM900.begin(19200); // for GSM shield
  SIM900power();  // turn on shield
  delay(20000);  // give time to log on to network.

  SIM900.print("AT+CMGF=1\r");  // set SMS mode to text
  delay(100);
  SIM900.print("AT+CNMI=2,2,0,0,0\r");
  // blurt out contents of new SMS upon receipt to the GSM shield's serial out
  delay(100);
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void loop()
{
  // Now we simply display any text that the GSM shield sends out on the serial monitor
  if(SIM900.available() >0)
  {
    incoming_char=SIM900.read(); //Get the character from the cellular serial port.
    Serial.print(incoming_char); //Print the incoming character to the terminal.
  }
}

```

# Answer
Most probably you are using `sim900` or `sim800` module. These modules would be either fixed to a certain baudrate like `9600` or `115200`, OR the module might be at `auto-baud` mode.

In auto baud mode you need to send `AT\r` to the modem after the modem is switched ON so it can know what baud you are using.

Please check the following...
> 1 votes

---
Tags: gsm
---


# Question
Title: How to send and receive hex or binary numbers via BLE UART?
I am trying to send hex or binary numbers through BLE UART, but it is taking only char value which is converted into ASCII value.

I am using Adafruit's Bluefruit micro device and Bluefruit LE apps.

https://github.com/adafruit/Bluefruit\_LE\_Connect\_Android https://github.com/adafruit/Adafruit\_BluefruitLE\_nRF51

```
Serial.print(F("[Recv] "));
Serial.println(ble.buffer);
BluetoothData=ble.buffer[0];
Serial.println(BluetoothData);

```

In the UART box I want to type only a hex number and receive it in the Ble.buffer of the Arduino only.

# Answer
ASCII is just a pattern of 0s and 1s, and can therefore be represented in binary, hex, octal, or decimal. The interpretation is entirely up to you in your code.
> 1 votes

# Answer
The hex button toggle switch will show what the value of your characters are in hex. find the character that matches the value you want to send and use that. if you type the string 0x01 the app will send 0x30 0x78 0x30 0x31 0x0A. Since it trys to convert your characters to hex.

this table is pretty handy showing what characters are represented by which hex numbers http://web.cs.mun.ca/~michael/c/ascii-table.html.

unfortunately the character representing 0x01 is pretty difficult to type.

You can work around this issue by using the toInt() function in Arduino if you send the number 1 as a character the toInt() function will convert it to an int with value of 1. The hex equivalent is 0x01.
> 0 votes

# Answer
Following code changes have been made to send the values in hex as input from user

1. replace the utf-8 conversion

value = message.getBytes("UTF-8");

by hex

int len = message.length(); byte\[\] data = new byte\[len / 2\]; for (int i = 0; i \< len; i += 2) { data\[i / 2\] = (byte) ((Character.digit(message.charAt(i), 16) \<\< 4) \+ Character.digit(message.charAt(i+1), 16)); } value=data;

2. suppress the exception headlining for UnsupportedEncodingException otherwise it throws a compile time error UnsupportedEncodingException

Result examples :

3F ( hex ) results in ? ( ascii ) 63 results in c
> 0 votes

# Answer
This is a question about data representation. The value you are entering is a string, a sequence of characters, e.g. 0x42. The string can be parsed and converted to binary form either on the transmitting or receiving side.

The string must first be checked that it is valid. In this case a valid hex or decimal number. There are conversion functions that do both at the same time. The standard string function strtol() is perfect for the job. With zero as base argument it will parse both hex, oct and dec number formats.

```
// Receive string
char buf[BUF_MAX];
...
// Convert string to number
char* bp;
long value = strtol(buf, &bp, 0);
bool valid = (*bp == 0);

```

There is also an unsigned variant, strtoul.
> 0 votes

---
Tags: nrf51
---


title: Processing Serial data

text:
# Question
Title: Processing Serial data
I have a PM10 sensor that I'd like to get the values from.

Here's the official documentation from the sensor:

I've looked as serial communication, but how do i process byte by byte of information if it's coming in byte at a time?

I'm looking at this example:

```
void setup() {
  Serial.begin(9600);
  Serial.println("<Arduino is ready>");
}

void loop() {
  recvOneChar();
  showNewData();
}

void recvOneChar() {
  if (Serial.available() > 0) {
    receivedChar = Serial.read();
    newData = true;
  }
}

void showNewData() {
  if (newData == true) {
    Serial.print("This just in ... ");
    Serial.println(receivedChar);
    newData = false;
  }
}

```

Ideally, i'd like to get the PM2 and PM10 values and print them out.

# Answer
The proper method of receiving this kind of data is to use a *sliding window*. That is you visualise the stream of bytes as just that - a stream of bytes (think letters on paper tape). You then have a conceptual "window" on that data which is the width of the packet (10 bytes in this case). As the data passes behind the window you see just 10 bytes of it. When that 10 bytes is in the "right" format (that is, it starts with 0xAA, ends with 0xAB and the checksum is valid) then you have a valid packet and can read the values from it.

The simplest method of implementing that is with a 10-byte array. As a byte arrives on the serial port you shuffle all the bytes down the array to make room for the new byte at the top of the array. Once 10 bytes have arrived that first byte should now have made its way to the bottom of the array.

For instance:

```
uint8_t window[10];

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

void loop() {
    if (Serial.available()) {
        // Slide the window
        for (uint8_t i = 0; i < 9; i++) {
            window[i] = window[i + 1];
        }
        // Add the new character
        window[9] = Serial.read();

        // Output the current window data for debugging
        dumpWin();

        // Check the framing characters
        if ((window[0] == 0xAA) && (window[9] == 0xAC)) {
            // Calculate the checksum
            uint8_t cs = 0;
            for (uint8_t i = 2; i < 8; i++) {
                cs += window[i];
            }
            // If the checksum matches...
            if (cs == window[8]) {
                // ...we have a valid packet!
            }
        }
    }
}

void dumpWin() {
    for (int i = 0; i < 10; i++) {
        Serial.print(window[i], HEX);
        Serial.print(" ");
    }
    Serial.println();
}

```

Getting the data out of the valid packet is now a case of combining bytes into 16-bit integers then dividing them into floats. For instance the PM2.5 would be:

```
uint16_t pm25i = (window[3] << 8) | window[2];
float pm25 = (float)pm25i / 10.0;

```

The PM10 would be the same but with window\[5\] and window\[4\] of course.

---

Since you can't really use the hardware UART for both communication with your sensor and communication with the PC you may want to investigate the use of SoftwareSerial instead of the hardware UART pins for communicating with the sensor.
> 3 votes

---
Tags: serial, sensors
---


title: Error compiling Arduino

text:
# Question
Title: Error compiling Arduino
I've just installed the last version of Arduino 1.6.7 plug my Arduino SmartEverything (http://www.smarteverything.it/) to OS X 10.11.2, try to compile this project: https://github.com/nicolsc/sigfox-weather-station/blob/master/sigfox\_smart\_weather.ino But i got this error

```
/Applications/Arduino.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware "/Applications/Arduino.app/Contents/Java/hardware" -hardware "/Users/nunito/Library/Arduino15/packages" -tools "/Applications/Arduino.app/Contents/Java/tools-builder" -tools "/Applications/Arduino.app/Contents/Java/hardware/tools/avr" -tools "/Users/nunito/Library/Arduino15/packages" -built-in-libraries "/Applications/Arduino.app/Contents/Java/libraries" -libraries "/Users/nunito/Documents/Arduino/libraries" -fqbn=AMEL:samd:AMEL_SmartEverything_native -vid-pid=0X2341_0XE002 -ide-version=10607 -build-path "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp" -warnings=none -prefs=build.warn_data_percentage=75 -verbose "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/arduino_50d3a89dbbfb2b67c903ba23d4913431/sketch_jan21c.ino"
/Applications/Arduino.app/Contents/Java/arduino-builder -compile -logger=machine -hardware "/Applications/Arduino.app/Contents/Java/hardware" -hardware "/Users/nunito/Library/Arduino15/packages" -tools "/Applications/Arduino.app/Contents/Java/tools-builder" -tools "/Applications/Arduino.app/Contents/Java/hardware/tools/avr" -tools "/Users/nunito/Library/Arduino15/packages" -built-in-libraries "/Applications/Arduino.app/Contents/Java/libraries" -libraries "/Users/nunito/Documents/Arduino/libraries" -fqbn=AMEL:samd:AMEL_SmartEverything_native -vid-pid=0X2341_0XE002 -ide-version=10607 -build-path "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp" -warnings=none -prefs=build.warn_data_percentage=75 -verbose "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/arduino_50d3a89dbbfb2b67c903ba23d4913431/sketch_jan21c.ino"
Build options changed, rebuilding all
""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/dev/null"
""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/dev/null"
""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/preproc/ctags_target_for_gcc_minus_e.cpp"
exec: "-w": executable file not found in $PATH
Error compiling.

```

# Answer
> 1 votes
Install Arduino SAMD Boards (32-bits ARM Cortex-M0+) board (using "Tools" -\> "Board" -\> "Boards Manager" menu).

Just search for "SAMD" in the search bar, choose the latest version and install.

---
Tags: compile
---


title: Send analog value over IR?

text:
# Question
Title: Send analog value over IR?
for my rc robot I want to use ir to send/receive the value from a jostick.

Is it possible ? I can't use any other radio chip like nrf24l01.

# Answer
> 3 votes
Yes, it is possible. That is already supported by the IR library. Please see this tutorial for further details. The outline of the sender is:

```
 uint16_t sample = analogRead(A0);
 irsend.sendSony(sample, 16);

```

And the receiver:

```
 if (irrecv.decode(&decodedSignal)) {
    uint16_t sample = decodedSignal.value;
    ...
 }

```

Cheers!

---
Tags: robotics, ir, wireless
---


title: Bluetooth HID module

text:
# Question
Title: Bluetooth HID module
I try to build custom controller and now searching for bluetooth hid module. Which BT HID module compatible with arduino? (not bluetooth serial)

List of some modules:

* BlueSMiRF HID - from sparkfun, expensive (based on rn-42, also available RN-42-EK evaluation board) ✔ compatible
* HM-10 bluetooth module - around $10 (aliexpress), based on cc2540 ht tp://www.ti.com/product/cc2540
* HC-05 Transceiver Module - less $10, maybe supports HID after firmware upgrade(??)
* Bluegiga wt12
* Bluefruit EZ-HID from Adafruit ~$20 (suggested by mwwalk) ✔ compatible

Thanks

# Answer
I'm not entirely sure from your question if you want just the module or a whole breakout board. If the latter, try this from adafruit. It can very easily do his either as mouse or keyboard and is well documented and supported so I think this would be much easier to get running initially. http://www.adafruit.com/products/1535
> 4 votes

# Answer
HC-05 HC-06 and, for example, RN-42 HID are the same looking on hardware design.

Only difference is in firmware.

For educational purposes you can dump firmware from RN42HID and flash HC-05/06 module and you've got a HID module.

The difference in costs of the HID modules is that CSR IDE costs $3000 per licence + developer seat, and when someone invests in developing wants the incomes to come.

Byron's blog will guide you, you need a SPI programmer, but you can use Arduino as programmer/debugger. And you will need blueflash software to backup some info from Your module (calibration of crystal for example, and IDS/MAC/serial) than you can flash the RN firmware, and you have exact copy of RN, last thing is to restore the settings saved from your original firmware.

Just Google it, here is not much place to put all the data and images.

But yes it is possible.
> 3 votes

---
Tags: bluetooth
---


# Question
Title: What project design tools are available?
What do you guys use for project designing?

I just found out about AutoDesk's 123D Circuits, which is nice but I wonder if there is something with more components, tools, etc?

For example, I can add an accelerometer to my project there but no signs of a LCD. I have been learning hardware recently and I feel there should be more complete tools out there.

I know this question may be opinion based but I could not find anywhere to ask. Thanks,

# Answer
> 2 votes
I am using KiCad. It's a full EDA/PCB design suite that is **free**. It's a really nice multi-platform package. It doesn't do circuit simulation(to my knowledge). It's relatively easy to learn via some youtube tutorials and there's a healthy development community and discussion board as well. It outputs industry standard gerber files so you can quote out your designs to pcb manufacturers.

link: http://www.kicad.org/

# Answer
> 1 votes
I think Fritzing is used quite a lot. I have used it myself a couple of times, and I felt it was quite comprehensive. But I haven't used it enough to say whether this is *the* tool to choose.

# Answer
> 1 votes
So, as the other users said, tou can use FRITZING, it is totally free and it does have LCD and a lot of other Shields. But the thing is, if you want a more complete design tool, PROTEUS 8.1 is a very used tool and by far more easy to use than any other design tool (as a complete designer solution). You can even simulate your lcd in software to test if everything is ok before start mounting your Circuit.

Proteus Site: http://www.labcenter.com/index.cfm

Proteus is not free but you can use a lot it.

Here's some images of arduinos in Proteus (The site in portuguese but you just need to see the pictures): http://microcontrolandos.blogspot.com.br/2013/04/proteus-8-professional.html

# Answer
> 0 votes
I use ExpressSCH for doing schematics, usually for posting on web sites like this. It is free, runs on Windows only, and is simple enough to use that I picked it up quite quickly. :)

Example schematic:

The red arrows I added later in the GIMP.

It comes with quite a few symbols pre-defined. You can make others from scratch (using boxes, lines, etc.) or take an existing one, "break it apart", and then re-assemble to your desires. Once you have something the way you want it you "group as symbol" and it can be used again in the future.

The program has a sister program ExpressPCB for PCB layouts, however I haven't used that much.

---
Tags: arduino-uno, project
---


# Question
Title: Share battery pack with Arduino and DC motors
I used 6 rechargable AA batteries (total 7.2V) to power my Arduino (UNO R3) Car's two DC Motors (using L293D IC as motor driver). I used separate 9V battery to power arduino itself. But I want to share same 6 battery pack to power my arduino via barrel jack. Please suggest me how can I do this? What precautions Should I take? Like decoupling capacitors or any other?

# Answer
> 3 votes
You may have read that the UNO can accept 7-12 volts as input power. Your AA battery pack (7.2 volts) is very near the low limit of 7 volts. After just a little discharge of the battery (and also voltage drop from motors running), your batteries are likely to deliver less than 7 volts.

As your AA battery goes below 7 volts, then the 5 volts (regulated) will also begin to go lower. A reasonable scenario would be if AA battery was 6.5 volts (1/2 volt low), then the 5 volts regulated would be about 4.5 volts. The UNO is likely to operate ok at this voltage, but as voltage goes lower operation could become a problem depending upon your program used.

Since you are experimenting with a toy car, I would say to go ahead and run both the motors and UNO from the same battery pack. Not a lot to lose on trying.

The UNO already has decoupling capacitors in it's 5 volt regulator circuit.

Just for fun, you could use an Analog input to measure your 5 volts and if the voltage drops to 4.5 volts, you could dis-allow motor operation and flash an LED (or other action). Just a low battery indicator.

If you decide to measure the 5 volts with an analog input, read up on using resistor dividers and the Analog reference (A-ref). Because 5 volts dropping to 4.5 volts could effect your analog reading, depending upon what you use for Analog reference.

---
Tags: arduino-uno, motor
---


title: How can I dim a 10w LED?

text:
# Question
Title: How can I dim a 10w LED?
I'm trying to dim a 10w LED via Arduino PWM.

This is the LED that I have: http://www.banggood.com/10W-Warm-Pure-White-High-Brightest-Save-Power-LED-Light-Lamp-p-88169.html

Without knowing much about this stuff, I bought this (namely because it had LED, DIM, and PWM in its name): http://www.ebay.com.au/itm/121437119430?\_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

I can't get the eBay dimmer to work for love or money. When I connect it to ground directly on the battery terminal, it goes off, which means the dimmer circuit is working. I don't even know where to start with MOSFET dimming solution, but I think that the IRFZ44N MOSFETs are the wrong ones because they won't turn on with 5v power (they need 10v or something, but those are the ones I have on hand).

I can't seem to find any good guides on how to do this after stacks of googling, and to be honest, I don't even know if those LED's can be dimmed in the first place.

What do I need to make this happen?

# Answer
> 1 votes
Well, it appears that your driver should do that for you. Since you already have the MBI6651 driver, read its datasheet and so you can get a guess on how it should work:

1. attach a 9-35V supply to the Vin-GND terminals. I suggest to use at least 12V
2. attach the LED to the terminals LED+ and LED- (remember the polarity!)
3. attach a transistor to pull down the pin DIM
4. send a PWM signal (frequency between 100Hz and 1000Hz) to the transistor and you should see the LED light up and then dim

If it works then you can try to send to DIM directly th PWM signal, but personally I don't recommend so (unless the board already have the transistor)

EDIT:

How to attach an nMOS to the DIM pin. Since the pin is internally pulled up, you don't need any pullup. So you just need an nMOS. I suggest you to use a SOT-23 logic level nMOS connected this way:

no external components (as long as the nMOS supports 5V on the gate, but every discrete mosfet should). As for the nMOS, I prefer the SMD case because it is easy to solder also on perfboards (just use three pads forming an L shape and you'll see that you can easily solder it). Just choose any n-channel mosfet with a maximum threshold voltage of 2V or less and you are done

# Answer
> 0 votes
I would suggest the CAT4101 PWM controllable constant current sink LED driver. You might want 2 in parallel for the higher current.

They can deal with up to 1A each (theoretically) though they may get a bit hot at that current level - so it would be better to parallel them so they deal with roughly 500mA each.

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


title: Check the value of character variable

text:
# Question
Title: Check the value of character variable
I'm writing some code for Arduino and I'm not sure if I'm checking the value of this character variable correctly. Can you please tell me if this is correct:

```
const char* front = "front";
const char* back = "back";

eyeballs(front);
eyeballs(back);

void eyeballs(const char* frontOrBack){

if (frontOrBack == "front") {
    digitalWrite(frontEyes, LOW);}//end if
  else if (frontOrBack == "back") {
    digitalWrite(backEyes, LOW);}//end else*/
}

```

# Answer
Since you are using C strings (array of characters) instead of the C++ String class, you cannot use the == operator.

Instead, you can use the C style strcmp function, which is also part of the C++ library:

```
    #include <string.h>
       .
       .
       .

    if (!strcmp(frontOrBack,"front")) {
        digitalWrite(frontEyes, LOW);}//end if
    else if (!strcmp(frontOrBack,"back")) {
        digitalWrite(backEyes, LOW);}//end else*/
    }

```
> 6 votes

# Answer
Another option would be an enum.

```
enum
{
   FRONT,
   BACK
}
.
.
.
   if (frontOrBack == FRONT)
   {
      // Stuff
   }
   else if (frontOrBack == BACK)
   {
      // Some other stuff
   }

```
> 3 votes

---
Tags: c
---


# Question
Title: arduino flexbot drone connected in a wrong way
I have an arduino flexbot, I was making some test and accidentally I connected the battery in the opposite way. The drone turned on the six motors when I connected the battery, but any led turned on to see if the processor was working. I disconnected the battery and connected it in the wrong way again same thing happened the six motors turned on again. Then I realize that the battery was connected in a wrong way and connected it in the right way. The LED's turned on as always, and also the blue-tooth module was working I could detect the device using the control-application. I tried to fly the drone but the motors didn't turn on, I could hear little click and I saw a little movement of a motor.

I connected my drone to my PC using the micro USB connection, also I connected the battery. I tried to turn on the drone and in this way it looks to work fine.

But when I disconnect the USB port and I tried to fly it the same thing happens, the click and the little movement. Any idea of what can I do to fix this drone?

# Answer
> 2 votes
The motors turning on is expected because or the reverse diode in the mosfets driving the motor.

Looking at the schematic, it seems like the problem is on the 5v rail. If 5v isn't supplied by the USB port, it is provided by the LTC3200 (DC/DC converter)(U3 on the pcb). I think that's where the problem is, as that would explain why it only work when USB is connected.

To confirm this you'd have to measure the output voltage (pin1 (pin nearest to the ATMega) of U3, and see if it's 5 volt.

To fix it you should ideally replace this part. But it might also work without, if you simply connect the battery voltage directly to the 5v (i.e. jumper pins 1 and 5).

---
Tags: arduino-leonardo
---


# Question
Title: Can I use my phone's charger to connect arduino M0 pro R3 with computer?
I found out that the arduino M0 pro R3 needs either micro HDMI or micro USB.

Since I don't have any micro USB or HDMI adapters, can I use the Samsung galaxy USB/micro adapter to connect?

# Answer
Echoing what Gerben said, in order to wrap up this question:

* If the Samsung cable has a micro-usb on one end, and a usb-a on the other side, then I don't see why not.
* You just want to power it, not connect it to a PC? A regular USB port only supplies upto 500mA, so 1.5A is plenty.
* The allowed input voltage range for this pin is 6-20 V. source. So your 12v adapter is also fine.
> 1 votes

---
Tags: arduino-pro-mini
---


title: How to change Void with button press

text:
# Question
Title: How to change Void with button press
I have 2 buttons and 2 voids (blink\_slow) (blink\_fast). i need to be able to press button 1 and blink-slow void will run, then press button 2 and blink fast will run. none of my code works, any idea how i can do this?

```
const int btn1 1;
const int btn2 2;
const int led  13;

void setup(){
pinMode(btn1,INPUT_PULLUP);
pinMode(btn2,INPUT_PULLUP);
pinMode(led,OUTPUT);
digitalWrite(led,HIGH);
}
void loop(){
if(digitalRead(btn2 =LOW)){
blink_slow();
}
if(digitalRead(btn3 =LOW)){
blink_fast();
}

void blink_slow(){
digitalWrite(led,LOW);
delay(1000)
digitalWrite(led,HIGH);
delay(1000)
}

void blink_fast(){
digitalWrite(led,LOW);
delay(500)
digitalWrite(led,HIGH);
delay(500)
}

```

# Answer
> 3 votes
Start by correcting the obvious:

```
const int btn1 = 2;
const int btn2 = 3;
const int led = 13;

void setup()
{
  pinMode(btn1, INPUT_PULLUP);
  pinMode(btn2, INPUT_PULLUP);
  pinMode(led, OUTPUT);
  digitalWrite(led, HIGH);
}

void loop()
{
  if (digitalRead(btn2) == LOW) {
    blink_slow();
  }
  else if (digitalRead(btn3) == LOW) {
    blink_fast();
  }

void blink_slow()
{
  digitalWrite(led, LOW);
  delay(1000)
  digitalWrite(led, HIGH);
  delay(1000)
}

void blink_fast()
{
  digitalWrite(led, LOW);
  delay(500)
  digitalWrite(led, HIGH);
  delay(500)
}

```

The mistakes where 1) const variable assignment, 2) using pin 1 (TX) is a potential risk if you later what to use Serial for debugging, etc, 3) condition expression, and a lot of formatting. Open your C/C++ book and check the syntax.

Now your turn to improve this!

---
Tags: c++, button
---


# Question
Title: Compilling error not highlighting line in code
A newbe here. How come when I compile with an error I do not get the line or line number highlighted? I Get the errors just can't find where they are.

# Answer
> 1 votes
The line in error can often be highlighted, however because of the way the IDE plays with your source file this is not always the case.

See my post about How the IDE organizes things.

The IDE adds extra lines to your source, and then tries to hide that with #line directives. This can confuse the way error messages are handled. It is another example of the "helpful" IDE not always being helpful.

In any event, as Igor said, you can look for the line number in the error message and use that to find the error. Failing that, look at the quoted source code and search for that.

---
Tags: arduino-uno, compile
---


# Question
Title: My arduino won't show up in Device Manager in any way, neither in unknown devices nor in COM port.
I have a brand new arduino(original), and it is not showing up in Device manager or anywhere else. Even the computer doesn't Prompt anything. I am using Windows 7 32 bit.

# Answer
As the OP reported: *It worked with a different cable.*

I converted his comment to an answer so the system would regard this issue as solved. Please accept this answer.

---

Some cheap USB cables only carry power, and not data. I have such a cable that came with a USB desk light. To save money they only run two wires and not four, since the desk light is not a data device.

Be cautious about grabbing any old cable from your desk for testing. Make sure it is designed for data use. If in doubt, try a known good cable.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Morse code translator Loop the same sentence
I'm a newbie so forgive my ignorance.

I'am using the Morse code translator to light up the LED which is fine but after it has processed the sentence it turns off. How can I get it to loop the sentence continuously.

Thanks

# Answer
I guess this is the sketch you are using. It reads characters from Serial and translates them to Morse code.

What you need to do to make it loop a sentence is, 1) read a sentence into a buffer, 2) loop though the buffer and translate to Morse code.
> 1 votes

---
Tags: led
---


title: Is my Arduino Uno broken?

text:
# Question
Title: Is my Arduino Uno broken?
I think I broke my Arduino Uno as I was playing with it. I connected an ultrasonic range finder to it and uploaded a sketch to it. It was working fine until I accidentally touched the ICSP headers for the USB interface (the pins near the USB port). Now,everything is still working but my computer cannot detect it and it does not show up in the device manager or the IDE. Please tell me if it is broken and how to fix it.

BTW, I just bought it and just started using it after another Arduino had the same problem.

# Answer
> Please tell me if it is broken and how to fix it.

See Have I bricked my Arduino Uno? Problems with uploading to board

Those tips may also help with fixing problems with your Mega (if you ever have them). ;)
> 0 votes

---
Tags: arduino-uno
---


title: panstamp device signature is random

text:
# Question
Title: panstamp device signature is random
I Have 2panstamp. I can program the first but not the second with the arduino program.

When I upload the sketch (a simple blink) on the second, I got this

```
Reading | ################################################## | 100% 0.03s

avrdude: Device signature = 0x004e22
avrdude: Expected signature for ATmega328P is 1E 95 0F
Double check chip, or use -F to override this check.

avrdude done.  Thank you.

```

And if I retry, I got this.

```
Reading | ################################################## | 100% 0.03s

avrdude: Device signature = 0x81f014
avrdude: Expected signature for ATmega328P is 1E 95 0F
Double check chip, or use -F to override this check.

avrdude done.  Thank you.

```

The device signature is not the same anymore ... I've changed the wire and re-open arduino program. But it don't change, the device signature change (often 0xE1E1E1). I've check the connection between the ATmega and the wire and everything is ok.

Is the Panstamp broken ? or should I do a kind of factory reset?

# Answer
> 0 votes
> Is the Panstamp broken ?

Sounds like it. If one works, and the other does not, using the same wiring, it looks like you have a faulty one.

> or should I do a kind of factory reset?

You can't really "factory reset" a chip like that. Possibly there is a problem with the fuses. You may be able to explore further here:

Have I bricked my Arduino Uno? Problems with uploading to board

---
Tags: rf
---


# Question
Title: Windows driver installer not detecting arduino
I'm trying to program my Arduino Uno with my Windows PC. I followed all the instructions on the site. I mistakenly downloaded the .zip file and didn't unzip it, before plugging in my Arduino Uno. So naturally, no message came up. I then followed the correct procedure, but Windows driver installer does not detect the Arduino Uno. What can I do to fix this?

# Answer
Per my comment above, the drivers are not installed when using the Arduino editor from an extracted zip file. If you are feeling adventurous, they are located in the /drivers folder and you can install them manually, there are plenty of instructions elsewhere on the internet on how to do that.

My recommendation would be to just download and run the installer version of Arduino, as that will take care of registering the drivers for you. The installer can be found on the download page indicated with the text "Windows Installer".
> 1 votes

---
Tags: arduino-uno, installation
---


# Question
Title: How to properly reverse DC motor direction with 2 limit switchws
Hello i am trying to reverse a dc motor direction upon hitting either limit switch. but noting is working can some one point me in right direction. all example i find use stepper motors and step count.

```
const int sw2 = 2;          //Up Limit switch
const int sw3 = 3;          //Down Limit switch
const int ic1_2 = 8;        //TA8409S IN2
const int ic1_1 = 9;        //TA8409S IN1
const int enable = 10;      //TA8409S Enable (motor)
int sw2State = 0;
int sw3State = 0;

void setup() {
  pinMode(sw2, INPUT_PULLUP);
  pinMode(sw3, INPUT_PULLUP);
  pinMode(ic1_1, OUTPUT);
  pinMode(ic1_2, OUTPUT);
  pinMode(enable, OUTPUT);
  digitalWrite(enable, 1);
  Serial.begin(9600);
}

void loop() {
  tilt_up();
}

void tilt_up()
{
Serial.print("up Started\n");
  digitalWrite(ic1_1, LOW);
  digitalWrite(ic1_2, HIGH);
  sw2State = digitalRead(sw2);
  if (digitalRead(sw2State == LOW)) {
    tilt_down();
    Serial.print("sw2 pressde\n");
  }
}

void tilt_down()
{
  Serial.print("down Started\n");
  digitalWrite(ic1_1, HIGH);
  digitalWrite(ic1_2, LOW);
  sw3State = digitalRead(sw3);
  if (digitalRead(sw3State == LOW)) {
    tilt_up();
    Serial.print("sw3 Pressed\n");
  }
 }

```

# Answer
> 1 votes
If you want to reverse the movement you sould remember where you are going. This, along with the brackets correction suggested by @MikaelPatel and @NickGammon, leads to this code:

```
boolean moving_up = true;

void loop() {
    if (moving_up)
        tilt_up();
    else
        tilt_down();
}

void tilt_up()
{
    digitalWrite(ic1_1, LOW);
    digitalWrite(ic1_2, HIGH);
    if (digitalRead(sw2State) == LOW) {
        moving_up = false;
        Serial.println("sw2 Pressed");
        Serial.println("down Started");
    }
}

void tilt_down()
{
    digitalWrite(ic1_1, HIGH);
    digitalWrite(ic1_2, LOW);
    sw3State = digitalRead(sw3);
    if (digitalRead(sw3State) == LOW) {
        moving_up = true;
        Serial.println("sw3 Pressed");
        Serial.println("up Started");
    }
}

```

# Answer
> 1 votes
```
void loop() {
  tilt_up();
}

void tilt_up()
{
...
  if (digitalRead(sw2State == LOW)) {
    tilt_down();
...
  }
}

...

void tilt_down()
{
...
  if (digitalRead(sw3State == LOW)) {
    tilt_up();
...
  }
 }

```

You are recursing here. `loop` calls `tilt_up` which eventually calls `tilt_down` which calls `tilt_up` and so on until you - rather quickly - run out of RAM.

Rewrite so that you are not doing that.

---

Also see what @MikaelPatel told you in your other question. You have the brackets in the wrong place.

```
  if (digitalRead(sw2State == LOW)) {

```

should be:

```
  if (digitalRead(sw2State) == LOW) {

```

# Answer
> 0 votes
I got it to work!!! do not know if it is the right way ... but it works. thank you all for your input/advice. here is the new working code:

```
/*

 */

// set pin numbers:
const int sw2 = 2;           // Down limit
const int sw3 = 3;           // Up Limit
const int ledPin =  13;      // Pwr L.E.D
const int ic1_2 = 8;         // TA8409S IN2
const int ic1_1 = 9;         // TA8409S IN1
const int enable = 10;       // TA8409S Enable (motor)

int sw2State = 0;            // Down Limit State
int sw3State = 0;            // Up   Limit State

void setup() {
  // Setting L.E.D and Motor In, Enable pins as an output:
  pinMode(ic1_1, OUTPUT);
  pinMode(ic1_2, OUTPUT);
  pinMode(enable, OUTPUT);
  pinMode(ledPin, OUTPUT);
  // Setting limit switches pins as inputs
  pinMode(sw2, INPUT_PULLUP);
  pinMode(sw3, INPUT_PULLUP);
  // Enables motor
  digitalWrite(enable, 1);
  //Starts program down
  down();
}

void loop() {
  // reads the state of the limit switches
  sw2State = digitalRead(sw2);
  sw3State = digitalRead(sw3);

  if (sw3State == LOW) {
    down();
  }
  if (sw2State == LOW) {
    up();
  }
}

void up() {
  digitalWrite(ic1_1, LOW);
  digitalWrite(ic1_2, HIGH);
}

void down() {
  digitalWrite(ic1_1, HIGH);
  digitalWrite(ic1_2, LOW);
}

void err() {
  digitalWrite(enable, LOW);
  digitalWrite(ic1_1, LOW);
  digitalWrite(ic1_2, LOW);
}

```

---
Tags: c++, h-bridge
---


# Question
Title: What is the simplest way to "ask" the arduino which input pins are HIGH?
I am trying to build a 36-line cable tester, using the Digistump DigiX (99 i/o pins). Digital pins 0-35 are outputs, connected via the cable in question, to (in a perfect world) digital input pins 36-72. The plan is to have 36 neopixels (to conserve DigiX pins), one corresponding to each line in the cable. Currently they light up green for connection and red for no connection.

It's easy to check if output 0 goes to input 36, but there are more potential problems in a cable than no connection...

What if there is a short and output 0 goes to 36 and 42? It will still show up as correct when it tests 0 to 36... I somehow need to "ask" it what, if any, inputs (pins 36-72) are HIGH when only output 0 is HIGH.

I'm not sure how I'm going to display this extra data yet (Lcd maybe? Or maybe any pins shorted together all use a unique led color...), but I want to make sure the idea will work before I move on to that. Here is what I have working so far, just using a 3-line cable for now. And yes, I'm new to this. Any advice would be greatly appreciated!

```
#include <FastLED.h>
#define NUM_LEDS 3
#define LED_PIN 6
CRGB leds[NUM_LEDS];
#define brightness 25
int var = 0;

void setup() {
  for (int sendPins=0; sendPins <= 2; sendPins++) {
    pinMode(sendPins, OUTPUT); }

  for (int recPins=3; recPins <= 5; recPins++) {
    pinMode(recPins, INPUT); }

    FastLED.addLeds<NEOPIXEL, LED_PIN>(leds, NUM_LEDS);
    FastLED.clear();
}

void loop() {
  while (var < 3) {    //so it only runs once for each line in the cable.
    var++;
  for (int sendPins=0; sendPins < 3; sendPins++) {
    digitalWrite(sendPins, HIGH);

    int recPins = map(sendPins, 0, 2, 3, 5);  //made more sense to me than another for loop.

     int recPin = digitalRead(recPins);
     if (recPin == HIGH)
     {
      leds[sendPins].g = brightness;
      leds[sendPins].r = 0;
      FastLED.show();
     }
     else
     {
      leds[sendPins].r = brightness;
      leds[sendPins].g = 0;
      FastLED.show();
     }

      digitalWrite(sendPins, LOW);
      delay(250);      //just for testing so i know it's going through them all.
  }
 }
}

```

# Answer
> 2 votes
There is a technique, which I used some 40 years ago to test for changes on a set of input pins. This can easily be configured to test serially.

Put a 1 on an output pin say 5. Create an integer e.g. 010000 with a `1` in the appropriate position. Read ALL inputs and `XOR` with the created integer. If one and only one input is `1` the resultant value will be `0`. This is easy to implement in a loop just by shifting the `1` left each time.

The technique works if you can read all inputs into a integer. This was OK for our 32 bits, but could be extended.

It is probably easier to code than explain, but depends on what you have to do to read all inputs.

# Answer
> 0 votes
I believe you can read the port register that contains the current state for your pin. The port names take the form of "PORTA" - "PORTE". (The number of port registers varies with the processor in your arduino, and the pin to port mappings are also different across processor models, so this approach will tie you to Arduino models that use the same processor chip)

Another approach would be to store the state you write to each pin to a boolean variable and just read that. Create a central method that takes a pin number and a new state. That method would save the new value to an array, indexed using the pin number, and then also set the pin. You could then write a method that would read the current pin value from the same array .

# Answer
> 0 votes
Use nested loops. Test each pin one by one. For each one pin test, look for the correct wire to be on and check all the others and either look for an "on" or count how many bad on's there are.

HTH.

---
Tags: pins, led, system-design, code-optimization
---


title: RS485 bus voltage?

text:
# Question
Title: RS485 bus voltage?
Does anyone know the voltage situation regarding multi-drop nodes on an RS485 bus please?

Nick Gammons RS485 article shows 2 different hardware configurations, one using 5v devices, and another using 3.3v devices, and I am fairly sure my Pelco PTZ CCTV system uses 12v.

But I have never seen anything mentioned anywhere about needing to voltage-match nodes on an RS485 bus.

So I am unsure whether the MAX driver chips isolate the RS485 bus voltage from the mcu logic levels.

Or do any lower voltage devices (3.3v or 5v) need logic-level matching to their MAX driver chips, which all need powering from the higher bus level (perhaps 12v)?

Basically, I wish to add an 'intelligent' arduino controller to an existing ptz cctv system.

# Answer
> 2 votes
RS-485 is a differential bus. As long as the *difference* in voltage between the two lines reaches certain thresholds the signal can be interpreted unambiguously regardless of the system supply voltages. Isolation (from ground loops) is not provided by default by the driver, but can be implemented easily enough.

# Answer
> 2 votes
According to my datasheet for the LTC1480:

* –7V to 12V Common Mode Range Permits ±7V Ground Difference Between Devices on the Data Line

**Absolute maximum ratings**

* Supply Voltage (V CC ) : 7V
* Driver Input Voltage : – 0.3V to V CC + 0.3V
* Driver Output Voltage : ±14V
* Receiver Input Voltage : ±14V
* Receiver Output Voltage : – 0.3V to V CC + 0.3V

---

> I am fairly sure my Pelco PTZ CCTV system uses 12v.

Judging by the above you would need to drop Vcc on the part involving your 12V gadget and use level shifters for the logic levels (if you used this particular chip).

# Answer
> 0 votes
I suspect that the line-driver Vcc may be using a commercial standard of 5v which we are not aware off.

The RS485 Vcc VMax is only 7v anyway, so presumably the thousands of different 12v RS485 CCTV devices on the market must use line-drivers chips with a Vcc of 5v because they were historically assumed to be interfacing to TTL logic levels, and therefore still will be for compatibility.

So for integration, I think any 3.3v logic nodes will require level-matching up to a line-driver chip which has its Vcc connected to 5v for RS485 bus compatibility.

Line-driver Vcc would not normally be a problem for any home-brew systems, but could offer a potentially serious gotcha if mixing 3.3v home-brew with existing commercial 5v equipment.

I had been expecting it to be an already known problem, but apparently not, so it would seem to be something worth being aware of.

---
Tags: communication, rs485
---


# Question
Title: Using Temperature sensor arduino to trip off an ac device
Using Temperation through arduino to trip off an ac device?

# Answer
Yes, there are lots and lots of project descriptions similar to yours (if I guesstimate) on the web. Google is your friend.

Here is one link to an interesting project - if you are interested in brewing beer.

Cheers!
> 2 votes

---
Tags: relay
---


title: Porting my project to multiple Nanos

text:
# Question
Title: Porting my project to multiple Nanos
I'm still fairly new to the Arduino world. I got myself a kit with a clone board couple of months ago and have successfully prototyped the project and got it to the state I want it to be. I now want to create 5 - 10 working models of what I've done.

I'd seen on Amazon that I could get 5 Nano clones for about £10 and this seemed ideal to me. Until I saw that people were complaining that some Nano's aren't quite a direct replacement for the Uno that I have working. There's some kind of problem with loading the software from the IDE.

I really don't want to do anything more than just load my software onto the Nanos "As Is" using the IDE I already have.

Can anyone recommend what I need to look out for to ensure that the Nanos I buy will work this way please?

# Answer
The Arduino Uno and Arduino Nano are fairly compatible.

**Problems:**

* The board layout isn't the same, Nano's won't wield a classic "shield".
* Nano's don't have a barrel jack.
* Nano's (usually) have a micro USB connector. While the Uno has another one.
* But, Nano's are smaller, withouth leaving out the USB connection.

**But wait!**

Microcontrollers of the same family are quite scaleable, Nano and Uno might even have the same micro on it! Be sure your Nano has the same Atmega328(P?) chip as your Uno. Check if the pins you're using, are accessible on the Nano. Then you should be fine.

There is a little problem with cheap Arduino Nano's, I've bought 2, from 2 different vendors. They we're about 3$.

* The first one featured a counterfeit FTDI chip. By installing the latest FTDI drivers, my FTDI actually got bricked. I had to undo this by using M\_PROG or some EEPROM flashing tool to unbrick the chip, and install older drivers (which didn't corrupt it).
* The second one featured an CH340G usb-serial chip. I had to download and install the drivers from a chinese website. But Windows wouldn't install unsinged drivers that easily. You have to go into advanced boot options mode and allow installing unsigned drivers.

Getting these Nano's working took me an reasonable amount of time. But they now are working quite well :) It's something to take into account when buying cheap.

I wouldn't really bother for the alternative crystal, as long as they're 16Mhz. For time-critical behaviour, I wouldn't rely too much on your crystal.
> 2 votes

# Answer
> ... people were complaining that some Nano's aren't quite a direct replacement for the Uno

First, I hope you have understood that the Nano and Uno have totally different board formats. The Uno is the classical Arduino format. And the Nano is for breadboards.

Second, (and this will have to be a guess in lack of info or reference in your question) the Nano USB hardware on clones may differ and require another device driver. There might be other component selections to reduce the cost such as alternative a crystal for the oscillator, protection fuse, etc.

Cheers!
> 1 votes

---
Tags: arduino-ide, arduino-nano
---


# Question
Title: need help for saving the millis function when arduino was rebooted
I have two questions want to ask

1. I'm using Arduino Uno with 16\*2 LCD Blue ( also I have temp. sensor and two motors also 3 limit switches) ,, my code is working good, but sometimes my lcd stop printing the values of Temperature and time \[print nothing i.e. print all the leds on\] \\ then when I reboot it everything works good .... why this problem happened ?
2. Is there any way to save the value of millis function when the arduino was rebooted ?

thanks for your help regards

---

My code is for an egg incubator , it consists of

1. Dht22 sensor \[humidity + Temp\]
2. three limit sw.
3. one motor
4. 16\*2 lcd
5. lamp \[acting as heaters\]

As I said previously, millis function that I'm using is for controlling the motor movement every 3 hours and stop the movement after 18 days of working

The main problem I faced is POINT 1 that I mentioned previously (I don't need to lose the time when I reboot the LCD)

If any one can help by giving me a short code as an example who to deal with EEPROM or any other idea.

Here is my code

```
#include "DHT.h"  //includes lib for the temperature-humdity sensor
#include <LiquidCrystal.h> //lcd lib

#define DHTPIN 13 //pin that DHT is connected to
#define DHTTYPE DHT22 //Sensor we are using

DHT dht(DHTPIN, DHTTYPE); //defines location for DHT

int sw1,sw2,sw3;
const int LM1=0;
const int LM2=1;
const int LM3=6;
const int LAMP=8;
const int CW=10;
const int CCW= 9;
const int Buzzer=7;
long previousMillis = 0;        // will store last time LED was updated
unsigned long RealTime = 0;
float MOTORTime =0;// This is the real time that present on LCD now.
unsigned long MOTORSTOP = 0;// store the valve after 18 days of ranning ,,

// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 10800000;           // interval at which to blink (milliseconds)(3 hours waiting)

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

void setup() {

  lcd.begin(16, 2);   // set up the LCD's number of rows and columns: [LCD that we have (Colomn,Row)]
  pinMode(LAMP,OUTPUT);
  pinMode(LM1,INPUT);
  pinMode(LM2,INPUT);
  pinMode(LM3,INPUT);
  pinMode(CW,OUTPUT);
  pinMode(CCW,OUTPUT);

 }
void loop() {
  sw3=digitalRead(LM3);
      unsigned long currentMillis = millis();
MOTORSTOP = currentMillis;
if (MOTORSTOP < 1555200000){ // 18 days
  float h = dht.readHumidity(); //defines the variable for humidity
  float t = dht.readTemperature(); //defines the variable for temperature
  // set the cursor to column 0, line 0
  lcd.setCursor(0,0);
  // print the humidity
  lcd.print("H ");
  lcd.print(h);
  lcd.print("% ");
  //move line down
  lcd.setCursor(0,1);
  lcd.print("T ");
  lcd.print(t);
  lcd.print("C ");

  lcd.setCursor(10,0);
  lcd.print("MOTOR"); // to print motor working time

if (t==37.65)digitalWrite(LAMP,LOW);// Lamp OFF
else if (t>37.65)digitalWrite (LAMP,LOW); // Lamp OFF
else { digitalWrite(LAMP,HIGH);}// Lamp ON

  delay(2000); //wait two sec. before taking another reading.
  ///////////////stepper motor control and delay time 2.45 hours.
 sw1= digitalRead(LM1);
  sw2= digitalRead(LM2);

  RealTime = currentMillis - previousMillis;
  MOTORTime=((RealTime/(1000))/60); ////////////////////////////////////////////
  MOTORTime = 180 - MOTORTime;

  if (MOTORTime >= 1){
   lcd.setCursor(10,1);
  lcd.print(MOTORTime); }// this will print the ACTUAL Time Remaining on LCD
  else {
    lcd.setCursor(10,1);
   lcd.print("<1 MIN");}

  if(RealTime > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

  if (sw1==LOW && sw2==HIGH){
    digitalWrite (CW,LOW);
    digitalWrite (CCW,LOW);
    do {
      digitalWrite(Buzzer,HIGH);
      digitalWrite (CW,HIGH);// change the direction of rotation (DOWN Movement)
      digitalWrite (CCW,LOW);

      sw2= digitalRead(LM2);}
      while(sw2==HIGH);}

      else if (sw1==HIGH && sw2==LOW){

      digitalWrite(CW,LOW);
      digitalWrite(CCW,LOW);

        do {
          digitalWrite(Buzzer,HIGH);
          digitalWrite(CW,LOW);// change the direction of rotation (UP Movement)
          digitalWrite(CCW,HIGH);

          sw1= digitalRead(LM1);}
          while(sw1 == HIGH);}}
}
//----------------------------------------------------------------------------------------------------------------------
else if (((MOTORSTOP/10800000)>= 144 )&& (LM3== LOW)&&(MOTORSTOP >= 1555200000)){
  digitalWrite (CW,LOW);
    digitalWrite (CCW,LOW);

   float h = dht.readHumidity(); //defines the variable for humidity
  float t = dht.readTemperature(); //defines the variable for temperature
  // set the cursor to column 0, line 0
  lcd.setCursor(0,0);
  // print the humidity
  lcd.print("H ");
  lcd.print(h);
  lcd.print("% ");
  //move line down
  lcd.setCursor(0,1);
  lcd.print("T ");
  lcd.print(t);
  lcd.print("C ");

  lcd.setCursor(10,0);
  lcd.print("MOTOR"); // to print motor working time
  lcd.setCursor(10,1);
  lcd.print("OFF");

if (t==36.70)digitalWrite(LAMP,LOW);// Lamp OFF
else if (t>36.70)digitalWrite (LAMP,LOW); // Lamp OFF
else { digitalWrite(LAMP,HIGH);}// Lamp ON

  delay(2000); //wait two sec. before taking another reading.

}
}

```

# Answer
You might try a real-time clock module instead of the `millis()` function. They keep time in external hardware and are battery backed so continue through a power down, you get calendar date and clock time instead of milliseconds since restart, and they don't overflow every 50 days.
> 3 votes

# Answer
It has been suggested to you to save the millis value in the EEPROM. Although this can work, there is a big issue with the frequency at which you save it. If you save too often, you will burn your EEPROM, as it is only rated to 105 writes. If you do not save often enough, you will have most of the time a very outdated value in EEPROM. The problem can be mitigated by adopting a wear-leveling strategy, but this adds significant complexity.

There is a simpler solution to this problem: instead of using the EEPROM, save the value in RAM. Actually, the millis value already lives in RAM, and since the RAM is not initialized by hardware on reset, you will find, when your program starts, that the last millis is right where you left it! It is then cleared by your program, in a function called `__do_clear_bss` that belongs to the C runtime and runs before `setup()`.

In order to preserve millis across a reset, you can do the following:

* Write a function that copies the millis value into some other global variable. This function must run early in the startup sequence, before `__do_clear_bss` clears millis. This can be achieved by putting the function in the *.init3* section of the program, as explained in the avr-libc documentation on memory sections. And the global variable must be in the *.noinit* section in order for the C runtime not to mess with it.
* In `setup()`, restore the millis value from that global variable.

This way you will have a continuous millis across resets, with one caveat: on a cold boot, it will start with an unpredictable value. This should be no issue if you take care to never rely on absolute time but only on time differences, which is a good practice if only to avoid issues when millis rolls over. If you nevertheless want to reset millis on a cold boot, you have several options:

1. Connect a "reset time" button to your Arduino and hold the button pressed when you power it up. `setup()` would then know it should not restore the millis value.
2. Write some magic number in RAM. If you find this number at startup, it is extremely likely that the program is starting from a warm reset.
3. If your Arduino has a fairly recent version of optiboot, you will find the reset flags in the CPU register r2 when your program starts. These flags tell you whether you come from a cold boot or a warm reset.

The program below is an example that implements strategy 2. It prints the millis value on the serial port roughly every second. On reset, it prints “-- starting --” and continues from where it left.

```
// If this is in RAM at startup, we come from a warm reset.
volatile const unsigned long magic = 0x12345678;

// This is where Arduino core keeps the millis() value.
extern volatile unsigned long timer0_millis;

// Here we will save a copy of timer0_millis.
unsigned long __attribute__((section(".noinit"))) savedMillis;

// Save the millis value at startup.
void __attribute__((section(".init3"),naked)) saveMillis()
{
    if (magic == 0x12345678)  // very likely a reset
        savedMillis = timer0_millis;
    else                      // cold boot
        savedMillis = 0;
}

void setup()
{
    // DO THIS FIRST: Restore the saved value of millis.
    noInterrupts();
    timer0_millis = savedMillis;
    interrupts();

    // Other initializations can be done now.
    Serial.begin(9600);
    Serial.println("-- starting --");
}

void loop()
{
    Serial.println(millis());
    delay(1000);
}

```
> 2 votes

# Answer
**Summary:**

You have an incorrect variable type assignment for previousMillis ('long' instead of 'unsigned long') resulting in illegal mixing of types in a subtraction.

It is not certain that this is causing your problems but, if not, it will cause problems at some stage if millis() is never reset - if only when millis() passes its halfway point.

It is not possible to prove with certainty that the mixing of types is not causing a problem without examining the compiled code as the action is 'illegal' and so no assurance is possible.
(We **hope** that the compiler writer 'got it right' :-) ).

---

**Details:**

Where you now use

> long previousMillis = 0;

You should use

> unsigned long previousMillis = 0;

Both 'long' and 'unsigned long' are 32 bit data types but long is signed and effectively "wraps around" at half value.

Apart from having funny things happen after about 25 days, if you mix data types in a calculation as you do in

> RealTime = currentMillis - previousMillis;
> where

* RealTime = unsigned long
* currentMillis = unsigned long , but
* previousMillis = long

then there is no certainty as to what the code will do when subtracting a long' from an 'unsigned long'.

We know what we would like it to do, and we hope that the compiler writer made the same assumptions as we do, but there is no guarantee.

Interestingly, while it does no harm for RealTime to be of type 'unsigned long', this is usually not essential, as we know that

> up to about 25 days the result will fit in the lower 31 bits of a 'long' and
> up to 65.535 seconds the result will fit in the 16 bits of an unsigned int and
> up to 32.767 seconds the result will fit in the lower 15 bits of an int.

So, if your period between millis() tests is guaranteed to fit in the above ranges then the lower range variables may be used.

While the mixing of types in the actual subtraction produces a technically undefined result, the use of a different type for the result than is used in the calculation is acceptable as the calculation result is well defined as long as the subtraction is performed correctly.

---

millis() wrap-around - **NOT** a problem:

People have expressed concern about incorrect results when millis() overflows after about 50 days, but this need not be a concern if correct data typing is used. When two variables or 'counters' (in this case eg millis() and previousMillis), both of type 'unsigned long' are subtracted or compared, the result is arithmetically valid, even if the "upper" variable ( millis() ) has reached the top of its range and 'wrapped around'. This result is true for any two unsigned integer counters which are both of the same length.
ie the result of eg

> delay = millis() - previousMillis

will ALWAYS be valid if millis() and previousMillis are both 'unsigned long's.
This result is not intuitively obvious to most people and there are many "solutions" to this "problem" on web which seek to correct a problem that does not exist. If you are interested in making use of this fact in other situations it is worth taking pencil and paper (or your favoured equivalent) and using eg 3 or 4 bit variables, working through how this works and why. What happens is that the overflowing / wrapping around higher counter (millis() in this case) "looks like" a longer unsigned variable with additional bits above its MSb. When the subtraction is carried out an MSb "bowwow" may occur - this is being "borrowed" from data bits that do not exist but this matters not when only the lower N bits (32 in this case) are of importance.

---

Variable (including the state of millis() ) can be saved in EEROM memory prior to a reboot. IF the data has to be validly written when a power outage occurs the system must detect the outage and continue to run long enough to validly write to EEROM. This requires proper design of power supply holdup time - without which EEROM corruption may occur due to power loss while writing to memory. As well as internal EEROM, it is possible to use low cost I^2C EEROM memory if non volatile storage requirements exceed uC EEROM capacity.

---

More detail on any of the above available if required.
> 1 votes

# Answer
1. You could be running out of memory. Posting your code would be helpful.

2. Not without some external memory such as an SD card.

2. As David points out in the comments the Arduino does have EEPROM memory (512bytes or 1024bytes depending on which version you have). See here for the library: http://www.arduino.cc/en/Reference/EEPROM
> 0 votes

---
Tags: lcd, time, millis, rtc
---


# Question
Title: afmotor saying "servo does not name a type"
I have made a sumobot with an arduino, an afmotor shield and a 4-pin ping sensor when I upload my code it keeps giving me this error: "'Servo' does not name a type" here is my code.

```
#include <AFMotor.h>
#include <NewPing.h>
#include <Servo.h>

#define TRIGGER_PIN  A0  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     A2  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

 //speed variables for the left and right motor
int Lspeed = 180;
int Rspeed = 255;

//declaring the left and right motors and attaching them to
//their corresponding connector on the motor shield
Servo leftMotor;
Servo rightMotor;

void setup() {
  Serial.begin(115200);
  //sets initial speed
  leftMotor.setSpeed(Lspeed);
  rightMotor.setSpeed(Rspeed);
}

void loop() {
  unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
  unsigned int CM = uS / US_ROUNDTRIP_CM;

  if (CM < 15 && CM > 0) {
    int iteration = 0;
    while( iteration == 0){
      leftMotor.run(FORWARD);
      rightMotor.run(BACKWARD);
      iteration = 1;
    }
    delay(600);
  }

  //starts motors going forward
  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);

  Serial.print("Ping: ");
  Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
}

```

# Answer
You are creating `Servo` objects instead of `AF_DCMotor` objects. Change this:

```
Servo leftMotor;
Servo rightMotor;

```

to this:

```
AF_DCMotor leftMotor(1);   // Change these numbers to the correct motor numbers
AF_DCMotor rightMotor(2);  // you are using on the shield

```
> 1 votes

---
Tags: servo
---


# Question
Title: Irrecvdemo program in or remote library gives fatal error #include<WProgram.h>
Whenever I compile irrecvdemo of or remote library it gives error saying that fatal error saying

> no file or directory exists `#include <WProgram.h>`

```
#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
}

```

# Answer
> 2 votes
You are using a very old library on a modern IDE. The file that was called `WProgram.h` in IDE version 0023 and below is now called `Arduino.h`. You will need to change any references to `WProgram.h` to `Arduino.h` instead.

Well written libraries do this with a #ifdef block:

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

```

---
Tags: arduino-uno, arduino-ide, remote-control
---


title: Arduino radio communications

text:
# Question
Title: Arduino radio communications
I have an Arduino and I am building a space satellite, just for fun. I'm not going to launch it obviously.

I have built all the sensors and everything works. I was looking into communication because if a satellite is in space it needs to send down the data.

Is it possible to have radio communication between two Arduino or an Arduino and something else that are 100km apart, it doesn't need to particle, I'm just wondering if it is possible and how it works. Is it possible without going out to buy shields?

# Answer
> 4 votes
There are three basic factors that control long distance communication:

1. Transmitter Power
2. Receiver Sensitivity
3. Signal Directionality

The more transmission power you have the "louder" your signal is at the receiver.

The more sensitive your receiver the "quieter" the signals it can pick up.

The more directional (focussed) your signal is the more arrives at the receiver and the less gets sent off elsewhere.

So you would think get all three of those and you're laughing, but it's not that simple:

* High power transmission requires high-power power source
* Good focus requires heavy and bulky antennae.

Neither of those are very good on a satellite, since you want it to be as small and light as possible and use as little power as possible.

So in general you have a medium to low power transmitter on the satellite with *reasonable* directionality, and put all the bulk on earth. That is why satellite dishes are so big. They give good focus, and the large size captures a lot of the signal making them more sensitive. You can also use very precise electronics to amplify the signal more.

There is, of course, nothing like that in a shield format, so you would have to create your own. The transmitter isn't so hard, since you don't want to have anything too meaty - the hard part comes when you want to make the base station. If you can afford enough power to transmit a strong enough signal and have it with enough directionality you can use a satellite TV dish (not a little Sky dish, one of the bigger solid round ones - Sky satellites actually have quite powerful transmitters and the massive solar panels to go with it; not really practical for a small home-built satellite). Getting the receiver and LNB (Low Noise Booster) tuned properly as well is vital - unless you're transmitting at the same frequency as the satellite the dish is intended to receive (which you mustn't or there'll be a lot of annoyed people around - there are specific frequency ranges you are allowed to use) then you will need to ensure the antenna is exactly the right length and that the LNB amplifies and filters the right frequency range.

Once you have got over all those hurdles the receiver is just a simple receiver.

The actual transmitter and receiver circuits themselves can be something fairly off-the-shelf (the lower the frequency the better since that goes further than higher frequencies) - it's what goes between - the antenna and amplifier - that makes it much more special and long range.

# Answer
> 1 votes
Majenko covered several aspects of radio communications between a satellite and a ground station. An additional factor to consider is that the azimuth or altitude of a low-altitude satellite changes rapidly as it passes over a ground station. For example, a satellite 100 km up takes about 86 minutes per orbit and travels at about 7.84 Km/s, and probably would be in view for less than a minute per pass. \[See eg *Orbit of a satellite Calculator* at casio.com.\] Unless a phased array is used, and assuming communication is highly directional, the big dish on the ground will need to swing at up to 4.5° per second (about 270° per minute) as it tracks the satellite passing over. The much smaller antenna on the spacecraft should rotate at the same rate, the opposite direction.

Note, an alternative to radio communications is a tight-beam laser system. Rather than using big, bulky microwave or UHF antennas to achieve directionality, you would use a small telescope (a few cm of aperture) on the satellite and a larger telescope (as much aperture as you can afford) at the ground station. Infrared or visible light lasers at each end of the link would be modulated to transmit at a high data rate. Accurate tracking and aiming might end up being important research projects for this approach.

---
Tags: arduino-uno, communication
---


# Question
Title: Converting TinkerKit to native Arduino pins
Over the years, I have acquired many TinkerKit modules for my Arduino Uno. My only issue is that I need to find a way to code using the native syntax, and not the less-powerful TinkerKit variation. To do this, I need to know if TinkerKit maps its 3-pin connector to the Arduino Board's pins (ex: 1, 3, 5). If it does, what are the mappings?

Thanks in advance!

# Answer
The TinkerKit Sensor Shield helps understand the mapping. There is also the TinkerKit Header File with symbol mapping.
> 1 votes

---
Tags: pins, port-mapping
---


title: Precision voltmeter using Arduino

text:
# Question
Title: Precision voltmeter using Arduino
I am newbie, I need to measure precise voltage in range 0.00-0.80V, two digits precision.

The voltage will not be greater than 1V-1.2V.

I wonder if I need divider or not, I am sure that voltage won't rise above 1.2V.

Can I connect the point to measure directly to analog input, or I still need to use divider? Please explain why.

# Answer
> 7 votes
A divider is used to (as the name suggests) reduce a higher voltage to a lower voltage. Using a divider on a small voltage will only make it smaller and harder to measure.

To get the most out of your measuring you need to have the *reference* voltage as close to the highest voltage you want to measure as possible. The highest voltage that can be applied is not dependent on the reference voltage, but the supply voltage, and as 1.2V is way less than 5V (or 3.3V on a 3.3V board) you have no worries there.

So you need to change the reference voltage - the voltage that the ADC uses as its upper *measurement* voltage. That's simple enough, since many of the Arduino boards include an internal 1.1V analog reference voltage generator that you can switch to (see: analogReference())

So when you have switched to the 1.1V analog reference the ADC is capable of measuring 0-1.1V in 1024 steps. That's 1.1/1023=0.00107V per bit of precision.

The formula is:

```
V = ADC / 1023 * Vref

```

So a reading of 1 would give you 0.00107V - a reading of 2 would be 0.00215V, etc. That's plenty of resolution to meet your 2 decimal places requirement.

***One thing to note*** though is that the internal 1.1V reference isn't that stable or accurate (or not even there on some chips). If you need better stability and accuracy then it could pay to use an external voltage reference chip. These are like a linear voltage regulator but are far more accurate and stable (and can't provide lots of current). Pick one that is greater than your upper measurement voltage but as close to it as you can get (so just above 0.8V) and feed the output into the external *ARef* pin and switch the analog reference to the `EXTERNAL` mode.

You *could* use a voltage divider on the external ARef pin to provide a low reference voltage, but the stability and accuracy will be no better (and probably worse) than the internal 1.1V voltage reference, so there really is no point.

---
Tags: arduino-uno, arduino-nano, analogread, voltage-level
---


title: How to latch a 200mS LOW pulse?

text:
# Question
Title: How to latch a 200mS LOW pulse?
Trying to latch a 200 mS, LOW event to log the event. LOW only occurs when external Watchdog timer sends reset pulse to the Arduino.

Is a D Latch suitable for this application? It has been years since my digital class; help most appreciated.

How would you proceed?

# Answer
> 1 votes
I understand your question to be : you want to latch (and indicate) whenever an external watchdog timer has reset your Arduino.

D type flip flop (latch) can be used. You would use the clock input as the trigger. However, most D types clock on a rising edge. You could use an inverter on the input to the clock to get the D type to clock on a falling edge. You would also connect the D (Data) input high (logic 1). Then when your input (event) goes low, the Q output will latch high. The 200 mS is irrelevant because the latch ocurrs at the change from high to low (low to high on clock input).

You would also need a means of resetting the latch, which many D types have a reset input or a clear input.

You could also use a more simple SR latch (set reset latch) using 2 Nand gates. SR latch changes state when the “set” input goes low (providing that R input was high). Make the R input go low to reset the latch.

POSSIBLE ALTERNATIVE : If you have some means of operator intervention (or even a switch). You could have your program light an LED at startup. Operator (person) could reset LED. Then afterwards, any reset (restart of program) would light the LED.

---
Tags: hardware
---


title: Detecting Motion behind a robot

text:
# Question
Title: Detecting Motion behind a robot
I am building a motion following robot. It has two PIR sensors on the left and right. It has an ultrasonic sensor in the front. When either of the PIR sensors detect motion then it turns to that side.
When both the PIR sensors sense motion then I calculate the distance first( with the ultrasonic sensor, if distance \<= 50 cm and \> 5 cm then the robot moves forward. But it could mean that the motion is either in the front or in the back. Thus, my robot moves forward even the motion is behind it.
I need some help devising a method so that when motion is detected behind then the robot will turn back. I tried making the robot turn right when both the sensors detect motion, then it will turn towards the left(i.e. front) or right(i.e. back). But in reality this method is not so practical as it would to a lot of confusion when the intruder we are trying to detect is still in motion. Plz help. A sample sketch would help.

# Answer
This is a basic problem of only having two sensors. There is no way that two sensors of this simple type (some motion yes/no) can be used to work out where the motion comes from except when there is a difference between the two sensors. Anything else is, and always will be, ambiguous.

If you think of it as a circle divided in two, you have only three possible conditions:

That is, *left*, *right* or *somewhere*. Not ideal.

So you need more data to be able to make a decision. That means more sensors. The ideal scenario is four sensors - left, right, front and rear. That gives you many possible scenarios, including:

As you can see from that you have a full 360° idea of where the motion is. You can even know how far to the left it is by if the front or rear is also on. For instance, using sailing terminology, those 8 circles would mean (in order):

1. Motion on the left beam
2. Motion on the port bow
3. Motion dead ahead
4. Motion on the starboard bow
5. Motion on the starboard beam
6. Motion on the starboard quarter
7. Motion dead astern
8. Motion on the port quarter

Also the dead-ahead and dead-astern could be indicated by just the forward or rear sensor on and the left/right sensors both off. You could even use that fact to give some indication of the distance of the motion depending on the angular coverage of the different sensors.
> 1 votes

---
Tags: sensors, sketch, project
---


# Question
Title: Using Bluetooth module HC-05 when Arduino is powered using a battery
I have a project that involves sending messages from an Android device to an Arduino using a bluetooth module. I am using an HC-05 bluetooth module and an Arduino Mega 2560.

It works as long as I power the Arduino to my laptop using a USB cable. However, I need to use an external power source and have been using a 6F22 9V battery connected through the VIN pin for this purpose, without facing any problems. But on connecting the HC-05, it does not even light up.

The Arduino is also connected to four dc motors, five servo motors (all of which are externally powered, only get digital signals from the Arduino), and seven HC-SR04 ultrasound sensors, whcih are powered through the 5V pin.

I have connected the HC-05 to the Arduino as follows:

HC-05 Arduino

VCC 3.3V

GND GND

TX RX

RX TX through a voltage divider

I am new to all this, and would be grateful for any help. Thank you.

# Answer
6F22 (PP3) batteries are among the wimpiest of batteries available. They are not a good choice for anything except extreme low power applications, and anything involving radio transmitters is definitely not an extreme low power application.

Use a better battery. I would recommend 6 AA batteries (you can get 6xAA battery holders with the same connector as a PP3 battery) which will give you considerably more power than a little PP3.

Either that or a 7.2V "2S" Li-Ion battery pack.
> 2 votes

---
Tags: arduino-mega, bluetooth, battery, hc-05
---