# Question
Title: Altering SoftwareSerial to transmit more than 1 byte at a time
I am trying to create a stable communication channel without any mis-synchronization. In the SoftwareSerial library, the write function transmits one byte at a time. The mis-synchronization occurs when the receiver misjudges which bit is the start bit. Why is this a problem? Because the internal delay between the start bit and the first message bit is different from the internal delay between each message bit.

One of the really good suggestions I have heard is to use Manchester encoding on the Arduino. While I am testing out this option, I also wanted advice on altering the software serial library in the following way. If I modify the write function to transmit 128 bytes instead of 1, then this can avoid the problem I explained above, I *assume.*

Here is how I have altered the write function of SoftwareSerial. I haven't thought of any issues with this approach, but does anyone else see any problems? Here is the whole altered function. (I changed the parameter, and added 2 new loops - one to invert all the bytes if(inv) and another loop outside the loop that transmits each bit of a byte. I have attached the original function, further below.

```
size_t SoftwareSerial::write(byte* b)
{
  if (_tx_delay == 0) {
    setWriteError();
    return 0;
  }

// By declaring these as local variables, the compiler will put them
// in registers _before_ disabling interrupts and entering the
// critical timing sections below, which makes it a lot easier to
// verify the cycle timings
volatile uint8_t *reg = _transmitPortRegister;
uint8_t reg_mask = _transmitBitMask;
uint8_t inv_mask = ~_transmitBitMask;
uint8_t oldSREG = SREG;
bool inv = _inverse_logic;
uint16_t delay = _tx_delay;

//Doubtful of this loop ------------------
for(int i = 0; i < 128; i++)
{
  if (inv)
    b[i] = ~(b[i]);
}

cli();  // turn off interrupts for a clean txmit

// Write the start bit
if (inv)
  *reg |= reg_mask;
else
  *reg &= inv_mask;

tunedDelay(delay);
for(int j = 0; j < 128; j++)
{
  // Write each of the 8 bits
  for (long i = 8; i > 0; --i)
  {
    if (b[j] & 1) // choose bit
      *reg |= reg_mask; // send 1
    else
      *reg &= inv_mask; // send 0

    tunedDelay(delay);
    b[j] >>= 1;
  }
}
// restore pin to natural state
if (inv)
  *reg &= inv_mask;
else
  *reg |= reg_mask;

SREG = oldSREG; // turn interrupts back on
tunedDelay(_tx_delay);

return 1;
}

```

Here is the original function.

```
size_t SoftwareSerial::write(uint8_t b)
{
if (_tx_delay == 0) {
  setWriteError();
  return 0;
}

// By declaring these as local variables, the compiler will put them
// in registers _before_ disabling interrupts and entering the
// critical timing sections below, which makes it a lot easier to
// verify the cycle timings
volatile uint8_t *reg = _transmitPortRegister;
uint8_t reg_mask = _transmitBitMask;
uint8_t inv_mask = ~_transmitBitMask;
uint8_t oldSREG = SREG;
bool inv = _inverse_logic;
uint16_t delay = _tx_delay;

if (inv)
  b = ~b;

cli();  // turn off interrupts for a clean txmit

// Write the start bit
if (inv)
  *reg |= reg_mask;
else
  *reg &= inv_mask;

tunedDelay(delay);

// Write each of the 8 bits
for (uint8_t i = 8; i > 0; --i)
{
  if (b & 1) // choose bit
    *reg |= reg_mask; // send 1
  else
    *reg &= inv_mask; // send 0

  tunedDelay(delay);
  b >>= 1;
}

// restore pin to natural state
if (inv)
  *reg &= inv_mask;
else
  *reg |= reg_mask;

SREG = oldSREG; // turn interrupts back on
tunedDelay(_tx_delay);

return 1;
}

```

The serial buffer can only hold 64 bytes at a time, but I am using the following code, courtesy of Nick Gammon to read the data from serial buffer without blocking. So it shouldn't be a problem on the receiving end either, I hope.

# Answer
> 0 votes
Basically your code has changed the size of the RS-232 packet from 10 bits to 1026 bits. There is nothing "wrong" with that, but it doesn't really solve the problem of a missed start bit - if anything it makes it worse since instead of losing 8 bits you lose 1024 bits.

Synchronisation is best done separately to the transmission of packets, and for that you need your packet to be nice and short.

A packet consists of 10 bits - the first is a LOW and the last is a HIGH; everything else in between is data. The trick is to provide a forced idle period before sending of *at least* the amount of time it takes to transfer one packet. That way if the receiver is mistakenly in a receive loop for whatever reason the 10 (or more) bits worth of HIGH will effectively cause the receiver to finish whatever it is doing and get ready to receive your real byte.

If you have a hugely long packet (1024 + 2 bits) flushing the receiver before transmitting will take a very long time - rather than just one byte's worth of time it will be your entire packet's transmit time.

On top of that you then have the problem of byte order and data integrity checking. Just sending two bytes (or 128 bytes) is not reliable. You need to wrap those bytes in a protocol including a start-of-packet indicator (0x55 0xAA is common, as is the special ASCII character 0x01: SOH), packet or payload length, and checksums. Options for things like sequence numbers, acknowledgements, packet retransmission, etc can also be built in to increase the reliability of the protocol.

Rather than trying to reinvent the wheel by changing the underlying data layer transmission you should learn the OSI 7 layer model and implement your protocol at a higher level than the data layer.

# Answer
> 1 votes
So far you have asked a *lot* of questions about your project which uses SoftwareSerial to send a lot of bits:

And now we have another one (this question).

I think you are flogging a dead horse with this. For one thing, what are you trying to achieve, that can't be achieved by just sending the bytes "normally" as 8-bit bytes? The only thing I can think of is a slight speed increase. By trying to make a 1024-bit packet, you are saving some start and stop bits in the middle, that's all.

In some of your other questions you mention 9600 baud, so let's run with that. At 9600 baud one bit is 1/9600 of a second, that is 104.17 µs.

To transmit 1024 bits "normally" you would need 128 bytes, each of which needs a start and stop bit, so the total is `128 * 10 * 104.17 µs = 133.338 ms.`

To use your system you need 1024 bits plus one start and stop bit, so that is `1026 * 104.17 µs = 106.878 ms.`

So far you have only saved 26.46 ms.

You could save a lot more by simply doubling the baud rate. Or quadrupling it. However SoftwareSerial is less reliable at higher baud rates. Why not use HardwareSerial?

Your next problem is that SoftwareSerial turns interrupts off during reception of one byte, so that it gets the timing right. For an 8-bit byte this means they are off for `10 * 104.17 µs = 1.0417 ms`. That's about the limit for turning interrupts off if you want the internal timer to work, the one which gives you `millis` and `micros`. If you turn them off for 128 times as long, you can say "goodbye" to knowing how much time has elapsed.

As I mentioned in a comment, too, since serial comms relies on external clocks (that is, both ends have to get the clocking right) you can only afford around a ±2% error in the receiving clock to ensure that we are sampling at the correct place (see the datasheet) for an *8-bit byte*. The error tolerance will drop to 1/128th of that if you try to send 128 bytes in a single stream. The crystal/resonator in the Arduino just won't be that good.

Finally, to avoid false detection of the start bit (which you have asked about elsewhere) you need a much longer gap between packets, to ensure that we get the correct start bit. Effectively you need a one-byte length (ie. the incoming data is continually HIGH) for 8-bit bytes. For 1024-bit packets you will need to introduce a gap of `1024 * 104.17 µs = 106.670 ms` between packets. This required gap totally wipes out any saving by not sending those extra start and stop bits.

---
Tags: c++, softwareserial, wireless, coding-standards
---


title: Diagnosing crashed Arduino Uno

text:
# Question
Title: Diagnosing crashed Arduino Uno
I have an Arduino Uno connected to a motor controller over I2C. The Arduino accepts commands from a Raspberry Pi via the USB serial line.

I'm trying to diagnose a problem where the Arduino will become completely unresponsive. It's programmed to respond to a "ping" request every N seconds, and for some reason I can't identify, it seems to crash and no longer respond to any commands. However, the motor controller continues powering the motors.

Everything is powered from a 12V Li-Po battery, but everything is located behind 5V regulators. When this problem happens, the battery is fully charged and the motors aren't sourcing much current, and neither the motor controller or Raspberry Pi are effected, so I've ruled out a brownout.

My theory is there's some subtle programming error in my Arduino code that's causing an "exception", but I don't know how to identify it. I've tried adding special code to allow me to trigger one of these, by indexing an array outside of its limits or calling a null function pointer, but the Arduino stubbornly refuses to crash when I try to explicitly make it.

How do I diagnose an Arduino becoming unresponsive?

# Answer
> 2 votes
Assuming you don't have access to a debugger, the most common way is to add debug logging. The ususal algorithm to solve those problems is more or less like this:

```
do {
    add_logs_in_suspicious_places();
    wait_until_it_crashes();
    analyze_logs();
} while( ! i_know_why_it_crashes() );

```

If you cannot add any debug logging because of a flawed system design (lack of I/O, etc) you've commited a captial engineering crime and this is your punishment. :)

# Answer
> 1 votes
There is an excellent post by Nick Gammon that covers a wide array of possible problems. Look into this, as might be useful.

# Answer
> 1 votes
If you have spare pins, add debugging LEDs. For example, toggle one at the start of `loop`, another at the start of another function, and so on. When the Arduino "crashes" the state of the LEDs should provide a hint as to where in the code it is.

> but the Arduino stubbornly refuses to crash when I try to explicitly make it.

Typically you are indexing outside an array or using uninitialized memory. Your debugging code has moved the problem around enough to stop it happening (or appearing to happen).

If you amend your question and post your code we might spot something.

---
Tags: arduino-uno, raspberrypi
---


title: Power problems stacked Arduino shields

text:
# Question
Title: Power problems stacked Arduino shields
I have a weird problem. I am currently building a BB-8. Therefore, I am using an Arduino Uno. On top, I have stacked an Adafruit Motor Shield v2.3 and, again, on top of this, I have stacked the Sparkfun USB Host Shield. The Arduino is powered by a 9V-Block battery, the motors are powered separately by two 18650 Li-Ion batteries. To control the two Pololu motors, which have a stall current of 1.6 amps each, I use a Xbox 360 wireless controller, where the receiver is connected to the USB Host Shield.

Now to my problem. Every seems to work fine, until i cover everything with a styrofoam hemisphere. Yes, you've read right. If that happens, the controller signals is lost and does not connect again, unless I restart the Arduino. I have uploaded a small video on youtube, where you can see the problem.

I guess, this is a power problem, since this issue does not occur, when I connect the Xbox receiver to my Mac. Has anyone an idea, how to solve this problem?

I already tried another power source. And the USB host shield should give enough power, since the specs are saying, that 500 mA is no problem, and hit is exactly the USB 2.0 spec. The combination of the shield shouldn't be a problem, too. I carefully chose this shields, because the motor shield is just using the pins A4 and A5, the USB host shield is using some of the digital pins, so I think there is no interference.

Thank you for your help.

**EDIT** I have tested it a bit more now and i think i can reduce the probable reasons. First, i tried some other power supplies, from AA batteries on the VIN pin to external power adaptors. Next, i tried other xbox receivers and controllers. I also tried a playstation 3 controller with a Bluetooth dongle. Nothing solved the problem. I also covered the Arduino with other things than styrofoam, like a garbage can, cardboard and some metal box. This worked, so the problem was only with styrofoam. Now i haven't covered the Arduino, but i slowly got closer. About 20 cm from the Arduino, it stopped working. My clue: static electricity. Do you think this can be a problem? And if yes, how can i solve this?

# Answer
So, I solved the problem. As is mentioned in my question, the problem was static electricity. I primed the styrofoam sphere with some special primer to make the styrofoam a little more stable and so on. That's it. Luckily I didn't touch the Arduino with the sphere. I think it would have damaged the Arduino.
> 1 votes

# Answer
Those 9v batteries are not known for their ability to supply current. Their best uses are long-term powering of low-current standby devices like smoke detectors. I'd first try replacing it with 4 double- or triple-A cells, whatever you can scrounge up for a quick test. My guess is when you cover the robot the Xbox receiver's current demand increases just enough to crash or reset something. A-cells may supply enough more current without the voltage sagging.
> 1 votes

---
Tags: arduino-uno, power
---


title: How can I reduce the size of my sketch?

text:
# Question
Title: How can I reduce the size of my sketch?
Looks like I'm overshooting the storage of my Adafruit Trinket:

```
Sketch uses 5,600 bytes (105%) of program storage space. Maximum is 5,310 bytes.
Global variables use 109 bytes of dynamic memory.

```

Any tips for reducing the footprint of my code?

```
#include <Adafruit_NeoPixel.h>
#include <Wire.h>
#include <RTClib.h>

#define LEDPIN 1
#define TONE 4
#define BTNPIN 3

RTC_DS1307 rtc;
Adafruit_NeoPixel strip = Adafruit_NeoPixel(4, LEDPIN, NEO_RGB);

long fadeTime = 1 * 10000L; // X minutes
int colorStops = 256;
int delaySpeed = fadeTime / colorStops;
int notes[] = {262,294,330,349};
int timeHour = 14;
int timeMinute = 43;
uint32_t alarmLength = 5 * 60000L; // 5 minutes

void setup() {
  rtc.begin();
  if(!rtc.isrunning()) {
    rtc.adjust(DateTime(__DATE__, __TIME__));
  }

  pinMode(TONE,OUTPUT);
  pinMode(BTNPIN, INPUT);
  digitalWrite(BTNPIN, HIGH);

  strip.begin();
  strip.show();
}

void loop() {
  DateTime now = rtc.now();

  if (now.hour() == timeHour && now.minute() == timeMinute && now.second() == 0){
    // Fade in light
    for(int i = 1; i<colorStops; i++){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
        strip.setPixelColor(np, strip.Color(i,i,0));
      }
      strip.show();
      delay(delaySpeed);
    }

    // Play tone after light fully bright
    for( uint32_t tStart = millis();  (millis()-tStart) < alarmLength; ){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
        strip.setPixelColor(np, strip.Color(random(100,255),random(100,255),random(100,255)));
      }
      strip.show();

      beep(TONE, notes[random(0,3)], 50);
      delay(100);
    }

    for(int np = 0;np<strip.numPixels(); np++){
      strip.setPixelColor(np, strip.Color(0,0,0));
    }
    strip.show();
  }
}

void beep (unsigned char speakerPin, int frequencyInHertz, long timeInMilliseconds)
{   // http://web.media.mit.edu/~leah/LilyPad/07_sound_code.html
  int x;
  long delayAmount = (long)(1000000/frequencyInHertz);
  long loopTime = (long)((timeInMilliseconds*1000)/(delayAmount*2));
  for (x=0;x<loopTime;x++)
  {
    digitalWrite(speakerPin,HIGH);
    delayMicroseconds(delayAmount);
    digitalWrite(speakerPin,LOW);
    delayMicroseconds(delayAmount);
  }
}

bool kill() {
  if (! digitalRead(BTNPIN)) {
    for(int np = 0;np<strip.numPixels(); np++){
      strip.setPixelColor(np, strip.Color(0,0,0));
    }
    strip.show();
    return true;
  }
  else {
    return false;
  }
}

```

# Answer
> 4 votes
The AdaFruit Trinket just doesn't have a lot of memory - 8kb, of which 3kb is used by the bootloader.

The order I look for things to reduce the footprint of an Arduino program are:

* data (e.g. large strings)
* libraries
* your code (especially doing the same things several times, which might be combined into loops or functions).

In this case, you don't have much data. Most of your resulting program size is in the libraries you use.

It seems like you use the clock solely to detect the year - that seems like a lot of overhead just to figure out what year it is. It then does nothing for subsequent years (or prior years), if I read your code correctly. Maybe you would consider dropping this code? Then you can skip the entire RTC library. At least try it to see how much you save. I suspect that the RTC library will use another library to do the underlying work.

You use the \<Wire.h\> library, but don't reference it in your code. It should be optimized out (unless used elsewhere), but there's no reason to have it there.

You may also save a little space by replacing initialized variables which don't change to constants. Storing `25` in a variable takes 1 byte, plus 2 bytes every time you reference it; `25` in a constant gets optimized away, and will take up 1 byte every time you reference it.

As mentioned in the comments, you can also save a few bytes by specifying the size of your int's, especially initialized ones.

Another option would be to use a larger chip - the AtMega328p used in (for example) the Arduino has 32kb of flash - 6 times the (available) size.

You can also save some bytes by removing the clause  `if(!rtc.isrunning()) {`, once you have set it up once.

**Additional**: I have had some success reducing footprints by reimplementing a subset of a library. Usually, libraries are very well implemented, but if your needs are substantially different/simpler than what the library was designed for, or you are willing to forgo parts of it (e.g. error checking), then SOMETIMES this can help. WARNING! There is a HIGH price to pay (coding, debugging, loss of error checking, undetected bugs etc), and it may *not* save you anything in the end.

You can also (sometimes) move data (e.g. large strings) to eeprom. The Trinket has 512 bytes of eeprom. You may need one sketch to load the data into eeprom, to run before loading your main sketch. eeprom has it's own overhead, so may not be worthwhile for 512 bytes, it is slower (which probably won't matter for this), and you have a limited number of writes.

Another few bytes may be saved by doing all the maths for the tone frequency/time beforehand, and sacrificing something. For example, you beep for 50ms. If, instead of passing the frequency (between 262 and 349 hertz) and instead pre-calculate the delayAmount (for 262 hz, this would be 1,000,000/262 = 3817ms); your looptime for this is ((timeInMilliseconds*1000)/(delayAmount*2)) = (50*1000)/(3817*2) = 6.55 cycles. 7 cycles is probably "close enough" for all the tones you want to produce. So you can hardcode 7 cycles (using a constant of 7 for looptime), and get rid of that formula to calculate looptime.

In a similar way, if you don't care too much about the exact frequency (which varies between 3817ms and 2865ms depending on your random number), you might specify the delayamount as 2865+random(0,3)\*238 (make sure you store at least the random number, you don't want it to change during the loop!).

You now have:

```
#define random_beep_length 7
void random_beep (unsigned char speakerPin)
{   // http://web.media.mit.edu/~leah/LilyPad/07_sound_code.html
    // Heavily modified!
  int x;
  unsigned char pitch = 2865+random(0,3)*238;
  for (x=0;x<random_beep_length;x++)
  {
    digitalWrite(speakerPin,HIGH);
    delayMicroseconds(delayAmount);
    digitalWrite(speakerPin,LOW);
    delayMicroseconds(delayAmount);
  }
}

```

# Answer
> 3 votes
An option not already mentioned, but may be worth mentioning, would be to remove the bootloader and program the chip directly with a hardware programmer (or another Arduino). That will increase the available sketch memory from 5kiB to the full 8kiB on the chip.

# Answer
> 3 votes
As already mentioned by AMADANON Inc. in his answer, you should qualify as `const` all the constant variables at the beginning of the program. This is probably the biggest space saver.

You can gain something like 100 bytes by using direct port access instead of pinMode/digitalRead/digitalWrite. In the case of the ATtiny85, you only have port B, and the Arduino pin numbers are the same as the Atmel bit numbers. So you would for example use `PINB & _BV(BTNPIN)` instead of `digitalRead(BTNPIN)`.

There are a few optimization opportunities in `beep()`:

* pass only one parameter, as `speakerPin` and `timeInMilliseconds` are constants in your program
* have this parameter be `delayAmount` instead of `frequencyInHertz`, and store these delays, instead of the frequencies, in the `notes[]` constant array
* do not compute the number of iterations (the misnamed `loopTime`) beforehand, instead compute the elapsed time and loop until you reach the required time

Here is my version of `beep()` with these optimizations:

```
void beep(int delayAmount)
{
  for (uint16_t t = 0; t < BEEP_TIME*1000/2; t += delayAmount)
  {
    PORTB |= _BV(TONE);  // digitalWrite(TONE,HIGH);
    delayMicroseconds(delayAmount);
    PORTB &= ~_BV(TONE);  // digitalWrite(TONE,LOW);
    delayMicroseconds(delayAmount);
  }
}

```

Notice that the loop variable is actually *half* the elapsed time. This saves a few bytes. Making the number of iterations constant, as proposed by AMADANON Inc., also saves a few bytes (6 bytes in my test).

You should also remove all the calls to `strip.Color()`: replace every instance of `strip.setPixelColor(np, strip.Color(r, g, b))` by `strip.setPixelColor(np, r, g, b)`.

With all these optimizations combined, I am quite confident you will gain more than the 290 bytes you need to fit your program in the Trinket.

---
Tags: adafruit, sketch-size
---


title: Wire.h not found newliquidcrystal

text:
# Question
Title: Wire.h not found newliquidcrystal
The arduino IDE can't seem to find the wire.h file when i'm using the new liquid crystal library. Does anyone know how to solve this? here is the code i'm using and the error message:

```
/*-----( Import needed libraries )-----*/
#include <Wire.h>  // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>

/*-----( Declare Constants )-----*/ /*-----( Declare objects )-----*/ // set the LCD address to 0x27 for a 16 chars 2 line display // A FEW use address 0x3F // Set the pins on the I2C chip used for LCD connections: //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

/*-----( Declare Variables )-----*/ //NONE

void setup()   /*----( SETUP: RUNS ONCE )----*/ {   Serial.begin(9600);  // Used to type in characters

  lcd.begin(16,2);   // initialize the lcd for 16 chars 2 lines, turn on backlight

// ------- Quick 3 blinks of backlight  -------------   for(int i = 0; i< 3; i++)   {
    lcd.backlight();
    delay(250);
    lcd.noBacklight();
    delay(250);   }   lcd.backlight(); // finish with backlight on

//-------- Write characters on the display ------------------ // NOTE: Cursor Position: (CHAR, LINE) start at 0     lcd.setCursor(0,0); //Start at character 4 on line 0   lcd.print("Hello, world!");   delay(1000);   lcd.setCursor(0,1);   lcd.print("HI!YourDuino.com");   delay(8000);

// Wait and then tell user they can start the Serial Monitor and type in characters to // Display. (Set Serial Monitor option to "No Line Ending")   lcd.clear();   lcd.setCursor(0,0); //Start at character 0 on line 0   lcd.print("Use Serial Mon");   lcd.setCursor(0,1);   lcd.print("Type to display");

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/ {   {
    // when characters arrive over the serial port...
    if (Serial.available()) {
      // wait a bit for the entire message to arrive
      delay(100);
      // clear the screen
      lcd.clear();
      // read all the available characters
      while (Serial.available() > 0) {
        // display each character to the LCD
        lcd.write(Serial.read());
      }
    }   }

}/* --(end main loop )-- */

```

Here is the compiler output

> Arduino: 1.6.7 (Windows 10), Board: "Arduino Nano, ATmega328"
>
> C:\Users\martin\Documents\Arduino\libraries\LiquidCrystal\I2CIO.cpp:35:26: fatal error: ../Wire/Wire.h: No such file or directory
>
> #include \<../Wire/Wire.h\>
>
> ```
>                       ^
>
> ```
>
> compilation terminated.
>
> exit status 1 Error compiling.
>
> This report would have more information with "Show verbose output during compilation" enabled in File \> Preferences.

# Answer
The liquid crystal library has to be installed in the same folder as the wire library:

```
libraries/Wire/Wire.h (etc)
libraries/LiquidCrystal/LiquidCrystal_I2C.h (etc)

```

There is a hard-coded path in the liquid crystal library pointing to the wire library that is relative to where the liquid crystal library is, which is done to get around the problem that the Arduino library doesn't recurse libraries. It's not actually needed since including the Wire library in the IDE is enough to tell it where to find it for the liquid crystal library, so I don't really know why they did it that way.
> 2 votes

---
Tags: lcd
---


# Question
Title: Proximity sensor without proximity sensor; is my hand magic, my competency crap, or my arduino fried?
here is a very simple circuit, with a LED between pin 2 and ground, and a loose wire in pin 8.

Here is the sketch that was intended for use with a small 4-contact switch like these in every arduino starter kit :

```
int yellowCIn = 8;
int yellowCOut = 2;

void setup() {
  pinMode(yellowCIn, INPUT);
  pinMode(yellowCOut, OUTPUT);
}

void loop() {
  if (digitalRead(yellowCIn) == HIGH) {
  digitalWrite(yellowCOut, HIGH);
  }
  else {
    digitalWrite(yellowCOut, LOW);
  }
}

```

However, simply moving my hand near the loose white wire is enough to light the LED, moving it away to put it off. As I am writing this, with the arduino connected by usb, rather than on the blue battery visible in the picture, I notice moving my hands away from the keyboard lights the led, moving them close to the keyboard powers it off...

So back to my title : are my hands magic, my electronics competency crap (well, it is, for sure) enough that I never heard of such a tremendous static electricity effect (and never fried one of the many computers I built from parts), or does this board have dire problems?

Thanks for your attention :)

# Answer
Nothing's broken; you have discovered the nature of a floating pin. Unfortunately, that means that strange things happen...

A very small charge from your hand is triggering the logic because the state of the pin (high or low) is not set. To fix this, you need to add a pull-up or pull-down resistor (or activate the internal input-pullup resistor).

You can read about how to accomplish this here.
> 2 votes

# Answer
Try configuring your input pin as INPUT\_PULLUP instead. This connects an internal pullup resistor to stop the input value from drifting around.

I would only use the "INPUT" mode on its own if I have that pin wired to something on the board and the levels won't be erratic.

Your hands are magic - they pick up interference from various sources and the high impedance input of the chip pick this up...

(There's a bit more on the modes here: Arduino DigitalPins page)
> 1 votes

---
Tags: electricity
---


title: Print the response from GSM shield

text:
# Question
Title: Print the response from GSM shield
I have a GSM shield connected with my Intel Galileo board.

I intend to connect the board with serial communication at a baud rate of 115200 instead of the GSM library. I want to print the results of "at" commands in my serial window, how should I do it?

# Answer
I have only worked with the SIMCOM series of GSM modules like the SIM900 and the SIM808. Here is a sample of the kind of code you should be looking at using. It will send one "AT" to the GSM module and then it will spit out the result in the serial monitor.

```
void setup()
{
  Serial.begin(115200);
  int bytesSent = Serial.write(“AT\r\n”); //send "AT" and send the end of line characters to signify end of the command
 }

 void loop()
{
   if (Serial.available() > 0) {
            // read the incoming byte:
            incomingByte = Serial.read();
    }
}

```
> 0 votes

---
Tags: gsm, arduino-galileo
---


# Question
Title: Arduino fried? Onboard blink ok; offboard blink not ok
EDIT :

I have plenty of weird bugs. I will open another thread, and come back to this one when I have better understanding, rather than completely modify this one halway through. Sorry to every answerer for my electronic incompetence which led me to ask the wrong questions; I hope the other thread makes more sense.

I have recently exhumed an arduino from a cupboard, and can't seem to make even a blinking LED circuit work correctly.

Here's the sketch :

```
void setup() {
  pinMode(9, OUTPUT);
}

void loop() {
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(1000);
}

```

This has been tried without the circuit, on pin 13, using the onboard LED, and it worked.

However, using the following circuit, it did not result in a blinking LED, using several pins (8, 9, 12, 13) and LEDS.

May I assume the arduino is fried?

Here is a thumbnail of the circuit :

# Answer
> 0 votes
My arduino is not bricked, I just don't know how many things I don't understand about electronics, and make every single mistake I can make, especially while cabling.

# Answer
> 1 votes
Here's a guide posted by Nick Gammon for checking if your Arduino is bricked Is My Arduino Bricked ?

# Answer
> 0 votes
Try lighting up the LED without using any resistance in the middle, if that doesn't work try with a LED which consumes less current even if that doesn't work put the pin to HIGH state in code and measure the voltage of the given pin using a multimeter it should read above 3.3V. If neither of these work then you can be sure that your arduino is fried

# Answer
> 0 votes
It it possible the non-working LED got wired backward (it wouldn't be the first time!)? If the LED is clear enough, hold it up to the light and look inside the plastic bubble. There will be two bits of metal, one attached to each lead. One of them is significantly larger than the other; that's the cathode and it needs to be connected to the more negative side of the circuit. Here's a picture.

# Answer
> 0 votes
You haven't exactly got the LED connected to pin 9, as in the code, have you?

I find it hard to believe that you can upload new sketches, but none of the pins work. Try pins 0 or 1, in the sketch, for example. Or the whole lot:

```
void setup() {
  for (int i = 0; i < 20; i++)
    pinMode (i, OUTPUT);
}

void loop() {
  for (int i = 0; i < 20; i++)
  {
    digitalWrite(i, HIGH);
    delay(1000);
    digitalWrite(i, LOW);
    delay(1000);
  }
}

```

Now methodically test every pin.

---

> What happens if you plug the white jumper into 5V rather than the current digital pin 12

> The LED doesn't light.

Something's wrong with your testing. The processor cannot be powering up, and accepting new sketches, yet not have power to the +5V pin.

---
Tags: c++, pins, hardware
---


title: Using map for DC motor instead of servo

text:
# Question
Title: Using map for DC motor instead of servo
I am trying to use map command which is used to power servo 180 degrees as the potentiometer moves...

in fact what i want to do is just when i adjust my potentiometer to zero; stop the dc motor then after turn the pot to 512 analog value turn the motor to the left (digitalWrite(I1, HIGH); digitalWrite(I2, LOW);)and then stop when it reach 512 then when adjust the pot back to zero turn the dc motor to the right (digitalWrite(I1, HIGH); digitalWrite(I2, LOW);) but the think is what i am trying to do is exactly what we can do with the servo motor in the knob http://www.arduino.cc/en/Tutorial/Knob

I'm using a normal DC motor and l293D IC but I want to control the DC as knob method like the 200 degrees.

**Code**

```
#define E1 11    // Enable Pin for motor
#define I1 10    // Control pin a for motor
#define I2 9     // Control pin b for motor
const int analogPin = A0;
int analogValue ;

void setup() {
  pinMode(E1, OUTPUT);
  pinMode(I1, OUTPUT);
  pinMode(I2, OUTPUT);

}

void loop() {

  int analogValue = analogRead(analogPin);

  if(analogValue > 0 && analogValue < 512)  {

  analogWrite(E1, 255);
  digitalWrite(I1, HIGH);
  digitalWrite(I2, LOW);
    delay(100);
} else
  analogWrite(E1, 255);
  digitalWrite(I1, LOW);
  digitalWrite(I2, HIGH);
 }

```

# Answer
It looks like you want to use the "analogValue" to control the direction and speed of your DC motor. If this is correct consider using this:

```
      //This method assumes: The center position of the pot is the motor's 0 speed point,
      //(because this is an ideal speed to actually reverse the motor's direction).
      //A PWM control range of 0-255, and the ADC input range of 0-1023.

      //First create a relative speed value from "analogValue",
      //with the pot mid point at 0 speed, and pot high/low points being full speed.

      int motorSpeed = 0;
      if (analogValue < 512 )
      {
       motorSpeed = map(analogValue, 0, 511, 255, 0);
      }  //Note that mapped range is reversed to give 0 speed at mid point.
      else
      {
       motorSpeed = map(analogValue, 512, 1023, 0, 255);
      }

      //then replace each analogWrite(E1, 255) with:
      analogWrite(E1, speedValue);

      //you should also change "  if (analogValue > 2 && analogValue < 500) {  " to:
      if (analogValue < 512) {

```
> 1 votes

---
Tags: c
---


# Question
Title: Trinket works with USB but not with wall adapter
My Adafruit 5V Trinket works fine when powered via USB connected to my computer (and the power going in to the Trinket is 5V), but if I use a 9V wall adapter with a microUSB adapter, it just powers on but doesn't seem to actually run the program on the Trinket.

Am I *over* powering the Trinket and sending too much voltage to everything? If that's the case, is there some way to decrease the voltage?

# Answer
> 0 votes
Yes, you are probably over-powering the trinket. The trinket expects 5V on the USB connector. However, it has an voltage regulator on board that can take up to 16V.

The BAT pin is connected to the voltage regulator and can take anywhere from 5.5V to 16V.

---
Tags: voltage-level, adafruit
---


# Question
Title: Can't program Arduino via Bluetooth (HC-06) with a Mac
I bought a HC-06 Module for my Arduino Uno the other day, yesterday it arrived and I'm having trouble using it with the Arduino IDE.

I set it up, connecting 5V, GND and RX/TX crossed. After a bit of searching, it shows up on the bluetooth settings on the macbook. When I click "connect", it fails, after I click "Options", then set the Pin to 1234 it says "Connected". The LED on the HC-06 is still blinking (which is OK I guess, since I'm not yet communicating).

I have a Sketch running on the Uno that prints out some text. When I open the serial monitor (after connecting like above) it works, displaying the values I expect. However, after closing the serial monitor the HC-06 changes to "not connected" on the mac.

Also, if I try to upload code via the Arduino IDE it states: `avrdude: ser_open(): can't open device "/dev/tty.HC-06-DevB": Resource busy
ioctl("TIOCMGET"): Inappropriate ioctl for device` or throws a `processing.app.SerialException: Fehler beim Öffnen des seriellen Ports "/dev/tty.HC-06-DevB".` (German for "Error while opening Serial Port "/dev...." ").

Do I have to configure the HC-06 or the Arduino IDE in any way to make this work, and, if so, how can I do that?

**Edit:** I've also connected TX and RX uncrossed, though that alone doesn't solve the problem.

Thanks in advance for your Support!

# Answer
> 3 votes
The on-board USB-to-serial pulses the reset line to start the bootloader. HC-0x don't have the extra signal available that USB uses for that so you'll have to manually reset the Arduino just as - or very slightly after - you click to start the upload on your Mac; you may need to experiment to get the timing right, but once you know it, it isn't hard to do. Keep Rx & Tx crossed as you do for Bluetooth terminal communication. And even with all that, I've never achieved anything like USB upload speeds (baud rate for baud rate) using Bluetooth.

Update:
In brief, it could be timing, baud-rate, or pairing.

I find it easy to get the timing: hold reset / click (and let go) the upload button / release reset. It doesn't need to be so fast that it's a challenge to coordinate but do it faster than counting seconds.

Your HC-06's baud rate will have to match the baud-rate your boot-loader expects. It looks like Uno's bootloader's use 19200 baud (and there are some way older ones that used 9600). My bare, pre-programmed chips' boot-loaders from Adafruit.com use 57600 baud. Your `preferences.txt` file should contain a line like 'atmega328o.upload.speed=115200'; assuming you're able to upload via USB, then use this baud rate for the HC-06. (The path to your preferences file is displayed on the Arduino IDE's preferences dialog.)

The 'Resource busy' message sounds like your Mac isn't paired with your HC-06. In the MacOS Bluetooth System Preferences pane, pair the Mac with the HC-06 and be sure HC-06's LED is on steady (not blinking).

# Answer
> 1 votes
If I remember correctly, you do not want to cross TX and RX.

Usually, you cross TX/RX because you are looking at it from the opposite side - the PC's TX is the Arduino's RX and vice-versa.

However, in the case of BlueTooth, the HC-06 has the same perspective as the Arduino - TX (transmit) is TX on the HC-06, since that is what the HC-06 transmits (over Bluetooth).

Also, if you are connect your Arduino via USB, the TX & RX are also connected via USB; I don't know if this would cause cross-talk. It shouldn't (so long as you don't send to your Arduino using Bluetooth AND USB at the same time), but it may. Also, as you're programming the Arduino using Bluetooth, you may get the Arduino's responses coming back to you via Bluetooth.

ADDITIONAL:

Go read http://arduino.cc/en/Hacking/Bootloader?from=Tutorial.Bootloader \- this is all about the bootloader.

It seems from that that current bootloaders run at 19200, some older ones run at 9600. There are commands to program the speed on HC-06 - instructions can be found at http://www.instructables.com/id/AT-command-mode-of-HC-05-Bluetooth-module/ (this covers the hc-06 too).

Based on the bootloader tutorial, I think you have "less than a second" (only two specific boards are mentioned, so this is a best guess; I am amazed that it is this long, I expected a few milliseconds). If you have a USBISP, you could compile and upload a new firmware, with settings more to your liking - this is outside the scope of this article.

Another option is to create a completely separate uploader - an AtTiny could do it. Connect the AtTiny to the serial port, and then get the AtTiny to reset and program the board, or even program it via ICSP. This is a lot of work, and also outside the scope of this article.

# Answer
> 1 votes
Regarding the ability to upload, that is correct - you won't be able to upload code via Bluetooth. In addition to providing a serial connection, the USB connection does something extra (hold reset, I think), when you upload via serial-over-usb.

# Answer
> 0 votes
After dealing with the problem for several hours I unexpectedly solve the problem.

The HC-06's LED keep blinking after I entered the "1234" code. In my case (I'm using Windows 10), the HC-06 status changed to "connected" for few seconds and then changed to "Paired". Once I opened the correct COM port to receive data from the HC-06 to my PC computer, the LED changed to solid ON. Then I was able to catch data from my Arduino UNO. As soon as I closed the COM port in my PC (I used CoolTerm), the LED changed to blinking back again. The COM port I used to receive the data was the one indicated with direction "Outgoing" in the PC's Bluetooth settings. So, I was expecting the HC-06 to behave as my Bluetooth speakers or my Bluetooth headphones: Always connected. I was wrong and it cost me several hours of testing.

In my firsts tests I focused opening the COM port with direction "Incoming". Nothing happened here and I lost a lot of time. I tested my wiring between the arduino and the HT-06 module by changing the device name from "HC-06" to "ArduinoBT01" and it worked.

This is the sketch I used to receive data form the Arduino via Bluetooth:

This is the CoolTerm's window capture:

Mysteriously, the CoolTerm speed setting is 14400bps but the speed in the device manager for COM34 is 9600bps. After triying opening many times the COM34 port with 9600bps I got this error in CoolTerm:

"An error occurred while attempting to open the port". "1168: Error 1168"

So, it only works with 14400 bps. Crazy!!

I hope this helps.

Sorry for bugs in my English.

---
Tags: arduino-uno, serial, programming, bluetooth
---


# Question
Title: Reading sensor data, massaging it and performing operation based on transformed data
This is the outline of my project:

1. interpret environment data (sensor, motor, etc..).
2. Modify this data into a more usable form,
3. send it back to the same motor for further operation from modified data.

As an example (this is not the project, but just an example to make sure I am being clear).

A motor moves a conveyor belt with various size flasks on it, some large other small. Depending on the reading of the position of the motor (from encoder) another process (filling the flasks) will take place. If the first motor encoder data indicated the flask was small then the amount of liquid poured will be small. If large, the amount of liquid dispensed will be large.

More generally, read the location of an item based on motor encoder feedback. Modify this data. Send this modified data back to a different motor so that it does something specifically as a function of the first motor encoder data.

I am able to send the original encoder feedback to a file, manually massage it and paste it into an Arduino script, compile and have everything work great. I just want to remove the manual steps (cut & paste) and data massaging (I'm looking to an Arduino program to do that).

To further complicate things, I want this process to be part of a distributable package that does not require further compiling. Reading from a sim card is fine. Also, I am not too price sensitive as the Arduino is a small portion of the total cost of the final product.

I hope someone can give me some insight or pathway to a solution. All the very best, John.

# Answer
Here's a back-of-envelope sketch, off the top of my head:

Conveyor belt driven by stepper motor, controlled by the Arduino. Each step is a known distance.

Bottles are either of exactly two heights, at random. Two beam break sensors, one to determine where a bottle starts and one to determine whether it's tall or short.

Some sort of valve to control the water flow - I presume you have some idea how this can be controlled. I don't, but washing machines have electrically-controlled valves so something broadly along those lines. Controllable on/off by the Arduino.

Software on the Arduino steps the motor until it sees the start of a bottle (first beam broken). Then uses second beam to determine whether the bottle is large or small.

Arduino switches on the water valve (outlet positioned exactly right to be above the bottle) for either 2s or 4s accoriding to bottle size, then off again. (Water pressure and flow rate regulated independently, perhaps fed from a header tank).

Arduino steps motor more until it sees another bottle.

---

No string concatenation in there, nor sorting of lists or need for a Raspberry Pi. It's not clear to me why you'd need those things for the application described.

I'm not aware that you can program the Arduino in Python unfortunately. Someone may know better. C isn't hard though - get an Arduino and some LEDs or whatever, go through some tutorials, you'll get the hang of it.
> 1 votes

---
Tags: datalogging
---


title: Did I Brick my Controllino?

text:
# Question
Title: Did I Brick my Controllino?
I recently obtained a Controllino Mini to be used in a small industrial project. While checking it out I also wanted to test the built-in RTC capabilities. In doing so I toyed around with the available commands from the supplied library. After uploading another sketch it seems I have bricked the Controllino, since I cannot upload anything else :

> avrdude: stk500\_recv(): programmer is not responding avrdude: stk500\_getsync() attempt 10 of 10: not in sync: resp=0x00

and the reset LED is permanently lid. When looking at the pinout diagram of the Controllino Mini I saw that there was a small remark near the top stating

> Not proper handling of the RTC/INT output can cause permanent controllino reset , so I guess I somehow reached that state.

Since I am pretty new to the whole Arduino / Microcontroller scene I don't really know where to go from here.

* Is it a viable idea to try and burn a new bootloader ?
* Is there a simpler way to reset the state of the device?
* What did I even do wrong ?

Any help is greatly appreciated !

Christian

Below is the sketch that got me into this mess:

```
#include <Controllino.h>

unsigned char day, weekday, month, year, hour, minute, sec;
#define analogInputPin A0
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(analogInputPin, INPUT);
Controllino_RTC_init(1);
Serial.print("Initalized RTC: ");
Controllino_SetTimeDate(1,6,4,2016,15,14,10);
}

void loop() {
 Controllino_ReadTimeDate(&day,&weekday,&month,&year,&hour,&minute,&sec);
  float voltage = 15*(analogRead(analogInputPin)/1023.0);
  Serial.print(hour);
  Serial.print(":");
  Serial.print(minute);
  Serial.print(":");
  Serial.print(sec);
  Serial.print(" : ");

  Serial.println(voltage);

}

```

# Answer
I just received an answer from the official team which should work, I'll leave it here for further reference:

> 1. Open the device and disconnect (remove) connection board for approx. 30 seconds from the control board – RTC is disconnected from power (gold cap disconnected) and because of that there is reset of all RTC registers.
> 2. Plug the connection board back in to the control board. Now we need to rewrite the SW inside the Controllino which caused wrong RTC setting.
> 3. Open the Controllino example RTC sketch in Arduino IDE and prepare it to upload (function Controllino\_RTC\_init(0); shall reset all registers inside the RTC).
> 4. Pres and hold reset button on the Controllino device.
> 5. Connect the USB Cable (still hold the reset button, SW inside the Controllino doesn’t start)
> 6. Click for upload the sketch in Aruduino IDE and wait for „uploading“ message on debug line, than immediately release the reset button and uploading shall be finished (=\> hold the reset button during the compiling phase)
> 7. If not successful, repeat the procedure
> 1 votes

# Answer
It certainly looks like the INT pin of the RTC can kill the whole unit. Bit of a FUBAR on their part I would say.

> Is it a viable idea to try and burn a new bootloader ?

If the problem is that INT pin then you won't be able to replace the bootloader, and even if you did it wouldn't fix the problem.

> Is there a simpler way to reset the state of the device?

It looks like you will have to make a hardware modification - cut the connection between /INT and /RESET on the board - if you can identify which track that might be - or use a soldering iron to heat and lift the /INT pin of the RTC chip, which might be easier, depending on what the chip is (they are amazingly short on information).

> What did I even do wrong ?

Probably nothing serious - it's the design that is at fault. Anything that has the potential to completely cripple a system like that without even trying is just idiotic.
> 4 votes

---
Tags: atmega328
---


# Question
Title: Arduino-Bluetooth HC-05 Android app blueterm connection for chatting
I want to communicate between an arduino and an Android phone that has an Android app blue term. I connected HC-05 with Arduino using software serial and I connected the hc05 as a device with the android app. I am able to send data ( data as in message) from Android to Arduino but I am unable to send message from arduino to Android though I have given `.write()` command to Bluetooth connected.

Is it such that the Android app does not show the received message? Or there is some master-slave configuration issue? Do I need to configure HC-05 in master mode? It was configured in slave mode by default when I had connected it to Android app.

# Answer
Its totally Normal. You must be doing something wrong. It has happen to my Arduino Code a lot of times. try following:

1. Try interchanging you Tx and Rx Pin Positions. (This happens all the time).
2. Try connecting using default **Serial** and using Pin 1 and Pin 0 as Tx/Rx. (In this case remember to unplug the Tx/Rx Pins while running code.)
3. Try using just basic **Serial.Write()** function in beginning.
> 0 votes

---
Tags: android, hc-05
---


# Question
Title: Stop multiple presses in vex bumper (Unexpected bumper output)
According to Official documentation of the Vex Bumper, it states that the bumpers will cause:

> the robot sometimes \[counts\] a press twice. This issue is also caused by the robot counting too fast and as the limit switch is released, a second press is registered by the robot.

The documentation suggests this code:

```
task main() {
    while(true) {
         string presses = buttonPresses;
         if(presses != last) {
             writeDebugStreamLine(presses);
         }
         last = presses;

         if(SensorValue(bump) == 1) {
             wait1Msec(5);
             while(SensorValue(bump) == 1){}
             buttonPresses++;
         }
    }
}

```

**However, if you are like me, this didn't work at all, multiple button presses were registered from holding down the button for a moment and releasing it.**

# Answer
> 0 votes
When you are testing buttons within a loop that runs repeatedly, there's no need for lengthy monolithic delays like `wait1Msec(15)`, and no need to store and test start times, like `time = time1[T1]` and `time1[T1] - time > 50`.

Instead, you can change your loop so it takes at least some small time (as via `wait1Msec(1)` in following code sample), and add a holdoff counter that inhibits sensor testing during probable bounce periods.

```
string last;
long bumpCount = 0;
byte holdoff=0, isbump=0;

task main() {
  while (SensorValue(go) != 1) {
    string presses = bumpCount;
    if(presses != last) {
      writeDebugStreamLine(presses);
    }
    last = presses;
    wait1Msec(1);
    if (holdoff) {      // Ignore bump sensor during holdoff
      --holdoff;
    } else {
      if (SensorValue(bump)) {
        if (isbump==0) {
          ++bumpCount;  // Count a new closure
          holdoff = 40; // Start a holdoff period
        }
        isbump = 1;     // We detected bump is on
      } else {
        isbump = 0;     // We detected bump is off
      }
    }
  }
}

```

The code shown above acts as follows:

• Initially, `bumpCount`, `holdoff`, and `isbump` are zero, to indicate we haven't counted any bumps, are not inhibiting bump sensing, and think the bump sensor is off.

• Under initial conditions and while the bump sensor is off, we will pass through the outer while loop, each time waiting a millisecond, then taking the `else` branch of `if (holdoff)` and the `else` branch of `if (SensorValue(bump))`, so will repeatedly set `isbump = 0`, thus maintaining initial conditions.

• When the bump sensor goes on, we take the first branch of `if (SensorValue(bump))`. From initial conditions, `isbump==0` so we increment `bumpCount` and set `holdoff = 40`. Lastly, set `isbump = 1` to reflect sensor state.

• During the next 40 milliseconds or so (that is, during the holdoff period) we repeatedly decrement `holdoff`, while ignoring the bump sensor, which may bounce a number of times or not, as it pleases, but we don't care.

• After the holdoff period, `SensorValue(bump)` may still be true. But since `isbump==0` is false, we don't change `bumpCount`.

• If the bump sensor opens after the holdoff, `isbump` will go zero, restoring two of the initial conditions. If it opens during the holdoff and stays open, the same thing happens at the end of the holdoff.

# Answer
> 0 votes
Because this problem was so infuriating and strange, I managed to do a workaround which the program refused to take a sudden addition to button counts after taking a first one. This enabled me to use the button without multiple extra counts.

```
string last;
float buttonPresses = 0;
float time = time1[T1];
bool isFirstTime = true;

task main()
{
    ClearTimer(T1);
    clearDebugStream();
    while(SensorValue(go) != 1) {

        string presses = buttonPresses;
        if(presses != last) {
            writeDebugStreamLine(presses);
        }
        last = presses;

        if(SensorValue(bump) == 1 && buttonPresses < 6) {
            if(isFirstTime || time1[T1] - time > 50) {
                isFirstTime = false;
                wait1Msec(15);
                while(SensorValue(bump) == 1){time = time1[T1];}
                buttonPresses++;
            }
        }

    }
}

```

If you want extra probability against multiple extra "presses" you can widen the interval of tolerance (in this case the 50 value) to something larger, but it makes it less accurate at registering quick taps.

---
Tags: c
---


# Question
Title: Why doesn't my 7 segment update every second like in the program?
I used sevseg.h library to write numbers to my 4 digit seven segment. The display should update every second with the current time since program started running. This is my code so far:

```
#include <SevSeg.h>

SevSeg sevseg;

void setup() {
    byte numDigits = 4;
    byte digitPins[] = {5, 4, 3, 2};
    byte segmentPins[] = {13, 12, 11, 10, 9, 8, 7, 6};
    sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(50);
    sevseg.setNumber(0000, -1);
}

void loop() {
    unsigned long timer = millis();
    for (int i = 0; i < 500; i++) {
        sevseg.setNumber(timer/1000, -1);
        sevseg.refreshDisplay();
        delay(2);
    }
}

```

Since the delay is 2, the for loop loops 500 times, resulting in 1000ms or 1 second. The current second is written to the display. For some reason, the display is updated every other 5 or 6 seconds. Why is this occurring? How can this be fixed so that my display turns into a stopwatch in a way?

# Answer
This is the code that fixed the issue:

```
  #include <SevSeg.h>
  SevSeg sevseg;

  void setup() {
    byte numDigits = 4;
    byte digitPins[] = {5, 4, 3, 2};
    byte segmentPins[] = {13, 12, 11, 10, 9, 8, 7, 6};
    sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(50);
    sevseg.setNumber(0000, -1);
  }

  void loop() {
    unsigned long timerGlobal = millis();
    sevseg.setNumber(timerGlobal/1000, -1);
    sevseg.refreshDisplay();
  }

```

In this, no delays are needed. `millis` is divided by 1000 and the integer second is drawn on the display. Proved to be much easier than I previously thought.
> 2 votes

# Answer
On SevSeg.h Arduino Page, It says:

> Your program must run the refreshDisplay() function repeatedly to display the number.

I think that's the Problem. You are calling it just once and then your **the number** is changed.

Plus, you are saying it must get updated after One Second, but I think in your code, its being updated ever other **2 milisecond** (WOW).

What I suggest is that you add a **delay()** for one second and then call **sevseg.refreshDisplay();** several times in a **for** loop. You also need to change the way you measure no. of seconds elapsed.

i.e. try Something like this:

```
#include <SevSeg.h>
SevSeg sevseg;
void setup() {
  byte numDigits = 4;
  byte digitPins[] = {5, 4, 3, 2};
  byte segmentPins[] = {13, 12, 11, 10, 9, 8, 7, 6};
  sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
  sevseg.setBrightness(50);
  sevseg.setNumber(0000, -1);
}
unsigned long timerGlobal = millis();
void loop() {
  delay(1000);
  sevseg.setNumber( (timerGlobal - millis())/1000, -1)
  for (int i = 0; i < 50; i++) {
    sevseg.refreshDisplay();
  }
}

```
> -1 votes

---
Tags: display, millis, 7-segment
---


title: Iterating an array of relays

text:
# Question
Title: Iterating an array of relays
Bear with me as I'm fairly adept at C# but I am having a problem understanding how to get an array iterated.

I am writing a program to test relay boards, it will eventually have an input mechanism to select the number of relays on the board. For now, i just need to get an array iterated to move on with the code.

The biggest relay board I've seen has 16 relays, so....

```
#define Relay1  2  // Arduino Digital I/O pin numbers for UNO R3
#define Relay2  3
#define Relay3  4
#define Relay4  5
#define Relay5  7
#define Relay6  8
#define Relay7  9
#define Relay8  10
#define Relay9  11
#define Relay10  12
#define Relay11  13
#define Relay12  A0
#define Relay13  A1
#define Relay14  A2
#define Relay15  A3
#define Relay16  A4

int relays[]{ Relay1,Relay2,Relay3,Relay4,
    Relay5,Relay6,Relay7,Relay8 };
int maxRelayCount = 8;
char rx_byte = 0;

void setup()   //Initializes all variables and settings
{
  Serial.begin(9600);
 // create an input for the amount of relays on the board
//hardcoded for now

//Set pins to OFF & declare pins as OUTPUTS
 for(int i = 0; i < maxRelayCount; i++)
 {
   digitalWrite(relays[i], RELAY_OFF);
   pinMode(relays[i], OUTPUT);
   //How to convert i to a string in c++?
   //Serial.print("Relay " +[i] + " set HIGH and as OUTPUTS");
 }

 //Check that all relays are inactive at Reset
 delay(4000);

}

```

So there are two issues. If I remove the loop and just hard code 8 times to set HIGH and OUTPUT it works fine, but the loop does not and won't upload to the Arduino, thus the reason I believe it is wrong. Secondary question is how to convert the counter i to a string to concatenate the message

# Answer
> 1 votes
As noted earlier, `RELAY_OFF` needs a defined value.

Note, rather than using clumsy list of `#define` statements to define a bunch of integer constants, you can use C's `enum` declaration to define them, as shown in the following sketch, which produces the output

```
Relay 1 should be OFF
Relay 2 should be OFF
Relay 3 should be OFF
Relay 4 should be OFF
Relay 5 should be OFF
Relay 6 should be OFF
Relay 7 should be OFF
Relay 8 should be OFF

```

when it is run.

```
#include <Streaming.h>

// Arduino Digital I/O pin numbers for UNO R3
enum { Relay1=2, Relay2=3, Relay3=4, Relay4=5, Relay5=7, Relay6=8,
       Relay7=9,   Relay8=10,  Relay9=11,  Relay10=12,  Relay11=13,
       Relay12=A0, Relay13=A1, Relay14=A2, Relay15=A3,  Relay16=A4};

int relays[] = {Relay1,Relay2,Relay3,Relay4,Relay5,Relay6,Relay7,Relay8};
// Number of relays in the array
enum { maxRelayCount = sizeof relays / sizeof relays[0] };
enum { RELAY_OFF = HIGH };  // Set LOW or HIGH as appropriate
char rx_byte = 0;

void setup() {          // Initialize variables and settings
  Serial.begin(9600);
  //Set pins to OFF & declare pins as OUTPUTS
  for(int i = 0; i < maxRelayCount; ++i) {
    digitalWrite(relays[i], RELAY_OFF);
    pinMode(relays[i], OUTPUT);
    // Serial.print("Relay " +[i] + " set HIGH and as OUTPUTS");
    Serial << "Relay " << i+1 << " should be OFF" << endl;
  }

 // Check that all relays are inactive at Reset
 delay(4000);
}

void loop() {}

```

Note, the `Streaming.h` library adds some “syntactic sugar” to Arduino C. At compile time it converts C++-like \<\< Serial stream operators to Serial.print statements, without increasing code size. You can install it by unzipping `Streaming5.zip` from arduiniana.org in your `sketchbook/libraries` directory

# Answer
> 2 votes
> the loop does not and won't upload to the Arduino

Most likely because `RELAY_OFF` has never been defined anywhere. Change that to HIGH (if that is what your relays need to turn off), or define it somewhere.

Also there is no `loop()` function - is that just you being economical with the paste?

> Secondary question is how to convert the counter i to a string to concatenate the message.

Simple: don't. There's no need.

```
Serial.print("Relay ");
Serial.print(i);
Serial.println(" set HIGH and as OUTPUT");

```

---
Tags: arduino-uno, array
---


title: Audio/Voice Recording Device

text:
# Question
Title: Audio/Voice Recording Device
I'd like to build a little voice recorder for my grandmother. She told me "I get a lot of idea when I'm driving but then I forget them. I want a necklace where I can just press a button and it'll record my voice and I can press a button and it'll stop recording." She wants each recording to save as a separate file. I was thinking of concealing a mini Arduino board or Rasberry Pi or something in a necklace, with a removable micro sd card. Or something like that. I just don't know where to start, I don't have much experience with this. Does anyone have any tips on what kind of device I could use or where to start? I suggested that she just have Siri take notes for her on her iPhone but she wants something around her neck, and she wants me to make it.

# Answer
Try this amazing breakout board. Its all you need. SparkFun Voice Recorder Breakout - ISD1932

Moreover, If you thinking on letting that device talk back, try this: VoiceShield

Well, there is also an instructable for this, HERE. This Instructable will show you how audio input can be repeatedly added to a 512 byte buffer and then transferred to a SD card in real time. The audio file can be played back on a standard audio application or analysed byte by byte.
> 0 votes

---
Tags: sensors, audio, raspberrypi
---


title: User input for utility program

text:
# Question
Title: User input for utility program
I am writing a utility program to test relay boards. I'd like to be able to accept a user input of the number of relays on the board. Is this doable via the serial monitor since when I'm testing boards I'm generally doing it at my desk with my testing Arduino attached to my laptop? I'd prefer not to go the LCD and keypad route.

Is there an accepted practice for doing this?

# Answer
Yes, it is perfectly do-able through the serial monitor. However the serial monitor is very very basic and you will be able to create a much better user experience using a proper serial terminal emulator (such as TeraTerm, Putty, etc) and using ANSI control codes to lay the screen out as a proper text-based application.

A useful resource is on Wikipedia: https://en.wikipedia.org/wiki/ANSI\_escape\_code

I have a little library that I started a while back and never finished that performs two basic ANSI control sequences - clear screen and set cursor. You can look at it to see how to perform ANSI control codes: https://github.com/MajenkoLibraries/ANSI
> 3 votes

---
Tags: arduino-uno, input
---


title: Simulator for AD8232 Chip

text:
# Question
Title: Simulator for AD8232 Chip
How can I get AD8232 chip in Arduino simulator? It is because I have my ciruit comprising AD8232 analogue chip but I dont get this chip? I want to make simulatoin of my ciruit. If it is can not be found in Arduino please direct me in which circuit simulating software can I get it!

# Answer
I don't think there would be an actual simulator for this chip. Its hard. But there is a way around.

What you are doing eventually is **ECG** and the output given by this chip is just analog signal i.e. **a single float value**. So, lets say for now, all you are concerned with is obtaining those float **values** irrespective of source. And of course you need a lot of them.

What you can do is to use a **dataset**. As indicated by its name, a **dataset** contains a large number of (recorded) value of something.

So, you can use a **dataset for heart reate** to **simulate** this chip.

There are many related **datasets** available online for free. just Google it. and find one that suits you.

Hope it help. Thanks.
> 1 votes

---
Tags: simulator
---


# Question
Title: How do we connect 2 FSR sensors to an Arduino Mega?
One can connect an FSR sensor (a force-sensitive resistor) to an Arduino via 5V, Gnd, and A0 port (as below, according to an adafruit.com page), but how will it work for two of them instead of one?

# Answer
Attach the second FSR mostly the same as the first, but connect the second analog voltage to A1 instead of to A0.

You can use several copies of the circuit (below left) with each circuit's analog voltage going to a different analog-converter input (A0, A1, A2, ...).

To connect up multiple 5V and ground connections, you can:

• use almost any popular shield
• use breadboards like those illustrated above
• cut and solder Dupont cables to add extra pins or sockets in or out (for example, cut two M-F Duponts in half, and connect both F halves to one M half)
• connect to the extra 5V and Gnd pins on Uno or Mega boards. (On a Mega, besides 5V and Gnd pins on programming headers, there are two 5V sockets next to 22 and 23, and two Gnds next to 52 and 53.)

The diagrams above right show the location of the 5V pins on the programming headers found on the Uno. Most Arduino boards have at least one AVRISP header like that.
> 1 votes

---
Tags: arduino-mega, sensors
---


# Question
Title: How can we replace a 10k potentiometer with resistors?
I am using an LCD (16x2) with an Arduino Uno R3, in for that I need a 10 kΩ potentiometer, but I don't have it now. How can I replace that?

I have resistors of many kinds and a 1 kΩ potentiometer.

# Answer
> 2 votes
Just use your 1k pot in place of the 10k pot. The resistance doesn't matter that much (though you don't want to go loo low or you could draw too much current) since it is just being used as a voltage divider to set an offset point for the LCD.

# Answer
> 1 votes
Derived from Ohm's Law:

* R = R1 + R2 + ... + Rn (For resistors in Series)
* (1/R) = (1/R1) + (1/R2) + ... + (1/Rn) (For resistors in Parallel)

---

You can use any resistance from 1k to 10k with your LCD but the actual value depends on your choice and preferences. You may start with 5k and if you have one then its allright. But if you do not have a resistor of that value you can join resistors of lower values in **series** with your 1k POT to get resistance of 5k ~ 6k.

In such a way you may get a variable resistance (1k pot) with a suitably high value (other resistors in series). If you wish, you may add more resistors to get higher values like 8k ~ 9k and so on.

# Answer
> 0 votes
Try using 9k~1k. (It worked for my 16\*2 LCD)

Or place 9k in series with 1K and vary that.

Connect 10 of your 1K resistors in series. Connect one end to GND and other end to VCC. Now, you will have 10 different nodes (including VCC and GND) each having a different voltage. Connect your desired input pin to any of those nodes.

---
Tags: arduino-uno, lcd, potentiometer
---


# Question
Title: How do I use an AtTiny85 (or other AtTiny) with Arduino?
*Please mind that this is an "example" question.*

**How to make a "tiny arduino"?**

I've ordered a bunch of ATtiny85's off E-bay, they're like tiny Arduino's.

I've set up the latest Arduino IDE and would like to run the blink example.

My process so far:

**Wiring**

**Code**

(The blink example)

```
// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
}

```

# Answer
**1. The Tiny**

The ATtiny differs a little from the Arduino, don't expect it to be "fully compatible". It's a microcontroller which is just a part of an Arduino and not a full Arduino itself.

It's more of a device for "advanced users" and gives some more flexibility (at cost of usability). You can easily add this microcontroller on a breadboard, since putting a full Arduino on a breadboard makes little sense.

***1.1 USB?***

Since the ATtiny is a microcontroller (like the ATmega on an Arduino) and not a development board (as an Arduino), it does not have an USB connector. The ATtiny series also does not have hardwareUART (Rx/Tx). The

You'll have to take care for a steady power-supply to your Microcontroller and the programming will be a little more tricky (details further below). It is however possible to use `SoftwareSerial` and a customized bootloader. My ATtiny85 runs software serial with 115200 fine, though I have found a post which states that the internal oscillator should be tuned for a reliable connection.

***1.2 RAM/program memory***

The ATtiny has less RAM and program memory. This essentially means your program can't be as 'big' as on a normal Arduino. It also means that you can't use as much variables. A program for the tiny should be "small" or very efficient.

***1.3 "Speed"***

My ATtiny came with 1Mhz internal clock set, but if you change the fuse bits you can make it run at 8Mhz. An standard Arduino has a 16Mhz clock on the board. So your code would run 16x slower on default and 2x slower on "max". You could use an external clock for the ATtiny, but that eats up 2 pins. The cool thing is, when you set it to 1Mhz it can run on about 2.7V (check datasheet first).

```
Arduino                   16Mhz
ATtiny (standard)         1Mhz
ATtiny (set fuses)        8Mhz
ATtiny (external crystal) up to 20Mhz

```

Higher Mhz is faster. Keep in mind that 1Mhz is roughly 1000000 instructions per second, which is still blazingly fast and good enough for most occasions, especially on such a tiny device.

**2. Programming the Tiny**

Most of the ATtiny's don't come with a customized (software serial) Arduino bootloader. This essentially means that you have to burn a custom bootloader by yourself or use another type of programmer. You should really watch the video from Ben Heck. He explains that Arduino boards have an USB converter on board and have custom code that is able to "bootload" your Arduino. But that ICSP/ISP programmers are used to upload programs without a bootloader/uart connection.

***2.1 The programmer***

You've got a load of options, check the "Programmer" item in the "tools" tab in your Arduino IDE. I'm using an USBasp which can be bought on ebay for as little as 3€. You should get one that has a selectable voltage (3.3V and 5V).

(If your ATtiny85 already has the bootloader, which is unlikely, you can use the software rx/tx pins for uploading)

***2.2 Preparation***

Check your microcontroller if it really is a ATtiny85 my E-bay reseller actually had one ATtiny45 included, which lead to an "error" when trying to upload.

The Arduino IDE does not know the "ATtiny board" so you can't select it easily. You'll have to let the IDE know that the ATtiny can also be programmed.

I found a very nice tutorial that describes how to do this.

> 1. Open the preferences dialog in the Arduino software. Find the “Additional Boards Manager URLs” field near the bottom of the dialog.
> 2. Paste the following URL into the field (use a comma to separate it from any URLs you’ve already added): https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package\_damellis\_attiny\_index.json
> 3. Click the OK button to save your updated preferences.
> 4. Open the boards manager in the “Tools \> Board” menu.
> 5. Scroll to the bottom of the list; you should see an entry for “ATtiny”.
> 6. Click on the ATtiny entry. An install button should appear.
> 7. Click the install button. The word “installed” should now appear next to the title of the ATtiny entry.
> 8. Close the boards manager. You should now see an entry for ATtiny in the “Tools \> Board” menu.

***2.3 Changing the internal clock***

Some interesting post I found told me that you can change the internal clock/oscillator to 8Mhz by selecting 8Mhz (internal) as the clock and pressing the "Burn bootloader" button. This won't flash a bootloader (since that makes little sense on a Tiny85) but does change the fuse-bits.

***2.4 Code***

You'll not get away with the standard blink tutorial. It uses digital pin 13 (the tiny only has 8 pins).

Mind that you might have to upload using Ctrl+Shift+U (or sketch-\>Upload with programmer).

I used the diagram below to check the pins (from highlowtech.org)

**3. Hardware**

Your "schematic" isn't complete, I don't see a way to program or power the microcontroller. And you might want to take some precautions.

I personally think a well-drawn schematic looks better as a "breadboard view".

The 10Kohm pull-up resistor on the reset pin is not 100% neccesary according to the datasheet. But the Uno has one in it's reference design (which I use as a reference).

There are two capacitors, one "big" capacitor as a reservoir. If one device suddenly pulls a lot of current, this capacitor will handle that. The smaller decoupling capacitor will damp the noise of other IC's or switching supplies. It may work withouth these, but your circuit will be more reliable with them. Mind that the decoupling capacitor should be (physically) close to the IC.

You can power the board through the programming header, but mind that you'll need a smooth voltage between (most likely) 3.3V and 5V. If you want to power it with a bigger voltage (9V battery) then you'll need a voltage regulator.
> 1 votes

---
Tags: arduino-ide, attiny, avr
---


# Question
Title: Arduino countdown timer preventing rest of program running
have a program that checks to see if an RFID tag has been read, if it has, it runs some code.

I also have a count down timer function (timer) that I'd like to run in the background. It displays the clock on the bottom of the LCD.

The problem I'm having is that when I put timer(); in the main loop, the rest of the program is delayed for the duration of the count down which means that no RFID cards are read.

The timer works, but nothing below timer(); is running. I assume this is because of the use of delay.

Does anyone know how I can prevent this? Thank you.

```
    #include <SPI.h>
#include <MFRC522.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

int readflag;
int initstate = 1;

int nextred = 4;
int nextblue = 8;

uint8_t readCard[4];

int minutes = 1; //start min
int seconds = 0; //start seconds

MFRC522 mfrc522(10, 9);
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

///////////////////////////////////////// Setup ///////////////////////////////////
void setup() {

    //Protocol Configuration
  Serial.begin(9600);
  SPI.begin();
  mfrc522.PCD_Init();
  mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);

  lcd.begin(20, 4);

}

///////////////////////////////////////////////////////////////////////////////
  // Main loop
///////////////////////////////////////////////////////////////////////////////
void loop () {

 do {
   readflag = checkread();
if (initstate == 0) {
  timer(); //start timer - timer works but nothing below timer(); is running.
   lcd.setCursor(0,0);
   lcd.print("Red team next: ");
   lcd.print(nextred);
    lcd.setCursor(0,1);
    lcd.print("Blue team next: ");
    lcd.print(nextblue);

}
  }
  while (!readflag);
  tone(8, 850, 15);
  recordid();
  updatenextteamnumbers();
}

///////////////////////////////////////////////////////////////////////////////
  // Function to update team next numbers
///////////////////////////////////////////////////////////////////////////////
void updatenextteamnumbers() {
//If Blue Tag scanned show team info
  if (*((uint32_t *)readCard) == 0xACB7D573) {

    Serial.println("Blue Tag detected, showing team info");
    initstate=0;

   }

//Red Team (sequence 4, 5, 2, 1, 9)
else if (*((uint32_t *)readCard) == 0x29FDC9F5 && initstate == 0) {
    Serial.println("CARD 4 detected");
    nextred = 5;

      }

else if (*((uint32_t *)readCard) == 0x3FCE7832 && initstate == 0) {

    Serial.println("CARD 5 detected");
    nextred = 2;

}

else if (*((uint32_t *)readCard) == 0x3FCCECE2 && initstate == 0) {

    Serial.println("CARD 2 detected");
    nextred = 1;

      }

  else if (*((uint32_t *)readCard) == 0x3F7AB752 && initstate == 0) {

    Serial.println("CARD 1 detected");
    nextred = 9;

    //activateredrelay

      }

  else if (*((uint32_t *)readCard) == 0x00000000 && initstate == 0) {

    Serial.println("CARD 9 detected");
    redwins();

      }

//Blue Team (sequence 8, 6, 3, 7, 10)

else if (*((uint32_t *)readCard) == 0x00000000 && initstate == 0) {
    Serial.println("CARD 8 detected");
    nextblue = 6;

      }

else if (*((uint32_t *)readCard) == 0x00000000 && initstate == 0) {

    Serial.println("CARD 6 detected");
    nextblue = 3;

}

else if (*((uint32_t *)readCard) == 0x3F7ABA82 && initstate == 0) {

    Serial.println("CARD 3 detected");
    nextblue = 7;

      }

  else if (*((uint32_t *)readCard) == 0x00000000 && initstate == 0) {

    Serial.println("CARD 7 detected");
    nextblue = 10;

    //activatebluerelay

      }

  else if (*((uint32_t *)readCard) == 0x00000000 && initstate == 0) {

    Serial.println("CARD 10 detected");
    bluewins();

      }

 }

///////////////////////////////////////////////////////////////////////////////
  // Stores the ID of the card that's been detected in readCard byte array
///////////////////////////////////////////////////////////////////////////////
void recordid() {
    mfrc522.PICC_IsNewCardPresent();
    mfrc522.PICC_ReadCardSerial();

    for (int i = 0; i < mfrc522.uid.size; i++) {
        readCard[i] = mfrc522.uid.uidByte[i];
        Serial.print(mfrc522.uid.uidByte[i], HEX);
        }
Serial.println("");
    mfrc522.PICC_HaltA();
  }

/////////////////////////////////////////////
  // Returns 1 if a card has been detected
/////////////////////////////////////////////
int checkread() {
   if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return 0; }                                        //no card detected

    mfrc522.PICC_HaltA();
    return 1; }                                       //card detected

/////////////////////////////////////////////
  // Runs if red team wins
/////////////////////////////////////////////
void redwins() {
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Red team wins!");
      lcd.display();
      Serial.println("Red team wins!");
      delay(36000);
}

 /////////////////////////////////////////////
  // Runs if blue team wins
/////////////////////////////////////////////
void bluewins() {
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Blue team wins!");
      lcd.display();
      Serial.println("Blue team wins!");
      delay(36000);
}

 /////////////////////////////////////////////
  // Count down timer
/////////////////////////////////////////////
void timer() {
lcd.setCursor(0,3);
  lcd.print("Time left:");
 while (minutes > 0 || seconds >= 0) {
  lcd.setCursor(15, 3);
 (minutes < 10) ? lcd.print("0") : NULL;
 lcd.print(minutes);
 lcd.print(":");
 (seconds < 10) ? lcd.print("0") : NULL;
 lcd.print(seconds);
 lcd.display();
 decrement();
 delay(1000);
 }
}

 /////////////////////////////////////////////
  // Decrement timer
/////////////////////////////////////////////
void decrement() {
      if (seconds > 0) {
          seconds -= 1;
      }
      else      {
         if (minutes > 0) {
           seconds = 59;
           minutes -= 1;
          }
          else  {
            timeup();
          }
       }
}

 /////////////////////////////////////////////
  // Called when time expires
/////////////////////////////////////////////
void timeup() {
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Time up!");
      lcd.display();
}

```

# Answer
> 1 votes
Of course not - your timer() function is **blocking** meaning that it does not return, and so does not permit anything else to execute, until its timing is completely done.

You will need to re-design your program. Some options include:

1) Capturing an initial timestamp from millis() and comparing to it on each iteration through loop() to decide when your time has approximately elapsed, and to update the display with an appropriate value if that point is not yet reached. This is probably the best choice for your application, but be aware that after about 50 days of uptime, the difference calculation can be briefly incorrect, unless you account for overflow.

2) Place a short delay in the main loop (maybe 100 ms), and count iterations of the main loop until you have reached your desired time. Beware though that your effective time will become longer if other parts of the loop take time (especially variable amounts of it) to execute.

3) Set up an event timer in the background with interrupts. This is a lot more complex and probably not advisable in your application.

---
Tags: arduino-uno
---


# Question
Title: GPS Transmits False Data with SD card in; True data with SD card out
I've programmed my Arduino Ethernet to receive data from a Skytraq Venus GPS receiver and separate it using TinyGPS, then store it on an SD card. With the SD card inserted, everything else except the time is totally wrong. Once I remove the SD card and reset, the longitude and latitude are still wrong but everything else is correct. I've tried supplying more power, replacing the receiver, antenna, the arduino itself, even switched the serial ports I use but I can't seem to find a solution.

Here's a link for the TinyGPS library and a link for the NewSoftSerial library. And for the schematics, I haven't drawn any yet but I'm using the Arduino Ethernet's SD port as my SD shield. My Skytraq GPS receiver's RX pin is connected to pin 2 on the arduino ethernet and the TX pin is connected to pin 3 on the ethernet. (Ethernet TX/RX has been set to pin 3 and 2 respectively.)

I'm using the Sparkfun Venus GPS with SMA connector from sparkfun.com. I would post the link but it says I need at least 10 reputation to post more than two links. Serial signals at 3.3V and GPS module is a 3.3V module. I use the same sketch with and without the SD Card. SD.begin is called just once and Serial.begin is also called once.

Here's my code:

```
#include <SoftwareSerial.h> //NewSoftwareSerial Library
#include <TinyGPS.h>        //TinyGPS Library
#include <SPI.h>            //This Library is used by the SD library.
                            //Must be defined before SD library to prevent errors.
#include <SD.h>             //SD Card Library

//NB: To avoid SD Card Errors, use an SD Card whose size is at most 2GB
//and use FAT16 format. Arduino has problems with FAT32 and cards>2GB.

#define RXPIN 2
#define TXPIN 3

const int chipSelect = 4; //This selects the SD card port for read/write

#define GPSBAUD 9600

File logs; //Used to write to SD card later

TinyGPS gps;

//Initialize the Software Serial to recognize
//our UART pins (Read(RX) and Write(TX))
SoftwareSerial read_gps(RXPIN, TXPIN);

void getdata(TinyGPS &gps);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);  //Start the serial port
  read_gps.begin(GPSBAUD);  //Start reading from the gps

  pinMode(chipSelect, OUTPUT); //Make pin 4 an output pin
  pinMode(10, OUTPUT);  //Pin 10 must always be set to output to avoid errors
  digitalWrite(10, HIGH); //Pin 10 must always be high to prevent errors.

  Serial.println("");
  Serial.println("Awaiting Lock");
  Serial.println("");

  //Initialize the SD Card
  SD.begin();
  Serial.println("Initializing SD Card. Please Wait.");
  if(!SD.begin(4)){//If card not available or card not recognized
    Serial.println("Failed.");
    return;
  }
  Serial.println("Card Initialized");

}

//the loop function is used to read the data from the gps,
//check for valid data and then separate the data based on our specs.
void loop() {
  // put your main code here, to run repeatedly:
  while(read_gps.available()){//as data is received from the gps
    int c = read_gps.read();
    if(gps.encode(c)){//check if new valid data available
      getgps(gps); //read the valid gps data and process
    }
  }

}

void getgps(TinyGPS &gps)
{
  float latitude, longitude;

  gps.f_get_position(&latitude, &longitude); //Feature of tinygps.
                                             //Gets the latitude and longitude

  Serial.print("Latitude: "); Serial.print(latitude);
  Serial.print("\nLongitude: "); Serial.print(longitude);

  int yr;
  byte mnth, dy, hr, minu, sec, hundredths;
  gps.crack_datetime(&yr, &mnth, &dy, &hr, &minu, &sec, &hundredths); //Gets the date and time and separates them
                                                                      //into individual components.

  Serial.print("\nDate: "); Serial.print(mnth, DEC); Serial.print("/");
  Serial.print(dy, DEC); Serial.print("/"); Serial.print(yr);
  Serial.print("   \nTime: "); Serial.print(hr, DEC); Serial.print(":");
  Serial.print(minu, DEC); Serial.print(":"); Serial.print(sec, DEC);
  Serial.print("."); Serial.println(hundredths, DEC);

  Serial.print("Altitude(metres): "); Serial.println(gps.f_altitude());

  Serial.print("Speed(kmph): "); Serial.println(gps.f_speed_kmph());
  Serial.println();

  logs = SD.open("datalogs.csv", FILE_WRITE);  //open the datalog file on the sd card. If it doesn't exist on the card, create it.

  if(logs){//Start writing data to SD Card
    Serial.print("Writing to datalogs...");
    logs.println("\nLatitude: "); logs.print(latitude);
    logs.print("\nLongitude: "); logs.print(longitude);
    logs.print("\nDate: "); logs.print(mnth, DEC); logs.print("/");
    logs.print(dy, DEC); logs.print("/"); logs.print(yr);
    logs.print("   \nTime: "); logs.print(hr, DEC); logs.print(":");
    logs.print(minu, DEC); logs.print(":"); logs.print(sec, DEC);
    logs.print("."); logs.println(hundredths, DEC);
    logs.print("Altitude(metres): "); logs.println(gps.f_altitude());

    logs.print("Speed(kmph): "); logs.println(gps.f_speed_kmph());
    logs.print("\n");
    logs.println();

    logs.close(); //close the file
    Serial.println("done.");
    Serial.println("\n");
  }
  else{
    Serial.println("Error opening file.");
  }

  unsigned long chars;
  unsigned short sentences, failed_checksum;
  gps.stats(&chars, &sentences, &failed_checksum);
}

```

# Answer
You're trying to do too much (SD and Serial print operations) at the wrong time (GPS character receiving).

Most GPS devices will send several "sentences" per second, in a batch. `TinyGPS.encode` returns `true` after *each* sentence, so your code will try to write multiple sentences per second to the SD card. But it takes so long to open/write/close the SD card (and print to `Serial`) that the input buffer fills up and overflows. Here's a detailed description of what is happening.

You must wait until the GPS "quiet time" begins. Even then, you could have trouble, depending on how much data you need to save and print.

It may be possible to make it work with TinyGPS, but I eventually gave up in frustration and wrote the NeoGPS library to help address these problems. It can be configured to save just the data you need (via the configuration files), and it can be used to detect when the quiet time begins (see NMEAorder.ino and NMEAfused.ino). It uses much less RAM and takes much less time to parse the GPS characters. This will be important if you try to add the Ethernet libraries to the sketch.

If you still have trouble getting all the information written during the quiet time, you can use a companion library (e.g., NeoSWSerial) to handle the GPS characters *during* the RX interrupt.

Regardless, I would suggest replacing `SoftwareSerial` with `NeoSWSerial`. It, too, is much more efficient than the CPU-killer `SoftwareSerial`. It won't fix the main problem, but it will pay off later.
> 1 votes

---
Tags: arduino-uno, gps
---


# Question
Title: Signal pin of buzzer is connected with which Arduino uno pin
I bought a 3 pin buzzer. It has positive, negative and signal pin.

I don't understand how this signal pin should be connected with the Arduino.

Here is reported the description page of the buzzer.

# Answer
As I have read in the page you have linked, I think you should program the Arduino to provide an impulse to the signal (`s`) pin.

Therefore, to answer your question you can use any digital pin of the Arduino. And I guess that as long as the impulse last as long as the buzzer will produce a sound.

Here an example of code:

```
int buzzPin =  2;    //Connect Buzzer on Digital Pin3
void setup()
{
 pinMode(buzzPin, OUTPUT);
}
 void loop()
{
 digitalWrite(buzzPin, HIGH);
 delayMicroseconds(50);
 digitalWrite(buzzPin, LOW);
 delayMicroseconds(50);
}

```
> 1 votes

# Answer
Usually a buzzer only has two wires, positive and negative. The module you have bought though uses a transistor to drive the buzzer, which is a nice thing for very low power boards, which is not your case I believe.

Anyway, the module will take power from the positive and negative connections, allowing you to control it via the signal, from which very little power is drained.

How does a buzzer work? Actually to emit a sound via a buzzer you have to send a series of electrical pulses to the signal pin. The number of pulses per second (frequency, expressed in hertz, Hz) will determine the tone of the sound. higher the frequency, higher the pitch of the sound emitted.

Human ear is capable to detect frequencies between 20 and 20000Hz, but not everybody has such a broad perception, it decreases with age and not everybody is born with full range, so I advice to stay in the 2000-15000Hz range.

There is a nice library called Tone which helps you generate the correct signal for specific notes, allowing to even play some music via the buzzer (don't expect polyphony though!)

So, to play a note on your buzzer, assuming you have the buzzer signal pin tied to digital pin 6, you can just:

```
void setup() { /* empty */ }

void loop() {
    noTone(6);
    // play a note on pin 6 for 200 ms:
    tone(6, 440, 200);
    delay(200);
}

```

Also have a look at ToneMelody if you wish to emit specific notes (each note has its own particular frequency)
> 1 votes

---
Tags: arduino-uno, buzzer
---


# Question
Title: I can't get code transferred to my Arduino Mini Pro
About 3 years ago Sparkfun had a sale on Arduino Minis, so I bought 6 of them (3 x 3.3 V @ 16 MHz and 3 x 5 V @16 MHz). I used two of them for separate projects (everything worked flawlessly) then stored the rest. Then last night I grabbed one of the 5 V and 3.3 V Minis and tried to upload the Blinking LED program to them. But I kept getting this error:

```
avrdude: stk500_recv(): programmer is not responding

```

I'm getting similar results on all of these computers: Mac OS X 10.10, Mac OS X 10.7, and Windows 7. I tested with default drivers and I tried installing fresh drivers based on the HardwareID's of the devices. I used both the newest version of Arduino IDE and a few older versions.

I've tried two different USB devices: Sparkfun Basic FTDI and a Generic USB to Serial PL2303 similar to this one. They both produce the same error, however the FTDI seems to be somewhat able to communicate since the RX & TX lights are flashing as well as the Arduino LED. With PL2303, the LED is lit constantly.

While searching last night, I found a few forums where people suggested things like hitting the reset button and selecting different Arduino boards in the IDE.

# Answer
Things have changed in the three years since you last used your FTDI board.

Most importantly avrdude has changed.

You will most likely find that you can program your boards perfectly fine using Arduino IDE 1.0.1.

What has changed is that avrdude has been modified to counter a change in the FTDI drivers. It used to be that the FTDI drivers would pulse the DTR line when the port was opened, but that stopped happening with newer drivers. So AVRDude started asserting the DTR line instead. However it doesn't pulse it, it just holds it low.

The problem with that is if the DTR is connected direct to the RESET pin the main chip is held in reset mode all the time instead of it just being reset briefly to reset the board.

The "fix" is to place a 100nF capacitor between DTR and RESET instead of directly connecting it. That converts the steady low into a short pulse which resets the board and enters the bootloader.
> 2 votes

# Answer
For programming a Pro Mini, I find the CP2104 adaptor works better than the FTDI or PL2303 based units, on both Mac and PC. You can find the CP2104 adaptor from many sources, such as TxHang Electronic:

http://www.ebay.com/itm/USB-2-0-TTL-UART-6PIN-Module-Serial-Converter-CP2104-STC-PRGMR-Replace-CP2102-/200958955841?hash=item2eca165141

(You may need to install CP2104 software drivers on some platforms) This is how I wire them together:

* **CP2104\_________PRO MINI**

+ DTR------------DTR
    + 3.3V--------- - * NOT USED (VCC)
    + 5V --------- - -\* NOT USED (VCC)
    + TXD------------RXD
    + RXD------------TXD
    + GND-----------GND

Note: * While you may be able to power your (unloaded) Pro Mini from your CP2104 adaptor, it's better to use a separate supply that is appropriate for the version of the Pro Mini you use. Good luck. /DerrickA
> 0 votes

---
Tags: serial, usb, ftdi, arduino-mini
---


# Question
Title: Is that correct that input and output pins are not supposed to have current through them?
Are input and output pins not supposed to have current through them and only either apply voltage or "measure" it?

# Answer
> 3 votes
An output pin (on an AVR 8-bit board like an Arduino Uno) can pass up to 40mA (*absolute maximum*). It is recommended not to exceed 25mA. This is called *sinking current* when the output pin is set to LOW, and *sourcing current* when it is set to HIGH.

An input pin is what is known as *high impedance*. I.e., it looks, to the circuit connected to the pin, like an incredibly high value resistor connected between the input and ground. Because of that only very tiny currents will ever flow through it (unless you do something silly like plug it direct into the mains).

# Answer
> 3 votes
First, you can not apply a voltage to or with an I/O pin connected to a circuit, and have no current flow as a result. There is a limit to the current a given pin on a given device can pass without damage and that is specified in the device's datasheet. How much current a given pin and circuit will pass or try to pass depends on the external circuit and the circuit internal to the device. Majenko's answer (except possibly for the specific limits, depending on the device) is correct.

You haven't specified what device. Is this a generic question or is it specific to the AVR micro-controllers used in most Arduino boards? If the latter, the limits in @Majenko's answer are also correct.

# Answer
> 2 votes
What everyone else said.

It's difficult to measure voltage without taking at least a tiny trickle of current, and that's what input pins do.

Anything that is driven needs current to drive it (power = current * voltage). However, an arduino pin - as someone mentioned - should only ever be used to supply about 25mA. Drawing a heavier current than that can fry the chip.

V=IR, so, the resistance on an output pin should be no less than 200 ohms, hence the 330 ohm current-limiting resistor you put on an LED. Power is IV, so the maximum power you can safely get get is 125mW (oh, you can get more - but you may fry your chip). This translates directly into the maximum safe brightness of a LED, the strength\*speed of a motor, the loudness of a buzzer powered by an output pin.

Another big thing when trying to drive coils (motors, solenoids, relays) is that when you switch off the power to a coil, it generates a spike of voltage going the other way. This spike also can fry the chip. This is why relay shields are a thing - they contain electronics to deal with this back-emf. If you want to drive a motor and don't want to buy a shield, look into darlington array chips. I used one to run a stepper - worked perfectly.

So.

* Inputs in theory need almost no current - but they do need that tiny trickle.
* Outputs must have current to do any work. The amount you can get off the board without frying it is limited.

---
Tags: voltage-level, current
---


# Question
Title: What minimal resistance should be between an input and output pin not to burn Arduino?
So, I'd like to put a button between input and output pins to read when button is pressed. What minimal resistance should I add to the scheme not to burn Arduino when the button is pressed? Does this value depend on Arduino model?

# Answer
Looking towards the high end of recommended (vs absolute maximum) current and considering Ohm's law at a 5v difference if two outputs are trying to drive each other to opposite values, you would probably get away with as little as 250 ohms. But in most cases that would needlessly waste power, and in the case of multiple instance you could start totaling towards the limit of power supply current for the chip overall.

Typical values for external pull up resistors are more in the range of 1K-10K though higher is not uncommon - the internal pullup which you can optionally activate by setting the output state of an *input* pin high has a value of several tens of kilo ohms. Lower values will consume more power, higher values may be less reliable in a noisy situation.
> 1 votes

# Answer
To read a button, normally you hook one end of the button to ground and one end to a pin in INPUT\_PULLUP mode. Normally the pin reads 'high' because it is connected to +5v with a biggish resistor inside the arduino. When you press the button, it shorts out to ground and the input reads 'low'. The chip already has suitable resistors in it to handle this, and you don't need to worry about it. Just connect one end of your button the the pin, the other to the chassis, INPUT\_PULLUP and away you go.

Output pins should have no less than 250Ω on them.

Beats me why you are thinking of connecting an output pin and an input pin together.
> 0 votes

---
Tags: voltage-level, current, voltage-protection
---