body:
I am reading the value of six potentiometers with a TX Arduino and receiving that data and applying those numbers to a motor using serial. It is working fine through TTL but I am going to need to do this over a 60 ft tether.

I have done a little research and see that I could use RS 232 but that the maximum you should go with that is 50 ft, which will not work if I'm not mistaken. I have also seen RS 485 which will give us 4000 ft, which is overkill but will work. However, that only offers one-way communication, if I'm not mistaken. What I'm wondering is which protocol should I convert it to, and how I would have to adjust my RX and TX code.

TX code:

    /*
      Transmitting Code
      Reads potentiometers and sends them through serial
    */

    int data [10];     // to send bytes
    int start [2];
    int pot0Pin = A0;  // analog pin used to connect the potentiometer
    int pot0;          // variable to read the pot0ue from the analog pin
    int pot1Pin = A1;
    int pot1;
    int pot2Pin = A2;
    int pot2;
    unsigned char checksum0;
    unsigned char checksum1;
    unsigned char checksum2;

    void setup() {
      Serial.begin(9600);
      Serial1.begin(9600);
      pinMode(19, INPUT);
      pinMode(18, OUTPUT);
    }

    void loop() {

    // READ THE POTENTIOMETERS:

      pot0 = analogRead(pot0Pin);   // reads the value of the potentiometer (pot0ue between 0 and 1023)
      data[0] = pot0 & 0xFF; //least significant 8 bit byte
      data[1] = (pot0 >> 8); //most significant 2 bits

      pot1 = analogRead(pot1Pin);
      data[2] = pot1 & 0xFF;
      data[3] = (pot1 >> 8);

      pot2 = analogRead(pot2Pin);
      data[4] = pot2 & 0xFF;
      data[5] = (pot2 >> 8);

    // CREATE CHECKSUMS:

      checksum0 = ~(data[0]+data[1]) + 1;

      checksum1 = ~(data[2]+data[3]) + 1;

      checksum2 = ~(data[2]+data[3]) + 1;

    // WRITE VALUES AND CHECKSUMS TO SERIAL:

      Serial1.write(data[0]);
      Serial1.write(data[1]);

      Serial1.write(data[2]);
      Serial1.write(data[3]); //bytes sent

      Serial1.write(data[4]);
      Serial1.write(data[5]);

      Serial1.write(checksum0);

      Serial1.write(checksum1);

      Serial1.write(checksum2); // send the checksum

     delay(10);        // delay in between reads for stability

    }

RX code:

    /*
      Receving Code
      Reads bytes from Transmitting Code and put thems back together
      Applies the read bytes to our motor control board
    */
    unsigned char val[10];    // variable to read the value from the analog pin
    int motorVal;
    int coolVal;      // 0-1024 received from serial
    int coolVal1;
    int coolVal2;
    unsigned char checksum1;
    unsigned char checksum2;
    unsigned char checksum3;
    unsigned char checkit1;
    unsigned char checkit2;
    unsigned char checkit3;
    int directionPin = 8;
    int PWM_out_pin = 9; // works on pins 2 - 13 and 44 - 46

    void setup() {
      Serial.begin(9600);
      Serial1.begin(9600);
    //  Serial1.begin(9600);
      pinMode(10, INPUT);
      pinMode(18, OUTPUT);
      pinMode(8, OUTPUT);
      pinMode(9, OUTPUT);
    }

    void loop() {

      if (Serial1.available()>5) {

        val[0]=Serial1.read();         // least significant 8 bits
        val[1]=Serial1.read();         // most significant 2 bits

        val[2]=Serial1.read();
        val[3]=Serial1.read();

        val[4]=Serial1.read();
        val[5]=Serial1.read();

        checksum1=Serial1.read();
        checksum2=Serial1.read();
        checksum3=Serial1.read();// get the checksum last

        checkit1 = val[0]+val[1]+checksum1;
        checkit2 = val[2]+val[3]+checksum2;
        checkit3 = val[4]+val[5]+checksum3;

      if (checkit1==0);  {
        coolVal = val[1]<<8 | val[0]; }

      if (checkit2==0);  {
        coolVal1 = val[3]<<8 | val[2];}

      if (checkit3==0);  {
        coolVal2 = val[5]<<8 | val[4];
        }

        Serial.print(coolVal);
        Serial.print(" ");
        Serial.print(coolVal1);
        Serial.print(" ");
        Serial.println(coolVal2);
        delay(10);

      }

    // FOR MOTOR 1 (more will be added once we achieve successful serial):
      if (coolVal > 550) {
        digitalWrite (directionPin, HIGH);
        motorVal = map(coolVal, 550, 1023, 0, 1023);
        analogWrite (PWM_out_pin, motorVal / 4); }

      if ((coolVal < 550) && (coolVal > 500)) {
        digitalWrite (directionPin, HIGH);
        analogWrite (PWM_out_pin, 0); }

      if (coolVal < 500) {
        digitalWrite (directionPin, LOW);
        motorVal = map(coolVal, 0, 500, 1023, 0);
        analogWrite (PWM_out_pin, motorVal / 4); }

    }

title: Long Distance Communication with Arduino

Answers: 2

body:
You're right that 60' exceeds the spec for RS-232. That said, distance specs are often quite conservative (as they should be, the spec is a promise that it will work and needs to account for marginal components and an unfavorable environment). I think the 50' limit for RS-232 was more observed in the breach than in practice. So for starters I'd be inclined to see if you could get 60' using RS-232 – I'd be kind of surprised if it didn't work.

Since reliability is important you're doing the right thing by checksumming and checking the data. If the checksum you use is good, it will go a long ways towards letting you detect corrupted data. Then, even if you are using a less than perfect underlying medium (e.g., RS-232 over a long distance), you can improve reliability by ignoring any corrupted values you receive. What that won't protect you from is a major data loss – for example a cut in your cable or a very noisy environment where most of your messages are getting lost. To defend against that you need a mechanism that also acknowledges your transmissions.

So, at this point you've got a choice – you could keep thinking of what might go wrong and designing solutions, or you could see if you could build on existing work. One thing you might want to look at is using something like the [SLIP][2] (**S**erial **L**ine **IP**) protocol which was developed to run TCP/IP over a dialup modem back in the dark ages of the Internet. I found, but haven't tried out, a couple of implementations for the Arduino:

- [SerialIP Library for Arduino][3] - a "proof of concept" version on the Arduino Playground.
- [Open Sound Control over SLIP][4] - newer, but not sure how hard it would be to extract out the SLIP part.

RS-485 is (can be) bi-directional, you just need a transmitter and receiver at each end. Another approach would be to use a [4-20 mA current loop][1].

You might also want to look into making the controller wireless. That would get you some added convenience (at the expense of a tether to help you find where you put the box) as well as a reliable two-way communication protocol.

[1]: http://www.bapihvac.com/content/uploads/2010/07/Understanding-4-20-mA-Current_Loops.pdf
[2]: https://en.wikipedia.org/wiki/Serial_Line_Internet_Protocol
[3]: http://playground.arduino.cc/Code/SerialIP
[4]: https://github.com/sepal/Arduino-Serial-SLIP-OSC

body:
You can do two-way communication with RS485. I have a [page about RS485](http://www.gammon.com.au/forum/?id=11428) with schematics and code, including calculating checksums.

You don't have to use twisted cable, that would just add to the reliability. You would need 4 cores (power, ground, A and /B) however if the other end was self-powered (ie. a battery) then you could skip that. There has been a bit of debate about whether the ground wire is needed (assuming you don't send power) but it is probably sensible to include it.

The page I linked above also describes a rolling master system, where each node has a chance to "talk" to other nodes. This demonstrates that you can send and receive on the same pair of wires.

In my test of the rolling master (using UTP cable) I had it working over 40 meters (ignore the figure on the schematic). So your 50 feet range should be easily achievable.

[![RS485 connection][1]][1]

  [1]: https://i.stack.imgur.com/I5ZZa.png


body:
I have a Nokia 5110 screen using u8gliv. I have it displaying an image and I can get it to display text:

       u8g.setFont(u8g_font_osb18);
       u8g.drawStr(0, 20, "PRESS START");

The problem is that this font size is way too big. How can I make it smaller? Do I have to use different fonts? If so how do I do that?

title: Arduino U8glib: how to display text?

Answers: 1

body:
Just choose a smaller font. You know, I showed you the documentation earlier. You really should read it, because it contains all the information you need.

For instance, here is the section on the available fonts: https://code.google.com/p/u8glib/wiki/fontgroup - each section contains a link to download the font group which of course you will need to do before you can use it.

You might find something like:

    u8g.setFont(u8g_font_fixed_v0);

more to your liking. And don't forget to download it via the link above first.


body:
I use the Arduino IDE to upload sketches to my Arduino Uno. My OS is Linux Ubuntu 14.04 LTS. The Arduino IDE has two ports by default for communication with the Arduino Uno:

    /dev/ttyACM0
    /dev/ttyS0

 1. What is the difference between these two ports ?
 2. What does "ACM0" and "S0" mean ?
 3. Are there configuration files somewhere in the OS folder structure that describe the parameters of these ports ?

I know that when I select `/dev/ttyACM0`, I am able to send data to my Arduino Uno. However it does not work when I select `/dev/ttyS0`.

I just want to better understand what these ports are exactly.

title: Difference between /dev/ttyACM0 and /dev/ttyS0 (Arduino IDE ports under Linux)

Answers: 2

body:
`/dev/ttyACM0` is a USB [communication device][1] (CDC) of sub-type "abstract control model" (ACM). That is what the Arduino is.

`/dev/ttyS0` is a hardware serial port - the (typically) 9-pin D connector on the back of your computer.

If you want to use `/dev/ttyS0` (why would you?!) you will require a special cable that converts the RS-232 voltage signals from the 9-pin D connector into the right TTL level signals for the Ardiuno and wire it in to the right pins on the board.

  [1]: https://en.wikipedia.org/wiki/USB_communications_device_class

body:
Some high-level languages (e.g. matlab) treat all serial ports as the  /dev/ttyS# selecter.  To interface with an Arduino with MATLAB you have to rename /dev/ttyACM0 as /dev/ttyS#.

This may also be an option in the Arduino IDE, and that is why those options exist.


body:
So i'm trying to use the [PubSubClient Library][1] on my arduino mini pro, but I'm connecting to the internet via wifi using an ESP8266.

Using a mini means I have to use software serial to connect to the ESP, but I've ran into a problem. I can't find anywhere such as `ESPWiFiClient` to use with the examples from the PubSubClient library where they use `EthernetClient`.

Is there any available libraries that can emulate EthernetClient with an ESP module over software serial?

  [1]: https://github.com/knolleary/pubsubclient

title: Use ESP8266 as WiFi client connected to Arduino Pro Mini

Answers: 1

body:
Ditch the Pro Mini.  Upload your Arduino code to the ESP directly. There's a GitHub repo with the details. ESP for Arduino IDE has a ton of libraries. I'm sure you'll find it there.

But if you're bent on using the Pro Mini,  you'll have to use AT commands over serial to control it or flash a custom firmware into the ESP using Lua or something. And Pro Mini can use its hardware serial just like a Uno does.


body:
I have two XBee Pro S2Bs: one is plugged in to a USB explorer, and; the other is plugged into an Arduino Wireless Protoshield, which is connected to an Arduino Uno.

My XBee connected to the explorer is configured as the *coordinator* in AT mode, and the XBee connected to the Arduino is configured as a *router* in AT mode. As a side note, I tested the network with a second USB explorer, and I was able to communicate between both XBees.

I uploaded the following code to the Arduino (which is just a sample I pulled off the internet somewhere):

<!-- language: c -->

    char rx_byte;

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

    void loop()
    {
     if (Serial.available() > 0)
     {
      rx_byte = Serial.read();
      Serial.print("You Typed: ");
      Serial.println(rx_byte);
     }
    }

Once I upload the code and turn on the serial monitor for the Arduino (using either the Arduino IDE or Visual Micro, with the Arduino plugged in via USB), and turn on the serial monitor on for the XBee connected to the USB explorer (using the serial monitor in XCTU), I get the following results:

 - If the wireless proto shield has its switch set to USB mode, then I can send data from the Arduino serial monitor to the serial monitor in XCTU, but the Arduino serial monitor doesn't receive data that is typed into the XCTU serial monitor.

 - If the wireless proto shield has its switch set to Micro mode, then I get mostly the opposite result.  I can send data from XCTU serial monitor to the Arduino serial monitor, which the result is returned to the XCTU serial monitor, e.g., if I type "X" in XCTU serial monitor, both serial monitors say "You Typed: X".  However, if I try to send data through the Arduino's serial monitor, neither serial monitor displays anything.

What I would like to do is be able to type in either serial monitor and have the data displayed in both serial monitors, like you would expect in a simple chat program.

Can someone see where I have gone wrong and/or how to get to the correct result?

title: Communication between Arduino and XBee

Answers: 1

body:
Check out https://learn.sparkfun.com/tutorials/xbee-shield-hookup-guide/example-communication-test
Essentially you need to set up Software Serial for your xbee to communicate on a couple of digital pins, instead of using hardware serial. When using hardware serial (the RX and TX pins) only one device works on it at a time, hence why you can't use the xbee and the serial monitor at the same time.


body:
I have an Arduino Uno connected to an HC-05 Bluetooth sender/receiver chip. I am trying to create a Bluetooth connection between my Acer laptop running under Ubuntu 14.04 LTS and the HC-05 chip.

Ubuntu detects the HC-05 chip, as can be seen below.

    phodor@ubuntu: hcitool scan
    Scanning ...
        11:22:33:44:55:66   HC-05

I am able to create a pair between my laptop Bluetooth device and the HC-05 chip. However, I am unable to create a connection with that pair from the Ubuntu interface. The "Connection" button cannot be clicked on, as you can see on the figure below.

I tried creating a connection using the terminal, but after that the terminal still did not detect any connection.

    phodor@ubuntu: sudo hcitool cc 11:22:33:44:55:66
    [sudo] password for phodor:
    phodor@ubuntu: hcitool con
    Connections:

I also checked that my computer Bluetooth device was working.

    phodor@ubuntu: hcitool dev
    Devices:
        hci0    AA:BB:CC:DD:EE:FF

Any idea why the connection cannot be created ? Any idea on how to do it using the Ubuntu interface or the terminal ?

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/dCsJp.png

title: Bluetooth connection to HC-05 paired but not connected (in Linux)

Answers: 2

body:
you can try this website for more information

http://wiki.micropython.org/official-accessories/Bluetooth-module-HC05

body:
You can find the answer in the [Bluetooth connection to HC-05 paired but not connected][1]

Step;

1.Once you have paired the HC-05 as you've described, bind the device by entering;

    sudo rfcomm bind 0 "MAC address" 1

2.To trigger the connection & display the data using minicom, run;

    sudo minicom -D /dev/rfcomm0

You'll notice that port /dev/rfcomm0 will be available from the arduino IDE as well.

3.To exit minicom, press ctrl+A and then X.

  [1]: https://askubuntu.com/questions/721954/bluetooth-connection-to-hc-05-paired-but-not-connected/1350834#1350834


body:
Hello I am using the u8glib library to draw text on the string but it keeps giving me an error with the string

<!-- language: c -->

     String name1 = "";
     ...
     void draw(){
      u8g.setFont(u8g_font_micro);
      u8g.drawStr(22, 37, name1);
     }

why dosnt this work?

Here is the error:

> C:\Program Files (x86)\Arduino\libraries\U8glib/U8glib.h:200:16: note:
> no known conversion for argument 3 from 'int' to 'const
> __FlashStringHelper*' no matching function for call to 'U8GLIB_PCD8544::drawStr(int, int, String&)'

title: Arduino String problem

Answers: 2

body: Like the documentation says, that method doesn't take a `String` object. Call the `c_str()` method of the `String` object and pass that instead.

body:
String is evil and should be avoided at all costs (http://hacking.majenko.co.uk/the-evils-of-arduino-strings)

The author of u8glib knows that and has refused (quite rightly) to implement them.

You should not use String either.  If you really *must* for some obscure reason then you will have to pass the internal "C string" reference to the `drawStr` function instead of the whole String object:

    u8g.drawStr(22, 37, name1.c_str());

The *only* reason people use String is because they are too lazy to learn the proper way of handling textual data in C.


body:
i am new to arduino and have no experience with programming

i have an uno r3 board, a wiznet ethernet sheild, and dh22 temp and humidity sensor.

      I would like to have it update plot.ly to view the data.

error returned on monitor is ...

    POST /clientresp HTTP/1.1
    Host: plot.ly:80
    User-Agent: Arduino/0.6.0
    Content-Length: 340

    version=2.3&origin=plot&platform=arduino&un=jozef.jones&key=tgcio4brx1&args=[{"y": [], "x": [], "type": "scatter", "stream": {"token": "ke1f6fwqas", "maxpoints": 100}}, {"y": [], "x": [], "type": "scatter", "stream": {"token": "k5lmga9qrl", "maxpoints": 100}}]&kwargs={"fileopt": "overwrite", "filename": "filename", "world_readable": true}
    ... Sent message, waiting for plotly's response...
    HTTP/1.1 200 OK
    Content-Type: application/json
    Date: Sun, 17 Jan 2016 16:22:32 GMT
    Server: nginx/1.8.0
    Set-Cookie: csrftoken=WknqVtPqjTYvlTyoKSC5QehqDgmt7Qp7; expires=Tue, 17-Jan-2017 16:22:32 GMT; Max-Age=31622400; Path=/; secure
    Set-Cookie: anoncsrf=2UDFDiQhQq1zf5MIMaoRJ0ayaqs7g58R; expires=Mon, 18-Jan-2016 16:22:32 GMT; httponly; Max-Age=86400; Path=/
    Vary: Accept-Encoding
    Vary: Cookie
    X-Frame-Options: SAMEORIGIN
    Content-Length: 138
    Connection: keep-alive

    {"url": "", "message": "", "warning": "", "filename": "", "error": "Missing required POST parameters: platform un key origin args kwargs"}

   code is

    #include <SPI.h>
    #include <Ethernet.h>
    #include "plotly_streaming_ethernet.h"
    #include "DHT.h"

    #define nTraces 2

    char *tokens[nTraces] = {"ke1f6fwqas", "k5lmga9qrl"};
    // arguments: username, api key, streaming token, filename
    plotly graph("jozef.jones", "tgcio4brx1", tokens, "filename", nTraces);

    // DHT Sensor Setup
    #define DHTPIN 2 // We have connected the DHT to Digital Pin 2
    #define DHTTYPE DHT22 // This is the type of DHT Sensor (Change it to DHT11 if you're using that model)
    DHT dht(DHTPIN, DHTTYPE); // Initialize DHT object

    byte mac[] = { 0x00, 0xAA, 0xBB, 0x00, 0x00, 0xCC };
    byte my_ip[] = { 192, 168, 1, 117 }; // google will tell you: "public ip address"

    void startEthernet(){
        Serial.println("... Initializing ethernet");
        if(Ethernet.begin(mac) == 0){
            Serial.println("... Failed to configure Ethernet using DHCP");
            // no point in carrying on, so do nothing forevermore:
            // try to congifure using IP address instead of DHCP:
            Ethernet.begin(mac, my_ip);
        }
        Serial.println("... Done initializing ethernet");
        delay(1000);
    }

    void setup() {
      graph.maxpoints = 100;
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      startEthernet();

      bool success;
      success = graph.init();
      if(!success){while(true){}}
      graph.openStream();
      dht.begin();
    }

    float h, t;

    void loop() {
          h = dht.readHumidity();
          t = dht.readTemperature();
          graph.plot(millis(), t, tokens[0]);
          graph.plot(millis(), h, tokens[1]);
    }

title: uno + ethernet sheild(wiznet) + dh22 temp humidity sensor + viewing data online

Answers: 0


body: I have been able to establish a successful connection between an RN-42 Bluetooth module and Arduino Uno, but I could not do the same with an Arduino Due. The module connects to the phone but whatever data I send is not registered. What is different on the Due in the context of Bluetooth connectivity? Baud-rate perhaps?

title: Bluetooth help with Arduino Due

Answers: 0


body:
Greetings dear reader!

I have some trouble storing my IMEI code inside a variable. It always returns an error: "void value not ignored as it ought to be".

Since then I tried to write it to the serial line by just running the `gsm.SimpleWriteln("AT+GSN");` AT command, but I am stuck at storing this displayed value inside a variable. Does anyone here know a way to store a serial value into a variable? I just want to send the IMEI code as an identifier to the cloud application...

Thanks in advance, your response is really appreciated.

The code:

    #include "SIM900.h"
    #include <SoftwareSerial.h>
    //#include "inetGSM.h"
    //#include "sms.h"
    //#include "call.h"

    //To change pins for Software Serial, use the two lines in GSM.cpp.

    //GSM Shield for Arduino
    //www.open-electronics.org
    //this code is based on the example of Arduino Labs.

    //Simple sketch to communicate with SIM900 through AT commands.

    //InetGSM inet;
    //CallGSM call;
    //SMSGSM sms;

    int numdata;
    char inSerial[40];
    int i=0;
    boolean startUp = false;

    void setup() {
      Serial.begin(9600);
      Serial.println("GSM Shield testing.");

      //Start configuration of shield with baudrate.
      //For http uses it is recommended to use 4800 or slower.
      if (gsm.begin(9600)) {
        Serial.println("\nstatus=READY");
        getIMEI();
      } else Serial.println("\nstatus=IDLE");
    };

    void loop() {
      //Read for new byte on serial hardware,
      //and write them on NewSoftSerial.
      serialhwread();
      //Read for new byte on NewSoftSerial.
      serialswread();
    };

    void serialhwread() {
      i=0;
      if (Serial.available() > 0) {
        while (Serial.available() > 0) {
          inSerial[i]=(Serial.read());
          delay(10);
          i++;
        }
        inSerial[i]='\0';
        if(!strcmp(inSerial,"/END")) {
          Serial.println("_");
          inSerial[0]=0x1a;
          inSerial[1]='\0';
          gsm.SimpleWriteln(inSerial);
        }
        //Send a saved AT command using serial port.
        if(!strcmp(inSerial,"TEST")) {
          Serial.println("SIGNAL QUALITY");
          gsm.SimpleWriteln("AT+CSQ");
        } else {
          Serial.println(inSerial);
          gsm.SimpleWriteln(inSerial);
        }
        inSerial[0]='\0';
      }
    }

    void serialswread() {
      gsm.SimpleRead();
    }

    void getIMEI() {
      long IMEI = gsm.SimpleWriteln("AT+GSN"); // IMEI code
      Serial.println(IMEI);
      return IMEI
    }

title: Gboard 800 (SIM900 + ATmega 328)

Answers: 1

body:
The `SimpleWriteln()` function just sends an instruction. It doesn't return anything.  Once you have sent the instruction to retrieve the IMEI you then have to actually *read* the IMEI.

However, fortunately, there is a function that does it for you:

    char imei[20];
    gsm.getIMEI(imei);

The IMEI should now be in the C string `imei`. What you do with it then is up to you.


body:
I've followed tutorials installing arduino drivers for a while, but this is getting in my way:

[![The "Update driver software" button doesn't show!][1]][1]

  [1]: https://i.stack.imgur.com/ojXBc.png

The all-important "Update driver software" button isn't showing? Can anyone explain this and how I can fix it? Many thanks!

title: "Update driver software" not showing. :(

Answers: 0


body:
While I was researching ideas for an Arduino clock, I found several clocks that incorporated an RTC (Real Time Clock) module.

I don't know why it is used in some clocks.

So, here are my questions:

 - How does an RTC module work?
 - Do I have to use it "like a rule" (is an RTC necessary or unnecessary) in my clock?

title: Do I have to use an RTC to build a clock?

Answers: 5

body:
> How does a RTC module works?

It counts. As simple as that. Once a second it ticks and counts up. It also remembers - most have a battery backup and will continue ticking when you turn the main power off.

> I have to use it "like a rule" (if it is necessary or unnecesary) in my clock?

If you want accuracy and continuation, yes.  An RTC is designed to tick at (as close as reasonably possible) once per second. Trying to do that with just an Arduino is incredibly difficult. The ceramic resonator on an Arduino is not as accurate as the quartz crystals used with an RTC. After a week you may find you are an hour out.

body:
> How does a RTC module works?

It is a specialized counter. It counts seconds, minutes, hours, days, months and years, properly handling such annoying problems as leap year, different days in months, etc.

Additionally it allows powering with a battery, so that clock ticks even when the device is not powered on, until battery discharges.

Usually RTC is clocked at 32768Hz using standarized quartz crystal.

> I have to use it "like a rule" (if it is necessary or unnecesary) in my clock?

Unless your microcontroller has RTC built-in, you should use an external one. There are many RTCs with I2C interface.

Built-in timer available in Arduino is not accurate enough and cannot tick when you remove power. Inaccurate counter will cause your clock to drift considerably and no backup power forces your clock to be connected all the time.

You can check out this example to see how to hook up:
https://iobtoolkit.com/docs/tutorials/i2c_terminal_mcp7940n.html

Disclaimer: i'm the author of IOB, but you don't need to use it. It's just a nice analysis of a rather popular RTC.

body:
RTC modules are used because they make it easier to keep accurate time. They do this by maintaining time when the system is shut down or rebooted (by way of a battery or some other mechanism for keeping running independently of the host system) and by providing a time base that is, usually, more accurate than that of the host.

Another way to keep very accurate time (potentially better than you can get with all but the best RTC modules) is to get your time from a GPS or from the Internet using NTP. If you're going to use a GPS anyway or need an Internet connection then either of those approaches are very good ways to go. If you don't, then they are considerably more expensive than an RTC module.

body:
For this "rule", and for many "rules" like this, the answer is "it's more of a guideline" (usually "it's not required, but may be easier that way").

Keeping time requires 3 things: an accurate "tick", a way of knowing the time initially, and counting the time since then.

The (16mHz) clock on the Arduino will give you a reasonably accurate "tick" - on the order of 50 parts per million. That means, over a million seconds, your clock will drift about 50 seconds. This works about (ballpark) 1 minute per fortnight. Is this accurate enough? This depends on what you are using it for.

The next thing on the list is knowing the time initially. If you buy a RTC, it may be set to the right time, or it may not. Even if it is "set", it may not be set to your timezone. Setting these is pretty easy. It will need to be set every time the clock (be it a RTC or your homebrew clock) loses power. For this reason, RTCs usually have a battery back up. How will your clock get it's time when it starts up? Note that, if your project is network connected, you may be able to get the clock from the internet - this will also mean the drift of your clock will not be an issue - you can retrieve it once per day, so it will never drift more than 4 seconds before it gets corrected.

The final thing that it needs (and the easiest) is a way of counting the time. This is probably the easiest - use the millis() function. Note that this overflows (resets to 0) after 4294967296 milliseconds - about once every 50 days. Millis() will tell you the number of milliseconds since the Arduino last rebooted. If you want your clock to run more than 50 days, you need to be prepared to that. This will happen part way through a second.

Note that this will give you milliseconds, and, fairly easily, seconds, minutes, hours. If you want the day (of the month), then you need to keep track of which month and year, since the length of each month will vary, as will leap days.

body:
I built a clock designed a while ago by Geoff Graham, who [synchronized to a GPS](http://geoffg.net/GPS_Synchronised_Clock.html) around every 24 hours, and used the internal clock in-between. The GPS corrected for drift in the internal clock (and, of course, gave you the time accurately in the process).

This is more expensive than a RTC, but more accurate. If you also had an RTC it would drift less during the day. Or, you could read from the GPS all the time and not have an RTC.

I made a [GPS clock](http://www.gammon.com.au/forum/?id=11991) myself which does that - just shows the GPS time.

[![GPS clock][1]][1]

Higher-contrast image:

[![GPS clock face][2]][2]

Internals:

[![Inside GPS clock][3]][3]

---

This is [another project](http://www.gammon.com.au/forum/?id=12106) that uses an RTC clock chip (indicated on photo):

[![Temperature sensor][4]][4]

However if you go for just an RTC chip you can expect it to drift over time. They are more accurate than counting processor ticks (and survive a power outage because of the backup battery) but are not as accurate as the GPS.

Those clock chips are pretty cheap. I got 30 of them for $10 from eBay.

  [1]: https://i.stack.imgur.com/aWQyV.jpg
  [2]: https://i.stack.imgur.com/NhA5R.jpg
  [3]: https://i.stack.imgur.com/r9MOy.jpg
  [4]: https://i.stack.imgur.com/2EZ5o.png


body:
İ'm making  a project on my arduino uno when i figured out i had no more GND left to finish the circuit. İs there any other way to optimize, use pins as input maybe. İ tried whit other websites, however, they weren't much of a use. Can you show an example also.

Thank you sooo much in advance,

Dario

title: İs there any way different way than GND's Arduino

Answers: 1

body:
Dario,

There are only 3 ground pins on the Arduino Uno, but don't be afraid to "breakout" these pins with wire. It doesn't matter if you connect multiple component grounds together, as long as they are connected to ground with no resistance between them, the circuit will close.

Strip board and pin headers will help you here, try this: http://www.instructables.com/id/Home-Made-Arduino-Prototype-Shield/


body: How would iconnect my Arduino Mega to house Mains, without buying a transformer, and having to make a whole setup for that.  Can i just use a regular phone adapter?  Or is 1 Amp too large (or 2 Amps).

title: Connecting Arduino To mains

Answers: 1

body:
Amps tell you how much current you can draw from the power supply, or "how much it can do".

You can hook up 3Amps power supply to a device that draws 1Amp and it will work ok, still having 2 amps of reserve.

You must pay attention to power supply **voltage** and keep it in specified range.

Arduino Mega has recommended input voltage of 7-12V, so you must deliver at least 7V. There are plenty of cheap wall power supplies with voltage regulation from 1.5V to 12V.

How much current it will draw depends on your application, but I doubt that you can suck more than 0,5-1A in a typical application.


body:
I'm trying to figure out how to use an RTC to send interrupts to my arduino. I'm using a DS3232. I can get an 'edge' interrupt, with the following toy code (I know the code is silly, it's just a short example to test if I have actually set the RTC to send the interrupt, and that the Arduino receives it):

    /*----------------------------------------------------------------------*
     * Minimal example of setting a recurring alarm with the DS3232 RTC     *
     * Attach an LED to pin 7, which will flash when the alarm fires.       *
     *                                                                      *
     * Attach the RTC SQ/INT pin to Uno pin 2, with a 10K pull-up to VCC.   *
     * Ard pin A4 -> RTC SDA, Ard A5 -> RTC SCL, 5v -> vcc, GND -> GND      *
     *----------------------------------------------------------------------*/

    #include <DS3232RTC.h>        //http://github.com/JChristensen/DS3232RTC
    #include <Time.h>             //http://playground.arduino.cc/Code/Time
    #include <Wire.h>             //http://arduino.cc/en/Reference/Wire

    #define WAKE_PIN 2
    #define LED_PIN 7

    void setup(void)
    {
        pinMode(LED_PIN, OUTPUT);

        // RTC config:
        RTC.squareWave(SQWAVE_NONE);
        pinMode(WAKE_PIN, INPUT_PULLUP);
        attachInterrupt(INT0, wakeUp, FALLING);
        RTC.setAlarm(ALM2_EVERY_MINUTE, 0, 0, 0, 1);
        RTC.alarm(ALARM_2);
        RTC.alarmInterrupt(ALARM_2, true);
    }

    void loop(void)
    {
      if(RTC.alarm(ALARM_2)){
        digitalWrite(LED_PIN, HIGH);
        delay(5000);
        digitalWrite(LED_PIN, LOW);
      }

    }

    void wakeUp (){
    // no-op, just checking if the interrupt fired
    }

Why doesn't this work if I set the interupt to "LOW", ie., `attachInterrupt(INT0, wakeUp, LOW);`?

The reason I ask is I'm trying to use an RTC to wake from low power mode, and I think this [doesn't work with a 'falling' interrupt][1].

  [1]: http://playground.arduino.cc/Learning/ArduinoSleepCode

title: Signal a LOW level interrupt with an RTC

Answers: 1

body:
[That page](http://playground.arduino.cc/Learning/ArduinoSleepCode) is incorrect, although it reflects what the datasheet says.

The processor **can** be woken from RISING/FALLING/CHANGE/LOW. I queried this with Atmel and got this response:

> Commented by Manoraj Gnanadhas (Atmel)
>
> 2015-01-20 06:23:36 GMT
>
> [Recipients: Nick Gammon]
>
> Hello Nick,
>
> Our design team has confirmed that “Note-3 mentioned under Table 10-1” is a datasheet bug. So you can use any type of interrupt (Rising edge/ Falling edge / Low level / Any logical change) to wake up from sleep mode. Sorry for the inconvenience caused.
>
> Best Regards,
>
> Manoraj Gnanadhas

This is mentioned on [my page about interrupts](http://www.gammon.com.au/interrupts).

---

Why does LOW hang the processor? The LOW interrupt is not an **edge** interrupt but a **continuous** one. Thus, while the signal is LOW the interrupt is being continually called, with only one processor instruction being executed after each call to the ISR (which itself takes around 5.125 µs). So, the ISR is not being interrupted, but effectively only one instruction of your code is being executed every 5.125 µs (probably about 1/40th of the usual speed).

---

>  and see how much of my problem is due to using an old and buggy IDE

It's nothing to do with the IDE. Change to a FALLING interrupt and your problems should go away. You may also want to clear the interrupt flag (as documented on my page) in case the interrupt event has already happened before you go to sleep. Specifically:

    EIFR = bit (INTF0);  // clear flag for interrupt 0


body:
I am trying to make an Arduino circuit as outlined here.

[![enter image description here][1]][1]

This is for connecting an Arduino input to a DCC system. DCC is a command control system for model railways that uses the same two wires for power and data (there's a wikipedia article that explains it better than I can)

I'm wondering what the optocoupler has more than 4 pins for? I'm new to this and I understand the purpose of the optocoupler but I am confused as to how this particular one works. It is a 6N136 optocoupler. I don't understand why it has the extra pins compared to 4 pin optocouplers, and I don't understand how it would read the polarity of the signal. DCC sends commands using polarity as I understand it, so I know I need to read the polarity, but how does the optocoupler do it here?

I have a very limited knowledge of electronics right now so pardon anything stupid I said :P

  [1]: https://i.stack.imgur.com/TzGoO.png

title: Optocouplers for Arduino DCC decoder - Explain?

Answers: 1

body:
That specific chip (the 6N137) uses a more efficient IC detector rather than a simple transistor junction.  It also has an "enable" pin that allows it to be turned on or off.  Consequently it needs a power supply to run it. That all means extra pins.

This design allows for higher speed communication (it's a 10Mbaud chip) with less leakage when compared to a traditional design.

The pin VE (pin 7) needs to be pulled up to make the chip work (the job of R2) and the output is pulled high (it's open drain) by R3.

The optocoupler will be on with one polarity and off with the other. It's as simple as that. The diode D1 protects the LED in the optocoupler from the reverse voltages.


body:
I am using the Adafruit TCS34725 to sense color. I have used the Colorview code example to set it up to sense all colors, works great. The thing I want is for it to tell me if it is seeing either green or red, I don't care about the other colors.

Can anyone suggest what I can do?

title: Use Adafruit Colorsensor to distinguish between green and red

Answers: 1

body:
Based on what I could find, you will have to calibrate the sensor to recognize these colours. First, run the Colourview code. Take down the raw RGB and CLEAR values obtained for an object you consider green and another you consider red. Find out if these values are consistent, each time you power down the sensor and turn it on again. If they aren't, record how much dead zone there is i.e. the maximum difference in readings (between resets) that you get for the same colour. Then using the values you get, try this code:

    #include <Wire.h>
    #include "Adafruit_TCS34725.h"

    #define MAX_OFFSET 50  // the maximum diff you found between readings

    typedef struct {  // struct to hold raw color data
       uint16_t red;
       uint16_t green;
       uint16_t blue;
       uint16_t clear;
    } Color;

    Color my_red = {3344, 3333, 23444, 3333}; //here you enter your minimum recorded values for red in the order of the struct members above
    Color my_green = {22222, 4444, 5555, 3333}; //the same for green

    void setup() {
      Serial.begin(9600);
      Serial.println("Color View Test!");

      if (tcs.begin()) {
        Serial.println("Found sensor");
      } else {
        Serial.println("No TCS34725 found ... check your connections");
        while (1); // halt!
      }
    }

    void loop() {
      uint16_t clear, red, green, blue;

      tcs.setInterrupt(false);      // turn on LED

      delay(60);  // takes 50ms to read

      tcs.getRawData(&red, &green, &blue, &clear);

      tcs.setInterrupt(true);  // turn off LED
      if (compare_colour(&my_red, red, green, blue, clear)){
          Serial.println("I see red.");
      }
      else if (compare_colour(&my_green, red, green, blue, clear)){
          Serial.println("I see green.");
      }
    }

    boolean compare_color(Color * std, uint16_t r, uint16_t g, uint16_t b, uint16_c){
    if ((r - std.red <= MAX_OFFSET) && (r - std.red >= 0) &&
          (g - std.green <= MAX_OFFSET) && (g - std.green >= 0) &&
          (b - std.blue <= MAX_OFFSET) && (b - std.blue >= 0) &&
          (c - std.clear <= MAX_OFFSET) && (c - std.clear >= 0))
      {
          return true;
      }
      return false;
    }

You can use this code directly after you have gotten the sensor readings for red and green objects.


body:
I'm printing an "unsigned long" value to HEX via:

    println(cardCode, HEX);

The value that I'm getting is: 69fb879d

I need it to be reversed as: 9d87fb69

I populate cardCode via the code:

    for (i=1;i<bitCount;i++)
    {
      cardCode <<=1;
      cardCode |= databits[i];
    }

going into this my bitCount value is 32, so basically I'm populating cardCode based on 32 bits from the variable databits which is of type unsigned char.

I am absolutely crap at bitwise conversions (bit-shifting, etc.), is there a simple way to do this reversal?  Is this even enough information to go on?

title: Reverse the order of a hex string

Answers: 2

body:
Your issue seems to be byte order (big endian) and not bit order. The simplest solution to byte order swap is to use the [builtin][1] functions provided by the compiler (AVR GCC).

    unsigned long cardCode;
    ...
    Serial.print(__builtin_bswap32(cardCode), HEX);

There are two compiler builtin functions for byte order swap. One for 16-bit data and one for 32-bit data.

    uint16_t __builtin_bswap16(uint16_t);
    uint32_t __builtin_bswap32(uint32_t);

AVR MCUs are little endian (least significant byte first in memory). There are many devices that use big endian (most significant byte first). This is also known as network order. There are a set of functions/macros to help write portable code, especially device drivers.

    #include <arpa/inet.h>
    uint32_t htonl(uint32_t hostlong);
    uint16_t htons(uint16_t hostshort);
    uint32_t ntohl(uint32_t netlong);
    uint16_t ntohs(uint16_t netshort);

These are used to map data from host to network byte order and reverse. They are defined as byte swap functions for hosts with little endian byte order. Unfortunately they are not available in the GCC AVR library but easy to define.

    #define htonl(x) __builtin_bswap32((uint32_t) (x))
    ...

Cheers!

  [1]: https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html

body:
The title of this question is "Reverse the order of a hex string" but it was actually about reversing byte order in an unsigned long int.

Here is an answer for reverse the order of a string (null terminated vector of char).

There is a [standard function][1] for that in the C string function library.

    char* strrev(char* s);

Cheers!

  [1]: http://www.nongnu.org/avr-libc/user-manual/group__avr__string.html#gacfdb3ab0c1f988f86d04d706d8e0ce3f


body:
I'm trying to build a smart thermostat for a particular application. I have the following design criteria and goals for the system:

- Must be able to set up and monitor the device from either a mobile
   phone or local network device.
- No go on Ethernet or other hardwired connection, except for initial setup.  This must be a wireless solution. I'm presuming WiFi is best.
- Needs a clock, an on time and an off time setting.
- The system does a system time verification check once daily.
- Needs a temperature input.
- Needs to run an existing heater system (24v) thru a relay.
- 120v AC power (battery backup not required.)
- Needs to be "hidden" in existing wall as much as possible.  (i.e. small & compact)  My intent is to hide the unit behind a double wide electrical duplex dead panel. (i.e. 4" x 4" nominal access thru drywall)

Here's a visual of my design intent package:[![Thermostat Design Package][1]][1]

As I review a number of different hardware controller devices, I can see some issues.  I am very familiar with the Intel Edison, and I know exactly how to do this project there, including using the controller as a stand alone web host. (The Edison uses Yocto Linux to create a node.js server using http module.)  I was hoping to save a few $$ on hardware using an alternative controller but not sure that will work.  I've been wading thru the code for both the Photon and generic Arduino devices, and I'm getting the impression that I may need a custom server / api tool for a web page interface.  Its not clear that those hardware choices will support an interactive web page, particularly for easy user data update via browser Submit button.  That's not a big problem, I'm a freelance software developer, handy in C/C++/Java, PHP and JavaScript. And as for the Raspberry Pi, I have no experience but the pricing on some of their boards is below $15.

Here are my questions:

   - Has anybody used an Arduino board to host an interactive web page, including user input via Submit / Form ?  (Can I declare a local network static IP address for an Arduino?)
   - Has anybody used an Particle Photon board to host an interactive web page, including user input via Submit / Form? (It looks like declaring a local network static IP address on a Photon is anything but easy...)
   - Has anybody written an API Restful server for their Arduino, with both `get` and `put` functionality?  (I'm thinking PHP, or node.js makes the most sense for me.)  I know if I have to use Dynamic IP addressing to the controller, that I can always make an API system work for the system.
   - Other comments?

  [1]: https://i.stack.imgur.com/TxreZ.jpg

title: Design Dilema -- What hardware?

Answers: 2

body:
> Has anybody used an Arduino board to host an interactive web page, including user input via Submit / Form ?

I have a [Tiny Web Server](http://www.gammon.com.au/forum/?id=12942) for the Arduino. It is designed to be light-weight on RAM. It supports GET/POST/Cookies for interacting with web forms.

[![Arduino web form][1]][1]

Example code and more information on the linked page above.

---

>  (Can I declare a local network static IP address for an Arduino?)

Yes.

---

> Other comments?

You could use NRF24L01 modules for short-range communication of wireless information. I have [example code and schematics](http://www.gammon.com.au/forum/?id=12821). My tests seemed to indicate 20m range was achievable.

  [1]: https://i.stack.imgur.com/yQCT5.png

body:
Have you looked at the [Adafruit Huzzah][1] boards? It's small, inexpensive ($10), comes with wireless capability and a 10-bit ADC for a temperature sensor. If you'll have access to the Internet, then you could use NTP to get time.

[1]: https://www.adafruit.com/products/2471


body:
I have two Lidar Lites, connected to one APM. I have no issue with getting data from one of them, i use the code below

    #include <I2C.h>
    #define    LIDARLite_ADDRESS   0x62          // Default I2C Address of LIDAR-Lite.
    #define    RegisterMeasure     0x00          // Register to write to initiate ranging.
    #define    MeasureValue        0x04          // Value to initiate ranging.
    #define    RegisterHighLowB    0x8f          // Register to get both High and Low bytes in 1 call.

    void setup(){
      Serial.begin(9600); //Opens serial connection at 9600bps.
      I2c.begin(); // Opens & joins the irc bus as master
      delay(100); // Waits to make sure everything is powered up before    sending or receiving data
      I2c.timeOut(50); // Sets a timeout to ensure no locking up of sketch if I2C communication fails
    }

    void loop(){
     // Write 0x04 to register 0x00
      uint8_t nackack = 100; // Setup variable to hold ACK/NACK resopnses
      while (nackack != 0){ // While NACK keep going (i.e. continue     polling until sucess message (ACK) is received )
        nackack = I2c.write(LIDARLite_ADDRESS,RegisterMeasure, MeasureValue); // Write 0x04 to 0x00
        delay(1); // Wait 1 ms to prevent overpolling
      }

      byte distanceArray[2]; // array to store distance bytes from read function

      // Read 2byte distance from register 0x8f
      nackack = 100; // Setup variable to hold ACK/NACK resopnses
      while (nackack != 0){ // While NACK keep going (i.e. continue polling until sucess message (ACK) is received )
        nackack = I2c.read(LIDARLite_ADDRESS,RegisterHighLowB, 2, distanceArray); // Read 2 Bytes from LIDAR-Lite Address and store in    array
       delay(1); // Wait 1 ms to prevent overpolling
      }
      int distance = (distanceArray[0] << 8) + distanceArray[1];  // Shift high byte [0] 8 to the left and add low byte [1] to create 16-bit int

      // Print Distance
      Serial.println(distance);
    }

i can get the distance fine, now have two connected, as follows

[![enter image description here][1]][1]

So my noob question is how to i get data from the 2, my guess is the wiring is ok.

I am using the code from [https://github.com/PulsedLight3D/LIDARLite_v2_Arduino_Library][2]

  [1]: https://i.stack.imgur.com/Ti90l.png
  [2]: https://github.com/PulsedLight3D/LIDARLite_v2_Arduino_Library

any help would be appreciated. thanks.

title: Multiple I2C Devices connected parallel

Answers: 1

body:
Connect one at a time and run the [change address sketch](https://github.com/PulsedLight3D/LIDARLite_v2_Arduino_Library/blob/master/LIDARLite/examples/Single Sensor/Change_I2C_Address/Change_I2C_Address.ino) mentioned by Yeti.

Naturally change each one (one at a time) to different addresses (ex. 0x62, 0x64, 0x66).

> i still don't know whats the address of the 2nd one

The address is what you change it to.

Then connect them all back up again and run the I2C scanner. You should see all 3 addresses.

---

> documents state that address changes will be gone when i power it off

If that is true, save the address for each module in EEPROM. Then use that code to change the module address in `setup`.

---

See the address in the code you posted?

    #define    LIDARLite_ADDRESS   0x62          // Default I2C Address of LIDAR-Lite.

If you don't want to save the address in EEPROM just upload three versions of the sketch with a different address in each one. Note that the address must be even (eg. 0x62, 0x64, 0x66).

But it would be very simple just to read from EEPROM in `setup` and keep the address in a variable rather than a #define.


body:
I am trying to write a simple software PWM to fade some LEDs because I don't have enough PWM I/O Ports.

The code evaluates how long you want the LED to fade, and breaks it down into a number of steps. During each step, it will evaluate the period the LED should be on.

I have the following code:

    class Led{
      public:
        Led(int pin);
        void setup();
        // void updateFadeDirection();
        void updateBrightness();

      private:
        int _pin;
        unsigned long _currentTime;
        unsigned long _startTime; // Very beginning of fade period
        unsigned long _fadePeriod; // How long to fade on and off
        int _fadeStep; // current fade step i.e. 1/255
        int _fadeSteps; // How many steps to take until full brightness
        int _fadeDirection; // low to high or high to low?
        float _T_on; // Amount of time to turn LED on
        float _T_fadeStep; // Amount of time per step increment of brightness
        unsigned long _stepTime; // Start of current step period

        bool _evaluated;
    };

    Led::Led(int pin){
      _pin = pin;
    }

    void Led::setup(){
      pinMode(_pin, OUTPUT);
      _startTime = micros();
      _fadePeriod = 2*1000000; //microseconds(us)
      _fadeStep = 50; // start at 0 brightness here
      _fadeSteps = 100;
      _fadeDirection = 1;

      _T_fadeStep = _fadePeriod/_fadeSteps; // i.e. 2000000us/100steps = 20000us/step of brightness
      _T_on = (_fadeStep/_fadeSteps) * _T_fadeStep; // i.e. 20/100 * 20000us = 4000us on

      _stepTime = micros();
      delayMicroseconds(200);
    }

    void Led::updateBrightness(){
      _currentTime = micros();

      if(_currentTime - _startTime < _fadePeriod){
        if (_currentTime - _stepTime > _T_on){
          digitalWrite(_pin, LOW);
        } else {
          digitalWrite(_pin, HIGH);
        }

        if(_currentTime - _stepTime >= _T_fadeStep){
          // _fadeStep++;
          _stepTime = _currentTime;
          _T_on = (_fadeStep/_fadeSteps) * _T_fadeStep;
        }
      }
      else{
        digitalWrite(_pin, HIGH);
      }
    }

    Led LED0(0);

    void setup() {
      LED0.setup();
    }

    void loop() {
      LED0.updateBrightness();
    }

The current behaviour when powered on is the single LED will be turned off, then will turn on after 2 seconds.

In particular, it never seems to enter the `else` part

      if (_currentTime - _stepTime > _T_on){
        digitalWrite(_pin, LOW);
      } else {
        digitalWrite(_pin, HIGH);
      }

The problem is that the LED will never hit `HIGH` until the outer `else` is triggered.

I believe it has to do with `_T_on` being an `int` and the timestamps being `unsigned long` and me not casting it.

The expected behaviour is 2 seconds of dimmed (50%) light, and then a full 100% when it hits the outer `else`.

title: Arduino non-blocking software PWM LED fader not working

Answers: 1

body:
As @ott-- has mentioned, because of the `int` datatype, `_fadeStep`/`_fadeSteps` will always evaluate to 0.

Here's the updated code along with some timing tweaks:

    float fadeSteps = 150; // How many steps to take until full brightness

    class Led{
      public:
        Led(int pin, float fadeStep=0);
        void setup();
        // void updateFadeDirection();
        void updateBrightness();

      private:
        int _pin;
        unsigned long _currentTime;
        unsigned long _startTime; // Very beginning of fade period
        unsigned long _fadePeriod; // How long to fade on and off
        float _fadeStep; // current fade step i.e. 1/255
        int _fadeDirection; // low to high or high to low?
        unsigned long _T_on; // Amount of time to turn LED on
        unsigned long _T_fadeStep; // Amount of time per step increment of brightness
        unsigned long _stepTime; // Start of current step period

        bool _evaluated;
    };

    Led::Led(int pin, float fadeStep){
      _pin = pin;
      _fadeStep = fadeStep;
    }

    void Led::setup(){
      pinMode(_pin, OUTPUT);
      _startTime = micros();
      _fadePeriod = 2000000; //microseconds(us)
      _fadeDirection = 1;

      _T_fadeStep = _fadePeriod/2/fadeSteps; // i.e. 2000000us/100steps = 20000us/step of brightness
      _T_on = (_fadeStep/fadeSteps) * _T_fadeStep; // i.e. 20/100 * 20000us = 4000us on

      _stepTime = micros();
    }

    void Led::updateBrightness(){
      _currentTime = micros();
      if (_currentTime - _stepTime > _T_on){
        digitalWrite(_pin, LOW);
      } else {
        digitalWrite(_pin, HIGH);
      }

      if(_currentTime - _stepTime >= _T_fadeStep){
        _fadeStep += _fadeDirection;
        _stepTime = _currentTime;
        _T_on = (_fadeStep/fadeSteps) * _T_fadeStep;
      }

      if(_fadeStep >= fadeSteps-1) {
        _fadeDirection = -1;
      } else if(_fadeStep <= 1) {
        _fadeDirection = 1;
      }
    }

    Led LED0(0);
    Led LED1(1,fadeSteps/5);
    Led LED2(2,2*fadeSteps/5);
    Led LED3(3,3*fadeSteps/5);
    Led LED4(4,4*fadeSteps/5);

    void setup() {
      LED0.setup();
      LED1.setup();
      LED2.setup();
      LED3.setup();
      LED4.setup();
    }

    void loop() {
      LED0.updateBrightness();
      LED1.updateBrightness();
      LED2.updateBrightness();
      LED3.updateBrightness();
      LED4.updateBrightness();
    }

Some refactoring is needed to be more modular, but will fade (using software PWM) LEDs asynchronously on every digital OUT port on an attiny85. Can also set the starting brightness so that you can make an LED fading chaser.


body:
I am doing a project which needs to meet the following specifications.

> On receiving an SMS arduino will start switching 1st relay on after some
> time duration(say 30 Seconds) relay 1 will be turned off and it will now turn on 2nd relay for (say 20seconds) so on 1>2>3>4.

The problem im facing is managing the time intervals between the switching process,i did think of using millis() i.e **(currentMillis-previousMillisx>Intervalx)** as in blinkWithoutDelay ,how ever this will work only once as i dont not know when will the next SMS come to the system ,if the user decides to send the message after 1hour currentMillis-previousMillisx will always return true so i cannot keep the motor on for (Say 30 seconds) and same will happen with all 4 cases.

If there is any alternative logic for this problem please suggest me or can i just add RTC for my project to manage time easily

Thank You

title: Managing timer intervals using millis at random intervals

Answers: 3

body:
You could use timer interrupts. I've (successfully) used the [TimerOne][1] library. There are countless other libraries that allow you to use timer interrupts easily. "Start" the timer when you receive the SMS message. You could use a pair of boolean flags to keep track of the two relays with one timer.

  [1]: https://github.com/PaulStoffregen/TimerOne

body:
Well, you need a sort of tracking for your active relay, don't you? So you just have to reset that tracking variable and the previousMillis variables and you are done.

Some code (note: untested and moreover I don't know how you are receiving the SMS)

    // The intervals for the different relays
    const byte Intervals[] = {30, 20, 10, 5};

    // The current state. 0 means relay 1 on,
    // 1 means relay 2 on, 2->3 and 3->4, while
    // 4 means no relay activated
    byte currentState = 4;

    unsigned long previousMillis;

    void loop()
    {
     if (received_sms)
     {
      currentState = 0;
      previousMillis = millis();
      digitalWrite(RELAY1, HIGH);
      // Maybe turn off all the other relays?
     }

     if (currentState < 4)
     { // Active state: check if we should advance
      unsigned long currentInterval = ((unsigned long)Intervals[currentState])*1000;
      while ((millis() - previousMillis) >= currentInterval)
      { // Advance to the next step
       switch(currentState)
       {
        case 0: // Advance from state 0 to 1
         digitalWrite(RELAY1, LOW);
         digitalWrite(RELAY2, HIGH);
         // Maybe turn off all the other relays?
         previousMillis += currentInterval;
         currentState = 1;
         break;
        ...
        // cases 1, 2, 3
        ...
        default:
         // It should never reach this
         previousMillis = millis();
         currentState = 4;
         break;
       }
      }

     }
    }

body:
I do not really understand your problem. More specifically,
“currentMillis-previousMillisx will always return true” does not make
sense, as it is not a boolean expression (it's `unsigned long`).

Anyway, the technique shown in blinkWithoutDelay is the way to go. Here
is my (untested) version:

<!-- language: lang-c++ -->

    const int relay_count = 4;  // we have 4 relays
    const int relay_pins[relay_count] = {2, 3, 4, 5};
    const unsigned long durations[relay_count] = {30000, 20000, 15000, 10000};
    bool sms_received();  // you implement this one

    void loop()
    {
        static int current_relay = -1;  // meaning: no active relay
        static unsigned long last_switch;
        unsigned long now = millis();

        // If no relay is active, wait for an SMS.
        if (current_relay == -1) {
            if (sms_received()) {
                // Switch on first relay.
                current_relay = 0;
                digitalWrite(relay_pins[current_relay], HIGH);
                last_switch = now;
            }
        }

        // Otherwise, switch relays when it is time to do so.
        else if (now - last_switch >= durations[current_relay]) {
            digitalWrite(relay_pins[current_relay], LOW);
            if (++current_relay == relay_count) {
                current_relay = -1;  // no active relay
            } else {
                digitalWrite(relay_pins[current_relay], HIGH);
                last_switch = now;
            }
        }
    }

BTW, you did not specify what should happen if you receive an SMS while
one of the relays is active. I assume the SMS are only acknowledged when
no relay is active. Otherwise you would have to change the code.


body: I was wondering if it is possible to send commands through the OBD-II on my car via an Arduino Uno Rev 3 with a CAN-BUS Shield from SEEDStudio. I am just going for basic functions i.e. lock control, window control, lights nothing really outside of those basic functions. My shield is currently in the mail and I was hoping anyone could shed light as to if this is even possible. My car model is a 2004 Mini Cooper S. Thanks.

title: Car Control via OBD-II port

Answers: 1

body:
Technically, yes: If you hook up this shield to the car buses through OBD-II, and know which messages to send (e.g., ones that the car will accept and work with), then it will work.

The problem is: There are some "official" messages, basically emission related stuff, that are mandatory on every cars. There are lists of these out there.
Unfortunately, most messages are OEM dependent (including those that may control the basic features you mentioned), and they don't want you to mess around this.
Said differently: The semantic of CAN frames/messages varies from one car to another.

Being able to send receive CAN frames (which this shield is) is like being able to emit sounds & hear them: Mandatory, if you want to discuss with someone, but useless/not enough if you do not speak the same language.


body:
I have two, three-wire load sensors (https://cdn.sparkfun.com//assets/parts/4/5/9/5/10245-01.jpg) hooked up in a half wheatstone bridge (I think), with two 1K resistors.  Using a multimeter, I am reading small voltage changes when applying pressure to either strain gauge, when measured on between the pins A+ and A- on the HX711 ADC amp, however my Arduino serial output shows all 0's when using a variety of code examples (for example, this one:  http://www.dfrobot.com/wiki/index.php/Weight_Sensor_Module_V1#Sample_code).

My concern is that my circuit is not setup correctly as I am fairly novice, however everything I have researched about wheatstone bridges, and half wheatstone bridges seems fairly straightforward, and seems to match my circuit.  Any guidance/advice on the attached breadboard circuit diagram would be extremely helpful.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/xkkqy.jpg

title: 3-wire strain gauge - HX711 Issue

Answers: 1

body:
In your diagram, the fixed 1KΩ resistors both tie to +5V at one set of ends, and their other ends tie to A+ and A-.  The strain gauges are from A+ to ground and A- to ground.

In a typical scale, where several strain gauges are similarly loaded, that topology will produce about zero volts between A+ and A-.  By contrast, the following  topology (from: [blog.l3l4.com](http://blog.l3l4.com/tag/load-cell/)) produces higher voltages for higher loading.  (Diagram uses S+, S- rather than A+, A-)

(I realize your question shows some voltage changes when sensors are separately loaded, so this answer might not be relevant to your current problem.)

[![Wheatstone bridge on a SparkCore with HX711][1]][1]

  [1]: https://i.stack.imgur.com/B4mFf.jpg


body:
In short, I've hooked up an HM-10 to digital pins 10 and 11 on my Uno (required because TX/RX (0/1) can't be used whilst a serial connection is present). The Bluetooth module is a [Sunfounder HM-10][1] which comes with a [data sheet][2]. I'm successfully communicating with the HM-10 and I've written a modified version of serial comms tutorial code provided so it stores the reads up in a buffer before outputting them which works fine, I can set all properties on the HM-10 using this method.

The delays were necessary as it seems the clock cycle can't 'keep up' - bytes go missing when reading/writing, so if I attempt to write by just using `Serial.read()` in `loop()` alone then not all of it is read/written.

Here's the code.

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); // RX, TX

    void setup()
    {
      // Open serial communications and wait for port to open:
      Serial.begin(57600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      Serial.println("Goodnight moon!");

      delay(500);

      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);
      mySerial.print("Wake up wake up wake up wake up wake up! Wake up wake up wake up wake up wake up!");
    }

    void loop() // run over and over
    {
      if (mySerial.available()) {
        String s = "";
        char c;
        while((c = mySerial.read()) != -1) {
          s += c;
          delay(10);
        }

        Serial.println("Received: " + s);
      }

      if (Serial.available()) {
        String s = "";
        char c;
        while((c = Serial.read()) != -1) {
          s += c;
          delay(10);
        }

        delay(10);

        Serial.println("Sent: " + s);

        mySerial.print(s);
      }
    }

This allows me to show input and output as follows:

    Sent: AT+ADDR?
    Received: OK+ADDR:F4B85EB42D64
    Sent: AT+ADVI?
    Received: OK+Get:0
    Sent: AT+ALLO?
    Received: OK+Get:0
    Sent: AT+BATT?
    Received: OK+Get:077

So good so far. Here's what I can't figure out from the data sheet. How do I make the bluetooth module discoverable on, say, my Mac or from my iPhone? I've tested setting `AT+ROLE0` or `AT+ROLE1` followed by `AT+RESET` and also set `AT+NAME` so I know what to expect, yet I can't discover the module.

Also to note, the status LED is flashing as per the specification as an unconnected status (500ms high, 500ms low) which indicates `AT+PIO10` is setup. `AT+ADTY?` is set to 0 which allows it to be advertising, responds to scanning and connectable.

I'm likely missing something quite obvious. Any ideas?

  [1]: http://www.sunfounder.com/index.php?c=show&id=38&model=HM-10
  [2]: http://www.sunfounder.com/js/edit/attached/file/Bluetooth4_en.zip

title: Arduino Uno, HM-10 Bluetooth Module, Not Discoverable

Answers: 2

body:
Ah, I jumped the gun. Just found out Mac/iPhone can't scan for BLE devices, so I downloaded a BLE scanning app and once I set AT+ROLE0 and AT+RESET it appeared.

So, the answer is you need a BLE scanning application.

body: Thanks for your answer! In another thread, I found a free iOS bluetooth scanning app called LightBlue Explorer (https://itunes.apple.com/au/app/lightblue-explorer-bluetooth/id557428110?mt=8) which also lets you read/write to the device. Super handy. Adding that here for the next person who encounters this thread and wants a rec for a scanning app.


body:
I'm using an Arduino Uno to read from a "HID multiCLASS (RP40CKPNN) reader", which is a stand-alone reader that reads cards and returns a number of bits via Weigand Data0/Data1 protocol.  The "multiCLASS" readers can read both 125HZ PROX tags, and 13.57MHz mifare tags.

I have it reading and decoding 125HZ (multiple-PROX format) tags of various bit-lengths just fine, but when the reader is presented with a 13MHz card (specifically Mifare cards) the reader decodes the CSR/UID of ALL Mifare cards to 32bits.  The Mifare cards come in two types, Classic (that use a 4byte UID), and Ultra (that use a 7byte UID), so I would expect 32bits for the Classic cards, and 56bits for the Ultra, but I only ever get back 32bits.

The reader's data-sheets specifically calls out that for mifare tags it should return a 32bit or 56bit CSR value based on the serial number of the card, but I've looked through lots of HID literature on this reader, and I can't find any specifics on how to change/modify its configuration.

Does anyone have any experience with these readers, and is there some trick to changing the configuration so that it returns more bits for Mifare cards?

title: HID multiCLASS RFID reader all Mifare to Wiegand 32bit

Answers: 1

body:
For this specific reader, communication is only one way, from the reader to the Arduino via Weigand protocol.  Because of this, changes to the configuration for these readers is handled by proprietary RFID cards obtained from HID Global. The reader reads the card, and changes its configuration accordingly.  I was able to reach out to HID Global technical support and they are sending me a card that will change the configuration to output 56bit CSN/CSR/UID for mifare cards (which will cover the 7byte UID of mifare ultra).

Thanks for the comments that helped me work this through.


body:
I send a date from my android to arduino without problem, but also i want send date from arduino to android later of received the date from android.

I have time trying it, but i can not yet, help me.
My codec of arduino

    char enter;
    #include <SoftwareSerial.h>
    SoftwareSerial conect(10,11);

    void setup()
    {
     pinMode(8,OUTPUT);
     conect.begin(9600);
     digitalWrite(8,LOW);
    }

    void loop()
    {
     if(conect.available()>0)
      {
       enter=conect.read();
       if(entrada=='1')
       {
        digitalWrite(8,HIGH);
        conect.print("1");
       }
     }
    }

And in the side from android this is my handler for drive the the date that arrive.

     Handler mhandler=new Handler(){
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case CONECTADO:
                    //ManejarDatos msjre = new ManejarDatos((BluetoothSocket)msg.obj);
                    msjre = new ManejarDatos((BluetoothSocket)msg.obj);
                    break;
                case MENSAJELEYENDO:
                    byte[] readBuf = (byte[])msg.obj;
                    String string = new String(readBuf,0,msg.arg1);
                    Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };

And on my class for read and write i have this

    private class ManejarDatos extends Thread
    {
        private final OutputStream salidadatos;
        private final BluetoothSocket sockk;
        private final InputStream entradadatos;
        public ManejarDatos(BluetoothSocket socke1)
        {
            sockk=socke1;
            OutputStream temporalsalida=null;
            InputStream temporalentrada=null;
            try
            {
                temporalentrada=socke1.getInputStream();
                temporalsalida=socke1.getOutputStream();
            }catch (IOException e){}
            salidadatos=temporalsalida;
            entradadatos=temporalentrada;
        }
        public void run()
        {
            byte[] espera;
            int esperaalmacen;
            while (true) {
                try {
                    espera=new byte [1024];
                    esperaalmacen=entradadatos.read(espera);
                    mhandler.obtainMessage(MENSAJELEYENDO,esperaalmacen,-1,espera)
                            .sendToTarget();
                }catch (IOException e){break;}
            }
        }
        public void escribe(byte[] bytes)
        {
            try {
                salidadatos.write(bytes);
                //handler.obtainMessage(MENSAJE_SALIDA,-1,-1,bytes).sendToTarget();
            }catch (IOException e){
                //Log.e(TAG, "....Error al enviar dato" + e.getMessage() + "...");
            }
        }
        public void cancel()
        {
            try{
                sockk.close();
            }catch (IOException e){}
        }

    }

When i push button, send a date to arduino, here my codec of button(i send 1 for bluetooth)

            Enviar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String salida="1";
                msjre.escribe(salida.getBytes());
            }
        });

title: Connection bluetooth master and slave with Android

Answers: 2

body:
First try

  if(conect.available()>0)
 {
enter=conect.read();
if(1)
{ digitalWrite(8,HIGH);
 conect.print("1");
}
 }
 }

If that works,  think about what entreda is and that exactly you're trying to do there.

body:
What is `entrada`? Replace `entrada` with `enter` in your arduino code and try again. Also try this `run()` code instead:

    public void run()
    {
        byte[] espera = new byte[1024];
        int esperaalmacen;
        while (true) {
            try {
                esperaalmacen=entradadatos.read(espera);
                mhandler.obtainMessage(MENSAJELEYENDO,esperaalmacen,-1,espera)
                        .sendToTarget();
            }catch (IOException e){break;}
        }
    }


body:
I'm trying to use an Arduino Uno to read values from a 2-axis joystick analogue input, and alter these values. Rather than the true joystick values, I arithmetically convert the values at neutral to range between 0 - 5, with 'neutral', i.e. when the joystick isn't being pushed, being at roughly 2.5 for each axis. These joystick values currently output to a live text file, to be graphed in real-time. One function I'm trying to implement is that when the joystick value is greater or less than a defined value (e.g. in the code, greater than 4.55, or less than 0.5)  that the Arduino sets that point to be the new 'neutral' position (i.e. 2.5), however my code at the moment isn't working and I'm not sure how to go about attempting this.

Any insight would be most appreciated!

Cheers

    const int buttonPin = 2;
    const int successPin = 13;

    int buttonState = 0;

    void setup()
    {
    // initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
    pinMode (buttonPin, INPUT);
    pinMode (successPin, OUTPUT);
    while (digitalRead(buttonPin) == LOW) {};
    }

    void loop () {

    int sensorValueY = analogRead(A0);
    int sensorValueX = analogRead(A1);

    //arithmetic operation that maps output values from 0 - 5 instead of 0 - 1023
    float voltageX = sensorValueX * (5.0 / 1023.0);
    float voltageY = sensorValueY * (5.0 / 1023.0);
    Serial.print(voltageX);
    Serial.print(" , ");
    Serial.print(voltageY);

    if (voltageX >= 4.55) {
      voltageX == 2.5;
      successPin==HIGH;
      delay(1);
      successPin==LOW;
    }

    if (voltageX <= 0.5) {
      voltageX ==2.5;
      successPin==HIGH;
      delay(1);
      successPin==LOW;
    }

    if (voltageY >=4.55) {
      voltageY == 2.5;
      successPin==HIGH;
      delay(1);
      successPin==LOW;
    }

    if (voltageY <= 0.5) {
      voltageY ==2.5;
      successPin==HIGH;
      delay(1);
      successPin==LOW;
    }
    Serial.println();

    }

title: How to alter joystick values with Arduino Uno?

Answers: 1

body:
<!-- language-all: lang-C++ -->

    if (voltageX >= 4.55) {
      voltageX == 2.5;
      successPin==HIGH;

The last two lines (and all similar ones later) are wrong. `==` is for **comparing**, `=` is for **assigning**. So change it to:

    if (voltageX >= 4.55) {
      voltageX = 2.5;
      successPin = HIGH;

You did that in a lot of places, so fix that up and get back to us.

---

    const int successPin = 13;
    ...
      successPin = HIGH;

Assuming you fix the compare to an assign you will get an error message here. You define successPin as 13, and then try to change it to 1 (which is what HIGH is defined as). Do you mean, to write to that pin? Like this?

    digitalWrite (successPin, HIGH);

You will need to change all those as well. And if you are hoping to see an LED on the pin flash, 1 ms is quite a small interval.


body:
Here is my code:

    #include <SPI.h>
    #include <OneWire.h>
    #include <EthernetV2_0.h>
    #include <EthernetClientV2_0.h>
    #include <EthernetServerV2_0.h>
    #include <EthernetUdpV2_0.h>
    #include <math.h>
    #include <Client.h>
    #include <WString.h>
         #include <stdlib.h>
    #include <OneWire.h>
    #include <stdio.h>
    #include <DhcpV2_0.h>
    #include <DnsV2_0.h>

    int whiteLevel;
    int colorLevel;
    int blueLevel;
    int standardLightingPattern[3] = { 200, 160, 250 };
    int twilightLightingPattern[3] = { 20, 50, 100 };
    int nightTimeLightingPattern[3] = { 0, 10, 40 };
    int morningLightingPattern[3] = { 50, 50, 100 };
    int deepNightLightingPattern[3] = { 0, 20, 80 };
    int feedingLightingPattern[3] = { 20, 20, 50 };
    int i;
    int j;
    char *buildUrlParameter(float ph, float temp1, float temp2);

    // Pin Delcarations
    int temperaturePins[2] = { 30,31 };
    int outletPins[] = { 22, 23, 24, 25, 26, 27 };
    const int whiteLedString = 44;    // connected to LDD-700HW on white strand
    const int colorLedString = 45;    // connected to LDD-1000HW on color strand
    const int blueLedString = 46;     // connected to LDD-1000HW on royal blue     strand

    // Sensor Variables
    float temps[2];
    String sensorstring = "";
    boolean sensor_string_complete = false;
    float pH;

    // Variables for URL char buffer
    char outBuf[100];
    char charBuf[6];
    char cnctPh[6];
    char cnctTemp1[7];
    char cnctTemp2[7];
    char urlParameter[34];
    char dest1[34];

    //char serverIP[] = "74,125,224,80";
    //char serverIP[] = "192.168.1.107";
    //char serverIP[] = "www.arduino.cc";

    // assign a MAC address for the ethernet controller.
    // fill in your address here:
    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
    // fill in an available IP address on your network here,
    // for manual configuration:
    IPAddress ip(192,168,1,199);

    // fill in your Domain Name Server address here:
    IPAddress myDns(8,8,8,8);

    // initialize the library instance:
    EthernetClient client;

    char server[] = "192.168.1.107";

    unsigned long lastConnectionTime = 0;          // last time you connected to the server, in milliseconds
    boolean lastConnected = false;                 // state of the connection last time through the main loop
    const unsigned long postingInterval = 10*1000;  // delay between updates, in milliseconds
    #define W5200_CS  10
    #define SDCARD_CS 4
    void setup() {
       // start serial port:
     Serial.begin(38400);
     Serial3.begin(38400);
     pinMode(SDCARD_CS,OUTPUT);
      digitalWrite(SDCARD_CS,HIGH);//Deselect the SD card
      // give the ethernet module time to boot up:
       delay(1000);
      // start the Ethernet connection using a fixed IP address and DNS server:
      Ethernet.begin(mac, ip, myDns);
      // print the Ethernet board/shield's IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {
      char c;
      dimLights(standardLightingPattern);
      dimLights(nightTimeLightingPattern);

      // if there's no net connection, but there was one last time
      // through the loop, then stop the client:
      if (!client.connected() && lastConnected) {
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();
      }
      // if you're not connected, and ten seconds have passed since
      // your last connection, then connect again and send data:
      if(!client.connected() && (millis() - lastConnectionTime >    postingInterval)) {
        getPh();
        getTemperature();
        httpRequest();
      }
      // store the state of the connection for next time through
      // the loop:
      lastConnected = client.connected();
    }

    void getPh() {
      Serial3.print("r<CR>");
      if (sensor_string_complete == true) {
       //Serial.println(sensorstring);
       if (isdigit(sensorstring[0])) {
          pH = sensorstring.toFloat();
        }
      }

     sensorstring = "";
     sensor_string_complete = false;
    }

    void dimLights(int lightingBrightnessArray[]) {
      analogWrite(whiteLedString, lightingBrightnessArray[0]);
      analogWrite(colorLedString, lightingBrightnessArray[1]);
      analogWrite(blueLedString, lightingBrightnessArray[2]);

    }

    float getTemp(int pin) {
      OneWire ds(pin);
      byte k;
      byte present = 0;
      byte type_s = 0;
      byte data[12];
      byte addr[8];
      float celsius;
      float fahrenheit;

      if (!ds.search(addr)) {
        Serial.println("No more addresses.");
        Serial.println();
        ds.reset_search();
        delay(2500);
      }

      ds.reset();
      ds.select(addr);

      // start conversion, with parasite power on at the end
      ds.write(0x44, 1);

      // maybe 750ms is enough, maybe not
      delay(1000);

      present = ds.reset();
      ds.select(addr);

      // Read Scratchpad
      ds.write(0xBE);

      // we need 9 bytes
      for (k = 0; k < 9; k++) {
        data[k] = ds.read();
      }

      int16_t raw = (data[1] << 8) | data[0];
      if (type_s) {

       // 9 bit resolution default
       raw = raw << 3;

       if (data[7] == 0x10) {
         // "count remain" gives full 12 bit resolution
          raw = (raw & 0xFFF0) + 12 - data[6];
        }
        } else {
          byte cfg = (data[4] & 0x60);
          // at lower res, the low bits are undefined, so let's zero them
          if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
          else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
          else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms

         // default is 12 bit resolution, 750 ms conversion time
        }

        celsius = (float)raw / 16.0;
        fahrenheit = celsius * 1.8 + 32.0;
        return fahrenheit;
    }

    void getTemperature() {

     //get temperature 1 from display
      temps[0] = getTemp(temperaturePins[0]);
      delay(1000);

      //get temperature 2 from sump
      temps[1] = getTemp(temperaturePins[1]);
      delay(1000);

      //used for building parameters for GET request for passing DB values
      Serial.println("");
      float temp1 = temps[0];
      float temp2 = temps[1];
      //converts pH sensor char buffer to float val
      //float pH = atof(stamp_data);

      //used for debugging
      Serial.println("Returned Temp 1: ");
      Serial.println(temp1);
      Serial.println("Returned Temp 2: ");
      Serial.println(temp2);
      Serial.println("ph val:");
      Serial.println(pH);

      //build url for GET request using above parameters
      *buildUrlParameter(pH, temp1, temp2);
      Serial.println(dest1);
      //make HTTP request
       httpRequest();
    }

    char *buildUrlParameter(float pH, float temp1, float temp2) {
      //builds char buffer from three float values passed from
      //sensors and apends proper sensor monikers
      dtostrf(pH, 4, 2, cnctPh);
      dtostrf(temp1, 5, 2, cnctTemp1);
      dtostrf(temp2, 5, 2, cnctTemp2);
      strcpy(dest1, "ph=");
      strcat(dest1, cnctPh);
      strcat(dest1, "&T1=");
      strcat(dest1, cnctTemp1);
      strcat(dest1, "&T2=");
      strcat(dest1, cnctTemp2);

      return dest1;
    }

     // this method makes a HTTP connection to the server:
       void httpRequest() {

       sprintf(outBuf, "GET http://192.168.1.107/ReefController/trunk/app/php/reef_controller_loadVals_all.php?%s HTTP/1.0", dest1);
       Serial.println(outBuf);
    //Serial.println("connecting...");
     delay(1000);
      //client.connect(server, 80);

      // if there's a successful connection:
      if (client.connect(server, 80)) {
        client.println(outBuf);
        Serial.println("connecting...");
        // send the HTTP PUT request:
        client.println("Host: localhost");
        client.println("User-Agent: arduino-ethernet");
        client.println("Content Type: application/json");
        client.println("Connection: close");
        client.println();

        Serial.println("Successfully recorded to database");
        // note the time that the connection was made:
        lastConnectionTime = millis();
      }
      else {
        // if you couldn't make a connection:
        Serial.println("connection failed");
        Serial.println("disconnecting.");
        client.stop();
      }
    }`

What is happening is when my program hits httpRequest the client.connect is successful maybe 2-3 times out of 5.  The PHP server is up and running fine.  It will just fall into the last else and give me connection failed / disconnecting when it isn't working.... when it does work I get a response back `500 internal server error` yet the PHP script runs and records my posted values to the database.  Any thoughts?

title: Arduino Ethernet intermittently connects to server

Answers: 1

body:
This is why I think the server returns a HTTP500:

Usually in HTTP requests you do not include the ip address, so:

`GET http://192.168.1.107/<really long part>?%s HTTP/1.0`

would become:

`GET /<really long part>?%s HTTP/1.0`

Also HTTP requests should use carriage return AND line feed to indicate the end of a line.
And an HTTP request should ALWAYS end in a full blank line.
You are using the HTTP1.0 protocol, so your request can be done in one line, so you can just end it with: `\r\n\r\n`. If your request would be multiple lines, every line should also end with `\r\n`.

So the result would be:

`GET /<really long part>?%s HTTP/1.0\r\n\r\n`

One `CRLF` (the `\r\n` part) to begin a new line and one more for the blank line.

As for the connection problem, I think this has to do with the fact that you need to open AND close the connection for each HTTP request. You are using the HTTP1.0 protocol which does not support multiple HTTP requests in one connection. You can send multiple HTTP requests when using HTTP1.1, but then you also have to think about the TCP keepalive and it makes your request more complicated.

Try changing your HTTP request as mentioned above and call  client.connect() and a client.stop() for every HTTP request. And don't forget to tell us the results!


body:
I am trying to figure out what I did wrong in my sketch.  In my void loop(), at the very bottom of the sketch, my if/else statement keeps compiling with the above error.  Originally, it was an if/else if/else statement.  I had the current else's an else if and the Update in my else.  Someone had corrected me on it and i removed the code and made the proper changes and the error started. Now, just for the sake of my sanity I went ahead and put the ';' at the end of my else, which I know is wrong, just to see if it compiled, which it did.  I ran the sketch and sure enough it broke the operation. I cannot figure out what it is looking for.  Any help would be appreciated.

        //ASHPD Barrel Version 4.0.2 (adding pulse) Created By Gixxerfool 01.11.2016

    #include <Adafruit_NeoPixel.h>
    #ifdef __AVR__
      #include <avr/power.h>
    #endif

    // Pattern types supported:
    enum  pattern {NONE, CHASE, PULSE};

    #define orange 255,128,0
    #define blue 0,0,255

    char targetColor = '0,0,255';

    // NeoPattern Class
    class NeoPatterns : public Adafruit_NeoPixel
    {
      public:

        // Member Variables:
        pattern  ActivePattern;  // which pattern is running

        unsigned long Interval;   // milliseconds between updates
        unsigned long lastUpdate; // last update of position

        uint32_t Color1;  // What color is used
        uint16_t TotalSteps;  // total number of steps in the pattern
        uint16_t Index;  // current step within the pattern

       // Constructor
        NeoPatterns(uint16_t pixels, uint8_t pin, uint8_t type)
        :Adafruit_NeoPixel(pixels, pin, type)

    {

    }
        // Update the pattern
        void Update()
        {
          if ((millis() - lastUpdate) > Interval) // time to update
          {
            lastUpdate = millis();
            switch (ActivePattern)
            {
              case CHASE:
                ChaseUpdate();
                break;
               // case PULSE:
                //PulseUpdate();
                //break;
              default:
                break;
            }
          }
        }

        // Increment the Index and reset at the end
        void Increment()
        {
            Index++;
            if (Index >= TotalSteps)
            {
              Index = 0;
            }
          }

        // Calculate 50% dimmed version of a color (used by ChaseUpdate)
        uint32_t DimColor(uint32_t color)
        {
            // Shift R, G and B components one bit to the right
            uint32_t dimColor = Color(Red(color) >> 1, Green(color) >> 1, Blue(color) >> 1);
            return dimColor;
        }
        // Returns the Red component of a 32-bit color
        uint8_t Red(uint32_t color)
        {
            return (color >> 16) & 0xFF;
        }

        // Returns the Green component of a 32-bit color
        uint8_t Green(uint32_t color)
        {
            return (color >> 8) & 0xFF;
        }

        // Returns the Blue component of a 32-bit color
        uint8_t Blue(uint32_t color)
        {
            return color & 0xFF;
        }

        // Initialize for a CHASE

    void Chase(uint32_t color1, uint8_t interval)
        {
            ActivePattern = CHASE;
            Interval = interval;
            TotalSteps = (numPixels());
            Color1 = color1;
            Index = 0;
        }

        // Update the Chase Pattern
        void ChaseUpdate()
        {
            for (int i = 0; i < numPixels() + 1; i++)
            {
                if (i == Index)  // Scan Pixel
                {
                     setPixelColor(i, Color1);
                }
                else // Fading tail
                {
                     setPixelColor(i, DimColor(getPixelColor(i)));
                }
            }
            show();
            Increment();
        }

    //Initialize for a pulse
    void Pulse(uint32_t color1, uint8_t interval)
        {
          ActivePattern = PULSE;
          Interval = interval;
          TotalSteps = 256;
          Color1 = color1;
          Index = 0;
        }

        //Update the Pulse
        void PulseUpdate()
       {
       for (int h = 0; h < 256; h++)
        {
        for (int i = 0; i < 126; i++)
         {
          for (int j = 0; j > -1; j--)
          {
          if (h == Index)
          {
          setPixelColor(i, Color1);
          }
          else
          {
          setPixelColor(j, Color1);
          }
        }
        show();
        Increment();
       }
      }
    }

    };
    // Define some NeoPatterns

    NeoPatterns Ring3(16, 4, NEO_GRB + NEO_KHZ800);
    NeoPatterns Ring2(12, 1, NEO_GRB + NEO_KHZ800);
    NeoPatterns Ring1(7, 0, NEO_GRB + NEO_KHZ800);

    // Initialize everything and prepare to start

    void setup()
    {
      // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
    #if defined (__AVR_ATtiny85__)
      if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
    #endif
      // End of trinket special code

    pinMode(2, INPUT); //Sets pin 2 as an input

      // Initialize all the pixels

      Ring1.begin();
      Ring2.begin();
      Ring3.begin();

      //Set all pixels to off

      Ring1.show();
      Ring2.show();
      Ring3.show();

      ring3Wipe(Ring3.Color(blue), 50); // Wipe ring 3 in blue once
      ring2Wipe(Ring2.Color(blue), 50); // wipe ring 2 in Blue once
      ring1FadeUpBlue(Ring1.Color(blue)); //Fade in ring1 once

      //Start the idle pattern
      //Name.PatternName(Name.Color(targetColor), Interval) Changing Interval will adjust the speed of the pattern
      Ring1.Pulse(Ring1.Color(blue), 500);
      Ring2.Chase(Ring2.Color(blue), 55);//keep the interval 15ms above ring3 for synchronicity
      Ring3.Chase(Ring3.Color(blue), 40);//keep the interval 15ms below ring2 for synchronicity

    }
        void ring1FadeUpBlue(uint8_t wait)
        {
       for(int j = 0; j < 255; j++)
       {
          uint32_t color = Ring1.Color(0, 0, j );  // ramp up the blue only
          for(uint16_t i=0; i < Ring1.numPixels(); i++)
          {
             Ring1.setPixelColor(i, color);
          }
          delay(7);
          Ring1.show();
       }
    }
    //wipes the ring2 once in blue
    void ring2Wipe(uint32_t c, uint8_t wait)
    {
        for(uint16_t i=0; i < Ring2.numPixels(); i++)  //This for loop runs reverse to ring3 loop
       {
          Ring2.setPixelColor(i, c);
          Ring2.show();
          delay(wait);
       }
    }

    //wipes the ring3 once for the color blue
    void ring3Wipe(uint32_t c, uint8_t wait)
    { //uint32_t and uint8_t are the colorWipe parameters c=color wait=#of ms between pixels. larger # slows the action
        for(uint16_t i=0; i < Ring3.numPixels(); i++)
       {
          Ring3.setPixelColor(i, c);
          Ring3.show();
          delay(wait);
       }
    }

    // Main loop
    void loop()
    {
      // Update the rings.
      Ring1.Update();
      Ring2.Update();
      Ring3.Update();

      // check for button press:
      if (digitalRead(2) == LOW) // Button is pressed
      {
        Ring3.Color1 = Ring3.Color(orange);//Change the target color to orange
        Ring2.Color1 = Ring2.Color(orange);
        Ring1.Color1 = Ring1.Color(orange);
      }
      else (digitalRead(2) == HIGH)//Kicks the color back to blue after the button is let go
      {
        Ring3.Color1 = Ring3.Color(blue);//Change the target color back to blue
        Ring2.Color1 = Ring2.Color(blue);
        Ring1.Color1 = Ring1.Color(blue);
      }
    }

title: expected ';' before '{' token error

Answers: 2

body:
This makes no sense - you can't store 7 characters in the space of one character:

    char targetColor = '0,0,255';

----
You're lacking an "if" here:

    } else (digitalRead(2) == HIGH) { //Kicks the color back to blue ...

----
You have numerous sign mismatches in comparisons.

body:
The if-else construct is incorrect.

It needs to be like this:

    if (condition)
    {
        //actions
    } else {
        //other actions
    }

Which reads: if the conditions are true, then do actions, otherwise do other actions.

OR it can be like like this

    if (condition)
    {
        //actions
    } else {
        if (other condition){
        //other actions
       }
    }

Which reads: if conditions are true, then do actions, otherwise, if other conditions are true, then do other actions.  Note that in this structure, if neither conditions or "other conditions" are true, then we do nothing.

So if DigitalRead can **only** be HIGH or LOW, then you don't need condition that in the "else" statement.  Your code can look like this:

     // check for button press:
      if (digitalRead(2) == LOW) // Button is pressed
      {
        Ring3.Color1 = Ring3.Color(orange);//Change the target color to orange
        Ring2.Color1 = Ring2.Color(orange);
        Ring1.Color1 = Ring1.Color(orange);
      }
      else
      {
        // digitalRead(2) must be HIGH if it's not LOW
        //Kicks the color back to blue after the button is let go
        Ring3.Color1 = Ring3.Color(blue);//Change the target color back to blue
        Ring2.Color1 = Ring2.Color(blue);
        Ring1.Color1 = Ring1.Color(blue);
      }

Only if digitalRead could return another value (e.g. 3, 100, 75 etc) then you would need the other conditions in your else clause, but the code would need to look like this:

     // check for button press:
      if (digitalRead(2) == LOW) // Button is pressed
      {
        Ring3.Color1 = Ring3.Color(orange);//Change the target color to orange
        Ring2.Color1 = Ring2.Color(orange);
        Ring1.Color1 = Ring1.Color(orange);
      }
      else
      {
        if (digitalRead(2) == HIGH)//Kicks the color back to blue after the button is let go
        {
          Ring3.Color1 = Ring3.Color(blue);//Change the target color back to blue
          Ring2.Color1 = Ring2.Color(blue);
          Ring1.Color1 = Ring1.Color(blue);
        }
      }

Note: you don't actually need the braces around the second "if" statement there, but it makes the structure more clear.


body:
Can you help me with the codes? I have gizduino(arduino clone), i used the codes in receiving sms from the internet but what i receive is a symbol "y" with two dots at the top. Whats wrong?

My gsm is set to suart.

<!-- language: c -->

    // Example 55.4

    #include <SoftwareSerial.h>
    SoftwareSerial SIM900(2,3);

    char incoming_char=0;

    void setup()
    {
      Serial.begin(19200); // for serial monitor
      SIM900.begin(19200); // for GSM shield
      SIM900power();  // turn on shield
      delay(20000);  // give time to log on to network.

      SIM900.print("AT+CMGF=1\r");  // set SMS mode to text
      delay(100);
      SIM900.print("AT+CNMI=2,2,0,0,0\r");
      // blurt out contents of new SMS upon receipt to the GSM shield's serial out
      delay(100);
    }

    void SIM900power()
    // software equivalent of pressing the GSM shield "power" button
    {
      digitalWrite(9, HIGH);
      delay(1000);
      digitalWrite(9, LOW);
      delay(7000);
    }

    void loop()
    {
      // Now we simply display any text that the GSM shield sends out on the serial monitor
      if(SIM900.available() >0)
      {
        incoming_char=SIM900.read(); //Get the character from the cellular serial port.
        Serial.print(incoming_char); //Print the incoming character to the terminal.
      }
    }

title: arduino and gsm module receive

Answers: 1

body:
Most probably you are using `sim900` or `sim800` module. These modules would be either fixed to a certain baudrate like `9600` or `115200`, OR the module might be at `auto-baud` mode.

In auto baud mode you need to send `AT\r` to the modem after the modem is switched ON so it can know what baud you are using.

Please check the following...

 - [GSM Modem/Module not responding to AT commands after firmware Upgrade??][1]
 - [Serial port AN][2]

  [1]: http://GSM Modem/Module not responding to AT commands after firmware Upgrade??
  [2]: http://simcom.ee/documents/SIM900/SIM900_Serial Port_Application Note_V1.03.pdf


body:
I just brought the camera OV7670 with fifo but I am unable to get the wiring of board with arduino and also I do not find any arduino library for OV7670 with fifo.

It will great if you can help to find some link which can help me.

Thanks,
Somnath

title: OV 7670 + FIFO (AL422B) with arduino

Answers: 1

body:
Here is a [link][1]. Use google to find more. It is not difficult.

  [1]: http://www.element14.com/community/docs/DOC-76210/l/trying-to-use-a-camera-module-to-show-footage-to-a-lcd-tft-screen