message:
Signal a LOW level interrupt with an RTC

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

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


sender: user

message:
Optocouplers for Arduino DCC decoder - Explain?

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

sender: assistant

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.


message:
Use Adafruit Colorsensor to distinguish between green and red

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?

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.


message:
Reverse the order of a hex string

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?

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


message:
Design Dilema -- What hardware?

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

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


message:
Multiple I2C Devices connected parallel

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.

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.


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

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`.

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.


message:
Managing timer intervals using millis at random intervals

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

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.


message:
Car Control via OBD-II port

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.

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.


message:
3-wire strain gauge - HX711 Issue

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

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


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

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

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.


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

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?

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.


message:
Connection bluetooth master and slave with Android

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());
            }
        });

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;}
        }
    }


message:
How to alter joystick values with Arduino Uno?

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();

    }

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.


message:
Arduino Ethernet intermittently connects to server

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?

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!


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

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);
      }
    }

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.


message:
arduino and gsm module receive

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.
      }
    }

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


message:
OV 7670 + FIFO (AL422B) with arduino

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

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


message:
Copy content of array

This may be an easy question, and if so im sorry, but i couldn't find out how to do this. I've programmed in python before and hoped that this would work, but it don't.

    int myArray1[] = {0, 2, 4, 5, 7, 9, 11};
    int myArray2[] = {0, 2, 3, 5, 7, 8, 10};
    int myArray3[] = {0, 3, 5, 6, 7, 10};

    int newArray[] = myArray2;

I wanted to only have to change one place in my code, which of the first three arrays i want my new array to take values from. Do anyone have any suggestions on how to do this?

body:
Make `newArray` be a pointer to whichever array you wish to work with.  For example:

    int myArray1[] = {0, 2, 4, 5, 7, 9, 11};
    int myArray2[] = {0, 2, 3, 5, 7, 8, 10};
    int myArray3[] = {0, 3, 5, 6, 7, 10};

    int *newArray = myArray2;

    // ... work with selected array, via newArray[] subscripting

Note, you may need to set an array-length variable at the same time as choosing the array.

For example:

    int *newArray = myArray2;
    int newSize = sizeof(myArray2)/sizeof myArray2[0];

    // ... work with selected array

    newArray = myArray3;
    newSize = sizeof(myArray3)/sizeof myArray3[0];
    // ... work with selected array

 Alternately, add an array-end marker at the end of each array (eg, a negative number), or more elegantly, make all the arrays the same length.

If you want to make a new copy of the original array, such that modifying the new array won't change the old, use (eg) `memcpy()`.  For example:

    int newArray[7];
    ...
    memcpy(newArray, myArray2, sizeof(myArray2));

Note that `memcpy()`'s size argument is given in bytes.  Also, if you need to declare `memcpy()` [I don't recall whether it's automatically declared in the Arduino environment], add `#include <string.h>` up front.


message:
Communication over I2C protocol with more than one A/D device

According to datasheet of MCP3021 A/D converter (Microchip, page 16) the MCP3021 can be accessed by proper address bits in control byte. In case of MCP3021 *5AT* the address is 101, in case of MCP3021 *4AT* the address is 100. Does than mean that to interface two MCP3021 diveces in one circuit one have to purchase two devices with *different* serial number, e.g. MCP3021 *5AT* and *4AT*?

body:
Yes, you need different devices for different addresses. Up to 8 addresses are possible:

> The first part
of the control byte consists of a 4-bit device code, which
is set to 1001 for the MCP3021. The device code is fol-
lowed by three address bits: A2, A1 and A0. The default
address bits are 101 (contact the Microchip factory for
additional address bit options).The address bits allow
up to eight MCP3021 devices on the same bus and are
used to determine which device is accessed

The number after the A in the part number indicates the address:

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

Off the shelf you get address 5. If you want other addresses you have to order them specially from Microchip.

The device sacrifices flexibility in favour of size. If you want multiple devices on the same bus and not have to order different parts specially then you generally end up with a bigger chip with more pins to allow you to manually configure the sub-address.

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


message:
Unable to initialize W5100 using Arduino Pro Mini

I am unable to initialize a W5100 module using an Arduino Pro Mini. I try setting the MAC and IP addresses but read invalid values thereafter.

Here is the Arduino program along with the output:

    void setup() {
        uint8_t mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
        uint8_t local_ip[] = {192, 168, 1, 100};
        Ethernet.begin(mac, local_ip);
        printMacAddress(); // OUTPUT: FF:FF:FF:FF:FF:FF
        printIpAddress(); // OUTPUT: 255.255.255.255
    }

    void printMacAddress() {
        uint8_t mac[6];
        W5100.getMACAddress(mac);
        Serial.print(mac[0], HEX); Serial.print(":"); Serial.print(mac[1], HEX); Serial.print(":");
        Serial.print(mac[2], HEX); Serial.print(":"); Serial.print(mac[3], HEX); Serial.print(":");
        Serial.print(mac[4], HEX); Serial.print(":"); Serial.print(mac[5], HEX); Serial.println();
    }

    void printIpAddress() {
        IPAddress ip = Ethernet.localIP();
        Serial.println(ip);
    }

I read in some blog posts that the Arduino may initialize before the W5100 initialization is completed so others recommend manually resetting the W5100 after Arduino initialization.
So I connected the W5100 reset pin to the Arduino digital output 4 and reset the W5100 during setup using the following code.

    const int W5100_RESET_PIN = 4;
    pinMode(W5100_RESET_PIN, OUTPUT);
    digitalWrite(W5100_RESET_PIN, LOW); // Activate reset pin by asserting low
    delay(5); // Wait for 5 msec
    digitalWrite(W5100_RESET_PIN, HIGH); // Deactivate reset pin by asserting high
    delay(300); // Wait for W5100 to initialize[/code]

I observed the W5100 resetting because the module LEDs flashed off and back on each time I manually reset the Arduino. However this does not fix the W5100 mac/IP initialization issue.

**How should I troubleshoot this issue?**

Here are pictures of the assembly.
https://i.stack.imgur.com/cjnHE.jpg

Here is an overview of the W5100 module.
http://arduino-info.wikispaces.com/Ethernet

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

One of the Ethernet examples shows you should test the result of the `begin` function call, like this:

    // start the Ethernet connection:
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // try to congifure using IP address instead of DHCP:
        Ethernet.begin(mac, ip);
      }

Try displaying the return value from `begin` to see if that initialization succeeded.


message:
BLE SPI Module with ATtiny85

Adafruit carries a number of Bluetooth LE 4.0 modules in their store, notably the SPI (https://www.adafruit.com/products/2633) and UART (https://www.adafruit.com/product/2479) version. I have used the NRF24L01 module with ATtiny85 via SPI to transmit data in the past, and this uses 3 pins. I used the following setup to do so: https://www.hackster.io/arjun/nrf24l01-with-attiny85-3-pins-74a1f2.

My previous system consisted of ATtiny85s communicating with a receiver (Bluefruit Feather) via NRF24L01 radios. As the receiver got data, it sent it to an iPhone app that I wrote. Now, I would like to cut out this receiver and BLE straight to the iPhone, which supports multiple peripheral connections.

However, unlike the RF24 library, the Adafruit BLE SPI library needs the actual SPI library to compile correctly, which for some reason the RF24 library (this version: http://tmrh20.github.io/RF24/) doesn't. I don't quite get how the RF24 library can compile fine without the SPI library when targeting the ATtiny85 - Is there some way to get this to work similar to the RF24 library?

Alternatively, I think there is a way to do software UART on ATtiny85, which I know nothing about, so if there truly is no way to do SPI is UART possible?

I realize that this is a question best asked to Adafruit, which I have done, but I thought I'd post it here and see if anyone can help.

Thanks,
Alex

body:
I find the ATTiny85 working well with software serial port. Serial UART (or in fact any of the protocols like I2C or SPI) are just bit banging - and you can do that pretty well in software. Of course, having a hardware support makes things easier and faster, but there is nothing badly wrong with a software uart either. Except that you have to continuously check if there is some data arrives.

I was using software serial on Adafruit Trinket (ATTiny85) in various projects to talk to a Bluetooth 2.1 module, and it worked pretty well.

Here
http://arduining.com/category/trinket-projects/ they use the same approach to talk to an ESP8266.

You may wish to look for the SoftwareSerial lib for Trinket, or in certain cases you may want to go for the SendOnlySoftwareSerial lib (send only, but smaller code footprint).

Also a hardware based serial lib is available:
https://blog.adafruit.com/2013/09/30/hardware-serial-library-for-the-trinket/


message:
How does serial communications work on the Arduino?

With reference to the Arduino Uno, Mega2560, Leonardo and similar boards:

* How does serial communications work?
* How fast is serial?
* How do I connect between a sender and receiver?

*Please note: This is intended as a reference question.*

body:
Asynchronous serial (usually referred to as serial) communications is used to send bytes from one device to another. A device could be one or more of the following:

* Arduino
* PC
* GPS
* RFID card reader
* LCD display
* Modem
* Other

---

## Clock rate and sampling of data

Unlike SPI / USB / I2C serial communications does not have a clock signal. The sampling clock is an agreed-upon sample rate (known as the baud rate). Both sender and receiver must be configured to be using the same rate or the receiver will receive meaningless data (due to the bits not being sampled at the same rate that they were sent).

The transmission is [asynchronous](https://en.wikipedia.org/wiki/Asynchronous_communication) which basically means that bytes can be sent at any time, with varying gaps between them. This graphic illustrates a single byte being sent:

[![Serial comms - sending one byte][1]][1]

The graphic above shows the letter 'F' being transmitted. In ASCII this is 0x46 (in hex) or 0b01000110 (in binary). The *least* significant (low-order) bit is transmitted first, thus in the above graphic you see the bits arriving in the order: `01100010`.

The "idle" time between bytes is transmitted as continuous "1" bits (effectively, the transmit line is held high continuously).

To indicate the start of a byte, the *Start Bit* is always indicated by pulling the line low as shown on the graphic. Once the receiver sees the start bit, it waits for 1.5 times the sample time, and then samples the data bits. It waits 1.5 times so that it:

* Skips the start bit
* Samples half-way through the next bit

If the baud rate is 9600 baud, for example, then the sample rate will be `1/9600 = 0.00010416` seconds (104.16 µs).

Thus, at 9600 baud, after receiving a start bit the receiver waits for 156.25 µs, and then samples every 104.16 µs.

[![Start bit timing][2]][2]

The purpose of the *Stop Bit* is to ensure that there definitely is a 1-bit between each byte. Without the stop bit, if a byte ended in a zero, then it would be impossible for the hardware to tell the difference between that and the start bit of the next byte.

To produce the above output on an Uno you could write this code:

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

    void setup()
      {
          Serial.begin(9600);
          Serial.print("F");
      }

    void loop ()
      {
      }

---

## Number of data bits

In order to save transmission time (in the olden days, heh) you were allowed to specify different numbers of data bits. The AtMega hardware supports data bits numbering from 5 to 9. Clearly the less data bits the less information you can send, but the faster it will be.

---

## Parity bits

You can optionally have a parity bit. This is calculated, if required, by counting the number of 1's in the character, and then making sure that this number is odd or even by setting the parity bit to 0 or 1 as required.

For example, for the letter "F" (or 0x46 or 0b01000110) you can see that there are 3 ones there (in 01000110). Thus we already have odd parity. So, the parity bit would be as follows:

* No parity: omitted
* Even parity: a 1 (3 + 1 is even)
* Odd parity: a 0 (3 + 0 is odd)

The parity bit, if present, appears after the last data bit but before the stop bit.

If the receiver does not get the correct parity bit, that is called a "parity error". It indicates that there is some problem. Possibly the sender and receiver are configured to use different baud (bit) rates, or there was noise on the line which turned a zero to a one or vice-versa.

Some early systems also used "mark" parity (where the parity bit was always 1 regardless of the data), or "space" parity (where the parity bit was always 0 regardless of the data).

---

## 9-bit transmission

Some communication equipment uses 9-bit data, so in these cases the parity bit is turned into the 9th bit. There are special techniques for sending this 9th bit (the registers are 8-bit registers so the 9th bit has to be put somewhere else).

---

## Number of stop bits

Early equipment tended to be somewhat slower electronically, so to give the receiver time to process the incoming byte, it was sometimes specified that the sender would send two stop bits. This basically adds more time where the data line is held high (one more bit time) before the next start bit can appear. This extra bit time gives the receiver time to process the last incoming byte.

If the receiver does not get a logical 1 when the stop bit is supposed to be, that is called a "framing error". It indicates that there is some problem. Quite possibly the sender and receiver are configured to use different baud (bit) rates.

---

## Notation

Commonly, serial communication is indicated by telling you the speed, number of data bits, type of parity, and number of stop bits, like this:

    9600/8-N-1

This is telling us:

* 9600 bits per second
* 8 data bits
* No parity (you might see instead: E=even, O=odd)
* 1 stop bit

It is important that the sender and receiver agree on the above, otherwise communication is unlikely to be successful.

---

## Pin-outs

The Arduino Uno has digital pins 0 and 1 available for hardware serial:

[![Arduino Uno serial pins][3]][3]

To connect two Arduinos you *swap* Tx and Rx like this:

[![Connecting two Arduinos together][4]][4]

---

## Speed

A wide range of speeds is supported (see graphic below). "Standard" speeds are usually a multiple of 300 baud (eg. 300/600/1200/2400 etc.).

Other "non-standard" speeds can be handled by setting the appropriate registers. The HardwareSerial class does this for you. eg.

    Serial.begin (115200);  // set speed to 115200 baud

As a rule-of-thumb, assuming you are using 8-bit data, then you can estimate the number of bytes you can transmit per second by dividing the baud rate by 10 (because of the start bit and stop bit).

Thus, at 9600 baud you can transmit 960 bytes (`9600 / 10 = 960`) per second.

---

## Baud rate errors

The baud rate on the Atmega is generated by dividing down the system clock, and then counting up to a pre-set number. This table from the datasheet shows the register values, and error percentages, for a 16 MHz clock (such as the one on the Arduino Uno).

[![Baud rate errors][5]][5]

The U2Xn bit affects the clock rate divisor (0 = divide by 16, 1 = divide by 8). The UBRRn register contains the number the processor counts up to.

So from the table above, we see that we get 9600 baud from a 16 MHz clock as follows:

    16000000 / 16 / 104 = 9615

We divide by 104 and not 103 because the counter is zero-relative. Thus the error here is `15 / 9600 = 0.0016` which is close to what the table above says (0.02%).

You will notice that some baud rates have a higher error amount than others.

According to the datasheet the maximum error percentage for 8 data bits is in the range of 1.5% to 2.0% (see the datasheet for more details).

---

## Arduino Leonardo

The Arduino Leonardo and Micro have a different approach to serial communications, as they connect directly via USB to the host computer, not via the serial port.

Because of this, you must wait for Serial to become "ready" (as the software establishes an USB connection), with an extra couple of lines, like this:

    void setup()
      {
          Serial.begin(115200);
          while (!Serial)
          {}  // wait for Serial comms to become ready
          Serial.print("Fab");
      }

    void loop ()
      {
      }

However, if you want to actually communicate via pins D0 and D1, (rather than by the USB cable) then you need to use Serial1 rather than Serial. You do so like this:

    void setup()
      {
          Serial1.begin(115200);
          Serial1.print("Fab");
      }

    void loop ()
      {
      }

---

## Voltage levels

Note that the Arduino uses TTL levels for serial communications. This means that it expects:

* A "zero" bit is 0V
* A "one" bit is +5V

Older serial equipment designed to plug into a PC's serial port probably uses RS232 voltage levels, namely:

* A "zero" bit is +3 to +15 volts
* A "one" bit is −3 to −15 volts

Not only is this "inverted" with respect to TTL levels (a "one" is more negative than a "zero"), the Arduino cannot handle negative voltages on its input pins (nor positive ones greater than 5V).

Thus you need an interface circuit for communicating with such devices. For input (to the Arduino) only, a simple transistor, diode, and a couple of resistors will do it:

[![Inverting buffer][6]][6]

For two-way communication you need to be able to generate negative voltages, so a more complex circuit is required. For example the MAX232 chip will do that, in conjunction with four 1 µF capacitors to act as charge-pump circuits.

---

## Software Serial

There is a library called SoftwareSerial that lets you do serial communications (up to a point) in software rather than hardware. This has the advantage that you can use different pin configurations for serial communications. The disadvantage is that doing serial in software is more processor-intensive and more prone to error. See [Software Serial](https://www.arduino.cc/en/Reference/SoftwareSerial) for more details.

---

## Mega2560

The Arduino "Mega" has 3 additional hardware serial ports. They are marked on the board as Tx1/Rx1, Tx2/Rx2, Tx3/Rx3. They should be used in preference to SoftwareSerial if possible. To open those other ports you use the names Serial1, Serial2, Serial3, like this:

    Serial1.begin (115200);  // start hardware serial port Tx1/Rx1
    Serial2.begin (115200);  // start hardware serial port Tx2/Rx2
    Serial3.begin (115200);  // start hardware serial port Tx3/Rx3

---

## Interrupts

Both sending and receiving, using the HardwareSerial library, use interrupts.

### Sending

When you do a `Serial.print`, the data you are trying to print is placed in an internal "transmit" buffer. If you have 1024 bytes or more of RAM (such as on the Uno) you get a 64-byte buffer, otherwise you get a 16-byte buffer. If the buffer has room, then the `Serial.print` returns immediately, thus not delaying your code. If there is no room, then it "blocks" waiting for the buffer to be emptied enough for there to be room.

Then, as each byte is transmitted by the hardware an interrupt is called (the "USART, Data Register Empty" interrupt) and the interrupt routine sends the next byte from the buffer out of the serial port.

### Receiving

As incoming data is received an interrupt routine is called (the "USART Rx Complete" interrupt) and the incoming byte is placed into a "receive" buffer (the same size as the transmit buffer mentioned above).

When you call `Serial.available` you find out how many bytes are available in that "receive" buffer. When you call `Serial.read` a byte is removed from the receive buffer and returned to your code.

On Arduinos with 1000 bytes or more of RAM, there is no rush to remove data from the receive buffer, provided you don't let it fill up. If it fills up then any further incoming data is discarded.

Note that because of the size of this buffer there is no point in waiting for a very large number of bytes to arrive, for example:

    while (Serial.available () < 200)
      { }  // wait for 200 bytes to arrive

This will never work because the buffer cannot hold that much.

---

## Tips

* Before reading, always make sure data is available. For example, this is wrong:

        if (Serial.available ())
          {
              char a = Serial.read ();
              char b = Serial.read ();  // may not be available
          }

    The `Serial.available` test only ensures you have *one* byte available, however the code tries to read two. It may work, if there are two bytes in the buffer, if not you will get -1 returned which will look like 'ÿ' if printed.

* Be aware of how long it takes to send data. As mentioned above, at 9600 baud you an only transmit 960 bytes per second, so trying to send 1000 readings from an analog port, at 9600 baud, won't be very successful.

---

## References

* [Async (Serial) peripheral interface - for Arduino](http://www.gammon.com.au/forum/?id=10894)
* [How to process incoming serial data without blocking](http://www.gammon.com.au/serial)
* [RS-232 - Wikipedia](http://en.wikipedia.org/wiki/RS-232)
* [Arduino Reference - Serial](http://arduino.cc/en/Reference/Serial)

  [1]: https://i.stack.imgur.com/LcurN.png
  [2]: https://i.stack.imgur.com/SoFKx.png
  [3]: https://i.stack.imgur.com/eFevW.png
  [4]: https://i.stack.imgur.com/QJO4F.png
  [5]: https://i.stack.imgur.com/Dlzee.png
  [6]: https://i.stack.imgur.com/8WUMU.png


message:
Take an Arduino or Teensy prototype to Mass production - Loading software onto microcontroller

I am developing an educational product that I would like to mass produce. I am not sure of the quantity yet, but I imagine we will make a few hundred PCBs at least to begin

I spoke with an electrical engineering about how to take an Arduino prototype to mass production, and he warned me that the code written in the Arduino IDE cannot be fused onto the processor. (He used the term "fuse", although I don't see this elsewhere in the forum. is this the right term?)

He said that I would probably have to take each product, and load the Arduino code on manually, plugging in each one to a computer and upload like one would when prototyping. Also, he said the other option would be to recode my Arduino sketch from scratch using an AVR code.

Can someone shed some light on this for me? How can I take Arduino prototyping code and use it in mass production?

body:
Arduino code and AVR code is essentially the same, at least once compiled it is. The only real difference is the existence of the bootloader, and that is not essential.

For quantities of a hundred or so it is probably most cost effective to manually program them via an ISP connector to the board. For larger quantities Atmel provide a mass programming service to pre-program the chips, but that costs money so the more you have done at once the cheaper it is per chip. I am not sure on Atmel's procedure off hand but others I have used just take either a .elf or .hex file which the Arduino IDE is perfectly capable of producing.

Either way you should design in an ISP connector on your board so the firmware can be upgraded in the future if needed.


body:
Arduino code **is** AVR code. There's no real difference. The only thing is that Arduino's tend to use bootloaders, which might cause a problem. But in your case I'd advice to not use a bootloader anyways.

Since you plan to build a lot of them, you probably want to use bare ATMega chips, and not arduino boards. Bare chips don't have a bootloader to begin with.

You'd program the boards using ISP.


body:
> I spoke with an electrical engineering about how to take an Arduino prototype to mass production, and he warned me that the code written in the Arduino IDE cannot be fused onto the processor.

That's nonsense. The output from the IDE compiler is a .hex file which is then sent via `avrdude` to program the board. If the output cannot be "fused" onto the processor how does he imagine we ever get anything done?

Possibly he is referring to changing the fuses to make it impossible to read the code back from the chip. This can be easily accomplished.

---

> He said that I would probably have to take each product, and load the Arduino code on manually, plugging in each one to a computer and upload like one would when prototyping.

You have obviously spoken to someone with no experience in Arduinos, possibly one of those engineers with an active dislike of it.

I have written code to run on an Arduino to upload sketches to another board.

You can read about it at [Atmega chip stand-alone programmer to upload .hex files](http://www.gammon.com.au/uploader). The idea is you take your .hex file, put it onto an SD card and then program your target board in a few seconds.

User "Crossroads" from the Arduino forum has taken that idea and made a [stand-alone board](http://crossroadsfencing.com/BobuinoRev17/index.html), looking like this:

[![Hex programmer][1]][1]

You put up to 255 hex files onto the SD card. You dial-up which one you want with the rotary dial. You plug in the ICSP cable into your target board, and hit the "program" button. The whole thing takes a few seconds.

It is designed to be used "in the field". All you have to do is plug in a power-pack to supply power to it.

If you needed to protect the target boards with a fuse setting after uploading, you would modify the code in the programmer slightly to do that for you.

It would be helpful to have an ICSP header on your target boards, both for programming before deployment, and in case you find a bug and have to change it.

Failing that you might put the chips into a suitable board first (eg. with a ZIF socket), program them off-board, and then solder them on. There are lots of options for you.

---

> Also, he said the other option would be to recode my Arduino sketch from scratch using an AVR code.

I don't see why that would be necessary, in any way.

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


message:
What if Ultrasonic sensor doesn't detect object?

I am trying to write a sketch where a function will only be triggered when the ultrasound doesn't return back. Thus when the echo pin is checked after 1 second after the trigger pin was written high, it must be low. Will it be a digitalRead function?

body:
What type of Ultrasonic sensor do you have?

I'll go with HC-SR04, since I've got one of those laying around here. The other ultrasonic sensors should be working in the same way.

**Before you start!**

Read the datasheet. A fast search on google with: "[manufacturer][device id][device description] datasheet .pdf" will do good.

Example: http://www.micropik.com/PDF/HCSR04.pdf

The datasheet will tell you important things/values and sometimes even interfacing examples or code.
Like:

 - Max input voltage
 - Max current
 - Pin-out diagrams
 - How to interface with the device
 - Min/max operating temperature

**Wiring up**

The datasheet will tell you what to connect, to which pins.

We've got 5V, Trigger (input), Echo (output), 0V (ground).

(As per datasheet)

It's best to do the wiring before you put power on it, because you can accidently short it when moving wires around.

**Interfacing**

I would recommend checking some code examples before you attempt to roll your own. Or just start from an example and edit it to your specifications.

The timing diagram shows us it needs a 10uS pulse on the trigger input.
And the duration of the echo will show the distance (58 uS per cm or 148 uS per inch).

The datasheet also suggest to use over 60ms measurement cycles.

**Code**

Taking all that into account:

    #define trigPin 13
    #define echoPin 12
    #define led 11
    #define led2 10

    const unsigned long timeout = 400*58; //Max of 400CM, adjust this to your own max.

    void setup() {
      Serial.begin(115200);//Stop using 9600 as default, it's not fast.
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(led, OUTPUT);
      pinMode(led2, OUTPUT);
    }

    void loop() {
      unsigned long distance;//unsigned, since we don't get negative distances.
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10); //10 uS pulse.
      digitalWrite(trigPin, LOW);

      distance = round(pulseIn(echoPin, HIGH,timeout) /58);//Distance in CM's, use /148 for inches.
      if (distance == 0){//Reached timeout
        Serial.println("Out of range");
      }
      else {
        Serial.print(distance);
        Serial.println(" cm");
      }
      delay(60);//Wait 60 ms for next cycle.
    }

To be honest, I'm not even slightly sure if this code is working.
I modified this code: http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/

So that you're actually using the timeout right, and do the timing according to the datasheet.


message:
Can RX and TX be temporarily transposed on demand?

Only 2 arduinos can normally be linked via serial port because TX and RX need to be cross-linked, and connecting multiple TXs together would cause conflict.

RS485 allows multiple nodes connected in parallel on a 2 wire differential 'bus', using a TX ENABLE pin to allow one master to transmit while all other slaves listen.

I suspect it should be possible to similarly connect multiple serial RXs together to give a common listening bus, and be able to use TX ENABLE on any one node at a time to transpose its RX and TX to allow its TX to transmit to the other RXs. This might be physically done using a changeover relay swapping RX with TX, but is it possible to somehow temporarily switch the TX and RX assignments on demand by software?

I doubt the actual pin assignments can be changed in-situ, but perhaps the same results are achievable with some programming wizards sleight-of-hand trickery?

body:
It sounds to me like you are misunderstanding the purpose of the TX Enable pin and you are trying to come up with some convoluted method to do exactly what TX Enable actually does.

Under normal circumstances, in RS485, the UART's RX pin is connected to the bus.  When TX Enable is asserted the RX pin is disconnected and the TX pin is connected, thus allowing any node on the bus to be a transmitter and all the other nodes a receiver.

The main thing to watch out for though is that only one node is ever a transmitter at a time, otherwise you get a *collision* which means that the data is completely garbled.

The simplest way of stopping that happening is to have one node nominated as the *master* and all the other nodes as *slaves*.  The *master* first initiates communication by making a request to a *slave*.  The *slave* will then respond with data (it becomes the transmitter and the *master* a receiver) to send data to the master.  That way the only node that is a transmitter is either the *master* making the request, or the *slave* that is responding to a request.

If you want "random" peer-to-peer communication where any node could become a transmitter at any time it becomes a whole lot more complex.  There are things you should implement to try to avoid, or deal with, collisions, including monitoring the bus and only transmitting after a certain amount of idle time has been detected, reading the bus while writing to it (requires more hardware) and confirming that the data you read from the bus is the same as the data you wrote to the bus, and random delays before retrying a failed communication.  That last one is probably the trickiest to get right, since random numbers on Arduinos aren't really random unless you "seed" them from a truly random source. You don't want both ends delaying for the same amount of time to retry otherwise it will never complete.

----

Since you apparently want to achieve that kind of thing but *without* using RS485, it all gets much more complex.

No, you cannot "swap" the functionality of the TX and RX pins in the Arduino.  **BUT** you can do serial communication (albeit somewhat heavyweight) using pure software.  Take a look at the SoftwareSerial library - you will most likely need to make modifications to that to achieve what you want.

To do it externally with hardware is possible, but the end result will most likely be more complex than just using a simple RS485 interface chip which are very inexpensive and easy to get hold of.

Yes, you could use relays (*clunky*) or buffers, or multiplexers, etc, but why would you when RS485 does what you want?


body:
On an AVR-based Arduino, you can selectively enable the transmitter and
receiver side of the UART (c.f. the datasheet of your MCU). Thus, you
could in principle just connect all the TX and RX together, and make
sure only one transmitter is enabled at a time, while all the others are
in high impedance. If you do this, I would strongly recommend you put a
current-limiting resistor in series with each TX, just in case.

For example, on an Arduino Uno
([Atmega328P](http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf)),
you can use the following functions:

<!-- language: lang-cpp -->

    static inline void enable_tx()  { UCSR0B |=  _BV(TXEN0); }
    static inline void disable_tx() { UCSR0B &= ~_BV(TXEN0); }
    static inline void enable_rx()  { UCSR0B |=  _BV(RXEN0); }
    static inline void disable_rx() { UCSR0B &= ~_BV(RXEN0); }

**Edit**: Beware that `Serial.begin()` enables both the transmitter and
the receiver.


message:
"EVERY_N_MILLISECONDS"

One of the FastLED examples that I've seen was using code that looks like this:

>   EVERY_N_MILLISECONDS( 300 ) { transition_step(); }

I've copied it and successfully used it in the same context - but I have no idea what it is or how it works.

A Google search finds no reference anywhere at all.

I'm still a beginner with C but this looks like a Define to me - all being in uppercase - is it defined somewhere in the FastLED library?

body:
Yes, it is defined in the FastLED library.  It is a *preprocessor macro* which is replaced by a block of code when compiled:

It is a very convoluted bit of preprocessing code that is difficult (even for me) to follow through with lots of concatenations and multiple layers of definition, so my advice is to just not worry about it and just use it.

If you want to try and decypher it all it's in the file `lib8tion.h` in the FastLED library.