# Question
Title: Why can't the Atmel ATtiny family delay over a minute?
I have some really simple code and tested on an 8 MHz ATtiny85 and ATtiny2313. It's basically a blocking blink:

```
int relayPin = 7;

long offPeriod = 1 * 60 * 1000;
long onPeriod = 1 * 60 * 1000;

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

void loop()
{
  digitalWrite(relayPin, LOW);
  delay(onPeriod);
  digitalWrite(relayPin, HIGH);
  delay(offPeriod);
}

```

When I assign `onPeriod` and `offPeriod` to be `1 * 1000` (1 second), the LED will blink as expected. When I add the 60 second multiplier in, it seems to fail.

For the ATtiny85 I use Arduino Pin 4 (physical pin 3) and for the ATtiny2313, I use Arduino pin 7 (physical pin 9).

I program through the Arduino IDE using boards manager to install the ATTinyCore library for the ATtiny2313 and this for the ATtiny85.

Am I doing something wrong here?

It looks like if I throw the delay in a function, and then invoke it with however many seconds I want, it will work. This is not good as it remains blocking. So perhaps the correct way to do this is to grab timestamps. Here's the somewhat working code:

```
int relayPin = 4;
unsigned long offPeriod = 60;
unsigned long onPeriod = 60;

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

void loop()
{
  digitalWrite(relayPin, LOW);
  delaySeconds(onPeriod);
  digitalWrite(relayPin, HIGH);
  delaySeconds(offPeriod);
}

void delaySeconds(int s) {
  for (int i = 0; i < s; i++) {
    delay(1000);
  }
}

```

# Answer
> 8 votes
This is absolutely nothing to do with "why can't the atmel attiny family delay over a minute?". It is all to do with the way that C++ works.

See my page about Integer arithmetic and overflow.

To excerpt from that:

---

On the Arduino (Uno) platform, what do you think will be printed here?

```
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  Serial.println (30000 + 30000); // twice 30000
  Serial.println (60 * 60 * 24);  // seconds in a day
  Serial.println (50 / 100 * 1000); // half of 1000
  }  // end of setup

void loop () { }

```

Did you guess:

```
60000
86400
500

```

Nope!

It prints:

```
-5536
20864
0

```

This is because of **integer arithmetic**. If the compiler can, it treats an numeric literal (like 60) as an int type, which means it has the range -32768 to +32767.

And, arithmetic is done using the type of the largest argument, which means the arithmetic in each case is done as 16-bit arithmetic, and thus it overflows once it reaches 32767.

For example, 30000 + 30000 = 60000 which is 0xEA60 in hex. Unfortunately, 0xEA60 is exactly how -5536 is stored in an int type, which is why it prints -5536.

Meanwhile, 60 * 60 * 24 = 86400 which is 0x15180 in hex. As that doesn't fit in 16 bits, it is truncated to 0x5180 which is 20864 in decimal (as printed).

Finally, in integer arithmetic 50/100 is zero, multiply zero by 1000 and you still get zero, which is why the final result is zero.

---

## Solution

First, you can add a suffix to numeric literals (eg. L for long, or UL for unsigned long), and add a decimal place to floats, like this:

```
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  Serial.println (30000L + 30000); // twice 30000
  Serial.println (60L * 60 * 24);  // seconds in a day
  Serial.println (50.0 / 100 * 1000); // half of 1000
  }  // end of setup

void loop () { }

```

Now we get:

```
60000
86400
500.00

```

You only need to help out with the first literal, once the compiler knows we are using longs (or floats) it sticks with them for the expression.\*

---

* It's actually somewhat more complex than that as this link explains: Understand integer conversion rules.

The compiler "promotes" a value in an expression to match another "higher-ranked" type, under certain circumstances. For example, adding an **int** and a **long** will result in the **int** being promoted to a **long** (regardless of whether it appears first in the expression or not). However if an **int** is being added to another **int**, it will not promote them to a **long**, even though the result may not fit into an **int**.

# Answer
> 4 votes
These are the problem lines:

```
long offPeriod = 1 * 60 * 1000;
long onPeriod = 1 * 60 * 1000;

```

Even though `long` should hold the result, integer operations in C++ are still done in `int` by default. And on AVR `int` is 16 bits. The fix is to tell the compiler what size the intermediate result should be:

```
long offPeriod = 1 * 60L * 1000;
long onPeriod = 1 * 60L * 1000;

```

# Answer
> -1 votes
According to AVR libC the implementation of the delay function has a limited value range that varies with the F\_CPU macro definition. So your `delaySeconds(int)` function is the only solution.

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


title: Arduino servo motor on pushbutton

text:
# Question
Title: Arduino servo motor on pushbutton
I'm working on my first arduino project and i have my first problem dealing with servo motor , i'm trying to control the servo from my pc with this code but it just spining :

```
  #include <Servo.h>

Servo servo1;
long num;

void setup()
{
   servo1.attach(7);
   Serial.begin(9600);
   Serial.print("Enter Position = ");
}

void loop()
{
  while(Serial.available()>0)
  {
    num= Serial.parseInt();
    Serial.print(num);
    Serial.println(" degree");
    Serial.print("Enter Position = ");
  }
  servo1.write(num);
  delay(15);
}

```

this is my setup

# Answer
I have reformatted your code and the problem becomes very clear (to me).

```
void loop()
{
  while(Serial.available()>0)
  {
    num= Serial.parseInt();
    Serial.print(num);
    Serial.println(" degree");
    Serial.print("Enter Position = ");
  }
  servo1.write(num);
  delay(15);
}

```

You are getting some input from the user and then setting the servo to that point.

When there is no data in the Serial buffer you set the servo to the value of write and delay 15ms before checking the buffer again.
I think what you want to do is if there is no data then you don't want to change the Servo position. In short move the `servo1.write(num);` line inside the } of the while loop.

Now much more importantly the first time you enter loop() you won't have any data there so the servo will be moved to the number held in `num` which is? Undefined, it could be anything at all from 0 to 4294967295 and if its the upper end of that it will take a while for the servo to get there, it might seem like all it does is spin. **ALWAYS INITIALIES VARIABLES BEFORE USE** :)

A minor point, your while loop could be, probably should be an if statement. That will prevent a cat sitting on the keyboard and blocking the servo movement.
> 0 votes

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


# Question
Title: How to use relay shield to control dc motor speed and direction?
I tried l298n before but its output voltage wasn't high

so I use relay shield but it seems that the car can only go forward or stop

Can I control the speed and direction of dc motors?

# Answer
Using a mechanical relay to control the speed is not a good idea. But you can control the directions.

I prefer you to use Solid state relays (SSR) to do this. Arrange 4 SSR as Hbridge and Use PWM to control the speed.

refer this

or you can use the devices like this which has direction control as well.
> 1 votes

# Answer
Yes you can, but the easiest way is by using a "motor shield". There are more options than just L298N.

Are you sure it was the voltage that wasn't high enough, its normally the current (Amps)?

To do it with a relay you need to change the polarity of the feeds to the motor. You could do this with 2 relays both connected all the time, but if you close the wrong one, you will short everything. It would be better using a motor controller.
> 0 votes

# Answer
Most refer to relays when talking about mechanical devices which are either closed or open. If you arrange several in an H-bridge configuration, you can make you car go forward, stop and reverse. But controlling speed is not possible.
> 0 votes

---
Tags: motor, relay
---


# Question
Title: Working with Seed BLE Shield and Adafruit Feather BLE
Long story short: I need to pair these devices:

* Arduino UNO with Seeed BLE Shield
* Adafruit Feather 32u4 Bluefruit LE.

The Seeed shield is configured and able to connect and communicate via the UART to an Android phone by HM BLE Terminal app from Google Play Store.

I can also connect the phone and Feather. The two independent connections work really well but a problem occurs when connecting the Seeed shield with Feather. Connection isn't troubling No errors are reported but I can't send/receive any data via the serial monitor (I'm using bleuart\_cmdmode or bleuart\_datamode from the Adafruit examples).

Basically my question is how to make them work: HM-11 module with BLE and the Adafruit board (nRF51822 chipset from Nordic).

# Answer
Although the nRF51822 supports Central (master) mode, the Adafruit Feather's firmware only support's Peripheral (slave) mode.

> The Bluefruit LE firmware from Adafruit is currently peripheral only, and doesn't run in Central mode, which would cause the module to behave similar to your mobile phone or BLE enabled laptop.
>
> At some point we might consider a new firmware image offering this, but since 98% of the uses cases for BLE involved running as a peripheral we've concentrated all of our development effort there for now.
>
> https://learn.adafruit.com/adafruit-feather-32u4-bluefruit-le/faq#faq-2

The HM-11 on your Seeed shield **is** capable of Central (master) mode though. This means your Uno will play the part that your Android phone was playing when you connected the Feather to the terminal app.

To set your HM-11 to Central mode, run the following AT command.

```
AT+ROLE1

```

Example code for the HM-11

---

Alternatively, you could burn the S120 Soft Device and your own custom firmware onto the Feather's nRF51822. You can find all the docs, tools, and Soft Device images on Nordic's website.
> 1 votes

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


title: Using logical operators

text:
# Question
Title: Using logical operators
This is a snip it of code from a program I am writing. I have the program turn an LED on and if a button is pressed when the LED is on I want it to add to a counter and print the counter value. The problem seems that my if statement is skipped. Right now the while loop is setup for 5 seconds using millis() and stays off using a short delay. This part (button\_press\_9())) is a function call to a Boolean I have setup for debouncing. If I put the function call in an if statement by its self for example to test it. It works and will turn an LED on and off. It seems the combination of the two is incompatible.

Thank you in advance.

```
unsigned long previousMillis = millis();
unsigned long currentMillis = millis();

while ((currentMillis - previousMillis) < onTime)
{
    digitalWrite(ledPin4, HIGH);
    if (ledPin4 == HIGH && (button_press_9()))
    {
        counter++;
        Serial.println(counter);
        currentMillis = onTime * 100;
    }
    currentMillis = millis();
}
digitalWrite(ledPin4, LOW);
delay(1000);

```

# Answer
> 1 votes
You should use

```
if (digitalRead(ledPin4) == HIGH && (button_press_9()))

```

instead of

```
if (ledPin4 == HIGH && (button_press_9()))

```

---
Tags: programming
---


title: Use a 2.8" TFT with my Leonardo

text:
# Question
Title: Use a 2.8" TFT with my Leonardo
for 2.8" diagonal color touchscreen TFT:

Readme states: "Works with any classic Arduino '328. Solder closed three jumpers to use the ICSP header for use with Leonardo or Mega"

What should I solder? See image.

# Answer
> 0 votes
It looks like that display doesn't have a touch screen, only a tft and sd card. The modifications you would need to make pertain only to the SD card and the nonexistent touch screen interface. The tft portion should work with any arduino since it is a bit banged 8 bit parallel interface.

---
Tags: arduino-leonardo, tft
---


# Question
Title: Having a problem to control digital servo with HC-06 bluetooth module
There are two problems to control digital servo(HD-1810MG) and HC-06 bluetooth module connection.

1. When I put a specific number to servo(in the video, I put 45), it shakes too much and shows useless movements before get to the right angle. I have no clue why this happens. Should I add more code to control it correctly?

This is my code.

```
#include SoftwareSerial.h
#include Servo.h

Servo myServo;
int TxD = 10;
int RxD = 11;
SoftwareSerial bluetooth(TxD, RxD);

void setup() {
  myServo.attach(9);
  Serial.begin(9600);       // start serial communication at 9600bps
  bluetooth.begin(9600);
}

void loop() {
  if (bluetooth.available()>0)
  {
    int servopos = bluetooth.read();
    Serial.println(servopos);
    myServo.write(servopos);
    delay(100);
  }
}

```
2. I used Nexus 5X and apk app to pair with HC-06. It pairs well at the first time of connection, but it loose connection after servo moved once. Application said it is connected with bluetooth, but HC-06's LED is blinking(which means disconnected). How can I maintain connection with HC-06?

This is my board.

And I made apk app using MIT App Inventor 2.

I'm so new to arduino and I'm not in major of engineering. Please give me an advice!

# Answer
> 1 votes
1. let have a look at following line of code:

```
int servopos = bluetooth.read();

```

I think that you are thinking that if you type in **1** in your Bluetooth application. **bluetooth.read()** will pass that **1** to **sevopos**. But, that's what not happens. What actually happens is that it will pass the **ASCII** value of whatever you type in you app, to integer. So, if you have typed in **1**, it will pass **49** to **servopos**.

> I put 45

Now, think about it. when you type in **4** of this **45**,

```
bluetooth.available()>0

```

becomes **true**.

```
int servopos = bluetooth.read();

```

**bluetooth.read()** will pass **52** (ASCII of **4**) to **servopos**. Next,

```
myServo.write(servopos);

```

**myservo** will move your servo to lets say **52** degrees. and then there will be a **delay**.

Now, when you type in **5** of this **45**, the procedure will be repeated and your servo will be moved again by **53** degrees.

Now, you might be wondering that why **4** and **5** sepratly? Well, all these intructution are being executed in **MHz**s. and secondly, you, yourself has programmed that **if** loop you read just **once character**. Yes, it will read **character by character**.
2. > but it loose connection after servo moved once

I think your servo is drawing too much current from Arduino Board which results in a drop in net voltage. And hence your HC-05 (kind of) tuns off. This is what happens most of the time.

# Answer
> -1 votes
It is not a problem in serial connection. I have experienced this problem when I was trying to make a biped robot using 12 servos. It is the programming bug where Arduino does not use its timers properly. You can say that it is arduino limitation. There are two main solutions : 1). Use Raspberry Pi instead of arduino. 2). Secondly you can make a small servo controlling shield of TLC5940 IC + servo controlling library... Here is he Link: http://bildr.org/2012/03/servos-tlc5940-arduino/

---
Tags: bluetooth, servo, hc-06
---


title: Arduino audio output circuit

text:
# Question
Title: Arduino audio output circuit
I am looking to build my own arduino-based board that, when triggered, will play a file (line out, not amped to a speaker). Most of the audio shields I see are more complicated than I need, so what I'm wondering is what is the barebones circuit I would need for audio output? I've got the atmega and SDcard side fine, I'm just not sure what IC's are involved in audio output. WAV's are fine so I don't have to deal with mp3 decoding.

PS feel free to move this to electronics instead of arduino, I'm not sure where it belonged since it's built into an arduino board but is more the electronic circuitry.

# Answer
> 1 votes
If you don't care much about quality then all you need is two capacitors and a resistor. Use PWM to create the audio (there is a timerpcm pr something library that will do it). The resistor and pne capacitor form a low pass filter for the PWM, and the other capacitor removes the dc offset.

```
----/\/\/\----+----||------
              |
             ---
             ---
              |
              _
              -

```

---
Tags: audio, pcb-design
---


# Question
Title: Problem with code for IR remote controlled robot
I recently wrote the code for this project but it's weird because when I press button on the remote nothing shows up on the Serial Monitor and consequently the robot doesn't respond. I know it's not a hardware issue because when I used the IRrecv Demo sketch values were displayed on the serial monitor

Please tell me what's wrong! I'm sure there are a lot of talented programmers out there!!

```
#include <IRremote.h>
#include <AFMotor.h>
AF_DCMotor rightMotor(1); // Right motor connected to port 1
AF_DCMotor leftMotor(2); // Left motor connected to port 2
IRrecv irrecv(A2);// IR receiver connected to pin A2(ANALOG PINS ON MOTOR             SHIELD USED AS DIGITAL INS!)
decode_results results;
#define Straight 0xC1CC42BD
#define Right 0xC1CCA25D
#define Left 0xC1CC22DD
#define Back 0xC1CCC23D

void setup(){
  Serial.begin(9600); // Establishing Serial Communication, THIS IS     IMPORTANT!!
  irrecv.enableIRIn(); // Start the receiver
}
void loop() {
  if (irrecv.decode(&results))
  {
      Serial.println(results.value, HEX);

      if((results.value)== Straight)
      {
      moveForward();
      }
      if((results.value)== Right)
      {
        turnRight();
       }
      if((results.value)== Left)
      {
        turnLeft();
      }
      if((results.value)== Back)
      {
        moveBackward();
      }
      else
      {
        Stop();
      }
      irrecv.resume();
  }
  delay(100);
}

void moveForward() {

    leftMotor.setSpeed(255);
    rightMotor.setSpeed(255);
    leftMotor.run(FORWARD);
    rightMotor.run(FORWARD);
}

void turnRight(){

  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
  leftMotor.run(FORWARD);
  rightMotor.run(BACKWARD);
  delay(400);

  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);
}

void turnLeft() {

  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
  leftMotor.run(BACKWARD);
  rightMotor.run(FORWARD);
  delay(400);

  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);
}
void moveBackward() {

    leftMotor.setSpeed(200);
    rightMotor.setSpeed(200);
    leftMotor.run(BACKWARD);
    rightMotor.run(BACKWARD);
}

void Stop(){
    leftMotor.setSpeed(0);
    rightMotor.setSpeed(0);

}

```

# Answer
You are using two libraries (Arduino-IRremote & Adafruit-Motor-Shield-library) which both use Timer2 on the microcontroller.

The motor library actually changes the setup of timer 2 (see line 92 of AFMotor.cpp) which will disrupt the timing that the IR sensor uses to determine the IR code received.

As far as I can see, the IR library is using Timer2 only. This means you should be able to change your motors over to port 3 & 4 which use Timer0 instead.

```
AF_DCMotor rightMotor(3); // Right motor connected to port 3
AF_DCMotor leftMotor(4); // Left motor connected to port 4

```
> 0 votes

# Answer
Try replacing you loop function with this one. It won't fix it.

```
void loop()
{
    if (irrecv.decode(&results))
    {
        Serial.println(results.value, HEX);

        switch (results.value)
        {
        case Straight:
            moveForward();
            break;
        case Right:
            turnRight();
            break;
        case Left:
            turnLeft();
            break;
        case Back:
            moveBackward();
            break;
        default:
            Stop();
        }
        irrecv.resume();
    }
    else
    {
        Serial.println ("Nothing received");    // This message will annoy you so comment it out as soon as you are happy with what is happening.
    delay(100);
}

```

The switch statement is just a neater way of doing your ifs. The Nothing received message will show you if decode is ever returning. If it is returning you need to work out why it is returning false, by looking in the library code. If it isn't returning then you need to look in the library code and see why. If it is returning, but not giving you an expected value, you need to look in the library code and see why.

Sorry but from what you describe it seems to be an issue with the library or your use of it, could be anything, but when you can get some more info post it back here.
> 0 votes

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


# Question
Title: How to turn servo to a specific location and then turn over
I work on my first arduino car project and i want to turn my servo to a position with a letter input

This is my code so far

```
 #include <Servo.h>
Servo servo;

 void setup() {
 Serial.begin(9600);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
 }

 void loop() {

 if(Serial.available()>0){
 int  caz=Serial.read();
 switch(caz)
{
  case 'w':
      digitalWrite(8,LOW);
      digitalWrite(7,HIGH);
      break;
  case 's':
      digitalWrite(7,LOW);
      digitalWrite(8,HIGH);
      break;
  case'd':
       servo.attach(12);
       servo.write(0);
       break;
  case'a':
       servo.attach(11);
       servo.write(180);
       break;
   default:
       digitalWrite(7,LOW);
       digitalWrite(8,LOW);
       servo.attach(0);
  }
}

```

when i input 'a' or 'd' it starts turning until i input something else and i want it to stop after 10-30 degree .

And also i would like to do that to my motor , moving a bit when i input the key.

# Answer
> 1 votes
Rather than writing to 180 and 0 write to a variable.

```
static const int MovementAmount = 30; //degrees
int position = 90;  // 90 is the start position.
...
case 'd':
   servo.attach(12);
   position += MovementAmount;
   if (position > 180)
   {
     position = 180;
   }
   servo.write(position);
   break;

```

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


title: connecting 3.3V to +3V

text:
# Question
Title: connecting 3.3V to +3V
Well, I hope this question won' t be buried to the dark depths of this forum as my previous q' s:) But I suppose it won' t this time cause it's pretty short without this introduction part...

I have an Arduino pro mini works with 3.3V and in the other hand, I have a DS1307 DIP ic, works with +3V. I was wondering if I could connect the ic to my Arduino directly.

Thats all. Thanks already:)

# Answer
The 3V input on the DS1307 is for a 3V battery, usually a CR2032 or similar. The *supply* voltage of the DS1307 is 5V, which means that it won't work with a 3.3V Arduino without a separate supply and level shifter.
> 2 votes

---
Tags: electronics, components, voltage-protection
---


# Question
Title: Voice recognition module: avrdude: stk500_getsync(): not in sync: resp=0x00
I am using a GeeeTech voice recognition module, I have recorded my voices using CoolTerm, and imported these voice commands in my sketch. However, when I plug in that voice recognition module, an error gets thrown: `avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00`; otherwise, it uploads normally. How can the computer and the Arduino lose connection when the voice recognition module gets plugged in? . I have checked my com ports, and checked the everything that it is connected to is correct.

```
#include <avr/sleep.h>
#include <avr/power.h>
//#include "math.h"
//This sketch is a metronome, in which each led pin shows one beat.
/**************************************/
const int speaker = 13;//speaker at pin 13
int ts = 6;//highest led pin
int count = 3;//"beat 1 pin"
const int keyPin = 11;//button to change time signature
const int keyPinR = 10;//button to change rhythm
const int keySwitch = 2;//sleep mode/wake up button

//All pins below use a pull-up resistor, so the states are inverted
int buttonState = LOW;
int buttonState2 = LOW;
int switchState = LOW;
int silentState = LOW;

int bpm = 120;//you do not need to know this,
//it's just a variable for the potentialmeter to change the tempo
int comdata;

int rthm = 1;//rhythm
int pressed = 0;//
long silent = 0;

byte com = 0; //reply from voice module
/**************************************/

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

 for(int thisPin = 3;thisPin <= ts;thisPin++)
  {
     pinMode(thisPin,OUTPUT); //initialize thisPin as an output
     pinMode(12, INPUT); //potentialmeter for changing tempo

   //Pin 9 to 11, along with pin 2, are all push buttons with pull-up resistors
    for(int i = 9; i<=11; i++)
    {
      pinMode(i, INPUT);
      digitalWrite(i, HIGH);
    }
    pinMode(2, INPUT);
    digitalWrite(2,HIGH);
  }
delay(2000);

//imported voice commands
Serial.write(0xAA);
Serial.write(0x37);
delay(1000);
Serial.write(0xAA);
Serial.write(0x21);

 Serial.print("Type in beats per minute");

}

/****************************************/
void loop()
{
  turnOn();
  getTS();
  getVoiceCommand();
}

void turnOn()
{
    buttonState = digitalRead(keyPin);//key for
    buttonState2 = digitalRead(keyPinR);
    switchState = digitalRead(keySwitch);
    silentState = digitalRead(9);

    if(switchState==LOW) pressed++;

    if(pressed!=0)
    {
      sleep_enable();
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);
      attachInterrupt(0, interrupt, LOW);
      sleep_cpu();
    }

  else{
    //The beat starts at pin 3, runs in consecutive pins, and ends at pin 8 at maximum

     if(buttonState==LOW){//changing time signature - up to 5 beats
            ts++;
          if(ts==8) ts = 3;  //8 - 3 = 5 beats max
     }
     if(buttonState2==LOW){//changing rhythm - quarter note to eighth, then
             //triplets and sixteenths, back to quarter notes
           rthm++;
          if(rthm==5) rthm = 1;
     }
     if(silentState==LOW) silent++; //if silent key pressed, go to silence (only LED's showing)

      runMetronome();//Run the metronome
     }
  }

  void runMetronome(){
    for(int thisPin = 3;thisPin <= ts;thisPin++)
      //LED's blinking beats (thisPin - LED pin (beat number + 2))
      {
           for(int r = 1; r<=rthm; r++){//nested loop for the rhythm
               bpm = pulseIn(12, HIGH);//pin 12 - tempo potentialmeter
               digitalWrite(thisPin,HIGH);//each LED blinks
               pinMode(13,OUTPUT); //pin 13 - speaker

              silent%2==0 ? noTone(13) : (count==3 && r==1 ? tone(13,4400,80) :
                   r==1 ? tone(13,2500,80) : tone(13,2200,60));
              delay((bpm-52)/rthm);
              digitalWrite(thisPin,LOW);//turn each off as we proceed to the next beat (LED)
              pinMode(13,INPUT);//speaker input
            }
          count++;//beat++

          if(count>ts) count = 3; //go back to beat 1
        }
    }

  void interrupt()  {
      sleep_disable();
      detachInterrupt(0);
  }

   void getTS(){
      if(Serial.available()>0){
          comdata = Serial.read();
          switch (comdata){
              case '1': ts = 3; break;
              case '2': ts = 4; break;
              case '3': ts = 5; break;
              case '4': ts = 6; break;
              case '5': ts = 7; break;
            }
     }
   }
     void getVoiceCommand(){
        while(Serial.available()){
            com = Serial.read();
            switch(com){
                case 0x11: ts = 3; break;
                case 0x12: ts = 4; break;
                case 0x13: ts = 5; break;
                case 0x14: ts = 6; break;
                case 0x15: ts = 7; break;
              }
          }
      }

```

# Answer
> 1 votes
It's not loosing connection, there just can't be two devices on the same serial port (I suppose this setup)

You can use software serial for VR module, arduino with more hardware serials (=mega) or you can use another arduino as ISP programmer.

---
Tags: arduino-uno, avrdude
---


title: Powering Down Arduino MKR1000

text:
# Question
Title: Powering Down Arduino MKR1000
The MKR1000 is still pretty new and I'm having a hard time getting good information on it. I'm using the Arduino IDE but don't find any functions to sleep the MKR1000. Most libraries I encounter are for AVR chips while the MKR1000 has an ARM chip. I want to put it to sleep until an external interrupt is called. I also use the millis() function, will this function be rendered useless if it goes to sleep?

In the data sheet for the ATSAMD21 it talks about the Wait for Interrupt instruction which puts the machine to sleep but it doesn't say how to call the instruction. How can I do this in the Arduino IDE?

# Answer
The rocketscream low power library looks like it supports the ATSAMD21.
> 0 votes

---
Tags: arduino-ide, sleep, mkr1000
---


title: Board won't show on one of my computers

text:
# Question
Title: Board won't show on one of my computers
I have the same problem with these two boards: Ruggeduino (Uno compatible) and DFRobot Romeo 1 (Duemilanove compatible). On one of my Macs (a Macbook Pro running 10.11.4), I can see a new port /dev/cu.usbmodem641 or /dev/a4005g3t depending on the board. On the other computer (a Mac Mini late 2014), they just won't show. Same cable, same boards, and no hub. I don't know where to look to see an indication of a failure of some sort.

These two ones use a type-b USB socket (printer style)

Also on the Mac Mini that won't see any of those boards, I can connect an EtherMega2560 (Arduino Mega 2560) which happens to use a micro USB socket. I don't know if that is related to the problem.

Both computers run the same OS (OS X 10.11.4) and the latest version of Arduino.

Here is a difference (found in /var/log/system.log):

On the working computer:

```
Mar  3 22:20:42 pc101 kernel[0]: AppleUSBFTDI: fInBufPool,kMaxInBufPool 8,64
Mar  3 22:20:42 pc101 kernel[0]: AppleUSBFTDI: Version number - 5.0.0, Input buffers 8, Output buffers 16

```

On the non working one:

```
cfprefsd[114]: BUG in libdispatch: 15E49a - 1718 - 0x0

```

..

# Answer
My Ruggeduino stopped showing up as a serial device under El Capitan (10.11.6). I was able to fix this by installing/updating the VCP drivers for Silicon Labs USB devices available here:

https://www.silabs.com/products/mcu/Pages/USBtoUARTBridgeVCPDrivers.aspx

After installing the Mac driver the Ruggeduino shows up as SLAB\_USBtoUART and works fine with the Arduino GUI.
> 2 votes

---
Tags: serial, usb, osx
---


title: TCS230 Low Pulse Length with Arduino

text:
# Question
Title: TCS230 Low Pulse Length with Arduino
My son and I are attempting to connect a TCS230 Color Sensor to an Arduino Nano using the tutorial at TopTechBoy.com (http://www.toptechboy.com/arduino/lesson-15-super-cool-arduino-color-sensor-project/) as guidance.

Everything seems to be working except that the conversion from pulseIn to RGB used on TopTechBoy is expecting a maximum pulse count of 102,400. Instead I am receiving pulseIn readings with a maximum of 2000.

Our Wiring

S0 - GND
S1 - 5V OE - No Connection (Tried GND)
GND - GND
S2 - D8
S3 - D7
OUT - D4
VCC - 5V

Our Code:

```
int S2 = 8;
int S3 = 7;
int OUT = 4;

void setup() {

Serial.begin(9600);
pinMode (S2, OUTPUT);
pinMode (S3, OUTPUT);
pinMode (OUT, INPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  int red , green, blue;

  red = getRed();
  Serial.print("Red : "); Serial.println(red);
  Serial.println("**********************");
  Serial.println();

  blue = getBlue();
  Serial.print("Blue : "); Serial.println(blue);
  Serial.println("**********************");
  Serial.println();

  green = getGreen();
  Serial.print("Green : "); Serial.println(green);
  Serial.println("**********************");
  Serial.println();

  delay(3000);

}

int getRed(void){ return getColor(0, 0, 19000, 24000); }

int getGreen(void){return getColor(1, 1, 13600, 19200);}

int getBlue(void){return getColor (0, 1, 16400, 21600);}

int getColor(int s2Value, int s3Value , int typicalPulseWidth, int maxPulseWidth){

  long divideForScale = typicalPulseWidth / 255 ;

  digitalWrite(S2, s2Value);
  digitalWrite(S3, s3Value);

  unsigned int pulseWidth = pulseIn(OUT,LOW);

  Serial.print("Pulse Width : "); Serial.println(pulseWidth);

  unsigned int rColor = pulseWidth / divideForScale ; //401.5686274509804
  Serial.print("Response Color - Inverted : "); Serial.println(rColor);

  rColor = 255 - rColor ;
  Serial.print("Response Color - Final : "); Serial.println(rColor);

  delay(500);

  return rColor ;

}

```

The pulses appear correct, just out of scale. Red items produce short Red pulses and so on.

I tried to correct for the shorter pulses by using the Typical Output Frequency (f0) found on page 4 of the data sheet. I'm not sure if this is the right use of this frequency output spec.

http://www.unihedron.com/projects/darksky/tcs230-e33.pdf

Lowering the max possible pulses per second from 100,400 to around 20,000 gave us a little more variation between RGB values, but still the output is nothing like the expected color.

Can anybody offer some insight as to why the TCS230 pulse count is far fewer than the TTB code expects and what can I do to fix either the pulse count or the scale? Kind regards.

Output from Measuring a Blue RFID Keyfob: divideForScale : 74 Pulse Width : 673 Response Color - Inverted : 9 Respponse Color - Final : 246 Red : 246 \**********************

```
divideForScale : 64
Pulse Width : 376
Response Color - Inverted : 5
Respponse Color - Final : 250
Blue : 250
**********************

divideForScale : 53
Pulse Width : 737
Response Color - Inverted : 13
Respponse Color - Final : 242
Green : 242
**********************

```

# Answer
> 1 votes
Connect S0 to 5V to get 100% OUTPUT FREQUENCY SCALING.

Currently, with S0 LOW and S1 HIGH, you get 2% OUTPUT FREQUENCY SCALING. Which would explain the 50 times to low values you get (100% / 2% = 50).

# Answer
> 0 votes
From the project page (a comment by Marius David) it seems some integer datatypes may not be the same on different platforms. If he is correct, you may be working with a 16 bit pulseWidth while 32 bits are needed.

Try using an `unsigned long` for the `pulseWidth` variable.

---
Tags: sensors, arduino-nano
---


# Question
Title: Can I convert 3.7V to 5V's using 3.3v to 5v converter
THe product: (https://www.sparkfun.com/products/12009)

So guys, here' s a pretty simple but important question for me: Can I convert 3.7V (li-po battery's voltage level) to 5V's (I do have arduino pro mini running on 5 volts) using 3.3v to 5v converter (picture shown above...) ??

Thanks already...

# Answer
> 2 votes
No. That is a level shifter. It uses a low voltage (3.3V) to switch a separate high voltage (5V) supply to create different logic levels.

It does not convert voltage, it merely switches.

To create 5V from 3.7V you need either a *boost converter* (inductor based circuit) or a *charge pump* converter (capacitor based circuit).

---
Tags: voltage-level, arduino-pro-mini
---


# Question
Title: Pin 0 (62) you are trying to use is not supporting interrupts
Using `RCLib` (github) I'm getting this error. The trick is that the RCLib example works on it's own but does not work in my program (github).

**Serial Output "Error"**

```
Pin 0 (62) you are trying to use is not supporting interrupts
Pin 1 (63) you are trying to use is not supporting interrupts
Pin 2 (64) you are trying to use is not supporting interrupts
Pin 3 (65) you are trying to use is not supporting interrupts
Pin 4 (66) you are trying to use is not supporting interrupts
Pin 5 (67) you are trying to use is not supporting interrupts

```

# Answer
> 2 votes
It is quite right. Those pins aren't interrupt pins. What you want to do is make it use *PinChange interrupt* pins instead.

This can (by the look of things) be done by including the PinChangeInt.h library before including the RCLib library.

---
Tags: arduino-mega, interrupt
---


title: Arduino Mega LCD

text:
# Question
Title: Arduino Mega LCD
I am interfacing an LCD with an Arduino. Sometimes it shows nothing after uploading the program. What should I do?

# Answer
An LCD will show blocks like that if it isn't initialized correctly. You may have an intermittently-bad connection on one or more of the control lines. \[But see edit 1, below, regarding contrast adjustment.\]

To diagnose intermittent connections, you could run a sketch that repeatedly initializes the LCD and then displays different sets of characters for a few seconds. This will allow you to wiggle different pins and find out which is responsible for the bad connection.

To avoid intermittent connections, you could use a shield with soldered pins, or could get multipin shells to replace the single-pin shells of the Dupont-type connectors shown in the photograph. Having adjacent connectors fixed in a single multipin shell results in more-stable connections.

---

*Edit 1:* As noted in a comment, blocks appearing on both lines is typical of contrast adjustment problems or missing contrast voltage. On the other hand, blocks appearing on just the first line is typical of incorrect initialization, which could be caused by poor connections or by software errors.

---

Below is a sketch that repeatedly initializes the LCD and then displays different sets of characters for a few seconds each.

Note, if you don't have the `Streaming.h` contributed library installed, you can get `Streaming5.zip` from arduiniana.org.

Note, if not using an I2C-interfaced LCD, change the included LCD library .h from `LiquidCrystal_I2C.h` to whatever is appropriate, and remove I2C-address-related stuff from the sketch. If you are using an I2C-interfaced LCD on a known fixed address, remove the `lcd.setAddress(address);` and `lcd.getAddress(address);` stuff. Those routines are not part of the usual LCD libraries; they probably can be added by subclassing `LiquidCrystal_I2C`, but on my system I added code as shown after the sketch.

---

```
/* Screen-test sketch for PCF8574/PCF8574A/PCF8574T I2C LCD Backpack
Uses library from https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads GNU General Public License, version 3 (GPL-3.0) */
#include <Streaming.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

enum { LCDcols=16, LCDrows=2 };        // # of rows and cols on LCD
enum { LCDaddr2=0x27, LCDaddr3=0x3F}; // For TI PCF8754 or PCF8754A
LiquidCrystal_I2C lcd(LCDaddr2,2,1,0,4,5,6,7);

void initLCD(byte address) {
  byte cdata[8];
  Serial << "initLCD(" << _HEX(address) << ')' << endl;
  lcd.setAddress(address);       // Set LCD I2C address
  Serial << "LCD address ... " << _HEX(lcd.getAddress()) << endl;
  // activate LCD module
  lcd.begin(LCDcols, LCDrows);
  lcd.setBacklightPin(3,POSITIVE);
  lcd.setBacklight(HIGH);
  lcd.noCursor();

  // Load custom characters
  for (int c=0; c<8; ++c) {
    unsigned int d = ((c+4)<<12 | (c|3)<<9 | (c|2)<<6 | (c|1)<<3 | c) ^ 0x5555;
    //Serial << "c=" << c << "  d=" << _HEX(d) << endl;
    for (byte k=0; k<8; ++k)
      cdata[k] = d >> k;
    lcd.createChar(c, cdata);
  }
  lcd.home ();
  lcd.print("Initialized");
  delay(1000);
}

void setup() {
  Serial.begin(115200);
  Serial << "Starting up" << endl;
  Wire.begin();                 // Setup to wirescan to check for 8754 addr
  Serial << "after Wire.begin()" << endl;
  TWBR = 152;  // 50 kHz, use if it works, or use slower rate
  TWBR = 158;  // 12.5 kHz, = slower rate
  TWSR |= bit (TWPS0);  // change prescaler
  Serial << "after TWBR / TWSR" << endl;
  Wire.beginTransmission (LCDaddr2);
  Serial << "after Wire.beginTransmission()" << endl;
  if (Wire.endTransmission() == 0) // Does 0x27 succeed?
    initLCD(LCDaddr2);          // Set up with 0x27 address
  else
    initLCD(LCDaddr3);          // Set up with 0x3F address
  Serial << "after initLCD()" << endl;
}

void show(char base, byte delt) {
  enum {MD=2000};
  byte k, ro;
  for (ro=0; ro<LCDrows; ++ro) {
    lcd.setCursor(0, ro);
    for (k=0; k<LCDcols; ++k) {
      lcd.print(base);
      base += delt;
    }
  }
  if (base==' ') {
    lcd.setCursor(1, 1);
    lcd << "LCD @" << _HEX(lcd.getAddress()) << " =" << lcd.getAddress();
  }
  delay(MD);
}

long p=0;
void loop() {
  byte c;
  Serial << "Pass " << p++ << " on " << _HEX(lcd.getAddress()) << " at t=" << millis() << endl;
  lcd.home ();          // Set cursor to 0,0
  show('#', 0);         // Screen of # characters
  show(' ', 0);         // Screen of ' ' characters
  show('@', 0);         // Screen of @ characters
  show( 0,  1);         // lo specials + ' '...'/'
  for (c=' '; c < '~'; c+=16)
    show(c, 1);

  lcd.setBacklight(HIGH);
  while (Serial.available()) {
    c = Serial.read();
    if (c == '2') initLCD(LCDaddr2);
    if (c == '3') initLCD(LCDaddr3);
  }
}

```

---

To add `lcd.setAddress(address);` and `lcd.getAddress(address);` routines:

```
// add after void setBacklight(...); in LiquidCrystal_I2C.h
void setAddress(uint8_t addr);
uint8_t getAddress();

```

and

```
// add after void setBacklight(...); in LiquidCrystal_I2C.cpp
void LiquidCrystal_I2C::setAddress(uint8_t addr) {
  LiquidCrystal_I2C::_Addr = addr;
}
uint8_t LiquidCrystal_I2C::getAddress() {
  return LiquidCrystal_I2C::_Addr;
}

```
> 2 votes

---
Tags: arduino-mega, lcd
---


# Question
Title: Why does this Arduino Pro Mini use a capacitor on the DTR reset line?
I'm kind of curious as to why there is a 0.1uF capacitor on this Arduino Pro Mini (https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf). It seems like it would work just fine without it.

# Answer
Most USB to serial chips set the DTR to LOW on connecting, but it keeps it LOW.

This would reset the arduino, but since the DTR never goes HIGH the Arduino will never get out of this reset state, and not run your code.

The capacitor will AC couple the signal. The the DTR goes low, the other side of the capacitor will go LOW too, but the pull-up resistor will slowly charge the capacitor, till the reset pin is HIGH again.

So it will convert a LOW transition to a LOW pulse.
> 7 votes

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


title: Posting data with ESP8266 module?

text:
# Question
Title: Posting data with ESP8266 module?
I have an ESP8266 module attached to an Arduino Uno that is connected to my local network. On the network, at address 192.168.1.13, I have a nodejs/express server running on port 3000. How would I go about posting an eight digit number from the Arduino to the webserver? In my current attempts the server console isn't receiving any data when using AT+CIPSEND while connected to it.

EDIT: My Code is as follows:

```
     #include <SoftwareSerial.h>

const byte rxPin = 9; // Wire this to Tx Pin of ESP8266
const byte txPin = 10; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600); // Change this to the baudrate used by ESP8266
  delay(1000); // Let the module self-initialize
  Serial.println("Sending an AT command...");
  ESP8266.println("AT+CWMODE=1");
  delay(1000);
  ESP8266.println("AT+CWJAP=\"username\",\"pass\"");
  delay(10000);
  ESP8266.println("AT+CIPMODE=1");
  delay(1000);
  ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\test\",3000");
  delay(1000);
  GetData();

}
void loop() {
 while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }
}
void GetData(){
  ESP8266.println("AT+CIPSEND=4");
  ESP8266.print("test");
}

```

and My output is this

```
  Sending an AT command...
Got reponse from ESP8266: AT+CWMODE=1

Got reponse from ESP8266:

Got reponse from ESP8266: OK

Got reponse from ESP8266: AT+CWJAP="surveillancevan4","7073199495"

Got reponse from ESP8266: AT+CIPSEND=4

Got reponse from ESP8266: testI

```

EDIT 2: I modified my code to this

```
    #include <SoftwareSerial.h>

const byte rxPin = 9; // Wire this to Tx Pin of ESP8266
const byte txPin = 10; // Wire this to Rx Pin of ESP8266
// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600); // Change this to the baudrate used by ESP8266
  ESP8266.println("AT");
  delay(1000);
  ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\",3000");
  delay(20000);
  String request = "POST /test HTTP/1.0 \r\n";
  ESP8266.println("AT+CIPSEND=19");
  delay(5000);
  ESP8266.println(request);

}

void loop() {
 while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }
}

```

and now my output claims it posted successfully, but I'm still not seeing any data in my nodejs server. Here is the output: Got reponse from ESP8266:

```
AT

Got reponse from ESP8266:

Got reponse from ESP8266: OK

Got reponse from ESP8266: AT+CIPSTART="TCP","192.168.1.13",3000

Got reponse from ESP8266: CONNECT

Got reponse from ESP8266:

Got reponse from ESP8266: O

Got reponse from ESP8266: busy sytes

Got reponse from ESP8266:

Got reponse from ESP8266: SEND OK

```

I can confirm that it is connecting to my web app because when I run the code on the module without the server running it returns an error.

# Answer
```
 ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\test\",3000");

```

That line is going to fail miserably for a number of reasons:

1. You need to provide an IP address or domain name - NOT a URL
2. Even if you could provide a URL this bit `192.168.1.13\test` would end up, after C escaping, as `92.168.1.13 est` since `\t` is a TAB character.

And then on top of all that I assume you are connecting to a HTTP server, yet you aren't sending a HTTP request, you are just sending the word "test", which the HTTP server has no hope of ever understanding.

You need to formulate and send a proper HTTP request and send it to the server. I suggest you go and look at a few tutorials and maybe look up how HTTP Servers actually operate and what the protocol looks like.
> 0 votes

---
Tags: arduino-uno, esp8266, node.js
---


# Question
Title: Why so different not connected analog inputs?
I took just Arduino Uno board, connected Ethernet Shield to it and compiled Web Server example. And it works.

But it outputs:

```
analog input 0 is 1023
analog input 1 is 1023
analog input 2 is 789
analog input 3 is 663
analog input 4 is 525
analog input 5 is 449

```

Why so different values? Shouldn't it be zeros? Is this static electricity or what?

# Answer
> 1 votes
Floating inputs, EMI, high input impedance and sample-and-hold capacitor. It can measure anything at this point (usually electro static charge is split between pin capacity and S&H capacitor. It can be used even for touch sense pins...

---
Tags: arduino-uno, analogread
---


# Question
Title: How to encode resistance change (reed) for Arduino?
I have a water counter which switches reed on each 10 liters of water. I would like to count these values with Arduino.

I wrote a program which counts changes from analog input and connected counter between `+5V` and analog input. It counts well but I am doubt I connected correctly. Because when reed is opened, then analog input is connected to nothing, while it should be connected to `GND`.

How to implement correct conversion from reed to analog or digital input?

# Answer
A reed switch is just a button. Treat it as such. Either connect it between a digital input and ground, with a pull-up resistor (internal one would do) or between a digital input and +5V and use a pull-down resistor.
> 1 votes

---
Tags: input, resistor
---


title: Perform function after a period of time

text:
# Question
Title: Perform function after a period of time
I am working on a project that I am supplying with voltage an LED through a digital pin (26) and I want the LED to be switched off after 4 seconds.

I am using Arduino Mega2560 and I am programming it using Arduino's IDE version 1.6.10. I have installed the SimpleTimer library .zip method but it does not seem to function.

**Code**

```
#include <SimpleTimer.h>

SimpleTimer timer;

void setup() {
pinMode(26, OUTPUT);
digitalWrite(26, HIGH);

timerId = timer.setTimeout(4000, switchOff);
}

void switchOff() {
  digitalWrite(26, LOW);
}

void loop() {
}

```

The problem is that the LED stays just on (*digitalWrite(26, HIGH);*) instead of going to the *switchOff* function and turning off (*digitalWrite(26, LOW);*). I have also tried using Timer1 and Timer libraries but they also do not work. Can someone who has made any of the libraries work, provide me with some guidance?

# Answer
> 1 votes
You have to call `timer.run()` inside loop function.

The SimpleTimer library is more like a scheduler. You call at every so often, and it checks if there is any event that has expired.

---
Tags: arduino-mega, library, digital
---


# Question
Title: How come my code does not wait for a specific time before going into an if statement?
I have an HC-SR04 attached to a servo. When the 90 degree reading is less than 30 cm, I want the motor to take 2 seconds to turn to 130 degrees, get a measurement on the right, and turn back to 90 degrees. My code does not seem to work. Even though I tell it to wait for 2000 ms, it skips directly to the if statement where the turning to 90 degrees is done. Here is the main code:

```
 #include <Servo.h>
#define trig 22
#define echo 24
long duration;
boolean turned130 = false;
int cm50, cm, cm130;
Servo servo;
boolean checkRight = false;
boolean mainPing = true;
unsigned long counter;
unsigned long servoTimer = millis();
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(echo, INPUT);
pinMode(trig, OUTPUT);
servo.attach(12);
servo.write(90);
delay(2000);

}

void loop(){
counter=millis();//my timer
  if(((counter-servoTimer) >= 250) && mainPing){//distance measured 4 times a second
    ping();
    cm=duration/29.1/2;
    Serial.println(cm);
    servoTimer=counter;//this if statement works fine
  }
  if((cm<30) && mainPing){

    mainPing=false;//makes the 90 degree ping and this if statement unable to run
    checkRight = true;//enables next if statement to run
    servoTimer=millis();
    servo.write(130);
    cm=30;//so that this if statement does not get called again until distance is obtained
    Serial.println("Inside less than 30 loop");//I added this for debugging, to let me know when the loop is called

  }
  if(checkRight && ((counter-servoTimer) >= 2000)){//after 2 seconds passes

    checkRight=false;
    ping();
    cm130 = duration/29.1/2;
    mainPing = true;//enable to other 2 if statements to run
    servoTimer=millis();
    Serial.println(cm130);
    servo.write(90);//turn motor back
    Serial.println("Inside other loop");//for debugging

  }

  delay(2);
  }

void ping(){

    digitalWrite(trig, LOW);
    delayMicroseconds(2);
    digitalWrite(trig, HIGH);
    delayMicroseconds(10);
    digitalWrite(trig, LOW);
    duration = pulseIn(echo, HIGH);

}

```

This is what I got in the Serial monitor:

```
25//distance triggers 2nd if statement
Inside less than 30 loop
261
Inside other loop
13
Inside less than 30 loop
14
Inside other loop
14
Inside less than 30 loop
14
Inside other loop
3242
13
Inside less than 30 loop
14
Inside other loop

```

This all happened within milliseconds. There was no 2 second pause and the servo never turned. What is wrong with my code that prevents the motor from turning and waiting 2 seconds? The order of the Serial messages is correct, but it is happening fast.

EDIT:

When I remove the Serial messages and disconnect from the computer, it kind of works. By that, I mean it turns and waits for 2 seconds 50% of the time. Other times, the servo just shakes a little bit and stops.

Another thing I noticed is that if I leave only Serial.println(cm) message and Serial.println("Inside less than 30 loop"), this is the result that I observe.

```
    12
    13
    Inside less than 30 loop

    15
    3
    Inside less than 30 loop

```

For some reason the loop does not get triggered the first time. Is there a possibility that I have a defective Arduino Mega?

EDIT 2:

I tested the same setup on an official Arduino Uno and it did not work either. This means that I do not have a broken Arduino. Could the servo motor be broken? That won't explain the Serial messages though.

# Answer
> 2 votes
I added some more debugging, and I think I have your issues detected.

Amended code:

```
#include <Servo.h>
#define trig 22
#define echo 24
long duration;
boolean turned130 = false;
int cm50, cm, cm130;
Servo servo;
boolean checkRight = false;
boolean mainPing = true;
unsigned long counter;
unsigned long servoTimer = millis();
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(echo, INPUT);
  pinMode(trig, OUTPUT);
  servo.attach(12);
  servo.write(90);
  delay(2000);
}

void loop() {
  counter = millis(); //my timer
  if (((counter - servoTimer) >= 250) && mainPing) { //distance measured 4 times a second
    Serial.print ("Doing ping at time ");
    Serial.println (counter);
    ping();
    cm = duration / 29.1 / 2;
    Serial.println(cm);
    servoTimer = counter; //this if statement works fine
  }
  if ((cm < 30) && mainPing) {

    mainPing = false; //makes the 90 degree ping and this if statement unable to run
    checkRight = true;//enables next if statement to run
    servoTimer = millis();
    servo.write(130);
    cm = 30; //so that this if statement does not get called again until distance is obtained
    Serial.println("Inside less than 30 loop");//I added this for debugging, to let me know when the loop is called
  }
  if (checkRight && ((counter - servoTimer) >= 2000)) { //after 2 seconds passes
    Serial.print ("counter = ");
    Serial.println (counter);
    Serial.print ("servoTimer = ");
    Serial.println (servoTimer);
    checkRight = false;
    ping();
    cm130 = duration / 29.1 / 2;
    mainPing = true;//enable to other 2 if statements to run
    servoTimer = millis();
    Serial.print ("cm130 = ");
    Serial.println(cm130);
    servo.write(90);//turn motor back
    Serial.println("Inside other loop");//for debugging
  }
  delay(2);
}

void ping() {
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
}

```

With no server (or anything) attached I get this output:

```
Doing ping at time 1999
0
Inside less than 30 loop
counter = 1999
servoTimer = 2693
cm130 = 0
Inside other loop

```

First note that `servoTimer` is somewhat higher than `counter` because the `pulseIn` function takes a while to execute (times out after 1 second allegedly, although that was less than a second).

Now we come to the problem "if" statement.

```
  if (checkRight && ((counter - servoTimer) >= 2000)) { //after 2 seconds passes

```

That can't be right, eh? `counter` is 1999 and `servoTimer` is 2693, and there is not 2000 difference. However you are doing the maths the other way:

```
counter - servoTimer =  1999 - 2693 = -694

```

Since we are using **unsigned long**, it cannot hold negative numbers so the result of the subtraction is 4294966602.

That is much larger than 2000, so the "if" branch is taken.

---
Tags: arduino-mega, servo, timers, millis, hc-sr04
---


title: Interrupt driven serial in Arduino Mega

text:
# Question
Title: Interrupt driven serial in Arduino Mega
This is the multi serial example from Arduino IDE

```
void setup() {
  // initialize both serial ports:
  Serial.begin(9600);
  Serial1.begin(9600);
}

void loop() {
  // read from port 1, send to port 0:
  if (Serial1.available()) {
  // plus do some operations
    int inByte = Serial1.read();
    Serial.write(inByte);
  }

  // read from port 0, send to port 1:
  if (Serial.available()) {
    // plus do some operations
    int inByte = Serial.read();
    Serial1.write(inByte);
  }
}

```

As you can see, the loop is running multiple times doing almost nothing at most of cycles, this will eat up battery life (if it has one).

Is it possible to read when data is available without looping, just like with an interrupt.

Also, is it a good practice to run a loop all the time? Is there any way to sleep? I have seen examples like this one http://playground.arduino.cc/Learning/ArduinoSleepCode which uses some other pin to wake up. I don't want that.

# Answer
> 1 votes
Serial input can wake the processor from sleep, assuming it is useful for it to sleep (for example, if it is battery-powered).

My page about power shows various technicques including using serial input to wake it from sleep (see reply #8 on that page). However a disadvantage of that is, it take a few microseconds to wake from sleep - sometimes quite a few - so you are likely to lose the first byte received from serial if you are asleep.

> Also, is it a good practice to run a loop all the time?

There is no harm, except for battery consumption.

# Answer
> 1 votes
Why do you not want to sleep the processor? If it's running at all, it doesn't matter whether it is polling the UARTs or executing something else; it will still be using power.

The first several paragraphs of the article you linked to describe putting the processor into low-power mode and reducing the power consumption further by disabling some internal hardware modules. When the UART receives a byte, the processor will wake up and continue execution from where it slept. Isn't that what you are asking for?

---
Tags: serial, arduino-mega
---


# Question
Title: Sketch does not work without delay() or other complex functions like digitalWrite()
I have a simple sketch here that should just blink a led once a second or so (approximately):

```
boolean onOff=true;
int count=0;

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

void loop() {
    count++;
    delay(1);

    if (count == 316) {
    onOff=!onOff;
    digitalWrite(13, onOff);
    count=0;
    }
}

```

So, if `count` is 316 it changes the state of led. It works right now, but it does not without `delay()` function or some other complex ones like `digitalWrite()` being in the `loop()` too. If i am deleting `delay()`, than led is just always on. I can feel it is smth about interrupts, but i am not sure.

---

What am i trying to do here is to make an alternative to `delay()` and `millis()` for my other project. One of the most needed thing for me is to make ASAP (as soon as possible) "timer", so that some code could run every 2(3-4...) iterations of loop(). delay() is bad always, and millis() uses `long` variable (which is bad for cpu time and ram), and while having problems with ram and cpu time in my project, i want smth lighter for ASAP and other not very precise timing. So, the questions are:

1. Why does my sketch works only with delay(), but does not work without it?
2. Why does blinking sketches work with millis(), while they do not use any delay() just like my sketch.
3. Am i a bad person for trying to make smth like an ASAP timer?:) Is saved ram and cpu time worth of it? Any other possible problems?
4. Can this sketch be workable without `delay()` or other complex or ram and cpu costly functions?

Thank you.

So, the sketch up there works indeed, but here is the version that you can can observe with your eyes:

```
boolean onOff=1;
unsigned int counter=0;
unsigned long time=0;

void setup() {
  pinMode(13, OUTPUT);
  Serial.begin(57600);
}

void loop() {
   if (counter==0)  time=micros();
    counter++;
    if (counter == 0) {
        onOff= !onOff;
    digitalWrite(13, onOff);
    Serial.println(micros()-time);
    }
}

```

With Serial i was checking delay between blinks, and it is 140164 mcs = 140 ms = 0.14s. But to be honest it feels slower, so please correct me if i can benchmark it in a better way.

# Answer
> 1 votes
As majenko answered in the comments, the blinking rate will be so fast you can not see it.
Also it is possible that without the delay the optimizer removes the whole counting. So increasing the number as proposed by majenko may not even work due to compiler optimisations.
Using a method based on counters is a very unreliable way to use timings.

Look at the blinkwithout delay example as proposed by Dirk.
It boils down to using millis() for timing. millis tells you how many millis the arduino is running.

```
void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the
  // difference between the current time and last time you blinked
  // the LED is bigger than the interval at which you want to
  // blink the LED.
  unsigned long currentMillis = millis();

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

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

```

# Answer
> 0 votes
This sketch blinks an LED on D10 (on a Uno) at one second intervals. It does not use `delay`, `micros`, `millis` or any unsigned long variables (apart from a constant).

```
const int STROBE_FREQ = 1000;     // sets the period in milliseconds
const unsigned long countTo = ((float) F_CPU / 1024.0) / (1000.0 / STROBE_FREQ);

void setup ()
  {
  // D10 to output
  bitSet (DDRB, 2);

  // Fast PWM top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11); // fast PWM
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS12) | bit (CS10);   // fast PWM, prescaler of 1024
  OCR1A = countTo - 1;                 // zero relative
  OCR1B = (countTo / 2) - 1;           // 50% duty cycle
  bitSet (TCCR1A, COM1B1);   // clear OC1B on compare
  }  // end of setup

 void loop ()
   {
    // do something useful
   }

```

It frees up the main loop to do something useful without worrying about time taken to do the blinking.

For more details see my page about timers.

---
Tags: interrupt, timers, millis, timing
---


title: POST data from Arduino to website

text:
# Question
Title: POST data from Arduino to website
I am working on a project where I am trying to send data using HTTP and POST method from my Arduino Mega2560 to a website which I host on localhost. I am living to a students' accommodation and thus, I do not have access to the router. However, I have bought a router and have connected it to the wall via the WAN. Also, the Arduino is connected to one of the ethernet plugs of the router via an Ethernet shield and my laptop to another ethernet plug. I am trying to retrieve the data from the website, but I cannot seem to load them.

**Arduino Code**

```
#include <dht.h>
#include <SPI.h>
#include <Ethernet.h>

dht DHT1;
int temperatureSensorPin1 = 25;

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
EthernetClient client;
EthernetServer server(80);

long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 250000;
String data;

long lastUpdate = 0;

void setup() {

  Serial.begin(9600);
  if(Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
  }

  data = "";

  pinMode(temperatureSensorPin1, INPUT);
}

void loop() {

int temp1 = DHT1.read11(temperatureSensorPin1);

switch (temp1)
  {
    case DHTLIB_OK:
        Serial.print("OK,\t");
        break;
    case DHTLIB_ERROR_CHECKSUM:
        Serial.print("Checksum error,\t");
        break;
    case DHTLIB_ERROR_TIMEOUT:
        Serial.print("Time out error,\t");
        break;
    case DHTLIB_ERROR_CONNECT:
        Serial.print("Connect error,\t");
        break;
    case DHTLIB_ERROR_ACK_L:
        Serial.print("Ack Low error,\t");
        break;
    case DHTLIB_ERROR_ACK_H:
        Serial.print("Ack High error,\t");
        break;
    default:
        Serial.print("Unknown error,\t");
        break;
  }

  currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
  }
  String data="temp1="+String(DHT1.temperature, 0)+"&temp2="+String(DHT2.temperature, 0)+"&temp3="+String(DHT3.temperature, 0)+"&temp4="+String(DHT4.temperature, 0)+"&temp5="+String(DHT5.temperature, 0)
                  +"&hum1="+String(DHT1.humidity, 0)+"&hum2="+String(DHT2.humidity, 0)+"&hum3="+String(DHT3.humidity, 0)+"&hum4="+String(DHT4.humidity, 0)+"&hum5="+String(DHT5.humidity, 0)+"&gas="+gasValue;

  Serial.println(Ethernet.localIP());
  if(client.connect("192.168.0.1", 80)) {
    client.println("POST /home/visualisation.php HTTP/1.1");
    client.println("Host:  192.168.0.1");
    //client.println("User-Agent: Arduino/1.0");
    //client.println("Connection: close");
    client.println("Content-Type: application/x-www-form-urlencoded;");
    client.print("Content-Length: ");
    client.println(data.length());
    client.println();
    client.print(data);
    //Serial.println(data);
    Serial.println("We have connection");
  }

  if(client.connected()) {
    Serial.println("We have abc");
    client.stop();
  }

  delay(4000);
}

```

**PHP Code**

```
<?php
$temp1 = "";
if(isset($_POST['temp1'])) {
    $temp1 = $_POST['temp1'];
}
echo $temp1;
?>

```

Windows ip configuration \[Router ip configuration\]\[2\]

Is the connection that I have made the appropriate one? How should I do it in order to work?

P.S.: I would like to clarify that I do not have an extended knowledge regarding networking.

**Router ip configuration** *LAN* MAC Address: 60-E3-27-E7-70-7A IP Address: 192.168.0.1 Subnet Mask: 255.255.255.0

*Wireless* Wireless Radio: Enable Name (SSID): TP-LINK\_707A Mode: 11bgn mixed Channel Width: Automatic Channel: Auto (Current channel 3) MAC Address: 60-E3-27-E7-70-7A WDS Status: Disable

*WAN* MAC Address: 60-E3-27-E7-70-7B IP Address: 100.66.166.2 Dynamic IP Subnet Mask: 255.255.255.192
Default Gateway: 100.66.166.1

DNS Server: 77.244.128.44 , 77.244.128.45

# Answer
The ip that I have Arduino send data to is the router's and thus, I should have used the 192.168.0.100 ip which is the one of my computer.

I also needed to save the value to a database to notice the changes because *echo $temp1;* did not seem to work, probably I should have it included into HTML *label* tags. Anyway, I just loaded the value from the database into a PHP variable and I was able to accomplish the task.
> 0 votes

---
Tags: web-server, networking, http
---


title: Weird OneWire bus problem

text:
# Question
Title: Weird OneWire bus problem
I have two DS18B20 temperature sensors connected via a OneWire bus to an arduino. I noticed that these sensors get hot, when permanently powered and decided to just turn them on for measurment.

First attempt: Define a pin as output and feed the sensors. Because I received only one value (first sensor on bus), I assumed that the current delivered may not be high enough and utilized a transistor (+resistor) as switch for the main 5V line to feed the sensors from the mains (as before). The result is the same. I only get the value of the first sensor. When I connect the sensors directly, I get both values.

I tried up to 4 seconds delay after switching the bus on and again after reading the values (before switching the bus off again), with no luck. Only the first sensor answers.

Do I have a timing or a current problem here?

**UPDATE**

Wiring (working): Two DS18B20 in parrallel with a 4,7k resisor between `DATA` and `VIN`. One Arduino pin used, Sensors directly powered by power-supply (same as arduino)

Wiring (not working): Broke the `VIN` line and added a transistor as switch between power-supply and sensors `VIN`. Used a second pin and a resistor to power up the line.

The transistor is a `TC124E` (npn) logic level transistor. I have the feeling, that this boy is not providing enough current to the sensors, which in addidtion have five meter cables attached...

**UPDATE II** It is not the current. I replaced the transistor with a mosfet (70T03H) and the result is exactly the same: When switched, only one sensor answers . When I connect the gate directly to a +5V line, I get both values as expected.

Kinda think, that the switching of the pin irritates the bus or the specific device.

**UPDATE III (Solution)**

I tracked this down to a mixture of

* Different resolution settings on the sensors
* my code not waiting long enough to get the sensor with the higher resolution to setup (on-to-read time). Giving the bus slightly more time to setup before any reading is accepted, solved my problem.

# Answer
> 1 votes
If you were trying to wire your bus in parasitic mode, here is what I am using:

```
OneWire Bus in parasitic mode:

+------------+     +5v            +---------+     +---------+
|    MCU     |      |             | DS18b20 |     | DS18b20 |
|            |  R_pu = 4.7K       | g  d +5 |     | g  d +5 |
| Strong-    |      |             +-o--o--o-+     +-o--o--o-+
| Pullup   > o------o               |  |  |         |  |  |
|            |      |               +--|--+         +--|--+
|            |      |               |  |            |  |
|    Data <> o------o---------------|--o------------|--o------ - - -
|            |                      |               |
+------------+                      V               V

```

I run at least three sensors this way on an approximately 6 meter bus, completely reliably.

---
Tags: 1-wire, ds18b20
---


# Question
Title: Is there any way to prevent Arduino CLI from closing each time?
I prefer writing code in Vim, so I'd like to get a workflow going with the Arduino CLI. I used to use `ino`, but I didn't like the restructuring of the project, which meant anyone who downloaded the code having to use `ino`.

I can build and verify using `/Applications/Arduino.app/Contents/MacOS/Arduino --verify MyProject.ino`, which pops up a new instance of the Java IDE, then exits after verifying.

While this works, and works well, it's incredibly slow. Is there any way to keep the IDE open to save the few seconds lost from the IDE starting again?

# Answer
> 2 votes
> Is there any way to prevent Arduino CLI from closing each time?

I would suggest working the other way around.

1. Start the Arduino IDE and set external editor in the Preferences (once).
2. Open the sketch file(s) in the Arduino IDE and VIM.
3. Edit the sketch file(s) in VIM.
4. Move to the Arduino IDE and Verify, Upload, Monitor, etc.
5. Repeat steps 3-4.

The alternative is to use a make based build system. An example may be found in the Cosa build system for Linux.

Cheers!

PS: VIM = any external editor such as GNU Emacs, TextEdit, etc.

---
Tags: arduino-ide, command-line
---


# Question
Title: OOP vs procedural programming on arduino
It seems like the majority of Arduino applications are written without using classes / objects. Is there a reason for this? Does is slow down the Arduino or somehow present undesirable behavior?

# Answer
Your assumption is quite wrong:

* The majority of libraries use OOP.
* The majority of in-built device drivers use OOP.
* The core is filled with many OOP helper objects and classes.
* 99.99% of all sketches use those OOP objects.

The sketches themselves may not be written as a class or set of classes for a number of reasons:

1. There is no point
2. The programmer doesn't know how

When a sketch is just stitching together calls to objects defined through libraries and making a few decisions there is little point in making the sketch itself an object. It's just a waste of time. In general if the sketch gets too complex to manage it gets broken down into smaller units - i.e., libraries - which are very often written as classes.

The moment you do `Serial.begin(9600);` you are using OOP.
> 10 votes

---
Tags: programming, c++, code-optimization
---


# Question
Title: How does Arduino decide when to go into flashing mode and normal mode?
Just this general question.As the titles says.

How does Arduino decide when to go into flashing mode and normal mode?

Is it by connecting certain pins to ground,so it's a hardware check or does it have to do with the code?

Other similar arduino like products such as the esp8266 work the same way as long as they use the same chip?

# Answer
> 1 votes
It first runs the bootloader. If there is no data coming into the serial connection within a certain amount, i.e. it's not being programmed, it will exit the bootloader and start the actual sketch.

In the UNO you will notice a 3 second delay between providing power, and your sketch starting.

---
Tags: esp8266
---


# Question
Title: Changing Uid Using MFRC522 Via Arduino Error
Well, I' ve just bought and recieved a MFRC522 rfıd module and done to much research on it. After watching several videos, I sorted out a library for using this module via arduino. You can click the first link below to be navigated to Miguel Balboa' s github page including the library that I mentioned and example codes written by him using that library. Though I' ve downloaded the zip file, ran such codes as dumpInfo, read and write, unfortunetely I couldn' t made "changeUid" example work. U can reach this example code via the link below as well. My connection is true, I' m sure bout' that If anybody had faced this kind of problem or knows the solution, their answers will be enough satisfying for me I guess... (By the way, error was this sentance: Are you sure this is a uid changeable card -I was sure, my card was a Mifare 1K card- failure, the card responded as NAK)

**link: https://github.com/miguelbalboa/rfid**

# Answer
Search for UID changeable card. The kit included this RFID reader just had a normal RFID card and keychain. You will probably have to buy it yourself. I bought it from aliexpress but I don' t remember which seller. Good Luck! (I mean who read this...)
> 1 votes

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


# Question
Title: How can I define a port extender MCP23s17 pin in Arduino
My task is to use a port extender (MCP23s17) to drive a touch keypad for which I have to define names of pins so that I can call those names in arguments of a function.

I have searched for different methods to define "PORT EXTENDER" pin but could not find any satisfactory results. Kindly help me handle the situation.

i have used the following libraries downloaded from Arduino playground 1. CapacitiveSensor.h 2. MCP23S17.h Now I have to use MCP23S17 Pin in the following function

```
#define key1 2
#define key2 4
CapacitiveSensor cs_4_2=Capacitivesensor(key2,key1);  //capacitive sensor is connected to pin 4 and 2

```

key1 and key2 are Arduino's pins. I want some method by which I can refer key1 and key2 to the port extender's (MSP23S17) pin. The above answers are surely helpful but they doesn't fulfill my requirement.

Thanks in Advance Sorry for English.

# Answer
> 1 votes
If you use this arduino library:

```
#define LED_PIN 15

mcp.pinMode(LED_PIN, LOW); //set led pin on the MCP23S17 to an OUTPUT

mcp.digitalWrite(LED_PIN, LOW)

```

# Answer
> 1 votes
If you are using my library you can do something like:

```
MCP23S17 expander1(&SPI, 10);

#define LED_PIN expander1, 15

void setPin(MCP23S17 &expander, int pin, bool level) {
    expander.digitalWrite(pin, level);
}

// ... later ...

setPin(LED_PIN, HIGH);

```

# Answer
> 1 votes
There is also the Adafruit Library, all do similar things, just in a slightly different way. I use this one, it just depends on which method you are most comfortable with and what your requirements are. Try them all and find out.

```
void setup() {
  Serial.begin(9600);  // debugging
  mcp.begin();      // use default address 0

      for(int i = 0; i < 6; i++) {
        mcp.pinMode(trafficLights1[i], OUTPUT);
      }
       for(int i = 0; i < 6; i++) {
        mcp.pinMode(trafficLights2[i], OUTPUT);
       }
        for(int i = 0; i < 5; i++) {
        mcp.pinMode(trafficLights3[i], OUTPUT);
        }
  for (int P=0;P<16;P++) {
    mcp.pullUp(P, HIGH);  // turn on a 100K pullup internally
    mcp.digitalWrite(P,LOW);
 }
      mcp.digitalWrite(11, HIGH);
}

```

---
Tags: arduino-uno
---


# Question
Title: Arduino nano digital pins not working with external power source
We are using an Arduino Nano for simple serial comms to fire a relay from a Windows 10 PC.

Initial issue we had was windows not recognizing the device (COM Port) when the pc is powered off (as per this link: Arduino Nano - USB not present after reboot ) so we powered the arduino nano over a 5V pin and now when Windows starts up the device is recognized.

However, as I'm learning with these chips, nothing is ever that simple. Now the relay that we are firing does not work with external power, but if you unplug the external power then the relay does fire (powered over USB)

The units are at a mine and at the moment and I believe that the problem is that the serial chip is now not responding as per this - from the official Arduino Nano page:

*The FTDI FT232RL chip on the Nano is only powered if the board is being powered over USB. As a result, when running on external (non-USB) power, the 3.3V output (which is supplied by the FTDI chip) is not available and the RX and TX LEDs will flicker if digital pins 0 or 1 are high.*

Note - I included the above from another question but this no longer appears on the official arduino nano page (can't past link as it's my first post)

The question is how can we get the digital pins on the arduino nano to fire using an external power source and input from a Windows PC?

Thanks

Diagram:

# Answer
> 2 votes
I think you may need to back up and start over again.

Rather than changing the power supply, you need to fix the problem that made you think you needed to change power supplies.

Following a link in a comment on the question you linked to leads to this thread on the Arduino forums.

The suggestion there is that a particular pin on the FTDI chip on the Nano isn't connected as it should be.

To be exact, the Test pin (pin 26 on the FT232RL chip) needs to be grounded to fix the original problem you were having with communications with the Nano.

The description there fits your description. The Nano can't talk to the PC if the Nano is connected to the PC at power on. The same thing happens with the circuit referenced in that Arduino forum thread, but they are using another embedded system instead of a PC.

If you fix that, then you won't need to use an external 5V supply.

To back up the conclusion from the Arduino forum, here's an excerpt from page 8 (pin descriptions) of the FT232RL datasheet:

> 26 TEST Input Puts the device into IC test mode. Must be tied to GND for normal operation, otherwise the device will appear to fail

You need to connect pins 25 (ground) and pin 26 (Test.)

Excerpt from the Nano schematic:

Pins 25 (ground) and 26 (Test) are right next to one another, so easy to fix.

You need to put a blob of solder on the red marked spot in this picture:

# Answer
> 0 votes
I accepted the answer from JRE as I believe this is the best answer. For certain reasons we weren't able to do this so I've posted this as a workaround.

We ended up splitting the USB input to the arduino nano by using a Y cable. We used the one end for the power to the device and the other end for comms from the PC (with power disabled). This solved our issue as the chip now received power and responded to comms and the USB driver also initialised correctly on Windows when starting up.

If you are unable to solder the chip then this is a workaround that we have used.

---
Tags: serial
---


# Question
Title: Can't upload sketch to arduino Uno board
I'm trying to upload a simple sketch to my Uno board but get this error message: avrdude: stk500\_recv(): programmer is not responding (full error message at the end).

I have other Uno boards who work fine so I guess it is something to do specifically with this board (which used to work) and not my system or cables (port,drivers,settings etc..).

I did a loop-back test (http://forum.arduino.cc/index.php?topic=73748.0) on the board and it worked fine.

I read about possible solutions but nothing seems to solve this. https://stackoverflow.com/questions/19765037/arduino-sketch-upload-issue-avrdude-stk500-recv-programmer-is-not-respondi

I also tried using an Arduino as an AVR ISP but it failed. (https://www.arduino.cc/en/Tutorial/ArduinoISP)

Any help will be appreciated, thanks in advance.

Full error message:

```
    avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM3
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xd3

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```

# Answer
> 1 votes
In Arduino IDE check that

* correct port number is selected in Tools -\> Port
* correct programmer is selected in Tools -\> Programmer (should be AVRISP mkII if you upload the code via USB cable)
* correct board is selected in Tools -\> Board (Arduino/Genuino Uno)

If above doesn't help, install the latest version of Arduino IDE.

# Answer
> 0 votes
Try the different boards in the menu. I had that with one of my boards and then it worked fine when I used the Due in the IDE instead. Something to do with one of the chip revisions I think.

---
Tags: arduino-uno
---


# Question
Title: How to split a string into substring Arduino
I'm about identify myself stupid, howcome I couldn' t figure out how to split a string into substring using arduino, even after 10 days of searching. The number is fact... So, As Mr.Arduino.cc says: *string*.substring() is just can be used as conditional phrase with loops like if. and there is no method such strtok() like in C can help me with this. So guys, I' m bagging you for help, please!

```
if (ks > 255 * 60)
            {
                    vek.print("Bu yazı, ", 25, 0);
                    vek.printNumI(255*60, 25, 8);
                    vek.print("karakterd-", 25, 16);
                    vek.print("en uzun ol", 25, 24);
                    vek.print("dugundan", 25, 32);
                    vek.print("gosterlemz", 25, 40);
            }

for (byte i = 0; i <= ss ; i ++)
            {
                    for (byte j = 0; j <= 6; j++)
                    {
                            int ilk_kar = j * 10 + i * 60;
                            int son_kar = ilk_kar + 10;

                            String yaz=readString.strtok(ilk_kar,son_kar);

                            vek.print(yaz, 25, j);

                            if (analogRead(A5) == 1023)
                            {
                                    continue;
                            }
                            else
                            {
                                    break;
                            }
                    }
            }
    }
}

```

Error: sketch\_aug22a.ino: In function ‘void loop()’: sketch\_aug22a.ino:83:56: error: ‘class String’ has no member named ‘strtok’

What am I supposed to do?

Thanks, already...

# Answer
> 1 votes
Import the *string.h* library by adding `#include <string.h>` on top of your sketch, in order to use the `strtok()` function. Checkout the usage example of `strtok()` here: http://www.cplusplus.com/reference/cstring/strtok/?kw=strtok

---
Tags: programming, arduino-ide, sketch
---


# Question
Title: max7219 chained display showing text only on the first display
I'm using a max7219 like this one max7219. When I first tested my circuit, I used an 8x8 display and the code worked just fine. Now, after I modified the code and changed the display with the chained one, the text is showing only on the first matrix. I've seen someone that had another problem with the same matrix module, only that in his case the same text was printed on all the matrixes unsolved problem, in the end he didn't find a solution. Below, I'll attach my code. Please help me find the problem.

```
//Pin connected to ST_CP of 74HC595
int latchPin = 6;
//Pin connected to SH_CP of 74HC595
int clockPin = 7;
////Pin connected to DS of 74HC595
int dataPin = 5;

int period = 30;

byte rotl(byte n, byte b)
{
  return (n << b) | (n >> (8 - b));
}

byte X[] {

0x80,
0x80,
0x80,   //L
0x80,
0x80,
0x80,
0x80,
0xFF,

/*0x10,
0x00,
0x10, //I
0x10,
0x10,
0x10,
0x10,
0x10,

0XF0,
0x90,
0x80, //C
0x80,
0x80,
0x80,
0x90,
0xF0,

0xF0,
0x09,
0x09,
0x09,
0x09,
0x09, //A
0x09,
0xF0*/

};

void setup() {
  //set pins to output so you can control the shift register
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop()
{
  for (int i = 0; i < 8; i++)
  {
    X[i] = rotl(X[i], 1);
  }
  for(int i = period;i>0;i--)
  {
    displayX();
  }

}

void DisplayMatrix(byte numCol, byte numLine)
{
  byte numberToDisplay1 = numCol;
  byte numberToDisplay2 = numLine;

  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay1);
  shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay2);
  digitalWrite(latchPin, HIGH);
  delay(1);

}

void displayX()
{
   DisplayMatrix(X[0],1);
   DisplayMatrix(X[1],2);
   DisplayMatrix(X[2],4);
   DisplayMatrix(X[3],8);
   DisplayMatrix(X[4],16);
   DisplayMatrix(X[5],32);
   DisplayMatrix(X[6],64);
   DisplayMatrix(X[7],128);
}

```

# Answer
> 3 votes
Communicating with more than one MAX7219 chip when cascaded involves sending data to all the chips at once. You have to treat the cascaded sequence of chips as a single entity - an entire display in its own right.

With one chip you send an 8-bit register value followed by an 8-bit data value. To use two chips you have to send twice that - an 8-bit register and 8-bit data for the second chip, followed by an 8-bit register and 8-bit data for the first chip.

The chips have a "NO-OP" register (0x00) which can be used to ensure that nothing is done on that chip if you don't want to change anything.

So setting line 3 to 0x55 on the first display, and line 5 to 0xAA on the second display you would send the sequence `\ 0x05,0xAA,0x03,0x55 /` as a single transaction (lower CS `\` before, raise it `/` afterwards).

If you only wanted to set line 2 on the second display to 0x69 you would send the sequence: `\ 0x02,0x69,0x00,0x00 /`

For three chips you need to send three blocks of 8+8 values. For four chips, 4 blocks of 8+8. Etc.

Note that it is important to send enough data for *all* the chips - you can't shortcut and only send data for the first display if that is all you want to talk to, since whatever is currently in the first display's shift register will get sent out to successive chips, and you will get the display duplication as seen in the other question.

---
Tags: arduino-uno, c, max7219
---


# Question
Title: Can MP3 be sent to SPI of Adafruit Music Maker Arduino shield instead of from its SD card?
Can uncompressed MP3 audio data be sent from Arduino board, by SPI, to Adafruit Music Maker shield instead of from the SD card on the Music Maker?

Instead of using SD card on Music Maker board, I want to send the compressed MP3 data from a Particle Photon board on the Particle shield shield, by SPI, to the VS1053B codec chip on Music Maker board, and then to amplifier for speakers.

Particle Shield Shield is attached to Particle Photon board, which has STM32F205RGY6 120Mhz ARM Cortex M3.

Particle Photon board uses its WiFi to receive uncompressed MP3.

# Answer
As far as I can see the SD card on the shield isn't read by the VS1053 directly, but by the arduino, which sends it to the VS1053.

So as far as I can see, you should be able to do what you want.
> 1 votes

---
Tags: shields, communication, spi
---


# Question
Title: How to access serial terminal through USBASP?
I have an Arduino Pro Mini that I use with a USBASP to program. These are actually a clone Pro Mini and a clone USBASP I'm using.

With this configuration, is it possible for me to access the serial port on the Arduino, through the USBASP, using the IDE serial terminal? If so, this would alleviate another connection to the computer for debugging. How to do this?

# Answer
From the USBASP documentation:

> * Planned: serial interface to target (e.g. for debugging).

..and further on..

> Firmware: The firmware dosn't support USB Suspend Mode. A bidirectional serial interface to slave exists in hardware but the firmware doesn't support it yet.

Keep in mind, that's from 2011, so it's possible someone has built an updated version of the firmware with that functionality. You'd have to do some searching (I'm not familiar with any such firmware).

For now, your best bet is just getting a TTL serial-USB converter (they're cheap) and connecting it directly to the Pro Mini.
> 3 votes

# Answer
I've searched in google and found a project in `Atmel Community` that supports `serial` with `USBasp` here. They called it `USBASP-tty`. I've not tested it yet but i think it will work. There are basically three requirements for it :

1. On the PC side, it uses a different software to capture the serial data from the `usbasp`.
2. It needs the conventionally bought `usbasp` programmers to have the two serial connections (image: `PDO` and `PD1` connected with the `ISCP` header) to work. If those aren't already made, you have to rewire the pins. Normally these connections aren't made and the `ICSP` pins are connected to ground.
3. The firmware of your `usbasp` programmer must be updated to the provided firmware using another programmer.
> 0 votes

---
Tags: serial
---


title: HTTP Post not working

text:
# Question
Title: HTTP Post not working
I am wanting to POST some data from Arduino to WebService (written in .NET), intending to save some temperature data to MS SQL Server.

My code in arduino is:

```
void PostarDados(String dados, String chamador) {
  if (client.connect("mysite.com.br",80)) {
    client.println(chamador);
    client.println(F("Host: mysite.com.br"));
    client.println(F("Content-Type: application/x-www-form-urlencoded"));
    client.print(F("Content-Length: "));
    client.println(dados.length());
    client.println();
    client.println(dados);
  }
  if (client.connected()) client.stop();
}

```

When sending to Serial instead of client, I am obtaining the following text:

```
POST /webservice.asmx/SetValoresTempUmidade HTTP/1.1
Host: mysite.com.br
Content-Type: application/x-www-form-urlencoded
Content-Length: 39

Chave=1&Temperatura=23.30&Umidade=42.20

```

I have enabled HTTP POST in web.config to make HTTP POST possible (I can successfully invoke webservice from browser):

```
  <location path="Webservice.asmx">
    <system.web>
      <webServices>
        <protocols>
          <add name="HttpGet"/>
          <add name="HttpPost"/>
        </protocols>
      </webServices>
    </system.web>
  </location>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

```

I have also set `ScriptMethod` to my webservice functions:

```
<WebMethod()> <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
Public Sub SetValoresTempUmidade(Chave As Integer, ByVal Temperatura As Double, ByVal Umidade As Double)
    Dim ctx As New DataClassesDataContext
    Try
        Dim A As New TBL_DADO
        A.CHAVE_INICIO = Chave
        A.DATA = Now
        A.TEMPERATURA = Temperatura
        A.UMIDADE = Umidade
        ctx.TBL_DADOs.InsertOnSubmit(A)
        ctx.SubmitChanges()
    Catch ex As Exception
    End Try
End Sub

```

Finally, I am trying to get some response from server using the following code (not receiving anything):

```
while (client.connected()) {
  while (client.available()) {
   buffer[counter++] = client.read();
  }
}

```

Explained that, I have two questions:

1. What am I doing wrong?
2. How could I debug this?

# Answer
> 1 votes
Using

```
byte server[] = {XX, XX, XX, XX}; //IP
if (client.connect(server,80)) {

```

instead of

```
if (client.connect("mysite.com.br",80)) {

```

worked

---
Tags: arduino-uno, ethernet, web-service
---


# Question
Title: how to use capacitive touch keypad without using CapacitiveSensor.h Library
i want to use multiple capacitive touch keypads with arduino uno but number of IO ports are not enough. So I decided to use MSP23S17 port extender. Now i have to find some methods to sense the touch keypad without using its library. Can anyone tell me if there is any way to do the task.

# Answer
> 1 votes
Here's one: Microchip mtch6102, though it might be a little more complex than you're looking for. All the others I found with a quick search were surface mount or single button controllers. You might be able to multiplex a single button controller like the Atmel AT42QT1011, but I don't know what the settling or reset times are. It may take to long to change pads, reset the chip, then wait for settling/calibration time (if any).

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


title: What SMS can send to switch LED?

text:
# Question
Title: What SMS can send to switch LED?
I have code but I don't know how to send SMS from my Mobile I mean what the message I can send to switch the Led? To switch On or Off. I use SIm900 and use this code

```
#include <SoftwareSerial.h>

 char inchar; // Will hold the incoming character from the GSM shield
 SoftwareSerial SIM900(7, 8);

 int led = 10;

 void setup()
 {
   Serial.begin(19200);
   // set up the digital pins to control
   pinMode(led, OUTPUT);
   digitalWrite(led, LOW);

   // wake up the GSM shield
   SIM900.begin(19200);
   delay(20000); // give time to log on to network.
   SIM900.print("AT+CMGF=1\r"); // set SMS mode to text
   delay(100);
   SIM900.print("AT+CNMI=2,2,0,0,0\r");
   // blurt out contents of new SMS upon receipt to the GSM shield's serial out
   delay(100);
   Serial.println("Ready...");
 }

 void loop()
 {
   //If a character comes in from the cellular module...
   if(SIM900.available() >0)
   {
     inchar=SIM900.read();
     if (inchar=='#')
     {
       delay(10);

       inchar=SIM900.read();
       if (inchar=='a')
       {
         delay(10);
         inchar=SIM900.read();
         if (inchar=='0')
         {
           digitalWrite(led, LOW);
         }
         else if (inchar=='1')
         {
           digitalWrite(led, HIGH);
         }
         delay(10);
         // SIM900.println("AT+CMGD=1,4"); // delete all SMS
       }
     }
   }
 }

```

# Answer
The code appears to be looking for an SMS that says `#a0` or `#a1`. The logic doesn't look very robust, though. It reads a character, then waits 10ms and tries to read another. What does `SIM900.read()` do if there is no next character? Will it return something? Or wait until there is another? If it waits, the code can get out of sync with incoming, badly-formed commands.
> 3 votes

---
Tags: gsm
---


title: Arduino I2C long string

text:
# Question
Title: Arduino I2C long string
I am trying to get 2-Arduinos passing data. The Master will request the data and the Slave send it. But, the length of the string the Slave will send is unknown each cycle.

I found some things here on writing strings with I2C but it seems it is limited to 32 bytes no matter what the Master requests. How can I get the full string sent each time?

Master makes request for string that could be about 180 bytes max - ever.

```
Wire.requestFrom(8,200);  // I2C-ID = 8, Length = 200
while (Wire.available())
{char c = Wire.read();
cmdInStr.concat(c);
}

```

Slave sends

```
int len = cmdOutStr.length()+1;
char ascii_num[len];
for (int i=0; i<len; ++i)
{ Wire.write(ascii_num[i]);
}

```

# Answer
> 1 votes
You can only send and receive fixed length amounts of data with I2C. The master has to know how much to request from the slave - or the slave to accept from the master.

There's a number of ways around it though:

1. Splitting / joining.

The trick here is to split the data into packets and re-assemble it at the remote end.

For instance, you split your string into 16-byte chunks. Then you send each chunk separately. Prefixed to each chunk (so the chunk becomes 17 bytes) is a byte telling the remote end how many characters are in this chunk. Any spare space in a chunk is padded with something (0x00 for instance) so it remains 17 bytes long in total.

2. two-stage transaction

In this method you first make a transaction which tells the remote end how many characters to receive in the next transaction, or retrieves the number of characters that need to be received from the remote end. The second transaction then receives (or sends) that specific number of characters.

If your strings are longer than the internal I2C buffer (32 bytes) then method 1 is probably the best way.

You can also combine the two methods so both ends know how much to expect to be transferred in total as well as how much of each packet is valid data. The sum of the second should match the first.

# Answer
> 0 votes
There is no maximum length for sending/receiving in I2C. It is the Wire library `BUFFER_LENGTH 32` macro, causing this limitation.

You can either copy some code from Wire library and implement your own `requestFrom` function which will store data directly to your `cmdInStr` string buffer or you can change Wire.h to have bigger `BUFFER_LENGTH`.

Or another way is to extend Wire.h like this:

```
#ifndef BUFFER_LENGTH
#define BUFFER_LENGTH 32
#endif

```

and in your sketch:

```
#define BUFFER_LENGTH 180
#include <Wire.h>

```

All depends on your preferences, but implementing own requestFrom and storing it directly into your `cmdInStr` buffer will be little bit more efficient than copying it into Wire buffer and then into your own buffer again.

And do you really need all these data in one string, isn't it possible to proceed it on the fly?

---
Tags: arduino-uno, i2c
---