# Question
Title: Ensuring specific frequency at specific time?
I, at the moment am trying to come up with a simple way where I can program an Arduino to provide a step signal with a given frequency, at a specific time.

The frequency has to be ramped up, and within a time duration of 10 seconds shall the frequency go from 0 Hz to 48000 Hz.

How do I ensure both the specific time of when the frequency occurs, and the specific frequency of the step signal?

Signal has to be used to driver a stepper motor.

**Edit: Code current:**

So i currently wrote this piece of code:

```
int timestep = 1;
while(1)
{
  unsigned long startTime = millis()
  while(startTime != 500)
  {
    digitalWrite(step_pin,LOW);
    delayMicroseconds(208/timestep);
    digitalWrite(step_pin,HIGH);
    delayMicroseconds(208/timestep);
  }

  timestep++;
}

```

For each 0.5s should the frequency be doubled.. would this work?

**Edit 2.0:**

I made an new implementation using @EdgarBonet 's answer, and with the help of Timer1 library that arduino provide (I guess?).

.h file

```
#ifndef stepper_motor_h
#define stepper_motor_h

#include "Arduino.h"
#include <TimerOne.h>

#define step_pin  13
#define dir_pin   12
#define en_pin    11
#define max_step  200

 class stepper_motor
{
  public:
    stepper_motor();
    void step_pwm();
    static void callback();
    TimerOne timer1;
  private:
    //uint32_t period;
    bool alive_bool;
    //int step_count;
    bool position_bool;
};

#endif

```

.cpp file

```
#include "stepper_motor.h"

int step_count = 0;
uint32_t period = 40825UL << 16; // 20412,5 us fixed point arithmetic time = 0

stepper_motor::stepper_motor()
{
  //pinMode(BUILTIN_LED,OUTPUT);
  pinMode(step_pin, OUTPUT);
  pinMode(dir_pin, OUTPUT);
  pinMode(en_pin, OUTPUT);
  alive_bool = true;
  position_bool = false;
  step_count = 0;

}

static void stepper_motor::callback()
{
  if (step_count < 240)
  {
    uint32_t new_period = sqrt(2 * step_count / 4.8);
    period -= new_period;
    step_count++;
  }
  else
  {
    return;
  }
}

void stepper_motor::step_pwm()
{

  digitalWrite(en_pin, HIGH);

  delay(0.005);

  digitalWrite(dir_pin, HIGH);
  //LOW  - Move towards the sensor
  //HIGH -  Move away from the sensor

  delay(0.005);

  timer1.initialize(period);
  timer1.attachInterrupt(callback);
  timer1.pwm(step_pin, 512);

}

```

# Answer
> 3 votes
Generating a linear frequency ramp with accurate timings is not an easy task. I am providing here only a partial answer, where I first go through the math of the problem, then give some ideas for the implementation.

## The math

We are dealing with a frequency-modulated signal, with the frequency ramping linearly from *f* = 0 at *t* = 0 up to a maximum *f* = *f*M at *t* = *t*M. Specifically, we have *f*M = 48 kHz and *t*M = 10 s. Then, the instantaneous frequency is

*f*(*t*) = *a* *t*

where *a* = *f*M/*t*M = 4.8 kHz/s is the “acceleration” of the pulsed signal.

Let's define the “integrated frequency” as

*n*(*t*) = ∫ *f*(*t*) dt = *a* *t*²/2

This quantity can be interpreted as the number of cycles completed at time *t*, except that it is a continuous variable. The first cycle starts when *n* = 0 and ends when *n* = 1, the next cycle starts when *n* = 1 and ends when *n* = 2, and so on. The output signal would be high when the fractional part of *n* is between 0.25 and 0.75 (or maybe between 0 and 0.5, depending on your choice of initial phase).

From here, we can calculate at what time each cycle should start:

*t*(*n*) = √(2 *n*/*a*)

and, by successive differences, the length of each cycle:

```
n       0     1       2       3      ... 239,998    239,999    240,000
t       0     20,412  28,868  35,355 ... 9,999,958  9,999,979  10,000,000
length   20,412   8,455   6,488      ...        20.833     20.833
diff          -11,957 -1,967  -1,018 ...            -0.000043
approx        +81,650 -1,408  -913   ...            -0.000043

```

In the table above, all times are in microseconds. The lines are:

* *t*: time
* length: length of one cycle
* diff: difference between lengths of successive cycles
* approx: approximated formula for that difference

The columns are staggered because each cycles spans the duration between two successive values of *t*, and duration differences are computed between successive cycles. The approximated formula is based on the Taylor expansion:

T(*n*+1) − T(*n*) ≈ dT/dn + 1/2 d²T/dn² = −aT³(1 − 3/2 aT²)

where T = 1/*f*, the instantaneous period, approximates the length of one cycle. The approximation is not good for the very first cycles, but it converges pretty fast to the correct value.

## Implementation

I did not write an implementation, so I am giving here only some ideas on how to do it.

I would use Timer 1 of the Arduino Uno, in one of the modes that allows frequency-modulation, i.e. a PWM mode where the counter TOP is set by a register (mode 8, 9, 10, 11, 14 or 15). I would set the prescaler to 8 in order to allow for the maximum required period length. The period resolution would then be:

* 8 CPU cycles = 0.5 µs in modes 14 or 15 (fast PWM)
* 16 CPU cyels = 1 µs in the other modes

It could be noted that single-cycle resolution is possible with the prescaler set to 1, but the first 5 cycles are too long for this setting. Maybe the prescaler could be changed after the fifth cycle, but it would be tricky to do so without any glitch.

The timer overflow interrupt would fire at the end of each cycle, and it's ISR (namely `TIMER1_OVF_vect`) would be responsible for updating the timer period in order to make the next cycle shorter than the one just elapsed. It would do something like

```
period -= delta(period);

```

The period should be computed with 32-bit arithmetic, because the changes get tiny by the end of the ramp. Only the 16 most significant bits of the computed period would actually be written to the timer register. The `delta()` function should be inlined and fast. I may try the approximation from the previous section implemented in fixed-point. Or maybe just a table lookup using only the most significant bits of the period as an index, with the table in PROGMEM.

For details on how to actually program the timer, see the datasheet of the ATmega328P, section 16.

---

**Update**: The following algorithm seems to work well. At least in simulation, I did not put it inside an ISR. It assumes fast PWM, i.e. a 0.5 µs timer resolution. It remembers the current value of delta and divides it by 2 each time the period falls below some threshold. The computed *f*(*t*) is almost as smooth as you can expect given the limited resolution of the timer.

```
uint32_t period = 40825UL << 16;  // 1st cycle is 20412.5 us
void update_period()  // should be in ISR(TIMER1_OVF_vect)
{
    static const uint16_t thresholds[] = {
            17633, 13309, 10229, 7954, 6230, 4905, 3873, 3063,
            2426, 1923, 1525, 1211, 960, 762, 605, 480, 381,
            302, 240, 190, 151, 120, 95, 76, 60, 48};
    static uint16_t threshold = 29000;
    static uint8_t index = 0;
    static uint32_t delta = 6UL << 27;

    uint16_t period_h = period >> 16;
    if (period_h <= 42) return;  // final frequency achieved
    if (period_h < threshold) {
        threshold = thresholds[index++];
        delta >>= 1;
    }
    period -= delta;
    // set the timer period register to (period >> 16) - 1.
}

```

# Answer
> 3 votes
As mentioned in comments and other answers, using timer 1 for hardware-timed bit toggling is likely to produce better results than code using delays based on calls like `delayMicroseconds()`, primarily because of overhead causing poor resolution or jitter.

Using timer 1 in a PWM mode offers an advantage: loading of the OCR1A register is double buffered in PWM modes. This makes it possible to smoothly transition from one frequency to another without glitches due to setup delays. The code shown below (program `freqSweep.ino`) illustrates one way of steadily ramping the period of a waveform. The *initial count, delta count*, and *number of steps* parameters `ic, dc, ns` also are double buffered, with the first set loaded via `rampInit ()`, and new sets loaded opportunely from time to time via `rampNext ()`.

In operation, the ramper causes timer 1 to produce a waveform with half cycles of lengths `ic, ic+dc, ic+2dc, ... ic+(ns-1)dc`. That is, it generates `ns` steps of varying lengths, using timer 1 interrupts to trigger its execution in the background. While the ISR produces a ramp of cycles, the user's `loop()` code can be computing parameters for the next ramp. Note, if `dc>0`, periods grow larger so the frequency ramp descends. If `dc<0`, periods grow smaller so the frequency ramp ascends. If `dc==0`, the ramp is flat. Note, `ic` and `dc` are 32-bit fixed-point numbers, with 16 binary places. Thus, while hardware only generates time intervals with integral numbers of cycles, the ramper software works with fractional values, so `dc` can have values like 0.5, 3.375, .076171875 (39/512) etc.

By generating a seamless series of small ramps, one can accurately approximate larger patterns of frequency ramps. For example, to generate a frequency-linear ramp from say 100 Hz up to 48 KHz in 10 seconds, one might divide that time into 100 parts. If f(t) denotes the frequency desired at time t, one would then (for each 0.1 second time step) compute half-periods p and q corresponding to frequencies f(t) and f(t+0.1). About n = 0.1\*f(t+0.05) cycles are available in 0.1 seconds for frequencies between f(t) and f(t+0.1), or about `ns` = 2\*n half-cycles. Choose `dc = (q-p)/ns` \[using 32:16 fixed point arithmetic, and noting that `dc` can be negative\] to smoothly ramp from frequency f(t) to f(t+0.1) in `ns` steps that take about 0.1 seconds total. 0.1 seconds, or 100 ms, is enough time to calculate and load a new set of parameters. See program comments (under the heading *General form of use of ramper*) re computing parameters.

Here is the example program:

```
// Sweep a frequency, on dig. pin 7, PD7 - jw 27 Sep 2016
#include <Streaming.h>

enum { outpin=7, mOutpin=1<<7 }; // Arduino dig. pin# & its bit mask
void setup() {
  pinMode(outpin, OUTPUT);
}

long RAMdcl, RAMdcn;    // dc is signed to allow ramps up or down
unsigned long RAMicl, RAMicn;
unsigned int RAMnsl, RAMnsn;
volatile unsigned int RAMrampsDone; // Number of ramps done so far
volatile byte RAMsendPars;  // Flag is 1 when ok to send params

void rampInit(unsigned long ic0, unsigned long dc0, unsigned long ns0, byte clockSource) {
  /* clockSource should be a 3-bit number, from 0 to 5:
   ..Bits.. ....Effect....   [See Table 16-5, p. 134 in specs]
    0 0 0   No clock source (Timer/Counter stopped).
    0 0 1   IOclock / 1    (No prescaling)
    0 1 0   IOclock / 8    (From prescaler)
    0 1 1   IOclock / 64   (From prescaler)
    1 0 0   IOclock / 256  (From prescaler)
    1 0 1   IOclock / 1024 (From prescaler)
  */
  TIMSK1 = 0;           // Turn off timer 1 interrupts
  // ic and dc (initial count and delta count) values
  // are 32:16 fixed point values; ie with 16 binary places.
  RAMicl = RAMicn = ic0;
  RAMdcl = RAMdcn = dc0;    // Set initial param values
  RAMnsl = RAMnsn = ns0;
  RAMrampsDone = 0;     // No ramps done yet
  RAMsendPars = 1;      // Next param set can load

    // Set timer 1 to Fast Pwm mode with OC1A (dig pin 9) toggling
  TCNT1 = 0;           // Zero the counter
  TCCR1A = 1<<WGM11 | 1<<WGM10; // for Fast Pwm with TOP from OCR1A
  OCR1A = (uint16_t)(RAMicl >> 16); // Initial TOP = integer part of icl
  TCCR1B = 1<<WGM13 | 1<<WGM12 | // for Fast Pwm with TOP from OCR1A
           clockSource;    // Start timer 1 with selected prescale
  TIMSK1 = 1<<TOIE1;       // Enable timer 1 overflow interrupt at TOP
}

// timer 1 overflow interrupt handler
ISR(TIMER1_OVF_vect) {
  OCR1A = (uint16_t)(RAMicl >> 16); // Update TOP with integer part of ic
  PIND = mOutpin;         // Toggle the output pin, eg dig pin 7, PD7
  // (Output bits toggle when a 1 is written to their input port bit)

  RAMicl += (unsigned long)RAMdcl;  // dc is signed but we need bare bits
  --RAMnsl;
  if (!RAMnsl) {        // Go on to next section?
    RAMicl = RAMicn;
    RAMdcl = RAMdcn;        // Set next param values
    RAMnsl = RAMnsn;
    ++RAMrampsDone;     // We are in the last half cycle of section
    RAMsendPars = 1;        // Ready for next param set
  }
}

// rampNext() busy-waits until it can load new param values
void rampNext (unsigned long ic, unsigned long dc, unsigned int ns) {
  while (!RAMsendPars) {}
  RAMsendPars = 0;
  RAMicn = ic;
  RAMdcn = dc;      // Set next param values
  RAMnsn = ns;
}

// rampStop() stops the ramp-processor, right now
void  rampStop() {
  TIMSK1 = 0;           // Turn off timer 1 interrupts
  RAMrampsDone = RAMsendPars = 0;
  digitalWrite(outpin, LOW);    // Turn off output bit
}

/*
  // General form of use of ramper:
  ...
  rampInit(icj, dcj, nsj, scaleBy1);  // Send first param set
  for (byte j=0; j<rampSections; ++j) {
    // Compute next param set ...
    icj = ...
    dcj = ...
    nsj = ...
    // Do other stuff here
    // ...
    // rampNext will busy-wait while sendPars is clear
    rampNext (icj, dcj, nsj);
  }
  // Busy-wait while last ramp finishes
  while (RAMrampsDone <= rampSections) {}
  rampStop();       // Stop the ramp-processor
*/

// Example: Play a sound with 5 ramp parts in loop(), with brief pauses
void loop() {
  enum { scaleBy1=1};
  unsigned long icj, dcj;       // My ramp param calc vars
  unsigned int nsj=1000;        // # of steps per ramp
  icj = ((unsigned long)1600)<<16;  // ic = initial count
  dcj = ((unsigned long)1)<<16;     // dc = step size
  nsj = 5000;
  rampInit (icj*3, dcj/2, nsj, scaleBy1);
  rampNext (icj, dcj, nsj/3);
  rampNext (icj*2, -dcj, nsj/2);
  rampNext (icj*2, -dcj, nsj/2);
  rampNext (icj, dcj, nsj/3);
  while (RAMrampsDone < 5) {};
  rampStop();           // Stop the ramp-processor
  delay(2500);          // silence-separator
}

```

# Answer
> 0 votes
There are three points:

1. Try to work in the terms of pulse duration. 48 000 Hz will give say 167 ticks for 8 MHz clock (83 ticks for HIGH level on active pin and 83 - LOW). Division on fly is very time consuming, so better to use period instead of frequency. 0 - switch the timer off. 1 Hz - 8 000 000 ticks (4000000 for High and 4000000 for LOW).
2. As I understand the stepper motor will have to drive some load, so acceleration needed depends not only on the parameters of motor itself but on the total mechanical system. So, to calculate needed data from the scratch will be rather difficult and inaccurate. Better try to calibrate the system. Tat will take a piece of job but will be more accurate.
3. You do not need to make smooth decrease of period but you can use several predefined steps. This will give you two arrays `t[i]` for period to be set in timer and `d[i]` \- number of steps, done with this period. The total time for the given period will be `d[i]*t[i]`. The total time of acceleration then will be the simple sum of time slices in the sequence `i` from 0 to max. So you can get it rather accurately.

It will take at least two timers - one for the period setting, other for counting periods in a time slice. After one time slice is finished you just increment array index and load new data in timers. Calibration will take to define best real data for array `t[]` and `d[]`.

If you will hold in `t[]` half-periods, then you need to double values in `d[]`, or taking values from `t[]` you can divide them by 2 (it's a simple shift so it takes little time) for one half-period is HIGH and next is LOW. The decision is up to you.

---
Tags: arduino-uno, stepper, frequency, timing
---


# Question
Title: Read speed between two ultrasonic sensors
I'm new to Arduino and in need of help for this small project.

I'm trying to build an Arduino code that reads the speed of an object passing through two ultrasonic sensors. The plan now is to ping the first ultrasonic sensor once an object passes. The second sensor will then activate and wait for the object to pass by. The time it takes to reach the second sensor will be given into the equation.

Speed will be calculated by the distance between the two ultrasonic sensors divided by the time for the object to reach the second sensor. I would like to display the speed if possible on my computer screen.

Here is my code so far. Any help will be appreciated:

```
int trig1 = 3; //Trig 1
int trig2 = 4; //Trig 2
int echo1 = 5; //echo1
int echo2 = 6; //echo2
int ECHO1;
int ECHO2;
double first_time;
double second_time;
double final_time;
double speed;

void setup()
{
   pinMode(trig1, OUTPUT);  //sets the digital pin 3 as output
   pinMode(trig2, OUTPUT);  //sets the digital pin 4 as output
   pinMode(echo1, INPUT);  //sets the digital pin 5 as input
   pinMode(echo2, INPUT);  //sets the digital pin 6 as input
}

void loop()
{
  ECHO1 = digitalRead(echo1);

  while (ECHO1 == 0)
  {
    digitalWrite(trig1,HIGH);
    delay(100);
    digitalWrite(trig1,LOW);
    ECHO1 = digitalRead(echo1);
  }

  first_time = time();

  ECHO2 = digitalRead(echo2);

  while (ECHO2 == 0)
  {
    digitalWrite(trig2,HIGH);
    delay(100);
    digitalWrite(trig2,LOW);
    ECHO2 = digitalRead(echo2);
  }

  second_time = time();

  final_time = second_time - first_time;

}

```

# Answer
> 2 votes
There are several issues with these ultrasonic modules and your code:

* How fast are these objects moving? If you don't have any reflection, it'll take almost 20ms for one measure. So precision will be low.
* What if the object is moving in oposite direction?
* What if the object stucked between?

and so on.

Anyway Laser interrupter circuit (or similar) would be much more suitable for this job.

Or if you want to use ultrasonic, you can use Doppler effect. But it's not possible with those `PING)))` modules (or clones).

# Answer
> 1 votes
If I understand correctly you are using the ultrasonic sensors like light barriers.

Measuring speed with ultrasonic would be done by sending the sound towards the object of interest and measuring the time for the reflected sound. The traveling speed of sound in air is somehow a constant. You will get the distance of the object * 2. With two measurements in a defined time period you are able to determine the speed of the object.

When using light barriers (infrared) I would try to trigger interrupts with the photo diodes and measure the time between the triggerings like you described. If hooked to the same interrupt the direction of the object should be irrelevant. If two interrupts are used even the direction is known.

---
Tags: sensors
---


# Question
Title: Function only taking the first 4 elements of a character array
I'm writing a function for my arduino program that takes a character array of any size and will mark all the characters that aren't in the alphabet by changing their value to '1'.

I have a switch variable (foundSym) that will turn to 0 if the character IS part of the alphabet. At the end of my first for loop if the switch never changed, that means the character was NOT a letter and will be marked. Note I also don't want to mark space characters (' ').

The issue I have is every array I pass into the function will only have a length of 4, no matter the size.

I've checked the length of each array before it enters the function and when it is in the function, everytime the size gets shortened to 4 elements!

Here is my function...what am I doing wrong??

```
void markSymbols(char str[]){
  for(int i = 0; i<sizeof(str); i++){
    int foundSym = 1;
    for (int j = 0; j<26; j++){
      if (str[i] == alphabet[j]) {
        foundSym = 0;
        break;
        }
    }
    if (str[i] == ' ') foundSym = 0;
    if (foundSym == 1) str[i] = '1';
  }

}

```

# Answer
You are passing a pointer (`char str[]`) and the `sizeof` operator is giving you the size of that pointer (4 bytes it appears in your case - on some Arduinos it would be 2 bytes).

The length of a character array is found by using `strlen` \- assuming the string is terminated by a null (0x00).
> 2 votes

# Answer
I think this will do the same as your code. I understand it doesn't directly answer the question, but I hope it shows you an alternative way of doing it using the library functions. But they are very difficult to find unless you know about them already.

```
void markSymbols(char* str)
{
  for(int i = 0; i < strlen(str); i++)
  {
    if (! ((isAlpha(str[i]) || (str[i] == ' ')))
    {  // If the character is not an letter of the alphabet (upper and lower case) and it is not a space (char 32).
        str[i] = '1';
     }
  }
}

```
> 0 votes

---
Tags: arduino-ide, array, debug
---


# Question
Title: I want to log GPS coordinates using my Arduino and other sensors
I want to log GPS coordinates using my Arduino and other sensors. The difficulty is that I will be in forested conditions. Would it be better to hardwire a gps device to the Arduino or to bluetooth an external device (a much more accurate, Trimble device that I know will give me the accuracy I need)? Can such devices pair to a bluetooth receiver that would hardwire to my Arduino, or do I need an intermediate device like my iPhone?

# Answer
> 1 votes
The GPS receiver I've always used is the Adafruit Ultimate GPS:

https://www.adafruit.com/products/746?gclid=CjwKEAjwoPG8BRCSi5uu6d6N5WcSJABHzD8FmldH1vIvTt8h-S-948CJmDR6fR\_BcF20UZMS4I-AEBoCt9Tw\_wcB

It comes with a spot for you to plug in an external antenna (with an adapter), so you can get more precision and presumably be able to receive data much more accurately in places like forests. However, I'm not sure of this, so an external device may be the way to go. Bluetooth would be possible, but it can be a little difficult to set up with Arduino if you lack the experience, so if you can I'd go with a wired connection (with an RS232 or other).

# Answer
> 1 votes
What's more important, GPS accuracy or GPS yield?

Normally it's a trade off between the two. Under difficult conditions such as lots of trees a high accuracy GPS may simply stop outputting locations because it can't guarantee the accuracy, it depends upon the target market for the GPS.e.g. a survey system will be very conservative, survey people don't like getting bad data. A cheaper lower accuracy GPS won't care and will still output a position no matter how dubious the signals are. I've seen $100 GPS units output a position when a $20,000 Trimble system refuses to.

The GPS should support NMEA output over bluetooth serial port protocol which would then work fine for a direct connection to your device however you may need to change the receiver settings to enable it, the default is likely to be outputting Trimbles binary TSIP format over the bluetooth.

# Answer
> 0 votes
If the Trimble has a serial output then you could connect via that.

If the Trimble supports the same Bluetooth spec as your receiver, then there is no reason why you shouldn't be able to connect them directly. You will need to find out if the Trimble is a Master, Slave or both and buy the appropriate receiver for you Arduino.

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


title: use only one input pin in L293?

text:
# Question
Title: use only one input pin in L293?
I have an L293 motor driver chip, in which the two input pins are used in order to turn the motor forward or reverse, or stop it. So I wοnder if I could use only one input pin, ...

**For running mode:** Since `Input1` should be the opposite of `Input2`, why not sending a signal from `Input1` to `Input2` via a hex inverter?

**For stop mode:** why not just sending `analogWtite(Enable, 0)` to Enable pin?

That way I could save an extra Output pin from Arduino. Do I lack some important detail?

My question goes the same for all the L29x family.

# Answer
> 1 votes
A H-Bridge has 3 modes of operation *in addition to disabled*. The **EN**able pin, when driven low, disconnects the power and stops the motor from being actively driven it is true. However that is not the same as the STOP mode of the H-Bridge.

The logical internal connections in the H-Bridge for the three modes are like this:

When in STOP mode the motor is effectively short circuited and the power supply is disconnected. When the motor is spinning and not being actively driven it is generating power. By feeding that power into a load you increase the load on the motor itself, slowing it down. The bigger the electrical load the slower the motor will go - and you can't get bigger than a dead short. So this mode effectively stops the motor in its tracks. It puts the breaks on.

Conversely, if you just disconnect the power, there is nothing much to stop the motor spinning, so it will keep going depending on the amount of friction, wind resistance, inertia, momentum, etc.

If you are happy with that kind of operation then yes, your method will work fine, since you will have access to forward, reverse, and a way of controlling the power to the motor. You just won't be able to apply the brakes, and you will have to either rely on the natural slow-down of whatever you are driving, or do something clever involving using just enough reverse to stop the motor before cutting the power.

---
Tags: motor, arduino-motor-shield
---


# Question
Title: Arduino uno + cnc shield v3 + Stepper Motor Driver A4988 + AccelStepper?
I successfully run the AccelStepper examples on an Arduino Mega with a RAMPS 1.4 shield, two A4988 stepper motor drivers and two 17HS16-0284S stepper motors.

I used 3 jumpers on the RAMPS to set the microstep resolution to 1/16.

I used this code inspired by the Polargraph Server for Polargraph:

```
#include <AccelStepper.h>

/*
// for the Arduino Uno + CNC shield V3

#define MOTOR_A_ENABLE_PIN 8
#define MOTOR_A_STEP_PIN 2
#define MOTOR_A_DIR_PIN 5

#define MOTOR_B_ENABLE_PIN 8
#define MOTOR_B_STEP_PIN 3
#define MOTOR_B_DIR_PIN 6
*/

// for the Arduino Mega + RAMPS 1.4
#define MOTOR_A_ENABLE_PIN 30
#define MOTOR_A_STEP_PIN 36
#define MOTOR_A_DIR_PIN 34

#define MOTOR_B_ENABLE_PIN 56
#define MOTOR_B_STEP_PIN 60
#define MOTOR_B_DIR_PIN 61

AccelStepper motorA(1, MOTOR_A_STEP_PIN, MOTOR_A_DIR_PIN);
AccelStepper motorB(1, MOTOR_B_STEP_PIN, MOTOR_B_DIR_PIN);

void setup()
{
  motorA.setEnablePin(MOTOR_A_ENABLE_PIN);
  motorA.setPinsInverted(false, false, true);
  motorB.setEnablePin(MOTOR_B_ENABLE_PIN);
  motorB.setPinsInverted(false, false, true);

  motorA.setAcceleration(100);
  motorA.move(1000);
  //motorA.setMaxSpeed(100);
  //motorA.setSpeed(100);

  motorB.setAcceleration(100);
  motorB.move(1000);
  //motorB.setMaxSpeed(100);
  //motorB.setSpeed(100);

  motorA.enableOutputs();
  motorB.enableOutputs();
}

void loop()
{

  motorA.run();
  motorB.run();

}

```

I tried to use the same code with the same stepper motor drivers and motors on a Arduino Uno and a CNC shield v3 without success (I also used the 3 jumpers to set the microstep resolution to 1/16). The motors do not work and jitter.

What is wrong with my code?

**Bonus questions**: I have taken this setup and code from the Polargraph server but I didn't get how I'm suppose to know how to use `setEnablePin()` and `setPinsInverted()` methods. In fact, I have troubles finding documentation about the CNC shield V3 and the A4988 drivers (I only found this page) to work with AccelStepper.

# Answer
Manually set the ENABLE pins as OUTPUTs, i.e. add in the `setup()` function:

```
pinMode(MOTOR_A_ENABLE_PIN, OUTPUT);
pinMode(MOTOR_B_ENABLE_PIN, OUTPUT);

```
> 3 votes

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


# Question
Title: How to power two stacked motor shields with one 3S Lipo battery (11.1V)?
I have these 2 motor shields: **Adafruit Motor Shield V2** and **Seed Motor Shield V2**.

They are stacked on top of an **Arduino UNO**.

My question is, how can I power 2 of those motor shields with one 3S Lipo battery(**Turnigy 3S 2200mAh 20C**), given that I have 6 identical 4.6-6V DC gearmotors?

Thanks!

# Answer
> 0 votes
You can avoid using a linear voltage regulator. Try using this voltage regulator.

You will get 5 Volts 2 Amp output which should be easy to connect to motor shield's input power ports.

---
Tags: arduino-uno, power, motor, arduino-motor-shield, battery
---


# Question
Title: Performing 32-bit arithmetic on embedded device
I am at the moment working with an Arduino Uno, and am struggling to understand how I perform 32-bit arithmetic using it.

The expression I have to calculate is this: √(2 n/a) in which `n` is an integer and `a` constant float.

I am at all not sure how I should do this so any advise would be helpful here.

# Answer
You wrote:

> the 16 most significant should be accurate.

Are you absolutely sure about that? Please reconsider. It is easy, when asking a question, to ask for something better than what you strictly need... until you realize the cost of fulfilling those expectations.

I have been working recently on a fixed-point implementation of the square root. It is meant to work with numbers in \[0, 1) represented in 0.16 format, i.e. unsigned, 0 bits integer part, 16 bits fractional part. It is based on the polynomial approximation

*x* ≈ 0.1908901 + 1.5392302 *x* − 1.4475870 *x*2 \+ 1.0217778 *x*3 − 0.3043110 *x*4

which is quite good for *x* ∈ \[0.25, 1\]. Numbers in (0, 0.25) can be moved to that interval by successive multiplications by 4, and then dividing the result by 2. In other words, by using the fact that

*x* = √(4 *x*) / 2

The maximum error is 2.56e-4, i.e. 16.8 ulps (units in the last place). It takes 298 CPU cycles to execute in the worst case. Note that, in order to achieve this performance, I had to implement the multiplication in assembly. Otherwise gcc would give me inefficient code.

Here is the code:

```
/*
 * Convert x to a 16-bit fixed point number
 * with n bits after the binary point.
 */
#define FIXED(x, n) ((uint16_t)((float)(x) * (1UL << (n)) + .5))

/*
 * Fixed point multiplication.
 *
 * Multiply two fixed point numbers in unsigned 0.16 format.
 * Returns result in the same format.
 * Rounds to nearest, ties rounded up.
 */
static uint16_t mul_fix_u16(uint16_t x, uint16_t y)
{
    uint16_t result;
#if defined(__AVR_HAVE_MUL__) && defined(__AVR_HAVE_MOVW__)
    /* Optimized ASM version. */
    asm volatile(
        "mul  %B1, %B2\n\t"
        "movw %A0, r0\n\t"
        "ldi  r19, 0x80\n\t"
        "clr  r18\n\t"
        "mul  %A1, %A2\n\t"
        "add  r19, r1\n\t"
        "adc  %A0, r18\n\t"
        "adc  %B0, r18\n\t"
        "mul  %B1, %A2\n\t"
        "add  r19, r0\n\t"
        "adc  %A0, r1\n\t"
        "adc  %B0, r18\n\t"
        "mul  %A1, %B2\n\t"
        "add  r19, r0\n\t"
        "adc  %A0, r1\n\t"
        "adc  %B0, r18\n\t"
        "clr  r1"
        : "=&r" (result)
        : "r" (x), "r" (y)
        : "r18", "r19"
    );
#else
    /* Generic C version. Compiles to inefficient 32 bit code. */
    result = ((uint32_t) x * y + 0x8000) >> 16;
#endif
    return result;
}

/*
 * Fixed point square root.
 * Argument and result in unsigned 0.16 format.
 *
 * If defined(REALLY_ACCURATE):
 *   max error = 7.67e-6
 *   execution time:
 *     937   cycles (worst case)
 *     828.1 cycles (average)
 * else
 *   max error = 2.56e-4
 *   execution time:
 *     298   cycles (worst case)
 *     184.7 cycles (average)
 */
uint16_t sqrt_fix(uint16_t x)
{
    if (x == 0) return 0;
    uint8_t n;
#ifdef REALLY_ACCURATE
    if (x == 0xffff) return 0xffff;
    uint16_t x0 = x;
#endif
    for (n = 0; x < 0x4000; n++) x <<= 2;  // scale the operand
    uint16_t y;
    y = FIXED(0.30435, 15);
    y = FIXED(1.02173, 15) - mul_fix_u16(x, y);
    y = FIXED(1.44754, 15) - mul_fix_u16(x, y);
    y = FIXED(1.53925, 15) - mul_fix_u16(x, y);
    y = FIXED(0.19089, 16) + (mul_fix_u16(x, y) << 1);
    while (n--) y >>= 1;                   // scale the result
#ifdef REALLY_ACCURATE
    y = (y + ((uint32_t)x0 << 16) / y + 1) / 2;  // Babylonian iteration
#endif
    return y;
}

```

If you really need a very accurate result, you can `#define REALLY_ACCURATE`. This will add a single iteration of the Babylonian method, which is essentially Newton's method applied to the square root:

*y* ← (*y* \+ *x*/*y*) / 2

where *y* is our approximation of √*x*. This looks like an easy win: just a division, an addition and a bit shift. And it makes the result practically perfect, with a maximum error of 7.67e-6 (0.502 ulps). But the execution time is increased more than threefold, at 937 cycles in the worst case. This is because the AVR chip has no hardware support for division, and the software alternative provided by the compiler is awfully slow.
> 2 votes

# Answer
Since you are using floats and need more than a quick approximation, I would recommend one of the following methods:

The Babylonian method

Digit-by-Digit

The first is a fast approximation with a known bound on the error, the second will give a known exact result but with more computation steps in general. Both obviously round to the precision of your data type.

EDIT:

For really fast computations check out the crazy fast inverse square root

of the first algorithm on this page. Disclaimer: I have never had to implement a square root like this, but I've done others like Sine(x).

EDIT 2: @pipe made a good point. If you just want it to work, use sqrt(x)
> 1 votes

---
Tags: arduino-uno, mathematics
---


title: Arduino Uno with Camera and LCD

text:
# Question
Title: Arduino Uno with Camera and LCD
I would like to ask you if I can display real time view from Camera in Arduino Uno with LCD.

**I have that components:**

* Camera OV7670 VGA 0.3 MPX
* LCD TFT 2.4 SPI ILI9341
* Arduino Uno R3

On a website: arducam.com there are used another components. I bought that parts because in a documentation in auction was that is compatible with Arduino. I see that in Arduino UNO is not so much pins.

Could somebody help me to resolve this challenge?

Regards

# Answer
No, this is not possible.

The camera outputs a JPEG image. To display that on the TFT screen it is necessary to decompress that JPEG image and send the raw 16-bit (RGB565) colour information to the screen.

The Arduino doesn't have enough memory to do the job.

I wrote an absolute minimal JPEG decompressor a while back. It uses the absolute minimum memory possible (it operates on one macroblock at a time), and still requires around 100KB. That's 50x more than the Arduino Uno has.

Also on a 200MHz, 32-bit chip with FPU it takes about a minute to decompress a 320x240 pixel image. I can't even begin to imagine how many days that would take on a little Arduino Uno even if it did have enough memory to do the job...

As has been suggested, you need a more powerful board. And if you're going that route you may as well drop the useless OV7670 and get a Raspberry Pi with a proper Pi Camera module (or at least a USB webcam).
> 2 votes

---
Tags: lcd
---


# Question
Title: How can i do something like multi threathing in arduino?
I am checking for ways to implement multi threathing in Arduino, I have also tried using the library `TimerOne` but it doesn't seem to work, what I'm trying to make is an Arduino application then, every time a certain amount of time passes, it pops an item from the stack, and between these times, the application allows me to add items to the stack, both processes working in parallel of course.

The items popped and pushed are numbers.

I have already tried some other questions, but their solutions don't work, especially one that seems very useful, but for some reason doesn't work, I'm speaking about the one of the `TimerOne` library.

Any suggestion to fix the problem some other way would be cool.

Here is the code:

```
#include <TimerOne.h>
#include <QueueList.h>
#include <StackList.h>

const uint16_t  NOTE_B0     =   31;
const uint16_t  NOTE_C1     =   33;
const uint16_t  NOTE_CS1    =   35;
const uint16_t  NOTE_D1     =   37;
const uint16_t  NOTE_DS1    =   39;
const uint16_t  NOTE_E1     =   41;
const uint16_t  NOTE_F1     =   44;
const uint16_t  NOTE_FS1    =   46;
const uint16_t  NOTE_G1     =   49;
. . . ETC . . .
const uint16_t  NOTE_DS8    = 4978;

uint16_t Notas[] =
{
      NOTE_B0
    , NOTE_C1
    . . . ETC . . .
    , NOTE_C8
    , NOTE_CS8
    , NOTE_D8
    , NOTE_DS8
};

QueueList<int> KeyNotesNode = QueueList<int>();
StackList<int> StackNote = StackList<int>();

char receivedChar1 = '<';
char receivedChar2 = '<';

char receivedChar[] = {receivedChar1, receivedChar2};

int TempInt = 0;
bool newData = false;

bool itPopUp = false;

int modality = 0;

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

  if(modality == 0){
    Serial.println("Ingrese el tipo de funcionalidad deseada");
    Serial.println("1.- Constructor de canciones en tonos");
    Serial.println("2.- Juego de imposicion musical");
  }

  Timer1.initialize(150000);
  Timer1.attachInterrupt( setForPop );
}

void loop() {
  //Checa y controla la recepcion de los char a traves de la consola de arduino

  if (Serial.available())
  {
    receiveChar();
    showReceivedChar();
  }

//   . . .  Here is some code to process the reception of data from serialData  . . .

// From somewhere here start the loop

// . . . LOOPED . . .

    //Here is used the data
    if(modality == 1){
       //This option doesn't matter
    }
    else if(modality == 2){
      StackNote.push( (((int)(receivedChar[0]-'0'))*10)+((int)receivedChar[1]-'0') );
      Serial.println("Agregado receivedChar exitosamente a la Pila");
      Serial.print("Tamano Total Lista: ");
      Serial.println(StackNote.count());
      Serial.print("Dato:");
      Serial.println( (((int)(receivedChar[0]-'0'))*10)+((int)receivedChar[1]-'0') );
      Serial.print("Dato(get):");
      receivedChar[0] = '<';
      receivedChar[1] = '<';
    }
}

    //Run and show the data on the stack
     if(modality == 1)
     {
           //This option doesn't matter
      }
      else if(modality == 2)
      {

        if(itPopUp){   //With this variable i want to control when it is show, this code is inside loop()
          Serial.print("Reproducido con exito la nota: "); //se escribe 'éxito' pero la consola no acepta tildes, que se arrepienta :P
          TempInt = StackNote.pop();
          Serial.println(TempInt);
          tone(9,Notas[((int)TempInt)],500);
          delay(500);
        }
      }

  } //Here the loop() end

//This function i want to run it asyncronously
 void setForPop(){
    if(itPopUp){
      itPopUp = !itPopUp;
    }
    else{
      itPopUp = !itPopUp;
    }
 }

```

# Answer
> 1 votes
You will not have full parallel execution in an Arduino (only one CPU).

* You might do multi-threading by implementing a small OS (e.g. FreeRTOS)
* Or write your own task scheduler.
* Or even just do state machine looping forever checking if push or pop has to be executed.
* Last and preferred solution: I would consider running the normal Push task always and execute the Pop task (function in fact) using interrupts.

# Answer
> 1 votes
I haven't used the TimerOne library, but I have had good success with the SimpleTimer library. http://playground.arduino.cc/Code/SimpleTimer

It's served me well in handling building small iot apps. As the arduino has to both maintain connection info as well as doing it's processing data, this library seems to handle keeping both happy pretty well.

Here's an example in use: https://github.com/adbacker/bcc2016/blob/master/bcc2016.blynk.kitchensink/bcc2016.blynk.kitchensink.ino

The money bit is at the end =\> the setup and loop functions. (note: yes, I know. the comment says every second, but it's actually every 2 seconds...)

```
void setup()
{
  Serial.begin(115200); // See the connection status in Serial Monitor
  pinMode(WATER_SENSOR_PIN, INPUT); //water sensor pin, init as input
  Blynk.begin(auth, WIFI_SSID, WIFI_PW);
  while (Blynk.connect() == false) {
    Serial.println("trying to connect ....");
  }

dht.begin();

// Setup a function to be called every second
timer.setInterval(2000L, sendTemp);
timer.setInterval(2000L, updateLcd);
timer.setInterval(2000L, checkForWater);
}

void loop()
{
  Blynk.run(); // Initiates Blynk
  timer.run(); // Initiates SimpleTimer
}

```

---
Tags: arduino-uno, programming, timers, data-type, threads
---


# Question
Title: I already have a button on my Arduino board, but I don't know what pin number should I use in my code?
I'm attaching a picture of my board which has the push button I want to use, but I cannot because I don't know what pin number should I write in my code.

my code:

```
int switchPin = Button;
int ledPin =13;

void setup() {
  // put your setup code here, to run once:
pinMode(switchPin, INPUT);
pinMode(ledPin, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
if(digitalRead(switchPin) == HIGH)
{
  digitalWrite(ledPin, HIGH);
}
else
{
  digitalWrite(ledPin, LOW);
}
}

```

This is a picture shows the button on the top right "green"

# Answer
The schematic at makeblock.com of the mbot mcore board shows switch S3 feeding pin A7, which is an analog input pin. Note, there is a deplorable 0.1 μF capacitor in parallel across S3, probably intended as hardware-level debouncing.

Also see the Port wiring mBot mCore board thread on the Makeblock forum, where one of the posts says there are multiple versions of the board, and provides reference links.

For example, sample code at newinnovators.ca's “mblock-to-arduino/button-control” page (Dead link) shows pin 2 being used to sense the button. You may need to run some tests.
> 3 votes

---
Tags: arduino-uno, arduino-ide
---


# Question
Title: Sending Large Packets and Reassembling over Serial
I'm trying to send info of about 30-40kB over the Serial ports on an Arduino Due. But I'm running into a few problems. First, before we get into the actual transfer over the Serial, I want to try storing 30000 Bytes into a char * array.

Also as a disclaimer, I've modified the SAM library's `RingBuffer.h` `SERIAL_BUFFER_SIZE` to 256 from 128.

```
void setup() {
  Serial.begin(115200);
int i,j=0, cksum=0;
int *test;
test = (int*)calloc(1,30000);
Serial.println("Starting...\n");

for(i=0;i<30000;i++){
  test[i]=i;
  cksum +=j;
  j++;
  if(j>255){j=0;}
}
Serial.print("cksum is: ");
Serial.println(cksum);
cksum = 0;
for(i=0;i<30000;i++){
  if(i<300){ //only print out the first 300 characters, otherwise it's hard to see anything
    Serial.print("[");
    Serial.print(test[i],HEX);
    Serial.print("]");
  }
  cksum+=(int)test[i];
}
Serial.print("\nNow cksum is: ");
Serial.println(cksum);
}

```

Obviously, since `*test` is a byte array, I'm only storing int8 into there - so from 0-255. That means that the data received in `*test` increments from `test[255]= 255` to `test[256] = 0`. The way around this would be to use some kind of `itoa` function to write out multiple bytes that represent the numbers being written (causing an overflow because it would no longer be an array for 30000 Bytes). But for these purposes is it ok to simply realize that this is happening and just write the bytes to the array.

Ok, so for part two, I want to do the same thing, but by writing to Serial2 from Serial3 and receiving all of the bytes:

```
void setup() {
  Serial.begin(115200);
  Serial2.begin(115200);
  Serial3.begin(115200);
int i,j=0;
double cksum=0;
char *buf;
Serial.println("Starting...\n");
buf = (char*)calloc(1,30000);

Serial.println("Writing to Serial3");
  for(i=0;i<30000;i++){
    Serial3.write((byte)i);
    cksum+=j;
    j++;
    if(j>255){j=0;}
  }
 Serial.println(cksum);
 Serial.println("Reading from Serial2");
 Serial2.readBytes(buf,30000);
 cksum = 0;
  Serial.print("Buf is: ");
  for(i=0;i<30000;i++){
    if(i<300){ //only print out the first 300 characters
      Serial.print("[");
      Serial.print(buf[i],HEX);
      Serial.print("]");
    }
    if(buf[i] != j){
      Serial.print("\nMismatch at i = ");
      Serial.print(i);
      Serial.print("\nBuf is: ");
      Serial.print(buf[i-1],HEX);
      Serial.print(",");
      Serial.println(buf[i],HEX);
    }
    cksum+=buf[i];
    j++;
    if(j>255){j=0;}
  }
  Serial.println("\n\nEnd");
  Serial.println(cksum);

}

```

What happens here is that I get a mismatch at byte 255. The increment (in hex) goes:

```
[254] = FE
[255] = 30
[256] = 31

```

But it **should** read:

```
[254] = FE
[255] = FF
[256] = 0

```

After reading some other forums, and the fine AVR Arduino post here, I feel like something is happening on the Serial interrupt level that I am not aware of. All of the data is properly transferred to the Serial and I am able to see all of the bytes in the correct order coming out of TX and into RX on my logic analyzer. I've also experimented with different baud rates, but see no reason why a 84Mhz chip would not be able to handle a baud rate of 115200.

Has anyone else run into this? How do you handle these transfers of continuous data that is larger than the buffer? Is the only option here to run `readBytes` in `SERIAL_BUFFER_SIZE` increments until Serial is no longer available? Or can I still salvage using readBytes all in one go as I am trying to do?

I know this question has been asked in certain forms in other threads like here and here but they do not solve this particular problem I am experiencing, most likely because they are not Due specific.

# Answer
> 2 votes
Let me dissect your program and show you precisely what is going on and why your approach is completely wrong:

Your first step is to throw 30,000 bytes at the serial port. Those go via the TX ringbuffer, which is (as you have changed it for some reason) 256 bytes:

```
buf = (char*)calloc(1,30000);

Serial.println("Writing to Serial3");
  for(i=0;i<30000;i++){
    Serial3.write((byte)i);
    cksum+=j;
    j++;
    if(j>255){j=0;}
  }

```

At this point 29744 bytes have left the hardware UART. 256 are still sat in the TX ringbuffer being sent out by the TX interrupt routine. The first 256 bytes that were sent out were picked up by the RX interrupt routine and stored in the RX ringbuffer. The next 29488 bytes were discarded (they are now all over the carpet with your marbles).

```
 Serial.println(cksum);
 Serial.println("Reading from Serial2");

```

Now you try and read 30,000 bytes from the 256 byte RX ringbuffer. While you are doing that the remaining 256 bytes in the TX ringbuffer are being slowly sent out. You are now making some room in that RX ringbuffer since you are removing bytes from it, so some of the remaining 256 received bytes can now be stored in it. The first one of those happens to be 0x30.

```
 Serial2.readBytes(buf,30000);

```

Now you go and print out your array, which has only a tiny fraction of the 30,000 bytes you sent in it.

```
 cksum = 0;
  Serial.print("Buf is: ");
  for(i=0;i<30000;i++){
    if(i<300){ //only print out the first 300 characters
      Serial.print("[");
      Serial.print(buf[i],HEX);
      Serial.print("]");
    }
    if(buf[i] != j){
      Serial.print("\nMismatch at i = ");
      Serial.print(i);
      Serial.print("\nBuf is: ");
      Serial.print(buf[i-1],HEX);
      Serial.print(",");
      Serial.println(buf[i],HEX);
    }
    cksum+=buf[i];
    j++;
    if(j>255){j=0;}
  }
  Serial.println("\n\nEnd");
  Serial.println(cksum);

}

```

The simple fact is, you are transmitting, en-masse, far more bytes than the Arduino's RX ringbuffer can hold. In order to receive more than the 256 bytes of the ringbuffer you have to read the bytes from that ringbuffer to make room for more to arrive. And since you are the one that is transmitting that means you have to do your receiving *at the same time as the transmitting*.

The only possible way that your arrangement of program could work would be if you increased the RX ringbuffer to greater than 30,000 bytes so it can store all the received bytes as you transmit them for you to then, afterwards, copy the contents of that ringbuffer into your own buffer.

# Answer
> 2 votes
> ```
> int *test;
> test = (int*)calloc(1,30000);
>
> ```

First, I would be testing if that calloc worked. 30000 bytes is a lot on any microprocessor. For example:

```
test = (int*)calloc(1,30000);
if (test == NULL)
  {
  Serial.println ("Insufficient memory.");
  exit (1);
  }

```

---

Second, can't you calculate the sumcheck on-the-fly?

> ```
> for(i=0;i<30000;i++){
>   test[i]=i;
>   cksum +=j;
>   j++;
>   if(j>255){j=0;}
> }
>
> ```

If you want to send a sumcheck at the end, calculate as you send each byte and then send it afterwards. That way you don't need the 30000 byte array.

---

Your technique of sending 30000 bytes and then trying to read them back is hoping that the 30000 bytes will be saved somewhere while you are writing and before you read. Where?

> I've modified the SAM library's RingBuffer.h SERIAL\_BUFFER\_SIZE to 256 from 128.

Certainly not there. That now holds 128 bytes.

So you are expecting a buffer of 30000 bytes which you set up, plus another 30000 bytes somewhere to hold the data while you send it. Even on the Due you are using most of your available RAM for this exercise.

---

What are you *really* trying to do here?

http://xyproblem.info/

---
Tags: serial, c++, arduino-due, interrupt
---


title: Arduino Nano and WS2812

text:
# Question
Title: Arduino Nano and WS2812
I am new to electronics and especially Arduino-based products. I am currently trying my hand at using 5 segments of WS2812 RGB LEDs and using a Nano to control them. I included the picture below for the pin numbers.

If I wanted to run 5 groups of LEDs and use a library like the Adafruit Neopixel or Fastled to control the leds, what would be the best way of wiring them up to the Nano?

I am under the impression that the positives should all be connected to pin 27, the 5v pin, with a 1000 µF 25V capacitor. The ground wires will all be connected together to pin 04, Ground. The data pins will be wired to pins 6, 8, 9, 12 and 13 and each will have a 470 ohm 1/2W resistor on each pin.

I am unsure whether any of the other pins can be used for data pins. The input voltage will vary since this is used on a multi-rotor that I am building. The battery voltage will vary from 12.6V all the way down to maybe 9 volts. I was thinking of using a step down adjusted to 12V to keep the voltage at or under 12v and that will be connected to pin 30. I would love to hear if there are any better ways of wiring this project up.

Also would it be a better idea to power the LEDs from a 5V dedicated source and just use the Nano for the data pin connection? I will only be using roughly 30-40 WS2812s.

# Answer
> 2 votes
Regarding “The data pins will be wired to pins 6, 8, 9, 12 and 13 and each will have a 470 ohm 1/2W resistor on each pin”, note that WS2812s typically are connected together in strings, with the DO (data out) pin of each upstream unit connected to the DI (data in) pin of the next unit downstream. Thus, there is no need to allocate five Arduino IO pins; one is enough.

For further background on WS2812 mechanisms, see for example Is it possible to infer the length of a neopixel string using 1-wire protocol?, and see discussions and diagrams at adafruit.com and sparkfun.com.

Regarding use of an efficient step-down switching-supply voltage regulator set for 12 V out, if you use an adjustable regulator you might as well set it lower than that, for example at 8 or 9 volts. Typically, the regulators on Arduino boards that convert Vin to +5 or +3.3 V are linear regulators rather than switching regulators, so every unnecessary extra volt (above the dropout limit) proportionally increases the amount of wasted energy.

In typical use, a WS2812 draws 20 to 60 mA current, supposing up-to-five-volt power. Thus, a string of 30 to 40 of them will draw at least 0.6 A, in most cases, and up to 2.4 A, if all are on at top brightness. In either case, an external power supply would be de rigueur. You would connect the external supply's ground to the Nano's ground; the +5Vs need not be connected together.

*Edit: Addressing questions from comments*

Re “if one data in will control the entire array of LEDs, it should be connected to D13”, I'm not aware of any reason for that idea, and indeed would recommend against it. On many Arduino models, D13 drives an LED. While the Uno uses a buffer amplifier to drive the LED, the Nano just has a 680 Ω resistor in series with an LED. I'd not load it further.

Wiring each of several strips in its own chain seems quite reasonable. Yes, you could wire all the DIs of 30 or 40 WS2812 units in parallel. However, parallel inputs would require 30 or 40 wire runs, vs. the simple wiring chain the WS2812 is intended for. Note, per its spec sheet the WS2812 DI load is ±1 µA max, so one '328 IO pin could drive hundreds of them. But input capacitance, up to 15 pF each, probably precludes driving thousands in parallel.

If performance is an issue, possibly use short chains (up to several dozen units long) in parallel, rather than one long chain of hundreds of units. The spec sheet says, “When the refresh rate is 30fps, low speed model cascade number are not less than 512 points, high speed mode not less than 1024 points.” (Low speed refers to 400Kbps signalling; high speed, 800Kbps).

Note, paralleled chains improve refresh rates only when multiple chains are used to show the same pattern. Otherwise, each chain being refreshed separately is no faster than refreshing the same number of units in series. The library that drives a chain of WS2812s hogs the whole processor each time it sends a chain of data. Also note that scan rates of 400 Hz are mentioned in the spec sheet. It is likely to be futile to try to exceed that by paralleling units.

Summary: If you have a dozen or so units on a rotor arm, I'd wire them in series. If it's more convenient to keep each arm's wiring separate from that of other arms, then do so. If each arm will show the same pattern as other arms, you could wire the chain inputs (the first units in each chain) in parallel, else would use separate driver pins.

---
Tags: arduino-nano
---


title: Controlling Relay Using Serial Monitor

text:
# Question
Title: Controlling Relay Using Serial Monitor
I tried to make a program that can control a 4 channel relay (with LEDs as indicators) with a serial monitor. First time I tried to program it using a `char` command to make it turn on only, it worked. Then I tried to make it off only, it also worked, but when I tried to combine them, to control it to On or Off in the same program, it didn't work.

this is my code

```
#define CH1 2
 #define CH2 3
 #define CH3 4
 #define CH4 5
  void setup(){
 Serial.begin(9600);

pinMode(CH1, OUTPUT);
pinMode(CH2, OUTPUT);
pinMode(CH3, OUTPUT);
pinMode(CH4, OUTPUT);
digitalWrite(CH1,HIGH);
digitalWrite(CH2,HIGH);
digitalWrite(CH3,HIGH);
digitalWrite(CH4,HIGH);
 }

 void loop (){
  if (Serial.available()) {

char ser = Serial.read();

 switch(ser){
 case 'on1':

 onPin1();

 break;

 case 'on2':

 onPin2();

 break;

 case'on3':

 onPin3();

 break;

 case 'on4':

 onPin4();

 break;

 case 'off1':

 offPin1();

 break;

 case 'off2':

 offPin2();

 break;

  case'off3':

 offPin3();

 break;

  case 'off4':

 offPin4();

 break;

   }

 }
 }

 void onPin1(){
    digitalWrite(CH1, LOW);
 }
  void onPin2(){
   digitalWrite(CH2, LOW);
 }
   void onPin3(){
   digitalWrite(CH3, LOW);
 }
  void onPin4(){
   digitalWrite(CH4, LOW);
 }

  void offPin1(){
   digitalWrite(CH1, HIGH);
 }
   void offPin2(){
   digitalWrite(CH2, HIGH);
 }
   void offPin3(){
   digitalWrite(CH3, HIGH);
 }
   void offPin4(){
   digitalWrite(CH4, HIGH);
 }

```

with that code, I got "duplicate value", maybe because the pin is double-called. But when I tried to make it in separate swicth case condition, no error but couldn't respond to the command `char`

# Answer
> 1 votes
This is `C++`, so the single quotes are used for character literals. If you want string literal, you have to use double quotes. However, string literals can't be used in `switch`.

And you can't definitely use it like that if you are reading only one character.

However you can use single characters for this:

```
#define CH1 2
#define CH2 3
#define CH3 4
#define CH4 5

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

  pinMode(CH1, OUTPUT);
  pinMode(CH2, OUTPUT);
  pinMode(CH3, OUTPUT);
  pinMode(CH4, OUTPUT);
  digitalWrite(CH1,HIGH);
  digitalWrite(CH2,HIGH);
  digitalWrite(CH3,HIGH);
  digitalWrite(CH4,HIGH);
}

void loop (){
  if (Serial.available()) {
    char ser = Serial.read();
    switch(ser){
      case '1':  onPin(CH1); break;
      case '2':  onPin(CH2); break;
      case '3':  onPin(CH3); break;
      case '4':  onPin(CH4); break;
      case '5': offPin(CH1); break;
      case '6': offPin(CH2); break;
      case '7': offPin(CH3); break;
      case '8': offPin(CH4); break;
    }
  }
}

void onPin(int8_t pin) {
  digitalWrite(pin, LOW);
}

void offPin(int8_t pin) {
  digitalWrite(pin, HIGH);
}

```

Or you can toggle the relay states.

Test strings as commands are little bit harder to use as you have to read whole command (or use state machine). Following example is little bit unnecessary hard but it's working...

```
constexpr uint8_t     channels = 4;
constexpr uint8_t ch[channels] = { 2, 3, 4, 5};

template <uint8_t pin, uint8_t val> void setChan() {
  digitalWrite(pin,val);

  Serial.print("setChan: "); Serial.print(pin);  Serial.print(' ');  Serial.println(val);
}

using action_t = void(*)(void);

action_t  on_actions[channels] = {
  &setChan<ch[0],LOW>,
  &setChan<ch[1],LOW>,
  &setChan<ch[2],LOW>,
  &setChan<ch[3],LOW>
};

action_t off_actions[channels] = {
  &setChan<ch[0],HIGH>,
  &setChan<ch[1],HIGH>,
  &setChan<ch[2],HIGH>,
  &setChan<ch[3],HIGH>
};

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

  for (auto pin : ch) {
    pinMode(pin, OUTPUT);
  }
}

String command = "";
action_t action = nullptr;

void loop() {
  if (action != nullptr) {
    action();
    action = nullptr;
  }
}

void serialEvent() {
  if (Serial.available() > 0) {
    char inChar = (char)Serial.read();
    if ((inChar == '\r' || inChar == '\n')) {
      if (command.length() > 0) {
        Serial.print(command);
        if (command.startsWith("on")) {
          uint8_t channel = command.substring(2).toInt()-1;
          if (channel < channels) {
            action = on_actions[channel];
          }
          Serial.print(" On="); Serial.print(channel+1);
        } else if (command.startsWith("off")) {
          uint8_t channel = command.substring(3).toInt()-1;
          if (channel < channels) {
            action = off_actions[channel];
          }
          Serial.print(" Off="); Serial.print(channel+1);
        }
        Serial.println();
        command = "";
      }
    } else {
      command += inChar;
    }
  }
}

```

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


# Question
Title: How does Arduino IDE for OSX work without drivers?
My Arduino IDE works right out of the box without me having to install any USB to UART drivers. I know the Atmega16U2 on the UNO is acting as UART bridge, but this means that OSX recognizes it on a hardware level, which doesn't make sense since no drivers were installed - unless there is some sort of standard here that the Atmega16U2 implements?

The reason why I ask this is that I have a project where I want to connect an ATMega328p to a client mac which may not have access to 3rd party drivers, so having serial work natively with screen would be ideal. If the Arduino IDE can implement serial monitor without any additional drivers then it means I can too.

Does anyone know how this is implemented?

Thanks!

# Answer
Windows 8.1 is the last version of any common desktop system that requires CDC/ACM (that is what the Arduino's USB port is) drivers.

OS X is based on BSD which, like Linux, has had CDC/ACM drivers built in since (pretty much) the dawn of time. It is only really Windows that has had the concept of drivers for anything that isn't vendor specific and/or complex (such as video cards, or devices that don't adhere to published standards).

Even Windows 10 now has the drivers for CDC/ACM built in (it's only taken Microsoft 20 years or so to catch up with the rest of the OS world).
> 1 votes

---
Tags: arduino-uno, arduino-ide, ftdi
---


title: smoke came out of Arduino Nano

text:
# Question
Title: smoke came out of Arduino Nano
I was working with Arduino and Xbee with LED, circuit LED + Servomotor and doing testing for 5 hours (not continuously).

Then once I omitted the Servomotor circuit and I connected flex sensor, which required connecting 10k Resistor and connect it the laptop as usual, smoke came out of the board (from USB side). I disconnected it immediately, but now the board doesn't light up and the 5V gives 1.5V.

Is there any chance to fix the board?

I discovered that the B2 diode cracked in the middle, the picture is showing a good Arduino Nano.

I found a very similar in this post about dead NANO

# Answer
> 2 votes
If my understanding is correct, the flex sensor was connected between 5V and GND. This acted like "short circuit" and should not have burned the AVR, but only the power supply side. If you have a multimeter and some soldering skills it should be possible to fix the board.

Supposing you have an genuine arduino UNO, here is a schematic but it may not be the right version

1. Remove the MCU
2. Check voltage between GND and XUSB is 5V (if not either your USB port is burned or you have a short on the board or a component)
3. Check voltage between GND and USBVCC is 5V (if not, replace the fuse)
4. Check voltage between GND and +5V is 5V (if it's still 1.5V as you mentioned, try replacing transistor T1 but I do not understand why it would burn. If it's 5V replace the MCU)

**EDIT for Arduino Nano**

I did not understand you had a nano board (schematic)

The component "B2" you mention is the diode D1 (MBR0520). It burned because of the short circuit you created and nothing else should be defect. It acted like a fuse. Simply replace it and it should be fine.

If you are VERY CAREFULL not to overload the nano with external circuitery and never bring external 5V you could just remove it and make a little solder bridge (waiting for replacement part)

# Answer
> 0 votes
The Nano has mainly surface-mounted devices on it. You need to be quite skilled to remove faulty ones and replace them, without special equipment.

By the time you have identified which one needs replacing, removed it (no easy task if it is the processor) and replaced it, it would be easier and probably cheaper to just buy a new board.

You may well have fried the main processor (Atmega328P) which I see with a quick search is selling for around $7 to $8 in one-off quantities, whereas you can buy the entire Nano for around $13 for a genuine one, or around $9 for a clone. It just won't be worth the trouble.

---
Tags: arduino-nano
---


# Question
Title: Why/when to use IoT publish/subscribe protocols rather then RESTful HTTP?
I am sending data (GPS coordinates) from Arduino once a minute with HTTP POST request to REST API (in OpenShift PaaS). Data is then stored to MySQL db.

Would so called "IoT" publish/subscribe protocols (XMPP, MQTT) be better? Why?

When exactly do you use those two protocols rather than Restful HTTP? Would I really save a significant baterry energy using them?

AFAIK in those protocols machine would "publish" a data to broker and my app would subscribe to it. If I would like to gather data every minute in my app I guess that I would got to have some CRON job that would subscribe to data every minute? Or how would data gathering be achieved?

# Answer
In my experience ReST is good for real-time data transfer and processing but has a lot of overhead for simple message passing. Plus, there's no queuing in it so store-forward configurations are troublesome.

MQTT is a message queue transport system where the message can be placed on the channel by the publisher and will stay there until the subscriber picks it up. So you can have some rudimentary store-forward capabilities with this. Also MQTT is more transparent and multicast so communicating to many nodes is no different than communicating to one.

With that, each have their place and use and ReST is great for sending large items (JSON blobs), sending data for calculation and getting it back, and for requesting a specific dataset. MQTT is more for "here's my sensor data every second, enjoy".
> 3 votes

# Answer
(shameless self-promotion) I did a talk on iot stuff this year at our local code camp. Notes are here: https://github.com/adbacker/bcc2016/blob/master/2016bcc-iotonthecheap.pdf

Super simplified per my limited experience: (experts correct at will :-) )

MQTT protocol:

- requires a broker
- maintains a connection to the broker (which allows for push notifications back to the device)
- was specifically designed for "small footprint" applications (read: limited RAM and processing power)

MQTT is optimized for sending simple data. GPS coordinates would be a good fit. I'm sure MQTT *could* be used to send complex data (ie: large json objects) but that doesn't seem to be what it's designed for.

You're not looking for push notifications back to the device, nor are you maintaining a connection to the REST server so (from a practical standpoint) I'm guessing your battery life improvement would be minuscule at the very best converting the solution to mqtt.

Adafruit has a pretty good mqtt tutorial and libraries, as well as a beta service that provides broker services: https://learn.adafruit.com/adafruit-io/mqtt-api

Also, for super-duper-easy IOT setups (that admittedly use a custom protocol), let me recommend blynk. ( www.blynk.cc ) It's free and so easy I rewrote my entire presentation around it. Additionally, there are (free) blynk ios and android apps that allow creation of custom dashboards that communicate (via the also-free blynk broker) with your device of choice. If you host the broker server (also free) yourself, it has it's own REST api that allows data access to/from your device.
> 2 votes

# Answer
Basically, MQTT reduces latency where there's relatively high latency like Wi-Fi by keeping the TCP connection alive so that data can be published and received very quickly. It uses port 1883 and not 80. As I understand it, the publishers and subscribers connect once to the broker and then ping the broker regularly to keep the connection alive; how often the broker is pinged depends on the pre-agreed keep-alive period. MQTT packets are also significantly smaller than HTTP requests. If the connection is somehow broken, the client repeatedly tries to re-establish the connection and when successful, the subscribers re-subscribe.

Subscribers define callbacks that are called after a topic has has been updated by some publisher. MQTT is best for time-critical jobs where HTTP requests would just take too long and where quick notification of changed topics is desired. I'm not sure but it will probably consume more battery power, since there's that matter of a constant TCP link to the broker.

Since you're only expecting data updates every minute, I think it makes more sense to connect and GET the feed data from the server every 60 seconds. You can use the feed's `Last-updated` time-stamp (if it doesn't exist, create one) to check if the feed has been updated by the Arduino yet. An MQTT technique would just spend most of the time connected to a broker for no reason since you already know that the update events occur every minute; that is a significant amount of time and power spent waiting for predictable data.

However, you could wait for about 55 seconds, subscribe to the topic and when you get the new data, you disconnect and then wait for 55 seconds again, though I dont know if this will be much of an improvement over REST. If you use this method, you can also set the keep-alive period to be just about 10 seconds, so that the Arduino has enough time to update the feed before your app is notified and there's no need for regular pings.

If you decide to go with MQTT, check out this Arduino library.
> 1 votes

# Answer
In my applications, the biggest power drain is turning on the radio to transmit data. I often keep the radio off, collect data points, and then turn on the radio to send multiple pieces of data together as one request using a RESTful HTTP call. For my case, RESTful HTTP is way more efficient since I do not need an always on connection.
> 0 votes

---
Tags: arduino-uno, arduino-mega, power, communication
---


# Question
Title: How do I use two PulseIn() functions simultaneously in Arduino?
I want to connect multiple Ultrasonic sensors to my Arduino board. For that, I need multiple pulseIn() functions to work at the same time. How can I do that?

# Answer
You can't. `pulseIn()` is a blocking function that waits for a pulse to arrive before returning.

Instead you will either have to use interrupts or (where available) *Input Capture* peripherals.

**However**, using multiple ultrasonic sensors at the same may not make sense. Unless you take great care with your physical design you will get interference between the two. Echoes from one bouncing around will trigger the other. For this reason it is normal to not trigger both at once, but to use them sequentially, in which case `pulseIn()` is still perfectly fine to use.
> 3 votes

---
Tags: arduino-uno, sensors, timers, pulsein, proximity
---


title: How to correctly code a LED STRIP?

text:
# Question
Title: How to correctly code a LED STRIP?
I recently bought a 5050 RGB 12V 3A LED strip and I set it all up with my Arduino and run this code (from adafruit website), everything is good: Example Code Once you have the strip wired up, it is easy to control the color of the strip by using PWM output, for Arduino you can use

```
#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3

#define FADESPEED 5     // make this higher to slow down

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);
}

void loop() {
  int r, g, b;

  // fade from blue to violet
  for (r = 0; r < 256; r++) {
    analogWrite(REDPIN, r);
    delay(FADESPEED);
  }
  // fade from violet to red
  for (b = 255; b > 0; b--) {
    analogWrite(BLUEPIN, b);
    delay(FADESPEED);
  }
  // fade from red to yellow
  for (g = 0; g < 256; g++) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }
  // fade from yellow to green
  for (r = 255; r > 0; r--) {
    analogWrite(REDPIN, r);
    delay(FADESPEED);
  }
  // fade from green to teal
  for (b = 0; b < 256; b++) {
    analogWrite(BLUEPIN, b);
    delay(FADESPEED);
  }
  // fade from teal to blue
  for (g = 255; g > 0; g--) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }
}

```

I tried to find a way to achieve the same effect but only with two colors...red to yellow..red fade to yellow and fade to red and so on..

EDIT: Thanks to @majenko I achieved this...Fade from Red to Yellow and back on:

```
    for (int r = 0; r < 256; r++) {
        analogWrite(REDPIN, r);
        analogWrite(GREENPINPIN, 255 - r);
        analogWrite(BLUEPIN, 0);
        delay(FADESPEED);
    }

    // Fade red down and blue up
      for (g = 0; g < 256; g++) {
        analogWrite(REDPIN, 255);
        analogWrite(BLUEPIN, 0);
        analogWrite(GREENPINPIN, G);
        delay(FADESPEED);
      }

```

# Answer
> 1 votes
The main difference between what you want and what that code does is that you want to fade both colours at once, but that code is aimed at only fading one colour at a time.

You want to fade R up whilst fading B down, and then fade R down whilst fading B up. The simplest way is with just two loops:

```
// Fade red up and blue down
for (int i = 0; i < 256; i++) {
  analogWrite(REDPIN, i);
  analogWrite(BLUEPIN, 255 - i);
  delay(FADESPEED);
}

// Fade red down and blue up
for (int i = 0; i < 256; i++) {
  analogWrite(REDPIN, 255 - i);
  analogWrite(BLUEPIN, i);
  delay(FADESPEED);
}

```

One fade value (`i`) per loop, and a little bit of maths to turn 0-255 into 255-0 for the value you are fading down.

---

For Red-\>Yellow-\>Red you just need to keep red on and fade green on and off. You already have code to fade green on and off in your original program:

```
  // fade from red to yellow
  for (g = 0; g < 256; g++) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }

  // fade from teal to blue
  for (g = 255; g > 0; g--) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }

```

Couple that with setting the red and blue to on and off respectively, and you have:

```
#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3

#define FADESPEED 5     // make this higher to slow down

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);

  analogWrite(REDPIN, 255);
  analogWrite(BLUEPIN, 0);
}

void loop() {
  int g;

  // fade from red to yellow
  for (g = 0; g < 256; g++) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }

  // fade from yellow to red
  for (g = 255; g > 0; g--) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }
}

```

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


# Question
Title: Arduino Text Scrolling on 16x02 I2c on NodeMcu (ESP8266-12)
I have managed to get my 1602 I2C LCD working on a NodeMCU devkit. I can display text parsed from the web but I am not sure how to set it to autroscroll if message is greater than 16 characters. I tried the `lcd.ScrollDisplayLeft()` but it doesn't work. I figured I would have to do it manually and it is a matter of getting string length and then looping the characters.

This is what I have so far:

```
#include <ESP8266WiFi.h>
#include <Wire.h>  // This library is already built in to the Arduino IDE
#include <LiquidCrystal_I2C.h> //This library you can add via Include Library > Manage Library >

LiquidCrystal_I2C lcd(0x3F, 16, 2);

const char* ssid = "ssid";
const char* password = "pass";
const char* host = "api.thingspeak.com";

int find_text(String needle, String haystack, int from) {
  int foundpos = -1;
  if (haystack.length() < needle.length())
    return foundpos;
  for (int i = from; (i < haystack.length() - needle.length()); i++) {
    if (haystack.substring(i, needle.length() + i) == needle) {
      foundpos = i;
      return foundpos;
    }
  }
  return foundpos;
}

void setup() {
  Serial.begin(115200);
  delay(100);
  lcd.init();   // initializing the LCD
  lcd.backlight(); // Enable or Turn On the backlight
  delay(200);

  // We start by connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  lcd.setCursor(0, 0);
  Serial.print("Connecting to ");
  lcd.print("Connecting");
  lcd.setCursor(1, 1);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    lcd.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Connected!!");
  delay(1000);
}
int value = 0;

void loop() {

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");

  }

  // We now create a URI for the request
  String url = "/apps/thinghttp/send_request?api_key=345345345345345";
  Serial.print("Requesting URL: ");
  Serial.println(url);
  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Fetching Data..");
  delay(10000);

  // Read all the lines of the reply from server and print them to Serial
  while (client.available()) {
    String line = client.readStringUntil('\r');

    int start_loc = find_text("<b>", line, 0);
    int end_loc = find_text("</b>", line, 0);
    if (start_loc > 0 && end_loc > 0)
    {
      lcd.clear();
      Serial.println("data:  ");
      lcd.print("data: ");
      lcd.setCursor(1, 1);
      for (int i = start_loc + 3; i < end_loc; i++)
      {
        Serial.print(line[i]);
        lcd.print(line[i]);
     }

  Serial.println();
  Serial.println("closing connection");
  delay(2000);

}
  }
}

```

# Answer
> 0 votes
Inspecting the library code, it is apparent that the method called only sets up a command bit field and it is actually the display that performs the operation.

So, you might check if your LCD is capable of performing the scrolling operation.

This web page contains a tutorial on how to use the scrolling feature. In this code example from that page:

```
void loop() {
  // scroll 13 positions (string length) to the left
  // to move it offscreen left:
  for (int positionCounter = 0; positionCounter < 13; positionCounter++) {
    // scroll one position left:
    lcd.scrollDisplayLeft();
    // wait a bit:
    delay(150);
  }

```

...you can see that it is not automatic. That you need to call the method each time you want to scroll (in this case) one position to the left.

---
Tags: programming, arduino-ide, lcd, communication
---


# Question
Title: Press the Windows key using "keyboard.press();"
Is it possible to allow an Arduino Leonardo to simulate pressing the Windows key using the `keyboard.press(......);` command?

If so, what is the required value?

# Answer
They `Keyboard.press()` command accept modifiers per the documentation. You may need to do multiple `press()` commands before releasing.

For example, if you want to launch File Explorer you could use:

```
Keyboard.press(KEY_LEFT_GUI);
Keyboard.press('e');
Keyboard.releaseAll();

```

This is equivalent to shortcut keys `Win` \+ `E`.

The modifier `GUI` is what stands in for the "command key" which is the Windows Logo on a PC or *clover* (⌘) on a Mac.

I don't have any restriction on the higher value on my board (Pro Micro), as indicated by @frarugi87.
> 6 votes

# Answer
Looking at the list of the HID keyboard codes (page 53), the keys you are looking for have a code of E3 (Keyboard Left GUI) or E7 (Keyboard Right GUI).

Unluckily the `Keyboard::press` function (you can see it here) does not accept a so high value, since you can only input numbers between 0 and 255 and, in order to send a raw value, you have to send its value plus 136 (which leads to values 363 and 367).

However, looking at the header file, there are two predefined keys called `KEY_LEFT_GUI` and `KEY_RIGHT_GUI`. Maybe these modifier keys behave in exactly the same way.

So my suggestion is to

1. try using one of those values (i.e. `keyboard.press(KEY_LEFT_GUI);` or `keyboard.press(KEY_RIGHT_GUI);`, or use the `keyboard.write(KEY_LEFT_GUI);` to simulate a press on the key instead of you keeping it pressed).
2. If this does not work, create your own library copying the keyboard.cpp and keyboard.h files, calling the class differently and adding the possibility to send the E3 and/or the E7 keys. In this case, you will just need to modify the press function.

Good luck
> 3 votes

---
Tags: arduino-leonardo, button, keyboard, windows
---


# Question
Title: Use Arduino Yun Shield as ISP for bootloaded ATMega328-PU
My question is how do I replace the Aarduino Uuno board in this circuit:

...With an Arduino Yun shield? I can setup the hardware - ICSP configuration is easy enough - but how do I go about using the IDE to do this? Cheers

# Answer
It's highly unlikely you will be able to do it from the IDE. Instead you will have to do it from the Yun's command line (SSH) using `avrdude` and the `linuxgpio` driver, or the handy `run-avrdude` script.

```
$ sudo run-avrdude bootloader.hex

```

where `bootloader.hex` is the bootloader file found somewhere in the IDE that you need to copy over to the Yun with `scp`.

You may find you need to tweak the fuse settings in the script to get the bootloader to work. I am not familiar with AVR fuses, but IIRC there is one that tells it to run the bootloader instead of the sketch. Just copy the values out of the boards.txt in the IDE and place them into a copy of `/usr/bin/run-avrdude` in your home directory.
> 0 votes

---
Tags: shields, arduino-yun, atmega328, isp, icsp
---


# Question
Title: MPU6050 Measure distance traveled or position
How can I use MPU-6050 with an arduino to measure the distance the robot traveled from it's starting point or just it's current position on the map?

The Robot should be moving in a map same as a 2D array and I need to detect it's position while it is moving and send the data to a station.

# Answer
You won't - not with any degree of accuracy anyway.

You could attempt "dead reckoning" whereby you estimate the current speed by the acceleration and deceleration over time, and from that get a rough idea about the distance travelled in any one direction, but the accuracy will be so poor and the drift so huge that it would be next to pointless.

Instead you really want to monitor the wheels. Count how many revolutions (or half revolutions, quarter revolutions, whatever accuracy you need) and combine that with the circumference of the wheels to calculate how far you have travelled.
> 1 votes

---
Tags: arduino-uno, robotics, mpu6050
---


# Question
Title: How do I use ATTiny pin 5 (RESET) as a digital output?
I am using an Arduino Uno as ISP (Using the standard ArduinoISP sketch) to program an ATTiny13A through the Arduino IDE. (I also have a USBtinyISP 2.0 and a USBASP 2.0, but can't reliably get either to program this chip with *any* sketch.)

I want to use all six I/O pins on the ATTiny to each control 1 LED. Pins 0 through 4 work fine, but since pin 5 is the RESET pin, it doesn't want to work as an output normally.

I have read from many sources that I can disable the reset pin by changing the fuse bits, and that once I do so I will not be able to program the chip any more. Every source I've seen has given this warning, but has then proceeded to NOT say *how* to accomplish the 1-time-write.

Assume I've got my sketch exactly 100% as I want it, don't have a high-voltage programmer, and am fine with only being able to program the ATTiny once. How can I program the chip and set the appropriate fuse bits with what I have access to?

# Answer
RSTDISBL is bit 0 of the high fuse byte. Use avrdude to read the current value of the high fuse byte (`-U hfuse:r:-:h`), clear bit 0, and then write the value back out (`-U hfuse:w:0xXX:m`).
> 1 votes

---
Tags: arduino-ide, attiny, arduinoisp
---


title: What to do after prototyping?

text:
# Question
Title: What to do after prototyping?
I want to make a USB gamepad, and I've heard that an Arduino would be great for this kind of project. But before I start to work on it, I want to make sure I understand some things. Here are my basic diagrams of what the project will look like during prototyping and *after* prototyping:

---

Do the diagrams look right? Am I understanding the process correctly? For me to properly build a final circuit, I would have to emulate all the necessary (the most important one being the USB) circuitry that an Arduino has around it's microprocessor.

And my final question is, how would I load my program on to the microprocessor (with and without the "Arduino-like" USB circuitry)?

# Answer
Yes, your thinking is pretty much correct.

You can place an ATMega32U4 chip and the associated required circuitry within your own circuit design. The required circuitry is actually quite simple - a crystal for the CPU clock, a few capacitors (load capacitors for the crystal, and decoupling), two 22Ω termination resistors for the USB bus, and a 10KΩ pullup on the reset pin. That's about it (besides power of course).

As far as programming goes, you can either install a bootloader (butterfly - like the Leonardo etc) that works through the USB, or you can directly program the chip using ICSP. It's best to provide an ICSP header anyway (it's the SPI pins plus RESET basically), and if you have done that (which you'd need really to be able to get a bootloader on there) then you may as will skip the bootloader entirely and just program direct through the ICSP header. Of course, you'll need some kind of programmer (an Arduino can do the job at a pinch, but it's worth spending the $10 to get a cheap AVR programmer from eBay).
> 3 votes

---
Tags: usb, prototype, atmega32u4
---


# Question
Title: Arduino uno - Ethernet Shield enc28j60 hangs after some time
I am using Ethernet Shield enc28j60 for retrieve data from web server, but Ethernet Shield enc28j60 hangs after some time and it only works after restarting power supply (router usb port).

My sketch : https://github.com/shyamjos/Arduino\_ServerMon

# Answer
I have fixed it myself by increasing `Ethernet::buffer`size, I have also heard that sometimes it is caused due to power issues so providing external 3.3V for enc28j60 may help.
> -2 votes

# Answer
Are you sure your ethernet connection works? Try to debug with `Serial.println(F("message"))` to find out where it hangs.

I used the same Ethernet Shield and EtherCard library, and I had to change

```
if (ether.begin(sizeof Ethernet::buffer, mymac) == 0) {

```

on line 152 to

```
if (ether.begin(sizeof Ethernet::buffer, mymac, 10) == 0) {

```

because the ENC28j60 uses a different default CS pin (10 instead of 8).
> 0 votes

---
Tags: arduino-uno, ethernet
---


# Question
Title: Arduino nano & pro micro SPI simple communication
I'm working with Arduino boards with AVR C coding to perform simple SPI communication from master for simple blink application on slave side.

They don't work, the TX function on the master side doesn't seem to work, after serial monitor debugging is discovered the function never get over the while loop! Why is that?

Here are the codes I worked on last night:

Master:

```
/* nano board is the Master and transmit
  data to slave to blink LEDs */

void SPI_Init(void);
void SPI_TX(uint8_t data);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);//start Serial
  Serial.println("Setting Up");
  void SPI_Init();
  delay(100);
  Serial.println("SPI intialization is complete");
}

void loop() {
  uint8_t d = 0x20;
  SPI_TX(d);
  Serial.println("just sent the 1st byte");
  _delay_ms(400);
  d = 01;
  SPI_TX(d);
  Serial.println("just sent the 2nd byte");
  _delay_ms(400);
}

void SPI_Init(void)
{
  DDRB = (1 << DDB3) | (1 << DDB1); // DDB2 MOSI, DDB1 SCK
  SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR0);
}

void SPI_TX(uint8_t data)
{
  SPDR = data;
  while (!(SPSR & (1 << SPIF)));
}

-------------------------------------------------------------- -

```

Slave:

```
-------------------------------------------------------------- -

/* pro micro as slave and receives data then push them on
  PORTD and PORTB to blink LEDs */

void SPI_Init_S(void);
void SPI_RX(void);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);//start Serial
  Serial.println("Setting Up");
  SPI_Init_S();
  delay(100);
  Serial.println("SPI intialization is complete");
  DDRD = (1 << DDD5); // TX LED as output
  DDRB = (1 << DDB0); // RX LED as output
}

void loop() {
  // put your main code here, to run repeatedly:
  SPI_RX();
  PORTD = SPDR;   // blink the TX LED on pro micro board
  _delay_ms(500);
  SPI_RX();
  PORTB = SPDR;   // blink the RX LED on pro micro board
  _delay_ms(500);
}

void SPI_Init_S(void)
{
  SPCR = (1 << SPE) | (1 << SPR0);
}

void SPI_RX(void)
{
  return SPDR;
}

```

# Answer
> 1 votes
> ```
>  void setup() {
> // put your setup code here, to run once:
>  Serial.begin(9600);//start Serial
>  Serial.println("Setting Up");
>  void SPI_Init(void);   // <---------------- this is wrong!
>  delay(100);
>  Serial.println("SPI intialization is complete");
>  }
>
> ```

That isn't how you call a function.

It should read:

```
SPI_Init ();

```

# Answer
> 0 votes
You should use `SS` (Select Slave) pin for synchronization on both devices. If you have master with default settings for `SS` pin (= `INPUT`), any interferences will switch your master into the slave mode and `SPI_TX` will wait forever for clock pulses from outside.

Without using `SS` on both sides it can be also shifted (unsynchronized).

Edit: And yes, also not calling `SPI_Init` causes pretty similar deadlock.

---
Tags: c++, spi
---


# Question
Title: How to read differential TTL signal from encoder using Arduino?
I am using Arduino UNO/ MEGA to read the incremental encoder pulses (Baumer encoder EIL580). Currently, I am using it in single-ended mode (reading A,B and Z outputs) as I am not sure how to read the differential signal in Arduino (A, Ainv, B, Binv, Z, Zinv) as it would improve the reliability of the data. Is there any addon shield or circuitry to interface this signal with Arduino?

# Answer
> 1 votes
It looks to me like something similar to RS485 (I have a page about that here).

You could use a chip like the LTC1480 to take the A+ and A- inputs and convert them to TTL levels.

I haven't tried it with your encoder but in principle it should work. (You would need two chips if you want to handle A+/A- and B+/B-. Or three if you want to handle R+/R- as well). Still, it's about a $6 chip.

---
Tags: arduino-mega, shields, rotary-encoder
---


title: An audio jack modem

text:
# Question
Title: An audio jack modem
I'm looking at controlling Arduino by reading audio commands sent from a raspberry pi (through javascript). I've found the SoftModem code and wonder how it works. It claims that "It uses the phone's audio jack and Bell 202 modem-like FSK encoding", but I wonder how it's done. Doesn't it need to sample the ADC and apply some filtering like FFT? I can't seem to find where all this is done.

Any thought appreciated.

# Answer
> 1 votes
Judging by the blog from the post you linked, he is calculating the frequency received by using the analog comparator built into the processor. That lets you detect a signal rising, falling or both, compared to a reference voltage.

With some interrupts and some timing, you could work out what frequency signal you were receiving, and thus deduce if you got a 0 or 1 bit incoming.

I have a page about the analog comparator if that helps.

---
Tags: audio, adc
---


# Question
Title: Error on Uploading Program to ESP8266 via Foca v2.2 (USB to TTL Adapter)
## BACKGROUND

To test the capability of uploading program to ESP8266, I use an empty program with only a blank setup function and a blank loop function. The result showed me that there are a **espcomm\_sync error** and a **espcomm\_open error**. Any idea to solve this problem?

---

## HARDWARE

##

---

## PIN CONNECTION

```
  Foca v2.2 <-> ESP8266
        TXD <-> RXD
        RXD <-> TXD
        DTR <-> RST

Arduino UNO <-> ESP8266
        GND <-> GND
       3.3V <-> Vcc

```

---

## PIN DIAGRAMS

Foca v2.2

ESP8266

---

## ON LINUX UBUNTU 15.04

---

## ON WINDOWS 10

## REFERENCE

---

Bring IoT to Arduino, together \[Getting Started\] - http://www.arduinesp.com/getting-started

# Answer
> 1 votes
by the comments I think you are not understanding correctly how to connect Reset and GPIO\_0 of ESP. To set esp-01 into flash mode (to program) you need to set GPIO\_0 Low (GND) and then also apply Low on RST ESP pin. To debug the things and be certain that there is no hardware problem let just start by doing these connections:

```
Foca v2.2 <-> ESP =1
      TXD <-> RXD
      RXD <-> TXD
      GND <-> GND
  Arduino <-> ESP 01
     3.3V <-> 3.3V
     3.3V <-> CH_PD
     GND  <-> GND

```

Now, with a wire, **connect GPIO\_0 to ground**. With another wire, **briefly** connect **RST of the ground** to make ESP reset. You should be now in flash mode. Remove the connection on GPIO\_0 and make it float. Now upload the code.

**Note:** this is basically the option C on the link you provide. If you have some buttons you can make it too:
(source: arduinesp.com)

**Now, does the code upload in Arduino IDE?**

If the answer is still no, try to add a small capacitor between 3.3v and ground.

If the answer is yes, now you can move on and try the other options described in the link you provide. I recommend using the option A:

(source: arduinesp.com)

Any generic npn transistor should work

# Answer
> -1 votes
I had the same problem. I solved connecting GPIO0 to GND and connecting RST to GND a while after uploading and then leave it floating while uploading

---
Tags: esp8266
---


title: combination of arduino uno and mega?

text:
# Question
Title: combination of arduino uno and mega?
I am new to Arduino. Can I combine Arduino UNO and MEGA in 1 project? Arduino UNO is for audio output and MEGA for LCD display. If I am wrong, is there any ideas how do combine both LCD display and audio output in one microcontroller?

# Answer
> 2 votes
When you want to transport 8 people to a festival you can either use two cars and have 4 in each car, or you can get a minibus and have everyone together in one vehicle. It's often simpler to get a minibus, though hiring one may be outside your budget, so two cars is quite often the norm. The tricky part is to set up some form of communication between the drivers so they can both get to the same place at the same time and find each other.

It is exactly the same with microcontrollers (which the Arduino basically is). You can use one big powerful microcontroller to do everything, or you can split your task between a number of smaller microcontrollers. The tricky part is setting up some form of communication between them so that they can all coordinate what they are doing. Bigger microcontrollers can be more expensive though, and if you already have a couple of Arduinos at your disposal then connecting them together and sharing out different parts of your project to them is a good way of going.

Communicating between the Arduinos can be done in a number of ways, depending on how many Arduinos you are connecting, what kind of data there is going between them, etc. One common method which is well documented is to use I2C (Wire.h) to communicate. This is often chosen because it uses just two wires. For higher speed communication SPI is a good choice, but it requires more pins (4 for bi-directional communication). Of course, you can also connect them together using the UARTs, but on the smaller chips (such as the ATMega328P you get on the Arduino Uno) you only get one UART and that is used for programming, so using that for other things gets tricky.

# Answer
> 1 votes
I think you can manage to find a display that uses only a few pins, like Adafruit 2.2 TFT which has a 3-pins SPI communication. Then you have a lot of pins left to connect for example an audio shield.

I think this could be done on a single Arduino, you'll just have to find an Arduino board compatible with both audio and video systems you choose.

I only wonder if the audio playing would be suffering from screen refresh if both communications are in SPI.

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


title: Read OUTPUT pin value in Arduino Due

text:
# Question
Title: Read OUTPUT pin value in Arduino Due
I am trying to read the value of an output pin. online forums say that `digitalRead(pinNum);` should work, but that is not the case here. digitalRead always returns 0 (LOW). This is the code:

```
int pin = 22; // or 13, or 3 ...
void setup()
{
  Serial.begin(9600);
  pinMode(pin,OUTPUT);
}
void loop()
{
  digitalWrite(pin,HIGH);
  delay(100);
  Serial.println(digitalRead(pin));
  delay(100);
  digitalWrite(pin,LOW);
  delay(100);
  Serial.println(digitalRead(pin));
  delay(100);
}

```

printed values:

```
0
0
0
...

```

# Answer
> 7 votes
That method only works on AVR based systems. It exploits a "feature" whereby the IO pin, when in OUTPUT mode, is also in INPUT mode at the same time, and reading the pin reads the value that the pin is being driven to by the digitalWrite function.

The same is not true of the Due, which is an ARM based system. The IO pins function completely differently and the same "feature" cannot be used.

You will have to remember the state of the pin yourself.

# Answer
> 1 votes
Majenko's answer basically explains the cause - apparently on the SAM3X8E reading the input data register will not show the state being driven on output lines in the way it would on some other devices like the AVR.

However the conclusion that "you will have to remember the state of the pin yourself" is not correct.

According to the data sheet, the output data state can be read from the relevant port's `PIO_ODSR` register. That the Arduino libraries don't do this could be an oversight, but probably is an efficiency decision, as they would need to examine the direction of each pin to determine the register to read for its state.

It would not be hard to make your own functions or macros to read the `PIO_ODSR` \- you could model them on the `digitalInput()` ones.

# Answer
> 1 votes
try editing...

```
Serial.println(digitalRead(pin));

```

to .....

```
Serial.println(digitalRead(pin), DEC);

```

This works on my arduino Leonardo.

# Answer
> 0 votes
Feed the output to a (spare) input pin and `digitalRead()` that pin!

---
Tags: pins, arduino-due
---


# Question
Title: What is LCD bias voltage and where do I have to connect it?
I noticed that I have VB0+, VB0-, VB1+ and VB1- pins on my LCD. In the datasheet it says they are for the "LCD Bias Voltage". I have never heard about that. So what is it? Where do I have to connect it?

Here is the datasheet of the LCD: http://www.buydisplay.com/download/manual/ERC12864-655\_Series\_Datasheet.pdf

# Answer
> 0 votes
You need to look at the interfacing document kindly provided on the same page as that datasheet:

It shows plainly that you need to connect 2.2µF capacitors between the + and - of each pair of pins.

---
Tags: lcd, voltage-level, electronics
---


# Question
Title: Measuring .7 volts on pin 2 and 0.0 on the rest when setting all pins low
Having my Arduino Nano 328P disconnected from any circuitry and setting all pins to `pinMode(OUTPUT)` and writing `LOW` to (almost) all the pins, when I connect my multimeter to every output pin and the Arduino ground, I measure 0.7 volts on pin 2 and 0.0 volts on 3 to 19. Here I mean the pin numbers on the edge of the Nano, not the processor pins.

For my project it worked out fine because I needed those 0.0 and not the 0.7, but I'm afraid it suddenly might not be pin 2 that's 0.7 in the future and my circuit would fail.

> Why is there this one pin giving 0.7 instead of 0.0 and how can I make sure or argue that it will only be pin 2 that gives 0.7?

EDIT as per request, the full test code is below.

```
void setup() {
  for (int i=1;i<20;i++){
  pinMode(i, OUTPUT);
  }
}

void loop() {
  for (int i=1;i<20;i++){
    digitalWrite(i, HIGH);
  }
    delay(3000);
    for (int i=1;i<20;i++){
    digitalWrite(i, LOW);
    }
    delay(3000);
}

```

# Answer
For future reference, thanks to Majenko: these values fall within the expected voltage output range of 0-0.9V, and you cannot be certain it will stay this way. See the datasheet page 313.
> 0 votes

---
Tags: pins
---