text:
Question regarding using Arduino and MIDI
I'm using an Arduino Leonardo for sending MIDI In and Out messages to Ableton Live.
Components include a Potentiometer, a Capacitive Touch Sensor, and a DC Motor, which I'm powering with a L298N Motor Driver.
Right now I have it set up so that I can record automation in by moving the potentiometer, send a MIDI note in when I'm touching the fader, and follow automation using the DC Motor.
The problem that I'm having is that when I go to play my tracks, the automation that I recorded with the potentiometer is deactivated, and therefore my motor doesn't respond. I believe this is because I'm sending MIDI Input and Output at the same time. Here's the current version of the code:
#include <Control_Surface.h>
#include <CapacitiveSensor.h>

int minimumCp = 200;
int lastfaderPosition = 0;     // previous state of the button

const byte touchSend = 7;
const byte touchReceive = 8;

CapacitiveSensor touchSensor = CapacitiveSensor(touchReceive, touchSend);
USBMIDI_Interface midi;
CCPotentiometer faderPosition { A0, MIDI_CC::General_Purpose_Controller_1 };

int incomingChannel;
int incomingNote;
int incomingVelocity;
const byte mainFaderPin = 0;
const byte motorUp      = 4;
const byte motorDown    = 5;
const byte motorPWM     = 6;
byte motorSpeed = 150;
byte tolerance  = 40;
double faderMax = 0;
double faderMin = 0;

struct MyMIDI_Callbacks : FineGrainedMIDI_Callbacks<MyMIDI_Callbacks> {

  void onControlChange(Channel channel, uint8_t controller, uint8_t value, Cable cable) {
    incomingNote = controller;
    incomingVelocity = value;
  }
  void onProgramChange(Channel channel, uint8_t program, Cable cable) {
    Serial << "Program Change: " << channel << ", program " << program << ", "
           << cable << endl;
  }
  void onAfterTouchChannel(Channel channel, uint8_t pressure, Cable cable) {
    Serial << "Channel Pressure: " << channel << ", pressure " << pressure
           << ", " << cable << endl;
  }
  void onPitchBend(Channel channel, uint16_t bend, Cable cable) {
    Serial << "Pitch Bend: " << channel << ", bend " << bend << ", " << cable
           << endl;
  }
  void onSystemExclusive(SysExMessage se) {
    Serial << F("System Exclusive: [") << se.length << "] "
           << AH::HexDump(se.data, se.length) << ", " << se.cable << endl;
  }
  void onTimeCodeQuarterFrame(uint8_t data, Cable cable) {
    Serial << "MTC Quarter Frame: " << data << ", " << cable << endl;
  }
  void onSongPosition(uint16_t beats, Cable cable) {
    Serial << "Song Position Pointer: " << beats << ", " << cable << endl;
  }
  void onSongSelect(uint8_t songnumber, Cable cable) {
    Serial << "Song Select: " << songnumber << ", " << cable << endl;
  }
  void onTuneRequest(Cable cable) {
    Serial << "Tune Request: " << cable << endl;
  }
  void onClock(Cable cable) { Serial << "Timing Clock: " << cable << endl; }
  void onStart(Cable cable) { Serial << "Start: " << cable << endl; }
  void onContinue(Cable cable) { Serial << "Continue: " << cable << endl; }
  void onStop(Cable cable) { Serial << "Stop: " << cable << endl; }
  void onActiveSensing(Cable cable) {
    Serial << "Active Sensing: " << cable << endl;
  }
  void onSystemReset(Cable cable) {
    Serial << "System Reset: " << cable << endl;
  }

} callback;

void setup() {
  touchSensor.set_CS_AutocaL_Millis(0xFFFFFFFF);
  midi.setCallbacks(callback);
  Control_Surface.begin();
  pinMode(motorDown, OUTPUT);
  pinMode(motorUp, OUTPUT);
  pinMode(motorPWM, OUTPUT);
  Serial.begin(250000);
  calibrateFader();
}

void calibrateFader() {
  digitalWrite(motorUp, HIGH);
  analogWrite(motorPWM, motorSpeed);
  delay(300);
  digitalWrite(motorUp, LOW);
  faderMax = analogRead(mainFaderPin) - tolerance;
  digitalWrite(motorDown, HIGH);
  analogWrite(motorPWM, motorSpeed);
  delay(300);
  digitalWrite(motorDown, LOW);
  faderMin = analogRead(mainFaderPin) + tolerance;
}

void loop() {
  int faderPos = analogRead(mainFaderPin);
  int totalCp =  touchSensor.capacitiveSensor(9);
  Control_Surface.loop();

  if ((faderPos == lastfaderPosition) && (totalCp <= minimumCp) && (incomingNote == 16)) {
    updateFader(incomingVelocity * 8);
    }

  if ((faderPos == lastfaderPosition) && (totalCp > minimumCp)) {
    midi.sendNoteOn({37, CHANNEL_2}, 127);
    digitalWrite(motorUp, LOW);
    digitalWrite(motorDown, LOW);
  }

  if (((faderPos < lastfaderPosition - 1) || (faderPos > lastfaderPosition + 1)) && (totalCp > minimumCp)) {
    digitalWrite(motorUp, LOW);
    digitalWrite(motorDown, LOW);
  }
  if (((faderPos < lastfaderPosition - 1) || (faderPos > lastfaderPosition + 1)) && (totalCp <=minimumCp)) {
// Stop Sending MIDI, and receive it only
  }
  lastfaderPosition = faderPos;
}

void updateFader(int position) {     //Function to move fader to a specific position between 0-1023 if it's not already there
  if (position < analogRead(mainFaderPin) - tolerance && position > faderMin) {
    digitalWrite(motorDown, HIGH);
    while (position < analogRead(mainFaderPin) - tolerance) {}; //Loops until motor is done moving
    digitalWrite(motorDown, LOW);
  }
  else if (position > analogRead(mainFaderPin) + tolerance && position < faderMax) {
    digitalWrite(motorUp, HIGH);
    while (position > analogRead(mainFaderPin) + tolerance) {}; //Loops until motor is done moving
    digitalWrite(motorUp, LOW);
  }
}

Note that when I use this version with an Arduino UNO, the whole thing works. I've tried discussing this with a few who are far more experienced than I, but surprisingly they were unable to provide insight as to why.
#include <SoftwareSerial.h> // MIDI Input
#include <MIDI.h> // MIDI Output
#include <CapacitiveSensor.h>

#define rxPin 0 // Input  (Grey)
#define txPin 1 // Output (Yellow)

SoftwareSerial midiSerial (rxPin, txPin);

const byte wiper        = 0; //Position of fader relative to GND (Analog 0)
const byte motorUp      = 4;
const byte motorDown    = 5;
const byte motorPWM     = 6;
const byte touchSend    = 7;//Send pin for Capacitance Sensing Circuit (Digital 7)
const byte touchReceive = 8; //Receive pin for Capacitance Sensing Circuit (Digital 8)
unsigned int incomingCommand;
unsigned int incomingNote;
unsigned int incomingVelocity;
byte motorSpeed = 150;  // Raise if the fader is too slow (0-255)
byte minimumCp  = 200; // Raise if the fader is too sensitive (0-16383)
byte tolerance  = 10;  // Raise if the fader is too shaky (0-1023)
double faderMax = 1023; //Value read by fader's maximum position (0-1023)
double faderMin = 0; //Value read by fader's minimum position (0-1023)
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay    = 15; // the debounce time; increase if the output flickers
int lastfaderValue    = 0;
int targetPosition;
byte ch1Vol = 176;
byte fullVel = 127;
byte ch_1 = 1;
byte Db_1 = 1;

CapacitiveSensor touch = CapacitiveSensor(touchReceive, touchSend);
MIDI_CREATE_DEFAULT_INSTANCE();

void setup() {
  touch.set_CS_AutocaL_Millis(0xFFFFFFFF);
  midiSerial.begin(31250);
  MIDI.begin();
  pinMode(motorDown, OUTPUT);
  pinMode(motorUp, OUTPUT);
  pinMode(motorPWM, OUTPUT);
  calibrateFader(); }

void calibrateFader() {
  digitalWrite(motorUp, HIGH);
  analogWrite(motorPWM, motorSpeed);
  delay(300);
  digitalWrite(motorUp, LOW);
  faderMax = analogRead(wiper) - tolerance;
  digitalWrite(motorDown, HIGH);
  analogWrite(motorPWM, motorSpeed);
  delay(300);
  digitalWrite(motorDown, LOW);
  faderMin = analogRead(wiper) + tolerance; }

void loop() {
  int faderPos = analogRead(wiper);
  int faderHiResMIDI = ((faderPos *16.0146627566) - 8191.5);

  while ( midiSerial.available()) {
    incomingCommand = midiSerial.read();
    incomingNote = midiSerial.read();
    incomingVelocity = midiSerial.read()*8.05511811024;
  if ((incomingVelocity  <=1023) && (incomingCommand >127) && (incomingNote <128)) {
    midiSerial.write(incomingCommand);
    midiSerial.write(incomingNote);
    midiSerial.write(incomingVelocity); } }

 { int totalCp =  touch.capacitiveSensor(30);
 if ( (millis() - lastDebounceTime) > debounceDelay) {
    if (totalCp <= minimumCp) {
      //if (incomingCommand == ch1Vol) {
        updateFader(incomingVelocity); }// }    // Not Touching fader
    if ((faderPos == lastfaderValue) && (totalCp > minimumCp)) {
      MIDI.sendNoteOn(Db_1, fullVel, ch_1); // Touching Fader
      digitalWrite(motorDown, LOW);
      digitalWrite(motorUp, LOW); }
    if (((faderPos > lastfaderValue+1) or (faderPos < lastfaderValue-1)) && (totalCp > minimumCp)) {   // Moving Fader
      MIDI.sendPitchBend(faderHiResMIDI, ch_1);
      digitalWrite(motorDown, LOW);
      digitalWrite(motorUp, LOW); }
    lastfaderValue = faderPos;
    lastDebounceTime = millis(); } } }

void updateFader(int position) {     //Function to move fader to a specific position between 0-1023 if it's not already there
  if (position < analogRead(wiper) - tolerance && position > faderMin) {
    digitalWrite(motorDown, HIGH);
    while (position < analogRead(wiper) - tolerance) {}; //Loops until motor is done moving
    digitalWrite(motorDown, LOW); }
  else if (position > analogRead(wiper) + tolerance && position < faderMax) {
    digitalWrite(motorUp, HIGH);
    while (position > analogRead(wiper) + tolerance) {}; //Loops until motor is done moving
    digitalWrite(motorUp, LOW); } }

Is updateFader() being called when it is supposed to be called? updateFader() is only called when faderPos == lastfaderPosition. This is unlikely to be the case because there will be noise (electrical due to quantisisation and vibration) on int faderPos = analogRead(mainFaderPin). Try something like if (abs(faderPos - lastfaderPosition) < some_threshold)...)

Yea, that seems to work pretty well. I added coupling/decoupling capacitors to the MIDI In/Out circuit, and that fixed the noise right up. It's actually very stable now

What happens if position is less than faderMin e.g. incomingVelocity is zero? Or if position is greater than  faderMax, e.g. incomingVelocity is 1016 (or 127 * 8) when faderMax is about 1023 - 40 = 983?

Hi Tim, when the motor is within the tolerance for error, it simply stops moving. Without this tolerance for error, the motor will move erratically back and forth, trying to find the exact value to position itself in. Give it a tolerance, and it works right out. This is a necessary step for motorized faders

The second version in your updated question works by fluke.

But the first version doesn't work at all, lol. I'm lost

I'm working on a explanation, but have to go now. I'll post later.

Firstly, you need a robust way to synchronise to and parse MIDI messages which can be 1 byte, 2 bytes or 3 bytes or more... See this Summary of MIDI 1.0 Messages by the MIDI Association.
A good way to achieve this is by using a state machine. I've written a simple one below that parses 3-byte MIDI messages. It could be expanded to parse different types of commands.
typedef enum State
{
    Idle,
    Command,
    Data1
};

State state = State::Idle;

const float INCOMING_VELOCITY_SCALE = 1023.0 / 127.0;

byte incomingCommand;
byte incomingNote;
byte incomingVelocity;

int targetPosition;

void loop()
{
    if (midiSerial.available())  // Use the `if` statement to get the next available byte.
    {
        byte incoming = midiSerial.read();

        // Synchronise to and parse the 3-byte MIDI message packet, i.e. 1nnnnnnn 0nnnnnnn 0nnnnnnn
        switch (state)
        {
        case State::Idle:
            if (IsMidiCommand(incoming))
            {
                Serial.println("Received command byte.");
                incomingCommand = incoming;
                state = State::Command;
            }
            else if (IsMidiData(incoming))
            {
                Serial.println("Received data byte.");
            }
            break;
        case State::Command:
            if (IsMidiCommand(incoming))  // Double check for an out of sync command.
            {
                Serial.println("Received command byte.");
                incomingCommand = incoming;
                state = State::Command;
            }
            else if (IsMidiData(incoming))
            {
                Serial.println("Received data1 byte.");
                incomingNote = incoming;
                state = State::Data1;
            }
            break;
        case State::Data1:
            if (IsMidiCommand(incoming))  // Triple check for an out of sync command.
            {
                Serial.println("Received command byte.");
                incomingCommand = incoming;
                state = State::Command;
            }
            else if (IsMidiData(incoming))
            {
                Serial.println("Received data2 byte.");
                incomingVelocity = incoming;
                midiSerial.write(incomingCommand);
                midiSerial.write(incomingNote);
                midiSerial.write(incomingVelocity);
                Serial.write(incomingCommand);
                Serial.write(incomingNote);
                Serial.write(incomingVelocity);
                Serial.println();
                targetPosition = incomingVelocity * INCOMING_VELOCITY_SCALE;
                if (targetPosition > faderMax)      // Clip if out of bounds.
                {
                    targetPosition = faderMax;
                }
                else if (targetPosition < faderMin)
                {
                    targetPosition = faderMin;
                }
                state = State::Idle;
            }
            break;
        default:
            state = State::Idle;
            break;
        }
    }
    . . .
    updateFader(targetPosition);
    . . .
}

bool IsMidiCommand(const byte b)
{
    return b >= 128;  // For MIDI command bytes, MSB is 1.
}

bool IsMidiData(const byte b)
{
    return b <= 127;  // For MIDI data bytes, MSB is 0.
}

Secondly, there is an issue with the updateFader() function regarding the tolerance. It's 40 in your first version and 10 in your second version. Consider the following values for the variables:
// In setup()
digitalWrite(motorDown, HIGH);
analogWrite(motorPWM, motorSpeed);
delay(300);
faderMin = analogRead(wiper) + tolerance;
faderMin = 0                 + 40;         // Bottom of range.
faderMin = 40;

// In loop()
incomingVelocity = midiSerial.read() * 8.05511811024;
incomingVelocity = 1                 * 8.05511811024;  // A quiet note, e.g. between 0 and 5, will a give a value of 0 to 40.
incomingVelocity = 8;

// In updateFader()
if (position < analogRead(wiper) - tolerance && position > faderMin)
if (8        < 512               - 40        && 8        > 40      )
if (8        < 472                           && 8        > 40      )
if (true                                     && false              )
if (false                                                          )

Result: the fader will not budge if a quiet note is received that puts position below faderMin and will leave the fader jamming somewhere in the middle of its scale rather than boogieing on down to faderMin. This effect would be exaggerated if faderMin were higher than 40 when analogRead(wiper) reads greater than zero in setup().
Similarly, this also happens with very loud notes and faderMax at the other end of the scale:
// In updateFader()
else if (position > analogRead(wiper) + tolerance && position < faderMax)

A better way would be to clip the targetPosition to the valid range before calling updateFader() and remove the second condition from the if statements in updateFader():
targetPosition = incomingVelocity * INCOMING_VELOCITY_SCALE;
if (targetPosition > faderMax)      // Clip if out of bounds.
{
    targetPosition = faderMax;
}
else if (targetPosition < faderMin)
{
    targetPosition = faderMin;
}
. . .
updateFader(targetPosition);
. . .
if (position < analogRead(wiper) - tolerance)
. . .
else if (position > analogRead(wiper) + tolerance)
. . .

Thirdly, updateFader() blocks until the fader motor has finished moving. If notes are being received faster than the fader can move, the tempo will rallentando, so consider using a non-blocking style like Blink Without Delay.
Fourthly, faderMin and faderMax should be just that – the minimum and maximum extent of fader travel. But by adding/substracting tolerance from min/max it is unnecessarily reducing the range. The tolerance is effectively being doubled by adjusting for it in both setup() and adjustFader(). The extent of fader travel can be obtained by taking an average of several values in calibrateFader(). Then the tolerance can be adjusted for only once in adjustFader() as described above.
void calibrateFader()
{
    const byte NUM_SAMPLES = 10;
    digitalWrite(motorUp, HIGH);
    analogWrite(motorPWM, motorSpeed);
    delay(300);
    digitalWrite(motorUp, LOW);
    faderMax = AnalogueAverage(wiper, NUM_SAMPLES);
    Serial.println(faderMax);
    digitalWrite(motorDown, HIGH);
    analogWrite(motorPWM, motorSpeed);
    delay(300);
    digitalWrite(motorDown, LOW);
    faderMin = AnalogueAverage(wiper, NUM_SAMPLES);
    Serial.println(faderMin);
}

unsigned int AnalogueAverage(const byte pin, const byte num_samples)
{
    const byte ROUND_OFF = num_samples / 2;
    unsigned long total = 0;
    for (byte i = 0; i < num_samples; i++)
    {
        total += analogRead(pin);
    }
    return (total + ROUND_OFF) / num_samples;
}

On a different note...
...I've been reading through the documentation and source code for the libraries you referenced in your code, which I think are these ones:

Control Surface
Arduino MIDI Library

These already implement the MIDI message parsing using callbacks, e.g.:

Using callbacks
Using callbacks .ino

That example stresses the importance of swift non-blocking code. This means that updateFader() should also be non-blocking. You have the option to write your own custom state machine parser or use the libraries' parsers.
Here is how your code could be re-written to use the MIDI library's parser with non-blocking callbacks and non-blocking updateFader(). You may want to double-check which pins you are using for midiSerial because pins 0 and 1 are used for the default Serial monitor or you could use MIDI.sendNoteOn() and MIDI.sendNoteOff().
#include <MIDI.h>

MIDI_CREATE_DEFAULT_INSTANCE();

unsigned int faderMax = 0;
unsigned int faderMin = 0;
unsigned int faderTargetPosition = 0;

void doNoteOn(byte channel, byte note, byte velocity)
{
    midiSerial.write(channel);
    midiSerial.write(note);
    midiSerial.write(velocity);
    faderTargetPosition = velocity * INCOMING_VELOCITY_SCALE;

    // Clip if out of bounds.
    if (faderTargetPosition > faderMax)
    {
        faderTargetPosition = faderMax;
    }
    else if (faderTargetPosition < faderMin)
    {
        faderTargetPosition = faderMin;
    }
}

void doNoteOff(byte channel, byte note, byte velocity)
{
    midiSerial.write(channel);
    midiSerial.write(note);
    midiSerial.write(velocity);
}

void setup()
{
    MIDI.setHandleNoteOn(doNoteOn);
    MIDI.setHandleNoteOff(doNoteOff);
    MIDI.begin(MIDI_CHANNEL_OMNI);
    . . .
}

void loop()
{
    // Parse the MIDI messages and call the callbacks.
    MIDI.read();

    if ((millis() - lastDebounceTime) > debounceDelay)
    {
        int totalCp = touch.capacitiveSensor(30);
        int faderPos = analogRead(FADER_PIN);
        int faderHiResMIDI = faderPos * 16.0146627566 - 8191.5;

        if (totalCp <= minimumCp)
        {
            // Not touching fader.
            //if (incomingCommand == ch1Vol)
            //{
            updateFader(faderTargetPosition);
            //}
        }
        else
        {
            if (faderPos == lastfaderValue)
            {
                // Touching fader.
                MIDI.sendNoteOn(Db_1, fullVel, ch_1);
                digitalWrite(MOTOR_DOWN_PIN, LOW);
                digitalWrite(MOTOR_UP_PIN, LOW);
            }
            else if ((faderPos > lastfaderValue + 1) or (faderPos < lastfaderValue - 1))
            {
                // Moving fader.
                MIDI.sendPitchBend(faderHiResMIDI, ch_1);
                digitalWrite(MOTOR_DOWN_PIN, LOW);
                digitalWrite(MOTOR_UP_PIN, LOW);
            }
        }
        lastfaderValue = faderPos;
        lastDebounceTime += debounceDelay;  // Constant interval.
    }
}

void updateFader(const unsigned int& faderTargetPosition)
{
    const unsigned int currentPosition = analogRead(FADER_PIN);
    if (faderTargetPosition < currentPosition - tolerance)      // Below the tolerance band.
    {
        digitalWrite(MOTOR_UP_PIN, LOW);                        // Switch the up control off before switching the down control on.
        digitalWrite(MOTOR_DOWN_PIN, HIGH);
    }
    else if (faderTargetPosition > currentPosition + tolerance) // Above the tolerance band.
    {
        digitalWrite(MOTOR_DOWN_PIN, LOW);                      // Switch the down control off before switching the up control on.
        digitalWrite(MOTOR_UP_PIN, HIGH);
    }
    else                                                        // Within the tolerance band.
    {
        digitalWrite(MOTOR_DOWN_PIN, LOW);
        digitalWrite(MOTOR_UP_PIN, LOW);
    }
}


text:
ESP-01 + UNO won't detect gateway
Apparently, this combination of hardware won't accept anything other than WiFiEsp.h together with SoftwareSerial.h (if anyone knows something better/newer than these two, please let me know).
Thing is: I can connect to wifi, send and receive data (to an apache server inside my home network) just fine. After my project was almost done, I decided to connect it to a real server on the internet only to discover that ESP-01 couldn't detect my gateway.
#include "WiFiEsp.h"
#include "SoftwareSerial.h"

int pinWifiRX = 6;
int pinWifiTX = 7;

char ssid[64]    = "*****";
char pass[32]    = "************";

SoftwareSerial Serial1(pinWifiRX, pinWifiTX);

int wifi_status;

void setup() {

  Serial.begin(9600);

  Serial1.begin(9600);
  while(!Serial1) (true);

  WiFi.init(&Serial1);

  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println(F("No shield"));
    while (true) {}
  }

  IPAddress localIp(192, 168, 1, 60);
  IPAddress subnetMask(255, 255, 255, 0);
  IPAddress gateway(192, 168, 1, 36);

  WiFi.config(localIp);  // <--- this line is accepted and works, but the other 3 gives compilation errors
//  WiFi.config(localIp, gateway);
//  WiFi.config(localIp, gateway, subnetMask);
//  WiFi.config(localIp, gateway, subnetMask, gateway);

  wifi_status = WiFi.begin(ssid, pass);

  if (wifi_status == WL_CONNECTED) {

    IPAddress ip;

    ip = WiFi.localIP();
    Serial.print(F("[WiFiEsp] IP Address: "));
    Serial.println(ip);

    ip = WiFi.subnetMask();
    Serial.print(F("[WiFiEsp] Subnet Mask: "));
    Serial.println(ip);

    ip = WiFi.gatewayIP();
    Serial.print(F("[WiFiEsp] Gateway: "));
    Serial.println(ip);

//    ip = WiFi.getDNS();  // <--- function doesn't exist
  }

}

void loop() {}

Results in:
[WiFiEsp] Initializing ESP module
[WiFiEsp] Initilization successful - 2.2.1
[WiFiEsp] IP address set 192.168.1.60
[WiFiEsp] Connected to *****
[WiFiEsp] IP Address: 192.168.1.60
[WiFiEsp] Subnet Mask: 255.255.255.0
[WiFiEsp] Gateway: 192.168.1.0

As one can see, Subnet Mask is corret, but it "detects" Geteway 192.168.1.0 when it should be 192.168.1.36. This way, I can connect to any device in LAN, but cannot access any address on the internet.
I even tried to send some AT commands directly to SoftwareSerial.h, but I don't get any response.
Will I have to start the whole project over from scratch (using another hardware combination), or is there a way to change gateway by hand? Better yet, is there a way to make it detect the gateway's address correctly?
EDIT: could it be related to the firmware I installed to the ESP-01? I followed this tutorial and got it from this link.
Thanks in advance.
EDIT: in this example, i used the WiFi.config(localIp) function to set a fix IP. I don't really need that, it was just an attempt to make it get the correct Gateway address. Even if I comment that line, the Gateway is still wrong.

use a gateway at 192.168.1.1

I can't do that. My gateway is configured at 192.168.1.36 and I can't change it. Besides, it would be nice if it could detect settings even if the device is some place else.

there is no way to detect settings. if you use static IP,  DHCP is not requested. the AT firmware uses default gateway address based on static IP. my WiFiEspAT library has full config, but requires AT 1.7.x (SDK3) and can't use https

I've had some progress in my researches towards this problem.
In fact, Arduino gets the correct gateway address from my DHCP server, but displays the wrong one. There must be a bug somewhere in WiFiEsp library somewhere.
To debug this, I made a few changes to the following files:

WiFiEsp-Master/src/WiFiEsp.h

void config(IPAddress local_ip, IPAddress gateway);
void config(IPAddress local_ip, IPAddress gateway, IPAddress subnetMask);

WiFiEsp-Master/src/WiFiEsp.c

void WiFiEspClass::config(IPAddress ip, IPAddress gateway)
{
  EspDrv::config(ip, gateway);
}
void WiFiEspClass::config(IPAddress ip, IPAddress gateway, IPAddress subnetMask)
{
  EspDrv::config(ip, gateway, subnetMask);
}

WiFiEsp-Master/src/utility/EspDrv.h

static void config(IPAddress local_ip, IPAddress gateway);
static void config(IPAddress local_ip, IPAddress gateway, IPAddress subnetMask);

WiFiEsp-Master/src/utility/EspDrv.cpp

void EspDrv::config(IPAddress ip, IPAddress gateway) {
  LOGDEBUG(F("> config"));

  // disable station DHCP
  sendCmd(F("AT+CWDHCP_CUR=1,0"));

  // it seems we need to wait here...
  delay(500);

  char buf_ip[16];
  sprintf_P(buf_ip, PSTR("%d.%d.%d.%d"), ip[0], ip[1], ip[2], ip[3]);

  char buf_gateway[16];
  sprintf_P(buf_gateway, PSTR("%d.%d.%d.%d"), gateway[0], gateway[1], gateway[2], gateway[3]);

  int ret = sendCmd(F("AT+CIPSTA_CUR=\"%s\",\"%s\""), 2000, buf_ip, buf_gateway);
  delay(500);

  if (ret==TAG_OK)
  {
    LOGINFO1(F("IP and gateway addresses set"), buf_ip);
  }
}

void EspDrv::config(IPAddress ip, IPAddress gateway, IPAddress subnet)
{

  LOGDEBUG(F("> config"));

  // disable station DHCP
  sendCmd(F("AT+CWDHCP_CUR=1,0"));

  // it seems we need to wait here...
  delay(500);

  char buf_ip[16];
  sprintf_P(buf_ip, PSTR("%d.%d.%d.%d"), ip[0], ip[1], ip[2], ip[3]);

  char buf_gateway[16];
  sprintf_P(buf_gateway, PSTR("%d.%d.%d.%d"), gateway[0], gateway[1], gateway[2], gateway[3]);

  char buf_subnet[16];
  sprintf_P(buf_subnet, PSTR("%d.%d.%d.%d"), subnet[0], subnet[1], subnet[2], subnet[3]);

  int ret = sendCmd(F("AT+CIPSTA_CUR=\"%s\",\"%s\",\"%s\""), 4000, buf_ip, buf_gateway, buf_subnet);
  delay(500);

  if (ret==TAG_OK)
  {
    LOGINFO1(F("IP, gateway and subnet mask addresses set"), buf_ip);
  }
}

These few changes should be enough to implement fix IP address and specify manual address for gateway and subnet mask (please feel free to correct me if I'm wrong).
But after doing this, I realized the gateway continued to be "192.168.1.0". Then I added this piece o code to the function EspDrv::readUntil, inside EspDrv.cpp:"
        ringBuf.push(c); // this line was already there
        Serial.print(c);

This way, I could see exactly all responses for the AT commands sent by WiFiEsp library. When asked, the results were:
+CIPSTA:ip:"192.168.1.60"
+CIPSTA:gateway:"192.168.1.36"
+CIPSTA:netmask:"255.255.255.0"

Then I realized the problem wasn't the gateway, but the DNS. If the library sends command "AT+CIPSTART=3,"TCP","www.google.com",80", the result was:
Not connected

busy p...

And, if increased the timeout value to 15000 instead of 5000, the result was:
DNS ERROR

Now my problem is partially solved. I can connect to an external server if I use an IP address, but I can't set a domain name because it won't be resolved by the DNS.
Apparently the firmware version of my ESP-01 won't accept "AT+CDNSCFG=?" required to set/retrive DNS address. I tried to set 8.8.8.8 as the DNS, but the result was "NOT OK".
I will stick to this "solution" for now, but would be glad to hear any comment about what I described here and a more final solution.
Thanks.

Using a static IP address with a gateway is not implemented (as you can see from the source code).
To get out to the internet with that library you can only use DHCP (by omitting the WiFi.config(localIp) call).

yes, that was the original form. It also gets wrong gateway address.

source: Stack Exchange

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

sort: votes


text:
Trying to track down macro or #define values, possibly in arduino preprocessor
In reading various code I stumble across symbols that seem to be the result
of #define or other macro like symbols that I cannot find just by tracking
through the code ( including its chain, if any, of includes ).
Can someone offer some reasonably simple, but complete, guidance on how the
arduino ide works with especially emphasis on automatically included files
( and their location ) and any other automagically appearing stuff.

The Arduino IDE handles very few of these itself. Try looking at what AVR-GCC does.

On Linux, I usually just grep -l FOO /usr/share/arduino/hardware/arduino/cores/arduino/*.h or grep -lr FOO /usr/lib/avr/include/.

Most of the #defines happen an Arduino.h and the board  variant files, although a few are passed as compiler arguments if you still can't find anything.

I usually do a search on the github page (https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/cores/arduino)

Arduino inclusion is dark magic mixed with randomness... I haven't been able to find a consistent include "scheme" for Arduino, although I haven't poked around in the source.

It might help to point out the use of -D switches of gcc here.
If you turn on verbose output of the Arduino IDE (I am using a pretty old version):

you will see, when you compile a sketch, that the compiler is not only called with a switch -m (e.g.  -mmcu=atmega328p) which describes the target (i.e. the ATMEL AVR instruction set or MCU type) for which the code is compiled, but also with a number of -D switches.
The -D switches predefine a name as a macro and also that depend on the target.
You might see for example
-DF_CPU=16000000L -DARDUINO=100

where F_CPU is used to pass information about the target's clock speed (16 MHz in this case) to code that depends on this, e.g. the delay function or the Serial library.
3 ways to define macros
In general, the confusion might come from the fact that including files in the Arduino build chain depends a lot on compiler flags, and there are several ways to define these:

#define
using -D switches
from the target specification (compiler built-in, -m)

The last point means that the above mentioned -matmega328p defines the macro __AVR_ATmega328P__ which is e.g. used in io.h to include the appropriate file with pin mappings, RAM sizes etc. (Google for avr-mcus.def to find a full list of these predefined macros for AVR targets.)
Finally, note that the Arduino IDE also sets include paths depending on the target. The appropriate set of pin definitions is selected by passing an include path like this to avr-g++:
-I/usr/share/arduino/hardware/arduino/variants/standard

where standard is replaced by leonardo, micro, mega etc.
Short answer / summary / how to debug
First, to generate a list of the current #define directives, use the -dM option like this (compiling an empty program that is specified to be C with -x c):
echo | avr-gcc -x c -E -dM -mmcu=atmega328p - | sort

Change -mmcu=atmega328p to your needs (you can also leave it out).
Second, you can use the option -g3 to include the macro definitions in the output. Keep the intermediate files by using -save-temps. You can append these to the compiler call by the IDE:
avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega168 -DF_CPU=8000000L -DARDUINO=100 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /tmp/build5017602110288.tmp/SerialManual.cpp -o/tmp/build5017602110288.tmp/SerialManual.cpp.o -save-temps -g3

which will create a long output file *.ii (here SerialManual.ii) that lists among others the defines and typedefs and, most importantly, from which files they come.
Sample output:
# 1 "/tmp/build501760211028815624.tmp/SerialManual.cpp"
# 1 "/tmp/1//"
# 1 "<built-in>"
#define __STDC__ 1
#define __cplusplus 1
#define __AVR_ATmega168__ 1
#define __CHAR16_TYPE__ short unsigned int
...
# 1 "<command-line>"
#define F_CPU 8000000L
#define ARDUINO 100
...
# 1 "/usr/lib/gcc/avr/4.5.3/../../../avr/include/avr/iom168.h" 1 3
# 34 "/usr/lib/gcc/avr/4.5.3/../../../avr/include/avr/iom168.h" 3
#define _AVR_IOM168_H_ 1
#define SPM_PAGESIZE 128
#define RAMSTART (0x100)
#define RAMEND 0x4FF
#define XRAMEND RAMEND
#define E2END 0x1FF
#define E2PAGESIZE 4
#define FLASHEND 0x3FFF
...

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


text:
Can I measure the current (mA) of my project with just a multi meter?
I have a project and wish to choose the correct battery back for it such that it will last the required amount of time between each recharge of the battery pack. I am using an Arduino Duemilanove with various attachements and shields.
I can measure that the draw on the project at the point the USB connects from my PC to the Arduino board (by attaching the multimeter to the Vcc and GND solder points on my Arduino board) which reads 5V DC as expected. Is there a way I can meausre the current (without any additional equipment) ?
I suspect somehow using Ohms law and measuring the resistance between two points would be the answer (knowing the voltage is 5V) but I can't work it out (as in where to measure) with my lack of any electrical knowledge.

No, you won't get the right result measuring resistance. Integrated circuits contain lots of semiconductors which are inherently non-linear.
You need to somehow put your multimeter in series with the power supply, set to the mA range. The easiest way I can think of is to use an external battery (7v or higher) and make up a custom cable with standard barrel jacks. As your board appears to have a linear voltage regulator, the current measured will be very close to the current consumed when powered from the USB port.

NOTE: This may be inaccurate if the power usage isn't constant - driving a stepper motor, for example; high current for a short period, low current the rest of the time. Your multimeter will not be quick enough to pick up the peaks and troughs. You will probably get the median (most common) current, not the mean (average).

That is a fairly simple method an electrical beginner like me can follow, thank you very much. I knew there would be a simple way but I couldn't see it myself.

A reasonable method is to place a small value resistor in series with the supply, connect a capacitor from the Arduino side of the resistor to ground and then measure the voltage drop across the resistor.
If you set the resistor value such that the highest current drawn drops less than about 0.1 Volts then it will have minimal effect on most circuits.
For example if max current is 100 mA then as R = V/I, Rmax <= V/I = 0.1/100 ma = 0.1V/0.1A = 1 Ohm.
So generally
Rseries <= Vdrop_max / Imax_A  (I in Amps) or
Rseries = Vdropmax x 1000 / Imax_mA   (I in milliAmps)
Then I_ma = Vmeter x 1000  / R
Example:
Max current = 350 mA.
R <= V/I = 0.1V /0.350  A = <= 0.286 Ohm.
A 0.1 Ohm - which is a readily available standard value, will probably be good.
Then if meter reads say 0.033 volt (33 millivolts) then
ImA = V_mv / R   = 33/0.1 = 330 mA.
A larger resistor value, giving a larger voltage drop, can be used if the circuit will tolerate the resultant lower supply voltage.

Measure the drop with a meter set to 0.2 V (200 millivolts). Nit all meters have a 0.2 V range but even some reasonably cheap ones do have and it is worth having a meter with this range for various purposes.
Connect a capacitor from Arduino 5Vin to ground - the more uF the better. 100 uF probably OK, 1000 uF better ... .
This method will smooth out short current peaks and give you an average current. This aspect can be expanded on if of interest.

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


text:
NodeMCU Arduino set PWM Frequency to specific frequency
I am using NodeMCU and I program it using Arduino IDE, I need to change the PWM frequency of a port, in Arduino I used to change the frequency using timers registers like that:
TCCR1B = (TCCR1B & 0xF8) | 1 ;

How can I change the frequency of a digital pin using some function like that:
analogWriteFrequency(pin, 31250);

So that the code will looks like that:
#ifdef __AVR__
TCCR1B = (TCCR1B & 0xF8) | 1 ; //generates the MCKL signal
#else
analogWriteFrequency(pin, 31250);
#endif
analogWrite(pin, 128) ;

Thanks.

PWM frequency is 1kHz by default. Call analogWriteFreq(new_frequency) to change the frequency.

source

Thanks.
but, can I adjust it to a specific pin ?

Probably not. They probably all use the same single PWM generator.

Source link is 404.

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


text:
ArduinoUNO/MEGA, Is there a way to exceed 256 in analogWrite
I am using Arduino UNO/MEGA, I want to
analogWrite(pin, val);

where the value is 0-1023.
How can I make that ?
Thanks.

It seems there are two types of answers emerging - those that increase the resolution of the PWM, and those that adapt your data to fit the existing resolution, using something like map.  I find both types of answers to be useful, but you might want to clarify what your intention is for going to 1023.

@GuitarPicker, the data that returns from analogRead is from 0-1023

@GuitarPicker  The data comes from analogRead is 0-1023, how can I output the same data using pwm, that's is .

Section 16, "16-bit Timer/Counter1 with PWM" of Atmel-8271J-AVR- ATmega-Datasheet_11/2015 describes using Timer/Counter-1 for 16-bit PWM, including sample code in both C and assembler. It might take a couple of reads over that section to get familiar with the hardware and learn what else T/C-1 is used for, and that you might have to give up while using it for PWM, but the code is fairly straightforward.
Using this T/C would give you 2-bits more resolution in your PWM output than mapping onto an 8-bit counter, if that is what your project needs.
+1 for the question. Not having needed PWM output for anything more than a demo with my DMM (yet), it hadn't occurred to me to look for a higher resolution until now.

This is the correct answer. Neither of the other 2 answers say how to output the resolution he wants.

The simplest way is to change your value range to 0-255. You can't change analogWrite's range, since that is fixed in the core software.
analogWrite(5, val >> 2);

The >> 2 bit-shifts the value two bits to the right, turning a 10-bit value (0-1023) into an 8-bit value (0-255). It's by far the most efficient way of dividing by 4.
On more complex 32-bit boards, like the Arduino Due, or the chipKIT range of boards, etc, you have the function analogWriteResolution() which can change the range, but that cannot be done on the 8-bit boards.
From what I have read online it looks like the ATMega chips may support higher resolutions for PWM - however there is no support in the core for that. If you need a higher resolution for some specific reason then you will need to program the registers manually yourself and not rely on the Arduino API to do the work for you. For that you will need to consult the datasheet for your chosen chip.

I'm pretty sure the compiler will optimize x / some_constant_power_of_two to x >> exponent_of_the_number.

@Kroltan Quite probably. It's something I would hope it did do. Personally I like to be explicit though, just on the offchance that it doesn't.

I agree with @Majenko's answer, though here is a more "beginner" friendly method of doing the same.
val = map(val,0,1023,0,255);
analogWrite(pin, val);

Not the most efficient, but still...

The other questions so far have correctly addressed one possible meaning of this question, "how can I increase the resolution?"  Here's another possible interpretation.
How can I increase the output magnitude?
It sounds like you might want to output a higher maximum voltage than what you get from using analogWrite(pin,255) on the Uno or Mega.  This is not possible using the Arduino by itself, because PWM represents a fraction of the maximum output, not an absolute value.
On the Uno and Mega, that maximum output is 5V, so the approximate values come out to:
analogWrite(pin,0);   // (0 / 255) * 5V   (0% of 5V == 0V)
analogWrite(pin,127); // (127 / 255) * 5V (50% of 5V == 2.5V)
analogWrite(pin,255); // (255 / 255) * 5V (100% of 5V == 5V)

If you want to make a higher absolute voltage, you will need an external power source and a method of translating the 0-5V output into another voltage range.  This is called "level shifting" and there are standalone ICs which can do this job.  Motor drivers and H-Bridge devices utilize this principle as well.
If you use some sort of level shifting circuitry, then you can map the analogWrite to a different range, such as 0-20V:
analogWrite(pin,0);   // (0 / 255) * 20V   (0V)
analogWrite(pin,127); // (127 / 255) * 20V (10V)
analogWrite(pin,255); // (255 / 255) * 20V (20V)


text:
Connecting PC speaker to Arduino
I've looted this speaker from my old PC and trying to understand how to connect it to Arduino to produce simple sound notification (and not fry anything in the process).
As far as I understand this is a piezo speaker, there is no markings on it. Here is how it looks:

How do I connect\control it?
Should I connect it to PWM pin? If so, what are the safe values to output on PWM pin?
Should I use resistor when connecting speaker? What resistor should I use?

Take a look at the tone() function, it may suit your purpose.

As far as connections go, I would connect the red wire to a PWM pin and the black one to a GND pin, but I'm not sure if a resistor is needed, wait for someone more expert than me to answer. :)

No need for a resistor. Just connect black to ground, and red to a IO pin. Use the tone function to specify a frequency.

I'd recommend using a resistor. The piezo conducts quite well and might fry the pin. http://arduino.cc/en/Tutorial/Tone Also see http://www.uchobby.com/index.php/2007/11/11/arduino-sound-part-1/

@MrJones A resistor might be needed for (electromagnetic) speakers, not for piezos. A piezo is more like a capacitor, and doesn't conduct any current.

Why is no resistor needed? I don't exactly know OP's speaker, but my speaker says 8 Ohm. 8 Ohm at 5V is much more than an Arduino can handle, isn't it?

@ThomasWeller OPs "Speaker" is actually a piezo. A piezo you can drive with an Arduino pin. With a (8-ohm) speaker, you can't do that.


text:
Receive multiple data from arduino using String builder
I am working on a small project where I have to read data from different hardware and display it on android app. I am using arduino Uno to get the values from a sensor and a motor and I use a bluetooth module to send the data to the android device. I know how to read data from motor only but not from motor AND sensor. The data displayed on the arduino can be assumed as follows:
Motor: 132
Sensor: 258
Motor: 259
Sensor: 992
So first, we will read the value of the motor then the sensor then the motor and so on. Here is part of the code where I used handler and string builder to read data from the motor. How to modify the code in order to read from BOTH the motor and sensor and keep the updating the values?
Code:
Handler mHandler = new Handler()
    {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    byte[] readBuf = (byte[]) msg.obj;
                    String strIncom = new String(readBuf, 0, msg.arg1);
                    sb.append(strIncom);
                    int endOfLineIndex = sb.indexOf("\r\n");
                    if (endOfLineIndex > 0) {
                        String sbprint = sb.substring(0, endOfLineIndex);
                        sb.delete(0, sb.length());
                        motor.setText(sbprint);             // update TextView
                    }

                    break;
            }
        };
    };

You can convert each value to string before sending to bluetooth using string.contain("string"), like this:
if (sbprint.contains("C"){
    temptv.setText(sbprint);}
if (sbprint.contains("H")){
    humidtytv.setText(sbprint);}


text:
Android stops reading from bluetooth module
I am trying to read from a bluetooth module connected to arduino Uno. My application is a simple counter where the values are displayed on the arduino and the android app. The problem is that my android application get readings for some time (40-50 sec) and then stop at a random reading. When I check on the arduino serial monitor, the counter keeps counting and doesn't stop. Can someone please help?
Note: Ignore the buttons that I created :D
Java code:
package com.example.ibm.bluetooth_3;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import com.example.ibm.bluetooth_3.R;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private static final String TAG = "bluetooth2";

    Button btnOn, btnOff;
    TextView txtArduino;
    Handler h;

    final int RECIEVE_MESSAGE = 1;      // Status  for Handler
    private BluetoothAdapter btAdapter = null;
    private BluetoothSocket btSocket = null;
    private StringBuilder sb = new StringBuilder();

    private ConnectedThread mConnectedThread;

    // SPP UUID service
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    // MAC-address of Bluetooth module (you must edit this line)
    private static String address = "00:06:66:68:30:D6";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnOn = (Button) findViewById(R.id.btnOn);                  // button LED ON
        btnOff = (Button) findViewById(R.id.btnOff);                // button LED OFF
        txtArduino = (EditText) findViewById(R.id.txtArduino);      // for display the received data from the Arduino
        h = new Handler() {
            public void handleMessage(android.os.Message msg) {
                switch (msg.what) {
                    case RECIEVE_MESSAGE:                                                   // if receive massage
                        byte[] readBuf = (byte[]) msg.obj;
                        String strIncom = new String(readBuf, 0, msg.arg1);                 // create string from bytes array
                        sb.append(strIncom);                                                // append string
                        int endOfLineIndex = sb.indexOf("\r\n");                            // determine the end-of-line
                        if (endOfLineIndex > 0) {                                           // if end-of-line,
                            String sbprint = sb.substring(0, endOfLineIndex);               // extract string
                           sb.delete(0, sb.length());                                       // and clear
                            txtArduino.setText(sbprint);                                    // update TextView
                        }
                        //Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
                        break;
                }
            };
        };

        btAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
        checkBTState();

        btnOn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                btnOn.setEnabled(true);
                mConnectedThread.write("1");    // Send "1" via Bluetooth
                //Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
            }
        });

        btnOff.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                btnOff.setEnabled(true);
                mConnectedThread.write("0");    // Send "0" via Bluetooth
                //Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
        if(Build.VERSION.SDK_INT >= 10){
            try {
                final Method  m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
                return (BluetoothSocket) m.invoke(device, MY_UUID);
            } catch (Exception e) {
                Log.e(TAG, "Could not create Insecure RFComm Connection",e);
            }
        }
        return  device.createRfcommSocketToServiceRecord(MY_UUID);
    }

    @Override
    public void onResume() {
        super.onResume();

        Log.d(TAG, "...onResume - try connect...");

        // Set up a pointer to the remote node using it's address.
        BluetoothDevice device = btAdapter.getRemoteDevice(address);

        // Two things are needed to make a connection:
        //   A MAC address, which we got above.
        //   A Service ID or UUID.  In this case we are using the
        //     UUID for SPP.

        try {
            btSocket = createBluetoothSocket(device);
        } catch (IOException e) {
            errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
        }

    /*try {
      btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) {
      errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }*/

        // Discovery is resource intensive.  Make sure it isn't going on
        // when you attempt to connect and pass your message.
        btAdapter.cancelDiscovery();

        // Establish the connection.  This will block until it connects.
        Log.d(TAG, "...Connecting...");
        try {
            btSocket.connect();
            Log.d(TAG, "....Connection ok...");
        } catch (IOException e) {
            try {
                btSocket.close();
            } catch (IOException e2) {
                errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
            }
        }

        // Create a data stream so we can talk to server.
        Log.d(TAG, "...Create Socket...");

        mConnectedThread = new ConnectedThread(btSocket);
        mConnectedThread.start();
    }

    @Override
    public void onPause() {
        super.onPause();

        Log.d(TAG, "...In onPause()...");

        try     {
            btSocket.close();
        } catch (IOException e2) {
            errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
        }
    }

    private void checkBTState() {
        // Check for Bluetooth support and then check to make sure it is turned on
        // Emulator doesn't support Bluetooth and will return null
        if(btAdapter==null) {
            errorExit("Fatal Error", "Bluetooth not support");
        } else {
            if (btAdapter.isEnabled()) {
                Log.d(TAG, "...Bluetooth ON...");
            } else {
                //Prompt user to turn on Bluetooth
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);
            }
        }
    }

    private void errorExit(String title, String message){
        Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
        finish();
    }

    private class ConnectedThread extends Thread {
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the input and output streams, using temp objects because
            // member streams are final
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer = new byte[1024];  // buffer store for the stream
            int bytes; // bytes returned from read()
            // Keep listening to the InputStream until an exception occurs
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);        // Get number of bytes and message in "buffer"
                    h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();     // Send to message queue Handler
                } catch (IOException e) {
                    break;
                }
            }
        }

        /* Call this from the main activity to send data to the remote device */
        public void write(String message) {
            Log.d(TAG, "...Data to send: " + message + "...");
            byte[] msgBuffer = message.getBytes();
            try {
                mmOutStream.write(msgBuffer);
            } catch (IOException e) {
                Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
            }
        }
    }
}

Android XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:focusable="true">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="On"
        android:id="@+id/btnOn"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="52dp"
        android:enabled="true"
        android:focusable="true"
        android:focusableInTouchMode="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Off"
        android:id="@+id/btnOff"
        android:layout_below="@+id/btnOn"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="63dp"
        android:enabled="true"
        android:focusable="true"
        android:focusableInTouchMode="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/txtArduino"
        android:layout_below="@+id/btnOff"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="65dp" />

</RelativeLayout>

Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ibm.bluetooth_3" >
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Arduino code:
#include <SoftwareSerial.h>
SoftwareSerial mySerial (3, 2);
void setup()
{
  Serial.begin (57600);
  mySerial.begin (115200);
}

void loop()
{
  for (int i=0; i < 1000000; i++)
  {
    mySerial.println (i);
    Serial.println (i);
    delay (100);
  }
}

So far, I am not able to solve the problem :'(

I am not sure if you have found the answer. Here are my observation. Those who are searching for same problem can refer to these...

Change your Android device. Devices will have different bluetooth stack provided by bluetooth chip makers. Cheap ones will have problems. I had this. When I tested with another couple of devices, they seem to have handled it very well. It is all in the bluetooth stack on Android device!
Though I have not had problems with Arduino bluetooth device, try changing that.
Disable all logging on Android app. This will reduce burden on device.
Disable Serial communication on Arduino used for debugging purpose. This way you can make sure that only one serial communication channel is active communicating with Android.

If you follow this, surely you will have solved your problem as I have solved the same.
-Sachin

On the Arduino side, try increasing the delay or decreasing the baud rate. I have an application that dumps a stored history to a Bluetooth module talking to Bluetooth Terminal/Graphics
on a Google Nexus 7. At 57600 baud, I've seen the same thing happen. My solution was to delay for 50ms after every 100 lines of output. While your Arduino code should be sending even slower than mine does, your Android system including your application code, might need an even slower input.

I made the delay 100 ms and it didn't work. Changing the baud rate of the bluetooth module is not an option because it works at high baud rate. I am using BlueSmirf Gold.

Unless I misunderstood something, you said it stopped working after a time and you're trying to find out why. I've suggested 2 experiments that may help you find out.

I used your app. It's very nice and it works perfectly when it comes to reading. When I choose "Terminal and Graph" I see the readings without stopping which is exactly what I am seeking for. Instead of using a listview that you are using I want to use an editext. Can you please tell me how?

The app isn't mine, just one I bought for graphing logged data from my instruments, and as you said, a very nice one. If you select "start logging" from its menu, it will capture its input to a text file, at which point you can do anything you want to with it. I don't know any way to interact with the data within the app other than using its terminal screen to send commands back to the Arduino/.


text:
"write" function in sd card is not working
I have recently started working with arduino UNO and the "write" function in sd Card library is not working. Below is my code. I have tried with "println" which is working fine. Any help regarding this is welcome.
void loop()
{
     byte b=10;
     File dataFile = SD.open("datalog.txt", FILE_WRITE);
    if (dataFile)
    {
        dataFile.write(b);
     }
}

How is the SD card reader connected? Is it part of a shield? It might also be helpful if you show us the complete program. Are you calling SD.begin() anywhere?

@peter Hi,I have called the SD.begin() in setup(). The issue is "write" function is not working. When I am using "print", I am able to write to the file. Thanks!

How do you know it's not working? What's actually happening?

I am writing the byte b to the text file. When I am reading the SD card, I can't see the byte in it which I am able to see when I use "print" function instead of "write". I desperately want "write" function to operate so that I can directly write arrays without any "for loops", which I will not be able to achieve if I use "print" function. Thanks!

The problem is that print() and write() behave differently when you give them numerical data, such as a byte.
When you pass your byte to print(), it converts it to text which is convenient for humans to read. For example:
byte b = 10;
dataFile.print(b);

This will result in the following ASCII characters being written to the file:
10

That's actually two bytes: one byte with the value 49, which represents ASCII character 1, followed by a byte with the value 48 representing character 0.
However, write() does not convert numbers into text. It writes them in their raw binary form. For example:
byte b = 10;
dataFile.write(b);

When you do this, it doesn't write a "1" and a "0" to the file. It literally writes a binary byte with the value 10. When you try to open this as a text file, your computer interprets that byte as a single ASCII character. It so happens that ASCII value 10 is the newline character, meaning your file basically contains a blank line.
For comparison, try this instead:
byte b = 65;
dataFile.write(b);

ASCII value 65 corresponds to the letter A (uppercase), so that's what you should see in the file.
The write() functions are useful for writing raw data to file in the most efficient form for another machine to read (as opposed to being human-readable). This is why they allow you to write arrays -- it acts like one big block of raw data with a fixed format.
In your case, print() is more appropriate. That means for outputting arrays of numbers, you will need to use loops. That functionality isn't built-in to the print() functions because different projects might need different formatting. For example, some people might want one number per line, whereas others might want numbers separated by commas, and so on.

Thanks Peter, but I want to store large chunks of data as fast as possible so that I can sample incoming data at high rates and using of loops slows the speed. Is there a way to achieve this?

@Naresh If speed is critical then it's preferable to use write() to output binary. However, you can't read raw binary files using a text editor. You would need some other program on your computer to load it or convert it into a useful format. I don't know of a general purpose program which would do that for you automatically. You'd probably have to write something yourself.

It is typical of file devices that an output file must be closed when the application is through writing to it - datafile.close(), using your variable names. Their drivers or libraries typically buffer output data in memory and may not write it to the device until the buffer fills or the application flushes the buffers or closes the file.
See the read/write SD card example at the Arduino site. Especially note the uses of the calls to:
begin
open
print or write, ...
close

Failing to close an output fail might leave unwritten data in memory buffers rather than flushing the last few bytes (all of the data, in the case of your one-byte-write example).
It is also possible that there is another fault - incorrect mapping of I/O pins to the card reader/writer, incorrect wiring, faulty device or card, but I think the programming sequence is the most likely culprit.

Hi, the issue is "write" function is not working. When I am using "print", I am able to write to the file. Thanks!

I would still make sure I used the whole {begin; open; write; close;} sequence, then examine the resulting output file with a hex-editor on your computer to confirm that does or does not contain what you expect it to.


text:
Unable to see SPI clock in oscilloscope
I am using the following code and when I am probing pin 13(SCK), I can't see any clock signal in the oscilloscope.
#include <SPI.h>
int SCS=10;
int SI=11;
int SCLK=13;
int EXTCOMIN=4;

void setup()
{
 pinMode(SCS,OUTPUT);
 pinMode(EXTCOMIN,OUTPUT);
 pinMode(SCLK,OUTPUT);
 digitalWrite(SCS,HIGH);
 tone(EXTCOMIN,50);
 SPI.setClockDivider(SPI_CLOCK_DIV16);
 SPI.begin();
}

void loop()
 {
 }

The SPI port is only clocked when you call SPI.transfer().

@EdgarBonet thanks, yeah now I am able to see the clock with the desired frequency

(META: This question has been answered in the comment section of the question itself. (And I'm also unable to comment to say that he should answer his own question...) That's why I'm putting this answer here.)
You might want to look into the basics of SPI, the clock will only oscillate when there is an actual data transaction in progress. (This will prevent desynchronisation by a bit. And will make both sides know when data is being send. Often along with a SS)
You can check this by continiously sending something in your code and then probe the clock pin with an ossciloscope.
You might want to accept this as an answer, so that nobody it's clear this question is already answered.


text:
Analog Input not going to Zero
Arduino Uno user here
I am building a project with 4 analog inputs A0 dose not work. A1 A2 and A3 work perfectly fine! But for last input when I connect to A4 or A5, then they do not go to zero. They are stuck between 400 to 900. Even when connected to arduino ground it gives 400 instead of 0.
Am I missing something here cause the circuit for A4 connected to A3 gives perfect input value. They both work fine as output. Same situation with A5.
Is there another way to get one more Analog Input without multiplex?
Thank you!

Circuit is simple... Just 4 potentiometer and 4 pwn leds.

What do A4 and A5 report when you connect it directly to GND? What sensors are you using?

A1 to 3 gives zero... A4 and A5 give 440 approx... All input connect to diff RC pass filters..

there is no shield connected to Uno.

You haven't set the pins to "Input Pullup" by any chance? And you haven't done a "digitalWrite(pin, HIGH);" ?

I did not... I used digitalWrite(pin, LOW) though.

Connect A3 and A4 together, then put a 1 kΩ resistor between A3 and GND, then analogRead() both A3 and A4. If they both give high values, this means A4 is trying to output something, maybe through its I²C interface, or maybe it has its internal pullup enabled. If only A4 reads high, then you have a really weird problem. You may have fried a portion of the input mux of the ADC.

Please edit your question and post your code.


text:
Arduino Code for Pulse Skip Modulation (PSM)
I have recently bought this light dimmer, and only when I received it I noticed it works with PSM (Pulse Skip Modulation) and not PWD (Pulse Width Modulation).
Does anyone know how to write Arduino code and do the wiring for this dimmer? I can't seems to find a working example.
Thanks

The module is basically a triac with some support components. So instead of PSM, you could do Phase cutting (leading edge cutting). This is where you turn on the triac somewhere during the sinewave. Once the triac is turned on, it stays on till the next zero crossing. So you use the zero crossing signal to know when the next cycle starts, and you then turn the triac on somewhere in the cycle. Just note that since you are chopping up the sinewave the resulting brightness will not be linearly proportional to the percentage of time it's turned on.

Also, mains led lights that support dimming do so by measuring the waveform that's coming in and calculate the PWM value based on than. Since the main part of an led is a bridge rectifier, and a smoothing capacitor. Using a regular led bulb on a dimmer will have very little effect, right until the dimmer is almost fully off.

I actually also recently bought this same dimmer switch. Is there any way to vary the intensity through more than high and low intensity? Is there a way to have let’s say 25-30 intensities of getting dimmer or brighter? I wanted to set some sort of counter on it so that over a span of like a minute it could decrease from full brightness to completely off. Also does the Z_C pin have to be a PWM pin on the Arduino? Thanks for all the help!

I assume you use this module.
PSM is often used because of it's higher efficiency with light loads. It's also better for AC loads, since they should get a complete AC voltage and not a DC voltage (when you cut half of the wave).
The module you have, is build to support you with implementing PSM correctly. It has a zero-crossing detection, which gives you a signal on the Z-C pin, every time the AC sine wave crosses zero voltage (which is the best time to switch). You can sense the signal with an interrupt in your Arduino. The website does not explain exactly, what is outputted by the Z-C pin on a zero crossing, but you can check this easily yourself, by monitoring both AC and Z-C voltage in operation. Most likely you will have to use either a FALLING or a CHANGE interrupt.
PSM works with modulating the number of pulses (in this case full sine wave periods) are transmitted to the load. Imagine you want to dim the light in 10 distinct values.

For full power you always set the pin marked with PWM to high, when a full sine wave is starting (this is at every second zero crossing). This means the PWM pin is always high.
For half power you turn the PWM pin high for 5 full periods and then turning it off for further 5 periods.
For 10% (a value of 1) you turn the PWM pin high for 1 full period and then off for 9 periods.

The downside of this method is, that you might see the light flickering when having low values.
When implementing this, you can use the attachInterrupt() function with the Z-C pin. In the callback function you toggle a global (volatile!) boolean variable, to indicate, if a new full period is starting, or if the zero crossing signal is only indicating the start of the negative part of the sine wave. Also use a global (volatile!) counter variable, that counts (increments every full period) to the value, you preset (Here something between 0 and 10). When the counter variable is 0 (and the desired value is greater than 0) you write HIGH to the PWM pin of your module. When the counter reaches the desired value, you write LOW to the PWM pin. When the counter reaches the maximum value, you have reset it to 0.
In code something like this:
volatile byte counter=0;
volatile boolean new_period = true;
volatile byte value=5;
#define MAX_VALUE 10

void setup(){
  // set pinModes for the correct pins

  // active interrupt. Note, that you may have to change FALLING to a value fitting the output of the module (see explanation above)
  attachInterrupt(digitalPinToInterrupt(Z_C_pin), zero_crossing, FALLING);
}

void zero_crossing(){
  if(new_period){
    if(counter==0 && value>0) digitalWrite(PWM_pin,HIGH);
    if(counter==value) digitalWrite(PWM_pin,LOW);
    counter++;
    if(counter > MAX_VALUE) counter=0;
  }
  new_period=!new_period;
}

Note: Especially when having a great range of possible values, some of the values can be exchanged by a better behavior, that would prevent a bit of the flickering. For example, when using 100 distinct dimming stages and wanting to dim to 50%, you can either (as depicted above) turn the light on for 50 periods and then turning it of for another 50 periods. Or you can turn on during every second period. Though this will not help you with really small values. So I left it out for simplicity.

Amazing answer. Works perfectly...

@chrisl Hi while I try on Mega 2560 with attachInterrupt(0, zero_crosss_int, RISING); or attachInterrupt(digitalPinToInterrupt(interruptPin), zero_crosss_int, RISING); I am getting
exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.
error. How to solve it?

The full error code is;
WInterrupts.c.o (symbol from plugin): In function `attachInterrupt':
(.text+0x0): multiple definition of `__vector_5'
libraries\RBDdimmer\RBDdimmer.cpp.o (symbol from plugin):(.text+0x0): first defined here
c:/program files (x86)/arduino/hardware/tools/avr/bin/../lib/gcc/avr/5.4.0/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.

The RBDdimmer library seems to also define the corresponding ISR, which cannot be done twice. Have you tried other pins? The Mega 2560 seems to have 8 external interrupts and the RBDdimmer library is locked to D2 as of the github page.

All ports (2, 3, 18, 19, 20, 21) results with the same error..

Mhh, maybe you should ask a new question with this and refer to this question in it

Just adding to chrisl's answer since I bought this module, too.
There is a simple example on the manufacturers website of this module which does not seem to implement PSM the obvious way:

/*
Connect RobotDyn AC Light Dimmer as follows:
Dimmer pin  --  Arduino pin
    VCC     --    5V
    GND     --    GND
    Z-C     --    D2
    PWM     --    D3

Glow sketch for AC Voltage dimmer with Zero cross detection
Based on the sketch by Charith Fernanado
Adapted by RobotDyn: http://www.robotdyn.com
License: Creative Commons Attribution Share-Alike 3.0 License.
Attach the Zero cross pin of the module to Arduino External Interrupt pin
Select the correct Interrupt # from the below table (the Pin numbers are digital pins, NOT physical pins: digital pin 2 [INT0]=physical pin 4 and digital pin 3 [INT1]= physical pin 5)

Pin    |  Interrrupt # | Arduino Platform
---------------------------------------
2      |  0            |  All
3      |  1            |  All
18     |  5            |  Arduino Mega Only
19     |  4            |  Arduino Mega Only
20     |  3            |  Arduino Mega Only
21     |  2            |  Arduino Mega Only

In the program pin 2 is chosen
*/
int AC_LOAD = 3;    // Output to Opto Triac pin
int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

void setup()
{
  pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
  attachInterrupt(0, zero_crosss_int, RISING);  // Choose the zero cross interrupt # from the table above
}

// the interrupt function must take no parameters and return nothing
void zero_crosss_int()  // function to be fired at the zero crossing to dim the light
{
  // Firing angle calculation : 1 full 50Hz wave =1/50=20ms
  // Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle) For 60Hz => 8.33ms (10.000/120)
  // 10ms=10000us
  // (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65

  int dimtime = (75*dimming);    // For 60Hz =>65
  delayMicroseconds(dimtime);    // Off cycle
  digitalWrite(AC_LOAD, HIGH);   // triac firing
  delayMicroseconds(10);         // triac On propogation delay (for 60Hz use 8.33)
  digitalWrite(AC_LOAD, LOW);    // triac Off
}

void loop()  {
  for (int i=5; i <= 120; i++){  // We use 120 as the lowest and 5 as the highest brightness setting. May be adjusted depending on the lamp used.
    dimming=i;
    delay(20);
   }
  for (int i=120; i >= 5; i--){  // Same as above
    dimming=i;
    delay(20);
   }
}

They are using an interrupt as suggested by chrisl.
There is no flickering present with low dim values (using an incandescent bulb).
See this video for a similar board with the original version of the above sketch.
Note: If you want to integrate your own code into this example, it will likely not work as intended because the Arduino is busy with delayMicroseconds() most of the time

EDIT: The manufacturer of this module just released a library. Check it out on their github

This module allows you to implement pulse skipping modulation but also phase angle control. The code that reins.ch posted is actually the latter.


text:
Question about infrared receiver with metal shell to detect heart pulse rate?
I'm newbie to the world of arduino and environmental sensing. I have been searching for a while about how can I measure the heart pulse rate, I came through the following tutorial:
Click Here
I have the following Arduino IR Receiver with metal shell module that I want to use as the previous tutorial suggesting, but, the IR receiver used in the tutorial has no metal shell, so, my question is if they are both functioning the same way?
Can I position my IR Receiver exactly as the one in the tutorial or do I need some workaround to reach my goal based on the fact that it has a metal shell?
Thanks in advance.

"Proper" oxygen meters use a bimodal LED - red + IR - so there will be limitations to this. They also have a piece of copper foil wrapped around the sensor & heavily earthed, so your shielded sensor has, already, an advantage!
You should be able to use your receiver exactly the same way. If you can ground the shield, do so.


text:
Isolating IR receiver from disruption?
I'm using a simple IR receiver connected to the Arduino through A0 analog pin. The problem is that I want to stabilize the output of IR receiver when it's not receiving an IR signal from a specific IR source, or at least minimizing the disruption to a specific range that I can handle, no matter where its position, But in my case moving the IR receiver a few inches in any direction will results in different voltage output. the difference between values on disruption is very random to handle.
What can I do to isolate IR receiver, may be a specific material or a specific color?

What receiver are you using? If you read this comparison they mentioned that one of the receivers would give random pulses from the sunlight.

speaking of sunlight, when I was experiment with the IR receiver in my room, I didn't expect that the sunlight can cause such a huge disruption, I had to close my window, the output now is much more stabilized, but still there's a small disruption that I want to minimize it as much as I can.

I would suggest two things. First You could put electrical tape around the receiver in such a way that it will only pick up signals from a certain direction. Also you could use low and high pass filters to accept input only in the 38khz range(range of most infra red remotes).  Keep in mind that you will need a couple of rounds for it to work effectively.

Filtering is a good idea (if not already implemented in the receiver package) however it should be noted that even with filters, some will  output spurious pulses.  Software may be the best place to reject those - rejecting ones which occur in isolation are easy, recovering intended transmissions that have noise spikes in them is trickier, but generally still possible.

Thanks a lot Einstein Jr, putting electrical tape and setting transmitting frequency to 38khz solved my problem, it's may be useful to mention that I needed several rounds of electrical tape around my IR receiver to isolate it entirely from disruption.

Glad I could help. I editted my answer with your suggestions.


text:
Over-the-air upgrades?
I'd like to be able to upgrade software on an arduino without physically touching the device or stringing a cable. Can it be done?
Will pick wireless protocol that makes that easiest.

Have a look at Moteino.

Looking very nice.

I have ordered a couple of Moteinos, and hopefully will get around to trying out upgrades in the next few days.

The best and easiest solution I've found is to use the Bluefruit EZ-Link from Adafruit.  They have a module you plug into the Serial/Power/reset pins (link here) or a shield for the uno (link here).  They've also got a great description and how-to guide (link here) that is pretty good.  It basically appears as a serial bluetooth link in the arduino IDE and you program it like normal.  It has the added benefit of being of use not only for programming, but also for sending and receiving data.

We have implemented remote updates on a Arduino Pro Mini (ATMega328P) by putting a "boot" command into the normal firmware. How it works is:

The host sends the command "boot" to the remote Arduino.
The Arduino jumps to the boot loader (program address 0x3C00 for the Pro Mini)
The host sends the new firmware over the link using avrdude (AVR109 protocol)

This doesn't require a new boot loader or hardware. It is not a good solution for commercial devices though, as if the uploaded firmware is corrupted the board will not be able to be put into boot loader mode without a hard reset.
Some wireless comms devices, such as XBees, have GPIO that can be toggled remotely. Connecting this to the Arduino reset pin will allow the board to be reset into the boot loader instead.

The Arduino Yun can be remotely reflashed (either via wifi or network cable): you'll have to select its IP address under the "Tools > Boards" menu of the Arduino IDE and then press the upload button as usual.

It's possible to write a bootloader running in RAM (or even in Flash, maybe in a special boot block - depends on the microcontroller).
This bootloader has to be able to establish the wireless communication, understand the protocol and to erase/write Flash memory.
There are basically two approaches for software upgrading:

The bootloader looks at startup for a "software upgrade" command. If it is received, it waits for the programming sequence. If it is not received, it starts the application.
The application is able to receive such a command and gives control to the bootloader then.

What protocol you choose is almost irrelevant. Just make sure that there are enough resources for keeping it in RAM/Flash.
On an Arduino Due - for instance - there are more than enough resources for any such implementation.

Ah! Would you happen to know of some freely available code that implemented that kind of thing somewhere?

Yes, it can be done. Lowpowerlab.com has Moteino which can be programmed OTA.

Spark.io boards are also very nice for OTA programmable Arduino-like devices. I have one and have found it to be fairly easy to work with.
https://www.spark.io/


text:
Do addressable RGB's need to be programmed differently from normal RGB's?
I bought these rgb's from Sparkfun, however I have no idea how to hook them up or how to program them. Obviously the data sheet was somewhat helpful, however I have no idea how the IC's in the LED's work themselves or how to control them separately, or even how to string them together. My best guess is currently going for what the led's appear as in the example picture by connecting the first and last pins and putting the respective Vcc and ground pins to Vcc and ground.
Is there any good examples for hooking these up and coding them, or a basic understandable explanation for how they work?
Thanks, I can't find a great resource yet.

These are much different than "normal" RGB LED: they use the WS2812 chip, which is the same as the chip used in famous Adafruit "neopixels" strips, rings...
Wiring is simple. For all LEDs:

GND to 0V
VDD to 5V

For the first LED (connected to Arduino):

DIN to any Arduino logical output pin
DOUT to the 2nd LED you want to address (on its DIN pin)

For all but the first LED:

DIN to the previous LED DOUT
DOUT to the next LED DIN (or left floating for the last LED)

Programming neopixel is quite hard because timing of sent commands must be very precise.
I highly suggest to use Adafruit libraries for that.

Wiring is not the same. RGB addressable LEDs will need 12V, they draw some "extra" power over what the LED would draw by itself. See this: https://www.youtube.com/watch?v=h_GXhJeCDD0

I don't see anywhere in the datasheet mentioned the need for 12V: datasheet says 4.5V~6V. Personally, I have used neopixels rings with 5V without any issue.

The WS2812 itself can run on lower voltage, but the LEDs won't. EDIT: oh, you're right - that one from Sparkfun is special.

@Jasmine that's why it is always important to refer to the datasheet when you have it, that must be THE reference. No hard feelings though, your work on neopixels is interesting, thanks for sharing.

Does neopixel use either I2C or SPI? Or is it something else entirely? We're just learning about communication interfaces in my current classes.

No they use their own protocol.

It just uses "clocked" serial data. I didn't check the link at first, I just assumed he was using the same RGB strips everyone uses. Those individual ones are a major pain :)


text:
Wiring Issues with Sparkfun Oled
I'm attempting to hook up an arduino uno with a Sparkfun Oled. I downloaded the example program and made these changes:
#define PIN_RESET 3  // Connect RST to pin 3
#define PIN_DC    4  // Connect DC to pin 4
#define PIN_CS    10 // Connect CS to pin 10
#define DC_JUMPER 0

I connected everything according to Sparfun's walkthrough. I also wired accordingly. However, I cannot seem to get the Oled to do, well, much of anything. I have tried switching the MOSI and MISO to see if that makes a difference, but it doesn't seem to have any effect.
I'm using:
pin 13 - clock (in the picture I was trying pin 8 for the clock but I have tried both)
pin 12 - MISO
pin 11 - MOSI
pin 10 - CS
pin 4 - DC
pin 3 - RESET
Can anyone tell me what's going wrong? I've tried to figure it out for a good long while now and I can't make the display do anything productive.
Thanks

Have you inspected the pins you soldered on for cold joints?

It looks almost like the wires are simply pushed through the holes of the OLED breakout board (i.e. not soldered at all). If that's the case then there's a good chance they aren't forming a reliable connection.

If I only want to test the oled without committing it to an actual application, is there any way I could do that without soldering?

(Old thread, but still.) This picture doesn't provide any useful information. Either draw a schematic or use something like Fritzing to create something legible!

Have you connected the GND pin from the UNO to the breadboard?  I can't hardly tell.  But it looks like you are also using 5V to power it?
How are you powering the UNO?  Is it just 3.3V?  I'm powering mine with a 5V but have level converters connected.
Mine:


text:
atTiny85 5V and servo usage
I have an AtTiny85 that I would like to move a servo on I/O "4" for this project.
I can't seem to get it to work, no matter what I do. I had tons of issues getting it to program, but I've gotten it to a place where it will program a blink, and it will also blink the LED in the circuit diagram in the link provided. I have the servo wired, and I'm pretty darn sure the wiring is correct (when are we 100% sure?). I've tried these programs to no success:
// Trinket Servo Monster sketch
// Hardware: Adafruit Trinket (3V or 5V), micro servo, LED + resistor
// Libraries: uses Adafruit_TiCoServo library to manage servo pulses,
// even though NeoPixels are NOT being used here.

#if !defined(__AVR_ATtiny85__)
 #error "This code is for ATtiny boards"
#endif
//#include <Adafruit_TiCoServo.h>
#include <ServoManager.h>
#include <avr/power.h>

// Servo parameters.  Pin MUST be 1 or 4 on a Trinket.  Servo position
// is specified in raw timer/counter ticks (1 tick = 0.128 milliseconds).
// Servo pulse timing is typically 1-2 ms, but can vary slightly among
// servos, so you may need to tweak these limits to match your reality.
#define SERVO_PIN  4 // Pins 1 or 4 are supported on Trinket
#define SERVO_MIN  4 // ~1 ms pulse
#define SERVO_MAX 26 // ~2 ms pulse

#define LED_PIN    0 // "Eye" LED is connected here

PrecisionServo* servo;

void setup(void) {
  ServoManager::setup(1);
  servo = ServoManager::createServo(4);
  //servo->setSetting(SERVO_MEDIUM_ENDPOINT);

//#if (F_CPU == 16000000L)
  // 16 MHz Trinket requires setting prescale for correct timing.
  // This MUST be done BEFORE servo.attach()!
//  clock_prescale_set(clock_div_1);
//#endif
  //servo.attach(SERVO_PIN);
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);
}

uint32_t lastLookTime = 0; // Time of last head-turn

void loop(void) {

  //unsigned long t = millis(); // Current time

  // If more than 1/2 second has passed since last head turn...
  servo->setTarget(0);
  ServoManager::waitUntilFinished();

  servo->setTarget(180);
  ServoManager::waitUntilFinished();

  // Unrelated to head-turn check,
  if(random(10) == 0) { // there's a 1-in-10 chance...
    // ...of an "eye blink":
    digitalWrite(LED_PIN, LOW);  // The LED turns OFF
    delay(random(50, 250));      // for just a short random moment
    digitalWrite(LED_PIN, HIGH); // then back ON
  }

  //delay(1000); // Repeat loop() about 10 times/second
}

SO I scaled back and just tried to write a high out as follows:
void setup() {
  pinMode(4, OUTPUT);
}

void loop() {
  digitalWrite(4, HIGH);
  delayMicroseconds(1000);
  // 1 millisecond determines the servo going forwards
  digitalWrite(4, LOW);
  delay(19);
}

But this didn't work either.
Shouldn't the servo move with just a write to 'high' and 'low'?

no it should not, not a hobby servo ... there are many tutorials on the web about the operation of hobby servos and how to control them

Can you link? Nothing I've found so far has helped.

https://duckduckgo.com/?q=arduino+hobby+servo&ia=web

The servo requires a PWM signal to the control lead to move.
This datasheet kind of bears that out...
http://www.datasheetcafe.com/sg90-datasheet-pdf-9-g-micro-servo/


text:
Internet connectivity for the Arduino Due using AtmelStudio?
What hardware and software solutions work and what are the tradeoffs for connecting an Arduino Due to the internet?  I gather the ethernet hardware is much cheaper than WiFi hardware (€29 versus €69).  In either case (wired or wireless), what software stacks and drivers work under AtmelStudio?

Greatt question

Atmel studio uses c++ right? Porting the Ethernet library cant be that hard.

Hoping so @TheDoctor.  I see an Ethernet PHY component and driver in the ASF Wizard but no TCP/IP pieces.  In answer to your question, yes, I see C++ hints everywhere but I've only used C so far.

@BobStein-VisiBone - That PHY component requires a specific external ethernet PHY (A DM9161A). It will not work with the arduino ethernet board/shield, which uses a Wiznet W5100 PHY/coprocessor).

Well, your best bet is to import the arduino libraries in your Atmel Studio project. Then you'll be able to use existing code to connect to the "traditional" Ethernet Shield using SPI.
Though, the Sam 3X features an hardware ethernet that is not wired, unlike the MBed LPC1768… Sadly that's the ethernet PHY component you saw, but won't be able to actually use…

You could always buy a Taijiuino Due, which is a 3rd party due clone that is code-compatible, but has the ethernet IO lines broken out.

You mean the Visual Micro plugin for Atmel Studio?  And with that make a TCP/IP server with the EthernetServer class?

I guess so, though I've not tried that. You may also include the sources or add headers + libraries as dependencies in your project (which is what I do)

What .c .cpp .h files do you use @zmo?  What kind of TCP/IP features do you have, or are they merely Ethernet?

This solution means I'd give up ASF (Atmel Studio Framework) correct?

Er… what are you actually asking? are you asking about the SAM3X Ethernet features, or using an ethernet shield on the Due? Anyway, that does not mean you have to give up ASF, just to complete it with parts of the Arduino framework.

Your answer says "import the arduino libraries".  Is that possible in a project that includes ASF?  I've only managed to be able to use one or the other, by New | Project or New | Arduino Project.  If it isn't too noob a question, can you walk me through the exact steps how to import the arduino libraries in a project that uses ASF?


text:
Problem converting character array into integer in arduino using atoi function
I'm receiving a character string from a radio signal on my arduino.  This character string consists of four character digits, which I want to convert into an integer.  The four digit sequence may contain zeros padded in front of the integer, such as '0025' to represent the integer 25.
So, I saved this character string onto a character array of length 5:
char left[5];

The first four characters in this array have the four character digits received in the radio signal.  I have a fifth character which I set to the character '\0' to signify a termination character.
The message received is any number ranging from 0 to 1023, but I need to use values between -255 and +255.  To convert the character into an integer, I use the atoi function as follows:
int leftpower = (atoi(left)-512)/2;

When I print out the variable "leftpower", it seems to give the correct value.  I'm even able to use "leftpower" in an if then statement as follows:
if (myvalue<0){
  Serial.println("inside the if-then statement");
  digitalWrite(in1,HIGH);
  digitalWrite(in2,LOW);
  //analogWrite(enableA,myvalue);
}

So, as far as I can tell, everything is working fine.  I want to use "myvalue" as a command to an analogWrite function call as follows:
//analogWrite(enablePinA,myvalue);

However, something strange happens when I uncomment this line.  WHen I uncomment it, the program seems to hang at the if statement, as if it paused at that point and neither crashes nor gives any error.  The program no longer prints out "inside the if-then statement" at all, but no other errors seem to be detected.  No other compilation or runtime errors.
The strange thing about this is that if I change "leftpower" to a number like 223 as follows:
analogWrite(enablePinA,223);

the program works as I expected it to, producing a motor command.  So, I know the problem is not with my wiring.  The problem seems to be associated with the variable "leftpower", which was converted from a character array to an integer using the atoi function.
What exactly is going on?  What problem is actually occurring and how can I fix it?  Any help would be greatly appreciated!
For reference, my code is posted below:
#include <RH_ASK.h> //radiohead library to read RF signals
#include <SPI.h> //just because radiohead library depends on it
RH_ASK driver; //default: transmitter data pin goes to arduino pin 11
int in1=4;
int in2=5;
int in3=6;
int in4=7;

int enableA = 9;
int enableB = 10;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  if (!driver.init()){
    Serial.println("receiver init failed");
  }
  pinMode(enableA,OUTPUT);
  pinMode(enableB,OUTPUT);
  pinMode(in1,OUTPUT);
  pinMode(in2,OUTPUT);
  pinMode(in3,OUTPUT);
  pinMode(in4,OUTPUT);
}
int leftpower,rightpower;
void loop() {
  // put your main code here, to run repeatedly:
  uint8_t buf[8];
  uint8_t buflen = sizeof(buf);
  if (driver.recv(buf, &buflen)){ //non-blocking
    //Convert buf (unsigned integer) to a character array
    char temp[8]="";
    sprintf(temp,"%s",(char*) buf);
    //Four characters for first integer, four for the second integer
    //So, we have to split them into two parts (left and right)
    char left[5]="";
    for (int i=0; i<4; i++){
      left[i]=temp[i];
    }
    //Put a terminating character at the end
    left[4]='\0';
    char right[5]="";
    for (int i=0; i<4; i++){
      right[i]=temp[4+i];
    }
    //Put a terminating character at the end
    right[4]='\0';
    leftpower=(int) (atoi(left)-512)/2;
    rightpower=(int) (atoi(right)-512)/2;
    constrain(leftpower,-255,255);
    constrain(rightpower,-255,255);
    Serial.println(leftpower);
    Serial.println(rightpower);
    if (leftpower<0) {
      //switch H-bridge to forward direction
      Serial.println("inside the if-then statement");
      digitalWrite(in1,HIGH);
      digitalWrite(in2,LOW);
      analogWrite(enableA,255);
      Serial.println("got this far");
    }
    else {
      digitalWrite(in1,LOW);
      digitalWrite(in2,HIGH);
      analogWrite(enableA,255);
    }
//    if (rightpower<0) {
//      //switch H-bridge to forward direction
//      digitalWrite(in3,LOW);
//      digitalWrite(in4,HIGH);
//      analogWrite(enableA,abs(rightpower));
//    }
//    else {
//      digitalWrite(in4,LOW);
//      digitalWrite(in3,HIGH);
//      analogWrite(enableA,abs(rightpower));
//    }

  }
}

analogWrite does not support negative values. You should probably use abs(leftpower).

You have a few issues here.

if (driver.recv(buf, &buflen)) { ... }

You don't check the value of buflen after calling the recv() method.
I didn't read the doc of the RH_ASK library you are using. Are you sure
it does preserve message boundaries? I let you check. If it only
transports bytes (rather than full messages), then you will have to
repeatedly recv() until you have a full message.
Edit: Looked at the doc. The communication is indeed packetized, so
you don't need to collect the message chunk by chunk. It is, however,
still a good idea to check whether the received size is what you expect:
if (driver.recv(buf, &buflen) && buflen == 8) { ... }

sprintf(temp,"%s",(char*) buf);

This is a serious bug, and most probably the reason your program behaves
inconsistently. Here buf is not a NUL-terminated string. The
sprintf() function will copy bytes from buf into temp until it
finds a NUL. It can potentially overwrite the receiving buffer and start
clobbering whatever happens to be past temp in your memory. This is
called “memory corruption” and can lead to any kind of unpredictable
behaviors.
Note that the whole copying you do here serves no useful purpose. You
can work from the initial buffer to start with:
char left[5];
memcpy(left, buf, 4);
left[4] = '\0';
char right[5];
memcpy(right, buf+4, 4);
right[4] = '\0';

constrain(leftpower,-255,255);

You are implicitly discarding the value computed by constrain(). You
probably mean
leftpower = constrain(leftpower, -255, 255);

The reason for the copy step is that the message received by the radio signal is actually 8 characters (two 4 character digit commands).  To convert to an integer, i need to split the message into 2 separate 4 character arrays.

@Paul: That's why I suggest doing the splitting using two partial copies (with memcpy()), as buf → (left, right). However, your original code did the splitting as buf → temp → (left, right), where you first make a full copy (buf → temp) for no good reason. Note that the splitting could even be made zero-copy if we were after that kind of optimization.

I think the reason i used sprintf is because the message received in the buffer was originally an unsigned integer uint8_t (not a character array) and i thought converting to a character array would be simpler (for parsing purposes) using sprintf.  Could i have parsed the two numbers out to a regular integer without converting to a character array first?

@Paul: Yes. buf is just an array of bytes. Same for temp. uint8_t, which is the same as unsigned char, means the bytes are interpreted as 8-bit unsigned integers. With int8_t (or signed char, or just char on Arduino), it's interpreted as a signed integer. The difference is irrelevant unless you plan to do arithmetics on those bytes, which you don't.