# Question
Title: Help with LCD's menu and seeing values continuously
I want to see the voltage data using `void volt();`, when I go to the "Item2SubItem3" within `void menuChanged`. Now I can only see the data *at that time*: how can I refresh the value every second?

```
void setup()
{
    // setup()...
}

void loop()
{
    //loop()...
}

// DC Voltometer
float vPow = 4.7;
float r1 = 100000;
float r2 = 10000;

void volt()
{
    lcd.clear();
    float v = (analogRead(0) * vPow) / 1024.0;
    float v2 = v / (r2 / (r1 + r2));
    lcd.setCursor(0, 0);
    lcd.print("DC VOLTOMETER");
    lcd.setCursor(0, 1);
    lcd.print(v2);
    delay(1000);
}

void menuChanged(MenuChangeEvent changed)
{
    MenuItem newMenuItem = changed.to; // get the destination menu
    lcd.setCursor(0, 1);            // set start position for lcd
                                 // printing to the second row

    if (newMenuItem.getName() == menu.getRoot())
    {
        lcd.print("Main Menu       ");
    }
    else if (newMenuItem.getName() == "Item1")
    {
        lcd.print("Item1           ");
    }
    else if (newMenuItem.getName() == "Item1SubItem1")
    {
        lcd.print("Item1SubItem1");
    }
    else if (newMenuItem.getName() == "Item1SubItem2")
    {
        lcd.print("Item1SubItem2   ");
    }
    else if (newMenuItem.getName() == "Item2")
    {
        lcd.print("Item2           ");
    }
    else if (newMenuItem.getName() == "Item2SubItem1")
    {
        lcd.print("Item2SubItem1   ");
    }
    else if (newMenuItem.getName() == "Item2SubItem2")
    {
        lcd.print("Item2SubItem2   ");
    }
    else if (newMenuItem.getName() == "Item2SubItem3")
    {
        lcd.print("Item2SubItem3   ");
        delay(2000);
        volt();
    }
    else if (newMenuItem.getName() == "Item3")
    {
        lcd.print("Item3           ");
    }
    else if (newMenuItem.getName() == "Item4")
    {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Item4           ");
    }
}

```

# Answer
> 0 votes
As Gerben implied in a comment, `menuChangeEvent` is called only when the menu selection changes. Thus, your voltmeter readout will print only whenever you change the menu selection to Item2SubItem3. The code shown below illustrates how to modify your `loop()` so that it checks the menu selection once per second. Each second the main loop will do whatever function is currently selected, such as displaying a current voltmeter reading. Note, you can make the menu decoding shorter and less tedious as shown in the answer, and can put variable declarations near where they are used instead of in random places.

```
void setup() {
}  // setup()...

// DC voltmeter reading
void volt () {
  const float vPow = 4.7, r1 = 100000, r2 = 10000;
  lcd.clear();
  float v = (analogRead(0) * vPow) / 1024.0;
  float v2 = v / (r2 / (r1 + r2));
  lcd.setCursor (0,0);
  lcd.print("DC Voltmeter");
  lcd.setCursor (0,1);
  lcd.print (v2);
  // Don't delay(1000) since loop() takes care of delay.
}

long int second = 0;
uint8_t itemcode = 0; // Will be number nm for Item n, Subitem m
int passnumber = 0;
void menuChanged(MenuChangeEvent changed) {
  MenuItem menuitem = changed.to; //get the destination menu
  String itemname = menuitem.getName();
  lcd.clear();        // Make printing spaces at line ends unnecessary
  lcd.setCursor(0,1);         //set lcd printing position = second row
  if(newMenuItem.getName() == menu.getRoot()){
    lcd.print("Main Menu");
    itemcode = 0;
  } else {
    lcd.print(itemname);
    itemcode = 10*(itemname[4] & 7);
    if (itemname.length() > 5)
      itemcode += itemname[itemname.length()-1] & 7;
  }
  passnumber = 0; // Actions can test passnumber if they like
  second = 0; // Cause actions to take place now
}

void loop() {
  long int now = millis()/1000; // Get elapsed-seconds
  if (now == second) return;    // Only do stuff once per second
  // Update to current second and do chosen menu item
  second = now;
  switch (itemcode) {
  case  0: break;
  case 10: break;
  case 11: break; // Fill in with code for different cases
  case 12: break;
  case 20: break;
  case 21: break;
  case 22: break;
  case 23:    // Item 2, subitem 3, read voltmeter
    volt();
    break;
  case 30: break;
  case 40: break;
  }
  // You can test passnumber to control for cases that only go once
  ++passnumber;
} // end of loop()

```

*Edit:* I moved the declaration of `second` and added `second = 0` within `menuChanged()` to decrease latency between a menu item being selected and its action taking place. Without `second` being zeroed in `menuChanged()`, up to a second could pass between an item's selection and its action; latency would average 0.5 seconds, which is undesirable in a user interface.

---
Tags: arduino-mega, lcd
---


title: HC-06 module versus 1sheeld

text:
# Question
Title: HC-06 module versus 1sheeld
Why would someone buy a 1sheeld?

Why not connect an Arduino to their smartphone using HC-06 bluetooth module and find an appropriate Android app, like for example RoboRemo. What is the advantage of using a 1sheeld?

# Answer
Why would you buy a car when you can cobble something together from some old pram wheels, a lawnmower engine, some old scaffolding, gaffer tape and chewing gum?

Because buying a car is considerably easier and more reliable. Plus your "friends" don't laugh at you when they see you trying to drive it to work.

Yes, you could cobble something together that might work using random components and other bits of software, but the work involved would be considerably more than plugging in a shield and downloading an app that is guaranteed to work perfectly with that shield.
> 1 votes

# Answer
Giving an equally biased answer as @Majenko, from the other side:

Because they're lazy, they don't know anything about electronics, and they don't want to. And they have more money than they know what to do with.

I am horrified at people shelling out for an "Arduino Temperature Sensor", "Arduino Shift Register", or "Arduino LED", each of which is a generic component soldered on to a board, with pins, at a 1000% markup

I also question the claim that "cobbled together" items are more reliable, or are less likely to have people laugh at you - if you want it to look nice, put it in a nice box (this applies both to "pre-made" items, and to cobbled together).

You will also learn a lot more from making it yourself; you will learn how things work, and you have a better idea and have the opportunity to fix when things go wrong. Your projects will also be a lot smaller.

If you want something that "just works", go buy an ipad. Then, when it doesn't work, throw it in the rubbish and buy a new one. And if you want it to do something it doesn't do, tough luck.
> 0 votes

---
Tags: bluetooth, shields
---


title: Using L239D with a joystick

text:
# Question
Title: 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!

# Answer
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 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).
> 3 votes

---
Tags: arduino-uno, motor, remote-control, electronics
---


# Question
Title: Interfacing an ATtiny85 with MIDI via Software Serial
In order to finish a synth project that I'm working on I built a MIDI interface. To test it, I drew up some code which (is supposed to) light up an LED when any key is pressed. The light turns off again when the key is released. This will later be merged with another branch of code here to tell me *which* note is playing. This sounds simple enough but the devil's in the details. Due to my project's size constraints I am using ATMEL's ATtiny85 chip instead of my Arduino Uno. The ATtiny doesn't support the Arduino Serial library and by extension the standard MIDI library. As I can't make use of simple functions like MIDI.read() I've opted to work with an alternative Software Serial technique I adapted from an Instructable. Unfortunately, the results have been less than exemplary. Simply put, the LED almost never lights up. I have conducted two test only 1 of which *somewhat* succeeded:

1)

```
if(velocityByte > 0 ){digitalWrite(LED, HIGH);}
if(velocityByte == 0 ){digitalWrite(LED, LOW);}

```

Initially, I had figured that would be the most successful of my options. My keyboard\* is binary about its ouput velocity. There are no pressure sensors so "on" is on and "off" is off. Unfortunately, however, the code seems to think otherwise.

2)

```
if(commandByte == noteOn ){digitalWrite(LED, HIGH);}
if(commandByte != noteOff ){digitalWrite(LED, LOW);}

```

Though originally less sure of this one, I've found it to be better than the other at catching notes. noteOn is the integer 144. While it does in fact trigger it does so only very rarely - once every 10 presses or so.

I believe I have however, whittled down the possible number of problems to 2:

1) Something is up with one or more of my calls to Serial. I've never really felt super confident with the author's method of obtaining data from Serial. For one, I have no confidence that I can insure I have collected the correct byte. If the code were to somehow "miss" counting a byte would it not assign, say, a commandByte to a noteByte? Is a better method available?

2) My keyboard's MIDI protocol is incompatible with my if-statement cases. At first I was under the assumption that my keyboard never sends a true "note off" message of any kind but instead a velocity = 0 message. But my test casts much doubt on this being the case and because of this, I don't *really* know how the keyboard handles note off messages. Does anyone else know?

\*A Yamaha YPT-230

```
//MIDI INPUT LED TEST
//Adapted from code written
//by Instructables user Amanda Ghassaei

#include <SoftwareSerial.h>

SoftwareSerial mySerial(0, 1);  //RX, TX

#define LED 2

byte commandByte;
byte noteByte;
byte velocityByte;

byte noteOn = 144;
byte noteOff = 128;

void setup(){
  mySerial.begin(31250);
  digitalWrite(LED, LOW);
  delay(1000);
}

void checkMIDI(){
  do{
    commandByte = mySerial.read();//read first byte
    noteByte = mySerial.read();//read next byte
    velocityByte = mySerial.read();//read final byte

    if (commandByte == noteOn){
      digitalWrite(LED, HIGH);
    }
    if(commandByte != noteOn){
      digitalWrite(LED, LOW);
    }

  }
  while (mySerial.available() > 2);//when at least three bytes available
}

void loop(){
  checkMIDI();
}
/*
void gotNoteOn(commandByte, noteByte, velocityByte){
  digitalWrite(LED,HIGH);
}

void gotNoteOff(commandByte, noteByte, velocityByte){
  digitalWrite(LED,LOW);
}
*/

```

**UPDATE** Following a suggesting, I have replaced the do .. while loop with an ordinary while loop. Relevant changes below:

```
void checkMIDI(){
  while(mySerial.available() > 2){
    commandByte = mySerial.read();
    if (velocityByte > 0x00){//if note on message
      digitalWrite(LED, HIGH);
    }
    if(velocityByte == 0x00){
      digitalWrite(LED, LOW);
    }
  }
}

```

I'd like to think it's an improvement but if so only a slight one. Curiously, it almost works backwards - The default state of the LED is on while pressing a key produces no change pressing and *holding* causes the light to briefly shut off. But even this is sporadic. It may also be worth noting that I elected to use hex '0x00' as opposed to decimal '0'.

**UPDATE II / NOTE** Having slept on the problem I think I now understand why I am encountering this issue in the first place. The author of the Instructables code I adapted used an Arduino for both MIDI In as well as MIDI Out. Had they simply hooked one Arduino Uno to the other in an in/out configuration they could have perfectly ensured there were no running status issues by just never sending any running status messages. This would explain the lack of conformity to the actual realities of MIDI on the input side. If you can control exactly what data you are sending on one end (MIDI Out) it becomes fairly trivial to receive that data on the other end (MIDI In). Generalizing, the author may have assumed that a true keyboard behave the same thing and failed to actually verify this. Thoughts?

**UPDATE III** Following the lead of CL but deviating somewhat because I didn't fully understand what CL was doing, I have written up a highly derivative, new code. It is based around what I now know to be the highly fluid nature of MIDI messages and seeks to intelligently discriminate important messages from non-important messages based on content. It does not work (except for LED test at the beginning) but seems like a promising step nonetheless.

```
//MIDI Input LED Test

#include <SoftwareSerial.h>

SoftwareSerial mySerial(0, 1);  //RX, TX

#define LED 2  //Test LED

void setup(){
  mySerial.begin(31250);
  digitalWrite(LED, HIGH); //Test
  delay(1000);
  digitalWrite(LED, LOW);
  delay(1000);
}

void loop(){
  checkMIDI();
}

void checkMIDI(){
/*Two of the three independent types of bytes are always
distinct and can be identified simply by their values.
A Status byte (on channel 1 at least) is always either
0x80 (off) or 0x90 (on). No other type of message
(Note, Velocity) can ever take this value and so if
this is the value of the byte received I can be
assured it is a Status byte.

The Note and Velocity bytes are a bit (haha) dicier.
They have overlapping ranges with both taking values of
anywhere between 0x00 to 0x7F. *Ordinarily*. A caveat
is that my Yamaha YPT-230 is binary as far as velocity
goes. A YPT-230 data is either 0x00 (full off) or 0x7F
(full on). As long as a Note byte is never 0 or 127 I can
use this to discriminate between these two types
in this manner.
*/

  if(mySerial.available() > 0){
    byte b = mySerial.read();

    if(b == 0x80 || 0x90){
      byte commandByte = b;
    }else if(b == 0x00 || 0x7F){
      if(b == 0x00){
        digitalWrite(LED, LOW);  //If vel = 0 turn LED off
      }else if(b == 0x7F){
        digitalWrite(LED, HIGH); //If vel = 127 turn LED on
      }
      //velocityByte = b;
    }else{
      byte noteByte = b;  //Do nothing with this for right now.
    }
  }
}

```

# Answer
> 4 votes
I suggest you first find what your Yamaha is sending you. I have a sketch that decodes MIDI for the Uno (assuming you have a Uno lying around). Run that, and see if you got note on with velocity zero, or note off. Then you are a little closer to solving the problem.

---

This part is quite wrong:

```
  do{
    commandByte = mySerial.read();//read first byte
    noteByte = mySerial.read();//read next byte
    velocityByte = mySerial.read();//read final byte

  ...

  }
  while (mySerial.available() > 2);//when at least three bytes available

```

You are reading 3 bytes, even if none are available. At least change it to:

```
while (mySerial.available() > 2)
  {
        commandByte = mySerial.read();//read first byte
        noteByte = mySerial.read();//read next byte
        velocityByte = mySerial.read();//read final byte

      ...

  }

```

The `do ... while` construct tests at the end of the loop. You must ensure you have 3 bytes "available" **before** reading 3 of them, not after.

---

## Example code for ATtiny85

The code below is an adaptation of the MIDI decoder in my link above. This one just reads the incoming MIDI and turns on the LED on a "note on" and turns it off on a "note off" (or note on with velocity zero). Tested, works perfectly.

```
//  MIDI_decoder for ATtiny85
//
// ATMEL ATTINY 25/45/85 / ARDUINO
// Pin 1 is /RESET
//
//                  +-\/-+
// Ain0 (D 5) PB5  1|    |8  Vcc
// Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
// Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
//            GND  4|    |5  PB0 (D 0) pwm0
//                  +----+

#include <SoftwareSerial.h>

const byte LED = 0;   // pin 5 on ATtiny85

// Plug MIDI into pin D2 (MIDI in serial) (pin 7 on ATtiny85)

SoftwareSerial midi (2, 3);  // Rx, Tx

const int noRunningStatus = -1;

int runningStatus;
unsigned long lastRead;
byte lastCommand;

void setup() {
  //  Set MIDI baud rate:
  midi.begin(31250);
  runningStatus = noRunningStatus;
  pinMode (LED, OUTPUT);
} // end of setup

void RealTimeMessage (const byte msg)
  {
    // ignore realtime messages
  } // end of RealTimeMessage

// get next byte from serial (blocks)
int getNext ()
  {

  if (runningStatus != noRunningStatus)
    {
    int c = runningStatus;
    // finished with look ahead
    runningStatus = noRunningStatus;
    return c;
    }

  while (true)
    {
    while (midi.available () == 0)
      {}
    byte c = midi.read ();
    if (c >= 0xF8)  // RealTime messages
      RealTimeMessage (c);
    else
      return c;
    }
  } // end of getNext

const char * notes [] = { "C ", "C#", "D ", "D#", "E ", "F ", "F#", "G ", "G#", "A ", "A#", "B " };

byte note;
byte octave;
byte velocity;

// interpret a note in terms of note name and octave
void getNote ()
  {
  note = getNext ();
  octave = note / 12;
  note %= 12;
  }  // end of getNote

void getVelocity ()
  {
  velocity = getNext ();
  }

// show a control message
void showControlMessage ()
  {
   byte message =  getNext () & 0x7F;
   byte param = getNext ();
  }  // end of showControlMessage

// read a system exclusive message
void showSystemExclusive ()
  {
  int count = 0;
  while (true)
    {
    while (midi.available () == 0)
      {}
    byte c = midi.read ();
    if (c >= 0x80)
      {
      runningStatus = c;
      return;
      }

    } // end of reading until all system exclusive done
  }  // end of showSystemExclusive

void loop()
{
  byte c = getNext ();
  unsigned int parameter;

  if (((c & 0x80) == 0) && (lastCommand & 0x80))
    {
    runningStatus = c;
    c = lastCommand;
    }

  // channel is in low order bits
  int channel = (c & 0x0F) + 1;

  // messages start with high-order bit set
  if (c & 0x80)
    {
    lastCommand = c;
    switch ((c >> 4) & 0x07)
      {
      case 0:   // Note off
        getNote ();
        getVelocity ();
        digitalWrite (LED, LOW);
        break;

      case 1:   // Note on
        getNote ();
        getVelocity ();
        if (velocity == 0)
          digitalWrite (LED, LOW);
        else
          digitalWrite (LED, HIGH);
        break;

      case 2:  // Polyphonic pressure
        getNote ();
        parameter = getNext ();  // pressure
        break;

      case 3: // Control change
        showControlMessage ();
        break;

      case 4:  // Program change
        parameter = getNext ();  // program
        break;

      case 5: // After-touch pressure
        parameter = getNext (); // value
        break;

      case 6: // Pitch wheel change
        parameter = getNext () |  getNext () << 7;
        break;

      case 7:  // system message
        {
        lastCommand = 0;           // these won't repeat I don't think
        switch (c & 0x0F)
          {
          case 0: // Exclusive
            parameter = getNext (); // vendor ID
            showSystemExclusive ();
            break;

          case 1: // Time code
            parameter = getNext () ;
            break;

          case 2:  // Song position
            parameter = getNext () |  getNext () << 7;
            break;

          case 3: // Song select
            parameter = getNext () ;  // song
            break;

          case 4:    // reserved
          case 5:    // reserved
          case 6:    // tune request
          case 7:    // end of exclusive
          case 8:    // timing clock
          case 9:    // reserved
          case 10:   // start
          case 11:   // continue
          case 12:   // stop
          case 13:   // reserved
          case 14:   // active sensing
          case 15:   // reset
             break;

          }  // end of switch on system message

        }  // end system message
        break;
      }  // end of switch
    }  // end of if
  else
    {
    // unexpected, ignore
    }

}  // end of loop

```

---

## Suggested schematic

---

From a comment:

> the 4N35 is too slow to work reliably with MIDI signals

Below is an updated schematic that uses a faster opto-coupler.

Admittedly the 4N35 is below spec for its rise time (it is supposed to be less than 2 μs rise time, however the 4N35 is slower at between 3 µs and 7 µs). However during my testing it worked OK. It sounds like the faster rise time is specified to allow for multiple devices to be connected in series, a slow rise time will introduce distortion.

# Answer
> 2 votes
This is not how the MIDI protocol works.

The incoming stream can contain other commands than note-on or note-off, and with running status, it is impossible to predict the length of any single command.

You need at least some kind of state machine to remember where in the command you are:

```
byte nr;

for (;;) {
    byte b = mySerial.read();
    if (b & 0x80) { // status byte
        if (b >= 0xf8) {
            // real-time command; ignore
        } else {
            commandByte = b;
            nr = 1;
        }
    } else { // data byte
        if ((commandByte & 0xf0) == 0x80 ||
            (commandByte & 0xf0) == 0x90) {
            if (nr == 1) {
                noteByte = b;
                nr = 2;
            } else if (nr == 2) {
                velocityByte = b;
                nr = 1;

                if ((commandByte & 0xf0) == 0x90 &&
                    velocityByte > 0) {
                    // note on
                } else {
                    // note off
                }
            }
        }
    }
}

```

# Answer
> 0 votes
Got it! After doing the requisite amount of research... I've developed a *much* improved checking system which allows me to truly demarcate between messages during running status much like Nick Gammon's code. While the code seems to work perfectly now it was still a bit glitchy when I tried it the other day. Perhaps I accidentally fixed it, most likely it'll crop back up again. How does it look?

```
//MIDI_Input_0x01
#include <SoftwareSerial.h>

SoftwareSerial mySerial(0,1);

const int LED = 2;

int isStatus();
int isAftertouch();
int isRealTimeCategory();

int dataByte;
int velocityByte;
int result;

void setup()
{
  mySerial.begin(31250);
  pinMode(LED, OUTPUT);

  digitalWrite(LED, HIGH);
  delay(1000);
  digitalWrite(LED, LOW);
  delay(1000);
}

void loop()
{

  while(mySerial.available())
  {
    //This is the protocol for reading new stuff
    byte myByte = mySerial.read();
    if(isRealTimeCategory(myByte))
    {
      ;
    }
    else
    {
      if(isStatus(myByte))
      {

        result = (myByte | 0x80);       //0b10000000
        switch(result)
        {
          case 0b10000000:
            digitalWrite(LED, LOW);
            break;
          case 0b10010000:
            digitalWrite(LED, HIGH);
            break;
          case 0b10100000:
            break;
          case 0b10110000:
            break;
          case 0b11000000:
            break;
          case 0b11010000:
            break;
          case 0b11100000:
            break;
          case 0b11110000:
            break;
        }
      }
      else
      {
        byte myByte = mySerial.read();  //This is the protocol for reading new stuff
        if(isRealTimeCategory(myByte))
        {
          ;
        }
        else
        {
          if(myByte > 0)
      {
        digitalWrite(LED, HIGH);
      }
      else
      {
        digitalWrite(LED, LOW);
      }
        }
      }
    }
  }
}  //END

/**********************
//function declarations
**********************/

int isStatus(int b)
{
  if( (b & 0x80) == 0x80)
  {
    return 1;
  }
  else if( (b & 0x80) == 0)
  {
  return 0;
  }
}

int isAftertouch(int b)
{
  if( (b & 0xf0) == 0xa0)
  {
    return 1;
  }
  else //if( (b & 0xf0) != 0xa0)
  {
    return 0;
  }
}

int isRealTimeCategory(int b)
  {
    if(b >= 0xF8)
    {
      return 1;
    }
    else
    {
      return 0;
    }
}

```

On top of this, I managed to tweak the code to output particular values to a shift register as I had initially intended. The method I use to differentiate between note and velocity bytes is less than ideal but works on my keyboard. Because of certain limitations it only works over a range of 13 notes but that's fine for now. Code and flowchart below.

```
//              MIDI_Input_0x02

#include <SoftwareSerial.h>             //The Attiny does not natively support the Serial library so this
                        //is the work-around.
SoftwareSerial mySerial(0,1);

const int latchPin = 2;
const int clockPin = 3;
const int dataPin = 4;

const int gate = 1;             //Note that initially, this was the tx pin.
                                //In this configuration absolutely every Attiny85 pin is used.
int isStatus();
int isAftertouch();
int isRealTimeCategory();

int result;
int dataByte;
int velocityByte;

//int noteApprox[13] = {1,3,5,7,9,12,14,17,20,23,26,29,32};
int noteApprox[13] = {32, 29, 26, 23, 20, 17, 14, 12, 9, 7, 5, 3, 1};
    //The above numbers are approximately 100 cents
    //apart from one another. This corresponds to notes of a scale.
    //They descend here because their corresponding
    //voltages will later become inverted in the circuit.

void setup()
{
  mySerial.begin(31250);

  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(gate, OUTPUT);        //'Gate' controls the level of the
                    //envelope generators. The signal
                    //becomes inverted later.

  digitalWrite(gate, HIGH);     //A simple test to ensure the
  delay(1000);              //circuit is wired correctly
  digitalWrite(gate, LOW);
  delay(1000);

}

void loop()
{

  while(mySerial.available())
  {
    //This is the protocol for reading new stuff
    byte myByte = mySerial.read();      //Read the oldest byte in the buffer
    if(isRealTimeCategory(myByte))      //See Function Notes
    {
      ;
    }
    else
    {
      if(isStatus(myByte))               //See Function Notes
      {
        result = (myByte | 0x80);       //0b10000000
        switch(result)
        {
          case 0b10000000:
            digitalWrite(gate, LOW);            //0b10000000 is the note Off
            break;                      //message
          case 0b10010000:
            digitalWrite(gate, HIGH);           //10010000 is the note On
            break;                      //message
          case 0b10100000:          //Absolutely none of these are important.
            break;
          case 0b10110000:
            break;
          case 0b11000000:
            break;
          case 0b11010000:
            break;
          case 0b11100000:
            break;
          case 0b11110000:
            break;
        }
      }
      else                                     //This is the part where I assume it's a data byte.
      {                                        //this might be causing problems...
        if( (myByte > 48) && (myByte < 61) )         //<-- That's 13 notes. An octave and an extra
        {
          digitalWrite(latchPin, LOW);
          shiftOut(dataPin, clockPin, MSBFIRST, noteApprox[myByte - 48]);   //Write to the shift
          digitalWrite(latchPin, HIGH);                     //register.
        }
        else
        {
          digitalWrite(gate, LOW);
        }

        byte myByte = mySerial.read();
        if(isRealTimeCategory(myByte))
        {
          ;
        }
        else
        {
          if(myByte > 0)
      {
        digitalWrite(gate, HIGH);  //Velocity Byte
      }
      else
      {
        digitalWrite(gate, LOW);
          }
        }
      }
    }
  }
}  //END

/***************************
    function Declarations
***************************/

int isStatus(int b)         //Determines if the incoming byte is a Status Byte of some sort.
                    //Returns 1 if so and 0 if not.
{
  if( (b & 0x80) == 0x80)
  {
    return 1;
  }
  else if( (b & 0x80) == 0)
  {
  return 0;
  }
}

int isRealTimeCategory(int b)           //Determines if the incoming byte is a Real Time Category byte
  {                 //I'm not positive what these *are* but they are only 1 byte long
    if(b >= 0xF8)           //a piece and easily detected (they're all greater than 11111000).
    {
      return 1;
    }
    else
    {
      return 0;
    }
}

/*              Bit Math Notes

    if(b & 0x80) == 0x80)

b    =  10000000
0x80 =  10010000
      & ________
        10000000 =/= 10010000

        Not a Note On byte.
        Return 0.

b    =  10010000
0x80 =  10010000
      & ________
        10010000 == 10010000

        A Note On byte! Hooray!
        Return 1.
*/

```

---
Tags: led, attiny, softwareserial, midi
---


# Question
Title: Suggest me a power source for my Arduino UNO project
I am working on a Project with:

1. 1 Arduino UNO
2. 5 micro 9g servos (Only one Working at a time)
3. 2 small LED bulbs
4. 1 MicroSD reader module
5. 1 Speaker

Can I power my Arduino UNO with a common 9v Battery?

I also have in mind to use an external power supply for servos... but what to use?

Please suggest me a perfect power supply system

# Answer
Unfortunately, the perfect power supply system doesn't exist yet. However, powering an Arduino is simple. You have to main options 9V for standard "full size" Arduinos (such as the UNO that you mention), although you *could* go for the low voltage 3.3V options.

Covering just the 9V option, from the Power section of Arduino Uno:

> **Power**
>
> The Arduino Uno can be powered via the USB connection or with an external power supply. The power source is selected automatically.
>
> External (non-USB) power can come either from an AC-to-DC adapter (wall-wart) or battery. The adapter can be connected by plugging a 2.1mm center-positive plug into the board's power jack. Leads from a battery can be inserted in the Gnd and Vin pin headers of the POWER connector.
>
> The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may be unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.

You should probably also take a look at Power Supplies, in particular the section on Batteries and cells, also from the following section Voltage conversion and regulation, it states:

> In a very simple scenario, you connect a disposable 9v battery (probably one of the (approx) 4cm x 2.5cm x 1.5cm units with two snap connectors on one end) to your Arduino, and the Arduino's built in voltage regulator takes care of reducing the voltage to a consistent 5v or 3.3v, depending on the sort of Arduino you have.

So you have a couple of choices regarding 9V, either the P9 cell

or a pack that holds six 1.5V AA or AAA batteries.

You may find this link, How to run an Arduino (clone) on (AA) batteries for over a year – part 2, an interesting read. Here the chap uses four AA batteries, which only gives 6V, to power an UNO:

I have just highlighted some information, you should take the time to read the links fully, and google for more information.

---

Regarding the servo motors, more current may be required. You *can* use the same four AA battery pack, thusly:

but the capacity of the batteries may leave something to be desired, especially if you use rechargeable batteries (which in today's eco-concious world, you should), so you *may* require something more hefty. A quick google will show you the options available.

### Addendum

The video Flite Test : RC Planes for Beginners: Batteries and Safety - Beginner Series - Ep. 7 is an extremely useful video tutorial about LiPO batteries for RC projects.
> 2 votes

# Answer
Everything @Greenonline said plus...

A 2 Cell Lipo battery is 7.4 V. A modest 500 mAH battery would run your project for several hours, perhaps days. If you're not satisfied with the run time, buy a battery with more mAH, they go well past 5000 mAH! After all, these are the same types of batteries used in all forms of Radio Control Aeromodeling (lots of servos and brushless DC motors).

The Uno can regulate the 7.4 V although you'll need to buy/build a cable to connect the battery to the Uno. I'm not sure how much current the Uno regulator can provide but I've driven two micro servos with mine.

If the servos chatter, hum, are otherwise not working right or if there is smoke coming out of the regulator, you probably need a separate power source for the servos. A BEC like this https://en.wikipedia.org/wiki/Battery\_eliminator\_circuit is an inexpensive alternate and also a common RC part. :)
> 1 votes

# Answer
Selecting a power supply involves considering the following:

**1. Voltage Requirement**

**2. Current Required**

**3. Running duration**

**4. Cost**

**Voltage Requirement:**

From the list of items specified all of your items except the microSD card (which works at 3.3V) works at 5V.

**Current Requirement:**

Arduino UNO: about 50mA

9G servo motor: 730mA peak

LED 5mm: 20mA\*2 = 40mA

microSD Card Reader: 200mA peak

Speaker: 350mA

**Total Current: 1.370 Amps**

**Running Duration:**

Say I want this device to run for 1 hour straight, in order to this I will need a battery supplying 5V 1370mAh and a 1C rating. So if you want your device to run longer you will need to get a battery with a higher capacity (for 2 hours 2740 mAh and so on)

**Cost**

I dont think i need to mention much in this criteria

**Solution 1:**

For these requirements your easiest solution is to use a USB power bank with 2000mAh or more.

On a protoboard solder 1x USB male, 1x USB female, 2x header pins. Solder All the positives together and all the negative together. And now you have a breakout for the power rails from the USB as well.

Power the Arduino via usb, microsd card via the 3.3V on the arduino and the rest via the breakout pins.

**Solution 2:**

Using lipo batteries. Lipo batteries have the advantage of having a large capacity in a small package (or a high power to weight ratio). In order to use this you will need a voltage regulator to get 5V. Please note that as per the calculation you will need a total of 1.37A to power your device at peak, this **cannot** be done via the on board regulator of the Arduino.

In total you will the following components to get this to work:

LiPo battery

Voltage regulator

LiPo Charger

**Solution 3:**

Using Alkaline battery. You can refer to the Minty Boost tutorial over at Adafruit to learn about this.

**Conclusion:**

If you want a **headache free solution** to your problem, buy a **USB power bank** , but if you want a more **customizable and low cost solution** go for the **LiPo battery**

And if you dont need a portable solution. Go for a wall adapter 5V/2A, thats pretty much every high end mobile phone charger
> 1 votes

# Answer
I have had a lot of success using an off-the-shelf power bank - they're easy to get, already have charging circuits (from USB), and are at the right voltage (+5V). You can plug the power bank directly into the USB port of the Arduino.

The only problem I've had is that some power banks shut down if there is not enough current being drawn - a resistor from +5V to GND solves that problem (make sure you work out how many watts your resistor is letting through, to make sure it can dissipate the heat - I used a 100Ohm resistor, at 5v; I put "Ohms Law calculator" into google, filled in 5V & 100 Ohm, and found that it needed to be a 1/4 watt resistor - perfect! I also noted that it drew 50 milli amps AKA 0.05 amps. I tried resistors with a higher resistance e.g. 200 Ohm, and the power bank powered down. If your project is drawing more power (continuously!) then you might get away with a higher resistance).

My power bank can supply 1.5 Amps, which should be plenty for your project.
> 0 votes

# Answer
You can use 9v battery and use separate one for servos. Due to voltage being "relative," you still need to connect the grounds.

You can connect the + of the battery to the VIN of the Arduino.
> -1 votes

---
Tags: power
---


title: Sending joystick data via bluetooth

text:
# Question
Title: 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!

# Answer
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.
> 1 votes

# Answer
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
> 0 votes

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


# Question
Title: 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. 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. 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?

# Answer
> 1 votes
"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.

---
Tags: programmer
---


title: Fast Python to arduino communications

text:
# Question
Title: 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).

# Answer
> 3 votes
The fastest means of communicating with the Arduino is 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.

# Answer
> 1 votes
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).

---
Tags: serial, usb
---


# Question
Title: 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
}

```

# Answer
> 0 votes
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);
       }

```

# Answer
> 0 votes
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)%10` (assuming the led's are numbered for 0 to 9).

---
Tags: arduino-mega, led, c++, button
---


# Question
Title: 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

```

# Answer
> 1 votes
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.

# Answer
> 0 votes
```
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:

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

```

---

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

# Answer
> 0 votes
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, plus possibly a gain of 1, 2, or 4 (per Section 43.6.9). Also see: Analog performance ... of Due's 12 bit ADC (including how to speed up `analogReads` on the Cortex), Differential Sensing with Arduino, Setting ADC compare mode in a differential input, and Due pinout diagram.

---
Tags: arduino-due, signal-processing
---


title: Arduino nano stopped working

text:
# Question
Title: Arduino nano stopped working
After programming Arduino Nano with the DIY Headtracker code, after trying to plug the Arduino to the receiver and some time, the LED stops flashing and now it's not recognized by the computer anymore.

When I plug it, it only lights the power LED.

The worst thing is that I've already tried with another Nano and it bricked also, can't use them any more. Anyone know any fix to this?

This is the error given when trying to upload the blink sketch to the board...

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

```

# Answer
> 1 votes
I suggest you visit the page Have I bricked my Arduino Uno? \- whilst you have a Nano and not a Uno, it is the same processor and most of the remarks there will apply.

As the Arduino Nano page says:

> It has more or less the same functionality of the Arduino Duemilanove, but in a different package.

If you have another Uno or similar lying around you could conduct the "chip detector" test described on that page. You could also perform the loopback test.

It is possible on the FTDI chip (underneath) is damaged in which case there would be alternatives to using that.

# Answer
> 0 votes
If you have access to an AVR ICE MKII or an AVRDragon, you could try High Voltage programming. It is, AFAIK, the ultimate way to revive a bricked device. There might be some alternative method to perform HV programming without any of the devices I mentioned (for example with another AVR), but I'm not aware of it, if it exists.

# Answer
> 0 votes
https://www.sparkfun.com/news/1629 Maybe your windows update has installed new drivers for your FTDI chip. You can check that your usb device PID is set to 0x0000

(You probably have the "Gravitech Nano V3.0" (with FTDI chip on the back)? I have, and this worked for me.)

In this case, you should download M\_PROG from FTDI And then check for the chip, when found, you set the PID to FTDI default (0x6001). Then simply press program, and it will re-set your device PID.

Also, you should download the "CDM-v2.12.00-WHQL-Certified.zip" drivers. Another source

---
Tags: arduino-nano, uploading, ide
---


# Question
Title: 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.

# Answer
> 1 votes
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 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.

# Answer
> 1 votes
Related to 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:

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

---
Tags: arduino-mega, led, c++, button
---


title: Arduino Uno Rx/Tx + Arduino Serial

text:
# Question
Title: 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

# Answer
> 3 votes
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.

# Answer
> 2 votes
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, 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.

---
Tags: arduino-uno, softwareserial
---


# Question
Title: 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;

  }
  }

```

# Answer
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.
> 0 votes

# Answer
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++;
}

```
> 0 votes

---
Tags: c++, interrupt, timers, rotary-encoder
---


title: I can upload via USB but not FTDI

text:
# Question
Title: 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.

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

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?

# Answer
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.
> 1 votes

---
Tags: ftdi
---


# Question
Title: 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.

# Answer
> 1 votes
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.

---
Tags: arduino-uno, wifi
---


title: Usage of SPI inside an ISR

text:
# Question
Title: 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.

# Answer
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.
> 4 votes

---
Tags: interrupt, spi, isr
---


title: Run a part of code upon call

text:
# Question
Title: 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, but I'm clueless on how to do this job.

# Answer
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.

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 votes

# Answer
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
> 0 votes

---
Tags: serial, programming
---


# Question
Title: Tried to fix ports on Mac OS X Yosemite. Now nothing works
I was having an issue very similar to this one:

Arduino compatible's 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

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.

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

How can I fix this?

The com ports just are not there.

# Answer
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.
> 0 votes

---
Tags: mac-os
---


# Question
Title: What's the benefits between different interrupts on Arduino
On an Arduino you can have several different interrupt types, two of them being RISING and FALLING. Looking past that RISING is from LOW to HIGH, and FALLING is the opposite, what are the benefits of using one or the other?

To clarify; why would you use a RISING interrupt or a FALLING interrupt?

# Answer
> 8 votes
Imagine that you have the circuit below:

simulate this circuit – Schematic created using CircuitLab

Let's say that you wanted to catch the user pressing the button. The input signal will go from high to low, which is a falling edge. So you would use a FALLING interrupt to catch this event. Easy, right?

Now let's say you wanted to catch a user releasing the button instead. This time the inverse is true, so you want to use a RISING interrupt.

You should note that since these interrupts are edge triggered, the simple circuit below would not be ideal. Without any debouncing, there may be several edges to trigger from, resulting in repeated interrupts. Also, given the analogue nature of the design, we can't be sure that the rise / fall times will be fast enough to trigger the edge interrupt. We can get around this by adding a 100nF capacitor across the switch and following by a Schmitt trigger (which I can't find a symbol for in the circuit editor!).

So to answer your question, you use the interrupt that is correct for the event you are trying to catch. The Arduino MCU implements both edges for completeness and flexibility in your design, so if this interrupt was coming from an external IC you have no control over the design of, you can easily match the interrupt to its behaviour without having to add in an inverter.

# Answer
> 1 votes
Suppose you have a pushbutton that connects Arduino pin to the ground. The pin is also pulled up to VCC (may be internally in Atmega chip, or through external resistor). Now, when the switch is open, Arduino sees HIGH, and when you press the button it sees LOW. If you would like to perform an action when the button is pressed, you would use FALLING interrupt. If you would like to know when the button is released, you would use RISING. There are no general benefits of using one over another.

# Answer
> 0 votes
The interrupt will be generated by an external circuit. In many cases, you have the control over the design of the external circuit, and you can choose whether it will be generating low-to-high edges or high-to-low edges. But in some cases you don't have the control over the design of the external circuit which generates the interrupt. Then you have to adapt your firmware code to the interrupt source.

---
Tags: pins, interrupt
---


# Question
Title: Replacing the Voltage regulator of a fried Arduino
I accidentally fried my Arduino. I found this Instructable. The symptoms are the same. The board not powering on connecting USB source and the over current protector was heating up. So I removed the voltage regulator as mentioned in the Instructable. But the problem is the pins 1 and 2 of where the regulator used to be are still shorted out. That is even after removing the regulator, the pins seem to be somehow internally shorted. I tried checking the continuity on another working Arduino and found it to be not shorted. What seems to be the problem?

# Answer
> 3 votes
I know it's an old thread, but others are likely to have this problem. If you check the open source schematics, there are a couple of nearby capacitors that connect pin 1 (GND) to pin 2 (+5V) of the regulator.

I would check C2 and PC2 (top right of the diagram) as well as C1 (top left of schematic diagram), and any other components you can find that bridge the rails between +5V and ground. Capacitors are more likely to fail shorted than many other components. You will have to remove at least one pin of each capacitor to test it since you don't know where the short is, or you can simply remove capacitors until the short goes away.

---
Tags: hardware
---