message:
Integrating an analog signal using Arduino Due

I have an 2 analog signal, and I want to calculate the difference between 2 signals (A0 and A1), then integrate an analog, but it doesn't work (I just started studying Arduino).

Please could you show me how to deal with this problem?

Thanks a lot

    float analogInPin = A0;
    float analogInPin1 = A1;
    float analogOutPin = DAC1;
    float FeqIn, FeqIn1, FeqIn2, FeqIn3, FeqOut, w, Triarea, Recarea, area, n, y, t;

    void setup() {
      Serial.begin(9600); // use the serial port
    }

    void loop() {
      FeqIn1 = analogRead(analogInPin);
      FeqIn2 = analogRead(analogInPin1);
      FeqIn3 = FeqIn1 - FeqIn2
      // integration
      area(1) = 0;
      y(1) = 0;
      for (n = 1; n = t; t++) {
        Triarea(n+1) = (0.5*t(2))*(FeqIn3(n+1) - FeqIn3(n));
        Recarea(n+1) = t(2)*(FeqIn3(n));
        area(n+1) = (Triarea(n+1) + Recarea(n+1)) + area(n);
      }
    }

The error message is:

    Arduino: 1.6.5 (Windows 8.1), Board: "Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"

    _02.ino:3: error: 'DAC1' was not declared in this scope
    _02.ino.ino: In function 'void loop()':
    _02.ino:20: error: expected ';' before 'area'
    _02.ino:21: error: 'y' cannot be used as a function
    _02.ino:24: error: 'Triarea' cannot be used as a function
    _02.ino:24: error: 't' cannot be used as a function
    _02.ino:24: error: 'FeqIn3' cannot be used as a function
    _02.ino:24: error: 'FeqIn3' cannot be used as a function
    _02.ino:25: error: 'Recarea' cannot be used as a function
    _02.ino:25: error: 't' cannot be used as a function
    _02.ino:25: error: 'FeqIn3' cannot be used as a function
    _02.ino:26: error: 'area' cannot be used as a function
    _02.ino:26: error: 'Triarea' cannot be used as a function
    _02.ino:26: error: 'Recarea' cannot be used as a function
    _02.ino:26: error: 'area' cannot be used as a function
    'DAC1' was not declared in this scope

body:
<!-- language-all: lang-C++ -->

    float FeqIn, FeqIn1, FeqIn2, FeqIn3, FeqOut, w, Triarea, Recarea, area, n, y, t;

    ...

          Triarea(n+1) = (0.5*t(2))*(FeqIn3(n+1) - FeqIn3(n));

I honestly don't know what you are doing here.

Triarea is a float, right? A single variable of type *float*.

What is this?

          Triarea(n+1) = (0.5*t(2))*(FeqIn3(n+1) - FeqIn3(n));

`Triarea(n+1)` looks like you are calling a function called Triarea with the argument n+1.

That doesn't make any sense because it isn't a function.

---

Maybe you mean to treat it as an array?

      Triarea[n+1] = (0.5*t[2])*(FeqIn3[n+1] - FeqIn3[n]);

But you have not declared those variables as arrays.

It is pure guesswork what is going on in your mind.

However your syntax certainly explains the error messages, for example:

<!-- language-all: lang-none -->

    _02.ino:24: error: 'Triarea' cannot be used as a function

---

If I may suggest, read a tutorial on basic C++ programming.


sender: user

sender: assistant

body:
I think your main problem here is a fundamental lack of understanding about C++.  There's numerous basic errors in your code.  Let's take a look at them:

    FeqIn3 = FeqIn1 - FeqIn2

All C++ statements must be terminated by a `;` otherwise it doesn't know where one statement finishes and the next one begins.

    area(1) = 0;
    (and many others)

You have declared a bunch of float variables in the global scope.  You are then trying to use those float variables as functions, and on top of that you are then trying to assign a value to the return value of that function.  That makes absolutely no logical sense whatsoever.

I think you meant to be using arrays of float values.  Arrays are denoted by `[` and `]` not `(` and `)`.  Further, they have to be defined as arrays, including the size of the array, not a single value.  Also in C++ arrays are *zero based* (i.e., they start at index 0 not index 1).

For example, `area` could be defined as:

    float area[1024]; // 1024 floating point values in an array
    // ...
    area[0] = 0;

Next:

    Recarea(n+1) = t(2)*(FeqIn3(n));

I don't even know what to make of this bit...  If I assume you should replace `(...)` with `[...]` for indices to arrays, it still makes no sense.  You're calculating a single value (`FreqIn3 = FreqIn1 - FreqIn2`) then using that as an array (`FreqIn3[n]`) which makes absolutely no sense to me at all.  Then you're using another value `t` which you are incrementing (incorrectly, more on that later), which again you are then trying to use as an array (`t[2]`).  Which is it - arrays or single values? And how do you increment an entire array?

Now the incrementing:

    for (n = 1; n = t; t++)

`n` starts at the value 1.  While `n` is assigned the value `t`, increment `t`.  Now, does that sound logical?  And what is `t`? when that loop starts?  It has no defined value, so it could be anything at all.  And when does the loop end?  Well, since you're using float values for your counters (which is idiotic at best) you won't ever get any integer wraparound, so `t` will never equal `0` and consequently the result of assigning `t` to `n` will never be `0`, so the loop will never end.

I think you need to go back to absolute basics and learn a bit more about syntax of C++, arrays, functions, loops, etc, before embarking on something complex like signal integration.


body:
As previous answers have pointed out, your understanding of C syntax has shortcomings, and you should study C further.  Besides those syntax issues, you may need to revise some of your concepts of how to program.

Firstly, the references you looked at regarding integration may have shown forms like Tₓ₊₁ = (δ/2)·(Vₓ₊₁ – Vₓ) for “triangle area” and Rₓ₊₁ = δ·Vₓ for “rectangle area” [where I've written δ in place of your t(2)].  In spite of the use of subscripts in these formulas, the array concepts mentioned in other answers are not relevant here.  Instead of saving voltage data in arrays, just save and work with two voltage values:  the current differential voltage reading and the previous differential voltage reading.  Letting Vᵣ and Vₓ stand for previous and new voltage differences, use Vᵣ where Vₓ is called for, and Vₓ where Vₓ₊₁ is called for.  At the end of each step, set Vᵣ = Vₓ.

Secondly, making separate computations of “triangle area” and “rectangle area” is verbose, unnecessary, and less accurate than a properly combined computation.  Note that Tₓ₊₁ + Rₓ₊₁, as used in computing areaₓ₊₁, is equal to  (δ/2)·(Vₓ₊₁ – Vₓ) + δ·Vₓ = (δ/2)·Vₓ₊₁ – (δ/2)·Vₓ + δ·Vₓ = (δ/2)·Vₓ₊₁ + (δ/2)·Vₓ = δ·(Vₓ₊₁ + Vₓ)/2.  Thus, instead of those three lines of code using two temporary variables and lots of indices, use code like the following for the integral:

    area += deltaT*(Volt_r + Volt_s)/2;
    Volt_r = Volt_s;

(In the above, `Volt_s` corresponds to your `FeqIn3` value.)

Thirdly, your attempted `for` loop needs to be replaced by an actual `for` loop; and in addition, `deltaT`, a time-step delta, needs to be computed.  (Your `t(2)` needs to represent a change in time, not an absolute time, to represent the time-width of the rectangle and triangle you are adding to the total.)  To get a `deltaT`, read `millis()` after the `analogRead` lines.  For example, you could say:

    Volt_s = analogRead(analogInPin) - analogRead(analogInPin1);
    t_s = millis();
    deltaT = t_s - t_r;
    area += deltaT*(Volt_r + Volt_s)/2;
    t_r = t_s;
    Volt_r = Volt_s;

Fourthly, using two `analogRead`s to get a differential voltage has two problems:  first, any common-mode voltage wastes bits of ADC resolution, so contributes to error; second, the two reads occur at different times so their voltages are not comparable.  Instead, you could use an external op-amp to subtract voltages, or could use the Due's differential-front-end ADC mode, per Section 43.6.8, *Differential Inputs*, on page 1326 in the [ARM Cortex M3 Processor manual](http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf), plus possibly a gain of 1, 2, or 4 (per Section 43.6.9).  Also see: [Analog performance ... of Due's 12 bit ADC](http://www.djerickson.com/arduino/) (including how to speed up `analogReads` on the Cortex), [Differential Sensing with Arduino](http://forum.arduino.cc/index.php?topic=147830.0), [Setting ADC compare mode in a differential input](http://forum.arduino.cc/index.php?topic=194770.0), and [Due pinout diagram](http://forum.arduino.cc/index.php?topic=132130.0).


message:
Arduino Uno vs Arduino Micro timers → pins

**Where do I find the pins relative to timers of each individual Arduino microcontroller?**

As I like Arduino's I already have various samples of them. The one I mostly use is the Uno and Micro for now... I'm planning to also get a Mega and others. Most simple things work on all devices, but if you start with complex code to fasten up things, every device is a little different.
A problem I could not solve for days now is the relation between pins and timers.

I cannot find any information about the Arduino Micro. I also don't know exactly what the proper keywords are that I need to find the relation between timers and pins.

**Example:**
A PWM driver multiplexing

As I for now just got some stuff from my local dealer I have no access to shift registers, PWM drivers and other proper integrated circuits.

So I used the Arduino as a PWM driver for 8 RGB or 24 (3*8) white LEDs.
The code works on Arduino Uno. But as the **Arduino Micro has no *Timer2***, `TCCR2B`, I cannot use the same code on the Arduino Micro.

Even if I understand the code (I wrote a lot in other languages...), some of the Atmel chip specific parameters are not clear.

This function sets the prescaler of the timer:

    void setPwmFrequency(int pin, int divisor){

      byte mode;
      if(pin==5||pin==6||pin==9||pin==10){
        switch(divisor){
          case 1:mode=0x01;break;
          case 8:mode=0x02;break;
          case 64:mode=0x03;break;
          case 256:mode=0x04;break;
          case 1024:mode=0x05;break;
          default:return;
        }
        if(pin==5||pin==6){
          TCCR0B=TCCR0B&0b11111000|mode;
        } else{
          TCCR1B=TCCR1B&0b11111000|mode;
        }
      }else if(pin==3||pin==11){
        switch(divisor){
          case 1:mode=0x01;break;
          case 8:mode=0x02;break;
          case 32:mode=0x03;break;
          case 64:mode=0x04;break;
          case 128:mode=0x05;break;
          case 256:mode=0x06;break;
          case 1024:mode=0x7;break;
          default:return;
        }
        TCCR2B=TCCR2B&0b11111000|mode;
      }
    }

First of all, I probably don't even need this function as soon I know what frequency I want, and so I probably need only two lines to set my three (RGB) pins.

    //Arduino Uno timer setup for pin 9, 10, and 11
    TCCR1B=TCCR1B&0b11111000|0x01; // Pin 9,10
    TCCR2B=TCCR2B&0b11111000|0x01; // Pin 11

1. Correct, I need to set `TCCR1B` only one time?

2. What does the `0b11111000` refer to?

In the setup function there is also this line:

    TIMSK2 = 1<<TOIE2;

3. What does this do?

While the above three questions are not so important until it works, **I need to understand how I can convert those timers to work with Arduino Micro**, but also later with other Arduino boards.

----------

**On Arduino Micro**

There is no timer 2

Do pin 9, 10, and 12 have the same timer?

    ??????=??????&0b11111000|0x01;

Also if I understand correctly the Arduino Micro has:

1. A higher PWM range 1024 vs 255 (UNO)??
2. A much higher frequency available in on Timer4 only for pin 13

**So is there somewhere a table describing the differences between all Arduino timers?**

**Full working (on Arduino Uno) code.**

    unsigned char Prescaler=0;
    unsigned char CurrentLED=0;
    unsigned char LEDValues[8][3];
    unsigned char ports[8]={
      0b00000100,
      0b00001000,
      0b00010000,
      0b00100000,
      0b01000000,
      0b10000000,
      0b00000001,
      0b00010000
    };//PINS 2,3,4,5,6,7,8,12

    #define PrescalerOverflowValue 4

    ISR(TIMER2_OVF_vect){
      if(Prescaler<PrescalerOverflowValue){
        Prescaler++;
      }else {
        Prescaler=0;
        Multiplex();
      }
    }

    void Multiplex(void){
      PORTD&=0b00000011;
      PORTB&=0b11101110;
      analogWrite(9,255-LEDValues[CurrentLED][0]);
      analogWrite(10,255-LEDValues[CurrentLED][1]);
      analogWrite(11,255-LEDValues[CurrentLED][2]);
      CurrentLED<6?(PORTD|=ports[CurrentLED]):(PORTB|=ports[CurrentLED]);
      CurrentLED++;
      if(CurrentLED>7)CurrentLED=0;
    }
    void setPwmFrequency(int pin, int divisor){
      byte mode;
      if(pin==5||pin==6||pin==9||pin==10){
        switch(divisor){
          case 1:mode=0x01;break;
          case 8:mode=0x02;break;
          case 64:mode=0x03;break;
          case 256:mode=0x04;break;
          case 1024:mode=0x05;break;
          default:return;
        }
        if(pin==5||pin==6){
          TCCR0B=TCCR0B&0b11111000|mode;
        }else{
          TCCR1B=TCCR1B&0b11111000|mode;
        }
      }else if(pin==3||pin==11){
        switch(divisor){
          case 1:mode=0x01;break;
          case 8:mode=0x02;break;
          case 32:mode=0x03;break;
          case 64:mode=0x04;break;
          case 128:mode=0x05;break;
          case 256:mode=0x06;break;
          case 1024:mode=0x7;break;
          default:return;
        }
        TCCR2B=TCCR2B&0b11111000|mode;
      }
    }

    void setup(void){

      pinMode(2,OUTPUT);//1
      pinMode(3,OUTPUT);//2
      pinMode(4,OUTPUT);//3
      pinMode(5,OUTPUT);//4
      pinMode(6,OUTPUT);//5
      pinMode(7,OUTPUT);//6
      pinMode(8,OUTPUT);//7
      pinMode(12,OUTPUT);//8
      pinMode(9,OUTPUT);//red
      pinMode(10,OUTPUT);//green
      pinMode(11,OUTPUT);//blue
      setPwmFrequency(9,8);
      setPwmFrequency(10,8);
      setPwmFrequency(11,8);
      TIMSK2=1<<TOIE2;
    }

    void loop(void){
      for(int i=0;i<8;i++){
        //LEDValues[i][0]; // Red
        //LEDValues[i][1]; // Green
        //LEDValues[i][2]; // Blue
      }
    }

body:
> I cannot find any information about the arduino micro. I also don't know exactly what the proper keywords are that i need to find the relation between timers and pins.

* Go to the [products page for the Micro](https://www.arduino.cc/en/Main/ArduinoBoardMicro) on the Arduino web site. You will find that the processor is the ATmega32U4.

* Download the [datasheet for the ATmega32U4](http://www.atmel.com/Images/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf) - it's on that page.

* Download the [reference schematic for the Micro](https://www.arduino.cc/en/uploads/Main/arduino-micro-schematic.pdf) - also on that page.

Now we know the processor, the datasheet tells you about the timers, and the schematic tells you which ATmega32U4 pins are connected to which pins on the Micro board.

---

>  But as the Arduino Micro has no Timer2 TCCR2B i cannot use the same code on the Arduino micro.

True. But it has Timer 1, Timer 3 and Timer 4. You just need to adjust the registers a bit.

---

> Correct, I need to set TCCR1B only one time?

Yes you can do that. Personally I normally stop the timer and then set the parameters in case setting them when it is running has a different effect. eg

    TCCR1A = 0;  // stop timer 1
    TCCR1B = 0;
    TCCR1C = 0;

---
>        TCCR1B=TCCR1B&0b11111000|0x01; //pin 9,10
>
> What do the 0b1111000 refer to?

In this case the first part `TCCR1B & 0b11111000` clears the low-order 3 bits (the rest are ANDed in with 1 so they stay the same as before).

Then it sets the lower-order bit. In this particular case you are setting up a prescaler of 1 times the clock rate.

[![TCCR1b][1]][1]

[![Clock pre-scalers for timer 1][2]][2]

---

>        TIMSK2=1<<TOIE2;
>
>    what does this ?

TIMSK2 is a timer register.

[![TIMSK2][3]][3]

By shifting 1 left "TOIE2" bits it sets that bit (ie., TOIE2 in TIMSK2).

In other words, it enables the overflow interrupt for Timer 2.

---

> On Arduino Micro
> There is no timer 2
> Pin 9,10,12 have the same timer ?

Look at the reference schematic. Yes it looks like it.

[![Micro schematic part][4]][4]

As you can see from that pin 30 (on the chip) is labelled `OC4B` which means it is the "output compare timer 4: B output". That pin has the net name "IO10*" which I presume means it is connected to board pin 10 (pin 30 on the chip).

---

> Also if I understand correctly the Arduino micro has:
>
>    1. a higher PWM range 1024 vs 255 (UNO)??
>    2. a much higher frequency available in on timer4 only for pin 13

No, the Uno has Timer 1 which is 16 bits (up to 65536). The Micro has Timer 4 which is 10 bits and therefore can count up to 1024.

Anyway, the frequency is a function of the clock speed. On either chip, by using a prescaler of 1, and counting up to 1, you can get an 8 MHz frequency (one up, one down from 16 MHz).

The higher number of bits in the timer, the *finer the resolution* - that is you can adjust the frequency in finer steps, and you can adjust the PWM duty cycle in finer steps.

**However** with Timer 4 on the Micro you can, apparently, clock it with 6 times the clock rate (96 MHz) which is used for the USB part of the chip. Setting appropriate bits (I haven't done this personally) you could get that higher frequency.

You can apparently get 96 MHz, 64 MHz or 48 MHz clock frequencies on Timer 4 (as well as the normal ones).

---

*Added in response to comments*

> Pin 12 on the chip has 2 timers, OC0A & OC1C??

Yes, from the datasheet:

> The Output Compare unit 1C and Output Compare unit 2 shares the PB7 port pin for output. The outputs of the Output Compare units (OC1C and OC0A) overrides the normal PORTB7 Register when one of them is enabled (i.e., when COMnx1:0 is not equal to zero). When both OC1C and OC0A are enabled at the same time, the modulator is automatically enabled.

---

> What timer do i need to use for let's say pin 9,10,12 on arduino micro?

Looks like Timer 4.

---

> in arduino ide i can only write analogWrite(255)

That is changing the PWM duty cycle for the timers configured in their default way.

Have a look in wiring.c:

 // timers 1 and 2 are used for phase-correct hardware pwm
 // this is better for motors as it ensures an even waveform
 // note, however, that fast pwm mode can achieve a frequency of up
 // 8 MHz (with a 16 MHz clock) at 50% duty cycle

analogWrite changes the duty cycle, not the frequency.

---

>  You can apparently get 96 MHz... so at the end arduino micro can go faster on timer 4

I'm not sure what you mean by "go faster" here.

---

>  but I actually did not solve the problem. I hope you give me a hint to how to make it work.

It isn't clear really what you want to happen.

* What devices are you driving?
* Why do you need high frequencies?
* What is the underlying problem?

---

### Reference

* [Timers and counters](http://www.gammon.com.au/timers) - mainly about the Atmega328P, however a lot of it applies to the other chips as well.

  [1]: https://i.stack.imgur.com/09JE7.png
  [2]: https://i.stack.imgur.com/pqJhv.png
  [3]: https://i.stack.imgur.com/yYVe8.png
  [4]: https://i.stack.imgur.com/CMnIB.png


body:
You can check `pins_arduino.h` file as well.

    // ATMEL ATMEGA32U4 / ARDUINO LEONARDO
    //
    // D0    PD2     RXD1/INT2
    // D1    PD3     TXD1/INT3
    // D2    PD1  SDA   SDA/INT1
    // D3#    PD0  PWM8/SCL OC0B/SCL/INT0
    // D4  A6  PD4     ADC8
    // D5#    PC6  ???   OC3A/#OC4A
    // D6#  A7  PD7  FastPWM  #OC4D/ADC10
    // D7    PE6     INT6/AIN0
    //
    // D8  A8  PB4     ADC11/PCINT4
    // D9#  A9  PB5  PWM16  OC1A/#OC4B/ADC12/PCINT5
    // D10#  A10  PB6  PWM16  OC1B/0c4B/ADC13/PCINT6
    // D11#    PB7  PWM8/16  0C0A/OC1C/#RTS/PCINT7
    // D12  A11  PD6     T1/#OC4D/ADC9
    // D13#    PC7  PWM10  CLK0/OC4A
    //
    // A0  D18  PF7     ADC7
    // A1  D19  PF6     ADC6
    // A2  D20  PF5     ADC5
    // A3  D21  PF4     ADC4
    // A4  D22  PF1     ADC1
    // A5  D23  PF0     ADC0
    //
    // New pins D14..D17 to map SPI port to digital pins
    //
    // MISO  D14  PB3     MISO,PCINT3
    // SCK  D15  PB1     SCK,PCINT1
    // MOSI  D16  PB2     MOSI,PCINT2
    // SS  D17  PB0     RXLED,SS/PCINT0
    //
    // TXLED D30  PD5     XCK1
    // RXLED D17     PB0
    // HWB    PE2     HWB

There is an array inside the same file with name  `digital_pin_to_timer_PGM` that list the timers also.

    const uint8_t PROGMEM digital_pin_to_timer_PGM[] = {
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     TIMER0B,  /* 3 */
     NOT_ON_TIMER,
     TIMER4A,  /* 5 */
     TIMER4D,  /* 6 */
     NOT_ON_TIMER,

     NOT_ON_TIMER,
     TIMER1A,  /* 9 */
     TIMER1B,  /* 10 */
     TIMER0A,  /* 11 */

     NOT_ON_TIMER,
     TIMER4A,  /* 13 */

     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,

     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
    };


message:
Using L239D with a joystick

Im making a small, controllable toy car. Im using the L239D motor controller to drive 2 6V DC motors, which I intend to control with a joystick. Using the L239D state table (shown below), I can make the car move forward, backward, left and right.

Thats all good, but I want the car to do all the bits in between those movements (drifting slightly left/right etc depending on joystick location). So far I have two separate functions that look at the x-axis and y-axis value from the joystick, scale them and apply a pwm signal. This works fine when only one function is on but ofcourse, they overwrite each other.

My idea then was to create a variable that takes the displacement of the joystick in both axis and divides them, this will be the duty cycle. I then have a delay at the end of each loop which is sized by this duty cycle. The only problem is that the motor stutters a lot and it dosent work very well at all.

I was wondering if anyone has a better idea for getting full motor control with the joy stick rather than the simple block movements (full right, full left, full forward, full backward). Thanks!

[![enter image description here][1]][1]
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/9Aw5R.png
  [2]: https://i.stack.imgur.com/JFiwV.png

body:
The problem here is that you lack the concept of speed with your motors.

It's not enough to turn the motors on or off in the right direction, you have to control the speed of them.

Your left/right control is fine as it is (without the delay in your loop), which is controlled by the inputs being either on or off to define the flow of current through the motor.  Now all you need to do is control the speed of the motors while they are in those states.

Fortunately there is another pair of inputs to the driver chip that you have completely overlooked: `ENABLE1` and `ENABLE2`.  These can accept a PWM signal and define the ratio of on-to-off for the motor on that channel.

So you can connect a PWM signal to each of those inputs (all the other inputs are just straight digital ON/OFF signals), and setting the duty cycle of those PWM signals defines the speed of the motor (0 = stop, 255 = full speed).

Now all you need to do is interpret the joystick properly, for instance:

* Between centre and half-left: Left = Stop, Right = Forward, Enable Right = percentage of half the joystick range
* Between half-left and full-left: Left = Reverse, Right = Forward, Enable Right = 100%, Enable Left = percentage of half the remaining joystick range

And of course reversed for right turns.

You could incorporate into that the forward/backward position of the joystick to add an overall forward or backward speed to the motors so you have full 2D motion.

It may be better to visualise the joystick in [Polar](https://en.wikipedia.org/wiki/Polar_coordinate_system) space instead of simple Cartesian space.  Convert the X/Y coordinates of the joystick's position into an angle and distance from the centre point.  The distance defines the overall speed, and the angle defines how that speed is split between the left and right motors (enable pins), and the direction of those motors (input pins).


message:
Sending joystick data via bluetooth

Joysticks usually have two outputs, one for the x-axis and one for the y-axis. Most of the bluetooth modules I have found only have one tx line.. Is there a way to set them up to use one bluetooth module to connect to arduino?

Im thinking of buying another but I'm wondering if anyone has a better idea than this, or if what I'm thinking is even possible.

Thanks!

body:
Unless you have a very special joystick and a very special bluetooth module you can't just connect a joystick to the TX pin of a bluetooth module.

Instead you have to have the joystick (I am assuming a 2D analog joystick) to a pair of analog inputs on (for instance) an Ardiuno, which then samples the analog values.  It is then up to you to decide what you do with that sampled data - in your case you want to send it out via serial to the bluetooth module (I assume something like a HC-05 or HC-06).  What that data is, and how you interpret it, is up to you.

You could send the data as plain text, such as:

    512,512
    512,512
    384,512
    229,512
    83,512
    83,938
    82,1012

Each line specifies a pair of analog values and is terminated by a line-feed.  The receiving end then needs to read each line, split it on the `,`, and interpret the two values as X/Y readings.

That's quite inefficient, though, and there are better "binary" methods that use less bytes to send the readings, but that is more advanced.


body:
So your joystick is sending bt signals?

If you can't find an appropiate data sheet to that i advise you link it with your pc, start hterm and analyse what exactly is sent.(requires to link the bt devices)

If your joystick is not able to out bt signals I'm not sure what you are trying to do there and need more info

PS: I already did the following: control a robot with your smartphone via bt

control a robot with an old ps2 joystick via cable


message:
What minimum equipment is needed to program the Freematics Vehicle Data Logger?

I was looking for a GPS/OBD2 data logger that logs data to an SD card and eventually arrived at the Arduino powered [Freematics Vehicle Data Logger][1]. It's great that it's programmable, but I have no experience with Arduino.

Reading the documentation, it says that I program the device [either by USBasp or Arduino as ISP][2]. The USBasp is a dongle programmer, but I don't know what is meant by Arduino as ISP.

My goal is to use this device to log data. I don't plan to extensive write programs for it. What is the minimum equipment that I need to have in order to be able to write a bit of code and flash it to the device?

  [1]: http://freematics.com/pages/products/freematics-obd-adapter/
  [2]: http://blog.freematics.com/2014/freematics-obd-ii-adapter-programming-guide/

body:
"Arduino as ISP" refers to using an Arduino board in place of a USBasp.  It involves loading a specific sketch onto the Arduino then using the SPI port (and a few other pins) as the programming interface to the target.

It is most often used to program blank chips for use in breadboards by people who don't have a USBasp.  Great for moving your project from the Arduino board to a breadboard without having to buy a hardware programmer.


message:
Fast Python to arduino communications

I've been communicating with a teensy arduino over USB using pySerial--which has been simple, but slow. With simple write commands from Python and a corresponding read command on the teensy, I can only achieve 200kHz transfer rates. I'm hoping to get over 1MHz at least, but I don't see a path towards that rate.

Are Ethernet shields capable of augmenting for rates over the MHz range? How can I get faster data transfer rates between my computer and arduino? I'm mainly interested in one-way communications (computer directs teensy).

body:
The fastest means of communicating with the Arduino is [SPI](http://www.gammon.com.au/spi). Ethernet shields use that (as do SD cards). It's quite fast, but it has limits. The fastest the SPI clock can go is the CPU (MCU) clock rate divided by 2 (per bit), that is one byte every 16 CPU clock cycles. There is also an overhead of a couple of clock cycles between bytes, so you can reckon on 888,888 bytes absolute maximum (ie. about 868 kHz) on an Arduino running at 16 MHz.

However that's just throwing the data away. It needs to be stored somewhere, compared to something, acted upon. That all takes clock cycles.

That is for the 16 MHz Arduinos. The Teensy 3.1 apparently runs at 72 MHz which is somewhat faster. I haven't timed SPI on that, presumably you can get a faster transmission rate, but I suspect that the ARM processors also take more instructions to do the same thing, so the 72 MHz might not be quite as fast as it looks.

Then you have the issue of how fast you can get data in and out of the Ethernet card, and how fast you can do whatever-it-is you want to do with it, in the processor.


body:
First of all, khz and mhz are not data transfer rates. They are frequencies - "something per second" - did you mean kilobits/second or kilobytes/second (both, confusingly, abbreviated to kbps by various people).

If you have not already done so, you can specify a bitrate for your communications - serial.begin takes a parameter which specifies the speed - most example seem to use 9600 bits/second, you can crank this all the way up to 115,200 bits/second - 12 times the speed. I don't know if this will work with a Teensy, and/or USB. You will probably at least need to specify this in your terminal program and/or pySerial.

I wonder what you are doing that requires 1Mbyte/second communication with an Arduino, and if you can do that a little smarter?

At that rate, the 64kbytes of memory can be filled up in 1/16th of a second.

You can get a faster "information transfer" by increasing the information density - for example, the English word "True" takes up 4 characters = 32 bits , but a logical true value only takes up 1 bit.

If you are processing the data on the Arduino, at 1mbyte/second, you have 72 instructions to do something with that byte before the next one is there - not much time.

You could increase the data rate by pushing the data in in parallel, using multiple pins - e.g. 32 bits in parallel, one on each of 32 pins, one data point per cycle. There would be no practical way to assimilate data at that speed.

If you are sending this from a PC, perhaps some of the data could be processed on the PC before sending?

Another option would be to divide the work over multiple Teensies, with the PC combining the work - e.g. if you have temperature sensors that output 4 byte values, you want to read 250 of them at a rate of 1000 samples per second (= total of 1mbyte/second), then you might be able to run 25 Teensies, each sampling 10 sensors, and each pushing data at 40kbytes/second, rather than one running at 1mbyte/second.

Quite frankly, these are all fairly contrived examples - most sensors can't be read that quickly; even an Arduino's analog read is limited to 10,000 reads per second - if you do nothing else. This produces 100 kbits/second, or 20kbytes per second (each 10-bit read is returned as two bytes, with the remaining 6 bits being 0).


message:
Multiple buttons activating different methods for an LED strip

I am trying to use different buttons to activate different methods for an LED strip. However, when one button is pressed after another has been pressed, I want it to interrupt the first buttons method and begin the second. For example: one button sends a rainbow pattern through the LED strip when pressed, however, while it is cycling through the rainbow, the second button is pressed which sends a white cycle through the LED strip. There will be 24 buttons total. I have gotten this to work with 2 buttons but am having trouble getting it to work for a third. The code is below:

         void loop(){

           if (digitalRead(inPin(1)) == HIGH && lastState == LOW){//if button has just been pressed
               stopCycle();
               theaterChaseRainbow(50);
           }
           if (digitalRead(inPin(2)) == HIGH){
               stopCycle();
               theaterChase(strip.Color(127, 127, 127), 50); // White
           }
           if (digitalRead(inPin(3)) == HIGH){
               stopCycle();
               rainbowCycle(0);
           }

         }

         //Theatre-style crawling lights.
    void theaterChase(uint32_t c, uint8_t wait) {
      for (int j=0; j<100; j++) {  //do 100 cycles of chasing
        if (digitalRead (inPin(1)) == LOW) { //checks that other button(s) have not been pressed
          if (digitalRead (inPin(3) == LOW)){
          for (int q=0; q < 3; q++) {
            for (int i=0; i < strip.numPixels(); i=i+3) {
              strip.setPixelColor(i+q, c);    //turn every third pixel on
            }
            strip.show();

            delay(wait);

            for (int i=0; i < strip.numPixels(); i=i+3) {
              strip.setPixelColor(i+q, 0);        //turn every third pixel off
            }
          }
        }
        }
      }
    }

    void rainbow(uint8_t wait) {
      int i, j;

      for (j=0; j < 384; j++) {
       if (digitalRead (inPin(2)) == LOW) { // 3 cycles of all 384 colors in the wheel
        if (digitalRead (inPin(3) == LOW)){
        for (i=0; i < strip.numPixels(); i++) {
          strip.setPixelColor(i, Wheel( (i + j) % 384));
        }
        strip.show();   // write all the pixels out
        delay(wait);
       }
       }
      }
    }

    uint32_t Wheel(uint16_t WheelPos)
    {
      byte r, g, b;
      switch(WheelPos / 128)
      {
        case 0:
          r = 127 - WheelPos % 128;   //Red down
          g = WheelPos % 128;      // Green up
          b = 0;                  //blue off
          break;
        case 1:
          g = 127 - WheelPos % 128;  //green down
          b = WheelPos % 128;      //blue up
          r = 0;                  //red off
          break;
        case 2:
          b = 127 - WheelPos % 128;  //blue down
          r = WheelPos % 128;      //red up
          g = 0;                  //green off
          break;
      }
      return(strip.Color(r,g,b));
    }

    void rainbowCycle(uint8_t wait) {
      uint16_t i, j;

      for (j=0; j < 384 * 5; j++) {     // 5 cycles of all 384 colors in the wheel
        if (inPin(1) == LOW) {
          if (inPin(2) == LOW) {
        for (i=0; i < strip.numPixels(); i++) {
          // tricky math! we use each pixel as a fraction of the full 384-color wheel
          // (thats the i / strip.numPixels() part)
          // Then add in j which makes the colors go around per pixel
          // the % 384 is to make the wheel cycle around
          strip.setPixelColor(i, Wheel( ((i * 384 / strip.numPixels()) + j) % 384) );
        }
        strip.show();   // write all the pixels out
        delay(wait);

          }
        }
      }
    }

    void stopCycle(){
        int i;
        for (i=0; i < strip.numPixels(); i++) {
          strip.setPixelColor(i, 0);
        }
        strip.show();   // write all the pixels out
    }

body:
<!-- language-all: lang-C++ -->

Inside each inner loop, just test the switches and `return` if they are pressed.

eg.

    //Theatre-style crawling lights.
    void theaterChase(uint32_t c, uint8_t wait) {
      for (int j=0; j<100; j++) {  //do 100 cycles of chasing
        for (int q=0; q < 3; q++) {
          for (int i=0; i < strip.numPixels(); i=i+3)
          {
            strip.setPixelColor(i+q, c);    //turn every third pixel on
          }
          strip.show();
          delay(wait);

          // give up if switches pressed
          if (digitalRead (inPin(1)) == HIGH ||
              digitalRead (inPin(2)) == HIGH ||
              digitalRead (inPin(3)) == HIGH )
            return;

          for (int i=0; i < strip.numPixels(); i=i+3) {
            strip.setPixelColor(i+q, 0);        //turn every third pixel off
          }
        }
      }
    }

---

> am having trouble getting it to work for a third

If that doesn't help please explain the nature of this "trouble".

---

You may need to debounce the switch presses. And you may need to wait for them to release the switch, eg.

     if (digitalRead(inPin(1)) == HIGH && lastState == LOW){//if button has just been pressed
               stopCycle();
               while (digitalRead(inPin(1)) == HIGH)
                  {  }   // wait for switch release
               delay (10);  // debounce
               theaterChaseRainbow(50);
           }


body:
I would normally do this (pseudocode):

    void loop() {
        static state=state_off;
        if (button_1_pushed) {
            state=state_1;
        } elseif (button_2_pushed) {
            state=state_2;
        }
        if (state==state_off) {
            turn_all_leds_off();
        } elseif (state==state_2) {
            shownextframe_rainbow();
        } elseif (state==state_2) {
            shownextframe_chaser();
        }
        delay(1);
    }

In shownextframe_chaser/shownextframe_rainbow, I would probably work out what should be shown based on the current millis() - e.g. if your chaser has 10 lights, and you want it to pulse over 1 second, then each led should be on for 100 millis, so at any instant, the led that should be on is `(millis()/100)` (assuming the led's are numbered for 0 to 9).


message:
Buttons for LED strip only work when held down

I am trying to make a 24 button board that assigns different methods to each button. When a button is pressed, it should interrupt the method of the previous button and begin the new method. Currently, the button has to be held down in order to work. I'm not sure why since the methods should continue without being held down. All 24 methods are similar to the one posted below.

    loop(){
      if (digitalRead(inPin(5)) == HIGH){
        fifthButtonTheatreChaseRedSlow(strip.Color(127,   0,   0), 100); // Red
      }

    void fifthButtonTheatreChaseRedSlow(uint32_t c, uint8_t wait) {
      for (int j=0; j<100; j++) {  //do 100 cycles of chasing
        for (int q=0; q < 3; q++) {
          for (int i=0; i < strip.numPixels(); i=i+3)
          {
            strip.setPixelColor(i+q, c);    //turn every third pixel on
          }
          strip.show();
          delay(wait);

          // give up if switches pressed
          if (digitalRead (inPin(1)) == HIGH ||
                 digitalRead (inPin(2)) == HIGH ||
                 digitalRead (inPin(3)) == HIGH ||
                 digitalRead (inPin(4)) == HIGH ||
                 digitalRead (inPin(6)) == HIGH ||
                 digitalRead (inPin(7)) == HIGH ||
                 digitalRead (inPin(8)) == HIGH ||
                 digitalRead (inPin(9)) == HIGH ||
                 digitalRead (inPin(10)) == HIGH ||
                 digitalRead (inPin(11)) == HIGH ||
                 digitalRead (inPin(12)) == HIGH ||
                 digitalRead (inPin(13)) == HIGH ||
                 digitalRead (inPin(14)) == HIGH ||
                 digitalRead (inPin(15)) == HIGH ||
                 digitalRead (inPin(16)) == HIGH ||
                 digitalRead (inPin(17)) == HIGH ||
                 digitalRead (inPin(18)) == HIGH ||
                 digitalRead (inPin(19)) == HIGH ||
                 digitalRead (inPin(20)) == HIGH ||
                 digitalRead (inPin(21)) == HIGH ||
                 digitalRead (inPin(22)) == HIGH ||
                 digitalRead (inPin(23)) == HIGH ||
                 digitalRead (inPin(24)) == HIGH)
                   return;

          for (int i=0; i < strip.numPixels(); i=i+3) {
            strip.setPixelColor(i+q, 0);        //turn every third pixel off
          }
        }
      }
    }

Not sure if it's a hardware issue or a software issue.

body:
It's a software issue.  You are basically saying "If this button is currently pressed down then run this sequence once", rather than "If this button has transitioned from OFF to ON then set my current sequence to X"

You need to learn about the [Finite State Machine](http://hacking.majenko.co.uk/finite-state-machine) and about switching from one state to another (or one selected sequence to another) when a button *changes* state not when it is *in* a state.

So basically the whole logic of your program is flawed and needs re-working.


body:
Related to <https://arduino.stackexchange.com/questions/14320/multiple-buttons-activating-different-methods-for-an-led-strip>

     // give up if switches pressed
      if (digitalRead (inPin(1)) == HIGH ||
             digitalRead (inPin(2)) == HIGH ||
             digitalRead (inPin(3)) == HIGH ||
             digitalRead (inPin(4)) == HIGH ||
             digitalRead (inPin(6)) == HIGH ||
             digitalRead (inPin(7)) == HIGH ||
             digitalRead (inPin(8)) == HIGH ||
             digitalRead (inPin(9)) == HIGH ||
             digitalRead (inPin(10)) == HIGH ||
             digitalRead (inPin(11)) == HIGH ||
             digitalRead (inPin(12)) == HIGH ||
             digitalRead (inPin(13)) == HIGH ||
             digitalRead (inPin(14)) == HIGH ||
             digitalRead (inPin(15)) == HIGH ||
             digitalRead (inPin(16)) == HIGH ||
             digitalRead (inPin(17)) == HIGH ||
             digitalRead (inPin(18)) == HIGH ||
             digitalRead (inPin(19)) == HIGH ||
             digitalRead (inPin(20)) == HIGH ||
             digitalRead (inPin(21)) == HIGH ||
             digitalRead (inPin(22)) == HIGH ||
             digitalRead (inPin(23)) == HIGH ||
             digitalRead (inPin(24)) == HIGH)
               return;

Time to learn about loops, buddy. How about:

    for (int i = 1; i <= 24; i++)
      if (digitalRead (inPin (i)) == HIGH)
        return;

My guess about this particular problem is that you are not debouncing. You enter the function, one of the bounces is detected, and you leave the function. I mentioned debouncing in your other, closely-related, thread.

---

Let me show you what a switch bounce looks like. Using a normal switch from my parts drawer, this is what you see when you press it:

[![Switch bounce][1]][1]

See that? It looks to the (fast) Arduino that you pressed the switch 20 or 30 times. That is the physical metal bouncing back and forwards. So if you test for one press, and then stop when you get another, your chances of it working are rather slim. That's why a simple delay of (say) 10 ms after detecting a change in state of the switch can help debounce it.

See: [Switches tutorial](http://www.gammon.com.au/switches)

  [1]: https://i.stack.imgur.com/tr6LT.png


message:
Arduino timers. How they work

**Explain this line in simple words.**

    TCCR0B=TCCR0B&0b11111000|0x01;

As the variuos arduinos have different chips. They also have different timers and different pins which use them.

Lately i want to rewrite a code(Arduino Uno) to make it work on a Arduino Micro.

I need to understand how this works in simple words. I normally write web based code(javascript,php...). Just lately i started writing in c++ or a "simplified" c++ in the arduino ide. It's not that hard. But some specific parameters are hard to understand for me.
Shortcuts like the following.

    TCCR0B=TCCR0B&0b11111000|0x01;

What does that?

    TCCR0B

`TCCR` = Prefix for timers. Correct?

`0` = Timer1 or 0 call it however you want.

`B` = **What is A,B,C and sometimes D for?** What does this?why in that code is the programmer using B and not A,C or D

`TCCR0B=` Timer 0 B is equal to:

`TCCR0B&` **if Timer 0 B return True .. exists "&" ?**

`0b11111000` **What is this?** i already asked this and the answer was something like "clears the low-order 3 bits". Like i said, i'm not very familiar with c++, bits and other stuff regarding the arduino. I now less about the various chips and also about how they implemented the various parameters from arduino ide to work with those chips. I know that i have here 8 values that i can change from 0 to 1. What does those values change relative to the timer. Please think of me as a 6 year old.

`|0x01;` I got this... it sets the prescaler... 1,8,32.. some timers have differnet values... no problem. I need it at 1.

body:
First I'll tackle what

    TCCR0B=TCCR0B&0b11111000|0x01;

means from a pure programming perspective:

Let's break it down into parts:

    TCCR0B = TCCR0B & 0b11111000 | 0x01;

`TCCR0B` is a register. It could be any variable really - it's just "a value" in this context. Just because it happens to control one of the timers is besides the point.

`0b11111000` is a binary representation of a value.  It's the same as the hexadecimal number `0xF8`.  F is 15.  15 in binary is 1111.  8 is 8 in both hexadecimal and decimal.  8 in binary is 1000.  Put the two together and you have 11111000.  Incidentally, in decimal that is 248.

`0x01` is hexadecimal for 1 in decimal - it's also 1 in binary.

Between them are *bitwise* operators - `&` is a bitwise `AND` operation, and `|` is a bitwise `OR` operation.  `AND` calculates which bits in a pair of binary numbers are both on, and `OR` calculates which bits in a pair of binary numbers are on in either of the numbers.

So take the first one first.  Say the `TCCR0B` register contains the value `0x6F`, which is 157 in decimal, or 01101111 in binary.  The first operation is to `AND` that with 11111000:

    01101111
    11111000 AND
    --------
    01101000

You can see that the last three bits of the value have been cleared because they aren't 1 in both the left and right operands to the `&` operator.

Ok, so the next operation is to `OR` it with 0x01:

    01101000
    00000001 OR
    --------
    01101001

Effectively the two operands have been overlaid on each other and any bits that are set in either operand will be reflected in the result.

So finally the value is then stored in `TCCR0B`.

In summary that specific operation *clears the lower three bits then sets the lowest bit* of TCCR0B.

Now what that actually means with respect to what the TCCR0B register does can be gleaned from the datasheet for the chip.  For instance, take the ATMega328P chip from the Arduino UNO board.  Section 14.9.2 "TCCR0B – Timer/Counter Control Register B" of [the datasheet](https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf) describes that register in detail.  The bit-wise overview looks like this:

[![enter image description here][1]][1]

Those bits all correspond 1:1 to the binary bits from above in the same order.  So the first stage, clearing of the lowest three bits, sets CS02, CS01 and CS00 to 0.  The second stage, ORing 0x01, then sets CS00 to 1.

The datasheet goes on to tell you what those mean:

> * Bits 2:0 – CS02:0: Clock Select
>
> The three Clock Select bits select the clock source to be used by the Timer/Counter.

And a table to show the different meanings of the possible values:

[![enter image description here][2]][2]

The value that has been masked and created for those three bits is, of course, 001, which in that table is "CLK I/O / (No prescaling)", which is the timer running at the frequency of the IO clock.  If you were to set those bits to 010, you'd get "CLK I/O / 8 (From prescaler)".  So your masking would change to:

    TCCR0B = TCCR0B & 0b11111000 | 0x02;

Or more explicitly so you can see the bits easier:

    TCCR0B = TCCR0B & 0b11111000 | 0b010;

As to what the "A" and "B" mean (TCCR0A and TCCR0B), there are two registers that are used to control the timer.  They each serve a different purpose.  TCCR0A has bits that control PWM, and TCCR0B has bits that control the timer itself.

Not to be confused with OCR0A and OCR0B which are two separate numeric values that are compared to the timer's counter value TCNT0 to provide two separate PWM outputs (OC0A as Uno pin D6, and OC0B as Uno pin D5) synchronised from the same timebase. (See sections 14.9.4 OCR0A – Output Compare Register A and 14.9.4 OCR0B – Output Compare Register B in the datasheet)

  [1]: https://i.stack.imgur.com/eQKLG.png
  [2]: https://i.stack.imgur.com/eMoHl.png


body:
The answer, at high level, is: each bit (or group of bits) in a register is, in practice, like a knob that can configure certain parts of the HW.
For each peripheral you want to control, you have to understand the block diagrams, the related knobs and in which registers those knobs are located.
Sometimes there are multiple (almost) identical instances of a certain HW block and in the ATMega case these instances are often addressed with letters.
So registers that have almost identical names, apart from A, B, C, are basically identical, but each of them will affect a separate instance of a certain peripheral.
Depending on which pins or interrupt you want to use, you can choose the specific instance of a certain peripheral.
You should check the ATMega328p programmer's manual (it's 2k pages, but it's easy to find the desired section.)


body:
To add to Majenko's very thorough and excellent answer (which I can't yet upvote because I'm very newbie):
Let's try to hone in on the line of code you need:

    TCCR0B=TCCR0B&0b11111000|0x01;

On that particular Ardiuno, TCCR0B is the register that controls the rate of that particular timer. More specifically, the lowest 3 bits (the last in the 8-bit value) control the prescaler. The manufacturer labels those as CS02, CS01, and CS00. The combination of 1s and 0s in those three bits determines if the clock time is scaled or not, and by how much (or even if there is an external clock source). The reproduced table 14-9 will tell you how much the clock is "slowed down". This lets you create a 1Hz (1-second) timer, for example, rather than the 16Mhz (or whatever your particular board runs at) by scaling down how fast the timer "ticks".
If you google "Arduino hardware timer calculator" or similar, you can find very helpful tools to help you set the clock frequency you want. *Do that,* since there are dangers to setting the wrong values, and your compiler may not catch what can be a serious error.

I only learned about hardware timers after exploring Arduino for a few years. Turns out they are very, very useful!


message:
Arduino Uno Rx/Tx + Arduino Serial

I was wondering if I can use the Rx and Tx Hardware on the Arduino Uno and also add another Rx/Tx pins using SoftwareSerial at the same time ? cause I need two to communicate with two motor Controllers (Roboclaw controller)
Thx

body:
Yes, you can.  That's the purpose of the SoftwareSerial - to allow you to complement the hardware TX/RX with other pins defined by software.

One thing to note with SoftwareSerial - it's half duplex. It can either send or receive, it can't receive while it's sending.


body:
You can, but be aware that SoftwareSerial can cause problems if you need strict timing, as it will keep the Arduino stuck while it is receiving, as it polls in interrupt context.

I would recommend to check which one of the two serial channels is more likely to receive data and use the real HW Serial port for it.

The duration of the polling of the SoftwareSerial library is also influenced by the bitrate used on the port: the higher the bitrate, the shorter the duration of the lockups, so try to use the highest bitrate you can afford, on the Software Serial port.

In case you find out that you cannot afford letting SW handle one of the 2 serial ports, you can try the [Arduino Mega 250][1], which has several UART HW blocks.

About the specific use case: if either of your motor controllers supports I2C or SPI, you could consider using that, as alternative to the SoftwareSerial.

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560


message:
counting pulses from encoder on interrupt 0 pin every 50 ms

I want to calculate the number of pulses coming from motor1 encoder pin2 (Int0) as input , and motor 2 encoder pin3 (Int1), I am working now for the first motor (just for the first motor ) so I set timer 2 to count 50 ms then throw flag in this moment I have to send the number of pulses to my screen, but not succeeded cause i see   on my screen zeros and ascii caracters but not the  number of pulses.:this my code .

     volatile int  pulses = 0;

     int flag=0;
     int setbit = 0;
     int encoder_in = 2;
     void count() {

           pulses++;
         }

      void setup()
       {

     Serial.begin(115200);
     pinMode(encoder_in, INPUT);
    digitalWrite(2, HIGH); //Enable pullup

    // initialize timer2
     noInterrupts();           // disable all interrupts

    TCCR2A = 0x00;
     TCCR2B = 0x07;
    TCNT2 = 0x64;
    //EIMSK = 0x03;     // Enable external interrupt INT0
    //EICRA = 0x0f;    // Trigger INT0 on falling edge

     TIMSK2 |= 0x01;  // enable timer compare interrupt
    interrupts();             // enable all interrupts
    attachInterrupt(0,count,RISING);

     }
      ISR(TIMER2_OVF_vect)
    {
    TCNT2 = 0x64;            // preload timer
     setbit=setbit+1;
      if(setbit==5)
      {
      flag=1;
     setbit=0;

       }
    }

     //ISR(EXT_INT0_vect)
     //{ pulses++; }

     void loop()
    {

     if (flag==1)
     {

       Serial.println(pulses);
        pulses=0;

      }
      }

body:
Check the Baud Rate in Serial Monitor. If baud rate is not correct i.e. 9600 bps then it will show garbage.

Remove the Timer and Wire Libs

add this code in void setup()

    attachInterrupt(0,void_counter,RISING);

the above is for the the external interrupt input.

and attach your sensor/incoming pulse wire on Pin 2 on arduino.

make a new function like this

    void_counter(){
    pulses++;
    }


body:
<!-- language-all: lang-C++ -->

Your technique looks convoluted to me. How about this?

    volatile bool counting;
    volatile unsigned long events;

    unsigned long startTime;
    const unsigned long INTERVAL = 50;  // ms

    void eventISR ()
      {
      if (counting)
        events++;
      }  // end of eventISR

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      pinMode (2, INPUT_PULLUP);
      attachInterrupt (0, eventISR, RISING);
      }  // end of setup

    void showResults ()
      {
      Serial.print ("I counted ");
      Serial.println (events);
      }  // end of showResults

    void loop ()
      {
      if (counting)
        {
        // is time up?
        if (millis () - startTime < INTERVAL)
          return;
        counting = false;
        showResults ();
        }  // end of if

      noInterrupts ();
      events = 0;
      startTime = millis ();
      EIFR = bit (INTF0);  // clear flag for interrupt 0
      counting = true;
      interrupts ();
      }  // end of loop

---

### Explanation

Using a timer to detect when 50 ms is up isn't particularly helpful in this case. You can't do printing inside an ISR, so you would have to set a flag that can be checked in the main loop.

If you are going to check a flag anyway, you may as well just check if the time is up, as my code does.

Inside the ISR, I stop adding to `events` if the flag `counting` is false. This is to stop `events` being changed at the exact moment it is being printed.


message:
How can I add additional boards to Eclipse with the Arduino add-on with only a URL, not a zip file

I want to add the following boards:

[https://redbearlab.github.io/arduino/package_redbearlab_index.json][1]

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

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

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

  [1]: https://redbearlab.github.io/arduino/package_redbearlab_index.json

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

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


message:
How to power an Arduino Uno with 3 1.5V batteries?

I have an **Arduino Uno** *(a SainSmart model, actually)*. I intend to power it with three 1.5V batteries. I measured them and they yield 4.67V in total. The Arduino requires 5V.

# The question is, if the arduino will work this way.

I'm not powering complicated microcontroller components here. These components are used:

* A buzzer
* An LED
* A unit of 4 seven segment displays
* A couple of buttons as input elements

If the volume or brightness of these components is slightly decreased, it doesn't matter at all. But I would like to know if it will work in the first place.

# And also...

Where exactly do I plug the power source in? The power jack, the USB jack, pins, somewhere else?

---

**The schematic looks like this**, just to illustrate it. I'm not a good drawer, but you'll get the idea...

[![schematic][1]][1]

  [1]: https://i.stack.imgur.com/6OazX.png

body:
The Arduino doesn't *require* 5V.

The Atmel chip on the board *requires* somewhere between 1.8V and 5.5V, the Arduino just happens to have chosen 5V as a good common widely used voltage to run at.

If you provide a voltage within that range to the +5V pin the board will operate.  There's a couple of caveats though:

* Anything below about 4V will mean the 3.3V regulator won't be working right, so the 3.3V pin won't be functioning properly
* At lower voltages the Atmel chip can't operate reliably at higher frequencies, which is why 3.3V Arduino boards operate at 8MHz instead of 16Mhz.

So 3 x AA batteries is a perfect power source for running the Arduino, direct into the 5V pin.  Just make sure that you don't power it any other way at the same time or you'll be pumping 5V into your batteries.  You may want to add a Schottky diode in series with your battery + (between battery + and the 5V pin) to stop that ever causing a problem.  Choose one with a very low forward voltage drop though, otherwise you could end up dropping too much of your precious voltage over the diode.

By the way, when you're powering it from USB the 5V could be anywhere between 4.75V and 5.25V.


body:
As per @Majenko's answer, yes, this will work fine.

Some caveats: the Atmel chip at the center of the Arduino has brown-out detection - if it drops below a certain voltage, the chip will shut down. This voltage is selectable: 4.3v, 2.7v, 1.8v, or off. The factory default for the chip is "off", I found a reference that the Uno sets this at 2.7V.

Also, if you are powering anything else with your battery, e.g. a motor, the voltage is will drop - if it drops below the brownout, the arduino will shut down (usually also shutting down the external device, causing the voltage to rise again, causing it to power up again). An LED (with a correct resistor) should be fine.


body:
You can power the Arduino via the 5V pin - but you need make sure you disconnect it when you are connected via USB - ie. don't power both the 5V pin and via the USB.

Any even better way is to power it from the USB socket - I use those emergency Phone battery packs, but you could cut up a usb cable and use that - this is a much better socket fit to use than the 5v pin and more energy efficient than passing a higher voltage through the 9V supply.


body:
For battery-operated Arduino Uno's I recommend thinking bigger (in terms of power, not physical size).

I power several by using 3x 18650 batteries in series, (providing about 14 Volts, connected to a 4x USB 5 Volt module.

The Unos are connected to power by a standard USB cable (into the programming port), and then you also have 3 other 5V USB charging or power ports available.

Or you can get a small converter unit that provides just one 5V USB.

Either way, bringing the power to the UNO is as simple as using the programming cable that comes with the board.

Or you can use any other converter and use wires to bring in Vin and GND.

You don't need to use 3 of the 18650s.  2 will do fine.  Or 4 in series/parallel for longer battery life.  No converter would be needed but again you would need wires to bring the voltage into the Unos.

18650s are very common, and are inexpensive.  They pack a whole lot more mAh than any AA battery you will find.

One warning about buying 18650s:  There are Chinese companies that advertise 9,800 mA batteries.  Don't believe it.  3,000 is about the max any reputable manufacturer will claim.


message:
I can upload via USB but not FTDI

I have a Adafruit Pro Trinket. I'm having issues getting GPS and and SD card working together. The trinket can be connected via USB but there is no serial connection do debugging my program is hard.

[![enter image description here][1]][1]

I purchased an FTDI connector from sparkfun, installed the FTDI software and connected to the trinket. My code complies but it won't flash. The error is confusing:

Can anyone please help me figure out how to get it to flash?

    Arduino: 1.6.4 (Mac OS X), Board: "Pro Trinket 3V/12MHz (FTDI)"

    Sketch uses 19,896 bytes (69%) of program storage space. Maximum is 28,672 bytes.
    Global variables use 1,476 bytes of dynamic memory.
    avrdude: ser_open(): can't open device "/dev/cu.usbmodem1a21": No such file or directory
    ioctl("TIOCMGET"): Inappropriate ioctl for device
    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Here is the "verbose" version of the error:

    Arduino: 1.6.4 (Mac OS X), Board: "Pro Trinket 3V/12MHz (FTDI)"

    Using library SPI in folder: /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SPI
    Using library Adafruit GPS Library in folder: /Users/futurebird/Documents/Arduino/libraries/Adafruit-GPS-Library-master
    Using library SoftwareSerial in folder: /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial
    Using library SdFat in folder: /Users/futurebird/Documents/Arduino/libraries/SdFat (legacy)

    /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=12000000L -DARDUINO=10604 -DARDUINO_AVR_PROTRINKET5FTDI -DARDUINO_ARCH_AVR -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/variants/eightanaloginputs -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SPI -I/Users/futurebird/Documents/Arduino/libraries/Adafruit-GPS-Library-master -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial -I/Users/futurebird/Documents/Arduino/libraries/SdFat /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp -o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.o
    Using previously compiled file: /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SPI/SPI.cpp.o

    (^^repeats many times for different files)

    /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-gcc -Wall -Os -Wl,--gc-sections -mmcu=atmega328p -o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.elf /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SPI/SPI.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/Adafruit GPS Library/Adafruit_GPS.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SoftwareSerial/SoftwareSerial.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/MinimumSerial.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdFatBase.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdFatUtil.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdSpiCard.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdSpiSAM3X.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdSpiSTM32F1.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdSpiTeensy3.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatFile.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatFileLFN.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatFilePrint.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatFileSFN.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatVolume.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FmtNumber.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/fstream.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/istream.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/ostream.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/StdioStream.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/core.a -L/var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp -lm
    /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.elf /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.eep
    /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy -O ihex -R .eeprom /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.elf /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.hex

    Sketch uses 19,896 bytes (69%) of program storage space. Maximum is 28,672 bytes.
    Global variables use 1,476 bytes of dynamic memory.
    /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.usbmodem1a21 -b115200 -D -Uflash:w:/var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.hex:i

    avrdude: Version 6.0.1, compiled on Apr 14 2015 at 16:30:25
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
             User configuration file is "/Users/futurebird/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/cu.usbmodem1a21
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: ser_open(): can't open device "/dev/cu.usbmodem1a21": No such file or directory
    ioctl("TIOCMGET"): Inappropriate ioctl for device

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

---------------------------
UPDATE
---------------------------
I looked in the /dev/ directory and found these which match the menu in Arduino.

cu.Bluetooth-Incoming-Port
cu.Bluetooth-Modem
cu.JabraREVOa400-SPPDev
cu.LightBlue-Bean

[![enter image description here][2]][2]

The above files are int the dev folder but not cu.usbmodem1a21. How can I get it? Or is it looking for the wrong file?

This is what my board selection looks like. I think the issue is the port?

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/p0OBI.jpg
  [2]: https://i.stack.imgur.com/WKYpG.jpg
  [3]: https://i.stack.imgur.com/u2wsB.jpg

body:
Things to check:

 - Does the file exist? check with `ls` if the file that avrdude tries to open is actually there

 - Do you have the right to open it? Opening a serial port requires having the appropriate rights, iow you user belongs to the same group that the device belongs to.
On linux this is usually wheel or dialout, depending on the distro. Again, `ls -la` is your friend.

 - Is your device identified correctly? Meaning that you are not trying to have avrdude address the device wit the wrong protocol.


message:
Run a part of code upon call

Lets say I have something that sends a command to the Arduino (for example, a PC sending through serial, Ethernet, etc). I want the Arduino to "check" what command it is and run a specific function linked to that command.

I don't need a very explanatory answer, just give me something so I can learn from. A sketch that shows a similar idea would be good, I can try to interpret it and adapt/remake for me.

The idea is to use the Arduino for a lot of different things. Let's say:

1. Turn a bunch of leds on/off;

2. Read data from a sensor and send it through Ethernet/I2C/Serial;

3. Control a servo.

But I want the Arduino to do that when I tell it to (in this case, sending the command through serial, etc). So let's say I send it 1, I'll want it to run the 1 function (turning the LEDs on/off).

I already took a [tutorial course on Arduino programming](http://sheepdogguides.com/arduino/FA1main.htm), but I'm clueless on how to do this job.

body:
<!-- language: lang-C++ -->

If you just want some example code, here is a smallish sketch I wrote that controls some LEDs via a shift register. Exactly how the shift register works isn't important, but you can see the basic idea for taking input from the serial port and decoding it:

    #include <SPI.h>

    const byte LATCH = 10;

    const byte numberOfChips = 4;
    const byte maxLEDs = numberOfChips * 8;

    byte LEDdata [numberOfChips] = { 0 };  // initial pattern

    void refreshLEDs ()
      {
      digitalWrite (LATCH, LOW);
      for (int i = numberOfChips - 1; i >= 0; i--)
        SPI.transfer (LEDdata [i]);
      digitalWrite (LATCH, HIGH);
      } // end of refreshLEDs

    // how much serial data we expect before a newline
    const unsigned int MAX_INPUT = 10;

    void setup ()
    {
      Serial.begin(115200);
      SPI.begin ();
      refreshLEDs ();
    } // end of setup

    // here to process incoming serial data after a terminator received
    void process_data (char * data)
      {
      Serial.print ("Got command: ");
      Serial.println (data);

      // C: clear all bits
      switch (toupper (data [0]))
        {
         case 'C':
            {
            for (int i = 0; i < numberOfChips; i++)
              LEDdata [i] = 0;
            Serial.println ("All bits cleared.");
            refreshLEDs ();
            return;
            }

        // S: set all bits
        case 'S':
            {
            for (int i = 0; i < numberOfChips; i++)
              LEDdata [i] = 0xFF;
            Serial.println ("All bits set.");
            refreshLEDs ();
            return;
            }

        // I: invert all bits
        case 'I':
            {
            for (int i = 0; i < numberOfChips; i++)
              LEDdata [i] ^= 0xFF;
            Serial.println ("All bits inverted.");
            refreshLEDs ();
            return;
            }
        } // end of switch

      // otherwise: nnx
      //   where nn is 1 to 89 and x is 0 for off, or 1 for on

      // check we got numbers
      for (int i = 0; i < 3; i++)
        if (!isdigit (data [i]))
          {
          Serial.println ("Did not get 3 digits.");
          return;
          }

      // convert first 2 digits to the LED number
      byte led = (data [0] - '0') * 10 + (data [1] - '0');

      // convert third digit to state (0 = off)
      byte state = data [2] - '0';  // 0 = off, otherwise on

      if (led > maxLEDs)
          {
          Serial.println ("LED # too high.");
          return;
          }

       led--;  // make zero relative

       // divide by 8 to work out which chip
       byte chip = led / 8;  // which chip

       // remainder is bit number
       byte bit = 1 << (led % 8);

       // turn bit on or off
       if (state)
         LEDdata [chip] |= bit;
       else
         LEDdata [chip] &= ~ bit;

      Serial.print ("Turning ");
      Serial.print (state ? "on" : "off");
      Serial.print (" bit ");
      Serial.print (led & 0x7, DEC);
      Serial.print (" on chip ");
      Serial.println (chip, DEC);

      refreshLEDs ();
      }  // end of process_data

    void loop()
    {
    static char input_line [MAX_INPUT];
    static unsigned int input_pos = 0;

      if (Serial.available () > 0)
        {
        char inByte = Serial.read ();

        switch (inByte)
          {

          case '\n':   // end of text
            input_line [input_pos] = 0;  // terminating null byte

            // terminator reached! process input_line here ...
            process_data (input_line);

            // reset buffer for next time
            input_pos = 0;
            break;

          case '\r':   // discard carriage return
            break;

          default:
            // keep adding if not full ... allow for terminating null byte
            if (input_pos < (MAX_INPUT - 1))
              input_line [input_pos++] = inByte;
            break;

          }  // end of switch

      }  // end of incoming data

      // do other stuff here like testing digital input (button presses) ...

    }  // end of loop

---

Example of commands understood by the above code:

    C    <-- clear all LEDs
    S    <-- set (turn on ) all LEDs
    I    <-- invert all LEDs (turn off if on, and vice-versa)
    021  <-- turn LED 02 on
    020  <-- turn LED 02 off
    161  <-- turn LED 16 on

This code processes a 3-digit string as:

    nnS

Where "nn" is the LED number and S is the new state (1 = on, 0 = off).

---

### Other examples

* There is a more elaborate example on my page about [using a 74HC595 output shift register as a port-expander](http://gammon.com.au/forum/?id=11518)

* [How to process incoming serial data without blocking](http://gammon.com.au/serial)

* [State machines](http://gammon.com.au/statemachine)


body:
If you want it really barebones and easy, you can checkout the Arduino "Dimmer" example sketch.

Instead of changing the brightness of an attached pin, you could take the input you send it over the serial console and execute various functions, depending on what you receive.

Something like this:

    boolean newCommand = false;
    void setup()
    {
      // initialize the serial communication:
      Serial.begin(9600);

      // other setup stuff here
    }

    void loop()
    {
      byte command;

      // check if data has been sent from the computer:
      if (Serial.available())
      {
        // read the most recent byte (which will be from 0 to 255):
        command = Serial.read();
        // say that you received a new command
        newCommand = true;
      }

      // is there a new command?
      if (newCommand == true)
      {
        // do something depending on what command you received
        switch(command)
        {
          // if you receive command "1", do something
          case 1: functionWhatever();
                  break;  // "break" out of the switch. otherwise it would continue executing the following commands as well
          case 2: functionWhatever2();
                  break;
          //for cases that are not caught, send out an error
          default: Serial.write("invalid command");
                  break;
        }
      }
    }

---

If you want to use an existing library, you might want to check out:
[EasyTransfer][1].

It can be used for communication between two Arduinos, which you then can use to execute functions on the other side of the line.

The code itself is relatively simple, so you might be able to adapt it to communicate with a processing script on your computer for example.

  [1]: https://github.com/madsci1016/Arduino-EasyTransfer


message:
Can wifi shield connect to local network without internet?

I have an Arduino Uno and a Texas Instruments CC3000 WiFi shield. I need to connect the Arduino to a local network which has no Internet access so that it can send information to a computer also connected to the same local network. I am using a Linksys WRT120N for the local network.

I can't use the Internet access WiFi because it is WPA2 Enterprise which is why I created the local network. Currently the computer is connected to the local network via WiFi.

I have downloaded and installed the correct library but when I run the connection test, it searches for Internet access which doesn't exist and sends back errors.

How do I verify that it is connecting to the local network?

Btw, I have almost no experience coding an Arduino but I have access to people who are proficient; However, they have no experience with a WiFi shield.

body: If you have created your own local network, you may need a DHCP server to give it an IP address, or you will have to configure your Arduino with a static ip. I can't think of a reason why it would need internet access, but it is not uncommon for devices to refer (incorrectly) to connectivity issues on the local network as "internet" issues.


message:
Usage of SPI inside an ISR

I learned, that SPI-code uses interrupts. So is it true then, that I can't use SPI related code inside an ISR?

Background: I want to capture one or more revolution speeds with an MCP23S17. I rewired the interrupt lines to INT1 and INT2 accordingly to get the interrupts at the Arduino.

I thought it was good to fetch the port registers from the MCP23S17 inside the ISR, but this apparently doesn't work.

Is the only thing I can do in my ISR set a flag for another test in the main loop? And let a routine called from lood() then poll the registers from the port expander? This opposes the idea to fetch the relevant data which issued the interrupt ASAP.

body:
SPI doesn't use interrupts.  It references the interrupt flag to know if a transfer has been completed, but it doesn't actually have interrupts enabled:

    SPDR = data;
    asm volatile("nop");
    while (!(SPSR & _BV(SPIF))) ; // wait
    return SPDR;

It should be perfectly possible to use SPI within the interrupt - indeed there is portions of the SPI API that deal specifically with this - see https://www.arduino.cc/en/Reference/SPIusingInterrupt for instance.


message:
How can an Arduino Mega 2560+Wifi Shield 2.0 (SeeedStudio) receive data from database in a XAMPP server on my PC?

I'm trying to connect my Arduino Mega via Wifi to my XAMPP server. My main objective is get a value from my database and store it on a variable in Arduino code. With this new variable I'll be able to control the rest of the program... So I need your help. Can someone give me advice?

I already tried every thing that I found on the internet but it just doesn't work.

I think that the simple way is to send a GET request to the server and read its response... But for some reason I can't send a GET request through...

I tested it on the browser directly and the value shows up, so I think that the server side is all right.

Here is my Arduino code:

    #include <Arduino.h>
    #include <SoftwareSerial.h>
    #include "WiFly.h"
    #include "HTTPClient.h"

    #define SSID      "mySSID"
    #define KEY       "myKEY"
    #define AUTH      WIFLY_AUTH_WPA2_PSK
    #define HTTP_GET_URL "http://192.168.1.80/xampp/training/send_data_db.php/?temp=0"

    // Pins' connection
    // Arduino       WiFly
    //  2    <---->    TX
    //  3    <---->    RX
    SoftwareSerial uart(10, 11);
    WiFly wifly(uart);
    HTTPClient http;
    char get;

    void setup() {
      Serial.begin(9600);
      Serial.println("------- WIFLY HTTP --------");
      uart.begin(9600); // WiFly UART Baud Rate: 9600
      // Wait WiFly to init
      //  delay(3000);

      // check if WiFly is associated with AP(SSID)
      if (!wifly.isAssociated(SSID)) {
        while (!wifly.join(SSID, KEY, AUTH)) {
          Serial.println("Failed to join " SSID);
          Serial.println("Wait 0.1 second and try again...");
          delay(100);
        }
        wifly.save(); // save configuration,
      }
      Serial.println("\r\nTry to get url - " HTTP_GET_URL);
      Serial.println("------------------------------");
      while (http.get(HTTP_GET_URL, 10000) < 0) {
      }
      while (wifly.receive((uint8_t *)&get, 1, 1000) == 1) {
        Serial.print(get);
      }
      if (wifly.commandMode()) {
        Serial.println("\r\n\r\nEnter command mode. Send \"exit\"(with \\r) to exit command mode");
      }
    }

    void loop() {
      int c;
      while (wifly.available()) {
        c = wifly.read();
        if (c > 0) {
          Serial.write((char)c);
        }
      }
      while (Serial.available()) {
        c = Serial.read();
        if (c >= 0) {
          wifly.write((char)c);
        }
      }
    }

And here is my PHP code:

    <? php
    include("./connection/database_connect.php");
    include("./top_table.php");

    if ((isset($_SESSION["ID"])) AND (isset($_GET["temp"]))) {
      $id = $_SESSION["ID"];
      $sql = "SELECT temp FROM perfil, client WHERE perfil.ID ='$id'";
      $consult = mysqli_query($connect, $sql);
      $result = mysqli_num_rows($consult);
      if (($result == 1)) {
        $person_data = mysqli_fetch_array($consult, MYSQLI_ASSOC);
        $temp = $person_data["temp"];
        header("HTTP/1.1" . " " . 200 . "OK");
        header("Content-Type: text/html; charset=UTF-8");
        header("Content-Length: 1112");
        header("Connection: close");
        header("/r/n");
        echo $temp;
      } else {
        //se user dosen't exist on data base
        header("Location: http://192.168.1.80/xampp/training/login.php");
        exit;
      }
    } else {
      header("Location: http://192.168.1.80/xampp/training/login.php");
      exit;
    }
    ?>

body:
You should forget about the $_SESSION["ID"]; on PHP side, because you are working stateless without any session!
You should give a parameter for identifying your variable from arduino to php script - is this the temp=0? If so you need to exchange

    $sql="SELECT temp FROM perfil, client WHERE perfil.ID ='$id'";

with

    $sql="SELECT temp FROM perfil, client WHERE perfil.ID =" . $_GET["temp"];

assuming that perfil.id is only an integer - if it is a string, then add "'".


body:
Yes you are right!

Meanwhile i finished this project.

The problem was with the Wi-Fi shield that I was using. The Http request wasn't in a right format.


message:
Tried to fix ports on Mac OS X Yosemite. Now nothing works

I was having an issue very similar to this one:

https://arduino.stackexchange.com/questions/3324/arduino-compatibles-serial-port-not-showing-mac-osx

Basically I have a clone (VISduino) and it's made with a different USB chip so it needed a driver. Installing the driver didn't help.

http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

Running:

     sudo nvram boot-args="kext-dev-mode=1"

didn't help. So I decided to delete Arduino and reinstall. Then I went through all of the steps again.

Well.... now nothing works. Before doing this I could use:

 - Adafruit metro
 - An uno clone
 - My genuine uno
 - lightBlue Bean
 - adafruit trinket and trinket pro
 - adafruit trinket pro via USB
 - digikey

[![enter image description here][1]][1]

I've reinstalled the drivers for these but NOTHING is working now. They were all working before. It just says Arduino Uno on COM1, or digikey on COM1 etc.

[![enter image description here][2]][2]

And of course my clone (vis duino) isn't working either.

How can I fix this?

[![enter image description here][3]][3]

The com ports just are not there.

  [1]: https://i.stack.imgur.com/TSdpy.jpg
  [2]: https://i.stack.imgur.com/c6Z1i.jpg
  [3]: https://i.stack.imgur.com/2VQUA.jpg

body:
I solved this issue by deleting all of the Arduino files and the Arduino app. I put my sketched folder aside but deleted all libraries.

Restarted the computer.

Installed Arduino fresh.

Restarted the computer.

Installed the drivers.

Ran the command.

Restarted the computer.

Restarted the computer.

Restarted the computer.

Then it worked.


message:
Can I use micros() to analyze TX23 anemometer signal?

I'm very new to Arduino, and I'm trying to read data from a LaCrosse TX23 V02(X) anemometer. It's supposed to behave like this https://www.john.geek.nz/2012/08/la-crosse-tx23u-anemometer-communication-protocol/, but it's not...

I don't have an oscilloscope, so I made this code, using micros() to try to trace the output from the TX23:

    void loop() {
      collectData();
    }

    int collectData(void){
       if (bitLength < 0){
          bitLength = 1200;// length of bit is equal to approx 1230 micro seconds;
       }
      // init sequence
      pinMode(dataPin, OUTPUT);
      Serial.print("Send LOW\n");
      digitalWrite(dataPin, LOW );
      Serial.print("Send HIGH\n");
      digitalWrite(dataPin, HIGH);
      delay(100);
      Serial.print("Send LOW\n");
      digitalWrite(dataPin, LOW );
      delay(500);

      Serial.print("Begin input mode\n");
      pinMode(dataPin, INPUT);

      int state = 0;
      int oldstate = 0;
      unsigned long oldmicros = micros();
      for (int i = 1; i<5250 ; i++) {
        state = (digitalRead(dataPin) == LOW)? 0:1;
        if (i != 0) {
          Serial.print("-");
        } else {
          Serial.print("+");
        }

        delayMicroseconds(10);
        if (state != oldstate) {
          oldstate = state;
          i = 1;
          Serial.print(oldstate);
          Serial.print(" @");
          Serial.print(micros() - oldmicros);
          oldmicros = micros();
          Serial.print("\n");
        }
      }
      Serial.print(state);
      Serial.println(micros()-oldmicros);
    }

Does it have a chance to provide a quite accurate monitoring of the TX23 output? (eg is using micros() or delayMicroseconds(10) accurate ?)

body:
You should really make use of `pulseIn()` to work out the bit rate of the signal.  The first HIGH pulse in the header is there for timing so you know how often to poll the input.

Step one, after sending your outgoing initiation pulse, should be to wait for that first pulse (you might need a slight delay first before it starts transmitting - wait for the line to be low first):

    while (digitalRead(dataPin) == HIGH); // Wait for TX start
    uint32_t pulseWidth = pulseIn(dataPin, HIGH); // Get first pulse

That gives you the width of the first pulse in microseconds.

Now you can read 45 times at that period.  If you first delay by half that amount before your first sample you will be roughly in the middle of the bit so you can cope with a slight amount of drift.

    // Wait for the middle of the first bit
    delayMicroseconds(pulseWidth / 2);

    uint32_t highBlock = 0;
    uint32_t lowBlock = 0;
    for (int i = 0; i < 45; i++) {
        // Shift the high 32-bits left one bit
        highBlock <<= 1;
        // Place in the highest bit of the low block as the lowest
        // bit of the high block
        highBlock |= (lowBlock & 0x80000000UL ? 1 : 0);
        // Shift the low 32-bits left one bit
        lowBlock <<= 1;
        // Add in the value of the bit from the data pin
        lowBlock |= digitalRead(dataPin);
        // Wait for the next bit
        delayMicroseconds(pulseWidth);
    }

You should now have two 32-bit words which, when put together, form the entire datagram.  You can now use bitwise operators to pull out the parts you are interested in.

A better, though more complex, method of doing it would be to employ a timer with an overflow period equal to the pulse width. That will afford you much more accurate timing than a simple loop with delays.


body:
Majenko showed a method for digitally recording the waveform, after measuring `pulseWidth` at the outset, and mentioned use of a timer for delays.   I'll address the part of your question about using `micros()` while tracing TX23 output:  “Does it have a chance to provide a quite accurate monitoring of the TX23 output?”

Some of the serial output that your method produces as it goes along will affect evenness of timing.  For example, the `Serial.print()` of + after every tenth reading introduces a small timing irregularity (the two branches of the `if` may differ a few cycles in execution time).

More seriously, your double-read of `micros()` (after you print `oldstate`, you print `micros() - oldmicros` and then read `micros()` again) introduces a few cycles of timing error.  It probably amounts to a few microseconds total over the course of recording the pulse train.  Instead of reading `micros()` twice, say something like `newmicros = micros()` directly after detecting a state change, before doing any serial printing, then use `newmicros` in place of other `micros()` calls.  Having serial prints before `oldmicros = micros();` causes an offset error, which will be microseconds or milliseconds depending on the data rate you set in `setup()`.  It mostly affects the reported length only of the first pulse.

What I would do for debug monitoring of the pulse train is along the following lines:

    enum { timelen=44, maxpause=50000 };
    unsigned long int times[timelen];

    int collectData() {
      byte ntimes = 0, state=LOW;
      unsigned long int prevtime;
      pinMode(dataPin, OUTPUT);
      digitalWrite(dataPin, LOW ); // Pull DTR low to trigger conversion
      delay(500);
      pinMode(dataPin, INPUT_PULLUP); // Release DTR and set pullup
      delay(1);     // Let TX23U pull DTR low
      prevtime = micros();
      while (micros() - prevtime < maxpause && ntimes < timelen) {
        if (digitalRead(dataPin) != state) {
          times[ntimes++] = prevtime = micros();
          state = 1-state;
        }
      }
      return ntimes;
    }

This code is intended to record times at which state changes occur.  After `loop()` calls `collectData()`, it can call a `reportData()` routine that will print out pulse lengths by subtracting adjacent entries of `times[]`.  Even-indexed array entries are times of rising edges in the pulse train; odd-indexed entries are times of falling edges.  Because the `if (digitalRead(dataPin) != state) {...}` statement isn't executed atomically, the data pin can change after being tested but before being recorded a couple of lines later.  Using `state = 1-state;` instead of `state = digitalRead(dataPin);` guarantees that even indexes are for rising edges, but does not guarantee that adjacent entries correspond to the same pulse edge.  That is, a noisy signal can produce misleading results.


body:
<!-- language-all: lang-C++ -->

I'm going to present a third way of working on this. :)

First, since I don't have a TX23 I wrote a TX23-simulator:

    const byte TESTPIN = 2;

    const byte test [6] = {
        0b00000011,
        0b01111011,
        0b01010100,
        0b00010100,
        0b01001010,
        0b10111111 };

    void setup ()
      {
      pinMode (TESTPIN, INPUT);
      delay (100);
      }  // end of setup

    void loop ()
      {
      // wait for host to pull pin low
      while (digitalRead (TESTPIN) == HIGH)
        { }
      // wait for host to release it
      while (digitalRead (TESTPIN) == LOW)
        { }
      digitalWrite (TESTPIN, HIGH);
      pinMode (TESTPIN, OUTPUT);
      for (byte i = 0; i < 6; i++)
        for (byte j = 0; j < 8; j++)
          {
          delayMicroseconds (1100);
          digitalWrite (TESTPIN, test [i] & bit (7 - j));
          }
      pinMode (TESTPIN, INPUT);
      }  // end of loop

Based on your [linked page about the TX23](https://www.john.geek.nz/2012/08/la-crosse-tx23u-anemometer-communication-protocol/) it outputs a series of low/high pulses corresponding to the example on that page, like this:

[![TX23 simulator][1]][1]

Note that you need a 10 k pull-up resistor for this to work properly.

---

Now the reading code uses interrupts to detect state changes:

    const byte READ_PIN = 2;
    const byte NUMBER_OF_CHANGES = 48;

    volatile unsigned long bitTime [NUMBER_OF_CHANGES];
    volatile byte state [NUMBER_OF_CHANGES];
    volatile byte count;

    void stateChange ()
      {
      unsigned long now = micros ();
      if (count >= NUMBER_OF_CHANGES)
        return;  // array full
      state [count] = digitalRead (READ_PIN);
      bitTime [count++] = now;
      } // end of stateChange

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      }  // end of setup

    void takeReading ()
      {
      count = 0;
      digitalWrite (READ_PIN, LOW);  // start reading
      pinMode (READ_PIN, OUTPUT);
      delay (20);  // pulse width
      pinMode (READ_PIN, INPUT);     // release line
      EIFR = bit (INTF0);  // clear flag for interrupt 0
      attachInterrupt (0, stateChange, CHANGE);
      delay (55);  // let readings fill up array
      detachInterrupt (0);
      }  // end of takeReading

    void loop ()
      {
      takeReading ();
      if (count == 0)
        return;  // nothing!

      delay (500);
      for (byte i = 0; i < count; i++)
        {
        Serial.print ("count: ");
        Serial.print ((int) i);
        Serial.print (" = ");
        Serial.print (bitTime [i]);
        Serial.print (", state = ");
        Serial.print (state [i]);
        if (i > 0)
          {
          Serial.print (", width = ");
          unsigned long width = bitTime [i] - bitTime [i - 1];
          Serial.print (width);
          Serial.print (" (");
          int bits = width / 1000;
          for (byte k = 0; k < bits; k++)
           Serial.print (state [i - 1]);
          Serial.print (")");
          }
        Serial.println ();
        }
        Serial.println ();
      }  // end of loop

---

Results were:

    count: 0 = 10952804, state = 1
    count: 1 = 10953928, state = 0, width = 1124 (1)
    count: 2 = 10960616, state = 1, width = 6688 (000000)
    count: 3 = 10962844, state = 0, width = 2228 (11)
    count: 4 = 10963960, state = 1, width = 1116 (0)
    count: 5 = 10968412, state = 0, width = 4452 (1111)
    count: 6 = 10969524, state = 1, width = 1112 (0)
    count: 7 = 10971752, state = 0, width = 2228 (11)
    count: 8 = 10972876, state = 1, width = 1124 (0)
    count: 9 = 10973988, state = 0, width = 1112 (1)
    count: 10 = 10975104, state = 1, width = 1116 (0)
    count: 11 = 10976216, state = 0, width = 1112 (1)
    count: 12 = 10977328, state = 1, width = 1112 (0)
    count: 13 = 10978440, state = 0, width = 1112 (1)
    count: 14 = 10984012, state = 1, width = 5572 (00000)
    count: 15 = 10985124, state = 0, width = 1112 (1)
    count: 16 = 10986244, state = 1, width = 1120 (0)
    count: 17 = 10987356, state = 0, width = 1112 (1)
    count: 18 = 10990700, state = 1, width = 3344 (000)
    count: 19 = 10991812, state = 0, width = 1112 (1)
    count: 20 = 10994040, state = 1, width = 2228 (00)
    count: 21 = 10995156, state = 0, width = 1116 (1)
    count: 22 = 10996268, state = 1, width = 1112 (0)
    count: 23 = 10997380, state = 0, width = 1112 (1)
    count: 24 = 10998500, state = 1, width = 1120 (0)
    count: 25 = 10999616, state = 0, width = 1116 (1)
    count: 26 = 11000728, state = 1, width = 1112 (0)

This seems to agree with the test data.

  [1]: https://i.stack.imgur.com/pGCKr.png


message:
Arduino Uno not able to handle 2-dimensional array

<!-- language-all: lang-C++ -->

Now the code I'm writing in Arduino (Using Arduino) uses multiple 2-dimensional arrays. Now when I print some thing using the Serial Monitor it prints it correctly but when I declare and initialize the 2-dimentional array it won't print it.

Code:

    void setup()
    {
      Serial.begin(9600);
      int image_width = 56;
      int image_height = 96;

      int image_result[image_width][image_height];
      for (int i=0; i<image_height; i++) {
        for (int j=0; j<image_width; j++) {
          image_result[j][i] = 5;
        }
      }

      Serial.print("code works");
    }

Now in this case "code works" does not print but when I remove the array declaration and initialization code works is printed. What is the problem?

Do 2 dimensional arrays work differently in Arduino or is it a space issue?

body:
2D arrays work fine on arduino, but you run out of space very quickly.

An uno has 2 kilobytes of ram; your array has 56*96 = 5376 2-byte elements.

I would guess that you are writing over some critical memory value with a 5 at some point causing the program to fail.


body:
<!-- language-all: lang-C++ -->

This is what I fed my Uno:

    #define IMAGEWIDTH 56
    #define IMAGEHEIGHT 96

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

      int i, j;
      int image_result[IMAGEWIDTH][IMAGEHEIGHT];

      for (i = 0; i < IMAGEWIDTH; i++) {
        Serial.print("\nIMAGEWIDTH ");
        Serial.print(i + 1);
        Serial.println(":");
        for (j = 0; j < IMAGEHEIGHT; j++) {
          image_result[i][j] = i + j;
          Serial.print("image_result[");
          Serial.print(i + 1);
          Serial.print("][");
          Serial.print(j + 1);
          Serial.print("]: ");
          Serial.println(image_result[i][j]);
        }
      }
      Serial.println(F("\nDone!"));
    }

    void loop() {
    }

This will run over the whole array, while printing progress over Serial, which then print "Done!" once it is. I suggest changing:

    #define IMAGEWIDTH 56
    #define IMAGEHEIGHT 96
To lesser values, unless you have a few good minutes at hand.


body:
You are trying to use more memory than you have available: 96 * 56 * 2 = 10.752KBytes. Not much that the MCU can do when this happens.

If you look into the [datasheet][1], you'll see that your microcontroller (ATmega328p) only has 2KBytes of RAM.

I guess the question then, is to ask yourself if you really need that large an array. You may consider getting an external flash chip or an SDcard shield. If you only need it for read-only purposes (such as a lookup table), you can use some of your [flash program memory][2] (you have 32KBytes).

  [1]: http://www.atmel.com/Images/doc8161.pdf
  [2]: https://www.arduino.cc/en/Reference/PROGMEM