text:
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.

Nothing to do with int/unsigned long - I've just tried it. Not sure why you didn't try it if you thought that was the problem!

I'm going through this now and I'm slightly confused as to precisely what you're trying to achieve. Ultimately do you want to be able to choose starting brightness, end brightness, and the time it takes to go from one to the other? That seems the most obvious, but it also seems like you want to specifiy how many individual brightness levels there are inbetween. Also, do you have any timers spare that you aren't using?

I think you have your logic completely arse about face (to use a colloquial expression). I see nothing there that would actually perform any PWM operation at all, only turning the LED ON or OFF at something like 2 seconds.

@Majenko: the LED HIGH at 2 seconds it just to show timestamps in microseconds work for my chip. The inner conditional block is what evaluates the duty cycle during each period (read: not the 2 second fadePeriod). @CharlieHanson: yes it's an LED fader using PWM, which you can set duration from 0 to full brightness, as well as how many steps in that duration (to simulate smoothness or harsh steps). I did try the int/unsigned long, but didn't work so thought I'd throw it up here for anyone to correct me. I am not using OCR1A/B.

Turns out the clock speed for my chip can't handle the software PWM that's fully asynchronous using timestamps. The amount of instructions exceed the individual periods of each duty cycle. Got it working and will do  a write up on my findings in I have time.

 _fadeStep/_fadeSteps always evaluates to zero unless  _fadeStep >= _fadeSteps.

float _T_on; - variable names starting with an underscore and followed by an upper-case letter are reserved by the C++ standard. I suggest you stop using them. Put trailing underscores in, if you want to indicate class variables.

@ott--: didn't even see that. Thanks.

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.


text:
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

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

    }
}

(a) Using a switch/case statement to select which relay to work on, with four blocks of nearly identical code (instead of using an array with pin numbers, and a single block of code) is odious.  (b) Although the while   (in the if (currentState < 4) block) works ok, it functions as an if statement and IMO should be written as such.

if(received_sms){} block made my day " previousMillis=millis()" inside that will now allow me to get the offset from the point i recieved the SMS ,,Thanks You

@jwpat7 I agree that if the code is nearly identical the switch/case can be rewritten in a more concise form, but often (almost always) you have to do something else in the cases (and that's why when dealing with simple - and complex - state machines my mind always implements it as switch/case). In this case, however, this could be simplified. The while, however, is much more secure than the if. Since previousMillis is not reset to millis() but just incremented (more precise), if some function blocks the thread for too much time you can lose one step; with the while you can recover it

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

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

i am now using TimerOne ,,,it however is not the best method and not very safe

@Lokanath I'm curious. Why do you say that?

Interrupts are good but how ever you cannot pass values to the ISR,as far as i know ISR will execute when the timerExpires and uses the values of variables current values at the expiry point inside ISR which i totally cannot control which makes program unpredictable

@Lokanath You could use global variables and declare them as 'volatile'. This tells the compiler to reload the variable every time you reference it as opposed to using a copy from a register.

ya you are right,,,usage of interrupts needs more than beginners knowledge,,,if you know how to use it you can manage them

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
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.

The question, as-is, is off topic. Yes it is possible to use an Arduino to communicate on a CAN bus via some kind of shield. However, the root of your question is whether or not it can be done for your specific car, which is a question better served by some form of car enthusiast site, perhaps one dedicated to Mini Coopers.

Did you try google? https://www.google.com/search?client=ubuntu&channel=fs&q=Arduino+CAN+Car+Control+via+OBD-II. Looks like a "yes".

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.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
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.

The white wires in your diagram are not in the center as in the linked picture.   Also, the E+/E-/A-/A+ labels seems off by one pin.   If the whites are the center wire on your device, they are likely the middle, sensing terminal of the load cells, and should connect to the A+/A- of the HX711 See the last paragraph of http://arduino.stackexchange.com/a/18698/6628 for using the sensors's other gauges as resistors.  Could be the precision of the resistors swamp the bridge.

Perhaps you should move your greens from +5/GND to the E+/E- to let the HX711 excite your bridge rather than the power supply.

I was directed in an Arduino forum to wire it up like this:  https://imgur.com/OkEuWV4   however I still cannot get it to work.  Going to move the greens around as well.

What is the no-load voltage difference across A-/A+?  I didn't dig into the code you pointed to, but it looks like it might be multiplying the value by 1992.0 and I'm not sure what offset it adds.  If the no-load voltage is far from zero, it might overflow or underflow something and give you a constant value.    I'd use the strain gauge's other halves as in the forum's diagram, instead of discrete resistors as in yours, since you need to balance things to near 0.1%.  The white-black connections they show put the tension(or compression) gauges on opposite sides, difft than your connections.

Also, check the resistances between the gauge terminals.  The sense/A+/A- should be the same color wire, and should lie halfway between the resistance between the other two terminals.  It is essentially the center tap of a ~2k potentiometer, and it should move about +/-0.1% or 2 ohms from the center at full load.

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

The OP has the strain gauges both on the bottom side of the wheatstone bridge, where if similarly loaded would pull both E+ and E- in the same direction when loaded.  What might be more of a problem, is if the values of the discrete resistors R1, R3 do not match the strain gauges to 0.1% perhaps making zero-load S+/S- voltage too large to work with.


text:
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 which comes with a data sheet. 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?

I'm voting to close this question as off-topic because it is about BLE and phones, not about Arduino.  The original migration to this site was improper; it should have remained where it was asked, or simply been closed.

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.

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.


text:
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?

Can't you just reverse the order of the bytes? This sounds like an "endian" issue of your library. Please provide a link to the library.

Were you possibly looking at my other question?  That was a question about reversing the order of the bytes (which is how I was finally able to to get the correct 4byte UID).  This question is specific to this readers.  It provides me only 32bits for both mifare classic (4byte UID) and mifare ultra (7byte UID).  I would expect it to return 32bits for mifare classic and 56bits for mifare ultra, or am I missing something completely?

it looks like it decodes the CSR/UID of all Mifare cards - what are the words "it" referring to here? Please provide a link to the card in question, the library in question, and your code. In what way does "it" look like it is doing "it"?

IT, as I state in my questions is an: "HID multiCLASS (RP40CKPNN) reader" http://www.hidglobal.com/products/readers/iclass-se/smart-card-readers. It uses a Wiegand interface to transfer information to my Arduino.  I've reviewed all of the information I can find on this specific reader, and from what I reading between the lines it looks like some of the configuration is done via proprietary cards, but I can find not further information on that.

To be clear, this is not one of the breakout board readers such as the PN522, or Paralax serial reader, etc.  It's a 3rd party "stand alone" reader that returns a set number of bits via Wiegand Data0/Data1 interface to the Arduino.  I'm just trying to find out if anyone has any specific experience with these readers.  THANKS!

I haven't, so I can't help you with that. You may help others to answer you if you provide your code. For example, on the Arduino side can you demonstrate that you are reading 56 bits?

It's not really an issue of code...  The reader itself is only sending 32bits of data for both Mifare classic and ultra.  I would expect 32bits for classic (4byte UID), and 56bits for ultra (7byte uid), but for both types of tags I only get back 32bits.  The question is more specific to if there's any trick I can use to configure the reader to send more bits for these card types. The data-sheets for the readers specifically mention that ability but not HOW to configure it. :)  Thanks for the effort.

Only Mifare classic is mentioned in its 2-page datasheet. Provide the exact link to the datasheet and also your code, since all config must be done with code after all

Actually the config is not determined by code for this reader, as it turns out configuration changes for these readers are done via specific cards that you obtain from HID Global.  The reader reads the cards, and then changes its configuration.

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.


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

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

Entrada is from my class Connection(other class), that i did use when i would want connect my device with arduino

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.

Sorry, your idea is the same that i have in my codec :(


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

}

Sorry, I read your post and the comment under @Nick Gammon's post but I couldn't understand what you are trying to achieve. Can you give some examples, for instance "i move the joystick all the way to the left: now it reads 0.1. I set this as new idle...." and so on? Otherwise it becomes very difficult to understand your needs..

Okay, so when the joystick moves all the way to the left, the analogue input value drops to 0, say. At neutral the value is roughly 2.5. What I want is the Arduino to then set the value of 0, when fully left, to 2.5, such that when the joystick physically returns to neutral, the value would read 5. Same would go for all the way up, for example, where the value would normally read 5. At near 5, I want the joystick to set to 2.5 (its starting value), such that when it physically returns to neutral i.e. not pushed, the value would then read 0. (Hope this makes a bit more sense!)

Ok... Now I understood ;) I can't understand the reason to do so though ;)

Anyway... When the joystick returns to neutral it'll be 0 again, so it will go back to 2.5 again...

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.

For lots of the LEDs on Arduino boards, 1 ms is long enough to see an LED flash; for that matter, a few microseconds is long enough.

I didn't say he wouldn't see it flash. I warned him the flash would be short. :)

Thanks so much for the input! The issue I now have is that although the Arduino sets >4.55 and <0.5 to be the new 'neutral' point of 2.5, when the joystick physically returns to neutral, i.e. when the values are under the defined thresholds, then rather than going from 2.5 to 0, say, the values go from 2.5, back to 4.54 and then back to 2.5 at physical neutral again.
What I'm trying to have is that once set to the new threshold of 2.5, that value stays set, such that when the joystick physically returns to neutral it's idling somewhere around 0, relative to the new threshold. Cheers!

It seems to me that you want the map function (or write something similar yourself). You want, as far as I can see, to unconditionally map the joystick input to a new range.


text:
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?

If i put 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();       }
I seem to have better results but I am not sure why I would need to stop the client after an httpRequest.

You need to stop the socket connection when you are done, in order for the server to successfully close the connection and also to free file handles, i think. In your GET request, get rid of the IP address; start with /ReefCont...also get rid of the other header fields in your GET request, and try again

@brianrho good point, I had not even seen the part where he adds the other headers. With HTTP1.0 you can get away with nothing more than just the GET line. If you want to keep the other headers do not forget to add \r\n after each line.

@brianrho do I not need the ip in my get because I'm already connected to that server?

Exactly. You are already connected.

@brianrho do you think this may fix the connection problem and the error 500 or just the error?

You will have to try it and see. Dont forget to remove the other header fields.

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!

Great thanks @larzz11.    I am going to try this when I eat home from work tonight.  It's 730am in my time zone right now. I'll update once I try it.


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

For starters change "else (digitalRead(2) == HIGH)" to "else if (digitalRead(2) == HIGH)" in loop().

Also take a long look at the definition of targetColor.

Thank you for your response, I am very new to this and am teaching myself on the fly.  I went back and eliminated the char altogether.

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.

Ok.  While I knew the first explanation, or thought I did, I thought I had tried this already.  Eliminating the condition fixed it.  I must have eliminated the condition and forgot to remove the if after else and got me turned around.  Thank you.  I can't vote your explanation up, but you made it very clear. as I mentioned to @Mikael Patel I am teaching myself on the fly.

No worries @Gixxerfool - good on you for teaching yourself and having a go - there's certainly no harm in that.

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.

Could you expand on what you mean by the sign mismatches? Thank you.

There are places where (especially in for loops) you define an int (signed) and then compare that to the return value of a function which is an unsigned value (eg numPixels()). That causes warnings if you have warnings turned on. 99.99999% of the time it is fine, but it's just something to be aware of because it can cause problems in some cases. Highly unlikely in your case, but still something to watch.

Ok. That makes perfect sense.  I guess since I never had a conflict, I never paid attention. Definitely something I will be more conscious in the future of that.  Thank you for the tip. Any help is always appreciated.


text:
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.
// 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.
  }
}

You are most likely using the wrong baud rate. Try 9600, 57600 and 115200. Are you sure of that power up procedure? Is there any evidence that the module is on?

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??
Serial port AN


text:
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

I google the OV7670 with FIFO and unfortunately I do not find the clear wiring with arduino and its simple code. I can find the book which can help as its written for this product only but it will be great if you can point to some good link which deal with OV7670 with FIFO. Please do not share the link for without fifo. Thanks.

Here is a link to a setup I built to explore the OV7670. There is a spread sheet with the wiring except for power. You are on your own for that, sorry.
https://joseph37920.github.io/OV7670-Explore/

Here is a link. Use google to find more. It is not difficult.

Hi Thanks for quick response . I already visited this page as its only page I found on web which work for camera + fifo https://github.com/arndtjenssen/ov7670.     All other explain camera without fifo ... I tried to check the code and code is basically written for avr and I know arduino is also based son avr only but it doesn't have DDRA and some other couple of register .


text:
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?

memcpy() is the C function for copying blocks of memory. If nobody has answered before I get back to a computer I shall write something up, providing you clarify whether you want to copy the contents or not, and whether the arrays are equal fixed length, different fixed lengths, or truly dynamic lengths.

I suggest you clarify if you want a copy of the contents, or merely make newArray refer to one of the existing arrays. Your wording which of the first three arrays i want my new array to take values from suggests you merely want to change a reference to one of the existing arrays.

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.

But this doesn't copy the contents, it just creates a duplicate reference...

@CharlieHanson, that complies with an interpretation of the question consistent with Python's implementation, which produces a new reference to a list.   Re Python's copy and deep copy see 8.17. copy — Shallow and deep copy operations

Yet it does not comply with the title "Copy content of array".

@CharlieHanson, I'd instead say the title does not comply with the content of the post.  We can hope OP clarifies.  Anyway, will add memcpy note

I'd instead say the content of the post does not comply with the title. Sic vita est.

memcpy(newArray, myArray2, sizeof(myArray2)); - I always like to take the size of the destination, not the source ... just in case.

@NickGammon, If source is myArray3 that will copy an extra word ... typically harmless, technically undefined.  Of course, one could preface the memcpy with an if to test sizeof(source) <= sizeof(dest)

Or something like: memcpy(newArray, myArray2, min (sizeof(myArray2), sizeof (newArray)));

Would there be much overhead in wrapping this in a simple class? I know there are a host of container classes in the C++ STL but they are all overkill, in this case at least. The ability to iterate and reference only within the bounds of the array would be a handy tool, and adding a copy function (a copy constructor, even?) could make using the array painless. Apart from the time taken to actually write the class, are there any drawbacks from an embedded point of view that would make this more harm than good?

Conceivably some sort of wrapper might run more slowly. I don't see any enormous disadvantages, except learning to use the class might take just as long as learning how to do the memcpy. :)


text:
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?

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:

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.

Thank you very much for a quick answer and helpfull information! That prevent me from buying unnecessary components.


text:
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

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.

Thanks for your comment Nick.  Calling Ethernet.begin(mac) returns non-zero and it fails to configure DHCP.  I also tried configuring IP manually and this fails as well.


text:
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

Have you considered porting the BLE library to a USI library?

Use an SPI library that does support the tiny. Like e.g. https://github.com/jscrane/SPI

Huh - I'll take a look at that SPI library and see. Thanks.

The ATtiny85 does not have an SPI port. It has an USI (Universal Serial Interface) that can be made to work like SPI (or I2C, or UART), but this needs some software support.

Keep in mind that many of the BLE chips are themselves computationally comparable to an ATtiny.  There's a good chance you can run your project itself on an nRF51822 - granted there can be some annoyances in setup but the mbed option should work even if you give up on the Arduino port.

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/

Thanks, this is very good information. I tried out SoftwareSerial and it appears to be working.


text:
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.

You might find this interesting about buffers on both sides of a Nano connected to a Raspian system running a Python data logger, using just a regular USB programming cable between the two:
https://arduino.stackexchange.com/questions/11710/does-data-came-on-serial-port-store-for-some-time

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 which basically means that bytes can be sent at any time, with varying gaps between them. This graphic illustrates a single byte being sent:

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.

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:
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:

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

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

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:

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 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
How to process incoming serial data without blocking
RS-232 - Wikipedia
Arduino Reference - Serial

In the 1st graphic: with the arrows it looks like the stop bit is transmitted first. If you exchanged Rx/Tx and the direction of the arrows I'd think it's less confusing.

It was intended to be read from left to right (as is this sentence) and thus the things on the left happen first. Put it like this: on an oscilloscope, that is how you would see the trace.

Ok with the oscilloscope explanaion I buy that. :-)

However I've been thinking that your point makes a lot of sense. What do others think? Would it be clearer if the arrows were reversed, and I exchanged Rx/Tx?

I am thinking that starting at the Tx end (the left side) if you follow the path of the pulses (in the direction of the arrows) they first hit the "Start bit" notation, and then the data bits, and then the "Stop bit".

Hi Nick! Great post. I don't know why your use of the word "garbage" in the first paragraph is bothering me. I know I've used the term (and others like "gobledygoop") this way myself. Since this is a reference article I think there's a better, technical term that could be used.

It's not a word I use all that often ("rubbish" is more usual where I am) - I suppose I was thinking of "garbage in, garbage out" - not that it applies in this case). I think "gobledygoop" might be confusing to people who don't have English as a first language. I'll try to think of a better way of putting it. :)\

@linhartr22  I amended it to read "meaningless data" which is probably closer.

@NickGammon: Great post. Could you tell me why Arduino IDE's serial monitor (1.8.9) has no trouble communicating with my Arduino Micro, even if the two are configured for wildly different baud rates, e.g. 300 bps and 115200 bps, respectively? I assume this has to do with the direct usb connection, but, then, does the baud rate setting have any meaning at all for the Micro?

This seems to suggest it does not matter: https://arduino.stackexchange.com/a/31034 (unless I set 1200 bps, then exit the serial monitor, because that triggers a reset, as expected)

Yes, see Getting Started with the Arduino ... Micro On the Leonardo, Leonardo ETH and Micro, the main Serial class refers to the virtual serial driver on the board for connection to your computer over USB. It's not connected to the physical pins 0 and 1 as it is on the Uno and earlier boards. To use the hardware serial port (pins 0 and 1, RX and TX), use Serial1. The real serial port is Serial1, the USB port is called Serial. Using Serial on the Micro, you could set the baud rate to 1 and still get very fast serial printing.


text:
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?

For easier programming, you might use a programmer with pogo-pins, and draw some connection pads on the PCB. Also, some programmers can program from stored memory, so you're not re-uploading it from PC everytime, but from the memory of the programmer.

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. 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, looking like this:

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.

Thanks for the response. That is just what I was looking for.

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.

Great to know that Atmel provides this service. Thanks for the tip

Actually, the difference between Arduino code vs. plain AVR code is the use of the Arduino libraries - the bootloader is, as you say, entirely optional.  The best "connector" to use may be a single row of unpopulated plated through holes, as a mass production setup can hit those with pogo pins, while in the lab you can hold in a set of pin headers at an angle, or solder in a set if you are going to be reprogramming it a lot - but it's best to consult the factory on the specifics.

That is the difference in source code. I am on about when compiled. There is no difference when compiled. And the libraries are just AVR code. There is nothing special about them.

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.


text:
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?

Many people use the PulseIn function (https://www.arduino.cc/en/Reference/PulseIn). You can set a time-out in there.
When it doesn't return before the timeout, it will return a 0.
This way you can check if it's 0 (nothing) or a distance ( 0> ).

can you give me some reference on the timeout function

The timeout isn't a function. PulseIn is the function (check the reference), timeout is an argument of that function.
You can do PulseIn(echoPin, HIGH, timeout); to receive the time that pin is high. When it's longer as the set timeout, it'll return 0.

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.

This is my first time working with arduino so I was having trouble grasping the format of the PulseIn function. Do we need to put some time in place of time-out or does it use the delayMicroseconds(10) value...

@Reptile1234 in my example, I added the line const unsigned long timeout = 400*58; //Max of 400CM, adjust this to your own max.  effectively storing the value of 400*58 in the variabel named timeout, and used this as an argument to the PulseIn function. You could also just put the value in the arguments of that function. The delayMicroseconds is to put the trigger pin high (wait 10uS) and then low, so the ranging will start.

What is the use of making the variable?

Not much really, it's more readable and easier to change I guess.

so what is meant by the 400cm there... I thought that timeout will have a specific amount of time.

@Reptile, the max ranging of the sensor (according to datasheet is 400cm. The time a pulse takes to Travel 400cm is 400*58, so yes, it's a time out in time. But I linked it to the distance, so it's easier configurable. You can set it to defect items at a distance lower than 50cm, or 100cm, really anything below the max. If it won't find an object, it'll just time out, which can be really usefull.

Thnx...I get it now.

@Paul Is there anyway I could translate this piece of code to Python?

@ItrysohardbutIcryharder Yes, you can look at what it functionally does and implement the same in Python. But searching for "HC-SR04 raspberry pi" will also do the trick. For example: https://tutorials-raspberrypi.com/raspberry-pi-ultrasonic-sensor-hc-sr04/