title: Multiple non-blocking countdown timers?

text:
# Question
Title: Multiple non-blocking countdown timers?
I'm building a control system for three sump pumps using a single Arduino and a set of relays. I have float sensors for each one, and need the Arduino to trigger the relays when the float sensors are triggered. Sensor 1 triggers pump 1, sensor 2 triggers pump 2, etc.

Simple enough, but I also need each pump to remain on for 30 seconds after its float sensor returns to normal. This throws me for a loop since I need the other pumps and sensors to function during this delay time. I quickly found that the blocking `delay()` function is no longer feasible.

How can I trigger the relays, keep them on for 30 seconds after the sensors return to normal, but all the while still monitor and control the other sensors/relays? Would a non-blocking timer solution work? Would I have to delve into interrupts?

# Answer
> Would a non-blocking timer solution work?

Yes. Your "timer" doesn't have to be anything more than a start time from `millis()` and a flag. Then your loop just compares the start time to the current `millis()` value, and if it's more than the interval you wanted, do the "thing". In code:

```
uint32_t startTime;
bool waiting = false;
const uint32_t PUMP_DURATION = 30000UL;

void setup()
{
  // start the "timer"
  startTime = millis();
  waiting = true;
}

void loop()
{
  if (waiting && (millis() - startTime >= PUMP_DURATION)) {
    waiting = false;
    // do something now!
    foo();
  }

```

The flag keeps it from checking when the pump *isn't* running.

If you have multiple timed things, just make another set of variables (i.e., `startTime2` and `waiting2`). Give 'em better names, eh?

There are also Arduino libraries that encapsulate this common design pattern. TimeMark is one.

Here's some sample code on the Arduino forum.
> 3 votes

# Answer
The "blink-without-delay"-pattern shows how this can be solved but with several time periods and logic this becomes complex. Some abstraction is needed. The Timemark library provides a solution. Belows is the logic for a single sensor-relay pair with a state trace to serial:

```
#include <Timemark.h>

const uint32_t TURN_OFF_TIMEOUT = 30000L;
Timemark turnOff(TURN_OFF_TIMEOUT);
const int sensorPin = 2;
const int relayPin = 3;

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

  pinMode(sensorPin, INPUT_PULLUP);
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, LOW);

  trace.start();
}

void loop()
{
  if (trace.expired()) {
    Serial.print(millis());
    Serial.print(F(":sensor="));
    Serial.print(digitalRead(sensorPin));
    Serial.print(F(", relay="));
    Serial.println(digitalRead(relayPin));
  }

  if (digitalRead(sensorPin) == LOW) {
    digitalWrite(relayPin, HIGH);
    turnOff.start();
  }
  else if (turnOff.expired()) {
    digitalWrite(relayPin, LOW);
  }
}

```

Expanding to three sensor-relays becomes:

```
#include <Timemark.h>

const uint32_t TURN_OFF_TIMEOUT = 30000L;
const int CONTROL_MAX = 3;
Timemark turnOff[CONTROL_MAX];
const int sensorPin[CONTROL_MAX] = { 2, 4, 6 };
const int relayPin[CONTROL_MAX] = { 3, 5, 7 };

void setup()
{
  for (int i = 0; i < CONTROL_MAX; i++) {
    turnOff[i].limitMillis(TURN_OFF_TIMEOUT);
    pinMode(sensorPin[i], INPUT_PULLUP);
    pinMode(relayPin[i], OUTPUT);
    digitalWrite(relayPin[i], LOW);
  }
}

void loop()
{
  for (int i = 0; i < CONTROL_MAX; i++) {
    if (digitalRead(sensorPin[i]) == LOW) {
      digitalWrite(relayPin[i], HIGH);
      turnOff[i].start();
    }
    else if (turnOff[i].expired()) {
      digitalWrite(relayPin[i], LOW);
    }
  }
}

```

An alternative solution is to use the Scheduler library. Below is a rewrite using template functions and a controller task per sensor-relay pair.

```
#include <Scheduler.h>

const uint32_t TURN_OFF_TIMEOUT = 30000L;
const uint32_t DEBOUNCE_TIMEOUT = 40L;

template<const int sensorPin, const int relayPin> void setupController()
{
  pinMode(sensorPin, INPUT_PULLUP);
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, LOW);
}

template<const int sensorPin, const int relayPin> void loopController()
{
  if (digitalRead(sensorPin) == LOW) {
    digitalWrite(relayPin, HIGH);
    while (digitalRead(sensorPin) == LOW) delay(DEBOUNCE_TIMEOUT);
    delay(TURN_OFF_TIMEOUT);
    digitalWrite(relayPin, LOW);
  }
  yield();
}

void setup()
{
  Scheduler.start(setupController<2,3>, loopController<2,3>);
  Scheduler.start(setupController<4,5>, loopController<4,5>);
  Scheduler.start(setupController<6,7>, loopController<6,7>);
}

void loop()
{
  yield();
}

```

Please note that the Scheduler requires yield() or delay() to switch between the tasks.

Cheers!
> 3 votes

# Answer
You might use something like this:

```
#define AMOUNT_OF_TIMERS 10
unsigned int timer[AMOUNT_OF_TIMERS];
unsigned int sensors[AMOUNT_OF_TIMERS];
unsigned int pumps[AMOUNT_OF_TIMERS];
void setup()
{
  sensors[0] = 1;
  sensors[1] = 2;
  sensors[2...
  ......s[9] = 12;
  pumps[0] = 13;
  pumps[1....
  ....s[9] = 22;
  for(unsigned int i = 0; i< AMOUNT_OF_TIMERS; i++){
    PinMode(sensors[i],INPUT);
    PinMode(pumps[i],OUTPUT);
  }
}

void loop()
{
  checkPins();
  decreaseTimers();
  delay(1000);
}

void checkPins(){
  for(unsigned int i = 0; i< AMOUNT_OF_TIMERS; i++){
    if(digitalRead(sensors[i])
    pump[i] = 30;
  }
}

void decreaseTimers(){
  for(unsigned int i = 0; i< AMOUNT_OF_TIMERS; i++){
    if(timer[i]>0)
    timer--;
  }
}

```

Personally, I think, handling the timing events in an interrupt is way better. Which might also be for the sensor inputs.

It's not the neatest thing, but it will do. Using interrupts should make it even more efficient.

* You should use interrupts.
* You might use unsigned chars to preserve extra RAM.
* You should adjust the timers/delay. (set timer to 300, and delay to 100ms) for better result.
> 0 votes

# Answer
Using info from every suggestion, I've so far come up with the following. I may not need to touch this code again for years and years (or a new house owner may need to look at it should I move out), so I tried to comment it as much as possible.

I don't like that I've repeated so much code in the readFloatSensor functions, but this is where I am so far. How can I eliminate the code duplication? I believe I could use arrays and `for` loops but now I've entered another grey area for my knowledge level.

```
// PumpController.ino

// ----CONSTANTS
// ----Edit these if you need to change the pin layout or pump duration

#define RELAY_ON 0                     // The pump relays are active-LOW; on when LOW (0)
#define RELAY_OFF 1                    // and off when HIGH (1). These #defines just help keep track.

const int pumpRelayPin1 =  12;         // Pin numbers for the pump relays
const int pumpRelayPin2 =  11;
const int pumpRelayPin3 =  10;

const int floatSensorPin1 = 7;         // Pin numbers for the float sensors
const int floatSensorPin2 = 8;
const int floatSensorPin3 = 9;

const int pumpDuration = 500;          // Number of millisecs that the pumps run
                                       // after the float sensors no longer detect water

// ----VARIABLES

byte pumpState1 = RELAY_OFF;           // Used to record whether the pumps are on or off
byte pumpState2 = RELAY_OFF;           // (default to HIGH/OFF)
byte pumpState3 = RELAY_OFF;

unsigned long currentMillis = 0;       // Stores the value of millis() in each iteration of loop()

unsigned long pumpTimerMillis1 = 0;    // Stores the times when the float sensors were last triggered
unsigned long pumpTimerMillis2 = 0;
unsigned long pumpTimerMillis3 = 0;

// ----SETUP (Sets up the pins at startup/reset)

void setup()
{

    // Debug
    Serial.begin(9600);
    Serial.println("Starting PumpController.ino");

    // Pump relays are active-LOW. Initialize pump
    // pins HIGH so the relays are inactive at startup/reset
    digitalWrite(pumpRelayPin1, RELAY_OFF);
    digitalWrite(pumpRelayPin2, RELAY_OFF);
    digitalWrite(pumpRelayPin3, RELAY_OFF);

    // THEN set the pins as outputs
    pinMode(pumpRelayPin1, OUTPUT);
    pinMode(pumpRelayPin2, OUTPUT);
    pinMode(pumpRelayPin3, OUTPUT);

    // Set the float sensor pins as inputs and use the built-in pullup resistors
    pinMode(floatSensorPin1, INPUT_PULLUP);
    pinMode(floatSensorPin2, INPUT_PULLUP);
    pinMode(floatSensorPin3, INPUT_PULLUP);

}

// ----MAIN LOOP

void loop()
{
    // Get the current clock count

    currentMillis = millis() + pumpDuration;       // We add the countdown timer duration to
                                                   // the clock to prevent the pumps from
                                                   // running at boot time, while the clock
                                                   // counter is still below the timer value

    // Call the functions that do the work

    readFloatSensor1();             // check each float sensor and decide whether
    readFloatSensor2();             // to start the pump and countdown timer
    readFloatSensor3();
    triggerPumps();                 // Actually toggles the relay pins based on
}                                   // the data from the above functions.

// ----WORKER FUNCTIONS

void readFloatSensor1()
{
    if (digitalRead(floatSensorPin1) == LOW)   // If the float sensor is tripped (pulled low)
    {
        pumpState1 = RELAY_ON;                 // then trigger the pump relay pin
        pumpTimerMillis1 = currentMillis;      // and set the pump countdown timer to the current clock time
    }

    if (currentMillis - pumpTimerMillis1 >= pumpDuration)   // If the countdown timer has expired,
    {
        pumpState1 = RELAY_OFF;                             // then turn off the pump relay pin
        pumpTimerMillis1 = 0;                               // and reset the timer to 0 for the next trigger
    }
}

//========

void readFloatSensor2()
{
    if (digitalRead(floatSensorPin2) == LOW)   // If the float sensor is tripped (pulled low)
    {
        pumpState2 = RELAY_ON;                 // then trigger the pump relay pin
        pumpTimerMillis2 = currentMillis;      // and set the pump countdown timer to the current clock time
    }

    if (currentMillis - pumpTimerMillis2 >= pumpDuration)   // If the countdown timer has expired,
    {
        pumpState2 = RELAY_OFF;                             // then turn off the pump relay pin
        pumpTimerMillis2 = 0;                               // and reset the timer to 0 for the next trigger
    }
}

//========

void readFloatSensor3()
{
    if (digitalRead(floatSensorPin3) == LOW)   // If the float sensor is tripped (pulled low)
    {
        pumpState3 = RELAY_ON;                 // then trigger the pump relay pin
        pumpTimerMillis3 = currentMillis;      // and set the pump countdown timer to the current clock time
    }

    if (currentMillis - pumpTimerMillis3 >= pumpDuration)   // If the countdown timer has expired,
    {
        pumpState3 = RELAY_OFF;                             // then turn off the pump relay pin
        pumpTimerMillis3 = 0;                               // and reset the timer to 0 for the next trigger
    }
}

//========

void triggerPumps()
{
    // Toggle the pump relay pins on and off based on
    // pumpState from the readFloatSensor functions

    digitalWrite(pumpRelayPin1, pumpState1);
    digitalWrite(pumpRelayPin2, pumpState2);
    digitalWrite(pumpRelayPin3, pumpState3);
}

//=====END

```
> 0 votes

---
Tags: arduino-uno, programming, sensors, relay, time
---


# Question
Title: Problem with running 2 DC motors with ultrasonic sensor
I'm not expert in electrical circuits, maybe I am making a very simple mistake or missing some basic points with my circuit.

What I'm trying to achieve is simple, to run 2 DC motors with an ultrasonic sensor to detect obstacles and change direction. When I unplug the ultrasonic sensor everything is working fine as expected without obstacle detection but when I connect the ultrasonic sensor, sensor always responds with 0 cm distance. Then I removed 9 V battery from the circuit and plug Arduino to computer via USB, sensor works fine but motors are not working properly, it looks like the power from USB is not enough to drive motors at the same time. I've added my circuit scheme below:

# Answer
How (acoustically) loud are the motors? If they're the typical RC car motors, they can screech harmonics right up into the 40 KHz range typical of ultrasound ranging sensors, interfering with the sensor's ability to work at all.

How (electrically) loud are the motors? If RC as above, they throw all sorts of transients onto the power lines (and everything else within electrical pickup range). You might want to put some ceramic capacitors across the motor leads to absorb some of those transients.

Kudos for the suggestions to provide separate power supplies for the motors and the Arduino / sensor combination. I'd go even further, and provide separate power for all three, and use opto-isolators for the connection between the ultrasound and the Arduino.

Some years ago I used two Novak Super-Rooster motor drivers for a battle-bot competition. They were driven by PWM outputs of an Arduino, where 50% duty cycle was off, 0% was full speed reverse, and 100% was full speed ahead. These were powered by a sealed lead acid battery, and driven full-out, the motors got +/- 12VDC at about 40 amps. There was a common ground with the Arduino, going to the Super Roosters, but not the motors, and the drivers took care of the electrical shielding, with a little help from the ceramic bypass capacitors I mentioned. Worked great!
> 1 votes

---
Tags: motor
---


# Question
Title: Why the need to use the volatile keyword on global variables when handling interrupts in Arduino?
I am familiar with the keyword `Volatile` being used to declare variables that are shared among multiple threads on a software application (basically on a multithreaded application).

But why do I need to declare a variable as `Volatile` when running the code on an an Arduino interrupt? Is the code running in the interrupt executing on different thread? Is there something else going on?

# Answer
First, it's `volatile` not `Volatile`. I cover these concepts in my page about Interrupts however to avoid giving a link-only answer I'll repeat the relevant bits.

---

## What are "volatile" variables?

Variables **shared** between ISR functions and normal functions should be declared `volatile`. This tells the compiler that such variables might change at any time, and thus the compiler must reload the variable whenever you reference it, rather than relying upon a copy it might have in a processor register.

For example:

```
volatile boolean flag;

// Interrupt Service Routine (ISR)
void isr ()
{
 flag = true;
}  // end of isr

void setup ()
{
  attachInterrupt (0, isr, CHANGE);  // attach interrupt handler
}  // end of setup

void loop ()
{
  if (flag)
    {
    // interrupt has occurred
    }
}  // end of loop

```

---

## Critical sections ... accessing volatile variables

There are some subtle issues regarding variables which are shared between interrupt service routines (ISRs) and the main code (that is, the code not in an ISR).

Since an ISR can fire at any time when interrupts are enabled, you need to be cautious about accessing such shared variables, as they may be being updated at the very moment you access them.

---

### First ... when do you use "volatile" variables?

A variable should only be marked volatile if it is used both inside an ISR, and outside one.

* Variables **only** used **outside** an ISR should **not** be volatile.
* Variables **only** used **inside** an ISR should **not** be volatile.
* Variables used both **inside and outside** an ISR **should be** volatile.

eg.

```
volatile int counter;

```

Marking a variable as volatile tells the compiler to not "cache" the variable's contents into a processor register, but always read it from memory, when needed. This may slow down processing, which is why you don't just make every variable volatile, when not needed.

---

### Atomic access

Consider this code:

```
volatile byte count;

ISR (TIMER1_OVF_vect)
  {
  count = 10;
  }

void setup ()
  {
  }

void loop ()
  {
  count++;
  }

```

The code generated for `count++` (add 1 to count) is this:

```
 14c:   80 91 00 02     lds r24, 0x0200
 150:   8f 5f           subi    r24, 0xFF     <<---- problem if interrupt occurs before this is executed
 152:   80 93 00 02     sts 0x0200, r24   <<---- problem if interrupt occurs before this is executed

```

*(Note that it adds 1 by subtracting -1)*

There are two danger points here, as marked. If the interrupt fires after the lds (load register 24 with the variable `count`), but before the sts (store back into the variable `count`) then the variable might be changed by the ISR (TIMER1\_OVF\_vect), however **this change is now lost**, because the variable in the register was used instead.

We need to protect the shared variable by turning off interrupts briefly, like this:

```
volatile byte count;

ISR (TIMER1_OVF_vect)
  {
  count = 10;
  }  // end of TIMER1_OVF_vect

void setup ()
  {
  }  // end of setup

void loop ()
  {
  noInterrupts ();
  count++;
  interrupts ();
  } // end of loop

```

Now the update of `count` is done "atomically" ... that is, it cannot be interrupted.

---

### Multi-byte variables

Let's make `count` a 2-byte variable, and see the other problem:

```
volatile unsigned int count;

ISR (TIMER1_OVF_vect)
  {
  count++;
  } // end of TIMER1_OVF_vect

void setup ()
  {
  pinMode (13, OUTPUT);
  }  // end of setup

void loop ()
  {
  if (count > 20)
     digitalWrite (13, HIGH);
  } // end of loop

```

OK, we are not changing `count` any more, so is there still a problem? Sadly, yes. Let's look at the generated code for the "if" statement:

```
 172:   80 91 10 02     lds r24, 0x0210
 176:   90 91 11 02     lds r25, 0x0211  <<---- problem if interrupt occurs before this is executed
 17a:   45 97           sbiw    r24, 0x15
 17c:   50 f0           brcs    .+20

```

Imagine that `count` was 0xFFFF and was about to "wrap around" back to zero. We load 0xFF into one register, but before we load the second 0xFF the variable changes to 0x00. Now we think `count` is 0x00FF which is neither the value it had before (0xFFFF) or now (0x0000).

So again we have to "protect" the access to the shared variable, like this:

```
void loop ()
  {
  noInterrupts ();
  if (count > 20)
     digitalWrite (13, HIGH);
  interrupts ();
  }  // end of loop

```

---

### What if you are not sure interrupts are on or off?

There is a final "gotcha" here. What if interrupts might be off already? Then turning them back on afterwards is a Bad Idea.

In that case you need to save the processor status register like this:

```
unsigned int getCount ()
  {
  unsigned int c;
  byte oldSREG = SREG;   // remember if interrupts are on or off

  noInterrupts ();   // turn interrupts off
  c = count;         // access the shared variable
  SREG = oldSREG;    // turn interrupts back on, if they were on before

  return c;          // return copy of shared variable
  }  // end of getCount

```

This "safe" code saves the current status of interrupts, turns them off (they may already be off), gets the shared variable into a temporary variable, turns interrupts back on - if they were on when we entered the function - and then returns the copy of the shared variable.

---

## Summary

Code may "appear to work" even if you don't take the above precautions. That is because the chances of the interrupt occurring at the exact wrong moment is fairly low (maybe 1 in 100, depending on the code size). But sooner or later it will happen at the wrong moment, and your code will either crash, or occasionally return the wrong results.

So for reliable code, pay attention to protecting access to shared variables.
> 16 votes

# Answer
`volatile` has nothing to do with multithreading per se, and it seems to be among the most miused keywords in that area. It is never a substitute for proper synchronization.

As per standard C, `volatile` invokes mostly implementation defined behaviour of telling the compiler to not optimize away accesses to the memory a variable resides in, even if the compiler thinks there can't be any other.

This *can* be useful in the following situations where the compiler is not aware that outside means can change a variable:

* memory mapped hardware registers
* variables accessed from other threads but checked in a tight loop
* variables accessed from interrupt or signal handlers but checked in a tight loop
> 7 votes

---
Tags: c++, interrupt, isr
---


# Question
Title: Is there a way to upload precompiled code to an arduino?
My company is developing a programmable remote control car which is driven by an Arduino Nano. We would like a way for the user to install software updates to the Arduino, but we don't want to give the user access to the code.

Is there a way to compile Arduino code without automatically uploading it, so that I can put the pre-compiled binary up for download on a website?

Then after this how would I go about manually uploading it (to the Arduino)?

# Answer
> Is there a way to compile arduino code without automatically uploading it, so that I can put the pre-compiled binary up for download on a website?

Yes, you can save the .hex file produced by the compiler. If you turn on verbose output from the compiler you can find the temporary directory where it is stored. Simply copy from there to a folder for download on the website.

> And then after this how would I go about manually uploading it (To the arduino)?

You can do that with the command line tool avrdude but as that is somewhat complex with a lot of parameters it might be easier to use a graphical front-end. One such tool is xloader. There are several. This depends on your end-users and the host machine that they will be using.

You can find some more info here.

Cheers!
> 7 votes

# Answer
I think if you do not publish the source code, the project will be a little bit unconstructive, both for developers and users, especially when it is based in open hardware.

You can put hex files available to users, but also the source code, allowing the community to participate in the development of your product.

Anyway, if you use third-party code in your project, such as libraries, remember to respect their licenses.

Best regards. Good luck with the project.
> 1 votes

---
Tags: arduino-nano, uploading, compile
---


title: Why need a delay between readings?

text:
# Question
Title: Why need a delay between readings?
When I learn the tutorial in

both of the code examples have a line of code of `delay(1)` and I cannot understand the comments clearly:

```
 delay(1);        // delay in between reads for stability

```

The **stability** for/of what?

# Answer
Those delays are nonsense. They don't add to the stability of anything. The best you could say is that they stop you spamming your serial port. (However 1 ms is not very long).

Sometimes people throw in a delay because "it seems to work better" without examining the underlying cause. I would speculate that in this case the author may have been using delays to improve receiving serial data, and got the idea into their head that the occasional delay now and then "improves stability".
> 9 votes

# Answer
**Analog Stability**

From the Datasheet of ATMEGA328 Page 240:

`When the bandgap reference voltage is used as input to the ADC, it will take a certain time for the voltage to stabilize. If not stabilized, the first value read after the first conversion may be wrong.`

So if you are doing multiple reads, you need to wait a few cycles.

Delays are not required when using auto-triggering:

`When Auto Triggering is used, the prescaler is reset when the trigger event occurs. This assures a fixed delay from the trigger event to the start of conversion. In this mode, the sample-and-hold takes place two ADC clock cycles after the rising edge on the trigger source signal. Three additional CPU clock cycles are used for synchronization logic.`

Also if reading different channels of the same ADC module, you need to provide a delay between the reads so that the analog MUX is positioned and the S&H capacitor is charged.

This information is from hardware perspective and I'm not sure if Arduino internal ADC routines compensate for those delays.

**Digital Stability**

From the digital read tutorial schmatic:

In the schematic, the push button is not electrically de-bounced. A delay in reading states would help de-bounce it in software.

As Nick Gammon suggested, they also improve serial flooding.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How to Publish to MQTT with retain option
I don't understand how to publish to mqtt with retain option (The fourth parameters)

I know that I need length in an byte array but I've try allot to determine how to calculate my payload message to an byte var.

here is my code to publish once I am connected.

```
String str;
char chBright[4];
str = String(ledBrightness); //converting integer into a string
str = str + '%';
str.toCharArray(chBright, 4);
MQTTClient.publish("/maison/GF/Escalier/stairLight/b", chBright);

```

document ask the third parameter to be an byte

> topic – the topic to publish to `char*`
>
> payload – the message to publish `byte array`
>
> length – the length of the message `byte`
>
> retained – whether the message should be retained `byte`
>
> > `0` – not retained
> >
> > `1` – retained

mqtt client for Arduino

**How in c++ to get bytes from the message I want to publish?**

Tank you to clarify my knowledge

# Answer
> 1 votes
> How to Publish to MQTT with retain option?

The quick answer is add payload length, and retained as true as the last parameters to publish().

```
const int BUF_MAX = 8;
char buf[BUF_MAX];
itoa(ledBrightness, buf, 10);
strcat(buf, "%");
int len = strlen(buf) + 1;
MQTTClient.publish("/maison/GF/Escalier/stairLight/b", buf, len, true);

```

Above is a rewrite with the extra parameter for "retained", payload length, and payload as a null-terminated string.

Cheers!

# Answer
> 2 votes
> How in c++ to get bytes length from the message I want to publish?

For a String object, the method `length()` tells you the length.

eg.

```
int len = str.length ();

```

For a null-terminated C-type string, you can use `strlen`, eg.

```
char foo [20] = "bar";
int len = strlen (foo);

```

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


title: How to read pinMode for digital pin?

text:
# Question
Title: How to read pinMode for digital pin?
Is there a way for me to read the pin mode for one of the digital pins on Arduino? In other words, can I determine whether a pin's been set to an input or output?

# Answer
Yes, you can use the data direction registers (DDR*B*, DDR*C*, DDR*D* depending on which port) to check what mode a pin is in.

If a pin is in output mode then the corresponding bit in DDRx will be 1.

One complication is that the Arduino functions give each pin an "Arduino" pin number, and you have to look at a pin map to figure out which DDR register and bit corresponds to the pin you want to check. You can find a pin map for Arduinos based on the ATMEGA168/ATMEGA328 (including Uno) here...

https://www.arduino.cc/en/Hacking/Atmega168Hardware

So, for example, if you want to check if Arduino digital pin #4 is set for output, you'd look at the map and see that corresponds to PD4. That means "port D" and "bit 4", so you could say...

```
if ( DDRD & _BV(4) ) {   // Check bit #4 of the data direction register for port D
    // If we get here, then Arduino digital pin #4 was in output mode
} else {
    // If we get here, then Arduino digital pin #4 was in input mode
}

```

If you want to check Arduino digital pin #14, then you would use `DDRB & _BV(5)`.

*(`_BV(x)` is a macro that shifts `1` `x` bits to the right.)*
> 4 votes

# Answer
There are functions which can get you the registers and bit numbers from a pin number built into the Arduino API.

```
uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);
volatile uint8_t *reg = portModeRegister(port);

if (*reg & bit) {
    // It's an output
} else {
    // It's an input
}

```
> 7 votes

# Answer
Seems like the Arduino core is missing a function to read the pinMode(). Here is a possible implementation:

```
int pinMode(uint8_t pin)
{
  if (pin >= NUM_DIGITAL_PINS) return (-1);

  uint8_t bit = digitalPinToBitMask(pin);
  uint8_t port = digitalPinToPort(pin);
  volatile uint8_t *reg = portModeRegister(port);
  if (*reg & bit) return (OUTPUT);

  volatile uint8_t *out = portOutputRegister(port);
  return ((*out & bit) ? INPUT_PULLUP : INPUT);
}

```

It handles illegal pin numbers (return -1), and all pin modes; OUTPUT, INPUT and INPUT\_PULLUP.

Cheers!

BW: I have added this as an issue on the Arduino github repository.
> 7 votes

---
Tags: pins
---


# Question
Title: How to connect a 12V power supply to an RGB LED strip receiving RGB values via Arduino Uno PWM pins?
**Desired Behaviour**

I want to send RGB values from my Arduino Uno PWM pins to an RGB LED strip.

**What I've Tried**

I've purchased this RGB LED strip and 12V power supply (specs below).

I'm trying to follow this adafruit tutorial but am finding the diagram references unclear.

I've mocked up a diagram but am not sure it would work:

( I haven't used the `Vin` pin before, so, just to be clear, that is the pin that is connected to the positive line on the breadboard - is that how to transfer the 12V power to the breadboard? )

**Questions**

**01)** Is the above diagram safe and sound?

**02)** How do I connect the power supply to the RGB LED strip?

**03)** Is it ok to keep the Arduino 'powered' by the USB whilst plugged in to the 12V power (so that it can keep sending the RGB values to the LED strip via the PWM pins)?

**04)** I've seen references to `grounding` the power source, how do I do that?

**05)** Are the MOSFETS I have from the Arduino Uno starter kit sufficient for this task?

Printed Text on MOSFET: IRF520 Y32K BE

MOSFET Datasheet: Link (IRF520NPbF)

**Specifications**

*RGB LED Strip*

* LED type: 5050 SMD
* Color: RGB
* LED quantity: 300LED
* Package: 5 Meter/REEL
* Voltage:: 12V DC
* Working Power: 14.4W
* Working temperature: -20° to 50°
* Size: ⌀180mm
* Length : 5m
* Life Span: 50000+hours
* Weight: 0.3kg

*Power Supply*

* Input Voltage: AC 100 - 240V
* Output Voltage : DC 12V, 6A
* Power : 72 Watts
* Connector Size:
* External Diameter: 5.5mm
* Internal Diameter: 2.5mm

# Answer
> 01) Is the above diagram safe and sound?

It looks to be OK, except one thing:

The current you can draw from the Arduino's VIN pin is limited to about 1A. That is a sixth of what your power supply can provide, and the LED strip when everything is on needs more than that (1.2A), so you could run into problems. The limit is threefold:

* The barrel jack itself is rated at up to 1A
* There is a protection diode with a limit of 1A
* The header pins are rated at up to 1A

And of course the Arduino itself needs to use some of that available 1A. So you might be better off splicing your LED circuit into the power supply's wire before it enters the Arduino.

> 02) How do I connect the power supply to the RGB LED strip?

Power goes in (+) to the common pin of the LED strip and then out of any of the three colour pins that happen to be connected to the ground of the power supply. That is, the ground of the Arduino in your schematic since they are (as they should be) all shared.

> 03) Is it ok to keep the Arduino 'powered' by the USB whilst plugged in to the 12V power (so that it can keep sending the RGB values to the LED strip via the PWM pins)?

Yes. There is circuitry on the Arduino that allows both the USB and barrel jack to be plugged in together.

> 04) I've seen references to grounding the power source, how do I do that?

That refers to connecting the external power supply's ground and the Arduino's ground together. By using the barrel jack that is all taken care of for you.

> 05) Are the MOSFETS I have from the Arduino Uno starter kit sufficient for this task?

Not really. They are designed to be switched with a higher voltage than the Arduino's IO pins provide. While they will work, they may cause the LEDs to be dimmer than they should be, or the MOSFETs might get hot. Basically a MOSFET has a "threshold" voltage range which is the voltage range at which the MOSFET transitions from off to on. That is 2V - 4V for that MOSFET, which while within the range of an IO pin isn't really that great. At 4V the MOSFET still isn't completely on. You may notice from the datasheet that the "R\_DS(ON)" value - that is the resistance of the MOSFET when it is on, is measured with the gate voltage at 10V. That is a voltage where the MOSFET is guaranteed to be fully on. Anything less than that and the resistance will be higher causing more losses across the MOSFET. I could see that instantly from the model number - it starts with "IRF". There is a specific range from International Rectifier which is designed to be directly driven by an IO pin - these are the "IRL" (for *International Rectifier Logic-level*) series. These have their R\_DS(ON) values measured typically at a gate voltage of 4.5V and a threshold voltage in the region of 500mV to 1.5V. When directly driving from an Arduino these IRL (or equivalent from other manufacturers) are preferred.
> 5 votes

---
Tags: arduino-uno, rgb-led
---


# Question
Title: Ultrasonic PING: multiple trig on single dig. pin
This may seem a little stupid, i apologize if so as i'm new to electronics/arduino.

I have 4, 4-pin ping sensors. I'm running out of available pins on my UNO.

I had a ponder & wondered if it was possible to link all 4 sensor's trig pins to a single digital pin, with the echo pins assigned to their own pin. In my head, on each sensor call (sorry i'm used to programming terms) all 4 sensors would send a pulse, then only the sensor (or echo pin) in question would be read. Is that plausible? each ping sensor is about 20-30 cm separated, but facing internally, in a spiral downwards.

# Answer
> 1 votes
I was able to achieve the result using my suggested method in the question. As BrettAM stated, the signals are wasted on the other 3 pins when checking 1. This solution was suitable as a proof of concept

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


# Question
Title: Arduino in Eclipse IDE: How to add SPI library (core library already added)?
I want to use eclipse for arduino programming, so I followed the guides to set up a static project for the arduino core library. Then I added the library file (.a) and the .h and .cpp files to my new project in the settings.
So far, so good.
But now I am trying to add the SPI library to my project without success (I only have the .h and .cpp files, **no** .a)!

My sample code

```
#include <Arduino.h>
#include <SPI.h>

int main(void) {
    init();
    pinMode(13, OUTPUT);
    for (;;) {
        digitalWrite(13,1);
        SPI.setBitOrder(0);
    }
}

```

The pinMode and digitalWrite parts work, but with the SPI method I get an error:

```
05:33:26 **** Build of configuration Debug for project ArduinoTestProject ****
make all
Building file: ../main.cpp
Invoking: AVR C++ Compiler
avr-g++ -I/home/fabio/Workspace/arduinoLIB/SPI -I/home/fabio/Workspace/arduinoCORE -Wall -g2 -gstabs -Os -ffunction-sections -fdata-sections -fno-exceptions -mmcu=atmega328p -DF_CPU=16000000UL -MMD -MP -MF"main.d" -MT"main.d" -c -o "main.o" "../main.cpp"
Finished building: ../main.cpp

Building target: ArduinoTestProject.elf
Invoking: AVR C++ Linker
avr-gcc -s -Os -o"ArduinoTestProject.elf"  ./main.o   -l"arduinoUNO" -l"m" -lm -Wl,-Map,ArduinoTestProject.map,--cref -mrelax -Wl,--gc-sections -L/home/fabio/Workspace/arduinoCORE/lib -mmcu=atmega328p; avr-nm -C -n "ArduinoTestProject.elf" >ArduinoTestProject.symbol
./main.o: In function `main':
../main.cpp:38: undefined reference to `SPIClass::setBitOrder(unsigned char)'
collect2: error: ld returned 1 exit status
avr-nm: 'ArduinoTestProject.elf': No such file
make: *** [ArduinoTestProject.elf] Error 1

05:33:26 Build Finished (took 72ms)

```

Does anyone see the problem?

# Answer
> 1 votes
As far as I understand you are using eclipse CDT directly. (I mean you are not using an "arduino eclipse plugin" that does the stuff below for you)

The first thing to understand is that a arduino library is not treated as a library when compiling a arduino sketch.

In other words in the Arduino IDE, a arduino library is compiled like standard source code just like your .ino files.

As such there is no SPI.a file created during the compilation process. In CDT you can have both options (with or without .a file) but the Arduino IDE way is the easiest, by far.

So lets first assume you want to compile the "Arduino way" aka without SPI.a. What you need to do is simply drag and drop the files in your project. If you want to drop in a subfolder (like libraries/SPI) you will need to add those folders to your include path. That is all there is to it.

If you want to treat the library as a real library (saying you want a SPI.a) the best thing I can think of is to create a new library project for each sketch-project . Drag and drop the SPI code in that project (like above) and make your project dependent on the library project. There are probably some include path issues but the .a file should be found and included in the build

Note that the second approach makes that you will need a SPI project for each and every (arduino) board you have. If you want to use project defines it is even more difficult.

I would strongly advise to start your arduino eclipse development with my arduino eclipse plugin because it is simply easier. Later you can evolve to the full freedom of CDT.

If you want to drag and drop folders instead of the .h and .cpp files you will have to add exclusion rules to your include path. This because otherwise all the examples of the library will be in your project making you have multiple setup and loop functions.

---
Tags: arduino-uno, spi, eclipse, avr-toolchain
---


title: One workspace, two IDEs - Possible?

text:
# Question
Title: One workspace, two IDEs - Possible?
How can I create a workspace & projects so that either the Arduino IDE or the EclipseArduino IDE may be used to develop the project, interchangeably?

I have both IDEs installed and working but in separate workspaces.

I need:

* One workspace that either IDE can understand and work in;
* Either to IDE build with the physically same set of library sources;
* Whichever IDE I open to see my sources as I last left them, regardless of which IDE I last used.

I want:

* The source files to have conventional names - .C or .C++, not .pde or .ino;
* Either IDE to build with the physically same set of library object modules;

My use-case is that I work in/with Eclipse, and I teach Arduino skills to people starting out with the Arduino IDE. I'd like to be able to prepare class work at home with Eclipse but open and project it in class with the Arduino IDE. It would be nice if I could demonstrate the two IDEs using the same code. Clearly, I could hack up a demonstration, but I'd rather do it honestly and without sync issues like having to apply twice any changes we made in class.

Update 20 Apr '16: At @Jantje's suggestion (in the comments below his answer), I created a github issue, "*Importing an ArduinoIDE project with the New Sketch Wizard and using same sketch-name, failed.*" The new sketch would over-write the .ino file with a new, empty sketch.

That issue got fixed in the April 14, 2016 nightly and now works as his answer to this question says it does.

# Answer
> 2 votes
Your requirements for not having `.ino` files and wanting to be able to work with the Arduino IDE are conflicting. Assume we drop that requirement it is very much possible to do what you want.

The Arduino Eclipse plugin has been supporting `.ino` files for a long time now. You can simply compile Arduino IDE-made sketches. You do not have to make links and so make the folder where your Arduino IDE makes its sketches the workspace in Eclipse.

In Eclipse, for each sketch you want to edit, start the new sketch wizard and use a project name that is the same as the sketch name in the Arduino IDE.

Now you can work in the Arduino Eclipse plugin and the Arduino IDE on the same files.

**Important:** In Windows, if you use a version of the plugin from before March 3, 2016, you need to delete the `.ino.cpp` file before starting the Arduino IDE. In Linux, the Arduino IDE ignores this file, but in 1.6.7 on Windows (just tested it) the file gets picked up by the Arduino IDE. You need to restart the Arduino IDE to tell it the file is gone.

From March 3, 2016 onwards, the code in the `.ino.cpp` file is inside a `#ifdef` that is not defined in Arduino IDE.

# Answer
> 2 votes
Are you willing / able to work with Xcode? There is a package called embedXcode that enables Arduino development on Macs – I'm just getting up to speed with it, but it does appear to allow you to work either in Xcode or with the Arduino IDE (the .ino file is present and is what you edit in Xcode). In my testing so far it appears that the easiest thing to do is to create a project using Xcode and then you can point the Arduino IDE at the project pretty easily, getting Xcode to pick up a sketch started in the Arduino IDE is currently beyond me.

From the point of view of your students I would think that you'd want to keep the .ino file rather than make them learn about the conventions of C or C++. It would also save you the hassle of somehow managing file names – although you could probably get make to do this for you.

I haven't looked into it at all, but I think you could do something similar with Atom (a quick Google found a blog post called *Arduino Development in Atom Editor* and an Atom package called nino that is described as a "Toolbelt for Arduino") or Emacs, or for that matter Vim is also like to have some Arduino support.

---
Tags: arduino-ide, eclipse
---


# Question
Title: Arduino Due uploading error using Eclipse plugin "avrdude: stk500_recv(): programmer is not responding"
I have a Arduino Due that I'm trying to upload a sketch to. I follow the tutorial http://playground.arduino.cc/Code/Eclipse to get the board running with the Eclipse plugin.

However uploading the sketch gives me the error

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

```

If I use the Arduino IDE everthing works fine. I'm using Eclipse mars with Arduino 1.6.5

What could have gone wrong?

# Answer
> 0 votes
> avrdude: stk500\_recv(): programmer is not responding avrdude: stk500\_getsync() attempt 1 of 10: not in sync: resp=0x03

There's your clue. 1) programmer is not responding - This usually means the device isn't connected, or powered, or reachable by the IDE, make sure you have eclipse configured correctly for your device, and it's location.

2) not in sync - This is a redundant, or overlapping error, of course it's not going to sync if it can't connect.

# Answer
> 0 votes
You are using the wrong upload tool.

The due is not using avr dude as upload tool. You need to use bossac.

If you turn on verbose upload in the arduino ide preferences you will see

```
...arduino\tools\bossac\1.6.1-arduino/bossac.exe ...

```

---
Tags: arduino-due, eclipse
---


# Question
Title: How can I add additional boards to Eclipse with the Arduino add-on with only a URL, not a zip file
I want to add the following boards:

https://redbearlab.github.io/arduino/package\_redbearlab\_index.json

Which I can add in the Arduino IDE by going to File -\> Preferences -\> Additional Boards Manager URLs and just pasting it there

Where is the equivalent function in Eclipse, or how do I configure Eclipse to allow me to develop for those boards?

From Eclipse, I have tried Window-\> Properties -\> Arduino and from there "Private Library Path" and "Private hardware path", and I have tried pointing them to "C:\Program Files (x86)\Arduino\hardware" and "C:\Program Files (x86)\Arduino\libraries", but that didn't seem to change anything (i.e. no new board options, even after running Eclipse as admin) - while the boards show up (examples and all) in the Arduino IDE

# Answer
With arduino eclipse plugin 2.4 you simply install the boards with the arduino ide -like you described- and you can use then in the arduino eclipse plugin.

Version 3.0 (that is the nightly as 3.0 still needs to be released) contains it's own boards and library manager in windows-\>preferences-\>arduino.
> 1 votes

---
Tags: eclipse
---


# Question
Title: Can someone explain how to program i2C communications without using the library?
I am starting to get into i2C, SPI, and other forms of communication. I have read about them and have a fuzzy idea of how they work electrically, but can someone explain how I would turn the electronic portion into the coding/controlling portion? I really want to get a great understanding of it.

# Answer
> 1 votes
The AVR microcontrollers that Arduino uses have built-in hardware support for the said protocols.

That means that you don't have to write program to control the transmission/reception process but you only need to configure the appropriate registers and the hardware will initiate transfer and inform you when it's done. I suggest you carefully read the datasheet of the microcontroller you are using with your Arduino and you should find all the information there. It even has code examples, so you can actually copy-paste functions and use them in your program, here is one of the examples:

```
void SPI_MasterInit(void)
{
    /* Set MOSI and SCK output, all others input */
    DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK);
    /* Enable SPI, Master, set clock rate fck/16 */
    SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
}

void SPI_MasterTransmit(char cData)
{
    /* Start transmission */
    SPDR = cData;
    /* Wait for transmission complete */
    while(!(SPSR & (1<<SPIF)));
}

```

The keywords with the capital letters are usually register and bit names: you can look them up in the datasheet.

# Answer
> 0 votes
> Can someone explain how to program i2C communications without using the library?

The AVR has hardware support for this but you can implement it with the pin functions. I2C is a lot about timing the signals and detecting the reply signal from the slave.

The hardware support for I2C requires understanding of a complex state-machine. If you have implemented the I2C protocol it becomes easy to understand the hardware support and how this help remove a lot of work from the processor core. The state machine, control and status registers and interrupts, are described in the AVR product specification. There are also lots of excellent descriptions on the web. Do not miss the AVR application notes for the I2C. Most of the code in the Arduino core originated from them.

Cheers!

# Answer
> 0 votes
A good way to learn how to code for these interfaces is to look at the source code for the libraries themselves. In the PC world, these will be in the directory

Program files (x86)\Arduino\hardware\arduino\avr\libraries

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


title: Signal noise on R/C car channel output

text:
# Question
Title: Signal noise on R/C car channel output
Doing a little project for work and trying to get the Arduino hooked to an RC car to read the throttle channel output and send that via bluetooth to a nearby laptop which will output an animation based on that speed.

Initial test worked very well and signals from my airplane Tx were solid with very little variance. Once the proof of concept worked, we went ahead and purchased a Traxxas car. I have a wire going from pin 5 to the signal wire on the Rx. With the serial monitor up and arduino powered via my usb cable, the #s jump from the 1400 (where its supposed to be) to 6000 and sometimes 11000. Even more interesting, is when I engaged the throttle via the transmitter, values went down to 30-50...?? I removed the Rx from the car and powered it via the 5v on arduino...#s are solid.

So, it appears the battery or esc is giving a lot of interference. Do I need to use a different kind of wire? If so, what kind of wire? Or ground it somehow?

# Answer
Old post, but here was my solution. Had to pickup some shielded cable. Pics below should clearly explain how everything was wired up.
> 1 votes

---
Tags: remote-control
---


title: Freeze with VCNL 4000 Proximity Sensor

text:
# Question
Title: Freeze with VCNL 4000 Proximity Sensor
I've the VCNL 4000 Proximity Sensor I use some sample code and at the very beginning

the following code hangs (never finishes)

```
 readVCNLByte(0x81); is called

```

Can this problem be caused because the contact of the pin isn't very good.

I only but the part with pins in the sensor without to solder it.

Is it likely that this may be the problem ? I have not many experince with solder and the sensor is really small so i'd like to avoid it for first tests ;)

Here the code. The last output in the Serial window is "pre product"

```
  Serial.println("VCNL");
  Wire.begin();
  Serial.println("pre product");
  uint8_t rev = read8(VCNL4000_PRODUCTID);
   Serial.println("post product");
  if ((rev & 0xF0) != 0x10) {
    Serial.println("Sensor not found :(");
    while (1);
  }

```

# Answer
> 1 votes
You really can't expect this to work unsoldered. The contacts will be at best intermittent, and poor contact. Even a 'dry joint' where the pin is mostly surrounded by solder doesn't work well, these are the ultimate examples! You could however use an edge-connector, if you can find one; not something you see often nowadays.

# Answer
> 0 votes
Sorry .. my answer comes late .. I had the same issue, this has nothing to do with bad connexion between wires (not only at least). But by playing with some parameter (current value \> 60mA) I noticed that the module begin to freeze more often. To fix that : You need to add a small delay within your readbyte function after a i2c.stop()

I found that an issue had been written about that : https://github.com/adafruit/VCNL4000/issues/1 They recommand a 170us delay

I'm testing myself at full current and max speed (an since 30min it didn't freeze)... Before it could freeze in a second.

Hope it helps ;)

---

EDIT : In order to better understand where the freeze comes from, I re-write a simple I2C library. I could get rid of the freeze by simple add a small delay in the i2c\_start function (that send the start condition along with the slave address)

```
uint8_t i2c_start(uint8_t i2c_slave_address){
       //reset TWI control register
       TWCR = 0;
       //transmit start condition
       TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);
       //wait for end of transmission
       while((TWCR & (1<<TWINT))==0){
              _delay_us(75); // <-- here is the trick
       }
       if( (TWSR & 0xF8)!= TW_START ){
              return -1;
       }
       // load slave address into data register
       TWDR = i2c_slave_address;
       //start address transmission
       TWCR = (1<<TWINT) | (1<<TWEN);
       //wait for transmission
       while ( (TWCR & (1<<TWINT))==0 );
       //check if the slave did acknoledge the Read/Write mode
       uint8_t twst = TW_STATUS & 0xF8;
       if ( (twst != TW_MT_SLA_ACK) && (twst != TW_MR_SLA_ACK) ){
               return -1;
       }
       return 0;
}

```

you will need to add these libraries : util/twi.h (for the macro TW\_STATUS .. TTW\_MT\_SLA\_ACK and so on)

util/delay.h

stdlib.h (for the uint8\_t way of typing variable ..not actually 100% sure)

I'm still not fully satisfy by this solution, but it is still more effective that the one that adafruit propose.

I suggest you write you own i2c library (5 functions : init / start / read / write / stop) you now have the start already .. so 4 left ;)

If you're still to much afraid : in twi.c ( .\arduino\avr\libraries\Wire\utility\twi.c) and twi\_readFrom(...) function. On line 155 and 159 you will see that arduino send the start condition, but do not wait / take care that the transmission as been done... you can add a while function as previously describe to ensure it.

---

MASTER EDIT :

My previous solution didn't solve the issue neither... Actually reading the application note (Designing VCNL4000 into an Application : google that) gives the solution (page 7)

after you send the command to perform a single measurement, you need to wait. I put a delay of 500ms and have none anywhere else. This works like a charm.

But for energy efficiency I recommend to put the uC in sleep mode for that period of time.

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


title: Help Connecting Arduino Uno To Computer

text:
# Question
Title: Help Connecting Arduino Uno To Computer
I am A Newbie to Arduino

I have a Windows 7 PC. Last Time I bought an Arduino Uno Clone but after working for a day, it stopped detecting on the port. So I bought a new Clone Of different brand. Now I Want in which sequence should I install its drivers, Coonect it, Unzip Arduino IDE...Reboot??

I dont want a problem this time. Another question is Should I first connect the clone and then Install its drivers Or first install drivers and then plug the board? When Is the reboot required?

Product Link : https://m.ebay.in/itm?itemId=121708881208

Please Explain... Thanks In Advance

# Answer
> 1 votes
I have shorted my bords a few time and they always came back to "life" after a minute. Maybe you should be more concern about the voltage you supply to the board. Even if it can take up to 12 volt I never use more then 9 volt on the board. And if you run motors on them its always good to supply them with an external power source and use something like a H bridge to power your devices. I made mistakes and my board are still in mint conditions.

# Answer
> 0 votes
I would like to start by pointing out that you are using a clone. The arduino IDE by default does support clones. Just install your port drivers that's far enough.

The reason your board got spoilt the last time definitely was not cause you did not install the drivers in the right order. It could be due to many reasons, few listed below:

1. Poor PCB quality
2. Humidity
3. Cheap USB to UART converter.
4. Short circuit in your connection

So what I recommend is the either the use of genuine arduino boards if you can afford.

**Note:** Most likely its only the USB to UART (CH340G) that has been destroyed, you could buy a hot air station and replace the IC, it is a much cheaper solution.

# Answer
> 0 votes
I just checked the link and the item is not available anymore. That way it is impossible to say which driver you should install.

I agree with the answers and comments so far, get the real board. I've heard of people who fried their USB ports because of Arduino clones and their terrible/absent circuit protection.

If you can't afford the original board, what will you do if it damages your computer?

---
Tags: arduino-uno
---


# Question
Title: Did I fry my ESP8266 module or was it something wrong with it?
I was trying to connect my Arduino Nano to my home Wi-Fi. To do that, I connected my Arduino to ESP8266 module.

I connected pins

```
Arduino  | ESP8266
3.3V     | VCC
3.3V     | CH_PD
D10      | RXD
D11      | TXD
GND      | GND

```

to connect to Wi-Fi, I used code which I found on internet.

What I'm getting is `"FAILED - Timeout exceeded"` which indicates there is no response from the ESP module. Is it possible I did something wrong and I fried it, or I connected it wrong? Or maybe it does not have enough power (I'm powering my Arduino via computer USB port)? I also read reviews which indicates customers who bought similar product from different vendors they had issues with firmware. Is it possible I have same problem?

# Code

```
#include <SoftwareSerial.h>
SoftwareSerial softSerial(10, 11); // RX, TX
String WSSID = "xxxxxxxxxxxx";
String WPASS = "xxxxxxxxxxxx";
bool r;

void setup() {
  /* SETUP SERIAL COMMUNICATION */
  espSerialSetup();
  delay(2000); // Without this delay, sometimes, the program will not start until Serial Monitor is connected
  r = espSendCommand( "AT+CIFSR" , "OK" , 5000 );
  if( !r ) {
    r = espSendCommand( "AT+CWMODE=1" , "OK" , 5000 );
    r = espSendCommand( "AT+CWJAP=\""+WSSID+"\",\""+WPASS+"\"" , "OK" , 15000 );
  }
}

void loop(){
  r = espSendCommand( "AT+CIPSTART=\"TCP\",\"108.59.11.102\",80" , "OK" , 5000 );
  String getRequest = "GET /shiznic/ HTTP/1.1\r\nHost: www.rootpower.com\r\n";
  int getRequestLength = getRequest.length() + 2; // add 2 because \r\n will be appended by SoftwareSerial.println().
  r = espSendCommand( "AT+CIPSEND=" + String(getRequestLength) , "OK" , 5000 );
  r = espSendCommand( getRequest , "+IPD" , 15000 );
  //r = espSendCommand( getRequest , "world" , 15000 ); // page should respond with Hello, world.
  if( !r ) {
    Serial.println( "Something wrong...Attempting reset...");
    espSendCommand( "AT+RST" , "ready" , 20000);
    espSendCommand( "AT+CWMODE=1" , "OK" , 5000 );
    espSendCommand( "AT+CWJAP=\""+WSSID+"\",\""+WPASS+"\"" , "OK" , 15000 );
  }
  delay(3000);
}

void espSerialSetup() {

  // change baud rate so SoftwareSerial works better -- need a certain version of ESP for this to work and be retained after power cycle
  // make sure Serial Monitor port speed is set to 9600
  softSerial.begin(115200); // default baud rate for ESP8266
  delay(1000);
  softSerial.println("AT+CIOBAUD=9600");
  delay(1000);
  softSerial.begin(9600);
  Serial.begin(9600);
}

bool espSendCommand(String cmd, String goodResponse, unsigned long timeout) {
  Serial.println("espSendCommand( " + cmd + " , " + goodResponse + " , " + String(timeout) + " )" );
  softSerial.println(cmd);
  unsigned long tnow = millis();
  unsigned long tstart = millis();
  unsigned long execTime = 0;
  String response = "";
  char c;
  while( true ) {
    if( tnow > tstart + timeout ) {
      Serial.println("espSendCommand: FAILED - Timeout exceeded " + String(timeout) + " seconds" );
      if( response.length() > 0 ) {
        Serial.println("espSendCommand: RESPONSE:");
        Serial.println( response );
      } else {
        Serial.println("espSendCommand: NO RESPONSE");
      }
      return false;
    }
    c = softSerial.read();
    if( c >= 0 ) {
      response += String(c);
      if( response.indexOf(goodResponse) >= 0 ) {

        execTime = ( millis() - tstart );
        Serial.println("espSendCommand: SUCCESS - Response time: " + String(execTime) + "ms");
        Serial.println("espSendCommand: RESPONSE:");
        Serial.println(response);
        while(softSerial.available() > 0) {
          Serial.write(softSerial.read());
        }
        return true;
      }
    }
    tnow = millis();
  }
}

```

**UPDATE** I changed connections to D11 | RXD D10 | TXD

and i also simplified my code

```
#include <SoftwareSerial.h>

SoftwareSerial esp(10, 11);

void setup() {
   Serial.begin(115200);
  while (!Serial);
  Serial.println("Started");
  esp.begin(115200);
  esp.write("AT\r\n");
}

void loop() {
  if (esp.available()) {
    Serial.write(esp.read());
  }

  if (Serial.available()) {
    esp.write(Serial.read());
  }
}

```

now I'm sending basic AT command to test connection, and still not getting any response. LED on ESP module is on, so I'm assuming it is working.

# Answer
By the looks of the information you have provided, it looks as though you have not made the crossed serial connection: `rx-tx tx-rx`.

Your wiring:

```
Arduino  | ESP8266
3.3V     | VCC
3.3V     | CH_PD
D10      | RXD
D11      | TXD
GND      | GND

```

And when you intialize the software serial library:

```
SoftwareSerial softSerial(10, 11); // RX, TX

```

You declare `D10` as `RX` and then connect it to the ESPs `RX` and ditto for the `TX` line.

What you need to do is the following:

```
Arduino  | ESP8266
3.3V     | VCC
3.3V     | CH_PD
D10      | TXD   //change to this
D11      | RXD   //change to this
GND      | GND

```

Also you need to ensure that the arduino TX line does not exceed 3.3V you can use a voltage divider, logic-level shifter board or a 74LVC245. This is important as the 5V arduino pins will damage a 3.3V device. This is a note as arduino nano is a 5V device from what I know(I may be corrected).
> 3 votes

# Answer
As far as I know, the 3.3v on the Arduino board might not have enough current for the ESP module, as it is very 'power hungry'.

I've had some hard time making my modules work properly, and your problem could be a number of things.

I will stick to Ockam's razor principle and go by the simple side.

In your code you are using 9600 baud,but the ESP8266 'base' speed is 115200. Try that speed (and CR+LF) also on your Usb cable and it might work.
> 2 votes

---
Tags: arduino-nano, esp8266
---


title: Sending colours to vga monitor

text:
# Question
Title: Sending colours to vga monitor
I'm looking for a simple way to send a signal from my arduino to a vga monitor.

What would be the easiest method, and what components would be needed?

I don't need to display an image, just a solid colour.

# Answer
> 7 votes
My page about Arduino Uno output to VGA monitor has a lot of theory on it, including a sketch that produces colour bars like this:

---

## Code

To produce a single colour is slightly simpler, this sketch did it for me:

```
/*
 VGA colour video generation

 Author:   Nick Gammon
 Date:     22nd April 2012
 Version:  1.0

 Connections:

 D3 : Horizontal Sync (68 ohms in series) --> Pin 13 on DB15 socket
 D4 : Red pixel output (470 ohms in series) --> Pin 1 on DB15 socket
 D5 : Green pixel output (470 ohms in series) --> Pin 2 on DB15 socket
 D6 : Blue pixel output (470 ohms in series) --> Pin 3 on DB15 socket
 D10 : Vertical Sync (68 ohms in series) --> Pin 14 on DB15 socket

 Gnd : --> Pins 5, 6, 7, 8, 10 on DB15 socket

*/

#include <TimerHelpers.h>
#include <avr/pgmspace.h>
#include <avr/sleep.h>

const byte hSyncPin = 3;     // <------- HSYNC

const byte redPin = 4;       // <------- Red pixel data
const byte greenPin = 5;     // <------- Green pixel data
const byte bluePin = 6;      // <------- Blue pixel data

const byte vSyncPin = 10;    // <------- VSYNC

const int horizontalBytes = 60;  // 480 pixels wide
const int verticalPixels = 480;  // 480 pixels high

// Timer 1 - Vertical sync

// output    OC1B   pin 16  (D10) <------- VSYNC

//   Period: 16.64 ms (60 Hz)
//      1/60 * 1e6 = 16666.66 µs
//   Pulse for 64 µs  (2 x HSync width of 32 µs)
//    Sync pulse: 2 lines
//    Back porch: 33 lines
//    Active video: 480 lines
//    Front porch: 10 lines
//       Total: 525 lines

// Timer 2 - Horizontal sync

// output    OC2B   pin 5  (D3)   <------- HSYNC

//   Period: 32 µs (31.25 kHz)
//      (1/60) / 525 * 1e6 = 31.74 µs
//   Pulse for 4 µs (96 times 39.68 ns)
//    Sync pulse: 96 pixels
//    Back porch: 48 pixels
//    Active video: 640 pixels
//    Front porch: 16 pixels
//       Total: 800 pixels

// Pixel time =  ((1/60) / 525 * 1e9) / 800 = 39.68  ns
//  frequency =  1 / (((1/60) / 525 * 1e6) / 800) = 25.2 MHz

// However in practice, it we can only pump out pixels at 375 ns each because it
//  takes 6 clock cycles to read one in from RAM and send it out the port.

const byte verticalBackPorchLines = 35;  // includes sync pulse?
const int verticalFrontPorchLines = 525 - verticalBackPorchLines;

volatile int vLine;
volatile byte backPorchLinesToGo;

#define nop asm volatile ("nop\n\t")

// ISR: Vsync pulse
ISR (TIMER1_OVF_vect)
  {
  vLine = 0;
  backPorchLinesToGo = verticalBackPorchLines;
  } // end of TIMER1_OVF_vect

// ISR: Hsync pulse ... this interrupt merely wakes us up
EMPTY_INTERRUPT  (TIMER2_OVF_vect)

void setup()
  {

  // disable Timer 0
  TIMSK0 = 0;  // no interrupts on Timer 0
  OCR0A = 0;   // and turn it off
  OCR0B = 0;

  // Timer 1 - vertical sync pulses
  pinMode (vSyncPin, OUTPUT);
  Timer1::setMode (15, Timer1::PRESCALE_1024, Timer1::CLEAR_B_ON_COMPARE);
  OCR1A = 259;  // 16666 / 64 µs = 260 (less one)
  OCR1B = 0;    // 64 / 64 µs = 1 (less one)
  TIFR1 = bit (TOV1);   // clear overflow flag
  TIMSK1 = bit (TOIE1);  // interrupt on overflow on timer 1

  // Timer 2 - horizontal sync pulses
  pinMode (hSyncPin, OUTPUT);
  Timer2::setMode (7, Timer2::PRESCALE_8, Timer2::CLEAR_B_ON_COMPARE);
  OCR2A = 63;   // 32 / 0.5 µs = 64 (less one)
  OCR2B = 7;    // 4 / 0.5 µs = 8 (less one)
  TIFR2 = bit (TOV2);   // clear overflow flag
  TIMSK2 = bit (TOIE2);  // interrupt on overflow on timer 2

  // prepare to sleep between horizontal sync pulses
  set_sleep_mode (SLEEP_MODE_IDLE);

  // pins for outputting the colour information
  pinMode (redPin, OUTPUT);
  pinMode (greenPin, OUTPUT);
  pinMode (bluePin, OUTPUT);

}  // end of setup

// draw a single scan line
void doOneScanLine ()
  {

  // after vsync we do the back porch
  if (backPorchLinesToGo)
    {
    backPorchLinesToGo--;
    return;
    }  // end still doing back porch

  // if all lines done, do the front porch
  if (vLine >= verticalPixels)
    return;

  PORTD = bit (5) | bit (6);  // cyan (green + blue)
  delayMicroseconds (27);     // one scan line

  PORTD = 0;  // back to black
  // finished this line
  vLine++;

  }  // end of doOneScanLine

void loop()
  {
  // sleep to ensure we start up in a predictable way
  sleep_mode ();
  doOneScanLine ();
 }  // end of loop

```

As @ChrisStratton suggested, the hardware timers are a big help.

---

## Wiring

I wired it up like this:

---

## TimerHelpers library

The **TimerHelpers.h** library is described on my timers page, a copy is below:

```
/*
 Timer Helpers library.

Devised and written by Nick Gammon.
Date: 21 March 2012
Version: 1.0

Licence: Released for public use.

See: http://www.gammon.com.au/forum/?id=11504

 Example:

 // set up Timer 1
 TCNT1 = 0;         // reset counter
 OCR1A =  999;       // compare A register value (1000 * clock speed)

 // Mode 4: CTC, top = OCR1A
 Timer1::setMode (4, Timer1::PRESCALE_1, Timer1::CLEAR_A_ON_COMPARE);

 TIFR1 |= bit (OCF1A);    // clear interrupt flag
 TIMSK1 = bit (OCIE1A);   // interrupt on Compare A Match

*/

#ifndef _TimerHelpers_h
#define _TimerHelpers_h

#include <Arduino.h>

/* ---------------------------------------------------------------
 Timer 0 setup
 --------------------------------------------------------------- */

namespace Timer0
{
  // TCCR0A, TCCR0B
  const byte Modes [8] [2] =
  {

  { 0,                         0 },            // 0: Normal, top = 0xFF
  { bit (WGM00),               0 },            // 1: PWM, Phase-correct, top = 0xFF
  {               bit (WGM01), 0 },            // 2: CTC, top = OCR0A
  { bit (WGM00) | bit (WGM01), 0 },            // 3: Fast PWM, top = 0xFF
  { 0,                         bit (WGM02) },  // 4: Reserved
  { bit (WGM00),               bit (WGM02) },  // 5: PWM, Phase-correct, top = OCR0A
  {               bit (WGM01), bit (WGM02) },  // 6: Reserved
  { bit (WGM00) | bit (WGM01), bit (WGM02) },  // 7: Fast PWM, top = OCR0A

  };  // end of Timer0::Modes

  // Activation
  // Note: T0 is pin 6, Arduino port: D4
  enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_64, PRESCALE_256, PRESCALE_1024, T0_FALLING, T0_RISING };

  // what ports to toggle on timer fire
  enum { NO_PORT = 0,

    // pin 12, Arduino port: D6
    TOGGLE_A_ON_COMPARE  = bit (COM0A0),
    CLEAR_A_ON_COMPARE   = bit (COM0A1),
    SET_A_ON_COMPARE     = bit (COM0A0) | bit (COM0A1),

    // pin 11, Arduino port: D5
    TOGGLE_B_ON_COMPARE  = bit (COM0B0),
    CLEAR_B_ON_COMPARE   = bit (COM0B1),
    SET_B_ON_COMPARE     = bit (COM0B0) | bit (COM0B1),
  };

  // choose a timer mode, set which clock speed, and which port to toggle
  void setMode (const byte mode, const byte clock, const byte port)
  {
  if (mode < 0 || mode > 7)  // sanity check
    return;

  // reset existing flags
  TCCR0A = 0;
  TCCR0B = 0;

  TCCR0A |= (Modes [mode] [0]) | port;
  TCCR0B |= (Modes [mode] [1]) | clock;
  }  // end of Timer0::setMode

}  // end of namespace Timer0

/* ---------------------------------------------------------------
 Timer 1 setup
 --------------------------------------------------------------- */

namespace Timer1
{
  // TCCR1A, TCCR1B
  const byte Modes [16] [2] =
  {

  { 0,                         0 },            // 0: Normal, top = 0xFFFF
  { bit (WGM10),               0 },            // 1: PWM, Phase-correct, 8 bit, top = 0xFF
  {               bit (WGM11), 0 },            // 2: PWM, Phase-correct, 9 bit, top = 0x1FF
  { bit (WGM10) | bit (WGM11), 0 },            // 3: PWM, Phase-correct, 10 bit, top = 0x3FF
  { 0,                         bit (WGM12) },  // 4: CTC, top = OCR1A
  { bit (WGM10),               bit (WGM12) },  // 5: Fast PWM, 8 bit, top = 0xFF
  {               bit (WGM11), bit (WGM12) },  // 6: Fast PWM, 9 bit, top = 0x1FF
  { bit (WGM10) | bit (WGM11), bit (WGM12) },  // 7: Fast PWM, 10 bit, top = 0x3FF
  { 0,                                       bit (WGM13) },  // 8: PWM, phase and frequency correct, top = ICR1
  { bit (WGM10),                             bit (WGM13) },  // 9: PWM, phase and frequency correct, top = OCR1A
  {               bit (WGM11),               bit (WGM13) },  // 10: PWM, phase correct, top = ICR1A
  { bit (WGM10) | bit (WGM11),               bit (WGM13) },  // 11: PWM, phase correct, top = OCR1A
  { 0,                         bit (WGM12) | bit (WGM13) },  // 12: CTC, top = ICR1
  { bit (WGM10),               bit (WGM12) | bit (WGM13) },  // 13: reserved
  {               bit (WGM11), bit (WGM12) | bit (WGM13) },  // 14: Fast PWM, TOP = ICR1
  { bit (WGM10) | bit (WGM11), bit (WGM12) | bit (WGM13) },  // 15: Fast PWM, TOP = OCR1A

  };  // end of Timer1::Modes

  // Activation
  // Note: T1 is pin 11, Arduino port: D5
  enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_64, PRESCALE_256, PRESCALE_1024, T1_FALLING, T1_RISING };

  // what ports to toggle on timer fire
  enum { NO_PORT = 0,

    // pin 15, Arduino port: D9
    TOGGLE_A_ON_COMPARE  = bit (COM1A0),
    CLEAR_A_ON_COMPARE   = bit (COM1A1),
    SET_A_ON_COMPARE     = bit (COM1A0) | bit (COM1A1),

    // pin 16, Arduino port: D10
    TOGGLE_B_ON_COMPARE  = bit (COM1B0),
    CLEAR_B_ON_COMPARE   = bit (COM1B1),
    SET_B_ON_COMPARE     = bit (COM1B0) | bit (COM1B1),
  };

  // choose a timer mode, set which clock speed, and which port to toggle
  void setMode (const byte mode, const byte clock, const byte port)
  {
  if (mode < 0 || mode > 15)  // sanity check
    return;

  // reset existing flags
  TCCR1A = 0;
  TCCR1B = 0;

  TCCR1A |= (Modes [mode] [0]) | port;
  TCCR1B |= (Modes [mode] [1]) | clock;
  }  // end of Timer1::setMode

}  // end of namespace Timer1

/* ---------------------------------------------------------------
 Timer 2 setup
 --------------------------------------------------------------- */

namespace Timer2
{
  // TCCR2A, TCCR2B
  const byte Modes [8] [2] =
  {

  { 0,                         0 },            // 0: Normal, top = 0xFF
  { bit (WGM20),               0 },            // 1: PWM, Phase-correct, top = 0xFF
  {               bit (WGM21), 0 },            // 2: CTC, top = OCR2A
  { bit (WGM20) | bit (WGM21), 0 },            // 3: Fast PWM, top = 0xFF
  { 0,                         bit (WGM22) },  // 4: Reserved
  { bit (WGM20),               bit (WGM22) },  // 5: PWM, Phase-correct, top = OCR2A
  {               bit (WGM21), bit (WGM22) },  // 6: Reserved
  { bit (WGM20) | bit (WGM21), bit (WGM22) },  // 7: Fast PWM, top = OCR2A

  };  // end of Timer2::Modes

  // Activation
  enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_32, PRESCALE_64, PRESCALE_128, PRESCALE_256, PRESCALE_1024 };

  // what ports to toggle on timer fire
  enum { NO_PORT = 0,

    // pin 17, Arduino port: D11
    TOGGLE_A_ON_COMPARE  = bit (COM2A0),
    CLEAR_A_ON_COMPARE   = bit (COM2A1),
    SET_A_ON_COMPARE     = bit (COM2A0) | bit (COM2A1),

    // pin 5, Arduino port: D3
    TOGGLE_B_ON_COMPARE  = bit (COM2B0),
    CLEAR_B_ON_COMPARE   = bit (COM2B1),
    SET_B_ON_COMPARE     = bit (COM2B0) | bit (COM2B1),
  };

  // choose a timer mode, set which clock speed, and which port to toggle
  void setMode (const byte mode, const byte clock, const byte port)
  {
  if (mode < 0 || mode > 7)  // sanity check
    return;

  // reset existing flags
  TCCR2A = 0;
  TCCR2B = 0;
  TimerHelpers.h
  TCCR2A |= (Modes [mode] [0]) | port;
  TCCR2B |= (Modes [mode] [1]) | clock;
  }  // end of Timer2::setMode

}  // end of namespace Timer2

#endif

```

---

## References

# Answer
> 4 votes
A quick Google search for "Arduino VGA" will give you a lot of information. There are a few variations on both circuits and programming, which also vary in resolution and color depth.

I was searching for this a few days ago, and these are my favorite (so far):

If using a TV is also a plausible option, check the Arduino TV out library. It can be installed directly from the Arduino IDE and has a good demo.

# Answer
> 3 votes
Not needing to display an actual image simplifies things substantially, as an Arduino lacks the memory and (except in a crude sense) the bandwidth to do so.

However, you cannot simply apply a steady analog voltage to the R, G, and B lines. Not only do you have to drive horizontal and vertical sync signals, you have to blank the RGB signals when not on the active portion of the screen, otherwise the monitor will assume their steady voltage means "black" and your colors will last only as a brief flash when your device is first connected or enabled.

Generating a large rectangular field of color from an Arduino is likely to be rather challenging, but probably not impossible. You may be able to use hardware PWM channels for the horizontal and a "color enable", and tightly coded software counters for the vertical aspect. You can then use the "color enable" to gate a network of potentially variable resistors to establish the single color of particular interest.

---
Tags: arduino-uno
---


# Question
Title: Can I use the TLC5940 LED Driver if I'm already using other SPI devices on my Arduino mega?
The way I understand SPI is that 3 wires are shared (MOSI, MISO, & SCHK). The slave select is pulled high when you want to write to a specific device. The 3 shared wires can be daisy chained. The TLC5940 LED Driver says that it uses SPI but I don't see any documentation about a slave select. Can I just include this in the standard daisy chaining and assign a new slave select? In some forums online some people seem to indicate you can't use the TLC5940 on the same SPI bus as other devices. I thought that was the whole point of SPI. Are there different forms of SPI? I'm quite confused, can I use the TLC5940 with other SPI devices?

# Answer
> 2 votes
> Can I just include this in the standard daisy chaining and assign a new slave select?

SPI is normally used as a parallel bus and requires MISO to be tri-state (disconnected when not selected).

> In some forums online some people seem to indicate you can't use the TLC5940 on the same SPI bus as other devices.

The device does not have a chip select which gives a challenge. No direct wiring is possible but can be solved.

> Are there different forms of SPI? I'm quite confused, can I use the TLC5940 with other SPI devices?

It is possible to connect the TLC5940 but it requires some extra logic. You can for instance block the clock signal when it is not selected. This can be done with a MOSFET or 74HC125 and a pull-low resistor.

Cheers!

---
Tags: arduino-mega, led, spi
---


# Question
Title: Can I use IO10 as digital IO while using SPI interface?
If my arduino is the master device in a SPI network, hence not using the slave select SS pin, can I use the same pin as IO10?

I am actually using an Intel Galileo, with the same pinout as an Arduino Uno Rev3.

# Answer
> 1 votes
> Can I use IO10 as digital IO while using SPI interface?

On AVR it must be OUTPUT when using SPI in master mode and INPUT in slave mode.

> If my arduino is the master device in a SPI network, hence not using the slave select SS pin, can I use the same pin as IO10?

The SS pin (D10) has to be OUTPUT when using SPI master mode. It can be used for chip select on the SPI bus (slave select) or some other output function.

So far the Arduino design with AVR (e.g. ATmega328). The Intel Galileo based Arduino has the following block diagram:

IO10-IO14 are multiplexed from SPI1 or GPIO. This implies that the SPI SS (IO10) signal is hardwired to the SPI controller when enabled. Last, according to the product info SPI is master only. More details schematics details here.

Cheers!

---
Tags: pins, spi, arduino-galileo
---


# Question
Title: How to slow ADC clock speed to 1MHz on Arduino Due?
I know that the ADC on the Arduino Due has a clock speed from 1 MHz to 20 MHz. I have two questions: 1. What is the default clock speed when I run a sketch, and 2. How can I change it? (I am using Arduino 1.6.4.)

The reason why I want to slow down the ADC as much as possible is to obtain the maximum source impedance. Is this logic correct? (i.e., if I slow down the ADC in the arduino code to kHz values, then the source impedance will reach MΩ values?)

# Answer
> 1 votes
You can change the prescaler (`ADCSR` register). Lowest scaler is 2, so it can never run at 20mHz. Also Atmel recommends a max ADC clock of 1MHz.

Arduino sets the ADC clock to 125 KHz (prescaler of 128)

So to match Arduino, you should select a prescaler of 8 ( set bits `ADPS1` and `ADPS0`)

# Answer
> 1 votes
The atod clock is set in the mode register. The clock is 42MHz/(PRESCAL#+1). One way of setting it is the use ADC-\>ADCMR = ADC\_MR\_PRESCAL(PRESCAL#), where PRESCAL# is some integer. These symbols are defined in component\_adc.h in the Arduino source code. In the AVR data sheet, the recommended clock is MIN=1MHz, MAX=20 MHZ, corresponding to numbers between 41 and 1. Look in the data sheet, section 43.

---
Tags: arduino-due
---


title: Two arduinos one power source

text:
# Question
Title: Two arduinos one power source
I was surprised that this question had no answer on Stack Exchange and I can't find much about it elsewhere so, in the hopes that it will be useful to people other than myself, I'd like to ask:

How can one power two arduinos using the same power source? Such that the first is connected by barrel jack to a 12v transformer.

I saw this youtube video which *very* briefly mentions doing this by make the connections:

> Ardu1 --\> Ardu2
>
> 5V --\> 5V
>
> GND --\> GND

This surprised me as I was not aware the 5V could operate as a power input. I was expecting the use of the `VIN` pin somewhere along the line.

Am I correct in thinking that the second arduino would take power on it's `VIN` pin from `5V` on arduino one?

If so, where should the second arduino ground to?

# Answer
I have powered numerous arduino's via the 5V pin. I would however call this an advanced usage because there are some limitation/dangers.

First of all: Power your arduino via 5V and plugin a powered USB cable or a powered plug and it may (probably will) damage your USB or arduino or both.

Secondly; it is best to assume that all arduino's are different on behalf of the behaviour of the +5V pin. I know for a fact there is a difference with uno,yun,due.

thirdly: The way it is used on the video -you linked to- (power jack 5V arduino 1 to 5V arduino 2 and ground arduino 1 to ground arduino 2) makes that all power goes through the voltage converter on the Arduino 1. These voltage converters can not handle much current. This is only sufficient in very low power drawing applications.

It s not a good idea to connect the 5V pin of arduino 1 to Vin of the arduino 2. This because the voltage converter on arduino 2 will not be able to provide 5V to The 5V cirquitry.

It is mutch smarter to connect the Vin from arduino 1 to Vin of Arduino2.

When I power arduino's from "standard batteries" I use a switching power supply that powers the arduino over a cut in halve USB cable. This way it is lots safer as I can add power over the jack and I can not plugin a second USB cable.
> 1 votes

# Answer
You could put the 12v from the barrel jack on both Arduninos Vin pins by jumpering the Vin pins together instead of the Vin-\>+5 or +5-\>+5. Then they'd have independent protection and regulation of 1A, 5V through their NCP1117ST50T3G chips.
> 3 votes

# Answer
Connecting the +5V pins together is acceptable providing you don't exceed the total load that the source of the +5V can provide. This would be either:

* The maximum the *USB interface* can provide:

```
Bus 003 Device 013: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)
Device Descriptor:
...
  bDeviceClass            2 Communications
...
  idVendor           0x2341 Arduino SA
  idProduct          0x0043 Uno R3 (CDC ACM)
...
  Configuration Descriptor:
...
    MaxPower              100mA

```

That would seem to be 100 mA from doing `lsusb -v` on my Ubuntu system.
* The maximum that the *voltage regulator* can provide (if you are using the power jack, **or** Vin). This would depend on the model of Arduino, plus what your input voltage is (the higher the input voltage, the hotter the voltage regulator will get).

---

When I am testing things like sending I2C from one Arduino to another, I will often connect the USB to one of them, and just connect together the +5V pins (**and ground** of course) so that the second Arduino gets powered.

---

**Caveat** : my page about power indicates that without using sleep modes and other techniques, a Uno may consume 50 mA on its own. Thus connecting two Unos is likely to be reaching the limit that the USB interface can provide. Connecting three or more is likely to be problematic.

---

Regarding the USB power issue, see How to get more than 100mA from a USB port. On that page it says:

> **USB-100mA**
>
> USB by default will deliver 100mA of current (it is 500mW power because we know it is 5v, right?) to a device. This is the most you can pull from a USB hub that does not have its own power supply, as they never offer more than 4 ports and keep a greedy 100mA for themselves.
>
> ...
>
> Near the end of enumeration you setup device parameters. Very specifically the configuration descriptors. If you look on this website they will show you all of the different pieces that can be set. It shows that you can get right up to 500mA of power requested.

As the negotiation in this case appears to be requesting 100 mA (and not 500 mA) the port on the PC may well limit you to that.
> 2 votes

# Answer
> This surprised me as I was not aware the 5V could operate as a power input. I was expecting the use of the VIN pin somewhere along the line.

Power is just power. It doesn't have a "direction" like an IO pin. It just flows from a point of higher potential to a point of lower potential. If you put a load onto the 5V pin then the power will flow out of the 5V pin, through the load, to the lower GROUND potential. And that is all the other Arduino is - a load. The power flows out of the 5V, into the other Arduino, through it, and down to the lower GROUND potential.

It's just like a rechargeable battery. Put a light on the battery and the electricity flows out of the battery to light the lamp. Apply a higher voltage to the battery from another supply and the power flows out of the supply into the battery, recharging it (or making it explode if the voltage is too high).
> 0 votes

---
Tags: power
---


# Question
Title: Motor Shield not giving full power, LED DIMS
I have an Adafruit Motor Shield, the V1. I have been using this thing with my OPSEPP Uno and a stepper motor with no issues. (Powered by 12v DC wall wart \[CASIO\]).

My question, or issue, not sure yet, is this:

Why when I connect my motor directly to the 12v power supply it operates efficiently (for my purposes) and when I run it through my Arduino with the Adafruit Motor.h library does it not power the same.

Basically on direct connection it works fine, but I want to be able to regulate the connection and reverse it, change the speed, etc.

It is possible I am utilizing the library or the board wrong.

Can someone indicate why the power or, torque seems to drop when through the board. I have tried all KHZ all speeds etc, no way to get the same 12v power directly and modulate it?

# Answer
> 1 votes
According to the Adafruit page the V1 version of the shield is not as powerful as their V2 version.

Where is the 12V coming from to get to the shield? There isn't really 12V broken out on the Uno anywhere. If it comes from Vin then there is a 0.7V drop through the reverse polarity protection diode. Plus, the tracks on the Arduino board may not be thick enough to provide enough current.

It looks like the shield may take an external power source (it is hard to tell because they discontinued it). You could try using that.

---
Tags: power, motor, adafruit
---


title: ATTiny watchdog and interrupt

text:
# Question
Title: ATTiny watchdog and interrupt
I'm trying to control an Arduino Barebone from an arduino with relays. Basically when the attiny starts it should switch on the arduino for 4 seconds. The Arduino sends a signal back to a digital pin of the attiny and as long as it is set to high the attiny should leave it working. If it is low the attiny should switch the relay of.

the problem is some changes to the code make the interrupt reset the attiny (which would switch of the arduino) othertimes- in this case. the interrupt doesn't work at all.

```
#include <avr/sleep.h>
#include <avr/wdt.h>
#include <avr/io.h>
#include <avr/interrupt.h>

#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

int pinBoard = 0;
bool boardOn = false;
bool startBoard_flag = false;
int pinBoardReturn = 3;

volatile boolean f_wdt = 1;

void setup() {
  cli();//disable interrupts during setup
  pinMode(pinBoard, OUTPUT);
  pinMode(pinBoardReturn, INPUT);
  setup_watchdog(9);
  cbi(ADCSRA, ADEN);                   // switch Analog to Digitalconverter OFF
  // cli();//disable interrupts during setup
  for (int i = 0; i < 10; i++) {
    digitalWrite(pinBoard, HIGH);
    delay(100);
    digitalWrite(pinBoard, LOW);
    delay(100);
  }

  PCMSK |= (1 << PCINT1); //sbi(PCMSK,INTERRUPTPIN) also works but I think this is more clear // tell pin change mask to listen to pin2 /pb3 //SBI
  GIMSK |= (1 << PCIE);   // enable PCINT interrupt in the general interrupt mask //SBI

  startBoard();

  DDRB &= ~(1 << DDB1); //cbi(DDRB, DATADIRECTIONPIN);//  set up as input  - pin2 clear bit  - set to zero
  PORTB |= (1 << PB1); //cbi(PORTB, PORTPIN);// disable pull-up. hook up pulldown resistor. - set to zero
}

void startBoard() {
  digitalWrite(pinBoard, HIGH);
  boardOn = true;
  startBoard_flag = false;
  cli();                                  // Disable interrupts
  delay(4000);
}

void shutdownBoard() {
  digitalWrite(pinBoard, LOW);
  boardOn = false;
}

void loop() {
  if (f_wdt == 1) { // wait for timed out watchdog / flag is set when a watchdog timeout occurs
    f_wdt = 0;     // reset flag
    if (startBoard_flag) {
      startBoard();
    }
    bool boardReturn = digitalRead(pinBoardReturn);
    if (boardOn && !boardReturn) {
      shutdownBoard();
    }
    system_sleep();
  }
}

//****************************************************************
// set system into the sleep state
// system wakes up when wtchdog is timed out
void system_sleep() {

  // GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
  // PCMSK |= _BV(PCINT3);                   // Use PB3 as interrupt pin

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement
  sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
  sleep_cpu();                            // sleep

  // PCMSK &= ~_BV(PCINT3);                  // Turn off PB3 as interrupt pin
  sleep_disable();                        // Clear SE bit

  // sei();                                  // Enable interrupts
}

//****************************************************************
// 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms
// 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec
void setup_watchdog(int ii) {

  byte bb;
  int ww;
  if (ii > 9 ) ii = 9;
  bb = ii & 7;
  if (ii > 7) bb |= (1 << 5);
  bb |= (1 << WDCE);
  ww = bb;

  MCUSR &= ~(1 << WDRF);
  // start timed sequence
  WDTCR  |= (1 << WDCE) | (1 << WDE);
  // set new watchdog timeout value
  WDTCR  = bb;
  WDTCR  |= _BV(WDIE);
}
//****************************************************************
// Watchdog Interrupt Service / is executed when  watchdog timed out
ISR(WDT_vect) {
  f_wdt = 1; // set global flag
}

ISR(PCINT_VECTOR) {
  for (int i = 0; i < 4; i++) {
    digitalWrite(pinBoard, HIGH);
    delay(1000);
    digitalWrite(pinBoard, LOW);
    delay(1000);
  }
  startBoard_flag = true;
  f_wdt = 1; // set global flag
}

```

# Answer
Disassembling the `delay` code indicates it uses `micros` which needs interrupts on to work.

```
void delay(unsigned long ms)
{
 27a:   cf 92           push    r12
 27c:   df 92           push    r13
 27e:   ef 92           push    r14
 280:   ff 92           push    r15
 282:   cf 93           push    r28
 284:   df 93           push    r29
 286:   6b 01           movw    r12, r22
 288:   7c 01           movw    r14, r24
    uint16_t start = (uint16_t)micros();
 28a:   d3 df           rcall   .-90        ; 0x232 <micros>
 28c:   eb 01           movw    r28, r22

    while (ms > 0) {
 28e:   c1 14           cp  r12, r1
 290:   d1 04           cpc r13, r1
 292:   e1 04           cpc r14, r1
 294:   f1 04           cpc r15, r1
 296:   79 f0           breq    .+30        ; 0x2b6 <delay+0x3c>
        yield();
 298:   ea d0           rcall   .+468       ; 0x46e <yield>
        if (((uint16_t)micros() - start) >= 1000) {
 29a:   cb df           rcall   .-106       ; 0x232 <micros>
 29c:   6c 1b           sub r22, r28
 29e:   7d 0b           sbc r23, r29
 2a0:   68 3e           cpi r22, 0xE8   ; 232
 2a2:   73 40           sbci    r23, 0x03   ; 3
 2a4:   a0 f3           brcs    .-24        ; 0x28e <delay+0x14>
            ms--;
 2a6:   81 e0           ldi r24, 0x01   ; 1
 2a8:   c8 1a           sub r12, r24
 2aa:   d1 08           sbc r13, r1
 2ac:   e1 08           sbc r14, r1
 2ae:   f1 08           sbc r15, r1
            start += 1000;
 2b0:   c8 51           subi    r28, 0x18   ; 24
 2b2:   dc 4f           sbci    r29, 0xFC   ; 252
 2b4:   ec cf           rjmp    .-40        ; 0x28e <delay+0x14>
        }
    }
}
 2b6:   df 91           pop r29
 2b8:   cf 91           pop r28
 2ba:   ff 90           pop r15
 2bc:   ef 90           pop r14
 2be:   df 90           pop r13
 2c0:   cf 90           pop r12
 2c2:   08 95           ret

```

---

That appears to confirm that the code in `wiring.c` is indeed what is being used on the ATtiny85 core:

```
void delay(unsigned long ms)
{
    uint16_t start = (uint16_t)micros();

    while (ms > 0) {
        yield();
        if (((uint16_t)micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

```

Turning interrupts off and then doing a `delay` is a Bad IdeaTM.

---

> So i would rather have a counter for the watchdog in order to wait for the specified time?

Using the watchdog timer is certainly one way of waiting for 4 seconds.
> 4 votes

---
Tags: interrupt, attiny
---


# Question
Title: Hall effect sensor direction detection using arduino
I'm using a hall effect sensor A1356 (linear application) to measure the amount of fluid in a container. The fluid is in constant use. My doubt is I'm placing the sensor and the magnet assembly in place, such that when it is exactly half filled, the magnet's center will align with the center of the sensor. In this condition I get 100% duty cycle output from the sensor.

Condition 1: If the fluid is filled then the magnet moves above the sensor and the duty cycle reduces say to 90%.

Condition 2: If the fluid is consumed then the magnet will move below the sensor and the duty cycle reduces to say 90%.

How do I differentiate between the rise and fall of the fluid? Or is there a better way of orienting the magnet and the sensor such that this problem could be avoided?

I'm interfacing it with an Arduino UNO

# Answer
> 2 votes
According to the data sheet (see below) the no-field PWM output is mid-range; north poles reduce it & south increase.

So if you had an arrangement whereby the float had north down & south up, ie a vertical bar-magnet, this would presumably give a rise-before-0 or fall-before-0 at the float vanishes, or a fall-to-minimum an rise-to-maximum as the float centres? The bit in the middle could be interesting!

From the datasheet: "The presence of a south polarity magnetic field, perpendicular to the branded surface of the package face, increases the output duty cycle from its quiescent value toward the maximum duty cycle limit. The amount of the output duty cycle increase is proportional to the magnitude of the magnetic field applied. Conversely, the application of a north polarity field decreases the output duty cycle from its quiescent value."

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


title: Arduino UNO and SPI eeprom (AT93C46D)

text:
# Question
Title: Arduino UNO and SPI eeprom (AT93C46D)
I'm trying to write to and read from an AT93C46D eeprom using an Arduino UNO but for some reason the output I'm getting is not what I expect.

The eeprom has a data structure of 128 words of 8 bits each and I'm trying to write 10000010 to each word. When reading back the data however I get 11000001. When I write 00000000 to all words I get 10000000 for all words when reading. I tested my code on 2 AT93C46D eeproms and both gave the same result.

It looks like the MSB is always 1 (when reading) for some reason.

I'm probably making a stupid mistake but I can't seem to find it, any help is greatly appreciated!

Datasheet: http://www.atmel.com/images/atmel-5193-seeprom-at93c46d-datasheet.pdf

```
#include<SPI.h>
#define DATAOUT 11//MOSI
#define DATAIN  12//MISO
#define SPICLOCK  13//sck
#define SS 10//ss

void setup()
{
  pinMode(SS,OUTPUT);
  pinMode(DATAOUT, OUTPUT);
  pinMode(DATAIN, INPUT);
  pinMode(SPICLOCK,OUTPUT);
  digitalWrite(SS,LOW);

  Serial.begin(9600);

  SPI.beginTransaction(SPISettings(2000000, MSBFIRST, SPI_MODE0));

  fill();

  dump();
}

void loop()
{

}

void fill()
{
  Serial.println("Send EWEN opcode");
  digitalWrite(SS,HIGH);
  SPI.transfer(B10011); //EWEN
  SPI.transfer(B0000000);
  digitalWrite(SS,LOW);

  delay(100);

  for (int i=0; i < 128; i++) {
    digitalWrite(SS,HIGH);
    SPI.transfer(B101);
    SPI.transfer(i);
    SPI.transfer(B10000010);
    delay(10);
    digitalWrite(SS,LOW);
  }

  delay(100);

  Serial.println("Send EWDS opcode");
  digitalWrite(SS,HIGH);
  SPI.transfer(B1000); //EWDS
  SPI.transfer(B00000000);
  digitalWrite(SS,LOW);

  delay(10);
}

void dump(){
  Serial.println("Dumping AT93C46D");

  byte b;

  for (int i=0; i < 128; i++) {
    digitalWrite(SS,HIGH);
    SPI.transfer(B110); //read opcode
    SPI.transfer(i);
    b = SPI.transfer(B00000000); //clock data out
    digitalWrite(SS,LOW);
    Serial.println(b, BIN);
  }
}

```

# Answer
After looking at the product spec again I think it might be possible to get this working. The protocol is MSB with a start bit S followed by two bit op-code, and parameters. SPI on AVR is 8-bit transfer but transfer can be byte aligned with the start bit.

READ is op-code(10) followed by 7-bit address, a dummy bit and the read value. That is in total 11+8-bits. Mapping that to 8-bit transfer would be:

```
spi.transfer(0b110);
spi.transfer(addr << 1);
data = spi.transfer(0);

```

That will give 5-bit zero, start-bit, op-code in the first transfer, and followed by 7-bit address and dummy bit (LSB) in second transfer. The third transfer is the read data.

EWEN would map to:

```
spi.transfer(0b1001);
spi.transfer(0b10000000);

```

EWEN has op-code(00), followed by 9-bits, 0b11XXXXXXX.

The WRITE operation becomes:

```
spi.transfer(0b10);
spi.transfer(0x80 | addr);
spi.transfer(data);

```

Cheers!
> 0 votes

---
Tags: arduino-uno, spi, eeprom
---


title: Eclipse add library

text:
# Question
Title: Eclipse add library
I am completely lost here, I have no idea what I am doing wrong. I am using Eclipse Mars using the Eclipse C++ Arduino extension. I am also using the COSA library, this is where the problem comes in. I can use all of the core COSA libraries but I can not figure out how to include the other libraries that are supplied with COSA specifically the ST7920.h file that is located in the libraries folder. Does anyone have any experience with this?

I have tried setting the path using the Project-\>C/C++ General-\>Preprocessor include paths and setting it there to no avail.

One thing that I am concerned about is in these separate libraries they are including files that are in other libs using only the header file, for example in the ST7920.hh file it has:

```
#include "Cosa/LCD.hh"
#include <HD44780.h>

```

I need to configure things so that the HD44780.h file needs to be found also. That file is located at "../HD44780/HD44780.h". How do I tell the compiler to search the "libraries" folder for files?

Also I tried to simply add the libraries folder as a linked folder in my project, that also did not work.

the only code I have is the #include and the compiler come back with that it can't find the file.

# Answer
I would advice to use the arduino eclipse plugin and not use the eclipse C++ arduino extension.

The eclipse C++ arduino extension is still very much in development.

The Arduino eclipse plugin has been around for years and contains far more features.

If you use V3 (that is still the nightly at the time of writing) you can use the boards manager and the cosa json file to import the cosa boards.

Importing a lib is a matter of typing

```
#include "libname"

```

and saving.
> 1 votes

# Answer
If you are using Linux I would recommend looking at the makefile based build script for Cosa (See Cosa/build). After configuration building from any IDE is more or less a simple command. No Makefile is required. The script cosa will do all the work.

```
$ cosa BOARD ACTION

```

such as

```
$ cosa uno avanti

```

which will build a sketch for Arduino Uno, upload and start a serial monitor. This can be used from any IDE. I use GNU Emacs, M-X compile (F2), with the command.

The way the Arduino pre-processor works each referenced library needs to be included in the sketch. For a sketch that uses ST7920:

```
#include <HD44780.h>
#include <ST7920.h>

```
> 0 votes

---
Tags: arduino-mega, eclipse
---