# Question
Title: Board and library updates required caused an error
I compiled my code several times today, I would quit and restart randomly through the day. each time I started I get a error box board and libraries need updates. I did an AVR board up date, then compiled and now I get this every time.....

---

avrdude: no programmer has been specified on the command line or the config file Specify a programmer using the -c option and try again

---

Yes I have tried rebooting my Windows 7 64 bit AMD machine.

this is on IDE "Arduino 1.6.8"

Of course I made the mistake of not backing up my IDE folders in the belief that an update would not screw my IDE up.

Nothing will upload, not even any of the examples. I turned on Show Verbose output during Compilation, and upload I pasted the full output and it was 4500 char to many for this so I turned of the compilation check and left just the upload check on show verbose errors

I loaded in the example blink,

## the file followed by the IDE lower window text.

```
/*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.

  Most Arduinos have an on-board LED you can control. On the Uno and
  Leonardo, it is attached to digital pin 13. If you're unsure what
  pin the on-board LED is connected to on your Arduino model, check
  the documentation at http://www.arduino.cc

  This example code is in the public domain.

  modified 8 May 2014
  by Scott Fitzgerald
 */

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
}

```

---

END OF FILE Copy and paste of the lower IDE window last lines the same as above

---

```
Sketch uses 928 bytes (2%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
C:\Users\Lee\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino2/bin/avrdude -CC:\Users\Lee\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino2/etc/avrdude.conf -v true -patmega328p -carduino -PCOM10 -b115200 -D -Uflash:w:C:\Users\Lee\AppData\Local\Temp\build9c9ef3bdfe2fccb480bc6e4bac749e41.tmp/Blink.ino.hex:i

avrdude: Version 6.3, compiled on Jun 22 2016 at 16:05:21
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\Lee\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino2/etc/avrdude.conf"

avrdude: no programmer has been specified on the command line or the config file
         Specify a programmer using the -c option and try again

```

---

There is that line again What do I do to fix this? besides deleting everything and starting all over again?

I do not want to delete and start over

# Answer
This sounds very much like the problem I had when I updated my ARV version,I was also getting "no programmer has been specified error", I run Windows 7 32bit, the way i got out of it was to go back to the update screen when it pops up and in Arduino ARV Boards area....select versions....I went back to version 1.6.10...now it all works again.....at this point I am no longer updating my ARV, but I will after a few more version updates come out, there is obviously something that conflicts at this stage, if you google the problem you will find other of ways to fix this.
> 1 votes

---
Tags: avrdude, programmer
---


title: Can't display text on LCD 1602

text:
# Question
Title: Can't display text on LCD 1602
Today I tried to display some text with my Arduino UNO and a LCD 1602A screen. I did find some schemas online, but I cannot get any character or "black boxes" on the display.

I connect wires like that : Pin 1 : GND Pin 2 : +5V Pin 3 : 50K Pot. Pin 4 : Pin 7 from Arduino Pin 5 : GND Pin 6 : Pin 6 from Arduino Pin 11 : Pin 5 from Arduino Pin 12 : Pin 4 from Arduino Pin 13 : Pin 3 from Arduino Pin 14 : Pin 2 from Arduino Pin 15 : +5V Pin 16 : GND

You can see my setup here : https://i.stack.imgur.com/u32sj.jpg

The LCD screen is lighten up, but nothing else appears. Pot. is working (increase or decrease light). I tried to change the LCD with another, but both are not working. I tested some many code, here an example :

```
/*
  LiquidCrystal Library - Hello World

 Demonstrates the use a 16x2 LCD display.  The LiquidCrystal
 library works with all LCD displays that are compatible with the
 Hitachi HD44780 driver. There are many of them out there, and you
 can usually tell them by the 16-pin interface.

 This sketch prints "Hello World!" to the LCD
 and shows the time.

  The circuit:
 * LCD RS pin to digital pin 12
 * LCD Enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4
 * LCD D6 pin to digital pin 3
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * LCD VSS pin to ground
 * LCD VCC pin to 5V
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)

 Library originally added 18 Apr 2008
 by David A. Mellis
 library modified 5 Jul 2009
 by Limor Fried (http://www.ladyada.net)
 example added 9 Jul 2009
 by Tom Igoe
 modified 22 Nov 2010
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/LiquidCrystal
 */

// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

```

Do you have an idea ? Thanks !

# Answer
> 2 votes
I realize that your question is based around using multiple connections to the arduino, however if you wish to simplify the setup/operation have a good look into I2C interface, this only uses 2 pins SDA and SCL to operate, you can get an interface board on Ebay for $1.00....just a thought.

# Answer
> 1 votes
Wiring on the photo and description you provided are not consistent. On the photo, LCD-RS (PIN 4) is connected to `D12` and LCD-E (PIN 6) is connected to `D11`?

If so, initialization must be `LiquidCrystal lcd(12, 11, 5, 4, 3, 2);`

---
Tags: arduino-uno, lcd
---


# Question
Title: Initialize a class (HX711) within a class with constructor and parameters
I am far from being an Arduino specialist, so please bear with me if some of my code below is far from correct.

I am writing a sketch in which I need to use 3 instances of the HX711 library, as I am using 3 different weight sensors.

In order to try to clean up the code, I want to put basically all the code using HX711 in my own class.

Here is what my ScaleMeasure.h looks like:

```
// ScaleMeasure.h
#ifndef _SCALEMEASURE_h
#define _SCALEMEASURE_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
#else
    #include "WProgram.h"
#endif

#include <CmdMessenger.h>
#include "HX711.h"

class ScaleMeasure
{
 public:
    ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID);
    void Setup();
    float Measure();

private:
    int _dout_pin;
    int _clk_pin;
    float _calibration_factor;
    byte _scaleID;
    HX711 _scale = HX711(_dout_pin, _clk_pin);
};

```

and .cpp

```
#include "ScaleMeasure.h"

ScaleMeasure::ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID)
{
    _clk_pin = Clk;
    _dout_pin = Dout;
    _calibration_factor = CalibF;
    _scaleID = ScaleID;
}

void ScaleMeasure::Setup()
{
    _scale.power_up();
    _scale.set_scale();
    _scale.set_scale(_calibration_factor);
    _scale.tare();
    _scale.read();
}

float ScaleMeasure::Measure()
{
    return _scale.get_units(5);
}

```

but there is obviously something wrong, as a call to the constructor lock the rest of the program. I believe that my instantiation, of HX711 in ScaleMeasure.h `HX711 _scale = HX711(_dout_pin, _clk_pin);` is not correct, or not in the right place. The code compile fine, though.

Thanks for your help.

# Answer
The right way, in C++, to properly construct a field member `b` (of type class `B`) inside a class `A` is to do it as follows in `A`'s constructor:

```
A::A() : b(...) {
    // Other init code here
}

```

In your situation that would mean:

```
class ScaleMeasure
{
 public:
    ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID);
    void Setup();
    float Measure();

private:
    int _dout_pin;
    int _clk_pin;
    float _calibration_factor;
    byte _scaleID;
    HX711 _scale;
};

```

Note that I have removed the init part for `_scale`.

```
ScaleMeasure::ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID)
: _scale(Dout, CLk)
{
    _clk_pin = Clk;
    _dout_pin = Dout;
    _calibration_factor = CalibF;
    _scaleID = ScaleID;
}

```
> 1 votes

# Answer
Unfortunatly HX711 has no default constructor. So the easiest way would be to add one in the header:

```
HX711() {} // default constructor, empty

```

Add member function to do the init job (done by original constructor), also in the header file

```
    void Init(byte dout, byte pd_sck, byte gain = 128) {
    PD_SCK  = pd_sck;
    DOUT    = dout;

    pinMode(PD_SCK, OUTPUT);
    pinMode(DOUT, INPUT);

    set_gain(gain);
}

```

Now your ScaleMeasure class will be like (header):

```
class ScaleMeasure
{
 public:
    ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID);
    void Setup();
    float Measure();

private:
    int _dout_pin;
    int _clk_pin;
    float _calibration_factor;
    byte _scaleID;
    HX711 _scale;
};

```

and cpp

```
ScaleMeasure::ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID)
{
    _clk_pin = Clk;
    _dout_pin = Dout;

    _scale.Init(_dout_pin, _clk_pin);

    _calibration_factor = CalibF;
    _scaleID = ScaleID;
}

```
> 1 votes

# Answer
The line

```
HX711 _scale = HX711(_dout_pin, _clk_pin);

```

would be executed at construction time, which is the wrong time for it to run since `_dout_pin` and `_clk_pin` won't be set. Instead (much as it pains me to recommend it) you will have to use dynamic allocation:

```
HX711 *_scale;

```

Then you can, in your constructor:

```
_scale = new HX711(_dout_pin, _clk_pin);

```

Since you now have a pointer all your accesses to it need to change to `->` instead of `.`:

```
_scale->power_up();
... etc ...

```

Also you should add a destructor to your class that deletes the object pointed to by `_scale` if it has been created.
> 0 votes

---
Tags: arduino-uno, class
---


title: Sniffing RF signals

text:
# Question
Title: Sniffing RF signals
I am using an Arduino UNO and an RXb6 (I would link to the data sheet if I could find one) to try to decode a RF Signal that controls a remote outlet. I have the devices connected as you would assume 5V+ to 5v, Gnd to Gnd, Antenna is not connected as I think it would only exacerbate my problem, and data is connected to the A0 pin on my UNO.

The problem I am having is with all the noise that I am getting with my signal.I hooked it up to my o-scope to give a better idea of whats happening. When no signal is being transmitted this is the noise I am seeing:

Just lots of static. When I press the remote button I can see a clean signal come through (note that it is cutoff):

I was able to export a CSV of the wave and manually clean it up but it was just such a pain trying to translate it back to highs and lows for the arduino to send.

**How can I reduce signal noise on my 433MHz receiver so the arduino can read the actual signal instead of noise?**

# Answer
> 4 votes
I'm adding another answer, because I don't think the core thing to grasp is mentioned, and others might benefit :)

The noise you are seeing, is actually the result of a feature of the RXB6, KSA6, and similar modules. When they see no signal, they increase gain/sensitivity until they do see a signal. The upside of this is they are very sensitive, and can operate well over quite long ranges. The downside is that if there really is no signal, they will start picking up anything that remotely looks like a signal, the noise you see :)

Dealing with this noise is the job of the software/protocol and other electronics built around the receiver. A common way to solve it, which the VirtualWire library also uses, is to send some unimportant 'data' first, which makes the receiver decrease it's sensitivity, and then send the important data. Another common way is to just repeat the data several times, this is also what your wall sockets most likely do.

In software you can usually find the 'important' parts by looking at pulse lengths, the noise is usually short high pulses, most protocols use far longer pulses, which also have a predictable/defined length.

What I did in exactly your case was to dump the sound recording as a raw signed pcm 16 bit file, which I could then easily read into a bit of software I wrote, which find's the high/low transitions, filters out any short pulses, and then writes out the output (like a csv) you want :)

---
Tags: arduino-uno, rf, signal-processing
---


title: Webserver on Arduino: Refresh issues

text:
# Question
Title: Webserver on Arduino: Refresh issues
I am using W5100 Ethernet Shield Network Module with arduino Unoas a webserver to trigger four relays connected to it.

The relays may be toggled through the four buttons attached to it physically, or through the four buttons on the hosted webpage. There is a counter how many times the relays are toggled which can be reset through a button on the webpage.

My issue is, whenever I toggle the relay through physical button, it does not update the counter on the webpage. And if I refresh the page, the last command from the page, such as togglerelay1 keeps echoing.

What solution do you propose to this problem:

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

int Relay1 = 2;
int Relay2 = 3;
int Relay3 = 4;
int Relay4 = 5;
int Button1 = 8;
int Button2 = 9;
int Button3 = 10;
int Button4 = 11;

String on = "On";
String off = "Off";

String Relay1Status = on;
String Relay2Status = on;
String Relay3Status = on;
String Relay4Status = on;

int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;

byte toggle1 = LOW;
byte toggle2 = LOW;
byte toggle3 = LOW;
byte toggle4 = LOW;

void toggleRelay1();
void toggleRelay2();
void toggleRelay3();
void toggleRelay4();

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };   //physical mac address
byte ip[] = { 172, 168, 1, 178 };                      // ip in lan (that's what you need to use in your browser. ("192.168.1.178")
byte gateway[] = { 172, 168, 1, 1 };                   // internet access via router
byte subnet[] = { 255, 255, 255, 0 };                  //subnet mask
EthernetServer server(80);                             //server port
String readString;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  pinMode(Relay1, OUTPUT);
  pinMode(Relay2, OUTPUT);
  pinMode(Relay3, OUTPUT);
  pinMode(Relay4, OUTPUT);
  pinMode(Button1, INPUT_PULLUP);
  pinMode(Button2, INPUT_PULLUP);
  pinMode(Button3, INPUT_PULLUP);
  pinMode(Button4, INPUT_PULLUP);
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {

  if (digitalRead(Button1) == LOW) {
    toggleRelay1();
    while (digitalRead(Button1) == LOW);
  }
  if (digitalRead(Button2) == LOW) {
    toggleRelay2();
    while (digitalRead(Button2) == LOW);
  }
  if (digitalRead(Button3) == LOW) {
    toggleRelay3();
    while (digitalRead(Button3) == LOW);
  }
  if (digitalRead(Button4) == LOW) {
    toggleRelay4();
    while (digitalRead(Button4) == LOW);
  }

  // Create a client connection
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        //read char by char HTTP request
        if (readString.length() < 100) {
          //store characters to string
          readString += c;
          //Serial.print(c);
        }

        //if HTTP request has ended
        if (c == '\n') {
          Serial.println(readString); //print to serial monitor for debuging
          homepage();
          //controls the Arduino if you press the buttons
          if (readString.indexOf("?resetcount1") > 0) {
            count1 = 0;
          }
          if (readString.indexOf("?resetcount2") > 0) {
            count2 = 0;
          }
          if (readString.indexOf("?resetcount3") > 0) {
            count3 = 0;
          }
          if (readString.indexOf("?resetcount4") > 0) {
            count4 = 0;
          }
          if (readString.indexOf("?togglerelay1") > 0) {
            toggleRelay1();
          }
          if (readString.indexOf("?togglerelay2") > 0) {
            toggleRelay2();
          }
          if (readString.indexOf("?togglerelay3") > 0) {
            toggleRelay3();
          }
          if (readString.indexOf("?togglerelay4") > 0) {
            toggleRelay4();
          }
        }
      }
    }
  }
  //clearing string for next read
  readString = "";

}

void toggleRelay1() {
  toggle1 = !toggle1;
  digitalWrite(Relay1, toggle1);
  if (toggle1 == HIGH) {
    count1++;
    Relay1Status = on;
  }
  else
    Relay1Status = off;
}

void toggleRelay2() {
  toggle2 = !toggle2;
  digitalWrite(Relay2, toggle2);
  if (toggle2 == HIGH) {
    count2++;
    Relay2Status = on;
  }
  else
    Relay2Status = off;
}

void toggleRelay3() {
  toggle3 = !toggle3;
  digitalWrite(Relay3, toggle3);
  if (toggle3 == HIGH) {
    count3++;
    Relay3Status = on;
  }
  else
    Relay3Status = off;
}

void toggleRelay4() {
  toggle4 = !toggle4;
  digitalWrite(Relay4, toggle4);
  if (toggle4 == HIGH) {
    count4++;
    Relay4Status = on;
  }
  else
    Relay4Status = off;
}

void homepage() {
  client.println("HTTP/1.1 200 OK"); //send new page
  client.println("Content-Type: text/html");
  client.println("Connection: Close");
  client.println();
  client.println("<HTML>");
  client.println("<HEAD>");
  client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
  client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
  client.println("<link rel='stylesheet' type='text/css' href='http://randomnerdtutorials.com/ethernetcss.css' />");
  client.println("<TITLE>Relay Control System</TITLE>");

  client.println("</HEAD>");
  client.println("<BODY>");
  client.println("<H1>Relay Control System</H1>");
  client.println("<hr />");
  client.println("<br />");

  client.println("<H2>Relays Status</H2>");
  client.println("<br />");

  client.println("Relay 1 Status: ");
  client.println(Relay1Status);
  client.println("<br />");

  client.println("Relay 2 Status: ");
  client.println(Relay2Status);
  client.println("<br />");

  client.println("Relay 3 Status: ");
  client.println(Relay3Status);
  client.println("<br /><br />");

  client.println("Relay 4 Status: ");
  client.println(Relay4Status);
  client.println("<br /><br />");

  client.println("Number of times Relay1 has been activated: ");
  client.println(count1);
  client.println("<a href=\"/?resetcount1\"\">Reset Counter</a>");
  client.println("<br /><br /><br />");

  client.println("Number of times Relay2 has been activated: ");
  client.println(count2);
  client.println("<a href=\"/?resetcount2\"\">Reset Counter</a>");
  client.println("<br /><br /><br />");

  client.println("Number of times Relay3 has been activated: ");
  client.println(count3);
  client.println("<a href=\"/?resetcount3\"\">Reset Counter</a>");
  client.println("<br /><br /><br />");

  client.println("Number of times Relay4 has been activated: ");
  client.println(count4);
  client.println("<a href=\"/?resetcount4\"\">Reset Counter</a>");
  client.println("<br /><br /><br />");

  client.println("<a href=\"/?togglerelay1\"\">Toggle Relay1</a>");

  client.println("<a href=\"/?togglerelay2\"\">Toggle Relay2</a>");

  client.println("<a href=\"/?togglerelay3\"\">Toggle Relay3</a>");

  client.println("<a href=\"/?togglerelay4\"\">Toggle Relay4</a>");

  client.println("</BODY>");
  client.println("</HTML>");

  delay(1);
  //stopping client
  client.stop();
}

```

# Answer
Instead of always responding with the `homepage()` for every request you should respond specially to the command requests with a `307` temporary redirect code to make the browser request the index page afresh

```
client.println("HTTP/1.1 307 Temporary Redirect");
client.println("Location: /");
client.println("Connection: Close");
client.println();
client.stop();

```

So the client gets `/?togglerelay3`, which happens, and then gets sent a reply telling it to `make a new request to get /` which it then does to get the new status. The URL in the browser will not have the `?togglerelay3` in it, so refreshing won't cause the command to be run again.

If you want live updating of the page with new count values as they happen you will have to be more cunning. Either use AJAX and JavaScript in the page to fetch new values to display, or periodically refresh the page (with a META Refresh).
> 1 votes

---
Tags: arduino-uno, ethernet, web-server
---


# Question
Title: Webserver on Arduino: How to 307 temporary redirect
I originally asked this question. Regarding a webserver Refresh issue on arduino.

I am totally new to web development and ethernet. The answer from @Majenko is correct, but I do not understand how to implement it. Should I change the `homepage()` function's first line to `HTTP/1.1 307 temporary redirect` and use `META REFRESH`?

Or do the `homepage()` first using `HTTP/1.1 200 OK` and then for all the following requests, use `HTTP/1.1 307 temporary redirect`?

# Answer
You need to make a decision on what to respond with depending on what the request is you have received.

If you receive a "command" URL (which you already check for by looking for certain sub-strings) then you need to respond with the `307` response. If you don't receive a "command" URL (so anything *except* the things you are specifically looking for) then you respond with the homepage.

A slight re-formatting of your decision code to use `else if` instead of just `if` would make it easier:

```
if (c == '\n') {
  Serial.println(readString); //print to serial monitor for debuging
  // homepage(); << This is now moved elsewhere.
  //controls the Arduino if you press the buttons
  if (readString.indexOf("?resetcount1") > 0) {
    count1 = 0;
    redirect();
  } else if (readString.indexOf("?resetcount2") > 0) {
    count2 = 0;
    redirect();
  } else if (readString.indexOf("?resetcount3") > 0) {
    count3 = 0;
    redirect();
  } else if (readString.indexOf("?resetcount4") > 0) {
    count4 = 0;
    redirect();
  } else if (readString.indexOf("?togglerelay1") > 0) {
    toggleRelay1();
    redirect();
  } else if (readString.indexOf("?togglerelay2") > 0) {
    toggleRelay2();
    redirect();
  } else if (readString.indexOf("?togglerelay3") > 0) {
    toggleRelay3();
    redirect();
  } else if (readString.indexOf("?togglerelay4") > 0) {
    toggleRelay4();
    redirect();
  } else { // If none of them match then send the homepage.
    homepage();
  }
}

```

`redirect()` is as simple as:

```
void redirect() {
  client.println("HTTP/1.1 307 Temporary Redirect");
  client.println("Location: /");
  client.println("Connection: Close");
  client.println();
  client.stop();
}

```
> 0 votes

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


# Question
Title: Help understanding SoftwareSerial recv() and PCINT
In the SoftwareSerial library, I see the beginning of recv() as follows

```
void SoftwareSerial::recv()
{

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Preserve the registers that the compiler misses
// (courtesy of Arduino forum user *etracer*)
  asm volatile(
    "push r18 \n\t"
    "push r19 \n\t"
    "push r20 \n\t"
    "push r21 \n\t"
    "push r22 \n\t"
    "push r23 \n\t"
    "push r26 \n\t"
    "push r27 \n\t"
    ::);
#endif

  uint8_t d = 0;

  // If RX line is high, then we don't see any start bit
  // so interrupt is probably not for us
  if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
  {

```

This comment seems to be testing for if the pin change was from low to high, or high to low. If you are using inverse logic - where the line is held high, and start bits are low - then a call to rx\_pin\_read() should return 0.

This doesn't seem correct. In inverse logic the line is held high and a drop indicates a start bit.

Is the SoftwareSerial library ignoring the start bit and relying on some kind of return to zero break between the start bit and any subsequent bits?

It seems like it can't handle start bits followed by high bits since there would be no change in the pin state.

# Answer
> This doesn't seem correct. In inverse logic the line is held high and a drop indicates a start bit.

No, in inverse logic (for a UART) the line is held LOW and a rise indicates a start bit. The diagrams you show in your question show that UART communication normally is HIGH with LOW for a start bit.

> It seems like it can't handle start bits followed by high bits since there would be no change in the pin state.

The PCINT is only used to identify the falling (or rising in the case of inverse logic) edge of the start bit. From then on it samples at pre-defined periods to read each bit. Accurate timing is needed for that, so assembly code is used to give precise delays (see `tunedDelay()`). Once the whole 10-bit packet has been received the interrupt handler finishes and control is returned to the main thread again. The PCINT is then free to look for the next start bit.
> 1 votes

---
Tags: softwareserial
---


title: Can't use enum as function argument

text:
# Question
Title: Can't use enum as function argument
I declared my enum and called it Dir. I wanted to use value of that type in my function Move(). Here's the code:

```
enum Dir
{
  forward = 1,
  backward = 2,
  left = 3,
  right = 4
};

void Move ( Dir direction , int distance )
{
     direction = forward;
}

void setup() {
  // put your setup code here, to run once:

}

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

}

```

Unfortunately i get the following errors:

```
V2.ino:23:13: error: variable or field 'Move' declared void
V2.ino:23:13: error: 'Dir' was not declared in this scope
V2.ino:23:29: error: expected primary-expression before 'int'

```

What's wrong?

# Answer
> 3 votes
The Arduino 1.7.x series from Arduino.org uses the old build system that is severely broken when you try and do anything more complex than simple types.

It adds prototypes to your functions to the top of the program so you don't have to get the order right, but it puts them in completely the wrong place. The result is a C++ file that looks like this:

```
#include <Arduino.h>
void Move ( Dir direction , int distance );
void setup();
void loop();

enum Dir
{
  forward = 1,
  backward = 2,
  left = 3,
  right = 4
};

void Move ( Dir direction , int distance )
{
     direction = forward;
}

void setup() {
  // put your setup code here, to run once:
}

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

```

As you can see the prototype involving `Dir` has been placed before the definition of `Dir`, and so it fails miserably.

There are some hacks you can do to force it to place the prototypes after your definition, but I can't recall what they are off hand.

The simple answer is to ditch Arduino 1.7.10 and switch to Arduino 1.6.10 from Arduino.cc instead. This uses the Arduino Builder system which does things much better, including placing the prototypes in the right place.

Despite the numbering 1.7.10 is not a newer version than 1.6.10 - it is an older version renumbered. It's all part of the schism between the two halves of Arduino.

Even better is to ditch the awful Arduino IDE entirely and use one of the many far better IDEs that exist.

# Answer
> 4 votes
I did not experience the problem because I usually use a Makefile instead of the Arduino IDE. I now tried with the IDE version 1.0.5 and I had the same problem as you. The fix is to explicitly declare the function before defining it:

```
void Move(Dir direction, int distance);
void Move(Dir direction, int distance)
{
     direction = forward;
}

```

# Answer
> 2 votes
As Majenko points out, this seems to be a problem with the parsing of the preprocessor.

You have two options:

- Use Edgar Bonets solution and declare the function before defining it
- Create a separate header file for your enum in a new tab and import it with #include "\[myEnumsHeaderFilename\].h"

```
#include "myEnums.h"

void Move(Dir direction, int distance)
{
   direction = forward;
}

void setup() {}

void loop() {}

```

# Answer
> 0 votes
You have to define a new enum type:

```
typedef enum
{
  forward = 1,
  backward = 2,
  left = 3,
  right = 4
} Dir;

void Move ( Dir direction , int distance )
{
     direction = forward;
}

```

without `typedef` your Dir is just static enum variable, it can't be used to define other vars.

---
Tags: programming
---


# Question
Title: Decoding IR codes with IR sensor rather than IR receiver module
I'm looking for a library to decode RAW IR signals from an IR sensor (looks like a black LED, two legged) rather than an IR module (3 legged, rated for a particular frequency - such as 38kHz).

Is there a library that supports IR sensors?

A picture of the two possibilities can be seen here

EDIT: This isn't a duplicate of my previous post, it is related to the same project however. On my previous question I asked what could be the cause. I've found out what it is - frequency. My previous IR detector was an IR module and not an IR sensor. The difference could be seen here

# Answer
I had a similar project a few months back and spotted this Arduino Library:

https://github.com/z3t0/Arduino-IRremote

and it is invaluable.

For your instance, you want the RAW Data which you can achieve using an Example included in the Library named: IRrecvDemo.

The wiring is easy and straight forward

> An IR detector/demodulator must be connected to the input RECV\_PIN.

Which is 11 by default but you can definitely change it :3

and the other two Legs of the IR detector/demodulator go to the power source.
> 1 votes

# Answer
IRremote (already recommended) - but to save you some time, use the IRRecvDump example to grab the raw codes you need for `sendRaw()`. They need to be averaged out across 10-20 reads. I log the output to a file, and use a perl script to do it for me, since it is painful to type this into a calculator a million times. The resistor you connect to the sensor affects its sensitivity - I used 330ohm, and have ~10 metres range from a 3V3 remote inside, 4-5 metres outside in sunlight. I would give you the script, but it's on my desktop. Let me know if you need it - or just use python, which is so popular nowadays (indent-or-fail... feh. what about people who don't like setting up the tab-space continuum, and don't have fancy editors...mumblemumble) Edit: my raw codes absolutely needed to be averaged out, or they were useless. Any negative values in the array can just be made positive, don't fret.
> 1 votes

# Answer
> I'm looking for a library to decode RAW IR signals from an IR sensor

AGirs includes a comprehensive library designed to work with raw IR signals. I've used GirsLite in an Arduino and IrScrutinzer in Windows to do advance IR protocol snooping.
> 0 votes

---
Tags: library, ir
---


# Question
Title: Connect to Arduino 2560 using a RS232 Connection
Is it possible to connect to an Arduino 2560 using a RS232 (DB9) connection rather than the regular connection using USB cable?

I am thinking of this connection scheme:

```
PC -> USB cable -> USB to RS232 Multiplexer -> DB9 Cable -> Adapter board -> Arduino 2560

```

# Answer
> 2 votes
Yes, perfectly possible. You need an RS-232 interface chip - the most common and well-known of these is the MAX232. You can get them as breakouts on eBay.

That interfaces between the DB9 and pins 0/1 (or other UART comms pins) on the Arduino.

If you are wanting to program the board through it you will also need to connect (after converting the voltage through the MAX232) the DTR line to RESET through a 100nF capacitor.

... Exactly like you would with a breadboard Arduino.

---
Tags: arduino-mega, usb, rs232
---


title: Water valve for food

text:
# Question
Title: Water valve for food
I am working on a project, where i need to control the flow of a liquid made from food.

For example: making chicken curry, I will separate all the liquid from the meat, and run that tough a pipe, where this control pipe is on.

But I have been unable to find a subtle valve for this, as the liquid on all of them will flow tough the mechanics of the valve, and this would not be optimal as it would make it impossible to clean, and it would diffidently get stuck.

Can one of you suggest a valve that would work for this case?

# Answer
I would suggest, instead of a valve, a Peristaltic Pump.

In short, it comprises a set of rollers that squeeze a flexible tube and push the fluid along. It has good advantages for food use:

* Very easy to clean - only the inside of the tube needs cleaning
* Pumped fluid is not in physical contact with the pump mechanism so can't be contaminated.

They are used in many sterile environments - medical, industrial, etc., because they are so easy to keep clean and have no way of contaminating the pumped fluid. They are also good with viscous (sticky, gloopy) fluids like soups and sauces.

They can also deliver precisely measured amounts very easily.
> 2 votes

---
Tags: hardware
---


title: UVB sensing with Arduino

text:
# Question
Title: UVB sensing with Arduino
As part of the research I am involved with, the detection (not imaging) of UV (ultraviolet) sources, either emitters or reflectors is an important factor.

I am aware of the SparkFun UV Sensor Breakout - ML8511 component, which, according to the product specifications, has a decent broadband response across the UVA and UVB, with little amount of visible light.

Is there an Arduino component that only detects the UVB waveband (280nm to 320nm)?

# Answer
The SparkFun board you mentioned should detect UVB and UVA, but I guess, from your question, that you want one that cannot detect UVA.

Basically any device that has an I2C interface *should* work with an Arduino as long as you know how to interface with the device in the code.

If your intention is professional research, than a demo device such as the SparkFun may not fit your needs anyway as it will not be particularly accurate and is mainly intended as a little board to play about with on your Arduino and say "Hey, look, there's UV light there!"

The answer to your question is that the best place to look is above the consumer range, at some higher-end UV sensors that are not generally suitable for the little Arduino demos due to price, but may give you much more accurate readings and only sense the UVB waveband.
> 1 votes

---
Tags: sensors, components
---


title: help with arduino programming

text:
# Question
Title: help with arduino programming
my project involves: 1 ultrasonic sensor. 1 servo motor. 3 leds. when a person comes in range of ultrasonic sensor (7 to 20),servo turns by 150 degree. then ultrasonic sensor check again if the person is in range, if yes then led1 turns on for 10sec n turns off, still if the person in in range then led2 turns on for 10sec and turns off, still if the person is in range then led3 turns on for 10sec and this keep on repeating for the leds(led1, led2, led3 but servo is still in 150) once detected and the person is not detected the leds should not glow and servo should return to 0

code:

```
if ((distance1>7)&&(distance1 <= 20))
 {
  myservo1.write(150);
  delay(1000);
 }
 {
  if ((distance2>7)&&(distance2 <= 20))
   {
   digitalWrite(led1,HIGH);
   delay(1000);
   digitalWrite(led1,LOW);
   }
  if ((distance1>7)&&(distance1 <= 20))
   {
   digitalWrite(led2,HIGH);
   delay(1000);
   digitalWrite(led2,LOW);
   }
   if ((distance1>7)&&(distance1 <= 20))
   {
   digitalWrite(led3,HIGH);
   delay(1000);
   digitalWrite(led3,LOW);
   }
else
{
 myservo1.write(0);
  }

```

but this code does not work the way i want. it blink the leds even when there is no person in range. need help in programing so that the leds blink only when ultrasonic detects the person in range and stops when person is not detected. thank u in advance

# Answer
Your indenting doesn't match your code.

Right after the very first `if` (without an `else`), you have a new open brace (`{`). This looks wrong:

```
if ((distance1>7)&&(distance1 <= 20))
 {
  myservo1.write(150);
  delay(1000);
 }
 { // <<<< What is this?

```

The very very final `else` matches the very very final `if` \- certainly not the first `if`!

Also, what is the difference between `distance1` and `distance2`? You only have one ultrasonic sensor - there is only one `distance`!

### EDIT:

I think what you need to do is use `loop()` more effectively. At the moment, you're pausing in the middle of your code, rather than letting the rest of the code work and using `millis()`. That function returns the number of milliseconds since the program started - which you can use for your problem (with a little mathematics):

### EDIT 2:

I've added a little extra code to play different tunes depending on the current state. It uses the library at http://www.rhydolabz.com/other-widgets-c-205\_124/mini-mp3-player-module-p-2159.html

```
static unsigned lastMilli = 0;
static byte lastLED = 0;
static const byte LEDs[] = { led1, led2, led3 };

distance1 = // Whatever you call to get the distance...
if (distance1>7) && (distance1<=20)) { // Too close?
   if (lastMilli==0) {       // Is this new???
       lastMilli = millis(); // Yes! Record that...
       mysero.write(150);    // ...and set servo.
   } // if
   unsigned delay = millis() - lastMilli; // Get how long it's been
   byte which = delay / 10000 % 3;        // Which LED / tune?
   byte LED = LEDs[which];                // Which LED?
   if (LED != lastLED) {                  // Has LED changed?
       if (lastLED!=0) {
           digitalWrite(lastLED, LOW);    // Yes! Stop that one
       } // if
       mp3_single_loop(true);             // Play forever!
       mp3_single_play(which+1);          // Play "mp3/000#.mp3"
       lastLED = LED;
       digitalWrite(LED, HIGH);           // And start the new one
   } // if
} // if
else if (lastMillis!=0) { // They're gone!
    digitalWrite(lastLED, LOW); // No LED
    myservo.write(0);           // No servo
    lastMilli = 0;              // So start again
    lastLED = 0;
    mp3_stop();
} // else

```
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Programming arduino using avrdude from command prompt
Out of curiosity, I am trying to upload a simple hex file to Arduino UNO using avrdude from windows command prompt.

As per this forum, I tried to implement it. But got stuck at

> avrdude: ser\_open(): can't open device "COM41": The system cannot find the file specified.

This command was directly imported from Arduino IDE verbose, and also it works fine when uploaded with Arduino IDE. I checked both the device and syntax are correct unless I would not be able to generate the hex file by Arduino compiler.

P.S. I have installed Winavr separately although it was pre-installed by Arduino itself.

Here is a snapshot of the error

What could be the possible reason for it to fail? Please notify, if anything is missing.

# Answer
After a lot of experiment, I finally made it. I got to know from some forum that when COM PORT is greater than 10, you have to put a '.' after COM PORT setting e.g. -P.COM41.

But, unfortunately that did not work. Then I changed the COM PORT to under 10 in device manager -\> Properties -\> COM Port Setting -\> Advanced Setting; e.g. COM6. Then it worked. At the time of flash just I have to press the RST button for once. And now bingo!!

Still, I will try to find out why it didn't work with higher COM Port.
> 2 votes

# Answer
```
can't open device "COM41": The system cannot find the file specified.

```

This means there is no device at `COM41`. This may be due to 2 reasons:

1. You may not have connected your arduino. If this is the case then you please connect the arduino and retry
2. Your arduino might be on a different COM port. If this is the case, then, go to device manager and check your arduino's COM port and replace `COM41` with that and retry.
> 1 votes

---
Tags: arduino-uno, serial, uploading, avrdude
---


title: SIM900 TCP Connection issue

text:
# Question
Title: SIM900 TCP Connection issue
I am having a strange issue where if I try and create a TCP connection to my service, it doesn't work. But any other website, such as google, works fine. The serial monitor output is also slightly different, but I cannot see any difference in the code. I am using this module for communications.

This is the method that I am using:

```
void SendPost()
{
  Serial1.println("AT+CGATT?");
  delay(1000);
  ShowSerialData();

  Serial1.println("AT+CSTT=\"everywhere\"");//start task and setting the APN,
  delay(1000);
  ShowSerialData();

  Serial1.println("AT+CIICR");//bring up wireless connection
  delay(3000);
  ShowSerialData();

  Serial1.println("AT+CIFSR");//get local IP adress
  delay(2000);
  ShowSerialData();

  Serial1.println("AT+CIPSPRT=0");
  delay(3000);
  ShowSerialData();

  Serial1.println("AT+CIPSTART=\"tcp\",\"www.google.com/\",\"80\"");//start up the connection //https://rocky-garden-56471.herokuapp.com/breadcrum/lifecycle/register
  delay(5000);
  ShowSerialData();

  Serial1.println("AT+CIPSEND");//begin send data to remote server
  delay(4000);
  ShowSerialData();

  Serial1.println("{\"device_info\":\"breadcrum-prototype-a\"}");
  delay(500);
  ShowSerialData();

  Serial1.println((char)26);//sending
  delay(5000);//waitting for reply, important! the time is base on the condition of internet

  Serial1.println();
  ShowSerialData();

  Serial1.println("AT+CIPCLOSE");//close the connection
  delay(100);
  ShowSerialData();
}

```

Using 'www.google.com' I get an OK upon tcp connection (with an expected error on the data as I try to POST):

```
Setup CompleteAT+CGATT?

+CGATT: 1

OK
AT+CSTT="everywhere"

OK
AT+CIICR

OK
AT+CIFSR

100.66.4.95
AT+CIPSPRT=0

OK
AT+CIPSTART="tcp","www.google.com/","80"

OK

STATE: IP STAAT+CIPSEND

ERROR
{"device_info":"breadcrum-prototype-a"}

AT+CIPCLOSE

ERROR

```

But using the address I actually want to post data to (https://rocky-garden-56471.herokuapp.com/breadcrum/lifecycle/register), it cannot connect and I get this:

```
Setup CompleteAT+CGATT?

+CGATT: 1

OK
AT+CSTT="everywhere"

OK
AT+CIICR

OK
AT+CIFSR

100.66.4.95
AT+CIPSPRT=0

OK
AT+CIPSTART="tcp","https://rocky-garden-56471.herokuapp.com/breAT+CIPSEND

ERROR
{"device_info":"breadcrum-prototype-a"}

AT+CIPCLOSE

ERROR

```

This errors on connection, and you can also see that the full address isn't printed out for some reason. Does anyone have any idea what could be causing this issue?

Thanks :)

EDIT: @Majenko, my previous version did what I believe you are describing. The issue being I got an error that I struggled to resolve so attempted this version. The previous version is:

```
void SubmitHttpRequest()
{
  Serial1.println("AT+CSQ");
  delay(100);
  ShowSerialData();

  Serial1.println("AT+CGATT?");
  delay(100);
  ShowSerialData();

  Serial1.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");//setting the SAPBR, the connection type is using gprs
  delay(1000);
  ShowSerialData();

  Serial1.println("AT+SAPBR=3,1,\"APN\",\"everywhere\"");//setting the APN, the second need you fill in your local apn server
  delay(4000);
  ShowSerialData();

 //Enable GPRS
  Serial1.println("AT+SAPBR=1,1");
  delay(2000);
  ShowSerialData();

  //Query if connection is setup correctly, return IP address if it is
  Serial1.println("AT+SAPBR=2,1");
  delay(2000);
  ShowSerialData();

  Serial1.println("AT+HTTPINIT"); //init the HTTP request
  delay(2000);
  ShowSerialData();

//Set up bearer profile identifier (NEW PART)
  Serial1.println("AT+HTTPPARA=\"CID\",1");
  delay(2000);
  ShowSerialData();

  Serial1.println("AT+HTTPPARA=\"URL\",\"https://rocky-garden-56471.herokuapp.com/breadcrum/lifecycle/register\"");// setting the httppara, the second parameter is the website you want to access
  delay(3000);
  ShowSerialData();

  Serial1.println("AT+HTTPPARA=\"CONTENT\",\"application/json\"");
  delay(3000);
  ShowSerialData();

  Serial1.println("AT+HTTPDATA=1000,10000");
  delay(3000);
  ShowSerialData();

  Serial1.println("{\"device_info\":\"breadcrum-prototype-a\"}");
  delay(3000);
  ShowSerialData();

  Serial1.println("AT+HTTPACTION=1");//submit the request //0:READ 1:POST 2:HEAD
  delay(10000);//the delay is very important, the delay time is base on the return from the website, if the return datas are very large, the time required longer.
  ShowSerialData();

  Serial1.println("AT+HTTPREAD");// read the data from the website you access
  delay(1000);
  ShowSerialData();

  Serial1.println("");
  delay(100);
}

```

But the results I got from this was another error when attempting to post:

```
Setup CompleteAT+CSQ

+CSQ: 18,0

OK
AT+CGATT?

+CGATT: 1

OK
AT+SAPBR=3,1,"CONTYPE","GPRS"

OK
AT+SAPBR=3,1,"APN","everywhere"

OK
AT+SAPBR=1,1

OK
AT+SAPBR=2,1

+SAPBR: 1,1,"19.177.18.205"

OK
AT+HTTPINIT

OK
AT+HTTPPARA="CID",1

OK
AT+HTTPPARA="URL","https://rocky-garden-56471.herokuapp.com/breAT+HTTPPARA="CONTENT","application/json"

OK
AT+HTTPDATA=1000,10000

DOWNLOAD

ERROR
AT+HTTPREAD

OK

```

EDIT 2: Following HTTPS commands:

```
 AT+CSQ

+CSQ: 18,0

OK
AT+CGATT?

+CGATT: 1

OK
AT+SAPBR=3,1,"CONTYPE","GPRS"

OK
AT+SAPBR=3,1,"APN","everywhere"

OK
AT+SAPBR=1,1

ERROR
AT+SAPBR=2,1

+SAPBR: 1,1,"31.94.203.234"

OK
AT+HTTPSSL=1

OK
AT+HTTPINIT

OK
AT+HTTPPARA="CID",1

OK
AT+HTTPPARA="URL","https://rocky-garden-56471.herokuapp.com/breAT+HTTPPARA="CONTENT","application/json"

OK
AT+HTTPDATA=100,10000

DOWNLOAD

ERROR
AT+HTTPREAD

OK
AT+HTTPTERM

OK

```

# Answer
> 0 votes
There is so many things wrong that I don't know where to start.

1. You are trying to use a URL in place of a hostname.
2. You are trying to connect to an HTTPS service which runs on port 443 not on port 80
3. HTTPS is encrypted. You are opening a plain TCP socket to an encrypted service.

Your whole methodology is wrong. You need to use the SIM900 HTTPS AT Command Set to get the SIM900 to perform an HTTPS request on your behalf rather than opening a socket and sending / receiving data.

---
Tags: arduino-mega, communication, tcpip
---


title: Sending data via bluetooth

text:
# Question
Title: Sending data via bluetooth
I am trying to both send and receive data using bluetooth module.

Receiving data works fine with this code:

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

void loop() {
    if (Serial1.available()) {
        Serial.println(Serial1.read());
    }

    delay(20);
}

```

But I cannot send any data. This is what I am doing:

```
void loop() {
    if (Serial1.available()) {
       Serial.println(Serial1.read());
    }

    delay(20);

    if (digitalRead(bluetoothInput) == HIGH) {
        Serial1.write("2");
        // only "send" prints. Nothing in android terminal
        Serial.println("send!");
        delay(1000);
    }

    delay(20);
}

```

What am I doing wrong?

I am using Arduino Leonardo and Bluetooth terminal app on Android device.

# Answer
> 2 votes
I've found the problem

It should be:

```
Serial1.println("2");

```

instead of:

```
Serial1.write("2");

```

---
Tags: serial, bluetooth, arduino-leonardo, android
---


title: A lot of "undefined reference" errors

text:
# Question
Title: A lot of "undefined reference" errors
I'm trying to create a program for my robot, but something is not right. Here's the code:

```
#include <SPI.h>
#include <Tone.h>
#include <Wire.h>   // standardowa biblioteka Arduino
#include <LiquidCrystal_I2C.h> // dolaczenie pobranej biblioteki I2C dla LCD

//Enums:
enum Dir
{
  forward = 1,
  backward = 2,
  left = 3,
  right = 4
};

enum State
{
    movingForward = 1,
    movingBack = 2,
    turningLeft = 3,
    turningRight = 4,
    doingNothing = 5,
    readyToMove = 6 //Potrzebne?
};

enum SpeedState
{
  slowingDown = 1,
  maxSpeed = 2,
  accelerating = 3,
  notMoving = 4
};

//Classes:
LiquidCrystal_I2C lcd1(0x27, 20, 4);

//Base class for devices
class Device
{
    public:
        virtual void Init() = 0;
};

//STEPPER::
class StepMotor: public Device
{
    public:
        int motorPin;
        int dirPin;
        int sleepPin;

        void Init ( void )
        {
            pinMode(motorPin, OUTPUT);
            pinMode(dirPin, OUTPUT);
            pinMode(sleepPin, OUTPUT);

            toneObject.begin(motorPin);
        }

        void SetSpeed ( int speed )
        {
          toneObject.play(speed);
        }

    private:
      Tone toneObject;
};

//VARIABLES:
int a = 1; //przyspieszenie (przyrost prędkości i jej ubytek przy hamowaniu
int s_accelerating = 1; //droga przyspieszania [mm]
int s_braking = 1;  //droga hamowania [mm]

class Robot
{
    public:
        static float x;
        static float y;
        static float t;
        static State state;
        static SpeedState speedState;
        static int currentSpeed;
};

class MoveOrder
{
  public:
    static Dir direction;
    static int distance;
    static int speed;
    static int distanceRemaining;
    static int distanceMade;
};

//FUNCTIONS:
void SetInterrupt ( void )
{
    noInterrupts();           // disable all interrupts
    TCCR5A = 0;
    TCCR5B = 0;
    TCNT5  = 0;
    OCR5A = 310;            // compare match register 16MHz/256/2Hz   400 okolo 6.4ms  380-6.1ms 300-4.9ms
    TCCR5B |= (1 << WGM12);   // CTC mode
    TCCR5B |= (1 << CS12);    // 256 prescaler
    TIMSK5 |= (1 << OCIE1A);  // enable timer compare interrupt
    interrupts();             // enable all interrupts
}

void SetSpeed ( int speedValue )
{
   //currently empty
}

void setup()
{
    SetInterrupt();
}

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

}

ISR(TIMER5_COMPA_vect)
{
    if (Robot::state != doingNothing)
    {
        if (Robot::state == movingForward || Robot::state == movingBack )
        {
          if (MoveOrder::distanceMade < s_accelerating)
            {

                Robot::currentSpeed += a;

                SetSpeed(4);

            }
        }
    }
}

```

Compilation returns this:

```
Arduino:1.6.10 (Windows 10), Płytka:"Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

C:\Users\Marcin\AppData\Local\Temp\ccU9OfJk.ltrans0.ltrans.o: In function `__vector_21':

ccU9OfJk.ltrans0.o:(.text+0x812): undefined reference to `Robot::state'

ccU9OfJk.ltrans0.o:(.text+0x816): undefined reference to `Robot::state'

C:\Users\Marcin\AppData\Local\Temp\ccU9OfJk.ltrans0.ltrans.o: In function `__vector_47':

ccU9OfJk.ltrans0.o:(.text+0x820): undefined reference to `MoveOrder::distanceMade'

ccU9OfJk.ltrans0.o:(.text+0x824): undefined reference to `MoveOrder::distanceMade'

ccU9OfJk.ltrans0.o:(.text+0x82e): undefined reference to `Robot::currentSpeed'

ccU9OfJk.ltrans0.o:(.text+0x832): undefined reference to `Robot::currentSpeed'

ccU9OfJk.ltrans0.o:(.text+0x838): undefined reference to `Robot::currentSpeed'

ccU9OfJk.ltrans0.o:(.text+0x83c): undefined reference to `Robot::currentSpeed'

collect2.exe: error: ld returned 1 exit status

exit status 1

```

I noticed that when I comment these lines:

```
        Robot::currentSpeed += a;

        SetSpeed(4);

```

errors are gone. Why?

# Answer
Because you have only *declared* the class static variables; you never *defined* them. For the `Robot` class, you must have:

```
class Robot
{
    public:
         ...
};

float      Robot::x;
float      Robot::y;
float      Robot::t;
State      Robot::state = doingNothing;
SpeedState Robot::speedState = notMoving;
int        Robot::currentSpeed;

void setup()
{

```

Ditto for other classes. (Dangit, Mikael! :) )
> 0 votes

---
Tags: interrupt
---


title: code wont upload to arduino starter kit

text:
# Question
Title: code wont upload to arduino starter kit
My operating system : OS X EL CAPITAN

Please help I was trying to do project 05 Mood cue of the arduino starter kit. I completed setting up my board and writing the code and when I tried to upload I got this error message:

```
Arduino: 1.7.10 (Mac OS X), Board: "Arduino Uno"

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/tty.usbmodem1411": Device not         configured
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

```

Can someone please help me?

# Answer
> -1 votes
Thank you Harry i managed to fix it by downloading CH341SER\_MAC.zip just in case someone has the same problem wch.cn/downfile/178

---
Tags: arduino-uno, uploading, mac-os
---


# Question
Title: How to convert Arduino GSR values to microsiemens?
In my project Arduino provides value range between 0-1024. I need to convert this serial value to a standard µSiemens value to measure emotional stress.

Can anybody point me to an answer that would give an appropriate equation for the conversion?

# Answer
A Siemens (aka a Mho) is a unit of conductance, the inverse of resistance.

You have a measure of the voltage (A/D value) between the pads so you can find voltage. You'll also need to know the current between the pads. Convert your A/D reading into voltage and use that and the current to find resistance (using Ohm's law), and the reciprocal of the resistance is in Siemens. 1 Siemens == 1,000,000 uSiemens.

https://en.wikipedia.org/wiki/Siemens\_(unit)
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: build simple IR sensor with 220 ohm and 1000 ohm resistors
I am brand new to the arduino board and I am trying to build a simple IR proximity sensor. I bought a handful of emitters and detectors from amazon here:

https://www.amazon.com/gp/product/B01HGIQ8NG/ref=oh\_aui\_detailpage\_o02\_s00?ie=UTF8&psc=1

I am about to pull my hair out and shoot my board with a 12 gauge shot gun if I don't figure this out soon. Can someone point me to a good SIMPLE tutorial that uses ONE emitter and ONE detector and ONE LED. All i can find are a bunch of complex circuits with multiple sets of sensors or a buzzer or whatever else and anything that is as simple as that has no information on schematic or code. Can someone please post a tutorial link?

# Answer
You could always start out attempting a simple IR detector circuit.

Google Arduino IR detector brings up several tutorials, such as this one from the Instructables website

You would have to change the buzzer in tutorial for an LED and resistor in series.
> 1 votes

---
Tags: arduino-uno, sensors, led, ir, proximity
---


title: How to increase voltage of Arduino?

text:
# Question
Title: How to increase voltage of Arduino?
Hey I'm very new to Arduino. I don't have very much knowledge in electrical engineering either.

My project: an EL wire working on Arduino. Since the Arduino can only support 5V and the wire needs 120V, how can I make sure that it works? (I assume the voltage provided by the Arduino is not high enough for the EL wire to operate.)

# Answer
> 2 votes
There are two ways of tackling this. You can either switch the low-voltage DC power to the EL wire inverter (which is safe and easy) or you can switch the high voltage AC power out of the inverter (which is harder, more dangerous, but does allow you to route the power to different EL wires for animation).

The former can be arranged in just the same way as switching any heavy load from an Arduino - with an N-channel MOSFET as a low-sided switch, or a combination of N- and P-channel MOSFETs as a high-side switch. You could add further isolation with a relay should you wish. BJTs could be used instead of MOSFETs but MOSFETs are better at switching higher currents from low current sources.

For switching the high-voltage side you will need a TRIAC circuit. While it is possible to switch a TRIAC direct from the Arduino it is preferred to opt-isolate the system from the Arduino both for safety and ease of switching at higher voltages.

The most common opto-isolator to use is the MOC3041 Opto-Isolated Triac. This is used to switch the gate of a higher voltage / power TRIAC to switch the load.

In that circuit the "220V" comes from the EL inverter, and the LOAD is the EL wire itself. Each EL wire you want to switch would use a copy of that circuit, but can (power permitting) use the same inverter as the source.

# Answer
> 0 votes
In this case, you can use relays. You can give your supply voltage (120v as you said) to EL via relays. And you can switch ON and switch OFF your EL by controlling relays with Arduino.

---
Tags: arduino-uno, voltage-level
---


# Question
Title: how to find find out capacitance using time constant?
i'm trying to find out the capacitance value using the time constant of the RC ciruit. so i followed the technique on the below link.

http://www.gammon.com.au/forum/?id=12075

Now, it's working fine.. but still i need wider range so i want to know the full core logic of that program like how the capacitance formula has been derived out in those program?

thanks in advance...

# Answer
> 3 votes
The key concept is this line:

> ... we find the point where the voltage reaches 63.2% ...

The time constant τ is how long it takes for a capacitor to charge up to 63.2% of the supply voltage. That is governed by both the capacitance (C) and the resistance (R). τ=RC. That is one of the basic formulae you should know as an Electronic Engineer.

If you know R (which you do because you chose it at 10KΩ) and you know τ (which you do because you measured it) then you can calculate C (τ/R).

Since τ, C and R are tied together like that it is possible to change the balance of C and R and keep τ the same. For instance, a 10KΩ resistor and a 47nF capacitor would give the same τ as a 1KΩ resistor and a 470nF capacitor. Also the same τ as a 100kΩ resistor and a 4.7nF capacitor.

You can easily change the range without having to change your time measurement system by changing the resistor to give a different scale.

---
Tags: arduino-uno
---


title: Identifying Bootloader ttyACM# device

text:
# Question
Title: Identifying Bootloader ttyACM# device
I'm using a modified version of Arduino Zero Bootloader. I am trying to write software to automatically detect which USB device the bootloader is currently running on in order to execute bossac.

I have noticed a few unique characteristics when using "lsusb -v". Things like "bDeviceClass" is always 2. and "bDeviceSubClass" is always 0; However, I do not feel confident in using these traits to identify the bootloader. Is there any clear indication of bootloader so I can find the correct ttyACM#?

# Answer
> 1 votes
The only things you have at your disposal are what is in `lsusb -v`. Using those you can craft a `udev` rule to create a symlink to a unique device name. I do that with all my boards so that they all get a unique name.

Here is one of my rules:

```
ATTRS{idVendor}=="2341", ATTRS{idProduct}=="0042",
  ATTRS{serial}=="95336333635351F091B1", KERNEL=="ttyACM*",
  MODE="0660", GROUP="plugdev", SYMLINK+="board/arduino/mega2560"

```

That links `/dev/board/arduino/mega2560` to whatever `/dev/ttyACM*` node got created when it was plugged in. That is in `/etc/udev/rules.d/50-boards.rules`

More on udev here: http://playground.arduino.cc/Linux/Udev

A useful command is `udevadm info -a -n /dev/ttyACM0` which lists all the attributes for that device which you can then use in the `udev` rule.

---
Tags: bootloader
---


# Question
Title: most effective ( progsize/speed ) SD card usage
I am making a project with several modules and libraries involved. I just tested the SD lib example, and got a binary at ~14KB - way too much. I'd like the SD bits to go below 8KB, since it's just for logging from an NFC and RTC module. I notice some 'stabs' debug bits in my Makefile, and wonder if I could do something with that. Besides that, perhaps the experts here can recommend a smaller library for my SD bits, so I won't exceed my ~27KB flash capacity. I am using the SD example for creating/deleting files. Ask me to clarify if needed.

# Answer
> 2 votes
For AVR + SDCard you should check FatFs from Chang. It is widely used and proven C library. You can tweak the configuration file to get minimal size (8K shall be easy). Check wrapper library for Arduino here (6K with default options).

There is also even smaller version called Petit FAT (2-4K) but it doesn't support file delete feature.

If you would like to get smallest possible code, there is option to use Atmel Studio for programming Arduino boards, but you will loose the convenience of Arduino libraries (re-implement the libraries or find AVR versions of them, work with registers directly etc).

---
Tags: arduino-nano, library, sd-card, core-libraries
---


title: How to code for cascading multiplexers?

text:
# Question
Title: How to code for cascading multiplexers?
I hope I can get some help on how to get this to work.

I have multiple Sensors (32 of these) which values I want to read. I am using a master multiplexer **HC4051** connected to 4 slave multiplexers, this is my wiring: \[here\]\[1\]

I tested it using one single multiplexer and it works as intended, but when adding the slave I cannot getting it to work, I am not sure how to code for it.

When using this code:

```
// 74XX4051 ADDRESS PINS :
#define  M_S0 2
#define  M_S1 3
#define  M_S2 4

#define  S_S0 7
#define  S_S1 6
#define  S_S2 5

// 74XX4051 ANALOG PIN :
#define  Z 0

void setup() {
    // CONFIGURE ADDRESS PINS
    pinMode(M_S0, OUTPUT);
    pinMode(M_S1, OUTPUT);
    pinMode(M_S2, OUTPUT);

    pinMode(S_S0, OUTPUT);
    pinMode(S_S1, OUTPUT);
    pinMode(S_S2, OUTPUT);

    // CONFIGURE SERIAL
    Serial.begin(57600);
}

void loop() {
    int value;

    // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER
    for ( byte count = 0; count < 4 ; count++ ) {
         // SET THE ADDRESS
         digitalWrite(M_S0, bitRead(count, 0) );
         digitalWrite(M_S1, bitRead(count, 1) );
         digitalWrite(M_S2, bitRead(count, 2) );

         // LOOP THROUGH ALL THE ADDRESSES OF THE SLAVES
         for ( byte count_1 = 0; count_1 < 32 ; count_1++ ) {
             digitalWrite(S_S0, bitRead(count_1, 0) );
             digitalWrite(S_S1, bitRead(count_1, 1) );
             digitalWrite(S_S2, bitRead(count_1, 2) );

             // READ THE ANALOG VALUE
             value = (bitRead(count_1, 2), bitRead(count_1, 1), bitRead(count_1, 0));
         }

         // READ THE ANALOG FOR THE MASTER ADRESSE
         value = analogRead(Z);

         // SERIAL OUTPUT
         // print : ### value
         Serial.print(bitRead(count, 2));
         Serial.print(bitRead(count, 1));
         Serial.print(bitRead(count, 0));
         Serial.print(' ');
         Serial.println(value);

         delay(100);
     }
}

```

I am only getting random readings really (the reading LED for the moisture sensor does not switch on when the reading is done).

What I am doing wrong? Any help is appreciated.

**UPDATE:**

i updated my code as follows :

```
// Master moisture sensor pins
#define  M_S0 7
#define  M_S1 8
#define  M_S2 9
// Slave moisture sensor pins
#define  S_S0 4
#define  S_S1 5
#define  S_S2 6

// PIN from the transistor to power the sensors only when doing a reading
int sensorVCC = 13;

//  ANALOG PIN :
#define  Z 0

void setup() {
    Serial.begin(9600);
    // CONFIGURE ADDRESS PINS
    pinMode(M_S0, OUTPUT);
    pinMode(M_S1, OUTPUT);
    pinMode(M_S2, OUTPUT);

    pinMode(S_S0, OUTPUT);
    pinMode(S_S1, OUTPUT);
    pinMode(S_S2, OUTPUT);
    pinMode(sensorVCC, OUTPUT);

    digitalWrite(sensorVCC, LOW);
}

void loop() {

    // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER
    for (int i = 0; i < 32; i++) {
    digitalWrite(sensorVCC, HIGH);
    delay(100); //make sure the sensor is powere

    digitalWrite(M_S2, i & 0b100000);
    digitalWrite(M_S1, i & 0b010000);
    digitalWrite(M_S0, i & 0b001000);
    digitalWrite(S_S2, i & 0b000100);
    digitalWrite(S_S1, i & 0b000010);
    digitalWrite(S_S0, i & 0b000001);

    delay(1);

    int humidityRaw = analogRead(Z); // 1023 to 0 ===> 0 to 100%
    int humidityReal = map(humidityRaw, 975, 523, 0, 100);
    digitalWrite(sensorVCC, LOW);

    Serial.print("Input ");
    Serial.print(i);
    Serial.print(": ");
    Serial.print(humidityReal);
    Serial.println(" % ");
    delay(1000);
}
}

```

and this is my output :

```
    Input 0: 100 %
    Input 1: 0 %
    Input 2: 100 %
    Input 3: 0 %
    .
    .
    .
    Input 0: 0 %
    Input 1: 100 %
    Input 2: 0 %
    Input 3: 0 %
    .
    .
    .
    Input 0: 100 %
    Input 1: 0 %
    Input 2: 0 %
    Input 3: 0 %
    .
    .
    .

```

ONLY channel 0 is hooked !! .... it seems that it reads with different delays. changing the delay gives me different sequence. what is wrong ?

# Answer
It becomes much easier if you start thinking in binary.

If you have an 8 bit multiplexer connected to four 8 bit multiplexers that gives you 32 inputs. Four of the inputs on the "master" multiplexer are unused and can be ignored.

You have 32 inputs. That's inputs numbered 0 to 31. In binary that equates to, in full,

```
0 = 000000   8 = 001000  16 = 010000  24 = 011000
1 = 000001   9 = 001001  17 = 010001  25 = 011001
2 = 000010  10 = 001010  18 = 010010  26 = 011010
3 = 000011  11 = 001011  19 = 010011  27 = 011011
4 = 000100  12 = 001100  20 = 010100  28 = 011100
5 = 000101  13 = 001101  21 = 010101  29 = 011101
6 = 000110  14 = 001110  22 = 010110  30 = 011110
7 = 000111  15 = 001111  23 = 010111  31 = 011111

```

I have laid it out like that especially so that you see a pattern occurring. Four columns with 8 rows. Four slave multiplexers with 8 inputs. A perfect match. Each column has bits that are distinct to that column. Each row has bits that are unique to that row. So you could split those bits up and know that the left-hand three bits indicate the column, and the right-hand three bits indicate the row. Between the two it's a unique location in the table.

The same applies to the multiplexers. The left-hand three bits indicate which slave multiplexer to use, the right-hand three bits which input to use on the selected multiplexer.

So you can loop through each of the 32 inputs with a single loop and examine the individual bits of the input number and apply those bits directly to the select outputs to control the multiplexers - the left-hand bits to the master to select which slave to use, and the right-hand bits to the slaves to select which input to use.

So you have:

```
for (int i = 0; i < 32; i++) {
    digitalWrite(M_S2, i & 0b100000);
    digitalWrite(M_S1, i & 0b010000);
    digitalWrite(M_S0, i & 0b001000);
    digitalWrite(S_S2, i & 0b000100);
    digitalWrite(S_S1, i & 0b000010);
    digitalWrite(S_S0, i & 0b000001);

    delay(1);

    int reading = analogRead(Z);
    Serial.print("Input ");
    Serial.print(i);
    Serial.print(": ");
    Serial.println(reading);
}

```

The `i & 0b000001` etc performs the same function as `bitRead()` but is more explicit using a mask that is far more visual as to what it achieves.

I also include a tiny delay after setting the multiplexers up so as to ensure they have settled into their new settings properly before reading. It shouldn't be needed, but it doesn't hurt.
> 0 votes

# Answer
I think that you have confused your address *encoding* in your code. Your complete address space is only a total of 5 bits, decimal 0 to 31. Your two loops (`for ( byte count = 0; count < 4 ; count++ )` and `for ( byte count_1 = 0; count_1 < 32 ; count_1++ )`) are actually counting through a 7 bit address space, just with the 3 MSBs of the inner loop being ignored.

For your 32-input example, I'm going to assume that the master 4051 only has inputs A-D (`y0` to `y3`) connected to downstream muxes and that the analog mux decodes based on the binary value of the input select. Then your digital outputs should correspond to, for `byte address` as your counter:

* `S_S0` -\> `bitRead(address, 0)` (LSB)
* `S_S1` -\> `bitRead(address, 1)`
* `S_S2` -\> `bitRead(address, 2)`
* `M_S0` -\> `bitRead(address, 3)`
* `M_S1` -\> `bitRead(address, 4)`
* `M_S2` -\> constant `0` (MSB)

Thus, your test should only use a `for ( byte address = 0; address < 32 ; address++ )` to acquire data from all 32 possible inputs. Remember to have a long enough delay from selecting a different multiplexer input to starting your ADC conversion to avoid errors due to signal settling.

Additionally, you should be calling only one analog read location corresponding to the pin connected to the `AnalogInPin` in the schematic. You will have to record what the current multiplexer selection to determine which of the 32 inputs is actually being recorded by that conversion. Basically, there's only one 'master" analog input.

Your use of `value = (bitRead(count_1, 2),bitRead(count_1, 1),bitRead(count_1, 0));` is confusing and seems incorrect. After you `digitalWrite()` the new address for your multiplexers, you shouldn't need to read-back the digital pins to know what address you have selected.
> 0 votes

---
Tags: arduino-uno, multiplexer
---


# Question
Title: Reading Two Quadrature Encoder using a single Arduino Due
I am working on an autonomous robot in my summer vacations. I am currently working on running the motors of my robot in a closed loop. In order to do so, I have to interface **two Quadrature encoders** of the motors with the Arduino Due that I have. My motor encoder have **3200 Edges per Revolution**. I have read the Atmel SAM3x8E datasheet and have successfully tested one encoder in Arduino IDE. It appears that TIOA0 and TIOBO are used to read PHA and PHB of of one Encoder which correspond to Pin 2 and 13 of Arduino Due. I am not using Index pin (TIOB1).

It seems that I can only interface 1 quadrature .Is their any way I can use Quadrature decoder to read 2 encoders instead of one. As I have stated earlier I am not using the index pin. So, maybe there might be a way to decode to encoders using the three available pins as shown in the above diagram. I don't want to use Interrupts to do this job.

Here's is the link of SAM3x Manual: http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A\_Datasheet.pdf

Link of Motor that i am using: www.pololu.com/product/2824

# Answer
> 1 votes
According to Quadrature Decoder QDEC for SAM3/4 Devices\_ApplicationNote\_AT11483 and referenced excel sheet with Device to No of QDEC channels it seems to have two of them. However in DUE almost none of interesting devices are wired to headers completely (Extmem, SD interface,...)

However TIOA6 and TIOB6 should be on pins 5 and 4

Pin configuration should be something like this:

```
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT);
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT);

```

And TC0 is pretty much same as TC2, so just copy&paste and change TC0 to TC2

Full config:

```
  REG_PMC_PCER0 = PMC_PCER0_PID27 | PMC_PCER0_PID28 | PMC_PCER0_PID29;
  REG_PMC_PCER1 = PMC_PCER1_PID33 | PMC_PCER1_PID34 | PMC_PCER1_PID35;

  PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB25B_TIOA0, PIO_DEFAULT); // arduino pin 2
  PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB27B_TIOB0, PIO_DEFAULT); // arduino pin 13

  REG_TC0_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
  REG_TC0_RC2   = F_CPU / 128 / 1;
  REG_TC0_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
  REG_TC0_BMR   = TC_BMR_QDEN | TC_BMR_SPEEDEN /*| TC_BMR_EDGPHA*/;
  REG_TC0_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC0_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC0_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;

  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT); // arduino pin 5
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT); // arduino pin 4

  REG_TC2_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
  REG_TC2_RC2   = F_CPU / 128 / 10;
  REG_TC2_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
  REG_TC2_BMR   = TC_BMR_QDEN | TC_BMR_POSEN /*| TC_BMR_EDGPHA*/;
  REG_TC2_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC2_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC2_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;

```

---
Tags: arduino-due, atmel-studio, rotary-encoder
---


# Question
Title: Send RF 433MHz data to Domoticz RfxCom with protocol X10 from Arduino Nano
I have installed Domoticz on Raspberry Pi and bought an RfxCom 433MHz emitter/receiver. It works well for example with Chacon DiO 54781 door sensor. I want to create my own sensor with Arduino that would be recognized by Domoticz as a native RF 433MHz device. In first place, I want to make a flooding sensor, I also need an On/Off information. I would like to implement X10 protocol because it seems to be the simplest one.

# Answer
I finally found a documentation about RF X10 protocol: X10 RF Receiver.pdf

With following Hardware :

I've created the following working code for Arduino Nano :

```
/*
* Custom sensor (base code)
*
* Emission in RF 433MHz with the X10 protocol for Domoticz
*
* Hardware :
*   Arduino Pro Mini 5V         (4€)        https://www.amazon.fr/gp/product/B00QPUEFNW/ref=oh_aui_search_detailpage?ie=UTF8&psc=1
*   RF 433MHz emitter/receiver  (3€)        https://www.amazon.fr/HDigiWorld-metteur-cepteur-commande-Arduino/dp/B00JTQI39G/ref=sr_1_3?s=computers&ie=UTF8&qid=1470813610&sr=1-3&keywords=433
*       Note: only the emitter is used
*   3 wires : VCC, GND, Signal (on Arduino pin 2)
*
* Documentation found for RF X10: http://www.printcapture.com/files/X10_RF_Receiver.pdf
*
* Example of malformed data received in RfxMngr in mode "nodec" (before this code was correctly debugged) :
*
*       Packettype        = UNDECODED RF Message
*       UNDECODED NEC:1C515C86F0
*
*
* Correct data that is now receveived by RfxMngr with this program :
*
*------------------------------------------------
*       Packettype    = Lighting1
*       subtype       = X10
*       Sequence nbr  = 13
*       housecode     = D
*       unitcode      = 1
*       Command       = On
*       Signal level  = 7  -64dBm
*------------------------------------------------
*       Packettype    = Lighting1
*       subtype       = X10
*       Sequence nbr  = 14
*       housecode     = D
*       unitcode      = 1
*       Command       = Off
*       Signal level  = 7  -64dBm
*------------------------------------------------
*/

const int pin_emit = 2;         // Signal pin for RF433 emitter
const int pin_led = 13;         // Internal LED : it will be ON when the "On" command is sent in RF, and OFF the the "Off" command is sent (changed each 60s)

const unsigned int X10_A1_ON = 0x00;
const unsigned int X10_A1_OFF = 0x20;

const unsigned int X10_address = 5;     // this is Housecode. In my case 5 results in "D" house code
unsigned int X10_data = X10_A1_ON;      // command. I have implemented only On/Off for unit code 1

void setup() {
  pinMode(pin_led, OUTPUT);
  pinMode(pin_emit, OUTPUT);
  digitalWrite(pin_emit, LOW);
}

/**
* Bit to 0 : 1.125ms between rising edges, so before next bit
*/
void X10_sendBit_zero()
{
  digitalWrite(pin_emit, HIGH);
  delayMicroseconds(555);       // Arbitrary value: I took around 1.125ms divided by two for the "VCC" state.
  digitalWrite(pin_emit, LOW);
  delayMicroseconds(570);       // Total 555+570 : 1125µs = 1.125ms
}

/**
* Bit à 1 : 2.25ms entre les "rising edges"
*/
void X10_sendBit_one()
{
  digitalWrite(pin_emit, HIGH);
  delayMicroseconds(555);       // Arbitrary value: I took around 1.125ms divided by two for the "VCC" state.
  digitalWrite(pin_emit, LOW);
  delayMicroseconds(1695);      // Total 555+1695 : 2250µs = 2.250ms
}

void X10_send8bits(unsigned int data)
{
  // - Send the 8 bits, and then the complementary of the 8 bits.
  // from documentation: "Within each byte, bit7 is received first and bit0 last"
  int mask = 0x80;
  for(int i = 0; i < 8; i++)
  {
    int bit = mask & data;
    if (bit == 0)
      X10_sendBit_zero();
    else
      X10_sendBit_one();

    mask = mask >> 1;
  }
}

/**
* Sending a byte consists of sending this byte, and then sending the opposite of the same byte.
* As we send the opposite as well as the data, the total duration is always the same : 8 * (1.125ms+2.250ms) = 8 * 3.375 = total of 27ms
*/
void X10_sendByte(unsigned int data)
{
  X10_send8bits(data);
  X10_send8bits(~data);
}

/**
* Send a complete X10 packet
*
* Total duration :
* (9ms + 4.5ms) + (27ms + 27ms) + 0.555ms + 40ms = 108.055 ms
*  from doc: "It appears, from articles on the 'net, that other people have seen a range from 95 msec to 116 msec for various transmitters and that standard X-10 transceivers can tolerate timing variations of 30-35% from nominal."
*/
void X10_sendState_once(unsigned int data)
{

  // - Header
  digitalWrite(pin_emit, HIGH); // "Burst" de 9ms
  delayMicroseconds(9000);
  digitalWrite(pin_emit, LOW); // Silence de 4.5ms
  delayMicroseconds(4500);

  // - Data
  X10_sendByte(0x50); // - Address
  X10_sendByte(data); // - Data

  // - Send a last rising edge to validate last bit
  digitalWrite(pin_emit, HIGH);
  delayMicroseconds(555);       // Arbitraty value (but always the same), for "VCC" state.

  // - Footer
  digitalWrite(pin_emit, LOW); // Silence de 40ms pour signifier la fin de l'émission
  delayMicroseconds(40000);

}

/**
* Send a complete packet multiple times (this X10 protocol has not ACK))
* From doc: "Most X-10 RF transmitters send a minimum of five copies of the code separated by 40 msec silences although some can send single bursts."
*
*  5 times 108.055ms = 540.275 ms, half a second
*/
void X10_sendState(unsigned int data)
{
  // - "clean" to be sure to have a zero for the first rising edge on init
  digitalWrite(pin_emit, LOW);
  delay(1);

  // - Send 5 time complete packet
  for(int repeat=0 ; repeat<5 ; repeat++)
    X10_sendState_once(data);

}

void loop() {

  if(X10_data == X10_A1_ON)
    digitalWrite(pin_led, HIGH);
  else
    digitalWrite(pin_led, LOW);
  X10_sendState(X10_data);
  delay(60000);              // 1 minute

  // - I change state each 60 seconds to see changes in Domoticz
  if(X10_data == X10_A1_ON)
    X10_data = X10_A1_OFF;
  else
    X10_data = X10_A1_ON;
}

```

By changing House code and data, it is now possible to create our own RF sensors.
> 2 votes

---
Tags: arduino-nano, wireless, rf
---


# Question
Title: How does if(serial) work, a c++ question
The Arduino documentation says **if(Serial)** always returns 1, except for the case where Leonardo USB serial connection delays becoming ready.

(Leonardo has two USB IDs, and switches between them for boot loader and Serial USB. After boot loader finishes and kicks off the program, it takes a while for the USB master (e.g. your PC) to process the disconnect of the boot loader USB device and the connection of the Serial USB device. Thus the need for a wait.)

Now "*Serial*" is a static external instantiation of the *Serial\_* class (defined as ***extern Serial\_ Serial;***).

The c++ rules, as I understand them, do not allow a constructor to return a value, nor may the class name (which is also the constructor name) be used as a member (function) name in the class.

"*Serial*" cannot be defined in class *Serial\_*, or the **if(Serial)** syntax would have to be **if(Serial.Serial)**.

"*Serial*" cannot be defined outside the **class Serial\_,** or it will conflict with (i.e. hide) the definition of *Serial* as an instantiation of *Serial\_*.

***So how does the Arduino IDE do it?***

All I can think of is that the magic pre-scanner does something... But what exactly, pray tell?

# Answer
> 3 votes
It's not the constructor that's returning the value, it's the `bool` operator:

Uno:

```
HardwareSerial::operator bool() {
    return true;
}

```

Leonardo:

```
Serial_::operator bool() {
    bool result = false;
    if (_usbLineInfo.lineState > 0)
        result = true;
    delay(10);
    return result;
}

```

When you use the object in a setting where a boolean value is expected of it (e.g., `if`, `while` etc.) the `bool()` operator is called (if it exists) and that value is used.

More specifically, the `bool()` operator is called when the object is being *cast* to a `bool` type, either implicitly (as in `if...`) or explicitly (as in `... = (bool)Serial;`).

More on C++ class operators here: http://en.cppreference.com/w/cpp/language/operators

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


# Question
Title: switch pump on with transistor, mosfet, or relay
I would like to control a pump. The pump rating is 12 volt 60watts. The pump mfg says to use a 12 volt power supply of 5 - 12 amps but AT LEAST 5 amps. This pump has a pressure turn off at 116 psi and the mfg states that the pump will not make maximum pressure with less than 5 amps.

So the question becomes, to be able to switch this pump on and off based on some sensor reading what would be considered best practice: transistor, MOSFET, or relay?

# Answer
* Transistor - Big voltage drop between C-E @ 5A (depends on type but it will be about 2V). Power dissipitation is voltage drop times current so about 24Watts. You must be careful with inductive load - induced high voltage must be supressed. Usual way is using anti-parallel fast diode over load.
* Mosfet - Voltage drop can be really small, so it might be possible to use it without heatsink. Big Gate capacity needs strong driver to charge and discharge. If not, slow switching causes huge losses (again voltage drop times current). For inductive load it's same as for transistor.
* Relay - It must be selected carefully as switch-off causes electric arc (= burning contacts) and because of DC current it's burning for much longer time than AC.
> 1 votes

# Answer
The problem with a MOSFET is that at 5A you might find that the arduino output pin can't deliver enough voltage to the gate of the MOSFET to get it to fully turn on.

For the transistor, it is possible to use a transistor however it is probably best to construct it as a high side switch as opposed to a low side switch. This is to deal with potential problems that may arise with disconnecting the ground from the pump whilst running.
This is a good article which explains why low side switching can be bad

The best possible solution in this circumstance would be to use a relay connected to a NPN transistor which switches the low side of the relay. This isolates the delicate arduino electronics from the pump.
> 1 votes

---
Tags: switch
---


# Question
Title: A question about resistance measurement with arduino
Lately I was asking myself about the possibility of measuring a potentiometer resistance with Arduino.

My questions are:

1. Is it possible?
2. If it's possible, what kind of restriction does the Arduino have with the resistance value measured?

# Answer
> 8 votes
If you know Ohm's Law (which you should) and you realise that the ADC measures voltage, you should be able to work it out from there. But I will go into minute detail for you to ensure you understand.

Ohm's Law defines the relationship between Voltage (V), Current (I) and Resistance (R).

```
R = V/I

```

To find one unknown value (in your case R) you need to know the other two values. That is, the current flowing through the resistor, and the voltage dropped across the resistor.

We have no way of directly measuring current, but we can measure voltage using the ADC. So if we can somehow measure a voltage and use that to calculate the current then we have two of the three values and we can calculate the third. However, calculating the current requires that we know the resistance - and that is what we are wanting to find out.

So we need to then provide a *known* resistance that we can measure the voltage across, and thus find the current flowing through it. First a couple of reminders of basics:

* Current flows the same through all resistances connected in series
* The sum of all voltages dropped across resistors in series equals the total voltage across all the resistors.

So if we put two resistors in series and apply an fixed voltage across it (5V in our case) a single current will flow through them both. With that two voltages will be dropped across the resistors - and those two voltages will add up to 5V.

If we have one known resistor and one unknown resistor and we know the voltage dropped across both resistors then we can calculate the current that is flowing through the known resistor. And that current is the same current that is flowing through the unknown resistor. And since we know the voltage drop across that resistor we can then calculate its resistance using that voltage and the current we have just calculated.

Here's the circuit I just described:

Vin us 5V. Let's have R1 as, say, 10KΩ (a common enough value). R2 we don't know.

Using the ADC of the Arduino we measure a value of 681. First we convert that into a voltage:

```
Vout = 681 / 1024.0 * 5.0
     = 3.325V

```

So we know that R2 has 3.325V dropped across it, and since all the voltages must add up to 5V we know that R1 has (5 - 3.325) 1.675V dropped across it.

So the current (I=V/R) through R1 must be (1.675 / 10,000) 167.5µA (0.0001675A).

Now we can calculate the resistance of R2 since R=V/I and V is 3.325 and I is 0.0001675, so R must be 19850Ω - or pretty much 20KΩ.

That's the long-hand version from a current-based perspective. However there is a short-cut.

Since the output voltage is a simple ratio of the input voltage defined by the ratio between the resistors we can use that to create a much simpler formula.

From the example above the output voltage is two thirds the input voltage - and R2 is two thirds the total resistance (R1+R2). The two match perfectly. So we can use a simple ratio calculation to give us the resistor.

For instance, the ratio formula:

```
Vout = R2 / (R1 + R2) * Vin

```

(that's R2 as a proportion of the total resistance multiplied by the input voltage)

When rearranged to get R2 gives us:

```
R2 = R1 * (1 / ((Vin / Vout) - 1))

```

So taking the voltage we measured above (3.325) and the known resistor (10,000Ω) and the input voltage (5V) and substituting those values into the formula, we get:

```
R2 = 10,000 * (1 / ((5 / 3.325) - 1))
   = 10,000 * (1 / (1.504) - 1)
   = 10,000 * (1 / 0.504)
   = 10,000 * 1.984
   = 19840

```

Or pretty much 20KΩ. (Note: the discrepancy in the results is purely due to rounding errors. Use higher precision values and you get better results).

You have to have a rough idea of the kind of order of magnitude of resistor you are trying to find, though, in order to select an R1 of a comparable value so that the voltage Vout is large enough to measure accurately.

Also you need to be aware that the input to the ADC has quite a (relatively) low impedance (can be very crudely thought of as a resistor between the input and ground) which is measured in the low mega-ohm range. This can have an impact on the values you read with the ADC if your resistors are too high, since this impedance will be in parallel to the resistor R2, so you'd actually be measuring the resistance of both R2 and the ADC's input in parallel. To measure very high resistances you should first buffer the ADC through a *voltage follower* with a very high (tens or hundreds of tera-ohms) impedance input.

# Answer
> 2 votes
*The question isn't explicitly clear, this answer is based on having a single known value pot and wishing to know its resistance at any one point rather than trying to find an unknown resistance entirely*

You can't measure resistance directly. What you can do however is measure the voltage across a potentiometer.
There is a really good example provided by arduino which can be found here.

Now, it is possible to turn this into a resistance value with a little bit of editing to the code

```
int potPin = A0;    // Select the input pin for the potentiometer
int potR = 1000;    // This is your max potentiometer resistance in Ohms
int val = 0;        // Variable to store the value coming from the sensor
float voltage;      // This is the voltage from the wiper of the pot
float resistance;   // This is the resistance of the pot at the wiper

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

void loop() {
  val = analogRead(potPin);                      // Read the value from the pot wiper
  voltage = val * (5.0 / 1023.0);                // Convert the value into a voltage
  resistance = (voltage / 5.0) * potR;           // Convert the voltage into a resistance
  Serial.print("Voltage = ");
  Serial.print(voltage);                         // Print the voltage
  Serial.println("V");
  Serial.print("Resistance = ");
  Serial.print(resistance);                      // Print the resistance
  Serial.println("R");
  delay(1000);                                   // Add a little delay
}

```

As for your second question, it can do as high a resistance as you want. As long as you update the potR value in the code with the resistance of your pot (e.g. 1000000 for a 1MOhm pot)

*I'm an electronics engineer by trade so my code could probably be cleaned up and made more efficient, this is just a starting point*

---
Tags: arduino-uno, arduino-leonardo, analogread, potentiometer, analogwrite
---


title: Powering multiple Arduino shields

text:
# Question
Title: Powering multiple Arduino shields
To start, I am a software guy, so I am not too clued up on the electronics side of things. My question is: I have a number of Arduino shields and would like to power them with a portable power source, and therefore would like some advice on what to use without frying any electronics.

This is a list of the current equipment that will require power:

The shields will be stacked on top of each other.

# Answer
> 1 votes
All the shields are 5v compatible. So no need to worry about 3.3v.

But there may be a chance of insufficient current if you use a battery to the power-jack of arduino mega (due to the internal voltage regulator). I'd suggest you cut a USB cable and solder the +5(red color) wire to VIN on the mega and ground(black wire) to GND pin. And use a 'power bank', which is used for mobile phones.

# Answer
> 1 votes
Your stack will need quite a lot of current - most probably more than the Arduino can supply itself.

You will need to provide your own regulated 5V supply - either from a USB port (convenient if you are by a computer) - as long as it can supply more than 500mA of current (you need a Charging Downstream Port *CDP* for that) or from some external regulated 5V power supply, such as a mobile phone charger.

That 5V supply should be connected direct to the 5V pin of the Arduino's power header.

One thing to note: the headers themselves are only rated for up to 1A. If you need more than 1A throughout the entire stack it could be worth connecting the 5V power supply direct to the 5V pins of ALL the shields in the stack. Also do the same with the GND pins to the negative of the power supply. That way the high current doesn't need to flow through the pins themselves.

---
Tags: power
---


title: IDE 1.6.10 on LinuxMint 17.3 Cinnamon

text:
# Question
Title: IDE 1.6.10 on LinuxMint 17.3 Cinnamon
When compiling I get the error 'as: unknown option »-mmcu=avr5« exit status 1'

I succeeded now using your piece of advise. Thank you so much.

# Answer
Delete or rename the old "Arduino15" directory located at /home/(username)/.arduino15 (a.k.a. ~/.arduino15) and re-install 1.6.10.
> 1 votes

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


title: LED bar graph script not working

text:
# Question
Title: LED bar graph script not working
I have LED bar graph on pins 2-11. Eventually I want to use a voltage divider to figure out the amount of voltage left in a power supply. Currently, this script should set the number of LEDs on the bar graph based on `round((v_actual/v_reference)*10)`, I am just using some placeholder numbers in the mean time to test this portion of the script e.g. `v_actual` of 5 and `v_reference` of 10. However, the `convert` variable *keeps printing 0*. I've checked that the other variables were passing and they are. What is the issue here?

```
#include <Wire.h>

int ledBarNum = 10;    // # of leds
int vref = 10;     // max voltage of power supply

void setup(){
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
}

void loop() {

  ledBarSetup(5);
}

void ledBarSetup(int v) {

  // logic vref=8; vactual or v = 4; (4/8)*10 = 2
  // e.g. number of leds we need to light up to represent the total amt left

  Serial.println(v);
  Serial.println(vref);

  int convert = round((v/vref)*10);

  Serial.println(convert);

  ledBar(convert);

}

void ledBar(int n) {

  int startingPin = 2;

  for (int thisPin = 2; thisPin < ledBarNum; thisPin++) {

    if (thisPin <= n) {

      digitalWrite(thisPin, HIGH);

    } else {

      digitalWrite(thisPin, LOW);

    }

  }

}

```

# Answer
Both `v` and `vref` are integers, which means that integer division will be performed. if `v` is ever less than `vref` then the result will be 0. Multiply first, then divide.
> 4 votes

---
Tags: led, arduino-nano, arduino-micro, mathematics
---


title: Problems with running multiple ESC

text:
# Question
Title: Problems with running multiple ESC
I've written a program which allows me to use my `Arduino Uno` to send a `PWM` to an **Electronic Speed Controller**. 5 seconds after startup the ESC is sent a config via `PWM` to signal the low to high `PWM` range to be used by the ESC. Then I can type into the `Serial Monitor` a single digit 0-9 to pick the `PWM` I want to send to my ESC. *(n\*2 = pwm)*

This works great when running code for *one* ESC, but adding code for a *second* ESC causes significant issues (I only have one ESC plugged in). When I send a `serial` command to specify `PWM` rate, my ESC only receives the `PWM` change *sometimes*. About 2/3 times it ignores the PWM change and keeps spinning at the same rate it was already at.

***What's going on here?***

# Code

**WorkingESCSoftware** *(main file of .eno)*

```
#include <SoftwareServo.h>
#include "TestClass.h"

int val;    // variable to read the value from the analog pin
int stage = 0;

TestClass t, t2;

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

  t = TestClass();
  t.setPin(3);
  t2 = TestClass();
  t2.setPin(5);
}

void loop()
{
  t.loop();
  t2.loop();
}

```

**TestClass.h**

```
class TestClass {
  private:
    SoftwareServo servo;
    bool _initialized = false;

    int PWM_MAX = 180;
    int PWM_HIGH = 170;
    int PWM_MEDIUM = 80;
    int PWM_LOW = 40;
    int PWM_OFF = 25; // has to be between esc config off (stop) and low (slow spin)
  public:
    TestClass();
    void setPin(int);
    void loop();
};

TestClass::TestClass() {
  Serial.println("cycle lipo power to esc");
}

void TestClass::setPin(int pin) {
  this->servo.attach(pin);
}

void TestClass::loop() {
  //  Serial.println("loop");

  // 5 seconds after power, send PWM range to ESC
  if(millis() > 5000 && this->_initialized == false) {
    this->_initialized = true;

    Serial.println("esc setup");
    this->servo.write(PWM_MAX);
    delay(5);
    this->servo.write(PWM_OFF);
    delay(5);
    Serial.println("esc ready");
  }

  char r = Serial.read();
  String inStr = String(r);
  if(r > -1) {
    Serial.print("serial in: ");
    Serial.println(inStr);
  }

  use h, m, l, o, or 0-9 to control PWM of ESC
  if(r <= -1) {
    // void
  } else if(inStr == "h") { // high
    Serial.print("HIGH: ");
    Serial.println(PWM_HIGH);
    this->servo.write(PWM_HIGH); // highest spinning (same as 160?)
  } else if(inStr == "m") { // medium
    Serial.print("MED: ");
    Serial.println(PWM_MEDIUM);
    this->servo.write(PWM_MEDIUM);
  } else if (inStr == "l") { // low
    Serial.print("LOW: ");
    Serial.println(PWM_LOW);
    this->servo.write(PWM_LOW);
  } else if (inStr == "o") {
    Serial.println("OFF");
    this->servo.write(PWM_OFF);
  } else if (inStr.toInt() >= 0 && inStr.toInt() <= 9) {
    int val = inStr.toInt() * 20;
    Serial.println(val);
    this->servo.write(val);
  }

//  SoftwareServo::refresh();
  this->servo.refresh();
}

```

# Answer
You have two copies of your program sharing one physical resource, the serial port input to the Arduino. It is by chance which of the two copies will receive and process the input data. So this approach will not work dependably.

Semiphoras are often used when sharing hardware among several programs. However you are not only sharing hardware, but also the data being sent to the Arduino. And the data will only be sent once.

In this case, you need to handle the data once in code that is separate from the 2 instantiations of the ESP class. That is, you need to process the received data once and pass that processed data to the appropriate instantiation of the ESP class.
> 1 votes

---
Tags: arduino-uno, pwm, servo, electronics
---


title: Low memory error using SD card

text:
# Question
Title: Low memory error using SD card
I called HTTP web service on Arduino Uno, now i am trying to store the data in SD card. But as soon as i compile the program, it shows LOW MEMORY error and no data stored in SD card. Any one can help?

# Answer
Try Arduino mega. It has more memory 8 KB RAM, 256 KB flash memory.
> 0 votes

# Answer
Try to use properly kind of variables for example if u r using Int in a value can would use byte of try to put some serial.println(F("wherever you can print ")) for running on sram instead of stack memory.
> 0 votes

---
Tags: arduino-uno
---