# Question
Title: Reading two sensors at different frequencies... multiple Timer3?
Originally, I had a single sensor which I was reading at 100MHz. I used Timer3 and function attached to it to do both reading and writing of the sensor data (print to com port).

Now I have added another sensor which can only be read at half the frequency. I still want to be able to write data in the same format as before for both sensor data at 100Hz, with slower sensor data just being repeated twice.

How do I handle this? Do I use multiple Timer3 attachments at different frequencies? I am planning to have three interrupts.. 1st for reading sensor A, 2nd for reading sensor B, and 3rd for writing data.

# Answer
> 1 votes
The rule is:

* One Timer, One Interrupt.

When the timer overflows it triggers its interrupt. It only has one. That interrupt then runs your ISR.

If you are using a library to provide abstraction from the timer registers then it is down to that library how it calls your ISR. It is possible for one to provide a mechanism whereby you can "attach" multiple routines to the same interrupt, but that is quite a lot of work and overhead for a simple timer library to provide, so it is highly unlikely anyone would ever bother.

So how do you do multiple sensor measurements from one timer? Simple: just do multiple sensor measurements. You don't have to restrict yourself to just reading one sensor within your interrupt - you can read as many as you like. There is just a couple of caveats though:

1. The whole ISR must take less that 10ms to run or it will overrun the timer overflow period.
2. You cannot do serial from inside an interrupt*

So in your interrupt you read the sensors and add their values to a buffer. Then in your main loop you read that buffer to send the data out through serial. You may want to set a flag in your interrupt routine to alert the main loop that there is data available, or implement a circular buffer which has an equivalent of a `.available()` function to see if there is any data to read from it.

---

\*You can place data in the serial TX buffer but it will not be transmitted out of the TX buffer until after the interrupt routine has finished. If you put too much data in that TX buffer it will block indefinitely waiting for it to empty.

# Answer
> 0 votes
Conceptually, this is best solved by having an ISR which always reads the high rate sensor, but implements a toggle so that it only ready the low rate sensor every other execution. On the times when you don't read it you could repeat a stored version of the last reading, though it would be more bandwidth efficient not to transmit that at all.

However, practically speaking this may not be the best choice. The process of reading sensors often has a latency - typically to achieve the highest possible rate you would need to start the reading, and claim the result sometime later. If your two sensors have distinct interfaces, or even if the they share an I2C or SPI bus, you may be able to start readings for both and then claim them with subsequent transactions after allowing them an overlapped measurement time.

It is also not clear that you are best to use an interrupt service routine at all. If your MCU has nothing else to do, the most *deterministic* and ultimately *fastest* behavior on an ATmega might be to accomplish reading and direct (unbuffered) serial transmission within the main program loop, busy waiting at each phase. This avoids not only the overhead of context switches when entering an ISR, but also a lot of the variability. That would be doubly true if you can be transmitting the old reading while waiting for the already-triggered sensors to measure the next one.

However, you mentioned you are using a Teensy 3.x, which probably communicates natively via USB, rather than a serial UART. That complicates things a bit - so called "serial" output flows in response to interrupts from the USB engine responding to the host, which is not really deterministic for you. Fortunately, the Teensy is enough faster that you are less likely to have issues with running out of time, particularly when sampling at 100 Hz.

---
Tags: timers
---


# Question
Title: Works for 2-3 hrs, then LED blinks rapidly - Sleep Mode and Watchdog timer wakeup
I hope somebody can shed some light on this problem. I've researched the internet and forums and noticed that others have experienced similar problems.

This sketch runs fine for a couple of hours...it activates a relay approximately every hour, has a 10 second loop for an LED flash and then enters sleep mode. The watchdog timer is set to 8 seconds and wakes it up from sleep. I don't know why it works for a couple of hours and then gets caught into some sort of loop with the LED flashing rapidly. The requirements for disabling and resetting the watchdog might be the problem but I just don't know where to go next. I have seen a few discussions on memory leakage but not sure what that means or how to check for it. I also wonder if need to add any short delays after resets, etc. Additionally, when I press the reset button it has no effect on restarting the sketch. The sketch is running on a breadboard atMega328p-pu. Any help would be greatly appreciated.

ps. in the preview I noticed the # statements are not shown. They are the following libraries: avr/sleep.h, avr/power.h, avr/wdt.h

```
// In this sketch, the LED's flash every 10 seconds, then at each approximately 1 hour period, the relay is activated
// for 12 seconds.  It uses the WDT at its maximum 8 second delay to wakeup the circuit from low power sleep.

// Source: citizen-sensing.org/2013/07/arduino-watchdog/

// Check this out for good explanation on the Watchdog timer and code.
// http://www.leonardomiliani.com/en/2013/impariamo-ad-usare-il-watchdog-2/

// SEE NOTE at the end on known WDT reset issue

#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>

int j = 1; // Elapsed time multiplication factor
int j2 = 0; // previous j value
float tCumm = 0.0; // Cummulative time
float hSet = 1.0; // Set relay activation once per hour
float hSet2 = 0.0; // Previous hSet value

// Create sleepNow function

void sleepNow() {

  wdt_reset();
  wdt_disable();

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Selecting the lowest power setting

// Set watchdog parameters
  MCUSR &= ~(1<<WDRF); // reset status flag
  WDTCSR |= (1<<WDCE) | (1<<WDE); // required to enable configuration changes
  WDTCSR = (1<<WDP0) | (1<<WDP3); // set the pre-scalar for 10, ie 8 seconds delay
  WDTCSR |= (1<<WDIE); // enable interrupt mode

// Disable the ADC
  ADCSRA &= ~(1<<ADEN); // Set bit 7 in ADC register to 1 to disable the ADC

// Ready for sleep
  sleep_enable(); // Enable sleep function
  sleep_mode(); // Go to sleep.  Will wake up upon interrupt via Watchdog timer in this sketch.

// disable sleep after waking up
  sleep_disable(); // Disable sleep for now after Watchdog timer interrupt activation
}

void setup() {

  pinMode(4, OUTPUT); // set pin 4 as output for LED
  pinMode(7, OUTPUT); // set pin 7 as output for relay
}

void loop() {

  // 10 second LED flashing + sleep loop

  for (int i = 0; i < 2; i++) {
  digitalWrite(4, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(200);               // wait for 0.2 sec
  digitalWrite(4, LOW);    // turn the LED off by making the voltage LOW
  delay(200);              // wait for 0.2 second
}

  // Add delay for total approx 2 sec
  delay(1200);

  // Start sleep / Low power / Watchdog interrupt
  sleepNow();

  // Cummulative time in increments of 10 seconds
  tCumm = ((2.0 + 8.0)*j)/3600.;

  // Time multiplication factor. Used to increment tCumm. Never resets to zero.
  j2 = j;
  j = j2 + 1;

  // Check to see if tCumm exceeds the user defined period (hSet) before activating relay
  if (tCumm > hSet) {

  // Activate relay for 12 seconds
    digitalWrite(7, HIGH);
    delay(12000);
    digitalWrite(7,LOW);

  // Reset hSet for next relay activation time
    hSet2 = hSet;
    hSet = hSet2 + 1.0;

    }
}

ISR (WDT_vect) {

}

```

NOTE from an online discussion: The problem is that a RESET does not turn off the watchdog timer once it has been turned on, and neither does the bootloader. So you set things up to have the watchdog cause a reset in 15ms, and the reset occurs. Now the bootloader starts up, and starts its LED-flashing, and OOPS another 15ms has gone by with no one feeding the watchdog, and it resets again. This repeats until a power cycle turns off the watchdog.
(This behavior is explicitly described in the ATmega datasheet...)

# Answer
> 1 votes
You have a watch dog timer for 8 seconds and when you activate the relays you do a delay of 12.
This means that your watchdog will trigger when you activate the relays.

# Answer
> 1 votes
Looking at this declaration

```
int j = 1; // Elapsed time multiplication factor
int j2 = 0; // previous j value

```

and then this code

```
// Cummulative time in increments of 10 seconds
  tCumm = ((2.0 + 8.0)*j)/3600.;

 // Time multiplication factor. Used to increment tCumm. Never resets to zero.
  j2 = j;
  j = j2 + 1;

```

along with the associated comments seems to indicate that this variable "j" which is a (signed) `int` only increments without ever resetting, and is critical to the process of calculating the next time at which your code will act.

Your includes indicate that you are building for an AVR-based Arduino, and under the compiler used, an `int` on this platform is only 16 bits, meaning it has a range of -32768 to 32767. Most modern platforms including this one use 2's complement representation, and most non-DSP platforms including this one do not use saturating arithmetic. **Therefore, incrementing a positive number beyond the positive limit will actually product a negative value.** Once your target time exceeds the maximum possible result of a calculation that has a positive `int` as an input, it becomes a target you will never be able to achieve.

Given the the amount of time your loop takes to execute, such integer overflow may not be not the issue you are hitting *first*, and does not seem perfectly correlated to your rapid-cycling failure mode. But if your loop takes around 10 seconds, it seems like this would be an issue in a little less than four days.

---
Tags: relay, sleep
---


title: calling a random function number

text:
# Question
Title: calling a random function number
I have a recurring problem that when I'm controlling leds, I make several different functions for different fx and just want to trigger them randomly but having a hard time to formulate it in an intelligent way and end up hardcoding every function call.

ex: I have let's say 10 functions called anim1();, anim2();, anim3(); etc and would like to called them randomly in that fashion :

```
randNumber = random(1,11);
anim[randNumber]();

```

I know that it's not that type of brackets I need to use but I can't find the proper syntax and I'm wondering if it's possible to do that.. I'm sure there must be a way ;)

thanks for your help

# Answer
> 3 votes
What you want is an *array of function pointers*.

```
void anim1() {
    // blah blah
}

void anim2() {
    // blah blah
}
// ... etc ...

typedef void (*animptr)();

animptr anims[10] = {
    anim1,
    anim2,
    anim3,
    // ... etc ...
    anim10
};

```

Then you can use:

```
anims[animNumber]();

```

# Answer
> 0 votes
I end up using another way and just wanted to share it here for anybody that would want a bit less efficient but simpler way of doing that ;) it's cleaner with Majenko's solution for sure but this gets the job done and is pretty easy to understand and troubleshoot. cheers!

```
int randNumber;

void loop(){
randNumber = random(1,14);

if (button is pressed or something){
callAnim(randNumber);
}
}

void callAnim(int randNumber){
if (randNumber==1){
anim1();
}
if (randNumber==2){
anim2();
}
}
// ... etc ...

void anim1() {
// blah blah
}

void anim2() {
// blah blah
}
// ... etc ...

```

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


title: Creating a library

text:
# Question
Title: Creating a library
I created a simple library for formatting text output on the serial monitor. It has thee functions, one that creates carriage returns, one that sets the number of spaces between characters and the last one prints dashes. I followed the tutorial on the Arduino.cc site. The problem I have is that I can’t pass the value to each of the functions when I call them in the code. If you look at the screenshot from the sketch when I create an instance of nFormat it requires me to put a value in and it passes that value to each of the functions (lines, spaces, dashes). I want to be able to specify the value directly when I call the function. See the second red line on the output screenshot. I know this post is a bit long I would appreciate it if someone could point me in the right direction.

nFormat.h

```
#ifndef nFormat_h
#define nFormat_h

#include "Arduino.h"

class nFormat
{
  public:
    nFormat(int counter);

    void lines();
    void spaces();
    void dashes();

   private:
    int _counter;
};

#endif

```

nFormat.cpp

```
#include "Arduino.h"
#include "nFormat.h"

nFormat::nFormat(int counter)
{
    _counter=counter;
}

void nFormat::lines()
{
for (int x = 0; x < _counter; x++)
    {
        Serial.println(" ");
    }

}

void nFormat::spaces()
{
    for (int x = 0; x < _counter; x++)
    {
        Serial.print(" ");
    }
}

void nFormat::dashes()
{
    for (int x = 0; x < _counter; x++)
    {
        Serial.print("-");
    }

```

# Answer
> 2 votes
If you want to specify the number of spaces/dashes/... every time you call any of these methods, you just have to make that number a parameter of the method:

```
void lines(int count)
{
    for (int x = 0; x < count; x++)
        Serial.println();
}

```

Then, your class does not need its private `_counter`. Then, since there is no data in the class, you do not need to instantiate it: just make all the methods `static` and call the methods as `nFormat::method_name()`. And since you are not making instances, you do not need a constructor either. And since the methods are really trivial, there is no point in implementing them in a .cpp file: you can just inline them in the class declaration. Combining all this gives this small demo program:

```
class nFormat
{
  public:
    static void lines(int count)
    {
        for (int x = 0; x < count; x++)
            Serial.println();
    }

    static void spaces(int count)
    {
        for (int x = 0; x < count; x++)
            Serial.print(" ");
    }

    static void dashes(int count)
    {
        for (int x = 0; x < count; x++)
            Serial.print("-");
    }
};

void setup()
{
    Serial.begin(9600);
    nFormat::dashes(5);
    nFormat::lines(5);
    nFormat::spaces(5);
    nFormat::dashes(5);
}

void loop() {}

```

It could be noted than this class serves only to avoid putting all the functions in the global namespace. It is essentially a namespace. You could as well replace `class` by `namespace` (and remove the `public` keyword) to make that more explicit.

---
Tags: library
---


# Question
Title: Is this a proper implementation of FreeRTOS for Arduino?
I'm using the **RGBLCDShield** library and a few analog input signals and since it seems the interrupts are being used by the SPI interface of the LCD Shield, I decided to try it with **FreeRTOS** instead. I don't currently have my arduino with me (left if at parents') but I wanted to get some feedback on this code to see if it would run properly; I might not be getting my UNO back for a few days but I wanted to at least have a usable code ready to be tested when I do get it.

The Analog inputs are just 2 low level signals and the digital outputs just control some IC switches. One PWM is fed through a lowpass filter and into an amplifier input.

**Here is my code in it's entirety:**

```
#include <Arduino_FreeRTOS.h>
#include <Adafruit_RGBLCDShield.h>
#include <Wire.h>
#include <math.h>

// define tasks
void TaskAnalogRead( void *pvParameters );  // Check voltage input
void TaskLCDShield( void *pvParameters );   // Control Display
void TaskUserInput( void *pvParameters );   // User Interface - System Process

Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
unsigned int vSet = 0;  // Desired Voltage (potentiometer set)
unsigned int vOut = 0;  // Voltage on capacitor

// the setup function runs once when you press reset or power the board
void setup() {

  // Set up Tasks to run independently
  xTaskCreate(
    TaskAnalogRead
    ,  (const portCHAR *) "AnalogRead"   // A name just for humans
    ,  128  // This stack size can be checked & adjusted by reading the Stack Highwater
    ,  NULL
    ,  2  // Priority, with 1 being the highest, and 4 being the lowest.
    ,  NULL );

  xTaskCreate(
    TaskLCDShield
    ,  (const portCHAR *) "LCDShield"
    ,  128  // Stack size
    ,  NULL
    ,  3  // Priority
    ,  NULL );

  xTaskCreate(
    TaskUserInput
    , (const portCHAR *) "UserInput"
    , 128
    , NULL
    , 1
    , NULL );

  // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started.
  lcd.begin(16, 2);
}

void loop()
{
  // Empty. Things are done in Tasks.
}

/*--------------------------------------------------*/
/*---------------------- Tasks ---------------------*/
/*--------------------------------------------------*/

void TaskLCDShield(void *pvParameters)  // This is a task.
{
  (void) pvParameters;

  // Start Display
  lcd.setBacklight(0x7);
  lcd.setCursor(0,0);
  lcd.println(" PORTABLE SPARK ");
  delay(5000);
  lcd.clear();

  for (;;) // Continuously Update display
  {

    int volts = vSet * 100.0;
    int chg   = (vOut * 0.488)/volts;
    int vpos, cpos;
    lcd.setCursor(0,0);
    lcd.print("Voltage:       ");
    lcd.setCursor(15, 0);
    lcd.print("V");
    lcd.setCursor(0,1);
    lcd.print("Charge :       ");
    lcd.setCursor(15,1);
    lcd.print("%");

    lcd.setCursor(9,0);
    if(volts < 100)
      {
        lcd.print("    ");
        vpos = 13;
      }
    else if(volts < 1000)
      {
        lcd.print("    ");
        vpos = 11;
      }
     else if(volts < 10000)
     {
      lcd.print("     ");
      vpos = 10;
     }
     else vpos = 9;
    lcd.setCursor(vpos,0);
    lcd.print(volts, DEC);

    lcd.setCursor(9,1);
    if(chg < 10)
      {
        lcd.print("    ");
        cpos = 13;
      }
    else if(chg < 100)
      {
        lcd.print("   ");
        cpos = 12;
      }
    else cpos = 11;
    lcd.setCursor(cpos,1);
    lcd.print(chg, DEC);
    //digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
    //digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
    //vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
  }
}

void TaskAnalogRead(void *pvParameters)  // Read Analog Voltages (VSet, Emonitor)
{
  (void) pvParameters;

  for (;;)
  {
    int eMon = analogRead(A0); // read input pins
    vTaskDelay(1);
    int vA = analogRead(A1);

    vSet = (vA/1024) * 15000;  // calculate actual values
    vOut = (5.0/1024.0) * 10000 * eMon;

    vTaskDelay(10);  // one tick delay (300ms) in between reads
  }
}  // End Analog Read

void TaskUserInput(void *pvParameters) // User Interface
{
  (void) pvParameters;

  // initialize digital pin 13 as an output.
  pinMode(8, OUTPUT);  // Fire signal
  pinMode(7, OUTPUT);  // Charge/Discharge signal
  pinMode(5, OUTPUT);  // Eprgm PWM output
  pinMode(4, OUTPUT);  // Cam/DAQ trigger

  bool charge = false;   // charge flag

  for (;;)
  {
    uint8_t button = lcd.readButtons();
    switch(charge)
    {
      case true:
        analogWrite(5, (vSet * 0.0204)/5);
        vTaskDelay(1);
        digitalWrite(7, HIGH);
        vTaskDelay(1);
        break;

       default:
        analogWrite(5, 0);
        vTaskDelay(1);
        digitalWrite(7, LOW);
        vTaskDelay(1);
        break;
    } // End Switch(charge)

    if(button & BUTTON_UP)  // Charge/Discharge button
    {
      charge = !charge;
    } // end if

    else if(button & BUTTON_DOWN) // Fire!
    {
      digitalWrite(8, HIGH);
      vTaskDelay(1);
      digitalWrite(4, HIGH);
      vTaskDelay(1);
      digitalWrite(7, LOW);
      charge = false;
      vTaskDelay(1);
      digitalWrite(4, LOW);
      vTaskDelay(1);
      digitalWrite(8, LOW);
    } // End else if

  }  // End for

} // End User Interface

```

My specific concern is with the 2wire interface of the LCD shield and whether it would be able to communicate with the Arduino - especially when it needs to read the button inputs.
Also, how do I determine the stack size for each task? Is 128 for each enough to handle what I have?

# Answer
> 3 votes
This is not a direct answer to the question. Instead, I suggest that you do not need an RTOS to do what you want. A lightweight alternative is to use `millis()` to decide when it is time to perform such or such task:

```
void loop()
{
    uint32_t now = millis();

    // Update the LCD every second.
    static uint32_t last_lcd_update;
    if (now - last_lcd_update >= 1000) {
        last_lcd_update = now;
        update_lcd();
    }

    // Read the analog inputs every 300 ms.
    static uint32_t last_analog_read;
    if (now - last_analog_read >= 300) {
        last_analog_read = now;
        do_analog_read();
    }

    // User input is handled continuously.
    handle_user_input();
}

```

This will use significantly less resources (flash, RAM and CPU time) than an RTOS. Another advantage is that you do not need to determine a stack size for each task, which is definitely *not* a simple thing to do.

---
Tags: arduino-uno, interrupt, threads, task
---


title: SIM800L project not working

text:
# Question
Title: SIM800L project not working
I got a SIM800L, same as the one under this link, Quickstart SIM800 (SIM800L) With Arduino, and played around with an Arduino Nano and Uno. I had a few problems, at the start, not getting it work properly. It turned out that my Nano 5V pin wasn't enough for the SIM unit. It works fine with Uno though.

There is the code I tested the GSM (same link) and got it working somehow, I got simple AT commands and managed to send an SMS. But after I dismantled the connections and the next day I tried again... Nothing. I can see the SIM unit connects to network as the LED blinking slows down to once every 3 seconds but when I type commands in nothing happens in the serial monitor. It doesn't give errors or anything, just nothing happens on the serial monitor.

I did wire it incorrectly, once with the Tx/Rx, but that shouldn't damage the unit, should it?

I tried to upload different programs to my Arduino and they work fine so that shouldn't be the problem. Is there a way to reset the SIM800 unit? Or am I missing something here?

# Answer
> 2 votes
The module needs a good 5v supplier as it might have a peak of 1A or 2A, when it registers to the network or connects to 3G.

You need to make sure that you share the ground between the power supplier and you use some 2 pins on your arduino to connect the GSM module. Dont try to get a fast baudrate as software serial doesnt work, try with 9600 to start then see if it response to the AT command.

SIM800 is a very simple module, try with an FTDI in case you want to make sure you didnt break your Arduino.

For more help, share your schematic how you have connected the arduino.

# Answer
> 1 votes
I have put in a lot of time with the SIM808, and I always have trouble delivering enough power to it. Note that the SIM808 will alert you with an "undervoltage warning" sometimes as a response to AT commands. I bet the SIM800 would do the same.

As Max above is alluding to - try powering the SIM800L via a separate 5V 2A adapter. When doing this don't forget to still hook up ground between the Uno and your SIM800L board.

If you accidentally hooked 5V to the VDD pin on your module, you may have damaged it.

FTDI is a tool every embedded dev should have. Get a few!

---
Tags: arduino-uno
---


# Question
Title: Is it possible to connect 2 ultra sonic sensors to 1 arduino?
I am currently using the Arduino Pro Micro board and I want to connect 2 ultrasonic sensors to 1 board, whilst knowing which sensor is being triggered. The sensor I am using is a HC-SR04 Ultrasonic sensor.

Please help me thank you :)

# Answer
> 1 votes
Yes, you can, as long as you serialize the send/receive pulse cycles, to avoid interferences. basically, you attach the Trig/Echo lines to a different pair of pins, then do the reading on one sensor, then do the reading on the other.

# Answer
> 1 votes
What you need to do, for each sensor, is the following:

* choose a GPIO that will drive the trigger line (make sure it is not a pin you are already planning to use, ex: TX/RX )
* choose a pin that will receive the information from the Echo line, ideally using an interrupt driven implementation, instead of polling. The 328P supports exactly 2 independent interrupt lines: INT0 and INT1, so you could use one of them for each sensor.
* have a time base and use it to time-stamp the Trig and Echo lines

Example for one sensor (for 2 just do the same and keep in mind that there might be interferences, like the OP said):

1. toggle the Trig line for the required duration (strobe)and save it
2. read the time
3. wait for the interrupt to occur (you can do other things in the meanwhile)
4. when the interrupt occurs, read again the time
5. subtract the timestamp taken after toggling Trig from the timestamp taken after the Echo interrupt
6. convert the delta time from the previous point into a linear measure, using the constant provided by the datasheet of the sensor

---
Tags: hardware, hc-sr04
---


# Question
Title: Weird characters in Serial Monitor and not functioning ESP8266 ESP-12e
I did a bit of playing with my new ESP-12e, but suddenly it kind of fails on me. It gives me some weird looks it didn't give me (as much) before.

**This is what the Serial Monitor prints when I try to run a very simple sketch.** When I restart the module, it just adds some more of these chars. **The following is the code for that:**

```
const int statusLED = 16;

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

  Serial.begin(115200);
  Serial.write("The ESP-12e has started.");
  delay(500);
}

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

```

This doesn't even involve the WIFI...

**These are my board settings:**
*Board: Generic ESP8266 Module
Flash mode: QIO
Flash frequency: 40MHz
CPU frequency: 80MHz
Flash size: 4M (3M SPIFFS)
Upload speed: 115200*

**And finally, if it might help, how I connected the module:**
All connections are solid, so that shouldn't be a problem. *The connection board has GPIO15 printed on it twice, but the one I connected to the LED is actually GPIO16.* I noticed that the onboard LED of the ESP-12e doesn't light on anymore.

I use the CP2102 USB to UART module.

Thanks!
Rogier

# Answer
Check what baud rate is serial window displaying. It should be the same as defined in your code.
> 2 votes

---
Tags: serial, esp8266, ide
---


title: Stepper Motor not Stepping Properly

text:
# Question
Title: Stepper Motor not Stepping Properly
I have an Arduino Uno connected to the Adafruit Motorshield v2. I have it hooked up to a stepper motor(27BYJ-48). I am trying to make the motor do one complete revolution. However, the number of steps I specify to the stepper motor(200 in the code) doesn't affect the motor steps. For example, the 2200 step in this code, is roughly one rotation and is completely unaffected by change the steps/revolution specified when instantiating the motor. How do I get the motor to do one exact revolution?

Here is the code on the arduino:

```
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Stepper test!");

  AFMS.begin();  // create with the default frequency 1.6KHz

  myMotor->setSpeed(2000);  // 10 rpm
}

void loop() {
  Serial.println("Single coil steps");
  myMotor->step(2200, FORWARD, DOUBLE);
  myMotor->step(2200, BACKWARD, DOUBLE);
}

```

Edit: Wiring:

# Answer
Ok so I'm not familiar with the sheild or API (or motor lol) but going off the spec sheets etc

Leave the red wire disconnected \[see 1\] and try this code and report back what happens:

```
  #include <Wire.h>
  #include <Adafruit_MotorShield.h>
  #include "utility/Adafruit_MS_PWMServoDriver.h"

  Adafruit_MotorShield AFMS = Adafruit_MotorShield();
  Adafruit_StepperMotor *myMotor = AFMS.getStepper(64, 2); // 64 steps pr revolution
                                                           // Using M3 and M4 of shield

  void setup()
  {
    AFMS.begin();  // create with the default frequency 1.6KHz
    myMotor->setSpeed(30);  // 30 rpm, so 1 full turn every 2sec
  }

  void loop()
  {
    // 64 steps per motor shaft revolution,
    // 64 revolutions of motor per output shaft revolution
    myMotor->step(4096, FORWARD, DOUBLE);    // Should be 1 rev in one direction
    myMotor->step(4096, BACKWARD, DOUBLE);   // and 1 rev in other direction
  }

```

\[1\] : your motor is unipolar (wikipedia on unipolar and bipolar motors), according to its documentation. The red wire is the central tap, and useless in this context.
> 1 votes

# Answer
I also tested 27BYJ-48 stepper motor with instructables source code. It works but I had the same "complete revolution" problem. They compute on their website that a revolution contains 4096 steps.

As @James said, indeed, there is gearing inside the stepper motor. The problem is the gearing could be different for the exact same reference ! Everything is described here : 28BYJ-48
> 1 votes

---
Tags: arduino-uno, motor, stepper
---


# Question
Title: How to connect a phone's camera to an Arduino?
I would like to ask how to connect my phone's camera to an Arduino, just like it is done in this this video. Is anyone familiar with this application they are using?

# Answer
That video shows a Bluetooth connection between the smartphone and the Arduino.

(A USB connection between the smartphone and the Arduino might be better in some ways).

## details

If you want more information after watching a video like this, click the "show more" button underneath the video to see the details. Those details clearly say "The Nexus S device connects to the IOIO board via Bluetooth, and uses the smartphone's camera in conjunction with OpenCV and the external IR sensors to control the vehicle." Those details also include a link to "Android Based Robotics".

The OpenCV image processing software runs on the smartphone. In this autonomous application, the image data never leaves the smartphone. The software on the smartphone reduces the image data to two integers -- the X,Y pixel location of the center of the green ball.

The Arduino and the Bluetooth link can easily handle a few integers at over 200 Hz. Neither one is suitable for handling live video data.

The Arduino could probably act as the controller. The camera could send the X,Y pixel location of the green ball to the Arduino; while the Arduino collects all the other sensor data; then the Arduino could use that to decide what to do; then send the appropriate control signals to the motor drivers.

However, in this autonomous toy car it appears that the the smart phone acts as a controller. The Arduino collects all the other sensor data, forwards that data to the smartphone; then software on the smart phone takes that data and the X,Y pixel location of the green ball; then the smartphone decides what motors need to turn; then the smartphone sends the appropriate commands to the Arduino, and the Arduino demultiplexes those commands to the motor drivers.

For even more details on building robots using smartphones and Arduino, see
> 1 votes

# Answer
Normally I would say that the phone is some kind of converting image to serial data and sending it to arduino via serial port. But there is no cables on the phone in the video. It is communicating wirelessly. But I don't think that vehicle is atonoumus? The phone should be transfering image data via ethernet (wifi) and the user controls it. The reason I don't think that's an atonoumus is because you can't simply process that image stream with an arduino it would be a enormous process for arduino's little chip. They must be processing it on a computer. Either two ways the phone is talking to another processor. Not the arduino. Maybe if you tell what you want to do spesificly I might help you instead of trying to figure out this video :)) EDIT: ***it could also be a Bluetooth connection :))***
> 0 votes

---
Tags: camera
---


# Question
Title: How to filter a blank line received over serial - ESP8266
How can I filter a garbage completely blank line over my serial data? It comes from the wifi module ESP8266

How I read data:

```
  while (Serial1.available()){
       String inData = Serial1.readStringUntil('\n');

       Serial.println("Got: " + inData);

  }

```

Here is my common output:

```
Got: AT+CIPSEND=6
Got:
Got: OK
Got: >
Got: Recv 6 bytes
Got:
Got: SEND OK
Got:
Got: +IPD,21:Volume From: 99 To 89AT+CIPCLOSE
Got: CLOSED
Got:
Got: OK

```

# Answer
> 1 votes
```
inData.trim();
if( inData.length() > 0 ){
   Serial.println("Got: " + inData + "\n");

```

::trim() removes all leading and trailing whitespace characters including newlines. A line of \[zero or more whitespace\] + \[newline\] will get trimmed to the null string. If the result isn't null, then append the stripped off newline and print it. Note that this will flatten any indentation or vertical spacing that was supplied in the incoming text.

---
Tags: serial, esp8266
---


# Question
Title: sending room temp data from multiple esp8266's to Mega 2560 to control CH gas boiler
My existing Arduino Mega set up has been in use for about 4 years controlling my gas CH system & heat pump HW system using an Arduino mega & 13 'wired' DS18B20 sensors; 2 of these sensors monitor the main room (lounge) temperature & 1 sensor monitors the outside temp. These 3 sensors control the CH by gas boiler using an algorithm that constantly adjusts the room temp setting as the outside temp changes. The others monitor HW tank temps, heat pump inlet & outlet temps.

I want to change this 'single zone' CH control to a 'multi zone' control using many more temp sensors (DS18B20 or ESP8266?) but laying in hidden wiring would be a real pain.

I've been looking at using ESP8266-07 as a wireless temp sensor for each 'zone', sending its data to the Mega for processing by the above refered to algorithm, so that the Mega can control the CH system better but I can't find any reference to receiving this wireless data at the Mega for processing within the IDE sketch.

I've tried testing the nRF24L01 & nRF24L01+ but my house has many 'black' reception areas & transmission is unreliable. My 2.4GHz wireless LAN has 3 extenders around the house so this would be my prefered wireless solution.

Could a wireless 'master' be used at the Mega to process data coming in from the 'slave' sensors or am I misunderstanding this?

My programming skill is limited to 'basic IDE' & I find 'wireless' a bit of a black art (I'm a retired mechanical engineer!)

# Answer
I am also in the middle of converting the control of my heating, multi-zone, but using Ciseco / Wirelessthings units as temperature sensors both inside and out. See https://www.wirelessthings.net

Simple serial interface is all you need from the Arduino to run these on a network. The coin cell battery lasts for over 1 year running 1 sample / 10min - the sample rate is configured but obviously the more samples you send the more the battery drains. Range seems to be OK and gets through 3 floors in the house and from the outside. I do use external antenna on the Arduino wireless unit to ensure I get all of the sensor readings.

However sounds like your house is BIG if running 3x WIFI extensions where as a single WIFI base station does me fine.
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: problem using GSM shield and GPS shield in one Arduino UNO R3
i try to program use the GSM shield Arduino with Arduino UNO i did it successfully but after that i try to use GPS shield but when i add the #include for the program i got the error

```
#include <GSM.h>
#include <TinyGPS.h>
#include <SoftwareSerial.h> // when i add that one i got the output eroor
// PIN Number for the SIM
#define PINNUMBER ""

```

i got this error out put

```
Arduino: 1.6.6 (Mac OS X), Board: "Arduino/Genuino Uno"

libraries/SoftwareSerial/SoftwareSerial.cpp.o: In function `__vector_3':
/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/SoftwareSerial.cpp:227: multiple definition of `__vector_3'
libraries/GSM/GSM3SoftSerial.cpp.o:/Applications/Arduino.app/Contents/Java/libraries/GSM/src/GSM3SoftSerial.cpp:499: first defined here
libraries/SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::read()':
/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/SoftwareSerial.cpp:392: multiple definition of `__vector_4'
libraries/GSM/GSM3SoftSerial.cpp.o:/Applications/Arduino.app/Contents/Java/libraries/GSM/src/GSM3SoftSerial.cpp:487: first defined here
libraries/SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::read()':
/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/SoftwareSerial.cpp:392: multiple definition of `__vector_5'
libraries/GSM/GSM3SoftSerial.cpp.o:/Applications/Arduino.app/Contents/Java/libraries/GSM/src/GSM3SoftSerial.cpp:487: first defined here
collect2: error: ld returned 1 exit status
exit status 1
Error compiling.

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

```

# Answer
It appears the GSM library has its own conflicting copy of SoftwareSerial, and not necessarily a matching version unless you're lucky.

Not sure how well this would work but you can try removing the library reference to SoftwareSerial, and fiddle about to use the GSM library's SoftwareSerial.
> 1 votes

---
Tags: gsm, tinygps
---


# Question
Title: Super slow serial (UART) communication on Arduino
I am using this device for my Arduino that connects to the OBD-II port of my car to get various information such as speed, rpm, etc. I am using this for a digital Nixie tube speedometer using the smart Nixie tube from a Kickstarter project.

I pass the information to the Nixie tubes through serial and get information from the OBD-II through serial as well. I am getting speed updates about every 20 seconds and that is incredibly slow when the device can supposedly update up to 100 times per second.

I originally was using an Arduino Uno and using software serial for the tubes, but I figured the slowdown was due to interupts interfering with the hardware serial, so I switched to the Arduino Mega 2560 to use a second hardware serial pin to hopefully fix the problem, yet the same issue is occurring.

Here is my code... There must be something I'm doing wrong. Serial2 is for the Nixie tubes.

```
#import <Arduino.h>

#include <OBD.h>

int ones = 0;
int tens = 0;

int kphValue = 0;
int mphValue = 0;

int rpmValue = 0;

String onesString;
String tensString;
String payloadString;
String rpmString;
COBD obd;

void setup(){
    Serial2.begin(9600);
    obd.begin();

    //Initiate OBD-II connection until success
    while (!obd.init()){
        Serial2.print("$0,Y,Y,255,255,000,000$0,Y,Y,255,255,000,000!");
        delay(1000);
        Serial2.print("$0,Y,Y,000,000,000,000$0,Y,Y,000,000,000,000!");
        delay(1000);
    }
}

void loop(){
    onesString = String(ones);
    tensString = String(tens);
    payloadString;
    rpmString;

    if(obd.read(PID_RPM, rpmValue)){
        if (rpmValue < 3000){
            rpmString =",N,N,255,000,255,000";
        }
        else if (rpmValue >= 5000){
            rpmString = ",N,N,255,255,000,000";
        }
        else if (rpmValue >= 3000){
            rpmString = ",N,N,255,255,030,000";
        }
    }

    if (obd.read(PID_SPEED, kphValue)){
        kphToMPH();
        payloadString = "$" + onesString + rpmString + "$" + tensString + "rpmString" + "!";
        Serial2.print(payloadString);
    }
}

void splitDigits(int input_number)
{
    ones = (input_number%10);
    tens = ((input_number/10)%10);
}

void kphToMPH()
{
    mphValue = kphValue * 0.621371;
    splitDigits(mphValue);
}

```

**EDIT:** I am using the following library: https://github.com/stanleyhuangyc/ArduinoOBD

# Answer
> 6 votes
I think the problem is not so much in the update speed, but in the fact that you loose accuracy in your calculation. The following lines are the culprit:

```
int kphValue = 0;  // [-32768:32767]
int mphValue = 0;
mphValue = kphValue * 0.621371;

```

Make sure the calculation will be entirely in integers to prevent calculation errors:

```
uint16_t kphValue = 0;  // [0:65535]
uint16_t mphValue = 0;
mphValue = ( kphValue * 621 ) / 1000;

```

This limits kphValue to just over 100, if you want to go higher than that there are two option:

* multiply by 62 and divide by 100;
* use longer integers `int32_t` \[-2147483648:2147483647\], which comes with enough room for multiplying by 621371 and dividing by 1000000, but will perform slower and with a larger memory footprint. Do you really need that accuracy?

# Answer
> 3 votes
try this:

```
#import <Arduino.h>
#include <OBD.h>

int kphValue = 0;
int rpmValue = 0;

COBD obd;

//array of character arrays, see http://arduino.cc/en/Reference/string
const char* rpmStrings[] = {    ",N,N,255,000,255,000",
                                ",N,N,255,255,030,000",
                                ",N,N,255,255,000,000" };

void setup(){
    Serial2.begin(9600);
    obd.begin();

    //Initiate OBD-II connection until success
    while ( !obd.init() ) {
        Serial2.print("$0,Y,Y,255,255,000,000$0,Y,Y,255,255,000,000!");
        delay(1000);
        Serial2.print("$0,Y,Y,000,000,000,000$0,Y,Y,000,000,000,000!");
        delay(1000);
    }
}

void loop() {
    if ( obd.read(PID_RPM, rpmValue) && obd.read(PID_SPEED, kphValue) )
    {
        int rpmStringIndex = determineRpmIndex(rpmValue);
        int mphValue = kphToMPH(kphValue);

        //payloadString = "$" + onesString + rpmString + "$" + tensString + "rpmString" + "!";
        //using Arduino String objects is generally not a good idea due to memory constraints
        //it's probably ok, but I'd rather use character arrays and/or print a bit at a time rather than trying to assemble a giant string
        Serial2.print("$");
        Serial2.print(mphValue % 10); //ones
        Serial2.print(rpmStrings[rpmStringIndex]);
        Serial2.print("$");
        Serial2.print(mphValue / 10); //tens - integer division, don't need modulo

        //do you really want to append the string "rpmString!" or did you want the contents of the variabe rmpString+"!" ?
        //I'm pretty sure you meant the latter
        Serial2.print(rpmStrings[rpmStringIndex]);
        Serial2.print("!");
    }
    else
    {
        //obd read error
        //add debugging output here to see if obd failed to respond correctly/on time
    }
}

int kphToMph( int kphValue ) {
    //return a value rather than updating a global variable
    return ( int ) ( kphValue * 0.621371 );
}

int determineRpmIndex( int rpmValue ) {
    if ( rpmValue >= 5000 )
        return 2;

    if ( rpmValue >= 3000 )
        return 1;

    return 0;
}

```

# Answer
> 1 votes
I was found solution with

Serial.setTimeout(100);

Like this (https://www.arduino.cc/en/Serial/SetTimeout) setTimeout was 1000ms default.

the check serial port per 1000ms.

I referenced this https://stackoverflow.com/a/28892086/929740

---
Tags: serial, uart
---


title: Using HC-05 to play a sound on an app

text:
# Question
Title: Using HC-05 to play a sound on an app
I connected a HC-SR04 Ultrasonic Sensor to Arduino Uno and built the circuit as shown in the link below. I also used the code below the link. Together, this code and the circuit detect any motion that occurs in front of the ultrasonic sensor. When the sensor detects motion, the console in the Arduino IDE prints that it detects motion and how far away the moving object is. Otherwise, nothing is printed.

I created an app using MIT App Inventor. Every time the Arduino detects motion, I want a sound to be played on the phone of the person with the app. In order to do this, I plan on using a HC-05 Bluetooth Module.

Does anyone have any suggestions for how I should build the circuit and what code I should use?

arduinobasics.blogspot.de/2012/11/arduinobasics-hc-sr04-ultrasonic-sensor.html

```
#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED

int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
 Serial.begin (9600);
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}

int prevdist = 0;

void loop() {
/* The following trigPin/echoPin cycle is used to determine the
 distance of the nearest object by bouncing soundwaves off of it. */
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2);

 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10);

 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);

 //Calculate the distance (in cm) based on the speed of sound.
 distance = duration/58.2;

 if (distance >= maximumRange || distance <= minimumRange){
 //Print "Out of range when there is no object within the range of the ultrasonic sensor.
 Serial.println("Out of range.");
 digitalWrite(LEDPin, HIGH);

 }
 else {

 /* Send the distance to the computer using Serial protocol, and
 turn LED OFF to indicate successful reading. */

   if((prevdist - distance) > 10 || (prevdist - distance) < -10)
   {
     prevdist = distance;
     Serial.println("[OBJECT MOVED]");
     Serial.print("Detecting object ");
     Serial.print(distance);
     Serial.println(" cm away");
     Serial.println();
     digitalWrite(LEDPin, LOW);
   }
 }

 //Delay 1 millisecond before next reading.
 delay(1);
}

```

# Answer
> 1 votes
> Every time the Arduino detects motion, I want a sound to be played on the phone of the person with the app. In order to do this, I plan on using a HC-05 Bluetooth Module.
>
> Does anyone have any suggestions for how I should build the circuit and what code I should use?

The Arduino sketch above is a good start.

The first step is to connect the Bluetooth module so that the Serial output can be sent. The circuit is simply connecting the Bluetooth module to RX/TX on the Arduino. I am assuming that you have written an app that can read from Bluetooth on the phone and write to the screen.

The second step is to parse the output and play the sound. That is also part of the app and not the code on the Arduino. To make this easier the sketch output statements can be changed to something easier to parse (detect).

All and all the work is mainly app programming.

Cheers!

---
Tags: arduino-uno, arduino-ide, bluetooth, hc-05, hc-sr04
---


# Question
Title: Building Multidimensional Arrays from simple arrays
Hi I am trying to write a functiont that will build a 2x4 array based on 2 1x4 arrays.

the two relevant functions are below. The first function gets information from some sensors and outputs it (I think) as a 1x4 array.

The second function is the problem and I have attached the error messages.

```
{
double quatCalib_mat[2][4];
double quatCalib_ABC[4];
double quatCalib_GHI[4];

 double  get_quat(Adafruit_BNO055 ref, double quatArray[])
{
  imu::Quaternion quat2 = ref.getQuat();

  quatArray[0]= quat2.w();
  quatArray[1]= quat2.x();
  quatArray[2]= quat2.y();
  quatArray[3] =quat2.z();

}

void Calibrate()
{
quatCalib_ABC=get_quat(bnoABC, quatCalib_ABC);

quatCalib_GHI=get_quat(bnoGHI, quatCalib_GHI);

quatCalib_mat= {
  {quatCalib_ABC},
  {quatCalib_GHI}
  };
}

```

the error messages

```
Arduino: 1.6.9 (Windows 7), Board: "Arduino/Genuino Uno"

E:\UNI2016\thesis\gizmo programming\Thesis_V3_M\Thesis_V3_M.ino: In function 'void Calibrate()':

Thesis_V3_M:101: error: incompatible types in assignment of 'double' to 'double [4]'

 quatCalib_ABC=get_quat(bnoABC, quatCalib_ABC);

              ^

Thesis_V3_M:103: error: incompatible types in assignment of 'double' to 'double [4]'

 quatCalib_GHI=get_quat(bnoGHI, quatCalib_GHI);

              ^

Thesis_V3_M:105: error: assigning to an array from an initializer list

 quatCalib_mat= {

              ^

exit status 1
incompatible types in assignment of 'double' to 'double [4]'

```

Cheers

Alex

# Answer
> 1 votes
As Mikael Patel said, the compiler is already hinting you about what is wrong. But there are other issues.

1. In `get_quat()`, there is no point in returning anything, as the function is already putting the relevant info in the `quatArray` parameter.
2. Then, when calling `get_quat()`, you don't want to assign the return value to anything.
3. You cannot assign an array like you did, unless it's an initialization. I would explicitly copy the sub-arrays with `memcpy()`:

```
void get_quat(Adafruit_BNO055 ref, double quatArray[])
{
    imu::Quaternion quat2 = ref.getQuat();
    quatArray[0] = quat2.w();
    quatArray[1] = quat2.x();
    quatArray[2] = quat2.y();
    quatArray[3] = quat2.z();
}

void Calibrate()
{
    get_quat(bnoABC, quatCalib_ABC);
    get_quat(bnoGHI, quatCalib_GHI);
    memcpy(quatCalib_mat[0], quatCalib_ABC, sizeof quatCalib_ABC);
    memcpy(quatCalib_mat[1], quatCalib_GHI, sizeof quatCalib_GHI);
}

```

It could be noted that storing the calibration array twice (as both one 2D array and two 1D arrays) is a waste of RAM. You could get rid of the 1D arrays and have instead `get_quat()` fill the lines of the 2D array directly:

```
void Calibrate()
{
    get_quat(bnoABC, quatCalib_mat[0]);
    get_quat(bnoGHI, quatCalib_mat[1]);
}

```

---
Tags: array
---


# Question
Title: Arduino: put string through variable in array
I have a problem and I can't fix it. I'm busy with an java to arduino project.

Java writes a string using writeString(); Arduino reads the serial monitor and put the incoming string into a function.

then I want to put the string into a variable and the variable into a char arr\[\];

The problem is: When I put the string directly in the arr\[\]; it works, but when I put first the incoming string in a variable and then the variable in the arr\[\]; it gives me the next error:

> string-parser:44: error: array must be initialized with a brace-enclosed initializer
>
> exit status 1
>
> initializer fails to determine size of 'arr'

this is the code that doesnt work:

```
input = "2,5>2,6>2,7>4,8";

String splitStringIntoCoordinates(String input){
  char arr[] = input; // Place incoming route in char array
}

```

This is the code that does work:

```
String splitStringIntoCoordinates(String input){
  char arr[] = "2,5>2,6>2,7>4,8"; // Place incoming route in char array
}

```

I hope anyone can help me. Thanks!

# Answer
A String isn't a char array. You can't assign one to the other.

You shouldn't be using String, it's too heavyweight, and how you are passing your String object is wrong, it wastes huge amounts of memory making clones.

You should read this.

The only time you should ever consider using a String object is if you are using a third party library that requires a String object - and even then you should consider other methods.

Regardless of that, you need to copy the *content* of your string, not the string itself. This code *should* work, but it doesn't address the underlying String issues:

```
String splitStringIntoCoordinates(String &input){
  char arr[input.length() + 1]; // Create a char array big enough including the terminating NULL
  strcpy(arr, input.c_str()); // Place incoming route in char array
  // ... etc ...
  // return a string
}

```

If you just want to reference the String as a C string you can just use the function `input.c_str()` to get the internal `char *` array pointer.
> 0 votes

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


# Question
Title: How do I power my Arduino Micro directly?
I just need some confirmation, before I break something. So far I have been powering my project from USB, no I would like to power it from a battery. The official spec claims I should use a voltage anywhere from 7-12V, so I got myself a 9V block battery and would connect the positive lead to the VIN pin and the negative lead to the ground pin right next to it, based on this schematic: https://40.media.tumblr.com/cdadca4e95808b376de52a88a5468367/tumblr\_mi61oww6cu1s5t695o1\_1280.png Do I need a resistor?

# Answer
> 3 votes
According to this schematic, VIN goes to the on arduino-micro's 5 and 3 volt regulators. So you should not need a resistor.

The 5 volt regulator needs a bit more than 5 volts at it's input to do a good job. That is why the specification calls for 7 to 12 volts.

---
Tags: battery, arduino-micro
---


title: Generate particular pulse using Arduino

text:
# Question
Title: Generate particular pulse using Arduino
How can I generate this pulse with an Arduino Micro?

Is it necessary an external component?

# Answer
Take two 10K or so resistors:

```
    +5V
     |
    10K
     |
Pin2-+---> output
     |
    10K
     |
    GND

```

The following program does the trick:

```
const uint8_t kPin = 2;
const uint32_t kDelay = 10;  // 100Hz

void setup() {
}

void loop() {
  pinMode(kPin, OUTPUT);
  digitalWrite(kPin, HIGH);
  delay(kDelay);

  pinMode(kPin, INPUT);
  delay(kDelay);

  pinMode(kPin, OUTPUT);
  digitalWrite(kPin, LOW);
  delay(kDelay);

  pinMode(kPin, INPUT);
  delay(kDelay);
}

```

When Pin2 (or any other pin for that matter) is set as `INPUT`, it is in high-impedance state (theoretically), so effectively you have a voltage divider giving you 1/2 Vcc. When it is set as `OUTPUT`, and now assuming that its output impedance is \<\< 10KΩ, it drives the output to either +5V or 0V.
> 6 votes

# Answer
If both inputs are 0V, the output will be 0V.

If both inputs are 5V, the output will be 5V.

If one input is 0V and one 5V the output will be 2.5V.

However, if the device attached to the output doesn't have a high input impedance, the voltage will drop some. You could add an opamp to prevent this.

I think you can generate the 2 pins outputs using one of the timers in phase correct pwm mode. Freeing up the cpu and giving a very clean output signal, as using software "pwm" could be slightly of due to interrupts occuring.
> 5 votes

---
Tags: arduino-micro
---


# Question
Title: Can the Arduino Eclipse plugin use the libraries installed by the Arduino IDE?
In Arduino Eclipse (v3, nightly build) I have not been able to load 'foreign' libraries, those written by me or someone else, so they are not among the available choices in the include-library dialogs.

I've tried adding them to a project as well as adding them as an available library resource using the built-in dialogs for doing so, but I don't see a way to select a library that isn't already included in those dialogs.

My ideal case would be a way for the Arduino Eclipse plugin to use the same boards and libraries as I use in my Arduino IDE installation, so that:

* An upgrade to the Arduino IDE would simultaneously upgrade the core libraries in Eclipse;
* An optional library would need installing in only one place;
* Modifying an optional library would only need to be done once, in one place.

The goal, as in an earlier question of mine, is to seamlessly permit using either IDE to advance a project. However, I'd be grateful to be able to add to my Eclipse installation any library of my choosing.

# Answer
I fear that what you want is not 100% possible.
For libraries I am 100% sure it will work but the problem is the platforms.
*UPDATE arduino IDE (no longer)? decompresses libraries and as such the libraries are unusable in Sloeber.*

**Lets start with the Libraries** What you do is: In arduino eclipse ide remove all libraries from the library manager.

In windows-\>preferences-\>arduino-\>"private libraries path" add the libraries folder in the arduino IDE install and add the libraries folder in the arduino15 folder maintained by the library manager.
It is important to point to the parent folder containing the libraries. All subfolders are assumed to be libraries.

**Then the boards** The problem here is that the boardsmanager adds environment variables to link boards to tools. You may have read remarks about A.RUNTIME.TOOLS.AVR-GCC.PATH and A.RUNTIME.TOOLS.AVRDUDE.PATH not being defined. Well it is the boardsmanager that maintains these based on json file content. If you can limit yourself to 1 version of AVR, SAM, AVRDUDE, BSON,... tool chain you can "make it work" as follows:
**Step 1:** Keep as little boards as possible installed. **You have to keep at least 1** or the plugin will reinstall the AVR boards of Arduino when started.
**Step 2:** In windows-\>preferences-\>arduino-\>"private hardware path" add the hardware folder in the arduino IDE install and add the packages folder in the arduino15 folder maintained by the Arduino IDE boards manager.
**Step 3:** Recreate the project in eclipse as described in your other question.
**Step 4:** If the build fails modify the \[eclipse installation\]/arduinoPlugin/post and pre processing files to try to get it to work.
**Step 5:** in project properties-\>Arduino select apply and OK (this will take your changes in step 4 into account)
**Step 6:** Goto Step 4

Good luck Jantje
> 2 votes

# Answer
## Making Blynk libraries, v0.3.6 and (presumably) later, Eclipse compatible.

With much help from Jantje (thank you!), I found 4 easy steps that make the Blynk v0.3.6 libraries Eclipse-compatible:

1. Create `.../libraries/Blynk/Blynk.h` (may be empty) and #include it before including any Blynk libraries.
2. Likewise, create and #include `.../libraries/BlynkESP8266_Lib/BlynkESP8266_Lib.h`
3. Delete the entire folder `.../libraries/Blynk/linux` (unless you're running Linux! In which case, some more discovery needs doing.)
4. In Blynk projects previously imported to Eclipse Arduino, delete the (possibly hidden) file `.ino.cpp` and do a clean build.

This recipe works for me under MacOS 10.11.5, the Eclipse Arduino IDE nightly build, and ArduinoIDE version 1.6.9. It should be reproducible by anyone wishing to compile Blynk programs in Eclipse. Under OSes other than Mac, especially linux, step 3 may need to be modified. I deleted the `linux` folder to prevent Eclipse from compiling `main.cpp` and `BlynkDebug.cpp` from there which was resulting in multiple definition errors at link time.

The above is an excerpt from a how-to I posted to the Blynk community but I think this has all of the relevant information.
> 1 votes

---
Tags: arduino-ide, library, core-libraries, eclipse, sloeber
---


# Question
Title: Syncing/taking external clock for SPI on Arduino Due
I have an Arduino Due with a SAM3X8E chip and am trying to read SPI data from an external source that is communicating in SPI. I was able to get data by identifying specific bytes that are identifiers but realized that the clock for my board is not synced with the source coming in. I print out the bytes in hexadecimal format (08 00 FF AB etc) and each message is 128 bytes long.

To be clear, the source is an SPI master that is sending out data on its own MOSI line, but I am currently treating my board as a master as well since I do not know how to do Slave mode on Due. I connect the Slaves MOSI line to my boards MISO line, and just transfer data and read 128 bytes but it would appear that I am not getting the same data. Is there a way for my to take in the clock from the external clock and synchronize my board with that clock to make sure? My source code is below. The only methods I can think of are to either figure out how to implement the board in slave mode (i'm not familiar enough with the registers and how to change this, or read data in slave mode) or synchronize the clocks so my board is reading and sampling the source data correctly.

Could someone check if my thinking is correct, or do I not need to make any changes since the data is in a shift register?

Thanks

---

```
void setup(){
Serial.begin(9600);
SPI.begin();
SPISettings settings (50000000, LSBFIRST, SPI_MODE1); //Sampling rate    50Mhz, source's max speed
SPI.beginTransaction(settings);
}

void loop(){
  int i = 0;
  uint8_t value;
  value = SPI.transfer(0x00);
  while (value != 8){//searching for identifier 0x08
    value = SPI.transfer(0x00);
  }
  SPI.transfer(buffer, 127);//get the rest of the 127 bytes
  Serial.print(value, HEX);
  Serial.print(" ");
  for (i = 0; i < 127; i++){
    if (buffer[i] == 0){
      Serial.print(buffer[i],HEX);
      Serial.print(0, HEX);
    }
    else{
      Serial.print(buffer[i], HEX);
    }
    Serial.print(" ");
  }
  Serial.println("\n");
}

```

# Answer
For your external source to be an SPI bus master, it has to be the only one generating the clock signal. Yet, calling `SPI.transfer()` also generates a clock signal *from the Arduino*; both devices are attempting to drive the clock line simultaneously, hence your problems.

You have to bit-bang this or manipulate the SAM registers yourself to configure it as a slave; the SPI library doesn't support slave mode. In order to bit-bang, you'll have to define your own MOSI, SCK, SS (and MISO, if you'll be writing to the master) pins and do all the sampling yourself with `digitalRead()`; there are no registers to be read from since you aren't using the SAM's SPI peripheral.

Since your SPI mode is MODE 1, it means the clock idle polarity is LOW, and that data is sampled on the falling edge. To bit-bang with `digitalRead()`, it is necessary that the SCK frequency be below 50 kHz (`digitalRead()` takes about 4us), taking overhead into account. You should use direct port manipulation, if you need a higher frequency. If you'll be blocking till you've read data, and assuming that the external source always sends data in byte units, then a basic algorithm:

1. Create a `byte` array to hold all the expected bytes
2. Define a `byte` variable (`curr_byte`, maybe) for holding each byte received
3. Wait till the SS pin goes LOW
4. Clear `curr_byte` to zero
5. Wait till SCK goes HIGH
6. Wait till SCK goes LOW
7. Read the bit on the MOSI line and shift it into `curr_byte`
8. If you've received up to 8 bits so far, save `curr_byte` to the `byte` array; if SS is still LOW, go to step 4, else exit this loop. But if you haven't received a complete byte yet, go to step 5.

After you leave the loop, you can then confirm the bytes you've received with Serial. If the external device can send data with any number of bits, then you should always check the SS line after you shift in a bit, to determine if the Due has been deselected or not i.e. if there are any more incoming bits.
> 3 votes

---
Tags: arduino-due, spi, oscillator-clock, timing
---


# Question
Title: ATTiny85, how to fix overwritten clock pins?
I'm using an ATTiny85 with an external 16MHz clock. I accidentally set pins 3 and 4 to output using pinMode() in a program and uploaded it, and now I'm getting an invalid device signature (the signature is 0) error when I try to upload a sketch.

How can I go about fixing this (if possible)?

I am using an Arduino UNO as ISP, with an external 16MHz clock and capacitors connected to pins 3 and 4, and have rechecked my wire setup multiple times.

# Answer
> 3 votes
Holding the chip in reset while powering it on will ensure that the pins are never reconfigured.

---
Tags: attiny
---


title: Arduino/Genuino not in board list

text:
# Question
Title: Arduino/Genuino not in board list
I've downloaded the Arduino IDE and the Genuino isn't in the list of boards. I'm running Rasbian and used the command line to install.

# Answer
"Genuino" is just a name, not an identifier. Pick the equivalent Arduino board from the list.
> 0 votes

---
Tags: arduino-ide
---


# Question
Title: Why is my potentiometer giving strange reading?
I have a 10kOhm linear Potentiometer. I connected it to analog 0, as in https://www.arduino.cc/en/Tutorial/Potentiometer.

The analogRead() gives a value between 0 and 1023, so I was expecting 0 if the potentiometer is at the lowest position, 1023 if it is at the highest position and 500 somewhere in the middle.

In fact I get ~40 at the lowest position, I get 1021 at the highest position (that's okay, I guess), and I also get 1021 at the middle. 500 is at a 1/4 position, I expected to have ~255 there.

I measured the resistance of the potentiometer. It reads ~200 Ohm at the lowest postion, 10kOhm (as expected) at the highest position and ~5kOhm in the middle, so, exactly as I expected.

So, what did I get wrong?

# Answer
Unfortunately I cannot comment. I can't really think of a reason why your readings are the way they are. Though you did not present to us an image of what potentiometer you are using and how you are really wring it up.

It is possible that your potentiometer is a center tapped type with 4 pins. You could have possibly connected the positive rail to the center tap pin, ground to the side pin and the wiper pin to the Arduino pin so that you would have the result you are getting.

Or potentially, you wired it correctly except for the fact the positive rail you connected to was 10V, but that is really dangerous.

Have you tried measuring the resistance of the potentiometer from one side pin to the other side pin?
> 1 votes

# Answer
It sounds like you have a *log taper* potentiometer rather than a *linear taper* potentiometer. These are used in audio applications.

You can tell the difference by looking at the resistance code. It may be written as:

> 103 B

or

> 10K B

both of which are 10KΩ LOG taper. The letter A or B as a suffix is the taper type. A is linear, and B is logarithmic. That's the "normal" standard, though, but Japan does it differently. They use A for Audio taper (log taper) and B for linear.
> 0 votes

---
Tags: analogread, potentiometer
---


# Question
Title: How to bootload a atmega328-pu using arduino uno?
I have some Atmega328-Pu micro-controllers without boot-loader program. Now I need to burn boot-loader to them all. I have two arduino uno boards having Atmega328 P-Pu micro-controllers on board. I used this circuit  from this page Installing an arduino boot-loader It does not work. The boot-loader is not uploaded. Can you please help me out? If you need any more informations please ask. I have been struggling with this kind of boot-loading techniques for more than a week. I am using arduino IDE 1.0.1 and the board is Arduino uno R3

# Answer
Hi friends thanks for your support. It worked well as it is. No external capacitor I used. I made the connection as shown in the above picture taken from LINK1. I modified the file "boards.txt" and "avrdude.conf" as given in step 4 of LINK2 I first uploaded the ArduinoISP sketch to the board on the left. And then I opened an "EMPTY ARDUINO SKETCH". From that empty sketch I made the following changes Tools-\>Board = "Arduino328" Port = COM4 in my pc Programmer = Arduino as ISP Last step "Burn Bootloader" Ta Da.... It worked. When I posted this question I burnt the boot-loader having the arduino ISP sketch opened. Only thing I changed now is I opened an empty sketch and hit burn from that sketch. Anyway.. thank you all. I dont think I wasted your time. If so, I apologise.
> 1 votes

---
Tags: bootloader, icsp
---


title: MQTT and IR code Raw

text:
# Question
Title: MQTT and IR code Raw
I want to upload/pubish RAW IR Code to MQTT server received through my ESP8266. I have received the following RAW IR code from the Television using the IR receiver sensor:

```
RAW IR CODE = {
  4650,4250, 700,1550, 650,1550, 700,1550, 650,450,
  650,500, 600,500, 600,500, 600,550, 550,1700, 550,
  1650, 600,1650, 550,550, 600,500, 600,550, 550,550,
  600,500, 600,550, 550,1650, 600,550, 550,550, 600,500,
  600,550, 550,550, 600,500, 600,1650, 600,500, 600,1650,
  550,1700, 550,1650, 600,1650, 550,1650, 600,1650, 600
}

```

I want to create a new variable with the following structure:

```
value = RAW IR CODE+";" + "ESP8266-01"(This is the ID of the esp8266)

value =  {
  4650,4250, 700,1550, 650,1550, 700,1550, 650,450, 650,500,
  600,500, 600,500, 600,550, 550,1700, 550,1650, 600,1650, 550,550,
  600,500, 600,550, 550,550, 600,500, 600,550, 550,1650, 600,550,
  550,550, 600,500, 600,550, 550,550, 600,500, 600,1650, 600,500,
  600,1650, 550,1700, 550,1650, 600,1650, 550,1650, 600,1650,
  600
}; ESP8266-01

```

I am unsure: which data type do I need to save the variable value so that it can later be retrieved/subscribed and sent to another IR sender using `irsend.sendRaw`, because I want to split the variable "value" into 2 parts after receiving it, the ID and the RAW code. After getting the RAW code, I want to use the `irsend.sendRaw`(RAW CODE, length of RAW , 38).

Could someone help me?

My attempts:
At first I tried to save it as a string, so that it can be retrieved and separated for `irsend.sendRaw`. However I am unable to compile it.

This is the code which I used to upload:

```
      /*
     * IRremoteESP8266: IRServer - MQTT IR server
     * An IR LED must be connected to ESP8266 RX port (GPIO-3)
     * An IR receiver to GPIO 0
     * used library:
     * https://github.com/markszabo/IRremoteESP8266
     */
    #include <WiFiClient.h>

   #include <ESP8266WiFi.h>

 #include <IRremoteESP8266.h>
    #include <PubSubClient.h>
    int RECV_PIN = 0; //an IR detector/demodulator is connected to GPIO pin 0

    IRrecv irrecv(RECV_PIN);
    decode_results results;

    const char* ssid = "MY-SSID";
    const char* password = "MY-WIFI-PSK";

    const char* topicRaportPrefix = "esp8266/02/info/";
    const char* topicSubscribe = "esp8266/02/sender/#";
    const char* topicPrefix = "esp8266/02/";

    const char* mqtt_server = "10.10.10.10";
    const char* mqtt_user = "mqtt_user";
    const char* mqtt_pass = "mqtt_pass";

    String clientName; // MQTT client name
    char message_buff[100];

     void dump(decode_results *results) {
        const int count = results->rawlen;
          Serial.println(c);
          c++;
          Serial.println("For IR Remote ");
          for (int i = 1; i < count; i++) {

          if ((i % 2) == 1) {
            Serial.print("+");
            Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
        uint16_t  raw_ir_code[count] = results->rawbuf[i]*USECPERTICK;
            client.publish( "esp8266/02/sender", raw_ir_code);

```

After doing the changes proposed, I still get an error in compiling:

> no matching function for call to 'PubSubClient::publish(const char \[18\], uint16\_t \[(int)count\])'

# Answer
> 1 votes
First create a topic and include the ESP8266 ID. Do **not** make it part of the published value.

Second publish the raw data as-is, `uint16_t raw_ir_code[RAW_IR_CODE_MAX]`. The alternative is to convert to string (characters). But if the subscriber has the same architecture (interpretation of data), there is no need to convert it to string and back. Simply publish the raw data as it is.

You will need to cast the `raw_ir_code` vector to the appropriate type for the MQTT publish call.

Cheers!

---
Tags: esp8266, ir
---


# Question
Title: Altering code to run a timer while checking for a data input
I am rather new to the Arduino world and am looking for a way to create my own tipping rain gauge with only one Arduino(micro).

I have had some help from a friend to get a loop that checks for when a switch is closed, which signals that the bucket has tipped and thus "x units" of rain have fallen. The code I have for sensing this is:

```
void loop()
{
  /*
    digitalWrite(4, HIGH);
    delay(500);
    digitalWrite(4, LOW);
    delay(6500);
  */
  int analogValue = digitalRead(8);

  if (analogValue==HIGH)
  {
    Serial.println(count);
    count++;
    delay(250);
  }
}

```

Then I developed a code to count up in 0.5 second intervals so that I could essentially time stamp when the switch from the first loop was closed/activated. The code for the timer is as follows:

```
void loop()
{
  while (ssec < 10)
  {
    Serial.print(hour);
    Serial.print(":");
    Serial.print(minute);
    Serial.print(":");
    Serial.print(sec);
    Serial.print(".");
    Serial.print(ssec);
    //Serial.print(" s");
    //Serial.println();
    ssec += 5;
    delay(500);
    Serial.println();
  }
  if (ssec == 10);
  {
    sec++;
    ssec = 0;
    //Serial.print(sec);
    //Serial.print(".");
    //Serial.print(ssec);
  }
  if (sec == 60)
  {
    minute++;
    sec = 0;
  }
  if (minute == 60)
  {
    hour++;
    minute = 0;
  }
  if (hour == 24)
  {
    Serial.println();
    Serial.print("DAY ");
    Serial.print(day);
    Serial.print(" COMPLETED!");
    Serial.print("Data Points: ");
    //Serial.print(count);
    Serial.println();
    Serial.println();
    hour = 0;
    day++;
  }
}

```

I understand that it is very hard to run these together at the same time due to the fact that I am using a delay function to run the timer.

Are there any ways to essentially run these side by side? Or a library I can use that will run the timer while i have the arduino looking for the switch to close, and I can simply call the timer when I need it?

Thank you for any and all help! :)

# Answer
> 1 votes
What's with the double-spacing? It makes it hard to read.

```
if(ssec==10);

```

That is wrong.

Arduino programming traps, tips and style guide

> I understand that it is very hard to run these together at the same time due to the fact that I am using a delay function to run the timer.

I know StackExchange doesn't like link-only answers, but it is this or copy-and-paste:

How to do multiple things at once ... like cook bacon and eggs

# Answer
> 0 votes
You can find some 3rd party library that does software emulation of threads. For example: ArduinoThread. With the use of such library I successfully developed an app that was switching LEDs on and off and at the same time listened to any data coming from Bluetooth (serial port). It is worth a try.

# Answer
> 0 votes
If you do not need to know the timing when the event occurs with a high resolution, *and do not have anything else you need to do*, you can simply delay in short intervals and check the condition in between them. Of course you will not know when the event occurred more precisely than knowing it happened sometime in the interval since the previous check.

Another approach is to not use the delay mechanism, but rather continually check the input in a loop, and also check the elapsed time so that you can accomplish your periodic events when intervals of time have elapsed. Do be aware of the `millis()` overflow eventuality if taking this approach.

If you had important work to do while waiting, you could accomplish the check with a pin change interrupt, and record a timestamp in the interrupt service routine, but if all you would be doing in the foreground is running a delay, this is inferior to the previous approach. Using an interrupt service routine (or any more elaborate form of threading) also requires care to ensure consistency of data shared between the main and interrupt or alternate thread context.

Ultimately the best solution for an actual real-world embedded application like this is typical to try to have the processor in a low powered sleep mode most of the time. Typically you would have a low power real time clock running, but the processor's high speed clock and associated logic stopped. Your tilt sensor would be wired as an interrupt that the MCU is configured to wake up to normal operation in response to. On wakeup, it would read the clock to accomplish a timestamp, then go back to sleep. You can also use various mechanisms in the real time clock or in the MCU to wake up periodically to announce the passing of time intervals. Wakeup on a small MCU is typically a fairly efficient process - it can be beneficial in terms of net power consumption to go (at least partially) to sleep even for a fraction of a second.

# Answer
> 0 votes
Yes, you can run the two `loop()` function side-by-side with a Multi-tasking Scheduler.

Please see https://github.com/mikaelpatel/Arduino-Scheduler. There are plenty of examples to get you started but basically you call `Scheduler.start()` with `loop()` functions. You will have to give them different names.

The Scheduler will context switch between the `loop()` functions on `yield()` or `delay()`.

Cheers!

---
Tags: c++, arduino-micro, timing
---


# Question
Title: Adruino Yun's Linux environment not working
I was recently given an Arduino Yun board from my university. I am able to upload sketch to the board, and it seems to function properly. However, I am unable to see the Linux booting up. When I want to reset the WLAN, ressing the WLAN RST button does nothing at all, the WLAN LED doesn't even blink or light up. Pressing the YUN RST button also does nothing.

So I did some Googling and found out that I could upload the YunSerialTerminal to the Yun, so I did that. And when I am trying to monitor the Linux boot up from the serial monitor. Nothing is shown. I press the TUN RST button as taught by the Arduino website while monitoring the Serial Monitor, nothing shows. However, the RX button does blink whenever I press enter.

Can anybody help me?

# Answer
You might need to re-flash the operating system. Unfortunately it's not a trivial task.

I had to do something similar with a Dragino shield (like a Yun on a shield) that uses the same OS and core chip. Instructions were scarce and hard to follow, plus I run Linux, so there's even less instructions. I worked it out, though, and wrote a tutorial here.

While that is for Linux and the Dragino shield I am sure the basic principles are the same for the Yun - just make sure you get the right image file for your Yun (don't get the Dragino one I link to).

The main thing is to gain access to the boot manager (dr-boot, or whatever the Yun has), which means setting up a wired (ethernet) network and messing with UDP sockets (using `nc` in Linux - no idea what you can use in Windows).

I'm sure you can find a tutorial for fixing the Yun from Windows (or whatever OS you use) to help you get into the boot manager and upload a new OS image.
> 1 votes

---
Tags: arduino-yun, linux
---


title: PID control arduino

text:
# Question
Title: PID control arduino
I am hooking up an accelerometer to an arduino uno and running it through this pid controller. However the output isnt going to my setpoint. When i move the accelerometer back and forth the data goes to 255 or 0. Any ideas?

Datasheet for accelerometer: https://www.sparkfun.com/datasheets/Components/SMD/adxl335.pdf

I get 336 for the x direction, which is the only direction i'm using, when its set flat on the table, which is my setpoint/desired output.

Note: Is the output the value away from the setpoint or the actual acceleration it calculates through the controller?

```
#include <PID_v1.h>

#define PIN_INPUT A0

//Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Define the aggressive and conservative Tuning Parameters
double aggKp=4, aggKi=0.2, aggKd=1;
double consKp=1, consKi=0.05, consKd=0.25;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);

void setup()
{
  //initialize the variables we're linked to
Serial.begin(9600); //Start a serial session
int  xdata = analogRead(PIN_INPUT);
Input = map(xdata, 0, 1024, 0, 255); //Change read scale to analog out scale
int setPoint = 336;
Setpoint = map(setPoint, 0, 1024, 0, 255); //Change read scale to analog out
//turn the PID on
myPID.SetMode(AUTOMATIC);
}

void loop()
{
int xdata = analogRead(PIN_INPUT);
Input = map(xdata, 0, 1024, 0, 255); //Change read scale to analog out scale

double gap = abs(Setpoint-Input); //distance away from setpoint
if (gap < 10)
{  //we're close to setpoint, use conservative tuning parameters
 myPID.SetTunings(consKp, consKi, consKd);
}
else
{
  //we're far from setpoint, use aggressive tuning parameters
  myPID.SetTunings(aggKp, aggKi, aggKd);
}

myPID.Compute();

Serial.print("Setpoint = ");
Serial.print(Setpoint);
Serial.print(" Input = ");
Serial.print(Input);
Serial.print(" Output = ");
Serial.print(Output);
Serial.print("\n");
// analogWrite(PIN_OUTPUT, Output);
}

```

OUTPUT:

```
Setpoint = 83.00 Input = 87.00 Output = 0.00
Setpoint = 83.00 Input = 81.00 Output = 0.00
Setpoint = 83.00 Input = 64.00 Output = 255.00
Setpoint = 83.00 Input = 64.00 Output = 255.00
Setpoint = 83.00 Input = 68.00 Output = 255.00
Setpoint = 83.00 Input = 79.00 Output = 0.00
Setpoint = 83.00 Input = 91.00 Output = 0.00
Setpoint = 83.00 Input = 96.00 Output = 0.00
Setpoint = 83.00 Input = 99.00 Output = 0.00
Setpoint = 83.00 Input = 88.00 Output = 0.00
Setpoint = 83.00 Input = 68.00 Output = 0.00
Setpoint = 83.00 Input = 58.00 Output = 255.00
Setpoint = 83.00 Input = 64.00 Output = 255.00
Setpoint = 83.00 Input = 78.00 Output = 255.00
Setpoint = 83.00 Input = 95.00 Output = 0.00
Setpoint = 83.00 Input = 97.00 Output = 0.00
Setpoint = 83.00 Input = 95.00 Output = 0.00

```

# Answer
Ensure that your period for the PID execution routine is reasonable for your system. I generally like to execute my PID loops at 5 to 20 times the system impulse response. For instance, with a motor, I will apply 100% power from a standstill and measure the time it takes to get up to 90% of final value. I will then multiply that time by 0.1 and start there. If it takes 1s, then I will start my PID loop executing every 0.1s. Sometimes I adjust this up or down, depending on system requirements, but this is not a bad starting point.

If your PID loop is executing too fast, then it will respond too quickly to actually have a real-world effect on the system. The output will tend to oscillate. Motors vibrate and make more noise.... different systems respond differently, but you see the point.

1. Start at `kp = 0`,`ki = 0`, `kd = 0`
2. Increase `kp` until you get a reasonable response. Don't expect your error to go to 0. As long as you aren't oscillating, that should be good.
3. Very slowly increase `ki`until you are happy.
4. You should probably keep `kd` to 0. It is for advanced usage and PI loops will meet the vast majority of application requirements.

This is a very crude guide. There are better on google, but this should get you started. PID loops are fun, especially with motors. Enjoy!
> 2 votes

---
Tags: accelerometer, pid
---


# Question
Title: Accessing configuration registers of OV7670 cam on i2c
I am a new user of Aurdino and want to interface OV7670 camera with aurdino uno which uses i2c mode of communication.I want to check the configuration of the device control registers and set them as per requirement. In this case, OV7670 is my slave device.
How can I access a particular register inside the slave device?(The parameters for commands like wire.begin() etc., include slave address but not the address of the registers inside a slave device.)

# Answer
To communicate with the OV7670:

* SIOC =\> SCL (pulled up to 3.3V)
* SIOD =\> SDA (pulled up to 3.3V)
* RESET =\> 3.3V
* PWDN =\> GND
* XCLK =\> Clock signal is necessary (at least 10 Mhz)
* Vcc =\> 3.3V
* GND =\> GND

The XCLK needs at least 10 MHz according to the datasheet, but from other accounts, it seems that's not a hard limit. You can get a 4 MHz clock from the Uno using its `timer0`; check out this post on how to do it. After this, you can write a small sketch along the lines of:

```
Wire.begin();
Wire.beginTransmission(0x21);
Wire.write(0x12);  // software reset
Wire.write(0x80);
Wire.endTransmission();
delay(500); // wait for reset to complete

Wire.beginTransmission(0x21);
Wire.write(0x01);  // u now read from reg 0x01
Wire.endTransmission();
Wire.requestFrom(0x21, 1);
while (Wire.available() == 0);  //block till u get something
while (Wire.available())
  Serial.println(Wire.read(), HEX);

```

You can place everything in `setup()` after including the `Wire` library and setting up the XCLK clock signal. If all goes well, `80` should be printed in the serial monitor and this will confirm that you're now communicating over the SCCB with the camera.

I should warn you that while others have used the Uno to grab images from the OV7670, the process is moderately complex, especially for a beginner, and it's not what the Uno is intended for; all you'll be able to do is grab frames and pass them on to some TFT screen or your PC and even then you'll get at most 5 fps, I think, with QVGA or QCIF output. You'd be better off with some ARM dev board, one running Linux perhaps. Good luck.
> 3 votes

# Answer
Take a look at the datasheet - that will show you the correct waveforms / transactions for this. However, something like this should work (assuming 8-bit addresses and registers)

```
// reading

Wire.beginTransmission(address);
Wire.write(reg); // set address to read from our requested register
Wire.endTransmission(false); // repeated start
Wire.requestFrom(address,(unsigned char)1);  // just a single byte
if(Wire.endTransmission()!=0){
    // put error code here
}
readValue = Wire.read();

// writing

Wire.beginTransmission(address);
Wire.write(reg);
Wire.write(value);
if(Wire.endTransmission()!=0){
    // put error code here
}

```
> 2 votes

---
Tags: i2c
---


# Question
Title: Powering 3 servo motors and Arduino Uno with one 9 V battery
I wish to power an Arduino Uno board AND 3 servo motors using a single 9 V battery.
I have connected the positive terminal of the 9 V battery to the VIN pin. The negative terminal of the battery is connected to the GND pin immediately following. This, I believe, powers the Arduino Uno board.
Next, I have connected the power wires of all 3 servo motors to the 5 V pin on the Arduino board ( using jumper wires and a breadboard). Similarly, all the servo ground wires have been connected to the second GND pin in the 'POWER' set of pins on the Arduino Uno board. And finally, the 3 signal wires from the servos have been connected to the three PWM pins on the 'DIGITAL' row, exactly pins 9, 10 and 11.
THE SERVOS ARE NOT OPERATED SIMULTANEOUSLY, THEY ARE BEING OPERATED ONE-BY-ONE (but the load is still attached to each of them, a couple of grams is all).
Since the servo motors operate between 4.8 V - 6 V, and I don't have any spare AA batteries to approximate a 6 V battery, I thought this could solve the problem.
My question is, does this pose any problems for the board or devices, does this draw a higher current? Will it damage the Arduino Uno board or the servo motors or any of the individual pins?
Please let me know soon, thank you very much.

# Answer
> 1 votes
I don't think anything should get damaged; the regulator is rated for 1A, and even beefy servos don't draw more than 200mA when moving against heavy load. The problem is that your battery won't last long. Even the heavy-duty Li primary 9V batteries are under 1000mAh, and the actual capacity is heavily dependent on the discharge rate.

Why can't you use a rechargeable Li-ion pack with an appropriate step-up or step-down converter?

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


title: Sketch not running as expected

text:
# Question
Title: Sketch not running as expected
I wrote this sketch along with an HC - SR 04 Ultrasonic transducer and a DC motor. Whenever the HC-SR 04 reads any distance less than 15 cm, the motor stops, otherwise it keeps running.

The problem is whenever I upload the sketch, the motor runs for a short while and stops. Then when I open my serial monitor, the motor runs until an object crosses the 15 cm threshold and stops right after the limit is crossed. But when I again put the object outside of the 15 cm range, the motor should start running again, but it doesn't.

I am using a this motor driver and a simple DC motor(12V).
Here's the code-

```
int trigPin1 = A0;
int echoPin1 = A1;
int distance1 = 0;
int E1 = 10;
int brake1 = 7;

void setup() {
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(brake1, OUTPUT);
  pinMode (E1, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  analogWrite(E1, 153);
  distance1 = getDistance(trigPin1, echoPin1);
  printDistance(1, distance1);
  delay(250);
  if(distance1 <=15){
    digitalWrite(brake1, HIGH);
  }
  else{
    analogWrite(E1, 153);
  }

}

int getDistance (int initPin, int echoPin) {
  digitalWrite(initPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(initPin, LOW);
  long pulseTime = pulseIn(echoPin, HIGH);
  int distance = pulseTime / 58.2;
  return distance;
}

void printDistance(int id, int dist) {

  Serial.print(id);
  if (dist >= 120 || dist <= 0 ) {
  Serial.println(" Out of range");
  }
  else{
   Serial.print("\t");
   Serial.print(dist);
   Serial.println(" cm");
}
}

```

What mistake am I doing? Moreover I am currently running it with one motor, I'll add another later on along with more sensors, so the motors are controlled by the left or right sensor. How do I make my code work with them?

Thanks...

# Answer
It was too damn simple...

I just had to add a line inside the else block in the loop function.

```
digitalWrite(brake1, LOW);

```

This was happening because the first time the threshold limit was crossed the `brake1` pin was left `HIGH` and was never set to `LOW` again, which caused a permanent brake in the motor.

I'm too damn stupid. But I still don't have any idea how will I use this code with multiple sensors and motors.
> 0 votes

---
Tags: arduino-uno, serial, motor, sketch, hc-sr04
---