title: Using 555 as an external Watchdog

text:
# Question
Title: Using 555 as an external Watchdog
I would like to use a 555 circuit as an external watchdog for my Arduino project. The project is a cellular tracker that goes to sleep for an hour, wakes up and does some measurements, uploads them and then goes to sleep again. The 555 should take care that the active period does not take too long because the systems hangs, and in that case trigger a reset. My first thought was to power the 555 circuit with a PIN of the Arduino so that it only goes on when the system is awake and is turned off while sleeping. But this does not work as the reset line has to stay high even while sleeping and if i turn the 555 off reset would also go low. Could a Mosfet help? Any other ideas?

# Answer
> 4 votes
ok guys - found the answer: this post here at electronics-stackexchange gave the right hint: Watch-Dog Timer. And my gut feeling was right as well - i simply use a NPN-Mosfet that is being triggered by an Arduino-PIN (which easily can be done while sleeping as well as sleeping means waking up every 8seconds anyway) that connects the capacitor to ground and therefore discharges the guy. Awesome. This solution can be used as a real fallback in case of whatever happens, while operating the system with built in watchdog-functions while everything is ok.

---
Tags: reset
---


title: Works on Uno but not on Yun

text:
# Question
Title: Works on Uno but not on Yun
I found some code that works to transmit the required signal to an RX-2B RC receiver, the code works great from my Uno but when I tried to run it from my Yún nothing happens.

The code has definitely uploaded as I tested with an LED and the pin is getting a HIGH voltage written to it.

Does anyone have any idea what the issue might be? Code below.

Thanks.

```
/**
* Control Realtek RX2 (RX2 -G) RC Receiver with Arduino
*
* @author Mircea Diaconescu, Octomber 28, 2013
* @source https://github.com/dimircea/
* GPL v3 License
*
 * Many cheap RC toys are based on TX2 / RX2 transmitter / receiver ICs.
 * This Arduino sketch allows to replace the TX2 based Remote Control with Arduino.
 * Just one single pin is used from the Arduino board.
 *
 * Connect Arduino pin 10 to the solder point where the toy antenna is connected or         to the toy antenna cable.
 * One can replace pin 10 with other free digital pin available on the Arduino board.
     *
 * TX-2B/RX-2B datasheet: http://www.datasheetarchive.com/dl/Datasheet-    035/DSA0017137.pdf
 */

/** Functions (aka W1) - as defined by the IC datasheet */
#define COMMAND_ENDCODE         4
#define COMMAND_FORWARD        10
#define COMMAND_FORWARD_TURBO  16
#define COMMAND_TURBO          22
#define COMMAND_FORWARD_LEFT   28
#define COMMAND_FORWARD_RIGHT  34
#define COMMAND_BACKWARD       40
#define COMMAND_BACKWARD_RIGHT 46
#define COMMAND_BACKWARD_LEFT  52
#define COMMAND_LEFT           58
#define COMMAND_RIGHT          64

//output pins
#define ANTENNA_PIN 9

/** Initialize the Arduino data and pin */
void setup() {
 pinMode( ANTENNA_PIN, OUTPUT);
}

/** Loop code */
void loop() {
 // add here your commands to control the RX2 module...
 // for test purposes, here a continuous forward command is sent

 sendCommand( COMMAND_FORWARD);

}

/** Send command to the RX2 IC */
void sendCommand( int command) {
 int w1 = 0, w2 = 0;

 /** start code sequence 4 x W2, ~625Hz, Duty Cycle 75% */
 for ( w2 = 0; w2 < 4; w2++) {
   digitalWrite( ANTENNA_PIN, HIGH);
   delayMicroseconds( 1200);
   digitalWrite( ANTENNA_PIN, LOW);
   delayMicroseconds( 400);
  }

 /** function code sequence, n x W1, ~1.25KHz, Duty Cycle 50% */
 for ( w1 = 0; w1 < command; w1++) {
   digitalWrite( ANTENNA_PIN, HIGH);
   delayMicroseconds( 400);
   digitalWrite( ANTENNA_PIN, LOW);
   delayMicroseconds( 400);
 }
}

```

# Answer
> 1 votes
A Yun is like a Leonardo with a CPU running GNU/Linux at its side. If your sketch works with a Leonardo, it's likely to work with a Yun.

Uno has a different MCU and thus not every sketch will just work, especially those using the hardware serial. You'll have to convert them.

---
Tags: arduino-uno, arduino-yun, pwm
---


title: Proxy and Authentication in Arduino Uno

text:
# Question
Title: Proxy and Authentication in Arduino Uno
I am using the Ethernet Shield on top of the Arduino Uno. I want to use this setup to access webpages. But I am unable to access because the ethernet connection is present in a University which requires a proxy server with authentication. I am unsure of what extra code to include so as to get past the proxy which requires authentication. Can anyone help in solving this problem?

# Answer
> 2 votes
Any semi-reputable authentication mechanism would be performed over HTTPS, which is an encrypted connection - this would require an SSL library to be installed for use along with the normal Ethernet and HTTP libraries, and I don't believe the arduino really has the processing capability to make connections like this feasible. Unfortunately this is one of those cases where a more sophisticated device may be more appropriate.... (like a Beaglebone Black, or a Raspberry Pi.)

It is possible that you could add headers into the HTTP connection packet to either bypass proxy authentication, or include a cookie that has already undergone authentication and is cached by the proxy. How you do this is almost entirely down to how your proxy works. You may also find this doesn't work unless you spoof the MAC address of your device to match that of the machine used to fulfill the authentication.

It is entirely possible to set up a system to share the internet connection (act as a router) between two adapters - so you end up making connection requests to webpages, but the authenticated proxy only sees requests coming from your system (this is kind of how mobile phone tethering works, when you access the internet on a laptop or tablet through your smartphone's internet connection).

**If** the proxy supports unencrypted authentication, it may be possible to pass through username/password details in plaintext (or Base64 encoded) in Basic access authentication, which is what HTTP (and HTTPS) often uses - but this is unsafe on HTTP and is **VERY** unsafe when any part of the connection is publicly transmitted - like when using wifi, for example. (Doesn't matter if the wifi is encrypted - as on a university network, everyone who can connect to the wifi can see your wifi traffic (typically).)

If you're going to be using your own personal university login credentials to do this, make sure you always use ethernet to do it, not wifi, and if possible, obtain a second username/password explicitly for connecting this way - you don't want to have to hard-code your own personal username and password into source code that you have to give to anyone.

Here's a few links to get you started:

---
Tags: arduino-uno
---


# Question
Title: Arduino Uno + Ethernet shield stability question
i have a climate control software which reports data back through the web browser. Everything seems to be working however I am running into an issue where

1 - after a bit it seems the page doesnt refresh completely and instead displays a long list of the same webpage, so i have like 30 pages of the same thing as you scroll down

2 - when i woke up in the morning i could not load the page at all

What i am wondering is how can i get this to be stable and reliable so that the climate control software / sensors can run non-stop.

Currently as long as i dont use the ethernet shield reporting everything else seems to work great, i leave it on for 12 -20 hours and it still runs, but not with the ethernet reporting.

any help wold be apreciated thanks.

this is my code:

```
//Define Start
#define NOTE_D2  73 //sound note for beep
#define DHTPIN 2
#define DHTTYPE DHT22
#define DHT2PIN 3
#define DHTTYPE2 DHT22
#define MAGENTA //Define a color for screen
#define sclk 8 //screen pin
#define mosi 5 //screen pin
#define cs   6 //screen pin
#define dc   7 //screen pin
#define rst  rstpin  // you can also connect this to the Arduino reset
#define ANALOG_IN 0 // for cds light sensor

//Define End
//Include start
#include <DHT.h>//dht sensor library
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>//needed to run screen
#include <Wire.h>
#include "RTClib.h"
#include <Ethernet.h>
//Include end
//declare start
DHT dht2(DHT2PIN, DHTTYPE2);
DHT dht(DHTPIN, DHTTYPE);
int powerswitch1 = A0;
int powerswitch2 = A1;
const int ledPin =  A2;
const int ledPin2 =  A3;
Adafruit_ST7735 tft = Adafruit_ST7735(cs, dc, mosi, sclk);
char* myString = { "OFF" };//relay1 on / off status
char* myString2 = { "OFF" };//relay2 on / off status
const int chipSelect = 4;
RTC_DS1307 RTC;
byte mac[] = {
  0x90, 0xA2, 0xDA, 0x00, 0x23, 0x36 }; //MAC address found on the back of your ethernet shield.
IPAddress ip(192,168,1,40);
//decalare end
EthernetServer server(80);

void setup() {
pinMode(ledPin, OUTPUT);
pinMode(ledPin2, OUTPUT);
tft.initR(INITR_BLACKTAB);   // initialize a ST7735S chip, black tab
tft.fillScreen(ST7735_RED);//make screen red
  pinMode(powerswitch1, OUTPUT);
  pinMode(powerswitch2, OUTPUT);
  Serial.begin(9600);
  Wire.begin();
  RTC.begin();
if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
 //   RTC.adjust(DateTime(__DATE__, __TIME__));
  }

// get time to display "sensor up time"
  uint16_t time = millis();
 // tft.fillScreen(ST7735_BLACK); //black screen
  time = millis() - time;

Serial.println(time, DEC);

  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}
void loop(){
  //Tone Start
    tone(9, NOTE_D2);
    delay(65);
    noTone(9);
//Tone End

//clock start
  DateTime now = RTC.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

 //hour conversion to 12 hour start
   int x;
   int timeresult;
   x = (now.hour());
   if (x > 12) {
   timeresult = x - 12;
   }
   else
   {
    timeresult = x;
   }
   Serial.println(timeresult);
    //hour conversion to 24 hour start
//clock end
//sensor 1 start
    //Serial.println("read DHT22 #1");
    float h = dht.readHumidity();
    float t = dht.readTemperature();
    float f = dht.readTemperature(true);
    //sensor 1 end
    //sensor 2 start
    //Serial.println("read DHT22 #2");
    float h2 = dht2.readHumidity();
    float t2 = dht2.readTemperature();
    float f2 = dht2.readTemperature(true);
    //sensor 2 end
    //temp average begin
    //Serial.println("average calculation");
    float havg = (h + h2) / 2;
    float favg = (f + f2) / 2;
    float tavg = (t + t2) / 2;
    //temp average end

//Relay 1 Start
    if (h < 42) //top threshold
    {
        if (h < 39) //bottom threshhold
        {
            digitalWrite(powerswitch1, HIGH);
            // Turn the Powertail on
            Serial.println("Switch ON");
digitalWrite(ledPin, HIGH);
            myString = "ON";
        }

    }
    else
    {
                myString = "OFF";
        digitalWrite(powerswitch1, LOW);    // turn the Powertail off
digitalWrite(ledPin, LOW);
        Serial.println("Switch OFF");

    }
//Relay 1 End
//Relay 2 Start
    if (f < 60) //top threshold
    {
        if (h < 60) //bottom threshhold
        {
            digitalWrite(powerswitch2, HIGH);
            // Turn the Powertail on
            Serial.println("Switch ON");
digitalWrite(ledPin2, HIGH);
            myString2 = "ON";
        }

    }
    else
    {
                myString2 = "OFF";
        digitalWrite(powerswitch2, LOW);    // turn the Powertail off
digitalWrite(ledPin2, LOW);
        Serial.println("Switch OFF");

    }
//Relay 2 End
//Screen start

delay(500);

tft.fillRect(20,19,80,140, ST7735_RED);//clear text
//(left wall,top wall px from top,right wall,bottom wall px from top)
tft.drawRect(20,19,80,140, ST7735_RED);//cleartext
//active text
tft.setCursor(35, 20);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(f);
tft.setCursor(35, 40);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(t);
tft.setCursor(35, 60);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(h);
tft.setCursor(25, 120);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(timeresult);
tft.setCursor(50, 120);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(now.minute(), DEC);
tft.setCursor(75, 120);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(now.second(), DEC);

//static text

tft.setCursor(105, 20);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println("F");
tft.setCursor(105, 40);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println("C");
tft.setCursor(105, 60);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println("%");
tft.setCursor(52, 80);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(myString);
tft.setCursor(105, 80);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println("H");
tft.setCursor(52, 100);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(myString2);
tft.setCursor(105, 100);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println("T");
tft.setCursor(52, 140);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(millis() / 1000);
tft.setCursor(105, 140);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println("-");

tft.print(millis() / 1000);
//Screen end

 EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
   client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          client.println("<body>");
          /////CSS
            client.println("<style>");
            client.println("#left {");
            client.println("float:left;");
            client.println("}");
            client.println("text1 {");
            client.println("color: #07BBF2;");
            client.println("font-size: 200%;");
            client.println("}");
            client.println("text2 {");
            client.println("color: #FC5400;");
            client.println("font-size: 200%;");
            client.println("}");
            client.println("text3 {");
            client.println("color: #02BA3C;");
            client.println("font-size: 200%;");
            client.println("}");
            client.println("text4 {");
            client.println("color: #EBF700;");
            client.println("font-size: 200%;");
            client.println("}");
            client.println("text5 {");
            client.println("color: #F7C600;");
            client.println("font-size: 200%;");
            client.println("}");
            client.println("text6 {");
            client.println("color: #000000;");
            client.println("font-size: 200%;");
            client.println("}");
            if (myString == "ON") {
            client.println("humidifier {");
            client.println("color: #02F04E;");
            client.println("font-size: 100%;");
            client.println("}");
            }
            else {
              client.println("humidifier {");
            client.println("color: #FC5400;");
            client.println("font-size: 200%;");
            client.println("}");
            }
            if (myString2 == "ON") {
            client.println("heater {");
            client.println("color: #02F04E;");
            client.println("font-size: 200%;");
            client.println("}");
            }
            else {
             client.println("heater {");
            client.println("color: #FC5400;");
            client.println("font-size: 200%;");
            client.println("}");
            }

             client.println("#right {");
            client.println("float:right;");
            //client.println("color:red;");
            client.println("}");
            // client.println("#header {");
           // client.println("background-color:black;");
           // client.println("}");

            client.println("#content {");
            client.println("background-color:grey;");
            client.println("width:500px;");
            client.println("height:200px;");
            client.println("}");
            client.println("</style>");
          ///CSS

          client.println("<div id = content>");
          client.println("<body bgcolor=""#000000::>"); //how to change color adruino version

            client.println("<div id = left>");
            client.println("<text4>");
            client.print("Sensor 1");
            client.println("</text4>");
            client.println("<p />");
            client.println("<text1>");
            client.print(h);
            client.print(" %\t");
            client.println("</text1>");
            client.println("<p />");
            client.println("<text2>");
            client.print(f);
            client.println(" °");
            client.println("F");
            client.println("</text2>");
            client.println("<p />");
            client.println("<text2>");
            client.print(t);
            client.println(" °");
            client.println("C");
            client.println("</text2>");
            client.println("<p />");
            client.println("</div>");
            client.println("<div id = right>");
            client.println("<text4>");
            client.print("Sensor 2");
            client.println("</text4>");
            client.println("<p />");
            client.println("<text1>");
            client.print(h2);
            client.print(" %\t");
            client.println("</text1>");
            client.println("<p />");
            client.println("<text2>");
            client.print(f2);
            client.println(" °");
            client.println("F");
            client.println("</text2>");
            client.println("<p />");
            client.println("<text2>");
            client.print(t);
            client.println(" °");
            client.println("C");
            client.println("</text2>");
            client.println("<p />");
            client.println("</div>");
            client.println("<div align=center>");
            client.println("<text5>");
            client.print("Humidifier: ");
            client.println("</text5>");
            client.println("<humidifier>");
            client.print(myString);
            client.println("</humidifier>");
            client.println("<text5>");
            client.print("Heater: ");
            client.println("</text5>");
            client.println("<heater>");
            client.print(myString2);
            client.println("</heater>");
            client.println("<text6>");
            client.println("<p />");
            client.print(millis() / 1000);
            client.println("</text6>");
            client.println("<text6>");
            client.print(timeresult);
            client.print(":");
            client.print(now.minute(), DEC);
            client.print(":");
            client.print(now.second(), DEC);
            client.println("</text6>");
             client.println("</div>");
              client.println("</div>");
          client.println("</body>");
          client.println("</html>");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disonnected");
  }

delay(3000);

}

```

# Answer
> 1 votes
I have had to program in a reset for the network connection on quite a few of my ethernet projects. I am not entirely sure the cause, but adding a close connection; open connection to run every x minutes seems to have helped prevent both the duplicating content and the timeout issues.

# Answer
> 0 votes
I would go for a memory issue - try to rewrite your code in a way that consumes less memory, the easiest first step is to avoid any Serial.printl("String"); and replace that with Serial.println(F("String"));. But in general you are using a lot of String objects which should be avoided if possible (try to use char() instead).

To check memory consumption of your sketch you can use a function like this and log the values from specific points in the code:

```
int freeRam () {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

```

# Answer
> 0 votes
I used to encounter weird issues, e.g. starting a new instance of a program with Arduino Yun. The issue in the end was power supply, a large capacitor before the voltage regulator has solved the problem. What do you use for power supply?

---
Tags: arduino-uno
---


title: How can I make pinMode calls faster?

text:
# Question
Title: How can I make pinMode calls faster?
I'm trying to use 3 pins as capacitive pins along side the Mozzi.

I had several attempts and so far the closest I had was using code from the ADCTouch library straight into the main code, but with the current implementation (removing averaging and taking less samples to speed things up) it's only fast enough to process 1 pin and I'd like to use 3.

Here is my implementation so far:

```
/*  Based on the Gain Example changing the gain of a sinewave,
    using Mozzi sonification library.

    Demonstrates the use of a control variable to influence an
    audio signal.

    Circuit: Audio output on digital pin 9 on a Uno or similar, or
    DAC/A14 on Teensy 3.0/3.1, or
    check the README or http://sensorium.github.com/Mozzi/

    Mozzi help/discussion/announcements:
    https://groups.google.com/forum/#!forum/mozzi-users

    Tim Barrass 2012, CC by-nc-sa.
*/

#include <MozziGuts.h>
#include <Oscil.h> // oscillator template
#include <tables/sin2048_int8.h> // sine table for oscillator

// use: Oscil <table_size, update_rate> oscilName (wavetable), look in .h file of table #included above
Oscil <SIN2048_NUM_CELLS, AUDIO_RATE> aSin(SIN2048_DATA);

// control variable, use the smallest data size you can for anything used in audio
byte gain = 255;

//ADC Touch setup
int sampleCount[3] = {0};
int values[3] = {0};

void setup(){
  startMozzi(); // start with default control rate of 64
  aSin.setFreq(4200); // set the frequency
}

void updateControl(){
  if(gain > 3){
    gain = gain - 3 ;
  }else{
    gain = 0;
  }
  //begin ADCTouch
  pinMode(A4, INPUT_PULLUP);

  ADMUX |=   0b11111;
  ADCSRA |= (1<<ADSC); //start conversion
  ADCSRA |= (1<<ADIF); //reset the flag

  pinMode(A4, INPUT);

  values[0] = mozziAnalogRead(A4);
  sampleCount[0]++;
  //end ADCTouch

  if(sampleCount[0] == 64){//wait for 64 samples
    if(values[0] > 500) {//did we get a touch with all these samples ?
      gain = 255;//amp it up
    }
    sampleCount[0] = 0;//reset count
  }

}

int updateAudio(){
  return (aSin.next()* gain)>>8; // shift back to STANDARD audio range, like /256 but faster
}

void loop(){
  audioHook(); // required here
}

```

The issue is as soon as do the pinMode calls for the second pin I'd like to use (A5) so I'm guessing pinMode needs to work faster. To use `pinMode(INPUT_PULLUP)` and `pinMode(INPUT)` calls for pins A4,A5 and digital 10, now can I write this using direct port manipulation ?

(I'm new to avr/arduino internals and slowly getting the grips with this).

# Answer
> 7 votes
First, figure out which port and pin you're using. Then, manipulate them.

```
DDRC &= ~_BV(PC5);
PORTC |= _BV(PC5);

```

...

```
DDRF &= ~_BV(PF5);
PORTF |= _BV(PF5);

```

...

```
DDRF &= ~_BV(PF0);
PORTF |= _BV(PF0);

```

---
Tags: avr, c++
---


# Question
Title: What sensor would I use to get the speed or velocity of my Arduino based nav system?
I'm building a Arduino Nano based underwater navigation system using an IMU and various sensors. The only problem with this is that I cannot get the speed or velocity(at least reliably) and it would help the accuracy of my navigation system immensely if I had accurate speed to go off of.

Does anyone have any ideas on how I could measure the speed of my Arduino underwater? I've seen some people recommend paddle wheel like sensors but this needs to be accurate for slow movement.

# Answer
On small recreational sailboats there is a small propeller on the bottom, when it turns it dials a speedometer, the faster it turns the faster the ship goes, a similar setup should be possible. With a small propeller and 2 ball bearings and an optocoupler, (same principle you got in the scroll button on your mouse, you should be able to pull it off with minimal resistance since there is no physical parts.
> 1 votes

# Answer
If you want accurate data (i.e. not by dead reckoning) then possibly GPS is an option. I suspect you will need to surface for it to work, as GPS signals are fairly week at the best of times - on a previous car I had, the windscreen was enough to stop the signal.
> 0 votes

---
Tags: arduino-nano
---


title: Arduino Yun, pass int data true REST

text:
# Question
Title: Arduino Yun, pass int data true REST
Would it be possible to instead of passing a state via a REST browser:

```
digital/13/1

```

to set an int value? For example, if in the sketch if I would name an int: 2, could I set this to 48 via REST?

If so, how?

# Answer
Check out the TemperatureWebPanel example: you'll see that you can make your own REST APIs and pass any values your sketch can handle.
> 1 votes

---
Tags: arduino-yun
---


# Question
Title: Arduino Uno + Wifi Shield + PS2 Keyboard + LCD Display
I'm new in the Arduino Community and I'm facing a problem when I try to use a PS2 Keyboard and an LCD Display (16x2) on an Arduino Uno with a Wifi shield.

I would like to write something with the keyboard and display it in the LCD before sending it to a webservice.

Here is my problem:

* When I use the keyboard and the display on my Arduino WITHOUT the wifi shield --\> All is OK. I can write on the display the key that has been pressed.
* When I use the keyboard and the display on my Arduino WITH the wifi shield --\> All is OK until I write something on the display. As soon as I write on the display with the function lcd.print(), the keyboard does not work anymore (it detect the character '2' every time I press a key).

It's very surprisingly because if I dont use lcd.print(), the keybord works without any problem.

Here is a part of my code:

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

LiquidCrystal lcd(12, 11, 2, 5, 6, 8);
PS2Keyboard keyboard;

const int DataPin = 9;
const int IRQpin = 3;

void setup(){
  keyboard.begin(DataPin, IRQpin);
  lcd.begin(16, 2);
}

void loop(){
  checkKeyboard();
}

void checkKeyboard(){
  if (keyboard.available()) {

    char c = keyboard.read();

    // check for some of the special keys
    if (c == PS2_ENTER) {
      Serial.println();
    } else if (c == PS2_TAB) {
      Serial.print("[Tab]");
    } else if (c == PS2_ESC) {
      Serial.print("[ESC]");
    } else if (c == PS2_PAGEDOWN) {
      Serial.print("[PgDn]");
    } else if (c == PS2_PAGEUP) {
      Serial.print("[PgUp]");
    } else if (c == PS2_LEFTARROW) {
      Serial.print("[Left]");
    } else if (c == PS2_RIGHTARROW) {
      Serial.print("[Right]");
    } else if (c == PS2_UPARROW) {
      Serial.print("[Up]");
    } else if (c == PS2_DOWNARROW) {
      Serial.print("[Down]");
    } else if (c == PS2_DELETE) {
      Serial.print("[Del]");
    } else {
      Serial.print(c);
      displayText(c);
    }
  }
}

void displayText(char c){
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Pressed key:");
  lcd.setCursor(0,1);
  lcd.print(c);
}

```

Does somebody know how to solve this problem?

Thank you very much in advance :)

Edit: Here are the pins that I use on the board :

* Arduino pin 2 -\> LCD pin 11
* Arduino pin 5 -\> LCD pin 12
* Arduino pin 6 -\> LCD pin 13
* Arduino pin 8 -\> LCD pin 14
* Arduino pin 11 -\> LCD pin 6
* Arduino pin 12 -\> LCD pin 4
* Arduino pin 3 -\> Keyboard IRQ
* Arduino pin 9 -\> Keyboard Data

# Answer
> 0 votes
As you say, I can't use pins 10, 11, 12, 13 because they are used for the SPI.

-\> So, I tried to use the pins 4 and 7 instead of 11 and 12.

The problem is that the pin 7 is used by the Wifi shield (Handshake) and I have no other free digital pin.

-\> So, I tried to use an analog pin instead of the pin 7 and ..... it works very well.

Here is my final solution :

* Arduino Pin 2 -\> LCD Pin 4 (RS)
* Arduino Pin 3 -\> Keyboard IRQ
* Arduino Pin 4 -\> LCD Pin 11 (D4)
* Arduino Pin 5 -\> LCD Pin 12 (D5)
* Arduino Pin 6 -\> LCD Pin 13 (D6)
* Arduino Pin 7 -\>
* Arduino Pin 8 -\> LCD Pin 14 (D7)
* Arduino Pin 9 -\> Keyboard Data
* Arduino Pin 10 -\>
* Arduino Pin 11 -\>
* Arduino Pin 12 -\>
* Arduino Pin 13 -\>
* Arduino Pin 14 (= Analog 1) -\> LCD Pin 6 (E)

# Answer
> 1 votes
Sorry I do not have enough reputation to place a comment.

@Valentin from the link, you provided, to the wifi shield it states that it uses pins 11 ,12 and 13 on the UNO which will give you a conflict on pins 11 and 12 with the LCD. Not sure why that manifests as an apparent keyboard error though:

From the linked page:

> Arduino communicates with both the Wifi shield's processor and SD card using the SPI bus (through the ICSP header). This is on digital pins 11, 12, and 13 on the Uno and pins 50, \>51, and 52 on the Mega. On both boards, pin 10 is used to select the HDG204 and pin 4 for \>the SD card. These pins cannot be used for general I/O. On the Mega, the hardware SS pin, \>53, is not used to select either the HDG204 or the SD card, but it must be kept as an output or the SPI interface won't work.

Again sorry this is not a full answer but thought it may help.

# Answer
> 0 votes
You must verify which pins the wifi shield is using and see if they aren't used also by the LCD. Can you provide further details on the wifi shield ?

---
Tags: arduino-uno, wifi, lcd, display
---


title: Arduino + WizFi 210 (WiFi) HTTP POST

text:
# Question
Title: Arduino + WizFi 210 (WiFi) HTTP POST
I would like to do an HTTP POST to Carriots. I saw a few tutorials.

Both of them are using ethernet instead of WiFi. I realize the ways of using Arduino WiFi shield and WizFi Shield are a bit different. What do I need to do to run a basic server using the WizFi Shield?

Code:

```
/******************************************************************
 WizFiShield Web Client Test Example
*****************************************************************/

// WizFiShield communicates using SPI, so include the SPI library:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <SPI.h>
#include <WizFi2x0.h>
#include <WizFiClient.h>
#include <TimerOne.h>

#define SSID    "EricLeong3"        // SSID of your AP
#define Key     "ericChoong91"  // Key or Passphrase
// Wi-Fi security option (NO_SECURITY, WEP_SECURITY, WPA_SECURITY, WPA2PSK_SECURITY)
#define Security        WPA2PSK_SECURITY
#define APIKEY  "xxxxxxxxx" // Replace with your Carriots apikey
#define DEVICE  "fypSensors@eric3231559.eric3231559"

WizFi2x0Class myWizFi;
WizFiClient myClient;
TimeoutClass ConnectInterval;
boolean Wifi_setup = false;

///////////////////////////////
// 1msec Timer
void Timer1_ISR() {
  myWizFi.ReplyCheckTimer.CheckIsTimeout();
}
//
//////////////////////////////

void setup() {
  byte retval;
  Serial.begin(9600);
  Serial.println("\r\nSerial Init");
  // initalize WizFi2x0 module:
  myWizFi.begin();
  ConnectInterval.init();
  // Socket Creation with Server IP address and Server Port num
  myClient =  WizFiClient("82,223,244,60", 80);
  // Timer1 Initialize
  Timer1.initialize(1000); // 1msec
  Timer1.attachInterrupt(Timer1_ISR);
  myWizFi.SendSync();
  myWizFi.ReplyCheckTimer.TimerStart(3000);
  Serial.println("Send Sync data");
  while(1) {
    if(myWizFi.CheckSyncReply()) {
      myWizFi.ReplyCheckTimer.TimerStop();
      Serial.println("Rcvd Sync data");
      break;
    }
    if(myWizFi.ReplyCheckTimer.GetIsTimeout()) {
      Serial.println("Rcving Sync Timeout!!");
      // Nothing to do forever;
      for(;;)
      ;
    }
  }
  ////////////////////////////////////////////////////////////////////////////
  // AP association
  while(1) {
    retval = myWizFi.associate(SSID, Key, Security, true);
    if(retval == 1) {
      Serial.println("AP association Success");
      Wifi_setup = true;
      break;
    } else {
      Serial.println("AP association Failed");
    }
  }
}

void loop() {
  Serial.println("apleleee ");
  uint8_t retval;
  retval = myClient.connect();
  if(retval == 1) {
    String json = "{\"protocol\":\"v2\",\"device\":\""+String(DEVICE)+"\",\"at\":\"now\",\"data\":{\"Air Temperature\":\"58\",\"Humidity\":\"59\"}}";
    Serial.println("Connected! ");
    //myClient.write((byte *)"GET /search?q=WizFi210 HTTP/1.0\r\n\r\n");
    myClient.write((byte *)"POST /streams HTTP/1.1");
    myClient.write((byte *)"Host: api.carriots.com");
    myClient.write((byte *)"Accept: application/json");
    myClient.write((byte *)"User-Agent: Arduino-Carriots");
    myClient.write((byte *)"Content-Type: application/json");
    myClient.write((byte *)"carriots.apikey: ");
    myClient.write((byte *)APIKEY);
    myClient.write((byte *)"Content-Length: ");
    byte thisLength = json.length();
    myClient.write(thisLength);
    myClient.write((byte *)"Connection: close");
    myClient.write((byte *)"");
    myClient.write((byte *)"{\"protocol\":\"v2\",\"device\":\"");
    myClient.write((byte *)DEVICE);
    myClient.write((byte *)"\",\"at\":\"now\",\"data\":{\"Air Temperature\":");
    myClient.write((byte *)"58");
    myClient.write((byte *)",\"Humidity\":");
    myClient.write((byte *)"59");
    myClient.write((byte *)"}}");
  } else
    Serial.println("Connection Failed");
  }

```

The response I get on the serial monitor

```
Serial Init
Send Sync data
Rcvd Sync data
AT

Rcvd Reply: [ERROR]
[ERROR]
Timeout  with ERROR reply
AP association Failed
AT

Rcvd Reply: õAT
õAT
-1

Rcvd Reply: [ERROR: INVALID INPUT]
[ERROR
INVALID
INPUT]
-1

Rcvd Reply: AT
AT
-1

Rcvd Reply: [OK]
[OK]
ATE0

Rcvd Reply: ATE0
ATE0
-1

Rcvd Reply: [OK]
[OK]
AT+XDUM=0

Rcvd Reply: [OK]
[OK]
AT+BDATA=1

Rcvd Reply: [OK]
[OK]
AT+WD

Rcvd Reply: [OK]
[OK]
AT+WM=0

Rcvd Reply: [OK]
[OK]
AT+WPAPSK=EricLeong3,ericChoong91

Rcvd Reply: Computing PSK from SSID and PassPhrase...
Computing
PSK
from
SSID
and
PassPhrase...
-1

Rcvd Reply: [OK]
[OK]
AT+NDHCP=1

Rcvd Reply: [OK]
[OK]
AT+WA=EricLeong3

Rcvd Reply:     IP              SubNet         Gateway
    IP              SubNet         Gateway
IP
SubNet
Gateway

Rcvd Reply:  192.168.1.42: 255.255.255.0: 192.168.1.1
 192.168.1.42: 255.255.255.0: 192.168.1.1
192.168.1.42
192.168.1.42
255.255.255.0
255.255.255.0
192.168.1.1
192.168.1.1

Rcvd Reply: [OK]
[OK]
AP association Success
apleleee
AT+DNSLOOKUP=82,223,244,60,3,5

Rcvd Reply: [ERROR: INVALID INPUT]
Token: [ERROR

```

May I know what's wrong with the code? Why does it show a token error instead of success? What I am trying to do is posting an HTTP POST request to Carriots, which is a place to do my m2m things. I am still wondering which part I am missing. I referred to few sources such as

http://forum.carriots.com/index.php/topic/61-wireless-gardening-with-arduino-cc3000-wifi-modules/page-2

https://github.com/Wiznet/WizFiShield

# Answer
> 1 votes
The library provides an example for a server.

Here's what it looks like:

```
/******************************************************************
 WizFiShield Web Server Test Example

 A simple web server that shows "Hello World" string

 Circuit:
 WizFi2x0 connected to Arduino via SPI

 RST: pin 2  // Output
 DRDY: pin 3  // Input
 CSB: pin 4  // output
 MOSI: pin 11  // output
 MISO: pin 12  // input
 SCK: pin 13  // out

 Created 27 Sep. 2012
 by James YS Kim  (jameskim@wiznet.co.kr, javakys@gmail.com)

 Modified 27 May. 2013
 by Jinbuhm Kim  (jbkim@wiznet.co.kr, jinbuhm.kim@gmail.com)
*****************************************************************/

// WizFi210 communicates using SPI, so include the SPI library:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <SPI.h>
#include <WizFi2x0.h>
#include <WizFiClient.h>
#include <WizFiServer.h>
#include <TimerOne.h>

#define SSID    ""        // SSID of your AP
#define Key     ""  // Key or Passphrase
// Wi-Fi security option (NO_SECURITY, WEP_SECURITY, WPA_SECURITY, WPA2PSK_SECURITY)
//#define Security        WPA_SECURITY

#define MAX_SOCK_NUM    4

unsigned int SrcPort = 80;

WizFi2x0Class myWizFi;
WizFiClient myClient[MAX_SOCK_NUM];//(SIP, ServerPort);
WizFiServer myServer(SrcPort);

boolean Wifi_setup = false;

///////////////////////////////
// 1msec Timer
void Timer1_ISR()
{
  myWizFi.ReplyCheckTimer.CheckIsTimeout();
}
//
//////////////////////////////
void setup() {
  byte retval, i;

  Serial.begin(9600);
  Serial.println("\r\nSerial Init");

  for(i=0; i<MAX_SOCK_NUM; i++)
    myClient[i] =  WizFiClient();

  myWizFi.begin();

  // Timer1 Initialize
  Timer1.initialize(1000); // 1msec
  Timer1.attachInterrupt(Timer1_ISR);

  myWizFi.SendSync();
  myWizFi.ReplyCheckTimer.TimerStart(3000);

  Serial.println("Send Sync data");

  while(1)
  {
    if(myWizFi.CheckSyncReply())
    {
      myWizFi.ReplyCheckTimer.TimerStop();
      Serial.println("Rcvd Sync data");
      break;
    }
    if(myWizFi.ReplyCheckTimer.GetIsTimeout())
    {
      Serial.println("Rcving Sync Timeout!!");
      return;
    }
  }

  ////////////////////////////////////////////////////////////////////////////
  // AP association
  while(1)
  {
    byte tmpstr[32];

    retval = myWizFi.associate(SSID, Key, Security, true);

    if(retval == 1){
      myWizFi.GetSrcIPAddr(tmpstr);
      Serial.println("WizFi2xo AP Associated");
      Serial.print("MY IPAddress: ");
      Serial.println((char *)tmpstr);
      Wifi_setup = true;
      break;
    }else{
      Serial.println("AP association Failed");
    }
  }

  if(myServer.begin())
    Serial.println("Server Listen OK");
  else
    Serial.println("Server Listen Failed");
}

void loop()
{
  uint8_t retval, i;
  byte rcvdBuf[129];

  memset(rcvdBuf, 0, 129);

  if(Wifi_setup)
  {
    myWizFi.RcvPacket();
    for(i=0; i<MAX_SOCK_NUM; i++)
    {
      if(myClient[i].available()){
         retval = myClient[i].read(rcvdBuf);
         if(retval > 0)
         {
           Serial.print("CID[");
           Serial.print((char)myClient[i].GetCID());
           Serial.print("]");
           Serial.println((char *)rcvdBuf);

           if((rcvdBuf[retval - 1] == 0x0A) && (rcvdBuf[retval - 2] == 0x0D) && (rcvdBuf[retval - 3] == 0x0A) && (rcvdBuf[retval - 4] == 0x0D))
           {
             Serial.print("Receiving Completed");
             myClient[i].write((byte *)"HTTP/1.1 200 OK\r\n");
             myClient[i].write((byte *)"Content-Type: text/html\r\n");
             myClient[i].write((byte *)"\r\n");
             myClient[i].write((byte *)"Hello World !\r\n");

             delay(100);
             myClient[i].disconnect();
           }
         }
       }
    }
  }
}

```

Using the `WizFiServer` class, it seems to assign a `WizFiClient` instance to each HTTP socket connection. It can then call `clientName.write( /* Data to be sent to client */ );` and `clientName.read();` to get values.

Once it is done with the client, it can free up resources by calling `clientName.disconnect();`.

---
Tags: arduino-mega, wifi
---


# Question
Title: Is it wise to use analog input pins to read digital buttons?
I am thinking about building a circuit that is literally going to take 11 of the 14 digital pins of an `UNO` to communicate with an SD card and an external EEPROM chip (EEPROM programmer).

Using 4 shift registers and the SD card, I will have 1 digital pin left. Well, I'm also reserving pins 0/1 for serial communication.

Anyway, I need to read some external buttons and I have the 6 analog pins that I haven't touched.

I will only need about 4-5 push buttons in my design so they should fit nicely on A0+.

So, my question is, will I run into any issues doing this? Or, are the analog inputs better left for true analog reading?

Thanks.

# Answer
The Analog pins are essentially identical in functionality to digital pins when used as digital I/O.

If desired you could "be clever" and use an analog input in analog mode to read multiple keys using one pin. eg using 10k, 22k, 39k, 82k, 150k in series with 5 buttons from V+ to pin and a say 4k7 to ground would result in 5 voltages which were easily distinguished using an analog read. This is a very very old technique indeed and allows far more than 5 keys on one input pin. THere are limitations which can be discussed if required.

R1 ... R5 correspond to buttons 1...5

Vout = V+ x Rb / (Rb + Rbutton)

Example only

Rb = 39k
R1 = 10k
R2 = 22k
R3 = 39k
R4 = 82k
R5 = 150k

Gives

* The % of V+ in column 2 when a button is pressed.
* The voltage in column 3 with V+ = 5V

Delta-V is the difference between that key and the one below - very ample clearance.
> 8 votes

# Answer
If you have no use for analog pins there is no problem. A5/A6 are used for I²C (on the Uno).
> 2 votes

---
Tags: arduino-uno, analogread, digital
---


title: W5100 module hookup help - Not a shield

text:
# Question
Title: W5100 module hookup help - Not a shield
I recently purchased a W5100 based ethernet shield for my arduino Uno, and looks like this. I had been following the guide here, and connected the pins accordingly - 5V to 5V, GND to GND, MOSI to 11, MOSO to 12, SCK to 13, and SS to ten.

I booted up a default sketch (webServer, under Ethernet), and plugged in and ethernet cable. - PWR, LINK, SPD,and FDX all lit up, with Rx blinking for first 10 or so seconds. I then go to the IP specified on the arduino sketch, and nada. Also, my router doesn't show the shield under the attached devices.

Therefore, I figure it's a problem with my connections. Can anyone help me? Googling has only brought my lots of info about shields, and little info on these modules.

# Answer
> 2 votes
First, if you cannot connect to arduino by ethernet, use Serial Monitor and add some Serial.println to your code to log what is going - what part of program Arduino is executing.

W5100 module has no automatic reset module as opposed to Ethernet shield. So try to connect W5100 RST pin to for example D8 and reset module in setup.

Here you are example from my (working) project:

```
const int W5100_RESET_PIN = 8;

void setup() {
  Serial.begin(SERIAL_SPEED);
  Serial.println();
  Serial.println(F("node starting..."));
  pinMode(W5100_RESET_PIN, OUTPUT);
  digitalWrite(W5100_RESET_PIN, LOW);
  delay(100);
  digitalWrite(W5100_RESET_PIN, HIGH);
  // give the Ethernet shield a second to initialize:
  delay(3000);
#ifdef USE_DHCP
  Serial.println(F("DHCP..."));
  while (Ethernet.begin(mac) == 0) {
    Serial.println(F("DHCP failed."));
    delay(10000);
  }
#else
  Serial.print(F("static IP..."));
  Ethernet.begin(mac, IPAddress(MY_IP));
#endif
  Serial.print(F("local IP:"));
  Serial.println(Ethernet.localIP());
  Serial.println(F("node started."));
}

```

Also after setup if your arduino lost ethernet connection and cannot get it again, you can try to reset w5100 and initialize Ethernet again.

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


# Question
Title: Is Arduino IDE enough to program with C or C++?
I am using Arduino IDE to program my ATmegas with bootloaders. I can directly manipulate ports, use timers, interrupts, PWM pins and timers, etc. Everything is working.

But this question arises: Does the Arduino IDE differ from AVR Studio in terms of using C or C++ on an ATmega chip?

I know AVR Studio has some features or something. My question is not about that. My question is that I am coding everything, not using extra libraries, features etc.

# Answer
In terms of the core language features, there's virtually no difference. In the background, the Arduino IDE and Atmel/AVR Studio both use GCC to compile the code.

GCC is an excellent toolset which supports all the core language features of C++. Admittedly, the version which currently comes with the Arduino IDE is a little old, so it doesn't support C++11 onwards. However, a lot of C++11 features are not very relevant or useful for microcontroller programming anyway (e.g. threading).

You're also likely to use the same standard library for both, which is AVR Libc. It provides pretty much all the standard C functionality that you're likely to use in an AVR project. It doesn't include the C++ stuff though, such as streams, containers, and algorithms. These tend to be very resource-hungry though, so are best avoided anyway.

The major difference is basically flexibility. Atmel/AVR Studio is designed to let you work on a wide range of projects and customize the build to suit very specific needs. You can also use alternative libraries with it more easily. In theory, the Arduino IDE can be modified in similar ways, but it's a major hassle because it provides no GUI to do it.

It's also important to note that the Arduino IDE does a number of non-standard things, such as re-organising declarations and including libraries in strange ways. It's designed to be more user-friendly, but often ends up just getting in the way. There are usually ways to work around those issues though.
> 11 votes

# Answer
It is unclear exactly what you are asking. The Arduino is different to most computers - it has NO OS (if you exclude the bootloader).

You can use a c/c++ compiler which translates your code to machine code. If you include libraries this may include machine code which someone else has compiled into a library.

You could write 100% of your code in assembler and produce exactly the same result. Even in the good (bad?) old days of the 1970s before we had compilers on microprocessors it was common to have prewritten code (libraries) for common functions.

You haven't lived until you have written your own assembler (hand coded).
> -1 votes

---
Tags: arduino-ide, c, avr
---


# Question
Title: How to "implement" an Arduino prototype?
I am starting with Arduinos, coming from the world of Linux (with the RPi as a bridge) and after having tested some setups I now wonder where to go next in implementation.

What I am trying to understand is whether it is recommended (time and cost-wise)

* to create a standalone, circuit-board based version of whatever I prototyped on the breadboard, with a micro-controller with connections trimmed down to what is needed for that specific setup?
* or rather just look at neatly packaging the Arduiono with the breadboard and wires in a case?

I expect to build 5 or 6 of the same simple setups (to put in various places in my house).

Note: there is a similar question (with almost the same title) but it deals with the legal aspects of commercializing a setup.

# Answer
> 1 votes
> with the breadboard

That phrase right there makes the solution a non-starter. Solderless breadboards are good for prototyping, but are too fragile for use in a final project.

As for whether or not you should use an actual Arduino or reduce the circuit to a minimum, that is between you and your wallet. It is possible to make a basic AVR board (including MCU) for under $6 in parts, but the time investment is not entirely trivial.

# Answer
> 1 votes
I started using an Arduino (Uno), and a solderless breadboard, to do my prototyping.

After the 2nd project, I started programming the Arduino, then pulling the AtMega chip off the board (if you have a through-hole chip rather than a surface mount one) and plugging that into my breadboard (you will need some supporting circuitry for this - a clock and a powersupply e.g. batteries). The AtMega has a larger range of voltages than the Arduino, and can be run up to 20mhz. You will need to jiggle some constants for this, or be ready for your delays to run quicker too.

I have since bought an USBISP (see Google), which can be hooked up to the Arduino board (there is a 6 pin header made for this, on the opposite side to the USB), or can be hooked up to specific pins. With this, I have started programming AtTiny chips - smaller, easier to set up, fewer pins to interface with, and really, really cheap!

All my long-term projects are on veroboard (see Google) - solder everything on, then cut it to the size you need. It's worth spending time before you solder working out your layout.

If you want to produce these in bulk, I would suggest getting some prototypes on veroboard first (you will, invariably, make changes once you start testing!), then when you're happy, you can copy the veroboard design (possibly tweaking it to optimize for greater flexibility), and order PCBs from a company that does this sort of thing.

Good luck!

# Answer
> 0 votes
> What I am trying to understand is whether it is recommended (time and cost-wise) to create a standalone, circuit-board based version of whatever I prototyped on the breadboard, with a micro-controller with connections trimmed down to what is needed for that specific setup? or rather just look at neatly packaging the Arduiono with the breadboard and wires in a case?

Given what is available in assembled form, using a complete commercial product per project would make most sense except where you are building in substantial volume.

Because ...

I am using Arduino Nano 3s from China which cost me $US3 each in quantities of 10 with free postage (takes 2 to 3 weeks to arrive here at the bottom of the world) and I see that the same people are now charging $2.85 each in 10's. There are numerous suppliers of similar products and I am only mentioning these as I have had good results from them and the quality is acceptable.

You would probably have trouble buying just the parts for the cost of a $3 assembled working Nano and you'd need to cost your time at $0/hour. Building your own for the experience, or if you are using many and you want a cut down subset and really must get the price well under $3 MAY make sense.

The same people also sell an **Arduino Pro mini** for $US1.85 in 10s free postage (ie $18.50 for TEN). You need to use a plug in USB module to program these via USB. I bought some of these as well - also good, but the convenience of the always available USB makes the Nano preferable (to me).

Note: USB cables cost extra !!! :-)

---

**Related:**

Some people have expressed reservations about buying Asian source Arduinos and suggest people should support either US fronted companies or the Arduino's originators.

I appreciate the merit of supporting the people who have put the effort into the system, but the system is very very consciously open source in all respects - and in fact code samples that come with the IDE are expressly Public Domain. (Documentation is CC by SA ...). If open source is to be truly meaningful it needs to be able to survive being truly so. Unlike many other products where Asian copies may have suspect IP legacies, the Arduino products are wholly legitimate (as far as I know).

I have not pored over them in detail (yet) but I note that the 5V voltage regulator on the Chinese ones is an LM1117 (LDO LM317-like) as opposed to the original LM2940. The USB bridge ICs are, as is well known, not "genuine" FTDI parts but Asian semi-equivalents which, with their own drivers, work well enough in this context.

You can certainly buy low cost rubbish versions from Asian sources, and part of the open source tradeoff is deciding where you do and don't get value for money overall.

---
Tags: prototype
---


# Question
Title: Arduino board not recognized by Linux (dmesg, lsusb, etc.)
I just received my first Arduino board which is essentially a Leonardo (ATmega32U4) customized to include a NFC reader (PN532).

When I plug it in, the PWR LED comes on steady, the D13 LED flashes a few times, and then the STA LED blinks once and only the PWR LED is left on. I can upload a basic sketch to the correct Serial Port, but the Serial Monitor is always empty.

I have noticed that, when uploading the sketch, the RX/TX LEDs stay off (which I thought was a sign of uploading/downloading data). I figured this was the root of my issue so I tried to look into it further. Running `lsusb` does not find the device and `dmesg` does not show any information when (un)plugging the device.

I also tried on a Windows install, but couldn't install the Leonardo drivers since Device Manager wouldn't register any unknown USB/Arduino devices.

Do you think my board is dead on arrival or am I doing something wrong?

---

**Update:**

I just uploaded the Blink tutorial sketch and it uploaded "successfully" but I noticed no differences. Please note that I don't have an external LED attached, but am looking at the board's LED on pin 13. This pin already flashes a few times (as mentioned above) on a reset, so I modified the delay times and still noticed no change.

I am uploading using board Leonardo, as recommended for my hardware, and the serial port /dev/ttyS0. I thought this was the right port because I remember not seeing it at first, but on second thought I had a permission issue at first (which is now resolved) causing me to not see the port.

*So it looks like my board is* ***not*** *detected by my computer and I'm successfully uploading sketches to a meaningless port.* Any troubleshooting options for me? I've tried different USB ports and am, as of recently, plugging my board into external power (9V). The only thing I can think of that on my end is that I'm using a Y-cable for my USB connection (I have a normal Mini-USB coming tomorrow via Amazon) since it is all I had. I can also confirm that this USB connection ***does*** power the board when plugged in.

# Answer
So, to summarise the comments trail; the blinking lights at power-up are the normal boot sequence for the Leonardo, indicating the processor is good, and that power is reaching the board; the device seen should be /dev/ttyACM0 or some other number; dmesg wasn't recording a plug-in event as the cable was not good.

We still don't quite know why the IDE thought it had sent a program to /dev/ttyS0, but presumably the level of interaction is much less (ie, none) via RS232 serial? Which explains why it said it had uploaded a test program when, in fact, it hadn't!

And replacing the USB cable has solved the problem - excellent news!
> 1 votes

---
Tags: arduino-leonardo, uploading
---


# Question
Title: Can I program AVR Microcontrollers using Arduino Development board with AVR Studio?
I know and I can program any AVR microcontroller with Arduino IDE and Arduino Uno board. Can I use Arduino board with AVR Studio? Or I have to buy an AVR Development board?

# Answer
You can use Atmel Studio to write code for the MCU(s) on the Arduino boards. If the IDE itself does not support *uploading* the code to the Arduino then it is still possible to use AVRDUDE or BOSSA to upload it via the command line.
> 4 votes

# Answer
There is an Arduino plugin available for AVR Studio, which allows you to upload sketches to an Arduino, just like you would with the Arduino IDE. I think this also enables you to upload plain C/C++ files created with the standard AVR tools.

Alternatively, if you have an AVR ISP programmer, you can use this to upload compiled C/C++ to the Arduino from AVR studio without needing the Arduino plugin.
> 1 votes

---
Tags: arduino-uno, avr, atmel-studio
---


title: Arduino LCD Display drawing image issue

text:
# Question
Title: Arduino LCD Display drawing image issue
I am playing with 3,5" (400x240) TFT display which is placed into Arduino Mega 2560 R3 board.

My final *goal* is taking .raw data from SD card and drawing it on display.

What I have done so far:

**-** My **drawing** method in the sketch:

```
void LoadImage(File& file)
{
    for (int y = 0; y < SCREEN_HEIGHT && file.available(); y++) {
        uint16_t buf[SCREEN_WIDTH];
        for (int x = SCREEN_WIDTH - 1; x >= 0; x--) {
            byte l = file.read();
            byte h = file.read();
            buf[x] = ((uint16_t)h << 8) | l;
        }
        myGLCD.drawPixelLine(0, y, SCREEN_WIDTH, buf);
    }
}

```

**-** For reference **drawPixelLine** method's implementation from UTFT library:

```
void UTFT::drawPixelLine(int x, int y, int sx, uint16_t* data)
{
    unsigned int col;
    cbi(P_CS, B_CS);
    setXY(x, y, x+sx-1, y);
    for (int tc=0; tc<sx; tc++)
    {
        char* p = (char*)&data[tc];
        LCD_Write_DATA(*(p + 1), *p);
    }
    sbi(P_CS, B_CS);
}
void UTFT::setXY(word x1, word y1, word x2, word y2)
{
    if (orient==LANDSCAPE)
    {
        swap(word, x1, y1);
        swap(word, x2, y2)
        y1=disp_y_size-y1;
        y2=disp_y_size-y2;
        swap(word, y1, y2)
    }
        LCD_Write_COM(0x2a);
        LCD_Write_DATA(x1>>8);
        LCD_Write_DATA(x1);
        LCD_Write_DATA(x2>>8);
        LCD_Write_DATA(x2);
        LCD_Write_COM(0x2b);
        LCD_Write_DATA(y1>>8);
        LCD_Write_DATA(y1);
        LCD_Write_DATA(y2>>8);
        LCD_Write_DATA(y2);
        LCD_Write_COM(0x2c);
}

```

*My current rendering:*

*Desired image:*

*TFT Lcd and Mega Board*

**UPDATE1**

I ran henningan test from utft library, drawing sin/cos graph and simple squares

Here is attempt to render yellow square 100x100 raw data

# Answer
> 1 votes
I'have the same LCD from mcufriend and it doesn't work with original UTFT library.

Try modified version from https://github.com/dgolda/UTFT and use:

```
myGLCD(NIC35WS,38,39,40,41); //3.5" TFTLCD for arduino 2560 from mcufriend.com

```

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


# Question
Title: Arduino Nano -- cannot download, no /dev/tty*** device
It appears to me that each Arduino has (should have?) a unique /dev/tty...USB... number assigned. Why this isn't explained anywhere (that I can find) is a mystery. When I plug my problem Nano into a USB port on my iMac no /dev/tty... for it appears. It used to work. Have I fried it? Can this be fixed?

# Answer
> 1 votes
This is probably a duplicate question and duplicate answer, but ...

Flip the board over, look at the bottom. If it says "FTDI" then this answer doesn't apply. But many cheap clones have moved to the CH340G chip for USB serial communication, it's a tenth of the cost with a tenth of the (unused) features.

You can find CH340/341 drivers from the manufacturer at WCH.CN or linked at the bottom of this post.

Or, skip the USB altogether and search for "ISP" on Tindie and grab a USBASP or TinyISP programmer.

---
Tags: serial
---


title: Programming an Array of ATTiny

text:
# Question
Title: Programming an Array of ATTiny
I am designing a board for my electronics project and i am using a number of ATTiny85 for it. The ATTiny's will be SMD so i will not be able to remove them for programming.

Moreover all of the pins of my uCs will be used for connections (apart from reset).

Is it possible in this case to achieve that, any ideas and suggestions are welcome

EDIT: Well, Vcc and Ground will be common, i will be using an external oscillator for all of them, the reset pin will be free, the other three pins will be used for gpio communication between the attinys. I am connecting about 10 attiny in a daisy chain kind of thing

# Answer
> 3 votes
As long as whatever you're connecting the MISO, MOSI, and SCK pins to doesn't mind being driven externally, you can still program the ATTiny in-circuit - just break out those pins with reset to a standard 6 pin header and program them that way.

If one or more of those pins can't be driven externally (eg, because they're connected to another device that drives them and has no output disable), you'll need to add a tristate buffer IC between the MCU and the other device, or some jumpers you can remove when you want to program them.

# Answer
> -1 votes
Well you need access to pins 0 & 1 to program them, so you either do it off-board, or design in a way to access them - perhaps a PCB hole you can wire to temporarily, or a link you can fit/remove that changes the connection.

You will probably need to program them before the rest of the board gets filled up?

You havn't said what you will be connecting to these pins nor how many is an "array" which kind of limits how specific we can be here!

---
Tags: programming, attiny, system-design
---


title: Chain of, or one big if sentence

text:
# Question
Title: Chain of, or one big if sentence
(This might be more of a common C question)

I want to test several conditions in an IF-sentence

```
if(variable) {            // fastest check
  if(register) {          // a bit slower
    if(read_peripheral) { // very slow check
      // [do something]
    }
  }
}

```

It seems obvious that I want to start with the fastest check, and move on to the slower ones afterwards, potentially avoiding to check them if the above was false.

Now since I need to check quite a few conditions, I'd like to know if the following is the same, or if all conditions will be evaluated prior to making a decision?

```
if(variable && register && read_peripheral) {
  // [do something]
}

```

# Answer
Putting them all in a single condition like that is absolutely fine. C/C++ uses "short circuit evaluation" which means it will stop as soon as it's determined the outcome. If everything is combined using logical AND operators (&&) then that means it will stop as soon as one of them evaluates to false.

For example:

```
 if (blah() && foo()) { ... }

```

If `blah()` returns false, it will never call `foo()` at all because it already knows the overall outcome is false.

The reverse happens with the logical OR operator (||):

```
 if (blah() || foo()) { ... }

```

If `blah()` returns *true* in this case, it won't call `foo()`. That's because it already knows the overall outcome is true.
> 8 votes

---
Tags: c
---


# Question
Title: 3.5" TFT LCD Display is not working with Arduino Mega 2560 R3
Even I can't do similarly with my 2.4" TFT LCD in here still: 2.4" TFT LCD Shield isn't working on Arduino Mega

Now, I have bought 3.5" TFT LCD display for my Arduino Mega 2560 R3 to try whether I could run the screen or not, and it is not working now! I am so depressed and angry for these two's misbehaviors. I have already checked website and a lot of Arduino IDE code examples and libraries such as UTFT.h, UTouch.h, UTFT\_MEGA, UTFT\_CTE, TFTLCD. I tried these and I can not run my 3.5" screen. Where am I faulty? There is something below the screen shield: www.mcufriend.com and 3.5" TFTLCD for Arduino 2560. Are there any basic code or have anyone tried to run Mcufriend's displays correctly?

# Answer
http://www.henningkarlsen.com/electronics/library.php?id=51

Download hennings new UTFT library.

in myGLCD define R61581 as this is the driver chip for 3.5 display.

Regards!
> 1 votes

# Answer
Try this code:

https://www.dropbox.com/s/fce43rxofttl001/Librer%C3%ADas%20UTFT%20%2B%20UTouch%20para%203.5%20TFTLCD%20para%20Arduino%20Mega%202560%20%20-%20copia.rar

First delete the old UTFT library, then copy and paste the library inside de RAR file.
> 0 votes

# Answer
This might be a silly suggestion, but the mega2560 is 5v, and the display is 3.3v...and you need an interface board between. I have successfully run a 3.2" display using this interface board

http://www.elecfreaks.com/store/lcd-tft01-arduino-shield-v20-shd09-p-213.html

Hope this helps
> 0 votes

# Answer
I have the same lcd shield from mcufriend. It has ILI9327 in 8 bit mode.

This shield doesn't work with original UTFT library (it supports only 16-bit mode).

Try modified version from https://github.com/dgolda/UTFT and use:

```
myGLCD(NIC35WS,38,39,40,41); //3.5" TFTLCD for arduino 2560 from mcufriend.com

```
> 0 votes

---
Tags: arduino-mega, shields, lcd, display
---


# Question
Title: What are the environmental requirements of an Arduino?
I'd like to use an Arduino Yún in a somewhat outdoor environment (in a metal box on a truck). I think I've seen that the temperature requirements of the Uno are -40 °C to +85 °C, but I can't find that information about the Yún. It would be nice to know where to find information about the temperature and humidity safe working requirements for every Arduino model.

# Answer
> 2 votes
The AtMega32u4 (the chip that drives the Arduino Yun) has an operating requirement of -40 to +85, so if you go outside that range, you will definitely void warranty (which is not to say it will break, of course!). See datasheet at http://www.atmel.com/devices/atmega32u4.aspx

A datasheet for the AR9331 seems to say that it only works down to 0°C ( http://www.eeboard.com/wp-content/uploads/downloads/2013/08/AR9331.pdf page 305, "Commercial Case Temperature") - this seems awfully high for a minimum temperature.

While that does not mean that, inside that range, you are safe, I would *GUESS* that you probably are - I would guess that the AtMega32u4 or AR9331 is going to be the most delicate part in there.

Of course, to get a definitive answer, you (or someone) would have to check the specs on each part.

---
Tags: arduino-yun, hardware
---


title: Adafruit CC3000 jumper pads

text:
# Question
Title: Adafruit CC3000 jumper pads
if I solder the jumper pads on the adafruit cc3000 for use with the Arduino Mega will it still work fine with the Uno?

# Answer
> 1 votes
**This module is designed to be "plug in and go"** without access to anything except the connector pads at the board edge. While there are a number of pads on the face of the board these are for "experts only" access and are unneeded for normal operation.

The only soldering required should be the addition of a 9 pin row of pins to allow the CC3000 module to be plugged into a solderless breadboard or a socket. If this is all you do then the module will work directly and interchangeably with Arduino Uno, Leonardo/Micro & Mega. These are the only Arduino versions that a full library is available for so far. ADAFruit promise more versions will be supported "sometime".

Additional information is available from
WIRELESS / WIFI / ADAFRUIT HUZZAH CC3000 WIFI BREAKOUT WITH ONBOARD ANTENNA

Solder on connector and go ...

**Larger version of photo here** makes pin use clear - + see link above

---

Example use **weather station**

**Low power use tutorial**

Example use **wireless lamp**

**Library**

---
Tags: arduino-uno, arduino-mega
---


# Question
Title: I am looking for the source and/or proper definition for the int() function
I am looking for the source and/or proper definition for the int() function. I have searched through the source in Arduino.app, without much success.

The reference gives a terse explanation

```
int(x)
 x: a value of any type
 Converts a value to the int data type

```

Passing 1, '1' or 49 returns the int 1. I haven't tested other types.

This seems to be an Arduino specific function - it doesn't seem to be in any c/c++ library.

# Answer
`int(x)` is not a function but **another way to perform an explicit cast** of `x` to an `int`. It is part of the C++ language itself, that is why you could not find it in a library.

This is not Arduino-specific.

In C and C++ you can cast a value to an int by doing this:

```
int y = (int) x;

```

**C++** has extended this notation by allowing to do it this way, which is equivalent:

```
int y = int(x);

```

You can find this in more details in C++ language reference.
> 2 votes

---
Tags: c++
---


title: Smaller version of the Mega

text:
# Question
Title: Smaller version of the Mega
I'm currently working on a Arduino Mega (GPS + IMU + SD card logging + BT). I need the Mega for extra memory and serial port. I would like to transition to something with a smaller form factor now. I need help with suggestions for a smaller form factor board/version of Mega.

Any suggestions? I can't really find anything.

The only small size yet meeting requirements (in terms of memory) option seems to be a Microduino \- but I'm not whether all the libraries (SDfat etc.) will work on this.

# Answer
> 1 votes
The ATmega1284P provides 128kB of flash, 16kB of SRAM, 4kB of EEPROM, and 2 USARTs in a 40/44/49-pin package. Mighty 1284P provides Arduino support for the '1284P.

There aren't too many actual boards that feature it, but it can be used very easily on a breadboard or custom PCB with a programmer.

# Answer
> 0 votes
The link uses the same chip that Ignacio recommended. The libraries will need some minor edits, but many of the standard ones do have a 1284P fork. It is mostly just redoing pin assignments, or adding the 1284P to the board definitions. I am working on a similar project and have gotten the 1284P to work with SDfat, a bunch of standard GPS libraries, and TinyGPS++ .

# Answer
> 0 votes
Look for "Mega2560-CORE" on ebay.

Some information: http://www.inhaos.com/product\_info.php?products\_id=88

---
Tags: arduino-mega
---


# Question
Title: Getting sensor data wirelessly from arduino to PC
I am working on a project that involves sending motion sensing data wirelessly from an arduino to computer. Sensor readings have to be transmitted continuously (say every mili second). I am not sure if Xbee is my bet. I came across this link which suggest s that there should be atleast 10 ms delay between packets if you're using xbees.

What are your experiences with xbees? I don't want to waste money.

# Answer
> 1 votes
Xbee costs about 1000INR. They are really expensive. You should buy HC-05 module, which costs about 320INR. You can easily interface them with Bluetooth of your Laptop using Processing Application.

You can even use ESP8266 ESP-01 Wireless Module. They Cost about 3$. Wireless module gets connected with your router. this tutorial will help you to start. You can by this module from here.

nRF24l01+ modules can not be interfaced with Laptop...

---
Tags: serial, xbee
---


title: Connecting Nokia 106 to Arduino

text:
# Question
Title: Connecting Nokia 106 to Arduino
I was wondering if this can be done. I got a Nokia 106 and am trying to make it talk, but the audio jack doesn't seem to cooperate and the Fbus pins are right under the SIM slot, which is right under the battery. Any advice?

Added: It seems that it talks AT commands, since it is a GSM model, but I'm not 100% positive.

# Answer
Here's the picture of the Nokia FBUS connector from your link:

And here's a (slightly dubious) method of connection from some random web page

which goes on to say

> The F-bus protocol uses 115,200bps so we can easily use the Arduino’s serial function to communication with the phone. All you need to is hook up the phones TX to the Arduino’s RX and then use a resistor divider (I choose 330 ohm resistors) to connect the Arduino’s TX to the phones RX as shown above.

That page goes on to show how to use an Arduino to get the phone to send SMS text messages.

Sources:
> 2 votes

# Answer
just trim the actual simcard, so its level with 'microsim insert' back edge. Its what i did on my Nokia 100/GPO 746 project, works fine, wont kill the phone
> -1 votes

---
Tags: serial
---


# Question
Title: CC3000 - Send GET request to an app on heroku
I'm struggling to get the CC3000 to connect to a heroku hosted app, and other examples posted online haven't turned on the light bulb quite yet for me.

The gist is that I collect some temperature and humidity readings, and then send those via a GET request using the CC3000. The heroku app then reads the parameters and displays them on a page.

The CC3000 hardware is A-OK, as I've tested it using the test sketches. The sketch I've put together (on github: https://github.com/jsimms/compost\_monitor) works except for the last bit where it needs to connect to the server and send the HTTP request. Which makes me wonder if this is a heroku quirk, or if I'm just screwing something up right at the finish line.

First, I define everything

```
#define WEBSITE      "myapp.herokuapp.com"
String route = "/sensor";
uint32_t ip;
int port = 80;

```

Then during setup, I use getHostByName to assign the ip variable. I print it out, just to confirm it was able to snag an ip. I then close it to make sure I don't screw up anything during the loop.

```
  ip = 0;
  Serial.print(WEBSITE); Serial.print(F(" -> "));
  while (ip == 0) {
    if (! cc3000.getHostByName(WEBSITE, &ip)) {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
  }

  cc3000.printIPdotsRev(ip);
  Serial.println("");

  // Close the connection
  Serial.println(F("Closing connection..."));
  cc3000.disconnect();
  Serial.println(F("Connection closed."));

```

During the loop, I create a String with the request, and then call a function that actually does the request.

```
String request = "GET " + route + "?temp=" + temperature + "&hum=" + humidity + " HTTP/1.0\r\n";
send_request(request);

```

Finally, the send\_request function is supposed to take care of connecting via TCP and sending it.

```
void send_request (String request)
{
  // Connect to server
  Serial.println("Connecting to server...");
  Adafruit_CC3000_Client www = cc3000.connectTCP(ip, port);

  // Send the request
  if (www.connected()) {
      www.println(request);
      www.println(F("User-agent: CompostMonitor/1.0\r\n"));
      www.println(F("\r\n"));
      Serial.println("Connected & data sent successfully...");
    }
    else {
      Serial.println(F("Connection failed."));
    }

    while (www.connected()) {
      while (www.available()) {

      // Read answer
      char c = www.read();
      Serial.println(c);
      }
    }

  // Disconnect
  Serial.println("Closing connection...");
  Serial.println("");
  www.close();
}

```

However, I never get anything but connection failed.

Any insight and help would be wonderfully appreciated. :)

UPDATE: Ok. So, through the comments below, I was able to identify by telnet'ing the web app, that there was something wrong with the HTTP requests. I made a small tweak to the app, but the real issue was that I wasn't including Host: weathervane.herokuapp.com in the header. FML! I'm going to test out sending the request with the Arduino later tonight. Hopefully that puts an end to this HTTP 101 lesson I've been doing.

# Answer
> 2 votes
Have a look at this code: https://github.com/adafruit/Adafruit\_CC3000\_Library/blob/master/examples/SendTweet/SendTweet.ino

There is a delay after `cc3000.connectTCP` to wait for connection. Your code does not wait for the connection and thus gives 'connection failed' straight away.

```
Serial.print(F("OK\r\nConnecting to server..."));
t = millis();
do {
    client = cc3000.connectTCP(ip, 80);
} while((!client.connected()) &&
    ((millis() - t) < connectTimeout));

if(client.connected()) { // Success!

etc

```

Edit based on comment:

getHostByName returns positive value on success and negative on failure. Therefore the check should be

```
if (cc3000.getHostByName(WEBSITE, &ip) < 0)

```

Also try putting `http://` in the website address

# Answer
> 0 votes
```
www.println(request);
www.println(F("User-agent: CompostMonitor/1.0\r\n"));
www.println(F("\r\n"));

```

Both `request` and the other two strings end with `\r\n`. You also use `println()`, which adds `\r\n` of itself. This means that you end every line with two CRLF sequences, which is not correct according to the HTTP standard (Sec 2.2, Basic Rules).

Instead, use `print()` which doesn't add anything, or don't add `\r\n` to the strings yourself.

Servers may not complain about this but your code is not conform the standard and may not work on all servers / may stop working after a server update. It's also possible that some of the header fields are not being considered by the server because it treats them as body instead of headers.

---

Besides that, you should considering use HTTP 1.1. There's no hard reason to change *now*, but it's newer, includes more features, is supported by (almost) all server software, and will still work even when (*if*) servers decide to start phasing out HTTP 1.0 support. You then need to change `1.0` to `1.1` in the `request` string, and after that specify the Host field explicitly:

```
www.println("Host: myapp.herokuapp.com");

```

---
Tags: arduino-uno
---


title: Pressure Sensor and Arduino

text:
# Question
Title: Pressure Sensor and Arduino
I am currently working on reading pressure values using a tekscan a201 sensor. The sensors I have are limited to 25lbs.

My plan is to use eight on these sensors of them with a arduino Mega. Since I am measuring the resistance, I am thinking of making a 8 similar voltage divider circuits and grabbing the voltage reading via arduinos analog pins.

At the moment, I am not sure how to convert these readings to engineering units. Any ideas?

# Answer
> 1 votes
I have not previously met the Flexscan sensors but from the datasheet it appears that there are versions of the A201 rated at 100 pounds are you committed to the 25 lbf version?

**A201 datasheet here**

Here is a **15 page user manual** thatexplains how to produce a voltage output using a single opamp per sensor - bottom of page 9.

Many idea starters **here**

---

What is your application and why do you wish to use these sensors. These seem to be a low accuracy alternative to eg load cells and seem to be expensive for what you get. If you need 8 for your task a loadcell based solution may e cheaper.

# Answer
> 0 votes
I decided go with the voltage divider approach as it seemed simple enough. The sensors themselves needed to be calibrated, which took me a while as I didn't have the required weights.

After the calibration, I used the line of best fit approach to find an equation that translated voltage to force.

---
Tags: arduino-mega
---


# Question
Title: Good way to get automatically generated code into a sketch
Situation:

Mac OS, Arduino IDE 1.5.6r2

I've got a sketch with several files, all classic .cpp and .h source and header files except the main sketch file. As the project goes more complex I started to generate code automatically by another program. Now I have hard times integrating the generated code it into my sketch. The arduino IDE seems to load the code on opening the sketch. After that, the source files aren't beeing checked for external changes by the IDE (as I would expect it from a real editor like *vim*). On top of that, when I verify my code the IDE seems to save the files from RAM into a temporary build directory ignoring the contents of the sketch directory further. So if I let my code generator change a source file while the sketch is opened in the IDE, the changes won't reach the build. I had to close the IDE and reopen it. The next thing I tried is to include my autogenerated file from an existing and opened code file inside the IDE. But the IDE ignores files, which aren't opened completely. Hence, the file is missing in the build directory.

Is there a trick to let the IDE take the code unknown to itself along into the build directory? Or how else can I deal with this situation? I don't want to close and open the IDE a hundred times a day.

# Answer
According to the release notes starting with V1.5.2 of the IDE you can verify and upload from the command line.

You could use your favorite editor and then use the command line to do the arduino build/upload instead of the IDE.

See: https://github.com/arduino/Arduino/blob/ide-1.5.x/build/shared/manpage.adoc

I have not used it so I can't say if it work well or not.
> 2 votes

---
Tags: arduino-ide, build
---


# Question
Title: Can the official arduino GSM shield library be changed to work with hardware serial on mega
I have a complex requirement that uses a number of libraries that depend on timing I.e. OneWire. When using the official GSM shield on a mega, it loads a version of software serial to talk to the GSM. I want to make it use a spare hardware serial port on the MEGA for more timing stability. How should I modify the GSM library to (optionally) auto detect a MEGA and then use a nominated serial port. I am happy to jumper the correct pins from the mega serial hardware port to the bent outwards pins 2 and 3 of the GSM shield ( pin 2 is already bent out if you use a MEGA anyway).

# Answer
Before we start, note that it might not be the right pinout for the GSM shield to use a hardware serial port on the Mega. Beware of some nasty wiring.

Poking around on Github, I found this is the directory for the GSM library. Ladies and gentlemen, it's time to break something important get our hands dirty! Draw your chairs close for a tale of touching code you shouldn't touch!

Click on the `src` folder to open it up. When I first opened this up, I was somewhat scared by the number of files. However, I had a plan:

1. Find the name of the SoftwareSerial instance. I'm guessing that they would use only one object to do this to prevent redundancy. In addition, I'm going to guess that most serial data is handles though a single file, but I'll have to confirm this.
2. Remove instances of the SoftwareSerial Object.
3. Clean up any remaining issues with the "port"

After more poking around, I noticed that the library actually uses a unique version of the SoftwareSerial library, so it will be even *harder* to do this. Yay us! On the upside, we know exactly what code to replace. Fasten your seatbelts, this is about to get pretty nasty.

Okay, take a step back here and figure out *what* we want to modify. First of all, it's a *terrible* idea to modify the libraries directly in the directory that the Arduino IDE uses.

So, if you were to make a copy from the `src` folder for the GSM library into the Arduino "libraries" folder, it wouldn't be enough. The Arduino IDE would get confused when there would be two identical header files to use. You will need to rename the *main header file* and use just that one instead to include into your projects. In addition, most of the files in the library probably reference that file, so make sure to rename any references within the library to that one file. A quick CTRL + SHIFT + F on the Atom text editor will search the entire project I'm working on. I'm not entirely sure if a folder name would mess up the Arduino IDE, but it'd be a good idea to rename the folder to whatever your library is called, at least for readability purposes.

Before we continue, let's make sure that the library still compiles without us playing with the code. Import the new library into a basic GSM example sketch and see if it compiles and works normally.

It compiles? Great. Let's go on!

The file that does serial is the `GSM3SoftSerial.cpp` file. Without actually porting it, I can't give you a ton of advice here. Look through and see when variables are created, used, and modified. If you're not sure, I'm in chat sometimes: feel free to ask there on minor questions and ping me with @AnnonomusPenguin or leave a comment on this post.

I'd also advise to leave everything in there that you're not sure of, make sure it works with hardware serial, and line by line start removing that variable and see if anything breaks. A great too for this would be to use a tool like Git/Github (or other version control software) to help you revert changes that broke something or to see, overall, what you've changed.

So, after replacing the code inside the functions (finalWrite, the ISRs, and the begin/clear seem like the ones you should touch), compile the code and see if it works!
> 1 votes

---
Tags: serial, arduino-mega, gsm, hardware
---


# Question
Title: RTClib library dependency on Wire library
I downloaded the RTClib library from https://github.com/adafruit/RTClib. In every provided example, `#include <Wire.h>` is written immediately above `#include "RTClib.h"` at the top of the sketch.

Why is this necessary? I know the RTClib library requires the functionality of the Wire library but, if this is the case, why can't I just `#include <Wire.h>` at the top of RTClib.h? I have tried the latter, even using just the following sketch, but my sketch failed to compile.

RTClib.h:

```
// Code by JeeLabs http://news.jeelabs.org/code/
// Released to the public domain! Enjoy!

#ifndef _RTCLIB_H_
#define _RTCLIB_H_

#include <Wire.h>
...

#endif // _RTCLIB_H_

```

Sketch:

```
#include "RTClib.h"
void setup() {}
void loop() {}

```

# Answer
> 4 votes
Not getting too formal here, The arduino IDE looks at which libraries are included in the top level sketch when deciding what libraries to include in the compilation.

It would make sense for only RTClib.h to include Wire.h yes, but the IDE does not get the information to add Wire to the compilation list that way. It is a quirk of the IDE that makes implementing libraries that use other libraries a bit more painful.

---
Tags: arduino-uno
---


title: Issue with PWM output pin

text:
# Question
Title: Issue with PWM output pin
I'm just starting off with using the Arduino and was learning about PWM
(http://arduino.cc/en/Tutorial/PWM).
Below is what my circuit looks like.

Below is the very simple code.

```
const int pinNine = 9;    // LED connected to digital pin 9

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
  // set the digital pins as outputs
  pinMode(pinNine,OUTPUT);
}

void loop() {
  analogWrite(pinNine, 0);
}

```

I was expecting my LED to not be lighted as its a 0% duty cycle. I even change the pinNine outputValue to (64, 127, etc) but for some reason the LED is always lighted. Any ideas?

---

# Answer
> 0 votes
Ok, it seems my understanding of the PWM was wrong. I tried the circuit and code from here (http://arduino.cc/en/Tutorial/Fade) and it worked as expected (fade in and out).

Actually when i wrote my original code i was expecting the LED to blink. So, as i got closer to 255 i was expecting it to spend more time being 'lit', as compared to 0 where it should spend less time being 'lit'.

> I even change the pinNine outputValue to (64, 127, etc) but for some reason the LED is always lighted.

It being lighted makes sense. What i missed out was it being dimmer when the value was lower.

Thanks for all your help..

# Answer
> 1 votes
Added at top:

**Your code runs correctly on a $US3 Arduino Nano** :-)

It seems extremely likely that you have a hardware problem of some sort.

If you have a voltmeter you can try these easy checks.
I carried these out to be sure that I got what was expected and the results are as you would expect them to me. Use a meter set to DC Volts - typical common meter circuitry averages the PWM well.

1. Remove LED etc connection to pin 9.
Measure the voltage from the 5V pin to ground. If powered from USB this will usually be slightly below 5V.
2. Run your code with the analogWrite set to 128 ie

analogWrite(pinNine, 128);
3. Measure the voltage on pin 9 relative to ground. It should be close tohalf the voltage on the 5V pin in 1. above. This is because the analogWrite value is controlled by PWM with values from 0 to 255. 128/255 ~= 50% so output is 50% of Vref = 5V by default. in a 5V system.
4. Set analogWrite to

```
 analogWrite(pinNine, 25);

```
5. The voltage on pin9 should be about 10% of the voltage on the 5V pin.

IF you get approximately the voltages shown in 3. and 5. your code is working OK and your hardware is OK. If not then 'summat aglae'.

Try another analog pin.

Check that the red wire to the LED goes to UNO ground.

The voltmeter is a surer way of checking that the LED is as you can see actual numeric values that result.

---

**OLDER:**

It always helps greatly if you show PIN IDs on photos so people can be confident re what you have done.

If you view the whole UNO-R2-R3 connector with numbering it is obvious that the important pinouts are the same. If however you view part of the connector with no numbering/ pin names shown, then on the R3 there are additional pins on the ARef end of the connector which make comparisons'more difficult).

You APPEAR to have an Arduino UNO R3
It would help if you gave actual model and weblink in future "just in case it matters". .

You appear to have connected to pin 9 (as you intended to) Pin 9 has PWM capability, as required. It seems that your code should work.

Thusly

IF the red wire connects to ground the circuit seems electrically correct.
Does it?

Code LOOKS OK.

Try digital write on / off on pin 9 to see if LED changes and that the port behaves as expected. A bad port pin is possible.

What pin is serial on?

Try another pin with PWM capability to see if it changes.

---

ARDUINO UNO R3 from UNO home page

The connector pinouts vary widely between models of UNO.

# Answer
> 1 votes
Flat side of LED is `-`. This means that your white wire is on `-` side and your red wire on `+` side. Therefore your power rail connection is reversed... and therefore your LED is ON when you send `0` on PWM. By the way, you will set the LED OFF by writing `255` on PWM.

Solution: connect power rails correctly and everything will be back to normal.

# Answer
> 0 votes
I have a few things you could try:

1. Remove `pinMode(pinNine, OUTPUT)`, this is only used for digitalWrite(), the PWM controller might be affected by this.
2. Did you select the correct Arduino Chip in the IDE? Arduino maps pin 9 to a hardware pin (PB1 for UNO), which is not consistent between different boards
3. Try inserting a `delay(100)` after `analogWrite(...)`. I'm not sure if the analogWrite call restarts the PWM cycle, resulting in very fast switching that might be seen as 'always on'

Other than that, your sketch seems to be correct. I assume the black wire in the breadboard is wired to Ground, correct?

---
Tags: pwm, analogwrite
---


title: What is Vin for the EthernetPOE board?

text:
# Question
Title: What is Vin for the EthernetPOE board?
I am working on a project that needs to drive a relay board. I'm looking at the ETHERNET board with PoE and according to the documentation here (http://arduino.cc/en/Main/ArduinoBoardEthernet) the output of the PoE module is 9V.

Is that the voltage to expect out of the Vin pin?

The Relay board that I want to use (http://numato.com/downloads/dl/file/id/29/product/47/user\_manual.pdf) specifies that it wants a 7-12V power supply.

I want to confirm that this is the case so I can use the voltage out of the PoE and I don't need to add a separate DC power supply to this system.

# Answer
> 0 votes
I wouldn't expect you to take any power from V-**in**-, but it actually seems like you can!

If you take a look at the schematic for the Rev.3 Arduino Ethernet, you can see the power rails from Ethernet is connected to Vin. (`V1+`, `V1-`, `V2+`, `V2-` --\> `Vin` in the leftmost part of the schematic)

# Answer
> 1 votes
Your question is a little confusing, so let me give you a couple pieces of information.

First things first - the VIn pin on the Arduino is strictly for power going to the Arduino board, you shouldn't be drawing power from this pin. The documentation in the link you sent is a little misleading on this - it's basically saying 9v is coming OUT of the PoE module, and going IN to the VIn on the Arduino itself. If you wanted to tap into this 9v power, you should connect to the PoE module VOut instead.

PoE by default can deliver 37-57 volts or 42-57 volts, depending on what type of PoE you're using (which 802.3 specification). Wikipedia has a good overview of this information.

That being said, the Arduino Ethernet board you're using can't handle this voltage by itself - unless these boards have changed, they require an additional PoE module, which is basically just a DC-to-DC buck converter that will convert the high PoE voltage down to 9v or 12v. At this point, the Arduino's built-in converter can consume that 9 or 12v and distribute it at 5v across the board.

Now, to your problem - you want to power a relay that requires 7-12v. You could theoretically connect the relay to the VOut of the PoE module, giving you 12v. However, if the relay draws too much power for too long, you will either get brownouts (and your Arduino will restart) or potentially damage the Arduino board. Unless the relay draws a lot of current or is being powered for extended periods, you should be fine. If you want to be more thorough, you could put a large capacitor between your PoE module and the relay.

You should NOT try to connect the relay directly to the PoE VOut, as the voltage will be far too high.

---
Tags: power, ethernet
---


# Question
Title: Freeduino avrdude stk500_getsync() not in sync
I have a Freeduino USB 1.1 board with atmega 8l-8pu microcontroller on it. When I try to upload program, it shows error:

```
avrdude stk500_getsync() not in sync: resp 0x00

```

I have tried reset and the red led blinks which I think suggest bootloader is working fine.

On Arduino IDE, I have set Arduino Uno and correct port which is shown in device manager.

One weird problem that I noticed is that no matter which USB port I connect to, it says COM9 on device manager. Is that something to look into?

Any ideas?

# Answer
There could be many reasons for the problem you have got.

1) Try to program your Board with any other device you have got. If you are trying to program it with PC try to do it using Laptop.

2) Plug your board to any other port. Then Right Click My Computer and Select Manage--\> Device Manager and find the port where your Freeduino is connected. Then Select that port in your Arduino IDE.

Solution 1 worked for me!
> 0 votes

---
Tags: arduino-ide
---


# Question
Title: Is it possible to use FrSky D8R-II Plus 8ch 2.4Ghz ACCST Receiver with an arduino Uno?
I'm in the process of buying a receiver and transmitter for my quad copter project. Would it be possible to use this receiver or a similar one to control the quad. I'm trying to read the signals using Pulse in. I'm inexperienced in RC and I only found one tutorial on how to do this.

I know that the receiver will have to be wired up to the analog pins on the arduino however, the receiver has an operating voltage of 3.5V-10V and an operating current of 100mA which exceeds the 40mA of the arduino board. I have seen videos of people using silar 2.4Ghz receivers on arduino Nanos without problems. Has anyone on this board done something similar and if so, can thou guide me?

# Answer
> 1 votes
I've used plenty of receivers like this with arduino.

The operating current is not really an issue; It is drawing power off of the 5v line, not the digital pins, which is capable of 100mA. In any case they usually have an extra "bat" line that you could plug in to a BEC from one of your speed controllers, and then just connect signal and ground lines to the arduino.

pulseIn works, but not ideally (especially for quadcopters). reading with pulseIn tends to have quite a bit of noise, and runs slow. Those receivers pulse around 50-60Hz, so reading those signals with pulseIn (which has to wait for the signal to finish) will take too long. I say "too long" because in all the open source quad copter programs I've looked at the sensor-read/stabilize update loop needs to run at 100 Hz or more.

What you need to use is the interrupt functionality of the AVR. That way you can detect the time between changes in state of the input pulse without causing the rest of the program to stop. This can get somewhat complicated so I'm not going to write a tutorial here. I recommend you research it yourself and ask new, specific questions here if you have any.

It doesn't magically fix everything for you though; the Uno only has 2 external interrupts. I think most arduino based quads use arduino megas or Leonardos, which have more. I know the APM 2 board has a separate chip converting those 8 single channel PPM signals into a single 8 channel PPM signal that goes into the main controller, despite the fact that it is a mega.

You can look into Aeroquad and Multiwii for inspiration. ArduPilot is open source as well but their code is messier, which makes reading it much more difficult. I don't think it is impossible to use an Uno, but it will be difficult.

---
Tags: arduino-uno, analogread, pulsein
---