title: Voltage and Current and Arduino

text:
# Question
Title: Voltage and Current and Arduino
I put a LED into 3.3V of the arduino and Ground, and it blew my LED violently, smoke was everyone, the whole half top of the led blew up across my room.

However, when i program the arduino with Pin13 HIGH per say, it will not blow up. Will be lit brightly. (Both using no resistors). However, if I plug mroe stuff in the board, for example, a lcd screen, rotary switches, and pushbuttons for my program, the LED dims to such a low brightness I cannot see.

Why is this? How Do I fix it?

Schematic:

Note, that i am using a mega, and some of it is slightly changed, and LED is being powered from A0 (Or Pin 54 on Mega)

# Answer
You *must* use a resistor. See The care and feeding of LEDs

> How Do I fix it?

Use a current-limiting resistor.
> 3 votes

# Answer
> “I put a LED into 3.3V of the arduino and Ground, and it blew my LED violently ... the whole half top of the led blew up ...” –

Current through the LED was so high that a tiny interconnect wire blew up. In typical LEDs, an almost-invisible wire connects from the anode lead frame to the LED chip on the cathode lead frame (at left and right, respectively, on each of the three lead frames pictured below). That wire acted like a fuse and blew up. With such a fine wire, it doesn't take particularly much current to pop it.

The diagram below shows how current through an LED increases exponentially as voltage across it rises. The diagram is from "mikesflightdeck.com LED dimmer" webpage, a page which may be useful in helping you understand why LEDs need series resistors or some other form of current limiting, eg a constant-current circuit.

When an LED is powered by an Arduino port output, the port's internal resistance is enough to limit LED current to non-lethal (to the LED) values. (However, the port itself may get burned out by delivering current beyond its 40 mA absolute max current rating.)

> “However, if I plug more stuff in the board ... the LED dims to such a low brightness ...” –

The stuff being plugged in apparently is drawing enough current to drop the system voltage. This can happen if your Arduino is powered by a low-power source like a 9-volt transistor-radio battery, or a laptop USB port that can't deliver the 500 mA that a standard USB port is rated at.

If either of those causes is behind the problem, use an external power supply, plugged into the power jack or connected to Vin and Ground. You can buy suitable “wall-warts” online, or at an electronics store, or quite cheaply at second-hand or thrift shops.

But if neither of those causes is the problem, you may have a clone of an Arduino using substandard parts, and unable to deliver reasonable current through its regulators. In this case, find a well-regulated 5 V supply to connect between +5V and Ground or to the USB's power pins. Such supplies are available not only at the aforementioned venues, but also whereever USB phone-chargers are sold, since 5.0 V is what a USB phone-charger should deliver.
> 1 votes

---
Tags: arduino-uno, led, voltage-level, current
---


# Question
Title: How do you use an Arduino to control a 4 - 20 mA transmitter?
I am using an Arduino Mega to control the speed of an AC pump. This can be done by connecting to the variable frequency drive. Here is a link of the relevant datasheet, pages 66 and 67 relate to what I am doing.

http://www.parker.com/Literature/SSD%20Drives/AC%20Drives/AC650/HA464828U003.pdf

From what I have read and been told already, I should be able to control this using a 4 - 20 mA loop, which is fed into AIN2, as long as I connect the 0V terminal as well?

My question is what is the best way to make a current loop transmitter using an Arduino Mega.

So far the options I have are:

I have a budget for my project so cost is not an issue, however I am running out of time. What would be the easiest method to implement and how?

I have been thinking of using options 2 or 3, however my issues are that this is my first Arduino project. I understand what PWM is but I don't know how I would go about implementing it. I also can't find any tutorials online that demonstrate how to program the MIKROE board using an Arduino.

Thank you in advance for any help :)

# Answer
> 1 votes
I can recommend the Click boards from MikroElektronica (I am the chief engineer porting support for them, and the PIC32-based Clicker development board series, to the chipKIT™ system).

The 4-20mA-T Click board is controlled by the Microchip MCP4921 DAC. This is a common DAC family used in many Arduino projects and there are plenty of libraries around for them (mine is here though it's aimed at the 4822 not the 4921).

Basically you set the DAC output voltage which sets the current output from an XTR116 current loop transmitter.

The XTR116 takes an input of 0 - 4.095v, and provides a convenient 4.095v reference voltage to the MCP4921.

The whole thing is isolated from your main board through an ADu M1411 to keep everything safe from industrial process noise.

# Answer
> 0 votes
> I don't know how I would go about implementing it.

Both option 2/3 require coding - generally simple and doable, even for newbies.

To go down the DAC route, current-feedback DACs are quite common, especially in the good old days. they are ideal here -\> make sure your device matches up with the dac in terms of current source vs. current sink.

option 1 is good if you don't like coding. turning a voltage into a current is fairly simple.

---
Tags: arduino-mega, pwm, voltage-level, current, remote-control
---


# Question
Title: Using same pins number in different arduino?
I'm new beginner in programming arduino, and I want ask a question about arduino code, this is the problem " i used two arduino to build a robot, but i don't know how to set the code that for two arduino uno that pins in first arduino i used them all and now i wanna use the pins in second arduino, and how write code for the second arduino, which it is the same pin number i used in first arduino, how to creat a code? thanks a lot guys for answer my question... (sorry for my bad english)...

# Answer
The notion that “both Arduinos are in the same sketch” is slightly off. Each of the Arduinos will contain a program; their programs might be identical if you do some fancy programming, but it is simpler to write one sketch per Arduino.

Thus, your first Arduino will run a sketch designed to control the devices it is connected to, and your second Arduino will run a sketch designed to control the devices that it's connected to. Conceivably, you might have some devices that both Arduinos connect to.

Calling the two sketches S1 and S2, the device on pin number *n* as referred to in S1 will typically be a different device than the one on pin number *n* as referred to in S2. Most but not all of the pin usage assignments for each pin number will be different in one sketch versus the other.

It's likely the two Arduinos will need to communicate with each other. For a range of methods, see for example *How to have an Arduino communicate with 3 other Arduinos*. For additional detail see *Arduino-to-Arduino serial communication* and *How to network many Arduinos with sensors using I2C*.

If you decide to use I2C, then also see MasterWriter Tutorial and Wire Library webpages at arduino.cc.
> 1 votes

# Answer
To expand on my comment, if you begin your sketch with conditional definitions, you can compile it for different sets of pin assignments just by changing the `#define ARDUINONUMBER xxx` statement:

```
#define ARDUINONUMBER 1

#if ARDUINONUMBER == 1
#define FRONTMOTORPIN 7
#define REARMOTORPIN  8

#elif ARDUINONUMBER == 2
#define FRONTMOTORPIN 12
#define REARMOTORPIN  13

#else
#error Board number must be 1 or 2.
#endif

void setup(void)
{
   pinMode(FRONTMOTORPIN, OUTPUT);
   pinMode(REARMOTORPIN, OUTPUT);
   ; // etc
}

void loop(void)
{
   ;
}

```
> 0 votes

---
Tags: arduino-uno, serial, programming, communication, robotics
---


# Question
Title: Integrating Freescale Multi Sensor board with Arduino
I recently bought Freescale's FRDM-FXS-MULTI-B, and have been trying to integrate it with an Arduino UNO. The board descriptions say that it has the shield layout that matches that of an Arduino shield. So in theory, I should be able to integrate it fine.

The problem comes when I plug it in and try to program the Arduino. As soon as I plug it in, the board resets and hangs. If I try to upload a simple code (just reading the analogue signal from the light sensor), the IDE hangs when uploading. Sometimes, I can fix it by removing the shield and pressing the reset button, but sometimes that doesn't work: the computer doesn't recognise the Arduino on the port, and the IDE removes the port from the Port Selection option. When I do remove it and it resumes functioning normally, and I re-attach the shield, the board resets and hangs again, until I go into the Serial Monitor.

With this board, I realised the Bluetooth module is connected to the Serial Receive pin, which explains the hang in the IDE, but I cannot understand why it resets and hangs when I plug it in.

Does anyone have any experience with this board, and can help me out? Why can I not find any tutorials online? With the multitude of sensors on this shield, I'm guessing you can access them via normal I2C and SPI communications, right? How do you use the Bluetooth module on the board?

# Answer
So... 20 months later I stumbled upon this question, only to find out I wrote it. Awkward! Anyway, for anyone who stumbles across this question in the future, here is the answer.

The Rx pin is connected to the Bluetooth module, and as such the module will keep the pin in an idle state (either idle-high or idle-low). The Rx pin of the Arduino UNO (or the Rx0 pin on the Mega/Due) requires to be free of anything that may interfere with the upload. The Arduinos rely on the Rx pin for the sketch upload. If anything is connected to it, the IDE will freeze and nothing will be uploaded. Simply disconnect the FRDM board, upload the code, and put the board back in place. Then it should work.
> 0 votes

---
Tags: sensors, shields
---


# Question
Title: NodeMCU serial port - use with computer and device at the same time
I'm trying to understand how serial communication for ESP8266 in NodeMCU actually works. I found a quote saying that normal `Serial` is mapped to ports GPIO 1 (TX) and GPIO 3 (RX). They are even labeled on the board like this, so I believe this is true.

However I'd like to understand the relationship between those pins and serial communication over USB. Does this work the same way as in normal Arduino where you can use either communication over USB or hardware serial on pins 0 & 1?

I did some tests and if I run simple program like:

```
Serial.begin();
//.......
Serial.println("Hello world");

```

I can see that in serial monitor on my PC. How does that impact serial communication on GPIO 1 & 3 ?

# Answer
> 4 votes
Yes, it is the same as Arduino. The TX and RX pins connect to a CH340G chip to convert the serial into USB. If you use USB serial you can't use the pins for anything else.

---
Tags: nodemcu
---


# Question
Title: Is there any way that the two 'different' programs of arduino can be run one after another keeping each one separate?
I have made a 8\*8\*8 led cube using arduino. I have found two different codes from different developers having different animations in them. i wanted to combine them and get to run all the animations at once. Both the codes have some similar function names and some are different as well. I wanted to know if i can keep both these separate from each other yet run them one after another. Almost all parameters are different including setup() of both codes. Please help

# Answer
You can achieve this fairly simply by using **namespaces**. Inside a namespace, symbols are relative to that space. So you could put all of your first sketch into the namespace sketch1, and all of the second sketch into the namespace sketch2 (assuming it all fits, of course).

Now you can call the first sketch's setup and then loop, by qualifying it with the namespace name as illustrated below.

```
// FIRST SKETCH

namespace sketch1
{

  // FUNCTION PROTOTYPES

  void func1(int a, int b);
  void func2();

  void setup()
  {
    Serial.begin (115200);
    Serial.println ("Inside sketch1 setup");
    func1 (5, 6);
  }

  void loop()
  {
    Serial.println ("Inside sketch1 loop");
    delay (1000);
    func2 ();
  }

  void func1(int a, int b)
  {
    // some function
  }

  void func2()
  {
    // some other function
  }

} // end of namespace sketch1

// SECOND SKETCH

namespace sketch2
{

  // DECLARE FUNCTIONS BEFORE CALLING THEM

  void func3(int a, int b)
  {
    // some function
  }

  void func4()
  {
    // some other function
  }

  void setup()
  {
    Serial.begin (115200);
    Serial.println ("Inside sketch2 setup");
    func3 (7, 8);
  }

  void loop()
  {
    Serial.println ("Inside sketch2 loop");
    delay (1000);
    func4 ();
  }

} // end of namespace sketch2

// MAIN LOOP AND SETUP

void setup()
{
  pinMode (10, INPUT_PULLUP);
  if (digitalRead (10) == HIGH)
  {
    sketch1::setup ();
    while (true)
      sketch1::loop ();
  }
  else
  {
    sketch2::setup ();
    while (true)
      sketch2::loop ();
  }
}   // end of setup

void loop()
{

} // end of loop

```

In my example I am testing a pin (10) to see if sketch1 or sketch2 should run.

---

> yet run them one after another

Yes, well sketches normally keep running inside `loop` forever, so you would need a way of deciding when to exit the sketch and run the other one. My example shows how you can choose between one or the other based on a digital input.

---

> I tried it but it is showing that the functions are not declared in this scope.

## Important note re function prototypes

It looks like the IDE's automatic generation of function prototypes doesn't work inside namespaces. Thus you need to do either:

* Make your own function prototypes (that is the function declaration without the actual function code) - see sketch 1 above; or
* Declare a function before it is used (sketch 2 above)

If this is someone else's code you may find it easier to just add the function prototypes as required. When you get the error message, find the function it is referring to, copy the "declaration" part, eg.

```
void foo (int a, int b)

```

Add a semicolon, eg.

```
void foo (int a, int b);

```

Then put that **before** it is called. Make sure it is still inside the namespace.

---

> can I call the setup if first namespace then some func. respective to that namespace then call the setup of second namespace and call func. from that namespace and keep all this in an infinite loop?

Well, you *can* do that, but you need to realize what each sketch is doing. For example if sketch1 turns some pins to output, but sketch2 assumes they are still inputs, then you need to undo that.

> And what is it to wrapup a function and 'how' to do it.

You need to inspect the sketches and see what they have done, so you can "undo" it. For example:

```
void wrapup ()
  {
  // set all pins to inputs and LOW
  for (int i = 0; i < 20; i++)
    {
    pinMode (i, INPUT);
    digitalWrite (i, LOW);
    }
  // if Serial used
  Serial.flush ();  // flush output
  Seral.end ();    // stop serial hardware

  // and so on

  }   // end of wrapup

```
> 1 votes

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


# Question
Title: How to have compiler know whether Arduino or ESP8266?
I am doing some work for both Arduino Mini Pro and for a NodeMCU style ESP8266 board. Within the Arduino IDE I tell it what board I am compiling for and downloading to.

How do I access which board in my scripts?

Some sections are for one or the other exclusively. Right now I'm using a `#define` at top of the script, but changing this to switch between boards not the best. For example, version control keeps on thinking I'm in a new branch when I'm not.

# Answer
There are a number of macros defined to help you with this:

* `__AVR__` for any board with AVR architecture.
* `ARDUINO_AVR_PRO` for the **Arduino Pro or Pro Mini** selection in the **Tools \> Board** menu.
* `ESP8266` for any ESP8266 board.
* `ARDUINO_ESP8266_NODEMCU` for the **NodeMCU 0.9 (ESP-12 Module)** or **NodeMCU 1.0 (ESP-12E Module)** selections in the **Tools \> Board** menu.

This allows you to do things like this:

```
#if defined(__AVR__)
// AVR specific code here
#elif defined(ESP8266)
// ESP8266 specific code here
#endif

```
> 6 votes

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


title: Problem with PWM interference

text:
# Question
Title: Problem with PWM interference
I have a following code

```
  #include <Servo.h> //library for servo drive
  int MotorAPinA = 9;   //pin number for DC drive
  int MotorAPinB = 10;  //pin number for DC drive
  Servo myservo; //create object myservo, class servo from Servo library

void setup() {
  // put your setup code here, to run once:
  pinMode(MotorAPinA, OUTPUT);
  pinMode(MotorAPinB, OUTPUT);
  //myservo.attach(6); //pin number for servo output
  myservo.write(65);
}

void loop() {
  analogWrite(MotorAPinA, 240);
}

```

This very code works only partly.
If I comment line

```
myservo.attach(6)

```

then I got my DC drive working.
If I uncomment this line, my Servo goings crazy (effect looks like myservo.write(0) constantly), until I comment line

```
analogWrite(MotorAPinA, 240);

```

and then I got my servo working properly. While myservo.attach(6) is uncommented, DC drive doesn't work (with uncommented analogWrite).

So, basically, I can have or PWM or Servo working simultaneously, but not both

Any ideas? Arduino Uno R3, Arduino 1.8.1.

# Answer
Well, your PWM outputs are both on `16b` `Timer/Counter 1` and the servo is attached to the `8b` `Timer/Counter 0`. So my guess is that `8bit` counter has too low resolution for driving the servo and it uses `Timer/Counter 1` in full `16b` mode for better precision instead (PWM uses just `8bits` from 16). Also `Timer/Counter 0` is used for counting millis, so its settings can't be changed anyway.

For the confirmation you can either:

* use pins `5` and `6` (`TC0`) or/and pins `3` and `11` (`TC2`) and for the servo use pin `9` or `10`
* You can read the values of `TC1` configuration registers and according to the datasheet you can figure out what mode is currently used.

EDIT: So on the Uno board is used Timer/Counter 1 for timing purposes:

```
  if(timer == _timer1) {
    TCCR1A = 0;             // normal counting mode
    TCCR1B = _BV(CS11);     // set prescaler of 8
    TCNT1 = 0;              // clear the timer count
    TIFR |= _BV(OCF1A);      // clear any pending interrupts;
    TIMSK |=  _BV(OCIE1A) ;  // enable the output compare interrupt
    timerAttach(TIMER1OUTCOMPAREA_INT, Timer1Service);
  }

```

So no `PWM` on the `OC1A` nor `OC1B` in normal mode and the channel A is taken by Servo.
> 1 votes

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


# Question
Title: Make something happen on a continous input just once and for a specific amount of time
My project is very complicated, but here is a visual synthesis

The input actually comes from a kinect, that detects a person position through Processing, which I connected via Serial to Arduino. Whenever my trigger is activated, a character is sent to arduino. What I need to make everything work properly is, upon the said input, some lines of code have to be executed once and for a specific amount of time. And upon repeated input, these lines must not be executed until the input changes.

A semplified version would be: I press a button, led turns on for one second and then turns off (even if i'm still pressing it). led doesn't turn on again until i stop pressing and press again. Obviously in my project the input is the character received via serial and the output is the motor to turn on for some time, and then turn off.

I wanted to make the serial thing specific because i think it makes the thing a little bit trickier than the led example.

# Answer
Well, te problem is actually the same provided that you write correctly the first program.

How did you solve the button problem? My suggestion is to use a simple state machine:

```
const byte ledPin = 13;
const byte buttonPin = 2;

const int onTimeMs = 1000; // The time the led should be on

// In this state the board waits
// for the user input
#define STATE_WAITING 0
// In this state the button was
// pressed (so the led is on)
#define STATE_PRESSED 1
// In this state the board is waiting
// for the button to be released
#define STATE_WAITREL 2

byte currState;
unsigned long pressTime;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  currState = STATE_WAITING;
}

void loop() {
    switch (currState)
    {
    case STATE_WAITING:
        if (digitalRead(buttonPin) == LOW)
        {
            digitalWrite(ledPin, HIGH);
            pressTime = millis();
            currState = STATE_PRESSED;
        }
        break;
    case STATE_PRESSED:
        if ((millis() - pressTime) > onTimeMs)
        {
            digitalWrite(ledPin, LOW);
            currState = STATE_WAITREL;
        }
        break;
    case STATE_WAITREL:
        if (digitalRead(buttonPin) == HIGH)
            currState = STATE_WAITING;
        break;
    }
}

```

In this case you can be in three states: waiting for the button press, waiting for the led to turn off (after one second) and waiting for the user to release the button.

So... The states remain the same even for the serial input, you just have to trigger the transitions in another way. The only problem is that the serial input is not continuous, so you have to determine what you mean by "stop sending". In my opinion, you can just set a timeout. The simplest way to achieve this is with this code, IMHO:

```
const byte ledPin = 13;
const char cmdChar = 'x';

const int onTimeMs = 1000; // The time the led should be on
const int timeoutCmdChar = 50; // The time the char should be off

// In this state the board waits
// for the user input
#define STATE_WAITING 0
// In this state the character was
// received (so the led is on)
#define STATE_RECEIVED 1
// In this state the board is waiting
// for the char to be absent
#define STATE_WAITABS 2

byte currState;
unsigned long recvTime;

unsigned long lastTimeCmdChar;

void setup() {
    pinMode(ledPin, OUTPUT);
    Serial.begin(9600);
    currState = STATE_WAITING;
}

void loop() {
    bool cmdCharReceived = false;
    while (Serial.available())
    {
        if (Serial.read() == cmdChar)
        { // Received the character
            cmdCharReceived = true;
            lastTimeCmdChar = millis();
        }
    }

    switch (currState)
    {
    case STATE_WAITING:
        if (cmdCharReceived)
        {
            digitalWrite(ledPin, HIGH);
            recvTime = millis();
            currState = STATE_RECEIVED;
        }
        break;
    case STATE_RECEIVED:
        if ((millis() - recvTime) > onTimeMs)
        {
            digitalWrite(ledPin, LOW);
            currState = STATE_WAITABS;
        }
        break;
    case STATE_WAITABS:
        if ((millis() - lastTimeCmdChar) > timeoutCmdChar)
            currState = STATE_WAITING;
        break;
    }
}

```
> 1 votes

# Answer
you want something along the lines:

```
bool continuing;
#define trigger 't'
void loop(){
  if( Serial.avaiable()) {
    char c;
    c=Serial.read();
    if (continuing) {
       if (c==trigger) { //do nothing, ignore it
       } else {
       continuing=False; }
   } else {
     continuing=True;
     motors.start();
     the_time=milis();
   }
 };
 if (the_time+timespan>milis()) {motors.stop();};
}

```
> 1 votes

---
Tags: serial, millis, input
---


# Question
Title: Bluetooth data: how to handle these data?
I'm reading a BLE device and my api return me this struct

```
typedef struct {
  LGATTAddress bd_addr;
  int32_t rssi;
  uint8_t eir_len;
  uint8_t eir[256];
} LGATTDeviceInfo;

```

I try to print some eir\_len and eir\[256\] and this is the result

```
  for(int i = 0; i < 255; i++)
  {
    Serial.print(info.eir[i], HEX);
  }
  Serial.println();

  Serial.print("Advertising data lenght: ");
  Serial.print(info.eir_len);
  Serial.println();

    21613FF4C0CE8E1B87D83CB43431A739F4496E0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    Advertising data lenght: 23

    2167FF4C0102B00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    Advertising data lenght: 11

    216320A0109524543414D3532474A5830313235315125005002A0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    Advertising data lenght: 33

```

I cannot understand the relation between the air and the lenght: in the second example the response is 13 char but the lenght is 11. Why?

According to bluetooth specs..

The data is 240 octets and consists of a significant part and a non-significant part. The significant part contains a sequence of data structures. Each data structure shall have a length field of one octet, which contains the Length value, and a data field of Length octets. The first n octets of the data field contain the extended inquiry response (EIR) data type. The content of the remaining Length - n octets in the data field depends on the value of the EIR data type and is called the EIR data. The non-significant part extends the extended inquiry response to 240 octets and shall contain all-zero octets.

How can I parse the eir to obtain all the data? For example the name of the device and the manufacturer data?

**update**

Let's take for example this response

\[LGATTC ino\]dev address : \[8:46:be:ca:2c:2\] rssi \[-63\]

```
2 1 6 9 8 69 53 65 6E 73 6F 72 20 9 FF BE CA 2C 2 46 2 5F 5D 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Advertising data lenght: 23

```

I try to convert the hex to string and this part `69 53 65 6E 73 6F 72` is the sensor name (iSensor).

This is a bluetooth sensor that change in this way

```
<be ca 2c 02 46 02 58 56> - > open
<be ca 2c 02 46 00 59 55> - > close
<be ca 2c 02 46 02 5a 58> - > open
<be ca 2c 02 46 00 5b 57> - > close
<be ca 2c 02 46 02 5c 5a> - > open
<be ca 2c 02 46 00 5d 59> - > close
<be ca 2c 02 46 02 5e 5c> - > open
<be ca 2c 02 46 00 5f 5b> - > close

```

These are the manufacturer data: the first part `be ca 2c 02` is the unique identifier of the device, the `02/00` identify the status of the sensor...

By the way I negin to understand... I notice now the match between the lenght and the eir!

I must now extract the name in char, the status and the device code!

**edit 2** I found the specs of my sensors...

# Answer
> 1 votes
> I cannot understand the relation between the air and the lenght: in the second example the response is 13 char but the lenght is 11. Why?

The hex numbers may be one or two digits long. The way the values are being printed does not enable you to discern between `1 2 3`, `12 3` and `1 23`. Try this:

```
for(int i = 0; i < 255; i++)
{
  Serial.print(info.eir[i], HEX);
  Serial.print(" ");
}

```

(Someone already told you this.)

---

> How can I parse the eir to obtain all the data? For example the name of the device and the manufacturer data?

This works for the only example of the data you have given. If I have guessed correctly how further data will follow, it'll work for them too. (If I haven't, it won't.) I have assumed that the name always starts in the same place, ends with a space, three bytes of stuff we don't care about, and that the data is groups of 8 bytes. It's very likely that some of the other bytes give details of the data to follow, but with only one example and no spec, it's basically impossible to tell.

```
// Let's assume the sensor name always starts at element 5...
char *sensorName = &(info.eir[5]);
// ...and ends on a 0x20 (space) - which is probably a risky assumption
char *end = strchr(sensorName, ' ');
if (end)
{
    *end = '\0';
    // Sensor name is now in sensorName

    // Let's assume the data starts exactly 4 bytes after the end of the name
    uint8_t *dataItemStart = (uint8_t*)(end + 3);
    uint8_t *dataEnd = info.eir + info.eir_len - 1;
    while(dataItemStart < dataEnd)
    {
        // We have a data item here, as 'dataItemStart'.
        // You can get bytes within it using, for example
        //   dataItemStart[5]
        // to get the 6th item (the 00 or 02 in your examples)

        // Each data item is 8 bytes long, so the next one starts 8 bytes later
        dataItemStart += 8;
    }
}

```

---
Tags: c++, bluetooth
---


# Question
Title: Timeout error uploading code to Arduino Mega 2560
I am new to Arduino programming, and my first sketch (from a tutorial) failed to upload. I am having trouble trying to figure out what is causing it (have tried to upload the sketch using different COM ports on my Mac).

Here's my setup:

> USB COM Port -\> Arduino Mega 2560 -\> Grove Mega Shield -\> Grove Temperature Sensor v1.2 connected to Mega Shield UART0.

Here's the code from the tutorial:

```
// Demo code for Grove - Temperature Sensor V1.1/1.2
// Loovee @ 2015-8-26

#include <math.h>

//R0 = 100000 results in 'overflow in implicit constant conversion'

const int B=4275;                 // B value of the thermistor
const int R0 = 100000;            // R0 = 100k
const int pinTempSensor = A5;     // Grove - Temperature Sensor connect to A5

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

void loop()
{
    int a = analogRead(pinTempSensor );

    float R = 1023.0/((float)a)-1.0;
    R = 100000.0*R;

    float temperature=1.0/(log(R/100000.0)/B+1/298.15)-273.15;//convert to temperature via datasheet ;

    Serial.print("temperature = ");
    Serial.println(temperature);

    delay(100);
}

```

And here's the error output:

```
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_cmd(): short reply, len = 0
avr_read(): error reading address 0x0000
    read operation not supported for memory "signature"
avrdude: error reading signature data for part "ATmega2560", rc=-2
avrdude: error reading signature data, rc=-1
avrdude: stk500v2_ReceiveMessage(): timeout

```

What I have done so far:

1) Disconnect and reconnect USB Cable
2) Restart Arduino IDE (1.6.9)
3) Changed COM Ports
4) Press the reset button

Could someone please explain to me what the error output means?

# Answer
Have you tried to upload your sketch without the shields? I had a similar problem once where I couldn't upload while a connection was plugged into UART0. Unplugging the sensor worked for me.
> 1 votes

# Answer
Connect Mega 2560 in one of your port, select the right com port, and try to load the white sketch, look if you obtain the same error..

```
//white sketch
void setup(){}
void loop(){}

```
> 1 votes

# Answer
Under tools I think it is. Make sure that the arduino you are using is selected and also the right com port (usb port) That might fix the problem
> 0 votes

---
Tags: arduino-mega, avrdude
---


# Question
Title: How can I see if volume buttons of Apple earphones are pressed?
I need to be able to see if the volume controls and the middle button of Apple earphones are pressed.

I am using an Arduino Uno. I was thinking about using the `analogRead` function.

I tried connecting the ground of the audio jack to the ground of the Arduino, the micro of the audio jack to the analogPin 0 on the left and right of the audio jack to the 3.3 volt output of the Arduino, but the results of the `analogRead` are not really useful. They are constantly changing.

---

So guys i have this code that constantly gives a bunch of numbers. They are never constant.

```
int analogPin = 0;
int ledPinBlue = 8;
int ledPinRed = 9;

int val = 0;
int times = 0;
int clickTimes = 0;

void setup()
{
  pinMode(ledPinBlue, OUTPUT);
  pinMode(ledPinRed, OUTPUT);
  times = 0;
  Serial.begin(9600);
}

void loop()
{
  val = analogRead(analogPin);
  if (val == 0) {
times = times + 1;
  }
  else if (!val == 0) {
times = 0;
  }
  if (times == 500) {
times = 0;
digitalWrite(ledPinBlue, HIGH);   // sets the LED on
delay (500);
digitalWrite(ledPinBlue, LOW);    // sets the LED off
Serial.println("Click");
  }
}

```

When I press the button of the microphone (the middle button) of the apple earphones, the numbers change to a constant 0.

But when I press the volume buttons, nothing seems to change. Any ideas?

# Answer
> 1 votes
Here is an article that explains the inner working of the Apple headphones:

http://tinymicros.com/wiki/Apple\_iPod\_Remote\_Protocol

# Answer
> 0 votes
Have you tried searching Apple Earphones Schematic or something similar? You probably won't find a schematic, at least not from Apple, but I did find this discussion of someone's attempt to figure out what the buttons do, on some kind of Apple earphones or other (you didn't say which ones you have). There must be others who have also experimented with this.

# Answer
> 0 votes
Since you say that an Android headset would be an alternative....

Google have published the specs for how headset controls work on Android: in short, (up to) four different values of resistor connected between `mic` and `gnd` represent the four buttons.

If you just need to read the controls, use a potential divider between Vcc and ground, and read the mid point with an analogue input to tell you which (if any) key is being pressed.

simulate this circuit – Schematic created using CircuitLab (Wow, that's big... Dunno how to make it smaller :-) )

---
Tags: arduino-uno, serial, analogread, audio
---


title: Not understanding C++ arrays

text:
# Question
Title: Not understanding C++ arrays
I'm attempting to re-write a library for the CD74HC4067 multiplexer. There is a library available for this device on the Arduino Playground, however, it's limited in its functionality.

I have this as a private data member in the class header file:

```
uint8_t channelSelects[16][4];

```

And this in the class constructor:

```
CD74HC4067::channelSelects[16][4] = {
    { 0,0,0,0 }, // channel 0
    { 1,0,0,0 }, // channel 1
    { 0,1,0,0 }, // channel 2
    { 1,1,0,0 }, // channel 3
    { 0,0,1,0 }, // channel 4
    { 1,0,1,0 }, // channel 5
    { 0,1,1,0 }, // channel 6
    { 1,1,1,0 }, // channel 7
    { 0,0,0,1 }, // channel 8
    { 1,0,0,1 }, // channel 9
    { 0,1,0,1 }, // channel 10
    { 1,1,0,1 }, // channel 11
    { 0,0,1,1 }, // channel 12
    { 1,0,1,1 }, // channel 13
    { 0,1,1,1 }, // channel 14
    { 1,1,1,1 }  // channel 15
};

```

And I'm getting this error:

```
cannot convert '<brace-enclosed initializer list>' to 'uint8_t {aka unsigned char}'

```

Could someone please explain what I'm not understanding here ?

Many thanks in advance.

# Answer
If you have in your constructor this:

```
CD74HC4067::channelSelects[16][4] = ...

```

then you are trying to assign something into the element at position `[16][4]`. Thats why it's telling you

> cannot convert '' to 'uint8\_t {aka unsigned char}'

Anyway - you don't even need that second dimension. You can use binary representation like `0b00001000` ...

And if you'll think about previous line, you don't even need any array, you can do it with simple counter value and getting its bits.

However if you want to rely on this array, the constructor should look like:

```
CD74HC4067::CD74HC4067() :
  channelSelects {
    { 0,0,0,0 }, // channel 0
    { 1,0,0,0 }, // channel 1
    { 0,1,0,0 }, // channel 2
    { 1,1,0,0 }, // channel 3
    { 0,0,1,0 }, // channel 4
    { 1,0,1,0 }, // channel 5
    { 0,1,1,0 }, // channel 6
    { 1,1,1,0 }, // channel 7
    { 0,0,0,1 }, // channel 8
    { 1,0,0,1 }, // channel 9
    { 0,1,0,1 }, // channel 10
    { 1,1,0,1 }, // channel 11
    { 0,0,1,1 }, // channel 12
    { 1,0,1,1 }, // channel 13
    { 0,1,1,1 }, // channel 14
    { 1,1,1,1 }  // channel 15
  }
{
   // constructor code
}

```

(maybe one more {} enclosure, I'm not sure right now exactly)

**EDIT**: I'd go this way (if you need only one or two instances):

```
// ADC READ channel + Address selection pins
template <uint8_t ADC_Chan, uint8_t Addr0, uint8_t Addr1, uint8_t Addr2, uint8_t Addr3>
class Mux16b {
public:
  void initPins () {
    pinMode(Addr0, OUTPUT);
    pinMode(Addr1, OUTPUT);
    pinMode(Addr2, OUTPUT);
    pinMode(Addr3, OUTPUT);
    pinMode(ADC_Chan, INPUT);
  }

  int readMux(uint8_t channel) {
    digitalWrite(Addr0, channel&1 != 0);
    digitalWrite(Addr1, channel&2 != 0);
    digitalWrite(Addr2, channel&4 != 0);
    digitalWrite(Addr3, channel&8 != 0);
    // maybe some delay to stabilize voltage at the ADC_Chan input ??
    return analogRead(ADC_Chan);
  }

  // not necessary but it's easier to use   mux(10) than mux.readMux(10)
  int operator()(uint8_t channel) { return readMux(channel); }
};

// analogRead from A0, Address pins: 4 9 5 2
Mux16b<A0,4,9,5,2>  mux;

void setup() {
  Serial.begin(115200);
  mux.initPins();
}

void loop() {
  Serial.println(mux.readMux(15));

  Serial.println(mux(12)); // using overloaded operator ()

  delay(5000);
}

```
> 1 votes

# Answer
I moved the initialization to the header file where it was first declared... It compiled without errors.
> 1 votes

# Answer
You need `,` at the channel 15 line too.
> -1 votes

---
Tags: c++, array
---


# Question
Title: Need help modelling and coding a feedback scenario
Above illustration is the basic setup for the question. The scenario will be the following:

> A potentiometer(providing 0 to 5V) is an analog input to A0. This potentiometer voltage is converted to PWM(pin9) which controls a fan M1. Which means the human controls directly the M1 fan speed.
>
> This directly speed-controlled M1 fan creates air pressure on a sensor Sen1.
>
> On the other hand I want M2 fan to reach to a speed(via pin10 PWM) such that Sen2 should output the same voltage as Sen1. Which means eventually voltage at A1 analog input should be equal to A2. So one can achieve same air pressures at Sen1 and Sen2.

I'm not experienced in PID or other type of controls. I would be glad if someone can help me to relate parameters and code this scenario.

# Answer
> 2 votes
Well, (very) simply you could slowly increase/decrease the PWM value driving M2 until the voltage at A1 equals that of A2. If you make the time between adjustments long enough you should not get any (significant) oscillations.

However, more likely you want to get to the correct M2 PWM value quickly and for that you need a **Proportional, integral, Differential *(PID)*** control algorithm. Explaining this in detail is outside the scope of a S.E. answer, but in summary:

You have a value that signifies the current state of the system - which will be the A2 reading. You also have a value that states where you want to get to - which will be the A1 reading. You also have a control value - which will be the PWM value of M2

The `Proportial` part looks at how far away the A2 reading is from the A1 reading. The `Integral` part looks at how quickly we (the A2 reading) are moving towards (or away from) the desired value (the A1 reading). The `Differential` part looks at how long we have been away from the desired value.

Each of these (PID) parts (with tuning values that you set) contributes towards determining a new value for PWM at M2 and this iterates around with new values getting the current state closer and closer to the desired value.

There are lots of Arduino PID examples around. I'd suggest you read up on the algorithm itself and have a look at the Arduino.cc samples here.

# Answer
> 1 votes
PID loops are a good way to go for something like this, but, you don't need to implement all three parts. I have done industrial control using just the P and I. Start by implementing just the proportional part.

For this, you calculate the error between the input signal (Va0) and the feedback signal (Va1). This is just a subtraction Err = Va0 - Va1.

You now multiply the Err by a constant and add that to Va0 to adjust the PWM.

A bit like this pseudo code:

```
  k = 0.5;
  Err = Va0 - Va1;
  pwm = Va0 + (Err * k);

```

Then set the pwm to the new calculated value.

This gives a correction **p**roportional to the error.

Experiment with k. Start at 1. See how it goes.

Depending on the sensors you may have to apply some gain and/or offset to the Va1 reading in order to make it so that when the motor is at the correct speed, the calculated Va1 reading reads the same as the Va0 input. For example, say the output range of the sensor is 0V to 2.5V, you will need to multiply by 2 before calculating the Err.

The P part of PID can give acceptable results. The next stage would be to implement an I part. Do the P and see whether the I is needed.

# Answer
> 0 votes
> I want M2 fan to reach to a speed(via pin10 PWM) such that Sen2 should output the same voltage as Sen1.

simple:

```
  adc_sens1 = readadc(SENS1_PIN); //read adc on sense 1 pin
  adc_sens2 = readadc(SENS2_PIN); //read adc on sense 2 pin
  if (adc_sens2>adc_sens1 + SENS_DELTA) pwm_set(M2_PIN, --dc_ms); //if sens2 value too high, slow down m2's duty cycle -> positive correlatin assumed
  if (adc_sens2<adc_sens1 - SENS_DELTA) pwm_set(M2_PIN, ++dc_ms); //otherwise, increment duty cycle

```

No error check, no boundary check, ..... but the basic idea is the same.

---
Tags: motor, pid
---


# Question
Title: Showing chronometer on PC controlling the begining and end of time by Arduino
I'm really new on this Arduino thing, so I don't know whether what I'm gona ask is feasible or not.

I'd like to make a chronometer in the computer but the controlling button (beginning and end of count) not to be some computer key. So I was wandering if I could make a button controlled by the arduino - maybe via a piezoelectric element?

Besides the problem of not knowing what to use as a button, I don't really know if it's possible to make a graphical interface (i know how to programme in C, Python, ...) showing the numbers in the screen of the computer and the beginning and end of counting controlled by that button. Is this possible to do?

Thanks for any help to both questions!

# Answer
It's perfectly possible to do, and the way I would probably do it is to use one of the ATMega32U4 based Arduinos (such as the Arduino Leonardo or the somewhat smaller Arduino Micro) to act like a keyboard. A keyboard with just one key - your chosen button.

Then you program the computer to respond to the keycode the Arduino sends to start and stop the chronometer. You could even use an off the shelf chronometer program that starts and stops with a specific keypress and tell the Arduino to send that keypress. It would probably take about 5 minutes to write the software - if that.
> 0 votes

# Answer
I am already familiarized with the concept of serial communication. I can turn on/off LED via Serial Monitor.

I can also connect it with Python and I've made a small program that makes the LED blink - and this works perfectly.

However I now added a pushbutton to my circuit, so that when it is pressed, the blinking process is interrupted. But this is not working. My attempt was to send a Serial.print when the pushbutton is pressed with the message "Exiting\n".

Part of my Arduino code is:

```
if(digitalRead(BUTTON) == HIGH){
Serial.print("Exiting\n");
while(1){}
}

```

And part of my Python code is:

```
while True:
    arduino.write("Y")
    print arduino.readline()
    time.sleep(0.5)
    arduino.write("N")
    time.sleep(0.5)

    try:
       if arduino.readline() == 'Exiting\n':
          print arduino.readline()
          break
    except:
          print("nothing\n")

```

The problem is that when I run the program, it gets stucked in the line

```
if arduino.readline() == 'Exiting\n':

```

Any help?
> 0 votes

---
Tags: programming, c, button, time, python
---


# Question
Title: Why won't my iMac recognize my Mega32u4 Arduino Pro Micro board (I've tried several cables)?
I bought this Pro Micro on eBay a while back, and I never really got around to using it. But now that I do my iMac won't recognize the board. I plug it into my iMac and open Arduino and go to the board tab, and it doesn't even have a Pro Micro choice, so I just choose Micro.

In ports it isn't showing up like my other boards do. Is it my computer, because my Chinese clone Uno and Mega weren't being recognized a while ago? I downloaded the CH340 chip driver for them because they used the CH340 chip and now they are recognized and work perfectly!

The thing is the Pro Micro does not use that chip so is there something else I have to do like another driver to download? It is not the cable because I have tried 5 cables and some had the symbol with the circle triangle and square connected on them, which is the usb serial symbol I think, so they aren't just power cables. If anyone knows what the problem is, that would be awesome! Here is the error it gives me when I try to upload it.

```
 Arduino: 1.6.9 (Mac OS X), Board: "Arduino/Genuino Micro"

failed MSpanList_Insert 0x31dea0 0x29ab70fa1fa 0x0
fatal error: MSpanList_Insert

runtime stack:
runtime.MSpanList_Insert(0x2c70d0, 0x31dea0)
/usr/local/go/src/runtime/mheap.c:692 +0x8f
runtime.MHeap_Alloc(0x2c6d20, 0x6, 0x10000000034, 0xf989)
runtime.MCentral_CacheSpan(0x2d10d8, 0x30c270)
/usr/local/go/src/runtime/mcentral.c:85 +0x167
runtime.MCache_Refill(0x308000, 0xc200000034, 0x30c270)
/usr/local/go/src/runtime/mcache.c:90 +0xa0

 goroutine 1 [running]:
 runtime.switchtoM()
/usr/local/go/src/runtime/asm_amd64.s:198 fp=0xc2082b7468          sp=0xc2082b7460
 runtime.mallocgc(0x2200, 0x19ff80, 0x0, 0xc2080d68e9)
/usr/local/go/src/runtime/malloc.go:178 +0x849 fp=0xc2082b7518     sp=0xc2082b7468
 runtime.newarray(0x19ff80, 0x20, 0xa5ca)
/usr/local/go/src/runtime/malloc.go:365 +0xc1 fp=0xc2082b7550    sp=0xc2082b7518
 runtime.hashGrow(0x1b4300, 0xc2080dc150)
/usr/local/go/src/runtime/hashmap.go:744 +0x86 fp=0xc2082b7580    sp=0xc2082b7550
 runtime.mapassign1(0x1b4300, 0xc2080dc150, 0xc2082b7698, 0xc2082b7688)
/usr/local/go/src/runtime/hashmap.go:456 +0x568 fp=0xc2082b7620  sp=0xc2082b7580
  arduino.cc/builder/props.PropertiesMap.Merge(0xc2080dc150,      0xc2082b7748, 0x1, 0x1, 0x3)
/Users/jenkins/jenkins/workspace/arduino-builder-     macosx/src/arduino.cc/builder/props/properties.go:162 +0x153     fp=0xc2082b7718 sp=0xc2082b7620
 arduino.cc/builder/props.PropertiesMap.Clone(0xc20803ce40, 0xb2f5f)
/Users/jenkins/jenkins/workspace/arduino-builder-    macosx/src/arduino.cc/builder/props/properties.go:170 +0xad fp=0xc2082b7770     sp=0xc2082b7718
 arduino.cc/builder.(*RecipeByPrefixSuffixRunner).Run(0xc20801e300,     0xc208068000, 0x0, 0x0)
/Users/jenkins/jenkins/workspace/arduino-builder-    macosx/src/arduino.cc/builder/recipe_runner.go:53 +0x2c4 fp=0xc2082b78e8    sp=0xc2082b7770
arduino.cc/builder.runCommands(0xc208068000, 0xc2082b7af8, 0x1c, 0x1c,     0xc208038001, 0x0, 0x0)
/Users/jenkins/jenkins/workspace/arduino-builder-   macosx/src/arduino.cc/builder/builder.go:181 +0x139 fp=0xc2082b7978    sp=0xc2082b78e8
 arduino.cc/builder.(*Builder).Run(0xc2082b7ce0, 0xc208068000, 0x0,   0x0)
/Users/jenkins/jenkins/workspace/arduino-builder-  macosx/src/arduino.cc/builder/builder.go:116 +0xe8e fp=0xc2082b7cc0   sp=0xc2082b7978
 arduino.cc/builder.RunBuilder(0xc208068000, 0x0, 0x0)
/Users/jenkins/jenkins/workspace/arduino-builder- macosx/src/arduino.cc/builder/builder.go:212 +0x49 fp=0xc2082b7ce8  sp=0xc2082b7cc0
 main.main()
/Users/jenkins/jenkins/workspace/arduino-builder-   macosx/src/arduino.cc/arduino-builder/main.go:316 +0x171b fp=0xc2082b7f98    sp=0xc2082b7ce8
 runtime.main()
/usr/local/go/src/runtime/proc.go:63 +0xf3 fp=0xc2082b7fe0   sp=0xc2082b7f98
 runtime.goexit()
/usr/local/go/src/runtime/asm_amd64.s:2232 +0x1 fp=0xc2082b7fe8    sp=0xc2082b7fe0
arduino-builder returned 2
Error compiling for board Arduino/Genuino Micro.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

# Answer
From what you say here:

> I plug it into my iMac and open Arduino and go to the board tab, and it doesn't even have a Pro Micro choice, so i just choose Micro.

and from the dump you provide:

> Arduino: 1.6.9 (Mac OS X), Board: "Arduino/Genuino Micro"

It looks to me like you're selecting the wrong board. Instead of just picking a "similar" board from the Tools menu, what you should do is add the Sparkfun board manager package and then select the Pro Micro from it.

Here you can find the procedure step by step. Follow it and you should be all set.

**EDIT:**

If you tried to upload a sketch with a wrong board selection, then your your Pro Micro may have become "bricked". In order to unbrick it, follow this procedure (same link as above, different section).

Once you unbrick it, upload the specific blink example code for Pro Micro that you can find in another section of the same link.

If it keeps not working, READ THE ENTIRE ARTICLE linked and try out all troubleshooting instructions before anything else.
> 1 votes

---
Tags: arduino-pro-micro, atmega32u4
---


title: Disable SCK temporarily to save power

text:
# Question
Title: Disable SCK temporarily to save power
for logging of environmental data, I am using a MicroSD card adapter (no brand name, eBay, China) and a 4GB Intenso SD card. I want to read data and write it to the SD card once every 10 minutes. Power consumption needs to be as low as possible.

Between the measurement points, I switch off the power supply to my sensor and SD card adapter using an NPN transistor (BC547B, 2N3904, 2SC945) and put my controller to sleep using jeelib. Everything works fine!

*But* I realized, that even during sleep, still 1mA of current is drawn. This disappears, when I remove the SCK connection between the Arduino and the SD controller. Doesn't sound like a lot, but for my purposes, it's a major concern (when SCK is removed, I'm around 6µA during sleep).

**Is it possible to switch the SCK signal off during sleep to save that last bit of power?**

In case it matters, I am using the SdFat library to write to SD. Initialization is done before each write. I figured, this would be necessary because of the poweroff of 10 minutes. Here's the function:

```
#include <SdFat.h>
const int chipSelect = 10;
String outfilename = "Bienen.log";

```

\[...\]

```
int writeToFile(String outfilename, String writestring) {

  SdFat SD;
  if (!SD.begin(chipSelect)) {
#ifdef DEBUG
    Serial.println("Card failed, or not present");
    error_signal();
#endif
  } else {
#ifdef DEBUG
    Serial.println("card initialized.");
#endif
  }

File outfile = SD.open(outfilename.c_str(), FILE_WRITE);
#ifdef DEBUG
  Serial.println(outfile);
#endif
  if (outfile) {
    outfile.println(writestring);
    outfile.close();
#ifdef DEBUG
    Serial.println("Wrote successfully.");
    ok_signal();
#endif
    return 0;
  } else {
#ifdef DEBUG
    Serial.println("Writing failed.");
    error_signal();
#endif
    return 1;
  }
}

```

ok\_signal() and error\_signal() are merely functions to flash an LED.

**EDIT:** Thanks for your reply! I tried the code snippets

```
SPCR &= ~_BV(SPE)

```

and

```
SPCR |= _BV(SPE)

```

at the appropriate places, although I did not understand them. There was, however, no change in power consumption - SCK still seems to run.

I could not adapt the physical changes detailed in the suggested wordpress article, as the adapter there is quite different from my microSD adapter, and I know too little about hardware to adapt the author's suggestions. It looks and sounds quite promising though ...

Thanks for your time! Any help is greatly appreciated!

# Answer
> 2 votes
Re-visiting the issue, I have found a simple answer:

I set the SPI pins as outputs and inputs respectively:

```
const int chipSelect = 10;
const int MOSIPin = 11;
const int MISOPin = 12;
const int SCKPin = 13;

```

and

```
  pinMode(chipSelect, OUTPUT);
  pinMode(MOSIPin, OUTPUT);
  pinMode(MISOPin, INPUT);
  pinMode(SCKPin, OUTPUT);

```

Now, before I power down my machine, I do the following:

```
  SPI.end();
  digitalWrite(SCKPin, HIGH);
  digitalWrite(chipSelect, HIGH);
  digitalWrite(MOSIPin, HIGH);

```

Now, the drawn current drops from 1mA to roughly 0,02mA, which is satisfactoy for me!

Thanks for reading!

---
Tags: power, spi, sd-card
---


title: What are devices in this picture?

text:
# Question
Title: What are devices in this picture?
I don't know the name of those. Please advise me.

Thanks very much.

# Answer
Item all the way to the right are these Excellway ET25 2/3/5 Pins Spring Terminal Block Electric Cable Wire Connectors
> 1 votes

# Answer
It's a Seeeduino Lotus (or a clone of it).
> 0 votes

---
Tags: arduino-uno
---


title: Newbie Arduino DC motor problem

text:
# Question
Title: Newbie Arduino DC motor problem
So I am new to Arduino and new to electronics in general. I've looked up a few tutorials and they all have a simple early tutorial that turns on a DC motor and turns it off again. Something like this:

<sub>(source: cloudfront.net)</sub>

The transistor I am using is a 2N2222 and the motor is a little 3V DC toy motor.

The problem is that the when I use this circuit, the motor barely turns (I need to give it a little help to get it it moving). I know my code is right (motor is on for 5 seconds, off for 1). i can tell this is working but clearly something is not right.

I am powering the Arduino off the USB port.

As a test, I swapped out the 2.2K Ohm resistor for a 560 Ohm resistor and the motor seems to run fine. However, it creeps during the "off" time (the motor is not under any load). Also, the transistor gets very hot after about a minute of running this loop.

So my questions are:

1. Why does the motor not work when I use the 2.2K Ohm resistor when I see that 2.2K Ohm resistor in different circuit diagrams that demonstrate this type of circuit?
2. Why does changing to the 560 Ohm have the effect that it does
3. Why does the motor creep during the off cycle when using the 560 Ohm?
4. Why does the transistor get so hot using the 560 Ohm resistor?
5. Finally, sometimes as a test, to simple try to turn turn the motor on, I will just reroute to pin 9 wire directly to the Arduino 5V on my breadboard (bypassing Arduino control altogether). Is there any reason this is a bad idea?

I am anticipating questions about current draw but my multimeter maxes out at 200mA; I am getting a new one that goes to 10A and will help me see how much I am drawing.

Thanks in advance of any help. I have tried to be clear and concise so hopefully this does not elicit any snark. If there are any resources to point me to, I would be happy to hear them.

Thank you!

Jim

# Answer
I see a couple of issues here, which are related to your questions. I will use numbers here, but these do not necessarily correspond to the numbers you have used when asking.

1. The first thing you need to do when controlling a motor is to know it maximum *stall* current. The stall current is the current that will circulate through the motor (and through the transistor) when you apply an external force to stop the motor's shaft. But it's also the same current needed for the motor to start when it's completely stopped. So, for dimentioning a transistor, you typically will select one that has, as a rule of thumb, a collector current **two times bigger than the motor's stall current.**
2. The 2N2222 has a maximum Ic of 800 mA (best case, since there are 600 mA versions as far as I know). Although you are not specifying much about your particular motor, a typical 3V DC motor may easily be asking for 500+ mA. Some small motors (specially bad quality ones) may have stall currents bigger than 1 A.
3. If your motor is asking for, let's say 300 mA when continuously running, then, you are near enough of the maximum current of the 2N2222.
4. But there is something more important here: dropout voltage in the transistor. The 2N2222 is a bipolar one, so it will have a Vce superior to 1V (probably around 2V), which means that you are dissipating a non trivial amount of power *in the transistor*. That power is not useful for your motor, nor for your transistor. Here, if the motor has a 3V nominal voltage, the 2V dropout in the transistor is even desirable, but I don't see your calculations about the real dropout in your description. So I assume that you are just counting that there will be an approximate 2V dropout. That means that, if your motor is taking 0.5A to work, you are dissipating 2V x 0.5A = 1W (Watt) in the transistor. **But the poor 2N2222 is a 0.5W transistor!** But even if your motor is using much less current, let's say 0.25 A, you are sill using it at its limits. That will explain why it's getting hot.
5. So, my advice is to go for a bigger transistor, if you want to count on its dropout to do not apply a voltage bigger than 3V to the motor (which can really reduce it lifespan **a lot**), AND do some calculations to be sure that at the currents you are using, you will have the Vce that you want.
6. Another option, probably better, is to replace that bipolar old transistor by a MOSFET, but you will need to provide the apropiate voltage for supplying the motor, since if not you will get nearly all the 5V to the motor (due to the very low Ron on Mosfets, and thus very low dropout voltage), and that will be very bad.
7. Also, please note that the 500mA of the USB port are probably not enough for your setup. But even if you are powering your Arduino from an external power supply through its power jack, you will find a good idea to use common grounds but different Vcc sources for logic and for the motor.
8. Finally a short advice: be sure that the diode protecting the back EMF (the diode connected with its cathode to Vcc in your circuit) is a **fast diode**. A slow, 1Nxxxx diode is usually to slow for effectively protecting your transistor. If you are using for example an 1N4007, you can switch to a UF4007 (Ultra Fast).
9. Regarding your 560R vs 2K2 resistor, this exceeds the answer a bit, so my advice is to read something about base resistors in transistors, like this. Also something about open collector configurations may help.
10. Finally, the practice of connecting the base resistor to Vcc in this kind of circuit to test the transistor should be fine. But DO NOT CONNECT the transistor's base directly, use always the resistor.
> 6 votes

# Answer
\***ERROR CORRECTION: Sorry all, I did have one error in my code that explains the creep. I thought I was running a loop to simply turn the motor on and off but actually it was running full on for 5 sec (255) and partial speed (120) of 1 sec, thus the creep. When resetting the code to on on for 5 sec, fully off for 1 sec, with a 560 Ohm resistor, things work as expected. (I still have the problem with the 2.2K Ohm though so most of my question stands.

nbloqs, Thank you ; I will review your answer in detail.

What would so many tutorials show this basic schematic if to has so many issues?

Thanks again!
> 0 votes

---
Tags: motor, resistor, transistor
---


title: Reading PushButton status with pyserial

text:
# Question
Title: Reading PushButton status with pyserial
I'm trying to read the status of a PushButton with python via pyserial.

In the loop function of Arduino Uno I have this:

```
void loop() {

if(digitalRead(BUTTON) == HIGH){
Serial.print("E\n");
while(1){}
}

```

So, if my pushbutton is pressed, it will send this message "E" via serial and then it will enter in an infinite loop so that nothing else happens.

But I want to detect this message in the python code. So this is my python code:

```
import serial
import time

try:
   arduino = serial.Serial('/dev/ttyACM0', 9600)
except:
   print "Failed to connect on /dev/ttyACM0"

try:
   print arduino.readline()

   while True:
      if arduino.readline() == 'E':
        print("Detected!\n")

except:
   print ("Failed to read!")

```

The first print before the infinite While is working: it is printing in the ubuntu terminal "Program Initiated", which is a message that I'm sending in the void Setup function of Arduino.

Then, it gets stucked in the line:

```
 if arduino.readline() == 'E':

```

I mean, I press several times my pushbutton, and nothing is happening.

Any help? Thanks!

# Answer
> 0 votes
The string you are sending (`"E\n"`) is not the same one you are checking for: `'E'`.

You could, for example, strip newlines from the string:

```
if arduino.readline().strip() == 'E':

```

---
Tags: serial, button, python
---


title: Need clarification with arduino syntax

text:
# Question
Title: Need clarification with arduino syntax
I've been learning how to program this fine piece of equipment but i seem stuck. I came upon the "Knight rider" example where you are supposed to blink LED's from one side to another and i can't understand where some of the code comes from. For example:

```
byte ledPin[] = {4,5,6,7,8,9,10,11,12,13};
int ledDelay;
int direction = 1;
int currentLED  = 0;
unsigned long changeTime;
int pot = 2;
int i;

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

    for (i = 0; i < 10; i++)
    {
        pinMode(ledPin[i], OUTPUT);
    }

    changeTime = millis();
}

void loop()
{
    ledDelay = analogRead(pot);

    if ((millis()- changeTime) > ledDelay)
    {
        changeLED();
        changeTime = millis();
    }
}

void changeLED()
{
    for (i = 0; i < 10; i++)
    {
        digitalWrite(ledPin[i], LOW);
        Serial.print("i = ");
        Serial.println(i);
    }

    digitalWrite(ledPin[currentLED], HIGH);

    currentLED += direction;

    if (currentLED == 9)
    {
        direction = -1;
    }

    if (currentLED == 0)
    {
        direction = 1;
    }
}

```

In this code I don't know where the "direction" variable is coming from I searched on the arduino reference page but can't find it. Are there other references where I could look or am I misunderstanding something?

# Answer
> 1 votes
It's coming from the program itself:

```
int direction = 1;

```

That means "Create a signed integer called 'direction' and assign it the value 1.

# Answer
> 1 votes
You defined the `direction` variable on the top with:

```
int direction = 1;

```

---
Tags: library, c
---


# Question
Title: How to program an Arduino Uno Pro with a makefile?
I'm using Arduino Makefile to compile sketches for Uno and Mega boards. I'm now trying to compile a sketch for an Arduino Uno Pro, which is an Uno with a replaced chip to give it features more like a Mega.

When writing a makefile to compile for this board, which `BOARD_TAG` should I use? I don't see this board listed in the official Arduino or Arduino Makefile docs.

# Answer
> 1 votes
After you edit your `boards.txt` file to incorporate the Arduino Uno Pro section from near the end of that Arduino Uno Pro webpage at hobbytronics.co.uk that you referenced, the board tag list produced by `make show_boards` will include the following line:

```
uno_pro       Arduino Uno*Pro

```

indicating the tag should be `uno_pro`.

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


title: Arduino Due connection with FLIR Lepton

text:
# Question
Title: Arduino Due connection with FLIR Lepton
I'm trying to connect a FLIR Lepton to an Arduino Due. A thread by pureengineering talks of rerouting some pins. I am not sure what they precisely mean.

Does this rerouting mentioned in the link also apply to Arduino Due?

# Answer
> 1 votes
According to the highlighted part of `Due` schematics it'd be better to connect `3.3V` to the `AREF` pin as there might be some significantly big resistor between `AREF` and `3.3V` source. So it might not be needed but one never knows.

Edit: Looking at the DUE board, there is "jumper" resistor, so you can choose 3V3 or AREF, that means AREF is not connected to anything by default. So if you connect 3v3 to AREF, it should be fine (even 5V, if you didn't changed anything on board yet )

---
Tags: arduino-due
---


# Question
Title: Is this example for playing music without delay correct?
I've followed the directions from this answer, to try and play music without delay. This is my code so far:

```
#include "pitches.h"

int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

const int tonePin = 4;
unsigned long previousMillis = 0;
int counter = 0;
int numberOfNotes = sizeof(melody)/sizeof(int);
boolean outputTone = false;

void setup() {
  pinMode(tonePin, OUTPUT);
  //Serial.begin(9600);
}

void loop() {
  unsigned long currentMillis = millis();
  unsigned long noteDuration = 1000 / noteDurations[counter];
  unsigned long pauseBetweenNotes = noteDuration * 1.30;

  if (counter < numberOfNotes) {
    if (outputTone && ((currentMillis - previousMillis) >= noteDuration)) {
        previousMillis = currentMillis;
        noTone(tonePin);
        outputTone = false;
        counter++;
    }
    else {
        if ((currentMillis - previousMillis) >= pauseBetweenNotes) {
        previousMillis = currentMillis;
        Serial.println(melody[counter]);

        if (melody[counter] == 0) {
          noTone(tonePin);
        } else {
          tone(tonePin, melody[counter]);
        }

        outputTone = true;
      }
    }
  }
}

```

`pitches.h` can be found here.

So with this code, the music plays, but slower. The pauses between notes seem longer, and I can't figure out why.

Also, I'm not sure where should I increment my notes counter.

# Answer
> 0 votes
In this code, your `pauseBetweenNotes` is \*in addition to * the duration of the note. In your previous code, IIRC, it included the duration of the note.

Change it to `0.3` times and I think it will behave as you expect.

# Answer
> 0 votes
There's a variable called "pauseBetweenNotes". Try modifying that and see if the pause between notes becomes smaller.

Regarding your counter question, the way the counter is set up looks fine to me.

---
Tags: code-optimization, code-review
---


# Question
Title: Why does my LCD screen display white rectangles?
I recently got an Arduino LCD screen. I tried connecting it to the UNO with the 10k potentiometer and all the needed equipment but all I got were white rectangles instead of characters. I have uploaded the hello world code but I saw no changes.

# Answer
> 2 votes
As @Majenko already mentioned, you have to set the right contrast. Use potentiometer to find out what value suits you right.

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


# Question
Title: Cisco Switch not receiving serial communication from Arduino
So I have an issue that I can't really think of a reason why it would be happening. I have an Arduino Mega connected on Serial3 to a RS232 breakout board with a male DB9 connector on it. I then have two female breakout boards connected. One is connected to the RS232 breakout board and the other to a Cisco DB9 to roll over cable, which is connected to my Cisco Switch, or if it is, it is being ignored.

For some reason no data sent from the Arduino is making it to the Cisco switch that I can tell. I did confirm that it is sending data using a USB to DB9 adapter and PUTTY. I can send and receive data from both the Arduino and PUTTY correctly to the other.

I can receive data from the switch perfectly. Cisco's default settings are the same as the Arduino's, 9600, 8bits, no parity, 1 stop bit etc...

I can also connect the switch to the USB to DB9 adapter directly and send and receive fine through it / PUTTY as well.

Does anyone have any suggestions why I'd be able to send data to and from Putty, but only receive data from the switch, or why the data going to the switch is failing?

```
void setup() {
  Serial.begin(9600, SERIAL_8N1);
  Serial3.begin(9600, SERIAL_8N1);
  Serial.println("Ready....");
  Serial.println();
}

void loop() {
  // read from Serial3, write to Serial
  if (Serial3.available()) {
    int inByte = Serial3.read();
    Serial.write(inByte);
  }
  // read from Serial, write to Serial3
  if (Serial.available()) {
    int inByte = Serial.read();
    Serial3.write(inByte);
  }
  Serial3.println(); // Added just to test if a cr could be passed
  Serial3.write(98); // Added just to test if a character could be directory passed
  Serial3.write(10); // Added just to test if a cr could be passed
}

```

# Answer
Assuming this is a flow control problem:

> Is there such a thing as inb vs oob for a serial console connection? This isn't on the internal network of the switch in any way but the console port

It assumed this is a managed switch and the traffic on the console port has nothing to do with the traffic going through the switch. Rather this is likely a port to the computer inside the switch. Such a port might be able to use RTS/CTS/DSR or X-on / and X-off.

If this is a flow control problem, consider first looking for thumb switches on the back of the switch to see if the method used for flow control over the console port can be selected. If that is not possible, consider simply hardwiring the out of band flow control pins to always allow for data to flow. At 9600 baud, a dedicated Aruidno should be able to keep up.

Refer to the 9 pin connector in this chart to find the out of band flow control pins.
> 1 votes

# Answer
Could be a voltage problem. You're using an TTL-\>RS232 Adapter as far as I can tell from the picture, which is absolutely necessary. Arduino only gives out TTL Signal Level, which would not be "understood" by the Cisco Switch, which works on RS232 / Serial Voltage Level (which is a lot higher). However, maybe the RS232 Converter Module is faulty. You could check the output voltage level with a Multimeter and see if it actually is in the required range (http://www.radio-electronics.com/info/telecommunications\_networks/rs232/signals-voltages-levels.php).

Also connecting ground correctly is important, but that should be ok on your setup :).
> 0 votes

---
Tags: arduino-mega
---


title: Demultiplexing Arduino with C++ code

text:
# Question
Title: Demultiplexing Arduino with C++ code
I have been working on a small project recently. I have a circuit like in the image below:

> Hardware Setup Demultiplexer IR Test

As you can see I have 8 IR LEDs, which are driven by an MC14051B Multiplexer/Demultiplexer. My goal is to select each IR led individually and send data over the selected IR LED. None of the other LEDs can send signals. Only one LED at a time can be sending IR codes.

---

> Hardware Setup Single IR Test

Below is the code I used to send the signal using the IR Library over one LED (no demultiplexer was used in this test).

```
// New function to send 'items' codes which are held in the array 'data'
void sendMulti (const uint8_t& items, const uint32_t* data) {
  for (int i = 0; i < 2; i++) {
    for (uint8_t itemIndex = 0; itemIndex < items; ++itemIndex) {
      irsend.sendNEC(data[itemIndex], 32);
      delay(1000);
    }
  }
  delay(5000); //5 second delay between each signal burst
}

void loop () {
  static const uint8_t MaxItems = 3;
  uint32_t  data[MaxItems] = {0x1067E21D,0x106722DD,0x106722DD,0x106722DD,0x106722DD,0x106722DD,0x106722DD,0x10676897,0x10676897,0x10676897,0x10676897,0x10676897,0x10676897,0x10678877,0x10676897,0x1067A857,0x1067A857,0x10678877,0x1067A857};
  sendMulti(MaxItems, data);
}

```

The Single IR Test was a success. However now I want to use the demultiplexer. Any advice or pointers will make me very happy.

# Answer
The most important document you have to read is called a datasheet. Here you can find the MC14051's.

I assume you already know how a mux/demux work, so... Well, you have eight LEDs, one on X0, another on X1, ... up to X7. The one connected to the pin X, which is your A0 (the pin used on irsend, I assume) is indexed by the three inputs A, B and C.

On page 5 you see the truth table. According to that table, you have to write a 0 on inhibit, and the value on ABC. So, to select led on X0, you have to write 0 on pins 7, 8, 9 and 10. If you want to select led X1, 8 should go high. For led X7, 8, 9 and 10 should be 1, while 7 is low. And this is for all the combinations...
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How I Can Send the status of switch in SMS by Arduino?
How I want help ,, I want send status of Switch If switch \> 20 send SMS status of switch OFF and when switch \<20 than mean switch ON , Don't want send the value of reading. I use Arduino uno

If I want use multiple switch and send all status of switchs in one message. I mean if switch1 \> 20 ON and switch2 \<20 I want send status of switch In one SMS Switch1 ON Switch2 OFF Switch3 OFF

How I can do this??

```
void loop()
Switch = analogRead(S_Switch);
if (Switch > 20 )
{
Serial.println(Switch);// If Switch > 20 show in SMS switch statuse  OFF,, If switch < 20 show in SMS switch statuse ON
Serial.print("\n******************\n");
Sim900Serial.print("AT+CMGF=1\r"); //Sending the SMS in text mode
delay(1000);
Sim900Serial.println("AT + CMGS = \"+***************\"");//The predefined phone number
delay(1000);
Sim900Serial.println("MY Swicth statuse is :");
Sim900Serial.println(Switch); // I don't want the value of Switch I want ( ON , OFF )
 Sim900Serial.print("              ");
Sim900Serial.println((char)26);//the ASCII code of the ctrl z is 26
delay(5000);
Sim900Serial.println();
}

```

# Answer
> 1 votes
Here, Updated Code...

```
const int switchOneInput = A0; // Switch 1
const int switchTwoInput = A1; // Switch 2

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

void loop()
{
  int switchOneStatus = analogRead(A0);
  int switchTwoStatus = analogRead(A1);

  // When Switch 1 is OFF and Switch 2 is OFF
  if(switchOneStatus < 20 && switchTwoStatus < 20)
  {
    smsOne();
  }

  // When Switch 1 is ON and Switch 2 is OFF
  else if(switchOneStatus > 20 && switchTwoStatus < 20)
  {
    smsTwo();
  }

  // When Switch 1 is OFF and Switch 2 is ON
  else if(switchOneStatus < 20 && switchTwoStatus > 20)
  {
    smsThree();
  }

  // When Switch 1 is ON and Switch 2 is ON
  else if(switchOneStatus > 20 && switchTwoStatus > 20)
  {
    smsFour();
  }

}

void smsOne()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Switch 1 is OFF and Switch 2 is OFF\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}

void smsTwo()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Switch 1 is ON and Switch 2 is OFF\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}

void smsThree()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Switch 1 is OFF and Switch 2 is ON\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}

void smsFour()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Switch 1 is ON and Switch 2 is ON\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}

```

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