title: LED Control through bluetooth

text:
# Question
Title: LED Control through bluetooth
I have an Android app that sends data to the arduino HC-06. It is however giving me colors i did not send to it. Eg. Red in place of green, white in place of red etc. Here is a snippet of my android code that sends the data via bluetooth

```
 public void onColorChanged(int color) {
    BluetoothV2 bluetooth = new BluetoothV2();
    int r,g,b;
    r = Color.red(color);
    g = Color.green(color);
    b = Color.blue(color);
    bluetooth.Message(r+","+g+","+b);
 }

```

Here is a snippet of my arduino code

```
void loop() {

if(Serial.available()>0){

while(Serial.available()>0){
   char inChar = (char)Serial.read();
   inputString += inChar;
}
   int red = Serial.parseInt();
   int green = Serial.parseInt();
   int blue = Serial.parseInt();
   color(red,green,blue);
   inputString = "";
   Serial.println("R:"&& red &&"G:"&& green &&"B:"&& blue);
  }
}

void color (unsigned char red, unsigned char green, unsigned char blue){
   analogWrite(redPin, 255-red);
   analogWrite(greenPin, 255-green);
   analogWrite(bluePin, 255-blue);
}

```

Terminal data

```
               2,,,,,,,,,,,,,2,,5,,,,,,,,,,,,,,,,,,,,,,,,,02725,1,502725,,,,,,,,,02514,5,602515     ,5,3,,,,,025

```

Is the problem how i get the data though Serial.read()? Or what am i missing

# Answer
```
int firstcomma = inputString.indexOf(',');
int secondcomma = inputString.indexOf(',',firstcomma+1);
String r = inputString.substring(0,firstcomma);
String g = inputString.substring(firstcomma+1,secondcomma);
String b =  inputString.substring(secondcomma+1);
red = r.toInt();
green = g.toInt();
blue = b.toInt();
Serial.print("R");
Serial.print(red);
Serial.print("G");
Serial.print(green);
Serial.print("B");
Serial.println(blue);

```

This solved my problems.
> 1 votes

# Answer
Maybe you can try again with something like this to check if the android part is not correct. From your terminal output it seems that you receive values higher than 255.

```
void onColorChanged(int red, int green, int blue) //values from 0 - 255
int r,g,b;
r= red;
g= green;
b= blue;
bluetooth.Message(r+","+g+","+b);

```

The receive part in your arduino code is like my code for a similar project. Try setting your color in the arduino code like this to check if the example code from above works:

```
void color (int red, int green, int blue)
{
analogWrite(redPin, red);  //the higher your send value the brighter the color
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}

```
> 0 votes

---
Tags: arduino-uno, serial, arduino-mega, android
---


title: Reading temp data

text:
# Question
Title: Reading temp data
I have hacked this kettle so that I can turn it on and off remotely via wifi and that is working perfectly.

Added this to get a better signal.

This is my micro controlling the 5v buttons on the kettle.

I keep running into a wall when it comes to reading the temperature of the water. The kettle does this automatically, but I want to transfer this information to my micro.

If I hook my multimeter to the ground and and yellow wire that connects to the lower voltage board (5v) that had the buttons and display I can use the voltage reading to predict the temp. The reading ranges from 0-5v, but my micro is a 3.3v micro so a direct connection isn't a great idea. I've tried using breakout boards designed to read voltage, but if I connect anything it throws the reading off.

The multi-meter is fine.

How can I get my micro to read the voltage as if it were a multi-meter? I even tried one of those little seven segment voltmeters but that threw off the reading just like the optocoupler and leds and other methods that I tried.

Here is how I have it set up:

# Answer
> 0 votes
## Voltage divider

You can possibly use a simple voltage divider. Try connecting two 100K ohm resistors in series between the voltage you want to measure and ground.

Yellow-\>100K ohm resistor-\>100K ohm resistor-\>ground

Now connect your multi-meter to the middle connection between the two resistors.

Depending on the circuit that happens to be driving the yellow wire, you should hopefully see a voltage that varies between ~ 0-2.5 volts. If so, you can connect this voltage to your 3.3v micro analog input.

Note that the value of the resistors is not critical - you just want them to be about the same and pretty large.

## Op Amp

If the yellow wire output is so weak that even a voltage divider with very large resistors is pulling the voltage down significantly, then you can use a high impedance op-amp with 1x gain to buffer the signal.

So, you'd connect the yellow wire to the `+` input of the op amp, and connect ground to the `-` input of the op amp. The output voltage of the op amp would not track the input voltage (the yellow wire) and you can use a voltage divider on the output as above.

## Use digital temp sensor

This option does not directly answer you question, but might be the best solution.

You can get something like a DS18B20 digital temperature sensor for a buck or two and connect it digitally to your MCU and avoid the problem altogether. This chip is happy at 3.3 volts, so you'd just need to put it physically someplace where it is sensing the same temperature as the yellow wire. This will likely be more accurate too!

---
Tags: voltage-level
---


# Question
Title: Different behavior than in simulator: 5V pin works instead of GND. Why is that?
I use this simulator to check if what I want to do works. This is how it looks like:

I've recently realised that I've connected my RGB LED to 5V pin instead of GND like on schema. It worked perfectly that way (led worked and chanaged colors). When I connected it back to GND pin, it didn't worked.

When I went back to simulator and changed things to those that worked physically (using 5V pin) it didn't worked, but GND did.

Why do you think there are some differences? Can I use 5V pin instead of GND if it works?

My Arduino: Arduino Leonardo.

# Answer
The RGB LED's are available with common cathode and common anode. That determines whether you connect the common pin to ground or to +5.

In your schematic you likely mismatched the selected part to what you actually have. If you have the opposite type of LED as planned, just reverse the connection as you did. You are not alone in this type of mistake. see similar whot? here

A digital multimeter with a diode test mode would be very useful here. The DMM would quickly measure the polarity of the diode tell you which lead connects to positive and which to ground.

But did it really work correctly? Don't you also see that you have to write LOW to the digital output to make the LED light up?
> 2 votes

---
Tags: power, arduino-leonardo, rgb-led
---


title: Input clock limit

text:
# Question
Title: Input clock limit
If you use an external oscillator, and divide-by-8 internally, can you apply up to 160MHz on PB6? For example, can I use my 50MHz oscillator to clock my 328p @ 6250KHz? Note: when I say oscillator I don't mean resonator or crystal

# Answer
> 1 votes
No! 20 MHz max (Please see 8.8 External Clock, pp. 34). The 50MHz clock could be divided by 8 with a counter or the 150MHz clock by 16 with a faster counter.

Cheers!

---
Tags: oscillator-clock, input
---


title: Can I run a loop in setup()

text:
# Question
Title: Can I run a loop in setup()
Are loops not allowed in setup()? The following doesn't print anything inside the `for` loop to the serial terminal

**Code:**

```
void setup() {
  Serial.begin(9600);
  Serial.println("Ping");
  for (int i = 0; i >= 10; i++) {
    Serial.println(i);
    Serial.println("Pong");
  }
}

void loop() {

}

```

**Output:**

```
Ping

```

# Answer
In principle yes, you can use a loop in setup() however this specific code

```
for (int i = 0; i >= 10; i++) {
  Serial.println(i);
  Serial.println("Pong");
}

```

will result in the body of the loop *never* executing, as the loop test `i >= 10` is *initially* false.

You probably meant `i <= 10`

Generally speaking, it would be poor program structure to use a loop in setup() in place of one in loop(), however if you need a loop to apply similar operations to a range of things, or to briefly busy wait on a condition as part of setting up operation, that kind of thing could be appropriate.
> 8 votes

# Answer
You could (and I occasionally do) write your entire program in the `setup()` function. `Setup()` and `loop()` are constructs provided for your convenience, but they aren't necessary. In C/C++ compiled programs, it conventional for the C run-time code to call `main()`, and for `main()` to be written by the programmer.

It is conventional within the Arduino IDE world to bury the complicated stuff to let new user get productive quickly with a gentle learning curve. That includes a pre-written `main()` that provides the calls to `setup()` and `loop()` for you.

The following `main()` function is typical of a number of pre-written Arduino `main()` functions, but you don't have to use the pre-written one; you can supply your own. It will need to call `init()`, and Arduino library function that prepares the hardware and software environment into a known state; after that you're good to go.

```
/*
 * main.cpp
 *
 *  Created on: Dec 13, 2011
 *      Author: jrobert
 */

#include "WProgram.h"

int main(void){
    init();
    setup();
    for(;;)
        loop();
}

extern "C" void __cxa_pure_virtual() {
    while (1)
        ;

}

```
> 3 votes

---
Tags: serial
---


# Question
Title: Upload a .hex file, using a standalone ISP, without overwriting bootloader
Is it possible to flash a `.hex` file on an AVR MCU, which already contains the Arduino bootloader, using an AVRISP mkII, without overwriting the bootloader?

In my concrete situation, I have an Arduino Uno that I would like to program sometimes over an AVRISP mkII, and sometimes using the built-in programmer (i.e. by just connecting the Uno via USB to a computer).

For reference, given a compiled `.hex` file, this is what I use to upload it using the built-in programmer:

```
avrdude -c arduino -p atmega328p -P/dev/ttyACM0 -b115200 -D -Uflash:w:_build/image.hex:i

```

By default, this works as expected. I can also use `avrdude` to upload it using the AVRISP:

```
avrdude -c avrisp2 -p atmega328p -U flash:w:_build/image.hex:i

```

This gets my image on the board as well; however, it also seems to overwrite the bootloader, i.e. after this, I can only use the AVRISP, and not the built-in one, to upload images. The only way back, at this point, is to re-flash the bootloader (via the AVRISP) on the Uno.

If I try to instruct `avrdude` to upload via the AVRISP without overwriting the bootloader:

```
avrdude -c avrisp2 -p atmega328p -D -U flash:w:_build/image.hex:i

```

then it fails in the verification phase:

```
avrdude: verification error; content mismatch

```

Based on @ChrisStratton's answer, I understand this means my problem actually starts before I even try to upload it, by the compiler emitting code which has addresses that should belong to the bootloader.

Here is the command I use to compile and link (I am not using the Arduino IDE at all)

```
avr-g++ -c -g -O3 -w -std=c++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -I.. -mmcu=atmega328p -DF_CPU=16000000L blinkPB5.cpp -o _build/blinkPB5.cpp.o -MMD -MF _build/blinkPB5.cpp.m
avr-g++ -Os -Wl,--gc-sections -mmcu=atmega328p -o _build/image.elf _build/blinkPB5.cpp.o
avr-objdump -S _build/image.elf
avr-objcopy -Oihex -R.eeprom _build/image.elf _build/image.hex

```

As explained above, I can use the same resulting `.hex` file both via the bootloader (by just uploading it via serial) and the AVRISP (by overwriting the bootloader).

# Answer
To preserve the bootloader, you should use the `-D` option in the ISP command line just as it was used in the bootloader upload command line. This will disable usage of full-chip erase.

I expect you would end up with something like

```
avrdude -c avrisp2 -p atmega328p -D -U flash:w:_build/image.hex

```

However, it is important to add something which I overlooked when first posting this answer, which is that **the ATmega series cannot do a *partial* flash erase via the ISP interface** in the way that it can when the bootloader causes the chip to program itself. This effectively means that you only get one shot at loading a program to an *already blank* area of the chip this way - after that, to load a different one to the same area you will have to do a mass erase *of the entire chip* and reload *both* the bootloader and the sketch, or else command the bootloader to erase the blocks where the sketch would reside.

Of course you will also need a hex file for your sketch with no contents that conflict with the bootloader, as while the bootloader would refuse to overwrite any of its own blocks when programming a sketch, the ISP is perfectly happy to try to write over the top of the bootloader, which would likely result in a logical AND of the bits of two different pieces of code, and cause the chip to boot to nonsense. A typical Arduino board configuration reserves space for the expected bootloader, so if the one you are using matches the size reserved in the chosen configuration, you should not have a conflict.

Another option could be to combine the bootloader and sketch hex files, literally concatenating their contents one after the other into the same file.
> 4 votes

---
Tags: bootloader, avrdude, isp
---


# Question
Title: Why is setup() executed twice at runtime?
**Code:**

```
void setup() {
  Serial.begin(9600);
  Serial.println("hello");
}

void loop() {
}

```

**Output:**

```
hello
hello

```

Why does `hello` print twice?

# Answer
> 4 votes
It isn't, it's displaying the previous message from when you didn't have the Serial Monitor open yet, plus the new message caused by the Arduino resetting from the Serial Monitor being opened.

If you put a longer message in there you'll probably see the first line get cut off and then the full line.

---
Tags: serial
---


title: SD Library writing char in a file

text:
# Question
Title: SD Library writing char in a file
I'm trying to write into a file using this code from the example of the library:

```
String dataString = "";
int sensor = 0;
dataString += String(sensor);
dataString += ",";
sensor +=1;

File dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
  dataFile.println(dataString);
  dataFile.close();
}

```

I have a char array that I want to write in the file, but it works only with String objects apparently. What can I do?

# Answer
Try using `dataFile.write(arrayName);`

https://www.arduino.cc/en/Reference/FileWrite
> 1 votes

# Answer
You can write char arrays? What makes you think you can't? Example:

```
char dataBuffer [80];
strcpy (dataBuffer, "Hello, world");

File dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
  dataFile.println(dataBuffer);
  dataFile.close();
}

```
> 0 votes

---
Tags: arduino-ide, sd-card, code-optimization, coding-standards
---


# Question
Title: #define macro not in scope when i try to use IR library
My code keeps saying that that Button\_8 and the rest of the #define macros are out of scope.

```
#include <IRLib.h>
#include <Servo.h>

#define MY_PROTOCOL SONY
#define RIGHT_ARROW   0xfd50af //Move several clockwise
#define LEFT_ARROW    0xfd10ef //Move servo counterclockwise
#define SELECT_BUTTON 0xfd906f //Center the servo
#define UP_ARROW      0xfda05f //Increased number of degrees servo
#define DOWN_ARROW    0xfdb04f //Decrease number of degrees servo moves
#define BUTTON_0 0xfd30cf  //Pushing buttons 0-9 moves to fixed  positions
#define BUTTON_1 0xfd08f7  // each 20 degrees greater
#define BUTTON_2 0xfd8877
#define BUTTON_3 0xfd48b7
#define BUTTON_4 0xfd28d7
#define BUTTON_5 0xfda857
#define BUTTON_6 0xfd6897
#define BUTTON_7 0xfd18e7
#define BUTTON_8 0xfd9867
#define BUTTON_9 0xfd58a7

IRrecv My_Receiver(11);//Receive on pin 11
IRdecode My_Decoder;
long Previous;
Servo myservo2;
Servo myservo;

void setup()
{
myservo.attach(8);
myservo2.attach(3);
My_Receiver.enableIRIn();
}

void loop()
{

  if (My_Receiver.GetResults(&My_Decoder))
{
   My_Decoder.decode();
   if(My_Decoder.decode_type==MY_PROTOCOL)
   {
       if(My_Decoder.value==0xFFFFFFFF)
       My_Decoder.value= Previous;
       if(My_Decoder.value == Button_9)
       {
       myservo.write(0);
       myservo2.write(180);
       }
     else if(My_Decoder.value == Button_8)
      {
         myservo.write(180);
          myservo2.write(180);
       }

    }
}
}

```

when i use a switch statement instead of the 4 and 5 if statement like so:

```
switch(My_Decoder.value) {
        case Button_8:   //do something; break;

```

it works, but i dont know why.

# Answer
> 2 votes
C++ is case-sensitive. `Button_8` is different from `BUTTON_8`.

---
Tags: arduino-uno, ir
---


# Question
Title: Share data between the two processors of the Arduino Yun
The linux processor runs a Python script from which I would like to send an array of integers to the Yun microprocessor. How can I do that?

And then, how can I retrieve and then use this array in my Arduino Sketch?

# Answer
> 1 votes
Given that my Python script printed the following

```
[10, 20, 30, 40]

```

This is the sketch I used to retrieve the array

```
#include <Bridge.h>
#include <Process.h>

void setup()
{
   Bridge.begin();
   Serial.begin(19200);
}

void loop()
{
   Process proc;
   int i=0;
   size_t dim = 1;
   int* array = (int*)malloc(dim);

   Serial.print("Running process...");
   Serial.println("done!");
   proc.runShellCommand("python /script.py");

   while (proc.available()){
     if((char)proc.read() != ']'){
        array[i] = proc.parseInt();
        dim++;
        array = (int*)realloc(array,dim);
        Serial.println(array[i]);
        i++;
      }
      else
        break;
   }

   Serial.println();
   delay(1000);
}

```

# Answer
> 1 votes
The Yun makes communication between the microprocessor and the Linux side easy. On the Arduino side, use the Bridge library in your "processing script" to read (or write) Bridge values set by the python program running on the Linux side. From the linux side, the bridge looks like a web address and you set values by addressing a URL with a get or put url http request. You can also manipulate these values from another computer on the network as well if you like.

I have some Arduino Yun dataloggers that use the Linux side to communicate via wifi with an ftp server that serves several Yun dataloggers. The arduino script reads the sensors, creates the records, etc. You can also have the microprocessor side write files that are used by the linux side of the Yun.

I find the Yun's combination of Linux and the regular arduino in one package makes the overall system easier to program and to interface with the rest of the web.

# Answer
> 0 votes
Serial1 on the Arduino side is connected to a serial console on the Linux side.

So, you could use calls on the Arduino to run your Python script on the Linux side and then listen to the output of the script to come back though the serial port and part it.

Here is an example of a project where I used a Yun like this. The Arduino side interfaces to some temperature sensors, and then types commands into the Linux side over the serial connection to run CURL and report data to internet URLs.

http://wp.josh.com/2014/06/05/tempurature-logging-to-a-google-spreadsheet-with-an-arduino-yun/#more-1797

I am going to warn you that this is very ugly. Then Yun itself is quite ugly too. There were so many problems that I ended up giving up on this platform completely.

---
Tags: arduino-yun, python
---


# Question
Title: Arduino C, Led > binary alternative all lights
I'm trying to alternatively have a random int generate a binary number with 4 lights.

This is my current code, However, it seems that all the lights(leds) go on, I don't think the minus option works. As in, it won't take a value from the currently randomized digit. (randombinary = randombinary - x)

I also tried just "randombinary - x"

---

```
const int button = 2;
const int redone = 13;
const int redtwo = 8;
const int greenone = 12;
const int greentwo = 7;
int randomnumber = 0;
int randombinary = 0;

void setup() {

  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(2, INPUT);

}
  void loop() {

delay(1000);

  int randomnumber = (1, 15);
  randombinary = randomnumber;

  if (randombinary >=8){
    digitalWrite(redone, HIGH);
   randombinary = randombinary - 8;
  }
 else {
   digitalWrite(redone, LOW);
 }

  if (randombinary >=4){
    digitalWrite(greenone, HIGH);
   randombinary = randombinary - 4;
  }
  else {
    digitalWrite(greenone, LOW);
  }

  if (randombinary >=2){
    digitalWrite(redtwo, HIGH);
  randombinary =  randombinary - 2;
  }
  else  {
    digitalWrite(greentwo, LOW);
  }

  if (randombinary >=1){
    digitalWrite(greentwo, HIGH);
  randombinary =  randombinary - 1;
  }
  else  {
    digitalWrite(greentwo, LOW);
  }

  }

```

Would appreciate any help!

# Answer
Code review (one possible solution can be found below)

* Absolute numbers in the code, like 15 as the limit for the random numbers are generally considered harmful. It would be better to give all absolute numbers a constantsname and use these throughout. The OP code did not use the constants for the pins, for instance.
* Writing similar pieces of code in a row makes maintenance hard. Therefore, group similar items in any kind of list, like an array, and iterate over them.
* Functions should have expressive names clearly stating what is going on inside.
* Functions should be short and concise, ideally having only a few lines.

Try something along these lines:

```
// setting the number of bits to analyze, corresponding pins and corresponding powers of two.
// the latter is here for instructional purposes although it is redundant.
const int numberOfBits = 4;
const int randLimit = 15;   // 2^(1+numberOfBits)-1 actually;
int ledPins[numberOfBits] = {13, 8, 12, 7};
int bitValue[numberOfBits] = {8, 4, 2, 1}; // the powers of two

void turnOffAllLeds ()
{
  Serial.println ("turning all off");
  for (int i = 0; i < numberOfBits; i++)
  {
    digitalWrite (ledPins[i], LOW);
  }
}

void selectivelyTurnOnLeds(int value)
{
  turnOffAllLeds ();

  // now for each bit, check if it is set in the value, if yes: turn on corresponding led
  for (int i = 0; i < numberOfBits; i++)
  {
    if ((value & bitValue[i]) > 0)
    {
      digitalWrite (ledPins[i], HIGH);
    }
  }
}

void setup()
{
  for (int i = 0; i < numberOfBits; i++)
  {
    pinMode (ledPins[i], OUTPUT);
  }
}

void loop()
{
  selectivelyTurnOnLeds (random (randLimit));
  delay (1000);
}

```

P.S. When posting a question, please also post what your code is supposed to do. If it were not for a lazy prechristmas workday, I would not have taken the time to reverse engineer your code.
> 2 votes

# Answer
```
int randomnumber = (1, 15);

```

Guess you have missed to call random. That statement actually always returns 15. C is a strange language.

```
int randomnumber = random(1, 15);

```

Cheers!
> 1 votes

# Answer
So here's the new version, very strange, when I set the number on random, it doesn't work. However, if I enter a number myself, it does.

```
const int button = 2;
const int redone = 13;
const int redtwo = 8;
const int greenone = 12;
const int greentwo = 7;
int randomnumber = 0;
int randombinary = 0;

void setup() {

  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(2, INPUT);

      maarten();

    }
      void loop() {

      }

      void maarten(){

      int randomnumber = random(1, 15);
      randombinary = randomnumber;

    if (randombinary >=8){

      digitalWrite(redone, HIGH);
      randombinary = randombinary - 8;
    }
    else {
      digitalWrite(redone, LOW);
 }

    if (randombinary >=4){

      digitalWrite(greenone, HIGH);
      randombinary = randombinary - 4;
    }
    else {
      digitalWrite(greenone, LOW);
    }

    if (randombinary >=2){

      digitalWrite(redtwo, HIGH);
      randombinary =  randombinary - 2;
    }
    else  {
      digitalWrite(greentwo, LOW);
    }

   if (randombinary >=1){

     digitalWrite(greentwo, HIGH);
     randombinary =  randombinary - 1;
   }
   else  {
     digitalWrite(greentwo, LOW);
  }

  }

```
> 0 votes

---
Tags: led, c
---


# Question
Title: Issue with Serial PINs (RX/TX) on Arduino
I have an issue with an Arduino Nano.

I want to communicate with it through the Serial-Port. Meaning I want to send and receive Serial commands. With USB and the "Serial Monitor" this works nice. Now I have connected the COM-Port of the PC with Adruinos Digital Pins 0 and 1 (RX and TX) and a GND PIN. (3 Cables total).

Here is a minimal example of my Code:

```
void setup() {
  Serial.begin(9600,SERIAL_8N1);
  Serial.println("Start");
}

void loop() {
  Serial.println("Hello World");

  delay( 1000 );
}

```

**The Serial Monitor says:**

```
Start
Hello World
Hello World
Hello World
Hello World
...

```

**Putty however says:**

```
▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒::
                                                     ▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒    ▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*

```

Putty is connected with \- BaudRate: 9600 \- Data Bits: \- Stop Bits: 1 \- Parity: None \- Flow Control: None

What is wrong here?

Update: The PC has a 9-pin D socket (Image) This is connected to a RS232 to RJ45 connector (image) From the RJ45-Cable I used the Brown, Blue, and White/Green Cable to connect with the Arduino

# Answer
> 3 votes
RS232 is not TTL. You need a level converter. For more details see https://www.sparkfun.com/tutorials/215.

---
Tags: serial, arduino-nano
---


# Question
Title: Use Arduino to transmit signal to a vibrating pager
I am an engineer at a machine shop. When a machine stops running, I want to be notified via a vibrating pager (like at restaurants). My plan is to attach the arduino board in the machine and when the machine stops (quits vibrating) I want it to trigger the vibrating pager that I have in my pocket. By what means can the arduino communicate with the vibrating pager to cause it to go off? SMS? Wifi? Bluetooth would likely be out of range. Other options?

# Answer
To do SMS through a GSM shield like https://www.arduino.cc/en/Main/ArduinoGSMShield with a dataplan, and the device should be accessible anywhere you can get reception. With a wifi shield like https://www.arduino.cc/en/Main/ArduinoWiFiShield101 you could make it work within your wifi network.

Sparkfun's sales guide at https://www.sparkfun.com/pages/wireless\_guide indicates there are a few bluetooth modules that reach 100m, so if your range is less than 100m, bluetooth is a possibility.
> 2 votes

---
Tags: arduino-uno, communication
---


# Question
Title: How can I attach sensors without a shield for a wearable project?
I am looking for a solution regarding the gsr, accelerometer, heart rate, skin temperature. From this other question seems that Grove isn't clear enough with their documentation. So I am looking for other ideas. I already know cooking hacks and I am afraid that with their hardware I can't make my Arduino wearable and comfortable enough, because at the end I'd like to attach a lithium battery with a case (that's why I don't want the extra bulk of a shield).

More details of what I am looking for.

Accelerometer: Range: +/- 1.0g Minimum resolution: 0.01g

Galvanic Skin Response Range: 56k Ohms to 20M Ohms Two-standard-deviation error of +/- 4.0% otherwise

Skin Temperature Range: 20.0°C to 40.0°C Resolution: 0.05°C Error: +/- 0.8°C

# Answer
> 1 votes
The accelerometer may be pretty easy (since it may not need to be in close contact with the person), but the GSR and skin temperature will need to be touching the person to work.

The first thing you will want to do is to identify the sensors that you want to use, and then come up with some ideas for how to make them wearable so that you can measure the parameters that you're looking for. Will you be able to attach them with straps, or does the attachment need to be more subtle or more comfortable? Small breakout boards are handy, but they may make the sensor uncomfortable to wear.

I'd suggest taking at look at the Adafruit site for some ideas on wearables and sensor interfacing. There is a lot of useful information there and much of it focuses on Arduino based designs. For the most part the sensors they sell and use are well documented either with data sheets or code (or both).

# Answer
> 1 votes
I ran into a similar quandary when making a prototype for a device that needed real test-data from an external, glove-worn accelerometer. I wound up running the data/power/etc pins from my Arduino board to a female RJ-45 jack (I've used a telephone jack on another project where only 4 wires were needed). Then I cut an old cat-5 network cable in half and soldered the wire-ends to data/power/etc pins on my external sensor board. This allowed me to separate one component's wiring scheme from the other's. (FYI: longer lengths of cable between components does increase the risk of noise/interference corrupting digital signals. This can usually be resolved by reducing data rates or by adding a few resistors/capacitors to filter the signal, but I have limited knowledge on this)

Even if you don't have any old RJ45 cables/jacks laying around, it can really help to find some way to "modularize" the various pieces that will be working together when your device is complete. If you're familiar with object oriented programming, think of it as "designing an interface" for each component. Then, even if you completely redesign the wiring for a particular component, you only need to ensure that your "interface" (aka connection) is the same, and you wont need to resolder anything on the other end of the line.

# Answer
> 0 votes
For accelerometer sensing I used LIS3DH from STMicroelectronics, its low power(down to 2uA), small (LGA package 3x3x1 mm) and has cool build-in features (like orientation, tap and doble tap detection among other things). http://www.st.com/web/catalog/sense\_power/FM89/SC444/PF250725?icmp=pf250725\_pron\_pr\_feb2014 and there are a lot of libraries like https://github.com/adafruit/Adafruit\_LIS3DH

For intro to GSR check this project http://cwwang.com/2008/04/13/gsr-reader/ Pretty easy ;) More advanced design will require a signal generator and an instrumentation amplifier. An example of such design can be found here https://www.maximintegrated.com/en/design/reference-design-center/system-board/6147.html/tb\_tab1 Another interesting project is the truth wristband http://produceconsumerobot.com/truth/

The temperature part can be done with a thermistor (IC temperature sensors do not compliant with your resolution spec) and a bridge circuit. For reference check this sensor http://www.digikey.com/product-detail/en/PR103J2/615-1069-ND/2651611 and also some literature about Wheatstone Bridge http://www.ametherm.com/thermistor/ntc-thermistors-temperature-measurement-with-wheatstone-bridge

Hope be helpful.

---
Tags: arduino-uno
---


# Question
Title: How Master and Slave concept works with Bluetooth?
From what I understand the master has primary control over the slaves and communicates with them. A master must always be present as well, and can be connected to (up to) 7 slaves.

**Question**

* If I have 2 arduinos with Bluetooth communicating with each other from within a radius of 80 meters or less, which arduino do I set as the **master** and which do I set as the **slave**? (what dictates which one should be set as master, etc.)

I want both arduinos to be able to transmit data to one-another (where neither has privilege over the other), so in my mind this is more like two slaves communicating. Both devices have the same controls on them and will effect the other devices the exact same way.

* How does the **communication** process work exactly, and how should more arduinos be addressed if they are to be added with similar privileges?

# Answer
Well, master/slave concept for Bluetooth resides on the protocol, not in the communications. On few words, this means Bluetooth Master is who has the ability to initiate connection with a peripheral (or slave), but onces connected both master and slave basically can interchange information without restriction (limited by application). If your bluetooth module or implementation has a SPP (serial port profile https://developer.bluetooth.org/TechnologyOverview/Pages/SPP.aspx) once the master finds and connect to the slave, information can flow in both ways like a chat (actually, chat application is the most common usage example of bluetooth modules)
> 3 votes

---
Tags: bluetooth, system-design
---


title: What does "Arduino compatible" mean?

text:
# Question
Title: What does "Arduino compatible" mean?
I wanted to buy an Arduino (ATmega) 2560 (8 Bit MCU) via Amazon. But there was no Arduino visible. There was only a

On both websides (SainSmart and SunFounder) there is the information that they are Arduino compatible. But all three boards (Atmel-orginal, SainSmart, SunFounder) do not look similar... There are differences. Is it possible to buy one of those boards without:

* checking the datasheet differences
* having problems with the Arduino Ethernet Shield !?

So, what is **compatible** ?

# Answer
> 3 votes
Arduino Compatible can mean many things, but most of the time it means that some company has made something they sell to a customer that supports development with the Arduino IDE.

The thing is that most Arduino Compatible units use the Atmel processors, but some use others too. Third party developers then make "board"-projects that you can add into the Arduino IDE.

Be aware though that you in some cases can run into issues if you dont do your homework, here are some of the issues you can run into:

* Some "compatible" boards use different architectures, so even if you can do many things with the Arduino IDE, maybe some sensor libraries are not supported. (Might have to be hacked or updated)
* Some "compatible" boards have different USB-circuits (if they have them at all)
* Most of the boards you buy off aliexpress, banggood etc. do not come with instructions at all and some times they differ from the "original" design (might be better, might be "the same" or might be worse.).

I'm not trying to scare you off, but just my experiences. You can find a lot of fun things on those sites like clones of lilitiny with the AtTiny 85. One example is in my blog heer: http://mjelde.blogspot.no/2015/12/lilytiny-lilypad-attiny85-wearable-iot.html

The main issue with the clones I've had is that some times they differ in some ways that the first times will make you scratch your head. Like: ESP8266 is Arduino Compatible with the boards manager added ( https://github.com/esp8266/Arduino ), BUT: The input pins are not "correct" marked. So you should then add constants to "remap" them in your code.

Also the ESP8266 does only support 1V analog read, while many Arduinos support 5V. But you can "fix" this with an 16bit ADC (analog to digital converter). The ESP8266 only has 3.3V also, so you cant run sensors that "must" have 5V, without then giving them a different power circuit :)

The AtTiny 85 LilyTiny clone i bought in a pair of 2 from AliExpress works fine and works different than the rest of the Arduinos. Uploading to those for instance means you leave them disconnected and then you hit upload in the IDE. Then it says in the status window to connect it, which you then do.

Then it uploads. It has very few inputs, but it's very cute id say. Primarily it's made for wearable and of course it has a lot of short comings compared to a large arduino board. But you can of course use it to control RGB leds, etc.

Remember to always check specifications (3V vs 5V, how much analog read resolution can it handle, etc). There is the sensor vs board (some sensors work on both 3.3V and 5V, some work only on 5V, some only on 3.3V).

For going to 5V to 3.3V you usually use a voltage divider. Either you can buy pre made ones or you can make it based off three resistors and some math :-)

# Answer
> 2 votes
Arduino is an open-source electronics platform. Lots of other manufacturers make Arduino-compatible boards, not just Arduino/Genuino. I have used both Arduino-branded and 3rd party manufactured boards without encountering any issues. I have not used boards by SainSmart or SunFounder, but they look compatible from a specifications perspective.

If you are worried about compatibility with the Ethernet Shield, you could always buy them as a pair (e.g. SainSmart Arduino Mega 2560 + Ethernet Shield for Arduino UNO Mega Duemilanove R3 AVR PIC ATMEL Robot) just to be on the safe side.

# Answer
> 0 votes
The other answer seem to focus on "compatible" meaning "works with the IDE" but that's not what they mean here. "Compatible" in this context means "clone of the original".

You can count on these boards being functionally identical. The microprocessor and pinout are the same, which is what a shield cares about. The peripheral circuitry might vary slightly, but that's not a big deal. They might (as mentioned) have a different USB-Serial chip but that won't cause any issues once you install the appropriate drivers on your PC.

---
Tags: arduino-mega
---


# Question
Title: Arduino DC motor causes disturbance. What can cause it?
I tried to fix this problem the whole weekend but, after no success I decided to post it here. I would really appreciate any help.

**The problem**

The Wi-Fi module activates the DC motor and lets it run for 3 seconds, but when the DC motor stops after that 3 seconds, the Wi-Fi module and display don't respond anymore. It only works once. (After I push the reset button the same thing happens.)

**Question**

**What causes this disturbance? Any advice on my circuit?** (I included a Fritzing Diagram because I am bad at drawing schematics)

```
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
SoftwareSerial ESP8266(9, 8); // RX = 8 en TX = 9

#define DEBUG true

boolean FAIL_8266 = false;
int LED = 13; // led op 13

int secondeAan = 3000;

String my_AP_SSID = "myID";
String my_AP_Pass = "myPass";

void setup()
{
  // -- stel led in --
  pinMode(LED, OUTPUT);

  // -- lcd scherm --
  lcd.begin(16, 2);
  lcd.clear();
  lcd.setCursor(0, 1);

  do {
    ESP8266.begin(115200); // start communicatie met esp8266

    //Wait Serial Monitor to start
    while (!Serial);

    lcd.clear();
    lcd.print("--- Start ---");

    ESP8266.print("AT\r\n");
    delay(500);

    if (ESP8266.find("OK"))
    {
      FAIL_8266 = false;
      sendData("AT+RST\r\n", 4000, DEBUG);
      sendData("AT+CWMODE=3\r\n", 2000, DEBUG);
      sendData("AT+CWJAP=\"" + my_AP_SSID + "\",\"" + my_AP_Pass + "\",9,4\r\n", 2000, DEBUG);
      sendData("AT+CIFSR\r\n", 2000, DEBUG);
      sendData("AT+CIPMUX=1\r\n", 2000, DEBUG);
      sendData("AT+CIPSERVER=1,80\r\n", 2000, DEBUG);

    } else {
      lcd.clear();
      lcd.setCursor(0, 1);
      lcd.print("Module have no response.");
      delay(500);
      FAIL_8266 = true;
    }
  } while (FAIL_8266);
}

void loop()
{
  // Get the number of bytes (characters) available for reading from the serial port
  if (ESP8266.find("+IPD,"))
  {
    lcd.clear();
    lcd.print("Nieuwe connectie");
    // -- sluit connectie --
    motorToggle();
    sendData("AT+CIPCLOSE=0\r\n", 100, DEBUG);
    sendData("AT+CIPCLOSE=1\r\n", 100, DEBUG);
    sendData("AT+CIPCLOSE=2\r\n", 100, DEBUG);
  }
}

void motorToggle () {
  digitalWrite(LED, HIGH);
  lcd.clear();
  lcd.print("eten gegeven");
  delay(secondeAan);
  digitalWrite(LED, LOW);
  delay(200);
}

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";

  ESP8266.print(command); // send the read character to the esp8266

  long int time = millis();

  while ( (time + timeout) > millis())
  {
    while (ESP8266.available())
    {
      char c = ESP8266.read();
      response += c;
    }
  }

  if (debug)
  { lcd.clear();
    lcd.print(response);
  }

  return response;
}

```

# Answer
> 5 votes
Thanks for the help everyone. I fixed it by using Capacitors. They suppress the noise that the dc motor produces. I found my information here

# Answer
> 3 votes
There are a couple of things that could be causing your problems:

* The current draw of the motor, especially at start up. The motor may be drawing enough power to pull down the voltage at the processor causing it to crash, or
* You may be seeing transients as the motor starts and/or stops that are causing the processor to crash.

One way you could detect problems like this is to use the on-board LED as a heart beat or run indicator. You could either blink it in `loop()` or do something like turn it off just before starting or stopping the motor and then back on afterwards. If the blink stops or if the LED goes out then you know that the processor has stopped running.

As a general rule, except with the tiniest of motors, I'd suggest using the Arduino to control a transistor that controls the motor from its own power supply line (it could be the same supply as the one the feeds the Arduino, just don't run the motor power through the Arduino). That and the suggestions in the comments will go a long way towards isolating the Arduino from the motor and power disturbances it will cause.

---
Tags: arduino-uno, motor, lcd, c, esp8266
---


# Question
Title: Does WiFiClient work on a Yún to send data over a certain IP and port to be received by a Python socket?
I haven't been able to get the example code from the page WiFi:Client:connect() to work on my Arduino Yún. Is this not how I'm supposed to send data over WiFi to be read by something like a socket?

If not, how would I go about doing so? (This is the only solution I've found from the internet).

# Answer
> 1 votes
No, that code is only for the WiFi shield. For the Yun you need to look at the Bridge library that is bundled with the IDE. It allows you to run commands and perform actions on the Linux based Atheros portion of the Yun which is what has access to the WiFi.

---
Tags: wifi, arduino-yun, communication, python
---


# Question
Title: How can I drive this LCD TFT with an Arduino?
As I understand it, the Arduino comes with a TFT library which uses SPI to drive LCD TFTs. I recently bought a TFT labelled "HY-32.TFT" on the front and "HY-TFT320\_262k heyaodz111211" on the back.

It uses an XPT2046 touch screen controller, but I'm more interested in just getting something on the screen currently.

To use the Arduino library, I need to connect pins:

* SCLK
* MOSI
* CS
* DC
* RESET

But I can't see these apart from some similarly named ones associated with TP (touchpad?) and SD (sd card), as the photo shows:

Is it possible to drive this with my Arduino? If so, how?

UPDATE: It looks like the datasheet for the controller and the board can be downloaded from 3.0" 3" TFT LCD Module Display + Touch Panel + PCB adapter.

# Answer
> 1 votes
From what I'm seeing, the touch screen and card reader use SPI but the LCD uses a bunch of Digital I/O lines. The link in Gerben's comment includes a library for the LCD that might be what you're looking for. I hope you're using a ATMega board as it doesn't look like an Uno or similar board will have enough I/O for the LCD.

# Answer
> 0 votes
If you search for "arduino lcd tft shield" on ebay you should if a few shields for your kind of lcd. But all of them require an Arduino MEGA (or DUE). You could also use some kind of a shift register to drive this lcd with an Arduino UNO (or other small boards).

---
Tags: spi, lcd
---


# Question
Title: RGB Led - mixing colors using analogWrite
Currently I'm controlling an RGB LED with my Arduino Nano.

I'm mixing the colors using analogWrite

Though, the LED's don't light up at all for low analogwrite values and the difference between the levels is not visible (to me).

I'm using 100 Ohms resistors between the LED's, using a 680Ohms didn't seem to make a difference.

Analogwrite is working by toggling the LED's fast (PWM)? So not by lowering voltage? This is why I think it's weird that they don't light up at all, on low write values.

My sketch below:

```
#include <SoftwareSerial.h>

int r, g, b = 0;
String command = "";
const byte rxPin = 11;
const byte txPin = 10;

SoftwareSerial blueTooth (rxPin, txPin);

void handleCommand() {
  r = rgbFromCommand("r=",";");
  g = rgbFromCommand("g=",";");
  b = rgbFromCommand("b=",";");

  if(r != -1){
    analogWrite(A2,r);
  }
  if(g != -1){
    analogWrite(A1,g);
  }
  if(b != -1){
    analogWrite(A0,b);
  }
}

int rgbFromCommand(String prefix, String postfix) {
  int idx = command.indexOf(prefix);
  int endIdx = command.indexOf(postfix,idx);
  if(idx>=0 && endIdx>=0){
    idx+=2;
    return command.substring(idx,endIdx).toInt();
  }
  return -1;
}

void setup() {
  pinMode(rxPin,INPUT);
  pinMode(txPin,OUTPUT);
  Serial.begin(9600);
  blueTooth.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    // read the incoming byte:
    char incomingByte = Serial.read();

    if(incomingByte == '\n'){
      handleCommand();
      command = "";
    }else{
      command += incomingByte;
    }
  }
  if(blueTooth.available() > 0){
        // read the incoming byte:
    char incomingByte = blueTooth.read();

    if(incomingByte == '\n'){
      handleCommand();
      command = "";
    }else{
      command += incomingByte;
    }
  }
}

```

# Answer
> 2 votes
Analog pins aren't PWM pins. Instead you have to use the pins marked with a `~`

Pins that aren't PWM pins will be off with a value of 0-127 and on with a value between 128 and 255.

---
Tags: analogwrite, rgb-led
---


title: Using CD4053 for arduino

text:
# Question
Title: Using CD4053 for arduino
I would like to use CD4053 for multiplexing in arduino but the problem is that I don't understand how CD4053 works, is it the same as CD4051, can someone help me, provide example code and circuit??

# Answer
Consider one of the many I2C I/O boards (search for i2c expander on eBay) that can be purchased for a few bucks. They are also available from many of the people that support Arduino. It then only requires 2 pins from the Arduino for up to 8 external devices which can have from 8, 16 and sometimes more I/O per board. They can be used as input or output.

You can also operate several displays on the same two pins as the I/O.

Have fun
> 0 votes

# Answer
The 4053 can replace the 4051 (data sheet). To do that the three output pins on 4053 should be tied together (pin 4, 14 and 15, see logic diagram).

The device allows adding eight analog pins at the cost of three digital pins and one analog pin. The device will multiplex the eight new analog pins onto the arduino analog pin. Three digital pins are used to select which pin is multiplexed.

The arduino tutorial for 4051 will work just fine with the above modification of the wiring.

Cheers!
> 0 votes

---
Tags: arduino-uno, programming, pins
---


title: How to read an RFID reader?

text:
# Question
Title: How to read an RFID reader?
I want to connect an RFID reader to an Arduino board. The RFID reader has several wires attached, and the manual mentions them as follows:

* Red: VCC +12V
* Black: GND
* Green: D 0/RX/4R+
* White: D 1/TX/4R−
* Blue: LED/CS
* Yellow: Beep

There is also another black wire attached, but the manual does not mention it. This is an image of it:

I have the red wire connected to the 5V pin and the black wire to the GND pin on Arduino board. Then I have the white wire connected to the RX pin on the Arduino board.

I'm trying to Serial-read the RX port using this code:

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

void loop() {
    if (Serial.available() > 0) {
        int b = Serial.read();
        Serial.print(b);
        Serial.print(" ");
    }
}

```

When I try to read a keyfob, only this is printed – nineteen times `248`:

```
248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248

```

To me it looks like there's something wrong with the connection somewhere.

How can I properly read this RFID reader? If above assumption is not correct, is there something I should know?

# Answer
Have you tried other baud rates? Could you paste a link to the manual or upload the manual itself? From what i could find quickly, the module supports 3 modes: RS232, RS485 and Wiegand 26/34. So the manual should provide some means of selecting a particular mode (perhaps the CS pin?). I suspect you arent actually using the RS232 mode, which is why you are getting strange results. If you can't find a way to select a mode, you could try brute-forcing it and try the WG26 mode next. This code from seeedstudio seems to do the job http://www.seeedstudio.com/depot/datasheet/RFID\_630\_WG.pde or you could look at the Wiegand protocol on Wikipedia and write your own code, since its relatively straight forward. Also a google image search turned up this link to Aliexpress: http://www.aliexpress.com/item/Waterproof-Security-Door-Access-Control-Wiegand-26-125KHz-RFID-ID-Card-Reader-EM4100-102A/1362129655.html; this is your reader, right?
> 1 votes

# Answer
From my personal experience, you should give some init time to the rfid reader to init.

Try to use a digital output to control the chip reset, and give it some milliseconds to init.

I had a similar behavior with a rfid reader and the reason was this I just told.

Good luck!
> 0 votes

---
Tags: rfid
---


title: 16 by 8 Keyboard matrix

text:
# Question
Title: 16 by 8 Keyboard matrix
I am working on a project, trying to construct an 80 button keypad. My problem is how to multiplex it so that i only feed the arduino with two sets of BCD or binary(whichever is easier) which are supposed to drive a 75 led display board simultaneously with a pair of 7 segments. The led display board is remote, which means i should drive the boards serially. The other 5 buttons remaining out of 80 are for other functions such as clear last number etc. Please help!

---

Thank you very much guys. To answer FuaZe, it is 16\*8 but will not use the whole 128 buttons. These extra buttons are for future expansion. The input should consist 16colums and 8 rows. The remote output board is a led matrix numbered from 1 to 75, arranged in a 15colums and 5rows. The same display board is to have a two digit 7seg display. The remote board is to be accessed serially so as to use few cables. When I press a button on the matrix, say column 5 row 2 the number 20 should appear on the 7seg plus a correspondind diode on column 5 row 2 to light. In short if is a bingo board with numbers 1 to 75..

# Answer
> 1 votes
Easiest would be to use 2 arduino's, which are connected in some way. One of them should tell the other one what to do. I suggest you make the one reading the buttons the "master" and the other one it's "slave" device.

You could use 8 inputs, for each column and 10 outputs for each row. Then you check all 8 inputs per column (pretty rapidly) and then you'll be able to read every button.

You could choose to either send changes or just every value to the slave device.

The slave device would have to do something similiar, but with 2 outputs, to address the right LED's/segments.

Alternatively you could use shift-registers.

There actually are a lot of tutorials on this to be found on the web. You should check out "Arduino multiplexing" or "Arduino led cube" tutorials.

# Answer
> 1 votes
Another option would be using both shift registers and port expanders, like Adafruit's MCP23017 I2C Port Expander.

You can use that for the buttons, just get a few of them and hook them up on the I2C bus and you have over eighty pins for the price of 2! If you choose to use the previously stated expander, you will also benefit from Adafruit's library.

Then, use a shift register for your LEDs, using one of the pins that is not I2C.

Note: Pin expanders can handle input and output. Shift registers are only for output!

Good luck!

---
Tags: keyboard
---


# Question
Title: Arduino hangs after less than a minute, but not on USB
I have arduino uno + ethernet shield + 9V/200mA adapter. I am trying to send some data with HTTP connection. When it's connected to USB it works perfectly, but when I plugged out USB, hangs (after less than a minute, it stops pinging).

I have tried this:

```
EthernetClient.cpp

int EthernetClient::connect(IPAddress ip, uint16_t port) {
  if (_sock != MAX_SOCK_NUM)
    return 0; // i changed to -1  as suggested on previous link

  for (int i = 0; i < MAX_SOCK_NUM; i++) {
    uint8_t s = socketStatus(i);
    if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT || s == SnSR::CLOSE_WAIT) {
      _sock = i;
      break;
    }
  }

```

and also example from library `Examples-library-WebClientRepeating`, but I get the same problem as in my code. Is my adapter too weak?

This code is from Example WebClientRepeating:

```
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED    };

// fill in your Domain Name Server address here:
IPAddress ip(193, 77, 60, 66);
IPAddress subnet(255, 255, 255, 0);
IPAddress gateway(193, 77, 60, 7);
IPAddress myDns(193, 77, 60, 213);

EthernetClient client;

char server[] = "www.arduino.cc";
//IPAddress server(64,131,82,241);

unsigned long lastConnectionTime = 0; // last time you connected to the server, in millisecond
const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
// the "L" is needed to use long type numbers

void setup() {
  // start serial port:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // give the ethernet module time to boot up:
  delay(1000);
  // start the Ethernet connection using a fixed IP address and DNS server:
  Ethernet.begin(mac, ip, myDns, gateway, subnet);

  // print the Ethernet board/shield's IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  if (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if ten seconds have passed since your last connection, then connect again and send data:
  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }
}

// this method makes a HTTP connection to the server:
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the WiFi shield
  client.stop();

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connecting...");
    // send the HTTP PUT request:
    client.println("GET /latest.txt HTTP/1.1");
    client.println("Host: www.arduino.cc");
    client.println("User-Agent: arduino-ethernet");
    client.println("Connection: close");
    client.println();

    // note the time that the connection was made:
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
  }
}

```

**EDIT 1:** Also when I plug USB in its start working with 9V power adapter.

# Answer
> 2 votes
The problem is that when you are using the external 9V power supply, you are relying on the Arduino's on-board regulator to provide the 5V power supply to both the Arduino and the Ethernet shield. This regulator has very limited current capacity — much less than the 500 mA that's available from a PC's USB port — and you're overloading it.

To avoid this problem, you should use a 5V plug pack with a USB connector to power your system.

# Answer
> 1 votes
It may be that, for some reason, the library thinks Serial communication is working, but when the buffer of unsent characters gets full, it hangs waiting to complete a Serial.print() or Serial.println().

So, try commenting out all use of Serial.

For example change

```
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

```

to

```
  /*
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  */

```

and `Serial.println(...);` to `// Serial.println(...);`

This might happen if the system is started with USB working, and then USB is unplugged.

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


# Question
Title: Combine bits from two ports into a single byte
I'm attempting to read the values of 8 pins at a time into a byte.

The obvious answer to this seems to be the Port registers, however with the way the Arduino is wired, I'd have to split my read across two registers.

In this case, I need a way to combine the lower 5 bits of PORTB with the upper 3 bits of PORTD into a single byte.

For example, this is the physical layout with the data lines I'm attempt to read/write to and their corresponding port assignments.

```
             SCSI
DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0
|   |   |   |   |   |   |   |
PB4 PB3 PB2 PB1 PB0 PD7 PD6 PD5
            AVR

```

From what I can gather I need to use some shift operators to achieve this, perhaps something like:

```
hi = PORTB & 3;
lo = PORTD >> 3;

```

But I'm unsure if that's correct and then how I would combine them.

Is it possible to write a macro to make getting and setting this byte easier?

Is there a good learning resource on bit manipulation like this?

# Answer
> 2 votes
Assuming PORTB and PORTD are correctly giving unsigned char values:

```
result = (PORTB << 3) | (PORTD>>5)

```

would do it.

As a macro:

```
#define SCSIBITS ((PORTB << 3) | (PORTD>>5))

```

Then use like this:

```
result = SCSIBITS

```

To make it clearer which specific bits are being used, write:

```
#define SCSIBITS (((PORTB & B00011111) << 3) | ((PORTD & B11100000) >> 5)))

```

It should be easier to see that the lower 5 bits of PORTB, and the upper 3 bits of PORTD are being used.

In the general case, where the values being manipulated are not unsigned char (should not be a problem in this specific case, but may be helpful to know), you might write:

```
#define SCSIBITS ((unsigned char)((PORTB & B00011111) << 3) | ((PORTD & B11100000) >> 5)))

```

or:

```
#define SCSIBITS ((((unsigned char)PORTB & B00011111) << 3) | (((unsigned char)PORTD & B11100000) >> 5)))

```

Here are a few links to bit-manipulation tutorials:
https://www.hackerearth.com/notes/bit-manipulation/
http://www.cprogramming.com/tutorial/bitwise\_operators.html
http://www.tutorialspoint.com/ansi\_c/c\_bits\_manipulation.htm

---
Tags: programming, c
---


title: Arduino read from Server periodically

text:
# Question
Title: Arduino read from Server periodically
I have an arduino attached with a RGB-Shield. I want to query my server for the RGB values periodically. I basically got it working using the Ethernet Shield but it takes too long to get the value (~500ms}. I really want to read the values from my server really really fast in an endless loop.

Can you give me any hints on how I can improve my code?

```
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress server(192,168,1,151);
IPAddress ip(192, 168, 1, 177);
EthernetClient client;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Ethernet.begin(mac, ip);
  }

  delay(1000);

  if (client.connect(server, 80)) {
    client.println("GET /rgb.php HTTP/1.1");
    client.println("Host: 192.168.1.151");
    client.println("Connection: close");
    client.println();
  }
  else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();

    ... read from Server

  }

  if (!client.connected()) {
    client.stop();
    if (client.connect(server, 80)) {
      client.println("GET /rgb.php HTTP/1.1");
      client.println("Host: 192.168.1.151");
      client.println("Connection: close");
      client.println();
    }
  }
}

```

# Answer
> 1 votes
You could try with a direct TCP connection (in this way you skip the HTTP layer) but you need to prepare also a small TCP server (in any language comfortable to you) that accepts the client connection, sends the data, waits the ACK and close the connection.

# Answer
> 0 votes
I would start with this section:

```
if (client.connect(server, 80)) {
  client.println("GET /rgb.php HTTP/1.1");
  client.println("Host: 192.168.1.151");
  client.println("Connection: close");
  client.println();
}

```

How many messages does the Arduino Ethernet library send for this block? Actually due to the implementation of the Arduino Print and EthernetClient class it sends 7 messages (no joke!). It does not collect this into a single message/frame.

The first optimization is to print a single string and send that as one frame.

```
  #define CR "\r\n"

  client.print("GET /rgb.php HTTP/1.1" CR
               "Host: 192.168.1.151" CR
               "Connection: close" CR
               CR);

```

Cheers!

---
Tags: ethernet
---


# Question
Title: A good water flow meter to monitor home usage with Arduino
I'm searching for a good water flow meter to add to my home controller project with Arduino. I have been searching in several pages and I only found some devices that work for low flow. I need to control the water usage in my home and I thought to add a flow meter at the point where the water enters my home, and view the data with Arduino.

Do you have experience with any flow meter with good quality?

# Answer
> 1 votes
I've used an arduino with an irrigation flow meter.

I think I'm getting accurate results, but I haven't checked against a bill. It can handle high flow, and the sensors will attach to any size pvc line. The sensor are a bit expensive, however. $150 for the sensor and $35 for the T junction that it plugs into.

However, as you are living in an apartment, you'll probably need a non-invasive sensor. Perhaps an acoustic one.

---
Tags: sensors, hardware
---


title: Compare const char * to const char

text:
# Question
Title: Compare const char * to const char
Using ArduinoJson I have assigned a value such as;

```
const char* id = root["id"];

```

in the original JSON id was "1"

```
if (strcmp(id, "1") == 0) {
    // this executes
}

```

I have an array of structs that I wish to compare the id against. The struct looks like;

```
typedef struct  {
   char id[2];
   ....
} Device;

```

I assign an id (1-9) into the struct id by

```
_cmd.id[0] = '0' + (++DevicesPtr);
_cmd.id[1] = '\0';
Devices[DevicesPtr-1] = _cmd;

```

where \_cmd is of type Device. Devices is an array with up to 8 entries Now I try to find a match in the devices using the JSON id

```
for (byte i = 0; i < DevicesPtr; i++) {
    if (strcmp(Devices[i].id, id) == 0) {
       // This code does not execute
    }
}

```

I can't seem to get a match I have also tried (Devices\[i\].id == id)

# Answer
> 1 votes
Try something like this:

```
typedef struct  {
  char id[2];
  ....
} Device;

const int DEVICES_MAX = 8;
Device Devices[DEVICES_MAX];

for (int i = 0; i < DEVICES_MAX; i++) {
  Devices[i].id[0] = '1' + i;
  Devices[i].id[1] = 0;
  ...
}

for (int i = 0; i < DEVICES_MAX; i++) {
  if (!strcmp(Devices[i].id, id)) {
  ...
}

```

Cheers!

# Answer
> 1 votes
You can't compare a char and a string.. How can you compare apples and bananas?

Now, you have two ways to do your job.

1) do as @Mikael Patel suggests, so convert your `id`s into strings. This is fine because it will allow you to deal with multiple chars ids.

2) a more efficient way to do this (note that this works with just SINGLE CHARS IDS) is the following one:

```
if (strlen(id) == 1) {
    for (byte i = 0; i < DevicesPtr; i++) {
        if (Devices[i].id == id[0]) {
           // This code will execute if ids match
        }
    }
}

```

Note that id should be exactly 1 char long, otherwise the whole comparison as you thought is meaningless

With this solution you don't need multibyte id char in the struct definition, so you can just define

```
typedef struct  {
   char id;
   ....
} Device;

```

and, in the code,

```
_cmd.id = '0' + (++DevicesPtr);
Devices[DevicesPtr-1] = _cmd;

```

---
Tags: programming, c
---


title: Arduino Nano gives 7V on the 5V PIN!

text:
# Question
Title: Arduino Nano gives 7V on the 5V PIN!
I have an Arduino Nano which is Powered by an external Power supply. This is connected with VIN and GND. The voltmeter says, there are `12,12 V`

I have some components connected on the 5V PIN, which altogether draw max. `100mA` Since some of the components are not working anymore, I started measuring...

I have disconnected everything, but the Arduino Nano Power supply. (`12,12V`)

When I now measure GND and the 5V PIN, the Voltmeter says **6,97V!** I guess this is why my components are giving up.

* But why are there `6,97 Volts` all of the sudden?
* Is my Arduino broken now?
* Can I fix this?
* How can this happen?

# Answer
> 3 votes
Of course the 5V regulator on the nano can be faulty. Another possibility is the 5V decoupling capacitor. If it goes open circuit the regulator will oscillate and the mean output voltage will be near half the input voltage. Most regs have a minimum decoupling cap value specified.

---
Tags: arduino-nano, voltage-level
---


# Question
Title: Small, Power-Efficient wireless communication with ATTiny85
For a project that I'm working on I need an extremely small, power efficient wireless device (could be radio, or some other interface) to network between a series of ATTiny85s and a larger Arduino. The communication range only needs to be about 1 foot, max. I'm currently using wired I2C, so it would be excellent if someone could suggest a radio or another device that can use the two digital pins previously occupied by the SCK and SDA lines on the ATTiny. I have those two, along with one extra digital pin available for use.

This device needs to be extremely small - this common NRF24L01 package is too big and its SPI interface uses too many pins.

Thanks for your help.

# Answer
An RF kit like this one. It's a 2-part kit, Tx and Rx separately -- each needing Vcc, GND and one pin. You need both on each ATTiny to be able to transmit and receive.
> 2 votes

# Answer
I've also had good results with using the Mchr3k - Arduino Manchester Encoding library with those 315mhz RF kits. It has support for ATTiny85 as well.
> 4 votes

---
Tags: arduino-uno, attiny
---


title: Using fluctuating voltage as an input

text:
# Question
Title: Using fluctuating voltage as an input
I had an idea to hack a wireless doorbell so it could send notifications to my phone when someone rings the doorbell.

I pulled out the PCB from the doorbell and powered it using the +5v from the Arduino - so far so good

I used the (once was a wire to the speaker) as an analog input

The issue I have is that the voltage for the chime continues for a long time. eg its at 0 before push then it fluctuates for a second, then returns to 519 for a while, before eventually returning to 0.

Is there a smarter way to do this - I have included my code below.

```
void loop()
{
  //detect a changing voltage
  val = analogRead(sensorPin); //pin A0
  delay(500);
  oldVal = analogRead(sensorPin);//pin A0

//if the voltage changed then +1 to the ring counter
  if (val != oldVal) {
      ringCounter = ringCounter+1;
  }

  if (ringCounter > 3 && pinDevid1State == false) // someone pressed the doorbell
  {
    if(DEBUG){Serial.println("pinDevid1 is HIGH");}
    pinDevid1State = true;
    Serial.println("DingDong");
    digitalWrite(ledPin, HIGH);
    delay(5000);
    Serial.println("Notification Sent.");

    //reset vars
    val = 0;
    oldVal = 0;
    ringCounter =0;
  }

  if (ringCounter < 3 && pinDevid1State == true) // the doorbell stopped ringing
  {
    if(DEBUG){Serial.println("pinDevid1 is LOW");}
    pinDevid1State = false;
    digitalWrite(ledPin, LOW);
    Serial.println("DingDongEnd");
    //Sending request to PushingBox when the pin is LOW
    //sendToPushingBox(DEVID1);    //Here you can run an other scenario by creating a DEVID2 variable

    //reset vars
    val = 0;
    oldVal = 0;
    ringCounter =0;

  }

```

# Answer
> 1 votes
> I wonder if there is another pin on the board I could read

I guess that would depend on the particular doorbell. The transmitter must send some representation of a button press to the receiver - a pulse train for the duration of the press, or perhaps just CW: carrier on, carrier off - which the receiver somehow passes on to trigger the audio. Look at the receiver's output side to identify that trigger signal and pass it, or a processed version of it, to the Arduino.

# Answer
> 1 votes
> I wonder if there is another pin on the board I could read

You could try to hook up a multimeter to the pins/leads from the doorbell button. Positive to doorbell button pin, negative to power supply ground/doorbell battery.

Once you figure out which pin has voltage when the doorbell button is pressed, you can have that go into a digital or analog input in the Arduino. Make sure that the ground from the doorbell PCB and the Arduino are connected so that they'll have common ground and it should be detectable.

---
Tags: arduino-uno
---


# Question
Title: How to make an SMS notification to my phone with Arduino Uno?
I am planning to make an SMS notification to my phone with Arduino Uno via a push of a button.

I have an Arduino Uno C520A Embedded System. Is it possible to do so with this model ? If yes, which WIFI module should I get ?

I just want to make an API request to the web through the push of a button.

# Answer
It is possible if your provider has a sms gateway e-mail-address. Just google which it is for your provider (e.g. number@tmomail.net for T-Mobile (US)). And there should be a lot of tutorial about how to send an email with an arduino.

Every wifi-module with arduino support will work if your WiFi is a standart 3.6Ghz. And yes it should work with any arduino compatible microcontroller.
> 1 votes

# Answer
Arduino uno is only the processor, you will need a Ethernet shield or Wifi shield to connect to the internet. I would suggest Ethernet as it is less pain to configure and no drop of connection.

Then you will need to buy a sms gateway, this one looks pretty cool as they have good http api.

By using the Arduino Ethernet sample, you will need to send a http request to the server when the button has been pressed.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: FFT (or similar) library for the Arduino
I'd like to build a "low fidelity" spectrum analyzer to run on an Adafruit Trinket Pro. My primary goal is to intrigue my seven year-old niece with something that can be hacked. The plan is to pick up sound from a violin with a mic and use a set of 5 or 6 NeoPixels to represent octaves and use color for amplitude.

My first pass at this used Amanda Ghassaei's frequency detection code. It kind of worked, but seemed to be having problems with complex waveforms. After doing some more reading and looking at simple spectrum analyzers it seems that I'd do better using something like a FFT to collect the frequency information. It also seems that that might be stretching the capability of an Arduino…

Are there any FFT libraries that run well on the Arduino (over a range of about 200 to 4000 Hz)? Or are there other approaches that might work better?

# Answer
I havent used any of the libraries to make the FFT for my personal project, due to complexity. Instead I bought a spectrum chip, which returns 7 frequencies: MSGEQ7 ( 63Hz, 160Hz, 400Hz, 1kHz, 2.5kHz, 6.25kHz and 16kHz ).

Otherwise if you are very keen on using a library, this one is very famous and fast for Arduino processors.

But again, if you dont need to have a precise band and the MSGEQ7 is good enough to detect what you want, go for it.
> 1 votes

---
Tags: signal-processing
---


# Question
Title: Arduino Micro project with Bluetooth low energy
I created my project prototype with Arduino Micro and Adafruit Bluetooth low energy device.

Now I need to develop the prototype to production (like a small USB device). I just need Rx, Tx, 3V pin from Arduino Micro.

I started design with ATmega32U4, USB and BLE by using Fritzing IDE. I am confused with Arduino Micro parts like reset, bootloader and other pins. Is there any problem if I leave the unwanted pins from Arduino unconnected, for my project? Will it work correctly like a Arduino micro?

This is my first PCB design. Please help me to design a final PCB with the unwanted pins left unconnected.

# Answer
I have started to look at the Arduino Uno schematics, which are free on the website. To make an Arduino is very simple, just need the chip, crystal, a few capacitors and that's it.

Try to copy the same schematics then add the Bluetooth to the RX and TX pins, but be careful about the 3.3V as you don't want to fry your Bluetooth module :)
> 1 votes

---
Tags: bluetooth, adafruit, arduino-micro, atmega32u4
---


title: How to program AVR in Mac OS X?

text:
# Question
Title: How to program AVR in Mac OS X?
In our college we are using a module developed by IIT Bombay (called FIREBIRD V\[ver 5\]). It has ATmega2560 and ATmega8 microcontrollers (master and slave) with bootloader.

The staff uses AVR Studio for programming. But since AVR Studio is supported only on Windows (and I have a Mac), I was looking for AVR programming in Mac. I downloaded Crosspack AVR. But I don't know how to proceed after this point. Also I downloaded TextWrangler (because I was told auto-suggestion is not available in TextEdit).

Also I have downloaded the Arduino IDE, and I don't know what is required or how to configure it to program AVR microcontrollers.

I searched on the web and nothing is clear (mostly they all depend on something to do with terminal and the command line).

I don't have Xcode installed in my Mac (I saw a relatively easy tutorial on how to set up Xcode for this purpose) and the file is 4GB. I am trying to work around using Xcode, but if it's the only nice way do let me know!

Pertinent suggestions would be helpful.

# Answer
> 3 votes
First, install and get familiar with version 1.6.x of the Arduino IDE. Then, under the sketchbook directory, within `hardware/nex/avr/` (create the directories if they don't exist) create the following files:

### boards.txt:

```
# NEX Robotics Fire Bird V
# Only ATmega2560@14.7456MHz supported for now

nexfirebirdv2560m14.name=Fire Bird V ATMEGA2560 @ 14.7456 MHz
nexfirebirdv2560m14.upload.tool=avrdude
nexfirebirdv2560m14.upload.protocol=avr109
nexfirebirdv2560m14.upload.maximum_size=129024
nexfirebirdv2560m14.upload.maximum_data_size=8192
nexfirebirdv2560m14.upload.speed=115200
nexfirebirdv2560m14.bootloader.low_fuses=0xFF
nexfirebirdv2560m14.bootloader.high_fuses=0xDA
nexfirebirdv2560m14.bootloader.extended_fuses=0xFD
nexfirebirdv2560m14.build.mcu=atmega2560
nexfirebirdv2560m14.build.f_cpu=14745600L
nexfirebirdv2560m14.build.core=arduino:arduino
# This is not the real variant, but it will get the board running
nexfirebirdv2560m14.build.variant=arduino:mega

```

### platform.txt:

```
name=NEX Robotics Fire Bird V
version=0.0.0

```

I have verified that an empty sketch will build, but do not have the hardware to test uploading. The `upload.protocol` value may need to be changed to `avr910` or `arduino` if the current value doesn't work. Make sure to restart the IDE after any changes to the configuration files.

Further improvements that can be done include:

* A real variant for the specific board
* Support for the on-board ATmega8 (for now just use one of the slave firmwares uploaded with avrdude)
* Support for the other AVR boards
* Support for the 8051 and ARM boards

# Answer
> 3 votes
If you don't want to use the Terminal and the command line, the Arduino IDE is your best option. Get yourself an AVR programmer (or an Arduino Uno to serve as programmer, with the ArduinoISP sketch uploaded), and code on it.

Then connect your Arduino to your module via SPI. Select the correct processor and port.

You can now upload the sketch:

---
Tags: avr, mac-os, avr-toolchain
---


title: Arduino Servo Free Rotation

text:
# Question
Title: Arduino Servo Free Rotation
I have a project where I use 22 servos. I attach all 22 of the servos in the setup and in the loop, I use `myservo.write()` command to make a particular servo move to a particular position.

The problem here is that, all the other servos become stiff at this point of time, even though I am not writing any value to those servos. By stiff I mean that the servo is holding at a particular random value. Which for most of the 22 servos is at or near 90°.

My question is how can I make a particular servo move, while allowing all the other servos to freely rotate. I think that when I attach a servo the program prevents the free rotation of the servo.

I was wondering if the signal to one of the servos is leaking to other servos because of an issue with wiring, but this is not the case. The other servos become stiff only when I attach them to the pins which have been "attached" as a servo in the program.

# Answer
> 0 votes
When you `attach` a servo the Arduino starts generating the PWM waveform for its currently selected angle. When you `write` to the servo you just change the current angle and the waveform changes to match. That waveform is constantly being generated from the moment the servo is attached, and will always be generated. That is how servos work. They are not really designed to be back-driven by the load turning the cogs - it is the role of the servo to do the driving, not to be driven.

Depending on the servo you might actually damage the mechanics by driving it backwards like that.

The only way you can stop the servo from being actively driven is to detach the pin from the servo system so that it doesn't think there is a servo there any more.

---
Tags: arduino-mega, arduino-ide, servo
---


# Question
Title: Basic C++ programming, how to pass constructor argument into class?
I'm having some programming problems.

So here's what's happening:

In my .ino file, I have a `tft` variable which holds the connection to a LCD. I want to make a class which can either automatically access that `tft` class contained in the .ino, or pass it into the constructor when it's created; so basically:

```
// assuming this is the .ino:

TFT_ILI9163C tft = TFT_ILI9163C(cs, dc, rst);

MenuClass *menu = MenuClass();
menu->init("Example", tft); // this should work and "menu" should now have access to the "tft" variable

```

Here's my Menu.cpp:

```
// Menu class

#include "Menu.h"
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <TFT_ILI9163C.h>

String menName = "Unnamed";

void MenuClass::init(const String name)
{
    menName = name;
}

String MenuClass::getName() {
    return menName;
}

void MenuClass::draw() {
    tft.setCursor(2, 2);
    tft.print(menName);
}

MenuClass Menu;

```

# Answer
Assuming you want to require every instance of MenuClass should be associated with a TFT\_ILI9163C display object, you could use something like this:

```
// MenuClass.h

class TFT_ILI9163C; // declare a class name which is defined in TFT_ILI9163C.h

class MenuClass
{
  private:
    // read-only private member initialized by constructor
    // (the m_ prefix is commonly used to denote class member values)
    TFT_ILI9163C* m_tft;

  public:
    // constructor
    MenuClass(TFT_ILI9163C* pTft) : m_tft(pTft) {};

  private:
    // private storage for the Name property
    String m_Name;
  public:
    // read the Name property
    String getName() {
      return m_Name;
    };
  public:
    // write the Name property
    void setName(String value) {
      m_Name = value;
    };

  public:
    void draw() {
      // the m_tft member is a reference to the display class
      m_tft->setCursor(2, 2);
      m_tft->print(m_Name);
    };
}
MenuClass Menu;

```

Note that there is only one constructor, and it requires a pointer to the TFT\_ILI9163C display. The body of the constructor `: m_tft(pTft) {};` initializes the private member `m_tft` with the constructor argument `pTft`, so MenuClass member functions invoke TFT functions as `m_tft->fn(args);` Since there is no "void constructor" `MenuClass(void)`, `m_tft` is effectively guaranteed to point to a valid TFT\_ILI9163C instance.

Since it looks like you were using `menName` kind of like a class property, I rewrote that in the more commonly used m\_propertyname style. Your `MenuClass::init()` was behaving like a name property setter; I'm not sure whether menu initialization requires anything else. This simple example has class MenuClass defined entirely inside the header file.

Usage is pretty similar to your example code, except now the MenuClass constructor requires a pointer to a previously constructed TFT\_ILI9163C display instance:

```
// Main application
#include <TFT_ILI9163C.h>
#include "MenuClass.h"
// ... etc ...

// the TFT_ILI9163C display instance
TFT_ILI9163C tft = TFT_ILI9163C(cs, dc, rst);

// an example menu that draws on the display
MenuClass *menuFoo = new MenuClass(&tft); // use new to get pointer to new class instance
// MenuClass *menuFoo = MenuClass(&tft); // cannot convert 'MenuClass' to 'MenuClass*' in initialization

void setup() {
  // an example menu that draws on the display
  menuFoo->setName("Example");
  menuFoo->draw();
}

```

If you wanted to pass the constructor an initial Name property value as well as the tft display pointer, you could define the constructor as

```
  public:
    // constructor
    MenuClass(TFT_ILI9163C* pTft, String name) : m_tft(pTft), m_Name(name) {};

```

You could even go a step further, and give the name argument a default value:

```
  public:
    // constructor
    MenuClass(TFT_ILI9163C* pTft, String name = "Unnamed") : m_tft(pTft), m_Name(name) {};

```

So with this modification, the expression `MenuClass(&myTFT)` is the same as the expression `MenuClass(&myTFT, "Unnamed")`, but you can still override the default value like `MenuClass(&myTFT, "DoSomething")`.

It is also perfectly legal to put statements inside the `{ }` block of the constructor, but in this example all of the work is accomplished by the `:memberName(value)` constructor syntax.

Edit: `MenuClass *menuFoo = new MenuClass(&tft);` thanks @BrettAM
> 2 votes

---
Tags: c++, arduino-ide, atmega32u4
---


# Question
Title: Could you tell me what is wrong with this Arduino code?
```
void fn( int pin, int pos)
{
    Servo temp;
    temp.attach(pin);
    temp.write(pos);
    delay(15);
    temp.detach();
}

void loop()
{
    int pos = 0 ;
    for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
        // in steps of 1 degree
        //tmp2.write(pos);
        //delay(15);
        fn(41,pos);
        fn(2,180 - pos);
    }
    for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
        fn(41,pos);
        fn(2,180 - pos);
    }
}

```

But when I run the code in mega , the servo does not move when attached to pin 2 or 41. The reason I am creating a function fn , is so that the servo does not stay attached. I want the servo to rotate freely when I am not giving it a pwm signal.

# Answer
Arrange your code like this:

```
Servo servo1, servo2;

void setup() {
    servo1.attach(41);
    servo2.attach(2);
}

void loop()
{
    int pos;

    for (pos = 0; pos <= 180; pos++) {
        servo1.write(pos);
        delay(15);
        servo2.write(180 - pos);
        delay(15);
    }

    // 2nd loop here

}

```

It's rather inefficient to detach a servo after each write and then attach it again for the next write. Simply keep it up all the time.
> 2 votes

---
Tags: arduino-mega, servo
---


# Question
Title: Starting usb on pro micro after deep sleep (ATmega32u4)
I have just started playing with a low power arduino project, and have managed to get the power drain down to about 220uA using `powerDown` from `LowPower`.

What I would love to be able to do is start the USB controller and send some data every 8 seconds, but I cant seem to send anything...

Any idea would be greatly appreciated :)

Her is my code:

```
// **** INCLUDES *****
#include <LowPower.h>

#include <avr/interrupt.h>
#include <avr/power.h>
#include <avr/sleep.h>
#include <avr/io.h>

void setup()
{
  DDRD = B00100000;       // PORTD5 = TXLED
  DDRB = B00000001;        // PORTB0 = RXLed

  Serial.begin(9600);
  while (!Serial) ; // Needed for Leonardo only
  Serial.println("Starter...");
  delay(100);
  Serial.end();

  /*
  *  IKKE FJERN DENNE!!! Da greier vi ikke å omprogramere kortet...
  */
  delay(10000);
  Serial.begin(9600);
  while (!Serial) ; // Needed for Leonardo only
  Serial.println("low-power...");
  delay(100);
  Serial.end();
  flash();
}

void loop()
{
  //LowPower.idle(SLEEP_8S, ADC_OFF, TIMER4_OFF, TIMER3_OFF, TIMER1_OFF, TIMER0_OFF, SPI_OFF, USART1_OFF, TWI_OFF, USB_OFF);//, USB_OFF);
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
  //USBCON &= B11011111; //Disable USB Freeze clock USBCON.FRZCLK
  //USBCON |= B10010001; //SET USB_MACRO_ENABLE_BIT USBCON.USBE

    PLLCSR |= B00000010;   //-Enable             PLL PLLCSR.PLLE = 1;
    while (!(PLLCSR & 1)); //-Wait PLL LOCK      while (PLLCSR.PLOCK != 1);
    USBCON &= B11011111;   //-Unfreeze USB clock USBCON.FRZCLK = 0; (Clear to unfreeze)
    //-Clear Resume information ???

  flash();

  /*
  * Test USB kommunikasjon :)
  */
  Serial.begin(9600);
  while (!Serial);
  delay(5);
  Serial.println("Hello world!!!");
  delay(5);
  Serial.end();
   PORTD |= B00100000;
   PORTB |= B00000001;
}

void flash() {

   PORTD &= B11011111;
   PORTB &= B11111110;
   delay(100);
   PORTD |= B00100000;
   PORTB |= B00000001;
   delay(100);

   PORTD &= B11011111;
   PORTB &= B11111110;
   delay(100);
   PORTD |= B00100000;
   PORTB |= B00000001;
   delay(100);

   PORTD &= B11011111;
   PORTB &= B11111110;
   delay(100);
   PORTD |= B00100000;
   PORTB |= B00000001;
   delay(100);
}

```

Best regards, Richard

# EDIT

The manual specifies this resume protocol: Resuming the USB interface (21.13 USB Software Operating Modes)

* Enable PLL
* Wait PLL lock
* Unfreeze USB clock
* Clear Resume Informtion

which I have translated into this:

```
PLLCSR |= B00000010;   //-Enable             PLL PLLCSR.PLLE = 1;
while (!(PLLCSR & 1)); //-Wait PLL LOCK      while (PLLCSR.PLOCK != 1);
USBCON &= B11011111;   //-Unfreeze USB clock USBCON.FRZCLK = 0; (Clear to unfreeze)
//-Clear Resume information ???

```

It have no effect whatsoever, have no idea how to **clear resume information** though...

Also, for the record, the LEDs are flashing happily every 8 seconds.

# Answer
I found an answer to a similar question here: https://forum.sparkfun.com/viewtopic.php?f=32&t=39214&start=15#p175098

Note: it requires you to close and open the serial monitor at proper timings.

```
// disable the USB prior going to sleep
USBCON |= _BV(FRZCLK);  //freeze USB clock
PLLCSR &= ~_BV(PLLE);   // turn off USB PLL
USBCON &= ~_BV(USBE);   // disable USB

// and wake it up after
//routine to properly wake up
sleep_disable();
delay(100);
USBDevice.attach(); // keep this
delay(100);
Serial.begin(9600);
delay(100);

```
> 1 votes

---
Tags: arduino-leonardo, arduino-micro
---


# Question
Title: Class is not tracking changes to a private field
I have a program where a device registers itself with a command object. The command object is losing track of the registrations. The following program repeats "0 devices registered" even though when it initializes it displays "Devices registered 1". My guess is that I am accidentally creating 2 copies of the command object. This is the main sketch

```
#include "command.h"
#include "widget.h"

Command command;
Widget widget;
void setup() {
  command.init();
  widget.init(command);
}

void loop() {
  command.update();
}

```

command.h

```
#include "Arduino.h"

#ifndef Command_h
#define Command_h

typedef struct  {
  char id;
  char name[20];
} Device;

class Command
{
  public:
    Command();
    void init();
    void registerDevice(Device _cmd);
    void update();
  private:
    Device Devices[20];
    byte DevicesPtr = 0;
};

#endif

```

command.cpp

```
#include <Arduino.h>
#include "command.h"

#define DEVICES_MAX 9

Command::Command() {
  DevicesPtr = 0;
  Device Devices[DEVICES_MAX];
}

void Command::init() {
  Serial.begin(9600);
}

void Command::update(){
  Serial.print( DevicesPtr );
  Serial.println( " devices registered" );
  delay(500);
}
void Command::registerDevice(Device _cmd) {
  _cmd.id = '0' + (++DevicesPtr);
  Devices[DevicesPtr] = _cmd;
  Serial.print("Devices registered ");
  Serial.println(DevicesPtr);
}

```

widget.h

```
#include "Arduino.h"
#include "command.h"

class Widget
{
  public:
    static void init(Command _command);

  private:
};

```

widget.cpp

```
#include "widget.h"
#include "command.h"

void Widget::init(Command _command) {
  Device device;
  strcpy(device.name, "Widget #1");
  _command.registerDevice(device);
}

```

# Answer
It is all about calling conventions and argument binding. The code is using call-by-value when it should be call-by-reference.

This is call-by-value (the incoming command is not updated, a copy is passed as parameter):

```
void Widget::init(Command _command)
...
widget.init(command);

```

This is call-by-reference (a pointer to command is passed as parameter):

```
void Widget::init(Command* _command)
{
   __command->registerDevice(...);
}
...
widget.init(&command);

```

Alternative syntax is:

```
void Widget::init(Command& _command)
{
   _command.registerDevice(...);
}
...
widget.init(command)

```

Cheers!
> 4 votes

---
Tags: class
---


# Question
Title: Is a HC-SR04 fast enough to make decisions on moving robot (4 Johnson motors 300 rpm)?
I am working on a project in which I have made a robot powered by 4 Johnson DC motors (300 rpm) and controlled by Arduino UNO R3. Now in my project I'd used ultrasonic sensor (HC-SR04) for detecting obstacles.

What I want is that as soon as my an obstacle is detected robot should turn by 180° but what actually happening is that sometimes robot takes turn very late (though I'd kept range of sensor approximately 50cm) and sometimes it just collides with obstacles.

As I'm new to Arduino I just want to know if an ultrasonic sensor is fast enough to sense obstacles and signal the Arduino about it, before it gets close enough?

Here's my code

```
int sense()
{
     analogWrite(trigPin, 0);
 // instead of digitalWrite(trigPin,LOW);
     delayMicroseconds(2);

/* as I'd used my digital pins for  motors and all i have to use pwm pin for  trigger pin of sensors i guess it doesn't make any difference*/

     analogWrite(trigPin, 255);
  // instead of digitalWrite(trigPin, HIGH);
     delayMicroseconds(10);

     analogWrite(trigPin, 0);
     duration = pulseIn(echoPin, HIGH);

     distance = duration/58.2;

      if (distance > maximumRange)
          return 0;
      else
          return 1;
}

```

# Answer
On it's max speed, how far is it's braking distance? Then you should start braking atleast from before that distance of the object.

Let's say your braking distance is 25cm, you should start braking \>25cm. But this is only when you would *instantly* brake at the moment you're within 25cm reach.

So we have to know how many distance we will travel during the calculation, before we start braking. You could just try it out, set the distance a little higher everytime you crash into it (Assuming it doesn't fail and is always at the same time).

We have to know the top speed of your motor, RPM doesn't say a lot in this story, we'll need to know how big your wheels are to be able to determine how many cm's you'll travel per revolution, and doing that times the RPM, you know your top speed. (Or you can also measure this, but it can change depending on how full your battery is)

Also, your code should be **real-time** you'll likely want to use **timers** to trigger the `trigPin` and use an interrupt on the `echoPin` to be sure none of your code will delay your sensor. This will improve execution speed aswell as reliability/deterministic timing. Also, it will make it possible to run it aside from your regular code.

So if you know, your top speed = 10cm/second.

And you know that 1 calculation+reaction-time is 200ms.

You can safely assume that you need \>2cm extra.

To be honest, you should add a little for when it's slippery/another surface or just so you won't touch the object.

So. The ping sensor is almost always fast enough, only if the calculated range is outside your max range, it will not work. You could however, use an IR proximity sensor which will trigger at a set distance. This way you don't have to do any calculations and just brake whenever you receive the interrupt. But it won't tell you the distance to the object.

The cool thing on the distance sensor is that you can also scale the brake distance on your driving speed, so that it will brake later when you're driving on half your speed. That way you can come very close to an object, but still be 100% sure that you won't crash into it.
> 1 votes

# Answer
Try using NewPing library. Ping sensors consistently and reliably at up to 30 times per second.
> 0 votes

---
Tags: sensors
---


# Question
Title: Use Unix terminal instead of the Monitor on Arduino IDE
I want to make a shell or C script that interprets the Arduino serial input to run commands. For that, I will need to make that script be the Serial monitor for my arduino. Another reason I want to use scripts or the command line as a Serial I/O is because the Arduino monitor function freezes the IDE.

My arduino's serial port is `/dev/tty.usbmodem1d112`

This is what I have tried so far:

1. `cat /dev/tty.usbmodem1d112` \< This returns absolutely nothing
2. `screen /dev/tty.usbmodem1d112` \< This Prints output, but has problems with input.
3. `cat < /dev/tty.usbmodem1d112` \< Same result as cat without the `<` symbol.

Sometimes, I also get annoying **Resource Busy** messages. This makes me re-plug the Arduino board.

---

OS X (10.9.5) Arduino IDE latest version. Arduino M0 pro board.

# Answer
> 8 votes
You'll need to condition the serial line with the `stty` command to get this to work. One of the easier ways to do it is to start by using the Serial Monitor and running the command:

`stty -g < /dev/tty.usbmodem1d112`

That will show you all of the settings that the Serial Monitor used to conditions the line. The `-g` flag to stty tells it to give you the results in a form that can be used as the arguments to another stty command. You could do this like this:

`echo -n 'stty ' > stty.arduino ; sudo stty -g -f /dev/tty.usbmodem1d112 >> stty.arduino`

`chmod +x stty.arduino`

The first line creates a shell script to condition the serial line. The second line makes it executable so that you can run it as a shell command – `./stty.arduino`. The `sudo` runs the command as root (with elevated privilege) which allows you to open the port even though the Serial Monitor will already have it open.

If you want you could move the command into a directory on your `$PATH` (for example ~/bin) so that it can be found regardless of where your current directory is.

After getting set up you can see the output from `Serial.println()` on the Arduino by doing:

`./stty.arduino`

`cat < /dev/tty.usbmodem1d112`

Depending on what you are trying to do, you might find the expect or script commands helpful. Expect (man page) lets you automate interactions with a text based application or process. Script (man page) creates a transcript of your interactions on the command line with another program or process.

---
Tags: serial
---