title: Adding fade to this RGB LED IMU

text:
# Question
Title: Adding fade to this RGB LED IMU
I've built an accelerometer based dice. It changes colour based on what side of the dice faces up. All is well and good, except I'd like the RGB to fade from one colour to the next instead of changes instantly.

Here's the code:

```
include <Wire.h>
include <Adafruit_Sensor.h>
include <Adafruit_LSM303_U.h>
include <Adafruit_9DOF.h>
include <Adafruit_L3GD20_U.h>

/* Assign a unique ID to the sensors */
Adafruit_9DOF                 dof   = Adafruit_9DOF();
Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(30301);
Adafruit_LSM303_Mag_Unified   mag   = Adafruit_LSM303_Mag_Unified(30302);

// OUTPUT: Use digital pins 9-11, the Pulse-width Modulation (PWM) pins
// LED's cathodes should be connected to digital GND
int redLEDPin = 11;   // Red LED,   connected to digital pin 9
int greenLEDPin = 10;  // Green LED, connected to digital pin 10
int blueLEDPin = 9;  // Blue LED,  connected to digital pin 11

// Program variables
int red = 255;   // Variables to store the values to send to the pins
int green = 255;
int blue = 255;

int lastOrientation = -1; // previous orientation

void initSensors()
{
  if(!accel.begin())
  {
    Serial.println(F("No LSM303 detected"));
    while(1);
  }
  if(!mag.begin())
  {
    Serial.println("No LSM303 detected");
    while(1);
  }
}

void setup() {

  Serial.begin(115200);
  Serial.println(F("RGB Dice... go!")); Serial.println("");

  /* Initialise the sensors */
  initSensors();

  pinMode(redLEDPin, OUTPUT);   // sets the pins as output
  pinMode(greenLEDPin, OUTPUT);
  pinMode(blueLEDPin, OUTPUT);

  int lastOrientation = -1; // previous orientation
}

void loop() {

  /* Get a new sensor event */
  sensors_event_t event;
  accel.getEvent(&event);

  int orientation = - 1; // dice orientation
  String orientationString; // string for printing orientation
  /*
   * orientation:
   * 1: cyan
   * 2: blue
   * 3: green
   * 4: magenta
   * 5: yellow
   * 6: red
   */

  // read accelerometer
  int x = event.acceleration.x;
  int y = event.acceleration.y;
  int z = event.acceleration.z;

  // calculate absolute values, and determin largest
  int absX = abs(x);
  int absY = abs(y);
  int absZ = abs(z);

  if ( (absZ > absX) && (absZ > absY)) {

    //base orientation Z
    if (z > 0) {
      orientationString = "1, cyan";
      orientation = 1;
      red = 255;
      green = 0;
      blue = 0;

    } else {
      orientationString = "6, red";
      orientation = 6;
      red = 0;
      green = 255;
      blue = 255;
    }

  } else if ( (absY > absX) && (absY > absZ)) {

    //base orientation Y
    if (y > 0) {
      orientationString = "2, blue";
      orientation = 2;
      red = 255;
      green = 255;
      blue = 0;

    } else {
      orientationString = "5, yellow";
      orientation = 5;
      red = 0;
      green = 0;
      blue = 255;
    }
  } else {
    //base orientation X
    if (x > 0) {
      orientationString = "4, magenta";
      orientation = 4;
      red = 0;
      green = 255;
      blue = 0;

    } else {
      orientationString = "3, green";
      orientation = 3;
      red = 255;
      green = 0;
      blue = 255;

    }
  }

  // if orientation changes, print out a description
  if (orientation != lastOrientation) {
    Serial.println(orientationString);
    lastOrientation = orientation;
  }

  analogWrite(redLEDPin, red);   // Write values to LED pins
  analogWrite(greenLEDPin, green);
  analogWrite(blueLEDPin, blue);
  delay(100);

}

```

Every fading example I have adopted has broken the code so far. I guess my initial code isn't set up for it. Any ideas for a workaround?

# Answer
You need to be a little clearer about the time that can exist between the sensor values changing. If you fade to slowly the correct value might never be reached before the sensor changes again. Maybe that's what you want?

You can't use a `delay()`.

You need a `currentRed`, `currentGreen` and `currentBlue` so you can fade to the values of red, green and blue.

```
unsigned long last_reading_ms;
int red = 255;   // Variables to store the TARGET rgb target values for each pin
int green = 255;
int blue = 255;
int currentRed = 0;   // Variables to store the current rgb values of the pins
int currentGreen = 0;
int currentBlue = 0;

void setup()
{
   last_reading_ms=millis();
}

void loop()
{
  /* read sensor every 100ms and set red, green,blue if changed */
  if (millis()-last_reading_ms > 100)
  {
    /* Get a new sensor event */
    sensors_event_t event;
    accel.getEvent(&event);
    //the rest of your sensor reading code here

    last_reading_ms=millis()
  }

  /* if orientation changes, print out a description */
  if (orientation != lastOrientation) {
   Serial.println(orientationString);
   lastOrientation = orientation;
  }

  calculateRGBFadeTo();

  analogWrite(redLEDPin, currentRed);   // Write values to LED pins
  analogWrite(greenLEDPin, currentGreen);
  analogWrite(blueLEDPin, currentBlue);

  //*** do not use a delay or use a very small one to slow the transition ***
  //delay(100);

}

/* get values 1 step closer to target red, green, blue */
void calculateRGBFadeTo()
{
  /* fade to required rgb values */
  if (currentRed<red)
   currentRed ++;
  else if (currentRed>red)
   currentRed --;

  if (currentGreen<green)
    currentGreen ++;
  else if (currentGreen>green)
    currentGreen --;

  if (currentBlue<blue)
    currentBlue ++;
  else if (currentBlue>blue)
    currentBlue --;

}

```

Notes:

The fade can be slowed down either with a small delay such as 5 ms. or by using another `millis()` variable to determine the time since the led was last set.

For example: `if (millis()-last_rgb_write_ms > 5)`

It's also possible to speed up the fade by using a larger increment. An increment of two, for example, `currentRed+=2;` instead of `currentRed++;`

Reminder, the comparison of when the target red, green, blue has been reached will be more complex with an increment greater than `1`.

An increment of `2` and a sensor read frequency of `128ms` (instead of 100) would ensure the correct RGB values are always reached. Alternatively reading the sensor every `255ms` (4-5 times per second) would also ensure the correct RGB values has been reached.

Using `millis()` and avoiding delays allows many more tasks to be performed with more accurate timings.
> 1 votes

---
Tags: accelerometer, rgb-led
---


title: XBee: How do I create a packet?

text:
# Question
Title: XBee: How do I create a packet?
I am currently using a simple protocol I created to send three bytes (unit information, data, and XOR) individually over an XBee radio (3 bytes are considered a single transmission). However, this is not always reliable if a byte is dropped. For this reason I'd like to encapsulate each individual byte as a packet in a way that the Arduino could identify which byte is which and if a byte is lost then just wait for the next transmission. What I am not sure about is creating a packet. I haven't been able to find any tutorials or example code.

# Answer
The biggest mistake people always make with serial communications of any form is to just send raw data over the connection. While you might just about get away with that on a 100% reliable direct serial connection over a short distance, as soon as you introduce anything with any form of uncertainty to it you are, as you have seen, doomed to failure.

So you have to come up with a reliable method of transferring data in such a way that the receiver knows that it has received valid data, and how to find valid data.

So you need to create a packet. That's not something where you just wave a magic wand and a packet is created. A packet starts it's life in your own head.

In order to reliably transfer data there are a few things you need to consider from the point of view of the receiver:

* Where is the start of my data?
* How much data is there?
* Is this data correct?

The receiver has to have some way of knowing where the start of a packet is amid the torrent of bytes it is being sent. It needs to look out for something unique, something it cannot mistake for anything else. This is called synchronisation. It is often done with a specific sequence of bytes (known as a *preamble*) that can, through various means, never appear anywhere else.

And at that point things start to get a little more complex, for now you need some way of wrestling that kind of thing into a system that can only send bytes of 0 to 255 with no way of distinguishing raw data from control information like this synchronisation sequence. And that is where the concept of *escaping* comes in. This is where you nominate certain byte values as control bytes and decide that these bytes will never appear in your data without some kind of marker to say they are data bytes. A common escape marker is 255 (used in the telnet protocol) or 27 (the ANSI ESC character) although any character can be chosen.

For instance if you choose to have a synchronisation sequence of 0xAA, 0x55, you can then decide that neither of those bytes will ever appear in your data without first being preceeded by character 0xFF. So if you happened to have that sequence in your data you would expand it out to 0xFF, 0xAA, 0xFF, 0x55. But what if you want to send the value 0xFF, in your data? How do you handle that? Well, you also escape 0xFF as well. 0xFF, being the escape character, has no actual value in the data. It only says that the next character must be interpreted as data. So to send 0xFF you would actually send 0xFF, 0xFF. Your receiver sees the first 0xFF and thinks "ah, the next byte that arrives, whatever it is, just be data." It then gets a second 0xFF and knows it is data. (Actually this is the opposite of escaping which says the next character is a control character, but the underlying concept is the same).

If it ever sees 0xAA, 0x55 then it knows, without a shadow of a doubt, that this is the start of a packet, or random noise. And that is where the next two points above come in: Validating your packet.

If your packets are always the same size then all you need to know is how many bytes to expect, which can be hard coded into your software. If you have different sizes of data to send then you also need to tell the receiver how big the data is. This forms part of the *packet header*. A small block of meta data that preceeds the actual data that holds information about the packet. Depending on your topology that could be things like the size of the data, where the packet came from, where it is going, etc, and maybe a checksum, though some people like to put the checksum after the data since it simplifies sending.

And then there is the checksum. Possibly the most important thing next to the synchronisation. And so easy to get wrong.

Having a checksum that is too simple is not so good. It can be fooled. That is, if values get corrupted in the data with a simple checksum it is far more likely that the checksum still says it's correct than with a more complex checksum. You should read up on existing checksum algoritms, such as Cyclic Redundancy Check (CRC) and things like the checksums used in IP packets. All are good lessons on how to deal with checksums properly.

So far we have just tackled the serial equivalent of UDP - throw a packet at a receiver and hope it gets there. Doing anything more reliable becomes much more complex. If you want to know if your packet actually got there you will need your receiver to acknowledge reception, possibly including some information about the packet it received, such as a sequence number. If the transmitter never receives that acknowledgement it needs to send the packet again, which means it needs to remember what the packet is that it sent. So you need a packet buffer, or even better, a packet queue. And timeouts. And sequence numbers.

That latter is most important. A sequence number is a unique (or unique over a reasonable period of time) identifier for a packet. When a transmitter doesn't receive an acknowledgement is it because the receiver never got the packet, or that the receiver did get the packet but the acknowledgement never made it back to the transmitter? If the latter then the receiver is liable to get the same packet multiple times through retransmission. By including a sequence number the receiver can go "hang on a moment, I have seen this packet already" and it can throw it away sending a new acknowledgement in the process.

So as you can see, reliable communication isn't as simple as just sending data, or even sending data in the form of a struct. There is a whole lot more to learn and understand.

I suggest you read some of the IP networking RFCs to learn more about reliable packet transmission and reception.

Oh, and I haven't even touched on sliding window reception and such like for how to best program your receiver software...
> 5 votes

# Answer
* The x-ctu xbee config tool has a few options worth exploring such as error checking. This means the xbee would do the work.

*OR using the Arduino(s)*

* Adding a couple more bytes to you your current system with a checksum of the first 3 bytes would be a simple way to check for a valid packet.
* You could also use a struct of values (along with a checksum). Bill Porter has written an Arduino Library called Arduino Easy Transfer. The library is designed to send and receive a struct along with checksum validation. This is an overview page for the library.
* Sending and receiving structs over `Serial` is also covered here
> 2 votes

---
Tags: xbee
---


title: Traffic lights using timer

text:
# Question
Title: Traffic lights using timer
My traffic light code for the Arduino doesn't run. I was wondering if anyone could point out where my issues lie. The red and green LEDs should be on for 15 seconds and the amber on for 5 seconds.

```
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdint-gcc.h>
/*15 second interrupt*/
#define INTERRUPTS 975

/*
 * col = current colour of light.
 * 'g', 'a', 'r', 'o'
 */
volatile uint8_t count;
volatile char col;

ISR(TIMER0_OVF_vect)
{
    count++;
    if (count >= INTERRUPTS){
        if (col == 'g'){
            /*switch to amber*/
            col = 'a';
            /*reset counter*/
            count = 0;
            /*timer counter to 171 as we only need 85 clicks for 5s*/
            TCNT0 = 171;
            PORTD = 0b00000010;
        } else if(col == 'a'){
            col = 'r';
            count = 0;
            TCNT0 = 0;
            PORTD = 0b00000100;
        } else if (col == 'r'){
            col = 'o';
            counter = 0;
            TCNT0 = 171;
            PORTD = 0b00000010;
        } else if (col == 'o'){
            col = 'g';
            count = 0;
            TCNT0 = 0;
            PORTD = 0b00000001;
        } else{
            return;
        }
    } else{
        if(col == 'g' || col == 'r'){
            TCNT0 = 0;
        } else if(col == 'a' || col == 'o'){
            TCNT0 = 171;
        }
    }
    return;
}

int main(void)
{
    /* normal mode */
    TCCR0A = 0b00000000;
    /* prescaler = 1024 */
    TCCR0B = 0b00000101;
    /* enable overflow interrupts */
    TIMSK0 = 0b00000001;
    TCNT0 = 0;
    sei();
    /*Initialise output*/
    DDRD = 0b11111111;
    count = 0;
    col = 'g';
    PORTD = 0b00000001;
    while (1){
    }
}

```

# Answer
> 3 votes
```
#define INTERRUPTS 975

volatile uint8_t count;

if (count >= INTERRUPTS){

```

`count` is an 8 bit integer, so the maximum value of it is `255`. Therefor `count` will never be bigger of equal to 975.

Use `volatile uint16_t count;` instead.

PS instead of messing with the `TCNT0` register, I'd use 2 different values of `INTERRUPTS` to change between 15 and 5 second intervals.

Something like `if( count>=975 || ( (col=='g'||col=='r') && count>=325 ) ){`

# Answer
> 1 votes
As far that i understand, you set the color using the Ports directly. In case green and red you set PORTD = 0b00000010;

# Answer
> 1 votes
If you want solution with a timer, I suggest to setup a 35 second cycle (35 = 15+15+5). Then, you will trigger next LED when 0,15,30 seconds passed, and restart cycle at 35 seconds.

Other ways to achieve same effect are: 1. Use classic `delay()` function.

```
while (true)
{
    TurnOn(Green);
    delay(15000);
    TurnOn(Red);
    delay(15000);
    TurnOn(Amber);
    delay(5000);
}

```
2. use `millis()` function

---
Tags: arduino-uno, c, timers
---


title: Motor Control Help

text:
# Question
Title: Motor Control Help
Here is my objective:

If the value of `EMGv` is at or above 900, start moving the motors left. The motors should continue to move left for a maximum of one second, provided `EMGv` stays at or above 900. If during this time `EMGv` goes below 900, the motors should move right for one second. Then the motors should stop. At any time after this should `EMGv` go above 900 again, the process should repeat.

In simpler terms, the project is a robotic hand, wired to an EMG circuit. When the EMG signal gets above 900 the hand should close by the motors all turning left for one second and when the signal goes below 900 the hand should open by the motors turning right for one second.

Here is my loop atm when `move(motor #, speed, direction (1 for left, 0 for right))` is the function to move the motors and `stop()` stops all motors

```
void loop(){

  unsigned long starttime; //time limit for hand movement
  int EMGv = analogRead(EMG);
  starttime=millis();
  while(EMGv >= 900){
    if (millis()-starttime < 1000) //limit on 1000ms
    {
    move(0, 255, 1); //motor 1, full speed, left
    move(1, 255, 1); //motor 2, full speed, left
    move(2, 255, 1); //motor 3, full speed, left
    move(3, 255, 1); //motor 4, full speed, left
    move(4, 255, 1); //motor 5, full speed, left
    } else {
      stop();
    }
  }
}

```

# Answer
> 1 votes
I suspect you would do well to first write (in English) the *exact* set of rules you want it to follow -- don't worry about the code to begin with - get it clear in your head what you want the code to do. (If this is already clear to you, then just write it :-) )

Here's what I think you might mean -- although it's not exactly what you wrote.

*If EMG is at or above 900, start moving the motors left. The motors should continue to move left for a maximum of one second, provided EMG stays at or above 900. If during this time EMG goes below 900, the motors should move right for one second. Then the motors should stop.*

Once you have that, turning it into code looks well within your ability, judging by the code you've posted. Here's my attempt - note that it'll only be correct if I have correctly stated your desired rules. (And if I've correctly guessed how the `move` API works - I guess it starts the motor moving, that you need to cancel it to stop it moving. Please say if this is wrong.)

I've used LEFT and RIGHT instead of 1 and *whatever*, for clarity.

```
void loop(){
  // If EMG is at or above 900
  int EMGv = analogRead(EMG);
  if (EMGv >= 900)
  {
    unsigned long starttime = millis();

    // Start the motors moving left
    move(0, 255, LEFT); //motor 1, full speed, left
    ...and the other motors...

    // Continue for a maximum of one second, and while EMG stays at or above 900
    while ( (millis()-starttime < 1000) && ((EMGv = analogRead(EMG)) >= 900)) {
      // Just wait
      delay(1);
    }

    // If during this time EMG goes below one second...
    if (EMGv < 900) {
      // ...the motors should move right for one second
      move(0, 255, RIGHT); //motor 1, full speed, right
      ...and the other motors...
    }

    // Then the motors should stop.
    move(0, 0, LEFT); //motor 1, stop, left
    ...and the other motors...
  }

// More stuff here, otherwise it will immediately go round the loop again and start moving again
}

```

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


title: Using Arduino with Assembly on MacOS

text:
# Question
Title: Using Arduino with Assembly on MacOS
I'm trying to use an Arduino UNO board with Assembly on MacOS, but I couldn't find any documentation about it.

How can I compile and upload Assembly files to the Arduino with MacOS?

# Answer
> 3 votes
You can add source code to the sketch in the Arduino IDE. When adding a new source code file make sure the extension is uppercase `.S`

Files with `.S` extension will be compiled as Assembly.

There is an Arduino IDE for the mac but if you want to use an external editor you have many options.

The simplest is to switch on `File>Preferences>External Editor` in the Arduino IDE. This makes the IDE work in "read-only/auto-reload" mode allowing edit in a different code editor but compile and upload (without reopening the code) in the Arduino IDE.

There are also the `File>Preferences` `Verbose Compile` and `Verbose Upload` options in the Arduino IDE. These options will show you the commands used to compile, link and upload. You will see that the IDE runs other programs, outside of the IDE, such as `avrdude` and `g++`. Therefore a small script file can be created to call the same commands from a different IDE if the external editor doesn't have a facility to run external commands.

The verbose output will show where the tools and sources for build and upload are located. Normally for `Uno` (avr) they are below `[IDE Folder]\hardware\arduino`.

---
Tags: atmega328, mac-os, osx, assembly
---


# Question
Title: Waking up async the Arduino while it's sleeping periodically
I´m using `LowPower.h` and `PinChangeInt.h` libraries to put my Arduino into the sleep mode every 8 seconds and then it wakes up, modifies a counter and it goes to sleep again, but also I need to wake it up when a button is pressed asynchronously.

I´ve reached to wake up the Arduino every 8 seconds using `LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF)` and, in other code, I´ve also reached to wake it up while it sleeps indefinitely with `LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF)` but I can´t combine that periodical awakening with the asynchronous awakening.

Here is my code:

```
void setup(){

    Serial.begin(9600);

    //Pines declaration

    loopsToSend = setTimeToSend();  //

    //The three async buttons
    PCintPort::attachInterrupt(4, readOpinion,RISING);
    PCintPort::attachInterrupt(5, readOpinion,RISING);
    PCintPort::attachInterrupt(6, readOpinion,RISING);
}

void loop(){

    if(loops < loopsToSend ){

        byte opinionValue = readOpinion(); //This method must awake the Arduino ASYNC to give a value to the opinionValue var, write the result in the file and go to sleep

        if(opinionValue != 0){
            Serial.println("Button pressed!");

            //Writing result in a file
            opiniones++;
            delay(500);
        }
        //Go to sleep 8 seconds
        LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
        opinionValue = 0;
    }
    else {
        wdt_disable();

        if(opiniones > 0){
            //Send file using GSM module
        }
        else{
            loops = 0;
        }
    }
    loops++;
}

```

Can anyone help me? Thanks

# Answer
> 2 votes
This one works for me:

```
#include <PinChangeInterrupt.h>
#include <LowPower.h>

// I want to know when it was interrupted by PCINT:
volatile byte flag = 0;
void handler() {
    flag = 1;
}

void setup() {
  Serial.begin(115200);
  pinMode(A0, INPUT_PULLUP);
  attachPCINT(digitalPinToPCINT(A0), handler, CHANGE);
}

void loop() {
  Serial.println("entering powerDown sleep mode");
  Serial.flush(); // wait for sending all data

  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);

  if (flag == 1) {
    flag = 0;
    Serial.println("Pin change interrupt");
  } else {
    Serial.println("Timeout");
  }
}

```

However if you use RISING (or FALLING), it also wakes up from the sleep when pin changes back to the oposite state (and it'll be reported as Timeout).

---
Tags: power, interrupt, arduino-pro-mini, sleep
---


# Question
Title: Update Variable via Arduino to Arduino I2C
I am attempting to send a simple 1 byte value from one arduino to another using I2C with the Wire library. From reading I see that this is typically done using the event monitor supplied by the Wire library, but this has caused problems for me because the handler function may only have one argument and it must be a `void` function or else the library throws errors during compilation. So I have a couple of questions about what is or is not possible with the Wire library short of modifying the source:

1. Should the `Wire.available()` function respond to attempted transmissions if the event handler referenced above does not exist? My first idea was to simply write my own function that would be called whenever this value is not 0, but it appears that this value never changes - unless the event handler is used.
2. Can you update variables which reside outside of a function from inside of the function WITHOUT passing those variables as pointer arguments? Because recall from above that I cannot pass any arguments besides the one specified for the number of bytes received.

I cannot understand how this library could be useful for Arduino to Arduino communication if it is literally not possible to use the transmitted values anywhere other than inside of the event handler. My next step is start modifying the source to suit my needs, but I would imagine what I'm describing is a basic thing and would be shocked to find out that it's not possible without modification.

# Answer
> 2 votes
I see now what the issue was. But to answer my questions:

1. `Wire.available();` will not work if called outside of an event handler. I confirmed this while reading through the `Wire.cpp` source code and it explicitly states that the function should only be called from an event handler.
2. It is as simple as only a matter of updating global variables. I feel quite silly for not realizing that simply declaring variables outside of a function gives ANY function access to it rather than only the main function.

I see that the other answer mentions applying the `volatile` modification to the variables, but this is only necessary when the function in question is attached to an interrupt handler.

# Answer
> 1 votes
> Can you update variables which reside outside of a function from inside of the function WITHOUT passing those variables as pointer arguments?

Yes, that's exactly what global variables are for. Make them `volatile` as they will be updated inside an ISR (or more exactly, a function called from an ISR).

---
Tags: i2c, communication, wire-library
---


# Question
Title: Getting the DS18B20 detected and temperature read
I'm quite new with the electronics part of Arduino, but I thought that this was the basic way to get the DS18B20 temperature device hooked up. However, I can't detect it in my program using OneWire and DallasTemperature.

This is an image of my connections:

Basically my approach was like this:

Connect ground on ground on the DS18B20. Connect 5V from the Arduino to both DQ from the DS18B20 and Port 2 on my Arduino (the two yellow cables). Between the 5V and the two yellow cables, I connected a 4.7K resistor. Vdd on the DS18B20 is not connected to anything.

Anyone have any idea why this is not working as expected for me?

Thanks in advance!

# Answer
> 4 votes
> Vdd on the DS18B20 is not connected to anything.

According to the datasheet:

> When the DS18B20 is used in parasite power mode, the VDD pin must be connected to ground

---

> Connect 5V from the Arduino to both DQ from the DS18B20 and Port 2 on my Arduino (the two yellow cables).

That means port 2 would always be high, right?

---

According to Temperature Sensor DS18B20 this is the wiring for non-parasitic power:

If you want the two-wire version (parasitic power) it would be:

---
Tags: electronics, resistor, ds18b20
---


# Question
Title: How to reprogram Arduino if USB port is already in use?
I'm developing a keyboard emulator using Digispark Pro (based on Arduino) which uses USB port as the keyboard interface. I haven't programmed it yet because I doubt how should I recognize the chip to Arduino IDE again using USB port after programming the board.

So my question is, how to reprogram Arduino if USB port is already recognized as keyboard HID?

# Answer
> 2 votes
https://digistump.com/wiki/digispark/tutorials/connectingpro It is suggested that in order to upload using the Arduino IDE you must:

* Add the repository `http://digistump.com/package_digistump_index.json` in Preferences \> Additional Boards Manager URLs
* Install Digistump from the boards manager.
* select the DigiSpark in Tools \> Boards.
* Then this is perhaps the important bit "**You do not need to plug in your Digispark Pro before invoking upload**" So hit upload before connecting the Digispark.
* Then connect the Digispark when prompted by the Arduino IDE.

---
Tags: usb, programming, keyboard
---


# Question
Title: How do you figure out an efficient battery setup for a project?
I have a project where I need an Arduino Uno and 4 DC motors to run on batteries. My first thought was that I'll just hook up 3 or 4 AAs to the Arduino and a 9V to the motor drivers.

I googled to be safe and the internet consensus seemed like that method would be very inefficient. Voltage wasn't the problem, but apparently 9V have very low current and I'd be wasting money, and the Arduino wastes current like a madman. Most solutions involved buying additional hardware.

**Is there a way I can efficiently power my project without buying more chips?**

# Answer
> 4 votes
Our beloved admin Nick Gammon has made a very neat articile on this subject, I suggest you read it and apply as many of the methods he described.

Also, it can be worth to check the requirements of your project, how long should it work on battery to be acceptable? Set some realistic boundarys to avoid getting lost in (trying to) optimizing beyond all practical purposes.

There are two places where you can save power:

**In software**

The Atmega328P has a few tricks to save power. Most notably is powering down peripheral devices and/or using sleep modes. I believe the P version of the Atmega328 also has more power saving modes/ is more efficient overall.

Also take a look at this.

**In hardware**

An Arduino board has a lot of chips that may not even be neccesary on your battery project. Most notably the USB interface chip, if you're going to run off battery, you most likely won't need this chip. But also, the voltage regulator on the Arduino is, I believe, a linear regulator and is likely to be inefficient. Also power/status LED's will some current.

You can choose to put a ATMega328P on a breadboard, and power it directly with a source that will be between the min/max voltage of the ATMega328P. This way you don't get the losses that a regulator will have. If you want to use a regulator (for a higher voltage source) you should use a switching regulator, they're typically more efficient.

Mind that on low voltages, the ATMega328P can't do a 16Mhz, but it's actually a pretty interesting point, since it will consume less power on 8Mhz, or even less on 1Mhz.

# Answer
> 3 votes
Agreed, the DC motors would drain the 9V in no time.

Consider the other way around. The 9V powers the Arduino and the 4 AA batteries power the motor.

Then again, you probably don't need the 9V at all, just power everything off of the 4 AA batteries.

I suggest using a large capacitor (something in the 470-1000uF region) to hold up the supply to the Arduino. Adding a diode before the capacitor will prevent the capacitor discharging to the motors when the motors are drawing a lot of current.

Using 4x 1.5V batteries will result in a voltage of just over 6V. The diode will have a voltage drop of around 0.6V, so the resulting voltage would be 5.4V.

This voltage is to low for the onboard voltage regulator on the Adruino. It is within limits for the raw 5V input (ie. 5.5V).

Optionally you can add a 5V zener diode across the Arduino's power input to protect ti from overvoltage. A 6.8 ohm resistor is added to limit the current flowing through the zener diode. As the voltage drops below 5V, the zener diode will turn off, allowing the micro to operate down to 4.5V. If you change to a lower frequency crystal/resonator you can operate the microcontroller down to 2.7V (1.8V is possible is the clock frequency is 4MHz or less but I doubt the motors will run).

simulate this circuit – Schematic created using CircuitLab

---
Tags: arduino-uno, battery
---


# Question
Title: How to turn on Solenoid based on Soil Moisture value?
I am powering solenoid with 24 volt as required however I am using TIP122

transistor that has base connected to Arduino Digital Pin 6 via a 1K Resistor. And the collector is connected to negative side of 1N4001 diode, this also serves as the Negative out for solenoid. and emitter is connected to the 24 volt power input. The positive input from power source is connected to positive terminal of diode is directly connected to solenoid.

As per the logic I am trying to turn on Solenoid based on Signal from Arduino PIN 6, but for some reason Solenoid doesnt power up.

In my code below I want to turn on solenoid if soil moisture goes above 60. the signal is coming from Pin 6 but solenoid doesnt power up.

```
#include <SPI.h>

int solenoidPin = 6;    //This is the output pin on the Arduino we are using

int GLED = 5; // Wet Soil Indicator at Digital PIN D5
int RLED = 9; // Dry Soil Indicator at Digital PIN D9
int SENSE = 1; // Soil Sensor input at Analog PIN A1
int val = 0;

int greenLedPin = 2; // LED on pin 2
int yellowLedPin = 3;
int redLedPin = 4;

int lightSensorPin = A0;
int analogValue = 0;

void setup() {
  pinMode(solenoidPin, OUTPUT);           //Sets the pin as an output

  // Open serial communications and wait for port to open:
  Serial.begin(9600);

  pinMode(greenLedPin, OUTPUT); // LED on pin 2
  pinMode(yellowLedPin, OUTPUT);
  pinMode(redLedPin, OUTPUT);

  pinMode(GLED, OUTPUT);
  pinMode(RLED, OUTPUT);

}

void loop() {
  val = analogRead(SENSE);
  val = val / 10;
  analogValue = analogRead(lightSensorPin);
  Serial.print("LDR value: ");
  Serial.print(analogValue);
  digitalWrite (redLedPin, analogValue < 55) ;
  digitalWrite (yellowLedPin, analogValue >= 55 && analogValue <= 100) ;
  digitalWrite (greenLedPin, analogValue > 100) ;

  Serial.print(" Soil Moisture: ");
  Serial.println(val);
  digitalWrite(GLED, (val < 50));
  digitalWrite(RLED, (val > 50));
  // Turn on Solenoid Valve if soil moisture value greater than 60
  digitalWrite(solenoidPin, (val > 60));

}

```

I am doubting on the diode to use , because I am powering solenoid of 24 volt and not sure if the diode is correct , as per my knowledge, diode can get direct if higher voltage is passed.

Any help will be greatly appreciated.

# Answer
When looking your schematic and assuming that **J1** connector is not powered by your MacBook as your Arduino board, the main problem is located to the **GND** signal.

In order to have a commutation current to the **Base** of the TIP122 through the 1K resistor, you need to link the **GND** signal its **Emitter** with the **GND** signal of your Arduino board.

See a proposed schematic from **"High-Power Control: Arduino + TIP120 Transistor"**
> 2 votes

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


# Question
Title: Arduino Serial Response is Slow when in While Loop
Good evening all,

I'm having an issue with a quick "test" project that I am tinkering with (learning the "do's" and "don'ts") the NeoPixel LED strip. I've been piecing together excerpts from other folks and so far everything is great.

I'm doing it over serial sending switch/case with numbers from the keyboard for different options. The issue I am currently having is "case 1:", when I hit the "1" key and it fires off, I want to be able to interrupt it immediately by using key "0". So basically, I'd like it to loop forever after hitting key "1" but terminate after hitting "0".

However, when hitting key "1", then key "0" immediately, the while loop repeats twice, then breaks. I haven't done any C/C++ since I was 12 and now I'm 38 so now it is all trial and error based so please pardon my syntax. Any help would be appreciated.

```
#include <Adafruit_NeoPixel.h>
#include <SoftwareSerial.h>

#define PIN 6
#define LEDs 16

int LED_Fade_Interval = 5;

Adafruit_NeoPixel strip = Adafruit_NeoPixel(LEDs, PIN, NEO_GRB + NEO_KHZ800);

void setup() {

  Serial.begin(9600);

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

}

void loop() {

  while (Serial.available() == 0);

  int numKey = Serial.read() - '0';

  uint32_t low = strip.Color(0, 0, 0);

  switch(numKey)
  {

    case 1:
      Serial.println("LED Strip is ON - BLUE FADE");
      while (numKey != 0)
      {
        int numKey = Serial.read() - '0';
        delay(50);

        ws2812_FadeInOut(0, 0, 255, LED_Fade_Interval);

        if (numKey == 0)
        {

          for( int i = 0; i<LEDs; i++){
            strip.setPixelColor(i, low);
            strip.show();
          }

          break;

        }

      }

    case 0:
      Serial.println("LED Strip is OFF");
      for( int i = 0; i<LEDs; i++){
          strip.setPixelColor(i, low);
          strip.show();
      }
      break;
   }
}

// *******************************************
// FADER Function
// *******************************************
void ws2812_FadeInOut(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }

     strip.show();
     delay(wait);
  };

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }
     strip.show();
     delay(wait);
  };
};

```

# Answer
> 1 votes
`Serial.read()` reads one character from the Serial stream, or returns -1 if there are no characters to read.

When you send a `1` from the Serial Monitor, the Arduino board first receives an Ascii 1, and then receives a line-end character (eg, an LF from Linux) or characters (eg, a CR and LF from MSWindows).

Since none of 1, CR, or LF are equal to an Ascii 0, the numkey value computed at the fourth line of case 1 is not 0, so the exit condition isn't met. Thus the fade loop continues running, until it sees a `0` character.

Instead of continuing to read characters within while loops within the switch/case statement, test if more serial input is available. Note, avoid exiting early from case 1, after you read a digit at the beginning of `loop()`, read and discard the line-ending characters that follow.

# Answer
> 1 votes
NeoPixels' timing requirements are pretty tight - not necessarily high frequency but high accuracy, for at least certain parts of the serial pulse train. To achieve that, I believe the (Adafruit) NeoPixel library takes over one of the timers during the transmission and turns off interrupts for at least some of the time. That will have a negative impact on any background processes. Read through the NeoPixel library code; it should be clear.

However, while researching my answer (so as to not embarrass myself too badly!), I found this article at josh.com that describes driving NeoPixels with a much lower impact and goes on to demonstrate his technique with a video of a 1000 NeoPixel string(!) driven at 30 FPS by an old, apparently Atmega 168-based, Duemilanove.

---
Tags: serial
---


# Question
Title: Multiple (3) RF transmitters to a single receiver?
How can I have three remote transmitters send distinct signals to a single receiver?

My project requires 3 remote controls, each with 2 inputs.

I need to distinctly identify these 6 signals from the 3 remotes onto one arduino board.

Is this possible to do with one receiver?

Would I be able to pair one remote to one receiver (so 3 receivers), or will there be noise / interference?

What is the simplest and/or cheapest solution to this?

FYI I am going to be using a 315 Mhz remote / receiver (remote control has 4 inputs). I am waiting for them to come in the mail but I want to start thinking about how I will build this.

# Answer
These transmitter all transmit on the same frequency so if you have multiple receivers they will all get the same signal.

The only way I can see you can do this is make some type of protocol where you send data with a station ID and only the receiver with the station ID matching the message will act on it.

EDIT:

Sorry have to get used to the double-enter making a send.

@JamesWierzba your 'remotes' will need to be more than just a push button to send a HIGH or LOW signal via the transmitter.

Your 'remotes' will need to each have a unique ID, we usually use DIP switches for this. A small microcontroller will need to read these DIP switch and compose the message to be send to the receiver.

A simple message like "ID\_BUTTON\_PRESS" where ID is the decimal or hex equivalent of the DIP switches.

On reception of the message the microcontroller receiving the message will know which remote it comes from by looking at the ID part of the message.
> 3 votes

---
Tags: arduino-uno, rf
---


title: Receiving a packet via XBee radio

text:
# Question
Title: Receiving a packet via XBee radio
I am sending a packet of sensor information over an Arduino XBee setup. The first byte of the packet is the packet header for synchronization. The second byte is the number of bytes in the packet (excluding header and packet size byte). The first byte of the packet payload is an identifying number for the sensor. The second payload byte is the data from the sensor. The third payload byte is an XOR for simple error checking. The first payload byte for the sensor ID will never need to be escaped, but the other two payload bytes may need to be escaped. The following is code I wrote for sending a single packet:

```
Serial.write(PACKET_HEADER); // Packet header for synchronization
Serial.write(calculatePacketSize(data, XOR)); // Size of packet
Serial.write(unitInfo);
// Check if the data byte needs to be escaped
if(data == ESCAPE || data == PACKET_HEADER) {
    Serial.write(ESCAPE);
}
Serial.write(data);
// Check if the XOR byte needs to be escaped
if(XOR == ESCAPE || XOR == PACKET_HEADER) {
    Serial.write(ESCAPE);
}
Serial.write(XOR);

```

What I am unsure about is how to process a packet on the receiving end. One issue I see is that because there are a variable number of payload bytes, I cannot check via `Serial.available()` whether or not there are enough bytes to process the payload during this run through of `loop()`. How do I go about processing a packet, and making sure the packet was received error free? I need to just discard incomplete packets or anything without a header.

# Answer
A state machine is what you want. That and to increase your preamble to two bytes, not one. The reason being is that due to the escaping of the preamble character in the data it is impossible to have that character twice in a row. By then having it twice in a row as the preamble it is unambiguous that it is the preamble.

You should also (if needed) escape the packet size:

```
Serial.write(PACKET_HEADER); // Packet header for synchronization
Serial.write(PACKET_HEADER); // Packet header for synchronization
uint8_t ps = calculatePacketSize(data, XOR); // Size of packet
if(ps == ESCAPE || ps == PACKET_HEADER) {
    Serial.write(ESCAPE);
}
Serial.write(ps);
Serial.write(unitInfo);
... etc ...

```

You might like to abstract the escaping into a function:

```
void sendEscape(uint8_t c) {
    if (c == ESCAPE || c == PACKET_HEADER) Serial.write(ESCAPE);
    Serial.write(c);
}

```

Then you can just call:

```
sendEscape(calculatePacketSize(data, XOR));

```

etc.

Now for receiving. Implement a Finite State Machine. In that machine you have a number of states, such as *look for first preamble*, *look for second preample*, *look for size*, *look for id*, and *look for data*. As bytes arrive they trigger the next state.

So you start by looking for the first preamble byte. When that arrives it triggers looking for the second preamble byte - any other byte besides the second preamble byte causes the FSM to reset. If it arrives, then it triggers the reading of the packet length. And so on.

In pseudocode it may be something like:

```
State is idle.
If character available:
    Read character into variable C

    Select on state:
        State IDLE:
            If C is PACKET_HEADER:
                Set state to PREAMBLE
        State PREAMBLE:
            If C is PACKET_HEADER:
                Set state to GETSIZE
            Else
                Set state to IDLE
        State GETSIZE:
            If C is ESCAPE and you haven't just seen ESCAPE
                Remeber you had an escape
            Else
                Store C in variable SIZE
                Clear array DATA and prepare for reception
                Reset Seen ESCAPE flag if needed
                Set state to GETID
        State GETID:
            If C is ESCAPE and you haven't just seen ESCAPE
                Remeber you had an escape
            Else
                Store C in variable ID
                Reset Seen ESCAPE flag if needed
                Set state to GETDATA
        State GETDATA:
            If C is ESCAPE and you haven't just seen ESCAPE
                Remeber you had an escape
            Else
                Append C to array DATA
                Decrement variable SIZE
                Reset Seen ESCAPE flag if needed
                If SIZE is 0
                    If checksum matches
                        Process packet
                    Set state to IDLE

```

The main thing to watch is the remembering (and subsequently forgetting) that you have just seen an ESCAPE. That way you can know if you have two ESCAPE characters in a row and you only discard the first one - the second gets handled as a real character.

The beauty of an FSM is that at any point in the sequence, if you decide that the packet is invalid (maybe the size is too big, or the sensor ID is invalid) you can just reset the FSM to the IDLE state and reset any flags/counters and you instantly start looking for a new packet.
> 1 votes

---
Tags: arduino-mega, xbee
---


title: Scan multiple ESP8266

text:
# Question
Title: Scan multiple ESP8266
I am working on wifi based LED project which involves various ESP to be connected to router. Basically grouping of ESP has to be done. The android app sends HTTP command to IP address which is given by router to the ESPs, the IP are not static and expires after some time. Now my question is how can mobile app can get the IP of all the ESP connected to router?

Does using HTTP protocol complicates the process? Shall I switch to multicast UDP? or use UnPn Protocol for scanning (Sounds complicated though).

Please help!

# Answer
You can go with UDP Multicast.
> 1 votes

# Answer
The best protocol for these kind of applications is MQTT.

Read more here
> 1 votes

# Answer
Yes, Multicast is the only option.
> 1 votes

---
Tags: arduino-ide, esp8266, http
---


title: Run 'Serial.begin(9600)' before loop()

text:
# Question
Title: Run 'Serial.begin(9600)' before loop()
My sketch looks somehow like this:

```
ClassA classA;

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

    classA = ClassA();
    Serial.println("Bar")

    ...
}

void loop() {
    classA.functionFoo();
}

```

The constructor of `ClassA` however calls some internal methods that perform a `Serial.println()`.

My problem is, that the first (implicit) call of the constructor of `ClassA` comes in the first line of the sketch with

```
ClassA classA;

```

This is before the Serial interface has been initialized (with `Serial.begin(9600)`). Therefore the Serial.monitor cannot interpret the first messages coming from the serial interface.

How can I either suppress any Serial.writes before the setup function or otherwise make sure that the Serial interface is initialized before the setup function?

# Answer
> 2 votes
You can make your current object a pointer so it isn't instantiated:

```
ClassA *classA;

```

Then create an object with new:

```
classA = new ClassA();

```

The constructor is then only called when the object is made.

Note that you will have to change your accessors to `->`:

```
classA->myFunction();

```

# Answer
> 2 votes
In order to be sure that your `classA` object doesn't use the `Serial.println()` function before the baudrate is defined, it is necessary to add functions in your `class ClassA` and to inform from `setup()` your `classA` object.

The simplest way is to add:

1. a boolean `bool bSerialReady`to keep the status of the Serial object,
2. in all `ClassA` constructors, initialize that `bSerialReady = false;`,
3. add a function `void SetSerialReady()` to switch the status `bSerialReady = true;`. The function should be called in the `setup()`function just after `Serial.begin(9600);`,
4. and in all functions of `ClassA`, add a if-condition `if (bSerialReady)` before calling the `Serial.println()`.

Your `class ClassA` will become:

```
class ClassA
{
private:
    bool bSerialReady;
public:
    ClassA() {
        // ...
        // Initialize bSerialReady
        bSerialReady = false;
    };
    void SetSerialReady() {
        bSerialReady = true;
    };
};

```

Your `setup()` function becomes:

```
void setup() {
    Serial.begin(9600);
    classA.SetSerialReady();
    ...
}

```

And in functions of `ClassA`, it looks like:

```
if (bSerialReady) {
    Serial.println("Bar");
}

```

---
Tags: serial, c++, class
---


# Question
Title: Serial question : Going from Mega to Uno
I have a code sample that uses serial3 (RX3 on a Mega) which I want to try and get working on a Uno. It reads on RX3 and streams to USB. What I had read, you use Serial for RX0, however Serial seems to be used for USB

```
 /*
Arduino Neato XV-11 Laser Distance Scanner
Motor control board v0.2 by Cheng-Lung Lee

XV-11 LDS adapter reads LDS data from RX3 then relay to TX. Also extract the speed
data from the data stream to do speed control on LDS motor. Everythin can power
from USB no extra power required.

Change log:
V0.2 Add simple speed control code update PWM 3 times per rev.
V0.1 Opend loop control version.

This code is tested on Arduino Mega 1280
I/O:
Motor drive by low side driver IPS041L connect to PWM Pin4, Motor power from 5V
Neato XV-11 LDS Vcc(red) : 5V
Neato XV-11 LDS TX(Orange) : RX3

 */

const int DesiredRPM=300;  // Setting Desired RPM Here.
const int MotorPWMPin=4;
int inByte = 0;         // incoming serial byte
unsigned char Data_status=0;
unsigned char Data_4deg_index=0;
unsigned char Data_loop_index=0;
unsigned char SpeedRPHhighbyte=0; //
unsigned char SpeedRPHLowbyte=0;

int SpeedRPH=0;
const unsigned char PWM4dutyMax=255;
const unsigned char PWM4dutyMin=100;
unsigned char PWM4duty=PWM4dutyMin;  // have to set a default value make motor start spining

 void setup() {
    pinMode(MotorPWMPin, OUTPUT);
    Serial.begin(115200);  // USB serial
    Serial3.begin(115200);  // XV-11 LDS data

  // prints title with ending line break
  Serial.println("Arduino Neato XV-11 Motor control board v0.1 by Cheng-Lung Lee");

  // Pick your magic number and drive your motor , 178 is 178/255*5V=3.49V
    analogWrite(MotorPWMPin, PWM4duty );
}

void loop() {
    // if we get a valid byte from LDS, read it and send it to USB-serial
  if (Serial3.available() > 0) {
    // get incoming byte:
    inByte = Serial3.read();
    //Serial.print(inByte, BYTE);
    //Serial.write(inByte);
    Serial.print((char)inByte);
    decodeData(inByte);
  }

}

void decodeData(unsigned char inByte){
  switch (Data_status){
  case 0: // no header
  if (inByte==0xFA)
  {
    Data_status=1;
    Data_loop_index=1;
  }
    break;
  case 1: // Find 2nd FA
    if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_status=2;
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      Data_loop_index++;
    }
    break;
  case 2: // Read data out

     if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      readData(inByte);
      Data_loop_index++;
    }
    break;
  }

}
void readData(unsigned char inByte){
  switch (Data_loop_index){
    case 1: // 4 degree index
    Data_4deg_index=inByte-0xA0;
//      Serial.print(Data_4deg_index, HEX);
//      Serial.print(": ");
    break;
    case 2: // Speed in RPH low byte
    SpeedRPHLowbyte=inByte;
    break;
    case 3: // Speed in RPH high byte
    SpeedRPHhighbyte=inByte;
    SpeedRPH=(SpeedRPHhighbyte<<8)|SpeedRPHLowbyte;

    SpeedControl ( DesiredRPM ) ; //
//      Serial.print(SpeedRPHhighbyte, HEX);
//      Serial.println(SpeedRPHLowbyte, HEX);
    break;
    default: // others do checksum
        break;
  }
}

// Very simple speed control
void SpeedControl ( int RPMinput)
{
 if (Data_4deg_index%30==0) {  // I only do 3 updat I feel it is good enough for now
  if (SpeedRPH<RPMinput*60)
     if (PWM4duty<PWM4dutyMax) PWM4duty++; // limit the max PWM make sure it don't overflow and make LDS stop working
  if (SpeedRPH>RPMinput*60)
     if(PWM4duty>PWM4dutyMin) PWM4duty--;  //Have to limit the lowest pwm keep motor running
  }
  analogWrite(MotorPWMPin, PWM4duty ); // update value
}

```

# Answer
Arduino UNO only has one **hardware** UART, hence only one `Serial` available, which is linked to USB, but you could still use it for something else by connecting directly to D0 & D1.

However, if you need 2 separate, independent, UART then go for `SoftwareSerial` for the second one.

Now, if you need to connect 2 devices, one to exclusively get data from, the other exclusively to send data to, then you can use just one UART, i.e. `Serial` for both devices, as long as both links work at the **same speed** and **settings** (parity...)

Also you must ensure that USB won't receive anything otherwise you would get it and confuse it with input from the first device.

The non USB device providing input to the Uno should be connected to D0 (RX).
> 3 votes

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


# Question
Title: What is the maximum current for each I/O pin?
### Question

As far as I know each I/O pin has to keep around 20mA, what are the consequences of going higher or lower? But if I am using all I/O pins is there a maximum current value I should keep in mind? For example, the sum of all currents in all pins should not be greater than 100mA.

# Answer
This comes up as first result when Googling your question:

And can be confirmed by page 313 and 314 of the datasheet:

To know where each pin is connected to (on the Arduino Uno) you can look the official (messy) schematic.

I provide an excerpt below that shows the **Vin** and **5V** pins at the headers, and the power barrel connection.

If you want to control a 12V motor or a 12V LED strip or other DC loads you can use the following (which is also easy to find using Google):

\*Note that your 12V Gnd and Arduino Gnd have to be connected.

simulate this circuit – Schematic created using CircuitLab
> 2 votes

# Answer
The power limits per pin and per chip are listed for each model (based on the Atmel chip). You can look up the Atmel chip number and see the power ratings. For example, the chip may have a maximum of 40mA per pin, but a total of 200mA for everything on the chip. These numbers are just examples. The actual numbers depend on which Arduino and which chip you are talkng about.

Remember that microcontroller chips are NOT designed to SWITCH any significant amount of power. That is NOT the job of the microcontroller. Its job is to CONTROL external devices (transistors, thyristors,SSR, relays, etc.) which do the actual "heavy lifting" of switching larger amounts of power.

Your last question really does not make any sense. Can you clarify it?

VCC is the name of the main power bus and input to the microcontroller chip. It may or may not be 5V depending on which Arduino you are talking about. The older ones were 5V, but newer chips (including those used in Arduino) are tending more to 3.3V.
> 1 votes

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


title: Can't run two separated DC Motors

text:
# Question
Title: Can't run two separated DC Motors
I'm trying to build Bluetooth RC car, but I can't run only one DC motor.. only both of them. Everything works fine, the bluetooth, the app but when i try to go forward/backward/left/right nothing happens, only when i run both of them. I'm running the Arduino Nano with usb cable. The bluetooth connection is stable, The DC motors are working. I don't know what I'm doing wrong. Thanks!

```
const int AIA = 2;
const int AIB = 3;
const int BIA = 4;
const int BIB = 5;
byte vSpeed = 255;
int state;

void setup() {
pinMode(AIA, OUTPUT);
pinMode(AIB, OUTPUT);
pinMode(BIA, OUTPUT);
pinMode(BIB, OUTPUT);

// Initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
}

void loop() {
  //Save income data to variable 'state'
    if(Serial.available() > 0){
      state = Serial.read();
    }

  /***********************Forward****************************/
  //If state is equal with letter 'F', car will go forward!
    if (state == 'F') {
      analogWrite(AIA, vSpeed);
      analogWrite(AIB, 0);
      analogWrite(BIA, 0);
      analogWrite(BIB, 0);
    }
  /**********************Forward Left************************/
  //If state is equal with letter 'G', car will go forward left
    else if (state == 'G') {
      analogWrite(AIA, vSpeed);
      analogWrite(AIB, 0);
      analogWrite(BIA, vSpeed);
      analogWrite(BIB, 0);
    }
  /**********************Forward Right************************/
  //If state is equal with letter 'I', car will go forward right
    else if (state == 'I') {
      analogWrite(AIA, vSpeed);
      analogWrite(AIB, 0);
      analogWrite(BIA, 0);
      analogWrite(BIB, vSpeed);
    }
  /***********************Backward****************************/
  //If state is equal with letter 'B', car will go backward
    else if (state == 'B') {
      analogWrite(AIA, 0);
      analogWrite(AIB, vSpeed);
    }
  /**********************Backward Left************************/
  //If state is equal with letter 'H', car will go backward left
    else if (state == 'H') {
      analogWrite(AIA, 0);
      analogWrite(AIB, vSpeed);
      analogWrite(BIA, vSpeed);
      analogWrite(BIB, 0);
    }
  /**********************Backward Right************************/
  //If state is equal with letter 'J', car will go backward right
    else if (state == 'J') {
      analogWrite(AIA, 0);
      analogWrite(AIB, vSpeed);
      analogWrite(BIA, 0);
      analogWrite(BIB, vSpeed);
    }
  /***************************Left*****************************/
  //If state is equal with letter 'L', wheels will turn left
    else if (state == 'L') {
      analogWrite(BIA, vSpeed);
      analogWrite(BIB, 0);
    }
  /***************************Right*****************************/
  //If state is equal with letter 'R', wheels will turn right
    else if (state == 'R') {
      analogWrite(BIA, 0);
      analogWrite(BIB, vSpeed);
    }
  /************************Stop*****************************/
  //If state is equal with letter 'S', stop the car
    else if (state == 'S'){
      analogWrite(AIA, 0);
      analogWrite(AIB, 0);
      analogWrite(BIA, 0);
      analogWrite(BIB, 0);
    }
}

```

# Answer
> 1 votes
Connect the Nano ground to the driver board ground. Since they do not share a common ground, they can have odd behavior as their ground planes float.

You need only connect the grounds, the USB can still provide +5 to the Nano, and the +9 can still provide power to the driver. The only energy that will flow through the black wire connecting the grounds is the energy that flows between pins 2,3,4,5 and the driver's AIA, AIB, BIA, BIB, for the logic signals, which I'd bet is in the sub-uA range.

---
Tags: arduino-uno, bluetooth
---


# Question
Title: Emulate non-standard keyboard from Arduino
I want to emulate keyboard presses in an old C64 microcomputer using an Arduino.

The keyboard connection is a non-standard 20-pin port (i.e. the Arduino keyboard libraries won't be useful) which, as I understand, works as a simple matrix of switches.

Since my Arduino Mega has more than 20 general purpose I/O ports, I understand I can approach the problem by simply mapping these 20 keyboard pins to individual "digital" Arduino ports, and then programming around it, right?

Or is this too naive and I'm missing something here?

I'm new to Arduino, so any comments highly appreciated. Thank you!

# Answer
> 1 votes
Emulating a keyboard matrix is actually harder than you would at first think. It's not just a case of setting certain combinations of pins as HIGH or LOW - you need to actively monitor one side of the matrix as it sweeps across each row and control the other side depending on the buttons that are pressed or not pressed on the current row. And all that has to be done fast enough that the C64 doesn't see buttons constantly bouncing up and down.

Further, you really need all your outputs to be *open drain* so as not to interfere with each other or the rest of the system (depending on just how the C64 system works), and Arduinos can't do *open drain* natively - instead you have to emulate it by switching between INPUT and OUTPUT + LOW which adds extra latency.

If you only want access to a few of the buttons a better arrangement would be to add a small N-channel (logic level) MOSFET or an NPN BJT between the two sides of the matrix for whichever button(s) you want to control (check the schematics for which pins and which way round to connect it). Activating the transistor would then be the same as pushing the button down. It can even be in parallel to the existing button so as to not break the keyboard.

---
Tags: keyboard
---


# Question
Title: Arduino Nano + ESP8266 and saving to EEPROM
I am going to create a project with a friend, but I have some technical questions.

The Arduino Nano has an EEPROM capable of storing the known WiFi connections. Basically what I want is say "Arduino, connect to this WiFi and remember it". When I then disconnect the Arduino completely, it should still save that information. Can the EEPROM store that without power?

I need an easy, but rather small, WiFi module to work with the Arduino Nano. I've looked at the ESP8266. I don't mind soldering the ESP8266 to the Arduino Nano *once*, but doing it more times (perhaps because I need more GPIO or something) is not a variable solution. If I get the ESP8266 ESP-12, I would only have to solder it to the Nano once. However:

1. Is the ESP8266 ESP-12 compatible with the Arduino Nano?
2. I like the ESP-05 because it's small and simple. Would that work?

Are there perhaps better ways of doing this whole thing? Should I go for something else than the Arduino Nano? I need to hook up:

* WiFi
* Microphone (smallest and easiest way)
* LEDs

# Answer
> 2 votes
The ESP8266 is a SoC (System On Chip) that includes a microcontroller. For most applications, you’ll need only the ESP without the Nano. ESP-12E boards are very handy for tinkering. You can program the ESP in different languages, even in Arduino C (https://github.com/esp8266/Arduino/).

Note that the ESP is only 3.3V tolerant, so it is not that easy to use it with a Nano that works at 5V. It is of course possible to use logic level shifters, but frankly, I would rather use the ESP alone.

You don’t have to worry about storing WiFi connection settings, they are usually hard-coded in the main program.

Connecting LED is described everywhere on the internet, so I don’t think that is a major problem. If you need a lot of LEDs, you can buy LED strips.

For the microphone I suggest that you search for I²C modules.

# Answer
> 1 votes
It sounds like you are quite new to all this stuff. In summary I think you are taking the wrong approach and need to re-think things.

EEPROM is capable of storing data without any power. Both the devices have EEPOROM, also you could look at external devices, which would be easier to replace if you wear them out (limited number of write cycles - see their data sheets for details but they are usually in the tens of thousands).

The difference between the ESP8266 range are the number of GPIO lines they offer up, to the 12E has more than the 5, etc.

You shouldn't be soldering this stuff more than once. You should design it right in the first place (easier said than done!) What you could do is mount the Nano on a board that took all the lines off to a single 30 odd pin connector the design a series of daughter boards for the ESP8266 which were compatible with the base board, so you could switch between the different ESPs.

Also, don't forget you will need logic level conversion between the 5V Arduino and the 3.3V ESP8266 unless you are planning on smoking electronics.

What do you think you are doing with the MIC connector? Are you planning on processing sound on the Arduino? You might want to research that before you design it.

Are you aware that the ESP8266 can be programmed via the Arduino and has a 80MHz processor and 256KB of RAM (compared to the Nano's 32Mhz & 32KB) so using the ESP as a slave to the Arduino is not necessarily the best idea.

If you are interested this is the approach I would take: 1. Solder some male pins to the Nano so you can put it into a bread board. 2. If you have a 12E, Buy a ESP8266 mounting board (£1 for 10 from you favourite Chinese web market) and solder pins to that. 3. If you have a 5 then solder pins to that. 4. Make all you other parts breadboard-able and try it all out. 5. Once it works download Fritzing and draw it up. 6. Make a Vero board version and play with it for real.

---
Tags: esp8266
---


# Question
Title: Arduino bug when "myFile = SD.open" is inside loop()
My Arduino resets / bugs each time I put `myFile = SD.open` in `loop()`.

In `setup()` it works fine.

I have a 20\*4 LCD and an RTC connected to I2C, an SD card reader connected to SPI, and a fingerprint sensor.

Here is my code:

```
#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SPI.h>
#include <SD.h>
#include <DS3231.h>;

LiquidCrystal_I2C lcd(0x3f,20,4);
DS3231  rtc(SDA, SCL);
SoftwareSerial mySerial(2, 3);

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);
Sd2Card card;
SdVolume volume;
SdFile root;

int etat = 0;
int getFingerprintIDez();
const int chipSelect = 10;
SDFile myFile;

void setup() {
  lcd.init();
  lcd.backlight();
  rtc.begin();
  finger.begin(57600);
  SD.begin();

  // Reglage Heure
  //rtc.setDOW(TUESDAY); // Set Day-of-Week to SUNDAY
  //rtc.setTime(10, 57, 0); // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(24, 11, 2016);   // Set the date to January 1st, 2014
  if (finger.verifyPassword()) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Capteur Initialise");
  } else {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Capteur Deconnecte");
  }
  delay(2000);
  if (SD.exists("data.csv")) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("data.csv OK.");
    delay (1000);
  } else {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Creating data.csv...");
    myFile = SD.open("data.csv", FILE_WRITE);
    myFile.close();
    delay (1000);
  }
}

void loop() {
  if (etat == 0) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Put Finger");
    getFingerprintIDez();
  }
  if  (etat == 1) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("ID #");
    lcd.setCursor(4,0);
    lcd.print(finger.fingerID);
//  myFile = SD.open("data.csv", FILE_WRITE);
//  myFile.print(rtc.getDateStr(1));
//  myFile.print("\t");
//  myFile.print(rtc.getTimeStr(1));
//  myFile.print("\t");
//  myFile.println(finger.fingerID);
//  myFile.close();
    lcd.setCursor(0,2);
    lcd.print("Loged");
    etat = 0;
  }
  delay(1000);
}

int getFingerprintIDez() {
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.image2Tz();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)  return -1;
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Found ID #");
  lcd.setCursor(14,0);
  lcd.print(finger.fingerID);
  etat = 1;
  return finger.fingerID;
  delay(1000);
}

```

Each time I uncomment lines using SD, the Arduino resets at the end of the loop.

What is the problem?

# Answer
> 1 votes
The solution to your problem is to extend your 2 states machine in a multiple states machine.

Declare the `enum eState` before `setup()`:

```
typedef enum e_State {
    STATE_START = 0,    // starting the loop (add some initialisation)
    STATE_READ_FINGER,  // Step1: read the finger print
    STATE_DISP_FINGER,  // Step2: display the finger print
    STATE_OPEN_LOGGER,  // Step3: open the log file
    STATE_WRITE_LINE,   // Step4: append a timestamp finger print
    STATE_CLOSE_LOGGER  // Step5: close the log file
} eState;

```

And update the `loop()` function with the state-machine:

```
void loop()
{
    static eState LoopState = STATE_START; // to store the current state

    eState NextState;  // for the next loop

    switch (LoopState) {
    case STATE_START:
        // add additional settings
        NextState = STATE_READ_FINGER;
        break;
    case STATE_READ_FINGER:
        etat = 0; // keep use your 'etat'
        // or return a boolean from your 'getFingerprintIDez()'
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Put Finger");
        getFingerprintIDez();
        if (etat == 1) {
            NextState = STATE_DISP_FINGER;
        }
        break;
    case STATE_DISP_FINGER:
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("ID #");
        lcd.setCursor(4,0);
        lcd.print(finger.fingerID);
        NextState = STATE_OPEN_LOGGER;
        break;
    case STATE_OPEN_LOGGER:
        myFile = SD.open("data.csv", FILE_WRITE);
        if (myFile) {
            // record only if file is opened
            NextState = STATE_WRITE_LINE;
        }
        else {
            lcd.setCursor(0,0);
            lcd.print("Can't open file");
        }
        break;
    case STATE_WRITE_LINE:
        myFile.print(rtc.getDateStr(1));
        myFile.print("\t");
        myFile.print(rtc.getTimeStr(1));
        myFile.print("\t");
        myFile.println(finger.fingerID);
        myFile.flush();
        NextState = STATE_CLOSE_LOGGER;
        break;
    case STATE_CLOSE_LOGGER:
        myFile.close();
        lcd.setCursor(0,2);
        lcd.print("Loged");
        NextState = STATE_READ_FINGER;
        etat = 0;
        break;
    default:
        NextState = STATE_START;
    }
    // next loop()
    LoopState = NextState;
    delay(200);
}

```

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


title: Serial 3 vs Software Serial

text:
# Question
Title: Serial 3 vs Software Serial
So I have a program that works great on the Mega, it uses serial 3 to read and streams out to the USB (I posted a previous question which someone answered) I tried to use Serial (D0) to read and then write to serial, which did not work. So now I am looking in to Software Serials

Is there a difference between a real serial and software serial as it does not seem to be working, It all runs a bit slower

```
#include <SoftwareSerial.h>

const int DesiredRPM=300;  // Setting Desired RPM Here.
const int MotorPWMPin=4;
int inByte = 0;         // incoming serial byte
unsigned char Data_status=0;
unsigned char Data_4deg_index=0;
unsigned char Data_loop_index=0;
unsigned char SpeedRPHhighbyte=0; //
unsigned char SpeedRPHLowbyte=0;

int SpeedRPH=0;
const unsigned char PWM4dutyMax=255;
const unsigned char PWM4dutyMin=100;
unsigned char PWM4duty=PWM4dutyMin;  // have to set a default value make motor start spining

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
    pinMode(MotorPWMPin, OUTPUT);
    Serial.begin(115200);  // USB serial
    Serial3.begin(115200);  // XV-11 LDS data

    // prints title with ending line break
    Serial.println("Arduino Neato XV-11 Motor control board v0.1 by Cheng-Lung Lee");

    // Pick your magic number and drive your motor , 178 is 178/255*5V=3.49V
    analogWrite(MotorPWMPin, PWM4duty );

    mySerial.begin(115200);
}

void loop() {
    // if we get a valid byte from LDS, read it and send it to USB-serial
  if (Serial3.available() > 0) {
    // get incoming byte:
    inByte = Serial3.read();
    //Serial.print(inByte, BYTE);
    //Serial.write(inByte);
    Serial.print((char)inByte);
    decodeData(inByte);
  }

  if (mySerial.available() > 0) {
    // get incoming byte:
    inByte = mySerial.read();
    //Serial.print(inByte, BYTE);
    //Serial.write(inByte);
    Serial.print((char)inByte);
    decodeData(inByte);
  }

}

void decodeData(unsigned char inByte){
  switch (Data_status){
  case 0: // no header
  if (inByte==0xFA)
  {
    Data_status=1;
    Data_loop_index=1;
  }
    break;
  case 1: // Find 2nd FA
    if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_status=2;
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      Data_loop_index++;
    }
    break;
  case 2: // Read data out

     if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      readData(inByte);
      Data_loop_index++;
    }
    break;
  }

}
void readData(unsigned char inByte){
  switch (Data_loop_index){
    case 1: // 4 degree index
    Data_4deg_index=inByte-0xA0;
//      Serial.print(Data_4deg_index, HEX);
//      Serial.print(": ");
    break;
    case 2: // Speed in RPH low byte
    SpeedRPHLowbyte=inByte;
    break;
    case 3: // Speed in RPH high byte
    SpeedRPHhighbyte=inByte;
    SpeedRPH=(SpeedRPHhighbyte<<8)|SpeedRPHLowbyte;

    SpeedControl ( DesiredRPM ) ; //
//      Serial.print(SpeedRPHhighbyte, HEX);
//      Serial.println(SpeedRPHLowbyte, HEX);
    break;
    default: // others do checksum
        break;
  }
}

// Very simple speed control
void SpeedControl ( int RPMinput)
{
 if (Data_4deg_index%30==0) {  // I only do 3 updat I feel it is good enough for now
  if (SpeedRPH<RPMinput*60)
     if (PWM4duty<PWM4dutyMax) PWM4duty++; // limit the max PWM make sure it don't overflow and make LDS stop working
  if (SpeedRPH>RPMinput*60)
     if(PWM4duty>PWM4dutyMin) PWM4duty--;  //Have to limit the lowest pwm keep motor running
  }
  analogWrite(MotorPWMPin, PWM4duty ); // update value
}

```

# Answer
> 2 votes
There are huge differences. The most important ones are:

* SoftwareSerial is half duplex (it can send or it can receive, it cannot do both at once)
* SoftwareSerial is blocking - while it is sending or receiving nothing else can happen

SoftwareSerial is very much a poor-man's serial port. It should only really be used for very low volume data (things like NEMA messages once a second or so) and only if you have absolutely no choice (and, let's face it, you always have a choice).

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


# Question
Title: How do I change PGA gain in this Arduino program?
Below is the link to three files I am using with a 32 bit ADC from TI, ADS1262, plus a link to it's datasheet. It works fine but I'm not getting any better voltage resolution than with a 16 bit ADC. I am using it for small voltage, from 0 to 0.070 volts. For example, for a known stable voltage of 0.01000 volts from a Fluke thermocouple calibrator I get 0.010000 to 0.010006. I get this same 0.000006 volt jitter if I short the ADS1262 input pins together. I suspect it may be a programmable gain amplifier issue. I can put 2.5 volts into it and not damage it. There is a line in the .ino file, #define PGA 1. On a guess, I changed this to #define PGA 32 but it had no effect on the results, it's like my attempted program change didn't take. I read in the ads1262 datasheet that the PGA Gain is in the MODE2 Register, address 05h. A gain of one is set with 000 and a gain of 32 is set with 101. But I do not know how to proceed. Perhaps somebody can help me out.

https://github.com/Protocentral/ProtoCentral\_ads1262/tree/master/Libraries http://www.ti.com/lit/ds/symlink/ads1262.pdf

# Answer
> 0 votes
The symbol `PGA` appears in `exapmle.ino` (sic) twice, once each in lines 28 and 30:

```
 #define PGA 1                     // Programmable Gain = 1
 ...
 #define VFSR VREF/PGA

```

It is not used elsewhere in the example or the library code. The only effect of changing its value from 1 to 32 is to change the value of `VFSR`, and as`VFSR` appears only in line 30, that effect is nil.

Looking at the `ads1262.cpp` file from github, it appears that `ads1262::ads1262_Init()` initializes register `MODE2` to 0x6, via:

```
ads1262_Reg_Write(MODE2, 0x06);

```

which per the ADS1262 spec sheet, page 93, table 44, enables the PGA and sets its gain to 1 and sets the sample rate to 60 SPS.

Apparently, if you wish to use some other gain setting, you should define `PGA` appropriately and put a corresponding setting into `MODE2`. For example, if you want to set up a gain of 16 and sample rate of 400 SPS, in `setup()` you could say

```
PC_ADS1262.ads1262_Reg_Write(MODE2, 4<<4 | 8); // 4=gain 16, 8=400 SPS

```

More generally, you could set up some constants for gain codes and SPS rates, and reference those constants when writing to `MODE2`. For example, after

```
enum { GainCode1, GainCode2, GainCode4, GainCode8, GainCode16, GainCode32 };
enum { SPSCode2p5, SPSCode5, SPSCode10, SPSCode16p6, SPSCode20, SPSCode50,
       SPSCode60, SPSCode100, SPSCode400, SPSCode1200, SPSCode2400,
       SPSCode4800, SPSCode7200, SPSCode14400, SPSCode19200, SPSCode38400};

```

you would say

```
PC_ADS1262.ads1262_Reg_Write(MODE2, GainCode32<<4 | SPSCode2400);

```

to set the gain at 32 and the sample rate at 2400 SPS.

(Note, `enum` is a C language element used to define integer constants. In an `enum`, each symbol mentioned without an explicit value has a value one more than the previous symbol, or zero if there's no preceding symbol. So `GainCode1` is 0, `GainCode2` is 1, `GainCode4` is 2, etc.)

Note, to get better ultimate resolution, you may need to combine multiple readings, or may need to set the ADS1262's filtering parameters.

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


# Question
Title: Can you tell me if this circuit will work?
Here's an image of my circuit diagram. There are 8 9g servos connected to the arduino gpio pins. The servos have an external power supply of 3 volts (may vary depending on the voltage requirement of the 9g) and the arduino is powered through an adaptor. Is this a convenient way of doing it? Have I gone wrong somewhere? I am new to circuit designing so I am confused.

Thank you! :)

# Answer
These servo are driven off of a PWM signal. This means that you need to connect the control line to a pin that is capable of PWM.

For the Uno it is D3, D5, D6, D9, D10 & D11.

Unfortunately there are only 6 PWM capable pins and you need 8.

You could consider bit banging the PWM for the 7th & 8th motor.

Alternatively, if two of the motors are to be driven exactly the same, they could share the PWM control line between them.

If you need to control each motor separately (without bit banging) you may have to upgrade to a Arduino Mega 2560. The Mega has 15 PWM channels.

An Arduino example of controlling the servo motor can be found in the Libraries section of the Arduino website. https://www.arduino.cc/en/Tutorial/Knob
> 1 votes

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


# Question
Title: How to break out of a loop if it is contained in a function
I am trying to figure out how to break out of a loop if it is being called from a function. I have a similar post, here, that I've decided to do something with the Arduino onboard LED, to isolate it from the NeoPixels Library and it is giving me the same issue. The answers I have received there have been helpful but something is still puzzling me.

Using serial from the Arduino to my PC, the below "Example 1" code, can break out of a local loop successfully (and immediately) when the Arduino received keyboard input with key "2".

```
//Example 1
int ledPIN = 13; // sets up onboard LED on Arduino located near PIN13
char rx_byte = 0; // variable to hold serial input from console;
int count = 0; // placeholder for incrementing during debugging of loops

void setup() {

  Serial.begin(115200);

  pinMode (ledPIN, OUTPUT);

}

void loop() {

  if (Serial.available() > 0) {    // is a character available?
    rx_byte = Serial.read();       // get the character

    // check if a number was received
    if ((rx_byte >= '0') && (rx_byte <= '9')) {
      switch(rx_byte) {
        case '1':
          Serial.println("You've entered: 1");
          for (int i; i <=5000; i++) {
            rx_byte = Serial.read(); // must read character again
            if (rx_byte == '2') {
              Serial.println("Quitting...");
              digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
              break;
            }
            else {
              Serial.println(i);
              digitalWrite(ledPIN, HIGH); // turn LED pin 13 on
            }
          }
          digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
          break;

      }
    } // end: if (Serial.available() > 0)
  }
}

```

From what I've been told, you shouldn't necessarily perform a "serial.read()" inside of a loop. However, if I do not include that in the for loop, it does not allow for any further input.

Since "Example 1" works, I am now trying to accomplish the same principle, but, this time, when calling a function which contains its own independent loop of course. I've spent countless hours trying to resolve this.

I was under the impression that I could use a while loop within "void loop()" and call in a function which also contains a loop, then be able to break it from the while loop. When attempting this various ways, the for loop within the function seems to blink the LED 10+ times and totally ignores my keystroke "2" to break the loop and is now infinite. I know I could just put the for loop up in "void loop()" and it would work to break out similar to Example 1, but I'm sure it can be broken from a function as well. I will eventually have similar functions that will contain parameters.

How would I go about doing this the correct way?

Below is "Example 2" that I am trying to break from the function. I'm assuming it's an issue with doing it from the while loop?

Again, any assistance is greatly appreciated.

```
//Example 2
int ledPIN = 13; // sets up onboard LED on Arduino located near PIN13
char rx_byte = 0; // variable to hold serial input from console;
int count = 0; // placeholder for incrementing during debugging of loops

void setup() {

  Serial.begin(115200);

  pinMode (ledPIN, OUTPUT);

}

void loop() {

  if (Serial.available() > 0) {    // is a character available?

    rx_byte = Serial.read();       // get the character
    boolean forceTerminate = false;

    // check if a number was received
    if ((rx_byte >= '0') && (rx_byte <= '9')) {

      switch(rx_byte) {
        case '1':
          Serial.println("You've entered: 1");
          while(forceTerminate == false) {
            rx_byte = Serial.read(); // must read character again
            if (rx_byte == '2') {
              Serial.println("Quitting...");
              digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
              forceTerminate = true;
              break;
            }
            else {
              //count = count+1;
              //Serial.println(count);
              blinkPIN13(); // FUNCTION: blinkPIN13
            }
          }
          digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
          break;

      } // end: switch(rx_byte)

    }

  } // end: if (Serial.available() > 0)

}

/************************************************************************************
 * FUNCTION for blinking LED located on PIN 13 to the state of ON(1)/OFF(0)
 ************************************************************************************/
void blinkPIN13() {

  for (int i; i <=10; i++) {
    digitalWrite(ledPIN, HIGH);
    delay(1000);
    digitalWrite(ledPIN,LOW);
    delay(1000);
  }

}

```

# Answer
To tell a function-caller what to do when the function exits, have the function return a status value. You can do this at multiple levels. For example:

```
byte doOtherStuff(int howLong) {
  digitalWrite(ledPIN, HIGH);
  delay(howLong);
  if (doneDoing()) return false;
  digitalWrite(ledPIN,LOW);
  delay(howLong);
  return !doneDoing();
}

void loop() {
  while(doMore) {
    doStuff();
    for (byte i=0; i<9 && doMore; ++i) {
      doMore = doOtherStuff(1234);
    }
    if (doMore) {
      doMoreOtherStuffInWhile();
    }
  }
}

```
> 1 votes

---
Tags: arduino-uno, serial, c
---


title: Arduino based Fan controller for PC

text:
# Question
Title: Arduino based Fan controller for PC
My fellow programmers,

I'm planning on creating a fan controller for my PC using an Arduino Duemilanove and a generic motor sheild. (Fan controllers are not exactly cheap here and i'd rather spend my money on an SSD than on a fan controller =)

On a normal scenario, I want my fans to spin slowly, just to keep some air flowing but not enough to make too much noise. Obviously, they should turn on at full speed (or so) during a demanding scenario, like playing a game.

My idea is to use a usb port to communicate with Windows, so that my arduino knows when a demanding application was started. Is there an easy way to do this or should I buy myself some cheap temperature sensors, place them on the more important parts and control my fans with these temperature readings?

I'd also like to have an option to turn of the communication between the arduino and whatever informs it about the computer usage, so that I can program it in order to test a different algorithm.

Thanks for any help!

# Answer
> 1 votes
Yes you can. One of the options is using Visual Studio if you are Windows user (using built in library is enough to meet your 'option to turn off' needs). There so many examples of serial communication using either C# or C++ with Arduino, so you can do communication between Laptop - Arduino via serial cable or even built in bluetooth in laptop (with extra bluetooth module for Arduino).

The most simple setup is your laptop act as master and arduino as slave. Arduino does not need any information about what program is running, instead just waiting command from Laptop wether to turn off or turn down the fan

You can read information from your PC (for Windows), such as temperature or battery level

# Answer
> 0 votes
Any Arduino with a USB interface can communicate with a PC via pseudo-serial ports (that is, serial-over-USB links). If you have a PC program that somehow monitors what processes are running, your plan of telling the Arduino to speed up the fan when certain programs are running is practical to do.

On Linux systems, fan speed can be controlled by user programs like fancontrol-gui and tpfanco. Probably similar programs are available on Windows and Mac systems. Your Arduino could measure temperatures and send them to the host OS for fan speed control. Or vice versa, your PC could use DBus or ACPI calls to measure its chip temperature and send it to the Arduino to control a fan.

Note, there's a thermometer built in to several ATmega devices. Its resolution isn't great and due to chip thermal mass it might not respond quickly, but you might find it worthwhile to experiment with. For example, see §24.8, Temperature Measurement, on page 247 of the document Atmel-8271J-AVR-ATmega-Datasheet\_11/2015, which says to select the internal 1.1 V ADC voltage reference, read ADC channel 8, and scale the result per Table 24-2 to get °C.

---
Tags: communication
---


# Question
Title: It seems like the math of arduino is off
*\[SOLVED\] By changing the offset for the incoming data into `int16_t` type there won't be any rounding errors and the values I'm getting are all back to zero in the sensor its base position*

This is my first project where I use Arduino.

Until today everything went good with the Arduino Pro Mini (3.3v). But as of today I got a bit of a weird problem. I am using a MPU gy-521 (doesn't really matter) and I'm working on calculating the actual movement.

The problem which occured is that I'm using a deadzone to negate the smallest numbers (I know, this isn't the right way to use data). The way I negate the numbers is with the following code

```
// Check deadzone values
  if (ax+axo < adz && ax+axo > -adz) ax = -axo;
  if (ay+ayo < adz && ay+ayo > -adz) ay = -ayo;
  if (az+azo < adz && az+azo > -adz) az = -azo;

  if (gx+gxo < gdz && gx+gxo > -gdz) gx = -gxo;
  if (gy+gyo < gdz && gy+gyo > -gdz) gy = -gyo;
  if (gz+gzo < gdz && gz+gzo > -gdz) gz = -gzo;

```

ax is accelerometer data over the x-axis, axo is the offset, adz is the accelerometer deadzone.

gx is gyroscope data over the x-axis, gxo is the offset, gdz is the gyroscope deadzone.

All of the other letters are the same, for different axis. After getting the values within the offset basically set to 0 with the offset I'm doing the following.

```
// Calculate acceleration
  axa = (ax+axo) / aFactor * g;
  aya = (ay+ayo) / aFactor * g;
  aza = (az+azo) / aFactor * g;

  gxa = (gx+gxo) / gFactor;
  gya = (gy+gyo) / gFactor;
  gza = (gz+gzo) / gFactor;

```

The a- and gFactor are mentioned in the datasheet, but these values should all be 0 if the value of axis plus the offset is within the deadzone. The problem is that I'm not just getting 0.00 values. I'm also getting -0.00 and 0.01.

```
0.00    0.00    -0.00   0.00    0.01    0.01

```

Could someone enlighten me about what's wrong in my situation or if this is just a Arduino issue.

*\[EDIT\]*

The data originally from the sensor is from type int16\_t (ax, ay, az, gx, gy, gz) and the other variables are doubles.

The values which are off are always the same ones: Accelerometer Z, Gyroscope Y and Z.

# Answer
If your program is basically working but gives you rounding errors, it can be that you are facing some problems related to conversion from floating-point to binary or reverse. It is a very common problem in computer science. For example, the decimal number `0.1` has no exact binary representation, it is infinite. For more information, you can read these pages:

http://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/ https://www3.ntu.edu.sg/home/ehchua/programming/java/datarepresentation.html

In order to solve your problem, you can try to apply appropriate rounding to your results and if possible avoid mixing different data types and use `double` only if absolutely needed (which I guess is the case in your application).
> 1 votes

---
Tags: arduino-ide, arduino-pro-mini, accelerometer, gyroscope, mathematics
---


title: Running multiple motors simultaneously

text:
# Question
Title: Running multiple motors simultaneously
I have this code for a DC motor (using this library)

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

//              ENA A   B   PWM   CS    inv
Vnh2sp30  mtrL( A0, 7,  8,  5,    A2,   0);

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

void loop() {
  if (Serial.available() > 0)   {
    String first  = Serial.readStringUntil(',');
    Serial.read();
    String second = Serial.readStringUntil(',');
    Serial.read();
    String third = Serial.readStringUntil(',');
    Serial.read();
    String echo = Serial.readString();
    Serial.println(echo);
       if(first == "start"){
                Serial.println("Starting DC motor");
                int duration = atoi(second.c_str());
                int power = atoi(third.c_str());
                int starttime = millis();
                int endtime = starttime;
                while ((endtime - starttime) <= duration) // mS
                {
                  endtime = millis();
                  mtrL.run(1023);
                }
                mtrL.stop();
                Serial.println("DONE");
       }
   }
}

```

Then I have this code to drive multiple stepper motors (using this library):

```
#include "BasicStepperDriver.h"

int incomingByte = 0;   // for incoming serial data
String readString = "";

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

void loop() {
    if (Serial.available() > 0) {
    String first  = Serial.readStringUntil(','); // start
    Serial.read();
    String second = Serial.readStringUntil(','); // motor number
    Serial.read();
    String third = Serial.readStringUntil(','); // motor steps
    Serial.read();
    String fourth = Serial.readStringUntil(','); // duration (millisec)
    Serial.read();
    String fifth = Serial.readStringUntil(','); // deg
                if(first == "start") {
                  if(second == "ALL") {
                    Serial.println("Starting stepper motor ALL");
                    int steps = atoi(third.c_str());
                    int duration = atoi(fourth.c_str());
                    int deg = atoi(fifth.c_str());

                    BasicStepperDriver stepper1(steps, DIR, STEP, ENBL);
                    stepper1.enable();
                    stepper1.setMicrostep(MICROSTEPS);
                    stepper1.setRPM(MAX_RPM);

                    BasicStepperDriver stepper2(steps, DIR_2, STEP_2, ENBL_2);
                    stepper2.enable();
                    stepper2.setMicrostep(MICROSTEPS);
                    stepper2.setRPM(MAX_RPM);

                    BasicStepperDriver stepper3(steps, DIR_3, STEP_3, ENBL_3);
                    stepper3.enable();
                    stepper3.setMicrostep(MICROSTEPS);
                    stepper3.setRPM(MAX_RPM);

                    BasicStepperDriver stepper4(steps, DIR_4, STEP_4, ENBL_4);
                    stepper4.enable();
                    stepper4.setMicrostep(MICROSTEPS);
                    stepper4.setRPM(MAX_RPM);

                    int starttime = millis();
                    int endtime = starttime;
                    while ((endtime - starttime) <= duration) // mS
                    {
                      stepper1.rotate(deg);
                      stepper2.rotate(deg);
                      stepper3.rotate(deg);
                      stepper4.rotate(deg);
                      endtime = millis();
                    }
                    stepper1.disable();
                    stepper2.disable();
                    stepper3.disable();
                    stepper4.disable();
                    Serial.println("DONE");
                  }
                }
        }
}

```

My goal is to merge this two codes together and still be able to run both the DC motor and one (or all) the stepper motors all together simultaneously. The first code is running on Arduino UNO and the other code runs on Arduino MEGA board and has been tested to work. The goal is to migrate the code from Arduino UNO to the MEGA board. Driving the motor for a specific time will block Arduino from executing the Stepper motors and vice versa with the DC motor. What can be done with these codes to make sure it can run the DC motor and Stepper motors at the same time?

# Answer
Use the AccelStepper library along with the Adafruit MotorShield library

https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/install-software
> 2 votes

---
Tags: arduino-mega, motor
---


# Question
Title: Arduino IDE crash when I connect Blend Micro
I recently bought Blend Micro and I am setting up Arduino IDE to start using it, but after installing the required libraries and the Blend Micro drivers, the IDE suddenly crashes without any visible error whenever I plug the blend micro to my PC. If it is already plugged in, the ide won't even start up. This was not happening before I installed the drivers. I don't know if it's relevant but blend micro was connected to my pc during the drivers installation. I have already looked for a way to solve this on Google without relevant results.

I am using Windows 10 with Arduino IDE 1.6.12

I would really appreciate any help with my problem, thank you in advance.

# Answer
The final solution to my problem was to download the latest arduino hourly build. There is probably a bug in the stable version that has been solved in the hourly build.
> 0 votes

# Answer
you should try to run the arduino from the consolle, on windows digit cmd on the search bar and the command promp program should appear.

Well, then you should navigate in out arudiono folder: digit `cd "XXX"` where XXX is the arduino executable location (something like c:/program files/blabla), you can copy paste it from the folder explorer.

then write `arduino_debug.exe` and you should see on the terminal the error appear; with that we may find the issue.
> 0 votes

---
Tags: arduino-ide
---


title: Arduino diy wireless

text:
# Question
Title: Arduino diy wireless
Is it possible to do simple wireless on an Arduino, digital, or analog (SDR)? I would like to hook one pin to an antenna (or piece of wire) and generate signals with simple modulations (analog or digital).

# Answer
here there's a nice tutorial on how to obtain it.

Basically it sets the registers so that a pin outputs a PWM signal at 800 kHz and then modulates that signal in code by just switching the pin and off (pinMode set to INPUT or OUTPUT). If you plug a cable (20 cm and on) to pin 8, and tune your radio to 800Khz you'll hear some noise going on and off.

If you read down the forum you'll see people suggesting how to actually send tones, by putting a very small delay (delay(1)) between the on/off of the pin.

In this link they guys have ogn further and they even implemented a morse code library.

Now I am trying to figure out a way to do the same for a receiver.
> 2 votes

# Answer
Based off of what you have said, the simplest way to achieve what you want to do with your Arduino would be to use a WiFi shield, and setup the Arduino to function as a web server. I have included two links: the first link shows you Arduino's sponsored WiFi shield and explains the basics of how to use it. The second link addresses your question of using the Arduino+WiFi shield to generate WiFi signals, by setting it up as a web server. Both links contain sample codes from Arduino that you can copy and paste. Assuming that you are using the native Arduino software, you can also go to: File \> Examples \> WiFi \> WiFiWebServer, and the same code from the Arduino websites that I listed will be there for you to use.

http://arduino.cc/en/Tutorial/WiFiWebServer

http://arduino.cc/en/Guide/ArduinoWiFiShield

Personally, I would always recommend that whenever you want to accomplish a certain task, such as WiFi signal generation, displaying characters on a LCD, or anything else, you search for a shield to use for that application. Shields always make life extremely easier. I hope this helps. :)
> -1 votes

---
Tags: rf
---